repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
openssl
openssl-master/crypto/asn1/asn_moid.c
/* * Copyright 2002-2020 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 */ #include <stdio.h> #include "crypto/ctype.h" #include <openssl/crypto.h> #include "internal/cryptlib.h" #include <openssl/conf.h> #include <openssl/x509.h> #include "crypto/asn1.h" #include "crypto/objects.h" /* Simple ASN1 OID module: add all objects in a given section */ static int do_create(const char *value, const char *name); static int oid_module_init(CONF_IMODULE *md, const CONF *cnf) { int i; const char *oid_section; STACK_OF(CONF_VALUE) *sktmp; CONF_VALUE *oval; oid_section = CONF_imodule_get_value(md); if ((sktmp = NCONF_get_section(cnf, oid_section)) == NULL) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ERROR_LOADING_SECTION); return 0; } for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) { oval = sk_CONF_VALUE_value(sktmp, i); if (!do_create(oval->value, oval->name)) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ADDING_OBJECT); return 0; } } return 1; } static void oid_module_finish(CONF_IMODULE *md) { } void ASN1_add_oid_module(void) { CONF_module_add("oid_section", oid_module_init, oid_module_finish); } /*- * Create an OID based on a name value pair. Accept two formats. * shortname = 1.2.3.4 * shortname = some long name, 1.2.3.4 */ static int do_create(const char *value, const char *name) { int nid; const char *ln, *ostr, *p; char *lntmp = NULL; p = strrchr(value, ','); if (p == NULL) { ln = name; ostr = value; } else { ln = value; ostr = p + 1; if (*ostr == '\0') return 0; while (ossl_isspace(*ostr)) ostr++; while (ossl_isspace(*ln)) ln++; p--; while (ossl_isspace(*p)) { if (p == ln) return 0; p--; } p++; if ((lntmp = OPENSSL_malloc((p - ln) + 1)) == NULL) return 0; memcpy(lntmp, ln, p - ln); lntmp[p - ln] = '\0'; ln = lntmp; } nid = OBJ_create(ostr, name, ln); OPENSSL_free(lntmp); return nid != NID_undef; }
2,433
23.585859
74
c
openssl
openssl-master/crypto/asn1/asn_mstbl.c
/* * Copyright 2012-2020 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 */ #include <stdio.h> #include <openssl/crypto.h> #include "internal/cryptlib.h" #include <openssl/conf.h> #include <openssl/x509v3.h> /* Multi string module: add table entries from a given section */ static int do_tcreate(const char *value, const char *name); static int stbl_module_init(CONF_IMODULE *md, const CONF *cnf) { int i; const char *stbl_section; STACK_OF(CONF_VALUE) *sktmp; CONF_VALUE *mval; stbl_section = CONF_imodule_get_value(md); if ((sktmp = NCONF_get_section(cnf, stbl_section)) == NULL) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ERROR_LOADING_SECTION); return 0; } for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) { mval = sk_CONF_VALUE_value(sktmp, i); if (!do_tcreate(mval->value, mval->name)) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_VALUE); return 0; } } return 1; } static void stbl_module_finish(CONF_IMODULE *md) { ASN1_STRING_TABLE_cleanup(); } void ASN1_add_stable_module(void) { CONF_module_add("stbl_section", stbl_module_init, stbl_module_finish); } /* * Create an table entry based on a name value pair. format is oid_name = * n1:v1, n2:v2,... where name is "min", "max", "mask" or "flags". */ static int do_tcreate(const char *value, const char *name) { char *eptr; int nid, i, rv = 0; long tbl_min = -1, tbl_max = -1; unsigned long tbl_mask = 0, tbl_flags = 0; STACK_OF(CONF_VALUE) *lst = NULL; CONF_VALUE *cnf = NULL; nid = OBJ_sn2nid(name); if (nid == NID_undef) nid = OBJ_ln2nid(name); if (nid == NID_undef) goto err; lst = X509V3_parse_list(value); if (!lst) goto err; for (i = 0; i < sk_CONF_VALUE_num(lst); i++) { cnf = sk_CONF_VALUE_value(lst, i); if (strcmp(cnf->name, "min") == 0) { tbl_min = strtoul(cnf->value, &eptr, 0); if (*eptr) goto err; } else if (strcmp(cnf->name, "max") == 0) { tbl_max = strtoul(cnf->value, &eptr, 0); if (*eptr) goto err; } else if (strcmp(cnf->name, "mask") == 0) { if (!ASN1_str2mask(cnf->value, &tbl_mask) || !tbl_mask) goto err; } else if (strcmp(cnf->name, "flags") == 0) { if (strcmp(cnf->value, "nomask") == 0) tbl_flags = STABLE_NO_MASK; else if (strcmp(cnf->value, "none") == 0) tbl_flags = STABLE_FLAGS_CLEAR; else goto err; } else goto err; } rv = 1; err: if (rv == 0) { if (cnf) ERR_raise_data(ERR_LIB_ASN1, ASN1_R_INVALID_STRING_TABLE_VALUE, "field=%s, value=%s", cnf->name, cnf->value); else ERR_raise_data(ERR_LIB_ASN1, ASN1_R_INVALID_STRING_TABLE_VALUE, "name=%s, value=%s", name, value); } else { rv = ASN1_STRING_TABLE_add(nid, tbl_min, tbl_max, tbl_mask, tbl_flags); if (!rv) ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); } sk_CONF_VALUE_pop_free(lst, X509V3_conf_free); return rv; }
3,529
29.964912
75
c
openssl
openssl-master/crypto/asn1/asn_pack.c
/* * Copyright 1999-2020 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1.h> /* ASN1 packing and unpacking functions */ ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it, ASN1_STRING **oct) { ASN1_STRING *octmp; if (oct == NULL || *oct == NULL) { if ((octmp = ASN1_STRING_new()) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); return NULL; } } else { octmp = *oct; } ASN1_STRING_set0(octmp, NULL, 0); if ((octmp->length = ASN1_item_i2d(obj, &octmp->data, it)) <= 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ENCODE_ERROR); goto err; } if (octmp->data == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if (oct != NULL && *oct == NULL) *oct = octmp; return octmp; err: if (oct == NULL || *oct == NULL) ASN1_STRING_free(octmp); return NULL; } /* Extract an ASN1 object from an ASN1_STRING */ void *ASN1_item_unpack(const ASN1_STRING *oct, const ASN1_ITEM *it) { const unsigned char *p; void *ret; p = oct->data; if ((ret = ASN1_item_d2i(NULL, &p, oct->length, it)) == NULL) ERR_raise(ERR_LIB_ASN1, ASN1_R_DECODE_ERROR); return ret; } void *ASN1_item_unpack_ex(const ASN1_STRING *oct, const ASN1_ITEM *it, OSSL_LIB_CTX *libctx, const char *propq) { const unsigned char *p; void *ret; p = oct->data; if ((ret = ASN1_item_d2i_ex(NULL, &p, oct->length, it,\ libctx, propq)) == NULL) ERR_raise(ERR_LIB_ASN1, ASN1_R_DECODE_ERROR); return ret; }
1,965
25.213333
78
c
openssl
openssl-master/crypto/asn1/bio_asn1.c
/* * Copyright 2006-2021 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 */ /* * Experimental ASN1 BIO. When written through the data is converted to an * ASN1 string type: default is OCTET STRING. Additional functions can be * provided to add prefix and suffix data. */ #include <string.h> #include "internal/bio.h" #include <openssl/asn1.h> #include "internal/cryptlib.h" /* Must be large enough for biggest tag+length */ #define DEFAULT_ASN1_BUF_SIZE 20 typedef enum { ASN1_STATE_START, ASN1_STATE_PRE_COPY, ASN1_STATE_HEADER, ASN1_STATE_HEADER_COPY, ASN1_STATE_DATA_COPY, ASN1_STATE_POST_COPY, ASN1_STATE_DONE } asn1_bio_state_t; typedef struct BIO_ASN1_EX_FUNCS_st { asn1_ps_func *ex_func; asn1_ps_func *ex_free_func; } BIO_ASN1_EX_FUNCS; typedef struct BIO_ASN1_BUF_CTX_t { /* Internal state */ asn1_bio_state_t state; /* Internal buffer */ unsigned char *buf; /* Size of buffer */ int bufsize; /* Current position in buffer */ int bufpos; /* Current buffer length */ int buflen; /* Amount of data to copy */ int copylen; /* Class and tag to use */ int asn1_class, asn1_tag; asn1_ps_func *prefix, *prefix_free, *suffix, *suffix_free; /* Extra buffer for prefix and suffix data */ unsigned char *ex_buf; int ex_len; int ex_pos; void *ex_arg; } BIO_ASN1_BUF_CTX; static int asn1_bio_write(BIO *h, const char *buf, int num); static int asn1_bio_read(BIO *h, char *buf, int size); static int asn1_bio_puts(BIO *h, const char *str); static int asn1_bio_gets(BIO *h, char *str, int size); static long asn1_bio_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int asn1_bio_new(BIO *h); static int asn1_bio_free(BIO *data); static long asn1_bio_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); static int asn1_bio_init(BIO_ASN1_BUF_CTX *ctx, int size); static int asn1_bio_flush_ex(BIO *b, BIO_ASN1_BUF_CTX *ctx, asn1_ps_func *cleanup, asn1_bio_state_t next); static int asn1_bio_setup_ex(BIO *b, BIO_ASN1_BUF_CTX *ctx, asn1_ps_func *setup, asn1_bio_state_t ex_state, asn1_bio_state_t other_state); static const BIO_METHOD methods_asn1 = { BIO_TYPE_ASN1, "asn1", bwrite_conv, asn1_bio_write, bread_conv, asn1_bio_read, asn1_bio_puts, asn1_bio_gets, asn1_bio_ctrl, asn1_bio_new, asn1_bio_free, asn1_bio_callback_ctrl, }; const BIO_METHOD *BIO_f_asn1(void) { return &methods_asn1; } static int asn1_bio_new(BIO *b) { BIO_ASN1_BUF_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx == NULL) return 0; if (!asn1_bio_init(ctx, DEFAULT_ASN1_BUF_SIZE)) { OPENSSL_free(ctx); return 0; } BIO_set_data(b, ctx); BIO_set_init(b, 1); return 1; } static int asn1_bio_init(BIO_ASN1_BUF_CTX *ctx, int size) { if (size <= 0) { ERR_raise(ERR_LIB_ASN1, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if ((ctx->buf = OPENSSL_malloc(size)) == NULL) return 0; ctx->bufsize = size; ctx->asn1_class = V_ASN1_UNIVERSAL; ctx->asn1_tag = V_ASN1_OCTET_STRING; ctx->state = ASN1_STATE_START; return 1; } static int asn1_bio_free(BIO *b) { BIO_ASN1_BUF_CTX *ctx; if (b == NULL) return 0; ctx = BIO_get_data(b); if (ctx == NULL) return 0; if (ctx->prefix_free != NULL) ctx->prefix_free(b, &ctx->ex_buf, &ctx->ex_len, &ctx->ex_arg); if (ctx->suffix_free != NULL) ctx->suffix_free(b, &ctx->ex_buf, &ctx->ex_len, &ctx->ex_arg); OPENSSL_free(ctx->buf); OPENSSL_free(ctx); BIO_set_data(b, NULL); BIO_set_init(b, 0); return 1; } static int asn1_bio_write(BIO *b, const char *in, int inl) { BIO_ASN1_BUF_CTX *ctx; int wrmax, wrlen, ret; unsigned char *p; BIO *next; ctx = BIO_get_data(b); next = BIO_next(b); if (in == NULL || inl < 0 || ctx == NULL || next == NULL) return 0; wrlen = 0; ret = -1; for (;;) { switch (ctx->state) { /* Setup prefix data, call it */ case ASN1_STATE_START: if (!asn1_bio_setup_ex(b, ctx, ctx->prefix, ASN1_STATE_PRE_COPY, ASN1_STATE_HEADER)) return -1; break; /* Copy any pre data first */ case ASN1_STATE_PRE_COPY: ret = asn1_bio_flush_ex(b, ctx, ctx->prefix_free, ASN1_STATE_HEADER); if (ret <= 0) goto done; break; case ASN1_STATE_HEADER: ctx->buflen = ASN1_object_size(0, inl, ctx->asn1_tag) - inl; if (!ossl_assert(ctx->buflen <= ctx->bufsize)) return -1; p = ctx->buf; ASN1_put_object(&p, 0, inl, ctx->asn1_tag, ctx->asn1_class); ctx->copylen = inl; ctx->state = ASN1_STATE_HEADER_COPY; break; case ASN1_STATE_HEADER_COPY: ret = BIO_write(next, ctx->buf + ctx->bufpos, ctx->buflen); if (ret <= 0) goto done; ctx->buflen -= ret; if (ctx->buflen) ctx->bufpos += ret; else { ctx->bufpos = 0; ctx->state = ASN1_STATE_DATA_COPY; } break; case ASN1_STATE_DATA_COPY: if (inl > ctx->copylen) wrmax = ctx->copylen; else wrmax = inl; ret = BIO_write(next, in, wrmax); if (ret <= 0) goto done; wrlen += ret; ctx->copylen -= ret; in += ret; inl -= ret; if (ctx->copylen == 0) ctx->state = ASN1_STATE_HEADER; if (inl == 0) goto done; break; case ASN1_STATE_POST_COPY: case ASN1_STATE_DONE: BIO_clear_retry_flags(b); return 0; } } done: BIO_clear_retry_flags(b); BIO_copy_next_retry(b); return (wrlen > 0) ? wrlen : ret; } static int asn1_bio_flush_ex(BIO *b, BIO_ASN1_BUF_CTX *ctx, asn1_ps_func *cleanup, asn1_bio_state_t next) { int ret; if (ctx->ex_len <= 0) return 1; for (;;) { ret = BIO_write(BIO_next(b), ctx->ex_buf + ctx->ex_pos, ctx->ex_len); if (ret <= 0) break; ctx->ex_len -= ret; if (ctx->ex_len > 0) ctx->ex_pos += ret; else { if (cleanup) cleanup(b, &ctx->ex_buf, &ctx->ex_len, &ctx->ex_arg); ctx->state = next; ctx->ex_pos = 0; break; } } return ret; } static int asn1_bio_setup_ex(BIO *b, BIO_ASN1_BUF_CTX *ctx, asn1_ps_func *setup, asn1_bio_state_t ex_state, asn1_bio_state_t other_state) { if (setup && !setup(b, &ctx->ex_buf, &ctx->ex_len, &ctx->ex_arg)) { BIO_clear_retry_flags(b); return 0; } if (ctx->ex_len > 0) ctx->state = ex_state; else ctx->state = other_state; return 1; } static int asn1_bio_read(BIO *b, char *in, int inl) { BIO *next = BIO_next(b); if (next == NULL) return 0; return BIO_read(next, in, inl); } static int asn1_bio_puts(BIO *b, const char *str) { return asn1_bio_write(b, str, strlen(str)); } static int asn1_bio_gets(BIO *b, char *str, int size) { BIO *next = BIO_next(b); if (next == NULL) return 0; return BIO_gets(next, str, size); } static long asn1_bio_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { BIO *next = BIO_next(b); if (next == NULL) return 0; return BIO_callback_ctrl(next, cmd, fp); } static long asn1_bio_ctrl(BIO *b, int cmd, long arg1, void *arg2) { BIO_ASN1_BUF_CTX *ctx; BIO_ASN1_EX_FUNCS *ex_func; long ret = 1; BIO *next; ctx = BIO_get_data(b); if (ctx == NULL) return 0; next = BIO_next(b); switch (cmd) { case BIO_C_SET_PREFIX: ex_func = arg2; ctx->prefix = ex_func->ex_func; ctx->prefix_free = ex_func->ex_free_func; break; case BIO_C_GET_PREFIX: ex_func = arg2; ex_func->ex_func = ctx->prefix; ex_func->ex_free_func = ctx->prefix_free; break; case BIO_C_SET_SUFFIX: ex_func = arg2; ctx->suffix = ex_func->ex_func; ctx->suffix_free = ex_func->ex_free_func; break; case BIO_C_GET_SUFFIX: ex_func = arg2; ex_func->ex_func = ctx->suffix; ex_func->ex_free_func = ctx->suffix_free; break; case BIO_C_SET_EX_ARG: ctx->ex_arg = arg2; break; case BIO_C_GET_EX_ARG: *(void **)arg2 = ctx->ex_arg; break; case BIO_CTRL_FLUSH: if (next == NULL) return 0; /* Call post function if possible */ if (ctx->state == ASN1_STATE_HEADER) { if (!asn1_bio_setup_ex(b, ctx, ctx->suffix, ASN1_STATE_POST_COPY, ASN1_STATE_DONE)) return 0; } if (ctx->state == ASN1_STATE_POST_COPY) { ret = asn1_bio_flush_ex(b, ctx, ctx->suffix_free, ASN1_STATE_DONE); if (ret <= 0) return ret; } if (ctx->state == ASN1_STATE_DONE) return BIO_ctrl(next, cmd, arg1, arg2); else { BIO_clear_retry_flags(b); return 0; } default: if (next == NULL) return 0; return BIO_ctrl(next, cmd, arg1, arg2); } return ret; } static int asn1_bio_set_ex(BIO *b, int cmd, asn1_ps_func *ex_func, asn1_ps_func *ex_free_func) { BIO_ASN1_EX_FUNCS extmp; extmp.ex_func = ex_func; extmp.ex_free_func = ex_free_func; return BIO_ctrl(b, cmd, 0, &extmp); } static int asn1_bio_get_ex(BIO *b, int cmd, asn1_ps_func **ex_func, asn1_ps_func **ex_free_func) { BIO_ASN1_EX_FUNCS extmp; int ret; ret = BIO_ctrl(b, cmd, 0, &extmp); if (ret > 0) { *ex_func = extmp.ex_func; *ex_free_func = extmp.ex_free_func; } return ret; } int BIO_asn1_set_prefix(BIO *b, asn1_ps_func *prefix, asn1_ps_func *prefix_free) { return asn1_bio_set_ex(b, BIO_C_SET_PREFIX, prefix, prefix_free); } int BIO_asn1_get_prefix(BIO *b, asn1_ps_func **pprefix, asn1_ps_func **pprefix_free) { return asn1_bio_get_ex(b, BIO_C_GET_PREFIX, pprefix, pprefix_free); } int BIO_asn1_set_suffix(BIO *b, asn1_ps_func *suffix, asn1_ps_func *suffix_free) { return asn1_bio_set_ex(b, BIO_C_SET_SUFFIX, suffix, suffix_free); } int BIO_asn1_get_suffix(BIO *b, asn1_ps_func **psuffix, asn1_ps_func **psuffix_free) { return asn1_bio_get_ex(b, BIO_C_GET_SUFFIX, psuffix, psuffix_free); }
11,507
24.573333
77
c
openssl
openssl-master/crypto/asn1/bio_ndef.c
/* * Copyright 2008-2021 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 */ #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/bio.h> #include <openssl/err.h> #include <stdio.h> /* Experimental NDEF ASN1 BIO support routines */ /* * The usage is quite simple, initialize an ASN1 structure, get a BIO from it * then any data written through the BIO will end up translated to * appropriate format on the fly. The data is streamed out and does *not* * need to be all held in memory at once. When the BIO is flushed the output * is finalized and any signatures etc written out. The BIO is a 'proper' * BIO and can handle non blocking I/O correctly. The usage is simple. The * implementation is *not*... */ /* BIO support data stored in the ASN1 BIO ex_arg */ typedef struct ndef_aux_st { /* ASN1 structure this BIO refers to */ ASN1_VALUE *val; const ASN1_ITEM *it; /* Top of the BIO chain */ BIO *ndef_bio; /* Output BIO */ BIO *out; /* Boundary where content is inserted */ unsigned char **boundary; /* DER buffer start */ unsigned char *derbuf; } NDEF_SUPPORT; static int ndef_prefix(BIO *b, unsigned char **pbuf, int *plen, void *parg); static int ndef_prefix_free(BIO *b, unsigned char **pbuf, int *plen, void *parg); static int ndef_suffix(BIO *b, unsigned char **pbuf, int *plen, void *parg); static int ndef_suffix_free(BIO *b, unsigned char **pbuf, int *plen, void *parg); /* * On success, the returned BIO owns the input BIO as part of its BIO chain. * On failure, NULL is returned and the input BIO is owned by the caller. * * Unfortunately cannot constify this due to CMS_stream() and PKCS7_stream() */ BIO *BIO_new_NDEF(BIO *out, ASN1_VALUE *val, const ASN1_ITEM *it) { NDEF_SUPPORT *ndef_aux = NULL; BIO *asn_bio = NULL; const ASN1_AUX *aux = it->funcs; ASN1_STREAM_ARG sarg; BIO *pop_bio = NULL; if (!aux || !aux->asn1_cb) { ERR_raise(ERR_LIB_ASN1, ASN1_R_STREAMING_NOT_SUPPORTED); return NULL; } ndef_aux = OPENSSL_zalloc(sizeof(*ndef_aux)); asn_bio = BIO_new(BIO_f_asn1()); if (ndef_aux == NULL || asn_bio == NULL) goto err; /* ASN1 bio needs to be next to output BIO */ out = BIO_push(asn_bio, out); if (out == NULL) goto err; pop_bio = asn_bio; if (BIO_asn1_set_prefix(asn_bio, ndef_prefix, ndef_prefix_free) <= 0 || BIO_asn1_set_suffix(asn_bio, ndef_suffix, ndef_suffix_free) <= 0 || BIO_ctrl(asn_bio, BIO_C_SET_EX_ARG, 0, ndef_aux) <= 0) goto err; /* * Now let the callback prepend any digest, cipher, etc., that the BIO's * ASN1 structure needs. */ sarg.out = out; sarg.ndef_bio = NULL; sarg.boundary = NULL; /* * The asn1_cb(), must not have mutated asn_bio on error, leaving it in the * middle of some partially built, but not returned BIO chain. */ if (aux->asn1_cb(ASN1_OP_STREAM_PRE, &val, it, &sarg) <= 0) { /* * ndef_aux is now owned by asn_bio so we must not free it in the err * clean up block */ ndef_aux = NULL; goto err; } /* * We must not fail now because the callback has prepended additional * BIOs to the chain */ ndef_aux->val = val; ndef_aux->it = it; ndef_aux->ndef_bio = sarg.ndef_bio; ndef_aux->boundary = sarg.boundary; ndef_aux->out = out; return sarg.ndef_bio; err: /* BIO_pop() is NULL safe */ (void)BIO_pop(pop_bio); BIO_free(asn_bio); OPENSSL_free(ndef_aux); return NULL; } static int ndef_prefix(BIO *b, unsigned char **pbuf, int *plen, void *parg) { NDEF_SUPPORT *ndef_aux; unsigned char *p; int derlen; if (parg == NULL) return 0; ndef_aux = *(NDEF_SUPPORT **)parg; derlen = ASN1_item_ndef_i2d(ndef_aux->val, NULL, ndef_aux->it); if (derlen < 0) return 0; if ((p = OPENSSL_malloc(derlen)) == NULL) return 0; ndef_aux->derbuf = p; *pbuf = p; ASN1_item_ndef_i2d(ndef_aux->val, &p, ndef_aux->it); if (*ndef_aux->boundary == NULL) return 0; *plen = *ndef_aux->boundary - *pbuf; return 1; } static int ndef_prefix_free(BIO *b, unsigned char **pbuf, int *plen, void *parg) { NDEF_SUPPORT *ndef_aux; if (parg == NULL) return 0; ndef_aux = *(NDEF_SUPPORT **)parg; if (ndef_aux == NULL) return 0; OPENSSL_free(ndef_aux->derbuf); ndef_aux->derbuf = NULL; *pbuf = NULL; *plen = 0; return 1; } static int ndef_suffix_free(BIO *b, unsigned char **pbuf, int *plen, void *parg) { NDEF_SUPPORT **pndef_aux = (NDEF_SUPPORT **)parg; if (!ndef_prefix_free(b, pbuf, plen, parg)) return 0; OPENSSL_free(*pndef_aux); *pndef_aux = NULL; return 1; } static int ndef_suffix(BIO *b, unsigned char **pbuf, int *plen, void *parg) { NDEF_SUPPORT *ndef_aux; unsigned char *p; int derlen; const ASN1_AUX *aux; ASN1_STREAM_ARG sarg; if (parg == NULL) return 0; ndef_aux = *(NDEF_SUPPORT **)parg; aux = ndef_aux->it->funcs; /* Finalize structures */ sarg.ndef_bio = ndef_aux->ndef_bio; sarg.out = ndef_aux->out; sarg.boundary = ndef_aux->boundary; if (aux->asn1_cb(ASN1_OP_STREAM_POST, &ndef_aux->val, ndef_aux->it, &sarg) <= 0) return 0; derlen = ASN1_item_ndef_i2d(ndef_aux->val, NULL, ndef_aux->it); if (derlen < 0) return 0; if ((p = OPENSSL_malloc(derlen)) == NULL) return 0; ndef_aux->derbuf = p; *pbuf = p; derlen = ASN1_item_ndef_i2d(ndef_aux->val, &p, ndef_aux->it); if (*ndef_aux->boundary == NULL) return 0; *pbuf = *ndef_aux->boundary; *plen = derlen - (*ndef_aux->boundary - ndef_aux->derbuf); return 1; }
6,243
26.147826
79
c
openssl
openssl-master/crypto/asn1/charmap.h
/* * WARNING: do not edit! * Generated by crypto/asn1/charmap.pl * * Copyright 2000-2021 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 */ #define CHARTYPE_HOST_ANY 4096 #define CHARTYPE_HOST_DOT 8192 #define CHARTYPE_HOST_HYPHEN 16384 #define CHARTYPE_HOST_WILD 32768 /* * Mask of various character properties */ static const unsigned short char_type[] = { 1026, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 120, 0, 1, 40, 0, 0, 0, 16, 1040, 1040, 33792, 25, 25, 16400, 8208, 16, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 16, 9, 9, 16, 9, 16, 0, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 0, 1025, 0, 0, 0, 0, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 4112, 0, 0, 0, 0, 2 };
1,443
40.257143
77
h
openssl
openssl-master/crypto/asn1/d2i_param.c
/* * Copyright 2019-2021 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/asn1.h> #include "internal/asn1.h" #include "crypto/asn1.h" #include "crypto/evp.h" EVP_PKEY *d2i_KeyParams(int type, EVP_PKEY **a, const unsigned char **pp, long length) { EVP_PKEY *ret = NULL; if ((a == NULL) || (*a == NULL)) { if ((ret = EVP_PKEY_new()) == NULL) return NULL; } else ret = *a; if (type != EVP_PKEY_get_id(ret) && !EVP_PKEY_set_type(ret, type)) goto err; if (ret->ameth == NULL || ret->ameth->param_decode == NULL) { ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_TYPE); goto err; } if (!ret->ameth->param_decode(ret, pp, length)) goto err; if (a != NULL) (*a) = ret; return ret; err: if (a == NULL || *a != ret) EVP_PKEY_free(ret); return NULL; } EVP_PKEY *d2i_KeyParams_bio(int type, EVP_PKEY **a, BIO *in) { BUF_MEM *b = NULL; const unsigned char *p; void *ret = NULL; int len; len = asn1_d2i_read_bio(in, &b); if (len < 0) goto err; p = (unsigned char *)b->data; ret = d2i_KeyParams(type, a, &p, len); err: BUF_MEM_free(b); return ret; }
1,587
23.060606
74
c
openssl
openssl-master/crypto/asn1/d2i_pr.c
/* * Copyright 1995-2021 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 */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/decoder.h> #include <openssl/engine.h> #include <openssl/x509.h> #include <openssl/asn1.h> #include "crypto/asn1.h" #include "crypto/evp.h" #include "internal/asn1.h" #include "internal/sizes.h" static EVP_PKEY * d2i_PrivateKey_decoder(int keytype, EVP_PKEY **a, const unsigned char **pp, long length, OSSL_LIB_CTX *libctx, const char *propq) { OSSL_DECODER_CTX *dctx = NULL; size_t len = length; EVP_PKEY *pkey = NULL, *bak_a = NULL; EVP_PKEY **ppkey = &pkey; const char *key_name = NULL; char keytypebuf[OSSL_MAX_NAME_SIZE]; int ret; const unsigned char *p = *pp; const char *structure; PKCS8_PRIV_KEY_INFO *p8info; const ASN1_OBJECT *algoid; if (keytype != EVP_PKEY_NONE) { key_name = evp_pkey_type2name(keytype); if (key_name == NULL) return NULL; } /* This is just a probe. It might fail, so we ignore errors */ ERR_set_mark(); p8info = d2i_PKCS8_PRIV_KEY_INFO(NULL, pp, len); ERR_pop_to_mark(); if (p8info != NULL) { if (key_name == NULL && PKCS8_pkey_get0(&algoid, NULL, NULL, NULL, p8info) && OBJ_obj2txt(keytypebuf, sizeof(keytypebuf), algoid, 0)) key_name = keytypebuf; structure = "PrivateKeyInfo"; PKCS8_PRIV_KEY_INFO_free(p8info); } else { structure = "type-specific"; } *pp = p; if (a != NULL && (bak_a = *a) != NULL) ppkey = a; dctx = OSSL_DECODER_CTX_new_for_pkey(ppkey, "DER", structure, key_name, EVP_PKEY_KEYPAIR, libctx, propq); if (a != NULL) *a = bak_a; if (dctx == NULL) goto err; ret = OSSL_DECODER_from_data(dctx, pp, &len); OSSL_DECODER_CTX_free(dctx); if (ret && *ppkey != NULL && evp_keymgmt_util_has(*ppkey, OSSL_KEYMGMT_SELECT_PRIVATE_KEY)) { if (a != NULL) *a = *ppkey; return *ppkey; } err: if (ppkey != a) EVP_PKEY_free(*ppkey); return NULL; } EVP_PKEY * ossl_d2i_PrivateKey_legacy(int keytype, EVP_PKEY **a, const unsigned char **pp, long length, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *ret; const unsigned char *p = *pp; if (a == NULL || *a == NULL) { if ((ret = EVP_PKEY_new()) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB); return NULL; } } else { ret = *a; #ifndef OPENSSL_NO_ENGINE ENGINE_finish(ret->engine); ret->engine = NULL; #endif } if (!EVP_PKEY_set_type(ret, keytype)) { ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE); goto err; } ERR_set_mark(); if (!ret->ameth->old_priv_decode || !ret->ameth->old_priv_decode(ret, &p, length)) { if (ret->ameth->priv_decode != NULL || ret->ameth->priv_decode_ex != NULL) { EVP_PKEY *tmp; PKCS8_PRIV_KEY_INFO *p8 = NULL; p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, length); if (p8 == NULL) { ERR_clear_last_mark(); goto err; } tmp = evp_pkcs82pkey_legacy(p8, libctx, propq); PKCS8_PRIV_KEY_INFO_free(p8); if (tmp == NULL) { ERR_clear_last_mark(); goto err; } EVP_PKEY_free(ret); ret = tmp; ERR_pop_to_mark(); if (EVP_PKEY_type(keytype) != EVP_PKEY_get_base_id(ret)) goto err; } else { ERR_clear_last_mark(); ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } } else { ERR_clear_last_mark(); } *pp = p; if (a != NULL) *a = ret; return ret; err: if (a == NULL || *a != ret) EVP_PKEY_free(ret); return NULL; } EVP_PKEY *d2i_PrivateKey_ex(int keytype, EVP_PKEY **a, const unsigned char **pp, long length, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *ret; ret = d2i_PrivateKey_decoder(keytype, a, pp, length, libctx, propq); /* try the legacy path if the decoder failed */ if (ret == NULL) ret = ossl_d2i_PrivateKey_legacy(keytype, a, pp, length, libctx, propq); return ret; } EVP_PKEY *d2i_PrivateKey(int type, EVP_PKEY **a, const unsigned char **pp, long length) { return d2i_PrivateKey_ex(type, a, pp, length, NULL, NULL); } static EVP_PKEY *d2i_AutoPrivateKey_legacy(EVP_PKEY **a, const unsigned char **pp, long length, OSSL_LIB_CTX *libctx, const char *propq) { STACK_OF(ASN1_TYPE) *inkey; const unsigned char *p; int keytype; p = *pp; /* * Dirty trick: read in the ASN1 data into a STACK_OF(ASN1_TYPE): by * analyzing it we can determine the passed structure: this assumes the * input is surrounded by an ASN1 SEQUENCE. */ inkey = d2i_ASN1_SEQUENCE_ANY(NULL, &p, length); p = *pp; /* * Since we only need to discern "traditional format" RSA and DSA keys we * can just count the elements. */ if (sk_ASN1_TYPE_num(inkey) == 6) { keytype = EVP_PKEY_DSA; } else if (sk_ASN1_TYPE_num(inkey) == 4) { keytype = EVP_PKEY_EC; } else if (sk_ASN1_TYPE_num(inkey) == 3) { /* This seems to be PKCS8, not * traditional format */ PKCS8_PRIV_KEY_INFO *p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, length); EVP_PKEY *ret; sk_ASN1_TYPE_pop_free(inkey, ASN1_TYPE_free); if (p8 == NULL) { ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE); return NULL; } ret = evp_pkcs82pkey_legacy(p8, libctx, propq); PKCS8_PRIV_KEY_INFO_free(p8); if (ret == NULL) return NULL; *pp = p; if (a != NULL) { *a = ret; } return ret; } else { keytype = EVP_PKEY_RSA; } sk_ASN1_TYPE_pop_free(inkey, ASN1_TYPE_free); return ossl_d2i_PrivateKey_legacy(keytype, a, pp, length, libctx, propq); } /* * This works like d2i_PrivateKey() except it passes the keytype as * EVP_PKEY_NONE, which then figures out the type during decoding. */ EVP_PKEY *d2i_AutoPrivateKey_ex(EVP_PKEY **a, const unsigned char **pp, long length, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *ret; ret = d2i_PrivateKey_decoder(EVP_PKEY_NONE, a, pp, length, libctx, propq); /* try the legacy path if the decoder failed */ if (ret == NULL) ret = d2i_AutoPrivateKey_legacy(a, pp, length, libctx, propq); return ret; } EVP_PKEY *d2i_AutoPrivateKey(EVP_PKEY **a, const unsigned char **pp, long length) { return d2i_AutoPrivateKey_ex(a, pp, length, NULL, NULL); }
7,703
29.939759
80
c
openssl
openssl-master/crypto/asn1/d2i_pu.c
/* * Copyright 1995-2022 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 */ /* * DSA low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/bn.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/asn1.h> #include <openssl/rsa.h> #include <openssl/dsa.h> #include <openssl/ec.h> #include "crypto/evp.h" EVP_PKEY *d2i_PublicKey(int type, EVP_PKEY **a, const unsigned char **pp, long length) { EVP_PKEY *ret; EVP_PKEY *copy = NULL; if ((a == NULL) || (*a == NULL)) { if ((ret = EVP_PKEY_new()) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB); return NULL; } } else { ret = *a; #ifndef OPENSSL_NO_EC if (evp_pkey_is_provided(ret) && EVP_PKEY_get_base_id(ret) == EVP_PKEY_EC) { if (!evp_pkey_copy_downgraded(&copy, ret)) goto err; } #endif } if ((type != EVP_PKEY_get_id(ret) || copy != NULL) && !EVP_PKEY_set_type(ret, type)) { ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB); goto err; } switch (EVP_PKEY_get_base_id(ret)) { case EVP_PKEY_RSA: if ((ret->pkey.rsa = d2i_RSAPublicKey(NULL, pp, length)) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } break; #ifndef OPENSSL_NO_DSA case EVP_PKEY_DSA: if (!d2i_DSAPublicKey(&ret->pkey.dsa, pp, length)) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } break; #endif #ifndef OPENSSL_NO_EC case EVP_PKEY_EC: if (copy != NULL) { /* use downgraded parameters from copy */ ret->pkey.ec = copy->pkey.ec; copy->pkey.ec = NULL; } if (!o2i_ECPublicKey(&ret->pkey.ec, pp, length)) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } break; #endif default: ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE); goto err; } if (a != NULL) (*a) = ret; EVP_PKEY_free(copy); return ret; err: if (a == NULL || *a != ret) EVP_PKEY_free(ret); EVP_PKEY_free(copy); return NULL; }
2,603
25.30303
75
c
openssl
openssl-master/crypto/asn1/evp_asn1.c
/* * Copyright 1995-2021 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1.h> #include <openssl/asn1t.h> #include "crypto/asn1.h" int ASN1_TYPE_set_octetstring(ASN1_TYPE *a, unsigned char *data, int len) { ASN1_STRING *os; if ((os = ASN1_OCTET_STRING_new()) == NULL) return 0; if (!ASN1_OCTET_STRING_set(os, data, len)) { ASN1_OCTET_STRING_free(os); return 0; } ASN1_TYPE_set(a, V_ASN1_OCTET_STRING, os); return 1; } /* int max_len: for returned value * if passing NULL in data, nothing is copied but the necessary length * for it is returned. */ int ASN1_TYPE_get_octetstring(const ASN1_TYPE *a, unsigned char *data, int max_len) { int ret, num; const unsigned char *p; if ((a->type != V_ASN1_OCTET_STRING) || (a->value.octet_string == NULL)) { ERR_raise(ERR_LIB_ASN1, ASN1_R_DATA_IS_WRONG); return -1; } p = ASN1_STRING_get0_data(a->value.octet_string); ret = ASN1_STRING_length(a->value.octet_string); if (ret < max_len) num = ret; else num = max_len; if (num > 0 && data != NULL) memcpy(data, p, num); return ret; } static ossl_inline void asn1_type_init_oct(ASN1_OCTET_STRING *oct, unsigned char *data, int len) { oct->data = data; oct->type = V_ASN1_OCTET_STRING; oct->length = len; oct->flags = 0; } static int asn1_type_get_int_oct(ASN1_OCTET_STRING *oct, int32_t anum, long *num, unsigned char *data, int max_len) { int ret = ASN1_STRING_length(oct), n; if (num != NULL) *num = anum; if (max_len > ret) n = ret; else n = max_len; if (data != NULL) memcpy(data, ASN1_STRING_get0_data(oct), n); return ret; } typedef struct { int32_t num; ASN1_OCTET_STRING *oct; } asn1_int_oct; ASN1_SEQUENCE(asn1_int_oct) = { ASN1_EMBED(asn1_int_oct, num, INT32), ASN1_SIMPLE(asn1_int_oct, oct, ASN1_OCTET_STRING) } static_ASN1_SEQUENCE_END(asn1_int_oct) DECLARE_ASN1_ITEM(asn1_int_oct) int ASN1_TYPE_set_int_octetstring(ASN1_TYPE *a, long num, unsigned char *data, int len) { asn1_int_oct atmp; ASN1_OCTET_STRING oct; atmp.num = num; atmp.oct = &oct; asn1_type_init_oct(&oct, data, len); if (ASN1_TYPE_pack_sequence(ASN1_ITEM_rptr(asn1_int_oct), &atmp, &a)) return 1; return 0; } int ASN1_TYPE_get_int_octetstring(const ASN1_TYPE *a, long *num, unsigned char *data, int max_len) { asn1_int_oct *atmp = NULL; int ret = -1; if ((a->type != V_ASN1_SEQUENCE) || (a->value.sequence == NULL)) { goto err; } atmp = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(asn1_int_oct), a); if (atmp == NULL) goto err; ret = asn1_type_get_int_oct(atmp->oct, atmp->num, num, data, max_len); if (ret == -1) { err: ERR_raise(ERR_LIB_ASN1, ASN1_R_DATA_IS_WRONG); } M_ASN1_free_of(atmp, asn1_int_oct); return ret; } typedef struct { ASN1_OCTET_STRING *oct; int32_t num; } asn1_oct_int; /* * Defined in RFC 5084 - * Section 2. "Content-Authenticated Encryption Algorithms" */ ASN1_SEQUENCE(asn1_oct_int) = { ASN1_SIMPLE(asn1_oct_int, oct, ASN1_OCTET_STRING), ASN1_EMBED(asn1_oct_int, num, INT32) } static_ASN1_SEQUENCE_END(asn1_oct_int) DECLARE_ASN1_ITEM(asn1_oct_int) int ossl_asn1_type_set_octetstring_int(ASN1_TYPE *a, long num, unsigned char *data, int len) { asn1_oct_int atmp; ASN1_OCTET_STRING oct; atmp.num = num; atmp.oct = &oct; asn1_type_init_oct(&oct, data, len); if (ASN1_TYPE_pack_sequence(ASN1_ITEM_rptr(asn1_oct_int), &atmp, &a)) return 1; return 0; } int ossl_asn1_type_get_octetstring_int(const ASN1_TYPE *a, long *num, unsigned char *data, int max_len) { asn1_oct_int *atmp = NULL; int ret = -1; if ((a->type != V_ASN1_SEQUENCE) || (a->value.sequence == NULL)) goto err; atmp = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(asn1_oct_int), a); if (atmp == NULL) goto err; ret = asn1_type_get_int_oct(atmp->oct, atmp->num, num, data, max_len); if (ret == -1) { err: ERR_raise(ERR_LIB_ASN1, ASN1_R_DATA_IS_WRONG); } M_ASN1_free_of(atmp, asn1_oct_int); return ret; }
4,793
24.5
83
c
openssl
openssl-master/crypto/asn1/f_int.c
/* * Copyright 1995-2020 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 */ #include <stdio.h> #include "crypto/ctype.h" #include "internal/cryptlib.h" #include <openssl/buffer.h> #include <openssl/asn1.h> int i2a_ASN1_INTEGER(BIO *bp, const ASN1_INTEGER *a) { int i, n = 0; static const char *h = "0123456789ABCDEF"; char buf[2]; if (a == NULL) return 0; if (a->type & V_ASN1_NEG) { if (BIO_write(bp, "-", 1) != 1) goto err; n = 1; } if (a->length == 0) { if (BIO_write(bp, "00", 2) != 2) goto err; n += 2; } else { for (i = 0; i < a->length; i++) { if ((i != 0) && (i % 35 == 0)) { if (BIO_write(bp, "\\\n", 2) != 2) goto err; n += 2; } buf[0] = h[((unsigned char)a->data[i] >> 4) & 0x0f]; buf[1] = h[((unsigned char)a->data[i]) & 0x0f]; if (BIO_write(bp, buf, 2) != 2) goto err; n += 2; } } return n; err: return -1; } int a2i_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *bs, char *buf, int size) { int i, j, k, m, n, again, bufsize; unsigned char *s = NULL, *sp; unsigned char *bufp; int num = 0, slen = 0, first = 1; bs->type = V_ASN1_INTEGER; bufsize = BIO_gets(bp, buf, size); for (;;) { if (bufsize < 1) goto err; i = bufsize; if (buf[i - 1] == '\n') buf[--i] = '\0'; if (i == 0) goto err; if (buf[i - 1] == '\r') buf[--i] = '\0'; if (i == 0) goto err; again = (buf[i - 1] == '\\'); for (j = 0; j < i; j++) { if (!ossl_isxdigit(buf[j])) { i = j; break; } } buf[i] = '\0'; /* * We have now cleared all the crap off the end of the line */ if (i < 2) goto err; bufp = (unsigned char *)buf; if (first) { first = 0; if ((bufp[0] == '0') && (bufp[1] == '0')) { bufp += 2; i -= 2; } } k = 0; i -= again; if (i % 2 != 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ODD_NUMBER_OF_CHARS); OPENSSL_free(s); return 0; } i /= 2; if (num + i > slen) { sp = OPENSSL_clear_realloc(s, slen, num + i * 2); if (sp == NULL) { OPENSSL_free(s); return 0; } s = sp; slen = num + i * 2; } for (j = 0; j < i; j++, k += 2) { for (n = 0; n < 2; n++) { m = OPENSSL_hexchar2int(bufp[k + n]); if (m < 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_NON_HEX_CHARACTERS); goto err; } s[num + j] <<= 4; s[num + j] |= m; } } num += i; if (again) bufsize = BIO_gets(bp, buf, size); else break; } bs->length = num; bs->data = s; return 1; err: ERR_raise(ERR_LIB_ASN1, ASN1_R_SHORT_LINE); OPENSSL_free(s); return 0; } int i2a_ASN1_ENUMERATED(BIO *bp, const ASN1_ENUMERATED *a) { return i2a_ASN1_INTEGER(bp, a); } int a2i_ASN1_ENUMERATED(BIO *bp, ASN1_ENUMERATED *bs, char *buf, int size) { int rv = a2i_ASN1_INTEGER(bp, bs, buf, size); if (rv == 1) bs->type = V_ASN1_INTEGER | (bs->type & V_ASN1_NEG); return rv; }
3,910
24.232258
74
c
openssl
openssl-master/crypto/asn1/f_string.c
/* * Copyright 1995-2020 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 */ #include <stdio.h> #include "crypto/ctype.h" #include "internal/cryptlib.h" #include <openssl/buffer.h> #include <openssl/asn1.h> int i2a_ASN1_STRING(BIO *bp, const ASN1_STRING *a, int type) { int i, n = 0; static const char *h = "0123456789ABCDEF"; char buf[2]; if (a == NULL) return 0; if (a->length == 0) { if (BIO_write(bp, "0", 1) != 1) goto err; n = 1; } else { for (i = 0; i < a->length; i++) { if ((i != 0) && (i % 35 == 0)) { if (BIO_write(bp, "\\\n", 2) != 2) goto err; n += 2; } buf[0] = h[((unsigned char)a->data[i] >> 4) & 0x0f]; buf[1] = h[((unsigned char)a->data[i]) & 0x0f]; if (BIO_write(bp, buf, 2) != 2) goto err; n += 2; } } return n; err: return -1; } int a2i_ASN1_STRING(BIO *bp, ASN1_STRING *bs, char *buf, int size) { int i, j, k, m, n, again, bufsize; unsigned char *s = NULL, *sp; unsigned char *bufp; int num = 0, slen = 0, first = 1; bufsize = BIO_gets(bp, buf, size); for (;;) { if (bufsize < 1) { if (first) break; else goto err; } first = 0; i = bufsize; if (buf[i - 1] == '\n') buf[--i] = '\0'; if (i == 0) goto err; if (buf[i - 1] == '\r') buf[--i] = '\0'; if (i == 0) goto err; again = (buf[i - 1] == '\\'); for (j = i - 1; j > 0; j--) { if (!ossl_isxdigit(buf[j])) { i = j; break; } } buf[i] = '\0'; /* * We have now cleared all the crap off the end of the line */ if (i < 2) goto err; bufp = (unsigned char *)buf; k = 0; i -= again; if (i % 2 != 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ODD_NUMBER_OF_CHARS); OPENSSL_free(s); return 0; } i /= 2; if (num + i > slen) { sp = OPENSSL_realloc(s, (unsigned int)num + i * 2); if (sp == NULL) { OPENSSL_free(s); return 0; } s = sp; slen = num + i * 2; } for (j = 0; j < i; j++, k += 2) { for (n = 0; n < 2; n++) { m = OPENSSL_hexchar2int(bufp[k + n]); if (m < 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_NON_HEX_CHARACTERS); OPENSSL_free(s); return 0; } s[num + j] <<= 4; s[num + j] |= m; } } num += i; if (again) bufsize = BIO_gets(bp, buf, size); else break; } bs->length = num; bs->data = s; return 1; err: ERR_raise(ERR_LIB_ASN1, ASN1_R_SHORT_LINE); OPENSSL_free(s); return 0; }
3,400
24.192593
74
c
openssl
openssl-master/crypto/asn1/i2d_evp.c
/* * Copyright 1995-2022 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 */ /* * Low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/encoder.h> #include <openssl/buffer.h> #include <openssl/x509.h> #include <openssl/rsa.h> /* For i2d_RSAPublicKey */ #include <openssl/dsa.h> /* For i2d_DSAPublicKey */ #include <openssl/ec.h> /* For i2o_ECPublicKey */ #include "crypto/asn1.h" #include "crypto/evp.h" struct type_and_structure_st { const char *output_type; const char *output_structure; }; static int i2d_provided(const EVP_PKEY *a, int selection, const struct type_and_structure_st *output_info, unsigned char **pp) { int ret; for (ret = -1; ret == -1 && output_info->output_type != NULL; output_info++) { /* * The i2d_ calls don't take a boundary length for *pp. However, * OSSL_ENCODER_to_data() needs one, so we make one up. Because * OSSL_ENCODER_to_data() decrements this number by the amount of * bytes written, we need to calculate the length written further * down, when pp != NULL. */ size_t len = INT_MAX; int pp_was_NULL = (pp == NULL || *pp == NULL); OSSL_ENCODER_CTX *ctx; ctx = OSSL_ENCODER_CTX_new_for_pkey(a, selection, output_info->output_type, output_info->output_structure, NULL); if (ctx == NULL) return -1; if (OSSL_ENCODER_to_data(ctx, pp, &len)) { if (pp_was_NULL) ret = (int)len; else ret = INT_MAX - (int)len; } OSSL_ENCODER_CTX_free(ctx); } if (ret == -1) ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_TYPE); return ret; } int i2d_KeyParams(const EVP_PKEY *a, unsigned char **pp) { if (evp_pkey_is_provided(a)) { static const struct type_and_structure_st output_info[] = { { "DER", "type-specific" }, { NULL, } }; return i2d_provided(a, EVP_PKEY_KEY_PARAMETERS, output_info, pp); } if (a->ameth != NULL && a->ameth->param_encode != NULL) return a->ameth->param_encode(a, pp); ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_TYPE); return -1; } int i2d_KeyParams_bio(BIO *bp, const EVP_PKEY *pkey) { return ASN1_i2d_bio_of(EVP_PKEY, i2d_KeyParams, bp, pkey); } int i2d_PrivateKey(const EVP_PKEY *a, unsigned char **pp) { if (evp_pkey_is_provided(a)) { static const struct type_and_structure_st output_info[] = { { "DER", "type-specific" }, { "DER", "PrivateKeyInfo" }, { NULL, } }; return i2d_provided(a, EVP_PKEY_KEYPAIR, output_info, pp); } if (a->ameth != NULL && a->ameth->old_priv_encode != NULL) { return a->ameth->old_priv_encode(a, pp); } if (a->ameth != NULL && a->ameth->priv_encode != NULL) { PKCS8_PRIV_KEY_INFO *p8 = EVP_PKEY2PKCS8(a); int ret = 0; if (p8 != NULL) { ret = i2d_PKCS8_PRIV_KEY_INFO(p8, pp); PKCS8_PRIV_KEY_INFO_free(p8); } return ret; } ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE); return -1; } int i2d_PublicKey(const EVP_PKEY *a, unsigned char **pp) { if (evp_pkey_is_provided(a)) { static const struct type_and_structure_st output_info[] = { { "DER", "type-specific" }, { "blob", NULL }, /* for EC */ { NULL, } }; return i2d_provided(a, EVP_PKEY_PUBLIC_KEY, output_info, pp); } switch (EVP_PKEY_get_base_id(a)) { case EVP_PKEY_RSA: return i2d_RSAPublicKey(EVP_PKEY_get0_RSA(a), pp); #ifndef OPENSSL_NO_DSA case EVP_PKEY_DSA: return i2d_DSAPublicKey(EVP_PKEY_get0_DSA(a), pp); #endif #ifndef OPENSSL_NO_EC case EVP_PKEY_EC: return i2o_ECPublicKey(EVP_PKEY_get0_EC_KEY(a), pp); #endif default: ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE); return -1; } }
4,601
29.885906
74
c
openssl
openssl-master/crypto/asn1/n_pkey.c
/* * Copyright 1995-2021 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 */ #include <openssl/opensslconf.h> #include "internal/cryptlib.h" #include <stdio.h> #include <openssl/rsa.h> #include <openssl/objects.h> #include <openssl/asn1t.h> #include <openssl/evp.h> #include <openssl/x509.h> #define ASN1_BROKEN_SEQUENCE(tname) \ static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_BROKEN, 0, 0, 0, 0}; \ ASN1_SEQUENCE(tname) #define static_ASN1_BROKEN_SEQUENCE_END(stname) \ static_ASN1_SEQUENCE_END_ref(stname, stname) typedef struct netscape_pkey_st { int32_t version; X509_ALGOR *algor; ASN1_OCTET_STRING *private_key; } NETSCAPE_PKEY; typedef struct netscape_encrypted_pkey_st { ASN1_OCTET_STRING *os; /* * This is the same structure as DigestInfo so use it: although this * isn't really anything to do with digests. */ X509_SIG *enckey; } NETSCAPE_ENCRYPTED_PKEY; ASN1_BROKEN_SEQUENCE(NETSCAPE_ENCRYPTED_PKEY) = { ASN1_SIMPLE(NETSCAPE_ENCRYPTED_PKEY, os, ASN1_OCTET_STRING), ASN1_SIMPLE(NETSCAPE_ENCRYPTED_PKEY, enckey, X509_SIG) } static_ASN1_BROKEN_SEQUENCE_END(NETSCAPE_ENCRYPTED_PKEY) DECLARE_ASN1_FUNCTIONS(NETSCAPE_ENCRYPTED_PKEY) DECLARE_ASN1_ENCODE_FUNCTIONS_name(NETSCAPE_ENCRYPTED_PKEY, NETSCAPE_ENCRYPTED_PKEY) IMPLEMENT_ASN1_FUNCTIONS(NETSCAPE_ENCRYPTED_PKEY) ASN1_SEQUENCE(NETSCAPE_PKEY) = { ASN1_EMBED(NETSCAPE_PKEY, version, INT32), ASN1_SIMPLE(NETSCAPE_PKEY, algor, X509_ALGOR), ASN1_SIMPLE(NETSCAPE_PKEY, private_key, ASN1_OCTET_STRING) } static_ASN1_SEQUENCE_END(NETSCAPE_PKEY) DECLARE_ASN1_FUNCTIONS(NETSCAPE_PKEY) DECLARE_ASN1_ENCODE_FUNCTIONS_name(NETSCAPE_PKEY, NETSCAPE_PKEY) IMPLEMENT_ASN1_FUNCTIONS(NETSCAPE_PKEY)
2,017
33.20339
84
c
openssl
openssl-master/crypto/asn1/nsseq.c
/* * Copyright 1999-2016 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 */ #include <stdio.h> #include <stdlib.h> #include <openssl/asn1t.h> #include <openssl/x509.h> #include <openssl/objects.h> static int nsseq_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if (operation == ASN1_OP_NEW_POST) { NETSCAPE_CERT_SEQUENCE *nsseq; nsseq = (NETSCAPE_CERT_SEQUENCE *)*pval; nsseq->type = OBJ_nid2obj(NID_netscape_cert_sequence); } return 1; } /* Netscape certificate sequence structure */ ASN1_SEQUENCE_cb(NETSCAPE_CERT_SEQUENCE, nsseq_cb) = { ASN1_SIMPLE(NETSCAPE_CERT_SEQUENCE, type, ASN1_OBJECT), ASN1_EXP_SEQUENCE_OF_OPT(NETSCAPE_CERT_SEQUENCE, certs, X509, 0) } ASN1_SEQUENCE_END_cb(NETSCAPE_CERT_SEQUENCE, NETSCAPE_CERT_SEQUENCE) IMPLEMENT_ASN1_FUNCTIONS(NETSCAPE_CERT_SEQUENCE)
1,144
31.714286
74
c
openssl
openssl-master/crypto/asn1/p5_pbe.c
/* * Copyright 1999-2021 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/x509.h> #include <openssl/rand.h> /* PKCS#5 password based encryption structure */ ASN1_SEQUENCE(PBEPARAM) = { ASN1_SIMPLE(PBEPARAM, salt, ASN1_OCTET_STRING), ASN1_SIMPLE(PBEPARAM, iter, ASN1_INTEGER) } ASN1_SEQUENCE_END(PBEPARAM) IMPLEMENT_ASN1_FUNCTIONS(PBEPARAM) /* Set an algorithm identifier for a PKCS#5 PBE algorithm */ int PKCS5_pbe_set0_algor_ex(X509_ALGOR *algor, int alg, int iter, const unsigned char *salt, int saltlen, OSSL_LIB_CTX *ctx) { PBEPARAM *pbe = NULL; ASN1_STRING *pbe_str = NULL; unsigned char *sstr = NULL; pbe = PBEPARAM_new(); if (pbe == NULL) { /* ERR_R_ASN1_LIB, because PBEPARAM_new() is defined in crypto/asn1 */ ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if (iter <= 0) iter = PKCS5_DEFAULT_ITER; if (!ASN1_INTEGER_set(pbe->iter, iter)) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if (!saltlen) saltlen = PKCS5_SALT_LEN; if (saltlen < 0) goto err; sstr = OPENSSL_malloc(saltlen); if (sstr == NULL) goto err; if (salt) memcpy(sstr, salt, saltlen); else if (RAND_bytes_ex(ctx, sstr, saltlen, 0) <= 0) goto err; ASN1_STRING_set0(pbe->salt, sstr, saltlen); sstr = NULL; if (!ASN1_item_pack(pbe, ASN1_ITEM_rptr(PBEPARAM), &pbe_str)) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } PBEPARAM_free(pbe); pbe = NULL; if (X509_ALGOR_set0(algor, OBJ_nid2obj(alg), V_ASN1_SEQUENCE, pbe_str)) return 1; err: OPENSSL_free(sstr); PBEPARAM_free(pbe); ASN1_STRING_free(pbe_str); return 0; } int PKCS5_pbe_set0_algor(X509_ALGOR *algor, int alg, int iter, const unsigned char *salt, int saltlen) { return PKCS5_pbe_set0_algor_ex(algor, alg, iter, salt, saltlen, NULL); } /* Return an algorithm identifier for a PKCS#5 PBE algorithm */ X509_ALGOR *PKCS5_pbe_set_ex(int alg, int iter, const unsigned char *salt, int saltlen, OSSL_LIB_CTX *ctx) { X509_ALGOR *ret; ret = X509_ALGOR_new(); if (ret == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_X509_LIB); return NULL; } if (PKCS5_pbe_set0_algor_ex(ret, alg, iter, salt, saltlen, ctx)) return ret; X509_ALGOR_free(ret); return NULL; } X509_ALGOR *PKCS5_pbe_set(int alg, int iter, const unsigned char *salt, int saltlen) { return PKCS5_pbe_set_ex(alg, iter, salt, saltlen, NULL); }
3,071
26.185841
78
c
openssl
openssl-master/crypto/asn1/p5_pbev2.c
/* * Copyright 1999-2022 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include "crypto/asn1.h" #include <openssl/asn1t.h> #include <openssl/core.h> #include <openssl/core_names.h> #include <openssl/x509.h> #include <openssl/rand.h> /* PKCS#5 v2.0 password based encryption structures */ ASN1_SEQUENCE(PBE2PARAM) = { ASN1_SIMPLE(PBE2PARAM, keyfunc, X509_ALGOR), ASN1_SIMPLE(PBE2PARAM, encryption, X509_ALGOR) } ASN1_SEQUENCE_END(PBE2PARAM) IMPLEMENT_ASN1_FUNCTIONS(PBE2PARAM) ASN1_SEQUENCE(PBKDF2PARAM) = { ASN1_SIMPLE(PBKDF2PARAM, salt, ASN1_ANY), ASN1_SIMPLE(PBKDF2PARAM, iter, ASN1_INTEGER), ASN1_OPT(PBKDF2PARAM, keylength, ASN1_INTEGER), ASN1_OPT(PBKDF2PARAM, prf, X509_ALGOR) } ASN1_SEQUENCE_END(PBKDF2PARAM) IMPLEMENT_ASN1_FUNCTIONS(PBKDF2PARAM) /* * Return an algorithm identifier for a PKCS#5 v2.0 PBE algorithm: yes I know * this is horrible! Extended version to allow application supplied PRF NID * and IV. */ X509_ALGOR *PKCS5_pbe2_set_iv_ex(const EVP_CIPHER *cipher, int iter, unsigned char *salt, int saltlen, unsigned char *aiv, int prf_nid, OSSL_LIB_CTX *libctx) { X509_ALGOR *scheme = NULL, *ret = NULL; int alg_nid, keylen, ivlen; EVP_CIPHER_CTX *ctx = NULL; unsigned char iv[EVP_MAX_IV_LENGTH]; PBE2PARAM *pbe2 = NULL; alg_nid = EVP_CIPHER_get_type(cipher); if (alg_nid == NID_undef) { ERR_raise(ERR_LIB_ASN1, ASN1_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER); goto err; } if ((pbe2 = PBE2PARAM_new()) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } /* Setup the AlgorithmIdentifier for the encryption scheme */ scheme = pbe2->encryption; scheme->algorithm = OBJ_nid2obj(alg_nid); if ((scheme->parameter = ASN1_TYPE_new()) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } /* Create random IV */ ivlen = EVP_CIPHER_get_iv_length(cipher); if (ivlen > 0) { if (aiv) memcpy(iv, aiv, ivlen); else if (RAND_bytes_ex(libctx, iv, ivlen, 0) <= 0) goto err; } ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB); goto err; } /* Dummy cipherinit to just setup the IV, and PRF */ if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, iv, 0)) goto err; if (EVP_CIPHER_param_to_asn1(ctx, scheme->parameter) <= 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ERROR_SETTING_CIPHER_PARAMS); goto err; } /* * If prf NID unspecified see if cipher has a preference. An error is OK * here: just means use default PRF. */ ERR_set_mark(); if ((prf_nid == -1) && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_PBE_PRF_NID, 0, &prf_nid) <= 0) { prf_nid = NID_hmacWithSHA256; } ERR_pop_to_mark(); EVP_CIPHER_CTX_free(ctx); ctx = NULL; /* If its RC2 then we'd better setup the key length */ if (alg_nid == NID_rc2_cbc) keylen = EVP_CIPHER_get_key_length(cipher); else keylen = -1; /* Setup keyfunc */ X509_ALGOR_free(pbe2->keyfunc); pbe2->keyfunc = PKCS5_pbkdf2_set_ex(iter, salt, saltlen, prf_nid, keylen, libctx); if (pbe2->keyfunc == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } /* Now set up top level AlgorithmIdentifier */ if ((ret = X509_ALGOR_new()) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_X509_LIB); goto err; } ret->algorithm = OBJ_nid2obj(NID_pbes2); /* Encode PBE2PARAM into parameter */ if (!ASN1_TYPE_pack_sequence(ASN1_ITEM_rptr(PBE2PARAM), pbe2, &ret->parameter)) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } PBE2PARAM_free(pbe2); pbe2 = NULL; return ret; err: EVP_CIPHER_CTX_free(ctx); PBE2PARAM_free(pbe2); /* Note 'scheme' is freed as part of pbe2 */ X509_ALGOR_free(ret); return NULL; } X509_ALGOR *PKCS5_pbe2_set_iv(const EVP_CIPHER *cipher, int iter, unsigned char *salt, int saltlen, unsigned char *aiv, int prf_nid) { return PKCS5_pbe2_set_iv_ex(cipher, iter, salt, saltlen, aiv, prf_nid, NULL); } X509_ALGOR *PKCS5_pbe2_set(const EVP_CIPHER *cipher, int iter, unsigned char *salt, int saltlen) { return PKCS5_pbe2_set_iv_ex(cipher, iter, salt, saltlen, NULL, -1, NULL); } X509_ALGOR *PKCS5_pbkdf2_set_ex(int iter, unsigned char *salt, int saltlen, int prf_nid, int keylen, OSSL_LIB_CTX *libctx) { X509_ALGOR *keyfunc = NULL; PBKDF2PARAM *kdf = NULL; ASN1_OCTET_STRING *osalt = NULL; if ((kdf = PBKDF2PARAM_new()) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if ((osalt = ASN1_OCTET_STRING_new()) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } kdf->salt->value.octet_string = osalt; kdf->salt->type = V_ASN1_OCTET_STRING; if (saltlen < 0) { ERR_raise(ERR_LIB_ASN1, ERR_R_PASSED_INVALID_ARGUMENT); goto err; } if (saltlen == 0) saltlen = PKCS5_SALT_LEN; if ((osalt->data = OPENSSL_malloc(saltlen)) == NULL) goto err; osalt->length = saltlen; if (salt) { memcpy(osalt->data, salt, saltlen); } else if (RAND_bytes_ex(libctx, osalt->data, saltlen, 0) <= 0) { ERR_raise(ERR_LIB_ASN1, ERR_R_RAND_LIB); goto err; } if (iter <= 0) iter = PKCS5_DEFAULT_ITER; if (!ASN1_INTEGER_set(kdf->iter, iter)) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } /* If have a key len set it up */ if (keylen > 0) { if ((kdf->keylength = ASN1_INTEGER_new()) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if (!ASN1_INTEGER_set(kdf->keylength, keylen)) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } } /* prf can stay NULL if we are using hmacWithSHA1 */ if (prf_nid > 0 && prf_nid != NID_hmacWithSHA1) { kdf->prf = ossl_X509_ALGOR_from_nid(prf_nid, V_ASN1_NULL, NULL); if (kdf->prf == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_X509_LIB); goto err; } } /* Finally setup the keyfunc structure */ keyfunc = X509_ALGOR_new(); if (keyfunc == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_X509_LIB); goto err; } keyfunc->algorithm = OBJ_nid2obj(NID_id_pbkdf2); /* Encode PBKDF2PARAM into parameter of pbe2 */ if (!ASN1_TYPE_pack_sequence(ASN1_ITEM_rptr(PBKDF2PARAM), kdf, &keyfunc->parameter)) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } PBKDF2PARAM_free(kdf); return keyfunc; err: PBKDF2PARAM_free(kdf); X509_ALGOR_free(keyfunc); return NULL; } X509_ALGOR *PKCS5_pbkdf2_set(int iter, unsigned char *salt, int saltlen, int prf_nid, int keylen) { return PKCS5_pbkdf2_set_ex(iter, salt, saltlen, prf_nid, keylen, NULL); }
7,780
27.192029
77
c
openssl
openssl-master/crypto/asn1/p5_scrypt.c
/* * Copyright 2015-2021 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/core_names.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/rand.h> #include "crypto/evp.h" #ifndef OPENSSL_NO_SCRYPT /* PKCS#5 scrypt password based encryption structures */ ASN1_SEQUENCE(SCRYPT_PARAMS) = { ASN1_SIMPLE(SCRYPT_PARAMS, salt, ASN1_OCTET_STRING), ASN1_SIMPLE(SCRYPT_PARAMS, costParameter, ASN1_INTEGER), ASN1_SIMPLE(SCRYPT_PARAMS, blockSize, ASN1_INTEGER), ASN1_SIMPLE(SCRYPT_PARAMS, parallelizationParameter, ASN1_INTEGER), ASN1_OPT(SCRYPT_PARAMS, keyLength, ASN1_INTEGER), } ASN1_SEQUENCE_END(SCRYPT_PARAMS) IMPLEMENT_ASN1_FUNCTIONS(SCRYPT_PARAMS) static X509_ALGOR *pkcs5_scrypt_set(const unsigned char *salt, size_t saltlen, size_t keylen, uint64_t N, uint64_t r, uint64_t p); /* * Return an algorithm identifier for a PKCS#5 v2.0 PBE algorithm using scrypt */ X509_ALGOR *PKCS5_pbe2_set_scrypt(const EVP_CIPHER *cipher, const unsigned char *salt, int saltlen, unsigned char *aiv, uint64_t N, uint64_t r, uint64_t p) { X509_ALGOR *scheme = NULL, *ret = NULL; int alg_nid; size_t keylen = 0; EVP_CIPHER_CTX *ctx = NULL; unsigned char iv[EVP_MAX_IV_LENGTH]; PBE2PARAM *pbe2 = NULL; if (!cipher) { ERR_raise(ERR_LIB_ASN1, ERR_R_PASSED_NULL_PARAMETER); goto err; } if (EVP_PBE_scrypt(NULL, 0, NULL, 0, N, r, p, 0, NULL, 0) == 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_SCRYPT_PARAMETERS); goto err; } alg_nid = EVP_CIPHER_get_type(cipher); if (alg_nid == NID_undef) { ERR_raise(ERR_LIB_ASN1, ASN1_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER); goto err; } pbe2 = PBE2PARAM_new(); if (pbe2 == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } /* Setup the AlgorithmIdentifier for the encryption scheme */ scheme = pbe2->encryption; scheme->algorithm = OBJ_nid2obj(alg_nid); scheme->parameter = ASN1_TYPE_new(); if (scheme->parameter == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } /* Create random IV */ if (EVP_CIPHER_get_iv_length(cipher)) { if (aiv) memcpy(iv, aiv, EVP_CIPHER_get_iv_length(cipher)); else if (RAND_bytes(iv, EVP_CIPHER_get_iv_length(cipher)) <= 0) goto err; } ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB); goto err; } /* Dummy cipherinit to just setup the IV */ if (EVP_CipherInit_ex(ctx, cipher, NULL, NULL, iv, 0) == 0) goto err; if (EVP_CIPHER_param_to_asn1(ctx, scheme->parameter) <= 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ERROR_SETTING_CIPHER_PARAMS); goto err; } EVP_CIPHER_CTX_free(ctx); ctx = NULL; /* If its RC2 then we'd better setup the key length */ if (alg_nid == NID_rc2_cbc) keylen = EVP_CIPHER_get_key_length(cipher); /* Setup keyfunc */ X509_ALGOR_free(pbe2->keyfunc); pbe2->keyfunc = pkcs5_scrypt_set(salt, saltlen, keylen, N, r, p); if (pbe2->keyfunc == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } /* Now set up top level AlgorithmIdentifier */ ret = X509_ALGOR_new(); if (ret == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } ret->algorithm = OBJ_nid2obj(NID_pbes2); /* Encode PBE2PARAM into parameter */ if (ASN1_TYPE_pack_sequence(ASN1_ITEM_rptr(PBE2PARAM), pbe2, &ret->parameter) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } PBE2PARAM_free(pbe2); pbe2 = NULL; return ret; err: PBE2PARAM_free(pbe2); X509_ALGOR_free(ret); EVP_CIPHER_CTX_free(ctx); return NULL; } static X509_ALGOR *pkcs5_scrypt_set(const unsigned char *salt, size_t saltlen, size_t keylen, uint64_t N, uint64_t r, uint64_t p) { X509_ALGOR *keyfunc = NULL; SCRYPT_PARAMS *sparam = SCRYPT_PARAMS_new(); if (sparam == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if (!saltlen) saltlen = PKCS5_SALT_LEN; /* This will either copy salt or grow the buffer */ if (ASN1_STRING_set(sparam->salt, salt, saltlen) == 0) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if (salt == NULL && RAND_bytes(sparam->salt->data, saltlen) <= 0) goto err; if (ASN1_INTEGER_set_uint64(sparam->costParameter, N) == 0) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if (ASN1_INTEGER_set_uint64(sparam->blockSize, r) == 0) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if (ASN1_INTEGER_set_uint64(sparam->parallelizationParameter, p) == 0) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } /* If have a key len set it up */ if (keylen > 0) { sparam->keyLength = ASN1_INTEGER_new(); if (sparam->keyLength == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } if (ASN1_INTEGER_set_int64(sparam->keyLength, keylen) == 0) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } } /* Finally setup the keyfunc structure */ keyfunc = X509_ALGOR_new(); if (keyfunc == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } keyfunc->algorithm = OBJ_nid2obj(NID_id_scrypt); /* Encode SCRYPT_PARAMS into parameter of pbe2 */ if (ASN1_TYPE_pack_sequence(ASN1_ITEM_rptr(SCRYPT_PARAMS), sparam, &keyfunc->parameter) == NULL) { ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); goto err; } SCRYPT_PARAMS_free(sparam); return keyfunc; err: SCRYPT_PARAMS_free(sparam); X509_ALGOR_free(keyfunc); return NULL; } int PKCS5_v2_scrypt_keyivgen_ex(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *c, const EVP_MD *md, int en_de, OSSL_LIB_CTX *libctx, const char *propq) { unsigned char *salt, key[EVP_MAX_KEY_LENGTH]; uint64_t p, r, N; size_t saltlen; size_t keylen = 0; int t, rv = 0; SCRYPT_PARAMS *sparam = NULL; if (EVP_CIPHER_CTX_get0_cipher(ctx) == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET); goto err; } /* Decode parameter */ sparam = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(SCRYPT_PARAMS), param); if (sparam == NULL) { ERR_raise(ERR_LIB_EVP, EVP_R_DECODE_ERROR); goto err; } t = EVP_CIPHER_CTX_get_key_length(ctx); if (t < 0) { ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH); goto err; } keylen = t; /* Now check the parameters of sparam */ if (sparam->keyLength) { uint64_t spkeylen; if ((ASN1_INTEGER_get_uint64(&spkeylen, sparam->keyLength) == 0) || (spkeylen != keylen)) { ERR_raise(ERR_LIB_EVP, EVP_R_UNSUPPORTED_KEYLENGTH); goto err; } } /* Check all parameters fit in uint64_t and are acceptable to scrypt */ if (ASN1_INTEGER_get_uint64(&N, sparam->costParameter) == 0 || ASN1_INTEGER_get_uint64(&r, sparam->blockSize) == 0 || ASN1_INTEGER_get_uint64(&p, sparam->parallelizationParameter) == 0 || EVP_PBE_scrypt_ex(NULL, 0, NULL, 0, N, r, p, 0, NULL, 0, libctx, propq) == 0) { ERR_raise(ERR_LIB_EVP, EVP_R_ILLEGAL_SCRYPT_PARAMETERS); goto err; } /* it seems that its all OK */ salt = sparam->salt->data; saltlen = sparam->salt->length; if (EVP_PBE_scrypt_ex(pass, passlen, salt, saltlen, N, r, p, 0, key, keylen, libctx, propq) == 0) goto err; rv = EVP_CipherInit_ex(ctx, NULL, NULL, key, NULL, en_de); err: if (keylen) OPENSSL_cleanse(key, keylen); SCRYPT_PARAMS_free(sparam); return rv; } int PKCS5_v2_scrypt_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *c, const EVP_MD *md, int en_de) { return PKCS5_v2_scrypt_keyivgen_ex(ctx, pass, passlen, param, c, md, en_de, NULL, NULL); } #endif /* OPENSSL_NO_SCRYPT */
9,130
28.266026
92
c
openssl
openssl-master/crypto/asn1/p8_pkey.c
/* * Copyright 1999-2020 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/x509.h> #include "crypto/x509.h" /* Minor tweak to operation: zero private key data */ static int pkey_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { /* Since the structure must still be valid use ASN1_OP_FREE_PRE */ if (operation == ASN1_OP_FREE_PRE) { PKCS8_PRIV_KEY_INFO *key = (PKCS8_PRIV_KEY_INFO *)*pval; if (key->pkey) OPENSSL_cleanse(key->pkey->data, key->pkey->length); } return 1; } ASN1_SEQUENCE_cb(PKCS8_PRIV_KEY_INFO, pkey_cb) = { ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, version, ASN1_INTEGER), ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, pkeyalg, X509_ALGOR), ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, pkey, ASN1_OCTET_STRING), ASN1_IMP_SET_OF_OPT(PKCS8_PRIV_KEY_INFO, attributes, X509_ATTRIBUTE, 0) } ASN1_SEQUENCE_END_cb(PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO) IMPLEMENT_ASN1_FUNCTIONS(PKCS8_PRIV_KEY_INFO) int PKCS8_pkey_set0(PKCS8_PRIV_KEY_INFO *priv, ASN1_OBJECT *aobj, int version, int ptype, void *pval, unsigned char *penc, int penclen) { if (version >= 0) { if (!ASN1_INTEGER_set(priv->version, version)) return 0; } if (!X509_ALGOR_set0(priv->pkeyalg, aobj, ptype, pval)) return 0; if (penc) ASN1_STRING_set0(priv->pkey, penc, penclen); return 1; } int PKCS8_pkey_get0(const ASN1_OBJECT **ppkalg, const unsigned char **pk, int *ppklen, const X509_ALGOR **pa, const PKCS8_PRIV_KEY_INFO *p8) { if (ppkalg) *ppkalg = p8->pkeyalg->algorithm; if (pk) { *pk = ASN1_STRING_get0_data(p8->pkey); *ppklen = ASN1_STRING_length(p8->pkey); } if (pa) *pa = p8->pkeyalg; return 1; } const STACK_OF(X509_ATTRIBUTE) * PKCS8_pkey_get0_attrs(const PKCS8_PRIV_KEY_INFO *p8) { return p8->attributes; } int PKCS8_pkey_add1_attr_by_NID(PKCS8_PRIV_KEY_INFO *p8, int nid, int type, const unsigned char *bytes, int len) { if (X509at_add1_attr_by_NID(&p8->attributes, nid, type, bytes, len) != NULL) return 1; return 0; } int PKCS8_pkey_add1_attr_by_OBJ(PKCS8_PRIV_KEY_INFO *p8, const ASN1_OBJECT *obj, int type, const unsigned char *bytes, int len) { return (X509at_add1_attr_by_OBJ(&p8->attributes, obj, type, bytes, len) != NULL); } int PKCS8_pkey_add1_attr(PKCS8_PRIV_KEY_INFO *p8, X509_ATTRIBUTE *attr) { return (X509at_add1_attr(&p8->attributes, attr) != NULL); }
2,984
31.445652
90
c
openssl
openssl-master/crypto/asn1/standard_methods.h
/* * Copyright 2006-2021 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 */ /* * This table MUST be kept in ascending order of the NID each method * represents (corresponding to the pkey_id field) as OBJ_bsearch * is used to search it. */ static const EVP_PKEY_ASN1_METHOD *standard_methods[] = { &ossl_rsa_asn1_meths[0], &ossl_rsa_asn1_meths[1], #ifndef OPENSSL_NO_DH &ossl_dh_asn1_meth, #endif #ifndef OPENSSL_NO_DSA &ossl_dsa_asn1_meths[0], &ossl_dsa_asn1_meths[1], &ossl_dsa_asn1_meths[2], &ossl_dsa_asn1_meths[3], &ossl_dsa_asn1_meths[4], #endif #ifndef OPENSSL_NO_EC &ossl_eckey_asn1_meth, #endif &ossl_rsa_pss_asn1_meth, #ifndef OPENSSL_NO_DH &ossl_dhx_asn1_meth, #endif #ifndef OPENSSL_NO_ECX &ossl_ecx25519_asn1_meth, &ossl_ecx448_asn1_meth, &ossl_ed25519_asn1_meth, &ossl_ed448_asn1_meth, #endif #ifndef OPENSSL_NO_SM2 &ossl_sm2_asn1_meth, #endif };
1,190
24.891304
74
h
openssl
openssl-master/crypto/asn1/t_bitst.c
/* * Copyright 1999-2016 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/conf.h> #include <openssl/x509v3.h> int ASN1_BIT_STRING_name_print(BIO *out, ASN1_BIT_STRING *bs, BIT_STRING_BITNAME *tbl, int indent) { BIT_STRING_BITNAME *bnam; char first = 1; BIO_printf(out, "%*s", indent, ""); for (bnam = tbl; bnam->lname; bnam++) { if (ASN1_BIT_STRING_get_bit(bs, bnam->bitnum)) { if (!first) BIO_puts(out, ", "); BIO_puts(out, bnam->lname); first = 0; } } BIO_puts(out, "\n"); return 1; } int ASN1_BIT_STRING_set_asc(ASN1_BIT_STRING *bs, const char *name, int value, BIT_STRING_BITNAME *tbl) { int bitnum; bitnum = ASN1_BIT_STRING_num_asc(name, tbl); if (bitnum < 0) return 0; if (bs) { if (!ASN1_BIT_STRING_set_bit(bs, bitnum, value)) return 0; } return 1; } int ASN1_BIT_STRING_num_asc(const char *name, BIT_STRING_BITNAME *tbl) { BIT_STRING_BITNAME *bnam; for (bnam = tbl; bnam->lname; bnam++) { if ((strcmp(bnam->sname, name) == 0) || (strcmp(bnam->lname, name) == 0)) return bnam->bitnum; } return -1; }
1,596
27.017544
77
c
openssl
openssl-master/crypto/asn1/t_pkey.c
/* * Copyright 1995-2016 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/objects.h> #include <openssl/buffer.h> #include "crypto/bn.h" /* Number of octets per line */ #define ASN1_BUF_PRINT_WIDTH 15 /* Maximum indent */ #define ASN1_PRINT_MAX_INDENT 128 int ASN1_buf_print(BIO *bp, const unsigned char *buf, size_t buflen, int indent) { size_t i; for (i = 0; i < buflen; i++) { if ((i % ASN1_BUF_PRINT_WIDTH) == 0) { if (i > 0 && BIO_puts(bp, "\n") <= 0) return 0; if (!BIO_indent(bp, indent, ASN1_PRINT_MAX_INDENT)) return 0; } /* * Use colon separators for each octet for compatibility as * this function is used to print out key components. */ if (BIO_printf(bp, "%02x%s", buf[i], (i == buflen - 1) ? "" : ":") <= 0) return 0; } if (BIO_write(bp, "\n", 1) <= 0) return 0; return 1; } int ASN1_bn_print(BIO *bp, const char *number, const BIGNUM *num, unsigned char *ign, int indent) { int n, rv = 0; const char *neg; unsigned char *buf = NULL, *tmp = NULL; int buflen; if (num == NULL) return 1; neg = BN_is_negative(num) ? "-" : ""; if (!BIO_indent(bp, indent, ASN1_PRINT_MAX_INDENT)) return 0; if (BN_is_zero(num)) { if (BIO_printf(bp, "%s 0\n", number) <= 0) return 0; return 1; } if (BN_num_bytes(num) <= BN_BYTES) { if (BIO_printf(bp, "%s %s%lu (%s0x%lx)\n", number, neg, (unsigned long)bn_get_words(num)[0], neg, (unsigned long)bn_get_words(num)[0]) <= 0) return 0; return 1; } buflen = BN_num_bytes(num) + 1; buf = tmp = OPENSSL_malloc(buflen); if (buf == NULL) goto err; buf[0] = 0; if (BIO_printf(bp, "%s%s\n", number, (neg[0] == '-') ? " (Negative)" : "") <= 0) goto err; n = BN_bn2bin(num, buf + 1); if (buf[1] & 0x80) n++; else tmp++; if (ASN1_buf_print(bp, tmp, n, indent + 4) == 0) goto err; rv = 1; err: OPENSSL_clear_free(buf, buflen); return rv; }
2,584
26.5
80
c
openssl
openssl-master/crypto/asn1/t_spki.c
/* * Copyright 1999-2021 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/x509.h> #include <openssl/asn1.h> #include <openssl/rsa.h> #include <openssl/dsa.h> #include <openssl/bn.h> /* Print out an SPKI */ int NETSCAPE_SPKI_print(BIO *out, NETSCAPE_SPKI *spki) { EVP_PKEY *pkey; ASN1_IA5STRING *chal; ASN1_OBJECT *spkioid; int i, n; char *s; BIO_printf(out, "Netscape SPKI:\n"); X509_PUBKEY_get0_param(&spkioid, NULL, NULL, NULL, spki->spkac->pubkey); i = OBJ_obj2nid(spkioid); BIO_printf(out, " Public Key Algorithm: %s\n", (i == NID_undef) ? "UNKNOWN" : OBJ_nid2ln(i)); pkey = X509_PUBKEY_get(spki->spkac->pubkey); if (pkey == NULL) BIO_printf(out, " Unable to load public key\n"); else { EVP_PKEY_print_public(out, pkey, 4, NULL); EVP_PKEY_free(pkey); } chal = spki->spkac->challenge; if (chal->length) BIO_printf(out, " Challenge String: %.*s\n", chal->length, chal->data); i = OBJ_obj2nid(spki->sig_algor.algorithm); BIO_printf(out, " Signature Algorithm: %s", (i == NID_undef) ? "UNKNOWN" : OBJ_nid2ln(i)); n = spki->signature->length; s = (char *)spki->signature->data; for (i = 0; i < n; i++) { if ((i % 18) == 0) BIO_write(out, "\n ", 7); BIO_printf(out, "%02x%s", (unsigned char)s[i], ((i + 1) == n) ? "" : ":"); } BIO_write(out, "\n", 1); return 1; }
1,806
30.701754
80
c
openssl
openssl-master/crypto/asn1/tasn_enc.c
/* * Copyright 2000-2021 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 */ #include <stddef.h> #include <string.h> #include "internal/cryptlib.h" #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/objects.h> #include "crypto/asn1.h" #include "asn1_local.h" static int asn1_i2d_ex_primitive(const ASN1_VALUE **pval, unsigned char **out, const ASN1_ITEM *it, int tag, int aclass); static int asn1_set_seq_out(STACK_OF(const_ASN1_VALUE) *sk, unsigned char **out, int skcontlen, const ASN1_ITEM *item, int do_sort, int iclass); static int asn1_template_ex_i2d(const ASN1_VALUE **pval, unsigned char **out, const ASN1_TEMPLATE *tt, int tag, int aclass); static int asn1_item_flags_i2d(const ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it, int flags); static int asn1_ex_i2c(const ASN1_VALUE **pval, unsigned char *cout, int *putype, const ASN1_ITEM *it); /* * Top level i2d equivalents: the 'ndef' variant instructs the encoder to use * indefinite length constructed encoding, where appropriate */ int ASN1_item_ndef_i2d(const ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it) { return asn1_item_flags_i2d(val, out, it, ASN1_TFLG_NDEF); } int ASN1_item_i2d(const ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it) { return asn1_item_flags_i2d(val, out, it, 0); } /* * Encode an ASN1 item, this is use by the standard 'i2d' function. 'out' * points to a buffer to output the data to. The new i2d has one additional * feature. If the output buffer is NULL (i.e. *out == NULL) then a buffer is * allocated and populated with the encoding. */ static int asn1_item_flags_i2d(const ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it, int flags) { if (out != NULL && *out == NULL) { unsigned char *p, *buf; int len; len = ASN1_item_ex_i2d(&val, NULL, it, -1, flags); if (len <= 0) return len; if ((buf = OPENSSL_malloc(len)) == NULL) return -1; p = buf; ASN1_item_ex_i2d(&val, &p, it, -1, flags); *out = buf; return len; } return ASN1_item_ex_i2d(&val, out, it, -1, flags); } /* * Encode an item, taking care of IMPLICIT tagging (if any). This function * performs the normal item handling: it can be used in external types. */ int ASN1_item_ex_i2d(const ASN1_VALUE **pval, unsigned char **out, const ASN1_ITEM *it, int tag, int aclass) { const ASN1_TEMPLATE *tt = NULL; int i, seqcontlen, seqlen, ndef = 1; const ASN1_EXTERN_FUNCS *ef; const ASN1_AUX *aux = it->funcs; ASN1_aux_const_cb *asn1_cb = NULL; if ((it->itype != ASN1_ITYPE_PRIMITIVE) && *pval == NULL) return 0; if (aux != NULL) { asn1_cb = ((aux->flags & ASN1_AFLG_CONST_CB) != 0) ? aux->asn1_const_cb : (ASN1_aux_const_cb *)aux->asn1_cb; /* backward compatibility */ } switch (it->itype) { case ASN1_ITYPE_PRIMITIVE: if (it->templates) return asn1_template_ex_i2d(pval, out, it->templates, tag, aclass); return asn1_i2d_ex_primitive(pval, out, it, tag, aclass); case ASN1_ITYPE_MSTRING: /* * It never makes sense for multi-strings to have implicit tagging, so * if tag != -1, then this looks like an error in the template. */ if (tag != -1) { ERR_raise(ERR_LIB_ASN1, ASN1_R_BAD_TEMPLATE); return -1; } return asn1_i2d_ex_primitive(pval, out, it, -1, aclass); case ASN1_ITYPE_CHOICE: /* * It never makes sense for CHOICE types to have implicit tagging, so * if tag != -1, then this looks like an error in the template. */ if (tag != -1) { ERR_raise(ERR_LIB_ASN1, ASN1_R_BAD_TEMPLATE); return -1; } if (asn1_cb && !asn1_cb(ASN1_OP_I2D_PRE, pval, it, NULL)) return 0; i = ossl_asn1_get_choice_selector_const(pval, it); if ((i >= 0) && (i < it->tcount)) { const ASN1_VALUE **pchval; const ASN1_TEMPLATE *chtt; chtt = it->templates + i; pchval = ossl_asn1_get_const_field_ptr(pval, chtt); return asn1_template_ex_i2d(pchval, out, chtt, -1, aclass); } /* Fixme: error condition if selector out of range */ if (asn1_cb && !asn1_cb(ASN1_OP_I2D_POST, pval, it, NULL)) return 0; break; case ASN1_ITYPE_EXTERN: /* If new style i2d it does all the work */ ef = it->funcs; return ef->asn1_ex_i2d(pval, out, it, tag, aclass); case ASN1_ITYPE_NDEF_SEQUENCE: /* Use indefinite length constructed if requested */ if (aclass & ASN1_TFLG_NDEF) ndef = 2; /* fall through */ case ASN1_ITYPE_SEQUENCE: i = ossl_asn1_enc_restore(&seqcontlen, out, pval, it); /* An error occurred */ if (i < 0) return 0; /* We have a valid cached encoding... */ if (i > 0) return seqcontlen; /* Otherwise carry on */ seqcontlen = 0; /* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */ if (tag == -1) { tag = V_ASN1_SEQUENCE; /* Retain any other flags in aclass */ aclass = (aclass & ~ASN1_TFLG_TAG_CLASS) | V_ASN1_UNIVERSAL; } if (asn1_cb && !asn1_cb(ASN1_OP_I2D_PRE, pval, it, NULL)) return 0; /* First work out sequence content length */ for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) { const ASN1_TEMPLATE *seqtt; const ASN1_VALUE **pseqval; int tmplen; seqtt = ossl_asn1_do_adb(*pval, tt, 1); if (!seqtt) return 0; pseqval = ossl_asn1_get_const_field_ptr(pval, seqtt); tmplen = asn1_template_ex_i2d(pseqval, NULL, seqtt, -1, aclass); if (tmplen == -1 || (tmplen > INT_MAX - seqcontlen)) return -1; seqcontlen += tmplen; } seqlen = ASN1_object_size(ndef, seqcontlen, tag); if (!out || seqlen == -1) return seqlen; /* Output SEQUENCE header */ ASN1_put_object(out, ndef, seqcontlen, tag, aclass); for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) { const ASN1_TEMPLATE *seqtt; const ASN1_VALUE **pseqval; seqtt = ossl_asn1_do_adb(*pval, tt, 1); if (!seqtt) return 0; pseqval = ossl_asn1_get_const_field_ptr(pval, seqtt); /* FIXME: check for errors in enhanced version */ asn1_template_ex_i2d(pseqval, out, seqtt, -1, aclass); } if (ndef == 2) ASN1_put_eoc(out); if (asn1_cb && !asn1_cb(ASN1_OP_I2D_POST, pval, it, NULL)) return 0; return seqlen; default: return 0; } return 0; } static int asn1_template_ex_i2d(const ASN1_VALUE **pval, unsigned char **out, const ASN1_TEMPLATE *tt, int tag, int iclass) { const int flags = tt->flags; int i, ret, ttag, tclass, ndef, len; const ASN1_VALUE *tval; /* * If field is embedded then val needs fixing so it is a pointer to * a pointer to a field. */ if (flags & ASN1_TFLG_EMBED) { tval = (ASN1_VALUE *)pval; pval = &tval; } /* * Work out tag and class to use: tagging may come either from the * template or the arguments, not both because this would create * ambiguity. Additionally the iclass argument may contain some * additional flags which should be noted and passed down to other * levels. */ if (flags & ASN1_TFLG_TAG_MASK) { /* Error if argument and template tagging */ if (tag != -1) /* FIXME: error code here */ return -1; /* Get tagging from template */ ttag = tt->tag; tclass = flags & ASN1_TFLG_TAG_CLASS; } else if (tag != -1) { /* No template tagging, get from arguments */ ttag = tag; tclass = iclass & ASN1_TFLG_TAG_CLASS; } else { ttag = -1; tclass = 0; } /* * Remove any class mask from iflag. */ iclass &= ~ASN1_TFLG_TAG_CLASS; /* * At this point 'ttag' contains the outer tag to use, 'tclass' is the * class and iclass is any flags passed to this function. */ /* if template and arguments require ndef, use it */ if ((flags & ASN1_TFLG_NDEF) && (iclass & ASN1_TFLG_NDEF)) ndef = 2; else ndef = 1; if (flags & ASN1_TFLG_SK_MASK) { /* SET OF, SEQUENCE OF */ STACK_OF(const_ASN1_VALUE) *sk = (STACK_OF(const_ASN1_VALUE) *)*pval; int isset, sktag, skaclass; int skcontlen, sklen; const ASN1_VALUE *skitem; if (*pval == NULL) return 0; if (flags & ASN1_TFLG_SET_OF) { isset = 1; /* 2 means we reorder */ if (flags & ASN1_TFLG_SEQUENCE_OF) isset = 2; } else isset = 0; /* * Work out inner tag value: if EXPLICIT or no tagging use underlying * type. */ if ((ttag != -1) && !(flags & ASN1_TFLG_EXPTAG)) { sktag = ttag; skaclass = tclass; } else { skaclass = V_ASN1_UNIVERSAL; if (isset) sktag = V_ASN1_SET; else sktag = V_ASN1_SEQUENCE; } /* Determine total length of items */ skcontlen = 0; for (i = 0; i < sk_const_ASN1_VALUE_num(sk); i++) { skitem = sk_const_ASN1_VALUE_value(sk, i); len = ASN1_item_ex_i2d(&skitem, NULL, ASN1_ITEM_ptr(tt->item), -1, iclass); if (len == -1 || (skcontlen > INT_MAX - len)) return -1; if (len == 0 && (tt->flags & ASN1_TFLG_OPTIONAL) == 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_ZERO_CONTENT); return -1; } skcontlen += len; } sklen = ASN1_object_size(ndef, skcontlen, sktag); if (sklen == -1) return -1; /* If EXPLICIT need length of surrounding tag */ if (flags & ASN1_TFLG_EXPTAG) ret = ASN1_object_size(ndef, sklen, ttag); else ret = sklen; if (!out || ret == -1) return ret; /* Now encode this lot... */ /* EXPLICIT tag */ if (flags & ASN1_TFLG_EXPTAG) ASN1_put_object(out, ndef, sklen, ttag, tclass); /* SET or SEQUENCE and IMPLICIT tag */ ASN1_put_object(out, ndef, skcontlen, sktag, skaclass); /* And the stuff itself */ asn1_set_seq_out(sk, out, skcontlen, ASN1_ITEM_ptr(tt->item), isset, iclass); if (ndef == 2) { ASN1_put_eoc(out); if (flags & ASN1_TFLG_EXPTAG) ASN1_put_eoc(out); } return ret; } if (flags & ASN1_TFLG_EXPTAG) { /* EXPLICIT tagging */ /* Find length of tagged item */ i = ASN1_item_ex_i2d(pval, NULL, ASN1_ITEM_ptr(tt->item), -1, iclass); if (i == 0) { if ((tt->flags & ASN1_TFLG_OPTIONAL) == 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_ZERO_CONTENT); return -1; } return 0; } /* Find length of EXPLICIT tag */ ret = ASN1_object_size(ndef, i, ttag); if (out && ret != -1) { /* Output tag and item */ ASN1_put_object(out, ndef, i, ttag, tclass); ASN1_item_ex_i2d(pval, out, ASN1_ITEM_ptr(tt->item), -1, iclass); if (ndef == 2) ASN1_put_eoc(out); } return ret; } /* Either normal or IMPLICIT tagging: combine class and flags */ len = ASN1_item_ex_i2d(pval, out, ASN1_ITEM_ptr(tt->item), ttag, tclass | iclass); if (len == 0 && (tt->flags & ASN1_TFLG_OPTIONAL) == 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_ZERO_CONTENT); return -1; } return len; } /* Temporary structure used to hold DER encoding of items for SET OF */ typedef struct { unsigned char *data; int length; const ASN1_VALUE *field; } DER_ENC; static int der_cmp(const void *a, const void *b) { const DER_ENC *d1 = a, *d2 = b; int cmplen, i; cmplen = (d1->length < d2->length) ? d1->length : d2->length; i = memcmp(d1->data, d2->data, cmplen); if (i) return i; return d1->length - d2->length; } /* Output the content octets of SET OF or SEQUENCE OF */ static int asn1_set_seq_out(STACK_OF(const_ASN1_VALUE) *sk, unsigned char **out, int skcontlen, const ASN1_ITEM *item, int do_sort, int iclass) { int i, ret = 0; const ASN1_VALUE *skitem; unsigned char *tmpdat = NULL, *p = NULL; DER_ENC *derlst = NULL, *tder; if (do_sort) { /* Don't need to sort less than 2 items */ if (sk_const_ASN1_VALUE_num(sk) < 2) do_sort = 0; else { derlst = OPENSSL_malloc(sk_const_ASN1_VALUE_num(sk) * sizeof(*derlst)); if (derlst == NULL) return 0; tmpdat = OPENSSL_malloc(skcontlen); if (tmpdat == NULL) goto err; } } /* If not sorting just output each item */ if (!do_sort) { for (i = 0; i < sk_const_ASN1_VALUE_num(sk); i++) { skitem = sk_const_ASN1_VALUE_value(sk, i); ASN1_item_ex_i2d(&skitem, out, item, -1, iclass); } return 1; } p = tmpdat; /* Doing sort: build up a list of each member's DER encoding */ for (i = 0, tder = derlst; i < sk_const_ASN1_VALUE_num(sk); i++, tder++) { skitem = sk_const_ASN1_VALUE_value(sk, i); tder->data = p; tder->length = ASN1_item_ex_i2d(&skitem, &p, item, -1, iclass); tder->field = skitem; } /* Now sort them */ qsort(derlst, sk_const_ASN1_VALUE_num(sk), sizeof(*derlst), der_cmp); /* Output sorted DER encoding */ p = *out; for (i = 0, tder = derlst; i < sk_const_ASN1_VALUE_num(sk); i++, tder++) { memcpy(p, tder->data, tder->length); p += tder->length; } *out = p; /* If do_sort is 2 then reorder the STACK */ if (do_sort == 2) { for (i = 0, tder = derlst; i < sk_const_ASN1_VALUE_num(sk); i++, tder++) (void)sk_const_ASN1_VALUE_set(sk, i, tder->field); } ret = 1; err: OPENSSL_free(derlst); OPENSSL_free(tmpdat); return ret; } static int asn1_i2d_ex_primitive(const ASN1_VALUE **pval, unsigned char **out, const ASN1_ITEM *it, int tag, int aclass) { int len; int utype; int usetag; int ndef = 0; utype = it->utype; /* * Get length of content octets and maybe find out the underlying type. */ len = asn1_ex_i2c(pval, NULL, &utype, it); /* * If SEQUENCE, SET or OTHER then header is included in pseudo content * octets so don't include tag+length. We need to check here because the * call to asn1_ex_i2c() could change utype. */ if ((utype == V_ASN1_SEQUENCE) || (utype == V_ASN1_SET) || (utype == V_ASN1_OTHER)) usetag = 0; else usetag = 1; /* -1 means omit type */ if (len == -1) return 0; /* -2 return is special meaning use ndef */ if (len == -2) { ndef = 2; len = 0; } /* If not implicitly tagged get tag from underlying type */ if (tag == -1) tag = utype; /* Output tag+length followed by content octets */ if (out) { if (usetag) ASN1_put_object(out, ndef, len, tag, aclass); asn1_ex_i2c(pval, *out, &utype, it); if (ndef) ASN1_put_eoc(out); else *out += len; } if (usetag) return ASN1_object_size(ndef, len, tag); return len; } /* Produce content octets from a structure */ static int asn1_ex_i2c(const ASN1_VALUE **pval, unsigned char *cout, int *putype, const ASN1_ITEM *it) { ASN1_BOOLEAN *tbool = NULL; ASN1_STRING *strtmp; ASN1_OBJECT *otmp; int utype; const unsigned char *cont; unsigned char c; int len; const ASN1_PRIMITIVE_FUNCS *pf; pf = it->funcs; if (pf && pf->prim_i2c) return pf->prim_i2c(pval, cout, putype, it); /* Should type be omitted? */ if ((it->itype != ASN1_ITYPE_PRIMITIVE) || (it->utype != V_ASN1_BOOLEAN)) { if (*pval == NULL) return -1; } if (it->itype == ASN1_ITYPE_MSTRING) { /* If MSTRING type set the underlying type */ strtmp = (ASN1_STRING *)*pval; utype = strtmp->type; *putype = utype; } else if (it->utype == V_ASN1_ANY) { /* If ANY set type and pointer to value */ ASN1_TYPE *typ; typ = (ASN1_TYPE *)*pval; utype = typ->type; *putype = utype; pval = (const ASN1_VALUE **)&typ->value.asn1_value; /* actually is const */ } else utype = *putype; switch (utype) { case V_ASN1_OBJECT: otmp = (ASN1_OBJECT *)*pval; cont = otmp->data; len = otmp->length; if (cont == NULL || len == 0) return -1; break; case V_ASN1_NULL: cont = NULL; len = 0; break; case V_ASN1_BOOLEAN: tbool = (ASN1_BOOLEAN *)pval; if (*tbool == -1) return -1; if (it->utype != V_ASN1_ANY) { /* * Default handling if value == size field then omit */ if (*tbool && (it->size > 0)) return -1; if (!*tbool && !it->size) return -1; } c = (unsigned char)*tbool; cont = &c; len = 1; break; case V_ASN1_BIT_STRING: return ossl_i2c_ASN1_BIT_STRING((ASN1_BIT_STRING *)*pval, cout ? &cout : NULL); case V_ASN1_INTEGER: case V_ASN1_ENUMERATED: /* * These are all have the same content format as ASN1_INTEGER */ return ossl_i2c_ASN1_INTEGER((ASN1_INTEGER *)*pval, cout ? &cout : NULL); case V_ASN1_OCTET_STRING: case V_ASN1_NUMERICSTRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_T61STRING: case V_ASN1_VIDEOTEXSTRING: case V_ASN1_IA5STRING: case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: case V_ASN1_GRAPHICSTRING: case V_ASN1_VISIBLESTRING: case V_ASN1_GENERALSTRING: case V_ASN1_UNIVERSALSTRING: case V_ASN1_BMPSTRING: case V_ASN1_UTF8STRING: case V_ASN1_SEQUENCE: case V_ASN1_SET: default: /* All based on ASN1_STRING and handled the same */ strtmp = (ASN1_STRING *)*pval; /* Special handling for NDEF */ if ((it->size == ASN1_TFLG_NDEF) && (strtmp->flags & ASN1_STRING_FLAG_NDEF)) { if (cout) { strtmp->data = cout; strtmp->length = 0; } /* Special return code */ return -2; } cont = strtmp->data; len = strtmp->length; break; } if (cout && len) memcpy(cout, cont, len); return len; }
20,237
30.572543
83
c
openssl
openssl-master/crypto/asn1/tasn_fre.c
/* * Copyright 2000-2021 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 */ #include <stddef.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/objects.h> #include "asn1_local.h" /* Free up an ASN1 structure */ void ASN1_item_free(ASN1_VALUE *val, const ASN1_ITEM *it) { ossl_asn1_item_embed_free(&val, it, 0); } void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { ossl_asn1_item_embed_free(pval, it, 0); } void ossl_asn1_item_embed_free(ASN1_VALUE **pval, const ASN1_ITEM *it, int embed) { const ASN1_TEMPLATE *tt = NULL, *seqtt; const ASN1_EXTERN_FUNCS *ef; const ASN1_AUX *aux = it->funcs; ASN1_aux_cb *asn1_cb; int i; if (pval == NULL) return; if ((it->itype != ASN1_ITYPE_PRIMITIVE) && *pval == NULL) return; if (aux && aux->asn1_cb) asn1_cb = aux->asn1_cb; else asn1_cb = 0; switch (it->itype) { case ASN1_ITYPE_PRIMITIVE: if (it->templates) ossl_asn1_template_free(pval, it->templates); else ossl_asn1_primitive_free(pval, it, embed); break; case ASN1_ITYPE_MSTRING: ossl_asn1_primitive_free(pval, it, embed); break; case ASN1_ITYPE_CHOICE: if (asn1_cb) { i = asn1_cb(ASN1_OP_FREE_PRE, pval, it, NULL); if (i == 2) return; } i = ossl_asn1_get_choice_selector(pval, it); if ((i >= 0) && (i < it->tcount)) { ASN1_VALUE **pchval; tt = it->templates + i; pchval = ossl_asn1_get_field_ptr(pval, tt); ossl_asn1_template_free(pchval, tt); } if (asn1_cb) asn1_cb(ASN1_OP_FREE_POST, pval, it, NULL); if (embed == 0) { OPENSSL_free(*pval); *pval = NULL; } break; case ASN1_ITYPE_EXTERN: ef = it->funcs; if (ef && ef->asn1_ex_free) ef->asn1_ex_free(pval, it); break; case ASN1_ITYPE_NDEF_SEQUENCE: case ASN1_ITYPE_SEQUENCE: if (ossl_asn1_do_lock(pval, -1, it) != 0) /* if error or ref-counter > 0 */ return; if (asn1_cb) { i = asn1_cb(ASN1_OP_FREE_PRE, pval, it, NULL); if (i == 2) return; } ossl_asn1_enc_free(pval, it); /* * If we free up as normal we will invalidate any ANY DEFINED BY * field and we won't be able to determine the type of the field it * defines. So free up in reverse order. */ tt = it->templates + it->tcount; for (i = 0; i < it->tcount; i++) { ASN1_VALUE **pseqval; tt--; seqtt = ossl_asn1_do_adb(*pval, tt, 0); if (!seqtt) continue; pseqval = ossl_asn1_get_field_ptr(pval, seqtt); ossl_asn1_template_free(pseqval, seqtt); } if (asn1_cb) asn1_cb(ASN1_OP_FREE_POST, pval, it, NULL); if (embed == 0) { OPENSSL_free(*pval); *pval = NULL; } break; } } void ossl_asn1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) { int embed = tt->flags & ASN1_TFLG_EMBED; ASN1_VALUE *tval; if (embed) { tval = (ASN1_VALUE *)pval; pval = &tval; } if (tt->flags & ASN1_TFLG_SK_MASK) { STACK_OF(ASN1_VALUE) *sk = (STACK_OF(ASN1_VALUE) *)*pval; int i; for (i = 0; i < sk_ASN1_VALUE_num(sk); i++) { ASN1_VALUE *vtmp = sk_ASN1_VALUE_value(sk, i); ossl_asn1_item_embed_free(&vtmp, ASN1_ITEM_ptr(tt->item), embed); } sk_ASN1_VALUE_free(sk); *pval = NULL; } else { ossl_asn1_item_embed_free(pval, ASN1_ITEM_ptr(tt->item), embed); } } void ossl_asn1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it, int embed) { int utype; /* Special case: if 'it' is a primitive with a free_func, use that. */ if (it) { const ASN1_PRIMITIVE_FUNCS *pf = it->funcs; if (embed) { if (pf && pf->prim_clear) { pf->prim_clear(pval, it); return; } } else if (pf && pf->prim_free) { pf->prim_free(pval, it); return; } } /* Special case: if 'it' is NULL, free contents of ASN1_TYPE */ if (!it) { ASN1_TYPE *typ = (ASN1_TYPE *)*pval; utype = typ->type; pval = &typ->value.asn1_value; if (*pval == NULL) return; } else if (it->itype == ASN1_ITYPE_MSTRING) { utype = -1; if (*pval == NULL) return; } else { utype = it->utype; if ((utype != V_ASN1_BOOLEAN) && *pval == NULL) return; } switch (utype) { case V_ASN1_OBJECT: ASN1_OBJECT_free((ASN1_OBJECT *)*pval); break; case V_ASN1_BOOLEAN: if (it) *(ASN1_BOOLEAN *)pval = it->size; else *(ASN1_BOOLEAN *)pval = -1; return; case V_ASN1_NULL: break; case V_ASN1_ANY: ossl_asn1_primitive_free(pval, NULL, 0); OPENSSL_free(*pval); break; default: ossl_asn1_string_embed_free((ASN1_STRING *)*pval, embed); break; } *pval = NULL; }
5,605
25.822967
83
c
openssl
openssl-master/crypto/asn1/tasn_new.c
/* * Copyright 2000-2021 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 */ #include <stddef.h> #include <openssl/asn1.h> #include <openssl/objects.h> #include <openssl/err.h> #include <openssl/asn1t.h> #include <string.h> #include "asn1_local.h" static int asn1_item_embed_new(ASN1_VALUE **pval, const ASN1_ITEM *it, int embed, OSSL_LIB_CTX *libctx, const char *propq); static int asn1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it, int embed); static void asn1_item_clear(ASN1_VALUE **pval, const ASN1_ITEM *it); static int asn1_template_new(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt, OSSL_LIB_CTX *libctx, const char *propq); static void asn1_template_clear(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt); static void asn1_primitive_clear(ASN1_VALUE **pval, const ASN1_ITEM *it); ASN1_VALUE *ASN1_item_new(const ASN1_ITEM *it) { ASN1_VALUE *ret = NULL; if (ASN1_item_ex_new(&ret, it) > 0) return ret; return NULL; } ASN1_VALUE *ASN1_item_new_ex(const ASN1_ITEM *it, OSSL_LIB_CTX *libctx, const char *propq) { ASN1_VALUE *ret = NULL; if (asn1_item_embed_new(&ret, it, 0, libctx, propq) > 0) return ret; return NULL; } /* Allocate an ASN1 structure */ int ossl_asn1_item_ex_new_intern(ASN1_VALUE **pval, const ASN1_ITEM *it, OSSL_LIB_CTX *libctx, const char *propq) { return asn1_item_embed_new(pval, it, 0, libctx, propq); } int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { return asn1_item_embed_new(pval, it, 0, NULL, NULL); } int asn1_item_embed_new(ASN1_VALUE **pval, const ASN1_ITEM *it, int embed, OSSL_LIB_CTX *libctx, const char *propq) { const ASN1_TEMPLATE *tt = NULL; const ASN1_EXTERN_FUNCS *ef; const ASN1_AUX *aux = it->funcs; ASN1_aux_cb *asn1_cb; ASN1_VALUE **pseqval; int i; if (aux && aux->asn1_cb) asn1_cb = aux->asn1_cb; else asn1_cb = 0; switch (it->itype) { case ASN1_ITYPE_EXTERN: ef = it->funcs; if (ef != NULL) { if (ef->asn1_ex_new_ex != NULL) { if (!ef->asn1_ex_new_ex(pval, it, libctx, propq)) goto asn1err; } else if (ef->asn1_ex_new != NULL) { if (!ef->asn1_ex_new(pval, it)) goto asn1err; } } break; case ASN1_ITYPE_PRIMITIVE: if (it->templates) { if (!asn1_template_new(pval, it->templates, libctx, propq)) goto asn1err; } else if (!asn1_primitive_new(pval, it, embed)) goto asn1err; break; case ASN1_ITYPE_MSTRING: if (!asn1_primitive_new(pval, it, embed)) goto asn1err; break; case ASN1_ITYPE_CHOICE: if (asn1_cb) { i = asn1_cb(ASN1_OP_NEW_PRE, pval, it, NULL); if (!i) goto auxerr; if (i == 2) { return 1; } } if (embed) { memset(*pval, 0, it->size); } else { *pval = OPENSSL_zalloc(it->size); if (*pval == NULL) return 0; } ossl_asn1_set_choice_selector(pval, -1, it); if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, NULL)) goto auxerr2; break; case ASN1_ITYPE_NDEF_SEQUENCE: case ASN1_ITYPE_SEQUENCE: if (asn1_cb) { i = asn1_cb(ASN1_OP_NEW_PRE, pval, it, NULL); if (!i) goto auxerr; if (i == 2) { return 1; } } if (embed) { memset(*pval, 0, it->size); } else { *pval = OPENSSL_zalloc(it->size); if (*pval == NULL) return 0; } /* 0 : init. lock */ if (ossl_asn1_do_lock(pval, 0, it) < 0) { if (!embed) { OPENSSL_free(*pval); *pval = NULL; } goto asn1err; } ossl_asn1_enc_init(pval, it); for (i = 0, tt = it->templates; i < it->tcount; tt++, i++) { pseqval = ossl_asn1_get_field_ptr(pval, tt); if (!asn1_template_new(pseqval, tt, libctx, propq)) goto asn1err2; } if (asn1_cb && !asn1_cb(ASN1_OP_NEW_POST, pval, it, NULL)) goto auxerr2; break; } return 1; asn1err2: ossl_asn1_item_embed_free(pval, it, embed); asn1err: ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); return 0; auxerr2: ossl_asn1_item_embed_free(pval, it, embed); auxerr: ERR_raise(ERR_LIB_ASN1, ASN1_R_AUX_ERROR); return 0; } static void asn1_item_clear(ASN1_VALUE **pval, const ASN1_ITEM *it) { const ASN1_EXTERN_FUNCS *ef; switch (it->itype) { case ASN1_ITYPE_EXTERN: ef = it->funcs; if (ef && ef->asn1_ex_clear) ef->asn1_ex_clear(pval, it); else *pval = NULL; break; case ASN1_ITYPE_PRIMITIVE: if (it->templates) asn1_template_clear(pval, it->templates); else asn1_primitive_clear(pval, it); break; case ASN1_ITYPE_MSTRING: asn1_primitive_clear(pval, it); break; case ASN1_ITYPE_CHOICE: case ASN1_ITYPE_SEQUENCE: case ASN1_ITYPE_NDEF_SEQUENCE: *pval = NULL; break; } } static int asn1_template_new(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt, OSSL_LIB_CTX *libctx, const char *propq) { const ASN1_ITEM *it = ASN1_ITEM_ptr(tt->item); int embed = tt->flags & ASN1_TFLG_EMBED; ASN1_VALUE *tval; int ret; if (embed) { tval = (ASN1_VALUE *)pval; pval = &tval; } if (tt->flags & ASN1_TFLG_OPTIONAL) { asn1_template_clear(pval, tt); return 1; } /* If ANY DEFINED BY nothing to do */ if (tt->flags & ASN1_TFLG_ADB_MASK) { *pval = NULL; return 1; } /* If SET OF or SEQUENCE OF, its a STACK */ if (tt->flags & ASN1_TFLG_SK_MASK) { STACK_OF(ASN1_VALUE) *skval; skval = sk_ASN1_VALUE_new_null(); if (!skval) { ERR_raise(ERR_LIB_ASN1, ERR_R_CRYPTO_LIB); ret = 0; goto done; } *pval = (ASN1_VALUE *)skval; ret = 1; goto done; } /* Otherwise pass it back to the item routine */ ret = asn1_item_embed_new(pval, it, embed, libctx, propq); done: return ret; } static void asn1_template_clear(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) { /* If ADB or STACK just NULL the field */ if (tt->flags & (ASN1_TFLG_ADB_MASK | ASN1_TFLG_SK_MASK)) *pval = NULL; else asn1_item_clear(pval, ASN1_ITEM_ptr(tt->item)); } /* * NB: could probably combine most of the real XXX_new() behaviour and junk * all the old functions. */ static int asn1_primitive_new(ASN1_VALUE **pval, const ASN1_ITEM *it, int embed) { ASN1_TYPE *typ; ASN1_STRING *str; int utype; if (!it) return 0; if (it->funcs) { const ASN1_PRIMITIVE_FUNCS *pf = it->funcs; if (embed) { if (pf->prim_clear) { pf->prim_clear(pval, it); return 1; } } else if (pf->prim_new) { return pf->prim_new(pval, it); } } if (it->itype == ASN1_ITYPE_MSTRING) utype = -1; else utype = it->utype; switch (utype) { case V_ASN1_OBJECT: *pval = (ASN1_VALUE *)OBJ_nid2obj(NID_undef); return 1; case V_ASN1_BOOLEAN: *(ASN1_BOOLEAN *)pval = it->size; return 1; case V_ASN1_NULL: *pval = (ASN1_VALUE *)1; return 1; case V_ASN1_ANY: if ((typ = OPENSSL_malloc(sizeof(*typ))) == NULL) return 0; typ->value.ptr = NULL; typ->type = -1; *pval = (ASN1_VALUE *)typ; break; default: if (embed) { str = *(ASN1_STRING **)pval; memset(str, 0, sizeof(*str)); str->type = utype; str->flags = ASN1_STRING_FLAG_EMBED; } else { str = ASN1_STRING_type_new(utype); *pval = (ASN1_VALUE *)str; } if (it->itype == ASN1_ITYPE_MSTRING && str) str->flags |= ASN1_STRING_FLAG_MSTRING; break; } if (*pval) return 1; return 0; } static void asn1_primitive_clear(ASN1_VALUE **pval, const ASN1_ITEM *it) { int utype; if (it && it->funcs) { const ASN1_PRIMITIVE_FUNCS *pf = it->funcs; if (pf->prim_clear) pf->prim_clear(pval, it); else *pval = NULL; return; } if (!it || (it->itype == ASN1_ITYPE_MSTRING)) utype = -1; else utype = it->utype; if (utype == V_ASN1_BOOLEAN) *(ASN1_BOOLEAN *)pval = it->size; else *pval = NULL; }
9,394
26.074928
76
c
openssl
openssl-master/crypto/asn1/tasn_prn.c
/* * Copyright 2000-2021 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 */ #include <stddef.h> #include "internal/cryptlib.h" #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/objects.h> #include <openssl/buffer.h> #include <openssl/err.h> #include <openssl/x509v3.h> #include "crypto/asn1.h" #include "asn1_local.h" /* * Print routines. */ /* ASN1_PCTX routines */ static ASN1_PCTX default_pctx = { ASN1_PCTX_FLAGS_SHOW_ABSENT, /* flags */ 0, /* nm_flags */ 0, /* cert_flags */ 0, /* oid_flags */ 0 /* str_flags */ }; ASN1_PCTX *ASN1_PCTX_new(void) { ASN1_PCTX *ret; ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; return ret; } void ASN1_PCTX_free(ASN1_PCTX *p) { OPENSSL_free(p); } unsigned long ASN1_PCTX_get_flags(const ASN1_PCTX *p) { return p->flags; } void ASN1_PCTX_set_flags(ASN1_PCTX *p, unsigned long flags) { p->flags = flags; } unsigned long ASN1_PCTX_get_nm_flags(const ASN1_PCTX *p) { return p->nm_flags; } void ASN1_PCTX_set_nm_flags(ASN1_PCTX *p, unsigned long flags) { p->nm_flags = flags; } unsigned long ASN1_PCTX_get_cert_flags(const ASN1_PCTX *p) { return p->cert_flags; } void ASN1_PCTX_set_cert_flags(ASN1_PCTX *p, unsigned long flags) { p->cert_flags = flags; } unsigned long ASN1_PCTX_get_oid_flags(const ASN1_PCTX *p) { return p->oid_flags; } void ASN1_PCTX_set_oid_flags(ASN1_PCTX *p, unsigned long flags) { p->oid_flags = flags; } unsigned long ASN1_PCTX_get_str_flags(const ASN1_PCTX *p) { return p->str_flags; } void ASN1_PCTX_set_str_flags(ASN1_PCTX *p, unsigned long flags) { p->str_flags = flags; } /* Main print routines */ static int asn1_item_print_ctx(BIO *out, const ASN1_VALUE **fld, int indent, const ASN1_ITEM *it, const char *fname, const char *sname, int nohdr, const ASN1_PCTX *pctx); static int asn1_template_print_ctx(BIO *out, const ASN1_VALUE **fld, int indent, const ASN1_TEMPLATE *tt, const ASN1_PCTX *pctx); static int asn1_primitive_print(BIO *out, const ASN1_VALUE **fld, const ASN1_ITEM *it, int indent, const char *fname, const char *sname, const ASN1_PCTX *pctx); static int asn1_print_fsname(BIO *out, int indent, const char *fname, const char *sname, const ASN1_PCTX *pctx); int ASN1_item_print(BIO *out, const ASN1_VALUE *ifld, int indent, const ASN1_ITEM *it, const ASN1_PCTX *pctx) { const char *sname; if (pctx == NULL) pctx = &default_pctx; if (pctx->flags & ASN1_PCTX_FLAGS_NO_STRUCT_NAME) sname = NULL; else sname = it->sname; return asn1_item_print_ctx(out, &ifld, indent, it, NULL, sname, 0, pctx); } static int asn1_item_print_ctx(BIO *out, const ASN1_VALUE **fld, int indent, const ASN1_ITEM *it, const char *fname, const char *sname, int nohdr, const ASN1_PCTX *pctx) { const ASN1_TEMPLATE *tt; const ASN1_EXTERN_FUNCS *ef; const ASN1_VALUE **tmpfld; const ASN1_AUX *aux = it->funcs; ASN1_aux_const_cb *asn1_cb = NULL; ASN1_PRINT_ARG parg; int i; if (aux != NULL) { parg.out = out; parg.indent = indent; parg.pctx = pctx; asn1_cb = ((aux->flags & ASN1_AFLG_CONST_CB) != 0) ? aux->asn1_const_cb : (ASN1_aux_const_cb *)aux->asn1_cb; /* backward compatibility */ } if (((it->itype != ASN1_ITYPE_PRIMITIVE) || (it->utype != V_ASN1_BOOLEAN)) && *fld == NULL) { if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_ABSENT) { if (!nohdr && !asn1_print_fsname(out, indent, fname, sname, pctx)) return 0; if (BIO_puts(out, "<ABSENT>\n") <= 0) return 0; } return 1; } switch (it->itype) { case ASN1_ITYPE_PRIMITIVE: if (it->templates) { if (!asn1_template_print_ctx(out, fld, indent, it->templates, pctx)) return 0; break; } /* fall through */ case ASN1_ITYPE_MSTRING: if (!asn1_primitive_print(out, fld, it, indent, fname, sname, pctx)) return 0; break; case ASN1_ITYPE_EXTERN: if (!nohdr && !asn1_print_fsname(out, indent, fname, sname, pctx)) return 0; /* Use new style print routine if possible */ ef = it->funcs; if (ef && ef->asn1_ex_print) { i = ef->asn1_ex_print(out, fld, indent, "", pctx); if (!i) return 0; if ((i == 2) && (BIO_puts(out, "\n") <= 0)) return 0; return 1; } else if (sname && BIO_printf(out, ":EXTERNAL TYPE %s\n", sname) <= 0) return 0; break; case ASN1_ITYPE_CHOICE: /* CHOICE type, get selector */ i = ossl_asn1_get_choice_selector_const(fld, it); /* This should never happen... */ if ((i < 0) || (i >= it->tcount)) { if (BIO_printf(out, "ERROR: selector [%d] invalid\n", i) <= 0) return 0; return 1; } tt = it->templates + i; tmpfld = ossl_asn1_get_const_field_ptr(fld, tt); if (!asn1_template_print_ctx(out, tmpfld, indent, tt, pctx)) return 0; break; case ASN1_ITYPE_SEQUENCE: case ASN1_ITYPE_NDEF_SEQUENCE: if (!nohdr && !asn1_print_fsname(out, indent, fname, sname, pctx)) return 0; if (fname || sname) { if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_SEQUENCE) { if (BIO_puts(out, " {\n") <= 0) return 0; } else { if (BIO_puts(out, "\n") <= 0) return 0; } } if (asn1_cb) { i = asn1_cb(ASN1_OP_PRINT_PRE, fld, it, &parg); if (i == 0) return 0; if (i == 2) return 1; } /* Print each field entry */ for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) { const ASN1_TEMPLATE *seqtt; seqtt = ossl_asn1_do_adb(*fld, tt, 1); if (!seqtt) return 0; tmpfld = ossl_asn1_get_const_field_ptr(fld, seqtt); if (!asn1_template_print_ctx(out, tmpfld, indent + 2, seqtt, pctx)) return 0; } if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_SEQUENCE) { if (BIO_printf(out, "%*s}\n", indent, "") < 0) return 0; } if (asn1_cb) { i = asn1_cb(ASN1_OP_PRINT_POST, fld, it, &parg); if (i == 0) return 0; } break; default: BIO_printf(out, "Unprocessed type %d\n", it->itype); return 0; } return 1; } static int asn1_template_print_ctx(BIO *out, const ASN1_VALUE **fld, int indent, const ASN1_TEMPLATE *tt, const ASN1_PCTX *pctx) { int i, flags; const char *sname, *fname; const ASN1_VALUE *tfld; flags = tt->flags; if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_FIELD_STRUCT_NAME) sname = ASN1_ITEM_ptr(tt->item)->sname; else sname = NULL; if (pctx->flags & ASN1_PCTX_FLAGS_NO_FIELD_NAME) fname = NULL; else fname = tt->field_name; /* * If field is embedded then fld needs fixing so it is a pointer to * a pointer to a field. */ if (flags & ASN1_TFLG_EMBED) { tfld = (const ASN1_VALUE *)fld; fld = &tfld; } if (flags & ASN1_TFLG_SK_MASK) { char *tname; const ASN1_VALUE *skitem; STACK_OF(const_ASN1_VALUE) *stack; /* SET OF, SEQUENCE OF */ if (fname) { if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_SSOF) { if (flags & ASN1_TFLG_SET_OF) tname = "SET"; else tname = "SEQUENCE"; if (BIO_printf(out, "%*s%s OF %s {\n", indent, "", tname, tt->field_name) <= 0) return 0; } else if (BIO_printf(out, "%*s%s:\n", indent, "", fname) <= 0) return 0; } stack = (STACK_OF(const_ASN1_VALUE) *)*fld; for (i = 0; i < sk_const_ASN1_VALUE_num(stack); i++) { if ((i > 0) && (BIO_puts(out, "\n") <= 0)) return 0; skitem = sk_const_ASN1_VALUE_value(stack, i); if (!asn1_item_print_ctx(out, &skitem, indent + 2, ASN1_ITEM_ptr(tt->item), NULL, NULL, 1, pctx)) return 0; } if (i == 0 && BIO_printf(out, "%*s<%s>\n", indent + 2, "", stack == NULL ? "ABSENT" : "EMPTY") <= 0) return 0; if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_SEQUENCE) { if (BIO_printf(out, "%*s}\n", indent, "") <= 0) return 0; } return 1; } return asn1_item_print_ctx(out, fld, indent, ASN1_ITEM_ptr(tt->item), fname, sname, 0, pctx); } static int asn1_print_fsname(BIO *out, int indent, const char *fname, const char *sname, const ASN1_PCTX *pctx) { static const char spaces[] = " "; static const int nspaces = sizeof(spaces) - 1; while (indent > nspaces) { if (BIO_write(out, spaces, nspaces) != nspaces) return 0; indent -= nspaces; } if (BIO_write(out, spaces, indent) != indent) return 0; if (pctx->flags & ASN1_PCTX_FLAGS_NO_STRUCT_NAME) sname = NULL; if (pctx->flags & ASN1_PCTX_FLAGS_NO_FIELD_NAME) fname = NULL; if (!sname && !fname) return 1; if (fname) { if (BIO_puts(out, fname) <= 0) return 0; } if (sname) { if (fname) { if (BIO_printf(out, " (%s)", sname) <= 0) return 0; } else { if (BIO_puts(out, sname) <= 0) return 0; } } if (BIO_write(out, ": ", 2) != 2) return 0; return 1; } static int asn1_print_boolean(BIO *out, int boolval) { const char *str; switch (boolval) { case -1: str = "BOOL ABSENT"; break; case 0: str = "FALSE"; break; default: str = "TRUE"; break; } if (BIO_puts(out, str) <= 0) return 0; return 1; } static int asn1_print_integer(BIO *out, const ASN1_INTEGER *str) { char *s; int ret = 1; s = i2s_ASN1_INTEGER(NULL, str); if (s == NULL) return 0; if (BIO_puts(out, s) <= 0) ret = 0; OPENSSL_free(s); return ret; } static int asn1_print_oid(BIO *out, const ASN1_OBJECT *oid) { char objbuf[80]; const char *ln; ln = OBJ_nid2ln(OBJ_obj2nid(oid)); if (!ln) ln = ""; OBJ_obj2txt(objbuf, sizeof(objbuf), oid, 1); if (BIO_printf(out, "%s (%s)", ln, objbuf) <= 0) return 0; return 1; } static int asn1_print_obstring(BIO *out, const ASN1_STRING *str, int indent) { if (str->type == V_ASN1_BIT_STRING) { if (BIO_printf(out, " (%ld unused bits)\n", str->flags & 0x7) <= 0) return 0; } else if (BIO_puts(out, "\n") <= 0) return 0; if ((str->length > 0) && BIO_dump_indent(out, (const char *)str->data, str->length, indent + 2) <= 0) return 0; return 1; } static int asn1_primitive_print(BIO *out, const ASN1_VALUE **fld, const ASN1_ITEM *it, int indent, const char *fname, const char *sname, const ASN1_PCTX *pctx) { long utype; ASN1_STRING *str; int ret = 1, needlf = 1; const char *pname; const ASN1_PRIMITIVE_FUNCS *pf; pf = it->funcs; if (!asn1_print_fsname(out, indent, fname, sname, pctx)) return 0; if (pf && pf->prim_print) return pf->prim_print(out, fld, it, indent, pctx); if (it->itype == ASN1_ITYPE_MSTRING) { str = (ASN1_STRING *)*fld; utype = str->type & ~V_ASN1_NEG; } else { utype = it->utype; if (utype == V_ASN1_BOOLEAN) str = NULL; else str = (ASN1_STRING *)*fld; } if (utype == V_ASN1_ANY) { const ASN1_TYPE *atype = (const ASN1_TYPE *)*fld; utype = atype->type; fld = (const ASN1_VALUE **)&atype->value.asn1_value; /* actually is const */ str = (ASN1_STRING *)*fld; if (pctx->flags & ASN1_PCTX_FLAGS_NO_ANY_TYPE) pname = NULL; else pname = ASN1_tag2str(utype); } else { if (pctx->flags & ASN1_PCTX_FLAGS_SHOW_TYPE) pname = ASN1_tag2str(utype); else pname = NULL; } if (utype == V_ASN1_NULL) { if (BIO_puts(out, "NULL\n") <= 0) return 0; return 1; } if (pname) { if (BIO_puts(out, pname) <= 0) return 0; if (BIO_puts(out, ":") <= 0) return 0; } switch (utype) { case V_ASN1_BOOLEAN: { int boolval = *(int *)fld; if (boolval == -1) boolval = it->size; ret = asn1_print_boolean(out, boolval); } break; case V_ASN1_INTEGER: case V_ASN1_ENUMERATED: ret = asn1_print_integer(out, str); break; case V_ASN1_UTCTIME: ret = ASN1_UTCTIME_print(out, str); break; case V_ASN1_GENERALIZEDTIME: ret = ASN1_GENERALIZEDTIME_print(out, str); break; case V_ASN1_OBJECT: ret = asn1_print_oid(out, (const ASN1_OBJECT *)*fld); break; case V_ASN1_OCTET_STRING: case V_ASN1_BIT_STRING: ret = asn1_print_obstring(out, str, indent); needlf = 0; break; case V_ASN1_SEQUENCE: case V_ASN1_SET: case V_ASN1_OTHER: if (BIO_puts(out, "\n") <= 0) return 0; if (ASN1_parse_dump(out, str->data, str->length, indent, 0) <= 0) ret = 0; needlf = 0; break; default: ret = ASN1_STRING_print_ex(out, str, pctx->str_flags); } if (!ret) return 0; if (needlf && BIO_puts(out, "\n") <= 0) return 0; return 1; }
15,203
27.260223
84
c
openssl
openssl-master/crypto/asn1/tasn_typ.c
/* * Copyright 2000-2016 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 */ #include <stdio.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> /* Declarations for string types */ #define IMPLEMENT_ASN1_STRING_FUNCTIONS(sname) \ IMPLEMENT_ASN1_TYPE(sname) \ IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(sname, sname, sname) \ sname *sname##_new(void) \ { \ return ASN1_STRING_type_new(V_##sname); \ } \ void sname##_free(sname *x) \ { \ ASN1_STRING_free(x); \ } IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_OCTET_STRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_INTEGER) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_ENUMERATED) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_BIT_STRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_UTF8STRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_PRINTABLESTRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_T61STRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_IA5STRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_GENERALSTRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_UTCTIME) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_GENERALIZEDTIME) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_VISIBLESTRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_UNIVERSALSTRING) IMPLEMENT_ASN1_STRING_FUNCTIONS(ASN1_BMPSTRING) IMPLEMENT_ASN1_TYPE(ASN1_NULL) IMPLEMENT_ASN1_FUNCTIONS(ASN1_NULL) IMPLEMENT_ASN1_TYPE(ASN1_OBJECT) IMPLEMENT_ASN1_TYPE(ASN1_ANY) /* Just swallow an ASN1_SEQUENCE in an ASN1_STRING */ IMPLEMENT_ASN1_TYPE(ASN1_SEQUENCE) IMPLEMENT_ASN1_FUNCTIONS_fname(ASN1_TYPE, ASN1_ANY, ASN1_TYPE) /* Multistring types */ IMPLEMENT_ASN1_MSTRING(ASN1_PRINTABLE, B_ASN1_PRINTABLE) IMPLEMENT_ASN1_FUNCTIONS_name(ASN1_STRING, ASN1_PRINTABLE) IMPLEMENT_ASN1_MSTRING(DISPLAYTEXT, B_ASN1_DISPLAYTEXT) IMPLEMENT_ASN1_FUNCTIONS_name(ASN1_STRING, DISPLAYTEXT) IMPLEMENT_ASN1_MSTRING(DIRECTORYSTRING, B_ASN1_DIRECTORYSTRING) IMPLEMENT_ASN1_FUNCTIONS_name(ASN1_STRING, DIRECTORYSTRING) /* Three separate BOOLEAN type: normal, DEFAULT TRUE and DEFAULT FALSE */ IMPLEMENT_ASN1_TYPE_ex(ASN1_BOOLEAN, ASN1_BOOLEAN, -1) IMPLEMENT_ASN1_TYPE_ex(ASN1_TBOOLEAN, ASN1_BOOLEAN, 1) IMPLEMENT_ASN1_TYPE_ex(ASN1_FBOOLEAN, ASN1_BOOLEAN, 0) /* Special, OCTET STRING with indefinite length constructed support */ IMPLEMENT_ASN1_TYPE_ex(ASN1_OCTET_STRING_NDEF, ASN1_OCTET_STRING, ASN1_TFLG_NDEF) ASN1_ITEM_TEMPLATE(ASN1_SEQUENCE_ANY) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, ASN1_SEQUENCE_ANY, ASN1_ANY) ASN1_ITEM_TEMPLATE_END(ASN1_SEQUENCE_ANY) ASN1_ITEM_TEMPLATE(ASN1_SET_ANY) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SET_OF, 0, ASN1_SET_ANY, ASN1_ANY) ASN1_ITEM_TEMPLATE_END(ASN1_SET_ANY) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(ASN1_SEQUENCE_ANY, ASN1_SEQUENCE_ANY, ASN1_SEQUENCE_ANY) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(ASN1_SEQUENCE_ANY, ASN1_SET_ANY, ASN1_SET_ANY)
2,998
34.282353
94
c
openssl
openssl-master/crypto/asn1/tasn_utl.c
/* * Copyright 2000-2021 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 */ #include <stddef.h> #include <string.h> #include "internal/cryptlib.h" #include "internal/refcount.h" #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/objects.h> #include <openssl/err.h> #include "asn1_local.h" /* Utility functions for manipulating fields and offsets */ /* Add 'offset' to 'addr' */ #define offset2ptr(addr, offset) (void *)(((char *) addr) + offset) /* * Given an ASN1_ITEM CHOICE type return the selector value */ int ossl_asn1_get_choice_selector(ASN1_VALUE **pval, const ASN1_ITEM *it) { int *sel = offset2ptr(*pval, it->utype); return *sel; } int ossl_asn1_get_choice_selector_const(const ASN1_VALUE **pval, const ASN1_ITEM *it) { int *sel = offset2ptr(*pval, it->utype); return *sel; } /* * Given an ASN1_ITEM CHOICE type set the selector value, return old value. */ int ossl_asn1_set_choice_selector(ASN1_VALUE **pval, int value, const ASN1_ITEM *it) { int *sel, ret; sel = offset2ptr(*pval, it->utype); ret = *sel; *sel = value; return ret; } /* * Do atomic reference counting. The value 'op' decides what to do. * If it is +1 then the count is incremented. * If |op| is 0, count is initialised and set to 1. * If |op| is -1, count is decremented and the return value is the current * reference count or 0 if no reference count is active. * It returns -1 on initialisation error. * Used by ASN1_SEQUENCE construct of X509, X509_REQ, X509_CRL objects */ int ossl_asn1_do_lock(ASN1_VALUE **pval, int op, const ASN1_ITEM *it) { const ASN1_AUX *aux; CRYPTO_RWLOCK **lock; CRYPTO_REF_COUNT *refcnt; int ret = -1; if ((it->itype != ASN1_ITYPE_SEQUENCE) && (it->itype != ASN1_ITYPE_NDEF_SEQUENCE)) return 0; aux = it->funcs; if (aux == NULL || (aux->flags & ASN1_AFLG_REFCOUNT) == 0) return 0; lock = offset2ptr(*pval, aux->ref_lock); refcnt = offset2ptr(*pval, aux->ref_offset); switch (op) { case 0: if (!CRYPTO_NEW_REF(refcnt, 1)) return -1; *lock = CRYPTO_THREAD_lock_new(); if (*lock == NULL) { CRYPTO_FREE_REF(refcnt); ERR_raise(ERR_LIB_ASN1, ERR_R_CRYPTO_LIB); return -1; } ret = 1; break; case 1: if (!CRYPTO_UP_REF(refcnt, &ret)) return -1; break; case -1: if (!CRYPTO_DOWN_REF(refcnt, &ret)) return -1; /* failed */ REF_PRINT_EX(it->sname, ret, (void *)it); REF_ASSERT_ISNT(ret < 0); if (ret == 0) { CRYPTO_THREAD_lock_free(*lock); *lock = NULL; CRYPTO_FREE_REF(refcnt); } break; } return ret; } static ASN1_ENCODING *asn1_get_enc_ptr(ASN1_VALUE **pval, const ASN1_ITEM *it) { const ASN1_AUX *aux; if (pval == NULL || *pval == NULL) return NULL; aux = it->funcs; if (aux == NULL || (aux->flags & ASN1_AFLG_ENCODING) == 0) return NULL; return offset2ptr(*pval, aux->enc_offset); } static const ASN1_ENCODING *asn1_get_const_enc_ptr(const ASN1_VALUE **pval, const ASN1_ITEM *it) { const ASN1_AUX *aux; if (pval == NULL || *pval == NULL) return NULL; aux = it->funcs; if (aux == NULL || (aux->flags & ASN1_AFLG_ENCODING) == 0) return NULL; return offset2ptr(*pval, aux->enc_offset); } void ossl_asn1_enc_init(ASN1_VALUE **pval, const ASN1_ITEM *it) { ASN1_ENCODING *enc = asn1_get_enc_ptr(pval, it); if (enc != NULL) { enc->enc = NULL; enc->len = 0; enc->modified = 1; } } void ossl_asn1_enc_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { ASN1_ENCODING *enc = asn1_get_enc_ptr(pval, it); if (enc != NULL) { OPENSSL_free(enc->enc); enc->enc = NULL; enc->len = 0; enc->modified = 1; } } int ossl_asn1_enc_save(ASN1_VALUE **pval, const unsigned char *in, int inlen, const ASN1_ITEM *it) { ASN1_ENCODING *enc = asn1_get_enc_ptr(pval, it); if (enc == NULL) return 1; OPENSSL_free(enc->enc); if (inlen <= 0) return 0; if ((enc->enc = OPENSSL_malloc(inlen)) == NULL) return 0; memcpy(enc->enc, in, inlen); enc->len = inlen; enc->modified = 0; return 1; } int ossl_asn1_enc_restore(int *len, unsigned char **out, const ASN1_VALUE **pval, const ASN1_ITEM *it) { const ASN1_ENCODING *enc = asn1_get_const_enc_ptr(pval, it); if (enc == NULL || enc->modified) return 0; if (out) { memcpy(*out, enc->enc, enc->len); *out += enc->len; } if (len != NULL) *len = enc->len; return 1; } /* Given an ASN1_TEMPLATE get a pointer to a field */ ASN1_VALUE **ossl_asn1_get_field_ptr(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) { ASN1_VALUE **pvaltmp = offset2ptr(*pval, tt->offset); /* * NOTE for BOOLEAN types the field is just a plain int so we can't * return int **, so settle for (int *). */ return pvaltmp; } /* Given an ASN1_TEMPLATE get a const pointer to a field */ const ASN1_VALUE **ossl_asn1_get_const_field_ptr(const ASN1_VALUE **pval, const ASN1_TEMPLATE *tt) { return offset2ptr(*pval, tt->offset); } /* * Handle ANY DEFINED BY template, find the selector, look up the relevant * ASN1_TEMPLATE in the table and return it. */ const ASN1_TEMPLATE *ossl_asn1_do_adb(const ASN1_VALUE *val, const ASN1_TEMPLATE *tt, int nullerr) { const ASN1_ADB *adb; const ASN1_ADB_TABLE *atbl; long selector; const ASN1_VALUE **sfld; int i; if ((tt->flags & ASN1_TFLG_ADB_MASK) == 0) return tt; /* Else ANY DEFINED BY ... get the table */ adb = ASN1_ADB_ptr(tt->item); /* Get the selector field */ sfld = offset2ptr(val, adb->offset); /* Check if NULL */ if (*sfld == NULL) { if (adb->null_tt == NULL) goto err; return adb->null_tt; } /* * Convert type to a long: NB: don't check for NID_undef here because it * might be a legitimate value in the table */ if ((tt->flags & ASN1_TFLG_ADB_OID) != 0) selector = OBJ_obj2nid((ASN1_OBJECT *)*sfld); else selector = ASN1_INTEGER_get((ASN1_INTEGER *)*sfld); /* Let application callback translate value */ if (adb->adb_cb != NULL && adb->adb_cb(&selector) == 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE); return NULL; } /* * Try to find matching entry in table Maybe should check application * types first to allow application override? Might also be useful to * have a flag which indicates table is sorted and we can do a binary * search. For now stick to a linear search. */ for (atbl = adb->tbl, i = 0; i < adb->tblcount; i++, atbl++) if (atbl->value == selector) return &atbl->tt; /* FIXME: need to search application table too */ /* No match, return default type */ if (!adb->default_tt) goto err; return adb->default_tt; err: /* FIXME: should log the value or OID of unsupported type */ if (nullerr) ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE); return NULL; }
7,863
26.211073
81
c
openssl
openssl-master/crypto/asn1/tbl_standard.h
/* * Copyright 1999-2020 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 */ /* size limits: this stuff is taken straight from RFC3280 */ #define ub_name 32768 #define ub_common_name 64 #define ub_locality_name 128 #define ub_state_name 128 #define ub_organization_name 64 #define ub_organization_unit_name 64 #define ub_title 64 #define ub_email_address 128 #define ub_serial_number 64 /* From RFC4524 */ #define ub_rfc822_mailbox 256 /* This table must be kept in NID order */ static const ASN1_STRING_TABLE tbl_standard[] = { {NID_commonName, 1, ub_common_name, DIRSTRING_TYPE, 0}, {NID_countryName, 2, 2, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, {NID_localityName, 1, ub_locality_name, DIRSTRING_TYPE, 0}, {NID_stateOrProvinceName, 1, ub_state_name, DIRSTRING_TYPE, 0}, {NID_organizationName, 1, ub_organization_name, DIRSTRING_TYPE, 0}, {NID_organizationalUnitName, 1, ub_organization_unit_name, DIRSTRING_TYPE, 0}, {NID_pkcs9_emailAddress, 1, ub_email_address, B_ASN1_IA5STRING, STABLE_NO_MASK}, {NID_pkcs9_unstructuredName, 1, -1, PKCS9STRING_TYPE, 0}, {NID_pkcs9_challengePassword, 1, -1, PKCS9STRING_TYPE, 0}, {NID_pkcs9_unstructuredAddress, 1, -1, DIRSTRING_TYPE, 0}, {NID_givenName, 1, ub_name, DIRSTRING_TYPE, 0}, {NID_surname, 1, ub_name, DIRSTRING_TYPE, 0}, {NID_initials, 1, ub_name, DIRSTRING_TYPE, 0}, {NID_serialNumber, 1, ub_serial_number, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, {NID_friendlyName, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK}, {NID_name, 1, ub_name, DIRSTRING_TYPE, 0}, {NID_dnQualifier, -1, -1, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, {NID_domainComponent, 1, -1, B_ASN1_IA5STRING, STABLE_NO_MASK}, {NID_ms_csp_name, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK}, {NID_rfc822Mailbox, 1, ub_rfc822_mailbox, B_ASN1_IA5STRING, STABLE_NO_MASK}, {NID_jurisdictionCountryName, 2, 2, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, {NID_INN, 1, 12, B_ASN1_NUMERICSTRING, STABLE_NO_MASK}, {NID_OGRN, 1, 13, B_ASN1_NUMERICSTRING, STABLE_NO_MASK}, {NID_SNILS, 1, 11, B_ASN1_NUMERICSTRING, STABLE_NO_MASK}, {NID_countryCode3c, 3, 3, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, {NID_countryCode3n, 3, 3, B_ASN1_NUMERICSTRING, STABLE_NO_MASK}, {NID_dnsName, 0, -1, B_ASN1_UTF8STRING, STABLE_NO_MASK}, {NID_id_on_SmtpUTF8Mailbox, 1, ub_email_address, B_ASN1_UTF8STRING, STABLE_NO_MASK} };
2,854
44.31746
87
h
openssl
openssl-master/crypto/asn1/x_algor.c
/* * Copyright 1998-2022 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 */ #include <stddef.h> #include <openssl/x509.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/err.h> #include "crypto/asn1.h" #include "crypto/evp.h" ASN1_SEQUENCE(X509_ALGOR) = { ASN1_SIMPLE(X509_ALGOR, algorithm, ASN1_OBJECT), ASN1_OPT(X509_ALGOR, parameter, ASN1_ANY) } ASN1_SEQUENCE_END(X509_ALGOR) ASN1_ITEM_TEMPLATE(X509_ALGORS) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, algorithms, X509_ALGOR) ASN1_ITEM_TEMPLATE_END(X509_ALGORS) IMPLEMENT_ASN1_FUNCTIONS(X509_ALGOR) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(X509_ALGORS, X509_ALGORS, X509_ALGORS) IMPLEMENT_ASN1_DUP_FUNCTION(X509_ALGOR) int X509_ALGOR_set0(X509_ALGOR *alg, ASN1_OBJECT *aobj, int ptype, void *pval) { if (alg == NULL) return 0; if (ptype != V_ASN1_UNDEF && alg->parameter == NULL && (alg->parameter = ASN1_TYPE_new()) == NULL) return 0; ASN1_OBJECT_free(alg->algorithm); alg->algorithm = aobj; if (ptype == V_ASN1_EOC) return 1; if (ptype == V_ASN1_UNDEF) { ASN1_TYPE_free(alg->parameter); alg->parameter = NULL; } else ASN1_TYPE_set(alg->parameter, ptype, pval); return 1; } X509_ALGOR *ossl_X509_ALGOR_from_nid(int nid, int ptype, void *pval) { ASN1_OBJECT *algo = OBJ_nid2obj(nid); X509_ALGOR *alg = NULL; if (algo == NULL) return NULL; if ((alg = X509_ALGOR_new()) == NULL) goto err; if (X509_ALGOR_set0(alg, algo, ptype, pval)) return alg; alg->algorithm = NULL; /* precaution to prevent double free */ err: X509_ALGOR_free(alg); /* ASN1_OBJECT_free(algo) is not needed due to OBJ_nid2obj() */ return NULL; } void X509_ALGOR_get0(const ASN1_OBJECT **paobj, int *pptype, const void **ppval, const X509_ALGOR *algor) { if (paobj) *paobj = algor->algorithm; if (pptype) { if (algor->parameter == NULL) { *pptype = V_ASN1_UNDEF; return; } else *pptype = algor->parameter->type; if (ppval) *ppval = algor->parameter->value.ptr; } } /* Set up an X509_ALGOR DigestAlgorithmIdentifier from an EVP_MD */ void X509_ALGOR_set_md(X509_ALGOR *alg, const EVP_MD *md) { int type = md->flags & EVP_MD_FLAG_DIGALGID_ABSENT ? V_ASN1_UNDEF : V_ASN1_NULL; (void)X509_ALGOR_set0(alg, OBJ_nid2obj(EVP_MD_get_type(md)), type, NULL); } int X509_ALGOR_cmp(const X509_ALGOR *a, const X509_ALGOR *b) { int rv; rv = OBJ_cmp(a->algorithm, b->algorithm); if (rv) return rv; if (!a->parameter && !b->parameter) return 0; return ASN1_TYPE_cmp(a->parameter, b->parameter); } int X509_ALGOR_copy(X509_ALGOR *dest, const X509_ALGOR *src) { if (src == NULL || dest == NULL) return 0; if (dest->algorithm) ASN1_OBJECT_free(dest->algorithm); dest->algorithm = NULL; if (dest->parameter) ASN1_TYPE_free(dest->parameter); dest->parameter = NULL; if (src->algorithm) if ((dest->algorithm = OBJ_dup(src->algorithm)) == NULL) return 0; if (src->parameter != NULL) { dest->parameter = ASN1_TYPE_new(); if (dest->parameter == NULL) return 0; /* Assuming this is also correct for a BOOL. * set does copy as a side effect. */ if (ASN1_TYPE_set1(dest->parameter, src->parameter->type, src->parameter->value.ptr) == 0) return 0; } return 1; } /* allocate and set algorithm ID from EVP_MD, default SHA1 */ int ossl_x509_algor_new_from_md(X509_ALGOR **palg, const EVP_MD *md) { X509_ALGOR *alg; /* Default is SHA1 so no need to create it - still success */ if (md == NULL || EVP_MD_is_a(md, "SHA1")) return 1; if ((alg = X509_ALGOR_new()) == NULL) return 0; X509_ALGOR_set_md(alg, md); *palg = alg; return 1; } /* convert algorithm ID to EVP_MD, default SHA1 */ const EVP_MD *ossl_x509_algor_get_md(X509_ALGOR *alg) { const EVP_MD *md; if (alg == NULL) return EVP_sha1(); md = EVP_get_digestbyobj(alg->algorithm); if (md == NULL) ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_DIGEST); return md; } X509_ALGOR *ossl_x509_algor_mgf1_decode(X509_ALGOR *alg) { if (OBJ_obj2nid(alg->algorithm) != NID_mgf1) return NULL; return ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(X509_ALGOR), alg->parameter); } /* Allocate and set MGF1 algorithm ID from EVP_MD */ int ossl_x509_algor_md_to_mgf1(X509_ALGOR **palg, const EVP_MD *mgf1md) { X509_ALGOR *algtmp = NULL; ASN1_STRING *stmp = NULL; *palg = NULL; if (mgf1md == NULL || EVP_MD_is_a(mgf1md, "SHA1")) return 1; /* need to embed algorithm ID inside another */ if (!ossl_x509_algor_new_from_md(&algtmp, mgf1md)) goto err; if (ASN1_item_pack(algtmp, ASN1_ITEM_rptr(X509_ALGOR), &stmp) == NULL) goto err; *palg = ossl_X509_ALGOR_from_nid(NID_mgf1, V_ASN1_SEQUENCE, stmp); if (*palg == NULL) goto err; stmp = NULL; err: ASN1_STRING_free(stmp); X509_ALGOR_free(algtmp); return *palg != NULL; }
5,631
27.16
79
c
openssl
openssl-master/crypto/asn1/x_bignum.c
/* * Copyright 2000-2016 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/bn.h> /* * Custom primitive type for BIGNUM handling. This reads in an ASN1_INTEGER * as a BIGNUM directly. Currently it ignores the sign which isn't a problem * since all BIGNUMs used are non negative and anything that looks negative * is normally due to an encoding error. */ #define BN_SENSITIVE 1 static int bn_new(ASN1_VALUE **pval, const ASN1_ITEM *it); static int bn_secure_new(ASN1_VALUE **pval, const ASN1_ITEM *it); static void bn_free(ASN1_VALUE **pval, const ASN1_ITEM *it); static int bn_i2c(const ASN1_VALUE **pval, unsigned char *cont, int *putype, const ASN1_ITEM *it); static int bn_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it); static int bn_secure_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it); static int bn_print(BIO *out, const ASN1_VALUE **pval, const ASN1_ITEM *it, int indent, const ASN1_PCTX *pctx); static ASN1_PRIMITIVE_FUNCS bignum_pf = { NULL, 0, bn_new, bn_free, 0, bn_c2i, bn_i2c, bn_print }; static ASN1_PRIMITIVE_FUNCS cbignum_pf = { NULL, 0, bn_secure_new, bn_free, 0, bn_secure_c2i, bn_i2c, bn_print }; ASN1_ITEM_start(BIGNUM) ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &bignum_pf, 0, "BIGNUM" ASN1_ITEM_end(BIGNUM) ASN1_ITEM_start(CBIGNUM) ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &cbignum_pf, BN_SENSITIVE, "CBIGNUM" ASN1_ITEM_end(CBIGNUM) static int bn_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { *pval = (ASN1_VALUE *)BN_new(); if (*pval != NULL) return 1; else return 0; } static int bn_secure_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { *pval = (ASN1_VALUE *)BN_secure_new(); if (*pval != NULL) return 1; else return 0; } static void bn_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { if (*pval == NULL) return; if (it->size & BN_SENSITIVE) BN_clear_free((BIGNUM *)*pval); else BN_free((BIGNUM *)*pval); *pval = NULL; } static int bn_i2c(const ASN1_VALUE **pval, unsigned char *cont, int *putype, const ASN1_ITEM *it) { BIGNUM *bn; int pad; if (*pval == NULL) return -1; bn = (BIGNUM *)*pval; /* If MSB set in an octet we need a padding byte */ if (BN_num_bits(bn) & 0x7) pad = 0; else pad = 1; if (cont) { if (pad) *cont++ = 0; BN_bn2bin(bn, cont); } return pad + BN_num_bytes(bn); } static int bn_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it) { BIGNUM *bn; if (*pval == NULL && !bn_new(pval, it)) return 0; bn = (BIGNUM *)*pval; if (!BN_bin2bn(cont, len, bn)) { bn_free(pval, it); return 0; } return 1; } static int bn_secure_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it) { int ret; BIGNUM *bn; if (*pval == NULL && !bn_secure_new(pval, it)) return 0; ret = bn_c2i(pval, cont, len, utype, free_cont, it); if (!ret) return 0; /* Set constant-time flag for all secure BIGNUMS */ bn = (BIGNUM *)*pval; BN_set_flags(bn, BN_FLG_CONSTTIME); return ret; } static int bn_print(BIO *out, const ASN1_VALUE **pval, const ASN1_ITEM *it, int indent, const ASN1_PCTX *pctx) { if (!BN_print(out, *(BIGNUM **)pval)) return 0; if (BIO_puts(out, "\n") <= 0) return 0; return 1; }
4,177
25.443038
91
c
openssl
openssl-master/crypto/asn1/x_info.c
/* * Copyright 1995-2020 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/asn1.h> #include <openssl/x509.h> X509_INFO *X509_INFO_new(void) { X509_INFO *ret; ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; return ret; } void X509_INFO_free(X509_INFO *x) { if (x == NULL) return; X509_free(x->x509); X509_CRL_free(x->crl); X509_PKEY_free(x->x_pkey); OPENSSL_free(x->enc_data); OPENSSL_free(x); }
829
20.842105
74
c
openssl
openssl-master/crypto/asn1/x_int64.c
/* * Copyright 2017-2021 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include "internal/numbers.h" #include <openssl/asn1t.h> #include <openssl/bn.h> #include "asn1_local.h" /* * Custom primitive types for handling int32_t, int64_t, uint32_t, uint64_t. * This converts between an ASN1_INTEGER and those types directly. * This is preferred to using the LONG / ZLONG primitives. */ /* * We abuse the ASN1_ITEM fields |size| as a flags field */ #define INTxx_FLAG_ZERO_DEFAULT (1<<0) #define INTxx_FLAG_SIGNED (1<<1) static int uint64_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { if ((*pval = (ASN1_VALUE *)OPENSSL_zalloc(sizeof(uint64_t))) == NULL) return 0; return 1; } static void uint64_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { OPENSSL_free(*pval); *pval = NULL; } static void uint64_clear(ASN1_VALUE **pval, const ASN1_ITEM *it) { **(uint64_t **)pval = 0; } static int uint64_i2c(const ASN1_VALUE **pval, unsigned char *cont, int *putype, const ASN1_ITEM *it) { uint64_t utmp; int neg = 0; /* this exists to bypass broken gcc optimization */ char *cp = (char *)*pval; /* use memcpy, because we may not be uint64_t aligned */ memcpy(&utmp, cp, sizeof(utmp)); if ((it->size & INTxx_FLAG_ZERO_DEFAULT) == INTxx_FLAG_ZERO_DEFAULT && utmp == 0) return -1; if ((it->size & INTxx_FLAG_SIGNED) == INTxx_FLAG_SIGNED && (int64_t)utmp < 0) { /* ossl_i2c_uint64_int() assumes positive values */ utmp = 0 - utmp; neg = 1; } return ossl_i2c_uint64_int(cont, utmp, neg); } static int uint64_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it) { uint64_t utmp = 0; char *cp; int neg = 0; if (*pval == NULL && !uint64_new(pval, it)) return 0; cp = (char *)*pval; /* * Strictly speaking, zero length is malformed. However, long_c2i * (x_long.c) encodes 0 as a zero length INTEGER (wrongly, of course), * so for the sake of backward compatibility, we still decode zero * length INTEGERs as the number zero. */ if (len == 0) goto long_compat; if (!ossl_c2i_uint64_int(&utmp, &neg, &cont, len)) return 0; if ((it->size & INTxx_FLAG_SIGNED) == 0 && neg) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_NEGATIVE_VALUE); return 0; } if ((it->size & INTxx_FLAG_SIGNED) == INTxx_FLAG_SIGNED && !neg && utmp > INT64_MAX) { ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LARGE); return 0; } if (neg) /* ossl_c2i_uint64_int() returns positive values */ utmp = 0 - utmp; long_compat: memcpy(cp, &utmp, sizeof(utmp)); return 1; } static int uint64_print(BIO *out, const ASN1_VALUE **pval, const ASN1_ITEM *it, int indent, const ASN1_PCTX *pctx) { if ((it->size & INTxx_FLAG_SIGNED) == INTxx_FLAG_SIGNED) return BIO_printf(out, "%jd\n", **(int64_t **)pval); return BIO_printf(out, "%ju\n", **(uint64_t **)pval); } /* 32-bit variants */ static int uint32_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { if ((*pval = (ASN1_VALUE *)OPENSSL_zalloc(sizeof(uint32_t))) == NULL) return 0; return 1; } static void uint32_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { OPENSSL_free(*pval); *pval = NULL; } static void uint32_clear(ASN1_VALUE **pval, const ASN1_ITEM *it) { **(uint32_t **)pval = 0; } static int uint32_i2c(const ASN1_VALUE **pval, unsigned char *cont, int *putype, const ASN1_ITEM *it) { uint32_t utmp; int neg = 0; /* this exists to bypass broken gcc optimization */ char *cp = (char *)*pval; /* use memcpy, because we may not be uint32_t aligned */ memcpy(&utmp, cp, sizeof(utmp)); if ((it->size & INTxx_FLAG_ZERO_DEFAULT) == INTxx_FLAG_ZERO_DEFAULT && utmp == 0) return -1; if ((it->size & INTxx_FLAG_SIGNED) == INTxx_FLAG_SIGNED && (int32_t)utmp < 0) { /* ossl_i2c_uint64_int() assumes positive values */ utmp = 0 - utmp; neg = 1; } return ossl_i2c_uint64_int(cont, (uint64_t)utmp, neg); } /* * Absolute value of INT32_MIN: we can't just use -INT32_MIN as it produces * overflow warnings. */ #define ABS_INT32_MIN ((uint32_t)INT32_MAX + 1) static int uint32_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it) { uint64_t utmp = 0; uint32_t utmp2 = 0; char *cp; int neg = 0; if (*pval == NULL && !uint64_new(pval, it)) return 0; cp = (char *)*pval; /* * Strictly speaking, zero length is malformed. However, long_c2i * (x_long.c) encodes 0 as a zero length INTEGER (wrongly, of course), * so for the sake of backward compatibility, we still decode zero * length INTEGERs as the number zero. */ if (len == 0) goto long_compat; if (!ossl_c2i_uint64_int(&utmp, &neg, &cont, len)) return 0; if ((it->size & INTxx_FLAG_SIGNED) == 0 && neg) { ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_NEGATIVE_VALUE); return 0; } if (neg) { if (utmp > ABS_INT32_MIN) { ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_SMALL); return 0; } utmp = 0 - utmp; } else { if (((it->size & INTxx_FLAG_SIGNED) != 0 && utmp > INT32_MAX) || ((it->size & INTxx_FLAG_SIGNED) == 0 && utmp > UINT32_MAX)) { ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LARGE); return 0; } } long_compat: utmp2 = (uint32_t)utmp; memcpy(cp, &utmp2, sizeof(utmp2)); return 1; } static int uint32_print(BIO *out, const ASN1_VALUE **pval, const ASN1_ITEM *it, int indent, const ASN1_PCTX *pctx) { if ((it->size & INTxx_FLAG_SIGNED) == INTxx_FLAG_SIGNED) return BIO_printf(out, "%d\n", (int)**(int32_t **)pval); return BIO_printf(out, "%u\n", (unsigned int)**(uint32_t **)pval); } /* Define the primitives themselves */ static ASN1_PRIMITIVE_FUNCS uint32_pf = { NULL, 0, uint32_new, uint32_free, uint32_clear, uint32_c2i, uint32_i2c, uint32_print }; static ASN1_PRIMITIVE_FUNCS uint64_pf = { NULL, 0, uint64_new, uint64_free, uint64_clear, uint64_c2i, uint64_i2c, uint64_print }; ASN1_ITEM_start(INT32) ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &uint32_pf, INTxx_FLAG_SIGNED, "INT32" ASN1_ITEM_end(INT32) ASN1_ITEM_start(UINT32) ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &uint32_pf, 0, "UINT32" ASN1_ITEM_end(UINT32) ASN1_ITEM_start(INT64) ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &uint64_pf, INTxx_FLAG_SIGNED, "INT64" ASN1_ITEM_end(INT64) ASN1_ITEM_start(UINT64) ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &uint64_pf, 0, "UINT64" ASN1_ITEM_end(UINT64) ASN1_ITEM_start(ZINT32) ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &uint32_pf, INTxx_FLAG_ZERO_DEFAULT|INTxx_FLAG_SIGNED, "ZINT32" ASN1_ITEM_end(ZINT32) ASN1_ITEM_start(ZUINT32) ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &uint32_pf, INTxx_FLAG_ZERO_DEFAULT, "ZUINT32" ASN1_ITEM_end(ZUINT32) ASN1_ITEM_start(ZINT64) ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &uint64_pf, INTxx_FLAG_ZERO_DEFAULT|INTxx_FLAG_SIGNED, "ZINT64" ASN1_ITEM_end(ZINT64) ASN1_ITEM_start(ZUINT64) ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &uint64_pf, INTxx_FLAG_ZERO_DEFAULT, "ZUINT64" ASN1_ITEM_end(ZUINT64)
7,959
26.638889
80
c
openssl
openssl-master/crypto/asn1/x_long.c
/* * Copyright 2000-2020 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #define COPY_SIZE(a, b) (sizeof(a) < sizeof(b) ? sizeof(a) : sizeof(b)) /* * Custom primitive type for long handling. This converts between an * ASN1_INTEGER and a long directly. */ static int long_new(ASN1_VALUE **pval, const ASN1_ITEM *it); static void long_free(ASN1_VALUE **pval, const ASN1_ITEM *it); static int long_i2c(const ASN1_VALUE **pval, unsigned char *cont, int *putype, const ASN1_ITEM *it); static int long_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it); static int long_print(BIO *out, const ASN1_VALUE **pval, const ASN1_ITEM *it, int indent, const ASN1_PCTX *pctx); static ASN1_PRIMITIVE_FUNCS long_pf = { NULL, 0, long_new, long_free, long_free, /* Clear should set to initial value */ long_c2i, long_i2c, long_print }; ASN1_ITEM_start(LONG) ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &long_pf, ASN1_LONG_UNDEF, "LONG" ASN1_ITEM_end(LONG) ASN1_ITEM_start(ZLONG) ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &long_pf, 0, "ZLONG" ASN1_ITEM_end(ZLONG) static int long_new(ASN1_VALUE **pval, const ASN1_ITEM *it) { memcpy(pval, &it->size, COPY_SIZE(*pval, it->size)); return 1; } static void long_free(ASN1_VALUE **pval, const ASN1_ITEM *it) { memcpy(pval, &it->size, COPY_SIZE(*pval, it->size)); } /* * Originally BN_num_bits_word was called to perform this operation, but * trouble is that there is no guarantee that sizeof(long) equals to * sizeof(BN_ULONG). BN_ULONG is a configurable type that can be as wide * as long, but also double or half... */ static int num_bits_ulong(unsigned long value) { size_t i; unsigned long ret = 0; /* * It is argued that *on average* constant counter loop performs * not worse [if not better] than one with conditional break or * mask-n-table-lookup-style, because of branch misprediction * penalties. */ for (i = 0; i < sizeof(value) * 8; i++) { ret += (value != 0); value >>= 1; } return (int)ret; } static int long_i2c(const ASN1_VALUE **pval, unsigned char *cont, int *putype, const ASN1_ITEM *it) { long ltmp; unsigned long utmp, sign; int clen, pad, i; memcpy(&ltmp, pval, COPY_SIZE(*pval, ltmp)); if (ltmp == it->size) return -1; /* * Convert the long to positive: we subtract one if negative so we can * cleanly handle the padding if only the MSB of the leading octet is * set. */ if (ltmp < 0) { sign = 0xff; utmp = 0 - (unsigned long)ltmp - 1; } else { sign = 0; utmp = ltmp; } clen = num_bits_ulong(utmp); /* If MSB of leading octet set we need to pad */ if (!(clen & 0x7)) pad = 1; else pad = 0; /* Convert number of bits to number of octets */ clen = (clen + 7) >> 3; if (cont != NULL) { if (pad) *cont++ = (unsigned char)sign; for (i = clen - 1; i >= 0; i--) { cont[i] = (unsigned char)(utmp ^ sign); utmp >>= 8; } } return clen + pad; } static int long_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it) { int i; long ltmp; unsigned long utmp = 0, sign = 0x100; if (len > 1) { /* * Check possible pad byte. Worst case, we're skipping past actual * content, but since that's only with 0x00 and 0xff and we set neg * accordingly, the result will be correct in the end anyway. */ switch (cont[0]) { case 0xff: cont++; len--; sign = 0xff; break; case 0: cont++; len--; sign = 0; break; } } if (len > (int)sizeof(long)) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INTEGER_TOO_LARGE_FOR_LONG); return 0; } if (sign == 0x100) { /* Is it negative? */ if (len && (cont[0] & 0x80)) sign = 0xff; else sign = 0; } else if (((sign ^ cont[0]) & 0x80) == 0) { /* same sign bit? */ ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_PADDING); return 0; } utmp = 0; for (i = 0; i < len; i++) { utmp <<= 8; utmp |= cont[i] ^ sign; } ltmp = (long)utmp; if (ltmp < 0) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INTEGER_TOO_LARGE_FOR_LONG); return 0; } if (sign) ltmp = -ltmp - 1; if (ltmp == it->size) { ERR_raise(ERR_LIB_ASN1, ASN1_R_INTEGER_TOO_LARGE_FOR_LONG); return 0; } memcpy(pval, &ltmp, COPY_SIZE(*pval, ltmp)); return 1; } static int long_print(BIO *out, const ASN1_VALUE **pval, const ASN1_ITEM *it, int indent, const ASN1_PCTX *pctx) { long l; memcpy(&l, pval, COPY_SIZE(*pval, l)); return BIO_printf(out, "%ld\n", l); }
5,492
26.883249
88
c
openssl
openssl-master/crypto/asn1/x_pkey.c
/* * Copyright 1995-2020 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> X509_PKEY *X509_PKEY_new(void) { X509_PKEY *ret = NULL; ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->enc_algor = X509_ALGOR_new(); ret->enc_pkey = ASN1_OCTET_STRING_new(); if (ret->enc_algor == NULL || ret->enc_pkey == NULL) { X509_PKEY_free(ret); ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB); return NULL; } return ret; } void X509_PKEY_free(X509_PKEY *x) { if (x == NULL) return; X509_ALGOR_free(x->enc_algor); ASN1_OCTET_STRING_free(x->enc_pkey); EVP_PKEY_free(x->dec_pkey); if (x->key_free) OPENSSL_free(x->key_data); OPENSSL_free(x); }
1,139
23.255319
74
c
openssl
openssl-master/crypto/asn1/x_sig.c
/* * Copyright 1995-2016 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/x509.h> #include "crypto/x509.h" ASN1_SEQUENCE(X509_SIG) = { ASN1_SIMPLE(X509_SIG, algor, X509_ALGOR), ASN1_SIMPLE(X509_SIG, digest, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(X509_SIG) IMPLEMENT_ASN1_FUNCTIONS(X509_SIG) void X509_SIG_get0(const X509_SIG *sig, const X509_ALGOR **palg, const ASN1_OCTET_STRING **pdigest) { if (palg) *palg = sig->algor; if (pdigest) *pdigest = sig->digest; } void X509_SIG_getm(X509_SIG *sig, X509_ALGOR **palg, ASN1_OCTET_STRING **pdigest) { if (palg) *palg = sig->algor; if (pdigest) *pdigest = sig->digest; }
1,079
26
74
c
openssl
openssl-master/crypto/asn1/x_spki.c
/* * Copyright 1995-2016 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/x509.h> #include <openssl/asn1t.h> ASN1_SEQUENCE(NETSCAPE_SPKAC) = { ASN1_SIMPLE(NETSCAPE_SPKAC, pubkey, X509_PUBKEY), ASN1_SIMPLE(NETSCAPE_SPKAC, challenge, ASN1_IA5STRING) } ASN1_SEQUENCE_END(NETSCAPE_SPKAC) IMPLEMENT_ASN1_FUNCTIONS(NETSCAPE_SPKAC) ASN1_SEQUENCE(NETSCAPE_SPKI) = { ASN1_SIMPLE(NETSCAPE_SPKI, spkac, NETSCAPE_SPKAC), ASN1_EMBED(NETSCAPE_SPKI, sig_algor, X509_ALGOR), ASN1_SIMPLE(NETSCAPE_SPKI, signature, ASN1_BIT_STRING) } ASN1_SEQUENCE_END(NETSCAPE_SPKI) IMPLEMENT_ASN1_FUNCTIONS(NETSCAPE_SPKI)
964
32.275862
74
c
openssl
openssl-master/crypto/asn1/x_val.c
/* * Copyright 1995-2016 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/x509.h> ASN1_SEQUENCE(X509_VAL) = { ASN1_SIMPLE(X509_VAL, notBefore, ASN1_TIME), ASN1_SIMPLE(X509_VAL, notAfter, ASN1_TIME) } ASN1_SEQUENCE_END(X509_VAL) IMPLEMENT_ASN1_FUNCTIONS(X509_VAL)
639
29.47619
74
c
openssl
openssl-master/crypto/async/async.c
/* * Copyright 2015-2022 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 */ /* * Without this we start getting longjmp crashes because it thinks we're jumping * up the stack when in fact we are jumping to an entirely different stack. The * cost of this is not having certain buffer overrun/underrun checks etc for * this source file :-( */ #undef _FORTIFY_SOURCE /* This must be the first #include file */ #include "async_local.h" #include <openssl/err.h> #include "crypto/cryptlib.h" #include <string.h> #define ASYNC_JOB_RUNNING 0 #define ASYNC_JOB_PAUSING 1 #define ASYNC_JOB_PAUSED 2 #define ASYNC_JOB_STOPPING 3 static CRYPTO_THREAD_LOCAL ctxkey; static CRYPTO_THREAD_LOCAL poolkey; static void async_delete_thread_state(void *arg); static async_ctx *async_ctx_new(void) { async_ctx *nctx; if (!ossl_init_thread_start(NULL, NULL, async_delete_thread_state)) return NULL; nctx = OPENSSL_malloc(sizeof(*nctx)); if (nctx == NULL) goto err; async_fibre_init_dispatcher(&nctx->dispatcher); nctx->currjob = NULL; nctx->blocked = 0; if (!CRYPTO_THREAD_set_local(&ctxkey, nctx)) goto err; return nctx; err: OPENSSL_free(nctx); return NULL; } async_ctx *async_get_ctx(void) { return (async_ctx *)CRYPTO_THREAD_get_local(&ctxkey); } static int async_ctx_free(void) { async_ctx *ctx; ctx = async_get_ctx(); if (!CRYPTO_THREAD_set_local(&ctxkey, NULL)) return 0; OPENSSL_free(ctx); return 1; } static ASYNC_JOB *async_job_new(void) { ASYNC_JOB *job = NULL; job = OPENSSL_zalloc(sizeof(*job)); if (job == NULL) return NULL; job->status = ASYNC_JOB_RUNNING; return job; } static void async_job_free(ASYNC_JOB *job) { if (job != NULL) { OPENSSL_free(job->funcargs); async_fibre_free(&job->fibrectx); OPENSSL_free(job); } } static ASYNC_JOB *async_get_pool_job(void) { ASYNC_JOB *job; async_pool *pool; pool = (async_pool *)CRYPTO_THREAD_get_local(&poolkey); if (pool == NULL) { /* * Pool has not been initialised, so init with the defaults, i.e. * no max size and no pre-created jobs */ if (ASYNC_init_thread(0, 0) == 0) return NULL; pool = (async_pool *)CRYPTO_THREAD_get_local(&poolkey); } job = sk_ASYNC_JOB_pop(pool->jobs); if (job == NULL) { /* Pool is empty */ if ((pool->max_size != 0) && (pool->curr_size >= pool->max_size)) return NULL; job = async_job_new(); if (job != NULL) { if (! async_fibre_makecontext(&job->fibrectx)) { async_job_free(job); return NULL; } pool->curr_size++; } } return job; } static void async_release_job(ASYNC_JOB *job) { async_pool *pool; pool = (async_pool *)CRYPTO_THREAD_get_local(&poolkey); if (pool == NULL) { ERR_raise(ERR_LIB_ASYNC, ERR_R_INTERNAL_ERROR); return; } OPENSSL_free(job->funcargs); job->funcargs = NULL; sk_ASYNC_JOB_push(pool->jobs, job); } void async_start_func(void) { ASYNC_JOB *job; async_ctx *ctx = async_get_ctx(); if (ctx == NULL) { ERR_raise(ERR_LIB_ASYNC, ERR_R_INTERNAL_ERROR); return; } while (1) { /* Run the job */ job = ctx->currjob; job->ret = job->func(job->funcargs); /* Stop the job */ job->status = ASYNC_JOB_STOPPING; if (!async_fibre_swapcontext(&job->fibrectx, &ctx->dispatcher, 1)) { /* * Should not happen. Getting here will close the thread...can't do * much about it */ ERR_raise(ERR_LIB_ASYNC, ASYNC_R_FAILED_TO_SWAP_CONTEXT); } } } int ASYNC_start_job(ASYNC_JOB **job, ASYNC_WAIT_CTX *wctx, int *ret, int (*func)(void *), void *args, size_t size) { async_ctx *ctx; OSSL_LIB_CTX *libctx; if (!OPENSSL_init_crypto(OPENSSL_INIT_ASYNC, NULL)) return ASYNC_ERR; ctx = async_get_ctx(); if (ctx == NULL) ctx = async_ctx_new(); if (ctx == NULL) return ASYNC_ERR; if (*job != NULL) ctx->currjob = *job; for (;;) { if (ctx->currjob != NULL) { if (ctx->currjob->status == ASYNC_JOB_STOPPING) { *ret = ctx->currjob->ret; ctx->currjob->waitctx = NULL; async_release_job(ctx->currjob); ctx->currjob = NULL; *job = NULL; return ASYNC_FINISH; } if (ctx->currjob->status == ASYNC_JOB_PAUSING) { *job = ctx->currjob; ctx->currjob->status = ASYNC_JOB_PAUSED; ctx->currjob = NULL; return ASYNC_PAUSE; } if (ctx->currjob->status == ASYNC_JOB_PAUSED) { if (*job == NULL) return ASYNC_ERR; ctx->currjob = *job; /* * Restore the default libctx to what it was the last time the * fibre ran */ libctx = OSSL_LIB_CTX_set0_default(ctx->currjob->libctx); if (libctx == NULL) { /* Failed to set the default context */ ERR_raise(ERR_LIB_ASYNC, ERR_R_INTERNAL_ERROR); goto err; } /* Resume previous job */ if (!async_fibre_swapcontext(&ctx->dispatcher, &ctx->currjob->fibrectx, 1)) { ctx->currjob->libctx = OSSL_LIB_CTX_set0_default(libctx); ERR_raise(ERR_LIB_ASYNC, ASYNC_R_FAILED_TO_SWAP_CONTEXT); goto err; } /* * In case the fibre changed the default libctx we set it back * again to what it was originally, and remember what it had * been changed to. */ ctx->currjob->libctx = OSSL_LIB_CTX_set0_default(libctx); continue; } /* Should not happen */ ERR_raise(ERR_LIB_ASYNC, ERR_R_INTERNAL_ERROR); async_release_job(ctx->currjob); ctx->currjob = NULL; *job = NULL; return ASYNC_ERR; } /* Start a new job */ if ((ctx->currjob = async_get_pool_job()) == NULL) return ASYNC_NO_JOBS; if (args != NULL) { ctx->currjob->funcargs = OPENSSL_malloc(size); if (ctx->currjob->funcargs == NULL) { async_release_job(ctx->currjob); ctx->currjob = NULL; return ASYNC_ERR; } memcpy(ctx->currjob->funcargs, args, size); } else { ctx->currjob->funcargs = NULL; } ctx->currjob->func = func; ctx->currjob->waitctx = wctx; libctx = ossl_lib_ctx_get_concrete(NULL); if (!async_fibre_swapcontext(&ctx->dispatcher, &ctx->currjob->fibrectx, 1)) { ERR_raise(ERR_LIB_ASYNC, ASYNC_R_FAILED_TO_SWAP_CONTEXT); goto err; } /* * In case the fibre changed the default libctx we set it back again * to what it was, and remember what it had been changed to. */ ctx->currjob->libctx = OSSL_LIB_CTX_set0_default(libctx); } err: async_release_job(ctx->currjob); ctx->currjob = NULL; *job = NULL; return ASYNC_ERR; } int ASYNC_pause_job(void) { ASYNC_JOB *job; async_ctx *ctx = async_get_ctx(); if (ctx == NULL || ctx->currjob == NULL || ctx->blocked) { /* * Could be we've deliberately not been started within a job so this is * counted as success. */ return 1; } job = ctx->currjob; job->status = ASYNC_JOB_PAUSING; if (!async_fibre_swapcontext(&job->fibrectx, &ctx->dispatcher, 1)) { ERR_raise(ERR_LIB_ASYNC, ASYNC_R_FAILED_TO_SWAP_CONTEXT); return 0; } /* Reset counts of added and deleted fds */ async_wait_ctx_reset_counts(job->waitctx); return 1; } static void async_empty_pool(async_pool *pool) { ASYNC_JOB *job; if (pool == NULL || pool->jobs == NULL) return; do { job = sk_ASYNC_JOB_pop(pool->jobs); async_job_free(job); } while (job); } int async_init(void) { if (!CRYPTO_THREAD_init_local(&ctxkey, NULL)) return 0; if (!CRYPTO_THREAD_init_local(&poolkey, NULL)) { CRYPTO_THREAD_cleanup_local(&ctxkey); return 0; } return async_local_init(); } void async_deinit(void) { CRYPTO_THREAD_cleanup_local(&ctxkey); CRYPTO_THREAD_cleanup_local(&poolkey); async_local_deinit(); } int ASYNC_init_thread(size_t max_size, size_t init_size) { async_pool *pool; size_t curr_size = 0; if (init_size > max_size) { ERR_raise(ERR_LIB_ASYNC, ASYNC_R_INVALID_POOL_SIZE); return 0; } if (!OPENSSL_init_crypto(OPENSSL_INIT_ASYNC, NULL)) return 0; if (!ossl_init_thread_start(NULL, NULL, async_delete_thread_state)) return 0; pool = OPENSSL_zalloc(sizeof(*pool)); if (pool == NULL) return 0; pool->jobs = sk_ASYNC_JOB_new_reserve(NULL, init_size); if (pool->jobs == NULL) { ERR_raise(ERR_LIB_ASYNC, ERR_R_CRYPTO_LIB); OPENSSL_free(pool); return 0; } pool->max_size = max_size; /* Pre-create jobs as required */ while (init_size--) { ASYNC_JOB *job; job = async_job_new(); if (job == NULL || !async_fibre_makecontext(&job->fibrectx)) { /* * Not actually fatal because we already created the pool, just * skip creation of any more jobs */ async_job_free(job); break; } job->funcargs = NULL; sk_ASYNC_JOB_push(pool->jobs, job); /* Cannot fail due to reserve */ curr_size++; } pool->curr_size = curr_size; if (!CRYPTO_THREAD_set_local(&poolkey, pool)) { ERR_raise(ERR_LIB_ASYNC, ASYNC_R_FAILED_TO_SET_POOL); goto err; } return 1; err: async_empty_pool(pool); sk_ASYNC_JOB_free(pool->jobs); OPENSSL_free(pool); return 0; } static void async_delete_thread_state(void *arg) { async_pool *pool = (async_pool *)CRYPTO_THREAD_get_local(&poolkey); if (pool != NULL) { async_empty_pool(pool); sk_ASYNC_JOB_free(pool->jobs); OPENSSL_free(pool); CRYPTO_THREAD_set_local(&poolkey, NULL); } async_local_cleanup(); async_ctx_free(); } void ASYNC_cleanup_thread(void) { if (!OPENSSL_init_crypto(OPENSSL_INIT_ASYNC, NULL)) return; async_delete_thread_state(NULL); } ASYNC_JOB *ASYNC_get_current_job(void) { async_ctx *ctx; if (!OPENSSL_init_crypto(OPENSSL_INIT_ASYNC, NULL)) return NULL; ctx = async_get_ctx(); if (ctx == NULL) return NULL; return ctx->currjob; } ASYNC_WAIT_CTX *ASYNC_get_wait_ctx(ASYNC_JOB *job) { return job->waitctx; } void ASYNC_block_pause(void) { async_ctx *ctx; if (!OPENSSL_init_crypto(OPENSSL_INIT_ASYNC, NULL)) return; ctx = async_get_ctx(); if (ctx == NULL || ctx->currjob == NULL) { /* * We're not in a job anyway so ignore this */ return; } ctx->blocked++; } void ASYNC_unblock_pause(void) { async_ctx *ctx; if (!OPENSSL_init_crypto(OPENSSL_INIT_ASYNC, NULL)) return; ctx = async_get_ctx(); if (ctx == NULL || ctx->currjob == NULL) { /* * We're not in a job anyway so ignore this */ return; } if (ctx->blocked > 0) ctx->blocked--; }
12,299
24.518672
80
c
openssl
openssl-master/crypto/async/async_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2021 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 */ #include <openssl/err.h> #include <openssl/asyncerr.h> #include "crypto/asyncerr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA ASYNC_str_reasons[] = { {ERR_PACK(ERR_LIB_ASYNC, 0, ASYNC_R_FAILED_TO_SET_POOL), "failed to set pool"}, {ERR_PACK(ERR_LIB_ASYNC, 0, ASYNC_R_FAILED_TO_SWAP_CONTEXT), "failed to swap context"}, {ERR_PACK(ERR_LIB_ASYNC, 0, ASYNC_R_INIT_FAILED), "init failed"}, {ERR_PACK(ERR_LIB_ASYNC, 0, ASYNC_R_INVALID_POOL_SIZE), "invalid pool size"}, {0, NULL} }; #endif int ossl_err_load_ASYNC_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(ASYNC_str_reasons[0].error) == NULL) ERR_load_strings_const(ASYNC_str_reasons); #endif return 1; }
1,113
28.315789
74
c
openssl
openssl-master/crypto/async/async_local.h
/* * Copyright 2015-2020 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 */ /* * Must do this before including any header files, because on MacOS/X <stlib.h> * includes <signal.h> which includes <ucontext.h> */ #if defined(__APPLE__) && defined(__MACH__) && !defined(_XOPEN_SOURCE) # define _XOPEN_SOURCE /* Otherwise incomplete ucontext_t structure */ # pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif #if defined(_WIN32) # include <windows.h> #endif #include "crypto/async.h" #include <openssl/crypto.h> typedef struct async_ctx_st async_ctx; typedef struct async_pool_st async_pool; #include "arch/async_win.h" #include "arch/async_posix.h" #include "arch/async_null.h" struct async_ctx_st { async_fibre dispatcher; ASYNC_JOB *currjob; unsigned int blocked; }; struct async_job_st { async_fibre fibrectx; int (*func) (void *); void *funcargs; int ret; int status; ASYNC_WAIT_CTX *waitctx; OSSL_LIB_CTX *libctx; }; struct fd_lookup_st { const void *key; OSSL_ASYNC_FD fd; void *custom_data; void (*cleanup)(ASYNC_WAIT_CTX *, const void *, OSSL_ASYNC_FD, void *); int add; int del; struct fd_lookup_st *next; }; struct async_wait_ctx_st { struct fd_lookup_st *fds; size_t numadd; size_t numdel; ASYNC_callback_fn callback; void *callback_arg; int status; }; DEFINE_STACK_OF(ASYNC_JOB) struct async_pool_st { STACK_OF(ASYNC_JOB) *jobs; size_t curr_size; size_t max_size; }; void async_local_cleanup(void); void async_start_func(void); async_ctx *async_get_ctx(void); void async_wait_ctx_reset_counts(ASYNC_WAIT_CTX *ctx);
1,929
22.536585
79
h
openssl
openssl-master/crypto/async/async_wait.c
/* * Copyright 2016-2020 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 */ /* This must be the first #include file */ #include "async_local.h" #include <openssl/err.h> ASYNC_WAIT_CTX *ASYNC_WAIT_CTX_new(void) { return OPENSSL_zalloc(sizeof(ASYNC_WAIT_CTX)); } void ASYNC_WAIT_CTX_free(ASYNC_WAIT_CTX *ctx) { struct fd_lookup_st *curr; struct fd_lookup_st *next; if (ctx == NULL) return; curr = ctx->fds; while (curr != NULL) { if (!curr->del) { /* Only try and cleanup if it hasn't been marked deleted */ if (curr->cleanup != NULL) curr->cleanup(ctx, curr->key, curr->fd, curr->custom_data); } /* Always free the fd_lookup_st */ next = curr->next; OPENSSL_free(curr); curr = next; } OPENSSL_free(ctx); } int ASYNC_WAIT_CTX_set_wait_fd(ASYNC_WAIT_CTX *ctx, const void *key, OSSL_ASYNC_FD fd, void *custom_data, void (*cleanup)(ASYNC_WAIT_CTX *, const void *, OSSL_ASYNC_FD, void *)) { struct fd_lookup_st *fdlookup; if ((fdlookup = OPENSSL_zalloc(sizeof(*fdlookup))) == NULL) return 0; fdlookup->key = key; fdlookup->fd = fd; fdlookup->custom_data = custom_data; fdlookup->cleanup = cleanup; fdlookup->add = 1; fdlookup->next = ctx->fds; ctx->fds = fdlookup; ctx->numadd++; return 1; } int ASYNC_WAIT_CTX_get_fd(ASYNC_WAIT_CTX *ctx, const void *key, OSSL_ASYNC_FD *fd, void **custom_data) { struct fd_lookup_st *curr; curr = ctx->fds; while (curr != NULL) { if (curr->del) { /* This one has been marked deleted so do nothing */ curr = curr->next; continue; } if (curr->key == key) { *fd = curr->fd; *custom_data = curr->custom_data; return 1; } curr = curr->next; } return 0; } int ASYNC_WAIT_CTX_get_all_fds(ASYNC_WAIT_CTX *ctx, OSSL_ASYNC_FD *fd, size_t *numfds) { struct fd_lookup_st *curr; curr = ctx->fds; *numfds = 0; while (curr != NULL) { if (curr->del) { /* This one has been marked deleted so do nothing */ curr = curr->next; continue; } if (fd != NULL) { *fd = curr->fd; fd++; } (*numfds)++; curr = curr->next; } return 1; } int ASYNC_WAIT_CTX_get_changed_fds(ASYNC_WAIT_CTX *ctx, OSSL_ASYNC_FD *addfd, size_t *numaddfds, OSSL_ASYNC_FD *delfd, size_t *numdelfds) { struct fd_lookup_st *curr; *numaddfds = ctx->numadd; *numdelfds = ctx->numdel; if (addfd == NULL && delfd == NULL) return 1; curr = ctx->fds; while (curr != NULL) { /* We ignore fds that have been marked as both added and deleted */ if (curr->del && !curr->add && (delfd != NULL)) { *delfd = curr->fd; delfd++; } if (curr->add && !curr->del && (addfd != NULL)) { *addfd = curr->fd; addfd++; } curr = curr->next; } return 1; } int ASYNC_WAIT_CTX_clear_fd(ASYNC_WAIT_CTX *ctx, const void *key) { struct fd_lookup_st *curr, *prev; curr = ctx->fds; prev = NULL; while (curr != NULL) { if (curr->del == 1) { /* This one has been marked deleted already so do nothing */ prev = curr; curr = curr->next; continue; } if (curr->key == key) { /* If fd has just been added, remove it from the list */ if (curr->add == 1) { if (ctx->fds == curr) { ctx->fds = curr->next; } else { prev->next = curr->next; } /* It is responsibility of the caller to cleanup before calling * ASYNC_WAIT_CTX_clear_fd */ OPENSSL_free(curr); ctx->numadd--; return 1; } /* * Mark it as deleted. We don't call cleanup if explicitly asked * to clear an fd. We assume the caller is going to do that (if * appropriate). */ curr->del = 1; ctx->numdel++; return 1; } prev = curr; curr = curr->next; } return 0; } int ASYNC_WAIT_CTX_set_callback(ASYNC_WAIT_CTX *ctx, ASYNC_callback_fn callback, void *callback_arg) { if (ctx == NULL) return 0; ctx->callback = callback; ctx->callback_arg = callback_arg; return 1; } int ASYNC_WAIT_CTX_get_callback(ASYNC_WAIT_CTX *ctx, ASYNC_callback_fn *callback, void **callback_arg) { if (ctx->callback == NULL) return 0; *callback = ctx->callback; *callback_arg = ctx->callback_arg; return 1; } int ASYNC_WAIT_CTX_set_status(ASYNC_WAIT_CTX *ctx, int status) { ctx->status = status; return 1; } int ASYNC_WAIT_CTX_get_status(ASYNC_WAIT_CTX *ctx) { return ctx->status; } void async_wait_ctx_reset_counts(ASYNC_WAIT_CTX *ctx) { struct fd_lookup_st *curr, *prev = NULL; ctx->numadd = 0; ctx->numdel = 0; curr = ctx->fds; while (curr != NULL) { if (curr->del) { if (prev == NULL) ctx->fds = curr->next; else prev->next = curr->next; OPENSSL_free(curr); if (prev == NULL) curr = ctx->fds; else curr = prev->next; continue; } if (curr->add) { curr->add = 0; } prev = curr; curr = curr->next; } }
6,343
24.684211
79
c
openssl
openssl-master/crypto/async/arch/async_null.c
/* * Copyright 2015-2022 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 */ /* This must be the first #include file */ #include "../async_local.h" #ifdef ASYNC_NULL int ASYNC_is_capable(void) { return 0; } int ASYNC_set_mem_functions(ASYNC_stack_alloc_fn alloc_fn, ASYNC_stack_free_fn free_fn) { return 0; } void ASYNC_get_mem_functions(ASYNC_stack_alloc_fn *alloc_fn, ASYNC_stack_free_fn *free_fn) { if (alloc_fn != NULL) *alloc_fn = NULL; if (free_fn != NULL) *free_fn = NULL; } void async_local_cleanup(void) { } #endif
878
21.538462
74
c
openssl
openssl-master/crypto/async/arch/async_null.h
/* * Copyright 2015-2022 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 */ #include <openssl/async.h> /* * If we haven't managed to detect any other async architecture then we default * to NULL. */ #ifndef ASYNC_ARCH # define ASYNC_NULL # define ASYNC_ARCH typedef struct async_fibre_st { int dummy; } async_fibre; # define async_fibre_swapcontext(o,n,r) 0 # define async_fibre_makecontext(c) 0 # define async_fibre_free(f) # define async_fibre_init_dispatcher(f) # define async_local_init() 1 # define async_local_deinit() #endif
845
24.636364
79
h
openssl
openssl-master/crypto/async/arch/async_posix.c
/* * Copyright 2015-2022 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 */ /* This must be the first #include file */ #include "../async_local.h" #ifdef ASYNC_POSIX # include <stddef.h> # include <unistd.h> # include <openssl/err.h> # include <openssl/crypto.h> #define STACKSIZE 32768 static CRYPTO_RWLOCK *async_mem_lock; static void *async_stack_alloc(size_t *num); static void async_stack_free(void *addr); int async_local_init(void) { async_mem_lock = CRYPTO_THREAD_lock_new(); return async_mem_lock != NULL; } void async_local_deinit(void) { CRYPTO_THREAD_lock_free(async_mem_lock); } static int allow_customize = 1; static ASYNC_stack_alloc_fn stack_alloc_impl = async_stack_alloc; static ASYNC_stack_free_fn stack_free_impl = async_stack_free; int ASYNC_is_capable(void) { ucontext_t ctx; /* * Some platforms provide getcontext() but it does not work (notably * MacOSX PPC64). Check for a working getcontext(); */ return getcontext(&ctx) == 0; } int ASYNC_set_mem_functions(ASYNC_stack_alloc_fn alloc_fn, ASYNC_stack_free_fn free_fn) { OPENSSL_init_crypto(OPENSSL_INIT_ASYNC, NULL); if (!CRYPTO_THREAD_write_lock(async_mem_lock)) return 0; if (!allow_customize) { CRYPTO_THREAD_unlock(async_mem_lock); return 0; } CRYPTO_THREAD_unlock(async_mem_lock); if (alloc_fn != NULL) stack_alloc_impl = alloc_fn; if (free_fn != NULL) stack_free_impl = free_fn; return 1; } void ASYNC_get_mem_functions(ASYNC_stack_alloc_fn *alloc_fn, ASYNC_stack_free_fn *free_fn) { if (alloc_fn != NULL) *alloc_fn = stack_alloc_impl; if (free_fn != NULL) *free_fn = stack_free_impl; } static void *async_stack_alloc(size_t *num) { return OPENSSL_malloc(*num); } static void async_stack_free(void *addr) { OPENSSL_free(addr); } void async_local_cleanup(void) { } int async_fibre_makecontext(async_fibre *fibre) { #ifndef USE_SWAPCONTEXT fibre->env_init = 0; #endif if (getcontext(&fibre->fibre) == 0) { size_t num = STACKSIZE; /* * Disallow customisation after the first * stack is allocated. */ if (allow_customize) { if (!CRYPTO_THREAD_write_lock(async_mem_lock)) return 0; allow_customize = 0; CRYPTO_THREAD_unlock(async_mem_lock); } fibre->fibre.uc_stack.ss_sp = stack_alloc_impl(&num); if (fibre->fibre.uc_stack.ss_sp != NULL) { fibre->fibre.uc_stack.ss_size = num; fibre->fibre.uc_link = NULL; makecontext(&fibre->fibre, async_start_func, 0); return 1; } } else { fibre->fibre.uc_stack.ss_sp = NULL; } return 0; } void async_fibre_free(async_fibre *fibre) { stack_free_impl(fibre->fibre.uc_stack.ss_sp); fibre->fibre.uc_stack.ss_sp = NULL; } #endif
3,247
23.059259
74
c
openssl
openssl-master/crypto/async/arch/async_posix.h
/* * Copyright 2015-2022 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 */ #ifndef OSSL_CRYPTO_ASYNC_POSIX_H #define OSSL_CRYPTO_ASYNC_POSIX_H #include <openssl/e_os2.h> #if defined(OPENSSL_SYS_UNIX) \ && defined(OPENSSL_THREADS) && !defined(OPENSSL_NO_ASYNC) \ && !defined(__ANDROID__) && !defined(__OpenBSD__) # include <unistd.h> # if _POSIX_VERSION >= 200112L \ && (_POSIX_VERSION < 200809L || defined(__GLIBC__)) # include <pthread.h> # define ASYNC_POSIX # define ASYNC_ARCH # if defined(__CET__) || defined(__ia64__) /* * When Intel CET is enabled, makecontext will create a different * shadow stack for each context. async_fibre_swapcontext cannot * use _longjmp. It must call swapcontext to swap shadow stack as * well as normal stack. * On IA64 the register stack engine is not saved across setjmp/longjmp. Here * swapcontext() performs correctly. */ # define USE_SWAPCONTEXT # endif # if defined(__aarch64__) && defined(__clang__) \ && defined(__ARM_FEATURE_BTI_DEFAULT) && __ARM_FEATURE_BTI_DEFAULT == 1 /* * setjmp/longjmp don't currently work with BTI on all libc implementations * when compiled by clang. This is because clang doesn't put a BTI after the * call to setjmp where it returns the second time. This then fails on libc * implementations - notably glibc - which use an indirect jump to there. * So use the swapcontext implementation, which does work. * See https://github.com/llvm/llvm-project/issues/48888. */ # define USE_SWAPCONTEXT # endif # include <ucontext.h> # ifndef USE_SWAPCONTEXT # include <setjmp.h> # endif typedef struct async_fibre_st { ucontext_t fibre; # ifndef USE_SWAPCONTEXT jmp_buf env; int env_init; # endif } async_fibre; int async_local_init(void); void async_local_deinit(void); static ossl_inline int async_fibre_swapcontext(async_fibre *o, async_fibre *n, int r) { # ifdef USE_SWAPCONTEXT swapcontext(&o->fibre, &n->fibre); # else o->env_init = 1; if (!r || !_setjmp(o->env)) { if (n->env_init) _longjmp(n->env, 1); else setcontext(&n->fibre); } # endif return 1; } # define async_fibre_init_dispatcher(d) int async_fibre_makecontext(async_fibre *fibre); void async_fibre_free(async_fibre *fibre); # endif #endif #endif /* OSSL_CRYPTO_ASYNC_POSIX_H */
2,607
27.043011
85
h
openssl
openssl-master/crypto/async/arch/async_win.c
/* * Copyright 2015-2022 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 */ /* This must be the first #include file */ #include "../async_local.h" #ifdef ASYNC_WIN # include <windows.h> # include "internal/cryptlib.h" int ASYNC_is_capable(void) { return 1; } int ASYNC_set_mem_functions(ASYNC_stack_alloc_fn alloc_fn, ASYNC_stack_free_fn free_fn) { return 0; } void ASYNC_get_mem_functions(ASYNC_stack_alloc_fn *alloc_fn, ASYNC_stack_free_fn *free_fn) { if (alloc_fn != NULL) *alloc_fn = NULL; if (free_fn != NULL) *free_fn = NULL; } void async_local_cleanup(void) { async_ctx *ctx = async_get_ctx(); if (ctx != NULL) { async_fibre *fibre = &ctx->dispatcher; if (fibre != NULL && fibre->fibre != NULL && fibre->converted) { ConvertFiberToThread(); fibre->fibre = NULL; } } } int async_fibre_init_dispatcher(async_fibre *fibre) { # if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x600 fibre->fibre = ConvertThreadToFiberEx(NULL, FIBER_FLAG_FLOAT_SWITCH); # else fibre->fibre = ConvertThreadToFiber(NULL); # endif if (fibre->fibre == NULL) { fibre->converted = 0; fibre->fibre = GetCurrentFiber(); if (fibre->fibre == NULL) return 0; } else { fibre->converted = 1; } return 1; } VOID CALLBACK async_start_func_win(PVOID unused) { async_start_func(); } #endif
1,746
22.293333
74
c
openssl
openssl-master/crypto/async/arch/async_win.h
/* * Copyright 2015-2022 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 */ /* * This is the same detection used in cryptlib to set up the thread local * storage that we depend on, so just copy that */ #if defined(_WIN32) && !defined(OPENSSL_NO_ASYNC) #include <openssl/async.h> # define ASYNC_WIN # define ASYNC_ARCH # include <windows.h> # include "internal/cryptlib.h" typedef struct async_fibre_st { LPVOID fibre; int converted; } async_fibre; # define async_fibre_swapcontext(o,n,r) \ (SwitchToFiber((n)->fibre), 1) # if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x600 # define async_fibre_makecontext(c) \ ((c)->fibre = CreateFiberEx(0, 0, FIBER_FLAG_FLOAT_SWITCH, \ async_start_func_win, 0)) # else # define async_fibre_makecontext(c) \ ((c)->fibre = CreateFiber(0, async_start_func_win, 0)) # endif # define async_fibre_free(f) (DeleteFiber((f)->fibre)) # define async_local_init() 1 # define async_local_deinit() int async_fibre_init_dispatcher(async_fibre *fibre); VOID CALLBACK async_start_func_win(PVOID unused); #endif
1,399
28.787234
74
h
openssl
openssl-master/crypto/bf/bf_cfb64.c
/* * Copyright 1995-2020 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 */ /* * BF low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/blowfish.h> #include "bf_local.h" /* * The input and output encrypted as though 64bit cfb mode is being used. * The extra state information to record how much of the 64bit block we have * used is contained in *num; */ void BF_cfb64_encrypt(const unsigned char *in, unsigned char *out, long length, const BF_KEY *schedule, unsigned char *ivec, int *num, int encrypt) { register BF_LONG v0, v1, t; register int n = *num; register long l = length; BF_LONG ti[2]; unsigned char *iv, c, cc; iv = (unsigned char *)ivec; if (encrypt) { while (l--) { if (n == 0) { n2l(iv, v0); ti[0] = v0; n2l(iv, v1); ti[1] = v1; BF_encrypt((BF_LONG *)ti, schedule); iv = (unsigned char *)ivec; t = ti[0]; l2n(t, iv); t = ti[1]; l2n(t, iv); iv = (unsigned char *)ivec; } c = *(in++) ^ iv[n]; *(out++) = c; iv[n] = c; n = (n + 1) & 0x07; } } else { while (l--) { if (n == 0) { n2l(iv, v0); ti[0] = v0; n2l(iv, v1); ti[1] = v1; BF_encrypt((BF_LONG *)ti, schedule); iv = (unsigned char *)ivec; t = ti[0]; l2n(t, iv); t = ti[1]; l2n(t, iv); iv = (unsigned char *)ivec; } cc = *(in++); c = iv[n]; iv[n] = cc; *(out++) = c ^ cc; n = (n + 1) & 0x07; } } v0 = v1 = ti[0] = ti[1] = t = c = cc = 0; *num = n; }
2,295
27.345679
77
c
openssl
openssl-master/crypto/bf/bf_ecb.c
/* * Copyright 1995-2020 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 */ /* * BF low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/blowfish.h> #include "bf_local.h" #include <openssl/opensslv.h> /* * Blowfish as implemented from 'Blowfish: Springer-Verlag paper' (From * LECTURE NOTES IN COMPUTER SCIENCE 809, FAST SOFTWARE ENCRYPTION, CAMBRIDGE * SECURITY WORKSHOP, CAMBRIDGE, U.K., DECEMBER 9-11, 1993) */ const char *BF_options(void) { return "blowfish(ptr)"; } void BF_ecb_encrypt(const unsigned char *in, unsigned char *out, const BF_KEY *key, int encrypt) { BF_LONG l, d[2]; n2l(in, l); d[0] = l; n2l(in, l); d[1] = l; if (encrypt) BF_encrypt(d, key); else BF_decrypt(d, key); l = d[0]; l2n(l, out); l = d[1]; l2n(l, out); l = d[0] = d[1] = 0; }
1,199
23
77
c
openssl
openssl-master/crypto/bf/bf_enc.c
/* * Copyright 1995-2020 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 */ /* * BF low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/blowfish.h> #include "bf_local.h" /* * Blowfish as implemented from 'Blowfish: Springer-Verlag paper' (From * LECTURE NOTES IN COMPUTER SCIENCE 809, FAST SOFTWARE ENCRYPTION, CAMBRIDGE * SECURITY WORKSHOP, CAMBRIDGE, U.K., DECEMBER 9-11, 1993) */ #if (BF_ROUNDS != 16) && (BF_ROUNDS != 20) # error If you set BF_ROUNDS to some value other than 16 or 20, you will have \ to modify the code. #endif void BF_encrypt(BF_LONG *data, const BF_KEY *key) { register BF_LONG l, r; register const BF_LONG *p, *s; p = key->P; s = &(key->S[0]); l = data[0]; r = data[1]; l ^= p[0]; BF_ENC(r, l, s, p[1]); BF_ENC(l, r, s, p[2]); BF_ENC(r, l, s, p[3]); BF_ENC(l, r, s, p[4]); BF_ENC(r, l, s, p[5]); BF_ENC(l, r, s, p[6]); BF_ENC(r, l, s, p[7]); BF_ENC(l, r, s, p[8]); BF_ENC(r, l, s, p[9]); BF_ENC(l, r, s, p[10]); BF_ENC(r, l, s, p[11]); BF_ENC(l, r, s, p[12]); BF_ENC(r, l, s, p[13]); BF_ENC(l, r, s, p[14]); BF_ENC(r, l, s, p[15]); BF_ENC(l, r, s, p[16]); # if BF_ROUNDS == 20 BF_ENC(r, l, s, p[17]); BF_ENC(l, r, s, p[18]); BF_ENC(r, l, s, p[19]); BF_ENC(l, r, s, p[20]); # endif r ^= p[BF_ROUNDS + 1]; data[1] = l & 0xffffffffU; data[0] = r & 0xffffffffU; } void BF_decrypt(BF_LONG *data, const BF_KEY *key) { register BF_LONG l, r; register const BF_LONG *p, *s; p = key->P; s = &(key->S[0]); l = data[0]; r = data[1]; l ^= p[BF_ROUNDS + 1]; # if BF_ROUNDS == 20 BF_ENC(r, l, s, p[20]); BF_ENC(l, r, s, p[19]); BF_ENC(r, l, s, p[18]); BF_ENC(l, r, s, p[17]); # endif BF_ENC(r, l, s, p[16]); BF_ENC(l, r, s, p[15]); BF_ENC(r, l, s, p[14]); BF_ENC(l, r, s, p[13]); BF_ENC(r, l, s, p[12]); BF_ENC(l, r, s, p[11]); BF_ENC(r, l, s, p[10]); BF_ENC(l, r, s, p[9]); BF_ENC(r, l, s, p[8]); BF_ENC(l, r, s, p[7]); BF_ENC(r, l, s, p[6]); BF_ENC(l, r, s, p[5]); BF_ENC(r, l, s, p[4]); BF_ENC(l, r, s, p[3]); BF_ENC(r, l, s, p[2]); BF_ENC(l, r, s, p[1]); r ^= p[0]; data[1] = l & 0xffffffffU; data[0] = r & 0xffffffffU; } void BF_cbc_encrypt(const unsigned char *in, unsigned char *out, long length, const BF_KEY *schedule, unsigned char *ivec, int encrypt) { register BF_LONG tin0, tin1; register BF_LONG tout0, tout1, xor0, xor1; register long l = length; BF_LONG tin[2]; if (encrypt) { n2l(ivec, tout0); n2l(ivec, tout1); ivec -= 8; for (l -= 8; l >= 0; l -= 8) { n2l(in, tin0); n2l(in, tin1); tin0 ^= tout0; tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; BF_encrypt(tin, schedule); tout0 = tin[0]; tout1 = tin[1]; l2n(tout0, out); l2n(tout1, out); } if (l != -8) { n2ln(in, tin0, tin1, l + 8); tin0 ^= tout0; tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; BF_encrypt(tin, schedule); tout0 = tin[0]; tout1 = tin[1]; l2n(tout0, out); l2n(tout1, out); } l2n(tout0, ivec); l2n(tout1, ivec); } else { n2l(ivec, xor0); n2l(ivec, xor1); ivec -= 8; for (l -= 8; l >= 0; l -= 8) { n2l(in, tin0); n2l(in, tin1); tin[0] = tin0; tin[1] = tin1; BF_decrypt(tin, schedule); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2n(tout0, out); l2n(tout1, out); xor0 = tin0; xor1 = tin1; } if (l != -8) { n2l(in, tin0); n2l(in, tin1); tin[0] = tin0; tin[1] = tin1; BF_decrypt(tin, schedule); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2nn(tout0, tout1, out, l + 8); xor0 = tin0; xor1 = tin1; } l2n(xor0, ivec); l2n(xor1, ivec); } tin0 = tin1 = tout0 = tout1 = xor0 = xor1 = 0; tin[0] = tin[1] = 0; }
4,704
24.851648
79
c
openssl
openssl-master/crypto/bf/bf_local.h
/* * Copyright 1995-2016 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 */ #ifndef OSSL_CRYPTO_BF_LOCAL_H # define OSSL_CRYPTO_BF_LOCAL_H # include <openssl/opensslconf.h> /* NOTE - c is not incremented as per n2l */ # define n2ln(c,l1,l2,n) { \ c+=n; \ l1=l2=0; \ switch (n) { \ case 8: l2 =((unsigned long)(*(--(c)))) ; \ /* fall through */ \ case 7: l2|=((unsigned long)(*(--(c))))<< 8; \ /* fall through */ \ case 6: l2|=((unsigned long)(*(--(c))))<<16; \ /* fall through */ \ case 5: l2|=((unsigned long)(*(--(c))))<<24; \ /* fall through */ \ case 4: l1 =((unsigned long)(*(--(c)))) ; \ /* fall through */ \ case 3: l1|=((unsigned long)(*(--(c))))<< 8; \ /* fall through */ \ case 2: l1|=((unsigned long)(*(--(c))))<<16; \ /* fall through */ \ case 1: l1|=((unsigned long)(*(--(c))))<<24; \ } \ } /* NOTE - c is not incremented as per l2n */ # define l2nn(l1,l2,c,n) { \ c+=n; \ switch (n) { \ case 8: *(--(c))=(unsigned char)(((l2) )&0xff); \ /* fall through */ \ case 7: *(--(c))=(unsigned char)(((l2)>> 8)&0xff); \ /* fall through */ \ case 6: *(--(c))=(unsigned char)(((l2)>>16)&0xff); \ /* fall through */ \ case 5: *(--(c))=(unsigned char)(((l2)>>24)&0xff); \ /* fall through */ \ case 4: *(--(c))=(unsigned char)(((l1) )&0xff); \ /* fall through */ \ case 3: *(--(c))=(unsigned char)(((l1)>> 8)&0xff); \ /* fall through */ \ case 2: *(--(c))=(unsigned char)(((l1)>>16)&0xff); \ /* fall through */ \ case 1: *(--(c))=(unsigned char)(((l1)>>24)&0xff); \ } \ } # undef n2l # define n2l(c,l) (l =((unsigned long)(*((c)++)))<<24L, \ l|=((unsigned long)(*((c)++)))<<16L, \ l|=((unsigned long)(*((c)++)))<< 8L, \ l|=((unsigned long)(*((c)++)))) # undef l2n # define l2n(l,c) (*((c)++)=(unsigned char)(((l)>>24L)&0xff), \ *((c)++)=(unsigned char)(((l)>>16L)&0xff), \ *((c)++)=(unsigned char)(((l)>> 8L)&0xff), \ *((c)++)=(unsigned char)(((l) )&0xff)) /* * This is actually a big endian algorithm, the most significant byte is used * to lookup array 0 */ # define BF_ENC(LL,R,S,P) ( \ LL^=P, \ LL^=((( S[ ((R>>24)&0xff)] + \ S[0x0100+((R>>16)&0xff)])^ \ S[0x0200+((R>> 8)&0xff)])+ \ S[0x0300+((R )&0xff)])&0xffffffffU \ ) #endif
4,066
46.847059
79
h
openssl
openssl-master/crypto/bf/bf_ofb64.c
/* * Copyright 1995-2020 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 */ /* * BF low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/blowfish.h> #include "bf_local.h" /* * The input and output encrypted as though 64bit ofb mode is being used. * The extra state information to record how much of the 64bit block we have * used is contained in *num; */ void BF_ofb64_encrypt(const unsigned char *in, unsigned char *out, long length, const BF_KEY *schedule, unsigned char *ivec, int *num) { register BF_LONG v0, v1, t; register int n = *num; register long l = length; unsigned char d[8]; register char *dp; BF_LONG ti[2]; unsigned char *iv; int save = 0; iv = (unsigned char *)ivec; n2l(iv, v0); n2l(iv, v1); ti[0] = v0; ti[1] = v1; dp = (char *)d; l2n(v0, dp); l2n(v1, dp); while (l--) { if (n == 0) { BF_encrypt((BF_LONG *)ti, schedule); dp = (char *)d; t = ti[0]; l2n(t, dp); t = ti[1]; l2n(t, dp); save++; } *(out++) = *(in++) ^ d[n]; n = (n + 1) & 0x07; } if (save) { v0 = ti[0]; v1 = ti[1]; iv = (unsigned char *)ivec; l2n(v0, iv); l2n(v1, iv); } t = v0 = v1 = ti[0] = ti[1] = 0; *num = n; }
1,738
24.573529
77
c
openssl
openssl-master/crypto/bf/bf_skey.c
/* * Copyright 1995-2020 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 */ /* * BF low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <stdio.h> #include <string.h> #include <openssl/blowfish.h> #include "bf_local.h" #include "bf_pi.h" void BF_set_key(BF_KEY *key, int len, const unsigned char *data) { int i; BF_LONG *p, ri, in[2]; const unsigned char *d, *end; memcpy(key, &bf_init, sizeof(BF_KEY)); p = key->P; if (len > ((BF_ROUNDS + 2) * 4)) len = (BF_ROUNDS + 2) * 4; d = data; end = &(data[len]); for (i = 0; i < (BF_ROUNDS + 2); i++) { ri = *(d++); if (d >= end) d = data; ri <<= 8; ri |= *(d++); if (d >= end) d = data; ri <<= 8; ri |= *(d++); if (d >= end) d = data; ri <<= 8; ri |= *(d++); if (d >= end) d = data; p[i] ^= ri; } in[0] = 0L; in[1] = 0L; for (i = 0; i < (BF_ROUNDS + 2); i += 2) { BF_encrypt(in, key); p[i] = in[0]; p[i + 1] = in[1]; } p = key->S; for (i = 0; i < 4 * 256; i += 2) { BF_encrypt(in, key); p[i] = in[0]; p[i + 1] = in[1]; } }
1,581
20.378378
77
c
openssl
openssl-master/crypto/bio/bf_buff.c
/* * Copyright 1995-2021 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 */ #include <stdio.h> #include <errno.h> #include "bio_local.h" #include "internal/cryptlib.h" static int buffer_write(BIO *h, const char *buf, int num); static int buffer_read(BIO *h, char *buf, int size); static int buffer_puts(BIO *h, const char *str); static int buffer_gets(BIO *h, char *str, int size); static long buffer_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int buffer_new(BIO *h); static int buffer_free(BIO *data); static long buffer_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); #define DEFAULT_BUFFER_SIZE 4096 static const BIO_METHOD methods_buffer = { BIO_TYPE_BUFFER, "buffer", bwrite_conv, buffer_write, bread_conv, buffer_read, buffer_puts, buffer_gets, buffer_ctrl, buffer_new, buffer_free, buffer_callback_ctrl, }; const BIO_METHOD *BIO_f_buffer(void) { return &methods_buffer; } static int buffer_new(BIO *bi) { BIO_F_BUFFER_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx == NULL) return 0; ctx->ibuf_size = DEFAULT_BUFFER_SIZE; ctx->ibuf = OPENSSL_malloc(DEFAULT_BUFFER_SIZE); if (ctx->ibuf == NULL) { OPENSSL_free(ctx); return 0; } ctx->obuf_size = DEFAULT_BUFFER_SIZE; ctx->obuf = OPENSSL_malloc(DEFAULT_BUFFER_SIZE); if (ctx->obuf == NULL) { OPENSSL_free(ctx->ibuf); OPENSSL_free(ctx); return 0; } bi->init = 1; bi->ptr = (char *)ctx; bi->flags = 0; return 1; } static int buffer_free(BIO *a) { BIO_F_BUFFER_CTX *b; if (a == NULL) return 0; b = (BIO_F_BUFFER_CTX *)a->ptr; OPENSSL_free(b->ibuf); OPENSSL_free(b->obuf); OPENSSL_free(a->ptr); a->ptr = NULL; a->init = 0; a->flags = 0; return 1; } static int buffer_read(BIO *b, char *out, int outl) { int i, num = 0; BIO_F_BUFFER_CTX *ctx; if (out == NULL) return 0; ctx = (BIO_F_BUFFER_CTX *)b->ptr; if ((ctx == NULL) || (b->next_bio == NULL)) return 0; num = 0; BIO_clear_retry_flags(b); start: i = ctx->ibuf_len; /* If there is stuff left over, grab it */ if (i != 0) { if (i > outl) i = outl; memcpy(out, &(ctx->ibuf[ctx->ibuf_off]), i); ctx->ibuf_off += i; ctx->ibuf_len -= i; num += i; if (outl == i) return num; outl -= i; out += i; } /* * We may have done a partial read. try to do more. We have nothing in * the buffer. If we get an error and have read some data, just return it * and let them retry to get the error again. copy direct to parent * address space */ if (outl > ctx->ibuf_size) { for (;;) { i = BIO_read(b->next_bio, out, outl); if (i <= 0) { BIO_copy_next_retry(b); if (i < 0) return ((num > 0) ? num : i); if (i == 0) return num; } num += i; if (outl == i) return num; out += i; outl -= i; } } /* else */ /* we are going to be doing some buffering */ i = BIO_read(b->next_bio, ctx->ibuf, ctx->ibuf_size); if (i <= 0) { BIO_copy_next_retry(b); if (i < 0) return ((num > 0) ? num : i); if (i == 0) return num; } ctx->ibuf_off = 0; ctx->ibuf_len = i; /* Lets re-read using ourselves :-) */ goto start; } static int buffer_write(BIO *b, const char *in, int inl) { int i, num = 0; BIO_F_BUFFER_CTX *ctx; if ((in == NULL) || (inl <= 0)) return 0; ctx = (BIO_F_BUFFER_CTX *)b->ptr; if ((ctx == NULL) || (b->next_bio == NULL)) return 0; BIO_clear_retry_flags(b); start: i = ctx->obuf_size - (ctx->obuf_len + ctx->obuf_off); /* add to buffer and return */ if (i >= inl) { memcpy(&(ctx->obuf[ctx->obuf_off + ctx->obuf_len]), in, inl); ctx->obuf_len += inl; return (num + inl); } /* else */ /* stuff already in buffer, so add to it first, then flush */ if (ctx->obuf_len != 0) { if (i > 0) { /* lets fill it up if we can */ memcpy(&(ctx->obuf[ctx->obuf_off + ctx->obuf_len]), in, i); in += i; inl -= i; num += i; ctx->obuf_len += i; } /* we now have a full buffer needing flushing */ for (;;) { i = BIO_write(b->next_bio, &(ctx->obuf[ctx->obuf_off]), ctx->obuf_len); if (i <= 0) { BIO_copy_next_retry(b); if (i < 0) return ((num > 0) ? num : i); if (i == 0) return num; } ctx->obuf_off += i; ctx->obuf_len -= i; if (ctx->obuf_len == 0) break; } } /* * we only get here if the buffer has been flushed and we still have * stuff to write */ ctx->obuf_off = 0; /* we now have inl bytes to write */ while (inl >= ctx->obuf_size) { i = BIO_write(b->next_bio, in, inl); if (i <= 0) { BIO_copy_next_retry(b); if (i < 0) return ((num > 0) ? num : i); if (i == 0) return num; } num += i; in += i; inl -= i; if (inl == 0) return num; } /* * copy the rest into the buffer since we have only a small amount left */ goto start; } static long buffer_ctrl(BIO *b, int cmd, long num, void *ptr) { BIO *dbio; BIO_F_BUFFER_CTX *ctx; long ret = 1; char *p1, *p2; int r, i, *ip; int ibs, obs; ctx = (BIO_F_BUFFER_CTX *)b->ptr; switch (cmd) { case BIO_CTRL_RESET: ctx->ibuf_off = 0; ctx->ibuf_len = 0; ctx->obuf_off = 0; ctx->obuf_len = 0; if (b->next_bio == NULL) return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; case BIO_CTRL_EOF: if (ctx->ibuf_len > 0) return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; case BIO_CTRL_INFO: ret = (long)ctx->obuf_len; break; case BIO_C_GET_BUFF_NUM_LINES: ret = 0; p1 = ctx->ibuf; for (i = 0; i < ctx->ibuf_len; i++) { if (p1[ctx->ibuf_off + i] == '\n') ret++; } break; case BIO_CTRL_WPENDING: ret = (long)ctx->obuf_len; if (ret == 0) { if (b->next_bio == NULL) return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); } break; case BIO_CTRL_PENDING: ret = (long)ctx->ibuf_len; if (ret == 0) { if (b->next_bio == NULL) return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); } break; case BIO_C_SET_BUFF_READ_DATA: if (num > ctx->ibuf_size) { if (num <= 0) return 0; p1 = OPENSSL_malloc((size_t)num); if (p1 == NULL) return 0; OPENSSL_free(ctx->ibuf); ctx->ibuf = p1; } ctx->ibuf_off = 0; ctx->ibuf_len = (int)num; memcpy(ctx->ibuf, ptr, (int)num); ret = 1; break; case BIO_C_SET_BUFF_SIZE: if (ptr != NULL) { ip = (int *)ptr; if (*ip == 0) { ibs = (int)num; obs = ctx->obuf_size; } else { /* if (*ip == 1) */ ibs = ctx->ibuf_size; obs = (int)num; } } else { ibs = (int)num; obs = (int)num; } p1 = ctx->ibuf; p2 = ctx->obuf; if ((ibs > DEFAULT_BUFFER_SIZE) && (ibs != ctx->ibuf_size)) { if (num <= 0) return 0; p1 = OPENSSL_malloc((size_t)num); if (p1 == NULL) return 0; } if ((obs > DEFAULT_BUFFER_SIZE) && (obs != ctx->obuf_size)) { p2 = OPENSSL_malloc((size_t)num); if (p2 == NULL) { if (p1 != ctx->ibuf) OPENSSL_free(p1); return 0; } } if (ctx->ibuf != p1) { OPENSSL_free(ctx->ibuf); ctx->ibuf = p1; ctx->ibuf_off = 0; ctx->ibuf_len = 0; ctx->ibuf_size = ibs; } if (ctx->obuf != p2) { OPENSSL_free(ctx->obuf); ctx->obuf = p2; ctx->obuf_off = 0; ctx->obuf_len = 0; ctx->obuf_size = obs; } break; case BIO_C_DO_STATE_MACHINE: if (b->next_bio == NULL) return 0; BIO_clear_retry_flags(b); ret = BIO_ctrl(b->next_bio, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_CTRL_FLUSH: if (b->next_bio == NULL) return 0; if (ctx->obuf_len <= 0) { ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; } for (;;) { BIO_clear_retry_flags(b); if (ctx->obuf_len > 0) { r = BIO_write(b->next_bio, &(ctx->obuf[ctx->obuf_off]), ctx->obuf_len); BIO_copy_next_retry(b); if (r <= 0) return (long)r; ctx->obuf_off += r; ctx->obuf_len -= r; } else { ctx->obuf_len = 0; ctx->obuf_off = 0; break; } } ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; case BIO_CTRL_DUP: dbio = (BIO *)ptr; if (BIO_set_read_buffer_size(dbio, ctx->ibuf_size) <= 0 || BIO_set_write_buffer_size(dbio, ctx->obuf_size) <= 0) ret = 0; break; case BIO_CTRL_PEEK: /* Ensure there's stuff in the input buffer */ { char fake_buf[1]; (void)buffer_read(b, fake_buf, 0); } if (num > ctx->ibuf_len) num = ctx->ibuf_len; memcpy(ptr, &(ctx->ibuf[ctx->ibuf_off]), num); ret = num; break; default: if (b->next_bio == NULL) return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; } return ret; } static long buffer_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { if (b->next_bio == NULL) return 0; return BIO_callback_ctrl(b->next_bio, cmd, fp); } static int buffer_gets(BIO *b, char *buf, int size) { BIO_F_BUFFER_CTX *ctx; int num = 0, i, flag; char *p; ctx = (BIO_F_BUFFER_CTX *)b->ptr; size--; /* reserve space for a '\0' */ BIO_clear_retry_flags(b); for (;;) { if (ctx->ibuf_len > 0) { p = &(ctx->ibuf[ctx->ibuf_off]); flag = 0; for (i = 0; (i < ctx->ibuf_len) && (i < size); i++) { *(buf++) = p[i]; if (p[i] == '\n') { flag = 1; i++; break; } } num += i; size -= i; ctx->ibuf_len -= i; ctx->ibuf_off += i; if (flag || size == 0) { *buf = '\0'; return num; } } else { /* read another chunk */ i = BIO_read(b->next_bio, ctx->ibuf, ctx->ibuf_size); if (i <= 0) { BIO_copy_next_retry(b); *buf = '\0'; if (i < 0) return ((num > 0) ? num : i); if (i == 0) return num; } ctx->ibuf_len = i; ctx->ibuf_off = 0; } } } static int buffer_puts(BIO *b, const char *str) { return buffer_write(b, str, strlen(str)); }
12,434
25.570513
77
c
openssl
openssl-master/crypto/bio/bf_lbuf.c
/* * Copyright 1995-2021 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 */ #include <stdio.h> #include <errno.h> #include "bio_local.h" #include "internal/cryptlib.h" #include <openssl/evp.h> static int linebuffer_write(BIO *h, const char *buf, int num); static int linebuffer_read(BIO *h, char *buf, int size); static int linebuffer_puts(BIO *h, const char *str); static int linebuffer_gets(BIO *h, char *str, int size); static long linebuffer_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int linebuffer_new(BIO *h); static int linebuffer_free(BIO *data); static long linebuffer_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); /* A 10k maximum should be enough for most purposes */ #define DEFAULT_LINEBUFFER_SIZE 1024*10 /* #define DEBUG */ static const BIO_METHOD methods_linebuffer = { BIO_TYPE_LINEBUFFER, "linebuffer", bwrite_conv, linebuffer_write, bread_conv, linebuffer_read, linebuffer_puts, linebuffer_gets, linebuffer_ctrl, linebuffer_new, linebuffer_free, linebuffer_callback_ctrl, }; const BIO_METHOD *BIO_f_linebuffer(void) { return &methods_linebuffer; } typedef struct bio_linebuffer_ctx_struct { char *obuf; /* the output char array */ int obuf_size; /* how big is the output buffer */ int obuf_len; /* how many bytes are in it */ } BIO_LINEBUFFER_CTX; static int linebuffer_new(BIO *bi) { BIO_LINEBUFFER_CTX *ctx; if ((ctx = OPENSSL_malloc(sizeof(*ctx))) == NULL) return 0; ctx->obuf = OPENSSL_malloc(DEFAULT_LINEBUFFER_SIZE); if (ctx->obuf == NULL) { OPENSSL_free(ctx); return 0; } ctx->obuf_size = DEFAULT_LINEBUFFER_SIZE; ctx->obuf_len = 0; bi->init = 1; bi->ptr = (char *)ctx; bi->flags = 0; return 1; } static int linebuffer_free(BIO *a) { BIO_LINEBUFFER_CTX *b; if (a == NULL) return 0; b = (BIO_LINEBUFFER_CTX *)a->ptr; OPENSSL_free(b->obuf); OPENSSL_free(a->ptr); a->ptr = NULL; a->init = 0; a->flags = 0; return 1; } static int linebuffer_read(BIO *b, char *out, int outl) { int ret = 0; if (out == NULL) return 0; if (b->next_bio == NULL) return 0; ret = BIO_read(b->next_bio, out, outl); BIO_clear_retry_flags(b); BIO_copy_next_retry(b); return ret; } static int linebuffer_write(BIO *b, const char *in, int inl) { int i, num = 0, foundnl; BIO_LINEBUFFER_CTX *ctx; if ((in == NULL) || (inl <= 0)) return 0; ctx = (BIO_LINEBUFFER_CTX *)b->ptr; if ((ctx == NULL) || (b->next_bio == NULL)) return 0; BIO_clear_retry_flags(b); do { const char *p; char c; for (p = in, c = '\0'; p < in + inl && (c = *p) != '\n'; p++) ; if (c == '\n') { p++; foundnl = 1; } else foundnl = 0; /* * If a NL was found and we already have text in the save buffer, * concatenate them and write */ while ((foundnl || p - in > ctx->obuf_size - ctx->obuf_len) && ctx->obuf_len > 0) { int orig_olen = ctx->obuf_len; i = ctx->obuf_size - ctx->obuf_len; if (p - in > 0) { if (i >= p - in) { memcpy(&(ctx->obuf[ctx->obuf_len]), in, p - in); ctx->obuf_len += p - in; inl -= p - in; num += p - in; in = p; } else { memcpy(&(ctx->obuf[ctx->obuf_len]), in, i); ctx->obuf_len += i; inl -= i; in += i; num += i; } } i = BIO_write(b->next_bio, ctx->obuf, ctx->obuf_len); if (i <= 0) { ctx->obuf_len = orig_olen; BIO_copy_next_retry(b); if (i < 0) return ((num > 0) ? num : i); if (i == 0) return num; } if (i < ctx->obuf_len) memmove(ctx->obuf, ctx->obuf + i, ctx->obuf_len - i); ctx->obuf_len -= i; } /* * Now that the save buffer is emptied, let's write the input buffer * if a NL was found and there is anything to write. */ if ((foundnl || p - in > ctx->obuf_size) && p - in > 0) { i = BIO_write(b->next_bio, in, p - in); if (i <= 0) { BIO_copy_next_retry(b); if (i < 0) return ((num > 0) ? num : i); if (i == 0) return num; } num += i; in += i; inl -= i; } } while (foundnl && inl > 0); /* * We've written as much as we can. The rest of the input buffer, if * any, is text that doesn't and with a NL and therefore needs to be * saved for the next trip. */ if (inl > 0) { memcpy(&(ctx->obuf[ctx->obuf_len]), in, inl); ctx->obuf_len += inl; num += inl; } return num; } static long linebuffer_ctrl(BIO *b, int cmd, long num, void *ptr) { BIO *dbio; BIO_LINEBUFFER_CTX *ctx; long ret = 1; char *p; int r; int obs; ctx = (BIO_LINEBUFFER_CTX *)b->ptr; switch (cmd) { case BIO_CTRL_RESET: ctx->obuf_len = 0; if (b->next_bio == NULL) return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; case BIO_CTRL_INFO: ret = (long)ctx->obuf_len; break; case BIO_CTRL_WPENDING: ret = (long)ctx->obuf_len; if (ret == 0) { if (b->next_bio == NULL) return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); } break; case BIO_C_SET_BUFF_SIZE: if (num > INT_MAX) return 0; obs = (int)num; p = ctx->obuf; if ((obs > DEFAULT_LINEBUFFER_SIZE) && (obs != ctx->obuf_size)) { p = OPENSSL_malloc((size_t)obs); if (p == NULL) return 0; } if (ctx->obuf != p) { if (ctx->obuf_len > obs) { ctx->obuf_len = obs; } memcpy(p, ctx->obuf, ctx->obuf_len); OPENSSL_free(ctx->obuf); ctx->obuf = p; ctx->obuf_size = obs; } break; case BIO_C_DO_STATE_MACHINE: if (b->next_bio == NULL) return 0; BIO_clear_retry_flags(b); ret = BIO_ctrl(b->next_bio, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_CTRL_FLUSH: if (b->next_bio == NULL) return 0; if (ctx->obuf_len <= 0) { ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; } for (;;) { BIO_clear_retry_flags(b); if (ctx->obuf_len > 0) { r = BIO_write(b->next_bio, ctx->obuf, ctx->obuf_len); BIO_copy_next_retry(b); if (r <= 0) return (long)r; if (r < ctx->obuf_len) memmove(ctx->obuf, ctx->obuf + r, ctx->obuf_len - r); ctx->obuf_len -= r; } else { ctx->obuf_len = 0; break; } } ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; case BIO_CTRL_DUP: dbio = (BIO *)ptr; if (BIO_set_write_buffer_size(dbio, ctx->obuf_size) <= 0) ret = 0; break; default: if (b->next_bio == NULL) return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; } return ret; } static long linebuffer_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { if (b->next_bio == NULL) return 0; return BIO_callback_ctrl(b->next_bio, cmd, fp); } static int linebuffer_gets(BIO *b, char *buf, int size) { if (b->next_bio == NULL) return 0; return BIO_gets(b->next_bio, buf, size); } static int linebuffer_puts(BIO *b, const char *str) { return linebuffer_write(b, str, strlen(str)); }
8,522
26.143312
76
c
openssl
openssl-master/crypto/bio/bf_nbio.c
/* * Copyright 1995-2021 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 */ #include <stdio.h> #include <errno.h> #include "bio_local.h" #include "internal/cryptlib.h" #include <openssl/rand.h> /* * BIO_put and BIO_get both add to the digest, BIO_gets returns the digest */ static int nbiof_write(BIO *h, const char *buf, int num); static int nbiof_read(BIO *h, char *buf, int size); static int nbiof_puts(BIO *h, const char *str); static int nbiof_gets(BIO *h, char *str, int size); static long nbiof_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int nbiof_new(BIO *h); static int nbiof_free(BIO *data); static long nbiof_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); typedef struct nbio_test_st { /* only set if we sent a 'should retry' error */ int lrn; int lwn; } NBIO_TEST; static const BIO_METHOD methods_nbiof = { BIO_TYPE_NBIO_TEST, "non-blocking IO test filter", bwrite_conv, nbiof_write, bread_conv, nbiof_read, nbiof_puts, nbiof_gets, nbiof_ctrl, nbiof_new, nbiof_free, nbiof_callback_ctrl, }; const BIO_METHOD *BIO_f_nbio_test(void) { return &methods_nbiof; } static int nbiof_new(BIO *bi) { NBIO_TEST *nt; if ((nt = OPENSSL_zalloc(sizeof(*nt))) == NULL) return 0; nt->lrn = -1; nt->lwn = -1; bi->ptr = (char *)nt; bi->init = 1; return 1; } static int nbiof_free(BIO *a) { if (a == NULL) return 0; OPENSSL_free(a->ptr); a->ptr = NULL; a->init = 0; a->flags = 0; return 1; } static int nbiof_read(BIO *b, char *out, int outl) { int ret = 0; int num; unsigned char n; if (out == NULL) return 0; if (b->next_bio == NULL) return 0; BIO_clear_retry_flags(b); if (RAND_priv_bytes(&n, 1) <= 0) return -1; num = (n & 0x07); if (outl > num) outl = num; if (num == 0) { ret = -1; BIO_set_retry_read(b); } else { ret = BIO_read(b->next_bio, out, outl); if (ret < 0) BIO_copy_next_retry(b); } return ret; } static int nbiof_write(BIO *b, const char *in, int inl) { NBIO_TEST *nt; int ret = 0; int num; unsigned char n; if ((in == NULL) || (inl <= 0)) return 0; if (b->next_bio == NULL) return 0; nt = (NBIO_TEST *)b->ptr; BIO_clear_retry_flags(b); if (nt->lwn > 0) { num = nt->lwn; nt->lwn = 0; } else { if (RAND_priv_bytes(&n, 1) <= 0) return -1; num = (n & 7); } if (inl > num) inl = num; if (num == 0) { ret = -1; BIO_set_retry_write(b); } else { ret = BIO_write(b->next_bio, in, inl); if (ret < 0) { BIO_copy_next_retry(b); nt->lwn = inl; } } return ret; } static long nbiof_ctrl(BIO *b, int cmd, long num, void *ptr) { long ret; if (b->next_bio == NULL) return 0; switch (cmd) { case BIO_C_DO_STATE_MACHINE: BIO_clear_retry_flags(b); ret = BIO_ctrl(b->next_bio, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_CTRL_DUP: ret = 0L; break; default: ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; } return ret; } static long nbiof_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { if (b->next_bio == NULL) return 0; return BIO_callback_ctrl(b->next_bio, cmd, fp); } static int nbiof_gets(BIO *bp, char *buf, int size) { if (bp->next_bio == NULL) return 0; return BIO_gets(bp->next_bio, buf, size); } static int nbiof_puts(BIO *bp, const char *str) { if (bp->next_bio == NULL) return 0; return BIO_puts(bp->next_bio, str); }
4,041
20.273684
74
c
openssl
openssl-master/crypto/bio/bf_null.c
/* * Copyright 1995-2021 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 */ #include <stdio.h> #include <errno.h> #include "bio_local.h" #include "internal/cryptlib.h" /* * BIO_put and BIO_get both add to the digest, BIO_gets returns the digest */ static int nullf_write(BIO *h, const char *buf, int num); static int nullf_read(BIO *h, char *buf, int size); static int nullf_puts(BIO *h, const char *str); static int nullf_gets(BIO *h, char *str, int size); static long nullf_ctrl(BIO *h, int cmd, long arg1, void *arg2); static long nullf_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); static const BIO_METHOD methods_nullf = { BIO_TYPE_NULL_FILTER, "NULL filter", bwrite_conv, nullf_write, bread_conv, nullf_read, nullf_puts, nullf_gets, nullf_ctrl, NULL, NULL, nullf_callback_ctrl, }; const BIO_METHOD *BIO_f_null(void) { return &methods_nullf; } static int nullf_read(BIO *b, char *out, int outl) { int ret = 0; if (out == NULL) return 0; if (b->next_bio == NULL) return 0; ret = BIO_read(b->next_bio, out, outl); BIO_clear_retry_flags(b); BIO_copy_next_retry(b); return ret; } static int nullf_write(BIO *b, const char *in, int inl) { int ret = 0; if ((in == NULL) || (inl <= 0)) return 0; if (b->next_bio == NULL) return 0; ret = BIO_write(b->next_bio, in, inl); BIO_clear_retry_flags(b); BIO_copy_next_retry(b); return ret; } static long nullf_ctrl(BIO *b, int cmd, long num, void *ptr) { long ret; if (b->next_bio == NULL) return 0; switch (cmd) { case BIO_C_DO_STATE_MACHINE: BIO_clear_retry_flags(b); ret = BIO_ctrl(b->next_bio, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_CTRL_DUP: ret = 0L; break; default: ret = BIO_ctrl(b->next_bio, cmd, num, ptr); } return ret; } static long nullf_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { if (b->next_bio == NULL) return 0; return BIO_callback_ctrl(b->next_bio, cmd, fp); } static int nullf_gets(BIO *bp, char *buf, int size) { if (bp->next_bio == NULL) return 0; return BIO_gets(bp->next_bio, buf, size); } static int nullf_puts(BIO *bp, const char *str) { if (bp->next_bio == NULL) return 0; return BIO_puts(bp->next_bio, str); }
2,663
22.368421
74
c
openssl
openssl-master/crypto/bio/bf_prefix.c
/* * Copyright 2018-2021 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 */ #include <stdio.h> #include <string.h> #include <errno.h> #include "bio_local.h" static int prefix_write(BIO *b, const char *out, size_t outl, size_t *numwritten); static int prefix_read(BIO *b, char *buf, size_t size, size_t *numread); static int prefix_puts(BIO *b, const char *str); static int prefix_gets(BIO *b, char *str, int size); static long prefix_ctrl(BIO *b, int cmd, long arg1, void *arg2); static int prefix_create(BIO *b); static int prefix_destroy(BIO *b); static long prefix_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp); static const BIO_METHOD prefix_meth = { BIO_TYPE_BUFFER, "prefix", prefix_write, NULL, prefix_read, NULL, prefix_puts, prefix_gets, prefix_ctrl, prefix_create, prefix_destroy, prefix_callback_ctrl, }; const BIO_METHOD *BIO_f_prefix(void) { return &prefix_meth; } typedef struct prefix_ctx_st { char *prefix; /* Text prefix, given by user */ unsigned int indent; /* Indentation amount, given by user */ int linestart; /* flag to indicate we're at the line start */ } PREFIX_CTX; static int prefix_create(BIO *b) { PREFIX_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx == NULL) return 0; ctx->prefix = NULL; ctx->indent = 0; ctx->linestart = 1; BIO_set_data(b, ctx); BIO_set_init(b, 1); return 1; } static int prefix_destroy(BIO *b) { PREFIX_CTX *ctx = BIO_get_data(b); OPENSSL_free(ctx->prefix); OPENSSL_free(ctx); return 1; } static int prefix_read(BIO *b, char *in, size_t size, size_t *numread) { return BIO_read_ex(BIO_next(b), in, size, numread); } static int prefix_write(BIO *b, const char *out, size_t outl, size_t *numwritten) { PREFIX_CTX *ctx = BIO_get_data(b); if (ctx == NULL) return 0; /* * If no prefix is set or if it's empty, and no indentation amount is set, * we've got nothing to do here */ if ((ctx->prefix == NULL || *ctx->prefix == '\0') && ctx->indent == 0) { /* * We do note if what comes next will be a new line, though, so we're * prepared to handle prefix and indentation the next time around. */ if (outl > 0) ctx->linestart = (out[outl-1] == '\n'); return BIO_write_ex(BIO_next(b), out, outl, numwritten); } *numwritten = 0; while (outl > 0) { size_t i; char c; /* * If we know that we're at the start of the line, output prefix and * indentation. */ if (ctx->linestart) { size_t dontcare; if (ctx->prefix != NULL && !BIO_write_ex(BIO_next(b), ctx->prefix, strlen(ctx->prefix), &dontcare)) return 0; BIO_printf(BIO_next(b), "%*s", ctx->indent, ""); ctx->linestart = 0; } /* Now, go look for the next LF, or the end of the string */ for (i = 0, c = '\0'; i < outl && (c = out[i]) != '\n'; i++) continue; if (c == '\n') i++; /* Output what we found so far */ while (i > 0) { size_t num = 0; if (!BIO_write_ex(BIO_next(b), out, i, &num)) return 0; out += num; outl -= num; *numwritten += num; i -= num; } /* If we found a LF, what follows is a new line, so take note */ if (c == '\n') ctx->linestart = 1; } return 1; } static long prefix_ctrl(BIO *b, int cmd, long num, void *ptr) { long ret = 0; PREFIX_CTX *ctx; if (b == NULL || (ctx = BIO_get_data(b)) == NULL) return -1; switch (cmd) { case BIO_CTRL_SET_PREFIX: OPENSSL_free(ctx->prefix); if (ptr == NULL) { ctx->prefix = NULL; ret = 1; } else { ctx->prefix = OPENSSL_strdup((const char *)ptr); ret = ctx->prefix != NULL; } break; case BIO_CTRL_SET_INDENT: if (num >= 0) { ctx->indent = (unsigned int)num; ret = 1; } break; case BIO_CTRL_GET_INDENT: ret = (long)ctx->indent; break; default: /* Commands that we intercept before passing them along */ switch (cmd) { case BIO_C_FILE_SEEK: case BIO_CTRL_RESET: ctx->linestart = 1; break; } if (BIO_next(b) != NULL) ret = BIO_ctrl(BIO_next(b), cmd, num, ptr); break; } return ret; } static long prefix_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { return BIO_callback_ctrl(BIO_next(b), cmd, fp); } static int prefix_gets(BIO *b, char *buf, int size) { return BIO_gets(BIO_next(b), buf, size); } static int prefix_puts(BIO *b, const char *str) { return BIO_write(b, str, strlen(str)); }
5,330
24.629808
79
c
openssl
openssl-master/crypto/bio/bf_readbuff.c
/* * Copyright 2021 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 */ /* * This is a read only BIO filter that can be used to add BIO_tell() and * BIO_seek() support to source/sink BIO's (such as a file BIO that uses stdin). * It does this by caching ALL data read from the BIO source/sink into a * resizable memory buffer. */ #include <stdio.h> #include <errno.h> #include "bio_local.h" #include "internal/cryptlib.h" #define DEFAULT_BUFFER_SIZE 4096 static int readbuffer_write(BIO *h, const char *buf, int num); static int readbuffer_read(BIO *h, char *buf, int size); static int readbuffer_puts(BIO *h, const char *str); static int readbuffer_gets(BIO *h, char *str, int size); static long readbuffer_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int readbuffer_new(BIO *h); static int readbuffer_free(BIO *data); static long readbuffer_callback_ctrl(BIO *h, int cmd, BIO_info_cb *fp); static const BIO_METHOD methods_readbuffer = { BIO_TYPE_BUFFER, "readbuffer", bwrite_conv, readbuffer_write, bread_conv, readbuffer_read, readbuffer_puts, readbuffer_gets, readbuffer_ctrl, readbuffer_new, readbuffer_free, readbuffer_callback_ctrl, }; const BIO_METHOD *BIO_f_readbuffer(void) { return &methods_readbuffer; } static int readbuffer_new(BIO *bi) { BIO_F_BUFFER_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx == NULL) return 0; ctx->ibuf_size = DEFAULT_BUFFER_SIZE; ctx->ibuf = OPENSSL_zalloc(DEFAULT_BUFFER_SIZE); if (ctx->ibuf == NULL) { OPENSSL_free(ctx); return 0; } bi->init = 1; bi->ptr = (char *)ctx; bi->flags = 0; return 1; } static int readbuffer_free(BIO *a) { BIO_F_BUFFER_CTX *b; if (a == NULL) return 0; b = (BIO_F_BUFFER_CTX *)a->ptr; OPENSSL_free(b->ibuf); OPENSSL_free(a->ptr); a->ptr = NULL; a->init = 0; a->flags = 0; return 1; } static int readbuffer_resize(BIO_F_BUFFER_CTX *ctx, int sz) { char *tmp; /* Figure out how many blocks are required */ sz += (ctx->ibuf_off + DEFAULT_BUFFER_SIZE - 1); sz = DEFAULT_BUFFER_SIZE * (sz / DEFAULT_BUFFER_SIZE); /* Resize if the buffer is not big enough */ if (sz > ctx->ibuf_size) { tmp = OPENSSL_realloc(ctx->ibuf, sz); if (tmp == NULL) return 0; ctx->ibuf = tmp; ctx->ibuf_size = sz; } return 1; } static int readbuffer_read(BIO *b, char *out, int outl) { int i, num = 0; BIO_F_BUFFER_CTX *ctx; if (out == NULL || outl == 0) return 0; ctx = (BIO_F_BUFFER_CTX *)b->ptr; if ((ctx == NULL) || (b->next_bio == NULL)) return 0; BIO_clear_retry_flags(b); for (;;) { i = ctx->ibuf_len; /* If there is something in the buffer just read it. */ if (i != 0) { if (i > outl) i = outl; memcpy(out, &(ctx->ibuf[ctx->ibuf_off]), i); ctx->ibuf_off += i; ctx->ibuf_len -= i; num += i; /* Exit if we have read the bytes required out of the buffer */ if (outl == i) return num; outl -= i; out += i; } /* Only gets here if the buffer has been consumed */ if (!readbuffer_resize(ctx, outl)) return 0; /* Do some buffering by reading from the next bio */ i = BIO_read(b->next_bio, ctx->ibuf + ctx->ibuf_off, outl); if (i <= 0) { BIO_copy_next_retry(b); if (i < 0) return ((num > 0) ? num : i); else return num; /* i == 0 */ } ctx->ibuf_len = i; } } static int readbuffer_write(BIO *b, const char *in, int inl) { return 0; } static int readbuffer_puts(BIO *b, const char *str) { return 0; } static long readbuffer_ctrl(BIO *b, int cmd, long num, void *ptr) { BIO_F_BUFFER_CTX *ctx; long ret = 1, sz; ctx = (BIO_F_BUFFER_CTX *)b->ptr; switch (cmd) { case BIO_CTRL_EOF: if (ctx->ibuf_len > 0) return 0; if (b->next_bio == NULL) return 1; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; case BIO_C_FILE_SEEK: case BIO_CTRL_RESET: sz = ctx->ibuf_off + ctx->ibuf_len; /* Assume it can only seek backwards */ if (num < 0 || num > sz) return 0; ctx->ibuf_off = num; ctx->ibuf_len = sz - num; break; case BIO_C_FILE_TELL: case BIO_CTRL_INFO: ret = (long)ctx->ibuf_off; break; case BIO_CTRL_PENDING: ret = (long)ctx->ibuf_len; if (ret == 0) { if (b->next_bio == NULL) return 0; ret = BIO_ctrl(b->next_bio, cmd, num, ptr); } break; case BIO_CTRL_DUP: case BIO_CTRL_FLUSH: ret = 1; break; default: ret = 0; break; } return ret; } static long readbuffer_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { if (b->next_bio == NULL) return 0; return BIO_callback_ctrl(b->next_bio, cmd, fp); } static int readbuffer_gets(BIO *b, char *buf, int size) { BIO_F_BUFFER_CTX *ctx; int num = 0, num_chars, found_newline; char *p; int i, j; if (size == 0) return 0; --size; /* the passed in size includes the terminator - so remove it here */ ctx = (BIO_F_BUFFER_CTX *)b->ptr; BIO_clear_retry_flags(b); /* If data is already buffered then use this first */ if (ctx->ibuf_len > 0) { p = ctx->ibuf + ctx->ibuf_off; found_newline = 0; for (num_chars = 0; (num_chars < ctx->ibuf_len) && (num_chars < size); num_chars++) { *buf++ = p[num_chars]; if (p[num_chars] == '\n') { found_newline = 1; num_chars++; break; } } num += num_chars; size -= num_chars; ctx->ibuf_len -= num_chars; ctx->ibuf_off += num_chars; if (found_newline || size == 0) { *buf = '\0'; return num; } } /* * If there is no buffered data left then read any remaining data from the * next bio. */ /* Resize if we have to */ if (!readbuffer_resize(ctx, 1 + size)) return 0; /* * Read more data from the next bio using BIO_read_ex: * Note we cannot use BIO_gets() here as it does not work on a * binary stream that contains 0x00. (Since strlen() will stop at * any 0x00 not at the last read '\n' in a FILE bio). * Also note that some applications open and close the file bio * multiple times and need to read the next available block when using * stdin - so we need to READ one byte at a time! */ p = ctx->ibuf + ctx->ibuf_off; for (i = 0; i < size; ++i) { j = BIO_read(b->next_bio, p, 1); if (j <= 0) { BIO_copy_next_retry(b); *buf = '\0'; return num > 0 ? num : j; } *buf++ = *p; num++; ctx->ibuf_off++; if (*p == '\n') break; ++p; } *buf = '\0'; return num; }
7,572
25.204152
80
c
openssl
openssl-master/crypto/bio/bio_cb.c
/* * Copyright 1995-2021 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 */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include <string.h> #include <stdlib.h> #include "bio_local.h" #include "internal/cryptlib.h" #include <openssl/err.h> long BIO_debug_callback_ex(BIO *bio, int cmd, const char *argp, size_t len, int argi, long argl, int ret, size_t *processed) { BIO *b; char buf[256]; char *p; int left; size_t l = 0; BIO_MMSG_CB_ARGS *args; long ret_ = ret; if (processed != NULL) l = *processed; left = BIO_snprintf(buf, sizeof(buf), "BIO[%p]: ", (void *)bio); /* Ignore errors and continue printing the other information. */ if (left < 0) left = 0; p = buf + left; left = sizeof(buf) - left; switch (cmd) { case BIO_CB_FREE: BIO_snprintf(p, left, "Free - %s\n", bio->method->name); break; case BIO_CB_READ: if (bio->method->type & BIO_TYPE_DESCRIPTOR) BIO_snprintf(p, left, "read(%d,%zu) - %s fd=%d\n", bio->num, len, bio->method->name, bio->num); else BIO_snprintf(p, left, "read(%d,%zu) - %s\n", bio->num, len, bio->method->name); break; case BIO_CB_WRITE: if (bio->method->type & BIO_TYPE_DESCRIPTOR) BIO_snprintf(p, left, "write(%d,%zu) - %s fd=%d\n", bio->num, len, bio->method->name, bio->num); else BIO_snprintf(p, left, "write(%d,%zu) - %s\n", bio->num, len, bio->method->name); break; case BIO_CB_PUTS: BIO_snprintf(p, left, "puts() - %s\n", bio->method->name); break; case BIO_CB_GETS: BIO_snprintf(p, left, "gets(%zu) - %s\n", len, bio->method->name); break; case BIO_CB_CTRL: BIO_snprintf(p, left, "ctrl(%d) - %s\n", argi, bio->method->name); break; case BIO_CB_RECVMMSG: args = (BIO_MMSG_CB_ARGS *)argp; BIO_snprintf(p, left, "recvmmsg(%zu) - %s", args->num_msg, bio->method->name); break; case BIO_CB_SENDMMSG: args = (BIO_MMSG_CB_ARGS *)argp; BIO_snprintf(p, left, "sendmmsg(%zu) - %s", args->num_msg, bio->method->name); break; case BIO_CB_RETURN | BIO_CB_READ: BIO_snprintf(p, left, "read return %d processed: %zu\n", ret, l); break; case BIO_CB_RETURN | BIO_CB_WRITE: BIO_snprintf(p, left, "write return %d processed: %zu\n", ret, l); break; case BIO_CB_RETURN | BIO_CB_GETS: BIO_snprintf(p, left, "gets return %d processed: %zu\n", ret, l); break; case BIO_CB_RETURN | BIO_CB_PUTS: BIO_snprintf(p, left, "puts return %d processed: %zu\n", ret, l); break; case BIO_CB_RETURN | BIO_CB_CTRL: BIO_snprintf(p, left, "ctrl return %d\n", ret); break; case BIO_CB_RETURN | BIO_CB_RECVMMSG: BIO_snprintf(p, left, "recvmmsg processed: %zu\n", len); ret_ = (long)len; break; case BIO_CB_RETURN | BIO_CB_SENDMMSG: BIO_snprintf(p, left, "sendmmsg processed: %zu\n", len); ret_ = (long)len; break; default: BIO_snprintf(p, left, "bio callback - unknown type (%d)\n", cmd); break; } b = (BIO *)bio->cb_arg; if (b != NULL) BIO_write(b, buf, strlen(buf)); #if !defined(OPENSSL_NO_STDIO) else fputs(buf, stderr); #endif return ret_; } #ifndef OPENSSL_NO_DEPRECATED_3_0 long BIO_debug_callback(BIO *bio, int cmd, const char *argp, int argi, long argl, long ret) { size_t processed = 0; if (ret > 0) processed = (size_t)ret; BIO_debug_callback_ex(bio, cmd, argp, (size_t)argi, argi, argl, ret > 0 ? 1 : (int)ret, &processed); return ret; } #endif
4,288
30.77037
75
c
openssl
openssl-master/crypto/bio/bio_dump.c
/* * Copyright 1995-2021 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 */ /* * Stolen from tjh's ssl/ssl_trc.c stuff. */ #include <stdio.h> #include "bio_local.h" #define DUMP_WIDTH 16 #define DUMP_WIDTH_LESS_INDENT(i) (DUMP_WIDTH - ((i - (i > 6 ? 6 : i) + 3) / 4)) #define SPACE(buf, pos, n) (sizeof(buf) - (pos) > (n)) int BIO_dump_cb(int (*cb) (const void *data, size_t len, void *u), void *u, const void *s, int len) { return BIO_dump_indent_cb(cb, u, s, len, 0); } int BIO_dump_indent_cb(int (*cb) (const void *data, size_t len, void *u), void *u, const void *v, int len, int indent) { const unsigned char *s = v; int res, ret = 0; char buf[288 + 1]; int i, j, rows, n; unsigned char ch; int dump_width; if (indent < 0) indent = 0; else if (indent > 64) indent = 64; dump_width = DUMP_WIDTH_LESS_INDENT(indent); rows = len / dump_width; if ((rows * dump_width) < len) rows++; for (i = 0; i < rows; i++) { n = BIO_snprintf(buf, sizeof(buf), "%*s%04x - ", indent, "", i * dump_width); for (j = 0; j < dump_width; j++) { if (SPACE(buf, n, 3)) { if (((i * dump_width) + j) >= len) { strcpy(buf + n, " "); } else { ch = *(s + i * dump_width + j) & 0xff; BIO_snprintf(buf + n, 4, "%02x%c", ch, j == 7 ? '-' : ' '); } n += 3; } } if (SPACE(buf, n, 2)) { strcpy(buf + n, " "); n += 2; } for (j = 0; j < dump_width; j++) { if (((i * dump_width) + j) >= len) break; if (SPACE(buf, n, 1)) { ch = *(s + i * dump_width + j) & 0xff; #ifndef CHARSET_EBCDIC buf[n++] = ((ch >= ' ') && (ch <= '~')) ? ch : '.'; #else buf[n++] = ((ch >= os_toascii[' ']) && (ch <= os_toascii['~'])) ? os_toebcdic[ch] : '.'; #endif buf[n] = '\0'; } } if (SPACE(buf, n, 1)) { buf[n++] = '\n'; buf[n] = '\0'; } /* * if this is the last call then update the ddt_dump thing so that we * will move the selection point in the debug window */ res = cb((void *)buf, n, u); if (res < 0) return res; ret += res; } return ret; } #ifndef OPENSSL_NO_STDIO static int write_fp(const void *data, size_t len, void *fp) { return UP_fwrite(data, len, 1, fp); } int BIO_dump_fp(FILE *fp, const void *s, int len) { return BIO_dump_cb(write_fp, fp, s, len); } int BIO_dump_indent_fp(FILE *fp, const void *s, int len, int indent) { return BIO_dump_indent_cb(write_fp, fp, s, len, indent); } #endif static int write_bio(const void *data, size_t len, void *bp) { return BIO_write((BIO *)bp, (const char *)data, len); } int BIO_dump(BIO *bp, const void *s, int len) { return BIO_dump_cb(write_bio, bp, s, len); } int BIO_dump_indent(BIO *bp, const void *s, int len, int indent) { return BIO_dump_indent_cb(write_bio, bp, s, len, indent); } int BIO_hex_string(BIO *out, int indent, int width, const void *data, int datalen) { const unsigned char *d = data; int i, j = 0; if (datalen < 1) return 1; for (i = 0; i < datalen - 1; i++) { if (i && !j) BIO_printf(out, "%*s", indent, ""); BIO_printf(out, "%02X:", d[i]); j = (j + 1) % width; if (!j) BIO_printf(out, "\n"); } if (i && !j) BIO_printf(out, "%*s", indent, ""); BIO_printf(out, "%02X", d[datalen - 1]); return 1; }
4,145
25.922078
80
c
openssl
openssl-master/crypto/bio/bio_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2022 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 */ #include <openssl/err.h> #include <openssl/bioerr.h> #include "crypto/bioerr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA BIO_str_reasons[] = { {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_ACCEPT_ERROR), "accept error"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_ADDRINFO_ADDR_IS_NOT_AF_INET), "addrinfo addr is not af inet"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_AMBIGUOUS_HOST_OR_SERVICE), "ambiguous host or service"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_BAD_FOPEN_MODE), "bad fopen mode"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_BROKEN_PIPE), "broken pipe"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_CONNECT_ERROR), "connect error"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_CONNECT_TIMEOUT), "connect timeout"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET), "gethostbyname addr is not af inet"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_GETSOCKNAME_ERROR), "getsockname error"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_GETSOCKNAME_TRUNCATED_ADDRESS), "getsockname truncated address"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_GETTING_SOCKTYPE), "getting socktype"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_INVALID_ARGUMENT), "invalid argument"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_INVALID_SOCKET), "invalid socket"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_IN_USE), "in use"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_LENGTH_TOO_LONG), "length too long"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_LISTEN_V6_ONLY), "listen v6 only"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_LOOKUP_RETURNED_NOTHING), "lookup returned nothing"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_MALFORMED_HOST_OR_SERVICE), "malformed host or service"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_NBIO_CONNECT_ERROR), "nbio connect error"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_NO_ACCEPT_ADDR_OR_SERVICE_SPECIFIED), "no accept addr or service specified"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_NO_HOSTNAME_OR_SERVICE_SPECIFIED), "no hostname or service specified"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_NO_PORT_DEFINED), "no port defined"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_NO_SUCH_FILE), "no such file"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_PORT_MISMATCH), "port mismatch"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_TFO_DISABLED), "tfo disabled"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_TFO_NO_KERNEL_SUPPORT), "tfo no kernel support"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_TRANSFER_ERROR), "transfer error"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_TRANSFER_TIMEOUT), "transfer timeout"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNABLE_TO_BIND_SOCKET), "unable to bind socket"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNABLE_TO_CREATE_SOCKET), "unable to create socket"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNABLE_TO_KEEPALIVE), "unable to keepalive"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNABLE_TO_LISTEN_SOCKET), "unable to listen socket"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNABLE_TO_NODELAY), "unable to nodelay"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNABLE_TO_REUSEADDR), "unable to reuseaddr"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNABLE_TO_TFO), "unable to tfo"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNAVAILABLE_IP_FAMILY), "unavailable ip family"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNINITIALIZED), "uninitialized"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNKNOWN_INFO_TYPE), "unknown info type"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNSUPPORTED_IP_FAMILY), "unsupported ip family"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNSUPPORTED_METHOD), "unsupported method"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_UNSUPPORTED_PROTOCOL_FAMILY), "unsupported protocol family"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_WRITE_TO_READ_ONLY_BIO), "write to read only BIO"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_WSASTARTUP), "WSAStartup"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_LOCAL_ADDR_NOT_AVAILABLE), "local address not available"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_PEER_ADDR_NOT_AVAILABLE), "peer address not available"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_NON_FATAL), "non-fatal or transient error"}, {ERR_PACK(ERR_LIB_BIO, 0, BIO_R_PORT_MISMATCH), "port mismatch"}, {0, NULL} }; #endif int ossl_err_load_BIO_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(BIO_str_reasons[0].error) == NULL) ERR_load_strings_const(BIO_str_reasons); #endif return 1; } #ifndef OPENSSL_NO_SOCK int BIO_err_is_non_fatal(unsigned int errcode) { if (ERR_SYSTEM_ERROR(errcode)) return BIO_sock_non_fatal_error(ERR_GET_REASON(errcode)); else if (ERR_GET_LIB(errcode) == ERR_LIB_BIO && ERR_GET_REASON(errcode) == BIO_R_NON_FATAL) return 1; else return 0; } #endif
5,020
42.66087
79
c
openssl
openssl-master/crypto/bio/bio_local.h
/* * Copyright 2005-2022 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 */ #include "internal/e_os.h" #include "internal/sockets.h" #include "internal/bio_addr.h" /* BEGIN BIO_ADDRINFO/BIO_ADDR stuff. */ #ifndef OPENSSL_NO_SOCK /* * Throughout this file and b_addr.c, the existence of the macro * AI_PASSIVE is used to detect the availability of struct addrinfo, * getnameinfo() and getaddrinfo(). If that macro doesn't exist, * we use our own implementation instead. */ /* * It's imperative that these macros get defined before openssl/bio.h gets * included. Otherwise, the AI_PASSIVE hack will not work properly. * For clarity, we check for internal/cryptlib.h since it's a common header * that also includes bio.h. */ # ifdef OSSL_INTERNAL_CRYPTLIB_H # error internal/cryptlib.h included before bio_local.h # endif # ifdef OPENSSL_BIO_H # error openssl/bio.h included before bio_local.h # endif # ifdef AI_PASSIVE /* * There's a bug in VMS C header file netdb.h, where struct addrinfo * always is the P32 variant, but the functions that handle that structure, * such as getaddrinfo() and freeaddrinfo() adapt to the initial pointer * size. The easiest workaround is to force struct addrinfo to be the * 64-bit variant when compiling in P64 mode. */ # if defined(OPENSSL_SYS_VMS) && __INITIAL_POINTER_SIZE == 64 # define addrinfo __addrinfo64 # endif # define bio_addrinfo_st addrinfo # define bai_family ai_family # define bai_socktype ai_socktype # define bai_protocol ai_protocol # define bai_addrlen ai_addrlen # define bai_addr ai_addr # define bai_next ai_next # else struct bio_addrinfo_st { int bai_family; int bai_socktype; int bai_protocol; size_t bai_addrlen; struct sockaddr *bai_addr; struct bio_addrinfo_st *bai_next; }; # endif #endif /* END BIO_ADDRINFO/BIO_ADDR stuff. */ #include "internal/cryptlib.h" #include "internal/bio.h" #include "internal/refcount.h" typedef struct bio_f_buffer_ctx_struct { /*- * Buffers are setup like this: * * <---------------------- size -----------------------> * +---------------------------------------------------+ * | consumed | remaining | free space | * +---------------------------------------------------+ * <-- off --><------- len -------> */ /*- BIO *bio; *//* * this is now in the BIO struct */ int ibuf_size; /* how big is the input buffer */ int obuf_size; /* how big is the output buffer */ char *ibuf; /* the char array */ int ibuf_len; /* how many bytes are in it */ int ibuf_off; /* write/read offset */ char *obuf; /* the char array */ int obuf_len; /* how many bytes are in it */ int obuf_off; /* write/read offset */ } BIO_F_BUFFER_CTX; struct bio_st { OSSL_LIB_CTX *libctx; const BIO_METHOD *method; /* bio, mode, argp, argi, argl, ret */ #ifndef OPENSSL_NO_DEPRECATED_3_0 BIO_callback_fn callback; #endif BIO_callback_fn_ex callback_ex; char *cb_arg; /* first argument for the callback */ int init; int shutdown; int flags; /* extra storage */ int retry_reason; int num; void *ptr; struct bio_st *next_bio; /* used by filter BIOs */ struct bio_st *prev_bio; /* used by filter BIOs */ CRYPTO_REF_COUNT references; uint64_t num_read; uint64_t num_write; CRYPTO_EX_DATA ex_data; }; #ifndef OPENSSL_NO_SOCK # ifdef OPENSSL_SYS_VMS typedef unsigned int socklen_t; # endif extern CRYPTO_RWLOCK *bio_lookup_lock; int BIO_ADDR_make(BIO_ADDR *ap, const struct sockaddr *sa); const struct sockaddr *BIO_ADDR_sockaddr(const BIO_ADDR *ap); struct sockaddr *BIO_ADDR_sockaddr_noconst(BIO_ADDR *ap); socklen_t BIO_ADDR_sockaddr_size(const BIO_ADDR *ap); socklen_t BIO_ADDRINFO_sockaddr_size(const BIO_ADDRINFO *bai); const struct sockaddr *BIO_ADDRINFO_sockaddr(const BIO_ADDRINFO *bai); # if defined(OPENSSL_SYS_WINDOWS) && defined(WSAID_WSARECVMSG) # define BIO_HAVE_WSAMSG extern LPFN_WSARECVMSG bio_WSARecvMsg; extern LPFN_WSASENDMSG bio_WSASendMsg; # endif #endif extern CRYPTO_REF_COUNT bio_type_count; void bio_sock_cleanup_int(void); #if BIO_FLAGS_UPLINK_INTERNAL==0 /* Shortcut UPLINK calls on most platforms... */ # define UP_stdin stdin # define UP_stdout stdout # define UP_stderr stderr # define UP_fprintf fprintf # define UP_fgets fgets # define UP_fread fread # define UP_fwrite fwrite # undef UP_fsetmod # define UP_feof feof # define UP_fclose fclose # define UP_fopen fopen # define UP_fseek fseek # define UP_ftell ftell # define UP_fflush fflush # define UP_ferror ferror # ifdef _WIN32 # define UP_fileno _fileno # define UP_open _open # define UP_read _read # define UP_write _write # define UP_lseek _lseek # define UP_close _close # else # define UP_fileno fileno # define UP_open open # define UP_read read # define UP_write write # define UP_lseek lseek # define UP_close close # endif #endif
5,566
29.587912
75
h
openssl
openssl-master/crypto/bio/bio_meth.c
/* * Copyright 2016-2020 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 */ #include "bio_local.h" #include "internal/thread_once.h" CRYPTO_REF_COUNT bio_type_count; static CRYPTO_ONCE bio_type_init = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(do_bio_type_init) { return CRYPTO_NEW_REF(&bio_type_count, BIO_TYPE_START); } int BIO_get_new_index(void) { int newval; if (!RUN_ONCE(&bio_type_init, do_bio_type_init)) { /* Perhaps the error should be raised in do_bio_type_init()? */ ERR_raise(ERR_LIB_BIO, ERR_R_CRYPTO_LIB); return -1; } if (!CRYPTO_UP_REF(&bio_type_count, &newval)) return -1; return newval; } BIO_METHOD *BIO_meth_new(int type, const char *name) { BIO_METHOD *biom = OPENSSL_zalloc(sizeof(BIO_METHOD)); if (biom == NULL || (biom->name = OPENSSL_strdup(name)) == NULL) { OPENSSL_free(biom); return NULL; } biom->type = type; return biom; } void BIO_meth_free(BIO_METHOD *biom) { if (biom != NULL) { OPENSSL_free(biom->name); OPENSSL_free(biom); } } int (*BIO_meth_get_write(const BIO_METHOD *biom)) (BIO *, const char *, int) { return biom->bwrite_old; } int (*BIO_meth_get_write_ex(const BIO_METHOD *biom)) (BIO *, const char *, size_t, size_t *) { return biom->bwrite; } /* Conversion for old style bwrite to new style */ int bwrite_conv(BIO *bio, const char *data, size_t datal, size_t *written) { int ret; if (datal > INT_MAX) datal = INT_MAX; ret = bio->method->bwrite_old(bio, data, (int)datal); if (ret <= 0) { *written = 0; return ret; } *written = (size_t)ret; return 1; } int BIO_meth_set_write(BIO_METHOD *biom, int (*bwrite) (BIO *, const char *, int)) { biom->bwrite_old = bwrite; biom->bwrite = bwrite_conv; return 1; } int BIO_meth_set_write_ex(BIO_METHOD *biom, int (*bwrite) (BIO *, const char *, size_t, size_t *)) { biom->bwrite_old = NULL; biom->bwrite = bwrite; return 1; } int (*BIO_meth_get_read(const BIO_METHOD *biom)) (BIO *, char *, int) { return biom->bread_old; } int (*BIO_meth_get_read_ex(const BIO_METHOD *biom)) (BIO *, char *, size_t, size_t *) { return biom->bread; } /* Conversion for old style bread to new style */ int bread_conv(BIO *bio, char *data, size_t datal, size_t *readbytes) { int ret; if (datal > INT_MAX) datal = INT_MAX; ret = bio->method->bread_old(bio, data, (int)datal); if (ret <= 0) { *readbytes = 0; return ret; } *readbytes = (size_t)ret; return 1; } int BIO_meth_set_read(BIO_METHOD *biom, int (*bread) (BIO *, char *, int)) { biom->bread_old = bread; biom->bread = bread_conv; return 1; } int BIO_meth_set_read_ex(BIO_METHOD *biom, int (*bread) (BIO *, char *, size_t, size_t *)) { biom->bread_old = NULL; biom->bread = bread; return 1; } int (*BIO_meth_get_puts(const BIO_METHOD *biom)) (BIO *, const char *) { return biom->bputs; } int BIO_meth_set_puts(BIO_METHOD *biom, int (*bputs) (BIO *, const char *)) { biom->bputs = bputs; return 1; } int (*BIO_meth_get_gets(const BIO_METHOD *biom)) (BIO *, char *, int) { return biom->bgets; } int BIO_meth_set_gets(BIO_METHOD *biom, int (*bgets) (BIO *, char *, int)) { biom->bgets = bgets; return 1; } long (*BIO_meth_get_ctrl(const BIO_METHOD *biom)) (BIO *, int, long, void *) { return biom->ctrl; } int BIO_meth_set_ctrl(BIO_METHOD *biom, long (*ctrl) (BIO *, int, long, void *)) { biom->ctrl = ctrl; return 1; } int (*BIO_meth_get_create(const BIO_METHOD *biom)) (BIO *) { return biom->create; } int BIO_meth_set_create(BIO_METHOD *biom, int (*create) (BIO *)) { biom->create = create; return 1; } int (*BIO_meth_get_destroy(const BIO_METHOD *biom)) (BIO *) { return biom->destroy; } int BIO_meth_set_destroy(BIO_METHOD *biom, int (*destroy) (BIO *)) { biom->destroy = destroy; return 1; } long (*BIO_meth_get_callback_ctrl(const BIO_METHOD *biom)) (BIO *, int, BIO_info_cb *) { return biom->callback_ctrl; } int BIO_meth_set_callback_ctrl(BIO_METHOD *biom, long (*callback_ctrl) (BIO *, int, BIO_info_cb *)) { biom->callback_ctrl = callback_ctrl; return 1; } int BIO_meth_set_sendmmsg(BIO_METHOD *biom, int (*bsendmmsg) (BIO *, BIO_MSG *, size_t, size_t, uint64_t, size_t *)) { biom->bsendmmsg = bsendmmsg; return 1; } int (*BIO_meth_get_sendmmsg(const BIO_METHOD *biom))(BIO *, BIO_MSG *, size_t, size_t, uint64_t, size_t *) { return biom->bsendmmsg; } int BIO_meth_set_recvmmsg(BIO_METHOD *biom, int (*brecvmmsg) (BIO *, BIO_MSG *, size_t, size_t, uint64_t, size_t *)) { biom->brecvmmsg = brecvmmsg; return 1; } int (*BIO_meth_get_recvmmsg(const BIO_METHOD *biom))(BIO *, BIO_MSG *, size_t, size_t, uint64_t, size_t *) { return biom->brecvmmsg; }
5,520
21.908714
108
c
openssl
openssl-master/crypto/bio/bio_sock.c
/* * Copyright 1995-2021 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 */ #include <stdio.h> #include <stdlib.h> #include "bio_local.h" #ifndef OPENSSL_NO_SOCK # define SOCKET_PROTOCOL IPPROTO_TCP # ifdef SO_MAXCONN # define MAX_LISTEN SO_MAXCONN # elif defined(SOMAXCONN) # define MAX_LISTEN SOMAXCONN # else # define MAX_LISTEN 32 # endif # if defined(OPENSSL_SYS_WINDOWS) static int wsa_init_done = 0; # endif # if defined __TANDEM # include <unistd.h> # include <sys/time.h> /* select */ # if defined(OPENSSL_TANDEM_FLOSS) # include <floss.h(floss_select)> # endif # elif defined _WIN32 # include <winsock.h> /* for type fd_set */ # else # include <unistd.h> # if defined __VMS # include <sys/socket.h> # elif defined _HPUX_SOURCE # include <sys/time.h> # else # include <sys/select.h> # endif # endif # ifndef OPENSSL_NO_DEPRECATED_1_1_0 int BIO_get_host_ip(const char *str, unsigned char *ip) { BIO_ADDRINFO *res = NULL; int ret = 0; if (BIO_sock_init() != 1) return 0; /* don't generate another error code here */ if (BIO_lookup(str, NULL, BIO_LOOKUP_CLIENT, AF_INET, SOCK_STREAM, &res)) { size_t l; if (BIO_ADDRINFO_family(res) != AF_INET) { ERR_raise(ERR_LIB_BIO, BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET); } else if (BIO_ADDR_rawaddress(BIO_ADDRINFO_address(res), NULL, &l)) { /* * Because only AF_INET addresses will reach this far, we can assert * that l should be 4 */ if (ossl_assert(l == 4)) ret = BIO_ADDR_rawaddress(BIO_ADDRINFO_address(res), ip, &l); } BIO_ADDRINFO_free(res); } else { ERR_add_error_data(2, "host=", str); } return ret; } int BIO_get_port(const char *str, unsigned short *port_ptr) { BIO_ADDRINFO *res = NULL; int ret = 0; if (str == NULL) { ERR_raise(ERR_LIB_BIO, BIO_R_NO_PORT_DEFINED); return 0; } if (BIO_sock_init() != 1) return 0; /* don't generate another error code here */ if (BIO_lookup(NULL, str, BIO_LOOKUP_CLIENT, AF_INET, SOCK_STREAM, &res)) { if (BIO_ADDRINFO_family(res) != AF_INET) { ERR_raise(ERR_LIB_BIO, BIO_R_ADDRINFO_ADDR_IS_NOT_AF_INET); } else { *port_ptr = ntohs(BIO_ADDR_rawport(BIO_ADDRINFO_address(res))); ret = 1; } BIO_ADDRINFO_free(res); } else { ERR_add_error_data(2, "host=", str); } return ret; } # endif int BIO_sock_error(int sock) { int j = 0, i; socklen_t size = sizeof(j); /* * Note: under Windows the third parameter is of type (char *) whereas * under other systems it is (void *) if you don't have a cast it will * choke the compiler: if you do have a cast then you can either go for * (char *) or (void *). */ i = getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *)&j, &size); if (i < 0) return get_last_socket_error(); else return j; } # ifndef OPENSSL_NO_DEPRECATED_1_1_0 struct hostent *BIO_gethostbyname(const char *name) { /* * Caching gethostbyname() results forever is wrong, so we have to let * the true gethostbyname() worry about this */ return gethostbyname(name); } # endif # ifdef BIO_HAVE_WSAMSG LPFN_WSARECVMSG bio_WSARecvMsg; LPFN_WSASENDMSG bio_WSASendMsg; # endif int BIO_sock_init(void) { # ifdef OPENSSL_SYS_WINDOWS static struct WSAData wsa_state; if (!wsa_init_done) { wsa_init_done = 1; memset(&wsa_state, 0, sizeof(wsa_state)); /* * Not making wsa_state available to the rest of the code is formally * wrong. But the structures we use are [believed to be] invariable * among Winsock DLLs, while API availability is [expected to be] * probed at run-time with DSO_global_lookup. */ if (WSAStartup(0x0202, &wsa_state) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling wsastartup()"); ERR_raise(ERR_LIB_BIO, BIO_R_WSASTARTUP); return -1; } /* * On Windows, some socket functions are not exposed as a prototype. * Instead, their function pointers must be loaded via this elaborate * process... */ # ifdef BIO_HAVE_WSAMSG { GUID id_WSARecvMsg = WSAID_WSARECVMSG; GUID id_WSASendMsg = WSAID_WSASENDMSG; DWORD len_out = 0; SOCKET s; s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (s != INVALID_SOCKET) { if (WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &id_WSARecvMsg, sizeof(id_WSARecvMsg), &bio_WSARecvMsg, sizeof(bio_WSARecvMsg), &len_out, NULL, NULL) != 0 || len_out != sizeof(bio_WSARecvMsg)) bio_WSARecvMsg = NULL; if (WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &id_WSASendMsg, sizeof(id_WSASendMsg), &bio_WSASendMsg, sizeof(bio_WSASendMsg), &len_out, NULL, NULL) != 0 || len_out != sizeof(bio_WSASendMsg)) bio_WSASendMsg = NULL; closesocket(s); } } # endif } # endif /* OPENSSL_SYS_WINDOWS */ # ifdef WATT32 extern int _watt_do_exit; _watt_do_exit = 0; /* don't make sock_init() call exit() */ if (sock_init()) return -1; # endif return 1; } void bio_sock_cleanup_int(void) { # ifdef OPENSSL_SYS_WINDOWS if (wsa_init_done) { wsa_init_done = 0; WSACleanup(); } # endif } int BIO_socket_ioctl(int fd, long type, void *arg) { int i; # ifdef __DJGPP__ i = ioctlsocket(fd, type, (char *)arg); # else # if defined(OPENSSL_SYS_VMS) /*- * 2011-02-18 SMS. * VMS ioctl() can't tolerate a 64-bit "void *arg", but we * observe that all the consumers pass in an "unsigned long *", * so we arrange a local copy with a short pointer, and use * that, instead. */ # if __INITIAL_POINTER_SIZE == 64 # define ARG arg_32p # pragma pointer_size save # pragma pointer_size 32 unsigned long arg_32; unsigned long *arg_32p; # pragma pointer_size restore arg_32p = &arg_32; arg_32 = *((unsigned long *)arg); # else /* __INITIAL_POINTER_SIZE == 64 */ # define ARG arg # endif /* __INITIAL_POINTER_SIZE == 64 [else] */ # else /* defined(OPENSSL_SYS_VMS) */ # define ARG arg # endif /* defined(OPENSSL_SYS_VMS) [else] */ i = ioctlsocket(fd, type, ARG); # endif /* __DJGPP__ */ if (i < 0) ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling ioctlsocket()"); return i; } # ifndef OPENSSL_NO_DEPRECATED_1_1_0 int BIO_get_accept_socket(char *host, int bind_mode) { int s = INVALID_SOCKET; char *h = NULL, *p = NULL; BIO_ADDRINFO *res = NULL; if (!BIO_parse_hostserv(host, &h, &p, BIO_PARSE_PRIO_SERV)) return INVALID_SOCKET; if (BIO_sock_init() != 1) return INVALID_SOCKET; if (BIO_lookup(h, p, BIO_LOOKUP_SERVER, AF_UNSPEC, SOCK_STREAM, &res) != 0) goto err; if ((s = BIO_socket(BIO_ADDRINFO_family(res), BIO_ADDRINFO_socktype(res), BIO_ADDRINFO_protocol(res), 0)) == INVALID_SOCKET) { s = INVALID_SOCKET; goto err; } if (!BIO_listen(s, BIO_ADDRINFO_address(res), bind_mode ? BIO_SOCK_REUSEADDR : 0)) { BIO_closesocket(s); s = INVALID_SOCKET; } err: BIO_ADDRINFO_free(res); OPENSSL_free(h); OPENSSL_free(p); return s; } int BIO_accept(int sock, char **ip_port) { BIO_ADDR res; int ret = -1; ret = BIO_accept_ex(sock, &res, 0); if (ret == (int)INVALID_SOCKET) { if (BIO_sock_should_retry(ret)) { ret = -2; goto end; } ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling accept()"); ERR_raise(ERR_LIB_BIO, BIO_R_ACCEPT_ERROR); goto end; } if (ip_port != NULL) { char *host = BIO_ADDR_hostname_string(&res, 1); char *port = BIO_ADDR_service_string(&res, 1); if (host != NULL && port != NULL) { *ip_port = OPENSSL_zalloc(strlen(host) + strlen(port) + 2); } else { *ip_port = NULL; ERR_raise(ERR_LIB_BIO, ERR_R_BIO_LIB); } if (*ip_port == NULL) { BIO_closesocket(ret); ret = (int)INVALID_SOCKET; } else { strcpy(*ip_port, host); strcat(*ip_port, ":"); strcat(*ip_port, port); } OPENSSL_free(host); OPENSSL_free(port); } end: return ret; } # endif int BIO_set_tcp_ndelay(int s, int on) { int ret = 0; # if defined(TCP_NODELAY) && (defined(IPPROTO_TCP) || defined(SOL_TCP)) int opt; # ifdef SOL_TCP opt = SOL_TCP; # else # ifdef IPPROTO_TCP opt = IPPROTO_TCP; # endif # endif ret = setsockopt(s, opt, TCP_NODELAY, (char *)&on, sizeof(on)); # endif return (ret == 0); } int BIO_socket_nbio(int s, int mode) { int ret = -1; int l; l = mode; # ifdef FIONBIO l = mode; ret = BIO_socket_ioctl(s, FIONBIO, &l); # elif defined(F_GETFL) && defined(F_SETFL) && (defined(O_NONBLOCK) || defined(FNDELAY)) /* make sure this call always pushes an error level; BIO_socket_ioctl() does so, so we do too. */ l = fcntl(s, F_GETFL, 0); if (l == -1) { ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(), "calling fcntl()"); ret = -1; } else { # if defined(O_NONBLOCK) l &= ~O_NONBLOCK; # else l &= ~FNDELAY; /* BSD4.x */ # endif if (mode) { # if defined(O_NONBLOCK) l |= O_NONBLOCK; # else l |= FNDELAY; /* BSD4.x */ # endif } ret = fcntl(s, F_SETFL, l); if (ret < 0) { ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(), "calling fcntl()"); } } # else /* make sure this call always pushes an error level; BIO_socket_ioctl() does so, so we do too. */ ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_INVALID_ARGUMENT); # endif return (ret == 0); } int BIO_sock_info(int sock, enum BIO_sock_info_type type, union BIO_sock_info_u *info) { switch (type) { case BIO_SOCK_INFO_ADDRESS: { socklen_t addr_len; int ret = 0; addr_len = sizeof(*info->addr); ret = getsockname(sock, BIO_ADDR_sockaddr_noconst(info->addr), &addr_len); if (ret == -1) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling getsockname()"); ERR_raise(ERR_LIB_BIO, BIO_R_GETSOCKNAME_ERROR); return 0; } if ((size_t)addr_len > sizeof(*info->addr)) { ERR_raise(ERR_LIB_BIO, BIO_R_GETSOCKNAME_TRUNCATED_ADDRESS); return 0; } } break; default: ERR_raise(ERR_LIB_BIO, BIO_R_UNKNOWN_INFO_TYPE); return 0; } return 1; } /* * Wait on fd at most until max_time; succeed immediately if max_time == 0. * If for_read == 0 then assume to wait for writing, else wait for reading. * Returns -1 on error, 0 on timeout, and 1 on success. */ int BIO_socket_wait(int fd, int for_read, time_t max_time) { fd_set confds; struct timeval tv; time_t now; if (fd < 0 || fd >= FD_SETSIZE) return -1; if (max_time == 0) return 1; now = time(NULL); if (max_time < now) return 0; FD_ZERO(&confds); openssl_fdset(fd, &confds); tv.tv_usec = 0; tv.tv_sec = (long)(max_time - now); /* might overflow */ return select(fd + 1, for_read ? &confds : NULL, for_read ? NULL : &confds, NULL, &tv); } #endif /* !defined(OPENSSL_NO_SOCK) */
12,666
26.83956
101
c
openssl
openssl-master/crypto/bio/bio_sock2.c
/* * Copyright 2016-2022 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 */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include "bio_local.h" #include "internal/ktls.h" #include "internal/bio_tfo.h" #include <openssl/err.h> #ifndef OPENSSL_NO_SOCK # ifdef SO_MAXCONN # define MAX_LISTEN SO_MAXCONN # elif defined(SOMAXCONN) # define MAX_LISTEN SOMAXCONN # else # define MAX_LISTEN 32 # endif /*- * BIO_socket - create a socket * @domain: the socket domain (AF_INET, AF_INET6, AF_UNIX, ...) * @socktype: the socket type (SOCK_STEAM, SOCK_DGRAM) * @protocol: the protocol to use (IPPROTO_TCP, IPPROTO_UDP) * @options: BIO socket options (currently unused) * * Creates a socket. This should be called before calling any * of BIO_connect and BIO_listen. * * Returns the file descriptor on success or INVALID_SOCKET on failure. On * failure errno is set, and a status is added to the OpenSSL error stack. */ int BIO_socket(int domain, int socktype, int protocol, int options) { int sock = -1; if (BIO_sock_init() != 1) return INVALID_SOCKET; sock = socket(domain, socktype, protocol); if (sock == -1) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling socket()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_CREATE_SOCKET); return INVALID_SOCKET; } return sock; } /*- * BIO_connect - connect to an address * @sock: the socket to connect with * @addr: the address to connect to * @options: BIO socket options * * Connects to the address using the given socket and options. * * Options can be a combination of the following: * - BIO_SOCK_KEEPALIVE: enable regularly sending keep-alive messages. * - BIO_SOCK_NONBLOCK: Make the socket non-blocking. * - BIO_SOCK_NODELAY: don't delay small messages. * - BIO_SOCK_TFO: use TCP Fast Open * * options holds BIO socket options that can be used * You should call this for every address returned by BIO_lookup * until the connection is successful. * * Returns 1 on success or 0 on failure. On failure errno is set * and an error status is added to the OpenSSL error stack. */ int BIO_connect(int sock, const BIO_ADDR *addr, int options) { const int on = 1; if (sock == -1) { ERR_raise(ERR_LIB_BIO, BIO_R_INVALID_SOCKET); return 0; } if (!BIO_socket_nbio(sock, (options & BIO_SOCK_NONBLOCK) != 0)) return 0; if (options & BIO_SOCK_KEEPALIVE) { if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (const void *)&on, sizeof(on)) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling setsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_KEEPALIVE); return 0; } } if (options & BIO_SOCK_NODELAY) { if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const void *)&on, sizeof(on)) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling setsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_NODELAY); return 0; } } if (options & BIO_SOCK_TFO) { # if defined(OSSL_TFO_CLIENT_FLAG) # if defined(OSSL_TFO_SYSCTL_CLIENT) int enabled = 0; size_t enabledlen = sizeof(enabled); /* Later FreeBSD */ if (sysctlbyname(OSSL_TFO_SYSCTL_CLIENT, &enabled, &enabledlen, NULL, 0) < 0) { ERR_raise(ERR_LIB_BIO, BIO_R_TFO_NO_KERNEL_SUPPORT); return 0; } /* Need to check for client flag */ if (!(enabled & OSSL_TFO_CLIENT_FLAG)) { ERR_raise(ERR_LIB_BIO, BIO_R_TFO_DISABLED); return 0; } # elif defined(OSSL_TFO_SYSCTL) int enabled = 0; size_t enabledlen = sizeof(enabled); /* macOS */ if (sysctlbyname(OSSL_TFO_SYSCTL, &enabled, &enabledlen, NULL, 0) < 0) { ERR_raise(ERR_LIB_BIO, BIO_R_TFO_NO_KERNEL_SUPPORT); return 0; } /* Need to check for client flag */ if (!(enabled & OSSL_TFO_CLIENT_FLAG)) { ERR_raise(ERR_LIB_BIO, BIO_R_TFO_DISABLED); return 0; } # endif # endif # if defined(OSSL_TFO_CONNECTX) sa_endpoints_t sae; memset(&sae, 0, sizeof(sae)); sae.sae_dstaddr = BIO_ADDR_sockaddr(addr); sae.sae_dstaddrlen = BIO_ADDR_sockaddr_size(addr); if (connectx(sock, &sae, SAE_ASSOCID_ANY, CONNECT_DATA_IDEMPOTENT | CONNECT_RESUME_ON_READ_WRITE, NULL, 0, NULL, NULL) == -1) { if (!BIO_sock_should_retry(-1)) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling connectx()"); ERR_raise(ERR_LIB_BIO, BIO_R_CONNECT_ERROR); } return 0; } # endif # if defined(OSSL_TFO_CLIENT_SOCKOPT) if (setsockopt(sock, IPPROTO_TCP, OSSL_TFO_CLIENT_SOCKOPT, (const void *)&on, sizeof(on)) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling setsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_TFO); return 0; } # endif # if defined(OSSL_TFO_DO_NOT_CONNECT) return 1; # endif } if (connect(sock, BIO_ADDR_sockaddr(addr), BIO_ADDR_sockaddr_size(addr)) == -1) { if (!BIO_sock_should_retry(-1)) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling connect()"); ERR_raise(ERR_LIB_BIO, BIO_R_CONNECT_ERROR); } return 0; } # ifndef OPENSSL_NO_KTLS /* * The new socket is created successfully regardless of ktls_enable. * ktls_enable doesn't change any functionality of the socket, except * changing the setsockopt to enable the processing of ktls_start. * Thus, it is not a problem to call it for non-TLS sockets. */ ktls_enable(sock); # endif return 1; } /*- * BIO_bind - bind socket to address * @sock: the socket to set * @addr: local address to bind to * @options: BIO socket options * * Binds to the address using the given socket and options. * * Options can be a combination of the following: * - BIO_SOCK_REUSEADDR: Try to reuse the address and port combination * for a recently closed port. * * When restarting the program it could be that the port is still in use. If * you set to BIO_SOCK_REUSEADDR option it will try to reuse the port anyway. * It's recommended that you use this. */ int BIO_bind(int sock, const BIO_ADDR *addr, int options) { # ifndef OPENSSL_SYS_WINDOWS int on = 1; # endif if (sock == -1) { ERR_raise(ERR_LIB_BIO, BIO_R_INVALID_SOCKET); return 0; } # ifndef OPENSSL_SYS_WINDOWS /* * SO_REUSEADDR has different behavior on Windows than on * other operating systems, don't set it there. */ if (options & BIO_SOCK_REUSEADDR) { if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const void *)&on, sizeof(on)) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling setsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_REUSEADDR); return 0; } } # endif if (bind(sock, BIO_ADDR_sockaddr(addr), BIO_ADDR_sockaddr_size(addr)) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error() /* may be 0 */, "calling bind()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_BIND_SOCKET); return 0; } return 1; } /*- * BIO_listen - Creates a listen socket * @sock: the socket to listen with * @addr: local address to bind to * @options: BIO socket options * * Binds to the address using the given socket and options, then * starts listening for incoming connections. * * Options can be a combination of the following: * - BIO_SOCK_KEEPALIVE: enable regularly sending keep-alive messages. * - BIO_SOCK_NONBLOCK: Make the socket non-blocking. * - BIO_SOCK_NODELAY: don't delay small messages. * - BIO_SOCK_REUSEADDR: Try to reuse the address and port combination * for a recently closed port. * - BIO_SOCK_V6_ONLY: When creating an IPv6 socket, make it listen only * for IPv6 addresses and not IPv4 addresses mapped to IPv6. * - BIO_SOCK_TFO: accept TCP fast open (set TCP_FASTOPEN) * * It's recommended that you set up both an IPv6 and IPv4 listen socket, and * then check both for new clients that connect to it. You want to set up * the socket as non-blocking in that case since else it could hang. * * Not all operating systems support IPv4 addresses on an IPv6 socket, and for * others it's an option. If you pass the BIO_LISTEN_V6_ONLY it will try to * create the IPv6 sockets to only listen for IPv6 connection. * * It could be that the first BIO_listen() call will listen to all the IPv6 * and IPv4 addresses and that then trying to bind to the IPv4 address will * fail. We can't tell the difference between already listening ourself to * it and someone else listening to it when failing and errno is EADDRINUSE, so * it's recommended to not give an error in that case if the first call was * successful. * * When restarting the program it could be that the port is still in use. If * you set to BIO_SOCK_REUSEADDR option it will try to reuse the port anyway. * It's recommended that you use this. */ int BIO_listen(int sock, const BIO_ADDR *addr, int options) { int on = 1; int socktype; socklen_t socktype_len = sizeof(socktype); if (sock == -1) { ERR_raise(ERR_LIB_BIO, BIO_R_INVALID_SOCKET); return 0; } if (getsockopt(sock, SOL_SOCKET, SO_TYPE, (void *)&socktype, &socktype_len) != 0 || socktype_len != sizeof(socktype)) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling getsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_GETTING_SOCKTYPE); return 0; } if (!BIO_socket_nbio(sock, (options & BIO_SOCK_NONBLOCK) != 0)) return 0; if (options & BIO_SOCK_KEEPALIVE) { if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (const void *)&on, sizeof(on)) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling setsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_KEEPALIVE); return 0; } } if (options & BIO_SOCK_NODELAY) { if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const void *)&on, sizeof(on)) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling setsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_NODELAY); return 0; } } /* On OpenBSD it is always IPv6 only with IPv6 sockets thus read-only */ # if defined(IPV6_V6ONLY) && !defined(__OpenBSD__) if (BIO_ADDR_family(addr) == AF_INET6) { /* * Note: Windows default of IPV6_V6ONLY is ON, and Linux is OFF. * Therefore we always have to use setsockopt here. */ on = options & BIO_SOCK_V6_ONLY ? 1 : 0; if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (const void *)&on, sizeof(on)) != 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling setsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_LISTEN_V6_ONLY); return 0; } } # endif if (!BIO_bind(sock, addr, options)) return 0; if (socktype != SOCK_DGRAM && listen(sock, MAX_LISTEN) == -1) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling listen()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_LISTEN_SOCKET); return 0; } # if defined(OSSL_TFO_SERVER_SOCKOPT) /* * Must do it explicitly after listen() for macOS, still * works fine on other OS's */ if ((options & BIO_SOCK_TFO) && socktype != SOCK_DGRAM) { int q = OSSL_TFO_SERVER_SOCKOPT_VALUE; # if defined(OSSL_TFO_CLIENT_FLAG) # if defined(OSSL_TFO_SYSCTL_SERVER) int enabled = 0; size_t enabledlen = sizeof(enabled); /* Later FreeBSD */ if (sysctlbyname(OSSL_TFO_SYSCTL_SERVER, &enabled, &enabledlen, NULL, 0) < 0) { ERR_raise(ERR_LIB_BIO, BIO_R_TFO_NO_KERNEL_SUPPORT); return 0; } /* Need to check for server flag */ if (!(enabled & OSSL_TFO_SERVER_FLAG)) { ERR_raise(ERR_LIB_BIO, BIO_R_TFO_DISABLED); return 0; } # elif defined(OSSL_TFO_SYSCTL) int enabled = 0; size_t enabledlen = sizeof(enabled); /* Early FreeBSD, macOS */ if (sysctlbyname(OSSL_TFO_SYSCTL, &enabled, &enabledlen, NULL, 0) < 0) { ERR_raise(ERR_LIB_BIO, BIO_R_TFO_NO_KERNEL_SUPPORT); return 0; } /* Need to check for server flag */ if (!(enabled & OSSL_TFO_SERVER_FLAG)) { ERR_raise(ERR_LIB_BIO, BIO_R_TFO_DISABLED); return 0; } # endif # endif if (setsockopt(sock, IPPROTO_TCP, OSSL_TFO_SERVER_SOCKOPT, (void *)&q, sizeof(q)) < 0) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling setsockopt()"); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_TFO); return 0; } } # endif return 1; } /*- * BIO_accept_ex - Accept new incoming connections * @sock: the listening socket * @addr: the BIO_ADDR to store the peer address in * @options: BIO socket options, applied on the accepted socket. * */ int BIO_accept_ex(int accept_sock, BIO_ADDR *addr_, int options) { socklen_t len; int accepted_sock; BIO_ADDR locaddr; BIO_ADDR *addr = addr_ == NULL ? &locaddr : addr_; len = sizeof(*addr); accepted_sock = accept(accept_sock, BIO_ADDR_sockaddr_noconst(addr), &len); if (accepted_sock == -1) { if (!BIO_sock_should_retry(accepted_sock)) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling accept()"); ERR_raise(ERR_LIB_BIO, BIO_R_ACCEPT_ERROR); } return INVALID_SOCKET; } if (!BIO_socket_nbio(accepted_sock, (options & BIO_SOCK_NONBLOCK) != 0)) { closesocket(accepted_sock); return INVALID_SOCKET; } return accepted_sock; } /*- * BIO_closesocket - Close a socket * @sock: the socket to close */ int BIO_closesocket(int sock) { if (sock < 0 || closesocket(sock) < 0) return 0; return 1; } #endif
15,146
32.363436
87
c
openssl
openssl-master/crypto/bio/bss_acpt.c
/* * Copyright 1995-2022 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 */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include <errno.h> #include "bio_local.h" #ifndef OPENSSL_NO_SOCK typedef struct bio_accept_st { int state; int accept_family; int bind_mode; /* Socket mode for BIO_listen */ int accepted_mode; /* Socket mode for BIO_accept (set on accepted sock) */ char *param_addr; char *param_serv; int accept_sock; BIO_ADDRINFO *addr_first; const BIO_ADDRINFO *addr_iter; BIO_ADDR cache_accepting_addr; /* Useful if we asked for port 0 */ char *cache_accepting_name, *cache_accepting_serv; BIO_ADDR cache_peer_addr; char *cache_peer_name, *cache_peer_serv; BIO *bio_chain; } BIO_ACCEPT; static int acpt_write(BIO *h, const char *buf, int num); static int acpt_read(BIO *h, char *buf, int size); static int acpt_puts(BIO *h, const char *str); static long acpt_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int acpt_new(BIO *h); static int acpt_free(BIO *data); static int acpt_state(BIO *b, BIO_ACCEPT *c); static void acpt_close_socket(BIO *data); static BIO_ACCEPT *BIO_ACCEPT_new(void); static void BIO_ACCEPT_free(BIO_ACCEPT *a); # define ACPT_S_BEFORE 1 # define ACPT_S_GET_ADDR 2 # define ACPT_S_CREATE_SOCKET 3 # define ACPT_S_LISTEN 4 # define ACPT_S_ACCEPT 5 # define ACPT_S_OK 6 static const BIO_METHOD methods_acceptp = { BIO_TYPE_ACCEPT, "socket accept", bwrite_conv, acpt_write, bread_conv, acpt_read, acpt_puts, NULL, /* connect_gets, */ acpt_ctrl, acpt_new, acpt_free, NULL, /* connect_callback_ctrl */ }; const BIO_METHOD *BIO_s_accept(void) { return &methods_acceptp; } static int acpt_new(BIO *bi) { BIO_ACCEPT *ba; bi->init = 0; bi->num = (int)INVALID_SOCKET; bi->flags = 0; if ((ba = BIO_ACCEPT_new()) == NULL) return 0; bi->ptr = (char *)ba; ba->state = ACPT_S_BEFORE; bi->shutdown = 1; return 1; } static BIO_ACCEPT *BIO_ACCEPT_new(void) { BIO_ACCEPT *ret; if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) return NULL; ret->accept_family = BIO_FAMILY_IPANY; ret->accept_sock = (int)INVALID_SOCKET; return ret; } static void BIO_ACCEPT_free(BIO_ACCEPT *a) { if (a == NULL) return; OPENSSL_free(a->param_addr); OPENSSL_free(a->param_serv); BIO_ADDRINFO_free(a->addr_first); OPENSSL_free(a->cache_accepting_name); OPENSSL_free(a->cache_accepting_serv); OPENSSL_free(a->cache_peer_name); OPENSSL_free(a->cache_peer_serv); BIO_free(a->bio_chain); OPENSSL_free(a); } static void acpt_close_socket(BIO *bio) { BIO_ACCEPT *c; c = (BIO_ACCEPT *)bio->ptr; if (c->accept_sock != (int)INVALID_SOCKET) { shutdown(c->accept_sock, 2); closesocket(c->accept_sock); c->accept_sock = (int)INVALID_SOCKET; bio->num = (int)INVALID_SOCKET; } } static int acpt_free(BIO *a) { BIO_ACCEPT *data; if (a == NULL) return 0; data = (BIO_ACCEPT *)a->ptr; if (a->shutdown) { acpt_close_socket(a); BIO_ACCEPT_free(data); a->ptr = NULL; a->flags = 0; a->init = 0; } return 1; } static int acpt_state(BIO *b, BIO_ACCEPT *c) { BIO *bio = NULL, *dbio; int s = -1, ret = -1; for (;;) { switch (c->state) { case ACPT_S_BEFORE: if (c->param_addr == NULL && c->param_serv == NULL) { ERR_raise_data(ERR_LIB_BIO, BIO_R_NO_ACCEPT_ADDR_OR_SERVICE_SPECIFIED, "hostname=%s, service=%s", c->param_addr, c->param_serv); goto exit_loop; } /* Because we're starting a new bind, any cached name and serv * are now obsolete and need to be cleaned out. * QUESTION: should this be done in acpt_close_socket() instead? */ OPENSSL_free(c->cache_accepting_name); c->cache_accepting_name = NULL; OPENSSL_free(c->cache_accepting_serv); c->cache_accepting_serv = NULL; OPENSSL_free(c->cache_peer_name); c->cache_peer_name = NULL; OPENSSL_free(c->cache_peer_serv); c->cache_peer_serv = NULL; c->state = ACPT_S_GET_ADDR; break; case ACPT_S_GET_ADDR: { int family = AF_UNSPEC; switch (c->accept_family) { case BIO_FAMILY_IPV6: if (1) { /* This is a trick we use to avoid bit rot. * at least the "else" part will always be * compiled. */ #if OPENSSL_USE_IPV6 family = AF_INET6; } else { #endif ERR_raise(ERR_LIB_BIO, BIO_R_UNAVAILABLE_IP_FAMILY); goto exit_loop; } break; case BIO_FAMILY_IPV4: family = AF_INET; break; case BIO_FAMILY_IPANY: family = AF_UNSPEC; break; default: ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_IP_FAMILY); goto exit_loop; } if (BIO_lookup(c->param_addr, c->param_serv, BIO_LOOKUP_SERVER, family, SOCK_STREAM, &c->addr_first) == 0) goto exit_loop; } if (c->addr_first == NULL) { ERR_raise(ERR_LIB_BIO, BIO_R_LOOKUP_RETURNED_NOTHING); goto exit_loop; } c->addr_iter = c->addr_first; c->state = ACPT_S_CREATE_SOCKET; break; case ACPT_S_CREATE_SOCKET: ERR_set_mark(); s = BIO_socket(BIO_ADDRINFO_family(c->addr_iter), BIO_ADDRINFO_socktype(c->addr_iter), BIO_ADDRINFO_protocol(c->addr_iter), 0); if (s == (int)INVALID_SOCKET) { if ((c->addr_iter = BIO_ADDRINFO_next(c->addr_iter)) != NULL) { /* * if there are more addresses to try, do that first */ ERR_pop_to_mark(); break; } ERR_clear_last_mark(); ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling socket(%s, %s)", c->param_addr, c->param_serv); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_CREATE_SOCKET); goto exit_loop; } c->accept_sock = s; b->num = s; c->state = ACPT_S_LISTEN; s = -1; break; case ACPT_S_LISTEN: { if (!BIO_listen(c->accept_sock, BIO_ADDRINFO_address(c->addr_iter), c->bind_mode)) { BIO_closesocket(c->accept_sock); goto exit_loop; } } { union BIO_sock_info_u info; info.addr = &c->cache_accepting_addr; if (!BIO_sock_info(c->accept_sock, BIO_SOCK_INFO_ADDRESS, &info)) { BIO_closesocket(c->accept_sock); goto exit_loop; } } c->cache_accepting_name = BIO_ADDR_hostname_string(&c->cache_accepting_addr, 1); c->cache_accepting_serv = BIO_ADDR_service_string(&c->cache_accepting_addr, 1); c->state = ACPT_S_ACCEPT; s = -1; ret = 1; goto end; case ACPT_S_ACCEPT: if (b->next_bio != NULL) { c->state = ACPT_S_OK; break; } BIO_clear_retry_flags(b); b->retry_reason = 0; OPENSSL_free(c->cache_peer_name); c->cache_peer_name = NULL; OPENSSL_free(c->cache_peer_serv); c->cache_peer_serv = NULL; s = BIO_accept_ex(c->accept_sock, &c->cache_peer_addr, c->accepted_mode); /* If the returned socket is invalid, this might still be * retryable */ if (s < 0) { if (BIO_sock_should_retry(s)) { BIO_set_retry_special(b); b->retry_reason = BIO_RR_ACCEPT; goto end; } } /* If it wasn't retryable, we fail */ if (s < 0) { ret = s; goto exit_loop; } bio = BIO_new_socket(s, BIO_CLOSE); if (bio == NULL) goto exit_loop; BIO_set_callback_ex(bio, BIO_get_callback_ex(b)); #ifndef OPENSSL_NO_DEPRECATED_3_0 BIO_set_callback(bio, BIO_get_callback(b)); #endif BIO_set_callback_arg(bio, BIO_get_callback_arg(b)); /* * If the accept BIO has an bio_chain, we dup it and put the new * socket at the end. */ if (c->bio_chain != NULL) { if ((dbio = BIO_dup_chain(c->bio_chain)) == NULL) goto exit_loop; if (!BIO_push(dbio, bio)) goto exit_loop; bio = dbio; } if (BIO_push(b, bio) == NULL) goto exit_loop; c->cache_peer_name = BIO_ADDR_hostname_string(&c->cache_peer_addr, 1); c->cache_peer_serv = BIO_ADDR_service_string(&c->cache_peer_addr, 1); c->state = ACPT_S_OK; bio = NULL; ret = 1; goto end; case ACPT_S_OK: if (b->next_bio == NULL) { c->state = ACPT_S_ACCEPT; break; } ret = 1; goto end; default: ret = 0; goto end; } } exit_loop: if (bio != NULL) BIO_free(bio); else if (s >= 0) BIO_closesocket(s); end: return ret; } static int acpt_read(BIO *b, char *out, int outl) { int ret = 0; BIO_ACCEPT *data; BIO_clear_retry_flags(b); data = (BIO_ACCEPT *)b->ptr; while (b->next_bio == NULL) { ret = acpt_state(b, data); if (ret <= 0) return ret; } ret = BIO_read(b->next_bio, out, outl); BIO_copy_next_retry(b); return ret; } static int acpt_write(BIO *b, const char *in, int inl) { int ret; BIO_ACCEPT *data; BIO_clear_retry_flags(b); data = (BIO_ACCEPT *)b->ptr; while (b->next_bio == NULL) { ret = acpt_state(b, data); if (ret <= 0) return ret; } ret = BIO_write(b->next_bio, in, inl); BIO_copy_next_retry(b); return ret; } static long acpt_ctrl(BIO *b, int cmd, long num, void *ptr) { int *ip; long ret = 1; BIO_ACCEPT *data; char **pp; data = (BIO_ACCEPT *)b->ptr; switch (cmd) { case BIO_CTRL_RESET: ret = 0; data->state = ACPT_S_BEFORE; acpt_close_socket(b); BIO_ADDRINFO_free(data->addr_first); data->addr_first = NULL; b->flags = 0; break; case BIO_C_DO_STATE_MACHINE: /* use this one to start the connection */ ret = (long)acpt_state(b, data); break; case BIO_C_SET_ACCEPT: if (ptr != NULL) { if (num == 0) { char *hold_serv = data->param_serv; /* We affect the hostname regardless. However, the input * string might contain a host:service spec, so we must * parse it, which might or might not affect the service */ OPENSSL_free(data->param_addr); data->param_addr = NULL; ret = BIO_parse_hostserv(ptr, &data->param_addr, &data->param_serv, BIO_PARSE_PRIO_SERV); if (hold_serv != data->param_serv) OPENSSL_free(hold_serv); b->init = 1; } else if (num == 1) { OPENSSL_free(data->param_serv); if ((data->param_serv = OPENSSL_strdup(ptr)) == NULL) ret = 0; else b->init = 1; } else if (num == 2) { data->bind_mode |= BIO_SOCK_NONBLOCK; } else if (num == 3) { BIO_free(data->bio_chain); data->bio_chain = (BIO *)ptr; } else if (num == 4) { data->accept_family = *(int *)ptr; } else if (num == 5) { data->bind_mode |= BIO_SOCK_TFO; } } else { if (num == 2) { data->bind_mode &= ~BIO_SOCK_NONBLOCK; } else if (num == 5) { data->bind_mode &= ~BIO_SOCK_TFO; } } break; case BIO_C_SET_NBIO: if (num != 0) data->accepted_mode |= BIO_SOCK_NONBLOCK; else data->accepted_mode &= ~BIO_SOCK_NONBLOCK; break; case BIO_C_SET_FD: b->num = *((int *)ptr); data->accept_sock = b->num; data->state = ACPT_S_ACCEPT; b->shutdown = (int)num; b->init = 1; break; case BIO_C_GET_FD: if (b->init) { ip = (int *)ptr; if (ip != NULL) *ip = data->accept_sock; ret = data->accept_sock; } else ret = -1; break; case BIO_C_GET_ACCEPT: if (b->init) { if (num == 0 && ptr != NULL) { pp = (char **)ptr; *pp = data->cache_accepting_name; } else if (num == 1 && ptr != NULL) { pp = (char **)ptr; *pp = data->cache_accepting_serv; } else if (num == 2 && ptr != NULL) { pp = (char **)ptr; *pp = data->cache_peer_name; } else if (num == 3 && ptr != NULL) { pp = (char **)ptr; *pp = data->cache_peer_serv; } else if (num == 4) { switch (BIO_ADDRINFO_family(data->addr_iter)) { #if OPENSSL_USE_IPV6 case AF_INET6: ret = BIO_FAMILY_IPV6; break; #endif case AF_INET: ret = BIO_FAMILY_IPV4; break; case 0: ret = data->accept_family; break; default: ret = -1; break; } } else ret = -1; } else ret = -1; break; case BIO_CTRL_GET_CLOSE: ret = b->shutdown; break; case BIO_CTRL_SET_CLOSE: b->shutdown = (int)num; break; case BIO_CTRL_PENDING: case BIO_CTRL_WPENDING: ret = 0; break; case BIO_CTRL_FLUSH: break; case BIO_C_SET_BIND_MODE: data->bind_mode = (int)num; break; case BIO_C_GET_BIND_MODE: ret = (long)data->bind_mode; break; case BIO_CTRL_DUP: break; case BIO_CTRL_EOF: if (b->next_bio == NULL) ret = 0; else ret = BIO_ctrl(b->next_bio, cmd, num, ptr); break; default: ret = 0; break; } return ret; } static int acpt_puts(BIO *bp, const char *str) { int n, ret; n = strlen(str); ret = acpt_write(bp, str, n); return ret; } BIO *BIO_new_accept(const char *str) { BIO *ret; ret = BIO_new(BIO_s_accept()); if (ret == NULL) return NULL; if (BIO_set_accept_name(ret, str) > 0) return ret; BIO_free(ret); return NULL; } #endif
16,761
28
79
c
openssl
openssl-master/crypto/bio/bss_bio.c
/* * Copyright 1999-2022 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 */ /* * Special method for a BIO where the other endpoint is also a BIO of this * kind, handled by the same thread (i.e. the "peer" is actually ourselves, * wearing a different hat). Such "BIO pairs" are mainly for using the SSL * library with I/O interfaces for which no specific BIO method is available. * See ssl/ssltest.c for some hints on how this can be used. */ #include "internal/e_os.h" #include <assert.h> #include <limits.h> #include <stdlib.h> #include <string.h> #include "bio_local.h" #include <openssl/err.h> #include <openssl/crypto.h> static int bio_new(BIO *bio); static int bio_free(BIO *bio); static int bio_read(BIO *bio, char *buf, int size); static int bio_write(BIO *bio, const char *buf, int num); static long bio_ctrl(BIO *bio, int cmd, long num, void *ptr); static int bio_puts(BIO *bio, const char *str); static int bio_make_pair(BIO *bio1, BIO *bio2); static void bio_destroy_pair(BIO *bio); static const BIO_METHOD methods_biop = { BIO_TYPE_BIO, "BIO pair", bwrite_conv, bio_write, bread_conv, bio_read, bio_puts, NULL /* no bio_gets */ , bio_ctrl, bio_new, bio_free, NULL /* no bio_callback_ctrl */ }; const BIO_METHOD *BIO_s_bio(void) { return &methods_biop; } struct bio_bio_st { BIO *peer; /* NULL if buf == NULL. If peer != NULL, then * peer->ptr is also a bio_bio_st, and its * "peer" member points back to us. peer != * NULL iff init != 0 in the BIO. */ /* This is for what we write (i.e. reading uses peer's struct): */ int closed; /* valid iff peer != NULL */ size_t len; /* valid iff buf != NULL; 0 if peer == NULL */ size_t offset; /* valid iff buf != NULL; 0 if len == 0 */ size_t size; char *buf; /* "size" elements (if != NULL) */ size_t request; /* valid iff peer != NULL; 0 if len != 0, * otherwise set by peer to number of bytes * it (unsuccessfully) tried to read, never * more than buffer space (size-len) * warrants. */ }; static int bio_new(BIO *bio) { struct bio_bio_st *b = OPENSSL_zalloc(sizeof(*b)); if (b == NULL) return 0; /* enough for one TLS record (just a default) */ b->size = 17 * 1024; bio->ptr = b; return 1; } static int bio_free(BIO *bio) { struct bio_bio_st *b; if (bio == NULL) return 0; b = bio->ptr; assert(b != NULL); if (b->peer) bio_destroy_pair(bio); OPENSSL_free(b->buf); OPENSSL_free(b); return 1; } static int bio_read(BIO *bio, char *buf, int size_) { size_t size = size_; size_t rest; struct bio_bio_st *b, *peer_b; BIO_clear_retry_flags(bio); if (!bio->init) return 0; b = bio->ptr; assert(b != NULL); assert(b->peer != NULL); peer_b = b->peer->ptr; assert(peer_b != NULL); assert(peer_b->buf != NULL); peer_b->request = 0; /* will be set in "retry_read" situation */ if (buf == NULL || size == 0) return 0; if (peer_b->len == 0) { if (peer_b->closed) return 0; /* writer has closed, and no data is left */ else { BIO_set_retry_read(bio); /* buffer is empty */ if (size <= peer_b->size) peer_b->request = size; else /* * don't ask for more than the peer can deliver in one write */ peer_b->request = peer_b->size; return -1; } } /* we can read */ if (peer_b->len < size) size = peer_b->len; /* now read "size" bytes */ rest = size; assert(rest > 0); do { /* one or two iterations */ size_t chunk; assert(rest <= peer_b->len); if (peer_b->offset + rest <= peer_b->size) chunk = rest; else /* wrap around ring buffer */ chunk = peer_b->size - peer_b->offset; assert(peer_b->offset + chunk <= peer_b->size); memcpy(buf, peer_b->buf + peer_b->offset, chunk); peer_b->len -= chunk; if (peer_b->len) { peer_b->offset += chunk; assert(peer_b->offset <= peer_b->size); if (peer_b->offset == peer_b->size) peer_b->offset = 0; buf += chunk; } else { /* buffer now empty, no need to advance "buf" */ assert(chunk == rest); peer_b->offset = 0; } rest -= chunk; } while (rest); return size; } /*- * non-copying interface: provide pointer to available data in buffer * bio_nread0: return number of available bytes * bio_nread: also advance index * (example usage: bio_nread0(), read from buffer, bio_nread() * or just bio_nread(), read from buffer) */ /* * WARNING: The non-copying interface is largely untested as of yet and may * contain bugs. */ static ossl_ssize_t bio_nread0(BIO *bio, char **buf) { struct bio_bio_st *b, *peer_b; ossl_ssize_t num; BIO_clear_retry_flags(bio); if (!bio->init) return 0; b = bio->ptr; assert(b != NULL); assert(b->peer != NULL); peer_b = b->peer->ptr; assert(peer_b != NULL); assert(peer_b->buf != NULL); peer_b->request = 0; if (peer_b->len == 0) { char dummy; /* avoid code duplication -- nothing available for reading */ return bio_read(bio, &dummy, 1); /* returns 0 or -1 */ } num = peer_b->len; if (peer_b->size < peer_b->offset + num) /* no ring buffer wrap-around for non-copying interface */ num = peer_b->size - peer_b->offset; assert(num > 0); if (buf != NULL) *buf = peer_b->buf + peer_b->offset; return num; } static ossl_ssize_t bio_nread(BIO *bio, char **buf, size_t num_) { struct bio_bio_st *b, *peer_b; ossl_ssize_t num, available; if (num_ > OSSL_SSIZE_MAX) num = OSSL_SSIZE_MAX; else num = (ossl_ssize_t) num_; available = bio_nread0(bio, buf); if (num > available) num = available; if (num <= 0) return num; b = bio->ptr; peer_b = b->peer->ptr; peer_b->len -= num; if (peer_b->len) { peer_b->offset += num; assert(peer_b->offset <= peer_b->size); if (peer_b->offset == peer_b->size) peer_b->offset = 0; } else peer_b->offset = 0; return num; } static int bio_write(BIO *bio, const char *buf, int num_) { size_t num = num_; size_t rest; struct bio_bio_st *b; BIO_clear_retry_flags(bio); if (!bio->init || buf == NULL || num_ <= 0) return 0; b = bio->ptr; assert(b != NULL); assert(b->peer != NULL); assert(b->buf != NULL); b->request = 0; if (b->closed) { /* we already closed */ ERR_raise(ERR_LIB_BIO, BIO_R_BROKEN_PIPE); return -1; } assert(b->len <= b->size); if (b->len == b->size) { BIO_set_retry_write(bio); /* buffer is full */ return -1; } /* we can write */ if (num > b->size - b->len) num = b->size - b->len; /* now write "num" bytes */ rest = num; assert(rest > 0); do { /* one or two iterations */ size_t write_offset; size_t chunk; assert(b->len + rest <= b->size); write_offset = b->offset + b->len; if (write_offset >= b->size) write_offset -= b->size; /* b->buf[write_offset] is the first byte we can write to. */ if (write_offset + rest <= b->size) chunk = rest; else /* wrap around ring buffer */ chunk = b->size - write_offset; memcpy(b->buf + write_offset, buf, chunk); b->len += chunk; assert(b->len <= b->size); rest -= chunk; buf += chunk; } while (rest); return num; } /*- * non-copying interface: provide pointer to region to write to * bio_nwrite0: check how much space is available * bio_nwrite: also increase length * (example usage: bio_nwrite0(), write to buffer, bio_nwrite() * or just bio_nwrite(), write to buffer) */ static ossl_ssize_t bio_nwrite0(BIO *bio, char **buf) { struct bio_bio_st *b; size_t num; size_t write_offset; BIO_clear_retry_flags(bio); if (!bio->init) return 0; b = bio->ptr; assert(b != NULL); assert(b->peer != NULL); assert(b->buf != NULL); b->request = 0; if (b->closed) { ERR_raise(ERR_LIB_BIO, BIO_R_BROKEN_PIPE); return -1; } assert(b->len <= b->size); if (b->len == b->size) { BIO_set_retry_write(bio); return -1; } num = b->size - b->len; write_offset = b->offset + b->len; if (write_offset >= b->size) write_offset -= b->size; if (write_offset + num > b->size) /* * no ring buffer wrap-around for non-copying interface (to fulfil * the promise by BIO_ctrl_get_write_guarantee, BIO_nwrite may have * to be called twice) */ num = b->size - write_offset; if (buf != NULL) *buf = b->buf + write_offset; assert(write_offset + num <= b->size); return num; } static ossl_ssize_t bio_nwrite(BIO *bio, char **buf, size_t num_) { struct bio_bio_st *b; ossl_ssize_t num, space; if (num_ > OSSL_SSIZE_MAX) num = OSSL_SSIZE_MAX; else num = (ossl_ssize_t) num_; space = bio_nwrite0(bio, buf); if (num > space) num = space; if (num <= 0) return num; b = bio->ptr; assert(b != NULL); b->len += num; assert(b->len <= b->size); return num; } static long bio_ctrl(BIO *bio, int cmd, long num, void *ptr) { long ret; struct bio_bio_st *b = bio->ptr; assert(b != NULL); switch (cmd) { /* specific CTRL codes */ case BIO_C_SET_WRITE_BUF_SIZE: if (b->peer) { ERR_raise(ERR_LIB_BIO, BIO_R_IN_USE); ret = 0; } else if (num == 0) { ERR_raise(ERR_LIB_BIO, BIO_R_INVALID_ARGUMENT); ret = 0; } else { size_t new_size = num; if (b->size != new_size) { OPENSSL_free(b->buf); b->buf = NULL; b->size = new_size; } ret = 1; } break; case BIO_C_GET_WRITE_BUF_SIZE: ret = (long)b->size; break; case BIO_C_MAKE_BIO_PAIR: { BIO *other_bio = ptr; if (bio_make_pair(bio, other_bio)) ret = 1; else ret = 0; } break; case BIO_C_DESTROY_BIO_PAIR: /* * Affects both BIOs in the pair -- call just once! Or let * BIO_free(bio1); BIO_free(bio2); do the job. */ bio_destroy_pair(bio); ret = 1; break; case BIO_C_GET_WRITE_GUARANTEE: /* * How many bytes can the caller feed to the next write without * having to keep any? */ if (b->peer == NULL || b->closed) ret = 0; else ret = (long)b->size - b->len; break; case BIO_C_GET_READ_REQUEST: /* * If the peer unsuccessfully tried to read, how many bytes were * requested? (As with BIO_CTRL_PENDING, that number can usually be * treated as boolean.) */ ret = (long)b->request; break; case BIO_C_RESET_READ_REQUEST: /* * Reset request. (Can be useful after read attempts at the other * side that are meant to be non-blocking, e.g. when probing SSL_read * to see if any data is available.) */ b->request = 0; ret = 1; break; case BIO_C_SHUTDOWN_WR: /* similar to shutdown(..., SHUT_WR) */ b->closed = 1; ret = 1; break; case BIO_C_NREAD0: /* prepare for non-copying read */ ret = (long)bio_nread0(bio, ptr); break; case BIO_C_NREAD: /* non-copying read */ ret = (long)bio_nread(bio, ptr, (size_t)num); break; case BIO_C_NWRITE0: /* prepare for non-copying write */ ret = (long)bio_nwrite0(bio, ptr); break; case BIO_C_NWRITE: /* non-copying write */ ret = (long)bio_nwrite(bio, ptr, (size_t)num); break; /* standard CTRL codes follow */ case BIO_CTRL_RESET: if (b->buf != NULL) { b->len = 0; b->offset = 0; } ret = 0; break; case BIO_CTRL_GET_CLOSE: ret = bio->shutdown; break; case BIO_CTRL_SET_CLOSE: bio->shutdown = (int)num; ret = 1; break; case BIO_CTRL_PENDING: if (b->peer != NULL) { struct bio_bio_st *peer_b = b->peer->ptr; ret = (long)peer_b->len; } else ret = 0; break; case BIO_CTRL_WPENDING: if (b->buf != NULL) ret = (long)b->len; else ret = 0; break; case BIO_CTRL_DUP: /* See BIO_dup_chain for circumstances we have to expect. */ { BIO *other_bio = ptr; struct bio_bio_st *other_b; assert(other_bio != NULL); other_b = other_bio->ptr; assert(other_b != NULL); assert(other_b->buf == NULL); /* other_bio is always fresh */ other_b->size = b->size; } ret = 1; break; case BIO_CTRL_FLUSH: ret = 1; break; case BIO_CTRL_EOF: if (b->peer != NULL) { struct bio_bio_st *peer_b = b->peer->ptr; if (peer_b->len == 0 && peer_b->closed) ret = 1; else ret = 0; } else { ret = 1; } break; default: ret = 0; } return ret; } static int bio_puts(BIO *bio, const char *str) { return bio_write(bio, str, strlen(str)); } static int bio_make_pair(BIO *bio1, BIO *bio2) { struct bio_bio_st *b1, *b2; assert(bio1 != NULL); assert(bio2 != NULL); b1 = bio1->ptr; b2 = bio2->ptr; if (b1->peer != NULL || b2->peer != NULL) { ERR_raise(ERR_LIB_BIO, BIO_R_IN_USE); return 0; } if (b1->buf == NULL) { b1->buf = OPENSSL_malloc(b1->size); if (b1->buf == NULL) return 0; b1->len = 0; b1->offset = 0; } if (b2->buf == NULL) { b2->buf = OPENSSL_malloc(b2->size); if (b2->buf == NULL) return 0; b2->len = 0; b2->offset = 0; } b1->peer = bio2; b1->closed = 0; b1->request = 0; b2->peer = bio1; b2->closed = 0; b2->request = 0; bio1->init = 1; bio2->init = 1; return 1; } static void bio_destroy_pair(BIO *bio) { struct bio_bio_st *b = bio->ptr; if (b != NULL) { BIO *peer_bio = b->peer; if (peer_bio != NULL) { struct bio_bio_st *peer_b = peer_bio->ptr; assert(peer_b != NULL); assert(peer_b->peer == bio); peer_b->peer = NULL; peer_bio->init = 0; assert(peer_b->buf != NULL); peer_b->len = 0; peer_b->offset = 0; b->peer = NULL; bio->init = 0; assert(b->buf != NULL); b->len = 0; b->offset = 0; } } } /* Exported convenience functions */ int BIO_new_bio_pair(BIO **bio1_p, size_t writebuf1, BIO **bio2_p, size_t writebuf2) { BIO *bio1 = NULL, *bio2 = NULL; long r; int ret = 0; bio1 = BIO_new(BIO_s_bio()); if (bio1 == NULL) goto err; bio2 = BIO_new(BIO_s_bio()); if (bio2 == NULL) goto err; if (writebuf1) { r = BIO_set_write_buf_size(bio1, writebuf1); if (!r) goto err; } if (writebuf2) { r = BIO_set_write_buf_size(bio2, writebuf2); if (!r) goto err; } r = BIO_make_bio_pair(bio1, bio2); if (!r) goto err; ret = 1; err: if (ret == 0) { BIO_free(bio1); bio1 = NULL; BIO_free(bio2); bio2 = NULL; } *bio1_p = bio1; *bio2_p = bio2; return ret; } size_t BIO_ctrl_get_write_guarantee(BIO *bio) { return BIO_ctrl(bio, BIO_C_GET_WRITE_GUARANTEE, 0, NULL); } size_t BIO_ctrl_get_read_request(BIO *bio) { return BIO_ctrl(bio, BIO_C_GET_READ_REQUEST, 0, NULL); } int BIO_ctrl_reset_read_request(BIO *bio) { return (BIO_ctrl(bio, BIO_C_RESET_READ_REQUEST, 0, NULL) != 0); } /* * BIO_nread0/nread/nwrite0/nwrite are available only for BIO pairs for now * (conceivably some other BIOs could allow non-copying reads and writes * too.) */ int BIO_nread0(BIO *bio, char **buf) { long ret; if (!bio->init) { ERR_raise(ERR_LIB_BIO, BIO_R_UNINITIALIZED); return -2; } ret = BIO_ctrl(bio, BIO_C_NREAD0, 0, buf); if (ret > INT_MAX) return INT_MAX; else return (int)ret; } int BIO_nread(BIO *bio, char **buf, int num) { int ret; if (!bio->init) { ERR_raise(ERR_LIB_BIO, BIO_R_UNINITIALIZED); return -2; } ret = (int)BIO_ctrl(bio, BIO_C_NREAD, num, buf); if (ret > 0) bio->num_read += ret; return ret; } int BIO_nwrite0(BIO *bio, char **buf) { long ret; if (!bio->init) { ERR_raise(ERR_LIB_BIO, BIO_R_UNINITIALIZED); return -2; } ret = BIO_ctrl(bio, BIO_C_NWRITE0, 0, buf); if (ret > INT_MAX) return INT_MAX; else return (int)ret; } int BIO_nwrite(BIO *bio, char **buf, int num) { int ret; if (!bio->init) { ERR_raise(ERR_LIB_BIO, BIO_R_UNINITIALIZED); return -2; } ret = BIO_ctrl(bio, BIO_C_NWRITE, num, buf); if (ret > 0) bio->num_write += ret; return ret; }
18,754
22.356164
78
c
openssl
openssl-master/crypto/bio/bss_conn.c
/* * Copyright 1995-2022 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 */ #include <stdio.h> #include <errno.h> #include "bio_local.h" #include "internal/bio_tfo.h" #include "internal/ktls.h" #ifndef OPENSSL_NO_SOCK typedef struct bio_connect_st { int state; int connect_family; char *param_hostname; char *param_service; int connect_mode; # ifndef OPENSSL_NO_KTLS unsigned char record_type; # endif int tfo_first; BIO_ADDRINFO *addr_first; const BIO_ADDRINFO *addr_iter; /* * int socket; this will be kept in bio->num so that it is compatible * with the bss_sock bio */ /* * called when the connection is initially made callback(BIO,state,ret); * The callback should return 'ret'. state is for compatibility with the * ssl info_callback */ BIO_info_cb *info_callback; } BIO_CONNECT; static int conn_write(BIO *h, const char *buf, int num); static int conn_read(BIO *h, char *buf, int size); static int conn_puts(BIO *h, const char *str); static int conn_gets(BIO *h, char *buf, int size); static long conn_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int conn_new(BIO *h); static int conn_free(BIO *data); static long conn_callback_ctrl(BIO *h, int cmd, BIO_info_cb *); static int conn_state(BIO *b, BIO_CONNECT *c); static void conn_close_socket(BIO *data); BIO_CONNECT *BIO_CONNECT_new(void); void BIO_CONNECT_free(BIO_CONNECT *a); #define BIO_CONN_S_BEFORE 1 #define BIO_CONN_S_GET_ADDR 2 #define BIO_CONN_S_CREATE_SOCKET 3 #define BIO_CONN_S_CONNECT 4 #define BIO_CONN_S_OK 5 #define BIO_CONN_S_BLOCKED_CONNECT 6 #define BIO_CONN_S_CONNECT_ERROR 7 static const BIO_METHOD methods_connectp = { BIO_TYPE_CONNECT, "socket connect", bwrite_conv, conn_write, bread_conv, conn_read, conn_puts, conn_gets, conn_ctrl, conn_new, conn_free, conn_callback_ctrl, }; static int conn_state(BIO *b, BIO_CONNECT *c) { int ret = -1, i; BIO_info_cb *cb = NULL; if (c->info_callback != NULL) cb = c->info_callback; for (;;) { switch (c->state) { case BIO_CONN_S_BEFORE: if (c->param_hostname == NULL && c->param_service == NULL) { ERR_raise_data(ERR_LIB_BIO, BIO_R_NO_HOSTNAME_OR_SERVICE_SPECIFIED, "hostname=%s service=%s", c->param_hostname, c->param_service); goto exit_loop; } c->state = BIO_CONN_S_GET_ADDR; break; case BIO_CONN_S_GET_ADDR: { int family = AF_UNSPEC; switch (c->connect_family) { case BIO_FAMILY_IPV6: if (1) { /* This is a trick we use to avoid bit rot. * at least the "else" part will always be * compiled. */ #if OPENSSL_USE_IPV6 family = AF_INET6; } else { #endif ERR_raise(ERR_LIB_BIO, BIO_R_UNAVAILABLE_IP_FAMILY); goto exit_loop; } break; case BIO_FAMILY_IPV4: family = AF_INET; break; case BIO_FAMILY_IPANY: family = AF_UNSPEC; break; default: ERR_raise(ERR_LIB_BIO, BIO_R_UNSUPPORTED_IP_FAMILY); goto exit_loop; } if (BIO_lookup(c->param_hostname, c->param_service, BIO_LOOKUP_CLIENT, family, SOCK_STREAM, &c->addr_first) == 0) goto exit_loop; } if (c->addr_first == NULL) { ERR_raise(ERR_LIB_BIO, BIO_R_LOOKUP_RETURNED_NOTHING); goto exit_loop; } c->addr_iter = c->addr_first; c->state = BIO_CONN_S_CREATE_SOCKET; break; case BIO_CONN_S_CREATE_SOCKET: ret = BIO_socket(BIO_ADDRINFO_family(c->addr_iter), BIO_ADDRINFO_socktype(c->addr_iter), BIO_ADDRINFO_protocol(c->addr_iter), 0); if (ret == (int)INVALID_SOCKET) { ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling socket(%s, %s)", c->param_hostname, c->param_service); ERR_raise(ERR_LIB_BIO, BIO_R_UNABLE_TO_CREATE_SOCKET); goto exit_loop; } b->num = ret; c->state = BIO_CONN_S_CONNECT; break; case BIO_CONN_S_CONNECT: BIO_clear_retry_flags(b); ERR_set_mark(); ret = BIO_connect(b->num, BIO_ADDRINFO_address(c->addr_iter), BIO_SOCK_KEEPALIVE | c->connect_mode); b->retry_reason = 0; if (ret == 0) { if (BIO_sock_should_retry(ret)) { BIO_set_retry_special(b); c->state = BIO_CONN_S_BLOCKED_CONNECT; b->retry_reason = BIO_RR_CONNECT; ERR_pop_to_mark(); } else if ((c->addr_iter = BIO_ADDRINFO_next(c->addr_iter)) != NULL) { /* * if there are more addresses to try, do that first */ BIO_closesocket(b->num); c->state = BIO_CONN_S_CREATE_SOCKET; ERR_pop_to_mark(); break; } else { ERR_clear_last_mark(); ERR_raise_data(ERR_LIB_SYS, get_last_socket_error(), "calling connect(%s, %s)", c->param_hostname, c->param_service); c->state = BIO_CONN_S_CONNECT_ERROR; break; } goto exit_loop; } else { ERR_clear_last_mark(); c->state = BIO_CONN_S_OK; } break; case BIO_CONN_S_BLOCKED_CONNECT: /* wait for socket being writable, before querying BIO_sock_error */ if (BIO_socket_wait(b->num, 0, time(NULL)) == 0) break; i = BIO_sock_error(b->num); if (i != 0) { BIO_clear_retry_flags(b); if ((c->addr_iter = BIO_ADDRINFO_next(c->addr_iter)) != NULL) { /* * if there are more addresses to try, do that first */ BIO_closesocket(b->num); c->state = BIO_CONN_S_CREATE_SOCKET; break; } ERR_raise_data(ERR_LIB_SYS, i, "calling connect(%s, %s)", c->param_hostname, c->param_service); ERR_raise(ERR_LIB_BIO, BIO_R_NBIO_CONNECT_ERROR); ret = 0; goto exit_loop; } else { c->state = BIO_CONN_S_OK; # ifndef OPENSSL_NO_KTLS /* * The new socket is created successfully regardless of ktls_enable. * ktls_enable doesn't change any functionality of the socket, except * changing the setsockopt to enable the processing of ktls_start. * Thus, it is not a problem to call it for non-TLS sockets. */ ktls_enable(b->num); # endif } break; case BIO_CONN_S_CONNECT_ERROR: ERR_raise(ERR_LIB_BIO, BIO_R_CONNECT_ERROR); ret = 0; goto exit_loop; case BIO_CONN_S_OK: ret = 1; goto exit_loop; default: /* abort(); */ goto exit_loop; } if (cb != NULL) { if ((ret = cb((BIO *)b, c->state, ret)) == 0) goto end; } } /* Loop does not exit */ exit_loop: if (cb != NULL) ret = cb((BIO *)b, c->state, ret); end: return ret; } BIO_CONNECT *BIO_CONNECT_new(void) { BIO_CONNECT *ret; if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) return NULL; ret->state = BIO_CONN_S_BEFORE; ret->connect_family = BIO_FAMILY_IPANY; return ret; } void BIO_CONNECT_free(BIO_CONNECT *a) { if (a == NULL) return; OPENSSL_free(a->param_hostname); OPENSSL_free(a->param_service); BIO_ADDRINFO_free(a->addr_first); OPENSSL_free(a); } const BIO_METHOD *BIO_s_connect(void) { return &methods_connectp; } static int conn_new(BIO *bi) { bi->init = 0; bi->num = (int)INVALID_SOCKET; bi->flags = 0; if ((bi->ptr = (char *)BIO_CONNECT_new()) == NULL) return 0; else return 1; } static void conn_close_socket(BIO *bio) { BIO_CONNECT *c; c = (BIO_CONNECT *)bio->ptr; if (bio->num != (int)INVALID_SOCKET) { /* Only do a shutdown if things were established */ if (c->state == BIO_CONN_S_OK) shutdown(bio->num, 2); BIO_closesocket(bio->num); bio->num = (int)INVALID_SOCKET; } } static int conn_free(BIO *a) { BIO_CONNECT *data; if (a == NULL) return 0; data = (BIO_CONNECT *)a->ptr; if (a->shutdown) { conn_close_socket(a); BIO_CONNECT_free(data); a->ptr = NULL; a->flags = 0; a->init = 0; } return 1; } static int conn_read(BIO *b, char *out, int outl) { int ret = 0; BIO_CONNECT *data; data = (BIO_CONNECT *)b->ptr; if (data->state != BIO_CONN_S_OK) { ret = conn_state(b, data); if (ret <= 0) return ret; } if (out != NULL) { clear_socket_error(); # ifndef OPENSSL_NO_KTLS if (BIO_get_ktls_recv(b)) ret = ktls_read_record(b->num, out, outl); else # endif ret = readsocket(b->num, out, outl); BIO_clear_retry_flags(b); if (ret <= 0) { if (BIO_sock_should_retry(ret)) BIO_set_retry_read(b); else if (ret == 0) b->flags |= BIO_FLAGS_IN_EOF; } } return ret; } static int conn_write(BIO *b, const char *in, int inl) { int ret; BIO_CONNECT *data; data = (BIO_CONNECT *)b->ptr; if (data->state != BIO_CONN_S_OK) { ret = conn_state(b, data); if (ret <= 0) return ret; } clear_socket_error(); # ifndef OPENSSL_NO_KTLS if (BIO_should_ktls_ctrl_msg_flag(b)) { ret = ktls_send_ctrl_message(b->num, data->record_type, in, inl); if (ret >= 0) { ret = inl; BIO_clear_ktls_ctrl_msg_flag(b); } } else # endif # if defined(OSSL_TFO_SENDTO) if (data->tfo_first) { int peerlen = BIO_ADDRINFO_sockaddr_size(data->addr_iter); ret = sendto(b->num, in, inl, OSSL_TFO_SENDTO, BIO_ADDRINFO_sockaddr(data->addr_iter), peerlen); data->tfo_first = 0; } else # endif ret = writesocket(b->num, in, inl); BIO_clear_retry_flags(b); if (ret <= 0) { if (BIO_sock_should_retry(ret)) BIO_set_retry_write(b); } return ret; } static long conn_ctrl(BIO *b, int cmd, long num, void *ptr) { BIO *dbio; int *ip; const char **pptr = NULL; long ret = 1; BIO_CONNECT *data; # ifndef OPENSSL_NO_KTLS ktls_crypto_info_t *crypto_info; # endif data = (BIO_CONNECT *)b->ptr; switch (cmd) { case BIO_CTRL_RESET: ret = 0; data->state = BIO_CONN_S_BEFORE; conn_close_socket(b); BIO_ADDRINFO_free(data->addr_first); data->addr_first = NULL; b->flags = 0; break; case BIO_C_DO_STATE_MACHINE: /* use this one to start the connection */ if (data->state != BIO_CONN_S_OK) ret = (long)conn_state(b, data); else ret = 1; break; case BIO_C_GET_CONNECT: if (ptr != NULL) { pptr = (const char **)ptr; if (num == 0) { *pptr = data->param_hostname; } else if (num == 1) { *pptr = data->param_service; } else if (num == 2) { *pptr = (const char *)BIO_ADDRINFO_address(data->addr_iter); } else if (num == 3) { switch (BIO_ADDRINFO_family(data->addr_iter)) { # if OPENSSL_USE_IPV6 case AF_INET6: ret = BIO_FAMILY_IPV6; break; # endif case AF_INET: ret = BIO_FAMILY_IPV4; break; case 0: ret = data->connect_family; break; default: ret = -1; break; } } else if (num == 4) { ret = data->connect_mode; } else { ret = 0; } } else { ret = 0; } break; case BIO_C_SET_CONNECT: if (ptr != NULL) { b->init = 1; if (num == 0) { /* BIO_set_conn_hostname */ char *hold_service = data->param_service; /* We affect the hostname regardless. However, the input * string might contain a host:service spec, so we must * parse it, which might or might not affect the service */ OPENSSL_free(data->param_hostname); data->param_hostname = NULL; ret = BIO_parse_hostserv(ptr, &data->param_hostname, &data->param_service, BIO_PARSE_PRIO_HOST); if (hold_service != data->param_service) OPENSSL_free(hold_service); } else if (num == 1) { /* BIO_set_conn_port */ OPENSSL_free(data->param_service); if ((data->param_service = OPENSSL_strdup(ptr)) == NULL) ret = 0; } else if (num == 2) { /* BIO_set_conn_address */ const BIO_ADDR *addr = (const BIO_ADDR *)ptr; char *host = BIO_ADDR_hostname_string(addr, 1); char *service = BIO_ADDR_service_string(addr, 1); ret = host != NULL && service != NULL; if (ret) { OPENSSL_free(data->param_hostname); data->param_hostname = host; OPENSSL_free(data->param_service); data->param_service = service; BIO_ADDRINFO_free(data->addr_first); data->addr_first = NULL; data->addr_iter = NULL; } else { OPENSSL_free(host); OPENSSL_free(service); } } else if (num == 3) { /* BIO_set_conn_ip_family */ data->connect_family = *(int *)ptr; } else { ret = 0; } } break; case BIO_C_SET_NBIO: if (num != 0) data->connect_mode |= BIO_SOCK_NONBLOCK; else data->connect_mode &= ~BIO_SOCK_NONBLOCK; break; #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO) case BIO_C_SET_TFO: if (num != 0) { data->connect_mode |= BIO_SOCK_TFO; data->tfo_first = 1; } else { data->connect_mode &= ~BIO_SOCK_TFO; data->tfo_first = 0; } break; #endif case BIO_C_SET_CONNECT_MODE: data->connect_mode = (int)num; if (num & BIO_SOCK_TFO) data->tfo_first = 1; else data->tfo_first = 0; break; case BIO_C_GET_FD: if (b->init) { ip = (int *)ptr; if (ip != NULL) *ip = b->num; ret = b->num; } else ret = -1; break; case BIO_CTRL_GET_CLOSE: ret = b->shutdown; break; case BIO_CTRL_SET_CLOSE: b->shutdown = (int)num; break; case BIO_CTRL_PENDING: case BIO_CTRL_WPENDING: ret = 0; break; case BIO_CTRL_FLUSH: break; case BIO_CTRL_DUP: { dbio = (BIO *)ptr; if (data->param_hostname) BIO_set_conn_hostname(dbio, data->param_hostname); if (data->param_service) BIO_set_conn_port(dbio, data->param_service); BIO_set_conn_ip_family(dbio, data->connect_family); BIO_set_conn_mode(dbio, data->connect_mode); /* * FIXME: the cast of the function seems unlikely to be a good * idea */ (void)BIO_set_info_callback(dbio, data->info_callback); } break; case BIO_CTRL_SET_CALLBACK: ret = 0; /* use callback ctrl */ break; case BIO_CTRL_GET_CALLBACK: { BIO_info_cb **fptr; fptr = (BIO_info_cb **)ptr; *fptr = data->info_callback; } break; case BIO_CTRL_EOF: ret = (b->flags & BIO_FLAGS_IN_EOF) != 0; break; # ifndef OPENSSL_NO_KTLS case BIO_CTRL_SET_KTLS: crypto_info = (ktls_crypto_info_t *)ptr; ret = ktls_start(b->num, crypto_info, num); if (ret) BIO_set_ktls_flag(b, num); break; case BIO_CTRL_GET_KTLS_SEND: return BIO_should_ktls_flag(b, 1) != 0; case BIO_CTRL_GET_KTLS_RECV: return BIO_should_ktls_flag(b, 0) != 0; case BIO_CTRL_SET_KTLS_TX_SEND_CTRL_MSG: BIO_set_ktls_ctrl_msg_flag(b); data->record_type = num; ret = 0; break; case BIO_CTRL_CLEAR_KTLS_TX_CTRL_MSG: BIO_clear_ktls_ctrl_msg_flag(b); ret = 0; break; case BIO_CTRL_SET_KTLS_TX_ZEROCOPY_SENDFILE: ret = ktls_enable_tx_zerocopy_sendfile(b->num); if (ret) BIO_set_ktls_zerocopy_sendfile_flag(b); break; # endif default: ret = 0; break; } return ret; } static long conn_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { long ret = 1; BIO_CONNECT *data; data = (BIO_CONNECT *)b->ptr; switch (cmd) { case BIO_CTRL_SET_CALLBACK: { data->info_callback = fp; } break; default: ret = 0; break; } return ret; } static int conn_puts(BIO *bp, const char *str) { int n, ret; n = strlen(str); ret = conn_write(bp, str, n); return ret; } int conn_gets(BIO *bio, char *buf, int size) { BIO_CONNECT *data; char *ptr = buf; int ret = 0; if (buf == NULL) { ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER); return -1; } if (size <= 0) { ERR_raise(ERR_LIB_BIO, BIO_R_INVALID_ARGUMENT); return -1; } *buf = '\0'; if (bio == NULL || bio->ptr == NULL) { ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER); return -1; } data = (BIO_CONNECT *)bio->ptr; if (data->state != BIO_CONN_S_OK) { ret = conn_state(bio, data); if (ret <= 0) return ret; } clear_socket_error(); while (size-- > 1) { # ifndef OPENSSL_NO_KTLS if (BIO_get_ktls_recv(bio)) ret = ktls_read_record(bio->num, ptr, 1); else # endif ret = readsocket(bio->num, ptr, 1); BIO_clear_retry_flags(bio); if (ret <= 0) { if (BIO_sock_should_retry(ret)) BIO_set_retry_read(bio); else if (ret == 0) bio->flags |= BIO_FLAGS_IN_EOF; break; } if (*ptr++ == '\n') break; } *ptr = '\0'; return ret > 0 || (bio->flags & BIO_FLAGS_IN_EOF) != 0 ? ptr - buf : ret; } BIO *BIO_new_connect(const char *str) { BIO *ret; ret = BIO_new(BIO_s_connect()); if (ret == NULL) return NULL; if (BIO_set_conn_hostname(ret, str)) return ret; BIO_free(ret); return NULL; } #endif
20,836
28.472419
85
c
openssl
openssl-master/crypto/bio/bss_core.c
/* * Copyright 2019-2022 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 */ #include <openssl/core_dispatch.h> #include "bio_local.h" #include "internal/cryptlib.h" #include "crypto/context.h" typedef struct { OSSL_FUNC_BIO_read_ex_fn *c_bio_read_ex; OSSL_FUNC_BIO_write_ex_fn *c_bio_write_ex; OSSL_FUNC_BIO_gets_fn *c_bio_gets; OSSL_FUNC_BIO_puts_fn *c_bio_puts; OSSL_FUNC_BIO_ctrl_fn *c_bio_ctrl; OSSL_FUNC_BIO_up_ref_fn *c_bio_up_ref; OSSL_FUNC_BIO_free_fn *c_bio_free; } BIO_CORE_GLOBALS; void ossl_bio_core_globals_free(void *vbcg) { OPENSSL_free(vbcg); } void *ossl_bio_core_globals_new(OSSL_LIB_CTX *ctx) { return OPENSSL_zalloc(sizeof(BIO_CORE_GLOBALS)); } static ossl_inline BIO_CORE_GLOBALS *get_globals(OSSL_LIB_CTX *libctx) { return ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_BIO_CORE_INDEX); } static int bio_core_read_ex(BIO *bio, char *data, size_t data_len, size_t *bytes_read) { BIO_CORE_GLOBALS *bcgbl = get_globals(bio->libctx); if (bcgbl == NULL || bcgbl->c_bio_read_ex == NULL) return 0; return bcgbl->c_bio_read_ex(BIO_get_data(bio), data, data_len, bytes_read); } static int bio_core_write_ex(BIO *bio, const char *data, size_t data_len, size_t *written) { BIO_CORE_GLOBALS *bcgbl = get_globals(bio->libctx); if (bcgbl == NULL || bcgbl->c_bio_write_ex == NULL) return 0; return bcgbl->c_bio_write_ex(BIO_get_data(bio), data, data_len, written); } static long bio_core_ctrl(BIO *bio, int cmd, long num, void *ptr) { BIO_CORE_GLOBALS *bcgbl = get_globals(bio->libctx); if (bcgbl == NULL || bcgbl->c_bio_ctrl == NULL) return -1; return bcgbl->c_bio_ctrl(BIO_get_data(bio), cmd, num, ptr); } static int bio_core_gets(BIO *bio, char *buf, int size) { BIO_CORE_GLOBALS *bcgbl = get_globals(bio->libctx); if (bcgbl == NULL || bcgbl->c_bio_gets == NULL) return -1; return bcgbl->c_bio_gets(BIO_get_data(bio), buf, size); } static int bio_core_puts(BIO *bio, const char *str) { BIO_CORE_GLOBALS *bcgbl = get_globals(bio->libctx); if (bcgbl == NULL || bcgbl->c_bio_puts == NULL) return -1; return bcgbl->c_bio_puts(BIO_get_data(bio), str); } static int bio_core_new(BIO *bio) { BIO_set_init(bio, 1); return 1; } static int bio_core_free(BIO *bio) { BIO_CORE_GLOBALS *bcgbl = get_globals(bio->libctx); if (bcgbl == NULL) return 0; BIO_set_init(bio, 0); bcgbl->c_bio_free(BIO_get_data(bio)); return 1; } static const BIO_METHOD corebiometh = { BIO_TYPE_CORE_TO_PROV, "BIO to Core filter", bio_core_write_ex, NULL, bio_core_read_ex, NULL, bio_core_puts, bio_core_gets, bio_core_ctrl, bio_core_new, bio_core_free, NULL, }; const BIO_METHOD *BIO_s_core(void) { return &corebiometh; } BIO *BIO_new_from_core_bio(OSSL_LIB_CTX *libctx, OSSL_CORE_BIO *corebio) { BIO *outbio; BIO_CORE_GLOBALS *bcgbl = get_globals(libctx); /* Check the library context has been initialised with the callbacks */ if (bcgbl == NULL || (bcgbl->c_bio_write_ex == NULL && bcgbl->c_bio_read_ex == NULL)) return NULL; if ((outbio = BIO_new_ex(libctx, BIO_s_core())) == NULL) return NULL; if (!bcgbl->c_bio_up_ref(corebio)) { BIO_free(outbio); return NULL; } BIO_set_data(outbio, corebio); return outbio; } int ossl_bio_init_core(OSSL_LIB_CTX *libctx, const OSSL_DISPATCH *fns) { BIO_CORE_GLOBALS *bcgbl = get_globals(libctx); if (bcgbl == NULL) return 0; for (; fns->function_id != 0; fns++) { switch (fns->function_id) { case OSSL_FUNC_BIO_READ_EX: if (bcgbl->c_bio_read_ex == NULL) bcgbl->c_bio_read_ex = OSSL_FUNC_BIO_read_ex(fns); break; case OSSL_FUNC_BIO_WRITE_EX: if (bcgbl->c_bio_write_ex == NULL) bcgbl->c_bio_write_ex = OSSL_FUNC_BIO_write_ex(fns); break; case OSSL_FUNC_BIO_GETS: if (bcgbl->c_bio_gets == NULL) bcgbl->c_bio_gets = OSSL_FUNC_BIO_gets(fns); break; case OSSL_FUNC_BIO_PUTS: if (bcgbl->c_bio_puts == NULL) bcgbl->c_bio_puts = OSSL_FUNC_BIO_puts(fns); break; case OSSL_FUNC_BIO_CTRL: if (bcgbl->c_bio_ctrl == NULL) bcgbl->c_bio_ctrl = OSSL_FUNC_BIO_ctrl(fns); break; case OSSL_FUNC_BIO_UP_REF: if (bcgbl->c_bio_up_ref == NULL) bcgbl->c_bio_up_ref = OSSL_FUNC_BIO_up_ref(fns); break; case OSSL_FUNC_BIO_FREE: if (bcgbl->c_bio_free == NULL) bcgbl->c_bio_free = OSSL_FUNC_BIO_free(fns); break; } } return 1; }
5,131
26.153439
89
c
openssl
openssl-master/crypto/bio/bss_log.c
/* * Copyright 1999-2021 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 */ /* * Why BIO_s_log? * * BIO_s_log is useful for system daemons (or services under NT). It is * one-way BIO, it sends all stuff to syslogd (on system that commonly use * that), or event log (on NT), or OPCOM (on OpenVMS). * */ #include <stdio.h> #include <errno.h> #include "bio_local.h" #include "internal/cryptlib.h" #if defined(OPENSSL_SYS_WINCE) #elif defined(OPENSSL_SYS_WIN32) #elif defined(__wasi__) # define NO_SYSLOG #elif defined(OPENSSL_SYS_VMS) # include <opcdef.h> # include <descrip.h> # include <lib$routines.h> # include <starlet.h> /* Some compiler options may mask the declaration of "_malloc32". */ # if __INITIAL_POINTER_SIZE && defined _ANSI_C_SOURCE # if __INITIAL_POINTER_SIZE == 64 # pragma pointer_size save # pragma pointer_size 32 void *_malloc32(__size_t); # pragma pointer_size restore # endif /* __INITIAL_POINTER_SIZE == 64 */ # endif /* __INITIAL_POINTER_SIZE && defined * _ANSI_C_SOURCE */ #elif defined(__DJGPP__) && defined(OPENSSL_NO_SOCK) # define NO_SYSLOG #elif (!defined(MSDOS) || defined(WATT32)) && !defined(OPENSSL_SYS_VXWORKS) && !defined(NO_SYSLOG) # include <syslog.h> #endif #include <openssl/buffer.h> #include <openssl/err.h> #ifndef NO_SYSLOG # if defined(OPENSSL_SYS_WIN32) # define LOG_EMERG 0 # define LOG_ALERT 1 # define LOG_CRIT 2 # define LOG_ERR 3 # define LOG_WARNING 4 # define LOG_NOTICE 5 # define LOG_INFO 6 # define LOG_DEBUG 7 # define LOG_DAEMON (3<<3) # elif defined(OPENSSL_SYS_VMS) /* On VMS, we don't really care about these, but we need them to compile */ # define LOG_EMERG 0 # define LOG_ALERT 1 # define LOG_CRIT 2 # define LOG_ERR 3 # define LOG_WARNING 4 # define LOG_NOTICE 5 # define LOG_INFO 6 # define LOG_DEBUG 7 # define LOG_DAEMON OPC$M_NM_NTWORK # endif static int slg_write(BIO *h, const char *buf, int num); static int slg_puts(BIO *h, const char *str); static long slg_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int slg_new(BIO *h); static int slg_free(BIO *data); static void xopenlog(BIO *bp, char *name, int level); static void xsyslog(BIO *bp, int priority, const char *string); static void xcloselog(BIO *bp); static const BIO_METHOD methods_slg = { BIO_TYPE_MEM, "syslog", bwrite_conv, slg_write, NULL, /* slg_write_old, */ NULL, /* slg_read, */ slg_puts, NULL, slg_ctrl, slg_new, slg_free, NULL, /* slg_callback_ctrl */ }; const BIO_METHOD *BIO_s_log(void) { return &methods_slg; } static int slg_new(BIO *bi) { bi->init = 1; bi->num = 0; bi->ptr = NULL; xopenlog(bi, "application", LOG_DAEMON); return 1; } static int slg_free(BIO *a) { if (a == NULL) return 0; xcloselog(a); return 1; } static int slg_write(BIO *b, const char *in, int inl) { int ret = inl; char *buf; char *pp; int priority, i; static const struct { int strl; char str[10]; int log_level; } mapping[] = { { 6, "PANIC ", LOG_EMERG }, { 6, "EMERG ", LOG_EMERG }, { 4, "EMR ", LOG_EMERG }, { 6, "ALERT ", LOG_ALERT }, { 4, "ALR ", LOG_ALERT }, { 5, "CRIT ", LOG_CRIT }, { 4, "CRI ", LOG_CRIT }, { 6, "ERROR ", LOG_ERR }, { 4, "ERR ", LOG_ERR }, { 8, "WARNING ", LOG_WARNING }, { 5, "WARN ", LOG_WARNING }, { 4, "WAR ", LOG_WARNING }, { 7, "NOTICE ", LOG_NOTICE }, { 5, "NOTE ", LOG_NOTICE }, { 4, "NOT ", LOG_NOTICE }, { 5, "INFO ", LOG_INFO }, { 4, "INF ", LOG_INFO }, { 6, "DEBUG ", LOG_DEBUG }, { 4, "DBG ", LOG_DEBUG }, { 0, "", LOG_ERR } /* The default */ }; if (inl < 0) return 0; if ((buf = OPENSSL_malloc(inl + 1)) == NULL) return 0; memcpy(buf, in, inl); buf[inl] = '\0'; i = 0; while (strncmp(buf, mapping[i].str, mapping[i].strl) != 0) i++; priority = mapping[i].log_level; pp = buf + mapping[i].strl; xsyslog(b, priority, pp); OPENSSL_free(buf); return ret; } static long slg_ctrl(BIO *b, int cmd, long num, void *ptr) { switch (cmd) { case BIO_CTRL_SET: xcloselog(b); xopenlog(b, ptr, num); break; default: break; } return 0; } static int slg_puts(BIO *bp, const char *str) { int n, ret; n = strlen(str); ret = slg_write(bp, str, n); return ret; } # if defined(OPENSSL_SYS_WIN32) static void xopenlog(BIO *bp, char *name, int level) { if (check_winnt()) bp->ptr = RegisterEventSourceA(NULL, name); else bp->ptr = NULL; } static void xsyslog(BIO *bp, int priority, const char *string) { LPCSTR lpszStrings[2]; WORD evtype = EVENTLOG_ERROR_TYPE; char pidbuf[DECIMAL_SIZE(DWORD) + 4]; if (bp->ptr == NULL) return; switch (priority) { case LOG_EMERG: case LOG_ALERT: case LOG_CRIT: case LOG_ERR: evtype = EVENTLOG_ERROR_TYPE; break; case LOG_WARNING: evtype = EVENTLOG_WARNING_TYPE; break; case LOG_NOTICE: case LOG_INFO: case LOG_DEBUG: evtype = EVENTLOG_INFORMATION_TYPE; break; default: /* * Should never happen, but set it * as error anyway. */ evtype = EVENTLOG_ERROR_TYPE; break; } sprintf(pidbuf, "[%lu] ", GetCurrentProcessId()); lpszStrings[0] = pidbuf; lpszStrings[1] = string; ReportEventA(bp->ptr, evtype, 0, 1024, NULL, 2, 0, lpszStrings, NULL); } static void xcloselog(BIO *bp) { if (bp->ptr) DeregisterEventSource((HANDLE) (bp->ptr)); bp->ptr = NULL; } # elif defined(OPENSSL_SYS_VMS) static int VMS_OPC_target = LOG_DAEMON; static void xopenlog(BIO *bp, char *name, int level) { VMS_OPC_target = level; } static void xsyslog(BIO *bp, int priority, const char *string) { struct dsc$descriptor_s opc_dsc; /* Arrange 32-bit pointer to opcdef buffer and malloc(), if needed. */ # if __INITIAL_POINTER_SIZE == 64 # pragma pointer_size save # pragma pointer_size 32 # define OPCDEF_TYPE __char_ptr32 # define OPCDEF_MALLOC _malloc32 # else /* __INITIAL_POINTER_SIZE == 64 */ # define OPCDEF_TYPE char * # define OPCDEF_MALLOC OPENSSL_malloc # endif /* __INITIAL_POINTER_SIZE == 64 [else] */ struct opcdef *opcdef_p; # if __INITIAL_POINTER_SIZE == 64 # pragma pointer_size restore # endif /* __INITIAL_POINTER_SIZE == 64 */ char buf[10240]; unsigned int len; struct dsc$descriptor_s buf_dsc; $DESCRIPTOR(fao_cmd, "!AZ: !AZ"); char *priority_tag; switch (priority) { case LOG_EMERG: priority_tag = "Emergency"; break; case LOG_ALERT: priority_tag = "Alert"; break; case LOG_CRIT: priority_tag = "Critical"; break; case LOG_ERR: priority_tag = "Error"; break; case LOG_WARNING: priority_tag = "Warning"; break; case LOG_NOTICE: priority_tag = "Notice"; break; case LOG_INFO: priority_tag = "Info"; break; case LOG_DEBUG: priority_tag = "DEBUG"; break; } buf_dsc.dsc$b_dtype = DSC$K_DTYPE_T; buf_dsc.dsc$b_class = DSC$K_CLASS_S; buf_dsc.dsc$a_pointer = buf; buf_dsc.dsc$w_length = sizeof(buf) - 1; lib$sys_fao(&fao_cmd, &len, &buf_dsc, priority_tag, string); /* We know there's an 8-byte header. That's documented. */ opcdef_p = OPCDEF_MALLOC(8 + len); opcdef_p->opc$b_ms_type = OPC$_RQ_RQST; memcpy(opcdef_p->opc$z_ms_target_classes, &VMS_OPC_target, 3); opcdef_p->opc$l_ms_rqstid = 0; memcpy(&opcdef_p->opc$l_ms_text, buf, len); opc_dsc.dsc$b_dtype = DSC$K_DTYPE_T; opc_dsc.dsc$b_class = DSC$K_CLASS_S; opc_dsc.dsc$a_pointer = (OPCDEF_TYPE) opcdef_p; opc_dsc.dsc$w_length = len + 8; sys$sndopr(opc_dsc, 0); OPENSSL_free(opcdef_p); } static void xcloselog(BIO *bp) { } # else /* Unix/Watt32 */ static void xopenlog(BIO *bp, char *name, int level) { # ifdef WATT32 /* djgpp/DOS */ openlog(name, LOG_PID | LOG_CONS | LOG_NDELAY, level); # else openlog(name, LOG_PID | LOG_CONS, level); # endif } static void xsyslog(BIO *bp, int priority, const char *string) { syslog(priority, "%s", string); } static void xcloselog(BIO *bp) { closelog(); } # endif /* Unix */ #else /* NO_SYSLOG */ const BIO_METHOD *BIO_s_log(void) { return NULL; } #endif /* NO_SYSLOG */
9,692
22.188995
98
c
openssl
openssl-master/crypto/bio/bss_mem.c
/* * Copyright 1995-2021 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 */ #include <stdio.h> #include <errno.h> #include "bio_local.h" #include "internal/cryptlib.h" static int mem_write(BIO *h, const char *buf, int num); static int mem_read(BIO *h, char *buf, int size); static int mem_puts(BIO *h, const char *str); static int mem_gets(BIO *h, char *str, int size); static long mem_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int mem_new(BIO *h); static int secmem_new(BIO *h); static int mem_free(BIO *data); static int mem_buf_free(BIO *data); static int mem_buf_sync(BIO *h); static const BIO_METHOD mem_method = { BIO_TYPE_MEM, "memory buffer", bwrite_conv, mem_write, bread_conv, mem_read, mem_puts, mem_gets, mem_ctrl, mem_new, mem_free, NULL, /* mem_callback_ctrl */ }; static const BIO_METHOD secmem_method = { BIO_TYPE_MEM, "secure memory buffer", bwrite_conv, mem_write, bread_conv, mem_read, mem_puts, mem_gets, mem_ctrl, secmem_new, mem_free, NULL, /* mem_callback_ctrl */ }; /* * BIO memory stores buffer and read pointer * however the roles are different for read only BIOs. * In that case the readp just stores the original state * to be used for reset. */ typedef struct bio_buf_mem_st { struct buf_mem_st *buf; /* allocated buffer */ struct buf_mem_st *readp; /* read pointer */ } BIO_BUF_MEM; /* * bio->num is used to hold the value to return on 'empty', if it is 0, * should_retry is not set */ const BIO_METHOD *BIO_s_mem(void) { return &mem_method; } const BIO_METHOD *BIO_s_secmem(void) { return(&secmem_method); } BIO *BIO_new_mem_buf(const void *buf, int len) { BIO *ret; BUF_MEM *b; BIO_BUF_MEM *bb; size_t sz; if (buf == NULL) { ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER); return NULL; } sz = (len < 0) ? strlen(buf) : (size_t)len; if ((ret = BIO_new(BIO_s_mem())) == NULL) return NULL; bb = (BIO_BUF_MEM *)ret->ptr; b = bb->buf; /* Cast away const and trust in the MEM_RDONLY flag. */ b->data = (void *)buf; b->length = sz; b->max = sz; *bb->readp = *bb->buf; ret->flags |= BIO_FLAGS_MEM_RDONLY; /* Since this is static data retrying won't help */ ret->num = 0; return ret; } static int mem_init(BIO *bi, unsigned long flags) { BIO_BUF_MEM *bb = OPENSSL_zalloc(sizeof(*bb)); if (bb == NULL) return 0; if ((bb->buf = BUF_MEM_new_ex(flags)) == NULL) { OPENSSL_free(bb); return 0; } if ((bb->readp = OPENSSL_zalloc(sizeof(*bb->readp))) == NULL) { BUF_MEM_free(bb->buf); OPENSSL_free(bb); return 0; } *bb->readp = *bb->buf; bi->shutdown = 1; bi->init = 1; bi->num = -1; bi->ptr = (char *)bb; return 1; } static int mem_new(BIO *bi) { return mem_init(bi, 0L); } static int secmem_new(BIO *bi) { return mem_init(bi, BUF_MEM_FLAG_SECURE); } static int mem_free(BIO *a) { BIO_BUF_MEM *bb; if (a == NULL) return 0; bb = (BIO_BUF_MEM *)a->ptr; if (!mem_buf_free(a)) return 0; OPENSSL_free(bb->readp); OPENSSL_free(bb); return 1; } static int mem_buf_free(BIO *a) { if (a == NULL) return 0; if (a->shutdown && a->init && a->ptr != NULL) { BIO_BUF_MEM *bb = (BIO_BUF_MEM *)a->ptr; BUF_MEM *b = bb->buf; if (a->flags & BIO_FLAGS_MEM_RDONLY) b->data = NULL; BUF_MEM_free(b); } return 1; } /* * Reallocate memory buffer if read pointer differs * NOT FOR RDONLY */ static int mem_buf_sync(BIO *b) { if (b != NULL && b->init != 0 && b->ptr != NULL) { BIO_BUF_MEM *bbm = (BIO_BUF_MEM *)b->ptr; if (bbm->readp->data != bbm->buf->data) { memmove(bbm->buf->data, bbm->readp->data, bbm->readp->length); bbm->buf->length = bbm->readp->length; bbm->readp->data = bbm->buf->data; } } return 0; } static int mem_read(BIO *b, char *out, int outl) { int ret = -1; BIO_BUF_MEM *bbm = (BIO_BUF_MEM *)b->ptr; BUF_MEM *bm = bbm->readp; if (b->flags & BIO_FLAGS_MEM_RDONLY) bm = bbm->buf; BIO_clear_retry_flags(b); ret = (outl >= 0 && (size_t)outl > bm->length) ? (int)bm->length : outl; if ((out != NULL) && (ret > 0)) { memcpy(out, bm->data, ret); bm->length -= ret; bm->max -= ret; bm->data += ret; } else if (bm->length == 0) { ret = b->num; if (ret != 0) BIO_set_retry_read(b); } return ret; } static int mem_write(BIO *b, const char *in, int inl) { int ret = -1; int blen; BIO_BUF_MEM *bbm = (BIO_BUF_MEM *)b->ptr; if (b->flags & BIO_FLAGS_MEM_RDONLY) { ERR_raise(ERR_LIB_BIO, BIO_R_WRITE_TO_READ_ONLY_BIO); goto end; } BIO_clear_retry_flags(b); if (inl == 0) return 0; if (in == NULL) { ERR_raise(ERR_LIB_BIO, ERR_R_PASSED_NULL_PARAMETER); goto end; } blen = bbm->readp->length; mem_buf_sync(b); if (BUF_MEM_grow_clean(bbm->buf, blen + inl) == 0) goto end; memcpy(bbm->buf->data + blen, in, inl); *bbm->readp = *bbm->buf; ret = inl; end: return ret; } static long mem_ctrl(BIO *b, int cmd, long num, void *ptr) { long ret = 1; char **pptr; BIO_BUF_MEM *bbm = (BIO_BUF_MEM *)b->ptr; BUF_MEM *bm, *bo; /* bio_mem, bio_other */ long off, remain; if (b->flags & BIO_FLAGS_MEM_RDONLY) { bm = bbm->buf; bo = bbm->readp; } else { bm = bbm->readp; bo = bbm->buf; } off = (bm->data == bo->data) ? 0 : bm->data - bo->data; remain = bm->length; switch (cmd) { case BIO_CTRL_RESET: bm = bbm->buf; if (bm->data != NULL) { if (!(b->flags & BIO_FLAGS_MEM_RDONLY)) { if (!(b->flags & BIO_FLAGS_NONCLEAR_RST)) { memset(bm->data, 0, bm->max); bm->length = 0; } *bbm->readp = *bbm->buf; } else { /* For read only case just reset to the start again */ *bbm->buf = *bbm->readp; } } break; case BIO_C_FILE_SEEK: if (num < 0 || num > off + remain) return -1; /* Can't see outside of the current buffer */ bm->data = (num != 0) ? bo->data + num : bo->data; bm->length = bo->length - num; bm->max = bo->max - num; off = num; /* FALLTHRU */ case BIO_C_FILE_TELL: ret = off; break; case BIO_CTRL_EOF: ret = (long)(bm->length == 0); break; case BIO_C_SET_BUF_MEM_EOF_RETURN: b->num = (int)num; break; case BIO_CTRL_INFO: ret = (long)bm->length; if (ptr != NULL) { pptr = (char **)ptr; *pptr = (char *)(bm->data); } break; case BIO_C_SET_BUF_MEM: mem_buf_free(b); b->shutdown = (int)num; bbm->buf = ptr; *bbm->readp = *bbm->buf; break; case BIO_C_GET_BUF_MEM_PTR: if (ptr != NULL) { if (!(b->flags & BIO_FLAGS_MEM_RDONLY)) mem_buf_sync(b); bm = bbm->buf; pptr = (char **)ptr; *pptr = (char *)bm; } break; case BIO_CTRL_GET_CLOSE: ret = (long)b->shutdown; break; case BIO_CTRL_SET_CLOSE: b->shutdown = (int)num; break; case BIO_CTRL_WPENDING: ret = 0L; break; case BIO_CTRL_PENDING: ret = (long)bm->length; break; case BIO_CTRL_DUP: case BIO_CTRL_FLUSH: ret = 1; break; case BIO_CTRL_PUSH: case BIO_CTRL_POP: default: ret = 0; break; } return ret; } static int mem_gets(BIO *bp, char *buf, int size) { int i, j; int ret = -1; char *p; BIO_BUF_MEM *bbm = (BIO_BUF_MEM *)bp->ptr; BUF_MEM *bm = bbm->readp; if (bp->flags & BIO_FLAGS_MEM_RDONLY) bm = bbm->buf; BIO_clear_retry_flags(bp); j = bm->length; if ((size - 1) < j) j = size - 1; if (j <= 0) { *buf = '\0'; return 0; } p = bm->data; for (i = 0; i < j; i++) { if (p[i] == '\n') { i++; break; } } /* * i is now the max num of bytes to copy, either j or up to * and including the first newline */ i = mem_read(bp, buf, i); if (i > 0) buf[i] = '\0'; ret = i; return ret; } static int mem_puts(BIO *bp, const char *str) { int n, ret; n = strlen(str); ret = mem_write(bp, str, n); /* memory semantics is that it will always work */ return ret; }
9,191
22.690722
76
c
openssl
openssl-master/crypto/bio/bss_null.c
/* * Copyright 1995-2021 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 */ #include <stdio.h> #include <errno.h> #include "bio_local.h" #include "internal/cryptlib.h" static int null_write(BIO *h, const char *buf, int num); static int null_read(BIO *h, char *buf, int size); static int null_puts(BIO *h, const char *str); static int null_gets(BIO *h, char *str, int size); static long null_ctrl(BIO *h, int cmd, long arg1, void *arg2); static const BIO_METHOD null_method = { BIO_TYPE_NULL, "NULL", bwrite_conv, null_write, bread_conv, null_read, null_puts, null_gets, null_ctrl, NULL, NULL, NULL, /* null_callback_ctrl */ }; const BIO_METHOD *BIO_s_null(void) { return &null_method; } static int null_read(BIO *b, char *out, int outl) { return 0; } static int null_write(BIO *b, const char *in, int inl) { return inl; } static long null_ctrl(BIO *b, int cmd, long num, void *ptr) { long ret = 1; switch (cmd) { case BIO_CTRL_RESET: case BIO_CTRL_EOF: case BIO_CTRL_SET: case BIO_CTRL_SET_CLOSE: case BIO_CTRL_FLUSH: case BIO_CTRL_DUP: ret = 1; break; case BIO_CTRL_GET_CLOSE: case BIO_CTRL_INFO: case BIO_CTRL_GET: case BIO_CTRL_PENDING: case BIO_CTRL_WPENDING: default: ret = 0; break; } return ret; } static int null_gets(BIO *bp, char *buf, int size) { return 0; } static int null_puts(BIO *bp, const char *str) { if (str == NULL) return 0; return strlen(str); }
1,833
20.325581
74
c
openssl
openssl-master/crypto/bio/bss_sock.c
/* * Copyright 1995-2022 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 */ #include <stdio.h> #include <errno.h> #include "bio_local.h" #include "internal/bio_tfo.h" #include "internal/cryptlib.h" #include "internal/ktls.h" #ifndef OPENSSL_NO_SOCK # include <openssl/bio.h> # ifdef WATT32 /* Watt-32 uses same names */ # undef sock_write # undef sock_read # undef sock_puts # define sock_write SockWrite # define sock_read SockRead # define sock_puts SockPuts # endif struct bss_sock_st { BIO_ADDR tfo_peer; int tfo_first; #ifndef OPENSSL_NO_KTLS unsigned char ktls_record_type; #endif }; static int sock_write(BIO *h, const char *buf, int num); static int sock_read(BIO *h, char *buf, int size); static int sock_puts(BIO *h, const char *str); static long sock_ctrl(BIO *h, int cmd, long arg1, void *arg2); static int sock_new(BIO *h); static int sock_free(BIO *data); int BIO_sock_should_retry(int s); static const BIO_METHOD methods_sockp = { BIO_TYPE_SOCKET, "socket", bwrite_conv, sock_write, bread_conv, sock_read, sock_puts, NULL, /* sock_gets, */ sock_ctrl, sock_new, sock_free, NULL, /* sock_callback_ctrl */ }; const BIO_METHOD *BIO_s_socket(void) { return &methods_sockp; } BIO *BIO_new_socket(int fd, int close_flag) { BIO *ret; ret = BIO_new(BIO_s_socket()); if (ret == NULL) return NULL; BIO_set_fd(ret, fd, close_flag); # ifndef OPENSSL_NO_KTLS { /* * The new socket is created successfully regardless of ktls_enable. * ktls_enable doesn't change any functionality of the socket, except * changing the setsockopt to enable the processing of ktls_start. * Thus, it is not a problem to call it for non-TLS sockets. */ ktls_enable(fd); } # endif return ret; } static int sock_new(BIO *bi) { bi->init = 0; bi->num = 0; bi->flags = 0; bi->ptr = OPENSSL_zalloc(sizeof(struct bss_sock_st)); if (bi->ptr == NULL) return 0; return 1; } static int sock_free(BIO *a) { if (a == NULL) return 0; if (a->shutdown) { if (a->init) { BIO_closesocket(a->num); } a->init = 0; a->flags = 0; } OPENSSL_free(a->ptr); a->ptr = NULL; return 1; } static int sock_read(BIO *b, char *out, int outl) { int ret = 0; if (out != NULL) { clear_socket_error(); # ifndef OPENSSL_NO_KTLS if (BIO_get_ktls_recv(b)) ret = ktls_read_record(b->num, out, outl); else # endif ret = readsocket(b->num, out, outl); BIO_clear_retry_flags(b); if (ret <= 0) { if (BIO_sock_should_retry(ret)) BIO_set_retry_read(b); else if (ret == 0) b->flags |= BIO_FLAGS_IN_EOF; } } return ret; } static int sock_write(BIO *b, const char *in, int inl) { int ret = 0; # if !defined(OPENSSL_NO_KTLS) || defined(OSSL_TFO_SENDTO) struct bss_sock_st *data = (struct bss_sock_st *)b->ptr; # endif clear_socket_error(); # ifndef OPENSSL_NO_KTLS if (BIO_should_ktls_ctrl_msg_flag(b)) { unsigned char record_type = data->ktls_record_type; ret = ktls_send_ctrl_message(b->num, record_type, in, inl); if (ret >= 0) { ret = inl; BIO_clear_ktls_ctrl_msg_flag(b); } } else # endif # if defined(OSSL_TFO_SENDTO) if (data->tfo_first) { struct bss_sock_st *data = (struct bss_sock_st *)b->ptr; socklen_t peerlen = BIO_ADDR_sockaddr_size(&data->tfo_peer); ret = sendto(b->num, in, inl, OSSL_TFO_SENDTO, BIO_ADDR_sockaddr(&data->tfo_peer), peerlen); data->tfo_first = 0; } else # endif ret = writesocket(b->num, in, inl); BIO_clear_retry_flags(b); if (ret <= 0) { if (BIO_sock_should_retry(ret)) BIO_set_retry_write(b); } return ret; } static long sock_ctrl(BIO *b, int cmd, long num, void *ptr) { long ret = 1; int *ip; struct bss_sock_st *data = (struct bss_sock_st *)b->ptr; # ifndef OPENSSL_NO_KTLS ktls_crypto_info_t *crypto_info; # endif switch (cmd) { case BIO_C_SET_FD: /* minimal sock_free() */ if (b->shutdown) { if (b->init) BIO_closesocket(b->num); b->flags = 0; } b->num = *((int *)ptr); b->shutdown = (int)num; b->init = 1; data->tfo_first = 0; memset(&data->tfo_peer, 0, sizeof(data->tfo_peer)); break; case BIO_C_GET_FD: if (b->init) { ip = (int *)ptr; if (ip != NULL) *ip = b->num; ret = b->num; } else ret = -1; break; case BIO_CTRL_GET_CLOSE: ret = b->shutdown; break; case BIO_CTRL_SET_CLOSE: b->shutdown = (int)num; break; case BIO_CTRL_DUP: case BIO_CTRL_FLUSH: ret = 1; break; # ifndef OPENSSL_NO_KTLS case BIO_CTRL_SET_KTLS: crypto_info = (ktls_crypto_info_t *)ptr; ret = ktls_start(b->num, crypto_info, num); if (ret) BIO_set_ktls_flag(b, num); break; case BIO_CTRL_GET_KTLS_SEND: return BIO_should_ktls_flag(b, 1) != 0; case BIO_CTRL_GET_KTLS_RECV: return BIO_should_ktls_flag(b, 0) != 0; case BIO_CTRL_SET_KTLS_TX_SEND_CTRL_MSG: BIO_set_ktls_ctrl_msg_flag(b); data->ktls_record_type = (unsigned char)num; ret = 0; break; case BIO_CTRL_CLEAR_KTLS_TX_CTRL_MSG: BIO_clear_ktls_ctrl_msg_flag(b); ret = 0; break; case BIO_CTRL_SET_KTLS_TX_ZEROCOPY_SENDFILE: ret = ktls_enable_tx_zerocopy_sendfile(b->num); if (ret) BIO_set_ktls_zerocopy_sendfile_flag(b); break; # endif case BIO_CTRL_EOF: ret = (b->flags & BIO_FLAGS_IN_EOF) != 0; break; case BIO_C_GET_CONNECT: if (ptr != NULL && num == 2) { const char **pptr = (const char **)ptr; *pptr = (const char *)&data->tfo_peer; } else { ret = 0; } break; case BIO_C_SET_CONNECT: if (ptr != NULL && num == 2) { ret = BIO_ADDR_make(&data->tfo_peer, BIO_ADDR_sockaddr((const BIO_ADDR *)ptr)); if (ret) data->tfo_first = 1; } else { ret = 0; } break; default: ret = 0; break; } return ret; } static int sock_puts(BIO *bp, const char *str) { int n, ret; n = strlen(str); ret = sock_write(bp, str, n); return ret; } int BIO_sock_should_retry(int i) { int err; if ((i == 0) || (i == -1)) { err = get_last_socket_error(); return BIO_sock_non_fatal_error(err); } return 0; } int BIO_sock_non_fatal_error(int err) { switch (err) { # if defined(OPENSSL_SYS_WINDOWS) # if defined(WSAEWOULDBLOCK) case WSAEWOULDBLOCK: # endif # endif # ifdef EWOULDBLOCK # ifdef WSAEWOULDBLOCK # if WSAEWOULDBLOCK != EWOULDBLOCK case EWOULDBLOCK: # endif # else case EWOULDBLOCK: # endif # endif # if defined(ENOTCONN) case ENOTCONN: # endif # ifdef EINTR case EINTR: # endif # ifdef EAGAIN # if EWOULDBLOCK != EAGAIN case EAGAIN: # endif # endif # ifdef EPROTO case EPROTO: # endif # ifdef EINPROGRESS case EINPROGRESS: # endif # ifdef EALREADY case EALREADY: # endif return 1; default: break; } return 0; } #endif /* #ifndef OPENSSL_NO_SOCK */
8,025
22.196532
77
c
openssl
openssl-master/crypto/bio/ossl_core_bio.c
/* * Copyright 2021 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 */ #include <openssl/core.h> #include "bio_local.h" /*- * Core BIO structure * This is distinct from a BIO to prevent casting between the two which could * lead to versioning problems. */ struct ossl_core_bio_st { CRYPTO_REF_COUNT ref_cnt; BIO *bio; }; static OSSL_CORE_BIO *core_bio_new(void) { OSSL_CORE_BIO *cb = OPENSSL_malloc(sizeof(*cb)); if (cb == NULL || !CRYPTO_NEW_REF(&cb->ref_cnt, 1)) { OPENSSL_free(cb); return NULL; } return cb; } int ossl_core_bio_up_ref(OSSL_CORE_BIO *cb) { int ref = 0; return CRYPTO_UP_REF(&cb->ref_cnt, &ref); } int ossl_core_bio_free(OSSL_CORE_BIO *cb) { int ref = 0, res = 1; if (cb != NULL) { CRYPTO_DOWN_REF(&cb->ref_cnt, &ref); if (ref <= 0) { res = BIO_free(cb->bio); CRYPTO_FREE_REF(&cb->ref_cnt); OPENSSL_free(cb); } } return res; } OSSL_CORE_BIO *ossl_core_bio_new_from_bio(BIO *bio) { OSSL_CORE_BIO *cb = core_bio_new(); if (cb == NULL || !BIO_up_ref(bio)) { ossl_core_bio_free(cb); return NULL; } cb->bio = bio; return cb; } static OSSL_CORE_BIO *core_bio_new_from_new_bio(BIO *bio) { OSSL_CORE_BIO *cb = NULL; if (bio == NULL) return NULL; if ((cb = core_bio_new()) == NULL) { BIO_free(bio); return NULL; } cb->bio = bio; return cb; } OSSL_CORE_BIO *ossl_core_bio_new_file(const char *filename, const char *mode) { return core_bio_new_from_new_bio(BIO_new_file(filename, mode)); } OSSL_CORE_BIO *ossl_core_bio_new_mem_buf(const void *buf, int len) { return core_bio_new_from_new_bio(BIO_new_mem_buf(buf, len)); } int ossl_core_bio_read_ex(OSSL_CORE_BIO *cb, void *data, size_t dlen, size_t *readbytes) { return BIO_read_ex(cb->bio, data, dlen, readbytes); } int ossl_core_bio_write_ex(OSSL_CORE_BIO *cb, const void *data, size_t dlen, size_t *written) { return BIO_write_ex(cb->bio, data, dlen, written); } int ossl_core_bio_gets(OSSL_CORE_BIO *cb, char *buf, int size) { return BIO_gets(cb->bio, buf, size); } int ossl_core_bio_puts(OSSL_CORE_BIO *cb, const char *buf) { return BIO_puts(cb->bio, buf); } long ossl_core_bio_ctrl(OSSL_CORE_BIO *cb, int cmd, long larg, void *parg) { return BIO_ctrl(cb->bio, cmd, larg, parg); } int ossl_core_bio_vprintf(OSSL_CORE_BIO *cb, const char *format, va_list args) { return BIO_vprintf(cb->bio, format, args); }
2,846
22.146341
78
c
openssl
openssl-master/crypto/bn/bn_blind.c
/* * Copyright 1998-2021 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 */ #include <openssl/opensslconf.h> #include "internal/cryptlib.h" #include "bn_local.h" #define BN_BLINDING_COUNTER 32 struct bn_blinding_st { BIGNUM *A; BIGNUM *Ai; BIGNUM *e; BIGNUM *mod; /* just a reference */ CRYPTO_THREAD_ID tid; int counter; unsigned long flags; BN_MONT_CTX *m_ctx; int (*bn_mod_exp) (BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); CRYPTO_RWLOCK *lock; }; BN_BLINDING *BN_BLINDING_new(const BIGNUM *A, const BIGNUM *Ai, BIGNUM *mod) { BN_BLINDING *ret = NULL; bn_check_top(mod); if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) return NULL; ret->lock = CRYPTO_THREAD_lock_new(); if (ret->lock == NULL) { ERR_raise(ERR_LIB_BN, ERR_R_CRYPTO_LIB); OPENSSL_free(ret); return NULL; } BN_BLINDING_set_current_thread(ret); if (A != NULL) { if ((ret->A = BN_dup(A)) == NULL) goto err; } if (Ai != NULL) { if ((ret->Ai = BN_dup(Ai)) == NULL) goto err; } /* save a copy of mod in the BN_BLINDING structure */ if ((ret->mod = BN_dup(mod)) == NULL) goto err; if (BN_get_flags(mod, BN_FLG_CONSTTIME) != 0) BN_set_flags(ret->mod, BN_FLG_CONSTTIME); /* * Set the counter to the special value -1 to indicate that this is * never-used fresh blinding that does not need updating before first * use. */ ret->counter = -1; return ret; err: BN_BLINDING_free(ret); return NULL; } void BN_BLINDING_free(BN_BLINDING *r) { if (r == NULL) return; BN_free(r->A); BN_free(r->Ai); BN_free(r->e); BN_free(r->mod); CRYPTO_THREAD_lock_free(r->lock); OPENSSL_free(r); } int BN_BLINDING_update(BN_BLINDING *b, BN_CTX *ctx) { int ret = 0; if ((b->A == NULL) || (b->Ai == NULL)) { ERR_raise(ERR_LIB_BN, BN_R_NOT_INITIALIZED); goto err; } if (b->counter == -1) b->counter = 0; if (++b->counter == BN_BLINDING_COUNTER && b->e != NULL && !(b->flags & BN_BLINDING_NO_RECREATE)) { /* re-create blinding parameters */ if (!BN_BLINDING_create_param(b, NULL, NULL, ctx, NULL, NULL)) goto err; } else if (!(b->flags & BN_BLINDING_NO_UPDATE)) { if (b->m_ctx != NULL) { if (!bn_mul_mont_fixed_top(b->Ai, b->Ai, b->Ai, b->m_ctx, ctx) || !bn_mul_mont_fixed_top(b->A, b->A, b->A, b->m_ctx, ctx)) goto err; } else { if (!BN_mod_mul(b->Ai, b->Ai, b->Ai, b->mod, ctx) || !BN_mod_mul(b->A, b->A, b->A, b->mod, ctx)) goto err; } } ret = 1; err: if (b->counter == BN_BLINDING_COUNTER) b->counter = 0; return ret; } int BN_BLINDING_convert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx) { return BN_BLINDING_convert_ex(n, NULL, b, ctx); } int BN_BLINDING_convert_ex(BIGNUM *n, BIGNUM *r, BN_BLINDING *b, BN_CTX *ctx) { int ret = 1; bn_check_top(n); if ((b->A == NULL) || (b->Ai == NULL)) { ERR_raise(ERR_LIB_BN, BN_R_NOT_INITIALIZED); return 0; } if (b->counter == -1) /* Fresh blinding, doesn't need updating. */ b->counter = 0; else if (!BN_BLINDING_update(b, ctx)) return 0; if (r != NULL && (BN_copy(r, b->Ai) == NULL)) return 0; if (b->m_ctx != NULL) ret = BN_mod_mul_montgomery(n, n, b->A, b->m_ctx, ctx); else ret = BN_mod_mul(n, n, b->A, b->mod, ctx); return ret; } int BN_BLINDING_invert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx) { return BN_BLINDING_invert_ex(n, NULL, b, ctx); } int BN_BLINDING_invert_ex(BIGNUM *n, const BIGNUM *r, BN_BLINDING *b, BN_CTX *ctx) { int ret; bn_check_top(n); if (r == NULL && (r = b->Ai) == NULL) { ERR_raise(ERR_LIB_BN, BN_R_NOT_INITIALIZED); return 0; } if (b->m_ctx != NULL) { /* ensure that BN_mod_mul_montgomery takes pre-defined path */ if (n->dmax >= r->top) { size_t i, rtop = r->top, ntop = n->top; BN_ULONG mask; for (i = 0; i < rtop; i++) { mask = (BN_ULONG)0 - ((i - ntop) >> (8 * sizeof(i) - 1)); n->d[i] &= mask; } mask = (BN_ULONG)0 - ((rtop - ntop) >> (8 * sizeof(ntop) - 1)); /* always true, if (rtop >= ntop) n->top = r->top; */ n->top = (int)(rtop & ~mask) | (ntop & mask); n->flags |= (BN_FLG_FIXED_TOP & ~mask); } ret = bn_mul_mont_fixed_top(n, n, r, b->m_ctx, ctx); bn_correct_top_consttime(n); } else { ret = BN_mod_mul(n, n, r, b->mod, ctx); } bn_check_top(n); return ret; } int BN_BLINDING_is_current_thread(BN_BLINDING *b) { return CRYPTO_THREAD_compare_id(CRYPTO_THREAD_get_current_id(), b->tid); } void BN_BLINDING_set_current_thread(BN_BLINDING *b) { b->tid = CRYPTO_THREAD_get_current_id(); } int BN_BLINDING_lock(BN_BLINDING *b) { return CRYPTO_THREAD_write_lock(b->lock); } int BN_BLINDING_unlock(BN_BLINDING *b) { return CRYPTO_THREAD_unlock(b->lock); } unsigned long BN_BLINDING_get_flags(const BN_BLINDING *b) { return b->flags; } void BN_BLINDING_set_flags(BN_BLINDING *b, unsigned long flags) { b->flags = flags; } BN_BLINDING *BN_BLINDING_create_param(BN_BLINDING *b, const BIGNUM *e, BIGNUM *m, BN_CTX *ctx, int (*bn_mod_exp) (BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx), BN_MONT_CTX *m_ctx) { int retry_counter = 32; BN_BLINDING *ret = NULL; if (b == NULL) ret = BN_BLINDING_new(NULL, NULL, m); else ret = b; if (ret == NULL) goto err; if (ret->A == NULL && (ret->A = BN_new()) == NULL) goto err; if (ret->Ai == NULL && (ret->Ai = BN_new()) == NULL) goto err; if (e != NULL) { BN_free(ret->e); ret->e = BN_dup(e); } if (ret->e == NULL) goto err; if (bn_mod_exp != NULL) ret->bn_mod_exp = bn_mod_exp; if (m_ctx != NULL) ret->m_ctx = m_ctx; do { int rv; if (!BN_priv_rand_range_ex(ret->A, ret->mod, 0, ctx)) goto err; if (int_bn_mod_inverse(ret->Ai, ret->A, ret->mod, ctx, &rv)) break; /* * this should almost never happen for good RSA keys */ if (!rv) goto err; if (retry_counter-- == 0) { ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_ITERATIONS); goto err; } } while (1); if (ret->bn_mod_exp != NULL && ret->m_ctx != NULL) { if (!ret->bn_mod_exp(ret->A, ret->A, ret->e, ret->mod, ctx, ret->m_ctx)) goto err; } else { if (!BN_mod_exp(ret->A, ret->A, ret->e, ret->mod, ctx)) goto err; } if (ret->m_ctx != NULL) { if (!bn_to_mont_fixed_top(ret->Ai, ret->Ai, ret->m_ctx, ctx) || !bn_to_mont_fixed_top(ret->A, ret->A, ret->m_ctx, ctx)) goto err; } return ret; err: if (b == NULL) { BN_BLINDING_free(ret); ret = NULL; } return ret; }
8,056
24.823718
80
c
openssl
openssl-master/crypto/bn/bn_const.c
/* * Copyright 2005-2021 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 */ #include <openssl/bn.h> #include "crypto/bn_dh.h" #define COPY_BN(dst, src) (dst != NULL) ? BN_copy(dst, &src) : BN_dup(&src) /*- * "First Oakley Default Group" from RFC2409, section 6.1. * * The prime is: 2^768 - 2 ^704 - 1 + 2^64 * { [2^638 pi] + 149686 } * * RFC2409 specifies a generator of 2. * RFC2412 specifies a generator of 22. */ BIGNUM *BN_get_rfc2409_prime_768(BIGNUM *bn) { static const unsigned char RFC2409_PRIME_768[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x3A, 0x36, 0x20, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }; return BN_bin2bn(RFC2409_PRIME_768, sizeof(RFC2409_PRIME_768), bn); } /*- * "Second Oakley Default Group" from RFC2409, section 6.2. * * The prime is: 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }. * * RFC2409 specifies a generator of 2. * RFC2412 specifies a generator of 22. */ BIGNUM *BN_get_rfc2409_prime_1024(BIGNUM *bn) { static const unsigned char RFC2409_PRIME_1024[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE6, 0x53, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }; return BN_bin2bn(RFC2409_PRIME_1024, sizeof(RFC2409_PRIME_1024), bn); } /*- * "1536-bit MODP Group" from RFC3526, Section 2. * * The prime is: 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 } * * RFC3526 specifies a generator of 2. * RFC2312 specifies a generator of 22. */ BIGNUM *BN_get_rfc3526_prime_1536(BIGNUM *bn) { return COPY_BN(bn, ossl_bignum_modp_1536_p); } /*- * "2048-bit MODP Group" from RFC3526, Section 3. * * The prime is: 2^2048 - 2^1984 - 1 + 2^64 * { [2^1918 pi] + 124476 } * * RFC3526 specifies a generator of 2. */ BIGNUM *BN_get_rfc3526_prime_2048(BIGNUM *bn) { return COPY_BN(bn, ossl_bignum_modp_2048_p); } /*- * "3072-bit MODP Group" from RFC3526, Section 4. * * The prime is: 2^3072 - 2^3008 - 1 + 2^64 * { [2^2942 pi] + 1690314 } * * RFC3526 specifies a generator of 2. */ BIGNUM *BN_get_rfc3526_prime_3072(BIGNUM *bn) { return COPY_BN(bn, ossl_bignum_modp_3072_p); } /*- * "4096-bit MODP Group" from RFC3526, Section 5. * * The prime is: 2^4096 - 2^4032 - 1 + 2^64 * { [2^3966 pi] + 240904 } * * RFC3526 specifies a generator of 2. */ BIGNUM *BN_get_rfc3526_prime_4096(BIGNUM *bn) { return COPY_BN(bn, ossl_bignum_modp_4096_p); } /*- * "6144-bit MODP Group" from RFC3526, Section 6. * * The prime is: 2^6144 - 2^6080 - 1 + 2^64 * { [2^6014 pi] + 929484 } * * RFC3526 specifies a generator of 2. */ BIGNUM *BN_get_rfc3526_prime_6144(BIGNUM *bn) { return COPY_BN(bn, ossl_bignum_modp_6144_p); } /*- * "8192-bit MODP Group" from RFC3526, Section 7. * * The prime is: 2^8192 - 2^8128 - 1 + 2^64 * { [2^8062 pi] + 4743158 } * * RFC3526 specifies a generator of 2. */ BIGNUM *BN_get_rfc3526_prime_8192(BIGNUM *bn) { return COPY_BN(bn, ossl_bignum_modp_8192_p); }
4,543
28.506494
75
c
openssl
openssl-master/crypto/bn/bn_conv.c
/* * Copyright 1995-2020 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 */ #include <openssl/err.h> #include "crypto/ctype.h" #include "bn_local.h" static const char Hex[] = "0123456789ABCDEF"; /* Must 'OPENSSL_free' the returned data */ char *BN_bn2hex(const BIGNUM *a) { int i, j, v, z = 0; char *buf; char *p; if (BN_is_zero(a)) return OPENSSL_strdup("0"); buf = OPENSSL_malloc(a->top * BN_BYTES * 2 + 2); if (buf == NULL) goto err; p = buf; if (a->neg) *p++ = '-'; for (i = a->top - 1; i >= 0; i--) { for (j = BN_BITS2 - 8; j >= 0; j -= 8) { /* strip leading zeros */ v = (int)((a->d[i] >> j) & 0xff); if (z || v != 0) { *p++ = Hex[v >> 4]; *p++ = Hex[v & 0x0f]; z = 1; } } } *p = '\0'; err: return buf; } #ifndef FIPS_MODULE /* No BIO_snprintf in FIPS_MODULE */ /* Must 'OPENSSL_free' the returned data */ char *BN_bn2dec(const BIGNUM *a) { int i = 0, num, ok = 0, n, tbytes; char *buf = NULL; char *p; BIGNUM *t = NULL; BN_ULONG *bn_data = NULL, *lp; int bn_data_num; /*- * get an upper bound for the length of the decimal integer * num <= (BN_num_bits(a) + 1) * log(2) * <= 3 * BN_num_bits(a) * 0.101 + log(2) + 1 (rounding error) * <= 3 * BN_num_bits(a) / 10 + 3 * BN_num_bits / 1000 + 1 + 1 */ i = BN_num_bits(a) * 3; num = (i / 10 + i / 1000 + 1) + 1; tbytes = num + 3; /* negative and terminator and one spare? */ bn_data_num = num / BN_DEC_NUM + 1; bn_data = OPENSSL_malloc(bn_data_num * sizeof(BN_ULONG)); buf = OPENSSL_malloc(tbytes); if (buf == NULL || bn_data == NULL) goto err; if ((t = BN_dup(a)) == NULL) goto err; p = buf; lp = bn_data; if (BN_is_zero(t)) { *p++ = '0'; *p++ = '\0'; } else { if (BN_is_negative(t)) *p++ = '-'; while (!BN_is_zero(t)) { if (lp - bn_data >= bn_data_num) goto err; *lp = BN_div_word(t, BN_DEC_CONV); if (*lp == (BN_ULONG)-1) goto err; lp++; } lp--; /* * We now have a series of blocks, BN_DEC_NUM chars in length, where * the last one needs truncation. The blocks need to be reversed in * order. */ n = BIO_snprintf(p, tbytes - (size_t)(p - buf), BN_DEC_FMT1, *lp); if (n < 0) goto err; p += n; while (lp != bn_data) { lp--; n = BIO_snprintf(p, tbytes - (size_t)(p - buf), BN_DEC_FMT2, *lp); if (n < 0) goto err; p += n; } } ok = 1; err: OPENSSL_free(bn_data); BN_free(t); if (ok) return buf; OPENSSL_free(buf); return NULL; } #endif int BN_hex2bn(BIGNUM **bn, const char *a) { BIGNUM *ret = NULL; BN_ULONG l = 0; int neg = 0, h, m, i, j, k, c; int num; if (a == NULL || *a == '\0') return 0; if (*a == '-') { neg = 1; a++; } for (i = 0; i <= INT_MAX / 4 && ossl_isxdigit(a[i]); i++) continue; if (i == 0 || i > INT_MAX / 4) return 0; num = i + neg; if (bn == NULL) return num; /* a is the start of the hex digits, and it is 'i' long */ if (*bn == NULL) { if ((ret = BN_new()) == NULL) return 0; } else { ret = *bn; if (BN_get_flags(ret, BN_FLG_STATIC_DATA)) { ERR_raise(ERR_LIB_BN, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } BN_zero(ret); } /* i is the number of hex digits */ if (bn_expand(ret, i * 4) == NULL) goto err; j = i; /* least significant 'hex' */ m = 0; h = 0; while (j > 0) { m = (BN_BYTES * 2 <= j) ? BN_BYTES * 2 : j; l = 0; for (;;) { c = a[j - m]; k = OPENSSL_hexchar2int(c); if (k < 0) k = 0; /* paranoia */ l = (l << 4) | k; if (--m <= 0) { ret->d[h++] = l; break; } } j -= BN_BYTES * 2; } ret->top = h; bn_correct_top(ret); *bn = ret; bn_check_top(ret); /* Don't set the negative flag if it's zero. */ if (ret->top != 0) ret->neg = neg; return num; err: if (*bn == NULL) BN_free(ret); return 0; } int BN_dec2bn(BIGNUM **bn, const char *a) { BIGNUM *ret = NULL; BN_ULONG l = 0; int neg = 0, i, j; int num; if (a == NULL || *a == '\0') return 0; if (*a == '-') { neg = 1; a++; } for (i = 0; i <= INT_MAX / 4 && ossl_isdigit(a[i]); i++) continue; if (i == 0 || i > INT_MAX / 4) goto err; num = i + neg; if (bn == NULL) return num; /* * a is the start of the digits, and it is 'i' long. We chop it into * BN_DEC_NUM digits at a time */ if (*bn == NULL) { if ((ret = BN_new()) == NULL) return 0; } else { ret = *bn; BN_zero(ret); } /* i is the number of digits, a bit of an over expand */ if (bn_expand(ret, i * 4) == NULL) goto err; j = BN_DEC_NUM - i % BN_DEC_NUM; if (j == BN_DEC_NUM) j = 0; l = 0; while (--i >= 0) { l *= 10; l += *a - '0'; a++; if (++j == BN_DEC_NUM) { if (!BN_mul_word(ret, BN_DEC_CONV) || !BN_add_word(ret, l)) goto err; l = 0; j = 0; } } bn_correct_top(ret); *bn = ret; bn_check_top(ret); /* Don't set the negative flag if it's zero. */ if (ret->top != 0) ret->neg = neg; return num; err: if (*bn == NULL) BN_free(ret); return 0; } int BN_asc2bn(BIGNUM **bn, const char *a) { const char *p = a; if (*p == '-') p++; if (p[0] == '0' && (p[1] == 'X' || p[1] == 'x')) { if (!BN_hex2bn(bn, p + 2)) return 0; } else { if (!BN_dec2bn(bn, p)) return 0; } /* Don't set the negative flag if it's zero. */ if (*a == '-' && (*bn)->top != 0) (*bn)->neg = 1; return 1; }
6,705
22.284722
78
c
openssl
openssl-master/crypto/bn/bn_ctx.c
/* * Copyright 2000-2021 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 */ #include <openssl/trace.h> #include "internal/cryptlib.h" #include "bn_local.h" /* How many bignums are in each "pool item"; */ #define BN_CTX_POOL_SIZE 16 /* The stack frame info is resizing, set a first-time expansion size; */ #define BN_CTX_START_FRAMES 32 /***********/ /* BN_POOL */ /***********/ /* A bundle of bignums that can be linked with other bundles */ typedef struct bignum_pool_item { /* The bignum values */ BIGNUM vals[BN_CTX_POOL_SIZE]; /* Linked-list admin */ struct bignum_pool_item *prev, *next; } BN_POOL_ITEM; /* A linked-list of bignums grouped in bundles */ typedef struct bignum_pool { /* Linked-list admin */ BN_POOL_ITEM *head, *current, *tail; /* Stack depth and allocation size */ unsigned used, size; } BN_POOL; static void BN_POOL_init(BN_POOL *); static void BN_POOL_finish(BN_POOL *); static BIGNUM *BN_POOL_get(BN_POOL *, int); static void BN_POOL_release(BN_POOL *, unsigned int); /************/ /* BN_STACK */ /************/ /* A wrapper to manage the "stack frames" */ typedef struct bignum_ctx_stack { /* Array of indexes into the bignum stack */ unsigned int *indexes; /* Number of stack frames, and the size of the allocated array */ unsigned int depth, size; } BN_STACK; static void BN_STACK_init(BN_STACK *); static void BN_STACK_finish(BN_STACK *); static int BN_STACK_push(BN_STACK *, unsigned int); static unsigned int BN_STACK_pop(BN_STACK *); /**********/ /* BN_CTX */ /**********/ /* The opaque BN_CTX type */ struct bignum_ctx { /* The bignum bundles */ BN_POOL pool; /* The "stack frames", if you will */ BN_STACK stack; /* The number of bignums currently assigned */ unsigned int used; /* Depth of stack overflow */ int err_stack; /* Block "gets" until an "end" (compatibility behaviour) */ int too_many; /* Flags. */ int flags; /* The library context */ OSSL_LIB_CTX *libctx; }; #ifndef FIPS_MODULE /* 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; BIO_printf(channel, "%s\n", text); BIO_printf(channel, " (%16p): ", (void*)ctx); while (bnidx < ctx->used) { BIO_printf(channel, "%03x ", item->vals[bnidx++ % BN_CTX_POOL_SIZE].dmax); if (!(bnidx % BN_CTX_POOL_SIZE)) item = item->next; } BIO_printf(channel, "\n"); bnidx = 0; BIO_printf(channel, " %16s : ", ""); while (fpidx < stack->depth) { while (bnidx++ < stack->indexes[fpidx]) BIO_printf(channel, " "); BIO_printf(channel, "^^^ "); bnidx++; fpidx++; } BIO_printf(channel, "\n"); } # define CTXDBG(str, ctx) \ OSSL_TRACE_BEGIN(BN_CTX) { \ ctxdbg(trc_out, str, ctx); \ } OSSL_TRACE_END(BN_CTX) #else /* We do not want tracing in FIPS module */ # define CTXDBG(str, ctx) do {} while(0) #endif /* FIPS_MODULE */ BN_CTX *BN_CTX_new_ex(OSSL_LIB_CTX *ctx) { BN_CTX *ret; if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) return NULL; /* Initialise the structure */ BN_POOL_init(&ret->pool); BN_STACK_init(&ret->stack); ret->libctx = ctx; return ret; } #ifndef FIPS_MODULE BN_CTX *BN_CTX_new(void) { return BN_CTX_new_ex(NULL); } #endif BN_CTX *BN_CTX_secure_new_ex(OSSL_LIB_CTX *ctx) { BN_CTX *ret = BN_CTX_new_ex(ctx); if (ret != NULL) ret->flags = BN_FLG_SECURE; return ret; } #ifndef FIPS_MODULE BN_CTX *BN_CTX_secure_new(void) { return BN_CTX_secure_new_ex(NULL); } #endif void BN_CTX_free(BN_CTX *ctx) { if (ctx == NULL) return; #ifndef FIPS_MODULE OSSL_TRACE_BEGIN(BN_CTX) { BN_POOL_ITEM *pool = ctx->pool.head; 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) BIO_printf(trc_out, "%02x ", pool->vals[loop++].dmax); pool = pool->next; } BIO_printf(trc_out, "\n"); } OSSL_TRACE_END(BN_CTX); #endif BN_STACK_finish(&ctx->stack); BN_POOL_finish(&ctx->pool); OPENSSL_free(ctx); } void BN_CTX_start(BN_CTX *ctx) { CTXDBG("ENTER BN_CTX_start()", ctx); /* If we're already overflowing ... */ if (ctx->err_stack || ctx->too_many) ctx->err_stack++; /* (Try to) get a new frame pointer */ else if (!BN_STACK_push(&ctx->stack, ctx->used)) { ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_TEMPORARY_VARIABLES); ctx->err_stack++; } CTXDBG("LEAVE BN_CTX_start()", ctx); } void BN_CTX_end(BN_CTX *ctx) { if (ctx == NULL) return; CTXDBG("ENTER BN_CTX_end()", ctx); if (ctx->err_stack) ctx->err_stack--; else { unsigned int fp = BN_STACK_pop(&ctx->stack); /* Does this stack frame have anything to release? */ if (fp < ctx->used) BN_POOL_release(&ctx->pool, ctx->used - fp); ctx->used = fp; /* Unjam "too_many" in case "get" had failed */ ctx->too_many = 0; } CTXDBG("LEAVE BN_CTX_end()", ctx); } BIGNUM *BN_CTX_get(BN_CTX *ctx) { BIGNUM *ret; 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) { /* * Setting too_many prevents repeated "get" attempts from cluttering * the error stack. */ ctx->too_many = 1; ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_TEMPORARY_VARIABLES); return NULL; } /* 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++; CTXDBG("LEAVE BN_CTX_get()", ctx); return ret; } OSSL_LIB_CTX *ossl_bn_get_libctx(BN_CTX *ctx) { if (ctx == NULL) return NULL; return ctx->libctx; } /************/ /* BN_STACK */ /************/ static void BN_STACK_init(BN_STACK *st) { st->indexes = NULL; st->depth = st->size = 0; } static void BN_STACK_finish(BN_STACK *st) { OPENSSL_free(st->indexes); st->indexes = NULL; } static int BN_STACK_push(BN_STACK *st, unsigned int idx) { if (st->depth == st->size) { /* Need to expand */ unsigned int newsize = st->size ? (st->size * 3 / 2) : BN_CTX_START_FRAMES; unsigned int *newitems; if ((newitems = OPENSSL_malloc(sizeof(*newitems) * newsize)) == NULL) return 0; if (st->depth) memcpy(newitems, st->indexes, sizeof(*newitems) * st->depth); OPENSSL_free(st->indexes); st->indexes = newitems; st->size = newsize; } st->indexes[(st->depth)++] = idx; return 1; } static unsigned int BN_STACK_pop(BN_STACK *st) { return st->indexes[--(st->depth)]; } /***********/ /* BN_POOL */ /***********/ static void BN_POOL_init(BN_POOL *p) { p->head = p->current = p->tail = NULL; p->used = p->size = 0; } static void BN_POOL_finish(BN_POOL *p) { unsigned int loop; BIGNUM *bn; while (p->head) { for (loop = 0, bn = p->head->vals; loop++ < BN_CTX_POOL_SIZE; bn++) if (bn->d) BN_clear_free(bn); p->current = p->head->next; OPENSSL_free(p->head); p->head = p->current; } } static BIGNUM *BN_POOL_get(BN_POOL *p, int flag) { BIGNUM *bn; unsigned int loop; /* Full; allocate a new pool item and link it in. */ if (p->used == p->size) { BN_POOL_ITEM *item; if ((item = OPENSSL_malloc(sizeof(*item))) == NULL) return NULL; for (loop = 0, bn = item->vals; loop++ < BN_CTX_POOL_SIZE; bn++) { bn_init(bn); if ((flag & BN_FLG_SECURE) != 0) BN_set_flags(bn, BN_FLG_SECURE); } item->prev = p->tail; item->next = NULL; if (p->head == NULL) p->head = p->current = p->tail = item; else { p->tail->next = item; p->tail = item; p->current = item; } p->size += BN_CTX_POOL_SIZE; p->used++; /* Return the first bignum from the new pool */ return item->vals; } if (!p->used) p->current = p->head; else if ((p->used % BN_CTX_POOL_SIZE) == 0) p->current = p->current->next; return p->current->vals + ((p->used++) % BN_CTX_POOL_SIZE); } static void BN_POOL_release(BN_POOL *p, unsigned int num) { unsigned int offset = (p->used - 1) % BN_CTX_POOL_SIZE; p->used -= num; while (num--) { bn_check_top(p->current->vals + offset); if (offset == 0) { offset = BN_CTX_POOL_SIZE - 1; p->current = p->current->prev; } else offset--; } }
9,461
24.923288
77
c
openssl
openssl-master/crypto/bn/bn_depr.c
/* * Copyright 2002-2021 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 */ /* * Support for deprecated functions goes here - static linkage will only * slurp this code if applications are using them directly. */ #include <openssl/opensslconf.h> #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include "bn_local.h" BIGNUM *BN_generate_prime(BIGNUM *ret, int bits, int safe, const BIGNUM *add, const BIGNUM *rem, void (*callback) (int, int, void *), void *cb_arg) { BN_GENCB cb; BIGNUM *rnd = NULL; BN_GENCB_set_old(&cb, callback, cb_arg); if (ret == NULL) { if ((rnd = BN_new()) == NULL) goto err; } else rnd = ret; if (!BN_generate_prime_ex(rnd, bits, safe, add, rem, &cb)) goto err; /* we have a prime :-) */ return rnd; err: BN_free(rnd); return NULL; } int BN_is_prime(const BIGNUM *a, int checks, void (*callback) (int, int, void *), BN_CTX *ctx_passed, void *cb_arg) { BN_GENCB cb; BN_GENCB_set_old(&cb, callback, cb_arg); return ossl_bn_check_prime(a, checks, ctx_passed, 0, &cb); } int BN_is_prime_fasttest(const BIGNUM *a, int checks, void (*callback) (int, int, void *), BN_CTX *ctx_passed, void *cb_arg, int do_trial_division) { BN_GENCB cb; BN_GENCB_set_old(&cb, callback, cb_arg); return ossl_bn_check_prime(a, checks, ctx_passed, do_trial_division, &cb); }
1,824
27.515625
78
c
openssl
openssl-master/crypto/bn/bn_div.c
/* * Copyright 1995-2022 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 */ #include <assert.h> #include <openssl/bn.h> #include "internal/cryptlib.h" #include "bn_local.h" /* The old slow way */ #if 0 int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, const BIGNUM *d, BN_CTX *ctx) { int i, nm, nd; int ret = 0; BIGNUM *D; bn_check_top(m); bn_check_top(d); if (BN_is_zero(d)) { ERR_raise(ERR_LIB_BN, BN_R_DIV_BY_ZERO); return 0; } if (BN_ucmp(m, d) < 0) { if (rem != NULL) { if (BN_copy(rem, m) == NULL) return 0; } if (dv != NULL) BN_zero(dv); return 1; } BN_CTX_start(ctx); D = BN_CTX_get(ctx); if (dv == NULL) dv = BN_CTX_get(ctx); if (rem == NULL) rem = BN_CTX_get(ctx); if (D == NULL || dv == NULL || rem == NULL) goto end; nd = BN_num_bits(d); nm = BN_num_bits(m); if (BN_copy(D, d) == NULL) goto end; if (BN_copy(rem, m) == NULL) goto end; /* * The next 2 are needed so we can do a dv->d[0]|=1 later since * BN_lshift1 will only work once there is a value :-) */ BN_zero(dv); if (bn_wexpand(dv, 1) == NULL) goto end; dv->top = 1; if (!BN_lshift(D, D, nm - nd)) goto end; for (i = nm - nd; i >= 0; i--) { if (!BN_lshift1(dv, dv)) goto end; if (BN_ucmp(rem, D) >= 0) { dv->d[0] |= 1; if (!BN_usub(rem, rem, D)) goto end; } /* CAN IMPROVE (and have now :=) */ if (!BN_rshift1(D, D)) goto end; } rem->neg = BN_is_zero(rem) ? 0 : m->neg; dv->neg = m->neg ^ d->neg; ret = 1; end: BN_CTX_end(ctx); return ret; } #else # if defined(BN_DIV3W) BN_ULONG bn_div_3_words(const BN_ULONG *m, BN_ULONG d1, BN_ULONG d0); # elif 0 /* * This is #if-ed away, because it's a reference for assembly implementations, * where it can and should be made constant-time. But if you want to test it, * just replace 0 with 1. */ # if BN_BITS2 == 64 && defined(__SIZEOF_INT128__) && __SIZEOF_INT128__==16 # undef BN_ULLONG # define BN_ULLONG uint128_t # define BN_LLONG # endif # ifdef BN_LLONG # define BN_DIV3W /* * Interface is somewhat quirky, |m| is pointer to most significant limb, * and less significant limb is referred at |m[-1]|. This means that caller * is responsible for ensuring that |m[-1]| is valid. Second condition that * has to be met is that |d0|'s most significant bit has to be set. Or in * other words divisor has to be "bit-aligned to the left." bn_div_fixed_top * does all this. The subroutine considers four limbs, two of which are * "overlapping," hence the name... */ static BN_ULONG bn_div_3_words(const BN_ULONG *m, BN_ULONG d1, BN_ULONG d0) { BN_ULLONG R = ((BN_ULLONG)m[0] << BN_BITS2) | m[-1]; BN_ULLONG D = ((BN_ULLONG)d0 << BN_BITS2) | d1; BN_ULONG Q = 0, mask; int i; for (i = 0; i < BN_BITS2; i++) { Q <<= 1; if (R >= D) { Q |= 1; R -= D; } D >>= 1; } mask = 0 - (Q >> (BN_BITS2 - 1)); /* does it overflow? */ Q <<= 1; Q |= (R >= D); return (Q | mask) & BN_MASK2; } # endif # endif static int bn_left_align(BIGNUM *num) { BN_ULONG *d = num->d, n, m, rmask; int top = num->top; int rshift = BN_num_bits_word(d[top - 1]), lshift, i; lshift = BN_BITS2 - rshift; rshift %= BN_BITS2; /* say no to undefined behaviour */ rmask = (BN_ULONG)0 - rshift; /* rmask = 0 - (rshift != 0) */ rmask |= rmask >> 8; for (i = 0, m = 0; i < top; i++) { n = d[i]; d[i] = ((n << lshift) | m) & BN_MASK2; m = (n >> rshift) & rmask; } return lshift; } # if !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) \ && !defined(PEDANTIC) && !defined(BN_DIV3W) # if defined(__GNUC__) && __GNUC__>=2 # if defined(__i386) || defined (__i386__) /*- * There were two reasons for implementing this template: * - GNU C generates a call to a function (__udivdi3 to be exact) * in reply to ((((BN_ULLONG)n0)<<BN_BITS2)|n1)/d0 (I fail to * understand why...); * - divl doesn't only calculate quotient, but also leaves * remainder in %edx which we can definitely use here:-) */ # undef bn_div_words # define bn_div_words(n0,n1,d0) \ ({ asm volatile ( \ "divl %4" \ : "=a"(q), "=d"(rem) \ : "a"(n1), "d"(n0), "r"(d0) \ : "cc"); \ q; \ }) # define REMAINDER_IS_ALREADY_CALCULATED # elif defined(__x86_64) && defined(SIXTY_FOUR_BIT_LONG) /* * Same story here, but it's 128-bit by 64-bit division. Wow! */ # undef bn_div_words # define bn_div_words(n0,n1,d0) \ ({ asm volatile ( \ "divq %4" \ : "=a"(q), "=d"(rem) \ : "a"(n1), "d"(n0), "r"(d0) \ : "cc"); \ q; \ }) # define REMAINDER_IS_ALREADY_CALCULATED # endif /* __<cpu> */ # endif /* __GNUC__ */ # endif /* OPENSSL_NO_ASM */ /*- * BN_div computes dv := num / divisor, rounding towards * zero, and sets up rm such that dv*divisor + rm = num holds. * Thus: * dv->neg == num->neg ^ divisor->neg (unless the result is zero) * rm->neg == num->neg (unless the remainder is zero) * If 'dv' or 'rm' is NULL, the respective value is not returned. */ int BN_div(BIGNUM *dv, BIGNUM *rm, const BIGNUM *num, const BIGNUM *divisor, BN_CTX *ctx) { int ret; if (BN_is_zero(divisor)) { ERR_raise(ERR_LIB_BN, BN_R_DIV_BY_ZERO); return 0; } /* * Invalid zero-padding would have particularly bad consequences so don't * just rely on bn_check_top() here (bn_check_top() works only for * BN_DEBUG builds) */ if (divisor->d[divisor->top - 1] == 0) { ERR_raise(ERR_LIB_BN, BN_R_NOT_INITIALIZED); return 0; } ret = bn_div_fixed_top(dv, rm, num, divisor, ctx); if (ret) { if (dv != NULL) bn_correct_top(dv); if (rm != NULL) bn_correct_top(rm); } return ret; } /* * It's argued that *length* of *significant* part of divisor is public. * Even if it's private modulus that is. Again, *length* is assumed * public, but not *value*. Former is likely to be pre-defined by * algorithm with bit granularity, though below subroutine is invariant * of limb length. Thanks to this assumption we can require that |divisor| * may not be zero-padded, yet claim this subroutine "constant-time"(*). * This is because zero-padded dividend, |num|, is tolerated, so that * caller can pass dividend of public length(*), but with smaller amount * of significant limbs. This naturally means that quotient, |dv|, would * contain correspongly less significant limbs as well, and will be zero- * padded accordingly. Returned remainder, |rm|, will have same bit length * as divisor, also zero-padded if needed. These actually leave sign bits * in ambiguous state. In sense that we try to avoid negative zeros, while * zero-padded zeros would retain sign. * * (*) "Constant-time-ness" has two pre-conditions: * * - availability of constant-time bn_div_3_words; * - dividend is at least as "wide" as divisor, limb-wise, zero-padded * if so required, which shouldn't be a privacy problem, because * divisor's length is considered public; */ int bn_div_fixed_top(BIGNUM *dv, BIGNUM *rm, const BIGNUM *num, const BIGNUM *divisor, BN_CTX *ctx) { int norm_shift, i, j, loop; BIGNUM *tmp, *snum, *sdiv, *res; BN_ULONG *resp, *wnum, *wnumtop; BN_ULONG d0, d1; int num_n, div_n, num_neg; assert(divisor->top > 0 && divisor->d[divisor->top - 1] != 0); bn_check_top(num); bn_check_top(divisor); bn_check_top(dv); bn_check_top(rm); BN_CTX_start(ctx); res = (dv == NULL) ? BN_CTX_get(ctx) : dv; tmp = BN_CTX_get(ctx); snum = BN_CTX_get(ctx); sdiv = BN_CTX_get(ctx); if (sdiv == NULL) goto err; /* First we normalise the numbers */ if (!BN_copy(sdiv, divisor)) goto err; norm_shift = bn_left_align(sdiv); sdiv->neg = 0; /* * Note that bn_lshift_fixed_top's output is always one limb longer * than input, even when norm_shift is zero. This means that amount of * inner loop iterations is invariant of dividend value, and that one * doesn't need to compare dividend and divisor if they were originally * of the same bit length. */ if (!(bn_lshift_fixed_top(snum, num, norm_shift))) goto err; div_n = sdiv->top; num_n = snum->top; if (num_n <= div_n) { /* caller didn't pad dividend -> no constant-time guarantee... */ if (bn_wexpand(snum, div_n + 1) == NULL) goto err; memset(&(snum->d[num_n]), 0, (div_n - num_n + 1) * sizeof(BN_ULONG)); snum->top = num_n = div_n + 1; } loop = num_n - div_n; /* * Lets setup a 'window' into snum This is the part that corresponds to * the current 'area' being divided */ wnum = &(snum->d[loop]); wnumtop = &(snum->d[num_n - 1]); /* Get the top 2 words of sdiv */ d0 = sdiv->d[div_n - 1]; d1 = (div_n == 1) ? 0 : sdiv->d[div_n - 2]; /* Setup quotient */ if (!bn_wexpand(res, loop)) goto err; num_neg = num->neg; res->neg = (num_neg ^ divisor->neg); res->top = loop; res->flags |= BN_FLG_FIXED_TOP; resp = &(res->d[loop]); /* space for temp */ if (!bn_wexpand(tmp, (div_n + 1))) goto err; for (i = 0; i < loop; i++, wnumtop--) { BN_ULONG q, l0; /* * the first part of the loop uses the top two words of snum and sdiv * to calculate a BN_ULONG q such that | wnum - sdiv * q | < sdiv */ # if defined(BN_DIV3W) q = bn_div_3_words(wnumtop, d1, d0); # else BN_ULONG n0, n1, rem = 0; n0 = wnumtop[0]; n1 = wnumtop[-1]; if (n0 == d0) q = BN_MASK2; else { /* n0 < d0 */ BN_ULONG n2 = (wnumtop == wnum) ? 0 : wnumtop[-2]; # ifdef BN_LLONG BN_ULLONG t2; # if defined(BN_LLONG) && defined(BN_DIV2W) && !defined(bn_div_words) q = (BN_ULONG)(((((BN_ULLONG) n0) << BN_BITS2) | n1) / d0); # else q = bn_div_words(n0, n1, d0); # endif # ifndef REMAINDER_IS_ALREADY_CALCULATED /* * rem doesn't have to be BN_ULLONG. The least we * know it's less that d0, isn't it? */ rem = (n1 - q * d0) & BN_MASK2; # endif t2 = (BN_ULLONG) d1 *q; for (;;) { if (t2 <= ((((BN_ULLONG) rem) << BN_BITS2) | n2)) break; q--; rem += d0; if (rem < d0) break; /* don't let rem overflow */ t2 -= d1; } # else /* !BN_LLONG */ BN_ULONG t2l, t2h; q = bn_div_words(n0, n1, d0); # ifndef REMAINDER_IS_ALREADY_CALCULATED rem = (n1 - q * d0) & BN_MASK2; # endif # if defined(BN_UMULT_LOHI) BN_UMULT_LOHI(t2l, t2h, d1, q); # elif defined(BN_UMULT_HIGH) t2l = d1 * q; t2h = BN_UMULT_HIGH(d1, q); # else { BN_ULONG ql, qh; t2l = LBITS(d1); t2h = HBITS(d1); ql = LBITS(q); qh = HBITS(q); mul64(t2l, t2h, ql, qh); /* t2=(BN_ULLONG)d1*q; */ } # endif for (;;) { if ((t2h < rem) || ((t2h == rem) && (t2l <= n2))) break; q--; rem += d0; if (rem < d0) break; /* don't let rem overflow */ if (t2l < d1) t2h--; t2l -= d1; } # endif /* !BN_LLONG */ } # endif /* !BN_DIV3W */ l0 = bn_mul_words(tmp->d, sdiv->d, div_n, q); tmp->d[div_n] = l0; wnum--; /* * ignore top values of the bignums just sub the two BN_ULONG arrays * with bn_sub_words */ l0 = bn_sub_words(wnum, wnum, tmp->d, div_n + 1); q -= l0; /* * Note: As we have considered only the leading two BN_ULONGs in * the calculation of q, sdiv * q might be greater than wnum (but * then (q-1) * sdiv is less or equal than wnum) */ for (l0 = 0 - l0, j = 0; j < div_n; j++) tmp->d[j] = sdiv->d[j] & l0; l0 = bn_add_words(wnum, wnum, tmp->d, div_n); (*wnumtop) += l0; assert((*wnumtop) == 0); /* store part of the result */ *--resp = q; } /* snum holds remainder, it's as wide as divisor */ snum->neg = num_neg; snum->top = div_n; snum->flags |= BN_FLG_FIXED_TOP; if (rm != NULL && bn_rshift_fixed_top(rm, snum, norm_shift) == 0) goto err; BN_CTX_end(ctx); return 1; err: bn_check_top(rm); BN_CTX_end(ctx); return 0; } #endif
14,051
29.481562
78
c
openssl
openssl-master/crypto/bn/bn_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2022 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 */ #include <openssl/err.h> #include <openssl/bnerr.h> #include "crypto/bnerr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA BN_str_reasons[] = { {ERR_PACK(ERR_LIB_BN, 0, BN_R_ARG2_LT_ARG3), "arg2 lt arg3"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_BAD_RECIPROCAL), "bad reciprocal"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_BIGNUM_TOO_LONG), "bignum too long"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_BITS_TOO_SMALL), "bits too small"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_CALLED_WITH_EVEN_MODULUS), "called with even modulus"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_DIV_BY_ZERO), "div by zero"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_ENCODING_ERROR), "encoding error"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_EXPAND_ON_STATIC_BIGNUM_DATA), "expand on static bignum data"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_INPUT_NOT_REDUCED), "input not reduced"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_INVALID_LENGTH), "invalid length"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_INVALID_RANGE), "invalid range"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_INVALID_SHIFT), "invalid shift"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_NOT_A_SQUARE), "not a square"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_NOT_INITIALIZED), "not initialized"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_NO_INVERSE), "no inverse"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_NO_PRIME_CANDIDATE), "no prime candidate"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_NO_SOLUTION), "no solution"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_NO_SUITABLE_DIGEST), "no suitable digest"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_PRIVATE_KEY_TOO_LARGE), "private key too large"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_P_IS_NOT_PRIME), "p is not prime"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_TOO_MANY_ITERATIONS), "too many iterations"}, {ERR_PACK(ERR_LIB_BN, 0, BN_R_TOO_MANY_TEMPORARY_VARIABLES), "too many temporary variables"}, {0, NULL} }; #endif int ossl_err_load_BN_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(BN_str_reasons[0].error) == NULL) ERR_load_strings_const(BN_str_reasons); #endif return 1; }
2,405
41.210526
79
c
openssl
openssl-master/crypto/bn/bn_exp2.c
/* * Copyright 1995-2022 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include "bn_local.h" #define TABLE_SIZE 32 int BN_mod_exp2_mont(BIGNUM *rr, const BIGNUM *a1, const BIGNUM *p1, const BIGNUM *a2, const BIGNUM *p2, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont) { int i, j, bits, b, bits1, bits2, ret = 0, wpos1, wpos2, window1, window2, wvalue1, wvalue2; int r_is_one = 1; BIGNUM *d, *r; const BIGNUM *a_mod_m; /* Tables of variables obtained from 'ctx' */ BIGNUM *val1[TABLE_SIZE], *val2[TABLE_SIZE]; BN_MONT_CTX *mont = NULL; bn_check_top(a1); bn_check_top(p1); bn_check_top(a2); bn_check_top(p2); bn_check_top(m); if (!BN_is_odd(m)) { ERR_raise(ERR_LIB_BN, BN_R_CALLED_WITH_EVEN_MODULUS); return 0; } bits1 = BN_num_bits(p1); bits2 = BN_num_bits(p2); if ((bits1 == 0) && (bits2 == 0)) { ret = BN_one(rr); return ret; } bits = (bits1 > bits2) ? bits1 : bits2; BN_CTX_start(ctx); d = BN_CTX_get(ctx); r = BN_CTX_get(ctx); val1[0] = BN_CTX_get(ctx); val2[0] = BN_CTX_get(ctx); if (val2[0] == NULL) goto err; if (in_mont != NULL) mont = in_mont; else { if ((mont = BN_MONT_CTX_new()) == NULL) goto err; if (!BN_MONT_CTX_set(mont, m, ctx)) goto err; } window1 = BN_window_bits_for_exponent_size(bits1); window2 = BN_window_bits_for_exponent_size(bits2); /* * Build table for a1: val1[i] := a1^(2*i + 1) mod m for i = 0 .. 2^(window1-1) */ if (a1->neg || BN_ucmp(a1, m) >= 0) { if (!BN_mod(val1[0], a1, m, ctx)) goto err; a_mod_m = val1[0]; } else a_mod_m = a1; if (BN_is_zero(a_mod_m)) { BN_zero(rr); ret = 1; goto err; } if (!BN_to_montgomery(val1[0], a_mod_m, mont, ctx)) goto err; if (window1 > 1) { if (!BN_mod_mul_montgomery(d, val1[0], val1[0], mont, ctx)) goto err; j = 1 << (window1 - 1); for (i = 1; i < j; i++) { if (((val1[i] = BN_CTX_get(ctx)) == NULL) || !BN_mod_mul_montgomery(val1[i], val1[i - 1], d, mont, ctx)) goto err; } } /* * Build table for a2: val2[i] := a2^(2*i + 1) mod m for i = 0 .. 2^(window2-1) */ if (a2->neg || BN_ucmp(a2, m) >= 0) { if (!BN_mod(val2[0], a2, m, ctx)) goto err; a_mod_m = val2[0]; } else a_mod_m = a2; if (BN_is_zero(a_mod_m)) { BN_zero(rr); ret = 1; goto err; } if (!BN_to_montgomery(val2[0], a_mod_m, mont, ctx)) goto err; if (window2 > 1) { if (!BN_mod_mul_montgomery(d, val2[0], val2[0], mont, ctx)) goto err; j = 1 << (window2 - 1); for (i = 1; i < j; i++) { if (((val2[i] = BN_CTX_get(ctx)) == NULL) || !BN_mod_mul_montgomery(val2[i], val2[i - 1], d, mont, ctx)) goto err; } } /* Now compute the power product, using independent windows. */ r_is_one = 1; wvalue1 = 0; /* The 'value' of the first window */ wvalue2 = 0; /* The 'value' of the second window */ wpos1 = 0; /* If wvalue1 > 0, the bottom bit of the * first window */ wpos2 = 0; /* If wvalue2 > 0, the bottom bit of the * second window */ if (!BN_to_montgomery(r, BN_value_one(), mont, ctx)) goto err; for (b = bits - 1; b >= 0; b--) { if (!r_is_one) { if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) goto err; } if (!wvalue1) if (BN_is_bit_set(p1, b)) { /* * consider bits b-window1+1 .. b for this window */ i = b - window1 + 1; while (!BN_is_bit_set(p1, i)) /* works for i<0 */ i++; wpos1 = i; wvalue1 = 1; for (i = b - 1; i >= wpos1; i--) { wvalue1 <<= 1; if (BN_is_bit_set(p1, i)) wvalue1++; } } if (!wvalue2) if (BN_is_bit_set(p2, b)) { /* * consider bits b-window2+1 .. b for this window */ i = b - window2 + 1; while (!BN_is_bit_set(p2, i)) i++; wpos2 = i; wvalue2 = 1; for (i = b - 1; i >= wpos2; i--) { wvalue2 <<= 1; if (BN_is_bit_set(p2, i)) wvalue2++; } } if (wvalue1 && b == wpos1) { /* wvalue1 is odd and < 2^window1 */ if (!BN_mod_mul_montgomery(r, r, val1[wvalue1 >> 1], mont, ctx)) goto err; wvalue1 = 0; r_is_one = 0; } if (wvalue2 && b == wpos2) { /* wvalue2 is odd and < 2^window2 */ if (!BN_mod_mul_montgomery(r, r, val2[wvalue2 >> 1], mont, ctx)) goto err; wvalue2 = 0; r_is_one = 0; } } if (!BN_from_montgomery(rr, r, mont, ctx)) goto err; ret = 1; err: if (in_mont == NULL) BN_MONT_CTX_free(mont); BN_CTX_end(ctx); bn_check_top(rr); return ret; }
5,937
28.39604
86
c
openssl
openssl-master/crypto/bn/bn_gcd.c
/* * Copyright 1995-2020 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 */ #include "internal/cryptlib.h" #include "bn_local.h" /* * bn_mod_inverse_no_branch is a special version of BN_mod_inverse. It does * not contain branches that may leak sensitive information. * * This is a static function, we ensure all callers in this file pass valid * arguments: all passed pointers here are non-NULL. */ static ossl_inline BIGNUM *bn_mod_inverse_no_branch(BIGNUM *in, const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx, int *pnoinv) { BIGNUM *A, *B, *X, *Y, *M, *D, *T, *R = NULL; BIGNUM *ret = NULL; int sign; bn_check_top(a); bn_check_top(n); BN_CTX_start(ctx); A = BN_CTX_get(ctx); B = BN_CTX_get(ctx); X = BN_CTX_get(ctx); D = BN_CTX_get(ctx); M = BN_CTX_get(ctx); Y = BN_CTX_get(ctx); T = BN_CTX_get(ctx); if (T == NULL) goto err; if (in == NULL) R = BN_new(); else R = in; if (R == NULL) goto err; if (!BN_one(X)) goto err; BN_zero(Y); if (BN_copy(B, a) == NULL) goto err; if (BN_copy(A, n) == NULL) goto err; A->neg = 0; if (B->neg || (BN_ucmp(B, A) >= 0)) { /* * Turn BN_FLG_CONSTTIME flag on, so that when BN_div is invoked, * BN_div_no_branch will be called eventually. */ { BIGNUM local_B; bn_init(&local_B); BN_with_flags(&local_B, B, BN_FLG_CONSTTIME); if (!BN_nnmod(B, &local_B, A, ctx)) goto err; /* Ensure local_B goes out of scope before any further use of B */ } } sign = -1; /*- * From B = a mod |n|, A = |n| it follows that * * 0 <= B < A, * -sign*X*a == B (mod |n|), * sign*Y*a == A (mod |n|). */ while (!BN_is_zero(B)) { BIGNUM *tmp; /*- * 0 < B < A, * (*) -sign*X*a == B (mod |n|), * sign*Y*a == A (mod |n|) */ /* * Turn BN_FLG_CONSTTIME flag on, so that when BN_div is invoked, * BN_div_no_branch will be called eventually. */ { BIGNUM local_A; bn_init(&local_A); BN_with_flags(&local_A, A, BN_FLG_CONSTTIME); /* (D, M) := (A/B, A%B) ... */ if (!BN_div(D, M, &local_A, B, ctx)) goto err; /* Ensure local_A goes out of scope before any further use of A */ } /*- * Now * A = D*B + M; * thus we have * (**) sign*Y*a == D*B + M (mod |n|). */ tmp = A; /* keep the BIGNUM object, the value does not * matter */ /* (A, B) := (B, A mod B) ... */ A = B; B = M; /* ... so we have 0 <= B < A again */ /*- * Since the former M is now B and the former B is now A, * (**) translates into * sign*Y*a == D*A + B (mod |n|), * i.e. * sign*Y*a - D*A == B (mod |n|). * Similarly, (*) translates into * -sign*X*a == A (mod |n|). * * Thus, * sign*Y*a + D*sign*X*a == B (mod |n|), * i.e. * sign*(Y + D*X)*a == B (mod |n|). * * So if we set (X, Y, sign) := (Y + D*X, X, -sign), we arrive back at * -sign*X*a == B (mod |n|), * sign*Y*a == A (mod |n|). * Note that X and Y stay non-negative all the time. */ if (!BN_mul(tmp, D, X, ctx)) goto err; if (!BN_add(tmp, tmp, Y)) goto err; M = Y; /* keep the BIGNUM object, the value does not * matter */ Y = X; X = tmp; sign = -sign; } /*- * The while loop (Euclid's algorithm) ends when * A == gcd(a,n); * we have * sign*Y*a == A (mod |n|), * where Y is non-negative. */ if (sign < 0) { if (!BN_sub(Y, n, Y)) goto err; } /* Now Y*a == A (mod |n|). */ if (BN_is_one(A)) { /* Y*a == 1 (mod |n|) */ if (!Y->neg && BN_ucmp(Y, n) < 0) { if (!BN_copy(R, Y)) goto err; } else { if (!BN_nnmod(R, Y, n, ctx)) goto err; } } else { *pnoinv = 1; /* caller sets the BN_R_NO_INVERSE error */ goto err; } ret = R; *pnoinv = 0; err: if ((ret == NULL) && (in == NULL)) BN_free(R); BN_CTX_end(ctx); bn_check_top(ret); return ret; } /* * This is an internal function, we assume all callers pass valid arguments: * all pointers passed here are assumed non-NULL. */ BIGNUM *int_bn_mod_inverse(BIGNUM *in, const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx, int *pnoinv) { BIGNUM *A, *B, *X, *Y, *M, *D, *T, *R = NULL; BIGNUM *ret = NULL; int sign; /* This is invalid input so we don't worry about constant time here */ if (BN_abs_is_word(n, 1) || BN_is_zero(n)) { *pnoinv = 1; return NULL; } *pnoinv = 0; if ((BN_get_flags(a, BN_FLG_CONSTTIME) != 0) || (BN_get_flags(n, BN_FLG_CONSTTIME) != 0)) { return bn_mod_inverse_no_branch(in, a, n, ctx, pnoinv); } bn_check_top(a); bn_check_top(n); BN_CTX_start(ctx); A = BN_CTX_get(ctx); B = BN_CTX_get(ctx); X = BN_CTX_get(ctx); D = BN_CTX_get(ctx); M = BN_CTX_get(ctx); Y = BN_CTX_get(ctx); T = BN_CTX_get(ctx); if (T == NULL) goto err; if (in == NULL) R = BN_new(); else R = in; if (R == NULL) goto err; if (!BN_one(X)) goto err; BN_zero(Y); if (BN_copy(B, a) == NULL) goto err; if (BN_copy(A, n) == NULL) goto err; A->neg = 0; if (B->neg || (BN_ucmp(B, A) >= 0)) { if (!BN_nnmod(B, B, A, ctx)) goto err; } sign = -1; /*- * From B = a mod |n|, A = |n| it follows that * * 0 <= B < A, * -sign*X*a == B (mod |n|), * sign*Y*a == A (mod |n|). */ if (BN_is_odd(n) && (BN_num_bits(n) <= 2048)) { /* * Binary inversion algorithm; requires odd modulus. This is faster * than the general algorithm if the modulus is sufficiently small * (about 400 .. 500 bits on 32-bit systems, but much more on 64-bit * systems) */ int shift; while (!BN_is_zero(B)) { /*- * 0 < B < |n|, * 0 < A <= |n|, * (1) -sign*X*a == B (mod |n|), * (2) sign*Y*a == A (mod |n|) */ /* * Now divide B by the maximum possible power of two in the * integers, and divide X by the same value mod |n|. When we're * done, (1) still holds. */ shift = 0; while (!BN_is_bit_set(B, shift)) { /* note that 0 < B */ shift++; if (BN_is_odd(X)) { if (!BN_uadd(X, X, n)) goto err; } /* * now X is even, so we can easily divide it by two */ if (!BN_rshift1(X, X)) goto err; } if (shift > 0) { if (!BN_rshift(B, B, shift)) goto err; } /* * Same for A and Y. Afterwards, (2) still holds. */ shift = 0; while (!BN_is_bit_set(A, shift)) { /* note that 0 < A */ shift++; if (BN_is_odd(Y)) { if (!BN_uadd(Y, Y, n)) goto err; } /* now Y is even */ if (!BN_rshift1(Y, Y)) goto err; } if (shift > 0) { if (!BN_rshift(A, A, shift)) goto err; } /*- * We still have (1) and (2). * Both A and B are odd. * The following computations ensure that * * 0 <= B < |n|, * 0 < A < |n|, * (1) -sign*X*a == B (mod |n|), * (2) sign*Y*a == A (mod |n|), * * and that either A or B is even in the next iteration. */ if (BN_ucmp(B, A) >= 0) { /* -sign*(X + Y)*a == B - A (mod |n|) */ if (!BN_uadd(X, X, Y)) goto err; /* * NB: we could use BN_mod_add_quick(X, X, Y, n), but that * actually makes the algorithm slower */ if (!BN_usub(B, B, A)) goto err; } else { /* sign*(X + Y)*a == A - B (mod |n|) */ if (!BN_uadd(Y, Y, X)) goto err; /* * as above, BN_mod_add_quick(Y, Y, X, n) would slow things down */ if (!BN_usub(A, A, B)) goto err; } } } else { /* general inversion algorithm */ while (!BN_is_zero(B)) { BIGNUM *tmp; /*- * 0 < B < A, * (*) -sign*X*a == B (mod |n|), * sign*Y*a == A (mod |n|) */ /* (D, M) := (A/B, A%B) ... */ if (BN_num_bits(A) == BN_num_bits(B)) { if (!BN_one(D)) goto err; if (!BN_sub(M, A, B)) goto err; } else if (BN_num_bits(A) == BN_num_bits(B) + 1) { /* A/B is 1, 2, or 3 */ if (!BN_lshift1(T, B)) goto err; if (BN_ucmp(A, T) < 0) { /* A < 2*B, so D=1 */ if (!BN_one(D)) goto err; if (!BN_sub(M, A, B)) goto err; } else { /* A >= 2*B, so D=2 or D=3 */ if (!BN_sub(M, A, T)) goto err; if (!BN_add(D, T, B)) goto err; /* use D (:= 3*B) as temp */ if (BN_ucmp(A, D) < 0) { /* A < 3*B, so D=2 */ if (!BN_set_word(D, 2)) goto err; /* * M (= A - 2*B) already has the correct value */ } else { /* only D=3 remains */ if (!BN_set_word(D, 3)) goto err; /* * currently M = A - 2*B, but we need M = A - 3*B */ if (!BN_sub(M, M, B)) goto err; } } } else { if (!BN_div(D, M, A, B, ctx)) goto err; } /*- * Now * A = D*B + M; * thus we have * (**) sign*Y*a == D*B + M (mod |n|). */ tmp = A; /* keep the BIGNUM object, the value does not matter */ /* (A, B) := (B, A mod B) ... */ A = B; B = M; /* ... so we have 0 <= B < A again */ /*- * Since the former M is now B and the former B is now A, * (**) translates into * sign*Y*a == D*A + B (mod |n|), * i.e. * sign*Y*a - D*A == B (mod |n|). * Similarly, (*) translates into * -sign*X*a == A (mod |n|). * * Thus, * sign*Y*a + D*sign*X*a == B (mod |n|), * i.e. * sign*(Y + D*X)*a == B (mod |n|). * * So if we set (X, Y, sign) := (Y + D*X, X, -sign), we arrive back at * -sign*X*a == B (mod |n|), * sign*Y*a == A (mod |n|). * Note that X and Y stay non-negative all the time. */ /* * most of the time D is very small, so we can optimize tmp := D*X+Y */ if (BN_is_one(D)) { if (!BN_add(tmp, X, Y)) goto err; } else { if (BN_is_word(D, 2)) { if (!BN_lshift1(tmp, X)) goto err; } else if (BN_is_word(D, 4)) { if (!BN_lshift(tmp, X, 2)) goto err; } else if (D->top == 1) { if (!BN_copy(tmp, X)) goto err; if (!BN_mul_word(tmp, D->d[0])) goto err; } else { if (!BN_mul(tmp, D, X, ctx)) goto err; } if (!BN_add(tmp, tmp, Y)) goto err; } M = Y; /* keep the BIGNUM object, the value does not matter */ Y = X; X = tmp; sign = -sign; } } /*- * The while loop (Euclid's algorithm) ends when * A == gcd(a,n); * we have * sign*Y*a == A (mod |n|), * where Y is non-negative. */ if (sign < 0) { if (!BN_sub(Y, n, Y)) goto err; } /* Now Y*a == A (mod |n|). */ if (BN_is_one(A)) { /* Y*a == 1 (mod |n|) */ if (!Y->neg && BN_ucmp(Y, n) < 0) { if (!BN_copy(R, Y)) goto err; } else { if (!BN_nnmod(R, Y, n, ctx)) goto err; } } else { *pnoinv = 1; goto err; } ret = R; err: if ((ret == NULL) && (in == NULL)) BN_free(R); BN_CTX_end(ctx); bn_check_top(ret); return ret; } /* solves ax == 1 (mod n) */ BIGNUM *BN_mod_inverse(BIGNUM *in, const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx) { BN_CTX *new_ctx = NULL; BIGNUM *rv; int noinv = 0; if (ctx == NULL) { ctx = new_ctx = BN_CTX_new_ex(NULL); if (ctx == NULL) { ERR_raise(ERR_LIB_BN, ERR_R_BN_LIB); return NULL; } } rv = int_bn_mod_inverse(in, a, n, ctx, &noinv); if (noinv) ERR_raise(ERR_LIB_BN, BN_R_NO_INVERSE); BN_CTX_free(new_ctx); return rv; } /* * The numbers a and b are coprime if the only positive integer that is a * divisor of both of them is 1. * i.e. gcd(a,b) = 1. * * Coprimes have the property: b has a multiplicative inverse modulo a * i.e there is some value x such that bx = 1 (mod a). * * Testing the modulo inverse is currently much faster than the constant * time version of BN_gcd(). */ int BN_are_coprime(BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { int ret = 0; BIGNUM *tmp; BN_CTX_start(ctx); tmp = BN_CTX_get(ctx); if (tmp == NULL) goto end; ERR_set_mark(); BN_set_flags(a, BN_FLG_CONSTTIME); ret = (BN_mod_inverse(tmp, a, b, ctx) != NULL); /* Clear any errors (an error is returned if there is no inverse) */ ERR_pop_to_mark(); end: BN_CTX_end(ctx); return ret; } /*- * This function is based on the constant-time GCD work by Bernstein and Yang: * https://eprint.iacr.org/2019/266 * Generalized fast GCD function to allow even inputs. * The algorithm first finds the shared powers of 2 between * the inputs, and removes them, reducing at least one of the * inputs to an odd value. Then it proceeds to calculate the GCD. * Before returning the resulting GCD, we take care of adding * back the powers of two removed at the beginning. * Note 1: we assume the bit length of both inputs is public information, * since access to top potentially leaks this information. */ int BN_gcd(BIGNUM *r, const BIGNUM *in_a, const BIGNUM *in_b, BN_CTX *ctx) { BIGNUM *g, *temp = NULL; BN_ULONG mask = 0; int i, j, top, rlen, glen, m, bit = 1, delta = 1, cond = 0, shifts = 0, ret = 0; /* Note 2: zero input corner cases are not constant-time since they are * handled immediately. An attacker can run an attack under this * assumption without the need of side-channel information. */ if (BN_is_zero(in_b)) { ret = BN_copy(r, in_a) != NULL; r->neg = 0; return ret; } if (BN_is_zero(in_a)) { ret = BN_copy(r, in_b) != NULL; r->neg = 0; return ret; } bn_check_top(in_a); bn_check_top(in_b); BN_CTX_start(ctx); temp = BN_CTX_get(ctx); g = BN_CTX_get(ctx); /* make r != 0, g != 0 even, so BN_rshift is not a potential nop */ if (g == NULL || !BN_lshift1(g, in_b) || !BN_lshift1(r, in_a)) goto err; /* find shared powers of two, i.e. "shifts" >= 1 */ for (i = 0; i < r->dmax && i < g->dmax; i++) { mask = ~(r->d[i] | g->d[i]); for (j = 0; j < BN_BITS2; j++) { bit &= mask; shifts += bit; mask >>= 1; } } /* subtract shared powers of two; shifts >= 1 */ if (!BN_rshift(r, r, shifts) || !BN_rshift(g, g, shifts)) goto err; /* expand to biggest nword, with room for a possible extra word */ top = 1 + ((r->top >= g->top) ? r->top : g->top); if (bn_wexpand(r, top) == NULL || bn_wexpand(g, top) == NULL || bn_wexpand(temp, top) == NULL) goto err; /* re arrange inputs s.t. r is odd */ BN_consttime_swap((~r->d[0]) & 1, r, g, top); /* compute the number of iterations */ rlen = BN_num_bits(r); glen = BN_num_bits(g); m = 4 + 3 * ((rlen >= glen) ? rlen : glen); for (i = 0; i < m; i++) { /* conditionally flip signs if delta is positive and g is odd */ cond = (-delta >> (8 * sizeof(delta) - 1)) & g->d[0] & 1 /* make sure g->top > 0 (i.e. if top == 0 then g == 0 always) */ & (~((g->top - 1) >> (sizeof(g->top) * 8 - 1))); delta = (-cond & -delta) | ((cond - 1) & delta); r->neg ^= cond; /* swap */ BN_consttime_swap(cond, r, g, top); /* elimination step */ delta++; if (!BN_add(temp, g, r)) goto err; BN_consttime_swap(g->d[0] & 1 /* g is odd */ /* make sure g->top > 0 (i.e. if top == 0 then g == 0 always) */ & (~((g->top - 1) >> (sizeof(g->top) * 8 - 1))), g, temp, top); if (!BN_rshift1(g, g)) goto err; } /* remove possible negative sign */ r->neg = 0; /* add powers of 2 removed, then correct the artificial shift */ if (!BN_lshift(r, r, shifts) || !BN_rshift1(r, r)) goto err; ret = 1; err: BN_CTX_end(ctx); bn_check_top(r); return ret; }
19,856
28.244477
84
c
openssl
openssl-master/crypto/bn/bn_intern.c
/* * Copyright 2014-2020 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 */ #include "internal/cryptlib.h" #include "bn_local.h" /* * Determine the modified width-(w+1) Non-Adjacent Form (wNAF) of 'scalar'. * This is an array r[] of values that are either zero or odd with an * absolute value less than 2^w satisfying * scalar = \sum_j r[j]*2^j * where at most one of any w+1 consecutive digits is non-zero * with the exception that the most significant digit may be only * w-1 zeros away from that next non-zero digit. */ signed char *bn_compute_wNAF(const BIGNUM *scalar, int w, size_t *ret_len) { int window_val; signed char *r = NULL; int sign = 1; int bit, next_bit, mask; size_t len = 0, j; if (BN_is_zero(scalar)) { r = OPENSSL_malloc(1); if (r == NULL) goto err; r[0] = 0; *ret_len = 1; return r; } if (w <= 0 || w > 7) { /* 'signed char' can represent integers with * absolute values less than 2^7 */ ERR_raise(ERR_LIB_BN, ERR_R_INTERNAL_ERROR); goto err; } bit = 1 << w; /* at most 128 */ next_bit = bit << 1; /* at most 256 */ mask = next_bit - 1; /* at most 255 */ if (BN_is_negative(scalar)) { sign = -1; } if (scalar->d == NULL || scalar->top == 0) { ERR_raise(ERR_LIB_BN, ERR_R_INTERNAL_ERROR); goto err; } len = BN_num_bits(scalar); r = OPENSSL_malloc(len + 1); /* * Modified wNAF may be one digit longer than binary representation * (*ret_len will be set to the actual length, i.e. at most * BN_num_bits(scalar) + 1) */ if (r == NULL) goto err; window_val = scalar->d[0] & mask; j = 0; while ((window_val != 0) || (j + w + 1 < len)) { /* if j+w+1 >= len, * window_val will not * increase */ int digit = 0; /* 0 <= window_val <= 2^(w+1) */ if (window_val & 1) { /* 0 < window_val < 2^(w+1) */ if (window_val & bit) { digit = window_val - next_bit; /* -2^w < digit < 0 */ #if 1 /* modified wNAF */ if (j + w + 1 >= len) { /* * Special case for generating modified wNAFs: * no new bits will be added into window_val, * so using a positive digit here will decrease * the total length of the representation */ digit = window_val & (mask >> 1); /* 0 < digit < 2^w */ } #endif } else { digit = window_val; /* 0 < digit < 2^w */ } if (digit <= -bit || digit >= bit || !(digit & 1)) { ERR_raise(ERR_LIB_BN, ERR_R_INTERNAL_ERROR); goto err; } window_val -= digit; /* * now window_val is 0 or 2^(w+1) in standard wNAF generation; * for modified window NAFs, it may also be 2^w */ if (window_val != 0 && window_val != next_bit && window_val != bit) { ERR_raise(ERR_LIB_BN, ERR_R_INTERNAL_ERROR); goto err; } } r[j++] = sign * digit; window_val >>= 1; window_val += bit * BN_is_bit_set(scalar, j + w); if (window_val > next_bit) { ERR_raise(ERR_LIB_BN, ERR_R_INTERNAL_ERROR); goto err; } } if (j > len + 1) { ERR_raise(ERR_LIB_BN, ERR_R_INTERNAL_ERROR); goto err; } *ret_len = j; return r; err: OPENSSL_free(r); return NULL; } int bn_get_top(const BIGNUM *a) { return a->top; } int bn_get_dmax(const BIGNUM *a) { return a->dmax; } void bn_set_all_zero(BIGNUM *a) { int i; for (i = a->top; i < a->dmax; i++) a->d[i] = 0; } int bn_copy_words(BN_ULONG *out, const BIGNUM *in, int size) { if (in->top > size) return 0; memset(out, 0, sizeof(*out) * size); if (in->d != NULL) memcpy(out, in->d, sizeof(*out) * in->top); return 1; } BN_ULONG *bn_get_words(const BIGNUM *a) { return a->d; } void bn_set_static_words(BIGNUM *a, const BN_ULONG *words, int size) { /* * |const| qualifier omission is compensated by BN_FLG_STATIC_DATA * flag, which effectively means "read-only data". */ a->d = (BN_ULONG *)words; a->dmax = a->top = size; a->neg = 0; a->flags |= BN_FLG_STATIC_DATA; bn_correct_top(a); } int bn_set_words(BIGNUM *a, const BN_ULONG *words, int num_words) { if (bn_wexpand(a, num_words) == NULL) { ERR_raise(ERR_LIB_BN, ERR_R_BN_LIB); return 0; } memcpy(a->d, words, sizeof(BN_ULONG) * num_words); a->top = num_words; bn_correct_top(a); return 1; }
5,416
26.637755
100
c
openssl
openssl-master/crypto/bn/bn_kron.c
/* * Copyright 2000-2016 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 */ #include "internal/cryptlib.h" #include "bn_local.h" /* least significant word */ #define BN_lsw(n) (((n)->top == 0) ? (BN_ULONG) 0 : (n)->d[0]) /* Returns -2 for errors because both -1 and 0 are valid results. */ int BN_kronecker(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { int i; int ret = -2; /* avoid 'uninitialized' warning */ int err = 0; BIGNUM *A, *B, *tmp; /*- * In 'tab', only odd-indexed entries are relevant: * For any odd BIGNUM n, * tab[BN_lsw(n) & 7] * is $(-1)^{(n^2-1)/8}$ (using TeX notation). * Note that the sign of n does not matter. */ static const int tab[8] = { 0, 1, 0, -1, 0, -1, 0, 1 }; bn_check_top(a); bn_check_top(b); BN_CTX_start(ctx); A = BN_CTX_get(ctx); B = BN_CTX_get(ctx); if (B == NULL) goto end; err = !BN_copy(A, a); if (err) goto end; err = !BN_copy(B, b); if (err) goto end; /* * Kronecker symbol, implemented according to Henri Cohen, * "A Course in Computational Algebraic Number Theory" * (algorithm 1.4.10). */ /* Cohen's step 1: */ if (BN_is_zero(B)) { ret = BN_abs_is_word(A, 1); goto end; } /* Cohen's step 2: */ if (!BN_is_odd(A) && !BN_is_odd(B)) { ret = 0; goto end; } /* now B is non-zero */ i = 0; while (!BN_is_bit_set(B, i)) i++; err = !BN_rshift(B, B, i); if (err) goto end; if (i & 1) { /* i is odd */ /* (thus B was even, thus A must be odd!) */ /* set 'ret' to $(-1)^{(A^2-1)/8}$ */ ret = tab[BN_lsw(A) & 7]; } else { /* i is even */ ret = 1; } if (B->neg) { B->neg = 0; if (A->neg) ret = -ret; } /* * now B is positive and odd, so what remains to be done is to compute * the Jacobi symbol (A/B) and multiply it by 'ret' */ while (1) { /* Cohen's step 3: */ /* B is positive and odd */ if (BN_is_zero(A)) { ret = BN_is_one(B) ? ret : 0; goto end; } /* now A is non-zero */ i = 0; while (!BN_is_bit_set(A, i)) i++; err = !BN_rshift(A, A, i); if (err) goto end; if (i & 1) { /* i is odd */ /* multiply 'ret' by $(-1)^{(B^2-1)/8}$ */ ret = ret * tab[BN_lsw(B) & 7]; } /* Cohen's step 4: */ /* multiply 'ret' by $(-1)^{(A-1)(B-1)/4}$ */ if ((A->neg ? ~BN_lsw(A) : BN_lsw(A)) & BN_lsw(B) & 2) ret = -ret; /* (A, B) := (B mod |A|, |A|) */ err = !BN_nnmod(B, B, A, ctx); if (err) goto end; tmp = A; A = B; B = tmp; tmp->neg = 0; } end: BN_CTX_end(ctx); if (err) return -2; else return ret; }
3,299
22.404255
74
c
openssl
openssl-master/crypto/bn/bn_mod.c
/* * Copyright 1998-2021 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 */ #include "internal/cryptlib.h" #include "bn_local.h" int BN_nnmod(BIGNUM *r, const BIGNUM *m, const BIGNUM *d, BN_CTX *ctx) { /* * like BN_mod, but returns non-negative remainder (i.e., 0 <= r < |d| * always holds) */ if (!(BN_mod(r, m, d, ctx))) return 0; if (!r->neg) return 1; /* now -|d| < r < 0, so we have to set r := r + |d| */ return (d->neg ? BN_sub : BN_add) (r, r, d); } int BN_mod_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, BN_CTX *ctx) { if (!BN_add(r, a, b)) return 0; return BN_nnmod(r, r, m, ctx); } /* * BN_mod_add variant that may be used if both a and b are non-negative and * less than m. The original algorithm was * * if (!BN_uadd(r, a, b)) * return 0; * if (BN_ucmp(r, m) >= 0) * return BN_usub(r, r, m); * * which is replaced with addition, subtracting modulus, and conditional * move depending on whether or not subtraction borrowed. */ int bn_mod_add_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m) { size_t i, ai, bi, mtop = m->top; BN_ULONG storage[1024 / BN_BITS2]; BN_ULONG carry, temp, mask, *rp, *tp = storage; const BN_ULONG *ap, *bp; if (bn_wexpand(r, mtop) == NULL) return 0; if (mtop > sizeof(storage) / sizeof(storage[0])) { tp = OPENSSL_malloc(mtop * sizeof(BN_ULONG)); if (tp == NULL) return 0; } ap = a->d != NULL ? a->d : tp; bp = b->d != NULL ? b->d : tp; for (i = 0, ai = 0, bi = 0, carry = 0; i < mtop;) { mask = (BN_ULONG)0 - ((i - a->top) >> (8 * sizeof(i) - 1)); temp = ((ap[ai] & mask) + carry) & BN_MASK2; carry = (temp < carry); mask = (BN_ULONG)0 - ((i - b->top) >> (8 * sizeof(i) - 1)); tp[i] = ((bp[bi] & mask) + temp) & BN_MASK2; carry += (tp[i] < temp); i++; ai += (i - a->dmax) >> (8 * sizeof(i) - 1); bi += (i - b->dmax) >> (8 * sizeof(i) - 1); } rp = r->d; carry -= bn_sub_words(rp, tp, m->d, mtop); for (i = 0; i < mtop; i++) { rp[i] = (carry & tp[i]) | (~carry & rp[i]); ((volatile BN_ULONG *)tp)[i] = 0; } r->top = mtop; r->flags |= BN_FLG_FIXED_TOP; r->neg = 0; if (tp != storage) OPENSSL_free(tp); return 1; } int BN_mod_add_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m) { int ret = bn_mod_add_fixed_top(r, a, b, m); if (ret) bn_correct_top(r); return ret; } int BN_mod_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, BN_CTX *ctx) { if (!BN_sub(r, a, b)) return 0; return BN_nnmod(r, r, m, ctx); } /* * BN_mod_sub variant that may be used if both a and b are non-negative, * a is less than m, while b is of same bit width as m. It's implemented * as subtraction followed by two conditional additions. * * 0 <= a < m * 0 <= b < 2^w < 2*m * * after subtraction * * -2*m < r = a - b < m * * Thus it takes up to two conditional additions to make |r| positive. */ int bn_mod_sub_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m) { size_t i, ai, bi, mtop = m->top; BN_ULONG borrow, carry, ta, tb, mask, *rp; const BN_ULONG *ap, *bp; if (bn_wexpand(r, mtop) == NULL) return 0; rp = r->d; ap = a->d != NULL ? a->d : rp; bp = b->d != NULL ? b->d : rp; for (i = 0, ai = 0, bi = 0, borrow = 0; i < mtop;) { mask = (BN_ULONG)0 - ((i - a->top) >> (8 * sizeof(i) - 1)); ta = ap[ai] & mask; mask = (BN_ULONG)0 - ((i - b->top) >> (8 * sizeof(i) - 1)); tb = bp[bi] & mask; rp[i] = ta - tb - borrow; if (ta != tb) borrow = (ta < tb); i++; ai += (i - a->dmax) >> (8 * sizeof(i) - 1); bi += (i - b->dmax) >> (8 * sizeof(i) - 1); } ap = m->d; for (i = 0, mask = 0 - borrow, carry = 0; i < mtop; i++) { ta = ((ap[i] & mask) + carry) & BN_MASK2; carry = (ta < carry); rp[i] = (rp[i] + ta) & BN_MASK2; carry += (rp[i] < ta); } borrow -= carry; for (i = 0, mask = 0 - borrow, carry = 0; i < mtop; i++) { ta = ((ap[i] & mask) + carry) & BN_MASK2; carry = (ta < carry); rp[i] = (rp[i] + ta) & BN_MASK2; carry += (rp[i] < ta); } r->top = mtop; r->flags |= BN_FLG_FIXED_TOP; r->neg = 0; return 1; } /* * BN_mod_sub variant that may be used if both a and b are non-negative and * less than m */ int BN_mod_sub_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m) { if (!BN_sub(r, a, b)) return 0; if (r->neg) return BN_add(r, r, m); return 1; } /* slow but works */ int BN_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, BN_CTX *ctx) { BIGNUM *t; int ret = 0; bn_check_top(a); bn_check_top(b); bn_check_top(m); BN_CTX_start(ctx); if ((t = BN_CTX_get(ctx)) == NULL) goto err; if (a == b) { if (!BN_sqr(t, a, ctx)) goto err; } else { if (!BN_mul(t, a, b, ctx)) goto err; } if (!BN_nnmod(r, t, m, ctx)) goto err; bn_check_top(r); ret = 1; err: BN_CTX_end(ctx); return ret; } int BN_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) { if (!BN_sqr(r, a, ctx)) return 0; /* r->neg == 0, thus we don't need BN_nnmod */ return BN_mod(r, r, m, ctx); } int BN_mod_lshift1(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) { if (!BN_lshift1(r, a)) return 0; bn_check_top(r); return BN_nnmod(r, r, m, ctx); } /* * BN_mod_lshift1 variant that may be used if a is non-negative and less than * m */ int BN_mod_lshift1_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *m) { if (!BN_lshift1(r, a)) return 0; bn_check_top(r); if (BN_cmp(r, m) >= 0) return BN_sub(r, r, m); return 1; } int BN_mod_lshift(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m, BN_CTX *ctx) { BIGNUM *abs_m = NULL; int ret; if (!BN_nnmod(r, a, m, ctx)) return 0; if (m->neg) { abs_m = BN_dup(m); if (abs_m == NULL) return 0; abs_m->neg = 0; } ret = BN_mod_lshift_quick(r, r, n, (abs_m ? abs_m : m)); bn_check_top(r); BN_free(abs_m); return ret; } /* * BN_mod_lshift variant that may be used if a is non-negative and less than * m */ int BN_mod_lshift_quick(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m) { if (r != a) { if (BN_copy(r, a) == NULL) return 0; } while (n > 0) { int max_shift; /* 0 < r < m */ max_shift = BN_num_bits(m) - BN_num_bits(r); /* max_shift >= 0 */ if (max_shift < 0) { ERR_raise(ERR_LIB_BN, BN_R_INPUT_NOT_REDUCED); return 0; } if (max_shift > n) max_shift = n; if (max_shift) { if (!BN_lshift(r, r, max_shift)) return 0; n -= max_shift; } else { if (!BN_lshift1(r, r)) return 0; --n; } /* BN_num_bits(r) <= BN_num_bits(m) */ if (BN_cmp(r, m) >= 0) { if (!BN_sub(r, r, m)) return 0; } } bn_check_top(r); return 1; }
7,934
23.490741
77
c
openssl
openssl-master/crypto/bn/bn_mont.c
/* * Copyright 1995-2021 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 */ /* * Details about Montgomery multiplication algorithms can be found at * http://security.ece.orst.edu/publications.html, e.g. * http://security.ece.orst.edu/koc/papers/j37acmon.pdf and * sections 3.8 and 4.2 in http://security.ece.orst.edu/koc/papers/r01rsasw.pdf */ #include "internal/cryptlib.h" #include "bn_local.h" #define MONT_WORD /* use the faster word-based algorithm */ #ifdef MONT_WORD static int bn_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont); #endif int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_MONT_CTX *mont, BN_CTX *ctx) { int ret = bn_mul_mont_fixed_top(r, a, b, mont, ctx); bn_correct_top(r); bn_check_top(r); return ret; } int bn_mul_mont_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_MONT_CTX *mont, BN_CTX *ctx) { BIGNUM *tmp; int ret = 0; int num = mont->N.top; #if defined(OPENSSL_BN_ASM_MONT) && defined(MONT_WORD) if (num > 1 && num <= BN_SOFT_LIMIT && a->top == num && b->top == num) { if (bn_wexpand(r, num) == NULL) return 0; if (bn_mul_mont(r->d, a->d, b->d, mont->N.d, mont->n0, num)) { r->neg = a->neg ^ b->neg; r->top = num; r->flags |= BN_FLG_FIXED_TOP; return 1; } } #endif if ((a->top + b->top) > 2 * num) return 0; BN_CTX_start(ctx); tmp = BN_CTX_get(ctx); if (tmp == NULL) goto err; bn_check_top(tmp); if (a == b) { if (!bn_sqr_fixed_top(tmp, a, ctx)) goto err; } else { if (!bn_mul_fixed_top(tmp, a, b, ctx)) goto err; } /* reduce from aRR to aR */ #ifdef MONT_WORD if (!bn_from_montgomery_word(r, tmp, mont)) goto err; #else if (!BN_from_montgomery(r, tmp, mont, ctx)) goto err; #endif ret = 1; err: BN_CTX_end(ctx); return ret; } #ifdef MONT_WORD static int bn_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont) { BIGNUM *n; BN_ULONG *ap, *np, *rp, n0, v, carry; int nl, max, i; unsigned int rtop; n = &(mont->N); nl = n->top; if (nl == 0) { ret->top = 0; return 1; } max = (2 * nl); /* carry is stored separately */ if (bn_wexpand(r, max) == NULL) return 0; r->neg ^= n->neg; np = n->d; rp = r->d; /* clear the top words of T */ for (rtop = r->top, i = 0; i < max; i++) { v = (BN_ULONG)0 - ((i - rtop) >> (8 * sizeof(rtop) - 1)); rp[i] &= v; } r->top = max; r->flags |= BN_FLG_FIXED_TOP; n0 = mont->n0[0]; /* * Add multiples of |n| to |r| until R = 2^(nl * BN_BITS2) divides it. On * input, we had |r| < |n| * R, so now |r| < 2 * |n| * R. Note that |r| * includes |carry| which is stored separately. */ for (carry = 0, i = 0; i < nl; i++, rp++) { v = bn_mul_add_words(rp, np, nl, (rp[0] * n0) & BN_MASK2); v = (v + carry + rp[nl]) & BN_MASK2; carry |= (v != rp[nl]); carry &= (v <= rp[nl]); rp[nl] = v; } if (bn_wexpand(ret, nl) == NULL) return 0; ret->top = nl; ret->flags |= BN_FLG_FIXED_TOP; ret->neg = r->neg; rp = ret->d; /* * Shift |nl| words to divide by R. We have |ap| < 2 * |n|. Note that |ap| * includes |carry| which is stored separately. */ ap = &(r->d[nl]); carry -= bn_sub_words(rp, ap, np, nl); /* * |carry| is -1 if |ap| - |np| underflowed or zero if it did not. Note * |carry| cannot be 1. That would imply the subtraction did not fit in * |nl| words, and we know at most one subtraction is needed. */ for (i = 0; i < nl; i++) { rp[i] = (carry & ap[i]) | (~carry & rp[i]); ap[i] = 0; } return 1; } #endif /* MONT_WORD */ int BN_from_montgomery(BIGNUM *ret, const BIGNUM *a, BN_MONT_CTX *mont, BN_CTX *ctx) { int retn; retn = bn_from_mont_fixed_top(ret, a, mont, ctx); bn_correct_top(ret); bn_check_top(ret); return retn; } int bn_from_mont_fixed_top(BIGNUM *ret, const BIGNUM *a, BN_MONT_CTX *mont, BN_CTX *ctx) { int retn = 0; #ifdef MONT_WORD BIGNUM *t; BN_CTX_start(ctx); if ((t = BN_CTX_get(ctx)) && BN_copy(t, a)) { retn = bn_from_montgomery_word(ret, t, mont); } BN_CTX_end(ctx); #else /* !MONT_WORD */ BIGNUM *t1, *t2; BN_CTX_start(ctx); t1 = BN_CTX_get(ctx); t2 = BN_CTX_get(ctx); if (t2 == NULL) goto err; if (!BN_copy(t1, a)) goto err; BN_mask_bits(t1, mont->ri); if (!BN_mul(t2, t1, &mont->Ni, ctx)) goto err; BN_mask_bits(t2, mont->ri); if (!BN_mul(t1, t2, &mont->N, ctx)) goto err; if (!BN_add(t2, a, t1)) goto err; if (!BN_rshift(ret, t2, mont->ri)) goto err; if (BN_ucmp(ret, &(mont->N)) >= 0) { if (!BN_usub(ret, ret, &(mont->N))) goto err; } retn = 1; bn_check_top(ret); err: BN_CTX_end(ctx); #endif /* MONT_WORD */ return retn; } int bn_to_mont_fixed_top(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont, BN_CTX *ctx) { return bn_mul_mont_fixed_top(r, a, &(mont->RR), mont, ctx); } BN_MONT_CTX *BN_MONT_CTX_new(void) { BN_MONT_CTX *ret; if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL) return NULL; BN_MONT_CTX_init(ret); ret->flags = BN_FLG_MALLOCED; return ret; } void BN_MONT_CTX_init(BN_MONT_CTX *ctx) { ctx->ri = 0; bn_init(&ctx->RR); bn_init(&ctx->N); bn_init(&ctx->Ni); ctx->n0[0] = ctx->n0[1] = 0; ctx->flags = 0; } void BN_MONT_CTX_free(BN_MONT_CTX *mont) { if (mont == NULL) return; BN_clear_free(&mont->RR); BN_clear_free(&mont->N); BN_clear_free(&mont->Ni); if (mont->flags & BN_FLG_MALLOCED) OPENSSL_free(mont); } int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx) { int i, ret = 0; BIGNUM *Ri, *R; if (BN_is_zero(mod)) return 0; BN_CTX_start(ctx); if ((Ri = BN_CTX_get(ctx)) == NULL) goto err; R = &(mont->RR); /* grab RR as a temp */ if (!BN_copy(&(mont->N), mod)) goto err; /* Set N */ if (BN_get_flags(mod, BN_FLG_CONSTTIME) != 0) BN_set_flags(&(mont->N), BN_FLG_CONSTTIME); mont->N.neg = 0; #ifdef MONT_WORD { BIGNUM tmod; BN_ULONG buf[2]; bn_init(&tmod); tmod.d = buf; tmod.dmax = 2; tmod.neg = 0; if (BN_get_flags(mod, BN_FLG_CONSTTIME) != 0) BN_set_flags(&tmod, BN_FLG_CONSTTIME); mont->ri = (BN_num_bits(mod) + (BN_BITS2 - 1)) / BN_BITS2 * BN_BITS2; # if defined(OPENSSL_BN_ASM_MONT) && (BN_BITS2<=32) /* * Only certain BN_BITS2<=32 platforms actually make use of n0[1], * and we could use the #else case (with a shorter R value) for the * others. However, currently only the assembler files do know which * is which. */ BN_zero(R); if (!(BN_set_bit(R, 2 * BN_BITS2))) goto err; tmod.top = 0; if ((buf[0] = mod->d[0])) tmod.top = 1; if ((buf[1] = mod->top > 1 ? mod->d[1] : 0)) tmod.top = 2; if (BN_is_one(&tmod)) BN_zero(Ri); else if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL) goto err; if (!BN_lshift(Ri, Ri, 2 * BN_BITS2)) goto err; /* R*Ri */ if (!BN_is_zero(Ri)) { if (!BN_sub_word(Ri, 1)) goto err; } else { /* if N mod word size == 1 */ if (bn_expand(Ri, (int)sizeof(BN_ULONG) * 2) == NULL) goto err; /* Ri-- (mod double word size) */ Ri->neg = 0; Ri->d[0] = BN_MASK2; Ri->d[1] = BN_MASK2; Ri->top = 2; } if (!BN_div(Ri, NULL, Ri, &tmod, ctx)) goto err; /* * Ni = (R*Ri-1)/N, keep only couple of least significant words: */ mont->n0[0] = (Ri->top > 0) ? Ri->d[0] : 0; mont->n0[1] = (Ri->top > 1) ? Ri->d[1] : 0; # else BN_zero(R); if (!(BN_set_bit(R, BN_BITS2))) goto err; /* R */ buf[0] = mod->d[0]; /* tmod = N mod word size */ buf[1] = 0; tmod.top = buf[0] != 0 ? 1 : 0; /* Ri = R^-1 mod N */ if (BN_is_one(&tmod)) BN_zero(Ri); else if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL) goto err; if (!BN_lshift(Ri, Ri, BN_BITS2)) goto err; /* R*Ri */ if (!BN_is_zero(Ri)) { if (!BN_sub_word(Ri, 1)) goto err; } else { /* if N mod word size == 1 */ if (!BN_set_word(Ri, BN_MASK2)) goto err; /* Ri-- (mod word size) */ } if (!BN_div(Ri, NULL, Ri, &tmod, ctx)) goto err; /* * Ni = (R*Ri-1)/N, keep only least significant word: */ mont->n0[0] = (Ri->top > 0) ? Ri->d[0] : 0; mont->n0[1] = 0; # endif } #else /* !MONT_WORD */ { /* bignum version */ mont->ri = BN_num_bits(&mont->N); BN_zero(R); if (!BN_set_bit(R, mont->ri)) goto err; /* R = 2^ri */ /* Ri = R^-1 mod N */ if ((BN_mod_inverse(Ri, R, &mont->N, ctx)) == NULL) goto err; if (!BN_lshift(Ri, Ri, mont->ri)) goto err; /* R*Ri */ if (!BN_sub_word(Ri, 1)) goto err; /* * Ni = (R*Ri-1) / N */ if (!BN_div(&(mont->Ni), NULL, Ri, &mont->N, ctx)) goto err; } #endif /* setup RR for conversions */ BN_zero(&(mont->RR)); if (!BN_set_bit(&(mont->RR), mont->ri * 2)) goto err; if (!BN_mod(&(mont->RR), &(mont->RR), &(mont->N), ctx)) goto err; for (i = mont->RR.top, ret = mont->N.top; i < ret; i++) mont->RR.d[i] = 0; mont->RR.top = ret; mont->RR.flags |= BN_FLG_FIXED_TOP; ret = 1; err: BN_CTX_end(ctx); return ret; } BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from) { if (to == from) return to; if (!BN_copy(&(to->RR), &(from->RR))) return NULL; if (!BN_copy(&(to->N), &(from->N))) return NULL; if (!BN_copy(&(to->Ni), &(from->Ni))) return NULL; to->ri = from->ri; to->n0[0] = from->n0[0]; to->n0[1] = from->n0[1]; return to; } BN_MONT_CTX *BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, CRYPTO_RWLOCK *lock, const BIGNUM *mod, BN_CTX *ctx) { BN_MONT_CTX *ret; if (!CRYPTO_THREAD_read_lock(lock)) return NULL; ret = *pmont; CRYPTO_THREAD_unlock(lock); if (ret) return ret; /* * We don't want to serialize globally while doing our lazy-init math in * BN_MONT_CTX_set. That punishes threads that are doing independent * things. Instead, punish the case where more than one thread tries to * lazy-init the same 'pmont', by having each do the lazy-init math work * independently and only use the one from the thread that wins the race * (the losers throw away the work they've done). */ ret = BN_MONT_CTX_new(); if (ret == NULL) return NULL; if (!BN_MONT_CTX_set(ret, mod, ctx)) { BN_MONT_CTX_free(ret); return NULL; } /* The locked compare-and-set, after the local work is done. */ if (!CRYPTO_THREAD_write_lock(lock)) { BN_MONT_CTX_free(ret); return NULL; } if (*pmont) { BN_MONT_CTX_free(ret); ret = *pmont; } else *pmont = ret; CRYPTO_THREAD_unlock(lock); return ret; }
12,474
25.655983
79
c
openssl
openssl-master/crypto/bn/bn_mpi.c
/* * Copyright 1995-2020 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 */ #include <stdio.h> #include "internal/cryptlib.h" #include "bn_local.h" int BN_bn2mpi(const BIGNUM *a, unsigned char *d) { int bits; int num = 0; int ext = 0; long l; bits = BN_num_bits(a); num = (bits + 7) / 8; if (bits > 0) { ext = ((bits & 0x07) == 0); } if (d == NULL) return (num + 4 + ext); l = num + ext; d[0] = (unsigned char)(l >> 24) & 0xff; d[1] = (unsigned char)(l >> 16) & 0xff; d[2] = (unsigned char)(l >> 8) & 0xff; d[3] = (unsigned char)(l) & 0xff; if (ext) d[4] = 0; num = BN_bn2bin(a, &(d[4 + ext])); if (a->neg) d[4] |= 0x80; return (num + 4 + ext); } BIGNUM *BN_mpi2bn(const unsigned char *d, int n, BIGNUM *ain) { long len; int neg = 0; BIGNUM *a = NULL; if (n < 4 || (d[0] & 0x80) != 0) { ERR_raise(ERR_LIB_BN, BN_R_INVALID_LENGTH); return NULL; } len = ((long)d[0] << 24) | ((long)d[1] << 16) | ((int)d[2] << 8) | (int) d[3]; if ((len + 4) != n) { ERR_raise(ERR_LIB_BN, BN_R_ENCODING_ERROR); return NULL; } if (ain == NULL) a = BN_new(); else a = ain; if (a == NULL) return NULL; if (len == 0) { a->neg = 0; a->top = 0; return a; } d += 4; if ((*d) & 0x80) neg = 1; if (BN_bin2bn(d, (int)len, a) == NULL) { if (ain == NULL) BN_free(a); return NULL; } a->neg = neg; if (neg) { BN_clear_bit(a, BN_num_bits(a) - 1); } bn_check_top(a); return a; }
1,936
21.264368
76
c
openssl
openssl-master/crypto/bn/bn_mul.c
/* * Copyright 1995-2018 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 */ #include <assert.h> #include "internal/cryptlib.h" #include "bn_local.h" #if defined(OPENSSL_NO_ASM) || !defined(OPENSSL_BN_ASM_PART_WORDS) /* * Here follows specialised variants of bn_add_words() and bn_sub_words(). * They have the property performing operations on arrays of different sizes. * The sizes of those arrays is expressed through cl, which is the common * length ( basically, min(len(a),len(b)) ), and dl, which is the delta * between the two lengths, calculated as len(a)-len(b). All lengths are the * number of BN_ULONGs... For the operations that require a result array as * parameter, it must have the length cl+abs(dl). These functions should * probably end up in bn_asm.c as soon as there are assembler counterparts * for the systems that use assembler files. */ BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, int cl, int dl) { BN_ULONG c, t; assert(cl >= 0); c = bn_sub_words(r, a, b, cl); if (dl == 0) return c; r += cl; a += cl; b += cl; if (dl < 0) { for (;;) { t = b[0]; r[0] = (0 - t - c) & BN_MASK2; if (t != 0) c = 1; if (++dl >= 0) break; t = b[1]; r[1] = (0 - t - c) & BN_MASK2; if (t != 0) c = 1; if (++dl >= 0) break; t = b[2]; r[2] = (0 - t - c) & BN_MASK2; if (t != 0) c = 1; if (++dl >= 0) break; t = b[3]; r[3] = (0 - t - c) & BN_MASK2; if (t != 0) c = 1; if (++dl >= 0) break; b += 4; r += 4; } } else { int save_dl = dl; while (c) { t = a[0]; r[0] = (t - c) & BN_MASK2; if (t != 0) c = 0; if (--dl <= 0) break; t = a[1]; r[1] = (t - c) & BN_MASK2; if (t != 0) c = 0; if (--dl <= 0) break; t = a[2]; r[2] = (t - c) & BN_MASK2; if (t != 0) c = 0; if (--dl <= 0) break; t = a[3]; r[3] = (t - c) & BN_MASK2; if (t != 0) c = 0; if (--dl <= 0) break; save_dl = dl; a += 4; r += 4; } if (dl > 0) { if (save_dl > dl) { switch (save_dl - dl) { case 1: r[1] = a[1]; if (--dl <= 0) break; /* fall through */ case 2: r[2] = a[2]; if (--dl <= 0) break; /* fall through */ case 3: r[3] = a[3]; if (--dl <= 0) break; } a += 4; r += 4; } } if (dl > 0) { for (;;) { r[0] = a[0]; if (--dl <= 0) break; r[1] = a[1]; if (--dl <= 0) break; r[2] = a[2]; if (--dl <= 0) break; r[3] = a[3]; if (--dl <= 0) break; a += 4; r += 4; } } } return c; } #endif #ifdef BN_RECURSION /* * Karatsuba recursive multiplication algorithm (cf. Knuth, The Art of * Computer Programming, Vol. 2) */ /*- * r is 2*n2 words in size, * a and b are both n2 words in size. * n2 must be a power of 2. * We multiply and return the result. * t must be 2*n2 words in size * We calculate * a[0]*b[0] * a[0]*b[0]+a[1]*b[1]+(a[0]-a[1])*(b[1]-b[0]) * a[1]*b[1] */ /* dnX may not be positive, but n2/2+dnX has to be */ void bn_mul_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2, int dna, int dnb, BN_ULONG *t) { int n = n2 / 2, c1, c2; int tna = n + dna, tnb = n + dnb; unsigned int neg, zero; BN_ULONG ln, lo, *p; # ifdef BN_MUL_COMBA # if 0 if (n2 == 4) { bn_mul_comba4(r, a, b); return; } # endif /* * Only call bn_mul_comba 8 if n2 == 8 and the two arrays are complete * [steve] */ if (n2 == 8 && dna == 0 && dnb == 0) { bn_mul_comba8(r, a, b); return; } # endif /* BN_MUL_COMBA */ /* Else do normal multiply */ if (n2 < BN_MUL_RECURSIVE_SIZE_NORMAL) { bn_mul_normal(r, a, n2 + dna, b, n2 + dnb); if ((dna + dnb) < 0) memset(&r[2 * n2 + dna + dnb], 0, sizeof(BN_ULONG) * -(dna + dnb)); return; } /* r=(a[0]-a[1])*(b[1]-b[0]) */ c1 = bn_cmp_part_words(a, &(a[n]), tna, n - tna); c2 = bn_cmp_part_words(&(b[n]), b, tnb, tnb - n); zero = neg = 0; switch (c1 * 3 + c2) { case -4: bn_sub_part_words(t, &(a[n]), a, tna, tna - n); /* - */ bn_sub_part_words(&(t[n]), b, &(b[n]), tnb, n - tnb); /* - */ break; case -3: zero = 1; break; case -2: bn_sub_part_words(t, &(a[n]), a, tna, tna - n); /* - */ bn_sub_part_words(&(t[n]), &(b[n]), b, tnb, tnb - n); /* + */ neg = 1; break; case -1: case 0: case 1: zero = 1; break; case 2: bn_sub_part_words(t, a, &(a[n]), tna, n - tna); /* + */ bn_sub_part_words(&(t[n]), b, &(b[n]), tnb, n - tnb); /* - */ neg = 1; break; case 3: zero = 1; break; case 4: bn_sub_part_words(t, a, &(a[n]), tna, n - tna); bn_sub_part_words(&(t[n]), &(b[n]), b, tnb, tnb - n); break; } # ifdef BN_MUL_COMBA if (n == 4 && dna == 0 && dnb == 0) { /* XXX: bn_mul_comba4 could take * extra args to do this well */ if (!zero) bn_mul_comba4(&(t[n2]), t, &(t[n])); else memset(&t[n2], 0, sizeof(*t) * 8); bn_mul_comba4(r, a, b); bn_mul_comba4(&(r[n2]), &(a[n]), &(b[n])); } else if (n == 8 && dna == 0 && dnb == 0) { /* XXX: bn_mul_comba8 could * take extra args to do * this well */ if (!zero) bn_mul_comba8(&(t[n2]), t, &(t[n])); else memset(&t[n2], 0, sizeof(*t) * 16); bn_mul_comba8(r, a, b); bn_mul_comba8(&(r[n2]), &(a[n]), &(b[n])); } else # endif /* BN_MUL_COMBA */ { p = &(t[n2 * 2]); if (!zero) bn_mul_recursive(&(t[n2]), t, &(t[n]), n, 0, 0, p); else memset(&t[n2], 0, sizeof(*t) * n2); bn_mul_recursive(r, a, b, n, 0, 0, p); bn_mul_recursive(&(r[n2]), &(a[n]), &(b[n]), n, dna, dnb, p); } /*- * t[32] holds (a[0]-a[1])*(b[1]-b[0]), c1 is the sign * r[10] holds (a[0]*b[0]) * r[32] holds (b[1]*b[1]) */ c1 = (int)(bn_add_words(t, r, &(r[n2]), n2)); if (neg) { /* if t[32] is negative */ c1 -= (int)(bn_sub_words(&(t[n2]), t, &(t[n2]), n2)); } else { /* Might have a carry */ c1 += (int)(bn_add_words(&(t[n2]), &(t[n2]), t, n2)); } /*- * t[32] holds (a[0]-a[1])*(b[1]-b[0])+(a[0]*b[0])+(a[1]*b[1]) * r[10] holds (a[0]*b[0]) * r[32] holds (b[1]*b[1]) * c1 holds the carry bits */ c1 += (int)(bn_add_words(&(r[n]), &(r[n]), &(t[n2]), n2)); if (c1) { p = &(r[n + n2]); lo = *p; ln = (lo + c1) & BN_MASK2; *p = ln; /* * The overflow will stop before we over write words we should not * overwrite */ if (ln < (BN_ULONG)c1) { do { p++; lo = *p; ln = (lo + 1) & BN_MASK2; *p = ln; } while (ln == 0); } } } /* * n+tn is the word length t needs to be n*4 is size, as does r */ /* tnX may not be negative but less than n */ void bn_mul_part_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n, int tna, int tnb, BN_ULONG *t) { int i, j, n2 = n * 2; int c1, c2, neg; BN_ULONG ln, lo, *p; if (n < 8) { bn_mul_normal(r, a, n + tna, b, n + tnb); return; } /* r=(a[0]-a[1])*(b[1]-b[0]) */ c1 = bn_cmp_part_words(a, &(a[n]), tna, n - tna); c2 = bn_cmp_part_words(&(b[n]), b, tnb, tnb - n); neg = 0; switch (c1 * 3 + c2) { case -4: bn_sub_part_words(t, &(a[n]), a, tna, tna - n); /* - */ bn_sub_part_words(&(t[n]), b, &(b[n]), tnb, n - tnb); /* - */ break; case -3: case -2: bn_sub_part_words(t, &(a[n]), a, tna, tna - n); /* - */ bn_sub_part_words(&(t[n]), &(b[n]), b, tnb, tnb - n); /* + */ neg = 1; break; case -1: case 0: case 1: case 2: bn_sub_part_words(t, a, &(a[n]), tna, n - tna); /* + */ bn_sub_part_words(&(t[n]), b, &(b[n]), tnb, n - tnb); /* - */ neg = 1; break; case 3: case 4: bn_sub_part_words(t, a, &(a[n]), tna, n - tna); bn_sub_part_words(&(t[n]), &(b[n]), b, tnb, tnb - n); break; } /* * The zero case isn't yet implemented here. The speedup would probably * be negligible. */ # if 0 if (n == 4) { bn_mul_comba4(&(t[n2]), t, &(t[n])); bn_mul_comba4(r, a, b); bn_mul_normal(&(r[n2]), &(a[n]), tn, &(b[n]), tn); memset(&r[n2 + tn * 2], 0, sizeof(*r) * (n2 - tn * 2)); } else # endif if (n == 8) { bn_mul_comba8(&(t[n2]), t, &(t[n])); bn_mul_comba8(r, a, b); bn_mul_normal(&(r[n2]), &(a[n]), tna, &(b[n]), tnb); memset(&r[n2 + tna + tnb], 0, sizeof(*r) * (n2 - tna - tnb)); } else { p = &(t[n2 * 2]); bn_mul_recursive(&(t[n2]), t, &(t[n]), n, 0, 0, p); bn_mul_recursive(r, a, b, n, 0, 0, p); i = n / 2; /* * If there is only a bottom half to the number, just do it */ if (tna > tnb) j = tna - i; else j = tnb - i; if (j == 0) { bn_mul_recursive(&(r[n2]), &(a[n]), &(b[n]), i, tna - i, tnb - i, p); memset(&r[n2 + i * 2], 0, sizeof(*r) * (n2 - i * 2)); } else if (j > 0) { /* eg, n == 16, i == 8 and tn == 11 */ bn_mul_part_recursive(&(r[n2]), &(a[n]), &(b[n]), i, tna - i, tnb - i, p); memset(&(r[n2 + tna + tnb]), 0, sizeof(BN_ULONG) * (n2 - tna - tnb)); } else { /* (j < 0) eg, n == 16, i == 8 and tn == 5 */ memset(&r[n2], 0, sizeof(*r) * n2); if (tna < BN_MUL_RECURSIVE_SIZE_NORMAL && tnb < BN_MUL_RECURSIVE_SIZE_NORMAL) { bn_mul_normal(&(r[n2]), &(a[n]), tna, &(b[n]), tnb); } else { for (;;) { i /= 2; /* * these simplified conditions work exclusively because * difference between tna and tnb is 1 or 0 */ if (i < tna || i < tnb) { bn_mul_part_recursive(&(r[n2]), &(a[n]), &(b[n]), i, tna - i, tnb - i, p); break; } else if (i == tna || i == tnb) { bn_mul_recursive(&(r[n2]), &(a[n]), &(b[n]), i, tna - i, tnb - i, p); break; } } } } } /*- * t[32] holds (a[0]-a[1])*(b[1]-b[0]), c1 is the sign * r[10] holds (a[0]*b[0]) * r[32] holds (b[1]*b[1]) */ c1 = (int)(bn_add_words(t, r, &(r[n2]), n2)); if (neg) { /* if t[32] is negative */ c1 -= (int)(bn_sub_words(&(t[n2]), t, &(t[n2]), n2)); } else { /* Might have a carry */ c1 += (int)(bn_add_words(&(t[n2]), &(t[n2]), t, n2)); } /*- * t[32] holds (a[0]-a[1])*(b[1]-b[0])+(a[0]*b[0])+(a[1]*b[1]) * r[10] holds (a[0]*b[0]) * r[32] holds (b[1]*b[1]) * c1 holds the carry bits */ c1 += (int)(bn_add_words(&(r[n]), &(r[n]), &(t[n2]), n2)); if (c1) { p = &(r[n + n2]); lo = *p; ln = (lo + c1) & BN_MASK2; *p = ln; /* * The overflow will stop before we over write words we should not * overwrite */ if (ln < (BN_ULONG)c1) { do { p++; lo = *p; ln = (lo + 1) & BN_MASK2; *p = ln; } while (ln == 0); } } } /*- * a and b must be the same size, which is n2. * r needs to be n2 words and t needs to be n2*2 */ void bn_mul_low_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2, BN_ULONG *t) { int n = n2 / 2; bn_mul_recursive(r, a, b, n, 0, 0, &(t[0])); if (n >= BN_MUL_LOW_RECURSIVE_SIZE_NORMAL) { bn_mul_low_recursive(&(t[0]), &(a[0]), &(b[n]), n, &(t[n2])); bn_add_words(&(r[n]), &(r[n]), &(t[0]), n); bn_mul_low_recursive(&(t[0]), &(a[n]), &(b[0]), n, &(t[n2])); bn_add_words(&(r[n]), &(r[n]), &(t[0]), n); } else { bn_mul_low_normal(&(t[0]), &(a[0]), &(b[n]), n); bn_mul_low_normal(&(t[n]), &(a[n]), &(b[0]), n); bn_add_words(&(r[n]), &(r[n]), &(t[0]), n); bn_add_words(&(r[n]), &(r[n]), &(t[n]), n); } } #endif /* BN_RECURSION */ int BN_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { int ret = bn_mul_fixed_top(r, a, b, ctx); bn_correct_top(r); bn_check_top(r); return ret; } int bn_mul_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { int ret = 0; int top, al, bl; BIGNUM *rr; #if defined(BN_MUL_COMBA) || defined(BN_RECURSION) int i; #endif #ifdef BN_RECURSION BIGNUM *t = NULL; int j = 0, k; #endif bn_check_top(a); bn_check_top(b); bn_check_top(r); al = a->top; bl = b->top; if ((al == 0) || (bl == 0)) { BN_zero(r); return 1; } top = al + bl; BN_CTX_start(ctx); if ((r == a) || (r == b)) { if ((rr = BN_CTX_get(ctx)) == NULL) goto err; } else rr = r; #if defined(BN_MUL_COMBA) || defined(BN_RECURSION) i = al - bl; #endif #ifdef BN_MUL_COMBA if (i == 0) { # if 0 if (al == 4) { if (bn_wexpand(rr, 8) == NULL) goto err; rr->top = 8; bn_mul_comba4(rr->d, a->d, b->d); goto end; } # endif if (al == 8) { if (bn_wexpand(rr, 16) == NULL) goto err; rr->top = 16; bn_mul_comba8(rr->d, a->d, b->d); goto end; } } #endif /* BN_MUL_COMBA */ #ifdef BN_RECURSION if ((al >= BN_MULL_SIZE_NORMAL) && (bl >= BN_MULL_SIZE_NORMAL)) { if (i >= -1 && i <= 1) { /* * Find out the power of two lower or equal to the longest of the * two numbers */ if (i >= 0) { j = BN_num_bits_word((BN_ULONG)al); } if (i == -1) { j = BN_num_bits_word((BN_ULONG)bl); } j = 1 << (j - 1); assert(j <= al || j <= bl); k = j + j; t = BN_CTX_get(ctx); if (t == NULL) goto err; if (al > j || bl > j) { if (bn_wexpand(t, k * 4) == NULL) goto err; if (bn_wexpand(rr, k * 4) == NULL) goto err; bn_mul_part_recursive(rr->d, a->d, b->d, j, al - j, bl - j, t->d); } else { /* al <= j || bl <= j */ if (bn_wexpand(t, k * 2) == NULL) goto err; if (bn_wexpand(rr, k * 2) == NULL) goto err; bn_mul_recursive(rr->d, a->d, b->d, j, al - j, bl - j, t->d); } rr->top = top; goto end; } } #endif /* BN_RECURSION */ if (bn_wexpand(rr, top) == NULL) goto err; rr->top = top; bn_mul_normal(rr->d, a->d, al, b->d, bl); #if defined(BN_MUL_COMBA) || defined(BN_RECURSION) end: #endif rr->neg = a->neg ^ b->neg; rr->flags |= BN_FLG_FIXED_TOP; if (r != rr && BN_copy(r, rr) == NULL) goto err; ret = 1; err: bn_check_top(r); BN_CTX_end(ctx); return ret; } void bn_mul_normal(BN_ULONG *r, BN_ULONG *a, int na, BN_ULONG *b, int nb) { BN_ULONG *rr; if (na < nb) { int itmp; BN_ULONG *ltmp; itmp = na; na = nb; nb = itmp; ltmp = a; a = b; b = ltmp; } rr = &(r[na]); if (nb <= 0) { (void)bn_mul_words(r, a, na, 0); return; } else rr[0] = bn_mul_words(r, a, na, b[0]); for (;;) { if (--nb <= 0) return; rr[1] = bn_mul_add_words(&(r[1]), a, na, b[1]); if (--nb <= 0) return; rr[2] = bn_mul_add_words(&(r[2]), a, na, b[2]); if (--nb <= 0) return; rr[3] = bn_mul_add_words(&(r[3]), a, na, b[3]); if (--nb <= 0) return; rr[4] = bn_mul_add_words(&(r[4]), a, na, b[4]); rr += 4; r += 4; b += 4; } } void bn_mul_low_normal(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n) { bn_mul_words(r, a, n, b[0]); for (;;) { if (--n <= 0) return; bn_mul_add_words(&(r[1]), a, n, b[1]); if (--n <= 0) return; bn_mul_add_words(&(r[2]), a, n, b[2]); if (--n <= 0) return; bn_mul_add_words(&(r[3]), a, n, b[3]); if (--n <= 0) return; bn_mul_add_words(&(r[4]), a, n, b[4]); r += 4; b += 4; } }
19,149
26.956204
78
c
openssl
openssl-master/crypto/bn/bn_ppc.c
/* * Copyright 2009-2022 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 */ #include <openssl/crypto.h> #include <openssl/bn.h> #include "crypto/ppc_arch.h" #include "bn_local.h" int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num) { int bn_mul_mont_int(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); int bn_mul4x_mont_int(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); int bn_mul_mont_fixed_n6(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); int bn_mul_mont_300_fixed_n6(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); if (num < 4) return 0; if ((num & 3) == 0) return bn_mul4x_mont_int(rp, ap, bp, np, n0, num); /* * There used to be [optional] call to bn_mul_mont_fpu64 here, * but above subroutine is faster on contemporary processors. * Formulation means that there might be old processors where * FPU code path would be faster, POWER6 perhaps, but there was * no opportunity to figure it out... */ #if defined(_ARCH_PPC64) && !defined(__ILP32__) if (num == 6) { if (OPENSSL_ppccap_P & PPC_MADD300) return bn_mul_mont_300_fixed_n6(rp, ap, bp, np, n0, num); else return bn_mul_mont_fixed_n6(rp, ap, bp, np, n0, num); } #endif return bn_mul_mont_int(rp, ap, bp, np, n0, num); }
2,056
37.092593
79
c
openssl
openssl-master/crypto/bn/bn_prime.c
/* * Copyright 1995-2021 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 */ #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include "bn_local.h" /* * The quick sieve algorithm approach to weeding out primes is Philip * Zimmermann's, as implemented in PGP. I have had a read of his comments * and implemented my own version. */ #include "bn_prime.h" static int probable_prime(BIGNUM *rnd, int bits, int safe, prime_t *mods, BN_CTX *ctx); static int probable_prime_dh(BIGNUM *rnd, int bits, int safe, prime_t *mods, const BIGNUM *add, const BIGNUM *rem, BN_CTX *ctx); static int bn_is_prime_int(const BIGNUM *w, int checks, BN_CTX *ctx, int do_trial_division, BN_GENCB *cb); #define square(x) ((BN_ULONG)(x) * (BN_ULONG)(x)) #if BN_BITS2 == 64 # define BN_DEF(lo, hi) (BN_ULONG)hi<<32|lo #else # define BN_DEF(lo, hi) lo, hi #endif /* * See SP800 89 5.3.3 (Step f) * The product of the set of primes ranging from 3 to 751 * Generated using process in test/bn_internal_test.c test_bn_small_factors(). * This includes 751 (which is not currently included in SP 800-89). */ static const BN_ULONG small_prime_factors[] = { BN_DEF(0x3ef4e3e1, 0xc4309333), BN_DEF(0xcd2d655f, 0x71161eb6), BN_DEF(0x0bf94862, 0x95e2238c), BN_DEF(0x24f7912b, 0x3eb233d3), BN_DEF(0xbf26c483, 0x6b55514b), BN_DEF(0x5a144871, 0x0a84d817), BN_DEF(0x9b82210a, 0x77d12fee), BN_DEF(0x97f050b3, 0xdb5b93c2), BN_DEF(0x4d6c026b, 0x4acad6b9), BN_DEF(0x54aec893, 0xeb7751f3), BN_DEF(0x36bc85c4, 0xdba53368), BN_DEF(0x7f5ec78e, 0xd85a1b28), BN_DEF(0x6b322244, 0x2eb072d8), BN_DEF(0x5e2b3aea, 0xbba51112), BN_DEF(0x0e2486bf, 0x36ed1a6c), BN_DEF(0xec0c5727, 0x5f270460), (BN_ULONG)0x000017b1 }; #define BN_SMALL_PRIME_FACTORS_TOP OSSL_NELEM(small_prime_factors) static const BIGNUM _bignum_small_prime_factors = { (BN_ULONG *)small_prime_factors, BN_SMALL_PRIME_FACTORS_TOP, BN_SMALL_PRIME_FACTORS_TOP, 0, BN_FLG_STATIC_DATA }; const BIGNUM *ossl_bn_get0_small_factors(void) { return &_bignum_small_prime_factors; } /* * Calculate the number of trial divisions that gives the best speed in * combination with Miller-Rabin prime test, based on the sized of the prime. */ static int calc_trial_divisions(int bits) { if (bits <= 512) return 64; else if (bits <= 1024) return 128; else if (bits <= 2048) return 384; else if (bits <= 4096) return 1024; return NUMPRIMES; } /* * Use a minimum of 64 rounds of Miller-Rabin, which should give a false * positive rate of 2^-128. If the size of the prime is larger than 2048 * the user probably wants a higher security level than 128, so switch * to 128 rounds giving a false positive rate of 2^-256. * Returns the number of rounds. */ static int bn_mr_min_checks(int bits) { if (bits > 2048) return 128; return 64; } int BN_GENCB_call(BN_GENCB *cb, int a, int b) { /* No callback means continue */ if (!cb) return 1; switch (cb->ver) { case 1: /* Deprecated-style callbacks */ if (!cb->cb.cb_1) return 1; cb->cb.cb_1(a, b, cb->arg); return 1; case 2: /* New-style callbacks */ return cb->cb.cb_2(a, b, cb); default: break; } /* Unrecognised callback type */ return 0; } int BN_generate_prime_ex2(BIGNUM *ret, int bits, int safe, const BIGNUM *add, const BIGNUM *rem, BN_GENCB *cb, BN_CTX *ctx) { BIGNUM *t; int found = 0; int i, j, c1 = 0; prime_t *mods = NULL; int checks = bn_mr_min_checks(bits); if (bits < 2) { /* There are no prime numbers this small. */ ERR_raise(ERR_LIB_BN, BN_R_BITS_TOO_SMALL); return 0; } else if (add == NULL && safe && bits < 6 && bits != 3) { /* * The smallest safe prime (7) is three bits. * But the following two safe primes with less than 6 bits (11, 23) * are unreachable for BN_rand with BN_RAND_TOP_TWO. */ ERR_raise(ERR_LIB_BN, BN_R_BITS_TOO_SMALL); return 0; } mods = OPENSSL_zalloc(sizeof(*mods) * NUMPRIMES); if (mods == NULL) return 0; BN_CTX_start(ctx); t = BN_CTX_get(ctx); if (t == NULL) goto err; loop: /* make a random number and set the top and bottom bits */ if (add == NULL) { if (!probable_prime(ret, bits, safe, mods, ctx)) goto err; } else { if (!probable_prime_dh(ret, bits, safe, mods, add, rem, ctx)) goto err; } if (!BN_GENCB_call(cb, 0, c1++)) /* aborted */ goto err; if (!safe) { i = bn_is_prime_int(ret, checks, ctx, 0, cb); if (i == -1) goto err; if (i == 0) goto loop; } else { /* * for "safe prime" generation, check that (p-1)/2 is prime. Since a * prime is odd, We just need to divide by 2 */ if (!BN_rshift1(t, ret)) goto err; for (i = 0; i < checks; i++) { j = bn_is_prime_int(ret, 1, ctx, 0, cb); if (j == -1) goto err; if (j == 0) goto loop; j = bn_is_prime_int(t, 1, ctx, 0, cb); if (j == -1) goto err; if (j == 0) goto loop; if (!BN_GENCB_call(cb, 2, c1 - 1)) goto err; /* We have a safe prime test pass */ } } /* we have a prime :-) */ found = 1; err: OPENSSL_free(mods); BN_CTX_end(ctx); bn_check_top(ret); return found; } #ifndef FIPS_MODULE int BN_generate_prime_ex(BIGNUM *ret, int bits, int safe, const BIGNUM *add, const BIGNUM *rem, BN_GENCB *cb) { BN_CTX *ctx = BN_CTX_new(); int retval; if (ctx == NULL) return 0; retval = BN_generate_prime_ex2(ret, bits, safe, add, rem, cb, ctx); BN_CTX_free(ctx); return retval; } #endif #ifndef OPENSSL_NO_DEPRECATED_3_0 int BN_is_prime_ex(const BIGNUM *a, int checks, BN_CTX *ctx_passed, BN_GENCB *cb) { return ossl_bn_check_prime(a, checks, ctx_passed, 0, cb); } int BN_is_prime_fasttest_ex(const BIGNUM *w, int checks, BN_CTX *ctx, int do_trial_division, BN_GENCB *cb) { return ossl_bn_check_prime(w, checks, ctx, do_trial_division, cb); } #endif /* Wrapper around bn_is_prime_int that sets the minimum number of checks */ int ossl_bn_check_prime(const BIGNUM *w, int checks, BN_CTX *ctx, int do_trial_division, BN_GENCB *cb) { int min_checks = bn_mr_min_checks(BN_num_bits(w)); if (checks < min_checks) checks = min_checks; return bn_is_prime_int(w, checks, ctx, do_trial_division, cb); } /* * Use this only for key generation. * It always uses trial division. The number of checks * (MR rounds) passed in is used without being clamped to a minimum value. */ int ossl_bn_check_generated_prime(const BIGNUM *w, int checks, BN_CTX *ctx, BN_GENCB *cb) { return bn_is_prime_int(w, checks, ctx, 1, cb); } int BN_check_prime(const BIGNUM *p, BN_CTX *ctx, BN_GENCB *cb) { return ossl_bn_check_prime(p, 0, ctx, 1, cb); } /* * Tests that |w| is probably prime * See FIPS 186-4 C.3.1 Miller Rabin Probabilistic Primality Test. * * Returns 0 when composite, 1 when probable prime, -1 on error. */ static int bn_is_prime_int(const BIGNUM *w, int checks, BN_CTX *ctx, int do_trial_division, BN_GENCB *cb) { int i, status, ret = -1; #ifndef FIPS_MODULE BN_CTX *ctxlocal = NULL; #else if (ctx == NULL) return -1; #endif /* w must be bigger than 1 */ if (BN_cmp(w, BN_value_one()) <= 0) return 0; /* w must be odd */ if (BN_is_odd(w)) { /* Take care of the really small prime 3 */ if (BN_is_word(w, 3)) return 1; } else { /* 2 is the only even prime */ return BN_is_word(w, 2); } /* first look for small factors */ if (do_trial_division) { int trial_divisions = calc_trial_divisions(BN_num_bits(w)); for (i = 1; i < trial_divisions; i++) { BN_ULONG mod = BN_mod_word(w, primes[i]); if (mod == (BN_ULONG)-1) return -1; if (mod == 0) return BN_is_word(w, primes[i]); } if (!BN_GENCB_call(cb, 1, -1)) return -1; } #ifndef FIPS_MODULE if (ctx == NULL && (ctxlocal = ctx = BN_CTX_new()) == NULL) goto err; #endif if (!ossl_bn_miller_rabin_is_prime(w, checks, ctx, cb, 0, &status)) { ret = -1; goto err; } ret = (status == BN_PRIMETEST_PROBABLY_PRIME); err: #ifndef FIPS_MODULE BN_CTX_free(ctxlocal); #endif return ret; } /* * Refer to FIPS 186-4 C.3.2 Enhanced Miller-Rabin Probabilistic Primality Test. * OR C.3.1 Miller-Rabin Probabilistic Primality Test (if enhanced is zero). * The Step numbers listed in the code refer to the enhanced case. * * if enhanced is set, then status returns one of the following: * BN_PRIMETEST_PROBABLY_PRIME * BN_PRIMETEST_COMPOSITE_WITH_FACTOR * BN_PRIMETEST_COMPOSITE_NOT_POWER_OF_PRIME * if enhanced is zero, then status returns either * BN_PRIMETEST_PROBABLY_PRIME or * BN_PRIMETEST_COMPOSITE * * returns 0 if there was an error, otherwise it returns 1. */ int ossl_bn_miller_rabin_is_prime(const BIGNUM *w, int iterations, BN_CTX *ctx, BN_GENCB *cb, int enhanced, int *status) { int i, j, a, ret = 0; BIGNUM *g, *w1, *w3, *x, *m, *z, *b; BN_MONT_CTX *mont = NULL; /* w must be odd */ if (!BN_is_odd(w)) return 0; BN_CTX_start(ctx); g = BN_CTX_get(ctx); w1 = BN_CTX_get(ctx); w3 = BN_CTX_get(ctx); x = BN_CTX_get(ctx); m = BN_CTX_get(ctx); z = BN_CTX_get(ctx); b = BN_CTX_get(ctx); if (!(b != NULL /* w1 := w - 1 */ && BN_copy(w1, w) && BN_sub_word(w1, 1) /* w3 := w - 3 */ && BN_copy(w3, w) && BN_sub_word(w3, 3))) goto err; /* check w is larger than 3, otherwise the random b will be too small */ if (BN_is_zero(w3) || BN_is_negative(w3)) goto err; /* (Step 1) Calculate largest integer 'a' such that 2^a divides w-1 */ a = 1; while (!BN_is_bit_set(w1, a)) a++; /* (Step 2) m = (w-1) / 2^a */ if (!BN_rshift(m, w1, a)) goto err; /* Montgomery setup for computations mod a */ mont = BN_MONT_CTX_new(); if (mont == NULL || !BN_MONT_CTX_set(mont, w, ctx)) goto err; if (iterations == 0) iterations = bn_mr_min_checks(BN_num_bits(w)); /* (Step 4) */ for (i = 0; i < iterations; ++i) { /* (Step 4.1) obtain a Random string of bits b where 1 < b < w-1 */ if (!BN_priv_rand_range_ex(b, w3, 0, ctx) || !BN_add_word(b, 2)) /* 1 < b < w-1 */ goto err; if (enhanced) { /* (Step 4.3) */ if (!BN_gcd(g, b, w, ctx)) goto err; /* (Step 4.4) */ if (!BN_is_one(g)) { *status = BN_PRIMETEST_COMPOSITE_WITH_FACTOR; ret = 1; goto err; } } /* (Step 4.5) z = b^m mod w */ if (!BN_mod_exp_mont(z, b, m, w, ctx, mont)) goto err; /* (Step 4.6) if (z = 1 or z = w-1) */ if (BN_is_one(z) || BN_cmp(z, w1) == 0) goto outer_loop; /* (Step 4.7) for j = 1 to a-1 */ for (j = 1; j < a ; ++j) { /* (Step 4.7.1 - 4.7.2) x = z. z = x^2 mod w */ if (!BN_copy(x, z) || !BN_mod_mul(z, x, x, w, ctx)) goto err; /* (Step 4.7.3) */ if (BN_cmp(z, w1) == 0) goto outer_loop; /* (Step 4.7.4) */ if (BN_is_one(z)) goto composite; } /* At this point z = b^((w-1)/2) mod w */ /* (Steps 4.8 - 4.9) x = z, z = x^2 mod w */ if (!BN_copy(x, z) || !BN_mod_mul(z, x, x, w, ctx)) goto err; /* (Step 4.10) */ if (BN_is_one(z)) goto composite; /* (Step 4.11) x = b^(w-1) mod w */ if (!BN_copy(x, z)) goto err; composite: if (enhanced) { /* (Step 4.1.2) g = GCD(x-1, w) */ if (!BN_sub_word(x, 1) || !BN_gcd(g, x, w, ctx)) goto err; /* (Steps 4.1.3 - 4.1.4) */ if (BN_is_one(g)) *status = BN_PRIMETEST_COMPOSITE_NOT_POWER_OF_PRIME; else *status = BN_PRIMETEST_COMPOSITE_WITH_FACTOR; } else { *status = BN_PRIMETEST_COMPOSITE; } ret = 1; goto err; outer_loop: ; /* (Step 4.1.5) */ if (!BN_GENCB_call(cb, 1, i)) goto err; } /* (Step 5) */ *status = BN_PRIMETEST_PROBABLY_PRIME; ret = 1; err: BN_clear(g); BN_clear(w1); BN_clear(w3); BN_clear(x); BN_clear(m); BN_clear(z); BN_clear(b); BN_CTX_end(ctx); BN_MONT_CTX_free(mont); return ret; } /* * Generate a random number of |bits| bits that is probably prime by sieving. * If |safe| != 0, it generates a safe prime. * |mods| is a preallocated array that gets reused when called again. * * The probably prime is saved in |rnd|. * * Returns 1 on success and 0 on error. */ static int probable_prime(BIGNUM *rnd, int bits, int safe, prime_t *mods, BN_CTX *ctx) { int i; BN_ULONG delta; int trial_divisions = calc_trial_divisions(bits); BN_ULONG maxdelta = BN_MASK2 - primes[trial_divisions - 1]; again: if (!BN_priv_rand_ex(rnd, bits, BN_RAND_TOP_TWO, BN_RAND_BOTTOM_ODD, 0, ctx)) return 0; if (safe && !BN_set_bit(rnd, 1)) return 0; /* we now have a random number 'rnd' to test. */ for (i = 1; i < trial_divisions; i++) { BN_ULONG mod = BN_mod_word(rnd, (BN_ULONG)primes[i]); if (mod == (BN_ULONG)-1) return 0; mods[i] = (prime_t) mod; } delta = 0; loop: for (i = 1; i < trial_divisions; i++) { /* * check that rnd is a prime and also that * gcd(rnd-1,primes) == 1 (except for 2) * do the second check only if we are interested in safe primes * in the case that the candidate prime is a single word then * we check only the primes up to sqrt(rnd) */ if (bits <= 31 && delta <= 0x7fffffff && square(primes[i]) > BN_get_word(rnd) + delta) break; if (safe ? (mods[i] + delta) % primes[i] <= 1 : (mods[i] + delta) % primes[i] == 0) { delta += safe ? 4 : 2; if (delta > maxdelta) goto again; goto loop; } } if (!BN_add_word(rnd, delta)) return 0; if (BN_num_bits(rnd) != bits) goto again; bn_check_top(rnd); return 1; } /* * Generate a random number |rnd| of |bits| bits that is probably prime * and satisfies |rnd| % |add| == |rem| by sieving. * If |safe| != 0, it generates a safe prime. * |mods| is a preallocated array that gets reused when called again. * * Returns 1 on success and 0 on error. */ static int probable_prime_dh(BIGNUM *rnd, int bits, int safe, prime_t *mods, const BIGNUM *add, const BIGNUM *rem, BN_CTX *ctx) { int i, ret = 0; BIGNUM *t1; BN_ULONG delta; int trial_divisions = calc_trial_divisions(bits); BN_ULONG maxdelta = BN_MASK2 - primes[trial_divisions - 1]; BN_CTX_start(ctx); if ((t1 = BN_CTX_get(ctx)) == NULL) goto err; if (maxdelta > BN_MASK2 - BN_get_word(add)) maxdelta = BN_MASK2 - BN_get_word(add); again: if (!BN_rand_ex(rnd, bits, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD, 0, ctx)) goto err; /* we need ((rnd-rem) % add) == 0 */ if (!BN_mod(t1, rnd, add, ctx)) goto err; if (!BN_sub(rnd, rnd, t1)) goto err; if (rem == NULL) { if (!BN_add_word(rnd, safe ? 3u : 1u)) goto err; } else { if (!BN_add(rnd, rnd, rem)) goto err; } if (BN_num_bits(rnd) < bits || BN_get_word(rnd) < (safe ? 5u : 3u)) { if (!BN_add(rnd, rnd, add)) goto err; } /* we now have a random number 'rnd' to test. */ for (i = 1; i < trial_divisions; i++) { BN_ULONG mod = BN_mod_word(rnd, (BN_ULONG)primes[i]); if (mod == (BN_ULONG)-1) goto err; mods[i] = (prime_t) mod; } delta = 0; loop: for (i = 1; i < trial_divisions; i++) { /* check that rnd is a prime */ if (bits <= 31 && delta <= 0x7fffffff && square(primes[i]) > BN_get_word(rnd) + delta) break; /* rnd mod p == 1 implies q = (rnd-1)/2 is divisible by p */ if (safe ? (mods[i] + delta) % primes[i] <= 1 : (mods[i] + delta) % primes[i] == 0) { delta += BN_get_word(add); if (delta > maxdelta) goto again; goto loop; } } if (!BN_add_word(rnd, delta)) goto err; ret = 1; err: BN_CTX_end(ctx); bn_check_top(rnd); return ret; }
18,003
28.132686
80
c
openssl
openssl-master/crypto/bn/bn_prime.h
/* * WARNING: do not edit! * Generated by crypto/bn/bn_prime.pl * * Copyright 1998-2021 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 */ typedef unsigned short prime_t; # define NUMPRIMES 2048 static const prime_t primes[2048] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087, 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791, 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133, 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833, 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207, 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919, 7927, 7933, 7937, 7949, 7951, 7963, 7993, 8009, 8011, 8017, 8039, 8053, 8059, 8069, 8081, 8087, 8089, 8093, 8101, 8111, 8117, 8123, 8147, 8161, 8167, 8171, 8179, 8191, 8209, 8219, 8221, 8231, 8233, 8237, 8243, 8263, 8269, 8273, 8287, 8291, 8293, 8297, 8311, 8317, 8329, 8353, 8363, 8369, 8377, 8387, 8389, 8419, 8423, 8429, 8431, 8443, 8447, 8461, 8467, 8501, 8513, 8521, 8527, 8537, 8539, 8543, 8563, 8573, 8581, 8597, 8599, 8609, 8623, 8627, 8629, 8641, 8647, 8663, 8669, 8677, 8681, 8689, 8693, 8699, 8707, 8713, 8719, 8731, 8737, 8741, 8747, 8753, 8761, 8779, 8783, 8803, 8807, 8819, 8821, 8831, 8837, 8839, 8849, 8861, 8863, 8867, 8887, 8893, 8923, 8929, 8933, 8941, 8951, 8963, 8969, 8971, 8999, 9001, 9007, 9011, 9013, 9029, 9041, 9043, 9049, 9059, 9067, 9091, 9103, 9109, 9127, 9133, 9137, 9151, 9157, 9161, 9173, 9181, 9187, 9199, 9203, 9209, 9221, 9227, 9239, 9241, 9257, 9277, 9281, 9283, 9293, 9311, 9319, 9323, 9337, 9341, 9343, 9349, 9371, 9377, 9391, 9397, 9403, 9413, 9419, 9421, 9431, 9433, 9437, 9439, 9461, 9463, 9467, 9473, 9479, 9491, 9497, 9511, 9521, 9533, 9539, 9547, 9551, 9587, 9601, 9613, 9619, 9623, 9629, 9631, 9643, 9649, 9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733, 9739, 9743, 9749, 9767, 9769, 9781, 9787, 9791, 9803, 9811, 9817, 9829, 9833, 9839, 9851, 9857, 9859, 9871, 9883, 9887, 9901, 9907, 9923, 9929, 9931, 9941, 9949, 9967, 9973, 10007, 10009, 10037, 10039, 10061, 10067, 10069, 10079, 10091, 10093, 10099, 10103, 10111, 10133, 10139, 10141, 10151, 10159, 10163, 10169, 10177, 10181, 10193, 10211, 10223, 10243, 10247, 10253, 10259, 10267, 10271, 10273, 10289, 10301, 10303, 10313, 10321, 10331, 10333, 10337, 10343, 10357, 10369, 10391, 10399, 10427, 10429, 10433, 10453, 10457, 10459, 10463, 10477, 10487, 10499, 10501, 10513, 10529, 10531, 10559, 10567, 10589, 10597, 10601, 10607, 10613, 10627, 10631, 10639, 10651, 10657, 10663, 10667, 10687, 10691, 10709, 10711, 10723, 10729, 10733, 10739, 10753, 10771, 10781, 10789, 10799, 10831, 10837, 10847, 10853, 10859, 10861, 10867, 10883, 10889, 10891, 10903, 10909, 10937, 10939, 10949, 10957, 10973, 10979, 10987, 10993, 11003, 11027, 11047, 11057, 11059, 11069, 11071, 11083, 11087, 11093, 11113, 11117, 11119, 11131, 11149, 11159, 11161, 11171, 11173, 11177, 11197, 11213, 11239, 11243, 11251, 11257, 11261, 11273, 11279, 11287, 11299, 11311, 11317, 11321, 11329, 11351, 11353, 11369, 11383, 11393, 11399, 11411, 11423, 11437, 11443, 11447, 11467, 11471, 11483, 11489, 11491, 11497, 11503, 11519, 11527, 11549, 11551, 11579, 11587, 11593, 11597, 11617, 11621, 11633, 11657, 11677, 11681, 11689, 11699, 11701, 11717, 11719, 11731, 11743, 11777, 11779, 11783, 11789, 11801, 11807, 11813, 11821, 11827, 11831, 11833, 11839, 11863, 11867, 11887, 11897, 11903, 11909, 11923, 11927, 11933, 11939, 11941, 11953, 11959, 11969, 11971, 11981, 11987, 12007, 12011, 12037, 12041, 12043, 12049, 12071, 12073, 12097, 12101, 12107, 12109, 12113, 12119, 12143, 12149, 12157, 12161, 12163, 12197, 12203, 12211, 12227, 12239, 12241, 12251, 12253, 12263, 12269, 12277, 12281, 12289, 12301, 12323, 12329, 12343, 12347, 12373, 12377, 12379, 12391, 12401, 12409, 12413, 12421, 12433, 12437, 12451, 12457, 12473, 12479, 12487, 12491, 12497, 12503, 12511, 12517, 12527, 12539, 12541, 12547, 12553, 12569, 12577, 12583, 12589, 12601, 12611, 12613, 12619, 12637, 12641, 12647, 12653, 12659, 12671, 12689, 12697, 12703, 12713, 12721, 12739, 12743, 12757, 12763, 12781, 12791, 12799, 12809, 12821, 12823, 12829, 12841, 12853, 12889, 12893, 12899, 12907, 12911, 12917, 12919, 12923, 12941, 12953, 12959, 12967, 12973, 12979, 12983, 13001, 13003, 13007, 13009, 13033, 13037, 13043, 13049, 13063, 13093, 13099, 13103, 13109, 13121, 13127, 13147, 13151, 13159, 13163, 13171, 13177, 13183, 13187, 13217, 13219, 13229, 13241, 13249, 13259, 13267, 13291, 13297, 13309, 13313, 13327, 13331, 13337, 13339, 13367, 13381, 13397, 13399, 13411, 13417, 13421, 13441, 13451, 13457, 13463, 13469, 13477, 13487, 13499, 13513, 13523, 13537, 13553, 13567, 13577, 13591, 13597, 13613, 13619, 13627, 13633, 13649, 13669, 13679, 13681, 13687, 13691, 13693, 13697, 13709, 13711, 13721, 13723, 13729, 13751, 13757, 13759, 13763, 13781, 13789, 13799, 13807, 13829, 13831, 13841, 13859, 13873, 13877, 13879, 13883, 13901, 13903, 13907, 13913, 13921, 13931, 13933, 13963, 13967, 13997, 13999, 14009, 14011, 14029, 14033, 14051, 14057, 14071, 14081, 14083, 14087, 14107, 14143, 14149, 14153, 14159, 14173, 14177, 14197, 14207, 14221, 14243, 14249, 14251, 14281, 14293, 14303, 14321, 14323, 14327, 14341, 14347, 14369, 14387, 14389, 14401, 14407, 14411, 14419, 14423, 14431, 14437, 14447, 14449, 14461, 14479, 14489, 14503, 14519, 14533, 14537, 14543, 14549, 14551, 14557, 14561, 14563, 14591, 14593, 14621, 14627, 14629, 14633, 14639, 14653, 14657, 14669, 14683, 14699, 14713, 14717, 14723, 14731, 14737, 14741, 14747, 14753, 14759, 14767, 14771, 14779, 14783, 14797, 14813, 14821, 14827, 14831, 14843, 14851, 14867, 14869, 14879, 14887, 14891, 14897, 14923, 14929, 14939, 14947, 14951, 14957, 14969, 14983, 15013, 15017, 15031, 15053, 15061, 15073, 15077, 15083, 15091, 15101, 15107, 15121, 15131, 15137, 15139, 15149, 15161, 15173, 15187, 15193, 15199, 15217, 15227, 15233, 15241, 15259, 15263, 15269, 15271, 15277, 15287, 15289, 15299, 15307, 15313, 15319, 15329, 15331, 15349, 15359, 15361, 15373, 15377, 15383, 15391, 15401, 15413, 15427, 15439, 15443, 15451, 15461, 15467, 15473, 15493, 15497, 15511, 15527, 15541, 15551, 15559, 15569, 15581, 15583, 15601, 15607, 15619, 15629, 15641, 15643, 15647, 15649, 15661, 15667, 15671, 15679, 15683, 15727, 15731, 15733, 15737, 15739, 15749, 15761, 15767, 15773, 15787, 15791, 15797, 15803, 15809, 15817, 15823, 15859, 15877, 15881, 15887, 15889, 15901, 15907, 15913, 15919, 15923, 15937, 15959, 15971, 15973, 15991, 16001, 16007, 16033, 16057, 16061, 16063, 16067, 16069, 16073, 16087, 16091, 16097, 16103, 16111, 16127, 16139, 16141, 16183, 16187, 16189, 16193, 16217, 16223, 16229, 16231, 16249, 16253, 16267, 16273, 16301, 16319, 16333, 16339, 16349, 16361, 16363, 16369, 16381, 16411, 16417, 16421, 16427, 16433, 16447, 16451, 16453, 16477, 16481, 16487, 16493, 16519, 16529, 16547, 16553, 16561, 16567, 16573, 16603, 16607, 16619, 16631, 16633, 16649, 16651, 16657, 16661, 16673, 16691, 16693, 16699, 16703, 16729, 16741, 16747, 16759, 16763, 16787, 16811, 16823, 16829, 16831, 16843, 16871, 16879, 16883, 16889, 16901, 16903, 16921, 16927, 16931, 16937, 16943, 16963, 16979, 16981, 16987, 16993, 17011, 17021, 17027, 17029, 17033, 17041, 17047, 17053, 17077, 17093, 17099, 17107, 17117, 17123, 17137, 17159, 17167, 17183, 17189, 17191, 17203, 17207, 17209, 17231, 17239, 17257, 17291, 17293, 17299, 17317, 17321, 17327, 17333, 17341, 17351, 17359, 17377, 17383, 17387, 17389, 17393, 17401, 17417, 17419, 17431, 17443, 17449, 17467, 17471, 17477, 17483, 17489, 17491, 17497, 17509, 17519, 17539, 17551, 17569, 17573, 17579, 17581, 17597, 17599, 17609, 17623, 17627, 17657, 17659, 17669, 17681, 17683, 17707, 17713, 17729, 17737, 17747, 17749, 17761, 17783, 17789, 17791, 17807, 17827, 17837, 17839, 17851, 17863, };
15,861
56.890511
74
h
openssl
openssl-master/crypto/bn/bn_print.c
/* * Copyright 1995-2017 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 */ #include <stdio.h> #include <openssl/bio.h> #include "bn_local.h" static const char Hex[] = "0123456789ABCDEF"; #ifndef OPENSSL_NO_STDIO int BN_print_fp(FILE *fp, const BIGNUM *a) { BIO *b; int ret; if ((b = BIO_new(BIO_s_file())) == NULL) return 0; BIO_set_fp(b, fp, BIO_NOCLOSE); ret = BN_print(b, a); BIO_free(b); return ret; } #endif int BN_print(BIO *bp, const BIGNUM *a) { int i, j, v, z = 0; int ret = 0; if ((a->neg) && BIO_write(bp, "-", 1) != 1) goto end; if (BN_is_zero(a) && BIO_write(bp, "0", 1) != 1) goto end; for (i = a->top - 1; i >= 0; i--) { for (j = BN_BITS2 - 4; j >= 0; j -= 4) { /* strip leading zeros */ v = (int)((a->d[i] >> j) & 0x0f); if (z || v != 0) { if (BIO_write(bp, &Hex[v], 1) != 1) goto end; z = 1; } } } ret = 1; end: return ret; } char *BN_options(void) { static int init = 0; static char data[16]; if (!init) { init++; #ifdef BN_LLONG BIO_snprintf(data, sizeof(data), "bn(%zu,%zu)", sizeof(BN_ULLONG) * 8, sizeof(BN_ULONG) * 8); #else BIO_snprintf(data, sizeof(data), "bn(%zu,%zu)", sizeof(BN_ULONG) * 8, sizeof(BN_ULONG) * 8); #endif } return data; }
1,721
22.589041
74
c
openssl
openssl-master/crypto/bn/bn_rand.c
/* * Copyright 1995-2021 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 */ #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include "crypto/rand.h" #include "bn_local.h" #include <openssl/rand.h> #include <openssl/sha.h> #include <openssl/evp.h> typedef enum bnrand_flag_e { NORMAL, TESTING, PRIVATE } BNRAND_FLAG; static int bnrand(BNRAND_FLAG flag, BIGNUM *rnd, int bits, int top, int bottom, unsigned int strength, BN_CTX *ctx) { unsigned char *buf = NULL; int b, ret = 0, bit, bytes, mask; OSSL_LIB_CTX *libctx = ossl_bn_get_libctx(ctx); if (bits == 0) { if (top != BN_RAND_TOP_ANY || bottom != BN_RAND_BOTTOM_ANY) goto toosmall; BN_zero(rnd); return 1; } if (bits < 0 || (bits == 1 && top > 0)) goto toosmall; bytes = (bits + 7) / 8; bit = (bits - 1) % 8; mask = 0xff << (bit + 1); buf = OPENSSL_malloc(bytes); if (buf == NULL) goto err; /* make a random number and set the top and bottom bits */ b = flag == NORMAL ? RAND_bytes_ex(libctx, buf, bytes, strength) : RAND_priv_bytes_ex(libctx, buf, bytes, strength); if (b <= 0) goto err; if (flag == TESTING) { /* * generate patterns that are more likely to trigger BN library bugs */ int i; unsigned char c; for (i = 0; i < bytes; i++) { if (RAND_bytes_ex(libctx, &c, 1, strength) <= 0) goto err; if (c >= 128 && i > 0) buf[i] = buf[i - 1]; else if (c < 42) buf[i] = 0; else if (c < 84) buf[i] = 255; } } if (top >= 0) { if (top) { if (bit == 0) { buf[0] = 1; buf[1] |= 0x80; } else { buf[0] |= (3 << (bit - 1)); } } else { buf[0] |= (1 << bit); } } buf[0] &= ~mask; if (bottom) /* set bottom bit if requested */ buf[bytes - 1] |= 1; if (!BN_bin2bn(buf, bytes, rnd)) goto err; ret = 1; err: OPENSSL_clear_free(buf, bytes); bn_check_top(rnd); return ret; toosmall: ERR_raise(ERR_LIB_BN, BN_R_BITS_TOO_SMALL); return 0; } int BN_rand_ex(BIGNUM *rnd, int bits, int top, int bottom, unsigned int strength, BN_CTX *ctx) { return bnrand(NORMAL, rnd, bits, top, bottom, strength, ctx); } #ifndef FIPS_MODULE int BN_rand(BIGNUM *rnd, int bits, int top, int bottom) { return bnrand(NORMAL, rnd, bits, top, bottom, 0, NULL); } int BN_bntest_rand(BIGNUM *rnd, int bits, int top, int bottom) { return bnrand(TESTING, rnd, bits, top, bottom, 0, NULL); } #endif int BN_priv_rand_ex(BIGNUM *rnd, int bits, int top, int bottom, unsigned int strength, BN_CTX *ctx) { return bnrand(PRIVATE, rnd, bits, top, bottom, strength, ctx); } #ifndef FIPS_MODULE int BN_priv_rand(BIGNUM *rnd, int bits, int top, int bottom) { return bnrand(PRIVATE, rnd, bits, top, bottom, 0, NULL); } #endif /* random number r: 0 <= r < range */ static int bnrand_range(BNRAND_FLAG flag, BIGNUM *r, const BIGNUM *range, unsigned int strength, BN_CTX *ctx) { int n; int count = 100; if (r == NULL) { ERR_raise(ERR_LIB_BN, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (range->neg || BN_is_zero(range)) { ERR_raise(ERR_LIB_BN, BN_R_INVALID_RANGE); return 0; } n = BN_num_bits(range); /* n > 0 */ /* BN_is_bit_set(range, n - 1) always holds */ if (n == 1) BN_zero(r); else if (!BN_is_bit_set(range, n - 2) && !BN_is_bit_set(range, n - 3)) { /* * range = 100..._2, so 3*range (= 11..._2) is exactly one bit longer * than range */ do { if (!bnrand(flag, r, n + 1, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY, strength, ctx)) return 0; /* * If r < 3*range, use r := r MOD range (which is either r, r - * range, or r - 2*range). Otherwise, iterate once more. Since * 3*range = 11..._2, each iteration succeeds with probability >= * .75. */ if (BN_cmp(r, range) >= 0) { if (!BN_sub(r, r, range)) return 0; if (BN_cmp(r, range) >= 0) if (!BN_sub(r, r, range)) return 0; } if (!--count) { ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_ITERATIONS); return 0; } } while (BN_cmp(r, range) >= 0); } else { do { /* range = 11..._2 or range = 101..._2 */ if (!bnrand(flag, r, n, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY, 0, ctx)) return 0; if (!--count) { ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_ITERATIONS); return 0; } } while (BN_cmp(r, range) >= 0); } bn_check_top(r); return 1; } int BN_rand_range_ex(BIGNUM *r, const BIGNUM *range, unsigned int strength, BN_CTX *ctx) { return bnrand_range(NORMAL, r, range, strength, ctx); } #ifndef FIPS_MODULE int BN_rand_range(BIGNUM *r, const BIGNUM *range) { return bnrand_range(NORMAL, r, range, 0, NULL); } #endif int BN_priv_rand_range_ex(BIGNUM *r, const BIGNUM *range, unsigned int strength, BN_CTX *ctx) { return bnrand_range(PRIVATE, r, range, strength, ctx); } #ifndef FIPS_MODULE int BN_priv_rand_range(BIGNUM *r, const BIGNUM *range) { return bnrand_range(PRIVATE, r, range, 0, NULL); } # ifndef OPENSSL_NO_DEPRECATED_3_0 int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom) { return BN_rand(rnd, bits, top, bottom); } int BN_pseudo_rand_range(BIGNUM *r, const BIGNUM *range) { return BN_rand_range(r, range); } # endif #endif /* * BN_generate_dsa_nonce generates a random number 0 <= out < range. Unlike * BN_rand_range, it also includes the contents of |priv| and |message| in * the generation so that an RNG failure isn't fatal as long as |priv| * remains secret. This is intended for use in DSA and ECDSA where an RNG * weakness leads directly to private key exposure unless this function is * used. */ int BN_generate_dsa_nonce(BIGNUM *out, const BIGNUM *range, const BIGNUM *priv, const unsigned char *message, size_t message_len, BN_CTX *ctx) { EVP_MD_CTX *mdctx = EVP_MD_CTX_new(); /* * We use 512 bits of random data per iteration to ensure that we have at * least |range| bits of randomness. */ unsigned char random_bytes[64]; unsigned char digest[SHA512_DIGEST_LENGTH]; unsigned done, todo; /* We generate |range|+8 bytes of random output. */ const unsigned num_k_bytes = BN_num_bytes(range) + 8; unsigned char private_bytes[96]; unsigned char *k_bytes = NULL; int ret = 0; EVP_MD *md = NULL; OSSL_LIB_CTX *libctx = ossl_bn_get_libctx(ctx); if (mdctx == NULL) goto err; k_bytes = OPENSSL_malloc(num_k_bytes); if (k_bytes == NULL) goto err; /* We copy |priv| into a local buffer to avoid exposing its length. */ if (BN_bn2binpad(priv, private_bytes, sizeof(private_bytes)) < 0) { /* * No reasonable DSA or ECDSA key should have a private key this * large and we don't handle this case in order to avoid leaking the * length of the private key. */ ERR_raise(ERR_LIB_BN, BN_R_PRIVATE_KEY_TOO_LARGE); goto err; } md = EVP_MD_fetch(libctx, "SHA512", NULL); if (md == NULL) { ERR_raise(ERR_LIB_BN, BN_R_NO_SUITABLE_DIGEST); goto err; } for (done = 0; done < num_k_bytes;) { if (RAND_priv_bytes_ex(libctx, random_bytes, sizeof(random_bytes), 0) <= 0) goto err; if (!EVP_DigestInit_ex(mdctx, md, NULL) || !EVP_DigestUpdate(mdctx, &done, sizeof(done)) || !EVP_DigestUpdate(mdctx, private_bytes, sizeof(private_bytes)) || !EVP_DigestUpdate(mdctx, message, message_len) || !EVP_DigestUpdate(mdctx, random_bytes, sizeof(random_bytes)) || !EVP_DigestFinal_ex(mdctx, digest, NULL)) goto err; todo = num_k_bytes - done; if (todo > SHA512_DIGEST_LENGTH) todo = SHA512_DIGEST_LENGTH; memcpy(k_bytes + done, digest, todo); done += todo; } if (!BN_bin2bn(k_bytes, num_k_bytes, out)) goto err; if (BN_mod(out, out, range, ctx) != 1) goto err; ret = 1; err: EVP_MD_CTX_free(mdctx); EVP_MD_free(md); OPENSSL_clear_free(k_bytes, num_k_bytes); OPENSSL_cleanse(digest, sizeof(digest)); OPENSSL_cleanse(random_bytes, sizeof(random_bytes)); OPENSSL_cleanse(private_bytes, sizeof(private_bytes)); return ret; }
9,460
27.932722
83
c
openssl
openssl-master/crypto/bn/bn_recp.c
/* * Copyright 1995-2020 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 */ #include "internal/cryptlib.h" #include "bn_local.h" void BN_RECP_CTX_init(BN_RECP_CTX *recp) { memset(recp, 0, sizeof(*recp)); bn_init(&(recp->N)); bn_init(&(recp->Nr)); } BN_RECP_CTX *BN_RECP_CTX_new(void) { BN_RECP_CTX *ret; if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) return NULL; bn_init(&(ret->N)); bn_init(&(ret->Nr)); ret->flags = BN_FLG_MALLOCED; return ret; } void BN_RECP_CTX_free(BN_RECP_CTX *recp) { if (recp == NULL) return; BN_free(&recp->N); BN_free(&recp->Nr); if (recp->flags & BN_FLG_MALLOCED) OPENSSL_free(recp); } int BN_RECP_CTX_set(BN_RECP_CTX *recp, const BIGNUM *d, BN_CTX *ctx) { if (BN_is_zero(d) || !BN_copy(&(recp->N), d)) return 0; BN_zero(&(recp->Nr)); recp->num_bits = BN_num_bits(d); recp->shift = 0; return 1; } int BN_mod_mul_reciprocal(BIGNUM *r, const BIGNUM *x, const BIGNUM *y, BN_RECP_CTX *recp, BN_CTX *ctx) { int ret = 0; BIGNUM *a; const BIGNUM *ca; BN_CTX_start(ctx); if ((a = BN_CTX_get(ctx)) == NULL) goto err; if (y != NULL) { if (x == y) { if (!BN_sqr(a, x, ctx)) goto err; } else { if (!BN_mul(a, x, y, ctx)) goto err; } ca = a; } else ca = x; /* Just do the mod */ ret = BN_div_recp(NULL, r, ca, recp, ctx); err: BN_CTX_end(ctx); bn_check_top(r); return ret; } int BN_div_recp(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, BN_RECP_CTX *recp, BN_CTX *ctx) { int i, j, ret = 0; BIGNUM *a, *b, *d, *r; BN_CTX_start(ctx); d = (dv != NULL) ? dv : BN_CTX_get(ctx); r = (rem != NULL) ? rem : BN_CTX_get(ctx); a = BN_CTX_get(ctx); b = BN_CTX_get(ctx); if (b == NULL) goto err; if (BN_ucmp(m, &(recp->N)) < 0) { BN_zero(d); if (!BN_copy(r, m)) { BN_CTX_end(ctx); return 0; } BN_CTX_end(ctx); return 1; } /* * We want the remainder Given input of ABCDEF / ab we need multiply * ABCDEF by 3 digests of the reciprocal of ab */ /* i := max(BN_num_bits(m), 2*BN_num_bits(N)) */ i = BN_num_bits(m); j = recp->num_bits << 1; if (j > i) i = j; /* Nr := round(2^i / N) */ if (i != recp->shift) recp->shift = BN_reciprocal(&(recp->Nr), &(recp->N), i, ctx); /* BN_reciprocal could have returned -1 for an error */ if (recp->shift == -1) goto err; /*- * d := |round(round(m / 2^BN_num_bits(N)) * recp->Nr / 2^(i - BN_num_bits(N)))| * = |round(round(m / 2^BN_num_bits(N)) * round(2^i / N) / 2^(i - BN_num_bits(N)))| * <= |(m / 2^BN_num_bits(N)) * (2^i / N) * (2^BN_num_bits(N) / 2^i)| * = |m/N| */ if (!BN_rshift(a, m, recp->num_bits)) goto err; if (!BN_mul(b, a, &(recp->Nr), ctx)) goto err; if (!BN_rshift(d, b, i - recp->num_bits)) goto err; d->neg = 0; if (!BN_mul(b, &(recp->N), d, ctx)) goto err; if (!BN_usub(r, m, b)) goto err; r->neg = 0; j = 0; while (BN_ucmp(r, &(recp->N)) >= 0) { if (j++ > 2) { ERR_raise(ERR_LIB_BN, BN_R_BAD_RECIPROCAL); goto err; } if (!BN_usub(r, r, &(recp->N))) goto err; if (!BN_add_word(d, 1)) goto err; } r->neg = BN_is_zero(r) ? 0 : m->neg; d->neg = m->neg ^ recp->N.neg; ret = 1; err: BN_CTX_end(ctx); bn_check_top(dv); bn_check_top(rem); return ret; } /* * len is the expected size of the result We actually calculate with an extra * word of precision, so we can do faster division if the remainder is not * required. */ /* r := 2^len / m */ int BN_reciprocal(BIGNUM *r, const BIGNUM *m, int len, BN_CTX *ctx) { int ret = -1; BIGNUM *t; BN_CTX_start(ctx); if ((t = BN_CTX_get(ctx)) == NULL) goto err; if (!BN_set_bit(t, len)) goto err; if (!BN_div(r, NULL, t, m, ctx)) goto err; ret = len; err: bn_check_top(r); BN_CTX_end(ctx); return ret; }
4,567
22.668394
90
c
openssl
openssl-master/crypto/bn/bn_rsa_fips186_4.c
/* * Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2018-2019, Oracle and/or its affiliates. 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 */ /* * According to NIST SP800-131A "Transitioning the use of cryptographic * algorithms and key lengths" Generation of 1024 bit RSA keys are no longer * allowed for signatures (Table 2) or key transport (Table 5). In the code * below any attempt to generate 1024 bit RSA keys will result in an error (Note * that digital signature verification can still use deprecated 1024 bit keys). * * FIPS 186-4 relies on the use of the auxiliary primes p1, p2, q1 and q2 that * must be generated before the module generates the RSA primes p and q. * Table B.1 in FIPS 186-4 specifies RSA modulus lengths of 2048 and * 3072 bits only, the min/max total length of the auxiliary primes. * FIPS 186-5 Table A.1 includes an additional entry for 4096 which has been * included here. */ #include <stdio.h> #include <openssl/bn.h> #include "bn_local.h" #include "crypto/bn.h" #include "internal/nelem.h" #if BN_BITS2 == 64 # define BN_DEF(lo, hi) (BN_ULONG)hi<<32|lo #else # define BN_DEF(lo, hi) lo, hi #endif /* 1 / sqrt(2) * 2^256, rounded up */ static const BN_ULONG inv_sqrt_2_val[] = { BN_DEF(0x83339916UL, 0xED17AC85UL), BN_DEF(0x893BA84CUL, 0x1D6F60BAUL), BN_DEF(0x754ABE9FUL, 0x597D89B3UL), BN_DEF(0xF9DE6484UL, 0xB504F333UL) }; const BIGNUM ossl_bn_inv_sqrt_2 = { (BN_ULONG *)inv_sqrt_2_val, OSSL_NELEM(inv_sqrt_2_val), OSSL_NELEM(inv_sqrt_2_val), 0, BN_FLG_STATIC_DATA }; /* * Refer to FIPS 186-5 Table B.1 for minimum rounds of Miller Rabin * required for generation of RSA aux primes (p1, p2, q1 and q2). */ static int bn_rsa_fips186_5_aux_prime_MR_rounds(int nbits) { if (nbits >= 4096) return 44; if (nbits >= 3072) return 41; if (nbits >= 2048) return 38; return 0; /* Error */ } /* * Refer to FIPS 186-5 Table B.1 for minimum rounds of Miller Rabin * required for generation of RSA primes (p and q) */ static int bn_rsa_fips186_5_prime_MR_rounds(int nbits) { if (nbits >= 3072) return 4; if (nbits >= 2048) return 5; return 0; /* Error */ } /* * FIPS 186-5 Table A.1. "Min length of auxiliary primes p1, p2, q1, q2". * (FIPS 186-5 has an entry for >= 4096 bits). * * Params: * nbits The key size in bits. * Returns: * The minimum size of the auxiliary primes or 0 if nbits is invalid. */ static int bn_rsa_fips186_5_aux_prime_min_size(int nbits) { if (nbits >= 4096) return 201; if (nbits >= 3072) return 171; if (nbits >= 2048) return 141; return 0; } /* * FIPS 186-5 Table A.1 "Max of len(p1) + len(p2) and * len(q1) + len(q2) for p,q Probable Primes". * (FIPS 186-5 has an entry for >= 4096 bits). * Params: * nbits The key size in bits. * Returns: * The maximum length or 0 if nbits is invalid. */ static int bn_rsa_fips186_5_aux_prime_max_sum_size_for_prob_primes(int nbits) { if (nbits >= 4096) return 2030; if (nbits >= 3072) return 1518; if (nbits >= 2048) return 1007; return 0; } /* * Find the first odd integer that is a probable prime. * * See section FIPS 186-4 B.3.6 (Steps 4.2/5.2). * * Params: * Xp1 The passed in starting point to find a probably prime. * p1 The returned probable prime (first odd integer >= Xp1) * ctx A BN_CTX object. * rounds The number of Miller Rabin rounds * cb An optional BIGNUM callback. * Returns: 1 on success otherwise it returns 0. */ static int bn_rsa_fips186_4_find_aux_prob_prime(const BIGNUM *Xp1, BIGNUM *p1, BN_CTX *ctx, int rounds, BN_GENCB *cb) { int ret = 0; int i = 0; int tmp = 0; if (BN_copy(p1, Xp1) == NULL) return 0; BN_set_flags(p1, BN_FLG_CONSTTIME); /* Find the first odd number >= Xp1 that is probably prime */ for (;;) { i++; BN_GENCB_call(cb, 0, i); /* MR test with trial division */ tmp = ossl_bn_check_generated_prime(p1, rounds, ctx, cb); if (tmp > 0) break; if (tmp < 0) goto err; /* Get next odd number */ if (!BN_add_word(p1, 2)) goto err; } BN_GENCB_call(cb, 2, i); ret = 1; err: return ret; } /* * Generate a probable prime (p or q). * * See FIPS 186-4 B.3.6 (Steps 4 & 5) * * Params: * p The returned probable prime. * Xpout An optionally returned random number used during generation of p. * p1, p2 The returned auxiliary primes. If NULL they are not returned. * Xp An optional passed in value (that is random number used during * generation of p). * Xp1, Xp2 Optional passed in values that are normally generated * internally. Used to find p1, p2. * nlen The bit length of the modulus (the key size). * e The public exponent. * ctx A BN_CTX object. * cb An optional BIGNUM callback. * Returns: 1 on success otherwise it returns 0. */ int ossl_bn_rsa_fips186_4_gen_prob_primes(BIGNUM *p, BIGNUM *Xpout, BIGNUM *p1, BIGNUM *p2, const BIGNUM *Xp, const BIGNUM *Xp1, const BIGNUM *Xp2, int nlen, const BIGNUM *e, BN_CTX *ctx, BN_GENCB *cb) { int ret = 0; BIGNUM *p1i = NULL, *p2i = NULL, *Xp1i = NULL, *Xp2i = NULL; int bitlen, rounds; if (p == NULL || Xpout == NULL) return 0; BN_CTX_start(ctx); p1i = (p1 != NULL) ? p1 : BN_CTX_get(ctx); p2i = (p2 != NULL) ? p2 : BN_CTX_get(ctx); Xp1i = (Xp1 != NULL) ? (BIGNUM *)Xp1 : BN_CTX_get(ctx); Xp2i = (Xp2 != NULL) ? (BIGNUM *)Xp2 : BN_CTX_get(ctx); if (p1i == NULL || p2i == NULL || Xp1i == NULL || Xp2i == NULL) goto err; bitlen = bn_rsa_fips186_5_aux_prime_min_size(nlen); if (bitlen == 0) goto err; rounds = bn_rsa_fips186_5_aux_prime_MR_rounds(nlen); /* (Steps 4.1/5.1): Randomly generate Xp1 if it is not passed in */ if (Xp1 == NULL) { /* Set the top and bottom bits to make it odd and the correct size */ if (!BN_priv_rand_ex(Xp1i, bitlen, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD, 0, ctx)) goto err; } /* (Steps 4.1/5.1): Randomly generate Xp2 if it is not passed in */ if (Xp2 == NULL) { /* Set the top and bottom bits to make it odd and the correct size */ if (!BN_priv_rand_ex(Xp2i, bitlen, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD, 0, ctx)) goto err; } /* (Steps 4.2/5.2) - find first auxiliary probable primes */ if (!bn_rsa_fips186_4_find_aux_prob_prime(Xp1i, p1i, ctx, rounds, cb) || !bn_rsa_fips186_4_find_aux_prob_prime(Xp2i, p2i, ctx, rounds, cb)) goto err; /* (Table B.1) auxiliary prime Max length check */ if ((BN_num_bits(p1i) + BN_num_bits(p2i)) >= bn_rsa_fips186_5_aux_prime_max_sum_size_for_prob_primes(nlen)) goto err; /* (Steps 4.3/5.3) - generate prime */ if (!ossl_bn_rsa_fips186_4_derive_prime(p, Xpout, Xp, p1i, p2i, nlen, e, ctx, cb)) goto err; ret = 1; err: /* Zeroize any internally generated values that are not returned */ if (p1 == NULL) BN_clear(p1i); if (p2 == NULL) BN_clear(p2i); if (Xp1 == NULL) BN_clear(Xp1i); if (Xp2 == NULL) BN_clear(Xp2i); BN_CTX_end(ctx); return ret; } /* * Constructs a probable prime (a candidate for p or q) using 2 auxiliary * prime numbers and the Chinese Remainder Theorem. * * See FIPS 186-4 C.9 "Compute a Probable Prime Factor Based on Auxiliary * Primes". Used by FIPS 186-4 B.3.6 Section (4.3) for p and Section (5.3) for q. * * Params: * Y The returned prime factor (private_prime_factor) of the modulus n. * X The returned random number used during generation of the prime factor. * Xin An optional passed in value for X used for testing purposes. * r1 An auxiliary prime. * r2 An auxiliary prime. * nlen The desired length of n (the RSA modulus). * e The public exponent. * ctx A BN_CTX object. * cb An optional BIGNUM callback object. * Returns: 1 on success otherwise it returns 0. * Assumptions: * Y, X, r1, r2, e are not NULL. */ int ossl_bn_rsa_fips186_4_derive_prime(BIGNUM *Y, BIGNUM *X, const BIGNUM *Xin, const BIGNUM *r1, const BIGNUM *r2, int nlen, const BIGNUM *e, BN_CTX *ctx, BN_GENCB *cb) { int ret = 0; int i, imax, rounds; int bits = nlen >> 1; BIGNUM *tmp, *R, *r1r2x2, *y1, *r1x2; BIGNUM *base, *range; BN_CTX_start(ctx); base = BN_CTX_get(ctx); range = BN_CTX_get(ctx); R = BN_CTX_get(ctx); tmp = BN_CTX_get(ctx); r1r2x2 = BN_CTX_get(ctx); y1 = BN_CTX_get(ctx); r1x2 = BN_CTX_get(ctx); if (r1x2 == NULL) goto err; if (Xin != NULL && BN_copy(X, Xin) == NULL) goto err; /* * We need to generate a random number X in the range * 1/sqrt(2) * 2^(nlen/2) <= X < 2^(nlen/2). * We can rewrite that as: * base = 1/sqrt(2) * 2^(nlen/2) * range = ((2^(nlen/2))) - (1/sqrt(2) * 2^(nlen/2)) * X = base + random(range) * We only have the first 256 bit of 1/sqrt(2) */ if (Xin == NULL) { if (bits < BN_num_bits(&ossl_bn_inv_sqrt_2)) goto err; if (!BN_lshift(base, &ossl_bn_inv_sqrt_2, bits - BN_num_bits(&ossl_bn_inv_sqrt_2)) || !BN_lshift(range, BN_value_one(), bits) || !BN_sub(range, range, base)) goto err; } /* * (Step 1) GCD(2r1, r2) = 1. * Note: This algorithm was doing a gcd(2r1, r2)=1 test before doing an * mod_inverse(2r1, r2) which are effectively the same operation. * (The algorithm assumed that the gcd test would be faster). Since the * mod_inverse is currently faster than calling the constant time * BN_gcd(), the call to BN_gcd() has been omitted. The inverse result * is used further down. */ if (!(BN_lshift1(r1x2, r1) && (BN_mod_inverse(tmp, r1x2, r2, ctx) != NULL) /* (Step 2) R = ((r2^-1 mod 2r1) * r2) - ((2r1^-1 mod r2)*2r1) */ && (BN_mod_inverse(R, r2, r1x2, ctx) != NULL) && BN_mul(R, R, r2, ctx) /* R = (r2^-1 mod 2r1) * r2 */ && BN_mul(tmp, tmp, r1x2, ctx) /* tmp = (2r1^-1 mod r2)*2r1 */ && BN_sub(R, R, tmp) /* Calculate 2r1r2 */ && BN_mul(r1r2x2, r1x2, r2, ctx))) goto err; /* Make positive by adding the modulus */ if (BN_is_negative(R) && !BN_add(R, R, r1r2x2)) goto err; /* * In FIPS 186-4 imax was set to 5 * nlen/2. * Analysis by Allen Roginsky * (See https://csrc.nist.gov/CSRC/media/Publications/fips/186/4/final/documents/comments-received-fips186-4-december-2015.pdf * page 68) indicates this has a 1 in 2 million chance of failure. * The number has been updated to 20 * nlen/2 as used in * FIPS186-5 Appendix B.9 Step 9. */ rounds = bn_rsa_fips186_5_prime_MR_rounds(nlen); imax = 20 * bits; /* max = 20/2 * nbits */ for (;;) { if (Xin == NULL) { /* * (Step 3) Choose Random X such that * sqrt(2) * 2^(nlen/2-1) <= Random X <= (2^(nlen/2)) - 1. */ if (!BN_priv_rand_range_ex(X, range, 0, ctx) || !BN_add(X, X, base)) goto err; } /* (Step 4) Y = X + ((R - X) mod 2r1r2) */ if (!BN_mod_sub(Y, R, X, r1r2x2, ctx) || !BN_add(Y, Y, X)) goto err; /* (Step 5) */ i = 0; for (;;) { /* (Step 6) */ if (BN_num_bits(Y) > bits) { if (Xin == NULL) break; /* Randomly Generated X so Go back to Step 3 */ else goto err; /* X is not random so it will always fail */ } BN_GENCB_call(cb, 0, 2); /* (Step 7) If GCD(Y-1) == 1 & Y is probably prime then return Y */ if (BN_copy(y1, Y) == NULL || !BN_sub_word(y1, 1)) goto err; if (BN_are_coprime(y1, e, ctx)) { int rv = ossl_bn_check_generated_prime(Y, rounds, ctx, cb); if (rv > 0) goto end; if (rv < 0) goto err; } /* (Step 8-10) */ if (++i >= imax) { ERR_raise(ERR_LIB_BN, BN_R_NO_PRIME_CANDIDATE); goto err; } if (!BN_add(Y, Y, r1r2x2)) goto err; } } end: ret = 1; BN_GENCB_call(cb, 3, 0); err: BN_clear(y1); BN_CTX_end(ctx); return ret; }
13,584
32.378378
130
c
openssl
openssl-master/crypto/bn/bn_s390x.c
/* * Copyright 2023-2023 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 */ #include "crypto/bn.h" #include "crypto/s390x_arch.h" #ifdef S390X_MOD_EXP # include <sys/types.h> # include <sys/stat.h> # include <fcntl.h> # include <asm/zcrypt.h> # include <sys/ioctl.h> # include <unistd.h> # include <errno.h> static int s390x_mod_exp_hw(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m) { struct ica_rsa_modexpo me; unsigned char *buffer; size_t size; int res = 0; if (OPENSSL_s390xcex == -1) return 0; size = BN_num_bytes(m); buffer = OPENSSL_zalloc(4 * size); if (buffer == NULL) return 0; me.inputdata = buffer; me.inputdatalength = size; me.outputdata = buffer + size; me.outputdatalength = size; me.b_key = buffer + 2 * size; me.n_modulus = buffer + 3 * size; if (BN_bn2binpad(a, me.inputdata, size) == -1 || BN_bn2binpad(p, me.b_key, size) == -1 || BN_bn2binpad(m, me.n_modulus, size) == -1) goto dealloc; if (ioctl(OPENSSL_s390xcex, ICARSAMODEXPO, &me) != -1) { if (BN_bin2bn(me.outputdata, size, r) != NULL) res = 1; } else if (errno == EBADF) { /*- * In this cases, someone (e.g. a sandbox) closed the fd. * Make sure to not further use this hardware acceleration. */ OPENSSL_s390xcex = -1; } dealloc: OPENSSL_clear_free(buffer, 4 * size); return res; } int s390x_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) { if (s390x_mod_exp_hw(r, a, p, m) == 1) return 1; return BN_mod_exp_mont(r, a, p, m, ctx, m_ctx); } int s390x_crt(BIGNUM *r, const BIGNUM *i, const BIGNUM *p, const BIGNUM *q, const BIGNUM *dmp, const BIGNUM *dmq, const BIGNUM *iqmp) { struct ica_rsa_modexpo_crt crt; unsigned char *buffer, *part; size_t size, plen, qlen; int res = 0; if (OPENSSL_s390xcex == -1) return 0; /*- * Hardware-accelerated CRT can only deal with p>q. Fall back to * software in the (hopefully rare) other cases. */ if (BN_ucmp(p, q) != 1) return 0; plen = BN_num_bytes(p); qlen = BN_num_bytes(q); size = (plen > qlen ? plen : qlen); buffer = OPENSSL_zalloc(9 * size + 24); if (buffer == NULL) return 0; part = buffer; crt.inputdata = part; crt.inputdatalength = 2 * size; part += 2 * size; crt.outputdata = part; crt.outputdatalength = 2 * size; part += 2 * size; crt.bp_key = part; part += size + 8; crt.bq_key = part; part += size; crt.np_prime = part; part += size + 8; crt.nq_prime = part; part += size; crt.u_mult_inv = part; if (BN_bn2binpad(i, crt.inputdata, crt.inputdatalength) == -1 || BN_bn2binpad(p, crt.np_prime, size + 8) == -1 || BN_bn2binpad(q, crt.nq_prime, size) == -1 || BN_bn2binpad(dmp, crt.bp_key, size + 8) == -1 || BN_bn2binpad(dmq, crt.bq_key, size) == -1 || BN_bn2binpad(iqmp, crt.u_mult_inv, size + 8) == -1) goto dealloc; if (ioctl(OPENSSL_s390xcex, ICARSACRT, &crt) != -1) { if (BN_bin2bn(crt.outputdata, crt.outputdatalength, r) != NULL) res = 1; } else if (errno == EBADF) { /*- * In this cases, someone (e.g. a sandbox) closed the fd. * Make sure to not further use this hardware acceleration. */ OPENSSL_s390xcex = -1; } dealloc: OPENSSL_clear_free(buffer, 9 * size + 24); return res; } #else int s390x_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) { return BN_mod_exp_mont(r, a, p, m, ctx, m_ctx); } int s390x_crt(BIGNUM *r, const BIGNUM *i, const BIGNUM *p, const BIGNUM *q, const BIGNUM *dmp, const BIGNUM *dmq, const BIGNUM *iqmp) { return 0; } #endif
4,271
28.666667
75
c