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/ssl/record/methods/recmethod_local.h | /*
* Copyright 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/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include "../../ssl_local.h"
#include "../record_local.h"
typedef struct dtls_bitmap_st {
/* Track 64 packets */
uint64_t map;
/* Max record number seen so far, 64-bit value in big-endian encoding */
unsigned char max_seq_num[SEQ_NUM_SIZE];
} DTLS_BITMAP;
typedef struct ssl_mac_buf_st {
unsigned char *mac;
int alloced;
} SSL_MAC_BUF;
typedef struct tls_buffer_st {
/* at least SSL3_RT_MAX_PACKET_SIZE bytes */
unsigned char *buf;
/* default buffer size (or 0 if no default set) */
size_t default_len;
/* buffer size */
size_t len;
/* where to 'copy from' */
size_t offset;
/* how many bytes left */
size_t left;
/* 'buf' is from application for KTLS */
int app_buffer;
/* The type of data stored in this buffer. Only used for writing */
int type;
} TLS_BUFFER;
typedef struct tls_rl_record_st {
/* Record layer version */
/* r */
int rec_version;
/* type of record */
/* r */
int type;
/* How many bytes available */
/* rw */
size_t length;
/*
* How many bytes were available before padding was removed? This is used
* to implement the MAC check in constant time for CBC records.
*/
/* rw */
size_t orig_len;
/* read/write offset into 'buf' */
/* r */
size_t off;
/* pointer to the record data */
/* rw */
unsigned char *data;
/* where the decode bytes are */
/* rw */
unsigned char *input;
/* only used with decompression - malloc()ed */
/* r */
unsigned char *comp;
/* epoch number, needed by DTLS1 */
/* r */
uint16_t epoch;
/* sequence number, needed by DTLS1 */
/* r */
unsigned char seq_num[SEQ_NUM_SIZE];
} TLS_RL_RECORD;
/* Macros/functions provided by the TLS_RL_RECORD component */
#define TLS_RL_RECORD_set_type(r, t) ((r)->type = (t))
#define TLS_RL_RECORD_set_rec_version(r, v) ((r)->rec_version = (v))
#define TLS_RL_RECORD_get_length(r) ((r)->length)
#define TLS_RL_RECORD_set_length(r, l) ((r)->length = (l))
#define TLS_RL_RECORD_add_length(r, l) ((r)->length += (l))
#define TLS_RL_RECORD_set_data(r, d) ((r)->data = (d))
#define TLS_RL_RECORD_set_input(r, i) ((r)->input = (i))
#define TLS_RL_RECORD_reset_input(r) ((r)->input = (r)->data)
/* Protocol version specific function pointers */
struct record_functions_st
{
/*
* Returns either OSSL_RECORD_RETURN_SUCCESS, OSSL_RECORD_RETURN_FATAL or
* OSSL_RECORD_RETURN_NON_FATAL_ERR if we can keep trying to find an
* alternative record layer.
*/
int (*set_crypto_state)(OSSL_RECORD_LAYER *rl, int level,
unsigned char *key, size_t keylen,
unsigned char *iv, size_t ivlen,
unsigned char *mackey, size_t mackeylen,
const EVP_CIPHER *ciph,
size_t taglen,
int mactype,
const EVP_MD *md,
COMP_METHOD *comp);
/*
* Returns:
* 0: if the record is publicly invalid, or an internal error, or AEAD
* decryption failed, or EtM decryption failed.
* 1: Success or MtE decryption failed (MAC will be randomised)
*/
int (*cipher)(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *recs, size_t n_recs,
int sending, SSL_MAC_BUF *macs, size_t macsize);
/* Returns 1 for success or 0 for error */
int (*mac)(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec, unsigned char *md,
int sending);
/* Return 1 for success or 0 for error */
int (*set_protocol_version)(OSSL_RECORD_LAYER *rl, int version);
/* Read related functions */
int (*read_n)(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
int clearold, size_t *readbytes);
int (*get_more_records)(OSSL_RECORD_LAYER *rl);
/* Return 1 for success or 0 for error */
int (*validate_record_header)(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec);
/* Return 1 for success or 0 for error */
int (*post_process_record)(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec);
/* Write related functions */
size_t (*get_max_records)(OSSL_RECORD_LAYER *rl, int type, size_t len,
size_t maxfrag, size_t *preffrag);
/* Return 1 for success or 0 for error */
int (*write_records)(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
size_t numtempl);
/* Allocate the rl->wbuf buffers. Return 1 for success or 0 for error */
int (*allocate_write_buffers)(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *templates,
size_t numtempl, size_t *prefix);
/*
* Initialise the packets in the |pkt| array using the buffers in |rl->wbuf|.
* Some protocol versions may use the space in |prefixtempl| to add
* an artificial template in front of the |templates| array and hence may
* initialise 1 more WPACKET than there are templates. |*wpinited|
* returns the number of WPACKETs in |pkt| that were successfully
* initialised. This must be 0 on entry and will be filled in even on error.
*/
int (*initialise_write_packets)(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *templates,
size_t numtempl,
OSSL_RECORD_TEMPLATE *prefixtempl,
WPACKET *pkt,
TLS_BUFFER *bufs,
size_t *wpinited);
/* Get the actual record type to be used for a given template */
unsigned int (*get_record_type)(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *template);
/* Write the record header data to the WPACKET */
int (*prepare_record_header)(OSSL_RECORD_LAYER *rl, WPACKET *thispkt,
OSSL_RECORD_TEMPLATE *templ,
unsigned int rectype,
unsigned char **recdata);
int (*add_record_padding)(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *thistempl,
WPACKET *thispkt,
TLS_RL_RECORD *thiswr);
/*
* This applies any mac that might be necessary, ensures that we have enough
* space in the WPACKET to perform the encryption and sets up the
* TLS_RL_RECORD ready for that encryption.
*/
int (*prepare_for_encryption)(OSSL_RECORD_LAYER *rl,
size_t mac_size,
WPACKET *thispkt,
TLS_RL_RECORD *thiswr);
/*
* Any updates required to the record after encryption has been applied. For
* example, adding a MAC if using encrypt-then-mac
*/
int (*post_encryption_processing)(OSSL_RECORD_LAYER *rl,
size_t mac_size,
OSSL_RECORD_TEMPLATE *thistempl,
WPACKET *thispkt,
TLS_RL_RECORD *thiswr);
/*
* Some record layer implementations need to do some custom preparation of
* the BIO before we write to it. KTLS does this to prevent coalescing of
* control and data messages.
*/
int (*prepare_write_bio)(OSSL_RECORD_LAYER *rl, int type);
};
struct ossl_record_layer_st
{
OSSL_LIB_CTX *libctx;
const char *propq;
int isdtls;
int version;
int role;
int direction;
int level;
const EVP_MD *md;
/* DTLS only */
uint16_t epoch;
/*
* A BIO containing any data read in the previous epoch that was destined
* for this epoch
*/
BIO *prev;
/* The transport BIO */
BIO *bio;
/*
* A BIO where we will send any data read by us that is destined for the
* next epoch.
*/
BIO *next;
/* Types match the equivalent fields in the SSL object */
uint64_t options;
uint32_t mode;
/* write IO goes into here */
TLS_BUFFER wbuf[SSL_MAX_PIPELINES + 1];
/* Next wbuf with pending data still to write */
size_t nextwbuf;
/* How many pipelines can be used to write data */
size_t numwpipes;
/* read IO goes into here */
TLS_BUFFER rbuf;
/* each decoded record goes in here */
TLS_RL_RECORD rrec[SSL_MAX_PIPELINES];
/* How many records have we got available in the rrec buffer */
size_t num_recs;
/* The record number in the rrec buffer that can be read next */
size_t curr_rec;
/* The number of records that have been released via tls_release_record */
size_t num_released;
/* where we are when reading */
int rstate;
/* used internally to point at a raw packet */
unsigned char *packet;
size_t packet_length;
/* Sequence number for the next record */
unsigned char sequence[SEQ_NUM_SIZE];
/* Alert code to be used if an error occurs */
int alert;
/*
* Read as many input bytes as possible (for non-blocking reads)
*/
int read_ahead;
/* The number of consecutive empty records we have received */
size_t empty_record_count;
/*
* Do we need to send a prefix empty record before application data as a
* countermeasure against known-IV weakness (necessary for SSLv3 and
* TLSv1.0)
*/
int need_empty_fragments;
/* cryptographic state */
EVP_CIPHER_CTX *enc_ctx;
/* Explicit IV length */
size_t eivlen;
/* used for mac generation */
EVP_MD_CTX *md_ctx;
/* compress/uncompress */
COMP_CTX *compctx;
/* Set to 1 if this is the first handshake. 0 otherwise */
int is_first_handshake;
/*
* The smaller of the configured and negotiated maximum fragment length
* or SSL3_RT_MAX_PLAIN_LENGTH if none
*/
unsigned int max_frag_len;
/* The maximum amount of early data we can receive/send */
uint32_t max_early_data;
/* The amount of early data that we have sent/received */
size_t early_data_count;
/* TLSv1.3 record padding */
size_t block_padding;
/* Only used by SSLv3 */
unsigned char mac_secret[EVP_MAX_MD_SIZE];
/* TLSv1.0/TLSv1.1/TLSv1.2 */
int use_etm;
/* Flags for GOST ciphers */
int stream_mac;
int tlstree;
/* TLSv1.3 fields */
/* static IV */
unsigned char iv[EVP_MAX_IV_LENGTH];
/* static read IV */
unsigned char read_iv[EVP_MAX_IV_LENGTH];
int allow_plain_alerts;
/* TLS "any" fields */
/* Set to true if this is the first record in a connection */
unsigned int is_first_record;
size_t taglen;
/* DTLS received handshake records (processed and unprocessed) */
record_pqueue unprocessed_rcds;
record_pqueue processed_rcds;
/* records being received in the current epoch */
DTLS_BITMAP bitmap;
/* renegotiation starts a new set of sequence numbers */
DTLS_BITMAP next_bitmap;
/*
* Whether we are currently in a handshake or not. Only maintained for DTLS
*/
int in_init;
/* Callbacks */
void *cbarg;
OSSL_FUNC_rlayer_skip_early_data_fn *skip_early_data;
OSSL_FUNC_rlayer_msg_callback_fn *msg_callback;
OSSL_FUNC_rlayer_security_fn *security;
OSSL_FUNC_rlayer_padding_fn *padding;
size_t max_pipelines;
/* Function pointers for version specific functions */
struct record_functions_st *funcs;
};
typedef struct dtls_rlayer_record_data_st {
unsigned char *packet;
size_t packet_length;
TLS_BUFFER rbuf;
TLS_RL_RECORD rrec;
} DTLS_RLAYER_RECORD_DATA;
extern struct record_functions_st ssl_3_0_funcs;
extern struct record_functions_st tls_1_funcs;
extern struct record_functions_st tls_1_3_funcs;
extern struct record_functions_st tls_any_funcs;
extern struct record_functions_st dtls_1_funcs;
extern struct record_functions_st dtls_any_funcs;
void ossl_rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
const char *fmt, ...);
#define RLAYERfatal(rl, al, r) RLAYERfatal_data((rl), (al), (r), NULL)
#define RLAYERfatal_data \
(ERR_new(), \
ERR_set_debug(OPENSSL_FILE, OPENSSL_LINE, OPENSSL_FUNC), \
ossl_rlayer_fatal)
#define RLAYER_USE_EXPLICIT_IV(rl) ((rl)->version == TLS1_1_VERSION \
|| (rl)->version == TLS1_2_VERSION \
|| (rl)->isdtls)
void ossl_tls_rl_record_set_seq_num(TLS_RL_RECORD *r,
const unsigned char *seq_num);
int ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER *rl,
EVP_CIPHER_CTX *ctx,
const EVP_CIPHER *ciph,
const EVP_MD *md);
int tls_increment_sequence_ctr(OSSL_RECORD_LAYER *rl);
int tls_alloc_buffers(OSSL_RECORD_LAYER *rl);
int tls_free_buffers(OSSL_RECORD_LAYER *rl);
int tls_default_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
int clearold, size_t *readbytes);
int tls_get_more_records(OSSL_RECORD_LAYER *rl);
int dtls_get_more_records(OSSL_RECORD_LAYER *rl);
int dtls_prepare_record_header(OSSL_RECORD_LAYER *rl,
WPACKET *thispkt,
OSSL_RECORD_TEMPLATE *templ,
unsigned int rectype,
unsigned char **recdata);
int dtls_post_encryption_processing(OSSL_RECORD_LAYER *rl,
size_t mac_size,
OSSL_RECORD_TEMPLATE *thistempl,
WPACKET *thispkt,
TLS_RL_RECORD *thiswr);
int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version);
int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *re);
int tls_do_compress(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *wr);
int tls_do_uncompress(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec);
int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec);
int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec);
int
tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
int role, int direction, int level, unsigned char *key,
size_t keylen, unsigned char *iv, size_t ivlen,
unsigned char *mackey, size_t mackeylen,
const EVP_CIPHER *ciph, size_t taglen,
int mactype,
const EVP_MD *md, COMP_METHOD *comp, BIO *prev,
BIO *transport, BIO *next,
BIO_ADDR *local, BIO_ADDR *peer,
const OSSL_PARAM *settings, const OSSL_PARAM *options,
const OSSL_DISPATCH *fns, void *cbarg,
OSSL_RECORD_LAYER **retrl);
int tls_free(OSSL_RECORD_LAYER *rl);
int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl);
int tls_processed_read_pending(OSSL_RECORD_LAYER *rl);
size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl);
size_t tls_get_max_records(OSSL_RECORD_LAYER *rl, int type, size_t len,
size_t maxfrag, size_t *preffrag);
int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
size_t numtempl);
int tls_retry_write_records(OSSL_RECORD_LAYER *rl);
int tls_get_alert_code(OSSL_RECORD_LAYER *rl);
int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio);
int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion,
int *type, const unsigned char **data, size_t *datalen,
uint16_t *epoch, unsigned char *seq_num);
int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle, size_t length);
int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version);
int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version);
void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow);
void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first);
void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines);
void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
const char **longstr);
int tls_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options);
const COMP_METHOD *tls_get_compression(OSSL_RECORD_LAYER *rl);
void tls_set_max_frag_len(OSSL_RECORD_LAYER *rl, size_t max_frag_len);
int tls_setup_read_buffer(OSSL_RECORD_LAYER *rl);
int tls_setup_write_buffer(OSSL_RECORD_LAYER *rl, size_t numwpipes,
size_t firstlen, size_t nextlen);
int tls_write_records_multiblock(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *templates,
size_t numtempl);
size_t tls_get_max_records_default(OSSL_RECORD_LAYER *rl, int type, size_t len,
size_t maxfrag, size_t *preffrag);
size_t tls_get_max_records_multiblock(OSSL_RECORD_LAYER *rl, int type,
size_t len, size_t maxfrag,
size_t *preffrag);
int tls_allocate_write_buffers_default(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *templates,
size_t numtempl, size_t *prefix);
int tls_initialise_write_packets_default(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *templates,
size_t numtempl,
OSSL_RECORD_TEMPLATE *prefixtempl,
WPACKET *pkt,
TLS_BUFFER *bufs,
size_t *wpinited);
int tls1_allocate_write_buffers(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *templates,
size_t numtempl, size_t *prefix);
int tls1_initialise_write_packets(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *templates,
size_t numtempl,
OSSL_RECORD_TEMPLATE *prefixtempl,
WPACKET *pkt,
TLS_BUFFER *bufs,
size_t *wpinited);
int tls_prepare_record_header_default(OSSL_RECORD_LAYER *rl,
WPACKET *thispkt,
OSSL_RECORD_TEMPLATE *templ,
unsigned int rectype,
unsigned char **recdata);
int tls_prepare_for_encryption_default(OSSL_RECORD_LAYER *rl,
size_t mac_size,
WPACKET *thispkt,
TLS_RL_RECORD *thiswr);
int tls_post_encryption_processing_default(OSSL_RECORD_LAYER *rl,
size_t mac_size,
OSSL_RECORD_TEMPLATE *thistempl,
WPACKET *thispkt,
TLS_RL_RECORD *thiswr);
int tls_write_records_default(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *templates,
size_t numtempl);
/* Macros/functions provided by the TLS_BUFFER component */
#define TLS_BUFFER_get_buf(b) ((b)->buf)
#define TLS_BUFFER_set_buf(b, n) ((b)->buf = (n))
#define TLS_BUFFER_get_len(b) ((b)->len)
#define TLS_BUFFER_get_left(b) ((b)->left)
#define TLS_BUFFER_set_left(b, l) ((b)->left = (l))
#define TLS_BUFFER_sub_left(b, l) ((b)->left -= (l))
#define TLS_BUFFER_get_offset(b) ((b)->offset)
#define TLS_BUFFER_set_offset(b, o) ((b)->offset = (o))
#define TLS_BUFFER_add_offset(b, o) ((b)->offset += (o))
#define TLS_BUFFER_set_app_buffer(b, l) ((b)->app_buffer = (l))
#define TLS_BUFFER_is_app_buffer(b) ((b)->app_buffer)
void ossl_tls_buffer_release(TLS_BUFFER *b);
| 21,009 | 37.83549 | 81 | h |
openssl | openssl-master/ssl/record/methods/ssl3_cbc.c | /*
* Copyright 2012-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 file has no dependencies on the rest of libssl because it is shared
* with the providers. It contains functions for low level MAC calculations.
* Responsibility for this lies with the HMAC implementation in the
* providers. However there are legacy code paths in libssl which also need to
* do this. In time those legacy code paths can be removed and this file can be
* moved out of libssl.
*/
/*
* MD5 and SHA-1 low level APIs are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include <openssl/evp.h>
#ifndef FIPS_MODULE
# include <openssl/md5.h>
#endif
#include <openssl/sha.h>
#include "internal/ssl3_cbc.h"
#include "internal/constant_time.h"
#include "internal/cryptlib.h"
/*
* MAX_HASH_BIT_COUNT_BYTES is the maximum number of bytes in the hash's
* length field. (SHA-384/512 have 128-bit length.)
*/
#define MAX_HASH_BIT_COUNT_BYTES 16
/*
* MAX_HASH_BLOCK_SIZE is the maximum hash block size that we'll support.
* Currently SHA-384/512 has a 128-byte block size and that's the largest
* supported by TLS.)
*/
#define MAX_HASH_BLOCK_SIZE 128
#ifndef FIPS_MODULE
/*
* u32toLE serializes an unsigned, 32-bit number (n) as four bytes at (p) in
* little-endian order. The value of p is advanced by four.
*/
# define u32toLE(n, p) \
(*((p)++) = (unsigned char)(n ), \
*((p)++) = (unsigned char)(n >> 8), \
*((p)++) = (unsigned char)(n >> 16), \
*((p)++) = (unsigned char)(n >> 24))
/*
* These functions serialize the state of a hash and thus perform the
* standard "final" operation without adding the padding and length that such
* a function typically does.
*/
static void tls1_md5_final_raw(void *ctx, unsigned char *md_out)
{
MD5_CTX *md5 = ctx;
u32toLE(md5->A, md_out);
u32toLE(md5->B, md_out);
u32toLE(md5->C, md_out);
u32toLE(md5->D, md_out);
}
#endif /* FIPS_MODULE */
static void tls1_sha1_final_raw(void *ctx, unsigned char *md_out)
{
SHA_CTX *sha1 = ctx;
l2n(sha1->h0, md_out);
l2n(sha1->h1, md_out);
l2n(sha1->h2, md_out);
l2n(sha1->h3, md_out);
l2n(sha1->h4, md_out);
}
static void tls1_sha256_final_raw(void *ctx, unsigned char *md_out)
{
SHA256_CTX *sha256 = ctx;
unsigned i;
for (i = 0; i < 8; i++)
l2n(sha256->h[i], md_out);
}
static void tls1_sha512_final_raw(void *ctx, unsigned char *md_out)
{
SHA512_CTX *sha512 = ctx;
unsigned i;
for (i = 0; i < 8; i++)
l2n8(sha512->h[i], md_out);
}
#undef LARGEST_DIGEST_CTX
#define LARGEST_DIGEST_CTX SHA512_CTX
/*-
* ssl3_cbc_digest_record computes the MAC of a decrypted, padded SSLv3/TLS
* record.
*
* ctx: the EVP_MD_CTX from which we take the hash function.
* ssl3_cbc_record_digest_supported must return true for this EVP_MD_CTX.
* md_out: the digest output. At most EVP_MAX_MD_SIZE bytes will be written.
* md_out_size: if non-NULL, the number of output bytes is written here.
* header: the 13-byte, TLS record header.
* data: the record data itself, less any preceding explicit IV.
* data_size: the secret, reported length of the data once the MAC and padding
* has been removed.
* data_plus_mac_plus_padding_size: the public length of the whole
* record, including MAC and padding.
* is_sslv3: non-zero if we are to use SSLv3. Otherwise, TLS.
*
* On entry: we know that data is data_plus_mac_plus_padding_size in length
* Returns 1 on success or 0 on error
*/
int ssl3_cbc_digest_record(const EVP_MD *md,
unsigned char *md_out,
size_t *md_out_size,
const unsigned char *header,
const unsigned char *data,
size_t data_size,
size_t data_plus_mac_plus_padding_size,
const unsigned char *mac_secret,
size_t mac_secret_length, char is_sslv3)
{
union {
OSSL_UNION_ALIGN;
unsigned char c[sizeof(LARGEST_DIGEST_CTX)];
} md_state;
void (*md_final_raw) (void *ctx, unsigned char *md_out);
void (*md_transform) (void *ctx, const unsigned char *block);
size_t md_size, md_block_size = 64;
size_t sslv3_pad_length = 40, header_length, variance_blocks,
len, max_mac_bytes, num_blocks,
num_starting_blocks, k, mac_end_offset, c, index_a, index_b;
size_t bits; /* at most 18 bits */
unsigned char length_bytes[MAX_HASH_BIT_COUNT_BYTES];
/* hmac_pad is the masked HMAC key. */
unsigned char hmac_pad[MAX_HASH_BLOCK_SIZE];
unsigned char first_block[MAX_HASH_BLOCK_SIZE];
unsigned char mac_out[EVP_MAX_MD_SIZE];
size_t i, j;
unsigned md_out_size_u;
EVP_MD_CTX *md_ctx = NULL;
/*
* mdLengthSize is the number of bytes in the length field that
* terminates * the hash.
*/
size_t md_length_size = 8;
char length_is_big_endian = 1;
int ret = 0;
/*
* This is a, hopefully redundant, check that allows us to forget about
* many possible overflows later in this function.
*/
if (!ossl_assert(data_plus_mac_plus_padding_size < 1024 * 1024))
return 0;
if (EVP_MD_is_a(md, "MD5")) {
#ifdef FIPS_MODULE
return 0;
#else
if (MD5_Init((MD5_CTX *)md_state.c) <= 0)
return 0;
md_final_raw = tls1_md5_final_raw;
md_transform =
(void (*)(void *ctx, const unsigned char *block))MD5_Transform;
md_size = 16;
sslv3_pad_length = 48;
length_is_big_endian = 0;
#endif
} else if (EVP_MD_is_a(md, "SHA1")) {
if (SHA1_Init((SHA_CTX *)md_state.c) <= 0)
return 0;
md_final_raw = tls1_sha1_final_raw;
md_transform =
(void (*)(void *ctx, const unsigned char *block))SHA1_Transform;
md_size = 20;
} else if (EVP_MD_is_a(md, "SHA2-224")) {
if (SHA224_Init((SHA256_CTX *)md_state.c) <= 0)
return 0;
md_final_raw = tls1_sha256_final_raw;
md_transform =
(void (*)(void *ctx, const unsigned char *block))SHA256_Transform;
md_size = 224 / 8;
} else if (EVP_MD_is_a(md, "SHA2-256")) {
if (SHA256_Init((SHA256_CTX *)md_state.c) <= 0)
return 0;
md_final_raw = tls1_sha256_final_raw;
md_transform =
(void (*)(void *ctx, const unsigned char *block))SHA256_Transform;
md_size = 32;
} else if (EVP_MD_is_a(md, "SHA2-384")) {
if (SHA384_Init((SHA512_CTX *)md_state.c) <= 0)
return 0;
md_final_raw = tls1_sha512_final_raw;
md_transform =
(void (*)(void *ctx, const unsigned char *block))SHA512_Transform;
md_size = 384 / 8;
md_block_size = 128;
md_length_size = 16;
} else if (EVP_MD_is_a(md, "SHA2-512")) {
if (SHA512_Init((SHA512_CTX *)md_state.c) <= 0)
return 0;
md_final_raw = tls1_sha512_final_raw;
md_transform =
(void (*)(void *ctx, const unsigned char *block))SHA512_Transform;
md_size = 64;
md_block_size = 128;
md_length_size = 16;
} else {
/*
* ssl3_cbc_record_digest_supported should have been called first to
* check that the hash function is supported.
*/
if (md_out_size != NULL)
*md_out_size = 0;
return ossl_assert(0);
}
if (!ossl_assert(md_length_size <= MAX_HASH_BIT_COUNT_BYTES)
|| !ossl_assert(md_block_size <= MAX_HASH_BLOCK_SIZE)
|| !ossl_assert(md_size <= EVP_MAX_MD_SIZE))
return 0;
header_length = 13;
if (is_sslv3) {
header_length = mac_secret_length
+ sslv3_pad_length
+ 8 /* sequence number */
+ 1 /* record type */
+ 2; /* record length */
}
/*
* variance_blocks is the number of blocks of the hash that we have to
* calculate in constant time because they could be altered by the
* padding value. In SSLv3, the padding must be minimal so the end of
* the plaintext varies by, at most, 15+20 = 35 bytes. (We conservatively
* assume that the MAC size varies from 0..20 bytes.) In case the 9 bytes
* of hash termination (0x80 + 64-bit length) don't fit in the final
* block, we say that the final two blocks can vary based on the padding.
* TLSv1 has MACs up to 48 bytes long (SHA-384) and the padding is not
* required to be minimal. Therefore we say that the final |variance_blocks|
* blocks can
* vary based on the padding. Later in the function, if the message is
* short and there obviously cannot be this many blocks then
* variance_blocks can be reduced.
*/
variance_blocks = is_sslv3 ? 2
: (((255 + 1 + md_size + md_block_size - 1)
/ md_block_size) + 1);
/*
* From now on we're dealing with the MAC, which conceptually has 13
* bytes of `header' before the start of the data (TLS) or 71/75 bytes
* (SSLv3)
*/
len = data_plus_mac_plus_padding_size + header_length;
/*
* max_mac_bytes contains the maximum bytes of bytes in the MAC,
* including * |header|, assuming that there's no padding.
*/
max_mac_bytes = len - md_size - 1;
/* num_blocks is the maximum number of hash blocks. */
num_blocks =
(max_mac_bytes + 1 + md_length_size + md_block_size -
1) / md_block_size;
/*
* In order to calculate the MAC in constant time we have to handle the
* final blocks specially because the padding value could cause the end
* to appear somewhere in the final |variance_blocks| blocks and we can't
* leak where. However, |num_starting_blocks| worth of data can be hashed
* right away because no padding value can affect whether they are
* plaintext.
*/
num_starting_blocks = 0;
/*
* k is the starting byte offset into the conceptual header||data where
* we start processing.
*/
k = 0;
/*
* mac_end_offset is the index just past the end of the data to be MACed.
*/
mac_end_offset = data_size + header_length;
/*
* c is the index of the 0x80 byte in the final hash block that contains
* application data.
*/
c = mac_end_offset % md_block_size;
/*
* index_a is the hash block number that contains the 0x80 terminating
* value.
*/
index_a = mac_end_offset / md_block_size;
/*
* index_b is the hash block number that contains the 64-bit hash length,
* in bits.
*/
index_b = (mac_end_offset + md_length_size) / md_block_size;
/*
* bits is the hash-length in bits. It includes the additional hash block
* for the masked HMAC key, or whole of |header| in the case of SSLv3.
*/
/*
* For SSLv3, if we're going to have any starting blocks then we need at
* least two because the header is larger than a single block.
*/
if (num_blocks > variance_blocks + (is_sslv3 ? 1 : 0)) {
num_starting_blocks = num_blocks - variance_blocks;
k = md_block_size * num_starting_blocks;
}
bits = 8 * mac_end_offset;
if (!is_sslv3) {
/*
* Compute the initial HMAC block. For SSLv3, the padding and secret
* bytes are included in |header| because they take more than a
* single block.
*/
bits += 8 * md_block_size;
memset(hmac_pad, 0, md_block_size);
if (!ossl_assert(mac_secret_length <= sizeof(hmac_pad)))
return 0;
memcpy(hmac_pad, mac_secret, mac_secret_length);
for (i = 0; i < md_block_size; i++)
hmac_pad[i] ^= 0x36;
md_transform(md_state.c, hmac_pad);
}
if (length_is_big_endian) {
memset(length_bytes, 0, md_length_size - 4);
length_bytes[md_length_size - 4] = (unsigned char)(bits >> 24);
length_bytes[md_length_size - 3] = (unsigned char)(bits >> 16);
length_bytes[md_length_size - 2] = (unsigned char)(bits >> 8);
length_bytes[md_length_size - 1] = (unsigned char)bits;
} else {
memset(length_bytes, 0, md_length_size);
length_bytes[md_length_size - 5] = (unsigned char)(bits >> 24);
length_bytes[md_length_size - 6] = (unsigned char)(bits >> 16);
length_bytes[md_length_size - 7] = (unsigned char)(bits >> 8);
length_bytes[md_length_size - 8] = (unsigned char)bits;
}
if (k > 0) {
if (is_sslv3) {
size_t overhang;
/*
* The SSLv3 header is larger than a single block. overhang is
* the number of bytes beyond a single block that the header
* consumes: either 7 bytes (SHA1) or 11 bytes (MD5). There are no
* ciphersuites in SSLv3 that are not SHA1 or MD5 based and
* therefore we can be confident that the header_length will be
* greater than |md_block_size|. However we add a sanity check just
* in case
*/
if (header_length <= md_block_size) {
/* Should never happen */
return 0;
}
overhang = header_length - md_block_size;
md_transform(md_state.c, header);
memcpy(first_block, header + md_block_size, overhang);
memcpy(first_block + overhang, data, md_block_size - overhang);
md_transform(md_state.c, first_block);
for (i = 1; i < k / md_block_size - 1; i++)
md_transform(md_state.c, data + md_block_size * i - overhang);
} else {
/* k is a multiple of md_block_size. */
memcpy(first_block, header, 13);
memcpy(first_block + 13, data, md_block_size - 13);
md_transform(md_state.c, first_block);
for (i = 1; i < k / md_block_size; i++)
md_transform(md_state.c, data + md_block_size * i - 13);
}
}
memset(mac_out, 0, sizeof(mac_out));
/*
* We now process the final hash blocks. For each block, we construct it
* in constant time. If the |i==index_a| then we'll include the 0x80
* bytes and zero pad etc. For each block we selectively copy it, in
* constant time, to |mac_out|.
*/
for (i = num_starting_blocks; i <= num_starting_blocks + variance_blocks;
i++) {
unsigned char block[MAX_HASH_BLOCK_SIZE];
unsigned char is_block_a = constant_time_eq_8_s(i, index_a);
unsigned char is_block_b = constant_time_eq_8_s(i, index_b);
for (j = 0; j < md_block_size; j++) {
unsigned char b = 0, is_past_c, is_past_cp1;
if (k < header_length)
b = header[k];
else if (k < data_plus_mac_plus_padding_size + header_length)
b = data[k - header_length];
k++;
is_past_c = is_block_a & constant_time_ge_8_s(j, c);
is_past_cp1 = is_block_a & constant_time_ge_8_s(j, c + 1);
/*
* If this is the block containing the end of the application
* data, and we are at the offset for the 0x80 value, then
* overwrite b with 0x80.
*/
b = constant_time_select_8(is_past_c, 0x80, b);
/*
* If this block contains the end of the application data
* and we're past the 0x80 value then just write zero.
*/
b = b & ~is_past_cp1;
/*
* If this is index_b (the final block), but not index_a (the end
* of the data), then the 64-bit length didn't fit into index_a
* and we're having to add an extra block of zeros.
*/
b &= ~is_block_b | is_block_a;
/*
* The final bytes of one of the blocks contains the length.
*/
if (j >= md_block_size - md_length_size) {
/* If this is index_b, write a length byte. */
b = constant_time_select_8(is_block_b,
length_bytes[j -
(md_block_size -
md_length_size)], b);
}
block[j] = b;
}
md_transform(md_state.c, block);
md_final_raw(md_state.c, block);
/* If this is index_b, copy the hash value to |mac_out|. */
for (j = 0; j < md_size; j++)
mac_out[j] |= block[j] & is_block_b;
}
md_ctx = EVP_MD_CTX_new();
if (md_ctx == NULL)
goto err;
if (EVP_DigestInit_ex(md_ctx, md, NULL /* engine */) <= 0)
goto err;
if (is_sslv3) {
/* We repurpose |hmac_pad| to contain the SSLv3 pad2 block. */
memset(hmac_pad, 0x5c, sslv3_pad_length);
if (EVP_DigestUpdate(md_ctx, mac_secret, mac_secret_length) <= 0
|| EVP_DigestUpdate(md_ctx, hmac_pad, sslv3_pad_length) <= 0
|| EVP_DigestUpdate(md_ctx, mac_out, md_size) <= 0)
goto err;
} else {
/* Complete the HMAC in the standard manner. */
for (i = 0; i < md_block_size; i++)
hmac_pad[i] ^= 0x6a;
if (EVP_DigestUpdate(md_ctx, hmac_pad, md_block_size) <= 0
|| EVP_DigestUpdate(md_ctx, mac_out, md_size) <= 0)
goto err;
}
ret = EVP_DigestFinal(md_ctx, md_out, &md_out_size_u);
if (ret && md_out_size)
*md_out_size = md_out_size_u;
ret = 1;
err:
EVP_MD_CTX_free(md_ctx);
return ret;
}
| 18,120 | 36.209446 | 80 | c |
openssl | openssl-master/ssl/record/methods/ssl3_meth.c | /*
* Copyright 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/evp.h>
#include <openssl/core_names.h>
#include "internal/ssl3_cbc.h"
#include "../../ssl_local.h"
#include "../record_local.h"
#include "recmethod_local.h"
static int ssl3_set_crypto_state(OSSL_RECORD_LAYER *rl, int level,
unsigned char *key, size_t keylen,
unsigned char *iv, size_t ivlen,
unsigned char *mackey, size_t mackeylen,
const EVP_CIPHER *ciph,
size_t taglen,
int mactype,
const EVP_MD *md,
COMP_METHOD *comp)
{
EVP_CIPHER_CTX *ciph_ctx;
int enc = (rl->direction == OSSL_RECORD_DIRECTION_WRITE) ? 1 : 0;
if (md == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
if ((rl->enc_ctx = EVP_CIPHER_CTX_new()) == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
ciph_ctx = rl->enc_ctx;
rl->md_ctx = EVP_MD_CTX_new();
if (rl->md_ctx == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
if ((md != NULL && EVP_DigestInit_ex(rl->md_ctx, md, NULL) <= 0)) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
#ifndef OPENSSL_NO_COMP
if (comp != NULL) {
rl->compctx = COMP_CTX_new(comp);
if (rl->compctx == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_COMPRESSION_LIBRARY_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
}
#endif
if (!EVP_CipherInit_ex(ciph_ctx, ciph, NULL, key, iv, enc)) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
if (EVP_CIPHER_get0_provider(ciph) != NULL
&& !ossl_set_tls_provider_parameters(rl, ciph_ctx, ciph, md)) {
/* ERR_raise already called */
return OSSL_RECORD_RETURN_FATAL;
}
if (mackeylen > sizeof(rl->mac_secret)) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
memcpy(rl->mac_secret, mackey, mackeylen);
return OSSL_RECORD_RETURN_SUCCESS;
}
/*
* ssl3_cipher encrypts/decrypts |n_recs| records in |inrecs|. Calls RLAYERfatal
* on internal error, but not otherwise. It is the responsibility of the caller
* to report a bad_record_mac
*
* Returns:
* 0: if the record is publicly invalid, or an internal error
* 1: Success or Mac-then-encrypt decryption failed (MAC will be randomised)
*/
static int ssl3_cipher(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *inrecs,
size_t n_recs, int sending, SSL_MAC_BUF *mac,
size_t macsize)
{
TLS_RL_RECORD *rec;
EVP_CIPHER_CTX *ds;
size_t l, i;
size_t bs;
const EVP_CIPHER *enc;
int provided;
rec = inrecs;
/*
* We shouldn't ever be called with more than one record in the SSLv3 case
*/
if (n_recs != 1)
return 0;
ds = rl->enc_ctx;
if (ds == NULL || (enc = EVP_CIPHER_CTX_get0_cipher(ds)) == NULL)
return 0;
provided = (EVP_CIPHER_get0_provider(enc) != NULL);
l = rec->length;
bs = EVP_CIPHER_CTX_get_block_size(ds);
/* COMPRESS */
if ((bs != 1) && sending && !provided) {
/*
* We only do this for legacy ciphers. Provided ciphers add the
* padding on the provider side.
*/
i = bs - (l % bs);
/* we need to add 'i-1' padding bytes */
l += i;
/*
* the last of these zero bytes will be overwritten with the
* padding length.
*/
memset(&rec->input[rec->length], 0, i);
rec->length += i;
rec->input[l - 1] = (unsigned char)(i - 1);
}
if (!sending) {
if (l == 0 || l % bs != 0) {
/* Publicly invalid */
return 0;
}
/* otherwise, rec->length >= bs */
}
if (provided) {
int outlen;
if (!EVP_CipherUpdate(ds, rec->data, &outlen, rec->input,
(unsigned int)l))
return 0;
rec->length = outlen;
if (!sending && mac != NULL) {
/* Now get a pointer to the MAC */
OSSL_PARAM params[2], *p = params;
/* Get the MAC */
mac->alloced = 0;
*p++ = OSSL_PARAM_construct_octet_ptr(OSSL_CIPHER_PARAM_TLS_MAC,
(void **)&mac->mac,
macsize);
*p = OSSL_PARAM_construct_end();
if (!EVP_CIPHER_CTX_get_params(ds, params)) {
/* Shouldn't normally happen */
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
} else {
if (EVP_Cipher(ds, rec->data, rec->input, (unsigned int)l) < 1) {
/* Shouldn't happen */
RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC, ERR_R_INTERNAL_ERROR);
return 0;
}
if (!sending)
return ssl3_cbc_remove_padding_and_mac(&rec->length,
rec->orig_len,
rec->data,
(mac != NULL) ? &mac->mac : NULL,
(mac != NULL) ? &mac->alloced : NULL,
bs,
macsize,
rl->libctx);
}
return 1;
}
static const unsigned char ssl3_pad_1[48] = {
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
};
static const unsigned char ssl3_pad_2[48] = {
0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
};
static int ssl3_mac(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec, unsigned char *md,
int sending)
{
unsigned char *mac_sec, *seq = rl->sequence;
const EVP_MD_CTX *hash;
unsigned char *p, rec_char;
size_t md_size;
size_t npad;
int t;
mac_sec = &(rl->mac_secret[0]);
hash = rl->md_ctx;
t = EVP_MD_CTX_get_size(hash);
if (t <= 0)
return 0;
md_size = t;
npad = (48 / md_size) * md_size;
if (!sending
&& EVP_CIPHER_CTX_get_mode(rl->enc_ctx) == EVP_CIPH_CBC_MODE
&& ssl3_cbc_record_digest_supported(hash)) {
#ifdef OPENSSL_NO_DEPRECATED_3_0
return 0;
#else
/*
* This is a CBC-encrypted record. We must avoid leaking any
* timing-side channel information about how many blocks of data we
* are hashing because that gives an attacker a timing-oracle.
*/
/*-
* npad is, at most, 48 bytes and that's with MD5:
* 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
*
* With SHA-1 (the largest hash speced for SSLv3) the hash size
* goes up 4, but npad goes down by 8, resulting in a smaller
* total size.
*/
unsigned char header[75];
size_t j = 0;
memcpy(header + j, mac_sec, md_size);
j += md_size;
memcpy(header + j, ssl3_pad_1, npad);
j += npad;
memcpy(header + j, seq, 8);
j += 8;
header[j++] = rec->type;
header[j++] = (unsigned char)(rec->length >> 8);
header[j++] = (unsigned char)(rec->length & 0xff);
/* Final param == is SSLv3 */
if (ssl3_cbc_digest_record(EVP_MD_CTX_get0_md(hash),
md, &md_size,
header, rec->input,
rec->length, rec->orig_len,
mac_sec, md_size, 1) <= 0)
return 0;
#endif
} else {
unsigned int md_size_u;
/* Chop the digest off the end :-) */
EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
if (md_ctx == NULL)
return 0;
rec_char = rec->type;
p = md;
s2n(rec->length, p);
if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
|| EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
|| EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
|| EVP_DigestUpdate(md_ctx, seq, 8) <= 0
|| EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
|| EVP_DigestUpdate(md_ctx, md, 2) <= 0
|| EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
|| EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
|| EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
|| EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
|| EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
|| EVP_DigestUpdate(md_ctx, md, md_size) <= 0
|| EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
EVP_MD_CTX_free(md_ctx);
return 0;
}
EVP_MD_CTX_free(md_ctx);
}
if (!tls_increment_sequence_ctr(rl))
return 0;
return 1;
}
struct record_functions_st ssl_3_0_funcs = {
ssl3_set_crypto_state,
ssl3_cipher,
ssl3_mac,
tls_default_set_protocol_version,
tls_default_read_n,
tls_get_more_records,
tls_default_validate_record_header,
tls_default_post_process_record,
tls_get_max_records_default,
tls_write_records_default,
/* These 2 functions are defined in tls1_meth.c */
tls1_allocate_write_buffers,
tls1_initialise_write_packets,
NULL,
tls_prepare_record_header_default,
NULL,
tls_prepare_for_encryption_default,
tls_post_encryption_processing_default,
NULL
};
| 10,584 | 31.271341 | 81 | c |
openssl | openssl-master/ssl/record/methods/tls13_meth.c | /*
* Copyright 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/evp.h>
#include <openssl/core_names.h>
#include "../../ssl_local.h"
#include "../record_local.h"
#include "recmethod_local.h"
static int tls13_set_crypto_state(OSSL_RECORD_LAYER *rl, int level,
unsigned char *key, size_t keylen,
unsigned char *iv, size_t ivlen,
unsigned char *mackey, size_t mackeylen,
const EVP_CIPHER *ciph,
size_t taglen,
int mactype,
const EVP_MD *md,
COMP_METHOD *comp)
{
EVP_CIPHER_CTX *ciph_ctx;
int mode;
int enc = (rl->direction == OSSL_RECORD_DIRECTION_WRITE) ? 1 : 0;
if (ivlen > sizeof(rl->iv)) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
memcpy(rl->iv, iv, ivlen);
ciph_ctx = rl->enc_ctx = EVP_CIPHER_CTX_new();
if (ciph_ctx == NULL) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
mode = EVP_CIPHER_get_mode(ciph);
if (EVP_CipherInit_ex(ciph_ctx, ciph, NULL, NULL, NULL, enc) <= 0
|| EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen,
NULL) <= 0
|| (mode == EVP_CIPH_CCM_MODE
&& EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_TAG, taglen,
NULL) <= 0)
|| EVP_CipherInit_ex(ciph_ctx, NULL, NULL, key, NULL, enc) <= 0) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
return OSSL_RECORD_RETURN_SUCCESS;
}
static int tls13_cipher(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *recs,
size_t n_recs, int sending, SSL_MAC_BUF *mac,
size_t macsize)
{
EVP_CIPHER_CTX *ctx;
unsigned char iv[EVP_MAX_IV_LENGTH], recheader[SSL3_RT_HEADER_LENGTH];
size_t ivlen, offset, loop, hdrlen;
unsigned char *staticiv;
unsigned char *seq = rl->sequence;
int lenu, lenf;
TLS_RL_RECORD *rec = &recs[0];
WPACKET wpkt;
const EVP_CIPHER *cipher;
int mode;
if (n_recs != 1) {
/* Should not happen */
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
ctx = rl->enc_ctx;
staticiv = rl->iv;
cipher = EVP_CIPHER_CTX_get0_cipher(ctx);
if (cipher == NULL) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
mode = EVP_CIPHER_get_mode(cipher);
/*
* If we're sending an alert and ctx != NULL then we must be forcing
* plaintext alerts. If we're reading and ctx != NULL then we allow
* plaintext alerts at certain points in the handshake. If we've got this
* far then we have already validated that a plaintext alert is ok here.
*/
if (ctx == NULL || rec->type == SSL3_RT_ALERT) {
memmove(rec->data, rec->input, rec->length);
rec->input = rec->data;
return 1;
}
ivlen = EVP_CIPHER_CTX_get_iv_length(ctx);
if (!sending) {
/*
* Take off tag. There must be at least one byte of content type as
* well as the tag
*/
if (rec->length < rl->taglen + 1)
return 0;
rec->length -= rl->taglen;
}
/* Set up IV */
if (ivlen < SEQ_NUM_SIZE) {
/* Should not happen */
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
offset = ivlen - SEQ_NUM_SIZE;
memcpy(iv, staticiv, offset);
for (loop = 0; loop < SEQ_NUM_SIZE; loop++)
iv[offset + loop] = staticiv[offset + loop] ^ seq[loop];
if (!tls_increment_sequence_ctr(rl)) {
/* RLAYERfatal already called */
return 0;
}
if (EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, sending) <= 0
|| (!sending && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
rl->taglen,
rec->data + rec->length) <= 0)) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
/* Set up the AAD */
if (!WPACKET_init_static_len(&wpkt, recheader, sizeof(recheader), 0)
|| !WPACKET_put_bytes_u8(&wpkt, rec->type)
|| !WPACKET_put_bytes_u16(&wpkt, rec->rec_version)
|| !WPACKET_put_bytes_u16(&wpkt, rec->length + rl->taglen)
|| !WPACKET_get_total_written(&wpkt, &hdrlen)
|| hdrlen != SSL3_RT_HEADER_LENGTH
|| !WPACKET_finish(&wpkt)) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
WPACKET_cleanup(&wpkt);
return 0;
}
/*
* For CCM we must explicitly set the total plaintext length before we add
* any AAD.
*/
if ((mode == EVP_CIPH_CCM_MODE
&& EVP_CipherUpdate(ctx, NULL, &lenu, NULL,
(unsigned int)rec->length) <= 0)
|| EVP_CipherUpdate(ctx, NULL, &lenu, recheader,
sizeof(recheader)) <= 0
|| EVP_CipherUpdate(ctx, rec->data, &lenu, rec->input,
(unsigned int)rec->length) <= 0
|| EVP_CipherFinal_ex(ctx, rec->data + lenu, &lenf) <= 0
|| (size_t)(lenu + lenf) != rec->length) {
return 0;
}
if (sending) {
/* Add the tag */
if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, rl->taglen,
rec->data + rec->length) <= 0) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
rec->length += rl->taglen;
}
return 1;
}
static int tls13_validate_record_header(OSSL_RECORD_LAYER *rl,
TLS_RL_RECORD *rec)
{
if (rec->type != SSL3_RT_APPLICATION_DATA
&& (rec->type != SSL3_RT_CHANGE_CIPHER_SPEC
|| !rl->is_first_handshake)
&& (rec->type != SSL3_RT_ALERT || !rl->allow_plain_alerts)) {
RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
return 0;
}
if (rec->rec_version != TLS1_2_VERSION) {
RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_WRONG_VERSION_NUMBER);
return 0;
}
if (rec->length > SSL3_RT_MAX_TLS13_ENCRYPTED_LENGTH) {
RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
return 0;
}
return 1;
}
static int tls13_post_process_record(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
{
/* Skip this if we've received a plaintext alert */
if (rec->type != SSL3_RT_ALERT) {
size_t end;
if (rec->length == 0
|| rec->type != SSL3_RT_APPLICATION_DATA) {
RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
SSL_R_BAD_RECORD_TYPE);
return 0;
}
/* Strip trailing padding */
for (end = rec->length - 1; end > 0 && rec->data[end] == 0; end--)
continue;
rec->length = end;
rec->type = rec->data[end];
}
if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
return 0;
}
if (!tls13_common_post_process_record(rl, rec)) {
/* RLAYERfatal already called */
return 0;
}
return 1;
}
static unsigned int tls13_get_record_type(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *template)
{
if (rl->allow_plain_alerts && template->type == SSL3_RT_ALERT)
return SSL3_RT_ALERT;
/*
* Aside from the above case we always use the application data record type
* when encrypting in TLSv1.3. The "inner" record type encodes the "real"
* record type from the template.
*/
return SSL3_RT_APPLICATION_DATA;
}
static int tls13_add_record_padding(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *thistempl,
WPACKET *thispkt,
TLS_RL_RECORD *thiswr)
{
size_t rlen;
/* Nothing to be done in the case of a plaintext alert */
if (rl->allow_plain_alerts && thistempl->type != SSL3_RT_ALERT)
return 1;
if (!WPACKET_put_bytes_u8(thispkt, thistempl->type)) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
TLS_RL_RECORD_add_length(thiswr, 1);
/* Add TLS1.3 padding */
rlen = TLS_RL_RECORD_get_length(thiswr);
if (rlen < rl->max_frag_len) {
size_t padding = 0;
size_t max_padding = rl->max_frag_len - rlen;
if (rl->padding != NULL) {
padding = rl->padding(rl->cbarg, thistempl->type, rlen);
} else if (rl->block_padding > 0) {
size_t mask = rl->block_padding - 1;
size_t remainder;
/* optimize for power of 2 */
if ((rl->block_padding & mask) == 0)
remainder = rlen & mask;
else
remainder = rlen % rl->block_padding;
/* don't want to add a block of padding if we don't have to */
if (remainder == 0)
padding = 0;
else
padding = rl->block_padding - remainder;
}
if (padding > 0) {
/* do not allow the record to exceed max plaintext length */
if (padding > max_padding)
padding = max_padding;
if (!WPACKET_memset(thispkt, 0, padding)) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
ERR_R_INTERNAL_ERROR);
return 0;
}
TLS_RL_RECORD_add_length(thiswr, padding);
}
}
return 1;
}
struct record_functions_st tls_1_3_funcs = {
tls13_set_crypto_state,
tls13_cipher,
NULL,
tls_default_set_protocol_version,
tls_default_read_n,
tls_get_more_records,
tls13_validate_record_header,
tls13_post_process_record,
tls_get_max_records_default,
tls_write_records_default,
tls_allocate_write_buffers_default,
tls_initialise_write_packets_default,
tls13_get_record_type,
tls_prepare_record_header_default,
tls13_add_record_padding,
tls_prepare_for_encryption_default,
tls_post_encryption_processing_default,
NULL
};
| 10,910 | 32.469325 | 81 | c |
openssl | openssl-master/ssl/record/methods/tls1_meth.c | /*
* Copyright 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/evp.h>
#include <openssl/core_names.h>
#include <openssl/rand.h>
#include <openssl/ssl.h>
#include "internal/ssl3_cbc.h"
#include "../../ssl_local.h"
#include "../record_local.h"
#include "recmethod_local.h"
static int tls1_set_crypto_state(OSSL_RECORD_LAYER *rl, int level,
unsigned char *key, size_t keylen,
unsigned char *iv, size_t ivlen,
unsigned char *mackey, size_t mackeylen,
const EVP_CIPHER *ciph,
size_t taglen,
int mactype,
const EVP_MD *md,
COMP_METHOD *comp)
{
EVP_CIPHER_CTX *ciph_ctx;
EVP_PKEY *mac_key;
int enc = (rl->direction == OSSL_RECORD_DIRECTION_WRITE) ? 1 : 0;
if (level != OSSL_RECORD_PROTECTION_LEVEL_APPLICATION)
return OSSL_RECORD_RETURN_FATAL;
if ((rl->enc_ctx = EVP_CIPHER_CTX_new()) == NULL) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
return OSSL_RECORD_RETURN_FATAL;
}
ciph_ctx = rl->enc_ctx;
rl->md_ctx = EVP_MD_CTX_new();
if (rl->md_ctx == NULL) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
#ifndef OPENSSL_NO_COMP
if (comp != NULL) {
rl->compctx = COMP_CTX_new(comp);
if (rl->compctx == NULL) {
ERR_raise(ERR_LIB_SSL, SSL_R_COMPRESSION_LIBRARY_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
}
#endif
/*
* If we have an AEAD Cipher, then there is no separate MAC, so we can skip
* setting up the MAC key.
*/
if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0) {
if (mactype == EVP_PKEY_HMAC) {
mac_key = EVP_PKEY_new_raw_private_key_ex(rl->libctx, "HMAC",
rl->propq, mackey,
mackeylen);
} else {
/*
* If its not HMAC then the only other types of MAC we support are
* the GOST MACs, so we need to use the old style way of creating
* a MAC key.
*/
mac_key = EVP_PKEY_new_mac_key(mactype, NULL, mackey,
(int)mackeylen);
}
if (mac_key == NULL
|| EVP_DigestSignInit_ex(rl->md_ctx, NULL, EVP_MD_get0_name(md),
rl->libctx, rl->propq, mac_key,
NULL) <= 0) {
EVP_PKEY_free(mac_key);
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
EVP_PKEY_free(mac_key);
}
if (EVP_CIPHER_get_mode(ciph) == EVP_CIPH_GCM_MODE) {
if (!EVP_CipherInit_ex(ciph_ctx, ciph, NULL, key, NULL, enc)
|| EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_GCM_SET_IV_FIXED,
(int)ivlen, iv) <= 0) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
} else if (EVP_CIPHER_get_mode(ciph) == EVP_CIPH_CCM_MODE) {
if (!EVP_CipherInit_ex(ciph_ctx, ciph, NULL, NULL, NULL, enc)
|| EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_IVLEN, 12,
NULL) <= 0
|| EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_TAG,
(int)taglen, NULL) <= 0
|| EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_CCM_SET_IV_FIXED,
(int)ivlen, iv) <= 0
|| !EVP_CipherInit_ex(ciph_ctx, NULL, NULL, key, NULL, enc)) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
} else {
if (!EVP_CipherInit_ex(ciph_ctx, ciph, NULL, key, iv, enc)) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
}
/* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) != 0
&& mackeylen != 0
&& EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_MAC_KEY,
(int)mackeylen, mackey) <= 0) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
if (EVP_CIPHER_get0_provider(ciph) != NULL
&& !ossl_set_tls_provider_parameters(rl, ciph_ctx, ciph, md))
return OSSL_RECORD_RETURN_FATAL;
/* Calculate the explicit IV length */
if (RLAYER_USE_EXPLICIT_IV(rl)) {
int mode = EVP_CIPHER_CTX_get_mode(ciph_ctx);
int eivlen = 0;
if (mode == EVP_CIPH_CBC_MODE) {
eivlen = EVP_CIPHER_CTX_get_iv_length(ciph_ctx);
if (eivlen < 0) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
return OSSL_RECORD_RETURN_FATAL;
}
if (eivlen <= 1)
eivlen = 0;
} else if (mode == EVP_CIPH_GCM_MODE) {
/* Need explicit part of IV for GCM mode */
eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
} else if (mode == EVP_CIPH_CCM_MODE) {
eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
}
rl->eivlen = (size_t)eivlen;
}
return OSSL_RECORD_RETURN_SUCCESS;
}
#define MAX_PADDING 256
/*-
* tls1_cipher encrypts/decrypts |n_recs| in |recs|. Calls RLAYERfatal on
* internal error, but not otherwise. It is the responsibility of the caller to
* report a bad_record_mac - if appropriate (DTLS just drops the record).
*
* Returns:
* 0: if the record is publicly invalid, or an internal error, or AEAD
* decryption failed, or Encrypt-then-mac decryption failed.
* 1: Success or Mac-then-encrypt decryption failed (MAC will be randomised)
*/
static int tls1_cipher(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *recs,
size_t n_recs, int sending, SSL_MAC_BUF *macs,
size_t macsize)
{
EVP_CIPHER_CTX *ds;
size_t reclen[SSL_MAX_PIPELINES];
unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
unsigned char *data[SSL_MAX_PIPELINES];
int pad = 0, tmpr, provided;
size_t bs, ctr, padnum, loop;
unsigned char padval;
const EVP_CIPHER *enc;
if (n_recs == 0) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (EVP_MD_CTX_get0_md(rl->md_ctx)) {
int n = EVP_MD_CTX_get_size(rl->md_ctx);
if (!ossl_assert(n >= 0)) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
ds = rl->enc_ctx;
if (!ossl_assert(rl->enc_ctx != NULL)) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
enc = EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx);
if (sending) {
int ivlen;
/* For TLSv1.1 and later explicit IV */
if (RLAYER_USE_EXPLICIT_IV(rl)
&& EVP_CIPHER_get_mode(enc) == EVP_CIPH_CBC_MODE)
ivlen = EVP_CIPHER_get_iv_length(enc);
else
ivlen = 0;
if (ivlen > 1) {
for (ctr = 0; ctr < n_recs; ctr++) {
if (recs[ctr].data != recs[ctr].input) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
} else if (RAND_bytes_ex(rl->libctx, recs[ctr].input,
ivlen, 0) <= 0) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
}
}
if (!ossl_assert(enc != NULL)) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
provided = (EVP_CIPHER_get0_provider(enc) != NULL);
bs = EVP_CIPHER_get_block_size(EVP_CIPHER_CTX_get0_cipher(ds));
if (n_recs > 1) {
if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ds))
& EVP_CIPH_FLAG_PIPELINE) == 0) {
/*
* We shouldn't have been called with pipeline data if the
* cipher doesn't support pipelining
*/
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_PIPELINE_FAILURE);
return 0;
}
}
for (ctr = 0; ctr < n_recs; ctr++) {
reclen[ctr] = recs[ctr].length;
if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ds))
& EVP_CIPH_FLAG_AEAD_CIPHER) != 0) {
unsigned char *seq;
seq = rl->sequence;
if (rl->isdtls) {
unsigned char dtlsseq[8], *p = dtlsseq;
s2n(rl->epoch, p);
memcpy(p, &seq[2], 6);
memcpy(buf[ctr], dtlsseq, 8);
} else {
memcpy(buf[ctr], seq, 8);
if (!tls_increment_sequence_ctr(rl)) {
/* RLAYERfatal already called */
return 0;
}
}
buf[ctr][8] = recs[ctr].type;
buf[ctr][9] = (unsigned char)(rl->version >> 8);
buf[ctr][10] = (unsigned char)(rl->version);
buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
if (pad <= 0) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (sending) {
reclen[ctr] += pad;
recs[ctr].length += pad;
}
} else if ((bs != 1) && sending && !provided) {
/*
* We only do this for legacy ciphers. Provided ciphers add the
* padding on the provider side.
*/
padnum = bs - (reclen[ctr] % bs);
/* Add weird padding of up to 256 bytes */
if (padnum > MAX_PADDING) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
/* we need to add 'padnum' padding bytes of value padval */
padval = (unsigned char)(padnum - 1);
for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
recs[ctr].input[loop] = padval;
reclen[ctr] += padnum;
recs[ctr].length += padnum;
}
if (!sending) {
if (reclen[ctr] == 0 || reclen[ctr] % bs != 0) {
/* Publicly invalid */
return 0;
}
}
}
if (n_recs > 1) {
/* Set the output buffers */
for (ctr = 0; ctr < n_recs; ctr++)
data[ctr] = recs[ctr].data;
if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
(int)n_recs, data) <= 0) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_PIPELINE_FAILURE);
return 0;
}
/* Set the input buffers */
for (ctr = 0; ctr < n_recs; ctr++)
data[ctr] = recs[ctr].input;
if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
(int)n_recs, data) <= 0
|| EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
(int)n_recs, reclen) <= 0) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_PIPELINE_FAILURE);
return 0;
}
}
if (!rl->isdtls && rl->tlstree) {
int decrement_seq = 0;
/*
* When sending, seq is incremented after MAC calculation.
* So if we are in ETM mode, we use seq 'as is' in the ctrl-function.
* Otherwise we have to decrease it in the implementation
*/
if (sending && !rl->use_etm)
decrement_seq = 1;
if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_TLSTREE, decrement_seq,
rl->sequence) <= 0) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
if (provided) {
int outlen;
/* Provided cipher - we do not support pipelining on this path */
if (n_recs > 1) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (!EVP_CipherUpdate(ds, recs[0].data, &outlen, recs[0].input,
(unsigned int)reclen[0]))
return 0;
recs[0].length = outlen;
/*
* The length returned from EVP_CipherUpdate above is the actual
* payload length. We need to adjust the data/input ptr to skip over
* any explicit IV
*/
if (!sending) {
if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_GCM_MODE) {
recs[0].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
recs[0].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
} else if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_CCM_MODE) {
recs[0].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
recs[0].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
} else if (bs != 1 && RLAYER_USE_EXPLICIT_IV(rl)) {
recs[0].data += bs;
recs[0].input += bs;
recs[0].orig_len -= bs;
}
/* Now get a pointer to the MAC (if applicable) */
if (macs != NULL) {
OSSL_PARAM params[2], *p = params;
/* Get the MAC */
macs[0].alloced = 0;
*p++ = OSSL_PARAM_construct_octet_ptr(OSSL_CIPHER_PARAM_TLS_MAC,
(void **)&macs[0].mac,
macsize);
*p = OSSL_PARAM_construct_end();
if (!EVP_CIPHER_CTX_get_params(ds, params)) {
/* Shouldn't normally happen */
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
ERR_R_INTERNAL_ERROR);
return 0;
}
}
}
} else {
/* Legacy cipher */
tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
(unsigned int)reclen[0]);
if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ds))
& EVP_CIPH_FLAG_CUSTOM_CIPHER) != 0
? (tmpr < 0)
: (tmpr == 0)) {
/* AEAD can fail to verify MAC */
return 0;
}
if (!sending) {
for (ctr = 0; ctr < n_recs; ctr++) {
/* Adjust the record to remove the explicit IV/MAC/Tag */
if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_GCM_MODE) {
recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
} else if (EVP_CIPHER_get_mode(enc) == EVP_CIPH_CCM_MODE) {
recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
} else if (bs != 1 && RLAYER_USE_EXPLICIT_IV(rl)) {
if (recs[ctr].length < bs)
return 0;
recs[ctr].data += bs;
recs[ctr].input += bs;
recs[ctr].length -= bs;
recs[ctr].orig_len -= bs;
}
/*
* If using Mac-then-encrypt, then this will succeed but
* with a random MAC if padding is invalid
*/
if (!tls1_cbc_remove_padding_and_mac(&recs[ctr].length,
recs[ctr].orig_len,
recs[ctr].data,
(macs != NULL) ? &macs[ctr].mac : NULL,
(macs != NULL) ? &macs[ctr].alloced
: NULL,
bs,
pad ? (size_t)pad : macsize,
(EVP_CIPHER_get_flags(enc)
& EVP_CIPH_FLAG_AEAD_CIPHER) != 0,
rl->libctx))
return 0;
}
}
}
return 1;
}
static int tls1_mac(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec, unsigned char *md,
int sending)
{
unsigned char *seq = rl->sequence;
EVP_MD_CTX *hash;
size_t md_size;
EVP_MD_CTX *hmac = NULL, *mac_ctx;
unsigned char header[13];
int t;
int ret = 0;
hash = rl->md_ctx;
t = EVP_MD_CTX_get_size(hash);
if (!ossl_assert(t >= 0))
return 0;
md_size = t;
if (rl->stream_mac) {
mac_ctx = hash;
} else {
hmac = EVP_MD_CTX_new();
if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash)) {
goto end;
}
mac_ctx = hmac;
}
if (!rl->isdtls
&& rl->tlstree
&& EVP_MD_CTX_ctrl(mac_ctx, EVP_MD_CTRL_TLSTREE, 0, seq) <= 0)
goto end;
if (rl->isdtls) {
unsigned char dtlsseq[8], *p = dtlsseq;
s2n(rl->epoch, p);
memcpy(p, &seq[2], 6);
memcpy(header, dtlsseq, 8);
} else {
memcpy(header, seq, 8);
}
header[8] = rec->type;
header[9] = (unsigned char)(rl->version >> 8);
header[10] = (unsigned char)(rl->version);
header[11] = (unsigned char)(rec->length >> 8);
header[12] = (unsigned char)(rec->length & 0xff);
if (!sending && !rl->use_etm
&& EVP_CIPHER_CTX_get_mode(rl->enc_ctx) == EVP_CIPH_CBC_MODE
&& ssl3_cbc_record_digest_supported(mac_ctx)) {
OSSL_PARAM tls_hmac_params[2], *p = tls_hmac_params;
*p++ = OSSL_PARAM_construct_size_t(OSSL_MAC_PARAM_TLS_DATA_SIZE,
&rec->orig_len);
*p++ = OSSL_PARAM_construct_end();
if (!EVP_PKEY_CTX_set_params(EVP_MD_CTX_get_pkey_ctx(mac_ctx),
tls_hmac_params))
goto end;
}
if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
|| EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
|| EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0)
goto end;
OSSL_TRACE_BEGIN(TLS) {
BIO_printf(trc_out, "seq:\n");
BIO_dump_indent(trc_out, seq, 8, 4);
BIO_printf(trc_out, "rec:\n");
BIO_dump_indent(trc_out, rec->data, rec->length, 4);
} OSSL_TRACE_END(TLS);
if (!rl->isdtls && !tls_increment_sequence_ctr(rl)) {
/* RLAYERfatal already called */
goto end;
}
OSSL_TRACE_BEGIN(TLS) {
BIO_printf(trc_out, "md:\n");
BIO_dump_indent(trc_out, md, md_size, 4);
} OSSL_TRACE_END(TLS);
ret = 1;
end:
EVP_MD_CTX_free(hmac);
return ret;
}
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
# ifndef OPENSSL_NO_COMP
# define MAX_PREFIX_LEN ((SSL3_ALIGN_PAYLOAD - 1) \
+ SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD \
+ SSL3_RT_HEADER_LENGTH \
+ SSL3_RT_MAX_COMPRESSED_OVERHEAD)
# else
# define MAX_PREFIX_LEN ((SSL3_ALIGN_PAYLOAD - 1) \
+ SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD \
+ SSL3_RT_HEADER_LENGTH)
# endif /* OPENSSL_NO_COMP */
#else
# ifndef OPENSSL_NO_COMP
# define MAX_PREFIX_LEN (SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD \
+ SSL3_RT_HEADER_LENGTH \
+ SSL3_RT_MAX_COMPRESSED_OVERHEAD)
# else
# define MAX_PREFIX_LEN (SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD \
+ SSL3_RT_HEADER_LENGTH)
# endif /* OPENSSL_NO_COMP */
#endif
/* This function is also used by the SSLv3 implementation */
int tls1_allocate_write_buffers(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *templates,
size_t numtempl, size_t *prefix)
{
/* Do we need to add an empty record prefix? */
*prefix = rl->need_empty_fragments
&& templates[0].type == SSL3_RT_APPLICATION_DATA;
/*
* In the prefix case we can allocate a much smaller buffer. Otherwise we
* just allocate the default buffer size
*/
if (!tls_setup_write_buffer(rl, numtempl + *prefix,
*prefix ? MAX_PREFIX_LEN : 0, 0)) {
/* RLAYERfatal() already called */
return 0;
}
return 1;
}
/* This function is also used by the SSLv3 implementation */
int tls1_initialise_write_packets(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *templates,
size_t numtempl,
OSSL_RECORD_TEMPLATE *prefixtempl,
WPACKET *pkt,
TLS_BUFFER *bufs,
size_t *wpinited)
{
size_t align = 0;
TLS_BUFFER *wb;
size_t prefix;
/* Do we need to add an empty record prefix? */
prefix = rl->need_empty_fragments
&& templates[0].type == SSL3_RT_APPLICATION_DATA;
if (prefix) {
/*
* countermeasure against known-IV weakness in CBC ciphersuites (see
* http://www.openssl.org/~bodo/tls-cbc.txt)
*/
prefixtempl->buf = NULL;
prefixtempl->version = templates[0].version;
prefixtempl->buflen = 0;
prefixtempl->type = SSL3_RT_APPLICATION_DATA;
wb = &bufs[0];
#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
align = (size_t)TLS_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
align = SSL3_ALIGN_PAYLOAD - 1
- ((align - 1) % SSL3_ALIGN_PAYLOAD);
#endif
TLS_BUFFER_set_offset(wb, align);
if (!WPACKET_init_static_len(&pkt[0], TLS_BUFFER_get_buf(wb),
TLS_BUFFER_get_len(wb), 0)) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
*wpinited = 1;
if (!WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
}
return tls_initialise_write_packets_default(rl, templates, numtempl,
NULL,
pkt + prefix, bufs + prefix,
wpinited);
}
/* TLSv1.0, TLSv1.1 and TLSv1.2 all use the same funcs */
struct record_functions_st tls_1_funcs = {
tls1_set_crypto_state,
tls1_cipher,
tls1_mac,
tls_default_set_protocol_version,
tls_default_read_n,
tls_get_more_records,
tls_default_validate_record_header,
tls_default_post_process_record,
tls_get_max_records_multiblock,
tls_write_records_multiblock, /* Defined in tls_multib.c */
tls1_allocate_write_buffers,
tls1_initialise_write_packets,
NULL,
tls_prepare_record_header_default,
NULL,
tls_prepare_for_encryption_default,
tls_post_encryption_processing_default,
NULL
};
struct record_functions_st dtls_1_funcs = {
tls1_set_crypto_state,
tls1_cipher,
tls1_mac,
tls_default_set_protocol_version,
tls_default_read_n,
dtls_get_more_records,
NULL,
NULL,
NULL,
tls_write_records_default,
/*
* Don't use tls1_allocate_write_buffers since that handles empty fragment
* records which aren't needed in DTLS. We just use the default allocation
* instead.
*/
tls_allocate_write_buffers_default,
/* Don't use tls1_initialise_write_packets for same reason as above */
tls_initialise_write_packets_default,
NULL,
dtls_prepare_record_header,
NULL,
tls_prepare_for_encryption_default,
dtls_post_encryption_processing,
NULL
};
| 24,832 | 35.04209 | 81 | c |
openssl | openssl-master/ssl/record/methods/tls_multib.c | /*
* Copyright 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 "../../ssl_local.h"
#include "../record_local.h"
#include "recmethod_local.h"
#if defined(OPENSSL_SMALL_FOOTPRINT) \
|| !(defined(AES_ASM) && (defined(__x86_64) \
|| defined(__x86_64__) \
|| defined(_M_AMD64) \
|| defined(_M_X64)))
# undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
# define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
#endif
static int tls_is_multiblock_capable(OSSL_RECORD_LAYER *rl, int type,
size_t len, size_t fraglen)
{
#if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
if (type == SSL3_RT_APPLICATION_DATA
&& len >= 4 * fraglen
&& rl->compctx == NULL
&& rl->msg_callback == NULL
&& !rl->use_etm
&& RLAYER_USE_EXPLICIT_IV(rl)
&& !BIO_get_ktls_send(rl->bio)
&& (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
& EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0)
return 1;
#endif
return 0;
}
size_t tls_get_max_records_multiblock(OSSL_RECORD_LAYER *rl, int type,
size_t len, size_t maxfrag,
size_t *preffrag)
{
if (tls_is_multiblock_capable(rl, type, len, *preffrag)) {
/* minimize address aliasing conflicts */
if ((*preffrag & 0xfff) == 0)
*preffrag -= 512;
if (len >= 8 * (*preffrag))
return 8;
return 4;
}
return tls_get_max_records_default(rl, type, len, maxfrag, preffrag);
}
/*
* Write records using the multiblock method.
*
* Returns 1 on success, 0 if multiblock isn't suitable (non-fatal error), or
* -1 on fatal error.
*/
static int tls_write_records_multiblock_int(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *templates,
size_t numtempl)
{
#if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
size_t i;
size_t totlen;
TLS_BUFFER *wb;
unsigned char aad[13];
EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
size_t packlen;
int packleni;
if (numtempl != 4 && numtempl != 8)
return 0;
/*
* Check templates have contiguous buffers and are all the same type and
* length
*/
for (i = 1; i < numtempl; i++) {
if (templates[i - 1].type != templates[i].type
|| templates[i - 1].buflen != templates[i].buflen
|| templates[i - 1].buf + templates[i - 1].buflen
!= templates[i].buf)
return 0;
}
totlen = templates[0].buflen * numtempl;
if (!tls_is_multiblock_capable(rl, templates[0].type, totlen,
templates[0].buflen))
return 0;
/*
* If we get this far, then multiblock is suitable
* Depending on platform multi-block can deliver several *times*
* better performance. Downside is that it has to allocate
* jumbo buffer to accommodate up to 8 records, but the
* compromise is considered worthy.
*/
/*
* Allocate jumbo buffer. This will get freed next time we do a non
* multiblock write in the call to tls_setup_write_buffer() - the different
* buffer sizes will be spotted and the buffer reallocated.
*/
packlen = EVP_CIPHER_CTX_ctrl(rl->enc_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
(int)templates[0].buflen, NULL);
packlen *= numtempl;
if (!tls_setup_write_buffer(rl, 1, packlen, packlen)) {
/* RLAYERfatal() already called */
return -1;
}
wb = &rl->wbuf[0];
mb_param.interleave = numtempl;
memcpy(aad, rl->sequence, 8);
aad[8] = templates[0].type;
aad[9] = (unsigned char)(templates[0].version >> 8);
aad[10] = (unsigned char)(templates[0].version);
aad[11] = 0;
aad[12] = 0;
mb_param.out = NULL;
mb_param.inp = aad;
mb_param.len = totlen;
packleni = EVP_CIPHER_CTX_ctrl(rl->enc_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
sizeof(mb_param), &mb_param);
packlen = (size_t)packleni;
if (packleni <= 0 || packlen > wb->len) { /* never happens */
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return -1;
}
mb_param.out = wb->buf;
mb_param.inp = templates[0].buf;
mb_param.len = totlen;
if (EVP_CIPHER_CTX_ctrl(rl->enc_ctx,
EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
sizeof(mb_param), &mb_param) <= 0) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return -1;
}
rl->sequence[7] += mb_param.interleave;
if (rl->sequence[7] < mb_param.interleave) {
int j = 6;
while (j >= 0 && (++rl->sequence[j--]) == 0) ;
}
wb->offset = 0;
wb->left = packlen;
return 1;
#else /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
return 0;
#endif
}
int tls_write_records_multiblock(OSSL_RECORD_LAYER *rl,
OSSL_RECORD_TEMPLATE *templates,
size_t numtempl)
{
int ret;
ret = tls_write_records_multiblock_int(rl, templates, numtempl);
if (ret < 0) {
/* RLAYERfatal already called */
return 0;
}
if (ret == 0) {
/* Multiblock wasn't suitable so just do a standard write */
if (!tls_write_records_default(rl, templates, numtempl)) {
/* RLAYERfatal already called */
return 0;
}
}
return 1;
}
| 6,079 | 31.340426 | 79 | c |
openssl | openssl-master/ssl/record/methods/tls_pad.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/rand.h>
#include <openssl/evp.h>
#include "internal/constant_time.h"
#include "internal/cryptlib.h"
#include "internal/ssl3_cbc.h"
/*
* This file has no dependencies on the rest of libssl because it is shared
* with the providers. It contains functions for low level CBC TLS padding
* removal. Responsibility for this lies with the cipher implementations in the
* providers. However there are legacy code paths in libssl which also need to
* do this. In time those legacy code paths can be removed and this file can be
* moved out of libssl.
*/
static int ssl3_cbc_copy_mac(size_t *reclen,
size_t origreclen,
unsigned char *recdata,
unsigned char **mac,
int *alloced,
size_t block_size,
size_t mac_size,
size_t good,
OSSL_LIB_CTX *libctx);
/*-
* ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
* record in |recdata| by updating |reclen| in constant time. It also extracts
* the MAC from the underlying record and places a pointer to it in |mac|. The
* MAC data can either be newly allocated memory, or a pointer inside the
* |recdata| buffer. If allocated then |*alloced| is set to 1, otherwise it is
* set to 0.
*
* origreclen: the original record length before any changes were made
* block_size: the block size of the cipher used to encrypt the record.
* mac_size: the size of the MAC to be extracted
* aead: 1 if an AEAD cipher is in use, or 0 otherwise
* returns:
* 0: if the record is publicly invalid.
* 1: if the record is publicly valid. If the padding removal fails then the
* MAC returned is random.
*/
int ssl3_cbc_remove_padding_and_mac(size_t *reclen,
size_t origreclen,
unsigned char *recdata,
unsigned char **mac,
int *alloced,
size_t block_size, size_t mac_size,
OSSL_LIB_CTX *libctx)
{
size_t padding_length;
size_t good;
const size_t overhead = 1 /* padding length byte */ + mac_size;
/*
* These lengths are all public so we can test them in non-constant time.
*/
if (overhead > *reclen)
return 0;
padding_length = recdata[*reclen - 1];
good = constant_time_ge_s(*reclen, padding_length + overhead);
/* SSLv3 requires that the padding is minimal. */
good &= constant_time_ge_s(block_size, padding_length + 1);
*reclen -= good & (padding_length + 1);
return ssl3_cbc_copy_mac(reclen, origreclen, recdata, mac, alloced,
block_size, mac_size, good, libctx);
}
/*-
* tls1_cbc_remove_padding_and_mac removes padding from the decrypted, TLS, CBC
* record in |recdata| by updating |reclen| in constant time. It also extracts
* the MAC from the underlying record and places a pointer to it in |mac|. The
* MAC data can either be newly allocated memory, or a pointer inside the
* |recdata| buffer. If allocated then |*alloced| is set to 1, otherwise it is
* set to 0.
*
* origreclen: the original record length before any changes were made
* block_size: the block size of the cipher used to encrypt the record.
* mac_size: the size of the MAC to be extracted
* aead: 1 if an AEAD cipher is in use, or 0 otherwise
* returns:
* 0: if the record is publicly invalid.
* 1: if the record is publicly valid. If the padding removal fails then the
* MAC returned is random.
*/
int tls1_cbc_remove_padding_and_mac(size_t *reclen,
size_t origreclen,
unsigned char *recdata,
unsigned char **mac,
int *alloced,
size_t block_size, size_t mac_size,
int aead,
OSSL_LIB_CTX *libctx)
{
size_t good = -1;
size_t padding_length, to_check, i;
size_t overhead = ((block_size == 1) ? 0 : 1) /* padding length byte */
+ mac_size;
/*
* These lengths are all public so we can test them in non-constant
* time.
*/
if (overhead > *reclen)
return 0;
if (block_size != 1) {
padding_length = recdata[*reclen - 1];
if (aead) {
/* padding is already verified and we don't need to check the MAC */
*reclen -= padding_length + 1 + mac_size;
return 1;
}
good = constant_time_ge_s(*reclen, overhead + padding_length);
/*
* The padding consists of a length byte at the end of the record and
* then that many bytes of padding, all with the same value as the
* length byte. Thus, with the length byte included, there are i+1 bytes
* of padding. We can't check just |padding_length+1| bytes because that
* leaks decrypted information. Therefore we always have to check the
* maximum amount of padding possible. (Again, the length of the record
* is public information so we can use it.)
*/
to_check = 256; /* maximum amount of padding, inc length byte. */
if (to_check > *reclen)
to_check = *reclen;
for (i = 0; i < to_check; i++) {
unsigned char mask = constant_time_ge_8_s(padding_length, i);
unsigned char b = recdata[*reclen - 1 - i];
/*
* The final |padding_length+1| bytes should all have the value
* |padding_length|. Therefore the XOR should be zero.
*/
good &= ~(mask & (padding_length ^ b));
}
/*
* If any of the final |padding_length+1| bytes had the wrong value, one
* or more of the lower eight bits of |good| will be cleared.
*/
good = constant_time_eq_s(0xff, good & 0xff);
*reclen -= good & (padding_length + 1);
}
return ssl3_cbc_copy_mac(reclen, origreclen, recdata, mac, alloced,
block_size, mac_size, good, libctx);
}
/*-
* ssl3_cbc_copy_mac copies |md_size| bytes from the end of the record in
* |recdata| to |*mac| in constant time (independent of the concrete value of
* the record length |reclen|, which may vary within a 256-byte window).
*
* On entry:
* origreclen >= mac_size
* mac_size <= EVP_MAX_MD_SIZE
*
* If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
* variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
* a single or pair of cache-lines, then the variable memory accesses don't
* actually affect the timing. CPUs with smaller cache-lines [if any] are
* not multi-core and are not considered vulnerable to cache-timing attacks.
*/
#define CBC_MAC_ROTATE_IN_PLACE
static int ssl3_cbc_copy_mac(size_t *reclen,
size_t origreclen,
unsigned char *recdata,
unsigned char **mac,
int *alloced,
size_t block_size,
size_t mac_size,
size_t good,
OSSL_LIB_CTX *libctx)
{
#if defined(CBC_MAC_ROTATE_IN_PLACE)
unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
unsigned char *rotated_mac;
char aux1, aux2, aux3, mask;
#else
unsigned char rotated_mac[EVP_MAX_MD_SIZE];
#endif
unsigned char randmac[EVP_MAX_MD_SIZE];
unsigned char *out;
/*
* mac_end is the index of |recdata| just after the end of the MAC.
*/
size_t mac_end = *reclen;
size_t mac_start = mac_end - mac_size;
size_t in_mac;
/*
* scan_start contains the number of bytes that we can ignore because the
* MAC's position can only vary by 255 bytes.
*/
size_t scan_start = 0;
size_t i, j;
size_t rotate_offset;
if (!ossl_assert(origreclen >= mac_size
&& mac_size <= EVP_MAX_MD_SIZE))
return 0;
/* If no MAC then nothing to be done */
if (mac_size == 0) {
/* No MAC so we can do this in non-constant time */
if (good == 0)
return 0;
return 1;
}
*reclen -= mac_size;
if (block_size == 1) {
/* There's no padding so the position of the MAC is fixed */
if (mac != NULL)
*mac = &recdata[*reclen];
if (alloced != NULL)
*alloced = 0;
return 1;
}
/* Create the random MAC we will emit if padding is bad */
if (RAND_bytes_ex(libctx, randmac, mac_size, 0) <= 0)
return 0;
if (!ossl_assert(mac != NULL && alloced != NULL))
return 0;
*mac = out = OPENSSL_malloc(mac_size);
if (*mac == NULL)
return 0;
*alloced = 1;
#if defined(CBC_MAC_ROTATE_IN_PLACE)
rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
#endif
/* This information is public so it's safe to branch based on it. */
if (origreclen > mac_size + 255 + 1)
scan_start = origreclen - (mac_size + 255 + 1);
in_mac = 0;
rotate_offset = 0;
memset(rotated_mac, 0, mac_size);
for (i = scan_start, j = 0; i < origreclen; i++) {
size_t mac_started = constant_time_eq_s(i, mac_start);
size_t mac_ended = constant_time_lt_s(i, mac_end);
unsigned char b = recdata[i];
in_mac |= mac_started;
in_mac &= mac_ended;
rotate_offset |= j & mac_started;
rotated_mac[j++] |= b & in_mac;
j &= constant_time_lt_s(j, mac_size);
}
/* Now rotate the MAC */
#if defined(CBC_MAC_ROTATE_IN_PLACE)
j = 0;
for (i = 0; i < mac_size; i++) {
/*
* in case cache-line is 32 bytes,
* load from both lines and select appropriately
*/
aux1 = rotated_mac[rotate_offset & ~32];
aux2 = rotated_mac[rotate_offset | 32];
mask = constant_time_eq_8(rotate_offset & ~32, rotate_offset);
aux3 = constant_time_select_8(mask, aux1, aux2);
rotate_offset++;
/* If the padding wasn't good we emit a random MAC */
out[j++] = constant_time_select_8((unsigned char)(good & 0xff),
aux3,
randmac[i]);
rotate_offset &= constant_time_lt_s(rotate_offset, mac_size);
}
#else
memset(out, 0, mac_size);
rotate_offset = mac_size - rotate_offset;
rotate_offset &= constant_time_lt_s(rotate_offset, mac_size);
for (i = 0; i < mac_size; i++) {
for (j = 0; j < mac_size; j++)
out[j] |= rotated_mac[i] & constant_time_eq_8_s(j, rotate_offset);
rotate_offset++;
rotate_offset &= constant_time_lt_s(rotate_offset, mac_size);
/* If the padding wasn't good we emit a random MAC */
out[i] = constant_time_select_8((unsigned char)(good & 0xff), out[i],
randmac[i]);
}
#endif
return 1;
}
| 11,630 | 36.398714 | 80 | c |
openssl | openssl-master/ssl/record/methods/tlsany_meth.c | /*
* Copyright 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/evp.h>
#include "../../ssl_local.h"
#include "../record_local.h"
#include "recmethod_local.h"
#define MIN_SSL2_RECORD_LEN 9
static int tls_any_set_crypto_state(OSSL_RECORD_LAYER *rl, int level,
unsigned char *key, size_t keylen,
unsigned char *iv, size_t ivlen,
unsigned char *mackey, size_t mackeylen,
const EVP_CIPHER *ciph,
size_t taglen,
int mactype,
const EVP_MD *md,
COMP_METHOD *comp)
{
if (level != OSSL_RECORD_PROTECTION_LEVEL_NONE) {
ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
return OSSL_RECORD_RETURN_FATAL;
}
/* No crypto protection at the "NONE" level so nothing to be done */
return OSSL_RECORD_RETURN_SUCCESS;
}
static int tls_any_cipher(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *recs,
size_t n_recs, int sending, SSL_MAC_BUF *macs,
size_t macsize)
{
return 1;
}
static int tls_validate_record_header(OSSL_RECORD_LAYER *rl, TLS_RL_RECORD *rec)
{
if (rec->rec_version == SSL2_VERSION) {
/* SSLv2 format ClientHello */
if (!ossl_assert(rl->version == TLS_ANY_VERSION)) {
RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if (rec->length < MIN_SSL2_RECORD_LEN) {
RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
return 0;
}
} else {
if (rl->version == TLS_ANY_VERSION) {
if ((rec->rec_version >> 8) != SSL3_VERSION_MAJOR) {
if (rl->is_first_record) {
unsigned char *p;
/*
* Go back to start of packet, look at the five bytes that
* we have.
*/
p = rl->packet;
if (HAS_PREFIX((char *)p, "GET ") ||
HAS_PREFIX((char *)p, "POST ") ||
HAS_PREFIX((char *)p, "HEAD ") ||
HAS_PREFIX((char *)p, "PUT ")) {
RLAYERfatal(rl, SSL_AD_NO_ALERT, SSL_R_HTTP_REQUEST);
return 0;
} else if (HAS_PREFIX((char *)p, "CONNE")) {
RLAYERfatal(rl, SSL_AD_NO_ALERT,
SSL_R_HTTPS_PROXY_REQUEST);
return 0;
}
/* Doesn't look like TLS - don't send an alert */
RLAYERfatal(rl, SSL_AD_NO_ALERT,
SSL_R_WRONG_VERSION_NUMBER);
return 0;
} else {
RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
SSL_R_WRONG_VERSION_NUMBER);
return 0;
}
}
} else if (rl->version == TLS1_3_VERSION) {
/*
* In this case we know we are going to negotiate TLSv1.3, but we've
* had an HRR, so we haven't actually done so yet. In TLSv1.3 we
* must ignore the legacy record version in plaintext records.
*/
} else if (rec->rec_version != rl->version) {
if ((rl->version & 0xFF00) == (rec->rec_version & 0xFF00)) {
if (rec->type == SSL3_RT_ALERT) {
/*
* The record is using an incorrect version number,
* but what we've got appears to be an alert. We
* haven't read the body yet to check whether its a
* fatal or not - but chances are it is. We probably
* shouldn't send a fatal alert back. We'll just
* end.
*/
RLAYERfatal(rl, SSL_AD_NO_ALERT,
SSL_R_WRONG_VERSION_NUMBER);
return 0;
}
/* Send back error using their minor version number */
rl->version = (unsigned short)rec->rec_version;
}
RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
SSL_R_WRONG_VERSION_NUMBER);
return 0;
}
}
if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
/*
* We use SSL_R_DATA_LENGTH_TOO_LONG instead of
* SSL_R_ENCRYPTED_LENGTH_TOO_LONG here because we are the "any" method
* and we know that we are dealing with plaintext data
*/
RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
return 0;
}
return 1;
}
static int tls_any_set_protocol_version(OSSL_RECORD_LAYER *rl, int vers)
{
if (rl->version != TLS_ANY_VERSION && rl->version != vers)
return 0;
rl->version = vers;
return 1;
}
static int tls_any_prepare_for_encryption(OSSL_RECORD_LAYER *rl,
size_t mac_size,
WPACKET *thispkt,
TLS_RL_RECORD *thiswr)
{
/* No encryption, so nothing to do */
return 1;
}
struct record_functions_st tls_any_funcs = {
tls_any_set_crypto_state,
tls_any_cipher,
NULL,
tls_any_set_protocol_version,
tls_default_read_n,
tls_get_more_records,
tls_validate_record_header,
tls_default_post_process_record,
tls_get_max_records_default,
tls_write_records_default,
tls_allocate_write_buffers_default,
tls_initialise_write_packets_default,
NULL,
tls_prepare_record_header_default,
NULL,
tls_any_prepare_for_encryption,
tls_post_encryption_processing_default,
NULL
};
static int dtls_any_set_protocol_version(OSSL_RECORD_LAYER *rl, int vers)
{
if (rl->version != DTLS_ANY_VERSION && rl->version != vers)
return 0;
rl->version = vers;
return 1;
}
struct record_functions_st dtls_any_funcs = {
tls_any_set_crypto_state,
tls_any_cipher,
NULL,
dtls_any_set_protocol_version,
tls_default_read_n,
dtls_get_more_records,
NULL,
NULL,
NULL,
tls_write_records_default,
tls_allocate_write_buffers_default,
tls_initialise_write_packets_default,
NULL,
dtls_prepare_record_header,
NULL,
tls_prepare_for_encryption_default,
dtls_post_encryption_processing,
NULL
};
| 6,917 | 33.939394 | 80 | c |
openssl | openssl-master/ssl/statem/extensions_cust.c | /*
* Copyright 2014-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
*/
/* Custom extension utility functions */
#include <openssl/ct.h>
#include "../ssl_local.h"
#include "internal/cryptlib.h"
#include "statem_local.h"
typedef struct {
void *add_arg;
custom_ext_add_cb add_cb;
custom_ext_free_cb free_cb;
} custom_ext_add_cb_wrap;
typedef struct {
void *parse_arg;
custom_ext_parse_cb parse_cb;
} custom_ext_parse_cb_wrap;
/*
* Provide thin wrapper callbacks which convert new style arguments to old style
*/
static int custom_ext_add_old_cb_wrap(SSL *s, unsigned int ext_type,
unsigned int context,
const unsigned char **out,
size_t *outlen, X509 *x, size_t chainidx,
int *al, void *add_arg)
{
custom_ext_add_cb_wrap *add_cb_wrap = (custom_ext_add_cb_wrap *)add_arg;
if (add_cb_wrap->add_cb == NULL)
return 1;
return add_cb_wrap->add_cb(s, ext_type, out, outlen, al,
add_cb_wrap->add_arg);
}
static void custom_ext_free_old_cb_wrap(SSL *s, unsigned int ext_type,
unsigned int context,
const unsigned char *out, void *add_arg)
{
custom_ext_add_cb_wrap *add_cb_wrap = (custom_ext_add_cb_wrap *)add_arg;
if (add_cb_wrap->free_cb == NULL)
return;
add_cb_wrap->free_cb(s, ext_type, out, add_cb_wrap->add_arg);
}
static int custom_ext_parse_old_cb_wrap(SSL *s, unsigned int ext_type,
unsigned int context,
const unsigned char *in,
size_t inlen, X509 *x, size_t chainidx,
int *al, void *parse_arg)
{
custom_ext_parse_cb_wrap *parse_cb_wrap =
(custom_ext_parse_cb_wrap *)parse_arg;
if (parse_cb_wrap->parse_cb == NULL)
return 1;
return parse_cb_wrap->parse_cb(s, ext_type, in, inlen, al,
parse_cb_wrap->parse_arg);
}
/*
* Find a custom extension from the list. The |role| param is there to
* support the legacy API where custom extensions for client and server could
* be set independently on the same SSL_CTX. It is set to ENDPOINT_SERVER if we
* are trying to find a method relevant to the server, ENDPOINT_CLIENT for the
* client, or ENDPOINT_BOTH for either
*/
custom_ext_method *custom_ext_find(const custom_ext_methods *exts,
ENDPOINT role, unsigned int ext_type,
size_t *idx)
{
size_t i;
custom_ext_method *meth = exts->meths;
for (i = 0; i < exts->meths_count; i++, meth++) {
if (ext_type == meth->ext_type
&& (role == ENDPOINT_BOTH || role == meth->role
|| meth->role == ENDPOINT_BOTH)) {
if (idx != NULL)
*idx = i;
return meth;
}
}
return NULL;
}
/*
* Initialise custom extensions flags to indicate neither sent nor received.
*/
void custom_ext_init(custom_ext_methods *exts)
{
size_t i;
custom_ext_method *meth = exts->meths;
for (i = 0; i < exts->meths_count; i++, meth++)
meth->ext_flags = 0;
}
/* Pass received custom extension data to the application for parsing. */
int custom_ext_parse(SSL_CONNECTION *s, unsigned int context,
unsigned int ext_type,
const unsigned char *ext_data, size_t ext_size, X509 *x,
size_t chainidx)
{
int al;
custom_ext_methods *exts = &s->cert->custext;
custom_ext_method *meth;
ENDPOINT role = ENDPOINT_BOTH;
if ((context & (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_2_SERVER_HELLO)) != 0)
role = s->server ? ENDPOINT_SERVER : ENDPOINT_CLIENT;
meth = custom_ext_find(exts, role, ext_type, NULL);
/* If not found return success */
if (!meth)
return 1;
/* Check if extension is defined for our protocol. If not, skip */
if (!extension_is_relevant(s, meth->context, context))
return 1;
if ((context & (SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_TLS1_3_SERVER_HELLO
| SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS)) != 0) {
/*
* If it's ServerHello or EncryptedExtensions we can't have any
* extensions not sent in ClientHello.
*/
if ((meth->ext_flags & SSL_EXT_FLAG_SENT) == 0) {
SSLfatal(s, TLS1_AD_UNSUPPORTED_EXTENSION, SSL_R_BAD_EXTENSION);
return 0;
}
}
/*
* Extensions received in the ClientHello or CertificateRequest are marked
* with the SSL_EXT_FLAG_RECEIVED. This is so we know to add the equivalent
* extensions in the response messages
*/
if ((context & (SSL_EXT_CLIENT_HELLO | SSL_EXT_TLS1_3_CERTIFICATE_REQUEST))
!= 0)
meth->ext_flags |= SSL_EXT_FLAG_RECEIVED;
/* If no parse function set return success */
if (meth->parse_cb == NULL)
return 1;
if (meth->parse_cb(SSL_CONNECTION_GET_SSL(s), ext_type, context, ext_data,
ext_size, x, chainidx, &al, meth->parse_arg) <= 0) {
SSLfatal(s, al, SSL_R_BAD_EXTENSION);
return 0;
}
return 1;
}
/*
* Request custom extension data from the application and add to the return
* buffer.
*/
int custom_ext_add(SSL_CONNECTION *s, int context, WPACKET *pkt, X509 *x,
size_t chainidx, int maxversion)
{
custom_ext_methods *exts = &s->cert->custext;
custom_ext_method *meth;
size_t i;
int al;
int for_comp = (context & SSL_EXT_TLS1_3_CERTIFICATE_COMPRESSION) != 0;
for (i = 0; i < exts->meths_count; i++) {
const unsigned char *out = NULL;
size_t outlen = 0;
meth = exts->meths + i;
if (!should_add_extension(s, meth->context, context, maxversion))
continue;
if ((context & (SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_TLS1_3_SERVER_HELLO
| SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS
| SSL_EXT_TLS1_3_CERTIFICATE
| SSL_EXT_TLS1_3_RAW_PUBLIC_KEY
| SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST)) != 0) {
/* Only send extensions present in ClientHello/CertificateRequest */
if (!(meth->ext_flags & SSL_EXT_FLAG_RECEIVED))
continue;
}
/*
* We skip it if the callback is absent - except for a ClientHello where
* we add an empty extension.
*/
if ((context & SSL_EXT_CLIENT_HELLO) == 0 && meth->add_cb == NULL)
continue;
if (meth->add_cb != NULL) {
int cb_retval = meth->add_cb(SSL_CONNECTION_GET_SSL(s),
meth->ext_type, context, &out,
&outlen, x, chainidx, &al,
meth->add_arg);
if (cb_retval < 0) {
if (!for_comp)
SSLfatal(s, al, SSL_R_CALLBACK_FAILED);
return 0; /* error */
}
if (cb_retval == 0)
continue; /* skip this extension */
}
if (!WPACKET_put_bytes_u16(pkt, meth->ext_type)
|| !WPACKET_start_sub_packet_u16(pkt)
|| (outlen > 0 && !WPACKET_memcpy(pkt, out, outlen))
|| !WPACKET_close(pkt)) {
if (!for_comp)
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
if ((context & SSL_EXT_CLIENT_HELLO) != 0) {
/*
* We can't send duplicates: code logic should prevent this.
*/
if (!ossl_assert((meth->ext_flags & SSL_EXT_FLAG_SENT) == 0)) {
if (!for_comp)
SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
return 0;
}
/*
* Indicate extension has been sent: this is both a sanity check to
* ensure we don't send duplicate extensions and indicates that it
* is not an error if the extension is present in ServerHello.
*/
meth->ext_flags |= SSL_EXT_FLAG_SENT;
}
if (meth->free_cb != NULL)
meth->free_cb(SSL_CONNECTION_GET_SSL(s), meth->ext_type, context,
out, meth->add_arg);
}
return 1;
}
/* Copy the flags from src to dst for any extensions that exist in both */
int custom_exts_copy_flags(custom_ext_methods *dst,
const custom_ext_methods *src)
{
size_t i;
custom_ext_method *methsrc = src->meths;
for (i = 0; i < src->meths_count; i++, methsrc++) {
custom_ext_method *methdst = custom_ext_find(dst, methsrc->role,
methsrc->ext_type, NULL);
if (methdst == NULL)
continue;
methdst->ext_flags = methsrc->ext_flags;
}
return 1;
}
/* Copy table of custom extensions */
int custom_exts_copy(custom_ext_methods *dst, const custom_ext_methods *src)
{
size_t i;
int err = 0;
if (src->meths_count > 0) {
dst->meths =
OPENSSL_memdup(src->meths,
sizeof(*src->meths) * src->meths_count);
if (dst->meths == NULL)
return 0;
dst->meths_count = src->meths_count;
for (i = 0; i < src->meths_count; i++) {
custom_ext_method *methsrc = src->meths + i;
custom_ext_method *methdst = dst->meths + i;
if (methsrc->add_cb != custom_ext_add_old_cb_wrap)
continue;
/*
* We have found an old style API wrapper. We need to copy the
* arguments too.
*/
if (err) {
methdst->add_arg = NULL;
methdst->parse_arg = NULL;
continue;
}
methdst->add_arg = OPENSSL_memdup(methsrc->add_arg,
sizeof(custom_ext_add_cb_wrap));
methdst->parse_arg = OPENSSL_memdup(methsrc->parse_arg,
sizeof(custom_ext_parse_cb_wrap));
if (methdst->add_arg == NULL || methdst->parse_arg == NULL)
err = 1;
}
}
if (err) {
custom_exts_free(dst);
return 0;
}
return 1;
}
void custom_exts_free(custom_ext_methods *exts)
{
size_t i;
custom_ext_method *meth;
for (i = 0, meth = exts->meths; i < exts->meths_count; i++, meth++) {
if (meth->add_cb != custom_ext_add_old_cb_wrap)
continue;
/* Old style API wrapper. Need to free the arguments too */
OPENSSL_free(meth->add_arg);
OPENSSL_free(meth->parse_arg);
}
OPENSSL_free(exts->meths);
}
/* Return true if a client custom extension exists, false otherwise */
int SSL_CTX_has_client_custom_ext(const SSL_CTX *ctx, unsigned int ext_type)
{
return custom_ext_find(&ctx->cert->custext, ENDPOINT_CLIENT, ext_type,
NULL) != NULL;
}
int ossl_tls_add_custom_ext_intern(SSL_CTX *ctx, custom_ext_methods *exts,
ENDPOINT role, unsigned int ext_type,
unsigned int context,
SSL_custom_ext_add_cb_ex add_cb,
SSL_custom_ext_free_cb_ex free_cb,
void *add_arg,
SSL_custom_ext_parse_cb_ex parse_cb,
void *parse_arg)
{
custom_ext_method *meth, *tmp;
/*
* Check application error: if add_cb is not set free_cb will never be
* called.
*/
if (add_cb == NULL && free_cb != NULL)
return 0;
if (exts == NULL)
exts = &ctx->cert->custext;
#ifndef OPENSSL_NO_CT
/*
* We don't want applications registering callbacks for SCT extensions
* whilst simultaneously using the built-in SCT validation features, as
* these two things may not play well together.
*/
if (ext_type == TLSEXT_TYPE_signed_certificate_timestamp
&& (context & SSL_EXT_CLIENT_HELLO) != 0
&& ctx != NULL
&& SSL_CTX_ct_is_enabled(ctx))
return 0;
#endif
/*
* Don't add if extension supported internally, but make exception
* for extension types that previously were not supported, but now are.
*/
if (SSL_extension_supported(ext_type)
&& ext_type != TLSEXT_TYPE_signed_certificate_timestamp)
return 0;
/* Extension type must fit in 16 bits */
if (ext_type > 0xffff)
return 0;
/* Search for duplicate */
if (custom_ext_find(exts, role, ext_type, NULL))
return 0;
tmp = OPENSSL_realloc(exts->meths,
(exts->meths_count + 1) * sizeof(custom_ext_method));
if (tmp == NULL)
return 0;
exts->meths = tmp;
meth = exts->meths + exts->meths_count;
memset(meth, 0, sizeof(*meth));
meth->role = role;
meth->context = context;
meth->parse_cb = parse_cb;
meth->add_cb = add_cb;
meth->free_cb = free_cb;
meth->ext_type = ext_type;
meth->add_arg = add_arg;
meth->parse_arg = parse_arg;
exts->meths_count++;
return 1;
}
static int add_old_custom_ext(SSL_CTX *ctx, ENDPOINT role,
unsigned int ext_type,
unsigned int context,
custom_ext_add_cb add_cb,
custom_ext_free_cb free_cb,
void *add_arg,
custom_ext_parse_cb parse_cb, void *parse_arg)
{
custom_ext_add_cb_wrap *add_cb_wrap
= OPENSSL_malloc(sizeof(*add_cb_wrap));
custom_ext_parse_cb_wrap *parse_cb_wrap
= OPENSSL_malloc(sizeof(*parse_cb_wrap));
int ret;
if (add_cb_wrap == NULL || parse_cb_wrap == NULL) {
OPENSSL_free(add_cb_wrap);
OPENSSL_free(parse_cb_wrap);
return 0;
}
add_cb_wrap->add_arg = add_arg;
add_cb_wrap->add_cb = add_cb;
add_cb_wrap->free_cb = free_cb;
parse_cb_wrap->parse_arg = parse_arg;
parse_cb_wrap->parse_cb = parse_cb;
ret = ossl_tls_add_custom_ext_intern(ctx, NULL, role, ext_type,
context,
custom_ext_add_old_cb_wrap,
custom_ext_free_old_cb_wrap,
add_cb_wrap,
custom_ext_parse_old_cb_wrap,
parse_cb_wrap);
if (!ret) {
OPENSSL_free(add_cb_wrap);
OPENSSL_free(parse_cb_wrap);
}
return ret;
}
/* Application level functions to add the old custom extension callbacks */
int SSL_CTX_add_client_custom_ext(SSL_CTX *ctx, unsigned int ext_type,
custom_ext_add_cb add_cb,
custom_ext_free_cb free_cb,
void *add_arg,
custom_ext_parse_cb parse_cb, void *parse_arg)
{
return add_old_custom_ext(ctx, ENDPOINT_CLIENT, ext_type,
SSL_EXT_TLS1_2_AND_BELOW_ONLY
| SSL_EXT_CLIENT_HELLO
| SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_IGNORE_ON_RESUMPTION,
add_cb, free_cb, add_arg, parse_cb, parse_arg);
}
int SSL_CTX_add_server_custom_ext(SSL_CTX *ctx, unsigned int ext_type,
custom_ext_add_cb add_cb,
custom_ext_free_cb free_cb,
void *add_arg,
custom_ext_parse_cb parse_cb, void *parse_arg)
{
return add_old_custom_ext(ctx, ENDPOINT_SERVER, ext_type,
SSL_EXT_TLS1_2_AND_BELOW_ONLY
| SSL_EXT_CLIENT_HELLO
| SSL_EXT_TLS1_2_SERVER_HELLO
| SSL_EXT_IGNORE_ON_RESUMPTION,
add_cb, free_cb, add_arg, parse_cb, parse_arg);
}
int SSL_CTX_add_custom_ext(SSL_CTX *ctx, unsigned int ext_type,
unsigned int context,
SSL_custom_ext_add_cb_ex add_cb,
SSL_custom_ext_free_cb_ex free_cb,
void *add_arg,
SSL_custom_ext_parse_cb_ex parse_cb, void *parse_arg)
{
return ossl_tls_add_custom_ext_intern(ctx, NULL, ENDPOINT_BOTH, ext_type,
context, add_cb, free_cb, add_arg,
parse_cb, parse_arg);
}
int SSL_extension_supported(unsigned int ext_type)
{
switch (ext_type) {
/* Internally supported extensions. */
case TLSEXT_TYPE_application_layer_protocol_negotiation:
case TLSEXT_TYPE_ec_point_formats:
case TLSEXT_TYPE_supported_groups:
case TLSEXT_TYPE_key_share:
#ifndef OPENSSL_NO_NEXTPROTONEG
case TLSEXT_TYPE_next_proto_neg:
#endif
case TLSEXT_TYPE_padding:
case TLSEXT_TYPE_renegotiate:
case TLSEXT_TYPE_max_fragment_length:
case TLSEXT_TYPE_server_name:
case TLSEXT_TYPE_session_ticket:
case TLSEXT_TYPE_signature_algorithms:
#ifndef OPENSSL_NO_SRP
case TLSEXT_TYPE_srp:
#endif
#ifndef OPENSSL_NO_OCSP
case TLSEXT_TYPE_status_request:
#endif
#ifndef OPENSSL_NO_CT
case TLSEXT_TYPE_signed_certificate_timestamp:
#endif
#ifndef OPENSSL_NO_SRTP
case TLSEXT_TYPE_use_srtp:
#endif
case TLSEXT_TYPE_encrypt_then_mac:
case TLSEXT_TYPE_supported_versions:
case TLSEXT_TYPE_extended_master_secret:
case TLSEXT_TYPE_psk_kex_modes:
case TLSEXT_TYPE_cookie:
case TLSEXT_TYPE_early_data:
case TLSEXT_TYPE_certificate_authorities:
case TLSEXT_TYPE_psk:
case TLSEXT_TYPE_post_handshake_auth:
case TLSEXT_TYPE_compress_certificate:
case TLSEXT_TYPE_client_cert_type:
case TLSEXT_TYPE_server_cert_type:
return 1;
default:
return 0;
}
}
| 18,825 | 33.543119 | 80 | c |
openssl | openssl-master/test/aesgcmtest.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 <openssl/evp.h>
#include "testutil.h"
static const unsigned char gcm_key[] = {
0xee, 0xbc, 0x1f, 0x57, 0x48, 0x7f, 0x51, 0x92, 0x1c, 0x04, 0x65, 0x66,
0x5f, 0x8a, 0xe6, 0xd1, 0x65, 0x8b, 0xb2, 0x6d, 0xe6, 0xf8, 0xa0, 0x69,
0xa3, 0x52, 0x02, 0x93, 0xa5, 0x72, 0x07, 0x8f
};
static const unsigned char gcm_iv[] = {
0x99, 0xaa, 0x3e, 0x68, 0xed, 0x81, 0x73, 0xa0, 0xee, 0xd0, 0x66, 0x84
};
static const unsigned char gcm_pt[] = {
0xf5, 0x6e, 0x87, 0x05, 0x5b, 0xc3, 0x2d, 0x0e, 0xeb, 0x31, 0xb2, 0xea,
0xcc, 0x2b, 0xf2, 0xa5
};
static const unsigned char gcm_aad[] = {
0x4d, 0x23, 0xc3, 0xce, 0xc3, 0x34, 0xb4, 0x9b, 0xdb, 0x37, 0x0c, 0x43,
0x7f, 0xec, 0x78, 0xde
};
static const unsigned char gcm_ct[] = {
0xf7, 0x26, 0x44, 0x13, 0xa8, 0x4c, 0x0e, 0x7c, 0xd5, 0x36, 0x86, 0x7e,
0xb9, 0xf2, 0x17, 0x36
};
static const unsigned char gcm_tag[] = {
0x67, 0xba, 0x05, 0x10, 0x26, 0x2a, 0xe4, 0x87, 0xd7, 0x37, 0xee, 0x62,
0x98, 0xf7, 0x7e, 0x0c
};
static int do_encrypt(unsigned char *iv_gen, unsigned char *ct, int *ct_len,
unsigned char *tag, int *tag_len)
{
int ret = 0;
EVP_CIPHER_CTX *ctx = NULL;
int outlen;
unsigned char outbuf[64];
*tag_len = 16;
ret = TEST_ptr(ctx = EVP_CIPHER_CTX_new())
&& TEST_true(EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL,
NULL) > 0)
&& TEST_true(EVP_EncryptInit_ex(ctx, NULL, NULL, gcm_key,
iv_gen != NULL ? NULL : gcm_iv) > 0)
&& TEST_true(EVP_EncryptUpdate(ctx, NULL, &outlen, gcm_aad,
sizeof(gcm_aad)) > 0)
&& TEST_true(EVP_EncryptUpdate(ctx, ct, ct_len, gcm_pt,
sizeof(gcm_pt)) > 0)
&& TEST_true(EVP_EncryptFinal_ex(ctx, outbuf, &outlen) > 0)
&& TEST_int_eq(EVP_CIPHER_CTX_get_tag_length(ctx), 16)
&& TEST_true(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, 16,
tag) > 0)
&& TEST_true(iv_gen == NULL
|| EVP_CIPHER_CTX_get_original_iv(ctx, iv_gen, 12));
EVP_CIPHER_CTX_free(ctx);
return ret;
}
static int do_decrypt(const unsigned char *iv, const unsigned char *ct,
int ct_len, const unsigned char *tag, int tag_len)
{
int ret = 0;
EVP_CIPHER_CTX *ctx = NULL;
int outlen, ptlen;
unsigned char pt[32];
unsigned char outbuf[32];
ret = TEST_ptr(ctx = EVP_CIPHER_CTX_new())
&& TEST_true(EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL,
NULL, NULL) > 0)
&& TEST_true(EVP_DecryptInit_ex(ctx, NULL, NULL, gcm_key, iv) > 0)
&& TEST_int_eq(EVP_CIPHER_CTX_get_tag_length(ctx), 16)
&& TEST_true(EVP_DecryptUpdate(ctx, NULL, &outlen, gcm_aad,
sizeof(gcm_aad)) > 0)
&& TEST_true(EVP_DecryptUpdate(ctx, pt, &ptlen, ct,
ct_len) > 0)
&& TEST_true(EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
tag_len, (void *)tag) > 0)
&& TEST_true(EVP_DecryptFinal_ex(ctx, outbuf, &outlen) > 0)
&& TEST_mem_eq(gcm_pt, sizeof(gcm_pt), pt, ptlen);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
static int kat_test(void)
{
unsigned char tag[32];
unsigned char ct[32];
int ctlen = 0, taglen = 0;
return do_encrypt(NULL, ct, &ctlen, tag, &taglen)
&& TEST_mem_eq(gcm_ct, sizeof(gcm_ct), ct, ctlen)
&& TEST_mem_eq(gcm_tag, sizeof(gcm_tag), tag, taglen)
&& do_decrypt(gcm_iv, ct, ctlen, tag, taglen);
}
static int badkeylen_test(void)
{
int ret;
EVP_CIPHER_CTX *ctx = NULL;
const EVP_CIPHER *cipher;
ret = TEST_ptr(cipher = EVP_aes_192_gcm())
&& TEST_ptr(ctx = EVP_CIPHER_CTX_new())
&& TEST_true(EVP_EncryptInit_ex(ctx, cipher, NULL, NULL, NULL))
&& TEST_int_le(EVP_CIPHER_CTX_set_key_length(ctx, 2), 0);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
static int ivgen_test(void)
{
unsigned char iv_gen[16];
unsigned char tag[32];
unsigned char ct[32];
int ctlen = 0, taglen = 0;
return do_encrypt(iv_gen, ct, &ctlen, tag, &taglen)
&& do_decrypt(iv_gen, ct, ctlen, tag, taglen);
}
int setup_tests(void)
{
ADD_TEST(kat_test);
ADD_TEST(badkeylen_test);
ADD_TEST(ivgen_test);
return 1;
}
| 4,943 | 35.087591 | 80 | c |
openssl | openssl-master/test/afalgtest.c | /*
* Copyright 2016-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 <openssl/opensslconf.h>
#include <string.h>
#include <openssl/engine.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include "testutil.h"
/* Use a buffer size which is not aligned to block size */
#define BUFFER_SIZE 17
#ifndef OPENSSL_NO_ENGINE
static ENGINE *e;
static int test_afalg_aes_cbc(int keysize_idx)
{
EVP_CIPHER_CTX *ctx;
const EVP_CIPHER *cipher;
unsigned char ebuf[BUFFER_SIZE + 32];
unsigned char dbuf[BUFFER_SIZE + 32];
const unsigned char *enc_result = NULL;
int encl, encf, decl, decf;
int ret = 0;
static const unsigned char key[] =
"\x06\xa9\x21\x40\x36\xb8\xa1\x5b\x51\x2e\x03\xd5\x34\x12\x00\x06"
"\x06\xa9\x21\x40\x36\xb8\xa1\x5b\x51\x2e\x03\xd5\x34\x12\x00\x06";
static const unsigned char iv[] =
"\x3d\xaf\xba\x42\x9d\x9e\xb4\x30\xb4\x22\xda\x80\x2c\x9f\xac\x41";
/* input = "Single block msg\n" 17 Bytes*/
static const unsigned char in[BUFFER_SIZE] =
"\x53\x69\x6e\x67\x6c\x65\x20\x62\x6c\x6f\x63\x6b\x20\x6d\x73\x67"
"\x0a";
static const unsigned char encresult_128[BUFFER_SIZE] =
"\xe3\x53\x77\x9c\x10\x79\xae\xb8\x27\x08\x94\x2d\xbe\x77\x18\x1a"
"\x2d";
static const unsigned char encresult_192[BUFFER_SIZE] =
"\xf7\xe4\x26\xd1\xd5\x4f\x8f\x39\xb1\x9e\xe0\xdf\x61\xb9\xc2\x55"
"\xeb";
static const unsigned char encresult_256[BUFFER_SIZE] =
"\xa0\x76\x85\xfd\xc1\x65\x71\x9d\xc7\xe9\x13\x6e\xae\x55\x49\xb4"
"\x13";
#ifdef OSSL_SANITIZE_MEMORY
/*
* Initialise the encryption & decryption buffers to pacify the memory
* sanitiser. The sanitiser doesn't know that this memory is modified
* by the engine, this tells it that all is good.
*/
OPENSSL_cleanse(ebuf, sizeof(ebuf));
OPENSSL_cleanse(dbuf, sizeof(dbuf));
#endif
switch (keysize_idx) {
case 0:
cipher = EVP_aes_128_cbc();
enc_result = &encresult_128[0];
break;
case 1:
cipher = EVP_aes_192_cbc();
enc_result = &encresult_192[0];
break;
case 2:
cipher = EVP_aes_256_cbc();
enc_result = &encresult_256[0];
break;
default:
cipher = NULL;
}
if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new()))
return 0;
if (!TEST_true(EVP_CipherInit_ex(ctx, cipher, e, key, iv, 1))
|| !TEST_true(EVP_CipherUpdate(ctx, ebuf, &encl, in, BUFFER_SIZE))
|| !TEST_true(EVP_CipherFinal_ex(ctx, ebuf + encl, &encf)))
goto end;
encl += encf;
if (!TEST_mem_eq(enc_result, BUFFER_SIZE, ebuf, BUFFER_SIZE))
goto end;
if (!TEST_true(EVP_CIPHER_CTX_reset(ctx))
|| !TEST_true(EVP_CipherInit_ex(ctx, cipher, e, key, iv, 0))
|| !TEST_true(EVP_CipherUpdate(ctx, dbuf, &decl, ebuf, encl))
|| !TEST_true(EVP_CipherFinal_ex(ctx, dbuf + decl, &decf)))
goto end;
decl += decf;
if (!TEST_int_eq(decl, BUFFER_SIZE)
|| !TEST_mem_eq(dbuf, BUFFER_SIZE, in, BUFFER_SIZE))
goto end;
ret = 1;
end:
EVP_CIPHER_CTX_free(ctx);
return ret;
}
static int test_pr16743(void)
{
int ret = 0;
const EVP_CIPHER * cipher;
EVP_CIPHER_CTX *ctx;
if (!TEST_true(ENGINE_init(e)))
return 0;
cipher = ENGINE_get_cipher(e, NID_aes_128_cbc);
ctx = EVP_CIPHER_CTX_new();
if (cipher != NULL && ctx != NULL)
ret = EVP_EncryptInit_ex(ctx, cipher, e, NULL, NULL);
TEST_true(ret);
EVP_CIPHER_CTX_free(ctx);
ENGINE_finish(e);
return ret;
}
int global_init(void)
{
ENGINE_load_builtin_engines();
# ifndef OPENSSL_NO_STATIC_ENGINE
OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_AFALG, NULL);
# endif
return 1;
}
#endif
int setup_tests(void)
{
#ifndef OPENSSL_NO_ENGINE
if ((e = ENGINE_by_id("afalg")) == NULL) {
/* Probably a platform env issue, not a test failure. */
TEST_info("Can't load AFALG engine");
} else {
ADD_ALL_TESTS(test_afalg_aes_cbc, 3);
ADD_TEST(test_pr16743);
}
#endif
return 1;
}
#ifndef OPENSSL_NO_ENGINE
void cleanup_tests(void)
{
ENGINE_free(e);
}
#endif
| 4,662 | 27.962733 | 78 | c |
openssl | openssl-master/test/algorithmid_test.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/asn1.h>
#include <openssl/pem.h>
#include "internal/sizes.h"
#include "crypto/evp.h"
#include "testutil.h"
/* Collected arguments */
static const char *eecert_filename = NULL; /* For test_x509_file() */
static const char *cacert_filename = NULL; /* For test_x509_file() */
static const char *pubkey_filename = NULL; /* For test_spki_file() */
#define ALGORITHMID_NAME "algorithm-id"
static int test_spki_aid(X509_PUBKEY *pubkey, const char *filename)
{
const ASN1_OBJECT *oid;
X509_ALGOR *alg = NULL;
EVP_PKEY *pkey = NULL;
EVP_KEYMGMT *keymgmt = NULL;
void *keydata = NULL;
char name[OSSL_MAX_NAME_SIZE] = "";
unsigned char *algid_legacy = NULL;
int algid_legacy_len = 0;
static unsigned char algid_prov[OSSL_MAX_ALGORITHM_ID_SIZE];
size_t algid_prov_len = 0;
const OSSL_PARAM *gettable_params = NULL;
OSSL_PARAM params[] = {
OSSL_PARAM_octet_string(ALGORITHMID_NAME,
&algid_prov, sizeof(algid_prov)),
OSSL_PARAM_END
};
int ret = 0;
if (!TEST_true(X509_PUBKEY_get0_param(NULL, NULL, NULL, &alg, pubkey))
|| !TEST_ptr(pkey = X509_PUBKEY_get0(pubkey)))
goto end;
if (!TEST_int_ge(algid_legacy_len = i2d_X509_ALGOR(alg, &algid_legacy), 0))
goto end;
X509_ALGOR_get0(&oid, NULL, NULL, alg);
if (!TEST_int_gt(OBJ_obj2txt(name, sizeof(name), oid, 0), 0))
goto end;
/*
* We use an internal functions to ensure we have a provided key.
* Note that |keydata| should not be freed, as it's cached in |pkey|.
* The |keymgmt|, however, should, as its reference count is incremented
* in this function.
*/
if ((keydata = evp_pkey_export_to_provider(pkey, NULL,
&keymgmt, NULL)) == NULL) {
TEST_info("The public key found in '%s' doesn't have provider support."
" Skipping...",
filename);
ret = 1;
goto end;
}
if (!TEST_true(EVP_KEYMGMT_is_a(keymgmt, name))) {
TEST_info("The AlgorithmID key type (%s) for the public key found in"
" '%s' doesn't match the key type of the extracted public"
" key.",
name, filename);
ret = 1;
goto end;
}
if (!TEST_ptr(gettable_params = EVP_KEYMGMT_gettable_params(keymgmt))
|| !TEST_ptr(OSSL_PARAM_locate_const(gettable_params, ALGORITHMID_NAME))) {
TEST_info("The %s provider keymgmt appears to lack support for algorithm-id."
" Skipping...",
name);
ret = 1;
goto end;
}
algid_prov[0] = '\0';
if (!TEST_true(evp_keymgmt_get_params(keymgmt, keydata, params)))
goto end;
algid_prov_len = params[0].return_size;
/* We now have all the algorithm IDs we need, let's compare them */
if (TEST_mem_eq(algid_legacy, algid_legacy_len,
algid_prov, algid_prov_len))
ret = 1;
end:
EVP_KEYMGMT_free(keymgmt);
OPENSSL_free(algid_legacy);
return ret;
}
static int test_x509_spki_aid(X509 *cert, const char *filename)
{
X509_PUBKEY *pubkey = X509_get_X509_PUBKEY(cert);
return test_spki_aid(pubkey, filename);
}
static int test_x509_sig_aid(X509 *eecert, const char *ee_filename,
X509 *cacert, const char *ca_filename)
{
const ASN1_OBJECT *sig_oid = NULL;
const X509_ALGOR *alg = NULL;
int sig_nid = NID_undef, dig_nid = NID_undef, pkey_nid = NID_undef;
EVP_MD_CTX *mdctx = NULL;
EVP_PKEY_CTX *pctx = NULL;
EVP_PKEY *pkey = NULL;
unsigned char *algid_legacy = NULL;
int algid_legacy_len = 0;
static unsigned char algid_prov[OSSL_MAX_ALGORITHM_ID_SIZE];
size_t algid_prov_len = 0;
const OSSL_PARAM *gettable_params = NULL;
OSSL_PARAM params[] = {
OSSL_PARAM_octet_string("algorithm-id",
&algid_prov, sizeof(algid_prov)),
OSSL_PARAM_END
};
int ret = 0;
X509_get0_signature(NULL, &alg, eecert);
X509_ALGOR_get0(&sig_oid, NULL, NULL, alg);
if (!TEST_int_eq(X509_ALGOR_cmp(alg, X509_get0_tbs_sigalg(eecert)), 0))
goto end;
if (!TEST_int_ne(sig_nid = OBJ_obj2nid(sig_oid), NID_undef)
|| !TEST_true(OBJ_find_sigid_algs(sig_nid, &dig_nid, &pkey_nid))
|| !TEST_ptr(pkey = X509_get0_pubkey(cacert)))
goto end;
if (!TEST_true(EVP_PKEY_is_a(pkey, OBJ_nid2sn(pkey_nid)))) {
TEST_info("The '%s' pubkey can't be used to verify the '%s' signature",
ca_filename, ee_filename);
TEST_info("Signature algorithm is %s (pkey type %s, hash type %s)",
OBJ_nid2sn(sig_nid), OBJ_nid2sn(pkey_nid), OBJ_nid2sn(dig_nid));
TEST_info("Pkey key type is %s", EVP_PKEY_get0_type_name(pkey));
goto end;
}
if (!TEST_int_ge(algid_legacy_len = i2d_X509_ALGOR(alg, &algid_legacy), 0))
goto end;
if (!TEST_ptr(mdctx = EVP_MD_CTX_new())
|| !TEST_true(EVP_DigestVerifyInit_ex(mdctx, &pctx,
OBJ_nid2sn(dig_nid),
NULL, NULL, pkey, NULL))) {
TEST_info("Couldn't initialize a DigestVerify operation with "
"pkey type %s and hash type %s",
OBJ_nid2sn(pkey_nid), OBJ_nid2sn(dig_nid));
goto end;
}
if (!TEST_ptr(gettable_params = EVP_PKEY_CTX_gettable_params(pctx))
|| !TEST_ptr(OSSL_PARAM_locate_const(gettable_params, ALGORITHMID_NAME))) {
TEST_info("The %s provider keymgmt appears to lack support for algorithm-id"
" Skipping...",
OBJ_nid2sn(pkey_nid));
ret = 1;
goto end;
}
algid_prov[0] = '\0';
if (!TEST_true(EVP_PKEY_CTX_get_params(pctx, params)))
goto end;
algid_prov_len = params[0].return_size;
/* We now have all the algorithm IDs we need, let's compare them */
if (TEST_mem_eq(algid_legacy, algid_legacy_len,
algid_prov, algid_prov_len))
ret = 1;
end:
EVP_MD_CTX_free(mdctx);
/* pctx is free by EVP_MD_CTX_free() */
OPENSSL_free(algid_legacy);
return ret;
}
static int test_spki_file(void)
{
X509_PUBKEY *pubkey = NULL;
BIO *b = BIO_new_file(pubkey_filename, "r");
int ret = 0;
if (b == NULL) {
TEST_error("Couldn't open '%s' for reading\n", pubkey_filename);
TEST_openssl_errors();
goto end;
}
if ((pubkey = PEM_read_bio_X509_PUBKEY(b, NULL, NULL, NULL)) == NULL) {
TEST_error("'%s' doesn't appear to be a SubjectPublicKeyInfo in PEM format\n",
pubkey_filename);
TEST_openssl_errors();
goto end;
}
ret = test_spki_aid(pubkey, pubkey_filename);
end:
BIO_free(b);
X509_PUBKEY_free(pubkey);
return ret;
}
static int test_x509_files(void)
{
X509 *eecert = NULL, *cacert = NULL;
BIO *bee = NULL, *bca = NULL;
int ret = 0;
if ((bee = BIO_new_file(eecert_filename, "r")) == NULL) {
TEST_error("Couldn't open '%s' for reading\n", eecert_filename);
TEST_openssl_errors();
goto end;
}
if ((bca = BIO_new_file(cacert_filename, "r")) == NULL) {
TEST_error("Couldn't open '%s' for reading\n", cacert_filename);
TEST_openssl_errors();
goto end;
}
if ((eecert = PEM_read_bio_X509(bee, NULL, NULL, NULL)) == NULL) {
TEST_error("'%s' doesn't appear to be a X.509 certificate in PEM format\n",
eecert_filename);
TEST_openssl_errors();
goto end;
}
if ((cacert = PEM_read_bio_X509(bca, NULL, NULL, NULL)) == NULL) {
TEST_error("'%s' doesn't appear to be a X.509 certificate in PEM format\n",
cacert_filename);
TEST_openssl_errors();
goto end;
}
ret = test_x509_sig_aid(eecert, eecert_filename, cacert, cacert_filename)
& test_x509_spki_aid(eecert, eecert_filename)
& test_x509_spki_aid(cacert, cacert_filename);
end:
BIO_free(bee);
BIO_free(bca);
X509_free(eecert);
X509_free(cacert);
return ret;
}
typedef enum OPTION_choice {
OPT_ERR = -1,
OPT_EOF = 0,
OPT_X509,
OPT_SPKI,
OPT_TEST_ENUM
} OPTION_CHOICE;
const OPTIONS *test_get_options(void)
{
static const OPTIONS test_options[] = {
OPT_TEST_OPTIONS_WITH_EXTRA_USAGE("file...\n"),
{ "x509", OPT_X509, '-', "Test X.509 certificates. Requires two files" },
{ "spki", OPT_SPKI, '-', "Test public keys in SubjectPublicKeyInfo form. Requires one file" },
{ OPT_HELP_STR, 1, '-',
"file...\tFile(s) to run tests on. All files must be PEM encoded.\n" },
{ NULL }
};
return test_options;
}
int setup_tests(void)
{
OPTION_CHOICE o;
int n, x509 = 0, spki = 0, testcount = 0;
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_X509:
x509 = 1;
break;
case OPT_SPKI:
spki = 1;
break;
case OPT_TEST_CASES:
break;
default:
case OPT_ERR:
return 0;
}
}
/* |testcount| adds all the given test types together */
testcount = x509 + spki;
if (testcount < 1)
BIO_printf(bio_err, "No test type given\n");
else if (testcount > 1)
BIO_printf(bio_err, "Only one test type may be given\n");
if (testcount != 1)
return 0;
n = test_get_argument_count();
if (spki && n == 1) {
pubkey_filename = test_get_argument(0);
} else if (x509 && n == 2) {
eecert_filename = test_get_argument(0);
cacert_filename = test_get_argument(1);
}
if (spki && pubkey_filename == NULL) {
BIO_printf(bio_err, "Missing -spki argument\n");
return 0;
} else if (x509 && (eecert_filename == NULL || cacert_filename == NULL)) {
BIO_printf(bio_err, "Missing -x509 argument(s)\n");
return 0;
}
if (x509)
ADD_TEST(test_x509_files);
if (spki)
ADD_TEST(test_spki_file);
return 1;
}
| 10,552 | 31.075988 | 103 | c |
openssl | openssl-master/test/asn1_decode_test.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 <string.h>
#include <openssl/rand.h>
#include <openssl/asn1t.h>
#include <openssl/obj_mac.h>
#include "internal/numbers.h"
#include "testutil.h"
#ifdef __GNUC__
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#ifdef __clang__
# pragma clang diagnostic ignored "-Wunused-function"
#endif
/* Badly coded ASN.1 INTEGER zero wrapped in a sequence */
static unsigned char t_invalid_zero[] = {
0x30, 0x02, /* SEQUENCE tag + length */
0x02, 0x00 /* INTEGER tag + length */
};
#ifndef OPENSSL_NO_DEPRECATED_3_0
/* LONG case ************************************************************* */
typedef struct {
long test_long;
} ASN1_LONG_DATA;
ASN1_SEQUENCE(ASN1_LONG_DATA) = {
ASN1_EMBED(ASN1_LONG_DATA, test_long, LONG),
} static_ASN1_SEQUENCE_END(ASN1_LONG_DATA)
IMPLEMENT_STATIC_ASN1_ENCODE_FUNCTIONS(ASN1_LONG_DATA)
IMPLEMENT_STATIC_ASN1_ALLOC_FUNCTIONS(ASN1_LONG_DATA)
static int test_long(void)
{
const unsigned char *p = t_invalid_zero;
ASN1_LONG_DATA *dectst =
d2i_ASN1_LONG_DATA(NULL, &p, sizeof(t_invalid_zero));
if (dectst == NULL)
return 0; /* Fail */
ASN1_LONG_DATA_free(dectst);
return 1;
}
#endif
/* INT32 case ************************************************************* */
typedef struct {
int32_t test_int32;
} ASN1_INT32_DATA;
ASN1_SEQUENCE(ASN1_INT32_DATA) = {
ASN1_EMBED(ASN1_INT32_DATA, test_int32, INT32),
} static_ASN1_SEQUENCE_END(ASN1_INT32_DATA)
IMPLEMENT_STATIC_ASN1_ENCODE_FUNCTIONS(ASN1_INT32_DATA)
IMPLEMENT_STATIC_ASN1_ALLOC_FUNCTIONS(ASN1_INT32_DATA)
static int test_int32(void)
{
const unsigned char *p = t_invalid_zero;
ASN1_INT32_DATA *dectst =
d2i_ASN1_INT32_DATA(NULL, &p, sizeof(t_invalid_zero));
if (dectst == NULL)
return 0; /* Fail */
ASN1_INT32_DATA_free(dectst);
return 1;
}
/* UINT32 case ************************************************************* */
typedef struct {
uint32_t test_uint32;
} ASN1_UINT32_DATA;
ASN1_SEQUENCE(ASN1_UINT32_DATA) = {
ASN1_EMBED(ASN1_UINT32_DATA, test_uint32, UINT32),
} static_ASN1_SEQUENCE_END(ASN1_UINT32_DATA)
IMPLEMENT_STATIC_ASN1_ENCODE_FUNCTIONS(ASN1_UINT32_DATA)
IMPLEMENT_STATIC_ASN1_ALLOC_FUNCTIONS(ASN1_UINT32_DATA)
static int test_uint32(void)
{
const unsigned char *p = t_invalid_zero;
ASN1_UINT32_DATA *dectst =
d2i_ASN1_UINT32_DATA(NULL, &p, sizeof(t_invalid_zero));
if (dectst == NULL)
return 0; /* Fail */
ASN1_UINT32_DATA_free(dectst);
return 1;
}
/* INT64 case ************************************************************* */
typedef struct {
int64_t test_int64;
} ASN1_INT64_DATA;
ASN1_SEQUENCE(ASN1_INT64_DATA) = {
ASN1_EMBED(ASN1_INT64_DATA, test_int64, INT64),
} static_ASN1_SEQUENCE_END(ASN1_INT64_DATA)
IMPLEMENT_STATIC_ASN1_ENCODE_FUNCTIONS(ASN1_INT64_DATA)
IMPLEMENT_STATIC_ASN1_ALLOC_FUNCTIONS(ASN1_INT64_DATA)
static int test_int64(void)
{
const unsigned char *p = t_invalid_zero;
ASN1_INT64_DATA *dectst =
d2i_ASN1_INT64_DATA(NULL, &p, sizeof(t_invalid_zero));
if (dectst == NULL)
return 0; /* Fail */
ASN1_INT64_DATA_free(dectst);
return 1;
}
/* UINT64 case ************************************************************* */
typedef struct {
uint64_t test_uint64;
} ASN1_UINT64_DATA;
ASN1_SEQUENCE(ASN1_UINT64_DATA) = {
ASN1_EMBED(ASN1_UINT64_DATA, test_uint64, UINT64),
} static_ASN1_SEQUENCE_END(ASN1_UINT64_DATA)
IMPLEMENT_STATIC_ASN1_ENCODE_FUNCTIONS(ASN1_UINT64_DATA)
IMPLEMENT_STATIC_ASN1_ALLOC_FUNCTIONS(ASN1_UINT64_DATA)
static int test_uint64(void)
{
const unsigned char *p = t_invalid_zero;
ASN1_UINT64_DATA *dectst =
d2i_ASN1_UINT64_DATA(NULL, &p, sizeof(t_invalid_zero));
if (dectst == NULL)
return 0; /* Fail */
ASN1_UINT64_DATA_free(dectst);
return 1;
}
typedef struct {
ASN1_STRING *invalidDirString;
} INVALIDTEMPLATE;
ASN1_SEQUENCE(INVALIDTEMPLATE) = {
/*
* DirectoryString is a CHOICE type so it must use explicit tagging -
* but we deliberately use implicit here, which makes this template invalid.
*/
ASN1_IMP(INVALIDTEMPLATE, invalidDirString, DIRECTORYSTRING, 12)
} static_ASN1_SEQUENCE_END(INVALIDTEMPLATE)
IMPLEMENT_STATIC_ASN1_ENCODE_FUNCTIONS(INVALIDTEMPLATE)
IMPLEMENT_STATIC_ASN1_ALLOC_FUNCTIONS(INVALIDTEMPLATE)
/* Empty sequence for invalid template test */
static unsigned char t_invalid_template[] = {
0x30, 0x03, /* SEQUENCE tag + length */
0x0c, 0x01, 0x41 /* UTF8String, length 1, "A" */
};
static int test_invalid_template(void)
{
const unsigned char *p = t_invalid_template;
INVALIDTEMPLATE *tmp = d2i_INVALIDTEMPLATE(NULL, &p,
sizeof(t_invalid_template));
/* We expect a NULL pointer return */
if (TEST_ptr_null(tmp))
return 1;
INVALIDTEMPLATE_free(tmp);
return 0;
}
static int test_reuse_asn1_object(void)
{
static unsigned char cn_der[] = { 0x06, 0x03, 0x55, 0x04, 0x06 };
static unsigned char oid_der[] = {
0x06, 0x06, 0x2a, 0x03, 0x04, 0x05, 0x06, 0x07
};
int ret = 0;
ASN1_OBJECT *obj;
unsigned char const *p = oid_der;
/* Create an object that owns dynamically allocated 'sn' and 'ln' fields */
if (!TEST_ptr(obj = ASN1_OBJECT_create(NID_undef, cn_der, sizeof(cn_der),
"C", "countryName")))
goto err;
/* reuse obj - this should not leak sn and ln */
if (!TEST_ptr(d2i_ASN1_OBJECT(&obj, &p, sizeof(oid_der))))
goto err;
ret = 1;
err:
ASN1_OBJECT_free(obj);
return ret;
}
int setup_tests(void)
{
#ifndef OPENSSL_NO_DEPRECATED_3_0
ADD_TEST(test_long);
#endif
ADD_TEST(test_int32);
ADD_TEST(test_uint32);
ADD_TEST(test_int64);
ADD_TEST(test_uint64);
ADD_TEST(test_invalid_template);
ADD_TEST(test_reuse_asn1_object);
return 1;
}
| 6,421 | 26.211864 | 80 | c |
openssl | openssl-master/test/asn1_dsa_internal_test.c | /*
* Copyright 2019-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 <string.h>
#include <openssl/bn.h>
#include "crypto/asn1_dsa.h"
#include "testutil.h"
static unsigned char t_dsa_sig[] = {
0x30, 0x06, /* SEQUENCE tag + length */
0x02, 0x01, 0x01, /* INTEGER tag + length + content */
0x02, 0x01, 0x02 /* INTEGER tag + length + content */
};
static unsigned char t_dsa_sig_extra[] = {
0x30, 0x06, /* SEQUENCE tag + length */
0x02, 0x01, 0x01, /* INTEGER tag + length + content */
0x02, 0x01, 0x02, /* INTEGER tag + length + content */
0x05, 0x00 /* NULL tag + length */
};
static unsigned char t_dsa_sig_msb[] = {
0x30, 0x08, /* SEQUENCE tag + length */
0x02, 0x02, 0x00, 0x81, /* INTEGER tag + length + content */
0x02, 0x02, 0x00, 0x82 /* INTEGER tag + length + content */
};
static unsigned char t_dsa_sig_two[] = {
0x30, 0x08, /* SEQUENCE tag + length */
0x02, 0x02, 0x01, 0x00, /* INTEGER tag + length + content */
0x02, 0x02, 0x02, 0x00 /* INTEGER tag + length + content */
};
/*
* Badly coded ASN.1 INTEGER zero wrapped in a sequence along with another
* (valid) INTEGER.
*/
static unsigned char t_invalid_int_zero[] = {
0x30, 0x05, /* SEQUENCE tag + length */
0x02, 0x00, /* INTEGER tag + length */
0x02, 0x01, 0x2a /* INTEGER tag + length */
};
/*
* Badly coded ASN.1 INTEGER (with leading zeros) wrapped in a sequence along
* with another (valid) INTEGER.
*/
static unsigned char t_invalid_int[] = {
0x30, 0x07, /* SEQUENCE tag + length */
0x02, 0x02, 0x00, 0x7f, /* INTEGER tag + length */
0x02, 0x01, 0x2a /* INTEGER tag + length */
};
/*
* Negative ASN.1 INTEGER wrapped in a sequence along with another
* (valid) INTEGER.
*/
static unsigned char t_neg_int[] = {
0x30, 0x06, /* SEQUENCE tag + length */
0x02, 0x01, 0xaa, /* INTEGER tag + length */
0x02, 0x01, 0x2a /* INTEGER tag + length */
};
static unsigned char t_trunc_der[] = {
0x30, 0x08, /* SEQUENCE tag + length */
0x02, 0x02, 0x00, 0x81, /* INTEGER tag + length */
0x02, 0x02, 0x00 /* INTEGER tag + length */
};
static unsigned char t_trunc_seq[] = {
0x30, 0x07, /* SEQUENCE tag + length */
0x02, 0x02, 0x00, 0x81, /* INTEGER tag + length */
0x02, 0x02, 0x00, 0x82 /* INTEGER tag + length */
};
static int test_decode(void)
{
int rv = 0;
BIGNUM *r;
BIGNUM *s;
const unsigned char *pder;
r = BN_new();
s = BN_new();
/* Positive tests */
pder = t_dsa_sig;
if (ossl_decode_der_dsa_sig(r, s, &pder, sizeof(t_dsa_sig)) == 0
|| !TEST_ptr_eq(pder, (t_dsa_sig + sizeof(t_dsa_sig)))
|| !TEST_BN_eq_word(r, 1) || !TEST_BN_eq_word(s, 2)) {
TEST_info("asn1_dsa test_decode: t_dsa_sig failed");
goto fail;
}
BN_clear(r);
BN_clear(s);
pder = t_dsa_sig_extra;
if (ossl_decode_der_dsa_sig(r, s, &pder, sizeof(t_dsa_sig_extra)) == 0
|| !TEST_ptr_eq(pder,
(t_dsa_sig_extra + sizeof(t_dsa_sig_extra) - 2))
|| !TEST_BN_eq_word(r, 1) || !TEST_BN_eq_word(s, 2)) {
TEST_info("asn1_dsa test_decode: t_dsa_sig_extra failed");
goto fail;
}
BN_clear(r);
BN_clear(s);
pder = t_dsa_sig_msb;
if (ossl_decode_der_dsa_sig(r, s, &pder, sizeof(t_dsa_sig_msb)) == 0
|| !TEST_ptr_eq(pder, (t_dsa_sig_msb + sizeof(t_dsa_sig_msb)))
|| !TEST_BN_eq_word(r, 0x81) || !TEST_BN_eq_word(s, 0x82)) {
TEST_info("asn1_dsa test_decode: t_dsa_sig_msb failed");
goto fail;
}
BN_clear(r);
BN_clear(s);
pder = t_dsa_sig_two;
if (ossl_decode_der_dsa_sig(r, s, &pder, sizeof(t_dsa_sig_two)) == 0
|| !TEST_ptr_eq(pder, (t_dsa_sig_two + sizeof(t_dsa_sig_two)))
|| !TEST_BN_eq_word(r, 0x100) || !TEST_BN_eq_word(s, 0x200)) {
TEST_info("asn1_dsa test_decode: t_dsa_sig_two failed");
goto fail;
}
/* Negative tests */
pder = t_invalid_int_zero;
if (ossl_decode_der_dsa_sig(r, s, &pder, sizeof(t_invalid_int_zero)) != 0) {
TEST_info("asn1_dsa test_decode: Expected t_invalid_int_zero to fail");
goto fail;
}
BN_clear(r);
BN_clear(s);
pder = t_invalid_int;
if (ossl_decode_der_dsa_sig(r, s, &pder, sizeof(t_invalid_int)) != 0) {
TEST_info("asn1_dsa test_decode: Expected t_invalid_int to fail");
goto fail;
}
BN_clear(r);
BN_clear(s);
pder = t_neg_int;
if (ossl_decode_der_dsa_sig(r, s, &pder, sizeof(t_neg_int)) != 0) {
TEST_info("asn1_dsa test_decode: Expected t_neg_int to fail");
goto fail;
}
BN_clear(r);
BN_clear(s);
pder = t_trunc_der;
if (ossl_decode_der_dsa_sig(r, s, &pder, sizeof(t_trunc_der)) != 0) {
TEST_info("asn1_dsa test_decode: Expected fail t_trunc_der");
goto fail;
}
BN_clear(r);
BN_clear(s);
pder = t_trunc_seq;
if (ossl_decode_der_dsa_sig(r, s, &pder, sizeof(t_trunc_seq)) != 0) {
TEST_info("asn1_dsa test_decode: Expected fail t_trunc_seq");
goto fail;
}
rv = 1;
fail:
BN_free(r);
BN_free(s);
return rv;
}
int setup_tests(void)
{
ADD_TEST(test_decode);
return 1;
}
| 5,866 | 30.713514 | 80 | c |
openssl | openssl-master/test/asn1_internal_test.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
*/
/* Internal tests for the asn1 module */
/*
* RSA 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/asn1.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include "testutil.h"
#include "internal/nelem.h"
/**********************************************************************
*
* Test of a_strnid's tbl_standard
*
***/
#include "../crypto/asn1/tbl_standard.h"
static int test_tbl_standard(void)
{
const ASN1_STRING_TABLE *tmp;
int last_nid = -1;
size_t i;
for (tmp = tbl_standard, i = 0; i < OSSL_NELEM(tbl_standard); i++, tmp++) {
if (tmp->nid < last_nid) {
last_nid = 0;
break;
}
last_nid = tmp->nid;
}
if (TEST_int_ne(last_nid, 0)) {
TEST_info("asn1 tbl_standard: Table order OK");
return 1;
}
TEST_info("asn1 tbl_standard: out of order");
for (tmp = tbl_standard, i = 0; i < OSSL_NELEM(tbl_standard); i++, tmp++)
TEST_note("asn1 tbl_standard: Index %zu, NID %d, Name=%s",
i, tmp->nid, OBJ_nid2ln(tmp->nid));
return 0;
}
/**********************************************************************
*
* Test of ameth_lib's standard_methods
*
***/
#include "crypto/asn1.h"
#include "../crypto/asn1/standard_methods.h"
static int test_standard_methods(void)
{
const EVP_PKEY_ASN1_METHOD **tmp;
int last_pkey_id = -1;
size_t i;
int ok = 1;
for (tmp = standard_methods, i = 0; i < OSSL_NELEM(standard_methods);
i++, tmp++) {
if ((*tmp)->pkey_id < last_pkey_id) {
last_pkey_id = 0;
break;
}
last_pkey_id = (*tmp)->pkey_id;
/*
* One of the following must be true:
*
* pem_str == NULL AND ASN1_PKEY_ALIAS is set
* pem_str != NULL AND ASN1_PKEY_ALIAS is clear
*
* Anything else is an error and may lead to a corrupt ASN1 method table
*/
if (!TEST_true(((*tmp)->pem_str == NULL && ((*tmp)->pkey_flags & ASN1_PKEY_ALIAS) != 0)
|| ((*tmp)->pem_str != NULL && ((*tmp)->pkey_flags & ASN1_PKEY_ALIAS) == 0))) {
TEST_note("asn1 standard methods: Index %zu, pkey ID %d, Name=%s",
i, (*tmp)->pkey_id, OBJ_nid2sn((*tmp)->pkey_id));
ok = 0;
}
}
if (TEST_int_ne(last_pkey_id, 0)) {
TEST_info("asn1 standard methods: Table order OK");
return ok;
}
TEST_note("asn1 standard methods: out of order");
for (tmp = standard_methods, i = 0; i < OSSL_NELEM(standard_methods);
i++, tmp++)
TEST_note("asn1 standard methods: Index %zu, pkey ID %d, Name=%s",
i, (*tmp)->pkey_id, OBJ_nid2sn((*tmp)->pkey_id));
return 0;
}
/**********************************************************************
*
* Test of that i2d fail on non-existing non-optional items
*
***/
#include <openssl/rsa.h>
static int test_empty_nonoptional_content(void)
{
RSA *rsa = NULL;
BIGNUM *n = NULL;
BIGNUM *e = NULL;
int ok = 0;
if (!TEST_ptr(rsa = RSA_new())
|| !TEST_ptr(n = BN_new())
|| !TEST_ptr(e = BN_new())
|| !TEST_true(RSA_set0_key(rsa, n, e, NULL)))
goto end;
n = e = NULL; /* They are now "owned" by |rsa| */
/*
* This SHOULD fail, as we're trying to encode a public key as a private
* key. The private key bits MUST be present for a proper RSAPrivateKey.
*/
if (TEST_int_le(i2d_RSAPrivateKey(rsa, NULL), 0))
ok = 1;
end:
RSA_free(rsa);
BN_free(n);
BN_free(e);
return ok;
}
/**********************************************************************
*
* Tests of the Unicode code point range
*
***/
static int test_unicode(const unsigned char *univ, size_t len, int expected)
{
const unsigned char *end = univ + len;
int ok = 1;
for (; univ < end; univ += 4) {
if (!TEST_int_eq(ASN1_mbstring_copy(NULL, univ, 4, MBSTRING_UNIV,
B_ASN1_UTF8STRING),
expected))
ok = 0;
}
return ok;
}
static int test_unicode_range(void)
{
const unsigned char univ_ok[] = "\0\0\0\0"
"\0\0\xd7\xff"
"\0\0\xe0\x00"
"\0\x10\xff\xff";
const unsigned char univ_bad[] = "\0\0\xd8\x00"
"\0\0\xdf\xff"
"\0\x11\x00\x00"
"\x80\x00\x00\x00"
"\xff\xff\xff\xff";
int ok = 1;
if (!test_unicode(univ_ok, sizeof univ_ok - 1, V_ASN1_UTF8STRING))
ok = 0;
if (!test_unicode(univ_bad, sizeof univ_bad - 1, -1))
ok = 0;
return ok;
}
/**********************************************************************
*
* Tests of object creation
*
***/
static int test_obj_create_once(const char *oid, const char *sn, const char *ln)
{
int nid;
ERR_set_mark();
nid = OBJ_create(oid, sn, ln);
if (nid == NID_undef) {
unsigned long err = ERR_peek_last_error();
int l = ERR_GET_LIB(err);
int r = ERR_GET_REASON(err);
/* If it exists, that's fine, otherwise not */
if (l != ERR_LIB_OBJ || r != OBJ_R_OID_EXISTS) {
ERR_clear_last_mark();
return 0;
}
}
ERR_pop_to_mark();
return 1;
}
static int test_obj_create(void)
{
/* Stolen from evp_extra_test.c */
#define arc "1.3.6.1.4.1.16604.998866."
#define broken_arc "25."
#define sn_prefix "custom"
#define ln_prefix "custom"
/* Try different combinations of correct object creation */
if (!TEST_true(test_obj_create_once(NULL, sn_prefix "1", NULL))
|| !TEST_int_ne(OBJ_sn2nid(sn_prefix "1"), NID_undef)
|| !TEST_true(test_obj_create_once(NULL, NULL, ln_prefix "2"))
|| !TEST_int_ne(OBJ_ln2nid(ln_prefix "2"), NID_undef)
|| !TEST_true(test_obj_create_once(NULL, sn_prefix "3", ln_prefix "3"))
|| !TEST_int_ne(OBJ_sn2nid(sn_prefix "3"), NID_undef)
|| !TEST_int_ne(OBJ_ln2nid(ln_prefix "3"), NID_undef)
|| !TEST_true(test_obj_create_once(arc "4", NULL, NULL))
|| !TEST_true(test_obj_create_once(arc "5", sn_prefix "5", NULL))
|| !TEST_int_ne(OBJ_sn2nid(sn_prefix "5"), NID_undef)
|| !TEST_true(test_obj_create_once(arc "6", NULL, ln_prefix "6"))
|| !TEST_int_ne(OBJ_ln2nid(ln_prefix "6"), NID_undef)
|| !TEST_true(test_obj_create_once(arc "7",
sn_prefix "7", ln_prefix "7"))
|| !TEST_int_ne(OBJ_sn2nid(sn_prefix "7"), NID_undef)
|| !TEST_int_ne(OBJ_ln2nid(ln_prefix "7"), NID_undef))
return 0;
if (!TEST_false(test_obj_create_once(NULL, NULL, NULL))
|| !TEST_false(test_obj_create_once(broken_arc "8",
sn_prefix "8", ln_prefix "8")))
return 0;
return 1;
}
static int test_obj_nid_undef(void)
{
if (!TEST_ptr(OBJ_nid2obj(NID_undef))
|| !TEST_ptr(OBJ_nid2sn(NID_undef))
|| !TEST_ptr(OBJ_nid2ln(NID_undef)))
return 0;
return 1;
}
int setup_tests(void)
{
ADD_TEST(test_tbl_standard);
ADD_TEST(test_standard_methods);
ADD_TEST(test_empty_nonoptional_content);
ADD_TEST(test_unicode_range);
ADD_TEST(test_obj_create);
ADD_TEST(test_obj_nid_undef);
return 1;
}
| 7,977 | 27.801444 | 102 | c |
openssl | openssl-master/test/asn1_string_table_test.c | /*
* Copyright 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
*/
/* Tests for the ASN1_STRING_TABLE_* functions */
#include <stdio.h>
#include <string.h>
#include <openssl/asn1.h>
#include "testutil.h"
static int test_string_tbl(void)
{
const ASN1_STRING_TABLE *tmp = NULL;
int nid = 12345678, nid2 = 87654321, rv = 0, ret = 0;
tmp = ASN1_STRING_TABLE_get(nid);
if (!TEST_ptr_null(tmp)) {
TEST_info("asn1 string table: ASN1_STRING_TABLE_get non-exist nid");
goto out;
}
ret = ASN1_STRING_TABLE_add(nid, -1, -1, MBSTRING_ASC, 0);
if (!TEST_true(ret)) {
TEST_info("asn1 string table: add NID(%d) failed", nid);
goto out;
}
ret = ASN1_STRING_TABLE_add(nid2, -1, -1, MBSTRING_ASC, 0);
if (!TEST_true(ret)) {
TEST_info("asn1 string table: add NID(%d) failed", nid2);
goto out;
}
tmp = ASN1_STRING_TABLE_get(nid);
if (!TEST_ptr(tmp)) {
TEST_info("asn1 string table: get NID(%d) failed", nid);
goto out;
}
tmp = ASN1_STRING_TABLE_get(nid2);
if (!TEST_ptr(tmp)) {
TEST_info("asn1 string table: get NID(%d) failed", nid2);
goto out;
}
ASN1_STRING_TABLE_cleanup();
/* check if all newly added NIDs are cleaned up */
tmp = ASN1_STRING_TABLE_get(nid);
if (!TEST_ptr_null(tmp)) {
TEST_info("asn1 string table: get NID(%d) failed", nid);
goto out;
}
tmp = ASN1_STRING_TABLE_get(nid2);
if (!TEST_ptr_null(tmp)) {
TEST_info("asn1 string table: get NID(%d) failed", nid2);
goto out;
}
rv = 1;
out:
return rv;
}
int setup_tests(void)
{
ADD_TEST(test_string_tbl);
return 1;
}
| 1,966 | 24.217949 | 76 | c |
openssl | openssl-master/test/asn1_time_test.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
*/
/* Time tests for the asn1 module */
#include <stdio.h>
#include <string.h>
#include <crypto/asn1.h>
#include <openssl/asn1.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include "testutil.h"
#include "internal/nelem.h"
struct testdata {
char *data; /* TIME string value */
int type; /* GENERALIZED OR UTC */
int expected_type; /* expected type after set/set_string_gmt */
int check_result; /* check result */
time_t t; /* expected time_t*/
int cmp_result; /* comparison to baseline result */
int convert_result; /* conversion result */
};
struct TESTDATA_asn1_to_utc {
char *input;
time_t expected;
};
static const struct TESTDATA_asn1_to_utc asn1_to_utc[] = {
{
/*
* last second of standard time in central Europe in 2021
* specified in GMT
*/
"210328005959Z",
1616893199,
},
{
/*
* first second of daylight saving time in central Europe in 2021
* specified in GMT
*/
"210328010000Z",
1616893200,
},
{
/*
* last second of standard time in central Europe in 2021
* specified in offset to GMT
*/
"20210328015959+0100",
1616893199,
},
{
/*
* first second of daylight saving time in central Europe in 2021
* specified in offset to GMT
*/
"20210328030000+0200",
1616893200,
},
{
/*
* Invalid strings should get -1 as a result
*/
"INVALID",
-1,
},
};
static struct testdata tbl_testdata_pos[] = {
{ "0", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, }, /* Bad time */
{ "ABCD", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "0ABCD", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "1-700101000000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "`9700101000000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "19700101000000Z", V_ASN1_UTCTIME, V_ASN1_UTCTIME, 0, 0, 0, 0, },
{ "A00101000000Z", V_ASN1_UTCTIME, V_ASN1_UTCTIME, 0, 0, 0, 0, },
{ "A9700101000000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "1A700101000000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "19A00101000000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "197A0101000000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "1970A101000000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "19700A01000000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "197001A1000000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "1970010A000000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "19700101A00000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "197001010A0000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "1970010100A000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "19700101000A00Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "197001010000A0Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "1970010100000AZ", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "700101000000X", V_ASN1_UTCTIME, V_ASN1_UTCTIME, 0, 0, 0, 0, },
{ "19700101000000X", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 0, 0, 0, 0, },
{ "19700101000000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_UTCTIME, 1, 0, -1, 1, }, /* Epoch begins */
{ "700101000000Z", V_ASN1_UTCTIME, V_ASN1_UTCTIME, 1, 0, -1, 1, }, /* ditto */
{ "20380119031407Z", V_ASN1_GENERALIZEDTIME, V_ASN1_UTCTIME, 1, 0x7FFFFFFF, 1, 1, }, /* Max 32bit time_t */
{ "380119031407Z", V_ASN1_UTCTIME, V_ASN1_UTCTIME, 1, 0x7FFFFFFF, 1, 1, },
{ "20371231235959Z", V_ASN1_GENERALIZEDTIME, V_ASN1_UTCTIME, 1, 2145916799, 1, 1, }, /* Just before 2038 */
{ "20371231235959Z", V_ASN1_UTCTIME, V_ASN1_UTCTIME, 0, 0, 0, 1, }, /* Bad UTC time */
{ "371231235959Z", V_ASN1_UTCTIME, V_ASN1_UTCTIME, 1, 2145916799, 1, 1, },
{ "19701006121456Z", V_ASN1_GENERALIZEDTIME, V_ASN1_UTCTIME, 1, 24063296, -1, 1, },
{ "701006121456Z", V_ASN1_UTCTIME, V_ASN1_UTCTIME, 1, 24063296, -1, 1, },
{ "19991231000000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_UTCTIME, 1, 946598400, 0, 1, }, /* Match baseline */
{ "199912310000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_UTCTIME, 1, 946598400, 0, 1, }, /* In various flavors */
{ "991231000000Z", V_ASN1_UTCTIME, V_ASN1_UTCTIME, 1, 946598400, 0, 1, },
{ "9912310000Z", V_ASN1_UTCTIME, V_ASN1_UTCTIME, 1, 946598400, 0, 1, },
{ "9912310000+0000", V_ASN1_UTCTIME, V_ASN1_UTCTIME, 1, 946598400, 0, 1, },
{ "199912310000+0000", V_ASN1_GENERALIZEDTIME, V_ASN1_UTCTIME, 1, 946598400, 0, 1, },
{ "9912310000-0000", V_ASN1_UTCTIME, V_ASN1_UTCTIME, 1, 946598400, 0, 1, },
{ "199912310000-0000", V_ASN1_GENERALIZEDTIME, V_ASN1_UTCTIME, 1, 946598400, 0, 1, },
{ "199912310100+0100", V_ASN1_GENERALIZEDTIME, V_ASN1_UTCTIME, 1, 946598400, 0, 1, },
{ "199912302300-0100", V_ASN1_GENERALIZEDTIME, V_ASN1_UTCTIME, 1, 946598400, 0, 1, },
{ "199912302300-A000", V_ASN1_GENERALIZEDTIME, V_ASN1_UTCTIME, 0, 946598400, 0, 1, },
{ "199912302300-0A00", V_ASN1_GENERALIZEDTIME, V_ASN1_UTCTIME, 0, 946598400, 0, 1, },
{ "9912310100+0100", V_ASN1_UTCTIME, V_ASN1_UTCTIME, 1, 946598400, 0, 1, },
{ "9912302300-0100", V_ASN1_UTCTIME, V_ASN1_UTCTIME, 1, 946598400, 0, 1, },
};
/* ASSUMES SIGNED TIME_T */
static struct testdata tbl_testdata_neg[] = {
{ "19011213204552Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 1, INT_MIN, -1, 0, },
{ "691006121456Z", V_ASN1_UTCTIME, V_ASN1_UTCTIME, 1, -7472704, -1, 1, },
{ "19691006121456Z", V_ASN1_GENERALIZEDTIME, V_ASN1_UTCTIME, 1, -7472704, -1, 1, },
};
/* explicit casts to time_t short warnings on systems with 32-bit time_t */
static struct testdata tbl_testdata_pos_64bit[] = {
{ "20380119031408Z", V_ASN1_GENERALIZEDTIME, V_ASN1_UTCTIME, 1, (time_t)0x80000000, 1, 1, },
{ "20380119031409Z", V_ASN1_GENERALIZEDTIME, V_ASN1_UTCTIME, 1, (time_t)0x80000001, 1, 1, },
{ "380119031408Z", V_ASN1_UTCTIME, V_ASN1_UTCTIME, 1, (time_t)0x80000000, 1, 1, },
{ "20500101120000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 1, (time_t)0x967b1ec0, 1, 0, },
};
/* ASSUMES SIGNED TIME_T */
static struct testdata tbl_testdata_neg_64bit[] = {
{ "19011213204551Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 1, (time_t)-2147483649LL, -1, 0, },
{ "19000101120000Z", V_ASN1_GENERALIZEDTIME, V_ASN1_GENERALIZEDTIME, 1, (time_t)-2208945600LL, -1, 0, },
};
/* A baseline time to compare to */
static ASN1_TIME gtime = {
15,
V_ASN1_GENERALIZEDTIME,
(unsigned char*)"19991231000000Z",
0
};
static time_t gtime_t = 946598400;
static int test_table(struct testdata *tbl, int idx)
{
int error = 0;
ASN1_TIME atime;
ASN1_TIME *ptime;
struct testdata *td = &tbl[idx];
int day, sec;
atime.data = (unsigned char*)td->data;
atime.length = strlen((char*)atime.data);
atime.type = td->type;
atime.flags = 0;
if (!TEST_int_eq(ASN1_TIME_check(&atime), td->check_result)) {
TEST_info("ASN1_TIME_check(%s) unexpected result", atime.data);
error = 1;
}
if (td->check_result == 0)
return 1;
if (!TEST_int_eq(ASN1_TIME_cmp_time_t(&atime, td->t), 0)) {
TEST_info("ASN1_TIME_cmp_time_t(%s vs %ld) compare failed", atime.data, (long)td->t);
error = 1;
}
if (!TEST_true(ASN1_TIME_diff(&day, &sec, &atime, &atime))) {
TEST_info("ASN1_TIME_diff(%s) to self failed", atime.data);
error = 1;
}
if (!TEST_int_eq(day, 0) || !TEST_int_eq(sec, 0)) {
TEST_info("ASN1_TIME_diff(%s) to self not equal", atime.data);
error = 1;
}
if (!TEST_true(ASN1_TIME_diff(&day, &sec, >ime, &atime))) {
TEST_info("ASN1_TIME_diff(%s) to baseline failed", atime.data);
error = 1;
} else if (!((td->cmp_result == 0 && TEST_true((day == 0 && sec == 0))) ||
(td->cmp_result == -1 && TEST_true((day < 0 || sec < 0))) ||
(td->cmp_result == 1 && TEST_true((day > 0 || sec > 0))))) {
TEST_info("ASN1_TIME_diff(%s) to baseline bad comparison", atime.data);
error = 1;
}
if (!TEST_int_eq(ASN1_TIME_cmp_time_t(&atime, gtime_t), td->cmp_result)) {
TEST_info("ASN1_TIME_cmp_time_t(%s) to baseline bad comparison", atime.data);
error = 1;
}
ptime = ASN1_TIME_set(NULL, td->t);
if (!TEST_ptr(ptime)) {
TEST_info("ASN1_TIME_set(%ld) failed", (long)td->t);
error = 1;
} else {
int local_error = 0;
if (!TEST_int_eq(ASN1_TIME_cmp_time_t(ptime, td->t), 0)) {
TEST_info("ASN1_TIME_set(%ld) compare failed (%s->%s)",
(long)td->t, td->data, ptime->data);
local_error = error = 1;
}
if (!TEST_int_eq(ptime->type, td->expected_type)) {
TEST_info("ASN1_TIME_set(%ld) unexpected type", (long)td->t);
local_error = error = 1;
}
if (local_error)
TEST_info("ASN1_TIME_set() = %*s", ptime->length, ptime->data);
ASN1_TIME_free(ptime);
}
ptime = ASN1_TIME_new();
if (!TEST_ptr(ptime)) {
TEST_info("ASN1_TIME_new() failed");
error = 1;
} else {
int local_error = 0;
if (!TEST_int_eq(ASN1_TIME_set_string(ptime, td->data), td->check_result)) {
TEST_info("ASN1_TIME_set_string_gmt(%s) failed", td->data);
local_error = error = 1;
}
if (!TEST_int_eq(ASN1_TIME_normalize(ptime), td->check_result)) {
TEST_info("ASN1_TIME_normalize(%s) failed", td->data);
local_error = error = 1;
}
if (!TEST_int_eq(ptime->type, td->expected_type)) {
TEST_info("ASN1_TIME_set_string_gmt(%s) unexpected type", td->data);
local_error = error = 1;
}
day = sec = 0;
if (!TEST_true(ASN1_TIME_diff(&day, &sec, ptime, &atime)) || !TEST_int_eq(day, 0) || !TEST_int_eq(sec, 0)) {
TEST_info("ASN1_TIME_diff(day=%d, sec=%d, %s) after ASN1_TIME_set_string_gmt() failed", day, sec, td->data);
local_error = error = 1;
}
if (!TEST_int_eq(ASN1_TIME_cmp_time_t(ptime, gtime_t), td->cmp_result)) {
TEST_info("ASN1_TIME_cmp_time_t(%s) after ASN1_TIME_set_string_gnt() to baseline bad comparison", td->data);
local_error = error = 1;
}
if (local_error)
TEST_info("ASN1_TIME_set_string_gmt() = %*s", ptime->length, ptime->data);
ASN1_TIME_free(ptime);
}
ptime = ASN1_TIME_new();
if (!TEST_ptr(ptime)) {
TEST_info("ASN1_TIME_new() failed");
error = 1;
} else {
int local_error = 0;
if (!TEST_int_eq(ASN1_TIME_set_string(ptime, td->data), td->check_result)) {
TEST_info("ASN1_TIME_set_string(%s) failed", td->data);
local_error = error = 1;
}
day = sec = 0;
if (!TEST_true(ASN1_TIME_diff(&day, &sec, ptime, &atime)) || !TEST_int_eq(day, 0) || !TEST_int_eq(sec, 0)) {
TEST_info("ASN1_TIME_diff(day=%d, sec=%d, %s) after ASN1_TIME_set_string() failed", day, sec, td->data);
local_error = error = 1;
}
if (!TEST_int_eq(ASN1_TIME_cmp_time_t(ptime, gtime_t), td->cmp_result)) {
TEST_info("ASN1_TIME_cmp_time_t(%s) after ASN1_TIME_set_string() to baseline bad comparison", td->data);
local_error = error = 1;
}
if (local_error)
TEST_info("ASN1_TIME_set_string() = %*s", ptime->length, ptime->data);
ASN1_TIME_free(ptime);
}
if (td->type == V_ASN1_UTCTIME) {
ptime = ASN1_TIME_to_generalizedtime(&atime, NULL);
if (td->convert_result == 1 && !TEST_ptr(ptime)) {
TEST_info("ASN1_TIME_to_generalizedtime(%s) failed", atime.data);
error = 1;
} else if (td->convert_result == 0 && !TEST_ptr_null(ptime)) {
TEST_info("ASN1_TIME_to_generalizedtime(%s) should have failed", atime.data);
error = 1;
}
if (ptime != NULL && !TEST_int_eq(ASN1_TIME_cmp_time_t(ptime, td->t), 0)) {
TEST_info("ASN1_TIME_to_generalizedtime(%s->%s) bad result", atime.data, ptime->data);
error = 1;
}
ASN1_TIME_free(ptime);
}
/* else cannot simply convert GENERALIZEDTIME to UTCTIME */
if (error)
TEST_error("atime=%s", atime.data);
return !error;
}
static int test_table_pos(int idx)
{
return test_table(tbl_testdata_pos, idx);
}
static int test_table_neg(int idx)
{
return test_table(tbl_testdata_neg, idx);
}
static int test_table_pos_64bit(int idx)
{
return test_table(tbl_testdata_pos_64bit, idx);
}
static int test_table_neg_64bit(int idx)
{
return test_table(tbl_testdata_neg_64bit, idx);
}
struct compare_testdata {
ASN1_TIME t1;
ASN1_TIME t2;
int result;
};
static unsigned char TODAY_GEN_STR[] = "20170825000000Z";
static unsigned char TOMORROW_GEN_STR[] = "20170826000000Z";
static unsigned char TODAY_UTC_STR[] = "170825000000Z";
static unsigned char TOMORROW_UTC_STR[] = "170826000000Z";
#define TODAY_GEN { sizeof(TODAY_GEN_STR)-1, V_ASN1_GENERALIZEDTIME, TODAY_GEN_STR, 0 }
#define TOMORROW_GEN { sizeof(TOMORROW_GEN_STR)-1, V_ASN1_GENERALIZEDTIME, TOMORROW_GEN_STR, 0 }
#define TODAY_UTC { sizeof(TODAY_UTC_STR)-1, V_ASN1_UTCTIME, TODAY_UTC_STR, 0 }
#define TOMORROW_UTC { sizeof(TOMORROW_UTC_STR)-1, V_ASN1_UTCTIME, TOMORROW_UTC_STR, 0 }
static struct compare_testdata tbl_compare_testdata[] = {
{ TODAY_GEN, TODAY_GEN, 0 },
{ TODAY_GEN, TODAY_UTC, 0 },
{ TODAY_GEN, TOMORROW_GEN, -1 },
{ TODAY_GEN, TOMORROW_UTC, -1 },
{ TODAY_UTC, TODAY_GEN, 0 },
{ TODAY_UTC, TODAY_UTC, 0 },
{ TODAY_UTC, TOMORROW_GEN, -1 },
{ TODAY_UTC, TOMORROW_UTC, -1 },
{ TOMORROW_GEN, TODAY_GEN, 1 },
{ TOMORROW_GEN, TODAY_UTC, 1 },
{ TOMORROW_GEN, TOMORROW_GEN, 0 },
{ TOMORROW_GEN, TOMORROW_UTC, 0 },
{ TOMORROW_UTC, TODAY_GEN, 1 },
{ TOMORROW_UTC, TODAY_UTC, 1 },
{ TOMORROW_UTC, TOMORROW_GEN, 0 },
{ TOMORROW_UTC, TOMORROW_UTC, 0 }
};
static int test_table_compare(int idx)
{
struct compare_testdata *td = &tbl_compare_testdata[idx];
return TEST_int_eq(ASN1_TIME_compare(&td->t1, &td->t2), td->result);
}
static int test_time_dup(void)
{
int ret = 0;
ASN1_TIME *asn1_time = NULL;
ASN1_TIME *asn1_time_dup = NULL;
ASN1_TIME *asn1_gentime = NULL;
asn1_time = ASN1_TIME_adj(NULL, time(NULL), 0, 0);
if (asn1_time == NULL) {
TEST_info("Internal error.");
goto err;
}
asn1_gentime = ASN1_TIME_to_generalizedtime(asn1_time, NULL);
if (asn1_gentime == NULL) {
TEST_info("Internal error.");
goto err;
}
asn1_time_dup = ASN1_TIME_dup(asn1_time);
if (!TEST_ptr_ne(asn1_time_dup, NULL)) {
TEST_info("ASN1_TIME_dup() failed.");
goto err;
}
if (!TEST_int_eq(ASN1_TIME_compare(asn1_time, asn1_time_dup), 0)) {
TEST_info("ASN1_TIME_dup() duplicated non-identical value.");
goto err;
}
ASN1_STRING_free(asn1_time_dup);
asn1_time_dup = ASN1_UTCTIME_dup(asn1_time);
if (!TEST_ptr_ne(asn1_time_dup, NULL)) {
TEST_info("ASN1_UTCTIME_dup() failed.");
goto err;
}
if (!TEST_int_eq(ASN1_TIME_compare(asn1_time, asn1_time_dup), 0)) {
TEST_info("ASN1_UTCTIME_dup() duplicated non-identical UTCTIME value.");
goto err;
}
ASN1_STRING_free(asn1_time_dup);
asn1_time_dup = ASN1_GENERALIZEDTIME_dup(asn1_gentime);
if (!TEST_ptr_ne(asn1_time_dup, NULL)) {
TEST_info("ASN1_GENERALIZEDTIME_dup() failed.");
goto err;
}
if (!TEST_int_eq(ASN1_TIME_compare(asn1_gentime, asn1_time_dup), 0)) {
TEST_info("ASN1_GENERALIZEDTIME_dup() dup'ed non-identical value.");
goto err;
}
ret = 1;
err:
ASN1_STRING_free(asn1_time);
ASN1_STRING_free(asn1_gentime);
ASN1_STRING_free(asn1_time_dup);
return ret;
}
static int convert_asn1_to_time_t(int idx)
{
time_t testdateutc;
testdateutc = ossl_asn1_string_to_time_t(asn1_to_utc[idx].input);
if (!TEST_time_t_eq(testdateutc, asn1_to_utc[idx].expected)) {
TEST_info("ossl_asn1_string_to_time_t (%s) failed: expected %lli, got %lli\n",
asn1_to_utc[idx].input,
(long long int)asn1_to_utc[idx].expected,
(long long int)testdateutc);
return 0;
}
return 1;
}
int setup_tests(void)
{
/*
* On platforms where |time_t| is an unsigned integer, t will be a
* positive number.
*
* We check if we're on a platform with a signed |time_t| with '!(t > 0)'
* because some compilers are picky if you do 't < 0', or even 't <= 0'
* if |t| is unsigned.
*/
time_t t = -1;
/*
* On some platforms, |time_t| is signed, but a negative value is an
* error, and using it with gmtime() or localtime() generates a NULL.
* If that is the case, we can't perform tests on negative values.
*/
struct tm *ptm = localtime(&t);
ADD_ALL_TESTS(test_table_pos, OSSL_NELEM(tbl_testdata_pos));
if (!(t > 0) && ptm != NULL) {
TEST_info("Adding negative-sign time_t tests");
ADD_ALL_TESTS(test_table_neg, OSSL_NELEM(tbl_testdata_neg));
}
if (sizeof(time_t) > sizeof(uint32_t)) {
TEST_info("Adding 64-bit time_t tests");
ADD_ALL_TESTS(test_table_pos_64bit, OSSL_NELEM(tbl_testdata_pos_64bit));
#ifndef __hpux
if (!(t > 0) && ptm != NULL) {
TEST_info("Adding negative-sign 64-bit time_t tests");
ADD_ALL_TESTS(test_table_neg_64bit, OSSL_NELEM(tbl_testdata_neg_64bit));
}
#endif
}
ADD_ALL_TESTS(test_table_compare, OSSL_NELEM(tbl_compare_testdata));
ADD_TEST(test_time_dup);
ADD_ALL_TESTS(convert_asn1_to_time_t, OSSL_NELEM(asn1_to_utc));
return 1;
}
| 19,664 | 39.630165 | 125 | c |
openssl | openssl-master/test/asynciotest.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 may obtain a copy of the License at
* https://www.openssl.org/source/license.html
* or in the file LICENSE in the source distribution.
*/
#include <string.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include "internal/packet.h"
#include "helpers/ssltestlib.h"
#include "testutil.h"
/* Should we fragment records or not? 0 = no, !0 = yes*/
static int fragment = 0;
static char *cert = NULL;
static char *privkey = NULL;
static int async_new(BIO *bi);
static int async_free(BIO *a);
static int async_read(BIO *b, char *out, int outl);
static int async_write(BIO *b, const char *in, int inl);
static long async_ctrl(BIO *b, int cmd, long num, void *ptr);
static int async_gets(BIO *bp, char *buf, int size);
static int async_puts(BIO *bp, const char *str);
/* Choose a sufficiently large type likely to be unused for this custom BIO */
# define BIO_TYPE_ASYNC_FILTER (0x80 | BIO_TYPE_FILTER)
static BIO_METHOD *methods_async = NULL;
struct async_ctrs {
unsigned int rctr;
unsigned int wctr;
};
static const BIO_METHOD *bio_f_async_filter(void)
{
if (methods_async == NULL) {
methods_async = BIO_meth_new(BIO_TYPE_ASYNC_FILTER, "Async filter");
if ( methods_async == NULL
|| !BIO_meth_set_write(methods_async, async_write)
|| !BIO_meth_set_read(methods_async, async_read)
|| !BIO_meth_set_puts(methods_async, async_puts)
|| !BIO_meth_set_gets(methods_async, async_gets)
|| !BIO_meth_set_ctrl(methods_async, async_ctrl)
|| !BIO_meth_set_create(methods_async, async_new)
|| !BIO_meth_set_destroy(methods_async, async_free))
return NULL;
}
return methods_async;
}
static int async_new(BIO *bio)
{
struct async_ctrs *ctrs;
ctrs = OPENSSL_zalloc(sizeof(struct async_ctrs));
if (ctrs == NULL)
return 0;
BIO_set_data(bio, ctrs);
BIO_set_init(bio, 1);
return 1;
}
static int async_free(BIO *bio)
{
struct async_ctrs *ctrs;
if (bio == NULL)
return 0;
ctrs = BIO_get_data(bio);
OPENSSL_free(ctrs);
BIO_set_data(bio, NULL);
BIO_set_init(bio, 0);
return 1;
}
static int async_read(BIO *bio, char *out, int outl)
{
struct async_ctrs *ctrs;
int ret = 0;
BIO *next = BIO_next(bio);
if (outl <= 0)
return 0;
if (next == NULL)
return 0;
ctrs = BIO_get_data(bio);
BIO_clear_retry_flags(bio);
if (ctrs->rctr > 0) {
ret = BIO_read(next, out, 1);
if (ret <= 0 && BIO_should_read(next))
BIO_set_retry_read(bio);
ctrs->rctr = 0;
} else {
ctrs->rctr++;
BIO_set_retry_read(bio);
}
return ret;
}
#define MIN_RECORD_LEN 6
#define CONTENTTYPEPOS 0
#define VERSIONHIPOS 1
#define VERSIONLOPOS 2
#define DATAPOS 5
static int async_write(BIO *bio, const char *in, int inl)
{
struct async_ctrs *ctrs;
int ret = 0;
size_t written = 0;
BIO *next = BIO_next(bio);
if (inl <= 0)
return 0;
if (next == NULL)
return 0;
ctrs = BIO_get_data(bio);
BIO_clear_retry_flags(bio);
if (ctrs->wctr > 0) {
ctrs->wctr = 0;
if (fragment) {
PACKET pkt;
if (!PACKET_buf_init(&pkt, (const unsigned char *)in, inl))
return -1;
while (PACKET_remaining(&pkt) > 0) {
PACKET payload, wholebody, sessionid, extensions;
unsigned int contenttype, versionhi, versionlo, data;
unsigned int msgtype = 0, negversion = 0;
if (!PACKET_get_1(&pkt, &contenttype)
|| !PACKET_get_1(&pkt, &versionhi)
|| !PACKET_get_1(&pkt, &versionlo)
|| !PACKET_get_length_prefixed_2(&pkt, &payload))
return -1;
/* Pretend we wrote out the record header */
written += SSL3_RT_HEADER_LENGTH;
wholebody = payload;
if (contenttype == SSL3_RT_HANDSHAKE
&& !PACKET_get_1(&wholebody, &msgtype))
return -1;
if (msgtype == SSL3_MT_SERVER_HELLO) {
if (!PACKET_forward(&wholebody,
SSL3_HM_HEADER_LENGTH - 1)
|| !PACKET_get_net_2(&wholebody, &negversion)
/* Skip random (32 bytes) */
|| !PACKET_forward(&wholebody, 32)
/* Skip session id */
|| !PACKET_get_length_prefixed_1(&wholebody,
&sessionid)
/*
* Skip ciphersuite (2 bytes) and compression
* method (1 byte)
*/
|| !PACKET_forward(&wholebody, 2 + 1)
|| !PACKET_get_length_prefixed_2(&wholebody,
&extensions))
return -1;
/*
* Find the negotiated version in supported_versions
* extension, if present.
*/
while (PACKET_remaining(&extensions)) {
unsigned int type;
PACKET extbody;
if (!PACKET_get_net_2(&extensions, &type)
|| !PACKET_get_length_prefixed_2(&extensions,
&extbody))
return -1;
if (type == TLSEXT_TYPE_supported_versions
&& (!PACKET_get_net_2(&extbody, &negversion)
|| PACKET_remaining(&extbody) != 0))
return -1;
}
}
while (PACKET_get_1(&payload, &data)) {
/* Create a new one byte long record for each byte in the
* record in the input buffer
*/
char smallrec[MIN_RECORD_LEN] = {
0, /* Content type */
0, /* Version hi */
0, /* Version lo */
0, /* Length hi */
1, /* Length lo */
0 /* Data */
};
smallrec[CONTENTTYPEPOS] = contenttype;
smallrec[VERSIONHIPOS] = versionhi;
smallrec[VERSIONLOPOS] = versionlo;
smallrec[DATAPOS] = data;
ret = BIO_write(next, smallrec, MIN_RECORD_LEN);
if (ret <= 0)
return -1;
written++;
}
/*
* We can't fragment anything after the ServerHello (or CCS <=
* TLS1.2), otherwise we get a bad record MAC
*/
if (contenttype == SSL3_RT_CHANGE_CIPHER_SPEC
|| (negversion == TLS1_3_VERSION
&& msgtype == SSL3_MT_SERVER_HELLO)) {
fragment = 0;
break;
}
}
}
/* Write any data we have left after fragmenting */
ret = 0;
if ((int)written < inl) {
ret = BIO_write(next, in + written, inl - written);
}
if (ret <= 0 && BIO_should_write(next))
BIO_set_retry_write(bio);
else
ret += written;
} else {
ctrs->wctr++;
BIO_set_retry_write(bio);
}
return ret;
}
static long async_ctrl(BIO *bio, int cmd, long num, void *ptr)
{
long ret;
BIO *next = BIO_next(bio);
if (next == NULL)
return 0;
switch (cmd) {
case BIO_CTRL_DUP:
ret = 0L;
break;
default:
ret = BIO_ctrl(next, cmd, num, ptr);
break;
}
return ret;
}
static int async_gets(BIO *bio, char *buf, int size)
{
/* We don't support this - not needed anyway */
return -1;
}
static int async_puts(BIO *bio, const char *str)
{
return async_write(bio, str, strlen(str));
}
#define MAX_ATTEMPTS 100
static int test_asyncio(int test)
{
SSL_CTX *serverctx = NULL, *clientctx = NULL;
SSL *serverssl = NULL, *clientssl = NULL;
BIO *s_to_c_fbio = NULL, *c_to_s_fbio = NULL;
int testresult = 0, ret;
size_t i, j;
const char testdata[] = "Test data";
char buf[sizeof(testdata)];
if (!TEST_true(create_ssl_ctx_pair(NULL, TLS_server_method(),
TLS_client_method(),
TLS1_VERSION, 0,
&serverctx, &clientctx, cert, privkey)))
goto end;
/*
* We do 2 test runs. The first time around we just do a normal handshake
* with lots of async io going on. The second time around we also break up
* all records so that the content is only one byte length (up until the
* CCS)
*/
if (test == 1)
fragment = 1;
s_to_c_fbio = BIO_new(bio_f_async_filter());
c_to_s_fbio = BIO_new(bio_f_async_filter());
if (!TEST_ptr(s_to_c_fbio)
|| !TEST_ptr(c_to_s_fbio)) {
BIO_free(s_to_c_fbio);
BIO_free(c_to_s_fbio);
goto end;
}
/* BIOs get freed on error */
if (!TEST_true(create_ssl_objects(serverctx, clientctx, &serverssl,
&clientssl, s_to_c_fbio, c_to_s_fbio))
|| !TEST_true(create_ssl_connection(serverssl, clientssl,
SSL_ERROR_NONE)))
goto end;
/*
* Send and receive some test data. Do the whole thing twice to ensure
* we hit at least one async event in both reading and writing
*/
for (j = 0; j < 2; j++) {
int len;
/*
* Write some test data. It should never take more than 2 attempts
* (the first one might be a retryable fail).
*/
for (ret = -1, i = 0, len = 0; len != sizeof(testdata) && i < 2;
i++) {
ret = SSL_write(clientssl, testdata + len,
sizeof(testdata) - len);
if (ret > 0) {
len += ret;
} else {
int ssl_error = SSL_get_error(clientssl, ret);
if (!TEST_false(ssl_error == SSL_ERROR_SYSCALL ||
ssl_error == SSL_ERROR_SSL))
goto end;
}
}
if (!TEST_size_t_eq(len, sizeof(testdata)))
goto end;
/*
* Now read the test data. It may take more attempts here because
* it could fail once for each byte read, including all overhead
* bytes from the record header/padding etc.
*/
for (ret = -1, i = 0, len = 0; len != sizeof(testdata) &&
i < MAX_ATTEMPTS; i++) {
ret = SSL_read(serverssl, buf + len, sizeof(buf) - len);
if (ret > 0) {
len += ret;
} else {
int ssl_error = SSL_get_error(serverssl, ret);
if (!TEST_false(ssl_error == SSL_ERROR_SYSCALL ||
ssl_error == SSL_ERROR_SSL))
goto end;
}
}
if (!TEST_mem_eq(testdata, sizeof(testdata), buf, len))
goto end;
}
/* Also frees the BIOs */
SSL_free(clientssl);
SSL_free(serverssl);
clientssl = serverssl = NULL;
testresult = 1;
end:
SSL_free(clientssl);
SSL_free(serverssl);
SSL_CTX_free(clientctx);
SSL_CTX_free(serverctx);
return testresult;
}
OPT_TEST_DECLARE_USAGE("certname privkey\n")
int setup_tests(void)
{
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
if (!TEST_ptr(cert = test_get_argument(0))
|| !TEST_ptr(privkey = test_get_argument(1)))
return 0;
ADD_ALL_TESTS(test_asyncio, 2);
return 1;
}
void cleanup_tests(void)
{
BIO_meth_free(methods_async);
}
| 12,584 | 29.107656 | 79 | c |
openssl | openssl-master/test/asynctest.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
*/
#ifdef _WIN32
# include <windows.h>
#endif
#include <stdio.h>
#include <string.h>
#include <openssl/async.h>
#include <openssl/crypto.h>
static int ctr = 0;
static ASYNC_JOB *currjob = NULL;
static int custom_alloc_used = 0;
static int custom_free_used = 0;
static int only_pause(void *args)
{
ASYNC_pause_job();
return 1;
}
static int add_two(void *args)
{
ctr++;
ASYNC_pause_job();
ctr++;
return 2;
}
static int save_current(void *args)
{
currjob = ASYNC_get_current_job();
ASYNC_pause_job();
return 1;
}
static int change_deflt_libctx(void *args)
{
OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new();
OSSL_LIB_CTX *oldctx, *tmpctx;
int ret = 0;
if (libctx == NULL)
return 0;
oldctx = OSSL_LIB_CTX_set0_default(libctx);
ASYNC_pause_job();
/* Check the libctx is set up as we expect */
tmpctx = OSSL_LIB_CTX_set0_default(oldctx);
if (tmpctx != libctx)
goto err;
/* Set it back again to continue to use our own libctx */
oldctx = OSSL_LIB_CTX_set0_default(libctx);
ASYNC_pause_job();
/* Check the libctx is set up as we expect */
tmpctx = OSSL_LIB_CTX_set0_default(oldctx);
if (tmpctx != libctx)
goto err;
ret = 1;
err:
OSSL_LIB_CTX_free(libctx);
return ret;
}
#define MAGIC_WAIT_FD ((OSSL_ASYNC_FD)99)
static int waitfd(void *args)
{
ASYNC_JOB *job;
ASYNC_WAIT_CTX *waitctx;
job = ASYNC_get_current_job();
if (job == NULL)
return 0;
waitctx = ASYNC_get_wait_ctx(job);
if (waitctx == NULL)
return 0;
/* First case: no fd added or removed */
ASYNC_pause_job();
/* Second case: one fd added */
if (!ASYNC_WAIT_CTX_set_wait_fd(waitctx, waitctx, MAGIC_WAIT_FD, NULL, NULL))
return 0;
ASYNC_pause_job();
/* Third case: all fd removed */
if (!ASYNC_WAIT_CTX_clear_fd(waitctx, waitctx))
return 0;
ASYNC_pause_job();
/* Last case: fd added and immediately removed */
if (!ASYNC_WAIT_CTX_set_wait_fd(waitctx, waitctx, MAGIC_WAIT_FD, NULL, NULL))
return 0;
if (!ASYNC_WAIT_CTX_clear_fd(waitctx, waitctx))
return 0;
return 1;
}
static int blockpause(void *args)
{
ASYNC_block_pause();
ASYNC_pause_job();
ASYNC_unblock_pause();
ASYNC_pause_job();
return 1;
}
static int test_ASYNC_init_thread(void)
{
ASYNC_JOB *job1 = NULL, *job2 = NULL, *job3 = NULL;
int funcret1, funcret2, funcret3;
ASYNC_WAIT_CTX *waitctx = NULL;
if ( !ASYNC_init_thread(2, 0)
|| (waitctx = ASYNC_WAIT_CTX_new()) == NULL
|| ASYNC_start_job(&job1, waitctx, &funcret1, only_pause, NULL, 0)
!= ASYNC_PAUSE
|| ASYNC_start_job(&job2, waitctx, &funcret2, only_pause, NULL, 0)
!= ASYNC_PAUSE
|| ASYNC_start_job(&job3, waitctx, &funcret3, only_pause, NULL, 0)
!= ASYNC_NO_JOBS
|| ASYNC_start_job(&job1, waitctx, &funcret1, only_pause, NULL, 0)
!= ASYNC_FINISH
|| ASYNC_start_job(&job3, waitctx, &funcret3, only_pause, NULL, 0)
!= ASYNC_PAUSE
|| ASYNC_start_job(&job2, waitctx, &funcret2, only_pause, NULL, 0)
!= ASYNC_FINISH
|| ASYNC_start_job(&job3, waitctx, &funcret3, only_pause, NULL, 0)
!= ASYNC_FINISH
|| funcret1 != 1
|| funcret2 != 1
|| funcret3 != 1) {
fprintf(stderr, "test_ASYNC_init_thread() failed\n");
ASYNC_WAIT_CTX_free(waitctx);
ASYNC_cleanup_thread();
return 0;
}
ASYNC_WAIT_CTX_free(waitctx);
ASYNC_cleanup_thread();
return 1;
}
static int test_callback(void *arg)
{
printf("callback test pass\n");
return 1;
}
static int test_ASYNC_callback_status(void)
{
ASYNC_WAIT_CTX *waitctx = NULL;
int set_arg = 100;
ASYNC_callback_fn get_callback;
void *get_arg;
int set_status = 1;
if ( !ASYNC_init_thread(1, 0)
|| (waitctx = ASYNC_WAIT_CTX_new()) == NULL
|| ASYNC_WAIT_CTX_set_callback(waitctx, test_callback, (void*)&set_arg)
!= 1
|| ASYNC_WAIT_CTX_get_callback(waitctx, &get_callback, &get_arg)
!= 1
|| test_callback != get_callback
|| get_arg != (void*)&set_arg
|| (*get_callback)(get_arg) != 1
|| ASYNC_WAIT_CTX_set_status(waitctx, set_status) != 1
|| set_status != ASYNC_WAIT_CTX_get_status(waitctx)) {
fprintf(stderr, "test_ASYNC_callback_status() failed\n");
ASYNC_WAIT_CTX_free(waitctx);
ASYNC_cleanup_thread();
return 0;
}
ASYNC_WAIT_CTX_free(waitctx);
ASYNC_cleanup_thread();
return 1;
}
static int test_ASYNC_start_job(void)
{
ASYNC_JOB *job = NULL;
int funcret;
ASYNC_WAIT_CTX *waitctx = NULL;
ctr = 0;
if ( !ASYNC_init_thread(1, 0)
|| (waitctx = ASYNC_WAIT_CTX_new()) == NULL
|| ASYNC_start_job(&job, waitctx, &funcret, add_two, NULL, 0)
!= ASYNC_PAUSE
|| ctr != 1
|| ASYNC_start_job(&job, waitctx, &funcret, add_two, NULL, 0)
!= ASYNC_FINISH
|| ctr != 2
|| funcret != 2) {
fprintf(stderr, "test_ASYNC_start_job() failed\n");
ASYNC_WAIT_CTX_free(waitctx);
ASYNC_cleanup_thread();
return 0;
}
ASYNC_WAIT_CTX_free(waitctx);
ASYNC_cleanup_thread();
return 1;
}
static int test_ASYNC_get_current_job(void)
{
ASYNC_JOB *job = NULL;
int funcret;
ASYNC_WAIT_CTX *waitctx = NULL;
currjob = NULL;
if ( !ASYNC_init_thread(1, 0)
|| (waitctx = ASYNC_WAIT_CTX_new()) == NULL
|| ASYNC_start_job(&job, waitctx, &funcret, save_current, NULL, 0)
!= ASYNC_PAUSE
|| currjob != job
|| ASYNC_start_job(&job, waitctx, &funcret, save_current, NULL, 0)
!= ASYNC_FINISH
|| funcret != 1) {
fprintf(stderr, "test_ASYNC_get_current_job() failed\n");
ASYNC_WAIT_CTX_free(waitctx);
ASYNC_cleanup_thread();
return 0;
}
ASYNC_WAIT_CTX_free(waitctx);
ASYNC_cleanup_thread();
return 1;
}
static int test_ASYNC_WAIT_CTX_get_all_fds(void)
{
ASYNC_JOB *job = NULL;
int funcret;
ASYNC_WAIT_CTX *waitctx = NULL;
OSSL_ASYNC_FD fd = OSSL_BAD_ASYNC_FD, delfd = OSSL_BAD_ASYNC_FD;
size_t numfds, numdelfds;
if ( !ASYNC_init_thread(1, 0)
|| (waitctx = ASYNC_WAIT_CTX_new()) == NULL
/* On first run we're not expecting any wait fds */
|| ASYNC_start_job(&job, waitctx, &funcret, waitfd, NULL, 0)
!= ASYNC_PAUSE
|| !ASYNC_WAIT_CTX_get_all_fds(waitctx, NULL, &numfds)
|| numfds != 0
|| !ASYNC_WAIT_CTX_get_changed_fds(waitctx, NULL, &numfds, NULL,
&numdelfds)
|| numfds != 0
|| numdelfds != 0
/* On second run we're expecting one added fd */
|| ASYNC_start_job(&job, waitctx, &funcret, waitfd, NULL, 0)
!= ASYNC_PAUSE
|| !ASYNC_WAIT_CTX_get_all_fds(waitctx, NULL, &numfds)
|| numfds != 1
|| !ASYNC_WAIT_CTX_get_all_fds(waitctx, &fd, &numfds)
|| fd != MAGIC_WAIT_FD
|| (fd = OSSL_BAD_ASYNC_FD, 0) /* Assign to something else */
|| !ASYNC_WAIT_CTX_get_changed_fds(waitctx, NULL, &numfds, NULL,
&numdelfds)
|| numfds != 1
|| numdelfds != 0
|| !ASYNC_WAIT_CTX_get_changed_fds(waitctx, &fd, &numfds, NULL,
&numdelfds)
|| fd != MAGIC_WAIT_FD
/* On third run we expect one deleted fd */
|| ASYNC_start_job(&job, waitctx, &funcret, waitfd, NULL, 0)
!= ASYNC_PAUSE
|| !ASYNC_WAIT_CTX_get_all_fds(waitctx, NULL, &numfds)
|| numfds != 0
|| !ASYNC_WAIT_CTX_get_changed_fds(waitctx, NULL, &numfds, NULL,
&numdelfds)
|| numfds != 0
|| numdelfds != 1
|| !ASYNC_WAIT_CTX_get_changed_fds(waitctx, NULL, &numfds, &delfd,
&numdelfds)
|| delfd != MAGIC_WAIT_FD
/* On last run we are not expecting any wait fd */
|| ASYNC_start_job(&job, waitctx, &funcret, waitfd, NULL, 0)
!= ASYNC_FINISH
|| !ASYNC_WAIT_CTX_get_all_fds(waitctx, NULL, &numfds)
|| numfds != 0
|| !ASYNC_WAIT_CTX_get_changed_fds(waitctx, NULL, &numfds, NULL,
&numdelfds)
|| numfds != 0
|| numdelfds != 0
|| funcret != 1) {
fprintf(stderr, "test_ASYNC_get_wait_fd() failed\n");
ASYNC_WAIT_CTX_free(waitctx);
ASYNC_cleanup_thread();
return 0;
}
ASYNC_WAIT_CTX_free(waitctx);
ASYNC_cleanup_thread();
return 1;
}
static int test_ASYNC_block_pause(void)
{
ASYNC_JOB *job = NULL;
int funcret;
ASYNC_WAIT_CTX *waitctx = NULL;
if ( !ASYNC_init_thread(1, 0)
|| (waitctx = ASYNC_WAIT_CTX_new()) == NULL
|| ASYNC_start_job(&job, waitctx, &funcret, blockpause, NULL, 0)
!= ASYNC_PAUSE
|| ASYNC_start_job(&job, waitctx, &funcret, blockpause, NULL, 0)
!= ASYNC_FINISH
|| funcret != 1) {
fprintf(stderr, "test_ASYNC_block_pause() failed\n");
ASYNC_WAIT_CTX_free(waitctx);
ASYNC_cleanup_thread();
return 0;
}
ASYNC_WAIT_CTX_free(waitctx);
ASYNC_cleanup_thread();
return 1;
}
static int test_ASYNC_start_job_ex(void)
{
ASYNC_JOB *job = NULL;
int funcret;
ASYNC_WAIT_CTX *waitctx = NULL;
OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new();
OSSL_LIB_CTX *oldctx, *tmpctx, *globalctx;
int ret = 0;
if (libctx == NULL) {
fprintf(stderr,
"test_ASYNC_start_job_ex() failed to create libctx\n");
goto err;
}
globalctx = oldctx = OSSL_LIB_CTX_set0_default(libctx);
if ((waitctx = ASYNC_WAIT_CTX_new()) == NULL
|| ASYNC_start_job(&job, waitctx, &funcret, change_deflt_libctx,
NULL, 0)
!= ASYNC_PAUSE) {
fprintf(stderr,
"test_ASYNC_start_job_ex() failed to start job\n");
goto err;
}
/* Reset the libctx temporarily to find out what it is*/
tmpctx = OSSL_LIB_CTX_set0_default(oldctx);
oldctx = OSSL_LIB_CTX_set0_default(tmpctx);
if (tmpctx != libctx) {
fprintf(stderr,
"test_ASYNC_start_job_ex() failed - unexpected libctx\n");
goto err;
}
if (ASYNC_start_job(&job, waitctx, &funcret, change_deflt_libctx, NULL, 0)
!= ASYNC_PAUSE) {
fprintf(stderr,
"test_ASYNC_start_job_ex() - restarting job failed\n");
goto err;
}
/* Reset the libctx and continue with the global default libctx */
tmpctx = OSSL_LIB_CTX_set0_default(oldctx);
if (tmpctx != libctx) {
fprintf(stderr,
"test_ASYNC_start_job_ex() failed - unexpected libctx\n");
goto err;
}
if (ASYNC_start_job(&job, waitctx, &funcret, change_deflt_libctx, NULL, 0)
!= ASYNC_FINISH
|| funcret != 1) {
fprintf(stderr,
"test_ASYNC_start_job_ex() - finishing job failed\n");
goto err;
}
/* Reset the libctx temporarily to find out what it is*/
tmpctx = OSSL_LIB_CTX_set0_default(libctx);
OSSL_LIB_CTX_set0_default(tmpctx);
if (tmpctx != globalctx) {
fprintf(stderr,
"test_ASYNC_start_job_ex() failed - global libctx check failed\n");
goto err;
}
ret = 1;
err:
ASYNC_WAIT_CTX_free(waitctx);
ASYNC_cleanup_thread();
OSSL_LIB_CTX_free(libctx);
return ret;
}
static void *test_alloc_stack(size_t *num)
{
custom_alloc_used = 1;
return OPENSSL_malloc(*num);
}
static void test_free_stack(void *addr)
{
custom_free_used = 1;
OPENSSL_free(addr);
}
static int test_ASYNC_set_mem_functions(void)
{
ASYNC_stack_alloc_fn alloc_fn;
ASYNC_stack_free_fn free_fn;
/* Not all platforms support this */
if (ASYNC_set_mem_functions(test_alloc_stack, test_free_stack) == 0) return 1;
ASYNC_get_mem_functions(&alloc_fn, &free_fn);
if ((alloc_fn != test_alloc_stack) || (free_fn != test_free_stack)) {
fprintf(stderr,
"test_ASYNC_set_mem_functions() - setting and retrieving custom allocators failed\n");
return 0;
}
if (!ASYNC_init_thread(1, 1)) {
fprintf(stderr,
"test_ASYNC_set_mem_functions() - failed initialising ctx pool\n");
return 0;
}
ASYNC_cleanup_thread();
if (!custom_alloc_used || !custom_free_used) {
fprintf(stderr,
"test_ASYNC_set_mem_functions() - custom allocation functions not used\n");
return 0;
}
return 1;
}
int main(int argc, char **argv)
{
if (!ASYNC_is_capable()) {
fprintf(stderr,
"OpenSSL build is not ASYNC capable - skipping async tests\n");
} else {
if (!test_ASYNC_init_thread()
|| !test_ASYNC_callback_status()
|| !test_ASYNC_start_job()
|| !test_ASYNC_get_current_job()
|| !test_ASYNC_WAIT_CTX_get_all_fds()
|| !test_ASYNC_block_pause()
|| !test_ASYNC_start_job_ex()
|| !test_ASYNC_set_mem_functions()) {
return 1;
}
}
printf("PASS\n");
return 0;
}
| 14,326 | 28.60124 | 102 | c |
openssl | openssl-master/test/bad_dtls_test.c | /*
* Copyright 2016-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
*/
/*
* Unit test for Cisco DTLS1_BAD_VER session resume, as used by
* AnyConnect VPN protocol.
*
* This is designed to exercise the code paths in
* http://git.infradead.org/users/dwmw2/openconnect.git/blob/HEAD:/dtls.c
* which have frequently been affected by regressions in DTLS1_BAD_VER
* support.
*
* Note that unlike other SSL tests, we don't test against our own SSL
* server method. Firstly because we don't have one; we *only* support
* DTLS1_BAD_VER as a client. And secondly because even if that were
* fixed up it's the wrong thing to test against - because if changes
* are made in generic DTLS code which don't take DTLS1_BAD_VER into
* account, there's plenty of scope for making those changes such that
* they break *both* the client and the server in the same way.
*
* So we handle the server side manually. In a session resume there isn't
* much to be done anyway.
*/
#include <string.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include <openssl/opensslconf.h>
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/kdf.h>
#include "internal/packet.h"
#include "internal/nelem.h"
#include "testutil.h"
/* For DTLS1_BAD_VER packets the MAC doesn't include the handshake header */
#define MAC_OFFSET (DTLS1_RT_HEADER_LENGTH + DTLS1_HM_HEADER_LENGTH)
static unsigned char client_random[SSL3_RANDOM_SIZE];
static unsigned char server_random[SSL3_RANDOM_SIZE];
/* These are all generated locally, sized purely according to our own whim */
static unsigned char session_id[32];
static unsigned char master_secret[48];
static unsigned char cookie[20];
/* We've hard-coded the cipher suite; we know it's 104 bytes */
static unsigned char key_block[104];
#define mac_key (key_block + 20)
#define dec_key (key_block + 40)
#define enc_key (key_block + 56)
static EVP_MD_CTX *handshake_md;
static int do_PRF(const void *seed1, int seed1_len,
const void *seed2, int seed2_len,
const void *seed3, int seed3_len,
unsigned char *out, int olen)
{
EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1_PRF, NULL);
size_t outlen = olen;
/* No error handling. If it all screws up, the test will fail anyway */
EVP_PKEY_derive_init(pctx);
EVP_PKEY_CTX_set_tls1_prf_md(pctx, EVP_md5_sha1());
EVP_PKEY_CTX_set1_tls1_prf_secret(pctx, master_secret, sizeof(master_secret));
EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed1, seed1_len);
EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed2, seed2_len);
EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed3, seed3_len);
EVP_PKEY_derive(pctx, out, &outlen);
EVP_PKEY_CTX_free(pctx);
return 1;
}
static SSL_SESSION *client_session(void)
{
static unsigned char session_asn1[] = {
0x30, 0x5F, /* SEQUENCE, length 0x5F */
0x02, 0x01, 0x01, /* INTEGER, SSL_SESSION_ASN1_VERSION */
0x02, 0x02, 0x01, 0x00, /* INTEGER, DTLS1_BAD_VER */
0x04, 0x02, 0x00, 0x2F, /* OCTET_STRING, AES128-SHA */
0x04, 0x20, /* OCTET_STRING, session id */
#define SS_SESSID_OFS 15 /* Session ID goes here */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x04, 0x30, /* OCTET_STRING, master secret */
#define SS_SECRET_OFS 49 /* Master secret goes here */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
const unsigned char *p = session_asn1;
/* Copy the randomly-generated fields into the above ASN1 */
memcpy(session_asn1 + SS_SESSID_OFS, session_id, sizeof(session_id));
memcpy(session_asn1 + SS_SECRET_OFS, master_secret, sizeof(master_secret));
return d2i_SSL_SESSION(NULL, &p, sizeof(session_asn1));
}
/* Returns 1 for initial ClientHello, 2 for ClientHello with cookie */
static int validate_client_hello(BIO *wbio)
{
PACKET pkt, pkt2;
long len;
unsigned char *data;
int cookie_found = 0;
unsigned int u = 0;
if ((len = BIO_get_mem_data(wbio, (char **)&data)) < 0)
return 0;
if (!PACKET_buf_init(&pkt, data, len))
return 0;
/* Check record header type */
if (!PACKET_get_1(&pkt, &u) || u != SSL3_RT_HANDSHAKE)
return 0;
/* Version */
if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER)
return 0;
/* Skip the rest of the record header */
if (!PACKET_forward(&pkt, DTLS1_RT_HEADER_LENGTH - 3))
return 0;
/* Check it's a ClientHello */
if (!PACKET_get_1(&pkt, &u) || u != SSL3_MT_CLIENT_HELLO)
return 0;
/* Skip the rest of the handshake message header */
if (!PACKET_forward(&pkt, DTLS1_HM_HEADER_LENGTH - 1))
return 0;
/* Check client version */
if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER)
return 0;
/* Store random */
if (!PACKET_copy_bytes(&pkt, client_random, SSL3_RANDOM_SIZE))
return 0;
/* Check session id length and content */
if (!PACKET_get_length_prefixed_1(&pkt, &pkt2) ||
!PACKET_equal(&pkt2, session_id, sizeof(session_id)))
return 0;
/* Check cookie */
if (!PACKET_get_length_prefixed_1(&pkt, &pkt2))
return 0;
if (PACKET_remaining(&pkt2)) {
if (!PACKET_equal(&pkt2, cookie, sizeof(cookie)))
return 0;
cookie_found = 1;
}
/* Skip ciphers */
if (!PACKET_get_net_2(&pkt, &u) || !PACKET_forward(&pkt, u))
return 0;
/* Skip compression */
if (!PACKET_get_1(&pkt, &u) || !PACKET_forward(&pkt, u))
return 0;
/* Skip extensions */
if (!PACKET_get_net_2(&pkt, &u) || !PACKET_forward(&pkt, u))
return 0;
/* Now we are at the end */
if (PACKET_remaining(&pkt))
return 0;
/* Update handshake MAC for second ClientHello (with cookie) */
if (cookie_found && !EVP_DigestUpdate(handshake_md, data + MAC_OFFSET,
len - MAC_OFFSET))
return 0;
(void)BIO_reset(wbio);
return 1 + cookie_found;
}
static int send_hello_verify(BIO *rbio)
{
static unsigned char hello_verify[] = {
0x16, /* Handshake */
0x01, 0x00, /* DTLS1_BAD_VER */
0x00, 0x00, /* Epoch 0 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Seq# 0 */
0x00, 0x23, /* Length */
0x03, /* Hello Verify */
0x00, 0x00, 0x17, /* Length */
0x00, 0x00, /* Seq# 0 */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x17, /* Fragment length */
0x01, 0x00, /* DTLS1_BAD_VER */
0x14, /* Cookie length */
#define HV_COOKIE_OFS 28 /* Cookie goes here */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
};
memcpy(hello_verify + HV_COOKIE_OFS, cookie, sizeof(cookie));
BIO_write(rbio, hello_verify, sizeof(hello_verify));
return 1;
}
static int send_server_hello(BIO *rbio)
{
static unsigned char server_hello[] = {
0x16, /* Handshake */
0x01, 0x00, /* DTLS1_BAD_VER */
0x00, 0x00, /* Epoch 0 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, /* Seq# 1 */
0x00, 0x52, /* Length */
0x02, /* Server Hello */
0x00, 0x00, 0x46, /* Length */
0x00, 0x01, /* Seq# */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x46, /* Fragment length */
0x01, 0x00, /* DTLS1_BAD_VER */
#define SH_RANDOM_OFS 27 /* Server random goes here */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x20, /* Session ID length */
#define SH_SESSID_OFS 60 /* Session ID goes here */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x2f, /* Cipher suite AES128-SHA */
0x00, /* Compression null */
};
static unsigned char change_cipher_spec[] = {
0x14, /* Change Cipher Spec */
0x01, 0x00, /* DTLS1_BAD_VER */
0x00, 0x00, /* Epoch 0 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x02, /* Seq# 2 */
0x00, 0x03, /* Length */
0x01, 0x00, 0x02, /* Message */
};
memcpy(server_hello + SH_RANDOM_OFS, server_random, sizeof(server_random));
memcpy(server_hello + SH_SESSID_OFS, session_id, sizeof(session_id));
if (!EVP_DigestUpdate(handshake_md, server_hello + MAC_OFFSET,
sizeof(server_hello) - MAC_OFFSET))
return 0;
BIO_write(rbio, server_hello, sizeof(server_hello));
BIO_write(rbio, change_cipher_spec, sizeof(change_cipher_spec));
return 1;
}
/* Create header, HMAC, pad, encrypt and send a record */
static int send_record(BIO *rbio, unsigned char type, uint64_t seqnr,
const void *msg, size_t len)
{
/* Note that the order of the record header fields on the wire,
* and in the HMAC, is different. So we just keep them in separate
* variables and handle them individually. */
static unsigned char epoch[2] = { 0x00, 0x01 };
static unsigned char seq[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
static unsigned char ver[2] = { 0x01, 0x00 }; /* DTLS1_BAD_VER */
unsigned char lenbytes[2];
EVP_MAC *hmac = NULL;
EVP_MAC_CTX *ctx = NULL;
EVP_CIPHER_CTX *enc_ctx = NULL;
unsigned char iv[16];
unsigned char pad;
unsigned char *enc;
OSSL_PARAM params[2];
int ret = 0;
seq[0] = (seqnr >> 40) & 0xff;
seq[1] = (seqnr >> 32) & 0xff;
seq[2] = (seqnr >> 24) & 0xff;
seq[3] = (seqnr >> 16) & 0xff;
seq[4] = (seqnr >> 8) & 0xff;
seq[5] = seqnr & 0xff;
pad = 15 - ((len + SHA_DIGEST_LENGTH) % 16);
enc = OPENSSL_malloc(len + SHA_DIGEST_LENGTH + 1 + pad);
if (enc == NULL)
return 0;
/* Copy record to encryption buffer */
memcpy(enc, msg, len);
/* Append HMAC to data */
if (!TEST_ptr(hmac = EVP_MAC_fetch(NULL, "HMAC", NULL))
|| !TEST_ptr(ctx = EVP_MAC_CTX_new(hmac)))
goto end;
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
"SHA1", 0);
params[1] = OSSL_PARAM_construct_end();
lenbytes[0] = (unsigned char)(len >> 8);
lenbytes[1] = (unsigned char)(len);
if (!EVP_MAC_init(ctx, mac_key, 20, params)
|| !EVP_MAC_update(ctx, epoch, 2)
|| !EVP_MAC_update(ctx, seq, 6)
|| !EVP_MAC_update(ctx, &type, 1)
|| !EVP_MAC_update(ctx, ver, 2) /* Version */
|| !EVP_MAC_update(ctx, lenbytes, 2) /* Length */
|| !EVP_MAC_update(ctx, enc, len) /* Finally the data itself */
|| !EVP_MAC_final(ctx, enc + len, NULL, SHA_DIGEST_LENGTH))
goto end;
/* Append padding bytes */
len += SHA_DIGEST_LENGTH;
do {
enc[len++] = pad;
} while (len % 16);
/* Generate IV, and encrypt */
if (!TEST_int_gt(RAND_bytes(iv, sizeof(iv)), 0)
|| !TEST_ptr(enc_ctx = EVP_CIPHER_CTX_new())
|| !TEST_true(EVP_CipherInit_ex(enc_ctx, EVP_aes_128_cbc(), NULL,
enc_key, iv, 1))
|| !TEST_int_ge(EVP_Cipher(enc_ctx, enc, enc, len), 0))
goto end;
/* Finally write header (from fragmented variables), IV and encrypted record */
BIO_write(rbio, &type, 1);
BIO_write(rbio, ver, 2);
BIO_write(rbio, epoch, 2);
BIO_write(rbio, seq, 6);
lenbytes[0] = (unsigned char)((len + sizeof(iv)) >> 8);
lenbytes[1] = (unsigned char)(len + sizeof(iv));
BIO_write(rbio, lenbytes, 2);
BIO_write(rbio, iv, sizeof(iv));
BIO_write(rbio, enc, len);
ret = 1;
end:
EVP_MAC_free(hmac);
EVP_MAC_CTX_free(ctx);
EVP_CIPHER_CTX_free(enc_ctx);
OPENSSL_free(enc);
return ret;
}
static int send_finished(SSL *s, BIO *rbio)
{
static unsigned char finished_msg[DTLS1_HM_HEADER_LENGTH +
TLS1_FINISH_MAC_LENGTH] = {
0x14, /* Finished */
0x00, 0x00, 0x0c, /* Length */
0x00, 0x03, /* Seq# 3 */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x0c, /* Fragment length */
/* Finished MAC (12 bytes) */
};
unsigned char handshake_hash[EVP_MAX_MD_SIZE];
/* Derive key material */
do_PRF(TLS_MD_KEY_EXPANSION_CONST, TLS_MD_KEY_EXPANSION_CONST_SIZE,
server_random, SSL3_RANDOM_SIZE,
client_random, SSL3_RANDOM_SIZE,
key_block, sizeof(key_block));
/* Generate Finished MAC */
if (!EVP_DigestFinal_ex(handshake_md, handshake_hash, NULL))
return 0;
do_PRF(TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
handshake_hash, EVP_MD_CTX_get_size(handshake_md),
NULL, 0,
finished_msg + DTLS1_HM_HEADER_LENGTH, TLS1_FINISH_MAC_LENGTH);
return send_record(rbio, SSL3_RT_HANDSHAKE, 0,
finished_msg, sizeof(finished_msg));
}
static int validate_ccs(BIO *wbio)
{
PACKET pkt;
long len;
unsigned char *data;
unsigned int u;
len = BIO_get_mem_data(wbio, (char **)&data);
if (len < 0)
return 0;
if (!PACKET_buf_init(&pkt, data, len))
return 0;
/* Check record header type */
if (!PACKET_get_1(&pkt, &u) || u != SSL3_RT_CHANGE_CIPHER_SPEC)
return 0;
/* Version */
if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER)
return 0;
/* Skip the rest of the record header */
if (!PACKET_forward(&pkt, DTLS1_RT_HEADER_LENGTH - 3))
return 0;
/* Check ChangeCipherSpec message */
if (!PACKET_get_1(&pkt, &u) || u != SSL3_MT_CCS)
return 0;
/* A DTLS1_BAD_VER ChangeCipherSpec also contains the
* handshake sequence number (which is 2 here) */
if (!PACKET_get_net_2(&pkt, &u) || u != 0x0002)
return 0;
/* Now check the Finished packet */
if (!PACKET_get_1(&pkt, &u) || u != SSL3_RT_HANDSHAKE)
return 0;
if (!PACKET_get_net_2(&pkt, &u) || u != DTLS1_BAD_VER)
return 0;
/* Check epoch is now 1 */
if (!PACKET_get_net_2(&pkt, &u) || u != 0x0001)
return 0;
/* That'll do for now. If OpenSSL accepted *our* Finished packet
* then it's evidently remembered that DTLS1_BAD_VER doesn't
* include the handshake header in the MAC. There's not a lot of
* point in implementing decryption here, just to check that it
* continues to get it right for one more packet. */
return 1;
}
#define NODROP(x) { x##UL, 0 }
#define DROP(x) { x##UL, 1 }
static struct {
uint64_t seq;
int drop;
} tests[] = {
NODROP(1), NODROP(3), NODROP(2),
NODROP(0x1234), NODROP(0x1230), NODROP(0x1235),
NODROP(0xffff), NODROP(0x10001), NODROP(0xfffe), NODROP(0x10000),
DROP(0x10001), DROP(0xff), NODROP(0x100000), NODROP(0x800000), NODROP(0x7fffe1),
NODROP(0xffffff), NODROP(0x1000000), NODROP(0xfffffe), DROP(0xffffff), NODROP(0x1000010),
NODROP(0xfffffd), NODROP(0x1000011), DROP(0x12), NODROP(0x1000012),
NODROP(0x1ffffff), NODROP(0x2000000), DROP(0x1ff00fe), NODROP(0x2000001),
NODROP(0x20fffff), NODROP(0x2105500), DROP(0x20ffffe), NODROP(0x21054ff),
NODROP(0x211ffff), DROP(0x2110000), NODROP(0x2120000)
/* The last test should be NODROP, because a DROP wouldn't get tested. */
};
static int test_bad_dtls(void)
{
SSL_SESSION *sess = NULL;
SSL_CTX *ctx = NULL;
SSL *con = NULL;
BIO *rbio = NULL;
BIO *wbio = NULL;
time_t now = 0;
int testresult = 0;
int ret;
int i;
RAND_bytes(session_id, sizeof(session_id));
RAND_bytes(master_secret, sizeof(master_secret));
RAND_bytes(cookie, sizeof(cookie));
RAND_bytes(server_random + 4, sizeof(server_random) - 4);
now = time(NULL);
memcpy(server_random, &now, sizeof(now));
sess = client_session();
if (!TEST_ptr(sess))
goto end;
handshake_md = EVP_MD_CTX_new();
if (!TEST_ptr(handshake_md)
|| !TEST_true(EVP_DigestInit_ex(handshake_md, EVP_md5_sha1(),
NULL)))
goto end;
ctx = SSL_CTX_new(DTLS_client_method());
if (!TEST_ptr(ctx)
|| !TEST_true(SSL_CTX_set_min_proto_version(ctx, DTLS1_BAD_VER))
|| !TEST_true(SSL_CTX_set_max_proto_version(ctx, DTLS1_BAD_VER))
|| !TEST_true(SSL_CTX_set_options(ctx,
SSL_OP_LEGACY_SERVER_CONNECT))
|| !TEST_true(SSL_CTX_set_cipher_list(ctx, "AES128-SHA")))
goto end;
SSL_CTX_set_security_level(ctx, 0);
con = SSL_new(ctx);
if (!TEST_ptr(con)
|| !TEST_true(SSL_set_session(con, sess)))
goto end;
SSL_SESSION_free(sess);
rbio = BIO_new(BIO_s_mem());
wbio = BIO_new(BIO_s_mem());
if (!TEST_ptr(rbio)
|| !TEST_ptr(wbio))
goto end;
SSL_set_bio(con, rbio, wbio);
if (!TEST_true(BIO_up_ref(rbio))) {
/*
* We can't up-ref but we assigned ownership to con, so we shouldn't
* free in the "end" block
*/
rbio = wbio = NULL;
goto end;
}
if (!TEST_true(BIO_up_ref(wbio))) {
wbio = NULL;
goto end;
}
SSL_set_connect_state(con);
/* Send initial ClientHello */
ret = SSL_do_handshake(con);
if (!TEST_int_le(ret, 0)
|| !TEST_int_eq(SSL_get_error(con, ret), SSL_ERROR_WANT_READ)
|| !TEST_int_eq(validate_client_hello(wbio), 1)
|| !TEST_true(send_hello_verify(rbio)))
goto end;
ret = SSL_do_handshake(con);
if (!TEST_int_le(ret, 0)
|| !TEST_int_eq(SSL_get_error(con, ret), SSL_ERROR_WANT_READ)
|| !TEST_int_eq(validate_client_hello(wbio), 2)
|| !TEST_true(send_server_hello(rbio)))
goto end;
ret = SSL_do_handshake(con);
if (!TEST_int_le(ret, 0)
|| !TEST_int_eq(SSL_get_error(con, ret), SSL_ERROR_WANT_READ)
|| !TEST_true(send_finished(con, rbio)))
goto end;
ret = SSL_do_handshake(con);
if (!TEST_int_gt(ret, 0)
|| !TEST_true(validate_ccs(wbio)))
goto end;
/* While we're here and crafting packets by hand, we might as well do a
bit of a stress test on the DTLS record replay handling. Not Cisco-DTLS
specific but useful anyway for the general case. It's been broken
before, and in fact was broken even for a basic 0, 2, 1 test case
when this test was first added.... */
for (i = 0; i < (int)OSSL_NELEM(tests); i++) {
uint64_t recv_buf[2];
if (!TEST_true(send_record(rbio, SSL3_RT_APPLICATION_DATA, tests[i].seq,
&tests[i].seq, sizeof(uint64_t)))) {
TEST_error("Failed to send data seq #0x%x%08x (%d)\n",
(unsigned int)(tests[i].seq >> 32), (unsigned int)tests[i].seq, i);
goto end;
}
if (tests[i].drop)
continue;
ret = SSL_read(con, recv_buf, 2 * sizeof(uint64_t));
if (!TEST_int_eq(ret, (int)sizeof(uint64_t))) {
TEST_error("SSL_read failed or wrong size on seq#0x%x%08x (%d)\n",
(unsigned int)(tests[i].seq >> 32), (unsigned int)tests[i].seq, i);
goto end;
}
if (!TEST_true(recv_buf[0] == tests[i].seq))
goto end;
}
/* The last test cannot be DROP() */
if (!TEST_false(tests[i-1].drop))
goto end;
testresult = 1;
end:
BIO_free(rbio);
BIO_free(wbio);
SSL_free(con);
SSL_CTX_free(ctx);
EVP_MD_CTX_free(handshake_md);
return testresult;
}
int setup_tests(void)
{
ADD_TEST(test_bad_dtls);
return 1;
}
| 20,843 | 33.226601 | 93 | c |
openssl | openssl-master/test/bftest.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 <stdlib.h>
#include <openssl/opensslconf.h> /* To see if OPENSSL_NO_BF is defined */
#include "testutil.h"
#include "internal/nelem.h"
#ifndef OPENSSL_NO_BF
# include <openssl/blowfish.h>
# ifdef CHARSET_EBCDIC
# include <openssl/ebcdic.h>
# endif
static char bf_key[2][30] = {
"abcdefghijklmnopqrstuvwxyz",
"Who is John Galt?"
};
/* big endian */
static BF_LONG bf_plain[2][2] = {
{0x424c4f57L, 0x46495348L},
{0xfedcba98L, 0x76543210L}
};
static BF_LONG bf_cipher[2][2] = {
{0x324ed0feL, 0xf413a203L},
{0xcc91732bL, 0x8022f684L}
};
/************/
/* Lets use the DES test vectors :-) */
# define NUM_TESTS 34
static unsigned char ecb_data[NUM_TESTS][8] = {
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10},
{0x7C, 0xA1, 0x10, 0x45, 0x4A, 0x1A, 0x6E, 0x57},
{0x01, 0x31, 0xD9, 0x61, 0x9D, 0xC1, 0x37, 0x6E},
{0x07, 0xA1, 0x13, 0x3E, 0x4A, 0x0B, 0x26, 0x86},
{0x38, 0x49, 0x67, 0x4C, 0x26, 0x02, 0x31, 0x9E},
{0x04, 0xB9, 0x15, 0xBA, 0x43, 0xFE, 0xB5, 0xB6},
{0x01, 0x13, 0xB9, 0x70, 0xFD, 0x34, 0xF2, 0xCE},
{0x01, 0x70, 0xF1, 0x75, 0x46, 0x8F, 0xB5, 0xE6},
{0x43, 0x29, 0x7F, 0xAD, 0x38, 0xE3, 0x73, 0xFE},
{0x07, 0xA7, 0x13, 0x70, 0x45, 0xDA, 0x2A, 0x16},
{0x04, 0x68, 0x91, 0x04, 0xC2, 0xFD, 0x3B, 0x2F},
{0x37, 0xD0, 0x6B, 0xB5, 0x16, 0xCB, 0x75, 0x46},
{0x1F, 0x08, 0x26, 0x0D, 0x1A, 0xC2, 0x46, 0x5E},
{0x58, 0x40, 0x23, 0x64, 0x1A, 0xBA, 0x61, 0x76},
{0x02, 0x58, 0x16, 0x16, 0x46, 0x29, 0xB0, 0x07},
{0x49, 0x79, 0x3E, 0xBC, 0x79, 0xB3, 0x25, 0x8F},
{0x4F, 0xB0, 0x5E, 0x15, 0x15, 0xAB, 0x73, 0xA7},
{0x49, 0xE9, 0x5D, 0x6D, 0x4C, 0xA2, 0x29, 0xBF},
{0x01, 0x83, 0x10, 0xDC, 0x40, 0x9B, 0x26, 0xD6},
{0x1C, 0x58, 0x7F, 0x1C, 0x13, 0x92, 0x4F, 0xEF},
{0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01},
{0x1F, 0x1F, 0x1F, 0x1F, 0x0E, 0x0E, 0x0E, 0x0E},
{0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1, 0xFE},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10}
};
static unsigned char plain_data[NUM_TESTS][8] = {
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01},
{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11},
{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0x01, 0xA1, 0xD6, 0xD0, 0x39, 0x77, 0x67, 0x42},
{0x5C, 0xD5, 0x4C, 0xA8, 0x3D, 0xEF, 0x57, 0xDA},
{0x02, 0x48, 0xD4, 0x38, 0x06, 0xF6, 0x71, 0x72},
{0x51, 0x45, 0x4B, 0x58, 0x2D, 0xDF, 0x44, 0x0A},
{0x42, 0xFD, 0x44, 0x30, 0x59, 0x57, 0x7F, 0xA2},
{0x05, 0x9B, 0x5E, 0x08, 0x51, 0xCF, 0x14, 0x3A},
{0x07, 0x56, 0xD8, 0xE0, 0x77, 0x47, 0x61, 0xD2},
{0x76, 0x25, 0x14, 0xB8, 0x29, 0xBF, 0x48, 0x6A},
{0x3B, 0xDD, 0x11, 0x90, 0x49, 0x37, 0x28, 0x02},
{0x26, 0x95, 0x5F, 0x68, 0x35, 0xAF, 0x60, 0x9A},
{0x16, 0x4D, 0x5E, 0x40, 0x4F, 0x27, 0x52, 0x32},
{0x6B, 0x05, 0x6E, 0x18, 0x75, 0x9F, 0x5C, 0xCA},
{0x00, 0x4B, 0xD6, 0xEF, 0x09, 0x17, 0x60, 0x62},
{0x48, 0x0D, 0x39, 0x00, 0x6E, 0xE7, 0x62, 0xF2},
{0x43, 0x75, 0x40, 0xC8, 0x69, 0x8F, 0x3C, 0xFA},
{0x07, 0x2D, 0x43, 0xA0, 0x77, 0x07, 0x52, 0x92},
{0x02, 0xFE, 0x55, 0x77, 0x81, 0x17, 0xF1, 0x2A},
{0x1D, 0x9D, 0x5C, 0x50, 0x18, 0xF7, 0x28, 0xC2},
{0x30, 0x55, 0x32, 0x28, 0x6D, 0x6F, 0x29, 0x5A},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}
};
static unsigned char cipher_data[NUM_TESTS][8] = {
{0x4E, 0xF9, 0x97, 0x45, 0x61, 0x98, 0xDD, 0x78},
{0x51, 0x86, 0x6F, 0xD5, 0xB8, 0x5E, 0xCB, 0x8A},
{0x7D, 0x85, 0x6F, 0x9A, 0x61, 0x30, 0x63, 0xF2},
{0x24, 0x66, 0xDD, 0x87, 0x8B, 0x96, 0x3C, 0x9D},
{0x61, 0xF9, 0xC3, 0x80, 0x22, 0x81, 0xB0, 0x96},
{0x7D, 0x0C, 0xC6, 0x30, 0xAF, 0xDA, 0x1E, 0xC7},
{0x4E, 0xF9, 0x97, 0x45, 0x61, 0x98, 0xDD, 0x78},
{0x0A, 0xCE, 0xAB, 0x0F, 0xC6, 0xA0, 0xA2, 0x8D},
{0x59, 0xC6, 0x82, 0x45, 0xEB, 0x05, 0x28, 0x2B},
{0xB1, 0xB8, 0xCC, 0x0B, 0x25, 0x0F, 0x09, 0xA0},
{0x17, 0x30, 0xE5, 0x77, 0x8B, 0xEA, 0x1D, 0xA4},
{0xA2, 0x5E, 0x78, 0x56, 0xCF, 0x26, 0x51, 0xEB},
{0x35, 0x38, 0x82, 0xB1, 0x09, 0xCE, 0x8F, 0x1A},
{0x48, 0xF4, 0xD0, 0x88, 0x4C, 0x37, 0x99, 0x18},
{0x43, 0x21, 0x93, 0xB7, 0x89, 0x51, 0xFC, 0x98},
{0x13, 0xF0, 0x41, 0x54, 0xD6, 0x9D, 0x1A, 0xE5},
{0x2E, 0xED, 0xDA, 0x93, 0xFF, 0xD3, 0x9C, 0x79},
{0xD8, 0x87, 0xE0, 0x39, 0x3C, 0x2D, 0xA6, 0xE3},
{0x5F, 0x99, 0xD0, 0x4F, 0x5B, 0x16, 0x39, 0x69},
{0x4A, 0x05, 0x7A, 0x3B, 0x24, 0xD3, 0x97, 0x7B},
{0x45, 0x20, 0x31, 0xC1, 0xE4, 0xFA, 0xDA, 0x8E},
{0x75, 0x55, 0xAE, 0x39, 0xF5, 0x9B, 0x87, 0xBD},
{0x53, 0xC5, 0x5F, 0x9C, 0xB4, 0x9F, 0xC0, 0x19},
{0x7A, 0x8E, 0x7B, 0xFA, 0x93, 0x7E, 0x89, 0xA3},
{0xCF, 0x9C, 0x5D, 0x7A, 0x49, 0x86, 0xAD, 0xB5},
{0xD1, 0xAB, 0xB2, 0x90, 0x65, 0x8B, 0xC7, 0x78},
{0x55, 0xCB, 0x37, 0x74, 0xD1, 0x3E, 0xF2, 0x01},
{0xFA, 0x34, 0xEC, 0x48, 0x47, 0xB2, 0x68, 0xB2},
{0xA7, 0x90, 0x79, 0x51, 0x08, 0xEA, 0x3C, 0xAE},
{0xC3, 0x9E, 0x07, 0x2D, 0x9F, 0xAC, 0x63, 0x1D},
{0x01, 0x49, 0x33, 0xE0, 0xCD, 0xAF, 0xF6, 0xE4},
{0xF2, 0x1E, 0x9A, 0x77, 0xB7, 0x1C, 0x49, 0xBC},
{0x24, 0x59, 0x46, 0x88, 0x57, 0x54, 0x36, 0x9A},
{0x6B, 0x5C, 0x5A, 0x9C, 0x5D, 0x9E, 0x0A, 0x5A},
};
static unsigned char cbc_key[16] = {
0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,
0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87
};
static unsigned char cbc_iv[8] =
{ 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10 };
static char cbc_data[40] = "7654321 Now is the time for ";
static unsigned char cbc_ok[32] = {
0x6B, 0x77, 0xB4, 0xD6, 0x30, 0x06, 0xDE, 0xE6,
0x05, 0xB1, 0x56, 0xE2, 0x74, 0x03, 0x97, 0x93,
0x58, 0xDE, 0xB9, 0xE7, 0x15, 0x46, 0x16, 0xD9,
0x59, 0xF1, 0x65, 0x2B, 0xD5, 0xFF, 0x92, 0xCC
};
static unsigned char cfb64_ok[] = {
0xE7, 0x32, 0x14, 0xA2, 0x82, 0x21, 0x39, 0xCA,
0xF2, 0x6E, 0xCF, 0x6D, 0x2E, 0xB9, 0xE7, 0x6E,
0x3D, 0xA3, 0xDE, 0x04, 0xD1, 0x51, 0x72, 0x00,
0x51, 0x9D, 0x57, 0xA6, 0xC3
};
static unsigned char ofb64_ok[] = {
0xE7, 0x32, 0x14, 0xA2, 0x82, 0x21, 0x39, 0xCA,
0x62, 0xB3, 0x43, 0xCC, 0x5B, 0x65, 0x58, 0x73,
0x10, 0xDD, 0x90, 0x8D, 0x0C, 0x24, 0x1B, 0x22,
0x63, 0xC2, 0xCF, 0x80, 0xDA
};
# define KEY_TEST_NUM 25
static unsigned char key_test[KEY_TEST_NUM] = {
0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87,
0x78, 0x69, 0x5a, 0x4b, 0x3c, 0x2d, 0x1e, 0x0f,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
0x88
};
static unsigned char key_data[8] =
{ 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10 };
static unsigned char key_out[KEY_TEST_NUM][8] = {
{0xF9, 0xAD, 0x59, 0x7C, 0x49, 0xDB, 0x00, 0x5E},
{0xE9, 0x1D, 0x21, 0xC1, 0xD9, 0x61, 0xA6, 0xD6},
{0xE9, 0xC2, 0xB7, 0x0A, 0x1B, 0xC6, 0x5C, 0xF3},
{0xBE, 0x1E, 0x63, 0x94, 0x08, 0x64, 0x0F, 0x05},
{0xB3, 0x9E, 0x44, 0x48, 0x1B, 0xDB, 0x1E, 0x6E},
{0x94, 0x57, 0xAA, 0x83, 0xB1, 0x92, 0x8C, 0x0D},
{0x8B, 0xB7, 0x70, 0x32, 0xF9, 0x60, 0x62, 0x9D},
{0xE8, 0x7A, 0x24, 0x4E, 0x2C, 0xC8, 0x5E, 0x82},
{0x15, 0x75, 0x0E, 0x7A, 0x4F, 0x4E, 0xC5, 0x77},
{0x12, 0x2B, 0xA7, 0x0B, 0x3A, 0xB6, 0x4A, 0xE0},
{0x3A, 0x83, 0x3C, 0x9A, 0xFF, 0xC5, 0x37, 0xF6},
{0x94, 0x09, 0xDA, 0x87, 0xA9, 0x0F, 0x6B, 0xF2},
{0x88, 0x4F, 0x80, 0x62, 0x50, 0x60, 0xB8, 0xB4},
{0x1F, 0x85, 0x03, 0x1C, 0x19, 0xE1, 0x19, 0x68},
{0x79, 0xD9, 0x37, 0x3A, 0x71, 0x4C, 0xA3, 0x4F},
{0x93, 0x14, 0x28, 0x87, 0xEE, 0x3B, 0xE1, 0x5C},
{0x03, 0x42, 0x9E, 0x83, 0x8C, 0xE2, 0xD1, 0x4B},
{0xA4, 0x29, 0x9E, 0x27, 0x46, 0x9F, 0xF6, 0x7B},
{0xAF, 0xD5, 0xAE, 0xD1, 0xC1, 0xBC, 0x96, 0xA8},
{0x10, 0x85, 0x1C, 0x0E, 0x38, 0x58, 0xDA, 0x9F},
{0xE6, 0xF5, 0x1E, 0xD7, 0x9B, 0x9D, 0xB2, 0x1F},
{0x64, 0xA6, 0xE1, 0x4A, 0xFD, 0x36, 0xB4, 0x6F},
{0x80, 0xC7, 0xD7, 0xD4, 0x5A, 0x54, 0x79, 0xAD},
{0x05, 0x04, 0x4B, 0x62, 0xFA, 0x52, 0xD0, 0x80},
};
static int print_test_data(void)
{
unsigned int i, j;
printf("ecb test data\n");
printf("key bytes\t\tclear bytes\t\tcipher bytes\n");
for (i = 0; i < NUM_TESTS; i++) {
for (j = 0; j < 8; j++)
printf("%02X", ecb_data[i][j]);
printf("\t");
for (j = 0; j < 8; j++)
printf("%02X", plain_data[i][j]);
printf("\t");
for (j = 0; j < 8; j++)
printf("%02X", cipher_data[i][j]);
printf("\n");
}
printf("set_key test data\n");
printf("data[8]= ");
for (j = 0; j < 8; j++)
printf("%02X", key_data[j]);
printf("\n");
for (i = 0; i < KEY_TEST_NUM - 1; i++) {
printf("c=");
for (j = 0; j < 8; j++)
printf("%02X", key_out[i][j]);
printf(" k[%2u]=", i + 1);
for (j = 0; j < i + 1; j++)
printf("%02X", key_test[j]);
printf("\n");
}
printf("\nchaining mode test data\n");
printf("key[16] = ");
for (j = 0; j < 16; j++)
printf("%02X", cbc_key[j]);
printf("\niv[8] = ");
for (j = 0; j < 8; j++)
printf("%02X", cbc_iv[j]);
printf("\ndata[%d] = '%s'", (int)strlen(cbc_data) + 1, cbc_data);
printf("\ndata[%d] = ", (int)strlen(cbc_data) + 1);
for (j = 0; j < strlen(cbc_data) + 1; j++)
printf("%02X", cbc_data[j]);
printf("\n");
printf("cbc cipher text\n");
printf("cipher[%d]= ", 32);
for (j = 0; j < 32; j++)
printf("%02X", cbc_ok[j]);
printf("\n");
printf("cfb64 cipher text\n");
printf("cipher[%d]= ", (int)strlen(cbc_data) + 1);
for (j = 0; j < strlen(cbc_data) + 1; j++)
printf("%02X", cfb64_ok[j]);
printf("\n");
printf("ofb64 cipher text\n");
printf("cipher[%d]= ", (int)strlen(cbc_data) + 1);
for (j = 0; j < strlen(cbc_data) + 1; j++)
printf("%02X", ofb64_ok[j]);
printf("\n");
return 0;
}
static int test_bf_ecb_raw(int n)
{
int ret = 1;
BF_KEY key;
BF_LONG data[2];
BF_set_key(&key, strlen(bf_key[n]), (unsigned char *)bf_key[n]);
data[0] = bf_plain[n][0];
data[1] = bf_plain[n][1];
BF_encrypt(data, &key);
if (!TEST_mem_eq(&(bf_cipher[n][0]), BF_BLOCK, &(data[0]), BF_BLOCK))
ret = 0;
BF_decrypt(&(data[0]), &key);
if (!TEST_mem_eq(&(bf_plain[n][0]), BF_BLOCK, &(data[0]), BF_BLOCK))
ret = 0;
return ret;
}
static int test_bf_ecb(int n)
{
int ret = 1;
BF_KEY key;
unsigned char out[8];
BF_set_key(&key, 8, ecb_data[n]);
BF_ecb_encrypt(&(plain_data[n][0]), out, &key, BF_ENCRYPT);
if (!TEST_mem_eq(&(cipher_data[n][0]), BF_BLOCK, out, BF_BLOCK))
ret = 0;
BF_ecb_encrypt(out, out, &key, BF_DECRYPT);
if (!TEST_mem_eq(&(plain_data[n][0]), BF_BLOCK, out, BF_BLOCK))
ret = 0;
return ret;
}
static int test_bf_set_key(int n)
{
int ret = 1;
BF_KEY key;
unsigned char out[8];
BF_set_key(&key, n+1, key_test);
BF_ecb_encrypt(key_data, out, &key, BF_ENCRYPT);
/* mips-sgi-irix6.5-gcc vv -mabi=64 bug workaround */
if (!TEST_mem_eq(out, 8, &(key_out[n][0]), 8))
ret = 0;
return ret;
}
static int test_bf_cbc(void)
{
unsigned char cbc_in[40], cbc_out[40], iv[8];
int ret = 1;
BF_KEY key;
BF_LONG len;
len = strlen(cbc_data) + 1;
BF_set_key(&key, 16, cbc_key);
memset(cbc_in, 0, sizeof(cbc_in));
memset(cbc_out, 0, sizeof(cbc_out));
memcpy(iv, cbc_iv, sizeof(iv));
BF_cbc_encrypt((unsigned char *)cbc_data, cbc_out, len,
&key, iv, BF_ENCRYPT);
if (!TEST_mem_eq(cbc_out, 32, cbc_ok, 32))
ret = 0;
memcpy(iv, cbc_iv, 8);
BF_cbc_encrypt(cbc_out, cbc_in, len, &key, iv, BF_DECRYPT);
if (!TEST_mem_eq(cbc_in, len, cbc_data, strlen(cbc_data) + 1))
ret = 0;
return ret;
}
static int test_bf_cfb64(void)
{
unsigned char cbc_in[40], cbc_out[40], iv[8];
int n, ret = 1;
BF_KEY key;
BF_LONG len;
len = strlen(cbc_data) + 1;
BF_set_key(&key, 16, cbc_key);
memset(cbc_in, 0, 40);
memset(cbc_out, 0, 40);
memcpy(iv, cbc_iv, 8);
n = 0;
BF_cfb64_encrypt((unsigned char *)cbc_data, cbc_out, (long)13,
&key, iv, &n, BF_ENCRYPT);
BF_cfb64_encrypt((unsigned char *)&(cbc_data[13]), &(cbc_out[13]),
len - 13, &key, iv, &n, BF_ENCRYPT);
if (!TEST_mem_eq(cbc_out, (int)len, cfb64_ok, (int)len))
ret = 0;
n = 0;
memcpy(iv, cbc_iv, 8);
BF_cfb64_encrypt(cbc_out, cbc_in, 17, &key, iv, &n, BF_DECRYPT);
BF_cfb64_encrypt(&(cbc_out[17]), &(cbc_in[17]), len - 17,
&key, iv, &n, BF_DECRYPT);
if (!TEST_mem_eq(cbc_in, (int)len, cbc_data, (int)len))
ret = 0;
return ret;
}
static int test_bf_ofb64(void)
{
unsigned char cbc_in[40], cbc_out[40], iv[8];
int n, ret = 1;
BF_KEY key;
BF_LONG len;
len = strlen(cbc_data) + 1;
BF_set_key(&key, 16, cbc_key);
memset(cbc_in, 0, 40);
memset(cbc_out, 0, 40);
memcpy(iv, cbc_iv, 8);
n = 0;
BF_ofb64_encrypt((unsigned char *)cbc_data, cbc_out, (long)13, &key, iv,
&n);
BF_ofb64_encrypt((unsigned char *)&(cbc_data[13]), &(cbc_out[13]),
len - 13, &key, iv, &n);
if (!TEST_mem_eq(cbc_out, (int)len, ofb64_ok, (int)len))
ret = 0;
n = 0;
memcpy(iv, cbc_iv, 8);
BF_ofb64_encrypt(cbc_out, cbc_in, 17, &key, iv, &n);
BF_ofb64_encrypt(&(cbc_out[17]), &(cbc_in[17]), len - 17, &key, iv, &n);
if (!TEST_mem_eq(cbc_in, (int)len, cbc_data, (int)len))
ret = 0;
return ret;
}
#endif
typedef enum OPTION_choice {
OPT_ERR = -1,
OPT_EOF = 0,
OPT_PRINT,
OPT_TEST_ENUM
} OPTION_CHOICE;
const OPTIONS *test_get_options(void)
{
static const OPTIONS test_options[] = {
OPT_TEST_OPTIONS_DEFAULT_USAGE,
{ "print", OPT_PRINT, '-', "Output test tables instead of running tests"},
{ NULL }
};
return test_options;
}
int setup_tests(void)
{
#ifndef OPENSSL_NO_BF
OPTION_CHOICE o;
# ifdef CHARSET_EBCDIC
int n;
ebcdic2ascii(cbc_data, cbc_data, strlen(cbc_data));
for (n = 0; n < 2; n++) {
ebcdic2ascii(bf_key[n], bf_key[n], strlen(bf_key[n]));
}
# endif
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_PRINT:
print_test_data();
return 1;
case OPT_TEST_CASES:
break;
default:
return 0;
}
}
ADD_ALL_TESTS(test_bf_ecb_raw, 2);
ADD_ALL_TESTS(test_bf_ecb, NUM_TESTS);
ADD_ALL_TESTS(test_bf_set_key, KEY_TEST_NUM-1);
ADD_TEST(test_bf_cbc);
ADD_TEST(test_bf_cfb64);
ADD_TEST(test_bf_ofb64);
#endif
return 1;
}
| 16,296 | 32.395492 | 82 | c |
openssl | openssl-master/test/bio_callback_test.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
*/
#define OPENSSL_SUPPRESS_DEPRECATED
#include <stdio.h>
#include <string.h>
#include <openssl/bio.h>
#include "testutil.h"
#define MAXCOUNT 5
static int my_param_count;
static BIO *my_param_b[MAXCOUNT];
static int my_param_oper[MAXCOUNT];
static const char *my_param_argp[MAXCOUNT];
static int my_param_argi[MAXCOUNT];
static long my_param_argl[MAXCOUNT];
static long my_param_ret[MAXCOUNT];
static size_t my_param_len[MAXCOUNT];
static size_t my_param_processed[MAXCOUNT];
static long my_bio_cb_ex(BIO *b, int oper, const char *argp, size_t len,
int argi, long argl, int ret, size_t *processed)
{
if (my_param_count >= MAXCOUNT)
return -1;
my_param_b[my_param_count] = b;
my_param_oper[my_param_count] = oper;
my_param_argp[my_param_count] = argp;
my_param_argi[my_param_count] = argi;
my_param_argl[my_param_count] = argl;
my_param_ret[my_param_count] = ret;
my_param_len[my_param_count] = len;
my_param_processed[my_param_count] = processed != NULL ? *processed : 0;
my_param_count++;
return ret;
}
static int test_bio_callback_ex(void)
{
int ok = 0;
BIO *bio;
int i;
char test1[] = "test";
const size_t test1len = sizeof(test1) - 1;
char test2[] = "hello";
const size_t test2len = sizeof(test2) - 1;
char buf[16];
my_param_count = 0;
bio = BIO_new(BIO_s_mem());
if (bio == NULL)
goto err;
BIO_set_callback_ex(bio, my_bio_cb_ex);
i = BIO_write(bio, test1, test1len);
if (!TEST_int_eq(i, test1len)
|| !TEST_int_eq(my_param_count, 2)
|| !TEST_ptr_eq(my_param_b[0], bio)
|| !TEST_int_eq(my_param_oper[0], BIO_CB_WRITE)
|| !TEST_ptr_eq(my_param_argp[0], test1)
|| !TEST_size_t_eq(my_param_len[0], test1len)
|| !TEST_long_eq(my_param_argl[0], 0L)
|| !TEST_int_eq((int)my_param_ret[0], 1)
|| !TEST_ptr_eq(my_param_b[1], bio)
|| !TEST_int_eq(my_param_oper[1], BIO_CB_WRITE | BIO_CB_RETURN)
|| !TEST_ptr_eq(my_param_argp[1], test1)
|| !TEST_size_t_eq(my_param_len[1], test1len)
|| !TEST_long_eq(my_param_argl[1], 0L)
|| !TEST_size_t_eq(my_param_processed[1], test1len)
|| !TEST_int_eq((int)my_param_ret[1], 1))
goto err;
my_param_count = 0;
i = BIO_read(bio, buf, sizeof(buf));
if (!TEST_mem_eq(buf, i, test1, test1len)
|| !TEST_int_eq(my_param_count, 2)
|| !TEST_ptr_eq(my_param_b[0], bio)
|| !TEST_int_eq(my_param_oper[0], BIO_CB_READ)
|| !TEST_ptr_eq(my_param_argp[0], buf)
|| !TEST_size_t_eq(my_param_len[0], sizeof(buf))
|| !TEST_long_eq(my_param_argl[0], 0L)
|| !TEST_int_eq((int)my_param_ret[0], 1)
|| !TEST_ptr_eq(my_param_b[1], bio)
|| !TEST_int_eq(my_param_oper[1], BIO_CB_READ | BIO_CB_RETURN)
|| !TEST_ptr_eq(my_param_argp[1], buf)
|| !TEST_size_t_eq(my_param_len[1], sizeof(buf))
|| !TEST_long_eq(my_param_argl[1], 0L)
|| !TEST_size_t_eq(my_param_processed[1], test1len)
|| !TEST_int_eq((int)my_param_ret[1], 1))
goto err;
/* By default a mem bio returns -1 if it has run out of data */
my_param_count = 0;
i = BIO_read(bio, buf, sizeof(buf));
if (!TEST_int_eq(i, -1)
|| !TEST_int_eq(my_param_count, 2)
|| !TEST_ptr_eq(my_param_b[0], bio)
|| !TEST_int_eq(my_param_oper[0], BIO_CB_READ)
|| !TEST_ptr_eq(my_param_argp[0], buf)
|| !TEST_size_t_eq(my_param_len[0], sizeof(buf))
|| !TEST_long_eq(my_param_argl[0], 0L)
|| !TEST_int_eq((int)my_param_ret[0], 1)
|| !TEST_ptr_eq(my_param_b[1], bio)
|| !TEST_int_eq(my_param_oper[1], BIO_CB_READ | BIO_CB_RETURN)
|| !TEST_ptr_eq(my_param_argp[1], buf)
|| !TEST_size_t_eq(my_param_len[1], sizeof(buf))
|| !TEST_long_eq(my_param_argl[1], 0L)
|| !TEST_size_t_eq(my_param_processed[1], 0)
|| !TEST_int_eq((int)my_param_ret[1], -1))
goto err;
/* Force the mem bio to return 0 if it has run out of data */
my_param_count = 0;
i = BIO_set_mem_eof_return(bio, 0);
if (!TEST_int_eq(i, 1)
|| !TEST_int_eq(my_param_count, 2)
|| !TEST_ptr_eq(my_param_b[0], bio)
|| !TEST_int_eq(my_param_oper[0], BIO_CB_CTRL)
|| !TEST_ptr_eq(my_param_argp[0], NULL)
|| !TEST_int_eq(my_param_argi[0], BIO_C_SET_BUF_MEM_EOF_RETURN)
|| !TEST_long_eq(my_param_argl[0], 0L)
|| !TEST_int_eq((int)my_param_ret[0], 1)
|| !TEST_ptr_eq(my_param_b[1], bio)
|| !TEST_int_eq(my_param_oper[1], BIO_CB_CTRL | BIO_CB_RETURN)
|| !TEST_ptr_eq(my_param_argp[1], NULL)
|| !TEST_int_eq(my_param_argi[1], BIO_C_SET_BUF_MEM_EOF_RETURN)
|| !TEST_long_eq(my_param_argl[1], 0L)
|| !TEST_int_eq((int)my_param_ret[1], 1))
goto err;
my_param_count = 0;
i = BIO_read(bio, buf, sizeof(buf));
if (!TEST_int_eq(i, 0)
|| !TEST_int_eq(my_param_count, 2)
|| !TEST_ptr_eq(my_param_b[0], bio)
|| !TEST_int_eq(my_param_oper[0], BIO_CB_READ)
|| !TEST_ptr_eq(my_param_argp[0], buf)
|| !TEST_size_t_eq(my_param_len[0], sizeof(buf))
|| !TEST_long_eq(my_param_argl[0], 0L)
|| !TEST_int_eq((int)my_param_ret[0], 1)
|| !TEST_ptr_eq(my_param_b[1], bio)
|| !TEST_int_eq(my_param_oper[1], BIO_CB_READ | BIO_CB_RETURN)
|| !TEST_ptr_eq(my_param_argp[1], buf)
|| !TEST_size_t_eq(my_param_len[1], sizeof(buf))
|| !TEST_long_eq(my_param_argl[1], 0L)
|| !TEST_size_t_eq(my_param_processed[1], 0)
|| !TEST_int_eq((int)my_param_ret[1], 0))
goto err;
my_param_count = 0;
i = BIO_puts(bio, test2);
if (!TEST_int_eq(i, 5)
|| !TEST_int_eq(my_param_count, 2)
|| !TEST_ptr_eq(my_param_b[0], bio)
|| !TEST_int_eq(my_param_oper[0], BIO_CB_PUTS)
|| !TEST_ptr_eq(my_param_argp[0], test2)
|| !TEST_int_eq(my_param_argi[0], 0)
|| !TEST_long_eq(my_param_argl[0], 0L)
|| !TEST_int_eq((int)my_param_ret[0], 1)
|| !TEST_ptr_eq(my_param_b[1], bio)
|| !TEST_int_eq(my_param_oper[1], BIO_CB_PUTS | BIO_CB_RETURN)
|| !TEST_ptr_eq(my_param_argp[1], test2)
|| !TEST_int_eq(my_param_argi[1], 0)
|| !TEST_long_eq(my_param_argl[1], 0L)
|| !TEST_size_t_eq(my_param_processed[1], test2len)
|| !TEST_int_eq((int)my_param_ret[1], 1))
goto err;
my_param_count = 0;
i = BIO_free(bio);
if (!TEST_int_eq(i, 1)
|| !TEST_int_eq(my_param_count, 1)
|| !TEST_ptr_eq(my_param_b[0], bio)
|| !TEST_int_eq(my_param_oper[0], BIO_CB_FREE)
|| !TEST_ptr_eq(my_param_argp[0], NULL)
|| !TEST_int_eq(my_param_argi[0], 0)
|| !TEST_long_eq(my_param_argl[0], 0L)
|| !TEST_int_eq((int)my_param_ret[0], 1))
goto finish;
ok = 1;
goto finish;
err:
BIO_free(bio);
finish:
/* This helps finding memory leaks with ASAN */
memset(my_param_b, 0, sizeof(my_param_b));
memset(my_param_argp, 0, sizeof(my_param_argp));
return ok;
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
static long my_bio_callback(BIO *b, int oper, const char *argp, int argi,
long argl, long ret)
{
if (my_param_count >= MAXCOUNT)
return -1;
my_param_b[my_param_count] = b;
my_param_oper[my_param_count] = oper;
my_param_argp[my_param_count] = argp;
my_param_argi[my_param_count] = argi;
my_param_argl[my_param_count] = argl;
my_param_ret[my_param_count] = ret;
my_param_count++;
return ret;
}
static int test_bio_callback(void)
{
int ok = 0;
BIO *bio;
int i;
char test1[] = "test";
const int test1len = sizeof(test1) - 1;
char test2[] = "hello";
const int test2len = sizeof(test2) - 1;
char buf[16];
my_param_count = 0;
bio = BIO_new(BIO_s_mem());
if (bio == NULL)
goto err;
BIO_set_callback(bio, my_bio_callback);
i = BIO_write(bio, test1, test1len);
if (!TEST_int_eq(i, test1len)
|| !TEST_int_eq(my_param_count, 2)
|| !TEST_ptr_eq(my_param_b[0], bio)
|| !TEST_int_eq(my_param_oper[0], BIO_CB_WRITE)
|| !TEST_ptr_eq(my_param_argp[0], test1)
|| !TEST_int_eq(my_param_argi[0], test1len)
|| !TEST_long_eq(my_param_argl[0], 0L)
|| !TEST_long_eq(my_param_ret[0], 1L)
|| !TEST_ptr_eq(my_param_b[1], bio)
|| !TEST_int_eq(my_param_oper[1], BIO_CB_WRITE | BIO_CB_RETURN)
|| !TEST_ptr_eq(my_param_argp[1], test1)
|| !TEST_int_eq(my_param_argi[1], test1len)
|| !TEST_long_eq(my_param_argl[1], 0L)
|| !TEST_long_eq(my_param_ret[1], (long)test1len))
goto err;
my_param_count = 0;
i = BIO_read(bio, buf, sizeof(buf));
if (!TEST_mem_eq(buf, i, test1, test1len)
|| !TEST_int_eq(my_param_count, 2)
|| !TEST_ptr_eq(my_param_b[0], bio)
|| !TEST_int_eq(my_param_oper[0], BIO_CB_READ)
|| !TEST_ptr_eq(my_param_argp[0], buf)
|| !TEST_int_eq(my_param_argi[0], sizeof(buf))
|| !TEST_long_eq(my_param_argl[0], 0L)
|| !TEST_long_eq(my_param_ret[0], 1L)
|| !TEST_ptr_eq(my_param_b[1], bio)
|| !TEST_int_eq(my_param_oper[1], BIO_CB_READ | BIO_CB_RETURN)
|| !TEST_ptr_eq(my_param_argp[1], buf)
|| !TEST_int_eq(my_param_argi[1], sizeof(buf))
|| !TEST_long_eq(my_param_argl[1], 0L)
|| !TEST_long_eq(my_param_ret[1], (long)test1len))
goto err;
/* By default a mem bio returns -1 if it has run out of data */
my_param_count = 0;
i = BIO_read(bio, buf, sizeof(buf));
if (!TEST_int_eq(i, -1)
|| !TEST_int_eq(my_param_count, 2)
|| !TEST_ptr_eq(my_param_b[0], bio)
|| !TEST_int_eq(my_param_oper[0], BIO_CB_READ)
|| !TEST_ptr_eq(my_param_argp[0], buf)
|| !TEST_int_eq(my_param_argi[0], sizeof(buf))
|| !TEST_long_eq(my_param_argl[0], 0L)
|| !TEST_long_eq(my_param_ret[0], 1L)
|| !TEST_ptr_eq(my_param_b[1], bio)
|| !TEST_int_eq(my_param_oper[1], BIO_CB_READ | BIO_CB_RETURN)
|| !TEST_ptr_eq(my_param_argp[1], buf)
|| !TEST_int_eq(my_param_argi[1], sizeof(buf))
|| !TEST_long_eq(my_param_argl[1], 0L)
|| !TEST_long_eq(my_param_ret[1], -1L))
goto err;
/* Force the mem bio to return 0 if it has run out of data */
BIO_set_mem_eof_return(bio, 0);
my_param_count = 0;
i = BIO_read(bio, buf, sizeof(buf));
if (!TEST_int_eq(i, 0)
|| !TEST_int_eq(my_param_count, 2)
|| !TEST_ptr_eq(my_param_b[0], bio)
|| !TEST_int_eq(my_param_oper[0], BIO_CB_READ)
|| !TEST_ptr_eq(my_param_argp[0], buf)
|| !TEST_int_eq(my_param_argi[0], sizeof(buf))
|| !TEST_long_eq(my_param_argl[0], 0L)
|| !TEST_long_eq(my_param_ret[0], 1L)
|| !TEST_ptr_eq(my_param_b[1], bio)
|| !TEST_int_eq(my_param_oper[1], BIO_CB_READ | BIO_CB_RETURN)
|| !TEST_ptr_eq(my_param_argp[1], buf)
|| !TEST_int_eq(my_param_argi[1], sizeof(buf))
|| !TEST_long_eq(my_param_argl[1], 0L)
|| !TEST_long_eq(my_param_ret[1], 0L))
goto err;
my_param_count = 0;
i = BIO_puts(bio, test2);
if (!TEST_int_eq(i, 5)
|| !TEST_int_eq(my_param_count, 2)
|| !TEST_ptr_eq(my_param_b[0], bio)
|| !TEST_int_eq(my_param_oper[0], BIO_CB_PUTS)
|| !TEST_ptr_eq(my_param_argp[0], test2)
|| !TEST_int_eq(my_param_argi[0], 0)
|| !TEST_long_eq(my_param_argl[0], 0L)
|| !TEST_long_eq(my_param_ret[0], 1L)
|| !TEST_ptr_eq(my_param_b[1], bio)
|| !TEST_int_eq(my_param_oper[1], BIO_CB_PUTS | BIO_CB_RETURN)
|| !TEST_ptr_eq(my_param_argp[1], test2)
|| !TEST_int_eq(my_param_argi[1], 0)
|| !TEST_long_eq(my_param_argl[1], 0L)
|| !TEST_long_eq(my_param_ret[1], (long)test2len))
goto err;
my_param_count = 0;
i = BIO_free(bio);
if (!TEST_int_eq(i, 1)
|| !TEST_int_eq(my_param_count, 1)
|| !TEST_ptr_eq(my_param_b[0], bio)
|| !TEST_int_eq(my_param_oper[0], BIO_CB_FREE)
|| !TEST_ptr_eq(my_param_argp[0], NULL)
|| !TEST_int_eq(my_param_argi[0], 0)
|| !TEST_long_eq(my_param_argl[0], 0L)
|| !TEST_long_eq(my_param_ret[0], 1L))
goto finish;
ok = 1;
goto finish;
err:
BIO_free(bio);
finish:
/* This helps finding memory leaks with ASAN */
memset(my_param_b, 0, sizeof(my_param_b));
memset(my_param_argp, 0, sizeof(my_param_argp));
return ok;
}
#endif
int setup_tests(void)
{
ADD_TEST(test_bio_callback_ex);
#ifndef OPENSSL_NO_DEPRECATED_3_0
ADD_TEST(test_bio_callback);
#endif
return 1;
}
| 13,892 | 37.484765 | 76 | c |
openssl | openssl-master/test/bio_comp_test.c | /*
* Copyright 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 <string.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/rand.h>
#include <openssl/comp.h>
#include "testutil.h"
#include "testutil/output.h"
#include "testutil/tu_local.h"
#define COMPRESS 1
#define EXPAND 0
#define BUFFER_SIZE 32 * 1024
#define NUM_SIZES 4
static int sizes[NUM_SIZES] = { 64, 512, 2048, 16 * 1024 };
/* using global buffers */
static unsigned char *original = NULL;
static unsigned char *result = NULL;
/*
* For compression:
* the write operation compresses
* the read operation decompresses
*/
static int do_bio_comp_test(const BIO_METHOD *meth, size_t size)
{
BIO *bcomp = NULL;
BIO *bmem = NULL;
BIO *bexp = NULL;
int osize;
int rsize;
int ret = 0;
/* Compress */
if (!TEST_ptr(meth))
goto err;
if (!TEST_ptr(bcomp = BIO_new(meth)))
goto err;
if (!TEST_ptr(bmem = BIO_new(BIO_s_mem())))
goto err;
BIO_push(bcomp, bmem);
osize = BIO_write(bcomp, original, size);
if (!TEST_int_eq(osize, size)
|| !TEST_true(BIO_flush(bcomp)))
goto err;
BIO_free(bcomp);
bcomp = NULL;
/* decompress */
if (!TEST_ptr(bexp = BIO_new(meth)))
goto err;
BIO_push(bexp, bmem);
rsize = BIO_read(bexp, result, size);
if (!TEST_int_eq(size, rsize)
|| !TEST_mem_eq(original, osize, result, rsize))
goto err;
ret = 1;
err:
BIO_free(bexp);
BIO_free(bcomp);
BIO_free(bmem);
return ret;
}
static int do_bio_comp(const BIO_METHOD *meth, int n)
{
int i;
int success = 0;
int size = sizes[n % 4];
int type = n / 4;
if (!TEST_ptr(original = OPENSSL_malloc(BUFFER_SIZE))
|| !TEST_ptr(result = OPENSSL_malloc(BUFFER_SIZE)))
goto err;
switch (type) {
case 0:
TEST_info("zeros of size %d\n", size);
memset(original, 0, BUFFER_SIZE);
break;
case 1:
TEST_info("ones of size %d\n", size);
memset(original, 1, BUFFER_SIZE);
break;
case 2:
TEST_info("sequential of size %d\n", size);
for (i = 0; i < BUFFER_SIZE; i++)
original[i] = i & 0xFF;
break;
case 3:
TEST_info("random of size %d\n", size);
if (!TEST_int_gt(RAND_bytes(original, BUFFER_SIZE), 0))
goto err;
break;
default:
goto err;
}
if (!TEST_true(do_bio_comp_test(meth, size)))
goto err;
success = 1;
err:
OPENSSL_free(original);
OPENSSL_free(result);
return success;
}
#ifndef OPENSSL_NO_ZSTD
static int test_zstd(int n)
{
return do_bio_comp(BIO_f_zstd(), n);
}
#endif
#ifndef OPENSSL_NO_BROTLI
static int test_brotli(int n)
{
return do_bio_comp(BIO_f_brotli(), n);
}
#endif
#ifndef OPENSSL_NO_ZLIB
static int test_zlib(int n)
{
return do_bio_comp(BIO_f_zlib(), n);
}
#endif
int setup_tests(void)
{
#ifndef OPENSSL_NO_ZLIB
ADD_ALL_TESTS(test_zlib, NUM_SIZES * 4);
#endif
#ifndef OPENSSL_NO_BROTLI
ADD_ALL_TESTS(test_brotli, NUM_SIZES * 4);
#endif
#ifndef OPENSSL_NO_ZSTD
ADD_ALL_TESTS(test_zstd, NUM_SIZES * 4);
#endif
return 1;
}
| 3,498 | 21.720779 | 74 | c |
openssl | openssl-master/test/bio_core_test.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 <string.h>
#include <openssl/bio.h>
#include "testutil.h"
struct ossl_core_bio_st {
int dummy;
BIO *bio;
};
static int tst_bio_core_read_ex(OSSL_CORE_BIO *bio, char *data, size_t data_len,
size_t *bytes_read)
{
return BIO_read_ex(bio->bio, data, data_len, bytes_read);
}
static int tst_bio_core_write_ex(OSSL_CORE_BIO *bio, const char *data,
size_t data_len, size_t *written)
{
return BIO_write_ex(bio->bio, data, data_len, written);
}
static int tst_bio_core_gets(OSSL_CORE_BIO *bio, char *buf, int size)
{
return BIO_gets(bio->bio, buf, size);
}
static int tst_bio_core_puts(OSSL_CORE_BIO *bio, const char *str)
{
return BIO_puts(bio->bio, str);
}
static long tst_bio_core_ctrl(OSSL_CORE_BIO *bio, int cmd, long num, void *ptr)
{
return BIO_ctrl(bio->bio, cmd, num, ptr);
}
static int tst_bio_core_up_ref(OSSL_CORE_BIO *bio)
{
return BIO_up_ref(bio->bio);
}
static int tst_bio_core_free(OSSL_CORE_BIO *bio)
{
return BIO_free(bio->bio);
}
static const OSSL_DISPATCH biocbs[] = {
{ OSSL_FUNC_BIO_READ_EX, (void (*)(void))tst_bio_core_read_ex },
{ OSSL_FUNC_BIO_WRITE_EX, (void (*)(void))tst_bio_core_write_ex },
{ OSSL_FUNC_BIO_GETS, (void (*)(void))tst_bio_core_gets },
{ OSSL_FUNC_BIO_PUTS, (void (*)(void))tst_bio_core_puts },
{ OSSL_FUNC_BIO_CTRL, (void (*)(void))tst_bio_core_ctrl },
{ OSSL_FUNC_BIO_UP_REF, (void (*)(void))tst_bio_core_up_ref },
{ OSSL_FUNC_BIO_FREE, (void (*)(void))tst_bio_core_free },
OSSL_DISPATCH_END
};
static int test_bio_core(void)
{
BIO *cbio = NULL, *cbiobad = NULL;
OSSL_LIB_CTX *libctx = OSSL_LIB_CTX_new_from_dispatch(NULL, biocbs);
int testresult = 0;
OSSL_CORE_BIO corebio;
const char *msg = "Hello world";
char buf[80];
corebio.bio = BIO_new(BIO_s_mem());
if (!TEST_ptr(corebio.bio)
|| !TEST_ptr(libctx)
/*
* Attempting to create a corebio in a libctx that was not
* created via OSSL_LIB_CTX_new_from_dispatch() should fail.
*/
|| !TEST_ptr_null((cbiobad = BIO_new_from_core_bio(NULL, &corebio)))
|| !TEST_ptr((cbio = BIO_new_from_core_bio(libctx, &corebio))))
goto err;
if (!TEST_int_gt(BIO_puts(corebio.bio, msg), 0)
/* Test a ctrl via BIO_eof */
|| !TEST_false(BIO_eof(cbio))
|| !TEST_int_gt(BIO_gets(cbio, buf, sizeof(buf)), 0)
|| !TEST_true(BIO_eof(cbio))
|| !TEST_str_eq(buf, msg))
goto err;
buf[0] = '\0';
if (!TEST_int_gt(BIO_write(cbio, msg, strlen(msg) + 1), 0)
|| !TEST_int_gt(BIO_read(cbio, buf, sizeof(buf)), 0)
|| !TEST_str_eq(buf, msg))
goto err;
testresult = 1;
err:
BIO_free(cbiobad);
BIO_free(cbio);
BIO_free(corebio.bio);
OSSL_LIB_CTX_free(libctx);
return testresult;
}
int setup_tests(void)
{
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
ADD_TEST(test_bio_core);
return 1;
}
| 3,481 | 28.016667 | 80 | c |
openssl | openssl-master/test/bio_dgram_test.c | /*
* Copyright 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 <string.h>
#include <openssl/bio.h>
#include <openssl/rand.h>
#include "testutil.h"
#include "internal/sockets.h"
#if !defined(OPENSSL_NO_DGRAM) && !defined(OPENSSL_NO_SOCK)
static int compare_addr(const BIO_ADDR *a, const BIO_ADDR *b)
{
struct in_addr xa, xb;
#if OPENSSL_USE_IPV6
struct in6_addr xa6, xb6;
#endif
void *pa, *pb;
size_t slen, tmplen;
if (BIO_ADDR_family(a) != BIO_ADDR_family(b))
return 0;
if (BIO_ADDR_family(a) == AF_INET) {
pa = &xa;
pb = &xb;
slen = sizeof(xa);
}
#if OPENSSL_USE_IPV6
else if (BIO_ADDR_family(a) == AF_INET6) {
pa = &xa6;
pb = &xb6;
slen = sizeof(xa6);
}
#endif
else {
return 0;
}
tmplen = slen;
if (!TEST_int_eq(BIO_ADDR_rawaddress(a, pa, &tmplen), 1))
return 0;
tmplen = slen;
if (!TEST_int_eq(BIO_ADDR_rawaddress(b, pb, &tmplen), 1))
return 0;
if (!TEST_mem_eq(pa, slen, pb, slen))
return 0;
if (!TEST_int_eq(BIO_ADDR_rawport(a), BIO_ADDR_rawport(b)))
return 0;
return 1;
}
static int do_sendmmsg(BIO *b, BIO_MSG *msg,
size_t num_msg, uint64_t flags,
size_t *num_processed)
{
size_t done;
for (done = 0; done < num_msg; ) {
if (!BIO_sendmmsg(b, msg + done, sizeof(BIO_MSG),
num_msg - done, flags, num_processed))
return 0;
done += *num_processed;
}
*num_processed = done;
return 1;
}
static int do_recvmmsg(BIO *b, BIO_MSG *msg,
size_t num_msg, uint64_t flags,
size_t *num_processed)
{
size_t done;
for (done = 0; done < num_msg; ) {
if (!BIO_recvmmsg(b, msg + done, sizeof(BIO_MSG),
num_msg - done, flags, num_processed))
return 0;
done += *num_processed;
}
*num_processed = done;
return 1;
}
static int test_bio_dgram_impl(int af, int use_local)
{
int testresult = 0;
BIO *b1 = NULL, *b2 = NULL;
int fd1 = -1, fd2 = -1;
BIO_ADDR *addr1 = NULL, *addr2 = NULL, *addr3 = NULL, *addr4 = NULL,
*addr5 = NULL, *addr6 = NULL;
struct in_addr ina;
#if OPENSSL_USE_IPV6
struct in6_addr ina6;
#endif
void *pina;
size_t inal, i;
union BIO_sock_info_u info1 = {0}, info2 = {0};
char rx_buf[128], rx_buf2[128];
BIO_MSG tx_msg[128], rx_msg[128];
char tx_buf[128];
size_t num_processed = 0;
if (af == AF_INET) {
TEST_info("# Testing with AF_INET, local=%d\n", use_local);
pina = &ina;
inal = sizeof(ina);
}
#if OPENSSL_USE_IPV6
else if (af == AF_INET6) {
TEST_info("# Testing with AF_INET6, local=%d\n", use_local);
pina = &ina6;
inal = sizeof(ina6);
}
#endif
else {
goto err;
}
memset(pina, 0, inal);
ina.s_addr = htonl(0x7f000001UL);
#if OPENSSL_USE_IPV6
ina6.s6_addr[15] = 1;
#endif
addr1 = BIO_ADDR_new();
if (!TEST_ptr(addr1))
goto err;
addr2 = BIO_ADDR_new();
if (!TEST_ptr(addr2))
goto err;
addr3 = BIO_ADDR_new();
if (!TEST_ptr(addr3))
goto err;
addr4 = BIO_ADDR_new();
if (!TEST_ptr(addr4))
goto err;
addr5 = BIO_ADDR_new();
if (!TEST_ptr(addr5))
goto err;
addr6 = BIO_ADDR_new();
if (!TEST_ptr(addr6))
goto err;
if (!TEST_int_eq(BIO_ADDR_rawmake(addr1, af, pina, inal, 0), 1))
goto err;
if (!TEST_int_eq(BIO_ADDR_rawmake(addr2, af, pina, inal, 0), 1))
goto err;
fd1 = BIO_socket(af, SOCK_DGRAM, IPPROTO_UDP, 0);
if (!TEST_int_ge(fd1, 0))
goto err;
fd2 = BIO_socket(af, SOCK_DGRAM, IPPROTO_UDP, 0);
if (!TEST_int_ge(fd2, 0))
goto err;
if (BIO_bind(fd1, addr1, 0) <= 0
|| BIO_bind(fd2, addr2, 0) <= 0) {
testresult = TEST_skip("BIO_bind() failed - assuming it's an unavailable address family");
goto err;
}
info1.addr = addr1;
if (!TEST_int_gt(BIO_sock_info(fd1, BIO_SOCK_INFO_ADDRESS, &info1), 0))
goto err;
info2.addr = addr2;
if (!TEST_int_gt(BIO_sock_info(fd2, BIO_SOCK_INFO_ADDRESS, &info2), 0))
goto err;
if (!TEST_int_gt(BIO_ADDR_rawport(addr1), 0))
goto err;
if (!TEST_int_gt(BIO_ADDR_rawport(addr2), 0))
goto err;
b1 = BIO_new_dgram(fd1, 0);
if (!TEST_ptr(b1))
goto err;
b2 = BIO_new_dgram(fd2, 0);
if (!TEST_ptr(b2))
goto err;
if (!TEST_int_gt(BIO_dgram_set_peer(b1, addr2), 0))
goto err;
if (!TEST_int_gt(BIO_write(b1, "hello", 5), 0))
goto err;
/* Receiving automatically sets peer as source addr */
if (!TEST_int_eq(BIO_read(b2, rx_buf, sizeof(rx_buf)), 5))
goto err;
if (!TEST_mem_eq(rx_buf, 5, "hello", 5))
goto err;
if (!TEST_int_gt(BIO_dgram_get_peer(b2, addr3), 0))
goto err;
if (!TEST_int_eq(compare_addr(addr3, addr1), 1))
goto err;
/* Clear peer */
if (!TEST_int_gt(BIO_ADDR_rawmake(addr3, af, pina, inal, 0), 0))
goto err;
if (!TEST_int_gt(BIO_dgram_set_peer(b1, addr3), 0))
goto err;
if (!TEST_int_gt(BIO_dgram_set_peer(b2, addr3), 0))
goto err;
/* Now test using sendmmsg/recvmmsg with no peer set */
tx_msg[0].data = "apple";
tx_msg[0].data_len = 5;
tx_msg[0].peer = NULL;
tx_msg[0].local = NULL;
tx_msg[0].flags = 0;
tx_msg[1].data = "orange";
tx_msg[1].data_len = 6;
tx_msg[1].peer = NULL;
tx_msg[1].local = NULL;
tx_msg[1].flags = 0;
/* First effort should fail due to missing destination address */
if (!TEST_false(do_sendmmsg(b1, tx_msg, 2, 0, &num_processed))
|| !TEST_size_t_eq(num_processed, 0))
goto err;
/*
* Second effort should fail due to local being requested
* when not enabled
*/
tx_msg[0].peer = addr2;
tx_msg[0].local = addr1;
tx_msg[1].peer = addr2;
tx_msg[1].local = addr1;
if (!TEST_false(do_sendmmsg(b1, tx_msg, 2, 0, &num_processed)
|| !TEST_size_t_eq(num_processed, 0)))
goto err;
/* Enable local if we are using it */
if (BIO_dgram_get_local_addr_cap(b1) > 0 && use_local) {
if (!TEST_int_eq(BIO_dgram_set_local_addr_enable(b1, 1), 1))
goto err;
} else {
tx_msg[0].local = NULL;
tx_msg[1].local = NULL;
use_local = 0;
}
/* Third effort should succeed */
if (!TEST_true(do_sendmmsg(b1, tx_msg, 2, 0, &num_processed))
|| !TEST_size_t_eq(num_processed, 2))
goto err;
/* Now try receiving */
rx_msg[0].data = rx_buf;
rx_msg[0].data_len = sizeof(rx_buf);
rx_msg[0].peer = addr3;
rx_msg[0].local = addr4;
rx_msg[0].flags = (1UL<<31); /* undefined flag, should be erased */
memset(rx_buf, 0, sizeof(rx_buf));
rx_msg[1].data = rx_buf2;
rx_msg[1].data_len = sizeof(rx_buf2);
rx_msg[1].peer = addr5;
rx_msg[1].local = addr6;
rx_msg[1].flags = (1UL<<31); /* undefined flag, should be erased */
memset(rx_buf2, 0, sizeof(rx_buf2));
/*
* Should fail at first due to local being requested when not
* enabled
*/
if (!TEST_false(do_recvmmsg(b2, rx_msg, 2, 0, &num_processed))
|| !TEST_size_t_eq(num_processed, 0))
goto err;
/* Fields have not been modified */
if (!TEST_int_eq((int)rx_msg[0].data_len, sizeof(rx_buf)))
goto err;
if (!TEST_int_eq((int)rx_msg[1].data_len, sizeof(rx_buf2)))
goto err;
if (!TEST_ulong_eq((unsigned long)rx_msg[0].flags, 1UL<<31))
goto err;
if (!TEST_ulong_eq((unsigned long)rx_msg[1].flags, 1UL<<31))
goto err;
/* Enable local if we are using it */
if (BIO_dgram_get_local_addr_cap(b2) > 0 && use_local) {
if (!TEST_int_eq(BIO_dgram_set_local_addr_enable(b2, 1), 1))
goto err;
} else {
rx_msg[0].local = NULL;
rx_msg[1].local = NULL;
use_local = 0;
}
/* Do the receive. */
if (!TEST_true(do_recvmmsg(b2, rx_msg, 2, 0, &num_processed))
|| !TEST_size_t_eq(num_processed, 2))
goto err;
/* data_len should have been updated correctly */
if (!TEST_int_eq((int)rx_msg[0].data_len, 5))
goto err;
if (!TEST_int_eq((int)rx_msg[1].data_len, 6))
goto err;
/* flags should have been zeroed */
if (!TEST_int_eq((int)rx_msg[0].flags, 0))
goto err;
if (!TEST_int_eq((int)rx_msg[1].flags, 0))
goto err;
/* peer address should match expected */
if (!TEST_int_eq(compare_addr(addr3, addr1), 1))
goto err;
if (!TEST_int_eq(compare_addr(addr5, addr1), 1))
goto err;
/*
* Do not test local address yet as some platforms do not reliably return
* local addresses for messages queued for RX before local address support
* was enabled. Instead, send some new messages and test they're received
* with the correct local addresses.
*/
if (!TEST_true(do_sendmmsg(b1, tx_msg, 2, 0, &num_processed))
|| !TEST_size_t_eq(num_processed, 2))
goto err;
/* Receive the messages. */
rx_msg[0].data_len = sizeof(rx_buf);
rx_msg[1].data_len = sizeof(rx_buf2);
if (!TEST_true(do_recvmmsg(b2, rx_msg, 2, 0, &num_processed))
|| !TEST_size_t_eq(num_processed, 2))
goto err;
if (rx_msg[0].local != NULL) {
/* If we are using local, it should match expected */
if (!TEST_int_eq(compare_addr(addr4, addr2), 1))
goto err;
if (!TEST_int_eq(compare_addr(addr6, addr2), 1))
goto err;
}
/*
* Try sending more than can be handled in one sendmmsg call (when using the
* sendmmsg implementation)
*/
for (i = 0; i < OSSL_NELEM(tx_msg); ++i) {
tx_buf[i] = (char)i;
tx_msg[i].data = tx_buf + i;
tx_msg[i].data_len = 1;
tx_msg[i].peer = addr2;
tx_msg[i].local = use_local ? addr1 : NULL;
tx_msg[i].flags = 0;
}
if (!TEST_true(do_sendmmsg(b1, tx_msg, OSSL_NELEM(tx_msg), 0, &num_processed))
|| !TEST_size_t_eq(num_processed, OSSL_NELEM(tx_msg)))
goto err;
/*
* Try receiving more than can be handled in one recvmmsg call (when using
* the recvmmsg implementation)
*/
for (i = 0; i < OSSL_NELEM(rx_msg); ++i) {
rx_buf[i] = '\0';
rx_msg[i].data = rx_buf + i;
rx_msg[i].data_len = 1;
rx_msg[i].peer = NULL;
rx_msg[i].local = NULL;
rx_msg[i].flags = 0;
}
if (!TEST_true(do_recvmmsg(b2, rx_msg, OSSL_NELEM(rx_msg), 0, &num_processed))
|| !TEST_size_t_eq(num_processed, OSSL_NELEM(rx_msg)))
goto err;
if (!TEST_mem_eq(tx_buf, OSSL_NELEM(tx_msg), rx_buf, OSSL_NELEM(tx_msg)))
goto err;
testresult = 1;
err:
BIO_free(b1);
BIO_free(b2);
if (fd1 >= 0)
BIO_closesocket(fd1);
if (fd2 >= 0)
BIO_closesocket(fd2);
BIO_ADDR_free(addr1);
BIO_ADDR_free(addr2);
BIO_ADDR_free(addr3);
BIO_ADDR_free(addr4);
BIO_ADDR_free(addr5);
BIO_ADDR_free(addr6);
return testresult;
}
struct bio_dgram_case {
int af, local;
};
static const struct bio_dgram_case bio_dgram_cases[] = {
/* Test without local */
{ AF_INET, 0 },
#if OPENSSL_USE_IPV6
{ AF_INET6, 0 },
#endif
/* Test with local */
{ AF_INET, 1 },
#if OPENSSL_USE_IPV6
{ AF_INET6, 1 }
#endif
};
static int test_bio_dgram(int idx)
{
return test_bio_dgram_impl(bio_dgram_cases[idx].af,
bio_dgram_cases[idx].local);
}
# if !defined(OPENSSL_NO_CHACHA)
static int random_data(const uint32_t *key, uint8_t *data, size_t data_len, size_t offset)
{
int ret = 0, outl;
EVP_CIPHER_CTX *ctx = NULL;
EVP_CIPHER *cipher = NULL;
static const uint8_t zeroes[2048];
uint32_t counter[4] = {0};
counter[0] = (uint32_t)offset;
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
goto err;
cipher = EVP_CIPHER_fetch(NULL, "ChaCha20", NULL);
if (cipher == NULL)
goto err;
if (EVP_EncryptInit_ex2(ctx, cipher, (uint8_t *)key, (uint8_t *)counter, NULL) == 0)
goto err;
while (data_len > 0) {
outl = data_len > sizeof(zeroes) ? (int)sizeof(zeroes) : (int)data_len;
if (EVP_EncryptUpdate(ctx, data, &outl, zeroes, outl) != 1)
goto err;
data += outl;
data_len -= outl;
}
ret = 1;
err:
EVP_CIPHER_CTX_free(ctx);
EVP_CIPHER_free(cipher);
return ret;
}
static int test_bio_dgram_pair(int idx)
{
int testresult = 0, blen, mtu1, mtu2, r;
BIO *bio1 = NULL, *bio2 = NULL;
uint8_t scratch[2048 + 4], scratch2[2048];
uint32_t key[8];
size_t i, num_dgram, num_processed = 0;
BIO_MSG msgs[2], rmsgs[2];
BIO_ADDR *addr1 = NULL, *addr2 = NULL, *addr3 = NULL, *addr4 = NULL;
struct in_addr in_local;
size_t total = 0;
const uint32_t ref_caps = BIO_DGRAM_CAP_HANDLES_SRC_ADDR
| BIO_DGRAM_CAP_HANDLES_DST_ADDR
| BIO_DGRAM_CAP_PROVIDES_SRC_ADDR
| BIO_DGRAM_CAP_PROVIDES_DST_ADDR;
memset(msgs, 0, sizeof(msgs));
memset(rmsgs, 0, sizeof(rmsgs));
in_local.s_addr = ntohl(0x7f000001);
for (i = 0; i < OSSL_NELEM(key); ++i)
key[i] = test_random();
if (idx == 0) {
if (!TEST_int_eq(BIO_new_bio_dgram_pair(&bio1, 0, &bio2, 0), 1))
goto err;
} else {
if (!TEST_ptr(bio1 = bio2 = BIO_new(BIO_s_dgram_mem())))
goto err;
}
mtu1 = BIO_dgram_get_mtu(bio1);
if (!TEST_int_ge(mtu1, 1280))
goto err;
mtu2 = BIO_dgram_get_mtu(bio2);
if (!TEST_int_ge(mtu2, 1280))
goto err;
if (!TEST_int_eq(mtu1, mtu2))
goto err;
if (!TEST_int_le(mtu1, sizeof(scratch) - 4))
goto err;
for (i = 0; idx == 0 || i < 9; ++i) {
if (!TEST_int_eq(random_data(key, scratch, sizeof(scratch), i), 1))
goto err;
blen = ((*(uint32_t*)scratch) % mtu1) + 1;
r = BIO_write(bio1, scratch + 4, blen);
if (r == -1)
break;
if (!TEST_int_eq(r, blen))
goto err;
total += blen;
if (!TEST_size_t_lt(total, 1 * 1024 * 1024))
goto err;
}
/*
* Should be able to fit at least 9 datagrams in default write buffer size
* in worst case
*/
if (!TEST_int_ge(i, 9))
goto err;
/* Check we read back the same data */
num_dgram = i;
for (i = 0; i < num_dgram; ++i) {
if (!TEST_int_eq(random_data(key, scratch, sizeof(scratch), i), 1))
goto err;
blen = ((*(uint32_t*)scratch) % mtu1) + 1;
r = BIO_read(bio2, scratch2, sizeof(scratch2));
if (!TEST_int_eq(r, blen))
goto err;
if (!TEST_mem_eq(scratch + 4, blen, scratch2, blen))
goto err;
}
/* Should now be out of data */
if (!TEST_int_eq(BIO_read(bio2, scratch2, sizeof(scratch2)), -1))
goto err;
/* sendmmsg/recvmmsg */
if (!TEST_int_eq(random_data(key, scratch, sizeof(scratch), 0), 1))
goto err;
msgs[0].data = scratch;
msgs[0].data_len = 19;
msgs[1].data = scratch + 19;
msgs[1].data_len = 46;
if (!TEST_true(BIO_sendmmsg(bio1, msgs, sizeof(BIO_MSG), OSSL_NELEM(msgs), 0,
&num_processed))
|| !TEST_size_t_eq(num_processed, 2))
goto err;
rmsgs[0].data = scratch2;
rmsgs[0].data_len = 64;
rmsgs[1].data = scratch2 + 64;
rmsgs[1].data_len = 64;
if (!TEST_true(BIO_recvmmsg(bio2, rmsgs, sizeof(BIO_MSG), OSSL_NELEM(rmsgs), 0,
&num_processed))
|| !TEST_size_t_eq(num_processed, 2))
goto err;
if (!TEST_mem_eq(rmsgs[0].data, rmsgs[0].data_len, scratch, 19))
goto err;
if (!TEST_mem_eq(rmsgs[1].data, rmsgs[1].data_len, scratch + 19, 46))
goto err;
/* sendmmsg/recvmmsg with peer */
addr1 = BIO_ADDR_new();
if (!TEST_ptr(addr1))
goto err;
if (!TEST_int_eq(BIO_ADDR_rawmake(addr1, AF_INET, &in_local,
sizeof(in_local), 1234), 1))
goto err;
addr2 = BIO_ADDR_new();
if (!TEST_ptr(addr2))
goto err;
if (!TEST_int_eq(BIO_ADDR_rawmake(addr2, AF_INET, &in_local,
sizeof(in_local), 2345), 1))
goto err;
addr3 = BIO_ADDR_new();
if (!TEST_ptr(addr3))
goto err;
addr4 = BIO_ADDR_new();
if (!TEST_ptr(addr4))
goto err;
msgs[0].peer = addr1;
/* fails due to lack of caps on peer */
if (!TEST_false(BIO_sendmmsg(bio1, msgs, sizeof(BIO_MSG),
OSSL_NELEM(msgs), 0, &num_processed))
|| !TEST_size_t_eq(num_processed, 0))
goto err;
if (!TEST_int_eq(BIO_dgram_set_caps(bio2, ref_caps), 1))
goto err;
if (!TEST_int_eq(BIO_dgram_get_caps(bio2), ref_caps))
goto err;
if (!TEST_int_eq(BIO_dgram_get_effective_caps(bio1), ref_caps))
goto err;
if (idx == 0 && !TEST_int_eq(BIO_dgram_get_effective_caps(bio2), 0))
goto err;
if (!TEST_int_eq(BIO_dgram_set_caps(bio1, ref_caps), 1))
goto err;
/* succeeds with cap now available */
if (!TEST_true(BIO_sendmmsg(bio1, msgs, sizeof(BIO_MSG), 1, 0, &num_processed))
|| !TEST_size_t_eq(num_processed, 1))
goto err;
/* enable local addr support */
if (!TEST_int_eq(BIO_dgram_set_local_addr_enable(bio2, 1), 1))
goto err;
rmsgs[0].data = scratch2;
rmsgs[0].data_len = 64;
rmsgs[0].peer = addr3;
rmsgs[0].local = addr4;
if (!TEST_true(BIO_recvmmsg(bio2, rmsgs, sizeof(BIO_MSG), OSSL_NELEM(rmsgs), 0,
&num_processed))
|| !TEST_size_t_eq(num_processed, 1))
goto err;
if (!TEST_mem_eq(rmsgs[0].data, rmsgs[0].data_len, msgs[0].data, 19))
goto err;
/* We didn't set the source address so this should be zero */
if (!TEST_int_eq(BIO_ADDR_family(addr3), 0))
goto err;
if (!TEST_int_eq(BIO_ADDR_family(addr4), AF_INET))
goto err;
if (!TEST_int_eq(BIO_ADDR_rawport(addr4), 1234))
goto err;
/* test source address */
msgs[0].local = addr2;
if (!TEST_int_eq(BIO_dgram_set_local_addr_enable(bio1, 1), 1))
goto err;
if (!TEST_true(BIO_sendmmsg(bio1, msgs, sizeof(BIO_MSG), 1, 0, &num_processed))
|| !TEST_size_t_eq(num_processed, 1))
goto err;
rmsgs[0].data = scratch2;
rmsgs[0].data_len = 64;
if (!TEST_true(BIO_recvmmsg(bio2, rmsgs, sizeof(BIO_MSG), OSSL_NELEM(rmsgs), 0, &num_processed))
|| !TEST_size_t_eq(num_processed, 1))
goto err;
if (!TEST_mem_eq(rmsgs[0].data, rmsgs[0].data_len,
msgs[0].data, msgs[0].data_len))
goto err;
if (!TEST_int_eq(BIO_ADDR_family(addr3), AF_INET))
goto err;
if (!TEST_int_eq(BIO_ADDR_rawport(addr3), 2345))
goto err;
if (!TEST_int_eq(BIO_ADDR_family(addr4), AF_INET))
goto err;
if (!TEST_int_eq(BIO_ADDR_rawport(addr4), 1234))
goto err;
/* test truncation, pending */
r = BIO_write(bio1, scratch, 64);
if (!TEST_int_eq(r, 64))
goto err;
memset(scratch2, 0, 64);
if (!TEST_int_eq(BIO_dgram_set_no_trunc(bio2, 1), 1))
goto err;
if (!TEST_int_eq(BIO_read(bio2, scratch2, 32), -1))
goto err;
if (!TEST_int_eq(BIO_pending(bio2), 64))
goto err;
if (!TEST_int_eq(BIO_dgram_set_no_trunc(bio2, 0), 1))
goto err;
if (!TEST_int_eq(BIO_read(bio2, scratch2, 32), 32))
goto err;
if (!TEST_mem_eq(scratch, 32, scratch2, 32))
goto err;
testresult = 1;
err:
if (idx == 0)
BIO_free(bio1);
BIO_free(bio2);
BIO_ADDR_free(addr1);
BIO_ADDR_free(addr2);
BIO_ADDR_free(addr3);
BIO_ADDR_free(addr4);
return testresult;
}
# endif /* !defined(OPENSSL_NO_CHACHA) */
#endif /* !defined(OPENSSL_NO_DGRAM) && !defined(OPENSSL_NO_SOCK) */
int setup_tests(void)
{
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
#if !defined(OPENSSL_NO_DGRAM) && !defined(OPENSSL_NO_SOCK)
ADD_ALL_TESTS(test_bio_dgram, OSSL_NELEM(bio_dgram_cases));
# if !defined(OPENSSL_NO_CHACHA)
ADD_ALL_TESTS(test_bio_dgram_pair, 2);
# endif
#endif
return 1;
}
| 21,162 | 26.307097 | 100 | c |
openssl | openssl-master/test/bio_enc_test.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 <string.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/rand.h>
#include "testutil.h"
#define ENCRYPT 1
#define DECRYPT 0
#define DATA_SIZE 1024
#define MAX_IV 32
#define BUF_SIZE (DATA_SIZE + MAX_IV)
static const unsigned char KEY[] = {
0x51, 0x50, 0xd1, 0x77, 0x2f, 0x50, 0x83, 0x4a,
0x50, 0x3e, 0x06, 0x9a, 0x97, 0x3f, 0xbd, 0x7c,
0xe6, 0x1c, 0x43, 0x2b, 0x72, 0x0b, 0x19, 0xd1,
0x8e, 0xc8, 0xd8, 0x4b, 0xdc, 0x63, 0x15, 0x1b
};
static const unsigned char IV[] = {
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
};
static int do_bio_cipher(const EVP_CIPHER* cipher, const unsigned char* key,
const unsigned char* iv)
{
BIO *b, *mem;
static unsigned char inp[BUF_SIZE] = { 0 };
unsigned char out[BUF_SIZE], ref[BUF_SIZE];
int i, lref, len;
/* Fill buffer with non-zero data so that over steps can be detected */
if (!TEST_int_gt(RAND_bytes(inp, DATA_SIZE), 0))
return 0;
/* Encrypt tests */
/* reference output for single-chunk operation */
b = BIO_new(BIO_f_cipher());
if (!TEST_ptr(b))
return 0;
if (!TEST_true(BIO_set_cipher(b, cipher, key, iv, ENCRYPT)))
goto err;
mem = BIO_new_mem_buf(inp, DATA_SIZE);
if (!TEST_ptr(mem))
goto err;
BIO_push(b, mem);
lref = BIO_read(b, ref, sizeof(ref));
BIO_free_all(b);
/* perform split operations and compare to reference */
for (i = 1; i < lref; i++) {
b = BIO_new(BIO_f_cipher());
if (!TEST_ptr(b))
return 0;
if (!TEST_true(BIO_set_cipher(b, cipher, key, iv, ENCRYPT))) {
TEST_info("Split encrypt failed @ operation %d", i);
goto err;
}
mem = BIO_new_mem_buf(inp, DATA_SIZE);
if (!TEST_ptr(mem))
goto err;
BIO_push(b, mem);
memset(out, 0, sizeof(out));
out[i] = ~ref[i];
len = BIO_read(b, out, i);
/* check for overstep */
if (!TEST_uchar_eq(out[i], (unsigned char)~ref[i])) {
TEST_info("Encrypt overstep check failed @ operation %d", i);
goto err;
}
len += BIO_read(b, out + len, sizeof(out) - len);
BIO_free_all(b);
if (!TEST_mem_eq(out, len, ref, lref)) {
TEST_info("Encrypt compare failed @ operation %d", i);
return 0;
}
}
/* perform small-chunk operations and compare to reference */
for (i = 1; i < lref / 2; i++) {
int delta;
b = BIO_new(BIO_f_cipher());
if (!TEST_ptr(b))
return 0;
if (!TEST_true(BIO_set_cipher(b, cipher, key, iv, ENCRYPT))) {
TEST_info("Small chunk encrypt failed @ operation %d", i);
goto err;
}
mem = BIO_new_mem_buf(inp, DATA_SIZE);
if (!TEST_ptr(mem))
goto err;
BIO_push(b, mem);
memset(out, 0, sizeof(out));
for (len = 0; (delta = BIO_read(b, out + len, i)); ) {
len += delta;
}
BIO_free_all(b);
if (!TEST_mem_eq(out, len, ref, lref)) {
TEST_info("Small chunk encrypt compare failed @ operation %d", i);
return 0;
}
}
/* Decrypt tests */
/* reference output for single-chunk operation */
b = BIO_new(BIO_f_cipher());
if (!TEST_ptr(b))
return 0;
if (!TEST_true(BIO_set_cipher(b, cipher, key, iv, DECRYPT)))
goto err;
/* Use original reference output as input */
mem = BIO_new_mem_buf(ref, lref);
if (!TEST_ptr(mem))
goto err;
BIO_push(b, mem);
(void)BIO_flush(b);
memset(out, 0, sizeof(out));
len = BIO_read(b, out, sizeof(out));
BIO_free_all(b);
if (!TEST_mem_eq(inp, DATA_SIZE, out, len))
return 0;
/* perform split operations and compare to reference */
for (i = 1; i < lref; i++) {
b = BIO_new(BIO_f_cipher());
if (!TEST_ptr(b))
return 0;
if (!TEST_true(BIO_set_cipher(b, cipher, key, iv, DECRYPT))) {
TEST_info("Split decrypt failed @ operation %d", i);
goto err;
}
mem = BIO_new_mem_buf(ref, lref);
if (!TEST_ptr(mem))
goto err;
BIO_push(b, mem);
memset(out, 0, sizeof(out));
out[i] = ~ref[i];
len = BIO_read(b, out, i);
/* check for overstep */
if (!TEST_uchar_eq(out[i], (unsigned char)~ref[i])) {
TEST_info("Decrypt overstep check failed @ operation %d", i);
goto err;
}
len += BIO_read(b, out + len, sizeof(out) - len);
BIO_free_all(b);
if (!TEST_mem_eq(inp, DATA_SIZE, out, len)) {
TEST_info("Decrypt compare failed @ operation %d", i);
return 0;
}
}
/* perform small-chunk operations and compare to reference */
for (i = 1; i < lref / 2; i++) {
int delta;
b = BIO_new(BIO_f_cipher());
if (!TEST_ptr(b))
return 0;
if (!TEST_true(BIO_set_cipher(b, cipher, key, iv, DECRYPT))) {
TEST_info("Small chunk decrypt failed @ operation %d", i);
goto err;
}
mem = BIO_new_mem_buf(ref, lref);
if (!TEST_ptr(mem))
goto err;
BIO_push(b, mem);
memset(out, 0, sizeof(out));
for (len = 0; (delta = BIO_read(b, out + len, i)); ) {
len += delta;
}
BIO_free_all(b);
if (!TEST_mem_eq(inp, DATA_SIZE, out, len)) {
TEST_info("Small chunk decrypt compare failed @ operation %d", i);
return 0;
}
}
return 1;
err:
BIO_free_all(b);
return 0;
}
static int do_test_bio_cipher(const EVP_CIPHER* cipher, int idx)
{
switch (idx)
{
case 0:
return do_bio_cipher(cipher, KEY, NULL);
case 1:
return do_bio_cipher(cipher, KEY, IV);
}
return 0;
}
static int test_bio_enc_aes_128_cbc(int idx)
{
return do_test_bio_cipher(EVP_aes_128_cbc(), idx);
}
static int test_bio_enc_aes_128_ctr(int idx)
{
return do_test_bio_cipher(EVP_aes_128_ctr(), idx);
}
static int test_bio_enc_aes_256_cfb(int idx)
{
return do_test_bio_cipher(EVP_aes_256_cfb(), idx);
}
static int test_bio_enc_aes_256_ofb(int idx)
{
return do_test_bio_cipher(EVP_aes_256_ofb(), idx);
}
# ifndef OPENSSL_NO_CHACHA
static int test_bio_enc_chacha20(int idx)
{
return do_test_bio_cipher(EVP_chacha20(), idx);
}
# ifndef OPENSSL_NO_POLY1305
static int test_bio_enc_chacha20_poly1305(int idx)
{
return do_test_bio_cipher(EVP_chacha20_poly1305(), idx);
}
# endif
# endif
int setup_tests(void)
{
ADD_ALL_TESTS(test_bio_enc_aes_128_cbc, 2);
ADD_ALL_TESTS(test_bio_enc_aes_128_ctr, 2);
ADD_ALL_TESTS(test_bio_enc_aes_256_cfb, 2);
ADD_ALL_TESTS(test_bio_enc_aes_256_ofb, 2);
# ifndef OPENSSL_NO_CHACHA
ADD_ALL_TESTS(test_bio_enc_chacha20, 2);
# ifndef OPENSSL_NO_POLY1305
ADD_ALL_TESTS(test_bio_enc_chacha20_poly1305, 2);
# endif
# endif
return 1;
}
| 7,578 | 27.385768 | 78 | c |
openssl | openssl-master/test/bio_memleak_test.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 <openssl/buffer.h>
#include <openssl/bio.h>
#include "testutil.h"
static int test_bio_memleak(void)
{
int ok = 0;
BIO *bio;
BUF_MEM bufmem;
static const char str[] = "BIO test\n";
char buf[100];
bio = BIO_new(BIO_s_mem());
if (!TEST_ptr(bio))
goto finish;
bufmem.length = sizeof(str);
bufmem.data = (char *) str;
bufmem.max = bufmem.length;
BIO_set_mem_buf(bio, &bufmem, BIO_NOCLOSE);
BIO_set_flags(bio, BIO_FLAGS_MEM_RDONLY);
if (!TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(str)))
goto finish;
if (!TEST_mem_eq(buf, sizeof(str), str, sizeof(str)))
goto finish;
ok = 1;
finish:
BIO_free(bio);
return ok;
}
static int test_bio_get_mem(void)
{
int ok = 0;
BIO *bio = NULL;
BUF_MEM *bufmem = NULL;
bio = BIO_new(BIO_s_mem());
if (!TEST_ptr(bio))
goto finish;
if (!TEST_int_eq(BIO_puts(bio, "Hello World\n"), 12))
goto finish;
BIO_get_mem_ptr(bio, &bufmem);
if (!TEST_ptr(bufmem))
goto finish;
if (!TEST_int_gt(BIO_set_close(bio, BIO_NOCLOSE), 0))
goto finish;
BIO_free(bio);
bio = NULL;
if (!TEST_mem_eq(bufmem->data, bufmem->length, "Hello World\n", 12))
goto finish;
ok = 1;
finish:
BIO_free(bio);
BUF_MEM_free(bufmem);
return ok;
}
static int test_bio_new_mem_buf(void)
{
int ok = 0;
BIO *bio;
BUF_MEM *bufmem;
char data[16];
bio = BIO_new_mem_buf("Hello World\n", 12);
if (!TEST_ptr(bio))
goto finish;
if (!TEST_int_eq(BIO_read(bio, data, 5), 5))
goto finish;
if (!TEST_mem_eq(data, 5, "Hello", 5))
goto finish;
if (!TEST_int_gt(BIO_get_mem_ptr(bio, &bufmem), 0))
goto finish;
if (!TEST_int_lt(BIO_write(bio, "test", 4), 0))
goto finish;
if (!TEST_int_eq(BIO_read(bio, data, 16), 7))
goto finish;
if (!TEST_mem_eq(data, 7, " World\n", 7))
goto finish;
if (!TEST_int_gt(BIO_reset(bio), 0))
goto finish;
if (!TEST_int_eq(BIO_read(bio, data, 16), 12))
goto finish;
if (!TEST_mem_eq(data, 12, "Hello World\n", 12))
goto finish;
ok = 1;
finish:
BIO_free(bio);
return ok;
}
static int test_bio_rdonly_mem_buf(void)
{
int ok = 0;
BIO *bio, *bio2 = NULL;
BUF_MEM *bufmem;
char data[16];
bio = BIO_new_mem_buf("Hello World\n", 12);
if (!TEST_ptr(bio))
goto finish;
if (!TEST_int_eq(BIO_read(bio, data, 5), 5))
goto finish;
if (!TEST_mem_eq(data, 5, "Hello", 5))
goto finish;
if (!TEST_int_gt(BIO_get_mem_ptr(bio, &bufmem), 0))
goto finish;
(void)BIO_set_close(bio, BIO_NOCLOSE);
bio2 = BIO_new(BIO_s_mem());
if (!TEST_ptr(bio2))
goto finish;
BIO_set_mem_buf(bio2, bufmem, BIO_CLOSE);
BIO_set_flags(bio2, BIO_FLAGS_MEM_RDONLY);
if (!TEST_int_eq(BIO_read(bio2, data, 16), 7))
goto finish;
if (!TEST_mem_eq(data, 7, " World\n", 7))
goto finish;
if (!TEST_int_gt(BIO_reset(bio2), 0))
goto finish;
if (!TEST_int_eq(BIO_read(bio2, data, 16), 7))
goto finish;
if (!TEST_mem_eq(data, 7, " World\n", 7))
goto finish;
ok = 1;
finish:
BIO_free(bio);
BIO_free(bio2);
return ok;
}
static int test_bio_rdwr_rdonly(void)
{
int ok = 0;
BIO *bio = NULL;
char data[16];
bio = BIO_new(BIO_s_mem());
if (!TEST_ptr(bio))
goto finish;
if (!TEST_int_eq(BIO_puts(bio, "Hello World\n"), 12))
goto finish;
BIO_set_flags(bio, BIO_FLAGS_MEM_RDONLY);
if (!TEST_int_eq(BIO_read(bio, data, 16), 12))
goto finish;
if (!TEST_mem_eq(data, 12, "Hello World\n", 12))
goto finish;
if (!TEST_int_gt(BIO_reset(bio), 0))
goto finish;
BIO_clear_flags(bio, BIO_FLAGS_MEM_RDONLY);
if (!TEST_int_eq(BIO_puts(bio, "Hi!\n"), 4))
goto finish;
if (!TEST_int_eq(BIO_read(bio, data, 16), 16))
goto finish;
if (!TEST_mem_eq(data, 16, "Hello World\nHi!\n", 16))
goto finish;
ok = 1;
finish:
BIO_free(bio);
return ok;
}
static int test_bio_nonclear_rst(void)
{
int ok = 0;
BIO *bio = NULL;
char data[16];
bio = BIO_new(BIO_s_mem());
if (!TEST_ptr(bio))
goto finish;
if (!TEST_int_eq(BIO_puts(bio, "Hello World\n"), 12))
goto finish;
BIO_set_flags(bio, BIO_FLAGS_NONCLEAR_RST);
if (!TEST_int_eq(BIO_read(bio, data, 16), 12))
goto finish;
if (!TEST_mem_eq(data, 12, "Hello World\n", 12))
goto finish;
if (!TEST_int_gt(BIO_reset(bio), 0))
goto finish;
if (!TEST_int_eq(BIO_read(bio, data, 16), 12))
goto finish;
if (!TEST_mem_eq(data, 12, "Hello World\n", 12))
goto finish;
BIO_clear_flags(bio, BIO_FLAGS_NONCLEAR_RST);
if (!TEST_int_gt(BIO_reset(bio), 0))
goto finish;
if (!TEST_int_lt(BIO_read(bio, data, 16), 1))
goto finish;
ok = 1;
finish:
BIO_free(bio);
return ok;
}
static int error_callback_fired;
static long BIO_error_callback(BIO *bio, int cmd, const char *argp,
size_t len, int argi,
long argl, int ret, size_t *processed)
{
if ((cmd & (BIO_CB_READ | BIO_CB_RETURN)) != 0) {
error_callback_fired = 1;
ret = 0; /* fail for read operations to simulate error in input BIO */
}
return ret;
}
/* Checks i2d_ASN1_bio_stream() is freeing all memory when input BIO ends unexpectedly. */
static int test_bio_i2d_ASN1_mime(void)
{
int ok = 0;
BIO *bio = NULL, *out = NULL;
BUF_MEM bufmem;
static const char str[] = "BIO mime test\n";
PKCS7 *p7 = NULL;
if (!TEST_ptr(bio = BIO_new(BIO_s_mem())))
goto finish;
bufmem.length = sizeof(str);
bufmem.data = (char *) str;
bufmem.max = bufmem.length;
BIO_set_mem_buf(bio, &bufmem, BIO_NOCLOSE);
BIO_set_flags(bio, BIO_FLAGS_MEM_RDONLY);
BIO_set_callback_ex(bio, BIO_error_callback);
if (!TEST_ptr(out = BIO_new(BIO_s_mem())))
goto finish;
if (!TEST_ptr(p7 = PKCS7_new()))
goto finish;
if (!TEST_true(PKCS7_set_type(p7, NID_pkcs7_data)))
goto finish;
error_callback_fired = 0;
if (!TEST_false(i2d_ASN1_bio_stream(out, (ASN1_VALUE*) p7, bio,
SMIME_STREAM | SMIME_BINARY,
ASN1_ITEM_rptr(PKCS7))))
goto finish;
if (!TEST_int_eq(error_callback_fired, 1))
goto finish;
ok = 1;
finish:
BIO_free(bio);
BIO_free(out);
PKCS7_free(p7);
return ok;
}
int setup_tests(void)
{
ADD_TEST(test_bio_memleak);
ADD_TEST(test_bio_get_mem);
ADD_TEST(test_bio_new_mem_buf);
ADD_TEST(test_bio_rdonly_mem_buf);
ADD_TEST(test_bio_rdwr_rdonly);
ADD_TEST(test_bio_nonclear_rst);
ADD_TEST(test_bio_i2d_ASN1_mime);
return 1;
}
| 7,357 | 24.19863 | 90 | c |
openssl | openssl-master/test/bio_prefix_text.c | /*
* Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include <stdarg.h>
#include <openssl/bio.h>
#include <openssl/safestack.h>
#include "opt.h"
static BIO *bio_in = NULL;
static BIO *bio_out = NULL;
static BIO *bio_err = NULL;
/*-
* This program sets up a chain of BIO_f_filter() on top of bio_out, how
* many is governed by the user through -n. It allows the user to set the
* indentation for each individual filter using -i and -p. Then it reads
* text from bio_in and prints it out through the BIO chain.
*
* The filter index is counted from the source/sink, i.e. index 0 is closest
* to it.
*
* Example:
*
* $ echo foo | ./bio_prefix_text -n 2 -i 1:32 -p 1:FOO -i 0:3
* FOO foo
* ^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* | |
* | +------ 32 spaces from filter 1
* +-------------------------- 3 spaces from filter 0
*/
static size_t amount = 0;
static BIO **chain = NULL;
typedef enum OPTION_choice {
OPT_ERR = -1,
OPT_EOF = 0,
OPT_AMOUNT,
OPT_INDENT,
OPT_PREFIX
} OPTION_CHOICE;
static const OPTIONS options[] = {
{ "n", OPT_AMOUNT, 'p', "Amount of BIO_f_prefix() filters" },
/*
* idx is the index to the BIO_f_filter chain(), where 0 is closest
* to the source/sink BIO. If idx isn't given, 0 is assumed
*/
{ "i", OPT_INDENT, 's', "Indentation in form '[idx:]indent'" },
{ "p", OPT_PREFIX, 's', "Prefix in form '[idx:]prefix'" },
{ NULL }
};
int opt_printf_stderr(const char *fmt, ...)
{
va_list ap;
int ret;
va_start(ap, fmt);
ret = BIO_vprintf(bio_err, fmt, ap);
va_end(ap);
return ret;
}
static int run_pipe(void)
{
char buf[4096];
while (!BIO_eof(bio_in)) {
size_t bytes_in;
size_t bytes_out;
if (!BIO_read_ex(bio_in, buf, sizeof(buf), &bytes_in))
return 0;
bytes_out = 0;
while (bytes_out < bytes_in) {
size_t bytes;
if (!BIO_write_ex(chain[amount - 1], buf, bytes_in, &bytes))
return 0;
bytes_out += bytes;
}
}
return 1;
}
static int setup_bio_chain(const char *progname)
{
BIO *next = NULL;
size_t n = amount;
chain = OPENSSL_zalloc(sizeof(*chain) * n);
if (chain != NULL) {
size_t i;
next = bio_out;
BIO_up_ref(next); /* Protection against freeing */
for (i = 0; n > 0; i++, n--) {
BIO *curr = BIO_new(BIO_f_prefix());
if (curr == NULL)
goto err;
chain[i] = BIO_push(curr, next);
if (chain[i] == NULL)
goto err;
next = chain[i];
}
}
return chain != NULL;
err:
/* Free the chain we built up */
BIO_free_all(next);
OPENSSL_free(chain);
return 0;
}
static void cleanup(void)
{
if (chain != NULL) {
BIO_free_all(chain[amount - 1]);
OPENSSL_free(chain);
}
BIO_free_all(bio_in);
BIO_free_all(bio_out);
BIO_free_all(bio_err);
}
static int setup(void)
{
OPTION_CHOICE o;
char *arg;
char *colon;
char *endptr;
size_t idx, indent;
const char *progname = opt_getprog();
bio_in = BIO_new_fp(stdin, BIO_NOCLOSE | BIO_FP_TEXT);
bio_out = BIO_new_fp(stdout, BIO_NOCLOSE | BIO_FP_TEXT);
bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);
#ifdef __VMS
bio_out = BIO_push(BIO_new(BIO_f_linebuffer()), bio_out);
bio_err = BIO_push(BIO_new(BIO_f_linebuffer()), bio_err);
#endif
OPENSSL_assert(bio_in != NULL);
OPENSSL_assert(bio_out != NULL);
OPENSSL_assert(bio_err != NULL);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_AMOUNT:
arg = opt_arg();
amount = strtoul(arg, &endptr, 10);
if (endptr[0] != '\0') {
BIO_printf(bio_err,
"%s: -n argument isn't a decimal number: %s",
progname, arg);
return 0;
}
if (amount < 1) {
BIO_printf(bio_err, "%s: must set up at least one filter",
progname);
return 0;
}
if (!setup_bio_chain(progname)) {
BIO_printf(bio_err, "%s: failed setting up filter chain",
progname);
return 0;
}
break;
case OPT_INDENT:
if (chain == NULL) {
BIO_printf(bio_err, "%s: -i given before -n", progname);
return 0;
}
arg = opt_arg();
colon = strchr(arg, ':');
idx = 0;
if (colon != NULL) {
idx = strtoul(arg, &endptr, 10);
if (endptr[0] != ':') {
BIO_printf(bio_err,
"%s: -i index isn't a decimal number: %s",
progname, arg);
return 0;
}
colon++;
} else {
colon = arg;
}
indent = strtoul(colon, &endptr, 10);
if (endptr[0] != '\0') {
BIO_printf(bio_err,
"%s: -i value isn't a decimal number: %s",
progname, arg);
return 0;
}
if (idx >= amount) {
BIO_printf(bio_err, "%s: index (%zu) not within range 0..%zu",
progname, idx, amount - 1);
return 0;
}
if (BIO_set_indent(chain[idx], (long)indent) <= 0) {
BIO_printf(bio_err, "%s: failed setting indentation: %s",
progname, arg);
return 0;
}
break;
case OPT_PREFIX:
if (chain == NULL) {
BIO_printf(bio_err, "%s: -p given before -n", progname);
return 0;
}
arg = opt_arg();
colon = strchr(arg, ':');
idx = 0;
if (colon != NULL) {
idx = strtoul(arg, &endptr, 10);
if (endptr[0] != ':') {
BIO_printf(bio_err,
"%s: -p index isn't a decimal number: %s",
progname, arg);
return 0;
}
colon++;
} else {
colon = arg;
}
if (idx >= amount) {
BIO_printf(bio_err, "%s: index (%zu) not within range 0..%zu",
progname, idx, amount - 1);
return 0;
}
if (BIO_set_prefix(chain[idx], colon) <= 0) {
BIO_printf(bio_err, "%s: failed setting prefix: %s",
progname, arg);
return 0;
}
break;
default:
case OPT_ERR:
return 0;
}
}
return 1;
}
int main(int argc, char **argv)
{
int rv = EXIT_SUCCESS;
opt_init(argc, argv, options);
rv = (setup() && run_pipe()) ? EXIT_SUCCESS : EXIT_FAILURE;
cleanup();
return rv;
}
| 7,570 | 27.25 | 78 | c |
openssl | openssl-master/test/bio_readbuffer_test.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/bio.h>
#include "testutil.h"
static const char *filename = NULL;
/*
* Test that a BIO_f_readbuffer() with a BIO_new_file() behaves nicely if
* BIO_gets() and BIO_read_ex() are both called.
* Since the BIO_gets() calls buffer the reads, the BIO_read_ex() should
* still be able to read the buffered data if we seek back to the start.
*
* The following cases are tested using tstid:
* 0 : Just use BIO_read_ex().
* 1 : Try a few reads using BIO_gets() before using BIO_read_ex()
* 2 : Read the entire file using BIO_gets() before using BIO_read_ex().
*/
static int test_readbuffer_file_bio(int tstid)
{
int ret = 0, len, partial;
BIO *in = NULL, *in_bio = NULL, *readbuf_bio = NULL;
char buf[255];
char expected[4096];
size_t readbytes = 0, bytes = 0, count = 0;
/* Open a file BIO and read all the data */
if (!TEST_ptr(in = BIO_new_file(filename, "r"))
|| !TEST_int_eq(BIO_read_ex(in, expected, sizeof(expected),
&readbytes), 1)
|| !TEST_int_lt(readbytes, sizeof(expected)))
goto err;
BIO_free(in);
in = NULL;
/* Create a new file bio that sits under a readbuffer BIO */
if (!TEST_ptr(readbuf_bio = BIO_new(BIO_f_readbuffer()))
|| !TEST_ptr(in_bio = BIO_new_file(filename, "r")))
goto err;
in_bio = BIO_push(readbuf_bio, in_bio);
readbuf_bio = NULL;
if (!TEST_int_eq(BIO_tell(in_bio), 0))
goto err;
if (tstid != 0) {
partial = 4;
while (!BIO_eof(in_bio)) {
len = BIO_gets(in_bio, buf, sizeof(buf));
if (len == 0) {
if (!TEST_true(BIO_eof(in_bio)))
goto err;
} else {
if (!TEST_int_gt(len, 0)
|| !TEST_int_le(len, (int)sizeof(buf) - 1))
goto err;
if (!TEST_true(buf[len] == 0))
goto err;
if (len > 1
&& !BIO_eof(in_bio)
&& len != ((int)sizeof(buf) - 1)
&& !TEST_true(buf[len - 1] == '\n'))
goto err;
}
if (tstid == 1 && --partial == 0)
break;
}
}
if (!TEST_int_eq(BIO_seek(in_bio, 0), 1))
goto err;
len = 8; /* Do a small partial read to start with */
while (!BIO_eof(in_bio)) {
if (!TEST_int_eq(BIO_read_ex(in_bio, buf, len, &bytes), 1))
break;
if (!TEST_mem_eq(buf, bytes, expected + count, bytes))
goto err;
count += bytes;
len = sizeof(buf); /* fill the buffer on subsequent reads */
}
if (!TEST_int_eq(count, readbytes))
goto err;
ret = 1;
err:
BIO_free(in);
BIO_free_all(in_bio);
BIO_free(readbuf_bio);
return ret;
}
typedef enum OPTION_choice {
OPT_ERR = -1,
OPT_EOF = 0,
OPT_TEST_ENUM
} OPTION_CHOICE;
const OPTIONS *test_get_options(void)
{
static const OPTIONS test_options[] = {
OPT_TEST_OPTIONS_WITH_EXTRA_USAGE("file\n"),
{ OPT_HELP_STR, 1, '-', "file\tFile to run tests on.\n" },
{ NULL }
};
return test_options;
}
int setup_tests(void)
{
OPTION_CHOICE o;
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_TEST_CASES:
break;
default:
return 0;
}
}
filename = test_get_argument(0);
ADD_ALL_TESTS(test_readbuffer_file_bio, 3);
return 1;
}
| 3,845 | 28.136364 | 74 | c |
openssl | openssl-master/test/bio_tfo_test.c | /*
* Copyright 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/bio.h>
#include "internal/e_os.h"
#include "internal/sockets.h"
#include "internal/bio_tfo.h"
#include "testutil.h"
/* If OS support is added in crypto/bio/bio_tfo.h, add it here */
#if defined(OPENSSL_SYS_LINUX)
# define GOOD_OS 1
#elif defined(__FreeBSD__)
# define GOOD_OS 1
#elif defined(OPENSSL_SYS_MACOSX)
# define GOOD_OS 1
#else
# ifdef GOOD_OS
# undef GOOD_OS
# endif
#endif
#if !defined(OPENSSL_NO_TFO) && defined(GOOD_OS)
/*
* This test is to ensure that if TCP Fast Open is configured, that socket
* connections will still work. These tests are able to detect if TCP Fast
* Open works, but the tests will pass as long as the socket connects.
*
* The first test function tests the socket interface as implemented as BIOs.
*
* The second test functions tests the socket interface as implemented as fds.
*
* The tests are run 5 times. The first time is without TFO.
* The second test will create the TCP fast open cookie,
* this can be seen in `ip tcp_metrics` and in /proc/net/netstat/ on Linux.
* e.g. on Linux 4.15.0-135-generic:
* $ grep '^TcpExt:' /proc/net/netstat | cut -d ' ' -f 84-90 | column -t
* The third attempt will use the cookie and actually do TCP fast open.
* The 4th time is client-TFO only, the 5th time is server-TFO only.
*/
# define SOCKET_DATA "FooBar"
# define SOCKET_DATA_LEN sizeof(SOCKET_DATA)
static int test_bio_tfo(int idx)
{
BIO *cbio = NULL;
BIO *abio = NULL;
BIO *sbio = NULL;
int ret = 0;
int sockerr = 0;
const char *port;
int server_tfo = 0;
int client_tfo = 0;
size_t bytes;
char read_buffer[20];
switch (idx) {
default:
case 0:
break;
case 1:
case 2:
server_tfo = 1;
client_tfo = 1;
break;
case 3:
client_tfo = 1;
break;
case 4:
server_tfo = 1;
break;
}
/* ACCEPT SOCKET */
if (!TEST_ptr(abio = BIO_new_accept("localhost:0"))
|| !TEST_true(BIO_set_nbio_accept(abio, 1))
|| !TEST_true(BIO_set_tfo_accept(abio, server_tfo))
|| !TEST_int_gt(BIO_do_accept(abio), 0)
|| !TEST_ptr(port = BIO_get_accept_port(abio))) {
sockerr = get_last_socket_error();
goto err;
}
/* Note: first BIO_do_accept will basically do the bind/listen */
/* CLIENT SOCKET */
if (!TEST_ptr(cbio = BIO_new_connect("localhost"))
|| !TEST_long_gt(BIO_set_conn_port(cbio, port), 0)
|| !TEST_long_gt(BIO_set_nbio(cbio, 1), 0)
|| !TEST_long_gt(BIO_set_tfo(cbio, client_tfo), 0)) {
sockerr = get_last_socket_error();
goto err;
}
/* FIRST ACCEPT: no connection should be established */
if (BIO_do_accept(abio) <= 0) {
if (!BIO_should_retry(abio)) {
sockerr = get_last_socket_error();
BIO_printf(bio_err, "Error: failed without EAGAIN\n");
goto err;
}
} else {
sbio = BIO_pop(abio);
BIO_printf(bio_err, "Error: accepted unknown connection\n");
goto err;
}
/* CONNECT ATTEMPT: different behavior based on TFO support */
if (BIO_do_connect(cbio) <= 0) {
sockerr = get_last_socket_error();
if (sockerr == EOPNOTSUPP) {
BIO_printf(bio_err, "Skip: TFO not enabled/supported for client\n");
goto success;
} else if (sockerr != EINPROGRESS) {
BIO_printf(bio_err, "Error: failed without EINPROGRESSn");
goto err;
}
}
/* macOS needs some time for this to happen, so put in a select */
if (!TEST_int_ge(BIO_wait(abio, time(NULL) + 2, 0), 0)) {
sockerr = get_last_socket_error();
BIO_printf(bio_err, "Error: socket wait failed\n");
goto err;
}
/* SECOND ACCEPT: if TFO is supported, this will still fail until data is sent */
if (BIO_do_accept(abio) <= 0) {
if (!BIO_should_retry(abio)) {
sockerr = get_last_socket_error();
BIO_printf(bio_err, "Error: failed without EAGAIN\n");
goto err;
}
} else {
if (idx == 0)
BIO_printf(bio_err, "Success: non-TFO connection accepted without data\n");
else if (idx == 1)
BIO_printf(bio_err, "Ignore: connection accepted before data, possibly no TFO cookie, or TFO may not be enabled\n");
else if (idx == 4)
BIO_printf(bio_err, "Success: connection accepted before data, client TFO is disabled\n");
else
BIO_printf(bio_err, "Warning: connection accepted before data, TFO may not be enabled\n");
sbio = BIO_pop(abio);
goto success;
}
/* SEND DATA: this should establish the actual TFO connection */
if (!TEST_true(BIO_write_ex(cbio, SOCKET_DATA, SOCKET_DATA_LEN, &bytes))) {
sockerr = get_last_socket_error();
goto err;
}
/* macOS needs some time for this to happen, so put in a select */
if (!TEST_int_ge(BIO_wait(abio, time(NULL) + 2, 0), 0)) {
sockerr = get_last_socket_error();
BIO_printf(bio_err, "Error: socket wait failed\n");
goto err;
}
/* FINAL ACCEPT: if TFO is enabled, socket should be accepted at *this* point */
if (BIO_do_accept(abio) <= 0) {
sockerr = get_last_socket_error();
BIO_printf(bio_err, "Error: socket not accepted\n");
goto err;
}
BIO_printf(bio_err, "Success: Server accepted socket after write\n");
if (!TEST_ptr(sbio = BIO_pop(abio))
|| !TEST_true(BIO_read_ex(sbio, read_buffer, sizeof(read_buffer), &bytes))
|| !TEST_size_t_eq(bytes, SOCKET_DATA_LEN)
|| !TEST_strn_eq(read_buffer, SOCKET_DATA, SOCKET_DATA_LEN)) {
sockerr = get_last_socket_error();
goto err;
}
success:
sockerr = 0;
ret = 1;
err:
if (sockerr != 0) {
const char *errstr = strerror(sockerr);
if (errstr != NULL)
BIO_printf(bio_err, "last errno: %d=%s\n", sockerr, errstr);
}
BIO_free(cbio);
BIO_free(abio);
BIO_free(sbio);
return ret;
}
static int test_fd_tfo(int idx)
{
struct sockaddr_storage sstorage;
socklen_t slen;
struct addrinfo *ai = NULL;
struct addrinfo hints;
int ret = 0;
int cfd = -1; /* client socket */
int afd = -1; /* accept socket */
int sfd = -1; /* server accepted socket */
BIO_ADDR *baddr = NULL;
char read_buffer[20];
int bytes_read;
int server_flags = BIO_SOCK_NONBLOCK;
int client_flags = BIO_SOCK_NONBLOCK;
int sockerr = 0;
unsigned short port;
void *addr;
size_t addrlen;
switch (idx) {
default:
case 0:
break;
case 1:
case 2:
server_flags |= BIO_SOCK_TFO;
client_flags |= BIO_SOCK_TFO;
break;
case 3:
client_flags |= BIO_SOCK_TFO;
break;
case 4:
server_flags |= BIO_SOCK_TFO;
break;
}
/* ADDRESS SETUP */
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (!TEST_int_eq(getaddrinfo(NULL, "0", &hints, &ai), 0))
goto err;
switch (ai->ai_family) {
case AF_INET:
port = ((struct sockaddr_in *)ai->ai_addr)->sin_port;
addr = &((struct sockaddr_in *)ai->ai_addr)->sin_addr;
addrlen = sizeof(((struct sockaddr_in *)ai->ai_addr)->sin_addr);
BIO_printf(bio_err, "Using IPv4\n");
break;
case AF_INET6:
port = ((struct sockaddr_in6 *)ai->ai_addr)->sin6_port;
addr = &((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr;
addrlen = sizeof(((struct sockaddr_in6 *)ai->ai_addr)->sin6_addr);
BIO_printf(bio_err, "Using IPv6\n");
break;
default:
BIO_printf(bio_err, "Unknown address family %d\n", ai->ai_family);
goto err;
}
if (!TEST_ptr(baddr = BIO_ADDR_new())
|| !TEST_true(BIO_ADDR_rawmake(baddr, ai->ai_family, addr, addrlen, port)))
goto err;
/* ACCEPT SOCKET */
if (!TEST_int_ge(afd = BIO_socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol, 0), 0)
|| !TEST_true(BIO_listen(afd, baddr, server_flags)))
goto err;
/* UPDATE ADDRESS WITH PORT */
slen = sizeof(sstorage);
if (!TEST_int_ge(getsockname(afd, (struct sockaddr *)&sstorage, &slen), 0))
goto err;
switch (sstorage.ss_family) {
case AF_INET:
port = ((struct sockaddr_in *)&sstorage)->sin_port;
addr = &((struct sockaddr_in *)&sstorage)->sin_addr;
addrlen = sizeof(((struct sockaddr_in *)&sstorage)->sin_addr);
break;
case AF_INET6:
port = ((struct sockaddr_in6 *)&sstorage)->sin6_port;
addr = &((struct sockaddr_in6 *)&sstorage)->sin6_addr;
addrlen = sizeof(((struct sockaddr_in6 *)&sstorage)->sin6_addr);
break;
default:
goto err;
}
if(!TEST_true(BIO_ADDR_rawmake(baddr, sstorage.ss_family, addr, addrlen, port)))
goto err;
/* CLIENT SOCKET */
if (!TEST_int_ge(cfd = BIO_socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol, 0), 0))
goto err;
/* FIRST ACCEPT: no connection should be established */
sfd = BIO_accept_ex(afd, NULL, 0);
if (sfd == -1) {
sockerr = get_last_socket_error();
/* Note: Windows would hit WSAEWOULDBLOCK */
if (sockerr != EAGAIN) {
BIO_printf(bio_err, "Error: failed without EAGAIN\n");
goto err;
}
} else {
BIO_printf(bio_err, "Error: accepted unknown connection\n");
goto err;
}
/* CONNECT ATTEMPT: different behavior based on TFO support */
if (!BIO_connect(cfd, baddr, client_flags)) {
sockerr = get_last_socket_error();
if (sockerr == EOPNOTSUPP) {
BIO_printf(bio_err, "Skip: TFO not enabled/supported for client\n");
goto success;
} else {
/* Note: Windows would hit WSAEWOULDBLOCK */
if (sockerr != EINPROGRESS) {
BIO_printf(bio_err, "Error: failed without EINPROGRESS\n");
goto err;
}
}
}
/* macOS needs some time for this to happen, so put in a select */
if (!TEST_int_ge(BIO_socket_wait(afd, 1, time(NULL) + 2), 0)) {
sockerr = get_last_socket_error();
BIO_printf(bio_err, "Error: socket wait failed\n");
goto err;
}
/* SECOND ACCEPT: if TFO is supported, this will still fail until data is sent */
sfd = BIO_accept_ex(afd, NULL, 0);
if (sfd == -1) {
sockerr = get_last_socket_error();
/* Note: Windows would hit WSAEWOULDBLOCK */
if (sockerr != EAGAIN) {
BIO_printf(bio_err, "Error: failed without EAGAIN\n");
goto err;
}
} else {
if (idx == 0)
BIO_printf(bio_err, "Success: non-TFO connection accepted without data\n");
else if (idx == 1)
BIO_printf(bio_err, "Ignore: connection accepted before data, possibly no TFO cookie, or TFO may not be enabled\n");
else if (idx == 4)
BIO_printf(bio_err, "Success: connection accepted before data, client TFO is disabled\n");
else
BIO_printf(bio_err, "Warning: connection accepted before data, TFO may not be enabled\n");
goto success;
}
/* SEND DATA: this should establish the actual TFO connection */
#ifdef OSSL_TFO_SENDTO
if (!TEST_int_ge(sendto(cfd, SOCKET_DATA, SOCKET_DATA_LEN, OSSL_TFO_SENDTO,
(struct sockaddr *)&sstorage, slen), 0)) {
sockerr = get_last_socket_error();
goto err;
}
#else
if (!TEST_int_ge(writesocket(cfd, SOCKET_DATA, SOCKET_DATA_LEN), 0)) {
sockerr = get_last_socket_error();
goto err;
}
#endif
/* macOS needs some time for this to happen, so put in a select */
if (!TEST_int_ge(BIO_socket_wait(afd, 1, time(NULL) + 2), 0)) {
sockerr = get_last_socket_error();
BIO_printf(bio_err, "Error: socket wait failed\n");
goto err;
}
/* FINAL ACCEPT: if TFO is enabled, socket should be accepted at *this* point */
sfd = BIO_accept_ex(afd, NULL, 0);
if (sfd == -1) {
sockerr = get_last_socket_error();
BIO_printf(bio_err, "Error: socket not accepted\n");
goto err;
}
BIO_printf(bio_err, "Success: Server accepted socket after write\n");
bytes_read = readsocket(sfd, read_buffer, sizeof(read_buffer));
if (!TEST_int_eq(bytes_read, SOCKET_DATA_LEN)
|| !TEST_strn_eq(read_buffer, SOCKET_DATA, SOCKET_DATA_LEN)) {
sockerr = get_last_socket_error();
goto err;
}
success:
sockerr = 0;
ret = 1;
err:
if (sockerr != 0) {
const char *errstr = strerror(sockerr);
if (errstr != NULL)
BIO_printf(bio_err, "last errno: %d=%s\n", sockerr, errstr);
}
if (ai != NULL)
freeaddrinfo(ai);
BIO_ADDR_free(baddr);
BIO_closesocket(cfd);
BIO_closesocket(sfd);
BIO_closesocket(afd);
return ret;
}
#endif
int setup_tests(void)
{
#if !defined(OPENSSL_NO_TFO) && defined(GOOD_OS)
ADD_ALL_TESTS(test_bio_tfo, 5);
ADD_ALL_TESTS(test_fd_tfo, 5);
#endif
return 1;
}
| 13,707 | 31.56057 | 128 | c |
openssl | openssl-master/test/bioprinttest.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
*/
#define TESTUTIL_NO_size_t_COMPARISON
#include <stdio.h>
#include <string.h>
#include <openssl/bio.h>
#include "internal/numbers.h"
#include "testutil.h"
#include "testutil/output.h"
#define nelem(x) (int)(sizeof(x) / sizeof((x)[0]))
static int justprint = 0;
static char *fpexpected[][10][5] = {
{
/* 00 */ { "0.0000e+00", "0.0000", "0", "0.0000E+00", "0" },
/* 01 */ { "6.7000e-01", "0.6700", "0.67", "6.7000E-01", "0.67" },
/* 02 */ { "6.6667e-01", "0.6667", "0.6667", "6.6667E-01", "0.6667" },
/* 03 */ { "6.6667e-04", "0.0007", "0.0006667", "6.6667E-04", "0.0006667" },
/* 04 */ { "6.6667e-05", "0.0001", "6.667e-05", "6.6667E-05", "6.667E-05" },
/* 05 */ { "6.6667e+00", "6.6667", "6.667", "6.6667E+00", "6.667" },
/* 06 */ { "6.6667e+01", "66.6667", "66.67", "6.6667E+01", "66.67" },
/* 07 */ { "6.6667e+02", "666.6667", "666.7", "6.6667E+02", "666.7" },
/* 08 */ { "6.6667e+03", "6666.6667", "6667", "6.6667E+03", "6667" },
/* 09 */ { "6.6667e+04", "66666.6667", "6.667e+04", "6.6667E+04", "6.667E+04" },
},
{
/* 10 */ { "0.00000e+00", "0.00000", "0", "0.00000E+00", "0" },
/* 11 */ { "6.70000e-01", "0.67000", "0.67", "6.70000E-01", "0.67" },
/* 12 */ { "6.66667e-01", "0.66667", "0.66667", "6.66667E-01", "0.66667" },
/* 13 */ { "6.66667e-04", "0.00067", "0.00066667", "6.66667E-04", "0.00066667" },
/* 14 */ { "6.66667e-05", "0.00007", "6.6667e-05", "6.66667E-05", "6.6667E-05" },
/* 15 */ { "6.66667e+00", "6.66667", "6.6667", "6.66667E+00", "6.6667" },
/* 16 */ { "6.66667e+01", "66.66667", "66.667", "6.66667E+01", "66.667" },
/* 17 */ { "6.66667e+02", "666.66667", "666.67", "6.66667E+02", "666.67" },
/* 18 */ { "6.66667e+03", "6666.66667", "6666.7", "6.66667E+03", "6666.7" },
/* 19 */ { "6.66667e+04", "66666.66667", "66667", "6.66667E+04", "66667" },
},
{
/* 20 */ { " 0.0000e+00", " 0.0000", " 0", " 0.0000E+00", " 0" },
/* 21 */ { " 6.7000e-01", " 0.6700", " 0.67", " 6.7000E-01", " 0.67" },
/* 22 */ { " 6.6667e-01", " 0.6667", " 0.6667", " 6.6667E-01", " 0.6667" },
/* 23 */ { " 6.6667e-04", " 0.0007", " 0.0006667", " 6.6667E-04", " 0.0006667" },
/* 24 */ { " 6.6667e-05", " 0.0001", " 6.667e-05", " 6.6667E-05", " 6.667E-05" },
/* 25 */ { " 6.6667e+00", " 6.6667", " 6.667", " 6.6667E+00", " 6.667" },
/* 26 */ { " 6.6667e+01", " 66.6667", " 66.67", " 6.6667E+01", " 66.67" },
/* 27 */ { " 6.6667e+02", " 666.6667", " 666.7", " 6.6667E+02", " 666.7" },
/* 28 */ { " 6.6667e+03", " 6666.6667", " 6667", " 6.6667E+03", " 6667" },
/* 29 */ { " 6.6667e+04", " 66666.6667", " 6.667e+04", " 6.6667E+04", " 6.667E+04" },
},
{
/* 30 */ { " 0.00000e+00", " 0.00000", " 0", " 0.00000E+00", " 0" },
/* 31 */ { " 6.70000e-01", " 0.67000", " 0.67", " 6.70000E-01", " 0.67" },
/* 32 */ { " 6.66667e-01", " 0.66667", " 0.66667", " 6.66667E-01", " 0.66667" },
/* 33 */ { " 6.66667e-04", " 0.00067", " 0.00066667", " 6.66667E-04", " 0.00066667" },
/* 34 */ { " 6.66667e-05", " 0.00007", " 6.6667e-05", " 6.66667E-05", " 6.6667E-05" },
/* 35 */ { " 6.66667e+00", " 6.66667", " 6.6667", " 6.66667E+00", " 6.6667" },
/* 36 */ { " 6.66667e+01", " 66.66667", " 66.667", " 6.66667E+01", " 66.667" },
/* 37 */ { " 6.66667e+02", " 666.66667", " 666.67", " 6.66667E+02", " 666.67" },
/* 38 */ { " 6.66667e+03", " 6666.66667", " 6666.7", " 6.66667E+03", " 6666.7" },
/* 39 */ { " 6.66667e+04", " 66666.66667", " 66667", " 6.66667E+04", " 66667" },
},
{
/* 40 */ { "0e+00", "0", "0", "0E+00", "0" },
/* 41 */ { "7e-01", "1", "0.7", "7E-01", "0.7" },
/* 42 */ { "7e-01", "1", "0.7", "7E-01", "0.7" },
/* 43 */ { "7e-04", "0", "0.0007", "7E-04", "0.0007" },
/* 44 */ { "7e-05", "0", "7e-05", "7E-05", "7E-05" },
/* 45 */ { "7e+00", "7", "7", "7E+00", "7" },
/* 46 */ { "7e+01", "67", "7e+01", "7E+01", "7E+01" },
/* 47 */ { "7e+02", "667", "7e+02", "7E+02", "7E+02" },
/* 48 */ { "7e+03", "6667", "7e+03", "7E+03", "7E+03" },
/* 49 */ { "7e+04", "66667", "7e+04", "7E+04", "7E+04" },
},
{
/* 50 */ { "0.000000e+00", "0.000000", "0", "0.000000E+00", "0" },
/* 51 */ { "6.700000e-01", "0.670000", "0.67", "6.700000E-01", "0.67" },
/* 52 */ { "6.666667e-01", "0.666667", "0.666667", "6.666667E-01", "0.666667" },
/* 53 */ { "6.666667e-04", "0.000667", "0.000666667", "6.666667E-04", "0.000666667" },
/* 54 */ { "6.666667e-05", "0.000067", "6.66667e-05", "6.666667E-05", "6.66667E-05" },
/* 55 */ { "6.666667e+00", "6.666667", "6.66667", "6.666667E+00", "6.66667" },
/* 56 */ { "6.666667e+01", "66.666667", "66.6667", "6.666667E+01", "66.6667" },
/* 57 */ { "6.666667e+02", "666.666667", "666.667", "6.666667E+02", "666.667" },
/* 58 */ { "6.666667e+03", "6666.666667", "6666.67", "6.666667E+03", "6666.67" },
/* 59 */ { "6.666667e+04", "66666.666667", "66666.7", "6.666667E+04", "66666.7" },
},
{
/* 60 */ { "0.0000e+00", "000.0000", "00000000", "0.0000E+00", "00000000" },
/* 61 */ { "6.7000e-01", "000.6700", "00000.67", "6.7000E-01", "00000.67" },
/* 62 */ { "6.6667e-01", "000.6667", "000.6667", "6.6667E-01", "000.6667" },
/* 63 */ { "6.6667e-04", "000.0007", "0.0006667", "6.6667E-04", "0.0006667" },
/* 64 */ { "6.6667e-05", "000.0001", "6.667e-05", "6.6667E-05", "6.667E-05" },
/* 65 */ { "6.6667e+00", "006.6667", "0006.667", "6.6667E+00", "0006.667" },
/* 66 */ { "6.6667e+01", "066.6667", "00066.67", "6.6667E+01", "00066.67" },
/* 67 */ { "6.6667e+02", "666.6667", "000666.7", "6.6667E+02", "000666.7" },
/* 68 */ { "6.6667e+03", "6666.6667", "00006667", "6.6667E+03", "00006667" },
/* 69 */ { "6.6667e+04", "66666.6667", "6.667e+04", "6.6667E+04", "6.667E+04" },
},
};
typedef struct z_data_st {
size_t value;
const char *format;
const char *expected;
} z_data;
static z_data zu_data[] = {
{ SIZE_MAX, "%zu", (sizeof(size_t) == 4 ? "4294967295"
: sizeof(size_t) == 8 ? "18446744073709551615"
: "") },
/*
* in 2-complement, the unsigned number divided by two plus one becomes the
* smallest possible negative signed number of the corresponding type
*/
{ SIZE_MAX / 2 + 1, "%zi", (sizeof(size_t) == 4 ? "-2147483648"
: sizeof(size_t) == 8 ? "-9223372036854775808"
: "") },
{ 0, "%zu", "0" },
{ 0, "%zi", "0" },
};
static int test_zu(int i)
{
char bio_buf[80];
const z_data *data = &zu_data[i];
BIO_snprintf(bio_buf, sizeof(bio_buf) - 1, data->format, data->value);
if (!TEST_str_eq(bio_buf, data->expected))
return 0;
return 1;
}
typedef struct j_data_st {
uint64_t value;
const char *format;
const char *expected;
} j_data;
static j_data jf_data[] = {
{ 0xffffffffffffffffULL, "%ju", "18446744073709551615" },
{ 0xffffffffffffffffULL, "%jx", "ffffffffffffffff" },
{ 0x8000000000000000ULL, "%ju", "9223372036854775808" },
/*
* These tests imply two's-complement, but it's the only binary
* representation we support, see test/sanitytest.c...
*/
{ 0x8000000000000000ULL, "%ji", "-9223372036854775808" },
};
static int test_j(int i)
{
const j_data *data = &jf_data[i];
char bio_buf[80];
BIO_snprintf(bio_buf, sizeof(bio_buf) - 1, data->format, data->value);
if (!TEST_str_eq(bio_buf, data->expected))
return 0;
return 1;
}
/* Precision and width. */
typedef struct pw_st {
int p;
const char *w;
} pw;
static pw pw_params[] = {
{ 4, "" },
{ 5, "" },
{ 4, "12" },
{ 5, "12" },
{ 0, "" },
{ -1, "" },
{ 4, "08" }
};
static int dofptest(int test, int sub, double val, const char *width, int prec)
{
static const char *fspecs[] = {
"e", "f", "g", "E", "G"
};
char format[80], result[80];
int ret = 1, i;
for (i = 0; i < nelem(fspecs); i++) {
const char *fspec = fspecs[i];
if (prec >= 0)
BIO_snprintf(format, sizeof(format), "%%%s.%d%s", width, prec,
fspec);
else
BIO_snprintf(format, sizeof(format), "%%%s%s", width, fspec);
BIO_snprintf(result, sizeof(result), format, val);
if (justprint) {
if (i == 0)
printf(" /* %d%d */ { \"%s\"", test, sub, result);
else
printf(", \"%s\"", result);
} else if (!TEST_str_eq(fpexpected[test][sub][i], result)) {
TEST_info("test %d format=|%s| exp=|%s|, ret=|%s|",
test, format, fpexpected[test][sub][i], result);
ret = 0;
}
}
if (justprint)
printf(" },\n");
return ret;
}
static int test_fp(int i)
{
int t = 0, r;
const double frac = 2.0 / 3.0;
const pw *pwp = &pw_params[i];
if (justprint)
printf(" {\n");
r = TEST_true(dofptest(i, t++, 0.0, pwp->w, pwp->p))
&& TEST_true(dofptest(i, t++, 0.67, pwp->w, pwp->p))
&& TEST_true(dofptest(i, t++, frac, pwp->w, pwp->p))
&& TEST_true(dofptest(i, t++, frac / 1000, pwp->w, pwp->p))
&& TEST_true(dofptest(i, t++, frac / 10000, pwp->w, pwp->p))
&& TEST_true(dofptest(i, t++, 6.0 + frac, pwp->w, pwp->p))
&& TEST_true(dofptest(i, t++, 66.0 + frac, pwp->w, pwp->p))
&& TEST_true(dofptest(i, t++, 666.0 + frac, pwp->w, pwp->p))
&& TEST_true(dofptest(i, t++, 6666.0 + frac, pwp->w, pwp->p))
&& TEST_true(dofptest(i, t++, 66666.0 + frac, pwp->w, pwp->p));
if (justprint)
printf(" },\n");
return r;
}
static int test_big(void)
{
char buf[80];
/* Test excessively big number. Should fail */
if (!TEST_int_eq(BIO_snprintf(buf, sizeof(buf),
"%f\n", 2 * (double)ULONG_MAX), -1))
return 0;
return 1;
}
typedef enum OPTION_choice {
OPT_ERR = -1,
OPT_EOF = 0,
OPT_PRINT,
OPT_TEST_ENUM
} OPTION_CHOICE;
const OPTIONS *test_get_options(void)
{
static const OPTIONS options[] = {
OPT_TEST_OPTIONS_DEFAULT_USAGE,
{ "expected", OPT_PRINT, '-', "Output values" },
{ NULL }
};
return options;
}
int setup_tests(void)
{
OPTION_CHOICE o;
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_PRINT:
justprint = 1;
break;
case OPT_TEST_CASES:
break;
default:
return 0;
}
}
ADD_TEST(test_big);
ADD_ALL_TESTS(test_fp, nelem(pw_params));
ADD_ALL_TESTS(test_zu, nelem(zu_data));
ADD_ALL_TESTS(test_j, nelem(jf_data));
return 1;
}
/*
* Replace testutil output routines. We do this to eliminate possible sources
* of BIO error
*/
BIO *bio_out = NULL;
BIO *bio_err = NULL;
static int tap_level = 0;
void test_open_streams(void)
{
}
void test_adjust_streams_tap_level(int level)
{
tap_level = level;
}
void test_close_streams(void)
{
}
/*
* This works out as long as caller doesn't use any "fancy" formats.
* But we are caller's caller, and test_str_eq is the only one called,
* and it uses only "%s", which is not "fancy"...
*/
int test_vprintf_stdout(const char *fmt, va_list ap)
{
return fprintf(stdout, "%*s# ", tap_level, "") + vfprintf(stdout, fmt, ap);
}
int test_vprintf_stderr(const char *fmt, va_list ap)
{
return fprintf(stderr, "%*s# ", tap_level, "") + vfprintf(stderr, fmt, ap);
}
int test_flush_stdout(void)
{
return fflush(stdout);
}
int test_flush_stderr(void)
{
return fflush(stderr);
}
int test_vprintf_tapout(const char *fmt, va_list ap)
{
return fprintf(stdout, "%*s", tap_level, "") + vfprintf(stdout, fmt, ap);
}
int test_vprintf_taperr(const char *fmt, va_list ap)
{
return fprintf(stderr, "%*s", tap_level, "") + vfprintf(stderr, fmt, ap);
}
int test_flush_tapout(void)
{
return fflush(stdout);
}
int test_flush_taperr(void)
{
return fflush(stderr);
}
| 12,760 | 34.15427 | 97 | c |
openssl | openssl-master/test/bn_internal_test.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 <assert.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <openssl/bn.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include "internal/nelem.h"
#include "internal/numbers.h"
#include "testutil.h"
#include "bn_prime.h"
#include "crypto/bn.h"
static BN_CTX *ctx;
static int test_is_prime_enhanced(void)
{
int ret;
int status = 0;
BIGNUM *bn = NULL;
ret = TEST_ptr(bn = BN_new())
/* test passing a prime returns the correct status */
&& TEST_true(BN_set_word(bn, 11))
/* return extra parameters related to composite */
&& TEST_true(ossl_bn_miller_rabin_is_prime(bn, 10, ctx, NULL, 1,
&status))
&& TEST_int_eq(status, BN_PRIMETEST_PROBABLY_PRIME);
BN_free(bn);
return ret;
}
static int composites[] = {
9, 21, 77, 81, 265
};
static int test_is_composite_enhanced(int id)
{
int ret;
int status = 0;
BIGNUM *bn = NULL;
ret = TEST_ptr(bn = BN_new())
/* negative tests for different composite numbers */
&& TEST_true(BN_set_word(bn, composites[id]))
&& TEST_true(ossl_bn_miller_rabin_is_prime(bn, 10, ctx, NULL, 1,
&status))
&& TEST_int_ne(status, BN_PRIMETEST_PROBABLY_PRIME);
BN_free(bn);
return ret;
}
/* Test that multiplying all the small primes from 3 to 751 equals a constant.
* This test is mainly used to test that both 32 and 64 bit are correct.
*/
static int test_bn_small_factors(void)
{
int ret = 0, i;
BIGNUM *b = NULL;
if (!(TEST_ptr(b = BN_new()) && TEST_true(BN_set_word(b, 3))))
goto err;
for (i = 1; i < NUMPRIMES; i++) {
prime_t p = primes[i];
if (p > 3 && p <= 751 && !BN_mul_word(b, p))
goto err;
if (p > 751)
break;
}
ret = TEST_BN_eq(ossl_bn_get0_small_factors(), b);
err:
BN_free(b);
return ret;
}
int setup_tests(void)
{
if (!TEST_ptr(ctx = BN_CTX_new()))
return 0;
ADD_TEST(test_is_prime_enhanced);
ADD_ALL_TESTS(test_is_composite_enhanced, (int)OSSL_NELEM(composites));
ADD_TEST(test_bn_small_factors);
return 1;
}
void cleanup_tests(void)
{
BN_CTX_free(ctx);
}
| 2,688 | 24.367925 | 78 | c |
openssl | openssl-master/test/bn_rand_range.h | /*
* WARNING: do not edit!
* Generated by statistics/bn_rand_range.py in the OpenSSL tool repository.
*
* Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
static const struct {
unsigned int range;
unsigned int iterations;
double critical;
} rand_range_cases[] = {
{ 2, 200, 3.841459 },
{ 3, 300, 5.991465 },
{ 4, 400, 7.814728 },
{ 5, 500, 9.487729 },
{ 6, 600, 11.070498 },
{ 7, 700, 12.591587 },
{ 8, 800, 14.067140 },
{ 9, 900, 15.507313 },
{ 10, 1000, 16.918978 },
{ 11, 1100, 18.307038 },
{ 12, 1200, 19.675138 },
{ 13, 1300, 21.026070 },
{ 14, 1400, 22.362032 },
{ 15, 1500, 23.684791 },
{ 16, 1600, 24.995790 },
{ 17, 1700, 26.296228 },
{ 18, 1800, 27.587112 },
{ 19, 1900, 28.869299 },
{ 20, 2000, 30.143527 },
{ 30, 3000, 42.556968 },
{ 40, 4000, 54.572228 },
{ 50, 5000, 66.338649 },
{ 60, 6000, 77.930524 },
{ 70, 7000, 89.391208 },
{ 80, 8000, 100.748619 },
{ 90, 9000, 112.021986 },
{ 100, 10000, 123.225221 },
{ 1000, 10000, 1073.642651 },
{ 2000, 20000, 2104.128222 },
{ 3000, 30000, 3127.515432 },
{ 4000, 40000, 4147.230012 },
{ 5000, 50000, 5164.598069 },
{ 6000, 60000, 6180.299514 },
{ 7000, 70000, 7194.738181 },
{ 8000, 80000, 8208.177159 },
{ 9000, 90000, 9220.799176 },
{ 10000, 100000, 10232.737266 },
};
static const int binomial_critical = 29;
| 2,009 | 33.067797 | 75 | h |
openssl | openssl-master/test/build_wincrypt_test.c | /*
* Copyright 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
*/
/*
* Simple buildtest to check for symbol collisions between wincrypt and
* OpenSSL headers
*/
#include <openssl/types.h>
#ifdef _WIN32
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# include <wincrypt.h>
# ifndef X509_NAME
# ifndef PEDANTIC
# ifdef _MSC_VER
# pragma message("wincrypt.h no longer defining X509_NAME before OpenSSL headers")
# else
# warning "wincrypt.h no longer defining X509_NAME before OpenSSL headers"
# endif
# endif
# endif
#endif
#include <openssl/opensslconf.h>
#ifndef OPENSSL_NO_STDIO
# include <stdio.h>
#endif
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
int main(void)
{
return 0;
}
| 1,056 | 21.489362 | 87 | c |
openssl | openssl-master/test/ca_internals_test.c | /*
* Copyright 2021-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 <string.h>
#include "apps.h"
#include "testutil.h"
#include "crypto/asn1.h"
#define binname "ca_internals_test"
char *default_config_file = NULL;
static int test_do_updatedb(void)
{
CA_DB *db = NULL;
time_t testdateutc;
int rv;
size_t argc = test_get_argument_count();
BIO *bio_tmp;
char *testdate;
char *indexfile;
int need64bit;
int have64bit;
if (argc != 4) {
TEST_error("Usage: %s: do_updatedb dbfile testdate need64bit\n", binname);
TEST_error(" testdate format: ASN1-String\n");
return 0;
}
/*
* if the test will only work with 64bit time_t and
* the build only supports 32, assume the test as success
*/
need64bit = (int)strtol(test_get_argument(3), NULL, 0);
have64bit = sizeof(time_t) > sizeof(uint32_t);
if (need64bit && !have64bit) {
BIO_printf(bio_out, "skipping test (need64bit: %i, have64bit: %i)",
need64bit, have64bit);
return 1;
}
testdate = test_get_argument(2);
testdateutc = ossl_asn1_string_to_time_t(testdate);
if (TEST_time_t_lt(testdateutc, 0)) {
return 0;
}
indexfile = test_get_argument(1);
db = load_index(indexfile, NULL);
if (TEST_ptr_null(db)) {
return 0;
}
bio_tmp = bio_err;
bio_err = bio_out;
rv = do_updatedb(db, &testdateutc);
bio_err = bio_tmp;
if (rv > 0) {
if (!TEST_true(save_index(indexfile, "new", db)))
goto end;
if (!TEST_true(rotate_index(indexfile, "new", "old")))
goto end;
}
end:
free_index(db);
return 1;
}
int setup_tests(void)
{
char *command = test_get_argument(0);
if (test_get_argument_count() < 1) {
TEST_error("%s: no command specified for testing\n", binname);
return 0;
}
if (strcmp(command, "do_updatedb") == 0)
return test_do_updatedb();
TEST_error("%s: command '%s' is not supported for testing\n", binname, command);
return 0;
}
| 2,356 | 24.074468 | 84 | c |
openssl | openssl-master/test/casttest.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
*/
/*
* CAST 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 <stdlib.h>
#include <openssl/opensslconf.h> /* To see if OPENSSL_NO_CAST is defined */
#include "internal/nelem.h"
#include "testutil.h"
#ifndef OPENSSL_NO_CAST
# include <openssl/cast.h>
static unsigned char k[16] = {
0x01, 0x23, 0x45, 0x67, 0x12, 0x34, 0x56, 0x78,
0x23, 0x45, 0x67, 0x89, 0x34, 0x56, 0x78, 0x9A
};
static unsigned char in[8] =
{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };
static int k_len[3] = { 16, 10, 5 };
static unsigned char c[3][8] = {
{0x23, 0x8B, 0x4F, 0xE5, 0x84, 0x7E, 0x44, 0xB2},
{0xEB, 0x6A, 0x71, 0x1A, 0x2C, 0x02, 0x27, 0x1B},
{0x7A, 0xC8, 0x16, 0xD1, 0x6E, 0x9B, 0x30, 0x2E},
};
static unsigned char in_a[16] = {
0x01, 0x23, 0x45, 0x67, 0x12, 0x34, 0x56, 0x78,
0x23, 0x45, 0x67, 0x89, 0x34, 0x56, 0x78, 0x9A
};
static unsigned char in_b[16] = {
0x01, 0x23, 0x45, 0x67, 0x12, 0x34, 0x56, 0x78,
0x23, 0x45, 0x67, 0x89, 0x34, 0x56, 0x78, 0x9A
};
static unsigned char c_a[16] = {
0xEE, 0xA9, 0xD0, 0xA2, 0x49, 0xFD, 0x3B, 0xA6,
0xB3, 0x43, 0x6F, 0xB8, 0x9D, 0x6D, 0xCA, 0x92
};
static unsigned char c_b[16] = {
0xB2, 0xC9, 0x5E, 0xB0, 0x0C, 0x31, 0xAD, 0x71,
0x80, 0xAC, 0x05, 0xB8, 0xE8, 0x3D, 0x69, 0x6E
};
static int cast_test_vector(int z)
{
int testresult = 1;
CAST_KEY key;
unsigned char out[80];
CAST_set_key(&key, k_len[z], k);
CAST_ecb_encrypt(in, out, &key, CAST_ENCRYPT);
if (!TEST_mem_eq(out, sizeof(c[z]), c[z], sizeof(c[z]))) {
TEST_info("CAST_ENCRYPT iteration %d failed (len=%d)", z, k_len[z]);
testresult = 0;
}
CAST_ecb_encrypt(out, out, &key, CAST_DECRYPT);
if (!TEST_mem_eq(out, sizeof(in), in, sizeof(in))) {
TEST_info("CAST_DECRYPT iteration %d failed (len=%d)", z, k_len[z]);
testresult = 0;
}
return testresult;
}
static int cast_test_iterations(void)
{
long l;
int testresult = 1;
CAST_KEY key, key_b;
unsigned char out_a[16], out_b[16];
memcpy(out_a, in_a, sizeof(in_a));
memcpy(out_b, in_b, sizeof(in_b));
for (l = 0; l < 1000000L; l++) {
CAST_set_key(&key_b, 16, out_b);
CAST_ecb_encrypt(&(out_a[0]), &(out_a[0]), &key_b, CAST_ENCRYPT);
CAST_ecb_encrypt(&(out_a[8]), &(out_a[8]), &key_b, CAST_ENCRYPT);
CAST_set_key(&key, 16, out_a);
CAST_ecb_encrypt(&(out_b[0]), &(out_b[0]), &key, CAST_ENCRYPT);
CAST_ecb_encrypt(&(out_b[8]), &(out_b[8]), &key, CAST_ENCRYPT);
}
if (!TEST_mem_eq(out_a, sizeof(c_a), c_a, sizeof(c_a))
|| !TEST_mem_eq(out_b, sizeof(c_b), c_b, sizeof(c_b)))
testresult = 0;
return testresult;
}
#endif
int setup_tests(void)
{
#ifndef OPENSSL_NO_CAST
ADD_ALL_TESTS(cast_test_vector, OSSL_NELEM(k_len));
ADD_TEST(cast_test_iterations);
#endif
return 1;
}
| 3,320 | 26.907563 | 76 | c |
openssl | openssl-master/test/cc_dummy.c | /*
* Copyright 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/quic_cc.h"
#include "internal/quic_types.h"
typedef struct ossl_cc_dummy_st {
size_t max_dgram_len;
size_t *p_diag_max_dgram_len;
} OSSL_CC_DUMMY;
static void dummy_update_diag(OSSL_CC_DUMMY *d);
static OSSL_CC_DATA *dummy_new(OSSL_TIME (*now_cb)(void *arg),
void *now_cb_arg)
{
OSSL_CC_DUMMY *d = OPENSSL_zalloc(sizeof(*d));
if (d == NULL)
return NULL;
d->max_dgram_len = QUIC_MIN_INITIAL_DGRAM_LEN;
return (OSSL_CC_DATA *)d;
}
static void dummy_free(OSSL_CC_DATA *cc)
{
OPENSSL_free(cc);
}
static void dummy_reset(OSSL_CC_DATA *cc)
{
}
static int dummy_set_input_params(OSSL_CC_DATA *cc, const OSSL_PARAM *params)
{
OSSL_CC_DUMMY *d = (OSSL_CC_DUMMY *)cc;
const OSSL_PARAM *p;
size_t value;
p = OSSL_PARAM_locate_const(params, OSSL_CC_OPTION_MAX_DGRAM_PAYLOAD_LEN);
if (p != NULL) {
if (!OSSL_PARAM_get_size_t(p, &value))
return 0;
if (value < QUIC_MIN_INITIAL_DGRAM_LEN)
return 0;
d->max_dgram_len = value;
dummy_update_diag(d);
}
return 1;
}
static int dummy_bind_diagnostic(OSSL_CC_DATA *cc, OSSL_PARAM *params)
{
OSSL_CC_DUMMY *d = (OSSL_CC_DUMMY *)cc;
const OSSL_PARAM *p;
p = OSSL_PARAM_locate_const(params, OSSL_CC_OPTION_MAX_DGRAM_PAYLOAD_LEN);
if (p != NULL) {
if (p->data_type != OSSL_PARAM_UNSIGNED_INTEGER
|| p->data_size != sizeof(size_t))
return 0;
d->p_diag_max_dgram_len = p->data;
}
dummy_update_diag(d);
return 1;
}
static int dummy_unbind_diagnostic(OSSL_CC_DATA *cc, OSSL_PARAM *params)
{
OSSL_CC_DUMMY *d = (OSSL_CC_DUMMY *)cc;
if (OSSL_PARAM_locate_const(params, OSSL_CC_OPTION_MAX_DGRAM_PAYLOAD_LEN)
!= NULL)
d->p_diag_max_dgram_len = NULL;
return 1;
}
static void dummy_update_diag(OSSL_CC_DUMMY *d)
{
if (d->p_diag_max_dgram_len != NULL)
*d->p_diag_max_dgram_len = d->max_dgram_len;
}
static uint64_t dummy_get_tx_allowance(OSSL_CC_DATA *cc)
{
return SIZE_MAX;
}
static OSSL_TIME dummy_get_wakeup_deadline(OSSL_CC_DATA *cc)
{
return ossl_time_infinite();
}
static int dummy_on_data_sent(OSSL_CC_DATA *cc,
uint64_t num_bytes)
{
return 1;
}
static int dummy_on_data_acked(OSSL_CC_DATA *cc,
const OSSL_CC_ACK_INFO *info)
{
return 1;
}
static int dummy_on_data_lost(OSSL_CC_DATA *cc,
const OSSL_CC_LOSS_INFO *info)
{
return 1;
}
static int dummy_on_data_lost_finished(OSSL_CC_DATA *cc,
uint32_t flags)
{
return 1;
}
static int dummy_on_data_invalidated(OSSL_CC_DATA *cc,
uint64_t num_bytes)
{
return 1;
}
const OSSL_CC_METHOD ossl_cc_dummy_method = {
dummy_new,
dummy_free,
dummy_reset,
dummy_set_input_params,
dummy_bind_diagnostic,
dummy_unbind_diagnostic,
dummy_get_tx_allowance,
dummy_get_wakeup_deadline,
dummy_on_data_sent,
dummy_on_data_acked,
dummy_on_data_lost,
dummy_on_data_lost_finished,
dummy_on_data_invalidated,
};
| 3,538 | 22.282895 | 78 | c |
openssl | openssl-master/test/cert_comp_test.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
*/
/*
* We need access to the deprecated low level HMAC APIs for legacy purposes
* when the deprecated calls are not hidden
*/
#ifndef OPENSSL_NO_DEPRECATED_3_0
# define OPENSSL_SUPPRESS_DEPRECATED
#endif
#include <openssl/ssl.h>
#include "internal/nelem.h"
#include "helpers/ssltestlib.h"
#include "testutil.h"
#include "../ssl/ssl_local.h"
#undef OSSL_NO_USABLE_TLS1_3
#if defined(OPENSSL_NO_TLS1_3) \
|| (defined(OPENSSL_NO_EC) && defined(OPENSSL_NO_DH))
/*
* If we don't have ec or dh then there are no built-in groups that are usable
* with TLSv1.3
*/
# define OSSL_NO_USABLE_TLS1_3
#endif
#if !defined(OSSL_NO_USEABLE_TLS1_3)
static char *certsdir = NULL;
static char *cert = NULL;
static char *privkey = NULL;
static int client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
{
X509 *xcert;
EVP_PKEY *privpkey;
BIO *in = NULL;
BIO *priv_in = NULL;
/* Check that SSL_get0_peer_certificate() returns something sensible */
if (!TEST_ptr(SSL_get0_peer_certificate(ssl)))
return 0;
in = BIO_new_file(cert, "r");
if (!TEST_ptr(in))
return 0;
if (!TEST_ptr(xcert = X509_new_ex(NULL, NULL))
|| !TEST_ptr(PEM_read_bio_X509(in, &xcert, NULL, NULL))
|| !TEST_ptr(priv_in = BIO_new_file(privkey, "r"))
|| !TEST_ptr(privpkey = PEM_read_bio_PrivateKey_ex(priv_in, NULL,
NULL, NULL,
NULL, NULL)))
goto err;
*x509 = xcert;
*pkey = privpkey;
BIO_free(in);
BIO_free(priv_in);
return 1;
err:
X509_free(xcert);
BIO_free(in);
BIO_free(priv_in);
return 0;
}
static int verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
{
return 1;
}
/*
* Test 0 = app pre-compresses certificate in SSL
* Test 1 = app pre-compresses certificate in SSL_CTX
* Test 2 = app pre-compresses certificate in SSL_CTX, client authentication
* Test 3 = app pre-compresses certificate in SSL_CTX, but it's unused due to prefs
*/
/* Compression helper */
static int ssl_comp_cert(SSL *ssl, int alg)
{
unsigned char *comp_data = NULL;
size_t comp_len = 0;
size_t orig_len = 0;
int retval = 0;
if (!TEST_size_t_gt(comp_len = SSL_get1_compressed_cert(ssl, alg, &comp_data, &orig_len), 0))
goto err;
if (!TEST_true(SSL_set1_compressed_cert(ssl, alg, comp_data, comp_len, orig_len)))
goto err;
retval = alg;
err:
OPENSSL_free(comp_data);
return retval;
}
static void cert_comp_info_cb(const SSL *s, int where, int ret)
{
int *seen = (int*)SSL_get_app_data(s);
if (SSL_is_server(s)) {
/* TLS_ST_SR_COMP_CERT */
if (!strcmp(SSL_state_string(s), "TRCCC") && seen != NULL)
*seen = 1;
} else {
/* TLS_ST_CR_COMP_CERT */
if (!strcmp(SSL_state_string(s), "TRSCC") && seen != NULL)
*seen = 1;
}
}
static int test_ssl_cert_comp(int test)
{
SSL_CTX *cctx = NULL, *sctx = NULL;
SSL *clientssl = NULL, *serverssl = NULL;
int testresult = 0;
int expected_client = TLSEXT_comp_cert_none;
int expected_server = TLSEXT_comp_cert_none;
int client_seen = 0;
int server_seen = 0;
/* reverse default order */
int server_pref[] = { TLSEXT_comp_cert_zstd, TLSEXT_comp_cert_zlib, TLSEXT_comp_cert_brotli };
/* default order */
int client_pref[] = { TLSEXT_comp_cert_brotli, TLSEXT_comp_cert_zlib, TLSEXT_comp_cert_zstd };
/* one of these *must* be defined! */
#ifndef OPENSSL_NO_BROTLI
expected_server = TLSEXT_comp_cert_brotli;
expected_client = TLSEXT_comp_cert_brotli;
#endif
#ifndef OPENSSL_NO_ZLIB
expected_server = TLSEXT_comp_cert_zlib;
if (expected_client == TLSEXT_comp_cert_none)
expected_client = TLSEXT_comp_cert_zlib;
#endif
#ifndef OPENSSL_NO_ZSTD
expected_server = TLSEXT_comp_cert_zstd;
if (expected_client == TLSEXT_comp_cert_none)
expected_client = TLSEXT_comp_cert_zstd;
#endif
/*
* If there's only one comp algorithm, pref won't do much
* Coverity can get confused in this case, and consider test == 3
* to be DEADCODE
*/
if (test == 3 && expected_client == expected_server) {
TEST_info("Only one compression algorithm configured");
return 1;
}
if (!TEST_true(create_ssl_ctx_pair(NULL, TLS_server_method(),
TLS_client_method(),
TLS1_3_VERSION, 0,
&sctx, &cctx, cert, privkey)))
goto end;
if (test == 3) {
/* coverity[deadcode] */
server_pref[0] = expected_server;
server_pref[1] = expected_client;
if (!TEST_true(SSL_CTX_set1_cert_comp_preference(sctx, server_pref, 2)))
goto end;
client_pref[0] = expected_client;
if (!TEST_true(SSL_CTX_set1_cert_comp_preference(cctx, client_pref, 1)))
goto end;
} else {
if (!TEST_true(SSL_CTX_set1_cert_comp_preference(sctx, server_pref, OSSL_NELEM(server_pref))))
goto end;
if (!TEST_true(SSL_CTX_set1_cert_comp_preference(cctx, client_pref, OSSL_NELEM(client_pref))))
goto end;
}
if (test == 2) {
/* Use callbacks from test_client_cert_cb() */
SSL_CTX_set_client_cert_cb(cctx, client_cert_cb);
SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
}
if (test == 1 || test== 2 || test == 3) {
if (!TEST_true(SSL_CTX_compress_certs(sctx, expected_server)))
goto end;
}
if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
NULL, NULL)))
goto end;
if (!TEST_true(SSL_set_app_data(clientssl, &client_seen)))
goto end;
if (!TEST_true(SSL_set_app_data(serverssl, &server_seen)))
goto end;
SSL_set_info_callback(clientssl, cert_comp_info_cb);
SSL_set_info_callback(serverssl, cert_comp_info_cb);
if (test == 0) {
if (!TEST_int_eq(ssl_comp_cert(serverssl, expected_server), expected_server))
goto end;
}
if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
goto end;
if (test == 3) {
/* coverity[deadcode] */
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(serverssl);
/* expect that the pre-compressed cert won't be used */
if (!TEST_int_eq(sc->cert->key->cert_comp_used, 0))
goto end;
if (!TEST_false(*(int*)SSL_get_app_data(clientssl)))
goto end;
} else {
SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(serverssl);
if (!TEST_int_gt(sc->cert->key->cert_comp_used, 0))
goto end;
if (!TEST_true(*(int*)SSL_get_app_data(clientssl)))
goto end;
}
if (test == 2) {
/* Only for client auth */
if (!TEST_true(*(int*)SSL_get_app_data(serverssl)))
goto end;
}
testresult = 1;
end:
SSL_free(serverssl);
SSL_free(clientssl);
SSL_CTX_free(sctx);
SSL_CTX_free(cctx);
return testresult;
}
#endif
OPT_TEST_DECLARE_USAGE("certdir\n")
int setup_tests(void)
{
#if !defined(OSSL_NO_USEABLE_TLS1_3)
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
if (!TEST_ptr(certsdir = test_get_argument(0)))
return 0;
cert = test_mk_file_path(certsdir, "servercert.pem");
if (cert == NULL)
goto err;
privkey = test_mk_file_path(certsdir, "serverkey.pem");
if (privkey == NULL)
goto err;
ADD_ALL_TESTS(test_ssl_cert_comp, 4);
return 1;
err:
OPENSSL_free(cert);
OPENSSL_free(privkey);
return 0;
#else
return 1;
#endif
}
void cleanup_tests(void)
{
#if !defined(OSSL_NO_USEABLE_TLS1_3)
OPENSSL_free(cert);
OPENSSL_free(privkey);
#endif
}
| 8,330 | 27.927083 | 102 | c |
openssl | openssl-master/test/chacha_internal_test.c | /*
* Copyright 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
*/
/*
* Internal tests for the chacha module. EVP tests would exercise
* complete 32-byte blocks. This test goes per byte...
*/
#include <string.h>
#include <openssl/opensslconf.h>
#include "testutil.h"
#include "crypto/chacha.h"
static const unsigned int key[] = {
0x03020100, 0x07060504, 0x0b0a0908, 0x0f0e0d0c,
0x13121110, 0x17161514, 0x1b1a1918, 0x1f1e1d1c
};
static const unsigned int ivp[] = {
0x00000000, 0x00000000, 0x03020100, 0x07060504
};
static const unsigned char ref[] = {
0xf7, 0x98, 0xa1, 0x89, 0xf1, 0x95, 0xe6, 0x69,
0x82, 0x10, 0x5f, 0xfb, 0x64, 0x0b, 0xb7, 0x75,
0x7f, 0x57, 0x9d, 0xa3, 0x16, 0x02, 0xfc, 0x93,
0xec, 0x01, 0xac, 0x56, 0xf8, 0x5a, 0xc3, 0xc1,
0x34, 0xa4, 0x54, 0x7b, 0x73, 0x3b, 0x46, 0x41,
0x30, 0x42, 0xc9, 0x44, 0x00, 0x49, 0x17, 0x69,
0x05, 0xd3, 0xbe, 0x59, 0xea, 0x1c, 0x53, 0xf1,
0x59, 0x16, 0x15, 0x5c, 0x2b, 0xe8, 0x24, 0x1a,
0x38, 0x00, 0x8b, 0x9a, 0x26, 0xbc, 0x35, 0x94,
0x1e, 0x24, 0x44, 0x17, 0x7c, 0x8a, 0xde, 0x66,
0x89, 0xde, 0x95, 0x26, 0x49, 0x86, 0xd9, 0x58,
0x89, 0xfb, 0x60, 0xe8, 0x46, 0x29, 0xc9, 0xbd,
0x9a, 0x5a, 0xcb, 0x1c, 0xc1, 0x18, 0xbe, 0x56,
0x3e, 0xb9, 0xb3, 0xa4, 0xa4, 0x72, 0xf8, 0x2e,
0x09, 0xa7, 0xe7, 0x78, 0x49, 0x2b, 0x56, 0x2e,
0xf7, 0x13, 0x0e, 0x88, 0xdf, 0xe0, 0x31, 0xc7,
0x9d, 0xb9, 0xd4, 0xf7, 0xc7, 0xa8, 0x99, 0x15,
0x1b, 0x9a, 0x47, 0x50, 0x32, 0xb6, 0x3f, 0xc3,
0x85, 0x24, 0x5f, 0xe0, 0x54, 0xe3, 0xdd, 0x5a,
0x97, 0xa5, 0xf5, 0x76, 0xfe, 0x06, 0x40, 0x25,
0xd3, 0xce, 0x04, 0x2c, 0x56, 0x6a, 0xb2, 0xc5,
0x07, 0xb1, 0x38, 0xdb, 0x85, 0x3e, 0x3d, 0x69,
0x59, 0x66, 0x09, 0x96, 0x54, 0x6c, 0xc9, 0xc4,
0xa6, 0xea, 0xfd, 0xc7, 0x77, 0xc0, 0x40, 0xd7,
0x0e, 0xaf, 0x46, 0xf7, 0x6d, 0xad, 0x39, 0x79,
0xe5, 0xc5, 0x36, 0x0c, 0x33, 0x17, 0x16, 0x6a,
0x1c, 0x89, 0x4c, 0x94, 0xa3, 0x71, 0x87, 0x6a,
0x94, 0xdf, 0x76, 0x28, 0xfe, 0x4e, 0xaa, 0xf2,
0xcc, 0xb2, 0x7d, 0x5a, 0xaa, 0xe0, 0xad, 0x7a,
0xd0, 0xf9, 0xd4, 0xb6, 0xad, 0x3b, 0x54, 0x09,
0x87, 0x46, 0xd4, 0x52, 0x4d, 0x38, 0x40, 0x7a,
0x6d, 0xeb, 0x3a, 0xb7, 0x8f, 0xab, 0x78, 0xc9,
0x42, 0x13, 0x66, 0x8b, 0xbb, 0xd3, 0x94, 0xc5,
0xde, 0x93, 0xb8, 0x53, 0x17, 0x8a, 0xdd, 0xd6,
0xb9, 0x7f, 0x9f, 0xa1, 0xec, 0x3e, 0x56, 0xc0,
0x0c, 0x9d, 0xdf, 0xf0, 0xa4, 0x4a, 0x20, 0x42,
0x41, 0x17, 0x5a, 0x4c, 0xab, 0x0f, 0x96, 0x1b,
0xa5, 0x3e, 0xde, 0x9b, 0xdf, 0x96, 0x0b, 0x94,
0xf9, 0x82, 0x9b, 0x1f, 0x34, 0x14, 0x72, 0x64,
0x29, 0xb3, 0x62, 0xc5, 0xb5, 0x38, 0xe3, 0x91,
0x52, 0x0f, 0x48, 0x9b, 0x7e, 0xd8, 0xd2, 0x0a,
0xe3, 0xfd, 0x49, 0xe9, 0xe2, 0x59, 0xe4, 0x43,
0x97, 0x51, 0x4d, 0x61, 0x8c, 0x96, 0xc4, 0x84,
0x6b, 0xe3, 0xc6, 0x80, 0xbd, 0xc1, 0x1c, 0x71,
0xdc, 0xbb, 0xe2, 0x9c, 0xcf, 0x80, 0xd6, 0x2a,
0x09, 0x38, 0xfa, 0x54, 0x93, 0x91, 0xe6, 0xea,
0x57, 0xec, 0xbe, 0x26, 0x06, 0x79, 0x0e, 0xc1,
0x5d, 0x22, 0x24, 0xae, 0x30, 0x7c, 0x14, 0x42,
0x26, 0xb7, 0xc4, 0xe8, 0xc2, 0xf9, 0x7d, 0x2a,
0x1d, 0x67, 0x85, 0x2d, 0x29, 0xbe, 0xba, 0x11,
0x0e, 0xdd, 0x44, 0x51, 0x97, 0x01, 0x20, 0x62,
0xa3, 0x93, 0xa9, 0xc9, 0x28, 0x03, 0xad, 0x3b,
0x4f, 0x31, 0xd7, 0xbc, 0x60, 0x33, 0xcc, 0xf7,
0x93, 0x2c, 0xfe, 0xd3, 0xf0, 0x19, 0x04, 0x4d,
0x25, 0x90, 0x59, 0x16, 0x77, 0x72, 0x86, 0xf8,
0x2f, 0x9a, 0x4c, 0xc1, 0xff, 0xe4, 0x30, 0xff,
0xd1, 0xdc, 0xfc, 0x27, 0xde, 0xed, 0x32, 0x7b,
0x9f, 0x96, 0x30, 0xd2, 0xfa, 0x96, 0x9f, 0xb6,
0xf0, 0x60, 0x3c, 0xd1, 0x9d, 0xd9, 0xa9, 0x51,
0x9e, 0x67, 0x3b, 0xcf, 0xcd, 0x90, 0x14, 0x12,
0x52, 0x91, 0xa4, 0x46, 0x69, 0xef, 0x72, 0x85,
0xe7, 0x4e, 0xd3, 0x72, 0x9b, 0x67, 0x7f, 0x80,
0x1c, 0x3c, 0xdf, 0x05, 0x8c, 0x50, 0x96, 0x31,
0x68, 0xb4, 0x96, 0x04, 0x37, 0x16, 0xc7, 0x30,
0x7c, 0xd9, 0xe0, 0xcd, 0xd1, 0x37, 0xfc, 0xcb,
0x0f, 0x05, 0xb4, 0x7c, 0xdb, 0xb9, 0x5c, 0x5f,
0x54, 0x83, 0x16, 0x22, 0xc3, 0x65, 0x2a, 0x32,
0xb2, 0x53, 0x1f, 0xe3, 0x26, 0xbc, 0xd6, 0xe2,
0xbb, 0xf5, 0x6a, 0x19, 0x4f, 0xa1, 0x96, 0xfb,
0xd1, 0xa5, 0x49, 0x52, 0x11, 0x0f, 0x51, 0xc7,
0x34, 0x33, 0x86, 0x5f, 0x76, 0x64, 0xb8, 0x36,
0x68, 0x5e, 0x36, 0x64, 0xb3, 0xd8, 0x44, 0x4a,
0xf8, 0x9a, 0x24, 0x28, 0x05, 0xe1, 0x8c, 0x97,
0x5f, 0x11, 0x46, 0x32, 0x49, 0x96, 0xfd, 0xe1,
0x70, 0x07, 0xcf, 0x3e, 0x6e, 0x8f, 0x4e, 0x76,
0x40, 0x22, 0x53, 0x3e, 0xdb, 0xfe, 0x07, 0xd4,
0x73, 0x3e, 0x48, 0xbb, 0x37, 0x2d, 0x75, 0xb0,
0xef, 0x48, 0xec, 0x98, 0x3e, 0xb7, 0x85, 0x32,
0x16, 0x1c, 0xc5, 0x29, 0xe5, 0xab, 0xb8, 0x98,
0x37, 0xdf, 0xcc, 0xa6, 0x26, 0x1d, 0xbb, 0x37,
0xc7, 0xc5, 0xe6, 0xa8, 0x74, 0x78, 0xbf, 0x41,
0xee, 0x85, 0xa5, 0x18, 0xc0, 0xf4, 0xef, 0xa9,
0xbd, 0xe8, 0x28, 0xc5, 0xa7, 0x1b, 0x8e, 0x46,
0x59, 0x7b, 0x63, 0x4a, 0xfd, 0x20, 0x4d, 0x3c,
0x50, 0x13, 0x34, 0x23, 0x9c, 0x34, 0x14, 0x28,
0x5e, 0xd7, 0x2d, 0x3a, 0x91, 0x69, 0xea, 0xbb,
0xd4, 0xdc, 0x25, 0xd5, 0x2b, 0xb7, 0x51, 0x6d,
0x3b, 0xa7, 0x12, 0xd7, 0x5a, 0xd8, 0xc0, 0xae,
0x5d, 0x49, 0x3c, 0x19, 0xe3, 0x8a, 0x77, 0x93,
0x9e, 0x7a, 0x05, 0x8d, 0x71, 0x3e, 0x9c, 0xcc,
0xca, 0x58, 0x04, 0x5f, 0x43, 0x6b, 0x43, 0x4b,
0x1c, 0x80, 0xd3, 0x65, 0x47, 0x24, 0x06, 0xe3,
0x92, 0x95, 0x19, 0x87, 0xdb, 0x69, 0x05, 0xc8,
0x0d, 0x43, 0x1d, 0xa1, 0x84, 0x51, 0x13, 0x5b,
0xe7, 0xe8, 0x2b, 0xca, 0xb3, 0x58, 0xcb, 0x39,
0x71, 0xe6, 0x14, 0x05, 0xb2, 0xff, 0x17, 0x98,
0x0d, 0x6e, 0x7e, 0x67, 0xe8, 0x61, 0xe2, 0x82,
0x01, 0xc1, 0xee, 0x30, 0xb4, 0x41, 0x04, 0x0f,
0xd0, 0x68, 0x78, 0xd6, 0x50, 0x42, 0xc9, 0x55,
0x82, 0xa4, 0x31, 0x82, 0x07, 0xbf, 0xc7, 0x00,
0xbe, 0x0c, 0xe3, 0x28, 0x89, 0xae, 0xc2, 0xff,
0xe5, 0x08, 0x5e, 0x89, 0x67, 0x91, 0x0d, 0x87,
0x9f, 0xa0, 0xe8, 0xc0, 0xff, 0x85, 0xfd, 0xc5,
0x10, 0xb9, 0xff, 0x2f, 0xbf, 0x87, 0xcf, 0xcb,
0x29, 0x57, 0x7d, 0x68, 0x09, 0x9e, 0x04, 0xff,
0xa0, 0x5f, 0x75, 0x2a, 0x73, 0xd3, 0x77, 0xc7,
0x0d, 0x3a, 0x8b, 0xc2, 0xda, 0x80, 0xe6, 0xe7,
0x80, 0xec, 0x05, 0x71, 0x82, 0xc3, 0x3a, 0xd1,
0xde, 0x38, 0x72, 0x52, 0x25, 0x8a, 0x1e, 0x18,
0xe6, 0xfa, 0xd9, 0x10, 0x32, 0x7c, 0xe7, 0xf4,
0x2f, 0xd1, 0xe1, 0xe0, 0x51, 0x5f, 0x95, 0x86,
0xe2, 0xf2, 0xef, 0xcb, 0x9f, 0x47, 0x2b, 0x1d,
0xbd, 0xba, 0xc3, 0x54, 0xa4, 0x16, 0x21, 0x51,
0xe9, 0xd9, 0x2c, 0x79, 0xfb, 0x08, 0xbb, 0x4d,
0xdc, 0x56, 0xf1, 0x94, 0x48, 0xc0, 0x17, 0x5a,
0x46, 0xe2, 0xe6, 0xc4, 0x91, 0xfe, 0xc7, 0x14,
0x19, 0xaa, 0x43, 0xa3, 0x49, 0xbe, 0xa7, 0x68,
0xa9, 0x2c, 0x75, 0xde, 0x68, 0xfd, 0x95, 0x91,
0xe6, 0x80, 0x67, 0xf3, 0x19, 0x70, 0x94, 0xd3,
0xfb, 0x87, 0xed, 0x81, 0x78, 0x5e, 0xa0, 0x75,
0xe4, 0xb6, 0x5e, 0x3e, 0x4c, 0x78, 0xf8, 0x1d,
0xa9, 0xb7, 0x51, 0xc5, 0xef, 0xe0, 0x24, 0x15,
0x23, 0x01, 0xc4, 0x8e, 0x63, 0x24, 0x5b, 0x55,
0x6c, 0x4c, 0x67, 0xaf, 0xf8, 0x57, 0xe5, 0xea,
0x15, 0xa9, 0x08, 0xd8, 0x3a, 0x1d, 0x97, 0x04,
0xf8, 0xe5, 0x5e, 0x73, 0x52, 0xb2, 0x0b, 0x69,
0x4b, 0xf9, 0x97, 0x02, 0x98, 0xe6, 0xb5, 0xaa,
0xd3, 0x3e, 0xa2, 0x15, 0x5d, 0x10, 0x5d, 0x4e
};
static int test_cha_cha_internal(int n)
{
unsigned char buf[sizeof(ref)];
unsigned int i = n + 1, j;
memset(buf, 0, i);
memcpy(buf + i, ref + i, sizeof(ref) - i);
ChaCha20_ctr32(buf, buf, i, key, ivp);
/*
* Idea behind checking for whole sizeof(ref) is that if
* ChaCha20_ctr32 oversteps i-th byte, then we'd know
*/
for (j = 0; j < sizeof(ref); j++)
if (!TEST_uchar_eq(buf[j], ref[j])) {
TEST_info("%d failed at %u (%02x)\n", i, j, buf[j]);
return 0;
}
return 1;
}
int setup_tests(void)
{
#ifdef CPUID_OBJ
OPENSSL_cpuid_setup();
#endif
ADD_ALL_TESTS(test_cha_cha_internal, sizeof(ref));
return 1;
}
| 8,198 | 41.926702 | 74 | c |
openssl | openssl-master/test/cipher_overhead_test.c | /*
* Copyright 2016-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/nelem.h"
#include "testutil.h"
#include "../ssl/ssl_local.h"
static int cipher_enabled(const SSL_CIPHER *ciph)
{
/*
* ssl_cipher_get_overhead() actually works with AEAD ciphers even if the
* underlying implementation is not present.
*/
if ((ciph->algorithm_mac & SSL_AEAD) != 0)
return 1;
if (ciph->algorithm_enc != SSL_eNULL
&& EVP_get_cipherbynid(SSL_CIPHER_get_cipher_nid(ciph)) == NULL)
return 0;
if (EVP_get_digestbynid(SSL_CIPHER_get_digest_nid(ciph)) == NULL)
return 0;
return 1;
}
static int cipher_overhead(void)
{
int ret = 1, i, n = ssl3_num_ciphers();
const SSL_CIPHER *ciph;
size_t mac, in, blk, ex;
for (i = 0; i < n; i++) {
ciph = ssl3_get_cipher(i);
if (!ciph->min_dtls)
continue;
if (!cipher_enabled(ciph)) {
TEST_skip("Skipping disabled cipher %s", ciph->name);
continue;
}
if (!TEST_true(ssl_cipher_get_overhead(ciph, &mac, &in, &blk, &ex))) {
TEST_info("Failed getting %s", ciph->name);
ret = 0;
} else {
TEST_info("Cipher %s: %zu %zu %zu %zu",
ciph->name, mac, in, blk, ex);
}
}
return ret;
}
int setup_tests(void)
{
ADD_TEST(cipher_overhead);
return 1;
}
| 1,693 | 25.888889 | 78 | c |
openssl | openssl-master/test/cipherbytes_test.c | /*
* Copyright 2017-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 may obtain a copy of the License at
* https://www.openssl.org/source/license.html
* or in the file LICENSE in the source distribution.
*/
#include <string.h>
#include <stdio.h>
#include <openssl/opensslconf.h>
#include <openssl/err.h>
#include <openssl/e_os2.h>
#include <openssl/ssl.h>
#include <openssl/ssl3.h>
#include <openssl/tls1.h>
#include "internal/nelem.h"
#include "testutil.h"
static SSL_CTX *ctx;
static SSL *s;
static int test_empty(void)
{
STACK_OF(SSL_CIPHER) *sk = NULL, *scsv = NULL;
const unsigned char bytes[] = {0x00};
int ret = 0;
if (!TEST_int_eq(SSL_bytes_to_cipher_list(s, bytes, 0, 0, &sk, &scsv), 0)
|| !TEST_ptr_null(sk)
|| !TEST_ptr_null(scsv))
goto err;
ret = 1;
err:
sk_SSL_CIPHER_free(sk);
sk_SSL_CIPHER_free(scsv);
return ret;
}
static int test_unsupported(void)
{
STACK_OF(SSL_CIPHER) *sk, *scsv;
/* ECDH-RSA-AES256 (unsupported), ECDHE-ECDSA-AES128, <unassigned> */
const unsigned char bytes[] = {0xc0, 0x0f, 0x00, 0x2f, 0x01, 0x00};
int ret = 0;
if (!TEST_true(SSL_bytes_to_cipher_list(s, bytes, sizeof(bytes),
0, &sk, &scsv))
|| !TEST_ptr(sk)
|| !TEST_int_eq(sk_SSL_CIPHER_num(sk), 1)
|| !TEST_ptr(scsv)
|| !TEST_int_eq(sk_SSL_CIPHER_num(scsv), 0)
|| !TEST_str_eq(SSL_CIPHER_get_name(sk_SSL_CIPHER_value(sk, 0)),
"AES128-SHA"))
goto err;
ret = 1;
err:
sk_SSL_CIPHER_free(sk);
sk_SSL_CIPHER_free(scsv);
return ret;
}
static int test_v2(void)
{
STACK_OF(SSL_CIPHER) *sk, *scsv;
/* ECDHE-ECDSA-AES256GCM, SSL2_RC4_1238_WITH_MD5,
* ECDHE-ECDSA-CHACHA20-POLY1305 */
const unsigned char bytes[] = {0x00, 0x00, 0x35, 0x01, 0x00, 0x80,
0x00, 0x00, 0x33};
int ret = 0;
if (!TEST_true(SSL_bytes_to_cipher_list(s, bytes, sizeof(bytes), 1,
&sk, &scsv))
|| !TEST_ptr(sk)
|| !TEST_int_eq(sk_SSL_CIPHER_num(sk), 2)
|| !TEST_ptr(scsv)
|| !TEST_int_eq(sk_SSL_CIPHER_num(scsv), 0))
goto err;
if (strcmp(SSL_CIPHER_get_name(sk_SSL_CIPHER_value(sk, 0)),
"AES256-SHA") != 0 ||
strcmp(SSL_CIPHER_get_name(sk_SSL_CIPHER_value(sk, 1)),
"DHE-RSA-AES128-SHA") != 0)
goto err;
ret = 1;
err:
sk_SSL_CIPHER_free(sk);
sk_SSL_CIPHER_free(scsv);
return ret;
}
static int test_v3(void)
{
STACK_OF(SSL_CIPHER) *sk = NULL, *scsv = NULL;
/* ECDHE-ECDSA-AES256GCM, ECDHE-ECDSA-CHACHAPOLY, DHE-RSA-AES256GCM,
* EMPTY-RENEGOTIATION-INFO-SCSV, FALLBACK-SCSV */
const unsigned char bytes[] = {0x00, 0x2f, 0x00, 0x33, 0x00, 0x9f, 0x00, 0xff,
0x56, 0x00};
int ret = 0;
if (!SSL_bytes_to_cipher_list(s, bytes, sizeof(bytes), 0, &sk, &scsv)
|| !TEST_ptr(sk)
|| !TEST_int_eq(sk_SSL_CIPHER_num(sk), 3)
|| !TEST_ptr(scsv)
|| !TEST_int_eq(sk_SSL_CIPHER_num(scsv), 2)
|| !TEST_str_eq(SSL_CIPHER_get_name(sk_SSL_CIPHER_value(sk, 0)),
"AES128-SHA")
|| !TEST_str_eq(SSL_CIPHER_get_name(sk_SSL_CIPHER_value(sk, 1)),
"DHE-RSA-AES128-SHA")
|| !TEST_str_eq(SSL_CIPHER_get_name(sk_SSL_CIPHER_value(sk, 2)),
"DHE-RSA-AES256-GCM-SHA384")
|| !TEST_str_eq(SSL_CIPHER_get_name(sk_SSL_CIPHER_value(scsv, 0)),
"TLS_EMPTY_RENEGOTIATION_INFO_SCSV")
|| !TEST_str_eq(SSL_CIPHER_get_name(sk_SSL_CIPHER_value(scsv, 1)),
"TLS_FALLBACK_SCSV"))
goto err;
ret = 1;
err:
sk_SSL_CIPHER_free(sk);
sk_SSL_CIPHER_free(scsv);
return ret;
}
int setup_tests(void)
{
if (!TEST_ptr(ctx = SSL_CTX_new(TLS_server_method()))
|| !TEST_ptr(s = SSL_new(ctx)))
return 0;
ADD_TEST(test_empty);
ADD_TEST(test_unsupported);
ADD_TEST(test_v2);
ADD_TEST(test_v3);
return 1;
}
void cleanup_tests(void)
{
SSL_free(s);
SSL_CTX_free(ctx);
}
| 4,462 | 28.753333 | 82 | c |
openssl | openssl-master/test/cipherlist_test.c | /*
* Copyright 2016-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 may obtain a copy of the License at
* https://www.openssl.org/source/license.html
* or in the file LICENSE in the source distribution.
*/
#include <stdio.h>
#include <string.h>
#include <openssl/opensslconf.h>
#include <openssl/err.h>
#include <openssl/e_os2.h>
#include <openssl/ssl.h>
#include <openssl/ssl3.h>
#include <openssl/tls1.h>
#include "internal/nelem.h"
#include "testutil.h"
typedef struct cipherlist_test_fixture {
const char *test_case_name;
SSL_CTX *server;
SSL_CTX *client;
} CIPHERLIST_TEST_FIXTURE;
static void tear_down(CIPHERLIST_TEST_FIXTURE *fixture)
{
if (fixture != NULL) {
SSL_CTX_free(fixture->server);
SSL_CTX_free(fixture->client);
fixture->server = fixture->client = NULL;
OPENSSL_free(fixture);
}
}
static CIPHERLIST_TEST_FIXTURE *set_up(const char *const test_case_name)
{
CIPHERLIST_TEST_FIXTURE *fixture;
if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture))))
return NULL;
fixture->test_case_name = test_case_name;
if (!TEST_ptr(fixture->server = SSL_CTX_new(TLS_server_method()))
|| !TEST_ptr(fixture->client = SSL_CTX_new(TLS_client_method()))) {
tear_down(fixture);
return NULL;
}
return fixture;
}
/*
* All ciphers in the DEFAULT cipherlist meet the default security level.
* However, default supported ciphers exclude SRP and PSK ciphersuites
* for which no callbacks have been set up.
*
* Supported ciphers also exclude TLSv1.2 ciphers if TLSv1.2 is disabled,
* and individual disabled algorithms. However, NO_RSA, NO_AES and NO_SHA
* are currently broken and should be considered mission impossible in libssl.
*/
static const uint32_t default_ciphers_in_order[] = {
#ifndef OPENSSL_NO_TLS1_3
TLS1_3_CK_AES_256_GCM_SHA384,
# if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
TLS1_3_CK_CHACHA20_POLY1305_SHA256,
# endif
TLS1_3_CK_AES_128_GCM_SHA256,
#endif
#ifndef OPENSSL_NO_TLS1_2
# ifndef OPENSSL_NO_EC
TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
# endif
# ifndef OPENSSL_NO_DH
TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384,
# endif
# if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305)
# ifndef OPENSSL_NO_EC
TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305,
# endif
# ifndef OPENSSL_NO_DH
TLS1_CK_DHE_RSA_WITH_CHACHA20_POLY1305,
# endif
# endif /* !OPENSSL_NO_CHACHA && !OPENSSL_NO_POLY1305 */
# ifndef OPENSSL_NO_EC
TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
# endif
# ifndef OPENSSL_NO_DH
TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256,
# endif
# ifndef OPENSSL_NO_EC
TLS1_CK_ECDHE_ECDSA_WITH_AES_256_SHA384,
TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384,
# endif
# ifndef OPENSSL_NO_DH
TLS1_CK_DHE_RSA_WITH_AES_256_SHA256,
# endif
# ifndef OPENSSL_NO_EC
TLS1_CK_ECDHE_ECDSA_WITH_AES_128_SHA256,
TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256,
# endif
# ifndef OPENSSL_NO_DH
TLS1_CK_DHE_RSA_WITH_AES_128_SHA256,
# endif
#endif /* !OPENSSL_NO_TLS1_2 */
#if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
/* These won't be usable if TLSv1.3 is available but TLSv1.2 isn't */
# ifndef OPENSSL_NO_EC
TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA,
# endif
#ifndef OPENSSL_NO_DH
TLS1_CK_DHE_RSA_WITH_AES_256_SHA,
# endif
# ifndef OPENSSL_NO_EC
TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA,
# endif
# ifndef OPENSSL_NO_DH
TLS1_CK_DHE_RSA_WITH_AES_128_SHA,
# endif
#endif /* !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3) */
#ifndef OPENSSL_NO_TLS1_2
TLS1_CK_RSA_WITH_AES_256_GCM_SHA384,
TLS1_CK_RSA_WITH_AES_128_GCM_SHA256,
#endif
#ifndef OPENSSL_NO_TLS1_2
TLS1_CK_RSA_WITH_AES_256_SHA256,
TLS1_CK_RSA_WITH_AES_128_SHA256,
#endif
#if !defined(OPENSSL_NO_TLS1_2) || defined(OPENSSL_NO_TLS1_3)
/* These won't be usable if TLSv1.3 is available but TLSv1.2 isn't */
TLS1_CK_RSA_WITH_AES_256_SHA,
TLS1_CK_RSA_WITH_AES_128_SHA,
#endif
};
static int test_default_cipherlist(SSL_CTX *ctx)
{
STACK_OF(SSL_CIPHER) *ciphers = NULL;
SSL *ssl = NULL;
int i, ret = 0, num_expected_ciphers, num_ciphers;
uint32_t expected_cipher_id, cipher_id;
if (ctx == NULL)
return 0;
if (!TEST_ptr(ssl = SSL_new(ctx))
|| !TEST_ptr(ciphers = SSL_get1_supported_ciphers(ssl)))
goto err;
num_expected_ciphers = OSSL_NELEM(default_ciphers_in_order);
num_ciphers = sk_SSL_CIPHER_num(ciphers);
if (!TEST_int_eq(num_ciphers, num_expected_ciphers))
goto err;
for (i = 0; i < num_ciphers; i++) {
expected_cipher_id = default_ciphers_in_order[i];
cipher_id = SSL_CIPHER_get_id(sk_SSL_CIPHER_value(ciphers, i));
if (!TEST_int_eq(cipher_id, expected_cipher_id)) {
TEST_info("Wrong cipher at position %d", i);
goto err;
}
}
ret = 1;
err:
sk_SSL_CIPHER_free(ciphers);
SSL_free(ssl);
return ret;
}
static int execute_test(CIPHERLIST_TEST_FIXTURE *fixture)
{
return fixture != NULL
&& test_default_cipherlist(fixture->server)
&& test_default_cipherlist(fixture->client);
}
#define SETUP_CIPHERLIST_TEST_FIXTURE() \
SETUP_TEST_FIXTURE(CIPHERLIST_TEST_FIXTURE, set_up)
#define EXECUTE_CIPHERLIST_TEST() \
EXECUTE_TEST(execute_test, tear_down)
static int test_default_cipherlist_implicit(void)
{
SETUP_CIPHERLIST_TEST_FIXTURE();
EXECUTE_CIPHERLIST_TEST();
return result;
}
static int test_default_cipherlist_explicit(void)
{
SETUP_CIPHERLIST_TEST_FIXTURE();
if (!TEST_true(SSL_CTX_set_cipher_list(fixture->server, "DEFAULT"))
|| !TEST_true(SSL_CTX_set_cipher_list(fixture->client, "DEFAULT"))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_CIPHERLIST_TEST();
return result;
}
/* SSL_CTX_set_cipher_list() should fail if it clears all TLSv1.2 ciphers. */
static int test_default_cipherlist_clear(void)
{
SSL *s = NULL;
SETUP_CIPHERLIST_TEST_FIXTURE();
if (!TEST_int_eq(SSL_CTX_set_cipher_list(fixture->server, "no-such"), 0))
goto end;
if (!TEST_int_eq(ERR_GET_REASON(ERR_get_error()), SSL_R_NO_CIPHER_MATCH))
goto end;
s = SSL_new(fixture->client);
if (!TEST_ptr(s))
goto end;
if (!TEST_int_eq(SSL_set_cipher_list(s, "no-such"), 0))
goto end;
if (!TEST_int_eq(ERR_GET_REASON(ERR_get_error()),
SSL_R_NO_CIPHER_MATCH))
goto end;
result = 1;
end:
SSL_free(s);
tear_down(fixture);
return result;
}
/* SSL_CTX_set_cipher_list matching with cipher standard name */
static int test_stdname_cipherlist(void)
{
SETUP_CIPHERLIST_TEST_FIXTURE();
if (!TEST_true(SSL_CTX_set_cipher_list(fixture->server, TLS1_RFC_RSA_WITH_AES_128_SHA))
|| !TEST_true(SSL_CTX_set_cipher_list(fixture->client, TLS1_RFC_RSA_WITH_AES_128_SHA))) {
goto end;
}
result = 1;
end:
tear_down(fixture);
fixture = NULL;
return result;
}
int setup_tests(void)
{
ADD_TEST(test_default_cipherlist_implicit);
ADD_TEST(test_default_cipherlist_explicit);
ADD_TEST(test_default_cipherlist_clear);
ADD_TEST(test_stdname_cipherlist);
return 1;
}
| 7,624 | 27.240741 | 101 | c |
openssl | openssl-master/test/ciphername_test.c | /*
* Copyright 2017-2020 The OpenSSL Project Authors. All Rights Reserved.
* Copyright 2017 BaishanCloud. 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 may obtain a copy of the License at
* https://www.openssl.org/source/license.html
* or in the file LICENSE in the source distribution.
*/
#include <stdio.h>
#include <string.h>
#include <openssl/opensslconf.h>
#include <openssl/err.h>
#include <openssl/e_os2.h>
#include <openssl/ssl.h>
#include <openssl/ssl3.h>
#include <openssl/tls1.h>
#include "internal/nelem.h"
#include "testutil.h"
typedef struct cipher_id_name {
int id;
const char *name;
} CIPHER_ID_NAME;
/* Cipher suites, copied from t1_trce.c */
static CIPHER_ID_NAME cipher_names[] = {
{0x0000, "TLS_NULL_WITH_NULL_NULL"},
{0x0001, "TLS_RSA_WITH_NULL_MD5"},
{0x0002, "TLS_RSA_WITH_NULL_SHA"},
{0x0003, "TLS_RSA_EXPORT_WITH_RC4_40_MD5"},
{0x0004, "TLS_RSA_WITH_RC4_128_MD5"},
{0x0005, "TLS_RSA_WITH_RC4_128_SHA"},
{0x0006, "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5"},
{0x0007, "TLS_RSA_WITH_IDEA_CBC_SHA"},
{0x0008, "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA"},
{0x0009, "TLS_RSA_WITH_DES_CBC_SHA"},
{0x000A, "TLS_RSA_WITH_3DES_EDE_CBC_SHA"},
{0x000B, "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA"},
{0x000C, "TLS_DH_DSS_WITH_DES_CBC_SHA"},
{0x000D, "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA"},
{0x000E, "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"},
{0x000F, "TLS_DH_RSA_WITH_DES_CBC_SHA"},
{0x0010, "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA"},
{0x0011, "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"},
{0x0012, "TLS_DHE_DSS_WITH_DES_CBC_SHA"},
{0x0013, "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA"},
{0x0014, "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA"},
{0x0015, "TLS_DHE_RSA_WITH_DES_CBC_SHA"},
{0x0016, "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA"},
{0x0017, "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5"},
{0x0018, "TLS_DH_anon_WITH_RC4_128_MD5"},
{0x0019, "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA"},
{0x001A, "TLS_DH_anon_WITH_DES_CBC_SHA"},
{0x001B, "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA"},
{0x001D, "SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA"},
{0x001E, "SSL_FORTEZZA_KEA_WITH_RC4_128_SHA"},
{0x001F, "TLS_KRB5_WITH_3DES_EDE_CBC_SHA"},
{0x0020, "TLS_KRB5_WITH_RC4_128_SHA"},
{0x0021, "TLS_KRB5_WITH_IDEA_CBC_SHA"},
{0x0022, "TLS_KRB5_WITH_DES_CBC_MD5"},
{0x0023, "TLS_KRB5_WITH_3DES_EDE_CBC_MD5"},
{0x0024, "TLS_KRB5_WITH_RC4_128_MD5"},
{0x0025, "TLS_KRB5_WITH_IDEA_CBC_MD5"},
{0x0026, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA"},
{0x0027, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA"},
{0x0028, "TLS_KRB5_EXPORT_WITH_RC4_40_SHA"},
{0x0029, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5"},
{0x002A, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5"},
{0x002B, "TLS_KRB5_EXPORT_WITH_RC4_40_MD5"},
{0x002C, "TLS_PSK_WITH_NULL_SHA"},
{0x002D, "TLS_DHE_PSK_WITH_NULL_SHA"},
{0x002E, "TLS_RSA_PSK_WITH_NULL_SHA"},
{0x002F, "TLS_RSA_WITH_AES_128_CBC_SHA"},
{0x0030, "TLS_DH_DSS_WITH_AES_128_CBC_SHA"},
{0x0031, "TLS_DH_RSA_WITH_AES_128_CBC_SHA"},
{0x0032, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA"},
{0x0033, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"},
{0x0034, "TLS_DH_anon_WITH_AES_128_CBC_SHA"},
{0x0035, "TLS_RSA_WITH_AES_256_CBC_SHA"},
{0x0036, "TLS_DH_DSS_WITH_AES_256_CBC_SHA"},
{0x0037, "TLS_DH_RSA_WITH_AES_256_CBC_SHA"},
{0x0038, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA"},
{0x0039, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"},
{0x003A, "TLS_DH_anon_WITH_AES_256_CBC_SHA"},
{0x003B, "TLS_RSA_WITH_NULL_SHA256"},
{0x003C, "TLS_RSA_WITH_AES_128_CBC_SHA256"},
{0x003D, "TLS_RSA_WITH_AES_256_CBC_SHA256"},
{0x003E, "TLS_DH_DSS_WITH_AES_128_CBC_SHA256"},
{0x003F, "TLS_DH_RSA_WITH_AES_128_CBC_SHA256"},
{0x0040, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"},
{0x0041, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA"},
{0x0042, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA"},
{0x0043, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA"},
{0x0044, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA"},
{0x0045, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA"},
{0x0046, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA"},
{0x0067, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"},
{0x0068, "TLS_DH_DSS_WITH_AES_256_CBC_SHA256"},
{0x0069, "TLS_DH_RSA_WITH_AES_256_CBC_SHA256"},
{0x006A, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"},
{0x006B, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"},
{0x006C, "TLS_DH_anon_WITH_AES_128_CBC_SHA256"},
{0x006D, "TLS_DH_anon_WITH_AES_256_CBC_SHA256"},
{0x0084, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA"},
{0x0085, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA"},
{0x0086, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA"},
{0x0087, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA"},
{0x0088, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA"},
{0x0089, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA"},
{0x008A, "TLS_PSK_WITH_RC4_128_SHA"},
{0x008B, "TLS_PSK_WITH_3DES_EDE_CBC_SHA"},
{0x008C, "TLS_PSK_WITH_AES_128_CBC_SHA"},
{0x008D, "TLS_PSK_WITH_AES_256_CBC_SHA"},
{0x008E, "TLS_DHE_PSK_WITH_RC4_128_SHA"},
{0x008F, "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA"},
{0x0090, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA"},
{0x0091, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA"},
{0x0092, "TLS_RSA_PSK_WITH_RC4_128_SHA"},
{0x0093, "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA"},
{0x0094, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA"},
{0x0095, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA"},
{0x0096, "TLS_RSA_WITH_SEED_CBC_SHA"},
{0x0097, "TLS_DH_DSS_WITH_SEED_CBC_SHA"},
{0x0098, "TLS_DH_RSA_WITH_SEED_CBC_SHA"},
{0x0099, "TLS_DHE_DSS_WITH_SEED_CBC_SHA"},
{0x009A, "TLS_DHE_RSA_WITH_SEED_CBC_SHA"},
{0x009B, "TLS_DH_anon_WITH_SEED_CBC_SHA"},
{0x009C, "TLS_RSA_WITH_AES_128_GCM_SHA256"},
{0x009D, "TLS_RSA_WITH_AES_256_GCM_SHA384"},
{0x009E, "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"},
{0x009F, "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"},
{0x00A0, "TLS_DH_RSA_WITH_AES_128_GCM_SHA256"},
{0x00A1, "TLS_DH_RSA_WITH_AES_256_GCM_SHA384"},
{0x00A2, "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256"},
{0x00A3, "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384"},
{0x00A4, "TLS_DH_DSS_WITH_AES_128_GCM_SHA256"},
{0x00A5, "TLS_DH_DSS_WITH_AES_256_GCM_SHA384"},
{0x00A6, "TLS_DH_anon_WITH_AES_128_GCM_SHA256"},
{0x00A7, "TLS_DH_anon_WITH_AES_256_GCM_SHA384"},
{0x00A8, "TLS_PSK_WITH_AES_128_GCM_SHA256"},
{0x00A9, "TLS_PSK_WITH_AES_256_GCM_SHA384"},
{0x00AA, "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256"},
{0x00AB, "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384"},
{0x00AC, "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256"},
{0x00AD, "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384"},
{0x00AE, "TLS_PSK_WITH_AES_128_CBC_SHA256"},
{0x00AF, "TLS_PSK_WITH_AES_256_CBC_SHA384"},
{0x00B0, "TLS_PSK_WITH_NULL_SHA256"},
{0x00B1, "TLS_PSK_WITH_NULL_SHA384"},
{0x00B2, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256"},
{0x00B3, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384"},
{0x00B4, "TLS_DHE_PSK_WITH_NULL_SHA256"},
{0x00B5, "TLS_DHE_PSK_WITH_NULL_SHA384"},
{0x00B6, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256"},
{0x00B7, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384"},
{0x00B8, "TLS_RSA_PSK_WITH_NULL_SHA256"},
{0x00B9, "TLS_RSA_PSK_WITH_NULL_SHA384"},
{0x00BA, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00BB, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00BC, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00BD, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00BE, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00BF, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256"},
{0x00C0, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00C1, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00C2, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00C3, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00C4, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00C5, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256"},
{0x00FF, "TLS_EMPTY_RENEGOTIATION_INFO_SCSV"},
{0x5600, "TLS_FALLBACK_SCSV"},
{0xC001, "TLS_ECDH_ECDSA_WITH_NULL_SHA"},
{0xC002, "TLS_ECDH_ECDSA_WITH_RC4_128_SHA"},
{0xC003, "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA"},
{0xC004, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA"},
{0xC005, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA"},
{0xC006, "TLS_ECDHE_ECDSA_WITH_NULL_SHA"},
{0xC007, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA"},
{0xC008, "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"},
{0xC009, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"},
{0xC00A, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"},
{0xC00B, "TLS_ECDH_RSA_WITH_NULL_SHA"},
{0xC00C, "TLS_ECDH_RSA_WITH_RC4_128_SHA"},
{0xC00D, "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA"},
{0xC00E, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA"},
{0xC00F, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA"},
{0xC010, "TLS_ECDHE_RSA_WITH_NULL_SHA"},
{0xC011, "TLS_ECDHE_RSA_WITH_RC4_128_SHA"},
{0xC012, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"},
{0xC013, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"},
{0xC014, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"},
{0xC015, "TLS_ECDH_anon_WITH_NULL_SHA"},
{0xC016, "TLS_ECDH_anon_WITH_RC4_128_SHA"},
{0xC017, "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA"},
{0xC018, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA"},
{0xC019, "TLS_ECDH_anon_WITH_AES_256_CBC_SHA"},
{0xC01A, "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA"},
{0xC01B, "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA"},
{0xC01C, "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA"},
{0xC01D, "TLS_SRP_SHA_WITH_AES_128_CBC_SHA"},
{0xC01E, "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA"},
{0xC01F, "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA"},
{0xC020, "TLS_SRP_SHA_WITH_AES_256_CBC_SHA"},
{0xC021, "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA"},
{0xC022, "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA"},
{0xC023, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"},
{0xC024, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"},
{0xC025, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256"},
{0xC026, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384"},
{0xC027, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"},
{0xC028, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"},
{0xC029, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256"},
{0xC02A, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384"},
{0xC02B, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"},
{0xC02C, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"},
{0xC02D, "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256"},
{0xC02E, "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384"},
{0xC02F, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"},
{0xC030, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"},
{0xC031, "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256"},
{0xC032, "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384"},
{0xC033, "TLS_ECDHE_PSK_WITH_RC4_128_SHA"},
{0xC034, "TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA"},
{0xC035, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA"},
{0xC036, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA"},
{0xC037, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256"},
{0xC038, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384"},
{0xC039, "TLS_ECDHE_PSK_WITH_NULL_SHA"},
{0xC03A, "TLS_ECDHE_PSK_WITH_NULL_SHA256"},
{0xC03B, "TLS_ECDHE_PSK_WITH_NULL_SHA384"},
{0xC03C, "TLS_RSA_WITH_ARIA_128_CBC_SHA256"},
{0xC03D, "TLS_RSA_WITH_ARIA_256_CBC_SHA384"},
{0xC03E, "TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256"},
{0xC03F, "TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384"},
{0xC040, "TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256"},
{0xC041, "TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384"},
{0xC042, "TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256"},
{0xC043, "TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384"},
{0xC044, "TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256"},
{0xC045, "TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384"},
{0xC046, "TLS_DH_anon_WITH_ARIA_128_CBC_SHA256"},
{0xC047, "TLS_DH_anon_WITH_ARIA_256_CBC_SHA384"},
{0xC048, "TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256"},
{0xC049, "TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384"},
{0xC04A, "TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256"},
{0xC04B, "TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384"},
{0xC04C, "TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256"},
{0xC04D, "TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384"},
{0xC04E, "TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256"},
{0xC04F, "TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384"},
{0xC050, "TLS_RSA_WITH_ARIA_128_GCM_SHA256"},
{0xC051, "TLS_RSA_WITH_ARIA_256_GCM_SHA384"},
{0xC052, "TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256"},
{0xC053, "TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384"},
{0xC054, "TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256"},
{0xC055, "TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384"},
{0xC056, "TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256"},
{0xC057, "TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384"},
{0xC058, "TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256"},
{0xC059, "TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384"},
{0xC05A, "TLS_DH_anon_WITH_ARIA_128_GCM_SHA256"},
{0xC05B, "TLS_DH_anon_WITH_ARIA_256_GCM_SHA384"},
{0xC05C, "TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256"},
{0xC05D, "TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384"},
{0xC05E, "TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256"},
{0xC05F, "TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384"},
{0xC060, "TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256"},
{0xC061, "TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384"},
{0xC062, "TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256"},
{0xC063, "TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384"},
{0xC064, "TLS_PSK_WITH_ARIA_128_CBC_SHA256"},
{0xC065, "TLS_PSK_WITH_ARIA_256_CBC_SHA384"},
{0xC066, "TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256"},
{0xC067, "TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384"},
{0xC068, "TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256"},
{0xC069, "TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384"},
{0xC06A, "TLS_PSK_WITH_ARIA_128_GCM_SHA256"},
{0xC06B, "TLS_PSK_WITH_ARIA_256_GCM_SHA384"},
{0xC06C, "TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256"},
{0xC06D, "TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384"},
{0xC06E, "TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256"},
{0xC06F, "TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384"},
{0xC070, "TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256"},
{0xC071, "TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384"},
{0xC072, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0xC073, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384"},
{0xC074, "TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0xC075, "TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384"},
{0xC076, "TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0xC077, "TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384"},
{0xC078, "TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256"},
{0xC079, "TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384"},
{0xC07A, "TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC07B, "TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC07C, "TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC07D, "TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC07E, "TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC07F, "TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC080, "TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC081, "TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC082, "TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC083, "TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC084, "TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC085, "TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC086, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC087, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC088, "TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC089, "TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC08A, "TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC08B, "TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC08C, "TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC08D, "TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC08E, "TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC08F, "TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC090, "TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC091, "TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC092, "TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256"},
{0xC093, "TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384"},
{0xC094, "TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256"},
{0xC095, "TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384"},
{0xC096, "TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256"},
{0xC097, "TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384"},
{0xC098, "TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256"},
{0xC099, "TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384"},
{0xC09A, "TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256"},
{0xC09B, "TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384"},
{0xC09C, "TLS_RSA_WITH_AES_128_CCM"},
{0xC09D, "TLS_RSA_WITH_AES_256_CCM"},
{0xC09E, "TLS_DHE_RSA_WITH_AES_128_CCM"},
{0xC09F, "TLS_DHE_RSA_WITH_AES_256_CCM"},
{0xC0A0, "TLS_RSA_WITH_AES_128_CCM_8"},
{0xC0A1, "TLS_RSA_WITH_AES_256_CCM_8"},
{0xC0A2, "TLS_DHE_RSA_WITH_AES_128_CCM_8"},
{0xC0A3, "TLS_DHE_RSA_WITH_AES_256_CCM_8"},
{0xC0A4, "TLS_PSK_WITH_AES_128_CCM"},
{0xC0A5, "TLS_PSK_WITH_AES_256_CCM"},
{0xC0A6, "TLS_DHE_PSK_WITH_AES_128_CCM"},
{0xC0A7, "TLS_DHE_PSK_WITH_AES_256_CCM"},
{0xC0A8, "TLS_PSK_WITH_AES_128_CCM_8"},
{0xC0A9, "TLS_PSK_WITH_AES_256_CCM_8"},
{0xC0AA, "TLS_PSK_DHE_WITH_AES_128_CCM_8"},
{0xC0AB, "TLS_PSK_DHE_WITH_AES_256_CCM_8"},
{0xC0AC, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM"},
{0xC0AD, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM"},
{0xC0AE, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8"},
{0xC0AF, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8"},
{0xCCA8, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256"},
{0xCCA9, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256"},
{0xCCAA, "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256"},
{0xCCAB, "TLS_PSK_WITH_CHACHA20_POLY1305_SHA256"},
{0xCCAC, "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256"},
{0xCCAD, "TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256"},
{0xCCAE, "TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256"},
{0x1301, "TLS_AES_128_GCM_SHA256"},
{0x1302, "TLS_AES_256_GCM_SHA384"},
{0x1303, "TLS_CHACHA20_POLY1305_SHA256"},
{0x1304, "TLS_AES_128_CCM_SHA256"},
{0x1305, "TLS_AES_128_CCM_8_SHA256"},
{0xFEFE, "SSL_RSA_FIPS_WITH_DES_CBC_SHA"},
{0xFEFF, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA"},
};
static const char *get_std_name_by_id(int id)
{
size_t i;
for (i = 0; i < OSSL_NELEM(cipher_names); i++)
if (cipher_names[i].id == id)
return cipher_names[i].name;
return NULL;
}
static int test_cipher_name(void)
{
SSL_CTX *ctx = NULL;
SSL *ssl = NULL;
const SSL_CIPHER *c;
STACK_OF(SSL_CIPHER) *sk = NULL;
const char *ciphers = "ALL:eNULL", *p, *q, *r;
int i, id = 0, ret = 0;
/* tests for invalid input */
p = SSL_CIPHER_standard_name(NULL);
if (!TEST_str_eq(p, "(NONE)")) {
TEST_info("test_cipher_name(std) failed: NULL input doesn't return \"(NONE)\"\n");
goto err;
}
p = OPENSSL_cipher_name(NULL);
if (!TEST_str_eq(p, "(NONE)")) {
TEST_info("test_cipher_name(ossl) failed: NULL input doesn't return \"(NONE)\"\n");
goto err;
}
p = OPENSSL_cipher_name("This is not a valid cipher");
if (!TEST_str_eq(p, "(NONE)")) {
TEST_info("test_cipher_name(ossl) failed: invalid input doesn't return \"(NONE)\"\n");
goto err;
}
/* tests for valid input */
ctx = SSL_CTX_new(TLS_server_method());
if (ctx == NULL) {
TEST_info("test_cipher_name failed: internal error\n");
goto err;
}
if (!SSL_CTX_set_cipher_list(ctx, ciphers)) {
TEST_info("test_cipher_name failed: internal error\n");
goto err;
}
ssl = SSL_new(ctx);
if (ssl == NULL) {
TEST_info("test_cipher_name failed: internal error\n");
goto err;
}
sk = SSL_get_ciphers(ssl);
if (sk == NULL) {
TEST_info("test_cipher_name failed: internal error\n");
goto err;
}
for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
c = sk_SSL_CIPHER_value(sk, i);
id = SSL_CIPHER_get_id(c) & 0xFFFF;
if ((id == 0xC102) || (id == 0xFF85) ||(id == 0xFF87))
/* skip GOST2012-GOST8912-GOST891 and GOST2012-NULL-GOST12 */
continue;
p = SSL_CIPHER_standard_name(c);
q = get_std_name_by_id(id);
if (!TEST_ptr(p)) {
TEST_info("test_cipher_name failed: expected %s, got NULL, cipher %x\n",
q, id);
goto err;
}
/* check if p is a valid standard name */
if (!TEST_str_eq(p, q)) {
TEST_info("test_cipher_name(std) failed: expected %s, got %s, cipher %x\n",
q, p, id);
goto err;
}
/* test OPENSSL_cipher_name */
q = SSL_CIPHER_get_name(c);
r = OPENSSL_cipher_name(p);
if (!TEST_str_eq(r, q)) {
TEST_info("test_cipher_name(ossl) failed: expected %s, got %s, cipher %x\n",
q, r, id);
goto err;
}
}
ret = 1;
err:
SSL_CTX_free(ctx);
SSL_free(ssl);
return ret;
}
int setup_tests(void)
{
ADD_TEST(test_cipher_name);
return 1;
}
| 21,078 | 43.753715 | 94 | c |
openssl | openssl-master/test/clienthellotest.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 <string.h>
#include <openssl/opensslconf.h>
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <time.h>
#include "internal/packet.h"
#include "testutil.h"
#define CLIENT_VERSION_LEN 2
#define TOTAL_NUM_TESTS 4
/*
* Test that explicitly setting ticket data results in it appearing in the
* ClientHello for a negotiated SSL/TLS version
*/
#define TEST_SET_SESSION_TICK_DATA_VER_NEG 0
/* Enable padding and make sure ClientHello is long enough to require it */
#define TEST_ADD_PADDING 1
/* Enable padding and make sure ClientHello is short enough to not need it */
#define TEST_PADDING_NOT_NEEDED 2
/*
* Enable padding and add a PSK to the ClientHello (this will also ensure the
* ClientHello is long enough to need padding)
*/
#define TEST_ADD_PADDING_AND_PSK 3
#define F5_WORKAROUND_MIN_MSG_LEN 0x7f
#define F5_WORKAROUND_MAX_MSG_LEN 0x200
static const char *sessionfile = NULL;
/* Dummy ALPN protocols used to pad out the size of the ClientHello */
/* ASCII 'O' = 79 = 0x4F = EBCDIC '|'*/
#ifdef CHARSET_EBCDIC
static const char alpn_prots[] =
"|1234567890123456789012345678901234567890123456789012345678901234567890123456789"
"|1234567890123456789012345678901234567890123456789012345678901234567890123456789";
#else
static const char alpn_prots[] =
"O1234567890123456789012345678901234567890123456789012345678901234567890123456789"
"O1234567890123456789012345678901234567890123456789012345678901234567890123456789";
#endif
static int test_client_hello(int currtest)
{
SSL_CTX *ctx;
SSL *con = NULL;
BIO *rbio;
BIO *wbio;
long len;
unsigned char *data;
PACKET pkt, pkt2, pkt3;
char *dummytick = "Hello World!";
unsigned int type = 0;
int testresult = 0;
size_t msglen;
BIO *sessbio = NULL;
SSL_SESSION *sess = NULL;
#ifdef OPENSSL_NO_TLS1_3
if (currtest == TEST_ADD_PADDING_AND_PSK)
return 1;
#endif
memset(&pkt, 0, sizeof(pkt));
memset(&pkt2, 0, sizeof(pkt2));
memset(&pkt3, 0, sizeof(pkt3));
/*
* For each test set up an SSL_CTX and SSL and see what ClientHello gets
* produced when we try to connect
*/
ctx = SSL_CTX_new(TLS_method());
if (!TEST_ptr(ctx))
goto end;
if (!TEST_true(SSL_CTX_set_max_proto_version(ctx, 0)))
goto end;
switch (currtest) {
case TEST_SET_SESSION_TICK_DATA_VER_NEG:
#if !defined(OPENSSL_NO_TLS1_3) && defined(OPENSSL_NO_TLS1_2)
/* TLSv1.3 is enabled and TLSv1.2 is disabled so can't do this test */
SSL_CTX_free(ctx);
return 1;
#else
/* Testing for session tickets <= TLS1.2; not relevant for 1.3 */
if (!TEST_true(SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION)))
goto end;
#endif
break;
case TEST_ADD_PADDING_AND_PSK:
/*
* In this case we're doing TLSv1.3 and we're sending a PSK so the
* ClientHello is already going to be quite long. To avoid getting one
* that is too long for this test we use a restricted ciphersuite list
*/
if (!TEST_false(SSL_CTX_set_cipher_list(ctx, "")))
goto end;
ERR_clear_error();
/* Fall through */
case TEST_ADD_PADDING:
case TEST_PADDING_NOT_NEEDED:
SSL_CTX_set_options(ctx, SSL_OP_TLSEXT_PADDING);
/* Make sure we get a consistent size across TLS versions */
SSL_CTX_clear_options(ctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
/*
* Add some dummy ALPN protocols so that the ClientHello is at least
* F5_WORKAROUND_MIN_MSG_LEN bytes long - meaning padding will be
* needed.
*/
if (currtest == TEST_ADD_PADDING) {
if (!TEST_false(SSL_CTX_set_alpn_protos(ctx,
(unsigned char *)alpn_prots,
sizeof(alpn_prots) - 1)))
goto end;
/*
* Otherwise we need to make sure we have a small enough message to
* not need padding.
*/
} else if (!TEST_true(SSL_CTX_set_cipher_list(ctx,
"AES128-SHA"))
|| !TEST_true(SSL_CTX_set_ciphersuites(ctx,
"TLS_AES_128_GCM_SHA256"))) {
goto end;
}
break;
default:
goto end;
}
con = SSL_new(ctx);
if (!TEST_ptr(con))
goto end;
if (currtest == TEST_ADD_PADDING_AND_PSK) {
sessbio = BIO_new_file(sessionfile, "r");
if (!TEST_ptr(sessbio)) {
TEST_info("Unable to open session.pem");
goto end;
}
sess = PEM_read_bio_SSL_SESSION(sessbio, NULL, NULL, NULL);
if (!TEST_ptr(sess)) {
TEST_info("Unable to load SSL_SESSION");
goto end;
}
/*
* We reset the creation time so that we don't discard the session as
* too old.
*/
if (!TEST_true(SSL_SESSION_set_time(sess, (long)time(NULL)))
|| !TEST_true(SSL_set_session(con, sess)))
goto end;
}
rbio = BIO_new(BIO_s_mem());
wbio = BIO_new(BIO_s_mem());
if (!TEST_ptr(rbio)|| !TEST_ptr(wbio)) {
BIO_free(rbio);
BIO_free(wbio);
goto end;
}
SSL_set_bio(con, rbio, wbio);
SSL_set_connect_state(con);
if (currtest == TEST_SET_SESSION_TICK_DATA_VER_NEG) {
if (!TEST_true(SSL_set_session_ticket_ext(con, dummytick,
strlen(dummytick))))
goto end;
}
if (!TEST_int_le(SSL_connect(con), 0)) {
/* This shouldn't succeed because we don't have a server! */
goto end;
}
if (!TEST_long_ge(len = BIO_get_mem_data(wbio, (char **)&data), 0)
|| !TEST_true(PACKET_buf_init(&pkt, data, len))
/* Skip the record header */
|| !PACKET_forward(&pkt, SSL3_RT_HEADER_LENGTH))
goto end;
msglen = PACKET_remaining(&pkt);
/* Skip the handshake message header */
if (!TEST_true(PACKET_forward(&pkt, SSL3_HM_HEADER_LENGTH))
/* Skip client version and random */
|| !TEST_true(PACKET_forward(&pkt, CLIENT_VERSION_LEN
+ SSL3_RANDOM_SIZE))
/* Skip session id */
|| !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
/* Skip ciphers */
|| !TEST_true(PACKET_get_length_prefixed_2(&pkt, &pkt2))
/* Skip compression */
|| !TEST_true(PACKET_get_length_prefixed_1(&pkt, &pkt2))
/* Extensions len */
|| !TEST_true(PACKET_as_length_prefixed_2(&pkt, &pkt2)))
goto end;
/* Loop through all extensions */
while (PACKET_remaining(&pkt2)) {
if (!TEST_true(PACKET_get_net_2(&pkt2, &type))
|| !TEST_true(PACKET_get_length_prefixed_2(&pkt2, &pkt3)))
goto end;
if (type == TLSEXT_TYPE_session_ticket) {
if (currtest == TEST_SET_SESSION_TICK_DATA_VER_NEG) {
if (TEST_true(PACKET_equal(&pkt3, dummytick,
strlen(dummytick)))) {
/* Ticket data is as we expected */
testresult = 1;
}
goto end;
}
}
if (type == TLSEXT_TYPE_padding) {
if (!TEST_false(currtest == TEST_PADDING_NOT_NEEDED))
goto end;
else if (TEST_true(currtest == TEST_ADD_PADDING
|| currtest == TEST_ADD_PADDING_AND_PSK))
testresult = TEST_true(msglen == F5_WORKAROUND_MAX_MSG_LEN);
}
}
if (currtest == TEST_PADDING_NOT_NEEDED)
testresult = 1;
end:
SSL_free(con);
SSL_CTX_free(ctx);
SSL_SESSION_free(sess);
BIO_free(sessbio);
return testresult;
}
OPT_TEST_DECLARE_USAGE("sessionfile\n")
int setup_tests(void)
{
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
if (!TEST_ptr(sessionfile = test_get_argument(0)))
return 0;
ADD_ALL_TESTS(test_client_hello, TOTAL_NUM_TESTS);
return 1;
}
| 8,739 | 31.37037 | 87 | c |
openssl | openssl-master/test/cmactest.c | /*
* Copyright 1995-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
*/
/*
* CMAC 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 <stdlib.h>
#include "internal/nelem.h"
#include <openssl/cmac.h>
#include <openssl/aes.h>
#include <openssl/evp.h>
#include "testutil.h"
static const char xtskey[32] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
};
static struct test_st {
const char key[32];
int key_len;
unsigned char data[4096];
int data_len;
const char *mac;
} test[] = {
{
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
0x0b, 0x0c, 0x0d, 0x0e, 0x0f
},
16,
"My test data",
12,
"29cec977c48f63c200bd5c4a6881b224"
},
{
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
},
32,
"My test data",
12,
"db6493aa04e4761f473b2b453c031c9a"
},
{
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
},
32,
"My test data again",
18,
"65c11c75ecf590badd0a5e56cbb8af60"
},
/* for aes-128-cbc */
{
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
0x0b, 0x0c, 0x0d, 0x0e, 0x0f
},
16,
/* repeat the string below until filling 3072 bytes */
"#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#",
3072,
"35da8a02a7afce90e5b711308cee2dee"
},
/* for aes-192-cbc */
{
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
0x16, 0x17
},
24,
/* repeat the string below until filling 4095 bytes */
"#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#",
4095,
"59053f4e81f3593610f987adb547c5b2"
},
/* for aes-256-cbc */
{
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
},
32,
/* repeat the string below until filling 2560 bytes */
"#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#",
2560,
"9c6cf85f7f4baca99725764a0df973a9"
},
/* for des-ede3-cbc */
{
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
},
24,
/* repeat the string below until filling 2048 bytes */
"#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#",
2048,
"2c2fccc7fcc5d98a"
},
/* for sm4-cbc */
{
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
0x0b, 0x0c, 0x0d, 0x0e, 0x0f
},
16,
/* repeat the string below until filling 2049 bytes */
"#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#",
2049,
"c9a9cbc82a3b2d96074e386fce1216f2"
},
};
static char *pt(unsigned char *md, unsigned int len);
static int test_cmac_bad(void)
{
CMAC_CTX *ctx = NULL;
int ret = 0;
ctx = CMAC_CTX_new();
if (!TEST_ptr(ctx)
|| !TEST_false(CMAC_Init(ctx, NULL, 0, NULL, NULL))
|| !TEST_false(CMAC_Update(ctx, test[0].data, test[0].data_len))
/* Should be able to pass cipher first, and then key */
|| !TEST_true(CMAC_Init(ctx, NULL, 0, EVP_aes_128_cbc(), NULL))
/* Must have a key */
|| !TEST_false(CMAC_Update(ctx, test[0].data, test[0].data_len))
/* Now supply the key */
|| !TEST_true(CMAC_Init(ctx, test[0].key, test[0].key_len, NULL, NULL))
/* Update should now work */
|| !TEST_true(CMAC_Update(ctx, test[0].data, test[0].data_len))
/* XTS is not a suitable cipher to use */
|| !TEST_false(CMAC_Init(ctx, xtskey, sizeof(xtskey), EVP_aes_128_xts(),
NULL))
|| !TEST_false(CMAC_Update(ctx, test[0].data, test[0].data_len)))
goto err;
ret = 1;
err:
CMAC_CTX_free(ctx);
return ret;
}
static int test_cmac_run(void)
{
char *p;
CMAC_CTX *ctx = NULL;
unsigned char buf[AES_BLOCK_SIZE];
size_t len;
int ret = 0;
size_t case_idx = 0;
ctx = CMAC_CTX_new();
/* Construct input data, fill repeatedly until reaching data length */
for (case_idx = 0; case_idx < OSSL_NELEM(test); case_idx++) {
size_t str_len = strlen((char *)test[case_idx].data);
size_t fill_len = test[case_idx].data_len - str_len;
size_t fill_idx = str_len;
while (fill_len > 0) {
if (fill_len > str_len) {
memcpy(&test[case_idx].data[fill_idx], test[case_idx].data, str_len);
fill_len -= str_len;
fill_idx += str_len;
} else {
memcpy(&test[case_idx].data[fill_idx], test[case_idx].data, fill_len);
fill_len = 0;
}
}
}
if (!TEST_true(CMAC_Init(ctx, test[0].key, test[0].key_len,
EVP_aes_128_cbc(), NULL))
|| !TEST_true(CMAC_Update(ctx, test[0].data, test[0].data_len))
|| !TEST_true(CMAC_Final(ctx, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_str_eq(p, test[0].mac))
goto err;
if (!TEST_true(CMAC_Init(ctx, test[1].key, test[1].key_len,
EVP_aes_256_cbc(), NULL))
|| !TEST_true(CMAC_Update(ctx, test[1].data, test[1].data_len))
|| !TEST_true(CMAC_Final(ctx, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_str_eq(p, test[1].mac))
goto err;
if (!TEST_true(CMAC_Init(ctx, test[2].key, test[2].key_len, NULL, NULL))
|| !TEST_true(CMAC_Update(ctx, test[2].data, test[2].data_len))
|| !TEST_true(CMAC_Final(ctx, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_str_eq(p, test[2].mac))
goto err;
/* Test reusing a key */
if (!TEST_true(CMAC_Init(ctx, NULL, 0, NULL, NULL))
|| !TEST_true(CMAC_Update(ctx, test[2].data, test[2].data_len))
|| !TEST_true(CMAC_Final(ctx, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_str_eq(p, test[2].mac))
goto err;
/* Test setting the cipher and key separately */
if (!TEST_true(CMAC_Init(ctx, NULL, 0, EVP_aes_256_cbc(), NULL))
|| !TEST_true(CMAC_Init(ctx, test[2].key, test[2].key_len, NULL, NULL))
|| !TEST_true(CMAC_Update(ctx, test[2].data, test[2].data_len))
|| !TEST_true(CMAC_Final(ctx, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_str_eq(p, test[2].mac))
goto err;
/* Test data length is greater than 1 block length */
if (!TEST_true(CMAC_Init(ctx, test[3].key, test[3].key_len,
EVP_aes_128_cbc(), NULL))
|| !TEST_true(CMAC_Update(ctx, test[3].data, test[3].data_len))
|| !TEST_true(CMAC_Final(ctx, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_str_eq(p, test[3].mac))
goto err;
if (!TEST_true(CMAC_Init(ctx, test[4].key, test[4].key_len,
EVP_aes_192_cbc(), NULL))
|| !TEST_true(CMAC_Update(ctx, test[4].data, test[4].data_len))
|| !TEST_true(CMAC_Final(ctx, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_str_eq(p, test[4].mac))
goto err;
if (!TEST_true(CMAC_Init(ctx, test[5].key, test[5].key_len,
EVP_aes_256_cbc(), NULL))
|| !TEST_true(CMAC_Update(ctx, test[5].data, test[5].data_len))
|| !TEST_true(CMAC_Final(ctx, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_str_eq(p, test[5].mac))
goto err;
#ifndef OPENSSL_NO_DES
if (!TEST_true(CMAC_Init(ctx, test[6].key, test[6].key_len,
EVP_des_ede3_cbc(), NULL))
|| !TEST_true(CMAC_Update(ctx, test[6].data, test[6].data_len))
|| !TEST_true(CMAC_Final(ctx, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_str_eq(p, test[6].mac))
goto err;
#endif
#ifndef OPENSSL_NO_SM4
if (!TEST_true(CMAC_Init(ctx, test[7].key, test[7].key_len,
EVP_sm4_cbc(), NULL))
|| !TEST_true(CMAC_Update(ctx, test[7].data, test[7].data_len))
|| !TEST_true(CMAC_Final(ctx, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_str_eq(p, test[7].mac))
goto err;
#endif
ret = 1;
err:
CMAC_CTX_free(ctx);
return ret;
}
static int test_cmac_copy(void)
{
char *p;
CMAC_CTX *ctx = NULL, *ctx2 = NULL;
unsigned char buf[AES_BLOCK_SIZE];
size_t len;
int ret = 0;
ctx = CMAC_CTX_new();
ctx2 = CMAC_CTX_new();
if (!TEST_ptr(ctx) || !TEST_ptr(ctx2))
goto err;
if (!TEST_true(CMAC_Init(ctx, test[0].key, test[0].key_len,
EVP_aes_128_cbc(), NULL))
|| !TEST_true(CMAC_Update(ctx, test[0].data, test[0].data_len))
|| !TEST_true(CMAC_CTX_copy(ctx2, ctx))
|| !TEST_true(CMAC_Final(ctx2, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_str_eq(p, test[0].mac))
goto err;
ret = 1;
err:
CMAC_CTX_free(ctx2);
CMAC_CTX_free(ctx);
return ret;
}
static char *pt(unsigned char *md, unsigned int len)
{
unsigned int i;
static char buf[80];
for (i = 0; i < len; i++)
sprintf(&(buf[i * 2]), "%02x", md[i]);
return buf;
}
int setup_tests(void)
{
ADD_TEST(test_cmac_bad);
ADD_TEST(test_cmac_run);
ADD_TEST(test_cmac_copy);
return 1;
}
| 10,851 | 30.183908 | 86 | c |
openssl | openssl-master/test/cmp_asn_test.c | /*
* Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright Nokia 2007-2019
* Copyright Siemens AG 2015-2019
*
* 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 "helpers/cmp_testlib.h"
static unsigned char rand_data[OSSL_CMP_TRANSACTIONID_LENGTH];
typedef struct test_fixture {
const char *test_case_name;
int expected;
ASN1_OCTET_STRING *src_string;
ASN1_OCTET_STRING *tgt_string;
} CMP_ASN_TEST_FIXTURE;
static CMP_ASN_TEST_FIXTURE *set_up(const char *const test_case_name)
{
CMP_ASN_TEST_FIXTURE *fixture;
if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture))))
return NULL;
fixture->test_case_name = test_case_name;
return fixture;
}
static void tear_down(CMP_ASN_TEST_FIXTURE *fixture)
{
ASN1_OCTET_STRING_free(fixture->src_string);
if (fixture->tgt_string != fixture->src_string)
ASN1_OCTET_STRING_free(fixture->tgt_string);
OPENSSL_free(fixture);
}
static int execute_cmp_asn1_get_int_test(CMP_ASN_TEST_FIXTURE *fixture)
{
int res;
ASN1_INTEGER *asn1integer = ASN1_INTEGER_new();
if (!TEST_ptr(asn1integer))
return 0;
if (!TEST_true(ASN1_INTEGER_set(asn1integer, 77))) {
ASN1_INTEGER_free(asn1integer);
return 0;
}
res = TEST_int_eq(77, ossl_cmp_asn1_get_int(asn1integer));
ASN1_INTEGER_free(asn1integer);
return res;
}
static int test_cmp_asn1_get_int(void)
{
SETUP_TEST_FIXTURE(CMP_ASN_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_cmp_asn1_get_int_test, tear_down);
return result;
}
static int execute_CMP_ASN1_OCTET_STRING_set1_test(CMP_ASN_TEST_FIXTURE *
fixture)
{
if (!TEST_int_eq(fixture->expected,
ossl_cmp_asn1_octet_string_set1(&fixture->tgt_string,
fixture->src_string)))
return 0;
if (fixture->expected != 0)
return TEST_int_eq(0, ASN1_OCTET_STRING_cmp(fixture->tgt_string,
fixture->src_string));
return 1;
}
static int test_ASN1_OCTET_STRING_set(void)
{
SETUP_TEST_FIXTURE(CMP_ASN_TEST_FIXTURE, set_up);
fixture->expected = 1;
if (!TEST_ptr(fixture->tgt_string = ASN1_OCTET_STRING_new())
|| !TEST_ptr(fixture->src_string = ASN1_OCTET_STRING_new())
|| !TEST_true(ASN1_OCTET_STRING_set(fixture->src_string, rand_data,
sizeof(rand_data)))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_CMP_ASN1_OCTET_STRING_set1_test, tear_down);
return result;
}
static int test_ASN1_OCTET_STRING_set_tgt_is_src(void)
{
SETUP_TEST_FIXTURE(CMP_ASN_TEST_FIXTURE, set_up);
fixture->expected = 1;
if (!TEST_ptr(fixture->src_string = ASN1_OCTET_STRING_new())
|| !(fixture->tgt_string = fixture->src_string)
|| !TEST_true(ASN1_OCTET_STRING_set(fixture->src_string, rand_data,
sizeof(rand_data)))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_CMP_ASN1_OCTET_STRING_set1_test, tear_down);
return result;
}
void cleanup_tests(void)
{
return;
}
int setup_tests(void)
{
RAND_bytes(rand_data, OSSL_CMP_TRANSACTIONID_LENGTH);
/* ASN.1 related tests */
ADD_TEST(test_cmp_asn1_get_int);
ADD_TEST(test_ASN1_OCTET_STRING_set);
ADD_TEST(test_ASN1_OCTET_STRING_set_tgt_is_src);
return 1;
}
| 3,781 | 29.5 | 79 | c |
openssl | openssl-master/test/cmp_client_test.c | /*
* Copyright 2007-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright Nokia 2007-2019
* Copyright Siemens AG 2015-2019
*
* 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 "helpers/cmp_testlib.h"
#include "cmp_mock_srv.h"
static const char *server_key_f;
static const char *server_cert_f;
static const char *client_key_f;
static const char *client_cert_f;
static const char *pkcs10_f;
typedef struct test_fixture {
const char *test_case_name;
OSSL_CMP_CTX *cmp_ctx;
OSSL_CMP_SRV_CTX *srv_ctx;
int req_type;
int expected;
STACK_OF(X509) *caPubs;
} CMP_SES_TEST_FIXTURE;
static OSSL_LIB_CTX *libctx = NULL;
static OSSL_PROVIDER *default_null_provider = NULL, *provider = NULL;
static EVP_PKEY *server_key = NULL;
static X509 *server_cert = NULL;
static EVP_PKEY *client_key = NULL;
static X509 *client_cert = NULL;
static unsigned char ref[CMP_TEST_REFVALUE_LENGTH];
/*
* For these unit tests, the client abandons message protection, and for
* error messages the mock server does so as well.
* Message protection and verification is tested in cmp_lib_test.c
*/
static void tear_down(CMP_SES_TEST_FIXTURE *fixture)
{
OSSL_CMP_CTX_free(fixture->cmp_ctx);
ossl_cmp_mock_srv_free(fixture->srv_ctx);
sk_X509_free(fixture->caPubs);
OPENSSL_free(fixture);
}
static CMP_SES_TEST_FIXTURE *set_up(const char *const test_case_name)
{
CMP_SES_TEST_FIXTURE *fixture;
OSSL_CMP_CTX *srv_cmp_ctx = NULL;
OSSL_CMP_CTX *ctx = NULL; /* for client */
if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture))))
return NULL;
fixture->test_case_name = test_case_name;
if (!TEST_ptr(fixture->srv_ctx = ossl_cmp_mock_srv_new(libctx, NULL))
|| !OSSL_CMP_SRV_CTX_set_accept_unprotected(fixture->srv_ctx, 1)
|| !ossl_cmp_mock_srv_set1_refCert(fixture->srv_ctx, client_cert)
|| !ossl_cmp_mock_srv_set1_certOut(fixture->srv_ctx, client_cert)
|| (srv_cmp_ctx =
OSSL_CMP_SRV_CTX_get0_cmp_ctx(fixture->srv_ctx)) == NULL
|| !OSSL_CMP_CTX_set1_cert(srv_cmp_ctx, server_cert)
|| !OSSL_CMP_CTX_set1_pkey(srv_cmp_ctx, server_key))
goto err;
if (!TEST_ptr(fixture->cmp_ctx = ctx = OSSL_CMP_CTX_new(libctx, NULL))
|| !OSSL_CMP_CTX_set_log_cb(fixture->cmp_ctx, print_to_bio_out)
|| !OSSL_CMP_CTX_set_transfer_cb(ctx, OSSL_CMP_CTX_server_perform)
|| !OSSL_CMP_CTX_set_transfer_cb_arg(ctx, fixture->srv_ctx)
|| !OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_SEND, 1)
|| !OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_ERRORS, 1)
|| !OSSL_CMP_CTX_set1_oldCert(ctx, client_cert)
|| !OSSL_CMP_CTX_set1_pkey(ctx, client_key)
/* client_key is by default used also for newPkey */
|| !OSSL_CMP_CTX_set1_srvCert(ctx, server_cert)
|| !OSSL_CMP_CTX_set1_referenceValue(ctx, ref, sizeof(ref)))
goto err;
fixture->req_type = -1;
return fixture;
err:
tear_down(fixture);
return NULL;
}
static int execute_exec_RR_ses_test(CMP_SES_TEST_FIXTURE *fixt)
{
return TEST_int_eq(OSSL_CMP_CTX_get_status(fixt->cmp_ctx),
OSSL_CMP_PKISTATUS_unspecified)
&& TEST_int_eq(OSSL_CMP_exec_RR_ses(fixt->cmp_ctx),
fixt->expected == OSSL_CMP_PKISTATUS_accepted)
&& TEST_int_eq(OSSL_CMP_CTX_get_status(fixt->cmp_ctx), fixt->expected);
}
static int execute_exec_GENM_ses_test_single(CMP_SES_TEST_FIXTURE *fixture)
{
OSSL_CMP_CTX *ctx = fixture->cmp_ctx;
ASN1_OBJECT *type = OBJ_txt2obj("1.3.6.1.5.5.7.4.2", 1);
OSSL_CMP_ITAV *itav = OSSL_CMP_ITAV_create(type, NULL);
STACK_OF(OSSL_CMP_ITAV) *itavs;
OSSL_CMP_CTX_push0_genm_ITAV(ctx, itav);
itavs = OSSL_CMP_exec_GENM_ses(ctx);
sk_OSSL_CMP_ITAV_pop_free(itavs, OSSL_CMP_ITAV_free);
return TEST_int_eq(OSSL_CMP_CTX_get_status(ctx), fixture->expected)
&& fixture->expected == OSSL_CMP_PKISTATUS_accepted ?
TEST_ptr(itavs) : TEST_ptr_null(itavs);
}
static int execute_exec_GENM_ses_test(CMP_SES_TEST_FIXTURE *fixture)
{
return execute_exec_GENM_ses_test_single(fixture)
&& OSSL_CMP_CTX_reinit(fixture->cmp_ctx)
&& execute_exec_GENM_ses_test_single(fixture);
}
static int execute_exec_certrequest_ses_test(CMP_SES_TEST_FIXTURE *fixture)
{
OSSL_CMP_CTX *ctx = fixture->cmp_ctx;
X509 *res = OSSL_CMP_exec_certreq(ctx, fixture->req_type, NULL);
int status = OSSL_CMP_CTX_get_status(ctx);
OSSL_CMP_CTX_print_errors(ctx);
if (!TEST_int_eq(status, fixture->expected)
&& !(fixture->expected == OSSL_CMP_PKISTATUS_waiting
&& TEST_int_eq(status, OSSL_CMP_PKISTATUS_trans)))
return 0;
if (fixture->expected != OSSL_CMP_PKISTATUS_accepted)
return TEST_ptr_null(res);
if (!TEST_ptr(res) || !TEST_int_eq(X509_cmp(res, client_cert), 0))
return 0;
if (fixture->caPubs != NULL) {
STACK_OF(X509) *caPubs = OSSL_CMP_CTX_get1_caPubs(fixture->cmp_ctx);
int ret = TEST_int_eq(STACK_OF_X509_cmp(fixture->caPubs, caPubs), 0);
OSSL_STACK_OF_X509_free(caPubs);
return ret;
}
return 1;
}
static int test_exec_RR_ses(int request_error)
{
SETUP_TEST_FIXTURE(CMP_SES_TEST_FIXTURE, set_up);
if (request_error)
OSSL_CMP_CTX_set1_oldCert(fixture->cmp_ctx, NULL);
fixture->expected = request_error ? OSSL_CMP_PKISTATUS_request
: OSSL_CMP_PKISTATUS_accepted;
EXECUTE_TEST(execute_exec_RR_ses_test, tear_down);
return result;
}
static int test_exec_RR_ses_ok(void)
{
return test_exec_RR_ses(0);
}
static int test_exec_RR_ses_request_error(void)
{
return test_exec_RR_ses(1);
}
static int test_exec_RR_ses_receive_error(void)
{
SETUP_TEST_FIXTURE(CMP_SES_TEST_FIXTURE, set_up);
ossl_cmp_mock_srv_set_statusInfo(fixture->srv_ctx,
OSSL_CMP_PKISTATUS_rejection,
OSSL_CMP_CTX_FAILINFO_signerNotTrusted,
"test string");
ossl_cmp_mock_srv_set_sendError(fixture->srv_ctx, OSSL_CMP_PKIBODY_RR);
fixture->expected = OSSL_CMP_PKISTATUS_rejection;
EXECUTE_TEST(execute_exec_RR_ses_test, tear_down);
return result;
}
static int test_exec_IR_ses(void)
{
SETUP_TEST_FIXTURE(CMP_SES_TEST_FIXTURE, set_up);
fixture->req_type = OSSL_CMP_IR;
fixture->expected = OSSL_CMP_PKISTATUS_accepted;
fixture->caPubs = sk_X509_new_null();
sk_X509_push(fixture->caPubs, server_cert);
sk_X509_push(fixture->caPubs, server_cert);
ossl_cmp_mock_srv_set1_caPubsOut(fixture->srv_ctx, fixture->caPubs);
EXECUTE_TEST(execute_exec_certrequest_ses_test, tear_down);
return result;
}
static int test_exec_IR_ses_poll(int check_after, int poll_count,
int total_timeout, int expect)
{
SETUP_TEST_FIXTURE(CMP_SES_TEST_FIXTURE, set_up);
fixture->req_type = OSSL_CMP_IR;
fixture->expected = expect;
ossl_cmp_mock_srv_set_checkAfterTime(fixture->srv_ctx, check_after);
ossl_cmp_mock_srv_set_pollCount(fixture->srv_ctx, poll_count);
OSSL_CMP_CTX_set_option(fixture->cmp_ctx,
OSSL_CMP_OPT_TOTAL_TIMEOUT, total_timeout);
EXECUTE_TEST(execute_exec_certrequest_ses_test, tear_down);
return result;
}
static int checkAfter = 1;
static int test_exec_IR_ses_poll_ok(void)
{
return test_exec_IR_ses_poll(checkAfter, 2, 0, OSSL_CMP_PKISTATUS_accepted);
}
static int test_exec_IR_ses_poll_no_timeout(void)
{
return test_exec_IR_ses_poll(checkAfter, 1 /* pollCount */, checkAfter + 1,
OSSL_CMP_PKISTATUS_accepted);
}
static int test_exec_IR_ses_poll_total_timeout(void)
{
return test_exec_IR_ses_poll(checkAfter + 1, 2 /* pollCount */, checkAfter,
OSSL_CMP_PKISTATUS_waiting);
}
static int test_exec_CR_ses(int implicit_confirm, int granted, int reject)
{
SETUP_TEST_FIXTURE(CMP_SES_TEST_FIXTURE, set_up);
fixture->req_type = OSSL_CMP_CR;
OSSL_CMP_CTX_set_option(fixture->cmp_ctx,
OSSL_CMP_OPT_IMPLICIT_CONFIRM, implicit_confirm);
OSSL_CMP_SRV_CTX_set_grant_implicit_confirm(fixture->srv_ctx, granted);
ossl_cmp_mock_srv_set_sendError(fixture->srv_ctx,
reject ? OSSL_CMP_PKIBODY_CERTCONF : -1);
fixture->expected = reject ? OSSL_CMP_PKISTATUS_rejection
: OSSL_CMP_PKISTATUS_accepted;
EXECUTE_TEST(execute_exec_certrequest_ses_test, tear_down);
return result;
}
static int test_exec_CR_ses_explicit_confirm(void)
{
return test_exec_CR_ses(0, 0, 0)
&& test_exec_CR_ses(0, 0, 1 /* reject */);
}
static int test_exec_CR_ses_implicit_confirm(void)
{
return test_exec_CR_ses(1, 0, 0)
&& test_exec_CR_ses(1, 1 /* granted */, 0);
}
static int test_exec_KUR_ses(int transfer_error, int pubkey, int raverified)
{
SETUP_TEST_FIXTURE(CMP_SES_TEST_FIXTURE, set_up);
fixture->req_type = OSSL_CMP_KUR;
/* ctx->oldCert has already been set */
if (transfer_error)
OSSL_CMP_CTX_set_transfer_cb_arg(fixture->cmp_ctx, NULL);
if (pubkey) {
EVP_PKEY *key = raverified /* wrong key */ ? server_key : client_key;
EVP_PKEY_up_ref(key);
OSSL_CMP_CTX_set0_newPkey(fixture->cmp_ctx, 0 /* not priv */, key);
OSSL_CMP_SRV_CTX_set_accept_raverified(fixture->srv_ctx, 1);
}
if (pubkey || raverified)
OSSL_CMP_CTX_set_option(fixture->cmp_ctx, OSSL_CMP_OPT_POPO_METHOD,
OSSL_CRMF_POPO_RAVERIFIED);
fixture->expected = transfer_error ? OSSL_CMP_PKISTATUS_trans :
raverified ? OSSL_CMP_PKISTATUS_rejection : OSSL_CMP_PKISTATUS_accepted;
EXECUTE_TEST(execute_exec_certrequest_ses_test, tear_down);
return result;
}
static int test_exec_KUR_ses_ok(void)
{
return test_exec_KUR_ses(0, 0, 0);
}
static int test_exec_KUR_ses_transfer_error(void)
{
return test_exec_KUR_ses(1, 0, 0);
}
static int test_exec_KUR_ses_wrong_popo(void)
{
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION /* cf ossl_cmp_verify_popo() */
return test_exec_KUR_ses(0, 0, 1);
#else
return 1;
#endif
}
static int test_exec_KUR_ses_pub(void)
{
return test_exec_KUR_ses(0, 1, 0);
}
static int test_exec_KUR_ses_wrong_pub(void)
{
return test_exec_KUR_ses(0, 1, 1);
}
static int test_certConf_cb(OSSL_CMP_CTX *ctx, X509 *cert, int fail_info,
const char **txt)
{
int *reject = OSSL_CMP_CTX_get_certConf_cb_arg(ctx);
if (*reject) {
*txt = "not to my taste";
fail_info = OSSL_CMP_PKIFAILUREINFO_badCertTemplate;
}
return fail_info;
}
static int test_exec_P10CR_ses(int reject)
{
OSSL_CMP_CTX *ctx;
X509_REQ *csr = NULL;
SETUP_TEST_FIXTURE(CMP_SES_TEST_FIXTURE, set_up);
fixture->req_type = OSSL_CMP_P10CR;
fixture->expected = reject ? OSSL_CMP_PKISTATUS_rejection
: OSSL_CMP_PKISTATUS_accepted;
ctx = fixture->cmp_ctx;
if (!TEST_ptr(csr = load_csr_der(pkcs10_f, libctx))
|| !TEST_true(OSSL_CMP_CTX_set1_p10CSR(ctx, csr))
|| !TEST_true(OSSL_CMP_CTX_set_certConf_cb(ctx, test_certConf_cb))
|| !TEST_true(OSSL_CMP_CTX_set_certConf_cb_arg(ctx, &reject))) {
tear_down(fixture);
fixture = NULL;
}
X509_REQ_free(csr);
EXECUTE_TEST(execute_exec_certrequest_ses_test, tear_down);
return result;
}
static int test_exec_P10CR_ses_ok(void)
{
return test_exec_P10CR_ses(0);
}
static int test_exec_P10CR_ses_reject(void)
{
return test_exec_P10CR_ses(1);
}
static int execute_try_certreq_poll_test(CMP_SES_TEST_FIXTURE *fixture)
{
OSSL_CMP_CTX *ctx = fixture->cmp_ctx;
int check_after;
const int CHECK_AFTER = 5;
const int TYPE = OSSL_CMP_KUR;
ossl_cmp_mock_srv_set_pollCount(fixture->srv_ctx, 3);
ossl_cmp_mock_srv_set_checkAfterTime(fixture->srv_ctx, CHECK_AFTER);
return TEST_int_eq(-1, OSSL_CMP_try_certreq(ctx, TYPE, NULL, &check_after))
&& check_after == CHECK_AFTER
&& TEST_ptr_eq(OSSL_CMP_CTX_get0_newCert(ctx), NULL)
&& TEST_int_eq(-1, OSSL_CMP_try_certreq(ctx, TYPE, NULL, &check_after))
&& check_after == CHECK_AFTER
&& TEST_ptr_eq(OSSL_CMP_CTX_get0_newCert(ctx), NULL)
&& TEST_int_eq(fixture->expected,
OSSL_CMP_try_certreq(ctx, TYPE, NULL, NULL))
&& TEST_int_eq(0,
X509_cmp(OSSL_CMP_CTX_get0_newCert(ctx), client_cert));
}
static int test_try_certreq_poll(void)
{
SETUP_TEST_FIXTURE(CMP_SES_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_try_certreq_poll_test, tear_down);
return result;
}
static int execute_try_certreq_poll_abort_test(CMP_SES_TEST_FIXTURE *fixture)
{
OSSL_CMP_CTX *ctx = fixture->cmp_ctx;
int check_after;
const int CHECK_AFTER = 99;
const int TYPE = OSSL_CMP_CR;
ossl_cmp_mock_srv_set_pollCount(fixture->srv_ctx, 3);
ossl_cmp_mock_srv_set_checkAfterTime(fixture->srv_ctx, CHECK_AFTER);
return TEST_int_eq(-1, OSSL_CMP_try_certreq(ctx, TYPE, NULL, &check_after))
&& check_after == CHECK_AFTER
&& TEST_ptr_eq(OSSL_CMP_CTX_get0_newCert(ctx), NULL)
&& TEST_int_eq(fixture->expected,
OSSL_CMP_try_certreq(ctx, -1 /* abort */, NULL, NULL))
&& TEST_ptr_eq(OSSL_CMP_CTX_get0_newCert(fixture->cmp_ctx), NULL);
}
static int test_try_certreq_poll_abort(void)
{
SETUP_TEST_FIXTURE(CMP_SES_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_try_certreq_poll_abort_test, tear_down);
return result;
}
static int test_exec_GENM_ses(int transfer_error, int total_timeout, int expect)
{
SETUP_TEST_FIXTURE(CMP_SES_TEST_FIXTURE, set_up);
if (transfer_error)
OSSL_CMP_CTX_set_transfer_cb_arg(fixture->cmp_ctx, NULL);
/*
* cannot use OSSL_CMP_CTX_set_option(... OSSL_CMP_OPT_TOTAL_TIMEOUT)
* here because this will correct total_timeout to be >= 0
*/
fixture->cmp_ctx->total_timeout = total_timeout;
fixture->expected = expect;
EXECUTE_TEST(execute_exec_GENM_ses_test, tear_down);
return result;
}
static int test_exec_GENM_ses_ok(void)
{
return test_exec_GENM_ses(0, 0, OSSL_CMP_PKISTATUS_accepted);
}
static int test_exec_GENM_ses_transfer_error(void)
{
return test_exec_GENM_ses(1, 0, OSSL_CMP_PKISTATUS_trans);
}
static int test_exec_GENM_ses_total_timeout(void)
{
return test_exec_GENM_ses(0, -1, OSSL_CMP_PKISTATUS_trans);
}
static int execute_exchange_certConf_test(CMP_SES_TEST_FIXTURE *fixture)
{
int res =
ossl_cmp_exchange_certConf(fixture->cmp_ctx, OSSL_CMP_CERTREQID,
OSSL_CMP_PKIFAILUREINFO_addInfoNotAvailable,
"abcdefg");
return TEST_int_eq(fixture->expected, res);
}
static int execute_exchange_error_test(CMP_SES_TEST_FIXTURE *fixture)
{
int res =
ossl_cmp_exchange_error(fixture->cmp_ctx,
OSSL_CMP_PKISTATUS_rejection,
1 << OSSL_CMP_PKIFAILUREINFO_unsupportedVersion,
"foo_status", 999, "foo_details");
return TEST_int_eq(fixture->expected, res);
}
static int test_exchange_certConf(void)
{
SETUP_TEST_FIXTURE(CMP_SES_TEST_FIXTURE, set_up);
fixture->expected = 0; /* client should not send certConf immediately */
if (!ossl_cmp_ctx_set0_newCert(fixture->cmp_ctx, X509_dup(client_cert))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_exchange_certConf_test, tear_down);
return result;
}
static int test_exchange_error(void)
{
SETUP_TEST_FIXTURE(CMP_SES_TEST_FIXTURE, set_up);
fixture->expected = 1; /* client may send error any time */
EXECUTE_TEST(execute_exchange_error_test, tear_down);
return result;
}
void cleanup_tests(void)
{
X509_free(server_cert);
EVP_PKEY_free(server_key);
X509_free(client_cert);
EVP_PKEY_free(client_key);
OSSL_PROVIDER_unload(default_null_provider);
OSSL_PROVIDER_unload(provider);
OSSL_LIB_CTX_free(libctx);
return;
}
#define USAGE "server.key server.crt client.key client.crt client.csr module_name [module_conf_file]\n"
OPT_TEST_DECLARE_USAGE(USAGE)
int setup_tests(void)
{
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
if (!TEST_ptr(server_key_f = test_get_argument(0))
|| !TEST_ptr(server_cert_f = test_get_argument(1))
|| !TEST_ptr(client_key_f = test_get_argument(2))
|| !TEST_ptr(client_cert_f = test_get_argument(3))
|| !TEST_ptr(pkcs10_f = test_get_argument(4))) {
TEST_error("usage: cmp_client_test %s", USAGE);
return 0;
}
if (!test_arg_libctx(&libctx, &default_null_provider, &provider, 5, USAGE))
return 0;
if (!TEST_ptr(server_key = load_pkey_pem(server_key_f, libctx))
|| !TEST_ptr(server_cert = load_cert_pem(server_cert_f, libctx))
|| !TEST_ptr(client_key = load_pkey_pem(client_key_f, libctx))
|| !TEST_ptr(client_cert = load_cert_pem(client_cert_f, libctx))
|| !TEST_int_eq(1, RAND_bytes_ex(libctx, ref, sizeof(ref), 0))) {
cleanup_tests();
return 0;
}
ADD_TEST(test_exec_RR_ses_ok);
ADD_TEST(test_exec_RR_ses_request_error);
ADD_TEST(test_exec_RR_ses_receive_error);
ADD_TEST(test_exec_CR_ses_explicit_confirm);
ADD_TEST(test_exec_CR_ses_implicit_confirm);
ADD_TEST(test_exec_IR_ses);
ADD_TEST(test_exec_IR_ses_poll_ok);
ADD_TEST(test_exec_IR_ses_poll_no_timeout);
ADD_TEST(test_exec_IR_ses_poll_total_timeout);
ADD_TEST(test_exec_KUR_ses_ok);
ADD_TEST(test_exec_KUR_ses_transfer_error);
ADD_TEST(test_exec_KUR_ses_wrong_popo);
ADD_TEST(test_exec_KUR_ses_pub);
ADD_TEST(test_exec_KUR_ses_wrong_pub);
ADD_TEST(test_exec_P10CR_ses_ok);
ADD_TEST(test_exec_P10CR_ses_reject);
ADD_TEST(test_try_certreq_poll);
ADD_TEST(test_try_certreq_poll_abort);
ADD_TEST(test_exec_GENM_ses_ok);
ADD_TEST(test_exec_GENM_ses_transfer_error);
ADD_TEST(test_exec_GENM_ses_total_timeout);
ADD_TEST(test_exchange_certConf);
ADD_TEST(test_exchange_error);
return 1;
}
| 18,690 | 33.232601 | 103 | c |
openssl | openssl-master/test/cmp_hdr_test.c | /*
* Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright Nokia 2007-2019
* Copyright Siemens AG 2015-2019
*
* 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 "helpers/cmp_testlib.h"
static unsigned char rand_data[OSSL_CMP_TRANSACTIONID_LENGTH];
typedef struct test_fixture {
const char *test_case_name;
int expected;
OSSL_CMP_CTX *cmp_ctx;
OSSL_CMP_PKIHEADER *hdr;
} CMP_HDR_TEST_FIXTURE;
static void tear_down(CMP_HDR_TEST_FIXTURE *fixture)
{
OSSL_CMP_PKIHEADER_free(fixture->hdr);
OSSL_CMP_CTX_free(fixture->cmp_ctx);
OPENSSL_free(fixture);
}
static CMP_HDR_TEST_FIXTURE *set_up(const char *const test_case_name)
{
CMP_HDR_TEST_FIXTURE *fixture;
if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture))))
return NULL;
fixture->test_case_name = test_case_name;
if (!TEST_ptr(fixture->cmp_ctx = OSSL_CMP_CTX_new(NULL, NULL)))
goto err;
if (!TEST_ptr(fixture->hdr = OSSL_CMP_PKIHEADER_new()))
goto err;
return fixture;
err:
tear_down(fixture);
return NULL;
}
static int execute_HDR_set_get_pvno_test(CMP_HDR_TEST_FIXTURE *fixture)
{
int pvno = 77;
if (!TEST_int_eq(ossl_cmp_hdr_set_pvno(fixture->hdr, pvno), 1))
return 0;
if (!TEST_int_eq(ossl_cmp_hdr_get_pvno(fixture->hdr), pvno))
return 0;
return 1;
}
static int test_HDR_set_get_pvno(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_set_get_pvno_test, tear_down);
return result;
}
#define X509_NAME_ADD(n, rd, s) \
X509_NAME_add_entry_by_txt((n), (rd), MBSTRING_ASC, (unsigned char *)(s), \
-1, -1, 0)
static int execute_HDR_get0_senderNonce_test(CMP_HDR_TEST_FIXTURE *fixture)
{
X509_NAME *sender = X509_NAME_new();
ASN1_OCTET_STRING *sn;
if (!TEST_ptr(sender))
return 0;
X509_NAME_ADD(sender, "CN", "A common sender name");
if (!TEST_int_eq(OSSL_CMP_CTX_set1_subjectName(fixture->cmp_ctx, sender),
1))
return 0;
if (!TEST_int_eq(ossl_cmp_hdr_init(fixture->cmp_ctx, fixture->hdr),
1))
return 0;
sn = ossl_cmp_hdr_get0_senderNonce(fixture->hdr);
if (!TEST_int_eq(ASN1_OCTET_STRING_cmp(fixture->cmp_ctx->senderNonce, sn),
0))
return 0;
X509_NAME_free(sender);
return 1;
}
static int test_HDR_get0_senderNonce(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_get0_senderNonce_test, tear_down);
return result;
}
static int execute_HDR_set1_sender_test(CMP_HDR_TEST_FIXTURE *fixture)
{
X509_NAME *x509name = X509_NAME_new();
if (!TEST_ptr(x509name))
return 0;
X509_NAME_ADD(x509name, "CN", "A common sender name");
if (!TEST_int_eq(ossl_cmp_hdr_set1_sender(fixture->hdr, x509name), 1))
return 0;
if (!TEST_int_eq(fixture->hdr->sender->type, GEN_DIRNAME))
return 0;
if (!TEST_int_eq(X509_NAME_cmp(fixture->hdr->sender->d.directoryName,
x509name), 0))
return 0;
X509_NAME_free(x509name);
return 1;
}
static int test_HDR_set1_sender(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_set1_sender_test, tear_down);
return result;
}
static int execute_HDR_set1_recipient_test(CMP_HDR_TEST_FIXTURE *fixture)
{
X509_NAME *x509name = X509_NAME_new();
if (!TEST_ptr(x509name))
return 0;
X509_NAME_ADD(x509name, "CN", "A common recipient name");
if (!TEST_int_eq(ossl_cmp_hdr_set1_recipient(fixture->hdr, x509name), 1))
return 0;
if (!TEST_int_eq(fixture->hdr->recipient->type, GEN_DIRNAME))
return 0;
if (!TEST_int_eq(X509_NAME_cmp(fixture->hdr->recipient->d.directoryName,
x509name), 0))
return 0;
X509_NAME_free(x509name);
return 1;
}
static int test_HDR_set1_recipient(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_set1_recipient_test, tear_down);
return result;
}
static int execute_HDR_update_messageTime_test(CMP_HDR_TEST_FIXTURE *fixture)
{
struct tm hdrtm, tmptm;
time_t hdrtime, before, after, now;
now = time(NULL);
/*
* Trial and error reveals that passing the return value from gmtime
* directly to mktime in a mingw 32 bit build gives unexpected results. To
* work around this we take a copy of the return value first.
*/
tmptm = *gmtime(&now);
before = mktime(&tmptm);
if (!TEST_true(ossl_cmp_hdr_update_messageTime(fixture->hdr)))
return 0;
if (!TEST_true(ASN1_TIME_to_tm(fixture->hdr->messageTime, &hdrtm)))
return 0;
hdrtime = mktime(&hdrtm);
if (!TEST_time_t_le(before, hdrtime))
return 0;
now = time(NULL);
tmptm = *gmtime(&now);
after = mktime(&tmptm);
return TEST_time_t_le(hdrtime, after);
}
static int test_HDR_update_messageTime(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_update_messageTime_test, tear_down);
return result;
}
static int execute_HDR_set1_senderKID_test(CMP_HDR_TEST_FIXTURE *fixture)
{
ASN1_OCTET_STRING *senderKID = ASN1_OCTET_STRING_new();
int res = 0;
if (!TEST_ptr(senderKID))
return 0;
if (!TEST_int_eq(ASN1_OCTET_STRING_set(senderKID, rand_data,
sizeof(rand_data)), 1))
goto err;
if (!TEST_int_eq(ossl_cmp_hdr_set1_senderKID(fixture->hdr, senderKID), 1))
goto err;
if (!TEST_int_eq(ASN1_OCTET_STRING_cmp(fixture->hdr->senderKID,
senderKID), 0))
goto err;
res = 1;
err:
ASN1_OCTET_STRING_free(senderKID);
return res;
}
static int test_HDR_set1_senderKID(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_set1_senderKID_test, tear_down);
return result;
}
static int execute_HDR_push0_freeText_test(CMP_HDR_TEST_FIXTURE *fixture)
{
ASN1_UTF8STRING *text = ASN1_UTF8STRING_new();
if (!TEST_ptr(text))
return 0;
if (!ASN1_STRING_set(text, "A free text", -1))
goto err;
if (!TEST_int_eq(ossl_cmp_hdr_push0_freeText(fixture->hdr, text), 1))
goto err;
if (!TEST_true(text == sk_ASN1_UTF8STRING_value(fixture->hdr->freeText, 0)))
goto err;
return 1;
err:
ASN1_UTF8STRING_free(text);
return 0;
}
static int test_HDR_push0_freeText(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_push0_freeText_test, tear_down);
return result;
}
static int execute_HDR_push1_freeText_test(CMP_HDR_TEST_FIXTURE *fixture)
{
ASN1_UTF8STRING *text = ASN1_UTF8STRING_new();
ASN1_UTF8STRING *pushed_text;
int res = 0;
if (!TEST_ptr(text))
return 0;
if (!ASN1_STRING_set(text, "A free text", -1))
goto err;
if (!TEST_int_eq(ossl_cmp_hdr_push1_freeText(fixture->hdr, text), 1))
goto err;
pushed_text = sk_ASN1_UTF8STRING_value(fixture->hdr->freeText, 0);
if (!TEST_int_eq(ASN1_STRING_cmp(text, pushed_text), 0))
goto err;
res = 1;
err:
ASN1_UTF8STRING_free(text);
return res;
}
static int test_HDR_push1_freeText(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_push1_freeText_test, tear_down);
return result;
}
static int
execute_HDR_generalInfo_push0_item_test(CMP_HDR_TEST_FIXTURE *fixture)
{
OSSL_CMP_ITAV *itav = OSSL_CMP_ITAV_new();
if (!TEST_ptr(itav))
return 0;
if (!TEST_int_eq(ossl_cmp_hdr_generalInfo_push0_item(fixture->hdr, itav),
1))
return 0;
if (!TEST_true(itav == sk_OSSL_CMP_ITAV_value(fixture->hdr->generalInfo,
0)))
return 0;
return 1;
}
static int test_HDR_generalInfo_push0_item(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_generalInfo_push0_item_test, tear_down);
return result;
}
static int
execute_HDR_generalInfo_push1_items_test(CMP_HDR_TEST_FIXTURE *fixture)
{
const char oid[] = "1.2.3.4";
char buf[20];
OSSL_CMP_ITAV *itav, *pushed_itav;
STACK_OF(OSSL_CMP_ITAV) *itavs = NULL, *ginfo;
ASN1_INTEGER *asn1int = ASN1_INTEGER_new();
ASN1_TYPE *val = ASN1_TYPE_new();
ASN1_TYPE *pushed_val;
int res = 0;
if (!TEST_ptr(asn1int))
return 0;
if (!TEST_ptr(val)
|| !TEST_true(ASN1_INTEGER_set(asn1int, 88))) {
ASN1_INTEGER_free(asn1int);
return 0;
}
ASN1_TYPE_set(val, V_ASN1_INTEGER, asn1int);
if (!TEST_ptr(itav = OSSL_CMP_ITAV_create(OBJ_txt2obj(oid, 1), val))) {
ASN1_TYPE_free(val);
return 0;
}
if (!TEST_true(OSSL_CMP_ITAV_push0_stack_item(&itavs, itav))) {
OSSL_CMP_ITAV_free(itav);
return 0;
}
if (!TEST_int_eq(ossl_cmp_hdr_generalInfo_push1_items(fixture->hdr, itavs),
1))
goto err;
ginfo = fixture->hdr->generalInfo;
pushed_itav = sk_OSSL_CMP_ITAV_value(ginfo, 0);
OBJ_obj2txt(buf, sizeof(buf), OSSL_CMP_ITAV_get0_type(pushed_itav), 0);
if (!TEST_int_eq(memcmp(oid, buf, sizeof(oid)), 0))
goto err;
pushed_val = OSSL_CMP_ITAV_get0_value(sk_OSSL_CMP_ITAV_value(ginfo, 0));
if (!TEST_int_eq(ASN1_TYPE_cmp(itav->infoValue.other, pushed_val), 0))
goto err;
res = 1;
err:
sk_OSSL_CMP_ITAV_pop_free(itavs, OSSL_CMP_ITAV_free);
return res;
}
static int test_HDR_generalInfo_push1_items(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_HDR_generalInfo_push1_items_test, tear_down);
return result;
}
static int
execute_HDR_set_and_check_implicitConfirm_test(CMP_HDR_TEST_FIXTURE
* fixture)
{
return TEST_false(ossl_cmp_hdr_has_implicitConfirm(fixture->hdr))
&& TEST_true(ossl_cmp_hdr_set_implicitConfirm(fixture->hdr))
&& TEST_true(ossl_cmp_hdr_has_implicitConfirm(fixture->hdr));
}
static int test_HDR_set_and_check_implicit_confirm(void)
{
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
EXECUTE_TEST(execute_HDR_set_and_check_implicitConfirm_test, tear_down);
return result;
}
static int execute_HDR_init_test(CMP_HDR_TEST_FIXTURE *fixture)
{
ASN1_OCTET_STRING *header_nonce, *header_transactionID;
ASN1_OCTET_STRING *ctx_nonce;
if (!TEST_int_eq(fixture->expected,
ossl_cmp_hdr_init(fixture->cmp_ctx, fixture->hdr)))
return 0;
if (fixture->expected == 0)
return 1;
if (!TEST_int_eq(ossl_cmp_hdr_get_pvno(fixture->hdr), OSSL_CMP_PVNO))
return 0;
header_nonce = ossl_cmp_hdr_get0_senderNonce(fixture->hdr);
if (!TEST_int_eq(0, ASN1_OCTET_STRING_cmp(header_nonce,
fixture->cmp_ctx->senderNonce)))
return 0;
header_transactionID = OSSL_CMP_HDR_get0_transactionID(fixture->hdr);
if (!TEST_true(ASN1_OCTET_STRING_cmp(header_transactionID,
fixture->cmp_ctx->transactionID) == 0))
return 0;
header_nonce = OSSL_CMP_HDR_get0_recipNonce(fixture->hdr);
ctx_nonce = fixture->cmp_ctx->recipNonce;
if (ctx_nonce != NULL
&& (!TEST_ptr(header_nonce)
|| !TEST_int_eq(0, ASN1_OCTET_STRING_cmp(header_nonce,
ctx_nonce))))
return 0;
return 1;
}
static int test_HDR_init_with_ref(void)
{
unsigned char ref[CMP_TEST_REFVALUE_LENGTH];
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
if (!TEST_int_eq(1, RAND_bytes(ref, sizeof(ref)))
|| !TEST_true(OSSL_CMP_CTX_set1_referenceValue(fixture->cmp_ctx,
ref, sizeof(ref)))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_HDR_init_test, tear_down);
return result;
}
static int test_HDR_init_with_subject(void)
{
X509_NAME *subject = NULL;
SETUP_TEST_FIXTURE(CMP_HDR_TEST_FIXTURE, set_up);
fixture->expected = 1;
if (!TEST_ptr(subject = X509_NAME_new())
|| !TEST_true(X509_NAME_ADD(subject, "CN", "Common Name"))
|| !TEST_true(OSSL_CMP_CTX_set1_subjectName(fixture->cmp_ctx,
subject))) {
tear_down(fixture);
fixture = NULL;
}
X509_NAME_free(subject);
EXECUTE_TEST(execute_HDR_init_test, tear_down);
return result;
}
void cleanup_tests(void)
{
return;
}
int setup_tests(void)
{
RAND_bytes(rand_data, OSSL_CMP_TRANSACTIONID_LENGTH);
/* Message header tests */
ADD_TEST(test_HDR_set_get_pvno);
ADD_TEST(test_HDR_get0_senderNonce);
ADD_TEST(test_HDR_set1_sender);
ADD_TEST(test_HDR_set1_recipient);
ADD_TEST(test_HDR_update_messageTime);
ADD_TEST(test_HDR_set1_senderKID);
ADD_TEST(test_HDR_push0_freeText);
/* indirectly tests ossl_cmp_pkifreetext_push_str(): */
ADD_TEST(test_HDR_push1_freeText);
ADD_TEST(test_HDR_generalInfo_push0_item);
ADD_TEST(test_HDR_generalInfo_push1_items);
ADD_TEST(test_HDR_set_and_check_implicit_confirm);
/* also tests public function OSSL_CMP_HDR_get0_transactionID(): */
/* also tests public function OSSL_CMP_HDR_get0_recipNonce(): */
/* also tests internal function ossl_cmp_hdr_get_pvno(): */
ADD_TEST(test_HDR_init_with_ref);
ADD_TEST(test_HDR_init_with_subject);
return 1;
}
| 14,239 | 27.884381 | 80 | c |
openssl | openssl-master/test/cmp_msg_test.c | /*
* Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright Nokia 2007-2019
* Copyright Siemens AG 2015-2019
*
* 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 "helpers/cmp_testlib.h"
static const char *newkey_f;
static const char *server_cert_f;
static const char *pkcs10_f;
typedef struct test_fixture {
const char *test_case_name;
OSSL_CMP_CTX *cmp_ctx;
/* for msg create tests */
int bodytype;
int err_code;
/* for certConf */
int fail_info;
/* for protection tests */
OSSL_CMP_MSG *msg;
int expected;
/* for error and response messages */
OSSL_CMP_PKISI *si;
} CMP_MSG_TEST_FIXTURE;
static OSSL_LIB_CTX *libctx = NULL;
static OSSL_PROVIDER *default_null_provider = NULL, *provider = NULL;
static unsigned char ref[CMP_TEST_REFVALUE_LENGTH];
static void tear_down(CMP_MSG_TEST_FIXTURE *fixture)
{
OSSL_CMP_CTX_free(fixture->cmp_ctx);
OSSL_CMP_MSG_free(fixture->msg);
OSSL_CMP_PKISI_free(fixture->si);
OPENSSL_free(fixture);
}
#define SET_OPT_UNPROTECTED_SEND(ctx, val) \
OSSL_CMP_CTX_set_option((ctx), OSSL_CMP_OPT_UNPROTECTED_SEND, (val))
static CMP_MSG_TEST_FIXTURE *set_up(const char *const test_case_name)
{
CMP_MSG_TEST_FIXTURE *fixture;
if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture))))
return NULL;
fixture->test_case_name = test_case_name;
if (!TEST_ptr(fixture->cmp_ctx = OSSL_CMP_CTX_new(libctx, NULL))
|| !TEST_true(SET_OPT_UNPROTECTED_SEND(fixture->cmp_ctx, 1))
|| !TEST_true(OSSL_CMP_CTX_set1_referenceValue(fixture->cmp_ctx,
ref, sizeof(ref)))) {
tear_down(fixture);
return NULL;
}
return fixture;
}
static EVP_PKEY *newkey = NULL;
static X509 *cert = NULL;
#define EXECUTE_MSG_CREATION_TEST(expr) \
do { \
OSSL_CMP_MSG *msg = NULL; \
int good = fixture->expected != 0 ? \
TEST_ptr(msg = (expr)) && TEST_true(valid_asn1_encoding(msg)) : \
TEST_ptr_null(msg = (expr)); \
\
OSSL_CMP_MSG_free(msg); \
ERR_print_errors_fp(stderr); \
return good; \
} while (0)
/*-
* The following tests call a cmp message creation function.
* if fixture->expected != 0:
* returns 1 if the message is created and syntactically correct.
* if fixture->expected == 0
* returns 1 if message creation returns NULL
*/
static int execute_certreq_create_test(CMP_MSG_TEST_FIXTURE *fixture)
{
EXECUTE_MSG_CREATION_TEST(ossl_cmp_certreq_new(fixture->cmp_ctx,
fixture->bodytype,
NULL));
}
static int execute_errormsg_create_test(CMP_MSG_TEST_FIXTURE *fixture)
{
EXECUTE_MSG_CREATION_TEST(ossl_cmp_error_new(fixture->cmp_ctx, fixture->si,
fixture->err_code,
"details", 0));
}
static int execute_rr_create_test(CMP_MSG_TEST_FIXTURE *fixture)
{
EXECUTE_MSG_CREATION_TEST(ossl_cmp_rr_new(fixture->cmp_ctx));
}
static int execute_certconf_create_test(CMP_MSG_TEST_FIXTURE *fixture)
{
EXECUTE_MSG_CREATION_TEST(ossl_cmp_certConf_new
(fixture->cmp_ctx, OSSL_CMP_CERTREQID,
fixture->fail_info, NULL));
}
static int execute_genm_create_test(CMP_MSG_TEST_FIXTURE *fixture)
{
EXECUTE_MSG_CREATION_TEST(ossl_cmp_genm_new(fixture->cmp_ctx));
}
static int execute_pollreq_create_test(CMP_MSG_TEST_FIXTURE *fixture)
{
EXECUTE_MSG_CREATION_TEST(ossl_cmp_pollReq_new(fixture->cmp_ctx, 4711));
}
static int execute_pkimessage_create_test(CMP_MSG_TEST_FIXTURE *fixture)
{
EXECUTE_MSG_CREATION_TEST(ossl_cmp_msg_create
(fixture->cmp_ctx, fixture->bodytype));
}
static int set1_newPkey(OSSL_CMP_CTX *ctx, EVP_PKEY *pkey)
{
if (!EVP_PKEY_up_ref(pkey))
return 0;
if (!OSSL_CMP_CTX_set0_newPkey(ctx, 1, pkey)) {
EVP_PKEY_free(pkey);
return 0;
}
return 1;
}
static int test_cmp_create_ir_protection_set(void)
{
OSSL_CMP_CTX *ctx;
unsigned char secret[16];
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
ctx = fixture->cmp_ctx;
fixture->bodytype = OSSL_CMP_PKIBODY_IR;
fixture->err_code = -1;
fixture->expected = 1;
if (!TEST_int_eq(1, RAND_bytes_ex(libctx, secret, sizeof(secret), 0))
|| !TEST_true(SET_OPT_UNPROTECTED_SEND(ctx, 0))
|| !TEST_true(set1_newPkey(ctx, newkey))
|| !TEST_true(OSSL_CMP_CTX_set1_secretValue(ctx, secret,
sizeof(secret)))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_certreq_create_test, tear_down);
return result;
}
static int test_cmp_create_ir_protection_fails(void)
{
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
fixture->bodytype = OSSL_CMP_PKIBODY_IR;
fixture->err_code = -1;
fixture->expected = 0;
if (!TEST_true(OSSL_CMP_CTX_set1_pkey(fixture->cmp_ctx, newkey))
|| !TEST_true(SET_OPT_UNPROTECTED_SEND(fixture->cmp_ctx, 0))
/* newkey used by default for signing does not match cert: */
|| !TEST_true(OSSL_CMP_CTX_set1_cert(fixture->cmp_ctx, cert))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_certreq_create_test, tear_down);
return result;
}
static int test_cmp_create_cr_without_key(void)
{
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
fixture->bodytype = OSSL_CMP_PKIBODY_CR;
fixture->err_code = -1;
fixture->expected = 0;
EXECUTE_TEST(execute_certreq_create_test, tear_down);
return result;
}
static int test_cmp_create_cr(void)
{
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
fixture->bodytype = OSSL_CMP_PKIBODY_CR;
fixture->err_code = -1;
fixture->expected = 1;
if (!TEST_true(set1_newPkey(fixture->cmp_ctx, newkey))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_certreq_create_test, tear_down);
return result;
}
static int test_cmp_create_certreq_with_invalid_bodytype(void)
{
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
fixture->bodytype = OSSL_CMP_PKIBODY_RR;
fixture->err_code = -1;
fixture->expected = 0;
if (!TEST_true(set1_newPkey(fixture->cmp_ctx, newkey))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_certreq_create_test, tear_down);
return result;
}
static int test_cmp_create_p10cr(void)
{
OSSL_CMP_CTX *ctx;
X509_REQ *p10cr = NULL;
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
ctx = fixture->cmp_ctx;
fixture->bodytype = OSSL_CMP_PKIBODY_P10CR;
fixture->err_code = CMP_R_ERROR_CREATING_CERTREQ;
fixture->expected = 1;
if (!TEST_ptr(p10cr = load_csr_der(pkcs10_f, libctx))
|| !TEST_true(set1_newPkey(ctx, newkey))
|| !TEST_true(OSSL_CMP_CTX_set1_p10CSR(ctx, p10cr))) {
tear_down(fixture);
fixture = NULL;
}
X509_REQ_free(p10cr);
EXECUTE_TEST(execute_certreq_create_test, tear_down);
return result;
}
static int test_cmp_create_p10cr_null(void)
{
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
fixture->bodytype = OSSL_CMP_PKIBODY_P10CR;
fixture->err_code = CMP_R_ERROR_CREATING_CERTREQ;
fixture->expected = 0;
if (!TEST_true(set1_newPkey(fixture->cmp_ctx, newkey))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_certreq_create_test, tear_down);
return result;
}
static int test_cmp_create_kur(void)
{
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
fixture->bodytype = OSSL_CMP_PKIBODY_KUR;
fixture->err_code = -1;
fixture->expected = 1;
if (!TEST_true(set1_newPkey(fixture->cmp_ctx, newkey))
|| !TEST_true(OSSL_CMP_CTX_set1_oldCert(fixture->cmp_ctx, cert))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_certreq_create_test, tear_down);
return result;
}
static int test_cmp_create_kur_without_oldcert(void)
{
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
fixture->bodytype = OSSL_CMP_PKIBODY_KUR;
fixture->err_code = -1;
fixture->expected = 0;
if (!TEST_true(set1_newPkey(fixture->cmp_ctx, newkey))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_certreq_create_test, tear_down);
return result;
}
static int test_cmp_create_certconf(void)
{
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
fixture->fail_info = 0;
fixture->expected = 1;
if (!TEST_true(ossl_cmp_ctx_set0_newCert(fixture->cmp_ctx,
X509_dup(cert)))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_certconf_create_test, tear_down);
return result;
}
static int test_cmp_create_certconf_badAlg(void)
{
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
fixture->fail_info = 1 << OSSL_CMP_PKIFAILUREINFO_badAlg;
fixture->expected = 1;
if (!TEST_true(ossl_cmp_ctx_set0_newCert(fixture->cmp_ctx,
X509_dup(cert)))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_certconf_create_test, tear_down);
return result;
}
static int test_cmp_create_certconf_fail_info_max(void)
{
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
fixture->fail_info = 1 << OSSL_CMP_PKIFAILUREINFO_MAX;
fixture->expected = 1;
if (!TEST_true(ossl_cmp_ctx_set0_newCert(fixture->cmp_ctx,
X509_dup(cert)))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_certconf_create_test, tear_down);
return result;
}
static int test_cmp_create_error_msg(void)
{
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
fixture->si = OSSL_CMP_STATUSINFO_new(OSSL_CMP_PKISTATUS_rejection,
OSSL_CMP_PKIFAILUREINFO_systemFailure,
NULL);
fixture->err_code = -1;
fixture->expected = 1; /* expected: message creation is successful */
if (!TEST_true(set1_newPkey(fixture->cmp_ctx, newkey))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_errormsg_create_test, tear_down);
return result;
}
static int test_cmp_create_pollreq(void)
{
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_pollreq_create_test, tear_down);
return result;
}
static int test_cmp_create_rr(void)
{
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
fixture->expected = 1;
if (!TEST_true(OSSL_CMP_CTX_set1_oldCert(fixture->cmp_ctx, cert))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_rr_create_test, tear_down);
return result;
}
static int test_cmp_create_genm(void)
{
OSSL_CMP_ITAV *iv = NULL;
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
fixture->expected = 1;
iv = OSSL_CMP_ITAV_create(OBJ_nid2obj(NID_id_it_implicitConfirm), NULL);
if (!TEST_ptr(iv)
|| !TEST_true(OSSL_CMP_CTX_push0_genm_ITAV(fixture->cmp_ctx, iv))) {
OSSL_CMP_ITAV_free(iv);
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_genm_create_test, tear_down);
return result;
}
static int execute_certrep_create(CMP_MSG_TEST_FIXTURE *fixture)
{
OSSL_CMP_CTX *ctx = fixture->cmp_ctx;
OSSL_CMP_CERTREPMESSAGE *crepmsg = OSSL_CMP_CERTREPMESSAGE_new();
OSSL_CMP_CERTRESPONSE *read_cresp, *cresp = OSSL_CMP_CERTRESPONSE_new();
X509 *certfromresp = NULL;
int res = 0;
if (crepmsg == NULL || cresp == NULL)
goto err;
if (!ASN1_INTEGER_set(cresp->certReqId, 99))
goto err;
if ((cresp->certifiedKeyPair = OSSL_CMP_CERTIFIEDKEYPAIR_new()) == NULL)
goto err;
cresp->certifiedKeyPair->certOrEncCert->type =
OSSL_CMP_CERTORENCCERT_CERTIFICATE;
if ((cresp->certifiedKeyPair->certOrEncCert->value.certificate =
X509_dup(cert)) == NULL
|| !sk_OSSL_CMP_CERTRESPONSE_push(crepmsg->response, cresp))
goto err;
cresp = NULL;
read_cresp = ossl_cmp_certrepmessage_get0_certresponse(crepmsg, 99);
if (!TEST_ptr(read_cresp))
goto err;
if (!TEST_ptr_null(ossl_cmp_certrepmessage_get0_certresponse(crepmsg, 88)))
goto err;
certfromresp = ossl_cmp_certresponse_get1_cert(ctx, read_cresp);
if (certfromresp == NULL || !TEST_int_eq(X509_cmp(cert, certfromresp), 0))
goto err;
res = 1;
err:
X509_free(certfromresp);
OSSL_CMP_CERTRESPONSE_free(cresp);
OSSL_CMP_CERTREPMESSAGE_free(crepmsg);
return res;
}
static int test_cmp_create_certrep(void)
{
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
EXECUTE_TEST(execute_certrep_create, tear_down);
return result;
}
static int execute_rp_create(CMP_MSG_TEST_FIXTURE *fixture)
{
OSSL_CMP_PKISI *si = OSSL_CMP_STATUSINFO_new(33, 44, "a text");
X509_NAME *issuer = X509_NAME_new();
ASN1_INTEGER *serial = ASN1_INTEGER_new();
OSSL_CRMF_CERTID *cid = NULL;
OSSL_CMP_MSG *rpmsg = NULL;
int res = 0;
if (si == NULL || issuer == NULL || serial == NULL)
goto err;
if (!X509_NAME_add_entry_by_txt(issuer, "CN", MBSTRING_ASC,
(unsigned char *)"The Issuer", -1, -1, 0)
|| !ASN1_INTEGER_set(serial, 99)
|| (cid = OSSL_CRMF_CERTID_gen(issuer, serial)) == NULL
|| (rpmsg = ossl_cmp_rp_new(fixture->cmp_ctx, si, cid, 1)) == NULL)
goto err;
if (!TEST_ptr(ossl_cmp_revrepcontent_get_CertId(rpmsg->body->value.rp, 0)))
goto err;
if (!TEST_ptr(ossl_cmp_revrepcontent_get_pkisi(rpmsg->body->value.rp, 0)))
goto err;
res = 1;
err:
ASN1_INTEGER_free(serial);
X509_NAME_free(issuer);
OSSL_CRMF_CERTID_free(cid);
OSSL_CMP_PKISI_free(si);
OSSL_CMP_MSG_free(rpmsg);
return res;
}
static int test_cmp_create_rp(void)
{
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
EXECUTE_TEST(execute_rp_create, tear_down);
return result;
}
static int execute_pollrep_create(CMP_MSG_TEST_FIXTURE *fixture)
{
OSSL_CMP_MSG *pollrep;
int res = 0;
pollrep = ossl_cmp_pollRep_new(fixture->cmp_ctx, 77, 2000);
if (!TEST_ptr(pollrep))
return 0;
if (!TEST_ptr(ossl_cmp_pollrepcontent_get0_pollrep(pollrep->body->
value.pollRep, 77)))
goto err;
if (!TEST_ptr_null(ossl_cmp_pollrepcontent_get0_pollrep(pollrep->body->
value.pollRep, 88)))
goto err;
res = 1;
err:
OSSL_CMP_MSG_free(pollrep);
return res;
}
static int test_cmp_create_pollrep(void)
{
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
EXECUTE_TEST(execute_pollrep_create, tear_down);
return result;
}
static int test_cmp_pkimessage_create(int bodytype)
{
X509_REQ *p10cr = NULL;
SETUP_TEST_FIXTURE(CMP_MSG_TEST_FIXTURE, set_up);
switch (fixture->bodytype = bodytype) {
case OSSL_CMP_PKIBODY_P10CR:
fixture->expected = 1;
p10cr = load_csr_der(pkcs10_f, libctx);
if (!TEST_true(OSSL_CMP_CTX_set1_p10CSR(fixture->cmp_ctx, p10cr))) {
tear_down(fixture);
fixture = NULL;
}
X509_REQ_free(p10cr);
break;
case OSSL_CMP_PKIBODY_IR:
case OSSL_CMP_PKIBODY_IP:
case OSSL_CMP_PKIBODY_CR:
case OSSL_CMP_PKIBODY_CP:
case OSSL_CMP_PKIBODY_KUR:
case OSSL_CMP_PKIBODY_KUP:
case OSSL_CMP_PKIBODY_RR:
case OSSL_CMP_PKIBODY_RP:
case OSSL_CMP_PKIBODY_PKICONF:
case OSSL_CMP_PKIBODY_GENM:
case OSSL_CMP_PKIBODY_GENP:
case OSSL_CMP_PKIBODY_ERROR:
case OSSL_CMP_PKIBODY_CERTCONF:
case OSSL_CMP_PKIBODY_POLLREQ:
case OSSL_CMP_PKIBODY_POLLREP:
fixture->expected = 1;
break;
default:
fixture->expected = 0;
break;
}
EXECUTE_TEST(execute_pkimessage_create_test, tear_down);
return result;
}
void cleanup_tests(void)
{
EVP_PKEY_free(newkey);
X509_free(cert);
OSSL_PROVIDER_unload(default_null_provider);
OSSL_PROVIDER_unload(provider);
OSSL_LIB_CTX_free(libctx);
}
#define USAGE "new.key server.crt pkcs10.der module_name [module_conf_file]\n"
OPT_TEST_DECLARE_USAGE(USAGE)
int setup_tests(void)
{
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
if (!TEST_ptr(newkey_f = test_get_argument(0))
|| !TEST_ptr(server_cert_f = test_get_argument(1))
|| !TEST_ptr(pkcs10_f = test_get_argument(2))) {
TEST_error("usage: cmp_msg_test %s", USAGE);
return 0;
}
if (!test_arg_libctx(&libctx, &default_null_provider, &provider, 3, USAGE))
return 0;
if (!TEST_ptr(newkey = load_pkey_pem(newkey_f, libctx))
|| !TEST_ptr(cert = load_cert_pem(server_cert_f, libctx))
|| !TEST_int_eq(1, RAND_bytes_ex(libctx, ref, sizeof(ref), 0))) {
cleanup_tests();
return 0;
}
/* Message creation tests */
ADD_TEST(test_cmp_create_certreq_with_invalid_bodytype);
ADD_TEST(test_cmp_create_ir_protection_fails);
ADD_TEST(test_cmp_create_ir_protection_set);
ADD_TEST(test_cmp_create_error_msg);
ADD_TEST(test_cmp_create_certconf);
ADD_TEST(test_cmp_create_certconf_badAlg);
ADD_TEST(test_cmp_create_certconf_fail_info_max);
ADD_TEST(test_cmp_create_kur);
ADD_TEST(test_cmp_create_kur_without_oldcert);
ADD_TEST(test_cmp_create_cr);
ADD_TEST(test_cmp_create_cr_without_key);
ADD_TEST(test_cmp_create_p10cr);
ADD_TEST(test_cmp_create_p10cr_null);
ADD_TEST(test_cmp_create_pollreq);
ADD_TEST(test_cmp_create_rr);
ADD_TEST(test_cmp_create_rp);
ADD_TEST(test_cmp_create_genm);
ADD_TEST(test_cmp_create_certrep);
ADD_TEST(test_cmp_create_pollrep);
ADD_ALL_TESTS_NOSUBTEST(test_cmp_pkimessage_create,
OSSL_CMP_PKIBODY_POLLREP + 1);
return 1;
}
| 18,591 | 30.142379 | 80 | c |
openssl | openssl-master/test/cmp_protect_test.c | /*
* Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright Nokia 2007-2019
* Copyright Siemens AG 2015-2019
*
* 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 "helpers/cmp_testlib.h"
static const char *ir_protected_f;
static const char *ir_unprotected_f;
static const char *ip_PBM_f;
typedef struct test_fixture {
const char *test_case_name;
OSSL_CMP_CTX *cmp_ctx;
/* for protection tests */
OSSL_CMP_MSG *msg;
OSSL_CMP_PKISI *si; /* for error and response messages */
EVP_PKEY *pubkey;
unsigned char *mem;
int memlen;
X509 *cert;
STACK_OF(X509) *certs;
STACK_OF(X509) *chain;
int with_ss;
int callback_arg;
int expected;
} CMP_PROTECT_TEST_FIXTURE;
static OSSL_LIB_CTX *libctx = NULL;
static OSSL_PROVIDER *default_null_provider = NULL, *provider = NULL;
static void tear_down(CMP_PROTECT_TEST_FIXTURE *fixture)
{
OSSL_CMP_CTX_free(fixture->cmp_ctx);
OSSL_CMP_MSG_free(fixture->msg);
OSSL_CMP_PKISI_free(fixture->si);
OPENSSL_free(fixture->mem);
sk_X509_free(fixture->certs);
sk_X509_free(fixture->chain);
OPENSSL_free(fixture);
}
static CMP_PROTECT_TEST_FIXTURE *set_up(const char *const test_case_name)
{
CMP_PROTECT_TEST_FIXTURE *fixture;
if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture))))
return NULL;
fixture->test_case_name = test_case_name;
if (!TEST_ptr(fixture->cmp_ctx = OSSL_CMP_CTX_new(libctx, NULL))) {
tear_down(fixture);
return NULL;
}
return fixture;
}
static EVP_PKEY *loadedprivkey = NULL;
static EVP_PKEY *loadedpubkey = NULL;
static EVP_PKEY *loadedkey = NULL;
static X509 *cert = NULL;
static unsigned char rand_data[OSSL_CMP_TRANSACTIONID_LENGTH];
static OSSL_CMP_MSG *ir_unprotected, *ir_protected;
static X509 *endentity1 = NULL, *endentity2 = NULL,
*root = NULL, *intermediate = NULL;
static int execute_calc_protection_fails_test(CMP_PROTECT_TEST_FIXTURE *fixture)
{
ASN1_BIT_STRING *protection =
ossl_cmp_calc_protection(fixture->cmp_ctx, fixture->msg);
int res = TEST_ptr_null(protection);
ASN1_BIT_STRING_free(protection);
return res;
}
static int execute_calc_protection_pbmac_test(CMP_PROTECT_TEST_FIXTURE *fixture)
{
ASN1_BIT_STRING *protection =
ossl_cmp_calc_protection(fixture->cmp_ctx, fixture->msg);
int res = TEST_ptr(protection)
&& TEST_true(ASN1_STRING_cmp(protection,
fixture->msg->protection) == 0);
ASN1_BIT_STRING_free(protection);
return res;
}
/*
* This function works similarly to parts of CMP_verify_signature in cmp_vfy.c,
* but without the need for an OSSL_CMP_CTX or a X509 certificate
*/
static int verify_signature(OSSL_CMP_MSG *msg,
ASN1_BIT_STRING *protection,
EVP_PKEY *pkey, EVP_MD *digest)
{
OSSL_CMP_PROTECTEDPART prot_part;
unsigned char *prot_part_der = NULL;
int len;
EVP_MD_CTX *ctx = NULL;
int res;
prot_part.header = OSSL_CMP_MSG_get0_header(msg);
prot_part.body = msg->body;
len = i2d_OSSL_CMP_PROTECTEDPART(&prot_part, &prot_part_der);
res =
TEST_int_ge(len, 0)
&& TEST_ptr(ctx = EVP_MD_CTX_new())
&& TEST_true(EVP_DigestVerifyInit(ctx, NULL, digest, NULL, pkey))
&& TEST_int_eq(EVP_DigestVerify(ctx, protection->data,
protection->length,
prot_part_der, len), 1);
/* cleanup */
EVP_MD_CTX_free(ctx);
OPENSSL_free(prot_part_der);
return res;
}
/* Calls OSSL_CMP_calc_protection and compares and verifies signature */
static int execute_calc_protection_signature_test(CMP_PROTECT_TEST_FIXTURE *
fixture)
{
ASN1_BIT_STRING *protection =
ossl_cmp_calc_protection(fixture->cmp_ctx, fixture->msg);
int ret = (TEST_ptr(protection)
&& TEST_true(ASN1_STRING_cmp(protection,
fixture->msg->protection) == 0)
&& TEST_true(verify_signature(fixture->msg, protection,
fixture->pubkey,
fixture->cmp_ctx->digest)));
ASN1_BIT_STRING_free(protection);
return ret;
}
static int test_cmp_calc_protection_no_key_no_secret(void)
{
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
if (!TEST_ptr(fixture->msg = load_pkimsg(ir_unprotected_f, libctx))
|| !TEST_ptr(fixture->msg->header->protectionAlg =
X509_ALGOR_new() /* no specific alg needed here */)) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_calc_protection_fails_test, tear_down);
return result;
}
static int test_cmp_calc_protection_pkey(void)
{
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
fixture->pubkey = loadedpubkey;
if (!TEST_true(OSSL_CMP_CTX_set1_pkey(fixture->cmp_ctx, loadedprivkey))
|| !TEST_ptr(fixture->msg = load_pkimsg(ir_protected_f, libctx))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_calc_protection_signature_test, tear_down);
return result;
}
static int test_cmp_calc_protection_pbmac(void)
{
unsigned char sec_insta[] = { 'i', 'n', 's', 't', 'a' };
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
if (!TEST_true(OSSL_CMP_CTX_set1_secretValue(fixture->cmp_ctx,
sec_insta, sizeof(sec_insta)))
|| !TEST_ptr(fixture->msg = load_pkimsg(ip_PBM_f, libctx))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_calc_protection_pbmac_test, tear_down);
return result;
}
static int execute_MSG_protect_test(CMP_PROTECT_TEST_FIXTURE *fixture)
{
return TEST_int_eq(fixture->expected,
ossl_cmp_msg_protect(fixture->cmp_ctx, fixture->msg));
}
#define SET_OPT_UNPROTECTED_SEND(ctx, val) \
OSSL_CMP_CTX_set_option((ctx), OSSL_CMP_OPT_UNPROTECTED_SEND, (val))
static int test_MSG_protect_unprotected_request(void)
{
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
fixture->expected = 1;
if (!TEST_ptr(fixture->msg = OSSL_CMP_MSG_dup(ir_unprotected))
|| !TEST_true(SET_OPT_UNPROTECTED_SEND(fixture->cmp_ctx, 1))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_MSG_protect_test, tear_down);
return result;
}
static int test_MSG_protect_with_msg_sig_alg_protection_plus_rsa_key(void)
{
const size_t size = sizeof(rand_data) / 2;
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
fixture->expected = 1;
if (!TEST_ptr(fixture->msg = OSSL_CMP_MSG_dup(ir_unprotected))
|| !TEST_true(SET_OPT_UNPROTECTED_SEND(fixture->cmp_ctx, 0))
/*
* Use half of the 16 bytes of random input
* for each reference and secret value
*/
|| !TEST_true(OSSL_CMP_CTX_set1_referenceValue(fixture->cmp_ctx,
rand_data, size))
|| !TEST_true(OSSL_CMP_CTX_set1_secretValue(fixture->cmp_ctx,
rand_data + size,
size))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_MSG_protect_test, tear_down);
return result;
}
static int test_MSG_protect_with_certificate_and_key(void)
{
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
fixture->expected = 1;
if (!TEST_ptr(fixture->msg =
OSSL_CMP_MSG_dup(ir_unprotected))
|| !TEST_true(SET_OPT_UNPROTECTED_SEND(fixture->cmp_ctx, 0))
|| !TEST_true(OSSL_CMP_CTX_set1_pkey(fixture->cmp_ctx, loadedkey))
|| !TEST_true(OSSL_CMP_CTX_set1_cert(fixture->cmp_ctx, cert))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_MSG_protect_test, tear_down);
return result;
}
static int test_MSG_protect_certificate_based_without_cert(void)
{
OSSL_CMP_CTX *ctx;
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
ctx = fixture->cmp_ctx;
fixture->expected = 0;
if (!TEST_ptr(fixture->msg =
OSSL_CMP_MSG_dup(ir_unprotected))
|| !TEST_true(SET_OPT_UNPROTECTED_SEND(ctx, 0))
|| !TEST_true(OSSL_CMP_CTX_set0_newPkey(ctx, 1, loadedkey))) {
tear_down(fixture);
fixture = NULL;
}
EVP_PKEY_up_ref(loadedkey);
EXECUTE_TEST(execute_MSG_protect_test, tear_down);
return result;
}
static int test_MSG_protect_no_key_no_secret(void)
{
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
fixture->expected = 0;
if (!TEST_ptr(fixture->msg = OSSL_CMP_MSG_dup(ir_unprotected))
|| !TEST_true(SET_OPT_UNPROTECTED_SEND(fixture->cmp_ctx, 0))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_MSG_protect_test, tear_down);
return result;
}
static int test_MSG_protect_pbmac_no_sender(int with_ref)
{
static unsigned char secret[] = { 47, 11, 8, 15 };
static unsigned char ref[] = { 0xca, 0xfe, 0xba, 0xbe };
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
fixture->expected = with_ref;
if (!TEST_ptr(fixture->msg = OSSL_CMP_MSG_dup(ir_unprotected))
|| !SET_OPT_UNPROTECTED_SEND(fixture->cmp_ctx, 0)
|| !ossl_cmp_hdr_set1_sender(fixture->msg->header, NULL)
|| !OSSL_CMP_CTX_set1_secretValue(fixture->cmp_ctx,
secret, sizeof(secret))
|| (!OSSL_CMP_CTX_set1_referenceValue(fixture->cmp_ctx,
with_ref ? ref : NULL,
sizeof(ref)))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_MSG_protect_test, tear_down);
return result;
}
static int test_MSG_protect_pbmac_no_sender_with_ref(void)
{
return test_MSG_protect_pbmac_no_sender(1);
}
static int test_MSG_protect_pbmac_no_sender_no_ref(void)
{
return test_MSG_protect_pbmac_no_sender(0);
}
static int execute_MSG_add_extraCerts_test(CMP_PROTECT_TEST_FIXTURE *fixture)
{
return TEST_true(ossl_cmp_msg_add_extraCerts(fixture->cmp_ctx,
fixture->msg));
}
static int test_MSG_add_extraCerts(void)
{
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
if (!TEST_ptr(fixture->msg = OSSL_CMP_MSG_dup(ir_protected))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_MSG_add_extraCerts_test, tear_down);
return result;
}
#ifndef OPENSSL_NO_EC
/* The cert chain tests use EC certs so we skip them in no-ec builds */
static int execute_cmp_build_cert_chain_test(CMP_PROTECT_TEST_FIXTURE *fixture)
{
int ret = 0;
OSSL_CMP_CTX *ctx = fixture->cmp_ctx;
X509_STORE *store;
STACK_OF(X509) *chain =
X509_build_chain(fixture->cert, fixture->certs, NULL,
fixture->with_ss, ctx->libctx, ctx->propq);
if (TEST_ptr(chain)) {
/* Check whether chain built is equal to the expected one */
ret = TEST_int_eq(0, STACK_OF_X509_cmp(chain, fixture->chain));
OSSL_STACK_OF_X509_free(chain);
}
if (!ret)
return 0;
if (TEST_ptr(store = X509_STORE_new())
&& TEST_true(X509_STORE_add_cert(store, root))) {
X509_VERIFY_PARAM_set_flags(X509_STORE_get0_param(store),
X509_V_FLAG_NO_CHECK_TIME);
chain = X509_build_chain(fixture->cert, fixture->certs, store,
fixture->with_ss, ctx->libctx, ctx->propq);
ret = TEST_int_eq(fixture->expected, chain != NULL);
if (ret && chain != NULL) {
/* Check whether chain built is equal to the expected one */
ret = TEST_int_eq(0, STACK_OF_X509_cmp(chain, fixture->chain));
OSSL_STACK_OF_X509_free(chain);
}
}
X509_STORE_free(store);
return ret;
}
static int test_cmp_build_cert_chain(void)
{
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
fixture->expected = 1;
fixture->with_ss = 0;
fixture->cert = endentity2;
if (!TEST_ptr(fixture->certs = sk_X509_new_null())
|| !TEST_ptr(fixture->chain = sk_X509_new_null())
|| !TEST_true(sk_X509_push(fixture->certs, endentity1))
|| !TEST_true(sk_X509_push(fixture->certs, root))
|| !TEST_true(sk_X509_push(fixture->certs, intermediate))
|| !TEST_true(sk_X509_push(fixture->chain, endentity2))
|| !TEST_true(sk_X509_push(fixture->chain, intermediate))) {
tear_down(fixture);
fixture = NULL;
}
if (fixture != NULL) {
result = execute_cmp_build_cert_chain_test(fixture);
fixture->with_ss = 1;
if (result && TEST_true(sk_X509_push(fixture->chain, root)))
result = execute_cmp_build_cert_chain_test(fixture);
}
tear_down(fixture);
return result;
}
static int test_cmp_build_cert_chain_missing_intermediate(void)
{
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
fixture->expected = 0;
fixture->with_ss = 0;
fixture->cert = endentity2;
if (!TEST_ptr(fixture->certs = sk_X509_new_null())
|| !TEST_ptr(fixture->chain = sk_X509_new_null())
|| !TEST_true(sk_X509_push(fixture->certs, endentity1))
|| !TEST_true(sk_X509_push(fixture->certs, root))
|| !TEST_true(sk_X509_push(fixture->chain, endentity2))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_cmp_build_cert_chain_test, tear_down);
return result;
}
static int test_cmp_build_cert_chain_no_root(void)
{
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
fixture->expected = 1;
fixture->with_ss = 0;
fixture->cert = endentity2;
if (!TEST_ptr(fixture->certs = sk_X509_new_null())
|| !TEST_ptr(fixture->chain = sk_X509_new_null())
|| !TEST_true(sk_X509_push(fixture->certs, endentity1))
|| !TEST_true(sk_X509_push(fixture->certs, intermediate))
|| !TEST_true(sk_X509_push(fixture->chain, endentity2))
|| !TEST_true(sk_X509_push(fixture->chain, intermediate))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_cmp_build_cert_chain_test, tear_down);
return result;
}
static int test_cmp_build_cert_chain_only_root(void)
{
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
fixture->expected = 1;
fixture->with_ss = 0; /* still chain must include the only cert (root) */
fixture->cert = root;
if (!TEST_ptr(fixture->certs = sk_X509_new_null())
|| !TEST_ptr(fixture->chain = sk_X509_new_null())
|| !TEST_true(sk_X509_push(fixture->certs, root))
|| !TEST_true(sk_X509_push(fixture->chain, root))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_cmp_build_cert_chain_test, tear_down);
return result;
}
static int test_cmp_build_cert_chain_no_certs(void)
{
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
fixture->expected = 0;
fixture->with_ss = 0;
fixture->cert = endentity2;
if (!TEST_ptr(fixture->certs = sk_X509_new_null())
|| !TEST_ptr(fixture->chain = sk_X509_new_null())
|| !TEST_true(sk_X509_push(fixture->chain, endentity2))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_cmp_build_cert_chain_test, tear_down);
return result;
}
#endif /* OPENSSL_NO_EC */
static int execute_X509_STORE_test(CMP_PROTECT_TEST_FIXTURE *fixture)
{
X509_STORE *store = X509_STORE_new();
STACK_OF(X509) *sk = NULL;
int res = 0;
if (!TEST_true(ossl_cmp_X509_STORE_add1_certs(store,
fixture->certs,
fixture->callback_arg)))
goto err;
sk = X509_STORE_get1_all_certs(store);
if (!TEST_int_eq(0, STACK_OF_X509_cmp(sk, fixture->chain)))
goto err;
res = 1;
err:
X509_STORE_free(store);
OSSL_STACK_OF_X509_free(sk);
return res;
}
static int test_X509_STORE(void)
{
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
fixture->callback_arg = 0; /* self-issued allowed */
if (!TEST_ptr(fixture->certs = sk_X509_new_null())
|| !sk_X509_push(fixture->certs, endentity1)
|| !sk_X509_push(fixture->certs, endentity2)
|| !sk_X509_push(fixture->certs, root)
|| !sk_X509_push(fixture->certs, intermediate)
|| !TEST_ptr(fixture->chain = sk_X509_dup(fixture->certs))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_X509_STORE_test, tear_down);
return result;
}
static int test_X509_STORE_only_self_issued(void)
{
SETUP_TEST_FIXTURE(CMP_PROTECT_TEST_FIXTURE, set_up);
fixture->certs = sk_X509_new_null();
fixture->chain = sk_X509_new_null();
fixture->callback_arg = 1; /* only self-issued */
if (!TEST_true(sk_X509_push(fixture->certs, endentity1))
|| !TEST_true(sk_X509_push(fixture->certs, endentity2))
|| !TEST_true(sk_X509_push(fixture->certs, root))
|| !TEST_true(sk_X509_push(fixture->certs, intermediate))
|| !TEST_true(sk_X509_push(fixture->chain, root))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_X509_STORE_test, tear_down);
return result;
}
void cleanup_tests(void)
{
EVP_PKEY_free(loadedprivkey);
EVP_PKEY_free(loadedpubkey);
EVP_PKEY_free(loadedkey);
X509_free(cert);
X509_free(endentity1);
X509_free(endentity2);
X509_free(root);
X509_free(intermediate);
OSSL_CMP_MSG_free(ir_protected);
OSSL_CMP_MSG_free(ir_unprotected);
OSSL_PROVIDER_unload(default_null_provider);
OSSL_PROVIDER_unload(provider);
OSSL_LIB_CTX_free(libctx);
}
#define USAGE "server.pem IR_protected.der IR_unprotected.der IP_PBM.der " \
"server.crt server.pem EndEntity1.crt EndEntity2.crt Root_CA.crt " \
"Intermediate_CA.crt module_name [module_conf_file]\n"
OPT_TEST_DECLARE_USAGE(USAGE)
int setup_tests(void)
{
char *server_f;
char *server_key_f;
char *server_cert_f;
char *endentity1_f;
char *endentity2_f;
char *root_f;
char *intermediate_f;
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
RAND_bytes(rand_data, OSSL_CMP_TRANSACTIONID_LENGTH);
if (!TEST_ptr(server_f = test_get_argument(0))
|| !TEST_ptr(ir_protected_f = test_get_argument(1))
|| !TEST_ptr(ir_unprotected_f = test_get_argument(2))
|| !TEST_ptr(ip_PBM_f = test_get_argument(3))
|| !TEST_ptr(server_cert_f = test_get_argument(4))
|| !TEST_ptr(server_key_f = test_get_argument(5))
|| !TEST_ptr(endentity1_f = test_get_argument(6))
|| !TEST_ptr(endentity2_f = test_get_argument(7))
|| !TEST_ptr(root_f = test_get_argument(8))
|| !TEST_ptr(intermediate_f = test_get_argument(9))) {
TEST_error("usage: cmp_protect_test %s", USAGE);
return 0;
}
if (!test_arg_libctx(&libctx, &default_null_provider, &provider, 10, USAGE))
return 0;
if (!TEST_ptr(loadedkey = load_pkey_pem(server_key_f, libctx))
|| !TEST_ptr(cert = load_cert_pem(server_cert_f, libctx)))
return 0;
if (!TEST_ptr(loadedprivkey = load_pkey_pem(server_f, libctx)))
return 0;
if (TEST_true(EVP_PKEY_up_ref(loadedprivkey)))
loadedpubkey = loadedprivkey;
if (!TEST_ptr(ir_protected = load_pkimsg(ir_protected_f, libctx))
|| !TEST_ptr(ir_unprotected = load_pkimsg(ir_unprotected_f, libctx)))
return 0;
if (!TEST_ptr(endentity1 = load_cert_pem(endentity1_f, libctx))
|| !TEST_ptr(endentity2 = load_cert_pem(endentity2_f, libctx))
|| !TEST_ptr(root = load_cert_pem(root_f, libctx))
|| !TEST_ptr(intermediate = load_cert_pem(intermediate_f, libctx)))
return 0;
if (!TEST_int_eq(1, RAND_bytes(rand_data, OSSL_CMP_TRANSACTIONID_LENGTH)))
return 0;
/* Message protection tests */
ADD_TEST(test_cmp_calc_protection_no_key_no_secret);
ADD_TEST(test_cmp_calc_protection_pkey);
ADD_TEST(test_cmp_calc_protection_pbmac);
ADD_TEST(test_MSG_protect_with_msg_sig_alg_protection_plus_rsa_key);
ADD_TEST(test_MSG_protect_with_certificate_and_key);
ADD_TEST(test_MSG_protect_certificate_based_without_cert);
ADD_TEST(test_MSG_protect_unprotected_request);
ADD_TEST(test_MSG_protect_no_key_no_secret);
ADD_TEST(test_MSG_protect_pbmac_no_sender_with_ref);
ADD_TEST(test_MSG_protect_pbmac_no_sender_no_ref);
ADD_TEST(test_MSG_add_extraCerts);
#ifndef OPENSSL_NO_EC
ADD_TEST(test_cmp_build_cert_chain);
ADD_TEST(test_cmp_build_cert_chain_only_root);
ADD_TEST(test_cmp_build_cert_chain_no_root);
ADD_TEST(test_cmp_build_cert_chain_missing_intermediate);
ADD_TEST(test_cmp_build_cert_chain_no_certs);
#endif
ADD_TEST(test_X509_STORE);
ADD_TEST(test_X509_STORE_only_self_issued);
return 1;
}
| 21,790 | 34.203554 | 80 | c |
openssl | openssl-master/test/cmp_server_test.c | /*
* Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright Nokia 2007-2020
* Copyright Siemens AG 2015-2020
*
* 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 "helpers/cmp_testlib.h"
typedef struct test_fixture {
const char *test_case_name;
int expected;
OSSL_CMP_SRV_CTX *srv_ctx;
OSSL_CMP_MSG *req;
} CMP_SRV_TEST_FIXTURE;
static OSSL_LIB_CTX *libctx = NULL;
static OSSL_PROVIDER *default_null_provider = NULL, *provider = NULL;
static OSSL_CMP_MSG *request = NULL;
static void tear_down(CMP_SRV_TEST_FIXTURE *fixture)
{
OSSL_CMP_SRV_CTX_free(fixture->srv_ctx);
OPENSSL_free(fixture);
}
static CMP_SRV_TEST_FIXTURE *set_up(const char *const test_case_name)
{
CMP_SRV_TEST_FIXTURE *fixture;
if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture))))
return NULL;
fixture->test_case_name = test_case_name;
if (!TEST_ptr(fixture->srv_ctx = OSSL_CMP_SRV_CTX_new(libctx, NULL)))
goto err;
return fixture;
err:
tear_down(fixture);
return NULL;
}
static int dummy_errorCode = CMP_R_MULTIPLE_SAN_SOURCES; /* any reason code */
static OSSL_CMP_PKISI *process_cert_request(OSSL_CMP_SRV_CTX *srv_ctx,
const OSSL_CMP_MSG *cert_req,
int certReqId,
const OSSL_CRMF_MSG *crm,
const X509_REQ *p10cr,
X509 **certOut,
STACK_OF(X509) **chainOut,
STACK_OF(X509) **caPubs)
{
ERR_raise(ERR_LIB_CMP, dummy_errorCode);
return NULL;
}
static int execute_test_handle_request(CMP_SRV_TEST_FIXTURE *fixture)
{
OSSL_CMP_SRV_CTX *ctx = fixture->srv_ctx;
OSSL_CMP_CTX *client_ctx;
OSSL_CMP_CTX *cmp_ctx;
char *dummy_custom_ctx = "@test_dummy", *custom_ctx;
OSSL_CMP_MSG *rsp = NULL;
OSSL_CMP_ERRORMSGCONTENT *errorContent;
int res = 0;
if (!TEST_ptr(client_ctx = OSSL_CMP_CTX_new(libctx, NULL))
|| !TEST_true(OSSL_CMP_CTX_set_transfer_cb_arg(client_ctx, ctx)))
goto end;
if (!TEST_true(OSSL_CMP_SRV_CTX_init(ctx, dummy_custom_ctx,
process_cert_request, NULL, NULL,
NULL, NULL, NULL))
|| !TEST_ptr(custom_ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(ctx))
|| !TEST_int_eq(strcmp(custom_ctx, dummy_custom_ctx), 0))
goto end;
if (!TEST_true(OSSL_CMP_SRV_CTX_set_send_unprotected_errors(ctx, 0))
|| !TEST_true(OSSL_CMP_SRV_CTX_set_accept_unprotected(ctx, 0))
|| !TEST_true(OSSL_CMP_SRV_CTX_set_accept_raverified(ctx, 1))
|| !TEST_true(OSSL_CMP_SRV_CTX_set_grant_implicit_confirm(ctx, 1)))
goto end;
if (!TEST_ptr(cmp_ctx = OSSL_CMP_SRV_CTX_get0_cmp_ctx(ctx))
|| !OSSL_CMP_CTX_set1_referenceValue(cmp_ctx,
(unsigned char *)"server", 6)
|| !OSSL_CMP_CTX_set1_secretValue(cmp_ctx,
(unsigned char *)"1234", 4))
goto end;
if (!TEST_ptr(rsp = OSSL_CMP_CTX_server_perform(client_ctx, fixture->req))
|| !TEST_int_eq(OSSL_CMP_MSG_get_bodytype(rsp),
OSSL_CMP_PKIBODY_ERROR)
|| !TEST_ptr(errorContent = rsp->body->value.error)
|| !TEST_int_eq(ASN1_INTEGER_get(errorContent->errorCode),
ERR_PACK(ERR_LIB_CMP, 0, dummy_errorCode)))
goto end;
res = 1;
end:
OSSL_CMP_MSG_free(rsp);
OSSL_CMP_CTX_free(client_ctx);
return res;
}
static int test_handle_request(void)
{
SETUP_TEST_FIXTURE(CMP_SRV_TEST_FIXTURE, set_up);
fixture->req = request;
fixture->expected = 1;
EXECUTE_TEST(execute_test_handle_request, tear_down);
return result;
}
void cleanup_tests(void)
{
OSSL_CMP_MSG_free(request);
OSSL_PROVIDER_unload(default_null_provider);
OSSL_PROVIDER_unload(provider);
OSSL_LIB_CTX_free(libctx);
return;
}
#define USAGE \
"CR_protected_PBM_1234.der module_name [module_conf_file]\n"
OPT_TEST_DECLARE_USAGE(USAGE)
int setup_tests(void)
{
const char *request_f;
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
if (!TEST_ptr(request_f = test_get_argument(0))) {
TEST_error("usage: cmp_server_test %s", USAGE);
return 0;
}
if (!test_arg_libctx(&libctx, &default_null_provider, &provider, 1, USAGE))
return 0;
if (!TEST_ptr(request = load_pkimsg(request_f, libctx))) {
cleanup_tests();
return 0;
}
/*
* this (indirectly) calls
* OSSL_CMP_SRV_CTX_new(),
* OSSL_CMP_SRV_CTX_free(),
* OSSL_CMP_CTX_server_perform(),
* OSSL_CMP_SRV_process_request(),
* OSSL_CMP_SRV_CTX_init(),
* OSSL_CMP_SRV_CTX_get0_cmp_ctx(),
* OSSL_CMP_SRV_CTX_get0_custom_ctx(),
* OSSL_CMP_SRV_CTX_set_send_unprotected_errors(),
* OSSL_CMP_SRV_CTX_set_accept_unprotected(),
* OSSL_CMP_SRV_CTX_set_accept_raverified(), and
* OSSL_CMP_SRV_CTX_set_grant_implicit_confirm()
*/
ADD_TEST(test_handle_request);
return 1;
}
| 5,596 | 31.352601 | 79 | c |
openssl | openssl-master/test/cmp_status_test.c | /*
* Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright Nokia 2007-2019
* Copyright Siemens AG 2015-2019
*
* 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 "helpers/cmp_testlib.h"
typedef struct test_fixture {
const char *test_case_name;
int pkistatus;
const char *str; /* Not freed by tear_down */
const char *text; /* Not freed by tear_down */
int pkifailure;
} CMP_STATUS_TEST_FIXTURE;
static CMP_STATUS_TEST_FIXTURE *set_up(const char *const test_case_name)
{
CMP_STATUS_TEST_FIXTURE *fixture;
if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture))))
return NULL;
fixture->test_case_name = test_case_name;
return fixture;
}
static void tear_down(CMP_STATUS_TEST_FIXTURE *fixture)
{
OPENSSL_free(fixture);
}
/*
* Tests PKIStatusInfo creation and get-functions
*/
static int execute_PKISI_test(CMP_STATUS_TEST_FIXTURE *fixture)
{
OSSL_CMP_PKISI *si = NULL;
int status;
ASN1_UTF8STRING *statusString = NULL;
int res = 0, i;
if (!TEST_ptr(si = OSSL_CMP_STATUSINFO_new(fixture->pkistatus,
fixture->pkifailure,
fixture->text)))
goto end;
status = ossl_cmp_pkisi_get_status(si);
if (!TEST_int_eq(fixture->pkistatus, status)
|| !TEST_str_eq(fixture->str, ossl_cmp_PKIStatus_to_string(status)))
goto end;
if (!TEST_ptr(statusString =
sk_ASN1_UTF8STRING_value(ossl_cmp_pkisi_get0_statusString(si),
0))
|| !TEST_mem_eq(fixture->text, strlen(fixture->text),
(char *)statusString->data, statusString->length))
goto end;
if (!TEST_int_eq(fixture->pkifailure,
ossl_cmp_pkisi_get_pkifailureinfo(si)))
goto end;
for (i = 0; i <= OSSL_CMP_PKIFAILUREINFO_MAX; i++)
if (!TEST_int_eq((fixture->pkifailure >> i) & 1,
ossl_cmp_pkisi_check_pkifailureinfo(si, i)))
goto end;
res = 1;
end:
OSSL_CMP_PKISI_free(si);
return res;
}
static int test_PKISI(void)
{
SETUP_TEST_FIXTURE(CMP_STATUS_TEST_FIXTURE, set_up);
fixture->pkistatus = OSSL_CMP_PKISTATUS_revocationNotification;
fixture->str = "PKIStatus: revocation notification - a revocation of the cert has occurred";
fixture->text = "this is an additional text describing the failure";
fixture->pkifailure = OSSL_CMP_CTX_FAILINFO_unsupportedVersion |
OSSL_CMP_CTX_FAILINFO_badDataFormat;
EXECUTE_TEST(execute_PKISI_test, tear_down);
return result;
}
void cleanup_tests(void)
{
return;
}
int setup_tests(void)
{
/*-
* this tests all of:
* OSSL_CMP_STATUSINFO_new()
* ossl_cmp_pkisi_get_status()
* ossl_cmp_PKIStatus_to_string()
* ossl_cmp_pkisi_get0_statusString()
* ossl_cmp_pkisi_get_pkifailureinfo()
* ossl_cmp_pkisi_check_pkifailureinfo()
*/
ADD_TEST(test_PKISI);
return 1;
}
| 3,279 | 28.818182 | 96 | c |
openssl | openssl-master/test/cmp_vfy_test.c | /*
* Copyright 2007-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright Nokia 2007-2019
* Copyright Siemens AG 2015-2019
*
* 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 "helpers/cmp_testlib.h"
#include "../crypto/crmf/crmf_local.h" /* for manipulating POPO signature */
static const char *server_f;
static const char *client_f;
static const char *endentity1_f;
static const char *endentity2_f;
static const char *root_f;
static const char *intermediate_f;
static const char *ir_protected_f;
static const char *ir_unprotected_f;
static const char *ir_rmprotection_f;
static const char *ip_waiting_f;
static const char *instacert_f;
static const char *instaca_f;
static const char *ir_protected_0_extracerts;
static const char *ir_protected_2_extracerts;
typedef struct test_fixture {
const char *test_case_name;
int expected;
OSSL_CMP_CTX *cmp_ctx;
OSSL_CMP_MSG *msg;
X509 *cert;
ossl_cmp_allow_unprotected_cb_t allow_unprotected_cb;
int additional_arg;
} CMP_VFY_TEST_FIXTURE;
static OSSL_LIB_CTX *libctx = NULL;
static OSSL_PROVIDER *default_null_provider = NULL, *provider = NULL;
static void tear_down(CMP_VFY_TEST_FIXTURE *fixture)
{
OSSL_CMP_MSG_free(fixture->msg);
OSSL_CMP_CTX_free(fixture->cmp_ctx);
OPENSSL_free(fixture);
}
static time_t test_time_valid = 0, test_time_after_expiration = 0;
static CMP_VFY_TEST_FIXTURE *set_up(const char *const test_case_name)
{
X509_STORE *ts;
CMP_VFY_TEST_FIXTURE *fixture;
if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture))))
return NULL;
ts = X509_STORE_new();
fixture->test_case_name = test_case_name;
if (ts == NULL
|| !TEST_ptr(fixture->cmp_ctx = OSSL_CMP_CTX_new(libctx, NULL))
|| !OSSL_CMP_CTX_set0_trusted(fixture->cmp_ctx, ts)
|| !OSSL_CMP_CTX_set_log_cb(fixture->cmp_ctx, print_to_bio_out)) {
tear_down(fixture);
X509_STORE_free(ts);
return NULL;
}
X509_VERIFY_PARAM_set_time(X509_STORE_get0_param(ts), test_time_valid);
X509_STORE_set_verify_cb(ts, X509_STORE_CTX_print_verify_cb);
return fixture;
}
static X509 *srvcert = NULL;
static X509 *clcert = NULL;
/* chain */
static X509 *endentity1 = NULL, *endentity2 = NULL,
*intermediate = NULL, *root = NULL;
/* INSTA chain */
static X509 *insta_cert = NULL, *instaca_cert = NULL;
static unsigned char rand_data[OSSL_CMP_TRANSACTIONID_LENGTH];
static OSSL_CMP_MSG *ir_unprotected, *ir_rmprotection;
/* secret value used for IP_waitingStatus_PBM.der */
static const unsigned char sec_1[] = {
'9', 'p', 'p', '8', '-', 'b', '3', '5', 'i', '-', 'X', 'd', '3',
'Q', '-', 'u', 'd', 'N', 'R'
};
static int flip_bit(ASN1_BIT_STRING *bitstr)
{
int bit_num = 7;
int bit = ASN1_BIT_STRING_get_bit(bitstr, bit_num);
return ASN1_BIT_STRING_set_bit(bitstr, bit_num, !bit);
}
static int execute_verify_popo_test(CMP_VFY_TEST_FIXTURE *fixture)
{
if ((fixture->msg = load_pkimsg(ir_protected_f, libctx)) == NULL)
return 0;
if (fixture->expected == 0) {
const OSSL_CRMF_MSGS *reqs = fixture->msg->body->value.ir;
const OSSL_CRMF_MSG *req = sk_OSSL_CRMF_MSG_value(reqs, 0);
if (req == NULL || !flip_bit(req->popo->value.signature->signature))
return 0;
}
return TEST_int_eq(fixture->expected,
ossl_cmp_verify_popo(fixture->cmp_ctx, fixture->msg,
fixture->additional_arg));
}
static int test_verify_popo(void)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
fixture->expected = 1;
EXECUTE_TEST(execute_verify_popo_test, tear_down);
return result;
}
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
static int test_verify_popo_bad(void)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
fixture->expected = 0;
EXECUTE_TEST(execute_verify_popo_test, tear_down);
return result;
}
#endif
/* indirectly checks also OSSL_CMP_validate_msg() */
static int execute_validate_msg_test(CMP_VFY_TEST_FIXTURE *fixture)
{
int res = TEST_int_eq(fixture->expected,
ossl_cmp_msg_check_update(fixture->cmp_ctx,
fixture->msg, NULL, 0));
X509 *validated = OSSL_CMP_CTX_get0_validatedSrvCert(fixture->cmp_ctx);
return res && (!fixture->expected || TEST_ptr_eq(validated, fixture->cert));
}
static int execute_validate_cert_path_test(CMP_VFY_TEST_FIXTURE *fixture)
{
X509_STORE *ts = OSSL_CMP_CTX_get0_trusted(fixture->cmp_ctx);
int res = TEST_int_eq(fixture->expected,
OSSL_CMP_validate_cert_path(fixture->cmp_ctx,
ts, fixture->cert));
OSSL_CMP_CTX_print_errors(fixture->cmp_ctx);
return res;
}
static int test_validate_msg_mac_alg_protection(int miss, int wrong)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
fixture->cert = NULL;
fixture->expected = !miss && !wrong;
if (!TEST_true(miss ? OSSL_CMP_CTX_set0_trusted(fixture->cmp_ctx, NULL)
: OSSL_CMP_CTX_set1_secretValue(fixture->cmp_ctx, sec_1,
wrong ? 4 : sizeof(sec_1)))
|| !TEST_ptr(fixture->msg = load_pkimsg(ip_waiting_f, libctx))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_validate_msg_test, tear_down);
return result;
}
static int test_validate_msg_mac_alg_protection_ok(void)
{
return test_validate_msg_mac_alg_protection(0, 0);
}
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
static int test_validate_msg_mac_alg_protection_missing(void)
{
return test_validate_msg_mac_alg_protection(1, 0);
}
static int test_validate_msg_mac_alg_protection_wrong(void)
{
return test_validate_msg_mac_alg_protection(0, 1);
}
static int test_validate_msg_mac_alg_protection_bad(void)
{
const unsigned char sec_bad[] = {
'9', 'p', 'p', '8', '-', 'b', '3', '5', 'i', '-', 'X', 'd', '3',
'Q', '-', 'u', 'd', 'N', 'r'
};
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
fixture->cert = NULL;
fixture->expected = 0;
if (!TEST_true(OSSL_CMP_CTX_set1_secretValue(fixture->cmp_ctx, sec_bad,
sizeof(sec_bad)))
|| !TEST_ptr(fixture->msg = load_pkimsg(ip_waiting_f, libctx))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_validate_msg_test, tear_down);
return result;
}
#endif
static int add_trusted(OSSL_CMP_CTX *ctx, X509 *cert)
{
return X509_STORE_add_cert(OSSL_CMP_CTX_get0_trusted(ctx), cert);
}
static int add_untrusted(OSSL_CMP_CTX *ctx, X509 *cert)
{
return X509_add_cert(OSSL_CMP_CTX_get0_untrusted(ctx), cert,
X509_ADD_FLAG_UP_REF);
}
static int test_validate_msg_signature_partial_chain(int expired)
{
X509_STORE *ts;
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
fixture->cert = srvcert;
ts = OSSL_CMP_CTX_get0_trusted(fixture->cmp_ctx);
fixture->expected = !expired;
if (ts == NULL
|| !TEST_ptr(fixture->msg = load_pkimsg(ir_protected_f, libctx))
|| !add_trusted(fixture->cmp_ctx, srvcert)) {
tear_down(fixture);
fixture = NULL;
} else {
X509_VERIFY_PARAM *vpm = X509_STORE_get0_param(ts);
X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_PARTIAL_CHAIN);
if (expired)
X509_VERIFY_PARAM_set_time(vpm, test_time_after_expiration);
}
EXECUTE_TEST(execute_validate_msg_test, tear_down);
return result;
}
static int test_validate_msg_signature_trusted_ok(void)
{
return test_validate_msg_signature_partial_chain(0);
}
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
static int test_validate_msg_signature_trusted_expired(void)
{
return test_validate_msg_signature_partial_chain(1);
}
#endif
static int test_validate_msg_signature_srvcert(int bad_sig, int miss, int wrong)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
fixture->cert = srvcert;
fixture->expected = !bad_sig && !wrong && !miss;
if (!TEST_ptr(fixture->msg = load_pkimsg(ir_protected_f, libctx))
|| !TEST_true(miss ? OSSL_CMP_CTX_set1_secretValue(fixture->cmp_ctx,
sec_1, sizeof(sec_1))
: OSSL_CMP_CTX_set1_srvCert(fixture->cmp_ctx,
wrong? clcert : srvcert))
|| (bad_sig && !flip_bit(fixture->msg->protection))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_validate_msg_test, tear_down);
return result;
}
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
static int test_validate_msg_signature_srvcert_missing(void)
{
return test_validate_msg_signature_srvcert(0, 1, 0);
}
#endif
static int test_validate_msg_signature_srvcert_wrong(void)
{
return test_validate_msg_signature_srvcert(0, 0, 1);
}
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
static int test_validate_msg_signature_bad(void)
{
return test_validate_msg_signature_srvcert(1, 0, 0);
}
#endif
static int test_validate_msg_signature_sender_cert_srvcert(void)
{
return test_validate_msg_signature_srvcert(0, 0, 0);
}
static int test_validate_msg_signature_sender_cert_untrusted(void)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
fixture->cert = insta_cert;
fixture->expected = 1;
if (!TEST_ptr(fixture->msg = load_pkimsg(ir_protected_0_extracerts, libctx))
|| !add_trusted(fixture->cmp_ctx, instaca_cert)
|| !add_untrusted(fixture->cmp_ctx, insta_cert)) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_validate_msg_test, tear_down);
return result;
}
static int test_validate_msg_signature_sender_cert_trusted(void)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
fixture->cert = insta_cert;
fixture->expected = 1;
if (!TEST_ptr(fixture->msg = load_pkimsg(ir_protected_0_extracerts, libctx))
|| !add_trusted(fixture->cmp_ctx, instaca_cert)
|| !add_trusted(fixture->cmp_ctx, insta_cert)) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_validate_msg_test, tear_down);
return result;
}
static int test_validate_msg_signature_sender_cert_extracert(void)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
fixture->expected = 1;
if (!TEST_ptr(fixture->msg = load_pkimsg(ir_protected_2_extracerts, libctx))
|| !add_trusted(fixture->cmp_ctx, instaca_cert)) {
tear_down(fixture);
fixture = NULL;
}
fixture->cert = sk_X509_value(fixture->msg->extraCerts, 1); /* Insta CA */
EXECUTE_TEST(execute_validate_msg_test, tear_down);
return result;
}
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
static int test_validate_msg_signature_sender_cert_absent(void)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
fixture->expected = 0;
if (!TEST_ptr(fixture->msg =
load_pkimsg(ir_protected_0_extracerts, libctx))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_validate_msg_test, tear_down);
return result;
}
#endif
static int test_validate_with_sender(const X509_NAME *name, int expected)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
fixture->cert = srvcert;
fixture->expected = expected;
if (!TEST_ptr(fixture->msg = load_pkimsg(ir_protected_f, libctx))
|| !TEST_true(OSSL_CMP_CTX_set1_expected_sender(fixture->cmp_ctx, name))
|| !TEST_true(OSSL_CMP_CTX_set1_srvCert(fixture->cmp_ctx, srvcert))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_validate_msg_test, tear_down);
return result;
}
static int test_validate_msg_signature_expected_sender(void)
{
return test_validate_with_sender(X509_get_subject_name(srvcert), 1);
}
static int test_validate_msg_signature_unexpected_sender(void)
{
return test_validate_with_sender(X509_get_subject_name(root), 0);
}
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
static int test_validate_msg_unprotected_request(void)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
fixture->expected = 0;
if (!TEST_ptr(fixture->msg = load_pkimsg(ir_unprotected_f, libctx))) {
tear_down(fixture);
fixture = NULL;
}
EXECUTE_TEST(execute_validate_msg_test, tear_down);
return result;
}
#endif
static void setup_path(CMP_VFY_TEST_FIXTURE **fixture, X509 *wrong, int expired)
{
(*fixture)->cert = endentity2;
(*fixture)->expected = wrong == NULL && !expired;
if (expired) {
X509_STORE *ts = OSSL_CMP_CTX_get0_trusted((*fixture)->cmp_ctx);
X509_VERIFY_PARAM *vpm = X509_STORE_get0_param(ts);
X509_VERIFY_PARAM_set_time(vpm, test_time_after_expiration);
}
if (!add_trusted((*fixture)->cmp_ctx, wrong == NULL ? root : wrong)
|| !add_untrusted((*fixture)->cmp_ctx, endentity1)
|| !add_untrusted((*fixture)->cmp_ctx, intermediate)) {
tear_down((*fixture));
(*fixture) = NULL;
}
}
static int test_validate_cert_path_ok(void)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
setup_path(&fixture, NULL, 0);
EXECUTE_TEST(execute_validate_cert_path_test, tear_down);
return result;
}
static int test_validate_cert_path_wrong_anchor(void)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
setup_path(&fixture, srvcert /* wrong/non-root cert */, 0);
EXECUTE_TEST(execute_validate_cert_path_test, tear_down);
return result;
}
static int test_validate_cert_path_expired(void)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
setup_path(&fixture, NULL, 1);
EXECUTE_TEST(execute_validate_cert_path_test, tear_down);
return result;
}
static int execute_msg_check_test(CMP_VFY_TEST_FIXTURE *fixture)
{
const OSSL_CMP_PKIHEADER *hdr = OSSL_CMP_MSG_get0_header(fixture->msg);
const ASN1_OCTET_STRING *tid = OSSL_CMP_HDR_get0_transactionID(hdr);
if (!TEST_int_eq(fixture->expected,
ossl_cmp_msg_check_update(fixture->cmp_ctx,
fixture->msg,
fixture->allow_unprotected_cb,
fixture->additional_arg)))
return 0;
if (fixture->expected == 0) /* error expected already during above check */
return 1;
return
TEST_int_eq(0,
ASN1_OCTET_STRING_cmp(ossl_cmp_hdr_get0_senderNonce(hdr),
fixture->cmp_ctx->recipNonce))
&& TEST_int_eq(0,
ASN1_OCTET_STRING_cmp(tid,
fixture->cmp_ctx->transactionID));
}
static int allow_unprotected(const OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg,
int invalid_protection, int allow)
{
return allow;
}
static void setup_check_update(CMP_VFY_TEST_FIXTURE **fixture, int expected,
ossl_cmp_allow_unprotected_cb_t cb, int arg,
const unsigned char *trid_data,
const unsigned char *nonce_data)
{
OSSL_CMP_CTX *ctx = (*fixture)->cmp_ctx;
int nonce_len = OSSL_CMP_SENDERNONCE_LENGTH;
(*fixture)->expected = expected;
(*fixture)->allow_unprotected_cb = cb;
(*fixture)->additional_arg = arg;
(*fixture)->msg = OSSL_CMP_MSG_dup(ir_rmprotection);
if ((*fixture)->msg == NULL
|| (nonce_data != NULL
&& !ossl_cmp_asn1_octet_string_set1_bytes(&ctx->senderNonce,
nonce_data, nonce_len))) {
tear_down((*fixture));
(*fixture) = NULL;
} else if (trid_data != NULL) {
ASN1_OCTET_STRING *trid = ASN1_OCTET_STRING_new();
if (trid == NULL
|| !ASN1_OCTET_STRING_set(trid, trid_data,
OSSL_CMP_TRANSACTIONID_LENGTH)
|| !OSSL_CMP_CTX_set1_transactionID(ctx, trid)) {
tear_down((*fixture));
(*fixture) = NULL;
}
ASN1_OCTET_STRING_free(trid);
}
}
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
static int test_msg_check_no_protection_no_cb(void)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
setup_check_update(&fixture, 0, NULL, 0, NULL, NULL);
EXECUTE_TEST(execute_msg_check_test, tear_down);
return result;
}
static int test_msg_check_no_protection_restrictive_cb(void)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
setup_check_update(&fixture, 0, allow_unprotected, 0, NULL, NULL);
EXECUTE_TEST(execute_msg_check_test, tear_down);
return result;
}
#endif
static int test_msg_check_no_protection_permissive_cb(void)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
setup_check_update(&fixture, 1, allow_unprotected, 1, NULL, NULL);
EXECUTE_TEST(execute_msg_check_test, tear_down);
return result;
}
static int test_msg_check_transaction_id(void)
{
/* Transaction id belonging to CMP_IR_rmprotection.der */
const unsigned char trans_id[OSSL_CMP_TRANSACTIONID_LENGTH] = {
0x39, 0xB6, 0x90, 0x28, 0xC4, 0xBC, 0x7A, 0xF6,
0xBE, 0xC6, 0x4A, 0x88, 0x97, 0xA6, 0x95, 0x0B
};
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
setup_check_update(&fixture, 1, allow_unprotected, 1, trans_id, NULL);
EXECUTE_TEST(execute_msg_check_test, tear_down);
return result;
}
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
static int test_msg_check_transaction_id_bad(void)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
setup_check_update(&fixture, 0, allow_unprotected, 1, rand_data, NULL);
EXECUTE_TEST(execute_msg_check_test, tear_down);
return result;
}
#endif
static int test_msg_check_recipient_nonce(void)
{
/* Recipient nonce belonging to CMP_IP_ir_rmprotection.der */
const unsigned char rec_nonce[OSSL_CMP_SENDERNONCE_LENGTH] = {
0x48, 0xF1, 0x71, 0x1F, 0xE5, 0xAF, 0x1C, 0x8B,
0x21, 0x97, 0x5C, 0x84, 0x74, 0x49, 0xBA, 0x32
};
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
setup_check_update(&fixture, 1, allow_unprotected, 1, NULL, rec_nonce);
EXECUTE_TEST(execute_msg_check_test, tear_down);
return result;
}
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
static int test_msg_check_recipient_nonce_bad(void)
{
SETUP_TEST_FIXTURE(CMP_VFY_TEST_FIXTURE, set_up);
setup_check_update(&fixture, 0, allow_unprotected, 1, NULL, rand_data);
EXECUTE_TEST(execute_msg_check_test, tear_down);
return result;
}
#endif
void cleanup_tests(void)
{
X509_free(srvcert);
X509_free(clcert);
X509_free(endentity1);
X509_free(endentity2);
X509_free(intermediate);
X509_free(root);
X509_free(insta_cert);
X509_free(instaca_cert);
OSSL_CMP_MSG_free(ir_unprotected);
OSSL_CMP_MSG_free(ir_rmprotection);
OSSL_PROVIDER_unload(default_null_provider);
OSSL_PROVIDER_unload(provider);
OSSL_LIB_CTX_free(libctx);
return;
}
#define USAGE "server.crt client.crt " \
"EndEntity1.crt EndEntity2.crt " \
"Root_CA.crt Intermediate_CA.crt " \
"CMP_IR_protected.der CMP_IR_unprotected.der " \
"IP_waitingStatus_PBM.der IR_rmprotection.der " \
"insta.cert.pem insta_ca.cert.pem " \
"IR_protected_0_extraCerts.der " \
"IR_protected_2_extraCerts.der module_name [module_conf_file]\n"
OPT_TEST_DECLARE_USAGE(USAGE)
int setup_tests(void)
{
/* Set test time stamps */
struct tm ts = { 0 };
ts.tm_year = 2018 - 1900; /* 2018 */
ts.tm_mon = 1; /* February */
ts.tm_mday = 18; /* 18th */
test_time_valid = mktime(&ts); /* February 18th 2018 */
ts.tm_year += 10; /* February 18th 2028 */
test_time_after_expiration = mktime(&ts);
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
RAND_bytes(rand_data, OSSL_CMP_TRANSACTIONID_LENGTH);
if (!TEST_ptr(server_f = test_get_argument(0))
|| !TEST_ptr(client_f = test_get_argument(1))
|| !TEST_ptr(endentity1_f = test_get_argument(2))
|| !TEST_ptr(endentity2_f = test_get_argument(3))
|| !TEST_ptr(root_f = test_get_argument(4))
|| !TEST_ptr(intermediate_f = test_get_argument(5))
|| !TEST_ptr(ir_protected_f = test_get_argument(6))
|| !TEST_ptr(ir_unprotected_f = test_get_argument(7))
|| !TEST_ptr(ip_waiting_f = test_get_argument(8))
|| !TEST_ptr(ir_rmprotection_f = test_get_argument(9))
|| !TEST_ptr(instacert_f = test_get_argument(10))
|| !TEST_ptr(instaca_f = test_get_argument(11))
|| !TEST_ptr(ir_protected_0_extracerts = test_get_argument(12))
|| !TEST_ptr(ir_protected_2_extracerts = test_get_argument(13))) {
TEST_error("usage: cmp_vfy_test %s", USAGE);
return 0;
}
if (!test_arg_libctx(&libctx, &default_null_provider, &provider, 14, USAGE))
return 0;
/* Load certificates for cert chain */
if (!TEST_ptr(endentity1 = load_cert_pem(endentity1_f, libctx))
|| !TEST_ptr(endentity2 = load_cert_pem(endentity2_f, libctx))
|| !TEST_ptr(root = load_cert_pem(root_f, NULL))
|| !TEST_ptr(intermediate = load_cert_pem(intermediate_f, libctx)))
goto err;
if (!TEST_ptr(insta_cert = load_cert_pem(instacert_f, libctx))
|| !TEST_ptr(instaca_cert = load_cert_pem(instaca_f, libctx)))
goto err;
/* Load certificates for message validation */
if (!TEST_ptr(srvcert = load_cert_pem(server_f, libctx))
|| !TEST_ptr(clcert = load_cert_pem(client_f, libctx)))
goto err;
if (!TEST_int_eq(1, RAND_bytes(rand_data, OSSL_CMP_TRANSACTIONID_LENGTH)))
goto err;
if (!TEST_ptr(ir_unprotected = load_pkimsg(ir_unprotected_f, libctx))
|| !TEST_ptr(ir_rmprotection = load_pkimsg(ir_rmprotection_f,
libctx)))
goto err;
/* Message validation tests */
ADD_TEST(test_verify_popo);
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
ADD_TEST(test_verify_popo_bad);
#endif
ADD_TEST(test_validate_msg_signature_trusted_ok);
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
ADD_TEST(test_validate_msg_signature_trusted_expired);
ADD_TEST(test_validate_msg_signature_srvcert_missing);
#endif
ADD_TEST(test_validate_msg_signature_srvcert_wrong);
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
ADD_TEST(test_validate_msg_signature_bad);
#endif
ADD_TEST(test_validate_msg_signature_sender_cert_srvcert);
ADD_TEST(test_validate_msg_signature_sender_cert_untrusted);
ADD_TEST(test_validate_msg_signature_sender_cert_trusted);
ADD_TEST(test_validate_msg_signature_sender_cert_extracert);
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
ADD_TEST(test_validate_msg_signature_sender_cert_absent);
#endif
ADD_TEST(test_validate_msg_signature_expected_sender);
ADD_TEST(test_validate_msg_signature_unexpected_sender);
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
ADD_TEST(test_validate_msg_unprotected_request);
#endif
ADD_TEST(test_validate_msg_mac_alg_protection_ok);
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
ADD_TEST(test_validate_msg_mac_alg_protection_missing);
ADD_TEST(test_validate_msg_mac_alg_protection_wrong);
ADD_TEST(test_validate_msg_mac_alg_protection_bad);
#endif
/* Cert path validation tests */
ADD_TEST(test_validate_cert_path_ok);
ADD_TEST(test_validate_cert_path_expired);
ADD_TEST(test_validate_cert_path_wrong_anchor);
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
ADD_TEST(test_msg_check_no_protection_no_cb);
ADD_TEST(test_msg_check_no_protection_restrictive_cb);
#endif
ADD_TEST(test_msg_check_no_protection_permissive_cb);
ADD_TEST(test_msg_check_transaction_id);
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
ADD_TEST(test_msg_check_transaction_id_bad);
#endif
ADD_TEST(test_msg_check_recipient_nonce);
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
ADD_TEST(test_msg_check_recipient_nonce_bad);
#endif
return 1;
err:
cleanup_tests();
return 0;
}
| 24,756 | 33.194751 | 80 | c |
openssl | openssl-master/test/cmsapitest.c | /*
* Copyright 2018-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 <string.h>
#include <openssl/cms.h>
#include <openssl/bio.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include "../crypto/cms/cms_local.h" /* for d.signedData and d.envelopedData */
#include "testutil.h"
static X509 *cert = NULL;
static EVP_PKEY *privkey = NULL;
static char *derin = NULL;
static int test_encrypt_decrypt(const EVP_CIPHER *cipher)
{
int testresult = 0;
STACK_OF(X509) *certstack = sk_X509_new_null();
const char *msg = "Hello world";
BIO *msgbio = BIO_new_mem_buf(msg, strlen(msg));
BIO *outmsgbio = BIO_new(BIO_s_mem());
CMS_ContentInfo* content = NULL;
BIO *contentbio = NULL;
char buf[80];
if (!TEST_ptr(certstack) || !TEST_ptr(msgbio) || !TEST_ptr(outmsgbio))
goto end;
if (!TEST_int_gt(sk_X509_push(certstack, cert), 0))
goto end;
content = CMS_encrypt(certstack, msgbio, cipher, CMS_TEXT);
if (!TEST_ptr(content))
goto end;
if (!TEST_true(CMS_decrypt(content, privkey, cert, NULL, outmsgbio,
CMS_TEXT)))
goto end;
if (!TEST_ptr(contentbio =
CMS_EnvelopedData_decrypt(content->d.envelopedData,
NULL, privkey, cert, NULL,
CMS_TEXT, NULL, NULL)))
goto end;
/* Check we got the message we first started with */
if (!TEST_int_eq(BIO_gets(outmsgbio, buf, sizeof(buf)), strlen(msg))
|| !TEST_int_eq(strcmp(buf, msg), 0))
goto end;
testresult = 1;
end:
BIO_free(contentbio);
sk_X509_free(certstack);
BIO_free(msgbio);
BIO_free(outmsgbio);
CMS_ContentInfo_free(content);
return testresult;
}
static int test_encrypt_decrypt_aes_cbc(void)
{
return test_encrypt_decrypt(EVP_aes_128_cbc());
}
static int test_encrypt_decrypt_aes_128_gcm(void)
{
return test_encrypt_decrypt(EVP_aes_128_gcm());
}
static int test_encrypt_decrypt_aes_192_gcm(void)
{
return test_encrypt_decrypt(EVP_aes_192_gcm());
}
static int test_encrypt_decrypt_aes_256_gcm(void)
{
return test_encrypt_decrypt(EVP_aes_256_gcm());
}
static int test_CMS_add1_cert(void)
{
CMS_ContentInfo *cms = NULL;
int ret = 0;
ret = TEST_ptr(cms = CMS_ContentInfo_new())
&& TEST_ptr(CMS_add1_signer(cms, cert, privkey, NULL, 0))
&& TEST_true(CMS_add1_cert(cms, cert)); /* add cert again */
CMS_ContentInfo_free(cms);
return ret;
}
static int test_d2i_CMS_bio_NULL(void)
{
BIO *bio, *content = NULL;
CMS_ContentInfo *cms = NULL;
unsigned int flags = CMS_NO_SIGNER_CERT_VERIFY;
int ret = 0;
/*
* Test data generated using:
* openssl cms -sign -md sha256 -signer ./test/certs/rootCA.pem -inkey \
* ./test/certs/rootCA.key -nodetach -outform DER -in ./in.txt -out out.der \
* -nosmimecap
*/
static const unsigned char cms_data[] = {
0x30, 0x82, 0x05, 0xc5, 0x06, 0x09, 0x2a, 0x86,
0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02, 0xa0,
0x82, 0x05, 0xb6, 0x30, 0x82, 0x05, 0xb2, 0x02,
0x01, 0x01, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x09,
0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
0x01, 0x30, 0x1c, 0x06, 0x09, 0x2a, 0x86, 0x48,
0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0xa0, 0x0f,
0x04, 0x0d, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20,
0x57, 0x6f, 0x72, 0x6c, 0x64, 0x0d, 0x0a, 0xa0,
0x82, 0x03, 0x83, 0x30, 0x82, 0x03, 0x7f, 0x30,
0x82, 0x02, 0x67, 0xa0, 0x03, 0x02, 0x01, 0x02,
0x02, 0x09, 0x00, 0x88, 0x43, 0x29, 0xcb, 0xc2,
0xeb, 0x15, 0x9a, 0x30, 0x0d, 0x06, 0x09, 0x2a,
0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b,
0x05, 0x00, 0x30, 0x56, 0x31, 0x0b, 0x30, 0x09,
0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x41,
0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55,
0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f, 0x6d, 0x65,
0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, 0x21,
0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c,
0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65,
0x74, 0x20, 0x57, 0x69, 0x64, 0x67, 0x69, 0x74,
0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74,
0x64, 0x31, 0x0f, 0x30, 0x0d, 0x06, 0x03, 0x55,
0x04, 0x03, 0x0c, 0x06, 0x72, 0x6f, 0x6f, 0x74,
0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x35,
0x30, 0x37, 0x30, 0x32, 0x31, 0x33, 0x31, 0x35,
0x31, 0x31, 0x5a, 0x17, 0x0d, 0x33, 0x35, 0x30,
0x37, 0x30, 0x32, 0x31, 0x33, 0x31, 0x35, 0x31,
0x31, 0x5a, 0x30, 0x56, 0x31, 0x0b, 0x30, 0x09,
0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x41,
0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55,
0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f, 0x6d, 0x65,
0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, 0x21,
0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c,
0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65,
0x74, 0x20, 0x57, 0x69, 0x64, 0x67, 0x69, 0x74,
0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74,
0x64, 0x31, 0x0f, 0x30, 0x0d, 0x06, 0x03, 0x55,
0x04, 0x03, 0x0c, 0x06, 0x72, 0x6f, 0x6f, 0x74,
0x43, 0x41, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d,
0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01,
0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82,
0x01, 0x01, 0x00, 0xc0, 0xf1, 0x6b, 0x77, 0x88,
0xac, 0x35, 0xdf, 0xfb, 0x73, 0x53, 0x2f, 0x92,
0x80, 0x2f, 0x74, 0x16, 0x32, 0x4d, 0xf5, 0x10,
0x20, 0x6f, 0x6c, 0x3a, 0x8e, 0xd1, 0xdc, 0x6b,
0xe1, 0x2e, 0x3e, 0xc3, 0x04, 0x0f, 0xbf, 0x9b,
0xc4, 0xc9, 0x12, 0xd1, 0xe4, 0x0b, 0x45, 0x97,
0xe5, 0x06, 0xcd, 0x66, 0x3a, 0xe1, 0xe0, 0xe2,
0x2b, 0xdf, 0xa2, 0xc4, 0xec, 0x7b, 0xd3, 0x3d,
0x3c, 0x8a, 0xff, 0x5e, 0x74, 0xa0, 0xab, 0xa7,
0x03, 0x6a, 0x16, 0x5b, 0x5e, 0x92, 0xc4, 0x7e,
0x5b, 0x79, 0x8a, 0x69, 0xd4, 0xbc, 0x83, 0x5e,
0xae, 0x42, 0x92, 0x74, 0xa5, 0x2b, 0xe7, 0x00,
0xc1, 0xa9, 0xdc, 0xd5, 0xb1, 0x53, 0x07, 0x0f,
0x73, 0xf7, 0x8e, 0xad, 0x14, 0x3e, 0x25, 0x9e,
0xe5, 0x1e, 0xe6, 0xcc, 0x91, 0xcd, 0x95, 0x0c,
0x80, 0x44, 0x20, 0xc3, 0xfd, 0x17, 0xcf, 0x91,
0x3d, 0x63, 0x10, 0x1c, 0x14, 0x5b, 0xfb, 0xc3,
0xa8, 0xc1, 0x88, 0xb2, 0x77, 0xff, 0x9c, 0xdb,
0xfc, 0x6a, 0x44, 0x44, 0x44, 0xf7, 0x85, 0xec,
0x08, 0x2c, 0xd4, 0xdf, 0x81, 0xa3, 0x79, 0xc9,
0xfe, 0x1e, 0x9b, 0x93, 0x16, 0x53, 0xb7, 0x97,
0xab, 0xbe, 0x4f, 0x1a, 0xa5, 0xe2, 0xfa, 0x46,
0x05, 0xe4, 0x0d, 0x9c, 0x2a, 0xa4, 0xcc, 0xb9,
0x1e, 0x21, 0xa0, 0x6c, 0xc4, 0xab, 0x59, 0xb0,
0x40, 0x39, 0xbb, 0xf9, 0x88, 0xad, 0xfd, 0xdf,
0x8d, 0xb4, 0x0b, 0xaf, 0x7e, 0x41, 0xe0, 0x21,
0x3c, 0xc8, 0x33, 0x45, 0x49, 0x84, 0x2f, 0x93,
0x06, 0xee, 0xfd, 0x4f, 0xed, 0x4f, 0xf3, 0xbc,
0x9b, 0xde, 0xfc, 0x25, 0x5e, 0x55, 0xd5, 0x75,
0xd4, 0xc5, 0x7b, 0x3a, 0x40, 0x35, 0x06, 0x9f,
0xc4, 0x84, 0xb4, 0x6c, 0x93, 0x0c, 0xaf, 0x37,
0x5a, 0xaf, 0xb6, 0x41, 0x4d, 0x26, 0x23, 0x1c,
0xb8, 0x02, 0xb3, 0x02, 0x03, 0x01, 0x00, 0x01,
0xa3, 0x50, 0x30, 0x4e, 0x30, 0x0c, 0x06, 0x03,
0x55, 0x1d, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01,
0x01, 0xff, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d,
0x0e, 0x04, 0x16, 0x04, 0x14, 0x85, 0x56, 0x89,
0x35, 0xe2, 0x9f, 0x00, 0x1a, 0xe1, 0x86, 0x03,
0x0b, 0x4b, 0xaf, 0x76, 0x12, 0x6b, 0x33, 0x6d,
0xfd, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23,
0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x85, 0x56,
0x89, 0x35, 0xe2, 0x9f, 0x00, 0x1a, 0xe1, 0x86,
0x03, 0x0b, 0x4b, 0xaf, 0x76, 0x12, 0x6b, 0x33,
0x6d, 0xfd, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86,
0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05,
0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x32, 0x0a,
0xbf, 0x2a, 0x0a, 0xe2, 0xbb, 0x4f, 0x43, 0xce,
0x88, 0xda, 0x5a, 0x39, 0x10, 0x37, 0x80, 0xbb,
0x37, 0x2d, 0x5e, 0x2d, 0x88, 0xdd, 0x26, 0x69,
0x9c, 0xe7, 0xb4, 0x98, 0x20, 0xb1, 0x25, 0xe6,
0x61, 0x59, 0x6d, 0x12, 0xec, 0x9b, 0x87, 0xbe,
0x57, 0xe1, 0x12, 0x05, 0xc5, 0x04, 0xf1, 0x17,
0xce, 0x14, 0xb8, 0x1c, 0x92, 0xd4, 0x95, 0x95,
0x2c, 0x5b, 0x28, 0x89, 0xfb, 0x72, 0x9c, 0x20,
0xd3, 0x32, 0x81, 0xa8, 0x85, 0xec, 0xc8, 0x08,
0x7b, 0xa8, 0x59, 0x5b, 0x3a, 0x6c, 0x31, 0xab,
0x52, 0xe2, 0x66, 0xcd, 0x14, 0x49, 0x5c, 0xf3,
0xd3, 0x3e, 0x62, 0xbc, 0x91, 0x16, 0xb4, 0x1c,
0xf5, 0xdd, 0x54, 0xaa, 0x3c, 0x61, 0x97, 0x79,
0xac, 0xe4, 0xc8, 0x43, 0x35, 0xc3, 0x0f, 0xfc,
0xf3, 0x70, 0x1d, 0xaf, 0xf0, 0x9c, 0x8a, 0x2a,
0x92, 0x93, 0x48, 0xaa, 0xd0, 0xe8, 0x47, 0xbe,
0x35, 0xc1, 0xc6, 0x7b, 0x6d, 0xda, 0xfa, 0x5d,
0x57, 0x45, 0xf3, 0xea, 0x41, 0x8f, 0x36, 0xc1,
0x3c, 0xf4, 0x52, 0x7f, 0x6e, 0x31, 0xdd, 0xba,
0x9a, 0xbc, 0x70, 0x56, 0x71, 0x38, 0xdc, 0x49,
0x57, 0x0c, 0xfd, 0x91, 0x17, 0xc5, 0xea, 0x87,
0xe5, 0x23, 0x74, 0x19, 0xb2, 0xb6, 0x99, 0x0c,
0x6b, 0xa2, 0x05, 0xf8, 0x51, 0x68, 0xed, 0x97,
0xe0, 0xdf, 0x62, 0xf9, 0x7e, 0x7a, 0x3a, 0x44,
0x71, 0x83, 0x57, 0x28, 0x49, 0x88, 0x69, 0xb5,
0x14, 0x1e, 0xda, 0x46, 0xe3, 0x6e, 0x78, 0xe1,
0xcb, 0x8f, 0xb5, 0x98, 0xb3, 0x2d, 0x6e, 0x5b,
0xb7, 0xf6, 0x93, 0x24, 0x14, 0x1f, 0xa4, 0xf6,
0x69, 0xbd, 0xff, 0x4c, 0x52, 0x50, 0x02, 0xc5,
0x43, 0x8d, 0x14, 0xe2, 0xd0, 0x75, 0x9f, 0x12,
0x5e, 0x94, 0x89, 0xd1, 0xef, 0x77, 0x89, 0x7d,
0x89, 0xd9, 0x9e, 0x76, 0x99, 0x24, 0x31, 0x82,
0x01, 0xf7, 0x30, 0x82, 0x01, 0xf3, 0x02, 0x01,
0x01, 0x30, 0x63, 0x30, 0x56, 0x31, 0x0b, 0x30,
0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02,
0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03,
0x55, 0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f, 0x6d,
0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31,
0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a,
0x0c, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e,
0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67, 0x69,
0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c,
0x74, 0x64, 0x31, 0x0f, 0x30, 0x0d, 0x06, 0x03,
0x55, 0x04, 0x03, 0x0c, 0x06, 0x72, 0x6f, 0x6f,
0x74, 0x43, 0x41, 0x02, 0x09, 0x00, 0x88, 0x43,
0x29, 0xcb, 0xc2, 0xeb, 0x15, 0x9a, 0x30, 0x0b,
0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03,
0x04, 0x02, 0x01, 0xa0, 0x69, 0x30, 0x18, 0x06,
0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01,
0x09, 0x03, 0x31, 0x0b, 0x06, 0x09, 0x2a, 0x86,
0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0x30,
0x1c, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
0x0d, 0x01, 0x09, 0x05, 0x31, 0x0f, 0x17, 0x0d,
0x32, 0x30, 0x31, 0x32, 0x31, 0x31, 0x30, 0x39,
0x30, 0x30, 0x31, 0x33, 0x5a, 0x30, 0x2f, 0x06,
0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01,
0x09, 0x04, 0x31, 0x22, 0x04, 0x20, 0xb0, 0x80,
0x22, 0xd3, 0x15, 0xcf, 0x1e, 0xb1, 0x2d, 0x26,
0x65, 0xbd, 0xed, 0x0e, 0x6a, 0xf4, 0x06, 0x53,
0xc0, 0xa0, 0xbe, 0x97, 0x52, 0x32, 0xfb, 0x49,
0xbc, 0xbd, 0x02, 0x1c, 0xfc, 0x36, 0x30, 0x0d,
0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82, 0x01,
0x00, 0x37, 0x44, 0x39, 0x08, 0xb2, 0x19, 0x52,
0x35, 0x9c, 0xd0, 0x67, 0x87, 0xae, 0xb8, 0x1c,
0x80, 0xf4, 0x03, 0x29, 0x2e, 0xe3, 0x76, 0x4a,
0xb0, 0x98, 0x10, 0x00, 0x9a, 0x30, 0xdb, 0x05,
0x28, 0x53, 0x34, 0x31, 0x14, 0xbd, 0x87, 0xb9,
0x4d, 0x45, 0x07, 0x97, 0xa3, 0x57, 0x0b, 0x7e,
0xd1, 0x67, 0xfb, 0x4e, 0x0f, 0x5b, 0x90, 0xb2,
0x6f, 0xe6, 0xce, 0x49, 0xdd, 0x72, 0x46, 0x71,
0x26, 0xa1, 0x1b, 0x98, 0x23, 0x7d, 0x69, 0x73,
0x84, 0xdc, 0xf9, 0xd2, 0x1c, 0x6d, 0xf6, 0xf5,
0x17, 0x49, 0x6e, 0x9d, 0x4d, 0xf1, 0xe2, 0x43,
0x29, 0x53, 0x55, 0xa5, 0x22, 0x1e, 0x89, 0x2c,
0xaf, 0xf2, 0x43, 0x47, 0xd5, 0xfa, 0xad, 0xe7,
0x89, 0x60, 0xbf, 0x96, 0x35, 0x6f, 0xc2, 0x99,
0xb7, 0x55, 0xc5, 0xe3, 0x04, 0x25, 0x1b, 0xf6,
0x7e, 0xf2, 0x2b, 0x14, 0xa9, 0x57, 0x96, 0xbe,
0xbd, 0x6e, 0x95, 0x44, 0x94, 0xbd, 0xaf, 0x9a,
0x6d, 0x77, 0x55, 0x5e, 0x6c, 0xf6, 0x32, 0x37,
0xec, 0xef, 0xe5, 0x81, 0xb0, 0xe3, 0x35, 0xc7,
0x86, 0xea, 0x47, 0x59, 0x38, 0xb6, 0x16, 0xfb,
0x1d, 0x10, 0x55, 0x48, 0xb1, 0x44, 0x33, 0xde,
0xf6, 0x29, 0xbe, 0xbf, 0xbc, 0x71, 0x3e, 0x49,
0xba, 0xe7, 0x9f, 0x4d, 0x6c, 0xfb, 0xec, 0xd2,
0xe0, 0x12, 0xa9, 0x7c, 0xc9, 0x9a, 0x7b, 0x85,
0x83, 0xb8, 0xca, 0xdd, 0xf6, 0xb7, 0x15, 0x75,
0x7b, 0x4a, 0x69, 0xcf, 0x0a, 0xc7, 0x80, 0x01,
0xe7, 0x94, 0x16, 0x7f, 0x8d, 0x3c, 0xfa, 0x1f,
0x05, 0x71, 0x76, 0x15, 0xb0, 0xf6, 0x61, 0x30,
0x58, 0x16, 0xbe, 0x1b, 0xd1, 0x93, 0xc4, 0x1a,
0x91, 0x0c, 0x48, 0xe2, 0x1c, 0x8e, 0xa5, 0xc5,
0xa7, 0x81, 0x44, 0x48, 0x3b, 0x10, 0xc2, 0x74,
0x07, 0xdf, 0xa8, 0xae, 0x57, 0xee, 0x7f, 0xe3,
0x6a
};
ret = TEST_ptr(bio = BIO_new_mem_buf(cms_data, sizeof(cms_data)))
&& TEST_ptr(cms = d2i_CMS_bio(bio, NULL))
&& TEST_true(CMS_verify(cms, NULL, NULL, NULL, NULL, flags))
&& TEST_ptr(content =
CMS_SignedData_verify(cms->d.signedData, NULL, NULL, NULL,
NULL, NULL, flags, NULL, NULL));
BIO_free(content);
CMS_ContentInfo_free(cms);
BIO_free(bio);
return ret;
}
static unsigned char *read_all(BIO *bio, long *p_len)
{
const int step = 256;
unsigned char *buf = NULL;
unsigned char *tmp = NULL;
int ret;
*p_len = 0;
for (;;) {
tmp = OPENSSL_realloc(buf, *p_len + step);
if (tmp == NULL)
break;
buf = tmp;
ret = BIO_read(bio, buf + *p_len, step);
if (ret < 0)
break;
*p_len += ret;
if (ret < step)
return buf;
}
/* Error */
OPENSSL_free(buf);
*p_len = 0;
return NULL;
}
static int test_d2i_CMS_decode(const int idx)
{
BIO *bio = NULL;
CMS_ContentInfo *cms = NULL;
unsigned char *buf = NULL;
const unsigned char *tmp = NULL;
long buf_len = 0;
int ret = 0;
if (!TEST_ptr(bio = BIO_new_file(derin, "r")))
goto end;
switch (idx) {
case 0:
if (!TEST_ptr(cms = d2i_CMS_bio(bio, NULL)))
goto end;
break;
case 1:
if (!TEST_ptr(buf = read_all(bio, &buf_len)))
goto end;
tmp = buf;
if (!TEST_ptr(cms = d2i_CMS_ContentInfo(NULL, &tmp, buf_len)))
goto end;
break;
}
if (!TEST_int_eq(ERR_peek_error(), 0))
goto end;
ret = 1;
end:
CMS_ContentInfo_free(cms);
BIO_free(bio);
OPENSSL_free(buf);
return ret;
}
OPT_TEST_DECLARE_USAGE("certfile privkeyfile derfile\n")
int setup_tests(void)
{
char *certin = NULL, *privkeyin = NULL;
BIO *certbio = NULL, *privkeybio = NULL;
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
if (!TEST_ptr(certin = test_get_argument(0))
|| !TEST_ptr(privkeyin = test_get_argument(1))
|| !TEST_ptr(derin = test_get_argument(2)))
return 0;
certbio = BIO_new_file(certin, "r");
if (!TEST_ptr(certbio))
return 0;
if (!TEST_true(PEM_read_bio_X509(certbio, &cert, NULL, NULL))) {
BIO_free(certbio);
return 0;
}
BIO_free(certbio);
privkeybio = BIO_new_file(privkeyin, "r");
if (!TEST_ptr(privkeybio)) {
X509_free(cert);
cert = NULL;
return 0;
}
if (!TEST_true(PEM_read_bio_PrivateKey(privkeybio, &privkey, NULL, NULL))) {
BIO_free(privkeybio);
X509_free(cert);
cert = NULL;
return 0;
}
BIO_free(privkeybio);
ADD_TEST(test_encrypt_decrypt_aes_cbc);
ADD_TEST(test_encrypt_decrypt_aes_128_gcm);
ADD_TEST(test_encrypt_decrypt_aes_192_gcm);
ADD_TEST(test_encrypt_decrypt_aes_256_gcm);
ADD_TEST(test_CMS_add1_cert);
ADD_TEST(test_d2i_CMS_bio_NULL);
ADD_ALL_TESTS(test_d2i_CMS_decode, 2);
return 1;
}
void cleanup_tests(void)
{
X509_free(cert);
EVP_PKEY_free(privkey);
}
| 16,904 | 37.420455 | 81 | c |
openssl | openssl-master/test/conf_include_test.c | /*
* Copyright 2016-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 <stdlib.h>
#include <string.h>
#include <openssl/conf.h>
#include <openssl/err.h>
#include "testutil.h"
#ifdef _WIN32
# include <direct.h>
# define DIRSEP "/\\"
# ifndef __BORLANDC__
# define chdir _chdir
# endif
# define DIRSEP_PRESERVE 0
#elif !defined(OPENSSL_NO_POSIX_IO)
# include <unistd.h>
# ifndef OPENSSL_SYS_VMS
# define DIRSEP "/"
# define DIRSEP_PRESERVE 0
# else
# define DIRSEP "/]:"
# define DIRSEP_PRESERVE 1
# endif
#else
/* the test does not work without chdir() */
# define chdir(x) (-1);
# define DIRSEP "/"
# define DIRSEP_PRESERVE 0
#endif
/* changes path to that of the filename */
static int change_path(const char *file)
{
char *s = OPENSSL_strdup(file);
char *p = s;
char *last = NULL;
int ret = 0;
if (s == NULL)
return -1;
while ((p = strpbrk(p, DIRSEP)) != NULL) {
last = p++;
}
if (last == NULL)
goto err;
last[DIRSEP_PRESERVE] = 0;
TEST_note("changing path to %s", s);
ret = chdir(s);
err:
OPENSSL_free(s);
return ret;
}
/*
* This test program checks the operation of the .include directive.
*/
static CONF *conf;
static BIO *in;
static int expect_failure = 0;
static int test_load_config(void)
{
long errline;
long val;
char *str;
long err;
if (!TEST_int_gt(NCONF_load_bio(conf, in, &errline), 0)
|| !TEST_int_eq(err = ERR_peek_error(), 0)) {
if (expect_failure)
return 1;
TEST_note("Failure loading the configuration at line %ld", errline);
return 0;
}
if (expect_failure) {
TEST_note("Failure expected but did not happen");
return 0;
}
if (!TEST_int_gt(CONF_modules_load(conf, NULL, 0), 0)) {
TEST_note("Failed in CONF_modules_load");
return 0;
}
/* verify whether CA_default/default_days is set */
val = 0;
if (!TEST_int_eq(NCONF_get_number(conf, "CA_default", "default_days", &val), 1)
|| !TEST_int_eq(val, 365)) {
TEST_note("default_days incorrect");
return 0;
}
/* verify whether req/default_bits is set */
val = 0;
if (!TEST_int_eq(NCONF_get_number(conf, "req", "default_bits", &val), 1)
|| !TEST_int_eq(val, 2048)) {
TEST_note("default_bits incorrect");
return 0;
}
/* verify whether countryName_default is set correctly */
str = NCONF_get_string(conf, "req_distinguished_name", "countryName_default");
if (!TEST_ptr(str) || !TEST_str_eq(str, "AU")) {
TEST_note("countryName_default incorrect");
return 0;
}
return 1;
}
static int test_check_null_numbers(void)
{
#if defined(_BSD_SOURCE) \
|| (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) \
|| (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
long val = 0;
/* Verify that a NULL config with a present environment variable returns
* success and the value.
*/
if (!TEST_int_eq(setenv("FNORD", "123", 1), 0)
|| !TEST_true(NCONF_get_number(NULL, "missing", "FNORD", &val))
|| !TEST_long_eq(val, 123)) {
TEST_note("environment variable with NULL conf failed");
return 0;
}
/*
* Verify that a NULL config with a missing environment variable returns
* a failure code.
*/
if (!TEST_int_eq(unsetenv("FNORD"), 0)
|| !TEST_false(NCONF_get_number(NULL, "missing", "FNORD", &val))) {
TEST_note("missing environment variable with NULL conf failed");
return 0;
}
#endif
return 1;
}
static int test_check_overflow(void)
{
#if defined(_BSD_SOURCE) \
|| (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) \
|| (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
long val = 0;
char max[(sizeof(long) * 8) / 3 + 3];
char *p;
p = max + sprintf(max, "0%ld", LONG_MAX) - 1;
setenv("FNORD", max, 1);
if (!TEST_true(NCONF_get_number(NULL, "missing", "FNORD", &val))
|| !TEST_long_eq(val, LONG_MAX))
return 0;
while (++*p > '9')
*p-- = '0';
setenv("FNORD", max, 1);
if (!TEST_false(NCONF_get_number(NULL, "missing", "FNORD", &val)))
return 0;
#endif
return 1;
}
typedef enum OPTION_choice {
OPT_ERR = -1,
OPT_EOF = 0,
OPT_FAIL,
OPT_TEST_ENUM
} OPTION_CHOICE;
const OPTIONS *test_get_options(void)
{
static const OPTIONS test_options[] = {
OPT_TEST_OPTIONS_WITH_EXTRA_USAGE("conf_file\n"),
{ "f", OPT_FAIL, '-', "A failure is expected" },
{ NULL }
};
return test_options;
}
int setup_tests(void)
{
const char *conf_file;
OPTION_CHOICE o;
if (!TEST_ptr(conf = NCONF_new(NULL)))
return 0;
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_FAIL:
expect_failure = 1;
break;
case OPT_TEST_CASES:
break;
default:
return 0;
}
}
conf_file = test_get_argument(0);
if (!TEST_ptr(conf_file)
|| !TEST_ptr(in = BIO_new_file(conf_file, "r"))) {
TEST_note("Unable to open the file argument");
return 0;
}
/*
* For this test we need to chdir as we use relative
* path names in the config files.
*/
change_path(conf_file);
ADD_TEST(test_load_config);
ADD_TEST(test_check_null_numbers);
ADD_TEST(test_check_overflow);
return 1;
}
void cleanup_tests(void)
{
BIO_vfree(in);
NCONF_free(conf);
CONF_modules_unload(1);
}
| 5,866 | 23.548117 | 83 | c |
openssl | openssl-master/test/confdump.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 <string.h>
#include <openssl/bio.h>
#include <openssl/conf.h>
#include <openssl/safestack.h>
#include <openssl/err.h>
static void dump_section(const char *name, const CONF *cnf)
{
STACK_OF(CONF_VALUE) *sect = NCONF_get_section(cnf, name);
int i;
printf("[ %s ]\n", name);
for (i = 0; i < sk_CONF_VALUE_num(sect); i++) {
CONF_VALUE *cv = sk_CONF_VALUE_value(sect, i);
printf("%s = %s\n", cv->name, cv->value);
}
}
int main(int argc, char **argv)
{
long eline;
CONF *conf = NCONF_new(NCONF_default());
int ret = 1;
STACK_OF(OPENSSL_CSTRING) *section_names = NULL;
if (conf != NULL && NCONF_load(conf, argv[1], &eline)) {
int i;
section_names = NCONF_get_section_names(conf);
for (i = 0; i < sk_OPENSSL_CSTRING_num(section_names); i++) {
dump_section(sk_OPENSSL_CSTRING_value(section_names, i), conf);
}
sk_OPENSSL_CSTRING_free(section_names);
ret = 0;
} else {
ERR_print_errors_fp(stderr);
}
NCONF_free(conf);
return ret;
}
| 1,433 | 26.576923 | 75 | c |
openssl | openssl-master/test/constant_time_test.c | /*
* Copyright 2014-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 <stdio.h>
#include <stdlib.h>
#include "internal/nelem.h"
#include "internal/constant_time.h"
#include "testutil.h"
#include "internal/numbers.h"
static const unsigned int CONSTTIME_TRUE = (unsigned)(~0);
static const unsigned int CONSTTIME_FALSE = 0;
static const unsigned char CONSTTIME_TRUE_8 = 0xff;
static const unsigned char CONSTTIME_FALSE_8 = 0;
static const size_t CONSTTIME_TRUE_S = ~((size_t)0);
static const size_t CONSTTIME_FALSE_S = 0;
static uint32_t CONSTTIME_TRUE_32 = (uint32_t)(~(uint32_t)0);
static uint32_t CONSTTIME_FALSE_32 = 0;
static uint64_t CONSTTIME_TRUE_64 = (uint64_t)(~(uint64_t)0);
static uint64_t CONSTTIME_FALSE_64 = 0;
static unsigned int test_values[] = {
0, 1, 1024, 12345, 32000, UINT_MAX / 2 - 1,
UINT_MAX / 2, UINT_MAX / 2 + 1, UINT_MAX - 1,
UINT_MAX
};
static unsigned char test_values_8[] = {
0, 1, 2, 20, 32, 127, 128, 129, 255
};
static int signed_test_values[] = {
0, 1, -1, 1024, -1024, 12345, -12345,
32000, -32000, INT_MAX, INT_MIN, INT_MAX - 1,
INT_MIN + 1
};
static size_t test_values_s[] = {
0, 1, 1024, 12345, 32000, SIZE_MAX / 2 - 1,
SIZE_MAX / 2, SIZE_MAX / 2 + 1, SIZE_MAX - 1,
SIZE_MAX
};
static uint32_t test_values_32[] = {
0, 1, 1024, 12345, 32000, UINT32_MAX / 2, UINT32_MAX / 2 + 1,
UINT32_MAX - 1, UINT32_MAX
};
static uint64_t test_values_64[] = {
0, 1, 1024, 12345, 32000, 32000000, 32000000001, UINT64_MAX / 2,
UINT64_MAX / 2 + 1, UINT64_MAX - 1, UINT64_MAX
};
static int test_binary_op(unsigned int (*op) (unsigned int a, unsigned int b),
const char *op_name, unsigned int a, unsigned int b,
int is_true)
{
if (is_true && !TEST_uint_eq(op(a, b), CONSTTIME_TRUE))
return 0;
if (!is_true && !TEST_uint_eq(op(a, b), CONSTTIME_FALSE))
return 0;
return 1;
}
static int test_binary_op_8(unsigned
char (*op) (unsigned int a, unsigned int b),
const char *op_name, unsigned int a,
unsigned int b, int is_true)
{
if (is_true && !TEST_uint_eq(op(a, b), CONSTTIME_TRUE_8))
return 0;
if (!is_true && !TEST_uint_eq(op(a, b), CONSTTIME_FALSE_8))
return 0;
return 1;
}
static int test_binary_op_s(size_t (*op) (size_t a, size_t b),
const char *op_name, size_t a, size_t b,
int is_true)
{
if (is_true && !TEST_size_t_eq(op(a, b), CONSTTIME_TRUE_S))
return 0;
if (!is_true && !TEST_uint_eq(op(a, b), CONSTTIME_FALSE_S))
return 0;
return 1;
}
static int test_binary_op_64(uint64_t (*op)(uint64_t a, uint64_t b),
const char *op_name, uint64_t a, uint64_t b,
int is_true)
{
uint64_t c = op(a, b);
if (is_true && c != CONSTTIME_TRUE_64) {
TEST_error("TRUE %s op failed", op_name);
BIO_printf(bio_err, "a=%jx b=%jx\n", a, b);
return 0;
} else if (!is_true && c != CONSTTIME_FALSE_64) {
TEST_error("FALSE %s op failed", op_name);
BIO_printf(bio_err, "a=%jx b=%jx\n", a, b);
return 0;
}
return 1;
}
static int test_is_zero(int i)
{
unsigned int a = test_values[i];
if (a == 0 && !TEST_uint_eq(constant_time_is_zero(a), CONSTTIME_TRUE))
return 0;
if (a != 0 && !TEST_uint_eq(constant_time_is_zero(a), CONSTTIME_FALSE))
return 0;
return 1;
}
static int test_is_zero_8(int i)
{
unsigned int a = test_values_8[i];
if (a == 0 && !TEST_uint_eq(constant_time_is_zero_8(a), CONSTTIME_TRUE_8))
return 0;
if (a != 0 && !TEST_uint_eq(constant_time_is_zero_8(a), CONSTTIME_FALSE_8))
return 0;
return 1;
}
static int test_is_zero_32(int i)
{
uint32_t a = test_values_32[i];
if (a == 0 && !TEST_true(constant_time_is_zero_32(a) == CONSTTIME_TRUE_32))
return 0;
if (a != 0 && !TEST_true(constant_time_is_zero_32(a) == CONSTTIME_FALSE_32))
return 0;
return 1;
}
static int test_is_zero_s(int i)
{
size_t a = test_values_s[i];
if (a == 0 && !TEST_size_t_eq(constant_time_is_zero_s(a), CONSTTIME_TRUE_S))
return 0;
if (a != 0 && !TEST_uint_eq(constant_time_is_zero_s(a), CONSTTIME_FALSE_S))
return 0;
return 1;
}
static int test_select(unsigned int a, unsigned int b)
{
if (!TEST_uint_eq(constant_time_select(CONSTTIME_TRUE, a, b), a))
return 0;
if (!TEST_uint_eq(constant_time_select(CONSTTIME_FALSE, a, b), b))
return 0;
return 1;
}
static int test_select_8(unsigned char a, unsigned char b)
{
if (!TEST_uint_eq(constant_time_select_8(CONSTTIME_TRUE_8, a, b), a))
return 0;
if (!TEST_uint_eq(constant_time_select_8(CONSTTIME_FALSE_8, a, b), b))
return 0;
return 1;
}
static int test_select_32(uint32_t a, uint32_t b)
{
if (!TEST_true(constant_time_select_32(CONSTTIME_TRUE_32, a, b) == a))
return 0;
if (!TEST_true(constant_time_select_32(CONSTTIME_FALSE_32, a, b) == b))
return 0;
return 1;
}
static int test_select_s(size_t a, size_t b)
{
if (!TEST_uint_eq(constant_time_select_s(CONSTTIME_TRUE_S, a, b), a))
return 0;
if (!TEST_uint_eq(constant_time_select_s(CONSTTIME_FALSE_S, a, b), b))
return 0;
return 1;
}
static int test_select_64(uint64_t a, uint64_t b)
{
uint64_t selected = constant_time_select_64(CONSTTIME_TRUE_64, a, b);
if (selected != a) {
TEST_error("test_select_64 TRUE failed");
BIO_printf(bio_err, "a=%jx b=%jx got %jx wanted a\n", a, b, selected);
return 0;
}
selected = constant_time_select_64(CONSTTIME_FALSE_64, a, b);
if (selected != b) {
BIO_printf(bio_err, "a=%jx b=%jx got %jx wanted b\n", a, b, selected);
return 0;
}
return 1;
}
static int test_select_int(int a, int b)
{
if (!TEST_int_eq(constant_time_select_int(CONSTTIME_TRUE, a, b), a))
return 0;
if (!TEST_int_eq(constant_time_select_int(CONSTTIME_FALSE, a, b), b))
return 0;
return 1;
}
static int test_eq_int_8(int a, int b)
{
if (a == b && !TEST_int_eq(constant_time_eq_int_8(a, b), CONSTTIME_TRUE_8))
return 0;
if (a != b && !TEST_int_eq(constant_time_eq_int_8(a, b), CONSTTIME_FALSE_8))
return 0;
return 1;
}
static int test_eq_s(size_t a, size_t b)
{
if (a == b && !TEST_size_t_eq(constant_time_eq_s(a, b), CONSTTIME_TRUE_S))
return 0;
if (a != b && !TEST_int_eq(constant_time_eq_s(a, b), CONSTTIME_FALSE_S))
return 0;
return 1;
}
static int test_eq_int(int a, int b)
{
if (a == b && !TEST_uint_eq(constant_time_eq_int(a, b), CONSTTIME_TRUE))
return 0;
if (a != b && !TEST_uint_eq(constant_time_eq_int(a, b), CONSTTIME_FALSE))
return 0;
return 1;
}
static int test_sizeofs(void)
{
if (!TEST_uint_eq(OSSL_NELEM(test_values), OSSL_NELEM(test_values_s)))
return 0;
return 1;
}
static int test_binops(int i)
{
unsigned int a = test_values[i];
int j;
int ret = 1;
for (j = 0; j < (int)OSSL_NELEM(test_values); ++j) {
unsigned int b = test_values[j];
if (!test_select(a, b)
|| !test_binary_op(&constant_time_lt, "ct_lt",
a, b, a < b)
|| !test_binary_op(&constant_time_lt, "constant_time_lt",
b, a, b < a)
|| !test_binary_op(&constant_time_ge, "constant_time_ge",
a, b, a >= b)
|| !test_binary_op(&constant_time_ge, "constant_time_ge",
b, a, b >= a)
|| !test_binary_op(&constant_time_eq, "constant_time_eq",
a, b, a == b)
|| !test_binary_op(&constant_time_eq, "constant_time_eq",
b, a, b == a))
ret = 0;
}
return ret;
}
static int test_binops_8(int i)
{
unsigned int a = test_values_8[i];
int j;
int ret = 1;
for (j = 0; j < (int)OSSL_NELEM(test_values_8); ++j) {
unsigned int b = test_values_8[j];
if (!test_binary_op_8(&constant_time_lt_8, "constant_time_lt_8",
a, b, a < b)
|| !test_binary_op_8(&constant_time_lt_8, "constant_time_lt_8",
b, a, b < a)
|| !test_binary_op_8(&constant_time_ge_8, "constant_time_ge_8",
a, b, a >= b)
|| !test_binary_op_8(&constant_time_ge_8, "constant_time_ge_8",
b, a, b >= a)
|| !test_binary_op_8(&constant_time_eq_8, "constant_time_eq_8",
a, b, a == b)
|| !test_binary_op_8(&constant_time_eq_8, "constant_time_eq_8",
b, a, b == a))
ret = 0;
}
return ret;
}
static int test_binops_s(int i)
{
size_t a = test_values_s[i];
int j;
int ret = 1;
for (j = 0; j < (int)OSSL_NELEM(test_values_s); ++j) {
size_t b = test_values_s[j];
if (!test_select_s(a, b)
|| !test_eq_s(a, b)
|| !test_binary_op_s(&constant_time_lt_s, "constant_time_lt_s",
a, b, a < b)
|| !test_binary_op_s(&constant_time_lt_s, "constant_time_lt_s",
b, a, b < a)
|| !test_binary_op_s(&constant_time_ge_s, "constant_time_ge_s",
a, b, a >= b)
|| !test_binary_op_s(&constant_time_ge_s, "constant_time_ge_s",
b, a, b >= a)
|| !test_binary_op_s(&constant_time_eq_s, "constant_time_eq_s",
a, b, a == b)
|| !test_binary_op_s(&constant_time_eq_s, "constant_time_eq_s",
b, a, b == a))
ret = 0;
}
return ret;
}
static int test_signed(int i)
{
int c = signed_test_values[i];
unsigned int j;
int ret = 1;
for (j = 0; j < OSSL_NELEM(signed_test_values); ++j) {
int d = signed_test_values[j];
if (!test_select_int(c, d)
|| !test_eq_int(c, d)
|| !test_eq_int_8(c, d))
ret = 0;
}
return ret;
}
static int test_8values(int i)
{
unsigned char e = test_values_8[i];
unsigned int j;
int ret = 1;
for (j = 0; j < sizeof(test_values_8); ++j) {
unsigned char f = test_values_8[j];
if (!test_select_8(e, f))
ret = 0;
}
return ret;
}
static int test_32values(int i)
{
uint32_t e = test_values_32[i];
size_t j;
int ret = 1;
for (j = 0; j < OSSL_NELEM(test_values_32); j++) {
uint32_t f = test_values_32[j];
if (!test_select_32(e, f))
ret = 0;
}
return ret;
}
static int test_64values(int i)
{
uint64_t g = test_values_64[i];
int j, ret = 1;
for (j = i + 1; j < (int)OSSL_NELEM(test_values_64); j++) {
uint64_t h = test_values_64[j];
if (!test_binary_op_64(&constant_time_lt_64, "constant_time_lt_64",
g, h, g < h)
|| !test_select_64(g, h)) {
TEST_info("test_64values failed i=%d j=%d", i, j);
ret = 0;
}
}
return ret;
}
int setup_tests(void)
{
ADD_TEST(test_sizeofs);
ADD_ALL_TESTS(test_is_zero, OSSL_NELEM(test_values));
ADD_ALL_TESTS(test_is_zero_8, OSSL_NELEM(test_values_8));
ADD_ALL_TESTS(test_is_zero_32, OSSL_NELEM(test_values_32));
ADD_ALL_TESTS(test_is_zero_s, OSSL_NELEM(test_values_s));
ADD_ALL_TESTS(test_binops, OSSL_NELEM(test_values));
ADD_ALL_TESTS(test_binops_8, OSSL_NELEM(test_values_8));
ADD_ALL_TESTS(test_binops_s, OSSL_NELEM(test_values_s));
ADD_ALL_TESTS(test_signed, OSSL_NELEM(signed_test_values));
ADD_ALL_TESTS(test_8values, OSSL_NELEM(test_values_8));
ADD_ALL_TESTS(test_32values, OSSL_NELEM(test_values_32));
ADD_ALL_TESTS(test_64values, OSSL_NELEM(test_values_64));
return 1;
}
| 12,635 | 29.448193 | 80 | c |
openssl | openssl-master/test/context_internal_test.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
*/
/* Internal tests for the OpenSSL library context */
#include "internal/cryptlib.h"
#include "testutil.h"
static int test_set0_default(void)
{
OSSL_LIB_CTX *global = OSSL_LIB_CTX_get0_global_default();
OSSL_LIB_CTX *local = OSSL_LIB_CTX_new();
OSSL_LIB_CTX *prev;
int testresult = 0;
if (!TEST_ptr(global)
|| !TEST_ptr(local)
|| !TEST_ptr_eq(global, OSSL_LIB_CTX_set0_default(NULL)))
goto err;
/* Check we can change the local default context */
if (!TEST_ptr(prev = OSSL_LIB_CTX_set0_default(local))
|| !TEST_ptr_eq(global, prev))
goto err;
/* Calling OSSL_LIB_CTX_set0_default() with a NULL should be a no-op */
if (!TEST_ptr_eq(local, OSSL_LIB_CTX_set0_default(NULL)))
goto err;
/* Global default should be unchanged */
if (!TEST_ptr_eq(global, OSSL_LIB_CTX_get0_global_default()))
goto err;
/* Check we can swap back to the global default */
if (!TEST_ptr(prev = OSSL_LIB_CTX_set0_default(global))
|| !TEST_ptr_eq(local, prev))
goto err;
testresult = 1;
err:
OSSL_LIB_CTX_free(local);
return testresult;
}
int setup_tests(void)
{
ADD_TEST(test_set0_default);
return 1;
}
| 1,582 | 27.267857 | 75 | c |
openssl | openssl-master/test/crltest.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
*/
#include "internal/nelem.h"
#include <string.h>
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include "testutil.h"
#define PARAM_TIME 1474934400 /* Sep 27th, 2016 */
static const char *kCRLTestRoot[] = {
"-----BEGIN CERTIFICATE-----\n",
"MIIDbzCCAlegAwIBAgIJAODri7v0dDUFMA0GCSqGSIb3DQEBCwUAME4xCzAJBgNV\n",
"BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBW\n",
"aWV3MRIwEAYDVQQKDAlCb3JpbmdTU0wwHhcNMTYwOTI2MTUwNjI2WhcNMjYwOTI0\n",
"MTUwNjI2WjBOMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQG\n",
"A1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJQm9yaW5nU1NMMIIBIjANBgkq\n",
"hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo16WiLWZuaymsD8n5SKPmxV1y6jjgr3B\n",
"S/dUBpbrzd1aeFzNlI8l2jfAnzUyp+I21RQ+nh/MhqjGElkTtK9xMn1Y+S9GMRh+\n",
"5R/Du0iCb1tCZIPY07Tgrb0KMNWe0v2QKVVruuYSgxIWodBfxlKO64Z8AJ5IbnWp\n",
"uRqO6rctN9qUoMlTIAB6dL4G0tDJ/PGFWOJYwOMEIX54bly2wgyYJVBKiRRt4f7n\n",
"8H922qmvPNA9idmX9G1VAtgV6x97XXi7ULORIQvn9lVQF6nTYDBJhyuPB+mLThbL\n",
"P2o9orxGx7aCtnnBZUIxUvHNOI0FaSaZH7Fi0xsZ/GkG2HZe7ImPJwIDAQABo1Aw\n",
"TjAdBgNVHQ4EFgQUWPt3N5cZ/CRvubbrkqfBnAqhq94wHwYDVR0jBBgwFoAUWPt3\n",
"N5cZ/CRvubbrkqfBnAqhq94wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\n",
"AQEAORu6M0MOwXy+3VEBwNilfTxyqDfruQsc1jA4PT8Oe8zora1WxE1JB4q2FJOz\n",
"EAuM3H/NXvEnBuN+ITvKZAJUfm4NKX97qmjMJwLKWe1gVv+VQTr63aR7mgWJReQN\n",
"XdMztlVeZs2dppV6uEg3ia1X0G7LARxGpA9ETbMyCpb39XxlYuTClcbA5ftDN99B\n",
"3Xg9KNdd++Ew22O3HWRDvdDpTO/JkzQfzi3sYwUtzMEonENhczJhGf7bQMmvL/w5\n",
"24Wxj4Z7KzzWIHsNqE/RIs6RV3fcW61j/mRgW2XyoWnMVeBzvcJr9NXp4VQYmFPw\n",
"amd8GKMZQvP0ufGnUn7D7uartA==\n",
"-----END CERTIFICATE-----\n",
NULL
};
static const char *kCRLTestLeaf[] = {
"-----BEGIN CERTIFICATE-----\n",
"MIIDkDCCAnigAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwTjELMAkGA1UEBhMCVVMx\n",
"EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxEjAQ\n",
"BgNVBAoMCUJvcmluZ1NTTDAeFw0xNjA5MjYxNTA4MzFaFw0xNzA5MjYxNTA4MzFa\n",
"MEsxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRIwEAYDVQQKDAlC\n",
"b3JpbmdTU0wxEzARBgNVBAMMCmJvcmluZy5zc2wwggEiMA0GCSqGSIb3DQEBAQUA\n",
"A4IBDwAwggEKAoIBAQDc5v1S1M0W+QWM+raWfO0LH8uvqEwuJQgODqMaGnSlWUx9\n",
"8iQcnWfjyPja3lWg9K62hSOFDuSyEkysKHDxijz5R93CfLcfnVXjWQDJe7EJTTDP\n",
"ozEvxN6RjAeYv7CF000euYr3QT5iyBjg76+bon1p0jHZBJeNPP1KqGYgyxp+hzpx\n",
"e0gZmTlGAXd8JQK4v8kpdYwD6PPifFL/jpmQpqOtQmH/6zcLjY4ojmqpEdBqIKIX\n",
"+saA29hMq0+NK3K+wgg31RU+cVWxu3tLOIiesETkeDgArjWRS1Vkzbi4v9SJxtNu\n",
"OZuAxWiynRJw3JwH/OFHYZIvQqz68ZBoj96cepjPAgMBAAGjezB5MAkGA1UdEwQC\n",
"MAAwLAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRl\n",
"MB0GA1UdDgQWBBTGn0OVVh/aoYt0bvEKG+PIERqnDzAfBgNVHSMEGDAWgBRY+3c3\n",
"lxn8JG+5tuuSp8GcCqGr3jANBgkqhkiG9w0BAQsFAAOCAQEAd2nM8gCQN2Dc8QJw\n",
"XSZXyuI3DBGGCHcay/3iXu0JvTC3EiQo8J6Djv7WLI0N5KH8mkm40u89fJAB2lLZ\n",
"ShuHVtcC182bOKnePgwp9CNwQ21p0rDEu/P3X46ZvFgdxx82E9xLa0tBB8PiPDWh\n",
"lV16jbaKTgX5AZqjnsyjR5o9/mbZVupZJXx5Syq+XA8qiJfstSYJs4KyKK9UOjql\n",
"ICkJVKpi2ahDBqX4MOH4SLfzVk8pqSpviS6yaA1RXqjpkxiN45WWaXDldVHMSkhC\n",
"5CNXsXi4b1nAntu89crwSLA3rEwzCWeYj+BX7e1T9rr3oJdwOU/2KQtW1js1yQUG\n",
"tjJMFw==\n",
"-----END CERTIFICATE-----\n",
NULL
};
static const char *kBasicCRL[] = {
"-----BEGIN X509 CRL-----\n",
"MIIBpzCBkAIBATANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJVUzETMBEGA1UE\n",
"CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJ\n",
"Qm9yaW5nU1NMFw0xNjA5MjYxNTEwNTVaFw0xNjEwMjYxNTEwNTVaoA4wDDAKBgNV\n",
"HRQEAwIBATANBgkqhkiG9w0BAQsFAAOCAQEAnrBKKgvd9x9zwK9rtUvVeFeJ7+LN\n",
"ZEAc+a5oxpPNEsJx6hXoApYEbzXMxuWBQoCs5iEBycSGudct21L+MVf27M38KrWo\n",
"eOkq0a2siqViQZO2Fb/SUFR0k9zb8xl86Zf65lgPplALun0bV/HT7MJcl04Tc4os\n",
"dsAReBs5nqTGNEd5AlC1iKHvQZkM//MD51DspKnDpsDiUVi54h9C1SpfZmX8H2Vv\n",
"diyu0fZ/bPAM3VAGawatf/SyWfBMyKpoPXEG39oAzmjjOj8en82psn7m474IGaho\n",
"/vBbhl1ms5qQiLYPjm4YELtnXQoFyC72tBjbdFd/ZE9k4CNKDbxFUXFbkw==\n",
"-----END X509 CRL-----\n",
NULL
};
static const char *kRevokedCRL[] = {
"-----BEGIN X509 CRL-----\n",
"MIIBvjCBpwIBATANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJVUzETMBEGA1UE\n",
"CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJ\n",
"Qm9yaW5nU1NMFw0xNjA5MjYxNTEyNDRaFw0xNjEwMjYxNTEyNDRaMBUwEwICEAAX\n",
"DTE2MDkyNjE1MTIyNlqgDjAMMAoGA1UdFAQDAgECMA0GCSqGSIb3DQEBCwUAA4IB\n",
"AQCUGaM4DcWzlQKrcZvI8TMeR8BpsvQeo5BoI/XZu2a8h//PyRyMwYeaOM+3zl0d\n",
"sjgCT8b3C1FPgT+P2Lkowv7rJ+FHJRNQkogr+RuqCSPTq65ha4WKlRGWkMFybzVH\n",
"NloxC+aU3lgp/NlX9yUtfqYmJek1CDrOOGPrAEAwj1l/BUeYKNGqfBWYJQtPJu+5\n",
"OaSvIYGpETCZJscUWODmLEb/O3DM438vLvxonwGqXqS0KX37+CHpUlyhnSovxXxp\n",
"Pz4aF+L7OtczxL0GYtD2fR9B7TDMqsNmHXgQrixvvOY7MUdLGbd4RfJL3yA53hyO\n",
"xzfKY2TzxLiOmctG0hXFkH5J\n",
"-----END X509 CRL-----\n",
NULL
};
static const char *kBadIssuerCRL[] = {
"-----BEGIN X509 CRL-----\n",
"MIIBwjCBqwIBATANBgkqhkiG9w0BAQsFADBSMQswCQYDVQQGEwJVUzETMBEGA1UE\n",
"CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEWMBQGA1UECgwN\n",
"Tm90IEJvcmluZ1NTTBcNMTYwOTI2MTUxMjQ0WhcNMTYxMDI2MTUxMjQ0WjAVMBMC\n",
"AhAAFw0xNjA5MjYxNTEyMjZaoA4wDDAKBgNVHRQEAwIBAjANBgkqhkiG9w0BAQsF\n",
"AAOCAQEAlBmjOA3Fs5UCq3GbyPEzHkfAabL0HqOQaCP12btmvIf/z8kcjMGHmjjP\n",
"t85dHbI4Ak/G9wtRT4E/j9i5KML+6yfhRyUTUJKIK/kbqgkj06uuYWuFipURlpDB\n",
"cm81RzZaMQvmlN5YKfzZV/clLX6mJiXpNQg6zjhj6wBAMI9ZfwVHmCjRqnwVmCUL\n",
"TybvuTmkryGBqREwmSbHFFjg5ixG/ztwzON/Ly78aJ8Bql6ktCl9+/gh6VJcoZ0q\n",
"L8V8aT8+Ghfi+zrXM8S9BmLQ9n0fQe0wzKrDZh14EK4sb7zmOzFHSxm3eEXyS98g\n",
"Od4cjsc3ymNk88S4jpnLRtIVxZB+SQ==\n",
"-----END X509 CRL-----\n",
NULL
};
/*
* This is kBasicCRL but with a critical issuing distribution point
* extension.
*/
static const char *kKnownCriticalCRL[] = {
"-----BEGIN X509 CRL-----\n",
"MIIBujCBowIBATANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJVUzETMBEGA1UE\n",
"CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJ\n",
"Qm9yaW5nU1NMFw0xNjA5MjYxNTEwNTVaFw0xNjEwMjYxNTEwNTVaoCEwHzAKBgNV\n",
"HRQEAwIBATARBgNVHRwBAf8EBzAFoQMBAf8wDQYJKoZIhvcNAQELBQADggEBAA+3\n",
"i+5e5Ub8sccfgOBs6WVJFI9c8gvJjrJ8/dYfFIAuCyeocs7DFXn1n13CRZ+URR/Q\n",
"mVWgU28+xeusuSPYFpd9cyYTcVyNUGNTI3lwgcE/yVjPaOmzSZKdPakApRxtpKKQ\n",
"NN/56aQz3bnT/ZSHQNciRB8U6jiD9V30t0w+FDTpGaG+7bzzUH3UVF9xf9Ctp60A\n",
"3mfLe0scas7owSt4AEFuj2SPvcE7yvdOXbu+IEv21cEJUVExJAbhvIweHXh6yRW+\n",
"7VVeiNzdIjkZjyTmAzoXGha4+wbxXyBRbfH+XWcO/H+8nwyG8Gktdu2QB9S9nnIp\n",
"o/1TpfOMSGhMyMoyPrk=\n",
"-----END X509 CRL-----\n",
NULL
};
/*
* kUnknownCriticalCRL is kBasicCRL but with an unknown critical extension.
*/
static const char *kUnknownCriticalCRL[] = {
"-----BEGIN X509 CRL-----\n",
"MIIBvDCBpQIBATANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJVUzETMBEGA1UE\n",
"CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJ\n",
"Qm9yaW5nU1NMFw0xNjA5MjYxNTEwNTVaFw0xNjEwMjYxNTEwNTVaoCMwITAKBgNV\n",
"HRQEAwIBATATBgwqhkiG9xIEAYS3CQABAf8EADANBgkqhkiG9w0BAQsFAAOCAQEA\n",
"GvBP0xqL509InMj/3493YVRV+ldTpBv5uTD6jewzf5XdaxEQ/VjTNe5zKnxbpAib\n",
"Kf7cwX0PMSkZjx7k7kKdDlEucwVvDoqC+O9aJcqVmM6GDyNb9xENxd0XCXja6MZC\n",
"yVgP4AwLauB2vSiEprYJyI1APph3iAEeDm60lTXX/wBM/tupQDDujKh2GPyvBRfJ\n",
"+wEDwGg3ICwvu4gO4zeC5qnFR+bpL9t5tOMAQnVZ0NWv+k7mkd2LbHdD44dxrfXC\n",
"nhtfERx99SDmC/jtUAJrGhtCO8acr7exCeYcduN7KKCm91OeCJKK6OzWst0Og1DB\n",
"kwzzU2rL3G65CrZ7H0SZsQ==\n",
"-----END X509 CRL-----\n",
NULL
};
/*
* kUnknownCriticalCRL2 is kBasicCRL but with a critical issuing distribution
* point extension followed by an unknown critical extension
*/
static const char *kUnknownCriticalCRL2[] = {
"-----BEGIN X509 CRL-----\n",
"MIIBzzCBuAIBATANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJVUzETMBEGA1UE\n",
"CAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzESMBAGA1UECgwJ\n",
"Qm9yaW5nU1NMFw0xNjA5MjYxNTEwNTVaFw0xNjEwMjYxNTEwNTVaoDYwNDAKBgNV\n",
"HRQEAwIBATARBgNVHRwBAf8EBzAFoQMBAf8wEwYMKoZIhvcSBAGEtwkAAQH/BAAw\n",
"DQYJKoZIhvcNAQELBQADggEBACTcpQC8jXL12JN5YzOcQ64ubQIe0XxRAd30p7qB\n",
"BTXGpgqBjrjxRfLms7EBYodEXB2oXMsDq3km0vT1MfYdsDD05S+SQ9CDsq/pUfaC\n",
"E2WNI5p8WircRnroYvbN2vkjlRbMd1+yNITohXYXCJwjEOAWOx3XIM10bwPYBv4R\n",
"rDobuLHoMgL3yHgMHmAkP7YpkBucNqeBV8cCdeAZLuhXFWi6yfr3r/X18yWbC/r2\n",
"2xXdkrSqXLFo7ToyP8YKTgiXpya4x6m53biEYwa2ULlas0igL6DK7wjYZX95Uy7H\n",
"GKljn9weIYiMPV/BzGymwfv2EW0preLwtyJNJPaxbdin6Jc=\n",
"-----END X509 CRL-----\n",
NULL
};
static const char **unknown_critical_crls[] = {
kUnknownCriticalCRL, kUnknownCriticalCRL2
};
static X509 *test_root = NULL;
static X509 *test_leaf = NULL;
/*
* Glue an array of strings together. Return a BIO and put the string
* into |*out| so we can free it.
*/
static BIO *glue2bio(const char **pem, char **out)
{
size_t s = 0;
*out = glue_strings(pem, &s);
return BIO_new_mem_buf(*out, s);
}
/*
* Create a CRL from an array of strings.
*/
static X509_CRL *CRL_from_strings(const char **pem)
{
X509_CRL *crl;
char *p;
BIO *b = glue2bio(pem, &p);
if (b == NULL) {
OPENSSL_free(p);
return NULL;
}
crl = PEM_read_bio_X509_CRL(b, NULL, NULL, NULL);
OPENSSL_free(p);
BIO_free(b);
return crl;
}
/*
* Create an X509 from an array of strings.
*/
static X509 *X509_from_strings(const char **pem)
{
X509 *x;
char *p;
BIO *b = glue2bio(pem, &p);
if (b == NULL) {
OPENSSL_free(p);
return NULL;
}
x = PEM_read_bio_X509(b, NULL, NULL, NULL);
OPENSSL_free(p);
BIO_free(b);
return x;
}
/*
* Verify |leaf| certificate (chained up to |root|). |crls| if
* not NULL, is a list of CRLs to include in the verification. It is
* also free'd before returning, which is kinda yucky but convenient.
* Returns a value from X509_V_ERR_xxx or X509_V_OK.
*/
static int verify(X509 *leaf, X509 *root, STACK_OF(X509_CRL) *crls,
unsigned long flags)
{
X509_STORE_CTX *ctx = X509_STORE_CTX_new();
X509_STORE *store = X509_STORE_new();
X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
STACK_OF(X509) *roots = sk_X509_new_null();
int status = X509_V_ERR_UNSPECIFIED;
if (!TEST_ptr(ctx)
|| !TEST_ptr(store)
|| !TEST_ptr(param)
|| !TEST_ptr(roots))
goto err;
/* Create a stack; upref the cert because we free it below. */
X509_up_ref(root);
if (!TEST_true(sk_X509_push(roots, root))
|| !TEST_true(X509_STORE_CTX_init(ctx, store, leaf, NULL)))
goto err;
X509_STORE_CTX_set0_trusted_stack(ctx, roots);
X509_STORE_CTX_set0_crls(ctx, crls);
X509_VERIFY_PARAM_set_time(param, PARAM_TIME);
if (!TEST_long_eq((long)X509_VERIFY_PARAM_get_time(param), PARAM_TIME))
goto err;
X509_VERIFY_PARAM_set_depth(param, 16);
if (flags)
X509_VERIFY_PARAM_set_flags(param, flags);
X509_STORE_CTX_set0_param(ctx, param);
param = NULL;
ERR_clear_error();
status = X509_verify_cert(ctx) == 1 ? X509_V_OK
: X509_STORE_CTX_get_error(ctx);
err:
OSSL_STACK_OF_X509_free(roots);
sk_X509_CRL_pop_free(crls, X509_CRL_free);
X509_VERIFY_PARAM_free(param);
X509_STORE_CTX_free(ctx);
X509_STORE_free(store);
return status;
}
/*
* Create a stack of CRL's. Upref each one because we call pop_free on
* the stack and need to keep the CRL's around until the test exits.
* Yes this crashes on malloc failure; it forces us to debug.
*/
static STACK_OF(X509_CRL) *make_CRL_stack(X509_CRL *x1, X509_CRL *x2)
{
STACK_OF(X509_CRL) *sk = sk_X509_CRL_new_null();
sk_X509_CRL_push(sk, x1);
X509_CRL_up_ref(x1);
if (x2 != NULL) {
sk_X509_CRL_push(sk, x2);
X509_CRL_up_ref(x2);
}
return sk;
}
static int test_basic_crl(void)
{
X509_CRL *basic_crl = CRL_from_strings(kBasicCRL);
X509_CRL *revoked_crl = CRL_from_strings(kRevokedCRL);
int r;
r = TEST_ptr(basic_crl)
&& TEST_ptr(revoked_crl)
&& TEST_int_eq(verify(test_leaf, test_root,
make_CRL_stack(basic_crl, NULL),
X509_V_FLAG_CRL_CHECK), X509_V_OK)
&& TEST_int_eq(verify(test_leaf, test_root,
make_CRL_stack(basic_crl, revoked_crl),
X509_V_FLAG_CRL_CHECK), X509_V_ERR_CERT_REVOKED);
X509_CRL_free(basic_crl);
X509_CRL_free(revoked_crl);
return r;
}
static int test_no_crl(void)
{
return TEST_int_eq(verify(test_leaf, test_root, NULL,
X509_V_FLAG_CRL_CHECK),
X509_V_ERR_UNABLE_TO_GET_CRL);
}
static int test_bad_issuer_crl(void)
{
X509_CRL *bad_issuer_crl = CRL_from_strings(kBadIssuerCRL);
int r;
r = TEST_ptr(bad_issuer_crl)
&& TEST_int_eq(verify(test_leaf, test_root,
make_CRL_stack(bad_issuer_crl, NULL),
X509_V_FLAG_CRL_CHECK),
X509_V_ERR_UNABLE_TO_GET_CRL);
X509_CRL_free(bad_issuer_crl);
return r;
}
static int test_known_critical_crl(void)
{
X509_CRL *known_critical_crl = CRL_from_strings(kKnownCriticalCRL);
int r;
r = TEST_ptr(known_critical_crl)
&& TEST_int_eq(verify(test_leaf, test_root,
make_CRL_stack(known_critical_crl, NULL),
X509_V_FLAG_CRL_CHECK), X509_V_OK);
X509_CRL_free(known_critical_crl);
return r;
}
static int test_unknown_critical_crl(int n)
{
X509_CRL *unknown_critical_crl = CRL_from_strings(unknown_critical_crls[n]);
int r;
r = TEST_ptr(unknown_critical_crl)
&& TEST_int_eq(verify(test_leaf, test_root,
make_CRL_stack(unknown_critical_crl, NULL),
X509_V_FLAG_CRL_CHECK),
X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION);
X509_CRL_free(unknown_critical_crl);
return r;
}
static int test_reuse_crl(void)
{
X509_CRL *reused_crl = CRL_from_strings(kBasicCRL);
char *p;
BIO *b = glue2bio(kRevokedCRL, &p);
if (b == NULL) {
OPENSSL_free(p);
X509_CRL_free(reused_crl);
return 0;
}
reused_crl = PEM_read_bio_X509_CRL(b, &reused_crl, NULL, NULL);
OPENSSL_free(p);
BIO_free(b);
X509_CRL_free(reused_crl);
return 1;
}
int setup_tests(void)
{
if (!TEST_ptr(test_root = X509_from_strings(kCRLTestRoot))
|| !TEST_ptr(test_leaf = X509_from_strings(kCRLTestLeaf)))
return 0;
ADD_TEST(test_no_crl);
ADD_TEST(test_basic_crl);
ADD_TEST(test_bad_issuer_crl);
ADD_TEST(test_known_critical_crl);
ADD_ALL_TESTS(test_unknown_critical_crl, OSSL_NELEM(unknown_critical_crls));
ADD_TEST(test_reuse_crl);
return 1;
}
void cleanup_tests(void)
{
X509_free(test_root);
X509_free(test_leaf);
}
| 15,309 | 35.980676 | 80 | c |
openssl | openssl-master/test/ct_test.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 <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/ct.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "testutil.h"
#include <openssl/crypto.h>
#ifndef OPENSSL_NO_CT
/* Used when declaring buffers to read text files into */
# define CT_TEST_MAX_FILE_SIZE 8096
static char *certs_dir = NULL;
static char *ct_dir = NULL;
typedef struct ct_test_fixture {
const char *test_case_name;
/* The current time in milliseconds */
uint64_t epoch_time_in_ms;
/* The CT log store to use during tests */
CTLOG_STORE* ctlog_store;
/* Set the following to test handling of SCTs in X509 certificates */
const char *certs_dir;
char *certificate_file;
char *issuer_file;
/* Expected number of SCTs */
int expected_sct_count;
/* Expected number of valid SCTS */
int expected_valid_sct_count;
/* Set the following to test handling of SCTs in TLS format */
const unsigned char *tls_sct_list;
size_t tls_sct_list_len;
STACK_OF(SCT) *sct_list;
/*
* A file to load the expected SCT text from.
* This text will be compared to the actual text output during the test.
* A maximum of |CT_TEST_MAX_FILE_SIZE| bytes will be read of this file.
*/
const char *sct_dir;
const char *sct_text_file;
/* Whether to test the validity of the SCT(s) */
int test_validity;
} CT_TEST_FIXTURE;
static CT_TEST_FIXTURE *set_up(const char *const test_case_name)
{
CT_TEST_FIXTURE *fixture = NULL;
if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture))))
goto end;
fixture->test_case_name = test_case_name;
fixture->epoch_time_in_ms = 1580335307000ULL; /* Wed 29 Jan 2020 10:01:47 PM UTC */
if (!TEST_ptr(fixture->ctlog_store = CTLOG_STORE_new())
|| !TEST_int_eq(
CTLOG_STORE_load_default_file(fixture->ctlog_store), 1))
goto end;
return fixture;
end:
if (fixture != NULL)
CTLOG_STORE_free(fixture->ctlog_store);
OPENSSL_free(fixture);
TEST_error("Failed to setup");
return NULL;
}
static void tear_down(CT_TEST_FIXTURE *fixture)
{
if (fixture != NULL) {
CTLOG_STORE_free(fixture->ctlog_store);
SCT_LIST_free(fixture->sct_list);
}
OPENSSL_free(fixture);
}
static X509 *load_pem_cert(const char *dir, const char *file)
{
X509 *cert = NULL;
char *file_path = test_mk_file_path(dir, file);
if (file_path != NULL) {
BIO *cert_io = BIO_new_file(file_path, "r");
if (cert_io != NULL)
cert = PEM_read_bio_X509(cert_io, NULL, NULL, NULL);
BIO_free(cert_io);
}
OPENSSL_free(file_path);
return cert;
}
static int read_text_file(const char *dir, const char *file,
char *buffer, int buffer_length)
{
int len = -1;
char *file_path = test_mk_file_path(dir, file);
if (file_path != NULL) {
BIO *file_io = BIO_new_file(file_path, "r");
if (file_io != NULL)
len = BIO_read(file_io, buffer, buffer_length);
BIO_free(file_io);
}
OPENSSL_free(file_path);
return len;
}
static int compare_sct_list_printout(STACK_OF(SCT) *sct,
const char *expected_output)
{
BIO *text_buffer = NULL;
char *actual_output = NULL;
int result = 0;
if (!TEST_ptr(text_buffer = BIO_new(BIO_s_mem())))
goto end;
SCT_LIST_print(sct, text_buffer, 0, "\n", NULL);
/* Append \0 because we're about to use the buffer contents as a string. */
if (!TEST_true(BIO_write(text_buffer, "\0", 1)))
goto end;
BIO_get_mem_data(text_buffer, &actual_output);
if (!TEST_str_eq(actual_output, expected_output))
goto end;
result = 1;
end:
BIO_free(text_buffer);
return result;
}
static int compare_extension_printout(X509_EXTENSION *extension,
const char *expected_output)
{
BIO *text_buffer = NULL;
char *actual_output = NULL;
int result = 0;
if (!TEST_ptr(text_buffer = BIO_new(BIO_s_mem()))
|| !TEST_true(X509V3_EXT_print(text_buffer, extension,
X509V3_EXT_DEFAULT, 0)))
goto end;
/* Append \n because it's easier to create files that end with one. */
if (!TEST_true(BIO_write(text_buffer, "\n", 1)))
goto end;
/* Append \0 because we're about to use the buffer contents as a string. */
if (!TEST_true(BIO_write(text_buffer, "\0", 1)))
goto end;
BIO_get_mem_data(text_buffer, &actual_output);
if (!TEST_str_eq(actual_output, expected_output))
goto end;
result = 1;
end:
BIO_free(text_buffer);
return result;
}
static int assert_validity(CT_TEST_FIXTURE *fixture, STACK_OF(SCT) *scts,
CT_POLICY_EVAL_CTX *policy_ctx)
{
int invalid_sct_count = 0;
int valid_sct_count = 0;
int i;
if (!TEST_int_ge(SCT_LIST_validate(scts, policy_ctx), 0))
return 0;
for (i = 0; i < sk_SCT_num(scts); ++i) {
SCT *sct_i = sk_SCT_value(scts, i);
switch (SCT_get_validation_status(sct_i)) {
case SCT_VALIDATION_STATUS_VALID:
++valid_sct_count;
break;
case SCT_VALIDATION_STATUS_INVALID:
++invalid_sct_count;
break;
case SCT_VALIDATION_STATUS_NOT_SET:
case SCT_VALIDATION_STATUS_UNKNOWN_LOG:
case SCT_VALIDATION_STATUS_UNVERIFIED:
case SCT_VALIDATION_STATUS_UNKNOWN_VERSION:
/* Ignore other validation statuses. */
break;
}
}
if (!TEST_int_eq(valid_sct_count, fixture->expected_valid_sct_count)) {
int unverified_sct_count = sk_SCT_num(scts) -
invalid_sct_count - valid_sct_count;
TEST_info("%d SCTs failed, %d SCTs unverified",
invalid_sct_count, unverified_sct_count);
return 0;
}
return 1;
}
static int execute_cert_test(CT_TEST_FIXTURE *fixture)
{
int success = 0;
X509 *cert = NULL, *issuer = NULL;
STACK_OF(SCT) *scts = NULL;
SCT *sct = NULL;
char expected_sct_text[CT_TEST_MAX_FILE_SIZE];
int sct_text_len = 0;
unsigned char *tls_sct_list = NULL;
size_t tls_sct_list_len = 0;
CT_POLICY_EVAL_CTX *ct_policy_ctx = CT_POLICY_EVAL_CTX_new();
if (fixture->sct_text_file != NULL) {
sct_text_len = read_text_file(fixture->sct_dir, fixture->sct_text_file,
expected_sct_text,
CT_TEST_MAX_FILE_SIZE - 1);
if (!TEST_int_ge(sct_text_len, 0))
goto end;
expected_sct_text[sct_text_len] = '\0';
}
CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE(
ct_policy_ctx, fixture->ctlog_store);
CT_POLICY_EVAL_CTX_set_time(ct_policy_ctx, fixture->epoch_time_in_ms);
if (fixture->certificate_file != NULL) {
int sct_extension_index;
int i;
X509_EXTENSION *sct_extension = NULL;
if (!TEST_ptr(cert = load_pem_cert(fixture->certs_dir,
fixture->certificate_file)))
goto end;
CT_POLICY_EVAL_CTX_set1_cert(ct_policy_ctx, cert);
if (fixture->issuer_file != NULL) {
if (!TEST_ptr(issuer = load_pem_cert(fixture->certs_dir,
fixture->issuer_file)))
goto end;
CT_POLICY_EVAL_CTX_set1_issuer(ct_policy_ctx, issuer);
}
sct_extension_index =
X509_get_ext_by_NID(cert, NID_ct_precert_scts, -1);
sct_extension = X509_get_ext(cert, sct_extension_index);
if (fixture->expected_sct_count > 0) {
if (!TEST_ptr(sct_extension))
goto end;
if (fixture->sct_text_file
&& !compare_extension_printout(sct_extension,
expected_sct_text))
goto end;
scts = X509V3_EXT_d2i(sct_extension);
for (i = 0; i < sk_SCT_num(scts); ++i) {
SCT *sct_i = sk_SCT_value(scts, i);
if (!TEST_int_eq(SCT_get_source(sct_i),
SCT_SOURCE_X509V3_EXTENSION)) {
goto end;
}
}
if (fixture->test_validity) {
if (!assert_validity(fixture, scts, ct_policy_ctx))
goto end;
}
} else if (!TEST_ptr_null(sct_extension)) {
goto end;
}
}
if (fixture->tls_sct_list != NULL) {
const unsigned char *p = fixture->tls_sct_list;
if (!TEST_ptr(o2i_SCT_LIST(&scts, &p, fixture->tls_sct_list_len)))
goto end;
if (fixture->test_validity && cert != NULL) {
if (!assert_validity(fixture, scts, ct_policy_ctx))
goto end;
}
if (fixture->sct_text_file
&& !compare_sct_list_printout(scts, expected_sct_text)) {
goto end;
}
tls_sct_list_len = i2o_SCT_LIST(scts, &tls_sct_list);
if (!TEST_mem_eq(fixture->tls_sct_list, fixture->tls_sct_list_len,
tls_sct_list, tls_sct_list_len))
goto end;
}
success = 1;
end:
X509_free(cert);
X509_free(issuer);
SCT_LIST_free(scts);
SCT_free(sct);
CT_POLICY_EVAL_CTX_free(ct_policy_ctx);
OPENSSL_free(tls_sct_list);
return success;
}
# define SETUP_CT_TEST_FIXTURE() SETUP_TEST_FIXTURE(CT_TEST_FIXTURE, set_up)
# define EXECUTE_CT_TEST() EXECUTE_TEST(execute_cert_test, tear_down)
static int test_no_scts_in_certificate(void)
{
SETUP_CT_TEST_FIXTURE();
fixture->certs_dir = certs_dir;
fixture->certificate_file = "leaf.pem";
fixture->issuer_file = "subinterCA.pem";
fixture->expected_sct_count = 0;
EXECUTE_CT_TEST();
return result;
}
static int test_one_sct_in_certificate(void)
{
SETUP_CT_TEST_FIXTURE();
fixture->certs_dir = certs_dir;
fixture->certificate_file = "embeddedSCTs1.pem";
fixture->issuer_file = "embeddedSCTs1_issuer.pem";
fixture->expected_sct_count = 1;
fixture->sct_dir = certs_dir;
fixture->sct_text_file = "embeddedSCTs1.sct";
EXECUTE_CT_TEST();
return result;
}
static int test_multiple_scts_in_certificate(void)
{
SETUP_CT_TEST_FIXTURE();
fixture->certs_dir = certs_dir;
fixture->certificate_file = "embeddedSCTs3.pem";
fixture->issuer_file = "embeddedSCTs3_issuer.pem";
fixture->expected_sct_count = 3;
fixture->sct_dir = certs_dir;
fixture->sct_text_file = "embeddedSCTs3.sct";
EXECUTE_CT_TEST();
return result;
}
static int test_verify_one_sct(void)
{
SETUP_CT_TEST_FIXTURE();
fixture->certs_dir = certs_dir;
fixture->certificate_file = "embeddedSCTs1.pem";
fixture->issuer_file = "embeddedSCTs1_issuer.pem";
fixture->expected_sct_count = fixture->expected_valid_sct_count = 1;
fixture->test_validity = 1;
EXECUTE_CT_TEST();
return result;
}
static int test_verify_multiple_scts(void)
{
SETUP_CT_TEST_FIXTURE();
fixture->certs_dir = certs_dir;
fixture->certificate_file = "embeddedSCTs3.pem";
fixture->issuer_file = "embeddedSCTs3_issuer.pem";
fixture->expected_sct_count = fixture->expected_valid_sct_count = 3;
fixture->test_validity = 1;
EXECUTE_CT_TEST();
return result;
}
static int test_verify_fails_for_future_sct(void)
{
SETUP_CT_TEST_FIXTURE();
fixture->epoch_time_in_ms = 1365094800000ULL; /* Apr 4 17:00:00 2013 GMT */
fixture->certs_dir = certs_dir;
fixture->certificate_file = "embeddedSCTs1.pem";
fixture->issuer_file = "embeddedSCTs1_issuer.pem";
fixture->expected_sct_count = 1;
fixture->expected_valid_sct_count = 0;
fixture->test_validity = 1;
EXECUTE_CT_TEST();
return result;
}
static int test_decode_tls_sct(void)
{
const unsigned char tls_sct_list[] = "\x00\x78" /* length of list */
"\x00\x76"
"\x00" /* version */
/* log ID */
"\xDF\x1C\x2E\xC1\x15\x00\x94\x52\x47\xA9\x61\x68\x32\x5D\xDC\x5C\x79"
"\x59\xE8\xF7\xC6\xD3\x88\xFC\x00\x2E\x0B\xBD\x3F\x74\xD7\x64"
"\x00\x00\x01\x3D\xDB\x27\xDF\x93" /* timestamp */
"\x00\x00" /* extensions length */
"" /* extensions */
"\x04\x03" /* hash and signature algorithms */
"\x00\x47" /* signature length */
/* signature */
"\x30\x45\x02\x20\x48\x2F\x67\x51\xAF\x35\xDB\xA6\x54\x36\xBE\x1F\xD6"
"\x64\x0F\x3D\xBF\x9A\x41\x42\x94\x95\x92\x45\x30\x28\x8F\xA3\xE5\xE2"
"\x3E\x06\x02\x21\x00\xE4\xED\xC0\xDB\x3A\xC5\x72\xB1\xE2\xF5\xE8\xAB"
"\x6A\x68\x06\x53\x98\x7D\xCF\x41\x02\x7D\xFE\xFF\xA1\x05\x51\x9D\x89"
"\xED\xBF\x08";
SETUP_CT_TEST_FIXTURE();
fixture->tls_sct_list = tls_sct_list;
fixture->tls_sct_list_len = 0x7a;
fixture->sct_dir = ct_dir;
fixture->sct_text_file = "tls1.sct";
EXECUTE_CT_TEST();
return result;
}
static int test_encode_tls_sct(void)
{
const char log_id[] = "3xwuwRUAlFJHqWFoMl3cXHlZ6PfG04j8AC4LvT9012Q=";
const uint64_t timestamp = 1;
const char extensions[] = "";
const char signature[] = "BAMARzBAMiBIL2dRrzXbplQ2vh/WZA89v5pBQpSVkkUwKI+j5"
"eI+BgIhAOTtwNs6xXKx4vXoq2poBlOYfc9BAn3+/6EFUZ2J7b8I";
SCT *sct = NULL;
SETUP_CT_TEST_FIXTURE();
fixture->sct_list = sk_SCT_new_null();
if (fixture->sct_list == NULL)
return 0;
if (!TEST_ptr(sct = SCT_new_from_base64(SCT_VERSION_V1, log_id,
CT_LOG_ENTRY_TYPE_X509, timestamp,
extensions, signature)))
return 0;
sk_SCT_push(fixture->sct_list, sct);
fixture->sct_dir = ct_dir;
fixture->sct_text_file = "tls1.sct";
EXECUTE_CT_TEST();
return result;
}
/*
* Tests that the CT_POLICY_EVAL_CTX default time is approximately now.
* Allow +-10 minutes, as it may compensate for clock skew.
*/
static int test_default_ct_policy_eval_ctx_time_is_now(void)
{
int success = 0;
CT_POLICY_EVAL_CTX *ct_policy_ctx = CT_POLICY_EVAL_CTX_new();
const time_t default_time =
(time_t)(CT_POLICY_EVAL_CTX_get_time(ct_policy_ctx) / 1000);
const time_t time_tolerance = 600; /* 10 minutes */
if (!TEST_time_t_le(abs((int)difftime(time(NULL), default_time)),
time_tolerance))
goto end;
success = 1;
end:
CT_POLICY_EVAL_CTX_free(ct_policy_ctx);
return success;
}
static int test_ctlog_from_base64(void)
{
CTLOG *ctlogp = NULL;
const char notb64[] = "\01\02\03\04";
const char pad[] = "====";
const char name[] = "name";
/* We expect these to both fail! */
if (!TEST_true(!CTLOG_new_from_base64(&ctlogp, notb64, name))
|| !TEST_true(!CTLOG_new_from_base64(&ctlogp, pad, name)))
return 0;
return 1;
}
#endif
int setup_tests(void)
{
#ifndef OPENSSL_NO_CT
if ((ct_dir = getenv("CT_DIR")) == NULL)
ct_dir = "ct";
if ((certs_dir = getenv("CERTS_DIR")) == NULL)
certs_dir = "certs";
ADD_TEST(test_no_scts_in_certificate);
ADD_TEST(test_one_sct_in_certificate);
ADD_TEST(test_multiple_scts_in_certificate);
ADD_TEST(test_verify_one_sct);
ADD_TEST(test_verify_multiple_scts);
ADD_TEST(test_verify_fails_for_future_sct);
ADD_TEST(test_decode_tls_sct);
ADD_TEST(test_encode_tls_sct);
ADD_TEST(test_default_ct_policy_eval_ctx_time_is_now);
ADD_TEST(test_ctlog_from_base64);
#else
printf("No CT support\n");
#endif
return 1;
}
| 16,129 | 29.549242 | 87 | c |
openssl | openssl-master/test/ctype_internal_test.c | /*
* Copyright 2017-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 "testutil.h"
#include "crypto/ctype.h"
#include "internal/nelem.h"
#include <ctype.h>
#include <stdio.h>
/*
* Even though the VMS C RTL claims to be C99 compatible, it's not entirely
* so far (C RTL version 8.4). Same applies to OSF. For the sake of these
* tests, we therefore define our own.
*/
#if (defined(__VMS) && __CRTL_VER <= 80400000) || defined(__osf__)
static int isblank(int c)
{
return c == ' ' || c == '\t';
}
#endif
static int test_ctype_chars(int n)
{
if (!TEST_int_eq(isascii((unsigned char)n) != 0, ossl_isascii(n) != 0))
return 0;
if (!ossl_isascii(n))
return 1;
return TEST_int_eq(isalpha(n) != 0, ossl_isalpha(n) != 0)
&& TEST_int_eq(isalnum(n) != 0, ossl_isalnum(n) != 0)
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
&& TEST_int_eq(isblank(n) != 0, ossl_isblank(n) != 0)
#endif
&& TEST_int_eq(iscntrl(n) != 0, ossl_iscntrl(n) != 0)
&& TEST_int_eq(isdigit(n) != 0, ossl_isdigit(n) != 0)
&& TEST_int_eq(isgraph(n) != 0, ossl_isgraph(n) != 0)
&& TEST_int_eq(islower(n) != 0, ossl_islower(n) != 0)
&& TEST_int_eq(isprint(n) != 0, ossl_isprint(n) != 0)
&& TEST_int_eq(ispunct(n) != 0, ossl_ispunct(n) != 0)
&& TEST_int_eq(isspace(n) != 0, ossl_isspace(n) != 0)
&& TEST_int_eq(isupper(n) != 0, ossl_isupper(n) != 0)
&& TEST_int_eq(isxdigit(n) != 0, ossl_isxdigit(n) != 0);
}
static struct {
int u;
int l;
} case_change[] = {
{ 'A', 'a' },
{ 'X', 'x' },
{ 'Z', 'z' },
{ '0', '0' },
{ '%', '%' },
{ '~', '~' },
{ 0, 0 },
{ EOF, EOF }
};
static int test_ctype_toupper(int n)
{
return TEST_int_eq(ossl_toupper(case_change[n].l), case_change[n].u)
&& TEST_int_eq(ossl_toupper(case_change[n].u), case_change[n].u);
}
static int test_ctype_tolower(int n)
{
return TEST_int_eq(ossl_tolower(case_change[n].u), case_change[n].l)
&& TEST_int_eq(ossl_tolower(case_change[n].l), case_change[n].l);
}
static int test_ctype_eof(void)
{
return test_ctype_chars(EOF);
}
int setup_tests(void)
{
ADD_ALL_TESTS(test_ctype_chars, 256);
ADD_ALL_TESTS(test_ctype_toupper, OSSL_NELEM(case_change));
ADD_ALL_TESTS(test_ctype_tolower, OSSL_NELEM(case_change));
ADD_TEST(test_ctype_eof);
return 1;
}
| 2,715 | 28.846154 | 76 | c |
openssl | openssl-master/test/d2i_test.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
*/
/* Regression tests for ASN.1 parsing bugs. */
#include <stdio.h>
#include <string.h>
#include "testutil.h"
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "internal/nelem.h"
static const ASN1_ITEM *item_type;
static const char *test_file;
typedef enum {
ASN1_UNKNOWN,
ASN1_OK,
ASN1_BIO,
ASN1_DECODE,
ASN1_ENCODE,
ASN1_COMPARE
} expected_error_t;
typedef struct {
const char *str;
expected_error_t code;
} error_enum;
static expected_error_t expected_error = ASN1_UNKNOWN;
static int test_bad_asn1(void)
{
BIO *bio = NULL;
ASN1_VALUE *value = NULL;
int ret = 0;
unsigned char buf[2048];
const unsigned char *buf_ptr = buf;
unsigned char *der = NULL;
int derlen;
int len;
bio = BIO_new_file(test_file, "r");
if (!TEST_ptr(bio))
return 0;
if (expected_error == ASN1_BIO) {
if (TEST_ptr_null(ASN1_item_d2i_bio(item_type, bio, NULL)))
ret = 1;
goto err;
}
/*
* Unless we are testing it we don't use ASN1_item_d2i_bio because it
* performs sanity checks on the input and can reject it before the
* decoder is called.
*/
len = BIO_read(bio, buf, sizeof(buf));
if (!TEST_int_ge(len, 0))
goto err;
value = ASN1_item_d2i(NULL, &buf_ptr, len, item_type);
if (value == NULL) {
if (TEST_int_eq(expected_error, ASN1_DECODE))
ret = 1;
goto err;
}
derlen = ASN1_item_i2d(value, &der, item_type);
if (der == NULL || derlen < 0) {
if (TEST_int_eq(expected_error, ASN1_ENCODE))
ret = 1;
goto err;
}
if (derlen != len || memcmp(der, buf, derlen) != 0) {
if (TEST_int_eq(expected_error, ASN1_COMPARE))
ret = 1;
goto err;
}
if (TEST_int_eq(expected_error, ASN1_OK))
ret = 1;
err:
/* Don't indicate success for memory allocation errors */
if (ret == 1
&& !TEST_false(ERR_GET_REASON(ERR_peek_error()) == ERR_R_MALLOC_FAILURE))
ret = 0;
BIO_free(bio);
OPENSSL_free(der);
ASN1_item_free(value, item_type);
return ret;
}
OPT_TEST_DECLARE_USAGE("item_name expected_error test_file.der\n")
/*
* Usage: d2i_test <name> <type> <file>, e.g.
* d2i_test generalname bad_generalname.der
*/
int setup_tests(void)
{
const char *test_type_name;
const char *expected_error_string;
size_t i;
static error_enum expected_errors[] = {
{"OK", ASN1_OK},
{"BIO", ASN1_BIO},
{"decode", ASN1_DECODE},
{"encode", ASN1_ENCODE},
{"compare", ASN1_COMPARE}
};
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
if (!TEST_ptr(test_type_name = test_get_argument(0))
|| !TEST_ptr(expected_error_string = test_get_argument(1))
|| !TEST_ptr(test_file = test_get_argument(2)))
return 0;
item_type = ASN1_ITEM_lookup(test_type_name);
if (item_type == NULL) {
TEST_error("Unknown type %s", test_type_name);
TEST_note("Supported types:");
for (i = 0;; i++) {
const ASN1_ITEM *it = ASN1_ITEM_get(i);
if (it == NULL)
break;
TEST_note("\t%s", it->sname);
}
return 0;
}
for (i = 0; i < OSSL_NELEM(expected_errors); i++) {
if (strcmp(expected_errors[i].str, expected_error_string) == 0) {
expected_error = expected_errors[i].code;
break;
}
}
if (expected_error == ASN1_UNKNOWN) {
TEST_error("Unknown expected error %s\n", expected_error_string);
return 0;
}
ADD_TEST(test_bad_asn1);
return 1;
}
| 4,185 | 23.623529 | 81 | c |
openssl | openssl-master/test/danetest.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 <string.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/conf.h>
#ifndef OPENSSL_NO_ENGINE
# include <openssl/engine.h>
#endif
#include "testutil.h"
#include "internal/nelem.h"
#define _UC(c) ((unsigned char)(c))
static const char *basedomain;
static const char *CAfile;
static const char *tlsafile;
/*
* Forward declaration, of function that uses internal interfaces, from headers
* included at the end of this module.
*/
static void store_ctx_dane_init(X509_STORE_CTX *, SSL *);
static int saved_errno;
static void save_errno(void)
{
saved_errno = errno;
}
static int restore_errno(void)
{
int ret = errno;
errno = saved_errno;
return ret;
}
static int verify_chain(SSL *ssl, STACK_OF(X509) *chain)
{
X509_STORE_CTX *store_ctx = NULL;
SSL_CTX *ssl_ctx = NULL;
X509_STORE *store = NULL;
int ret = 0;
int store_ctx_idx = SSL_get_ex_data_X509_STORE_CTX_idx();
if (!TEST_ptr(store_ctx = X509_STORE_CTX_new())
|| !TEST_ptr(ssl_ctx = SSL_get_SSL_CTX(ssl))
|| !TEST_ptr(store = SSL_CTX_get_cert_store(ssl_ctx))
|| !TEST_true(X509_STORE_CTX_init(store_ctx, store, NULL, chain))
|| !TEST_true(X509_STORE_CTX_set_ex_data(store_ctx, store_ctx_idx,
ssl)))
goto end;
X509_STORE_CTX_set_default(store_ctx, SSL_is_server(ssl)
? "ssl_client" : "ssl_server");
X509_VERIFY_PARAM_set1(X509_STORE_CTX_get0_param(store_ctx),
SSL_get0_param(ssl));
store_ctx_dane_init(store_ctx, ssl);
if (SSL_get_verify_callback(ssl) != NULL)
X509_STORE_CTX_set_verify_cb(store_ctx, SSL_get_verify_callback(ssl));
/* Mask "internal failures" (-1) from our return value. */
if (!TEST_int_ge(ret = X509_STORE_CTX_verify(store_ctx), 0))
ret = 0;
SSL_set_verify_result(ssl, X509_STORE_CTX_get_error(store_ctx));
end:
X509_STORE_CTX_free(store_ctx);
return ret;
}
static STACK_OF(X509) *load_chain(BIO *fp, int nelem)
{
int count;
char *name = 0;
char *header = 0;
unsigned char *data = 0;
long len;
char *errtype = 0; /* if error: cert or pkey? */
STACK_OF(X509) *chain;
typedef X509 *(*d2i_X509_t)(X509 **, const unsigned char **, long);
if (!TEST_ptr(chain = sk_X509_new_null()))
goto err;
for (count = 0;
count < nelem && errtype == 0
&& PEM_read_bio(fp, &name, &header, &data, &len) == 1;
++count) {
if (strcmp(name, PEM_STRING_X509) == 0
|| strcmp(name, PEM_STRING_X509_TRUSTED) == 0
|| strcmp(name, PEM_STRING_X509_OLD) == 0) {
d2i_X509_t d = strcmp(name, PEM_STRING_X509_TRUSTED) != 0
? d2i_X509_AUX : d2i_X509;
X509 *cert;
const unsigned char *p = data;
if (!TEST_ptr(cert = d(0, &p, len))
|| !TEST_long_eq(p - data, len)) {
TEST_info("Certificate parsing error");
goto err;
}
if (!TEST_true(sk_X509_push(chain, cert)))
goto err;
} else {
TEST_info("Unknown chain file object %s", name);
goto err;
}
OPENSSL_free(name);
OPENSSL_free(header);
OPENSSL_free(data);
name = header = NULL;
data = NULL;
}
if (count == nelem) {
ERR_clear_error();
return chain;
}
err:
OPENSSL_free(name);
OPENSSL_free(header);
OPENSSL_free(data);
OSSL_STACK_OF_X509_free(chain);
return NULL;
}
static char *read_to_eol(BIO *f)
{
static char buf[4096];
int n;
if (BIO_gets(f, buf, sizeof(buf)) <= 0)
return NULL;
n = strlen(buf);
if (buf[n - 1] != '\n') {
if (n + 1 == sizeof(buf))
TEST_error("input too long");
else
TEST_error("EOF before newline");
return NULL;
}
/* Trim trailing whitespace */
while (n > 0 && isspace(_UC(buf[n - 1])))
buf[--n] = '\0';
return buf;
}
/*
* Hex decoder that tolerates optional whitespace
*/
static ossl_ssize_t hexdecode(const char *in, void *result)
{
unsigned char **out = (unsigned char **)result;
unsigned char *ret;
unsigned char *cp;
uint8_t byte;
int nibble = 0;
if (!TEST_ptr(ret = OPENSSL_malloc(strlen(in) / 2)))
return -1;
cp = ret;
for (byte = 0; *in; ++in) {
int x;
if (isspace(_UC(*in)))
continue;
x = OPENSSL_hexchar2int(*in);
if (x < 0) {
OPENSSL_free(ret);
return 0;
}
byte |= (char)x;
if ((nibble ^= 1) == 0) {
*cp++ = byte;
byte = 0;
} else {
byte <<= 4;
}
}
if (nibble != 0) {
OPENSSL_free(ret);
return 0;
}
return cp - (*out = ret);
}
static ossl_ssize_t checked_uint8(const char *in, void *out)
{
uint8_t *result = (uint8_t *)out;
const char *cp = in;
char *endp;
long v;
int e;
save_errno();
v = strtol(cp, &endp, 10);
e = restore_errno();
if (((v == LONG_MIN || v == LONG_MAX) && e == ERANGE) ||
endp == cp || !isspace(_UC(*endp)) ||
v != (*(uint8_t *)result = (uint8_t) v)) {
return -1;
}
for (cp = endp; isspace(_UC(*cp)); ++cp)
continue;
return cp - in;
}
struct tlsa_field {
void *var;
const char *name;
ossl_ssize_t (*parser)(const char *, void *);
};
static int tlsa_import_rr(SSL *ssl, const char *rrdata)
{
static uint8_t usage;
static uint8_t selector;
static uint8_t mtype;
static unsigned char *data = NULL;
static struct tlsa_field tlsa_fields[] = {
{ &usage, "usage", checked_uint8 },
{ &selector, "selector", checked_uint8 },
{ &mtype, "mtype", checked_uint8 },
{ &data, "data", hexdecode },
{ NULL, }
};
int ret;
struct tlsa_field *f;
const char *cp = rrdata;
ossl_ssize_t len = 0;
for (f = tlsa_fields; f->var; ++f) {
if ((len = f->parser(cp += len, f->var)) <= 0) {
TEST_info("bad TLSA %s field in: %s", f->name, rrdata);
return 0;
}
}
ret = SSL_dane_tlsa_add(ssl, usage, selector, mtype, data, len);
OPENSSL_free(data);
if (ret == 0) {
TEST_info("unusable TLSA rrdata: %s", rrdata);
return 0;
}
if (ret < 0) {
TEST_info("error loading TLSA rrdata: %s", rrdata);
return 0;
}
return ret;
}
static int allws(const char *cp)
{
while (*cp)
if (!isspace(_UC(*cp++)))
return 0;
return 1;
}
static int test_tlsafile(SSL_CTX *ctx, const char *base_name,
BIO *f, const char *path)
{
char *line;
int testno = 0;
int ret = 1;
SSL *ssl;
while (ret > 0 && (line = read_to_eol(f)) != NULL) {
STACK_OF(X509) *chain;
int ntlsa;
int ncert;
int noncheck;
int want;
int want_depth;
int off;
int i;
int ok;
int err;
int mdpth;
if (*line == '\0' || *line == '#')
continue;
++testno;
if (sscanf(line, "%d %d %d %d %d%n",
&ntlsa, &ncert, &noncheck, &want, &want_depth, &off) != 5
|| !allws(line + off)) {
TEST_error("Malformed line for test %d", testno);
return 0;
}
if (!TEST_ptr(ssl = SSL_new(ctx)))
return 0;
SSL_set_connect_state(ssl);
if (SSL_dane_enable(ssl, base_name) <= 0) {
SSL_free(ssl);
return 0;
}
if (noncheck)
SSL_dane_set_flags(ssl, DANE_FLAG_NO_DANE_EE_NAMECHECKS);
for (i = 0; i < ntlsa; ++i) {
if ((line = read_to_eol(f)) == NULL || !tlsa_import_rr(ssl, line)) {
SSL_free(ssl);
return 0;
}
}
/* Don't report old news */
ERR_clear_error();
if (!TEST_ptr(chain = load_chain(f, ncert))) {
SSL_free(ssl);
return 0;
}
ok = verify_chain(ssl, chain);
OSSL_STACK_OF_X509_free(chain);
err = SSL_get_verify_result(ssl);
/*
* Peek under the hood, normally TLSA match data is hidden when
* verification fails, we can obtain any suppressed data by setting the
* verification result to X509_V_OK before looking.
*/
SSL_set_verify_result(ssl, X509_V_OK);
mdpth = SSL_get0_dane_authority(ssl, NULL, NULL);
/* Not needed any more, but lead by example and put the error back. */
SSL_set_verify_result(ssl, err);
SSL_free(ssl);
if (!TEST_int_eq(err, want)) {
if (want == X509_V_OK)
TEST_info("Verification failure in test %d: %d=%s",
testno, err, X509_verify_cert_error_string(err));
else
TEST_info("Unexpected error in test %d", testno);
ret = 0;
continue;
}
if (!TEST_false(want == 0 && ok == 0)) {
TEST_info("Verification failure in test %d: ok=0", testno);
ret = 0;
continue;
}
if (!TEST_int_eq(mdpth, want_depth)) {
TEST_info("In test test %d", testno);
ret = 0;
}
}
ERR_clear_error();
return ret;
}
static int run_tlsatest(void)
{
SSL_CTX *ctx = NULL;
BIO *f = NULL;
int ret = 0;
if (!TEST_ptr(f = BIO_new_file(tlsafile, "r"))
|| !TEST_ptr(ctx = SSL_CTX_new(TLS_client_method()))
|| !TEST_int_gt(SSL_CTX_dane_enable(ctx), 0)
|| !TEST_true(SSL_CTX_load_verify_file(ctx, CAfile))
|| !TEST_int_gt(SSL_CTX_dane_mtype_set(ctx, EVP_sha512(), 2, 1), 0)
|| !TEST_int_gt(SSL_CTX_dane_mtype_set(ctx, EVP_sha256(), 1, 2), 0)
|| !TEST_int_gt(test_tlsafile(ctx, basedomain, f, tlsafile), 0))
goto end;
ret = 1;
end:
BIO_free(f);
SSL_CTX_free(ctx);
return ret;
}
OPT_TEST_DECLARE_USAGE("basedomain CAfile tlsafile\n")
int setup_tests(void)
{
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
if (!TEST_ptr(basedomain = test_get_argument(0))
|| !TEST_ptr(CAfile = test_get_argument(1))
|| !TEST_ptr(tlsafile = test_get_argument(2)))
return 0;
ADD_TEST(run_tlsatest);
return 1;
}
#include "internal/dane.h"
static void store_ctx_dane_init(X509_STORE_CTX *store_ctx, SSL *ssl)
{
X509_STORE_CTX_set0_dane(store_ctx, SSL_get0_dane(ssl));
}
| 11,302 | 25.225058 | 80 | c |
openssl | openssl-master/test/defltfips_test.c | /*
* Copyright 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 <string.h>
#include <openssl/evp.h>
#include <openssl/provider.h>
#include "testutil.h"
static int is_fips;
static int bad_fips;
static int test_is_fips_enabled(void)
{
int is_fips_enabled, is_fips_loaded;
EVP_MD *sha256 = NULL;
/*
* Check we're in FIPS mode when we're supposed to be. We do this early to
* confirm that EVP_default_properties_is_fips_enabled() works even before
* other function calls have auto-loaded the config file.
*/
is_fips_enabled = EVP_default_properties_is_fips_enabled(NULL);
is_fips_loaded = OSSL_PROVIDER_available(NULL, "fips");
/*
* Check we're in an expected state. EVP_default_properties_is_fips_enabled
* can return true even if the FIPS provider isn't loaded - it is only based
* on the default properties. However we only set those properties if also
* loading the FIPS provider.
*/
if (!TEST_int_eq(is_fips || bad_fips, is_fips_enabled)
|| !TEST_int_eq(is_fips && !bad_fips, is_fips_loaded))
return 0;
/*
* Fetching an algorithm shouldn't change the state and should come from
* expected provider.
*/
sha256 = EVP_MD_fetch(NULL, "SHA2-256", NULL);
if (bad_fips) {
if (!TEST_ptr_null(sha256)) {
EVP_MD_free(sha256);
return 0;
}
} else {
if (!TEST_ptr(sha256))
return 0;
if (is_fips
&& !TEST_str_eq(OSSL_PROVIDER_get0_name(EVP_MD_get0_provider(sha256)),
"fips")) {
EVP_MD_free(sha256);
return 0;
}
EVP_MD_free(sha256);
}
/* State should still be consistent */
is_fips_enabled = EVP_default_properties_is_fips_enabled(NULL);
if (!TEST_int_eq(is_fips || bad_fips, is_fips_enabled))
return 0;
return 1;
}
int setup_tests(void)
{
size_t argc;
char *arg1;
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
argc = test_get_argument_count();
switch (argc) {
case 0:
is_fips = 0;
bad_fips = 0;
break;
case 1:
arg1 = test_get_argument(0);
if (strcmp(arg1, "fips") == 0) {
is_fips = 1;
bad_fips = 0;
break;
} else if (strcmp(arg1, "badfips") == 0) {
/* Configured for FIPS, but the module fails to load */
is_fips = 0;
bad_fips = 1;
break;
}
/* fall through */
default:
TEST_error("Invalid argument\n");
return 0;
}
/* Must be the first test before any other libcrypto calls are made */
ADD_TEST(test_is_fips_enabled);
return 1;
}
| 3,082 | 27.284404 | 82 | c |
openssl | openssl-master/test/dsa_no_digest_size_test.c | /*
* Copyright 2018-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
*/
/*
* DSA low level APIs are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include <stdlib.h>
#include <string.h>
#include "testutil.h"
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#ifndef OPENSSL_NO_DSA
#include <openssl/dsa.h>
static DSA *dsakey;
/*
* These parameters are from test/recipes/04-test_pem_data/dsaparam.pem,
* converted using dsaparam -C
*/
static DSA *load_dsa_params(void)
{
static unsigned char dsap_2048[] = {
0xAE, 0x35, 0x7D, 0x4E, 0x1D, 0x96, 0xE2, 0x9F, 0x00, 0x96,
0x60, 0x5A, 0x6E, 0x4D, 0x07, 0x8D, 0xA5, 0x7C, 0xBC, 0xF9,
0xAD, 0xD7, 0x9F, 0xD5, 0xE9, 0xEE, 0xA6, 0x33, 0x51, 0xDE,
0x7B, 0x72, 0xD2, 0x75, 0xAA, 0x71, 0x77, 0xF1, 0x63, 0xFB,
0xB6, 0xEC, 0x5A, 0xBA, 0x0D, 0x72, 0xA2, 0x1A, 0x1C, 0x64,
0xB8, 0xE5, 0x89, 0x09, 0x6D, 0xC9, 0x6F, 0x0B, 0x7F, 0xD2,
0xCE, 0x9F, 0xEF, 0x87, 0x5A, 0xB6, 0x67, 0x2F, 0xEF, 0xEE,
0xEB, 0x59, 0xF5, 0x5E, 0xFF, 0xA8, 0x28, 0x84, 0x9E, 0x5B,
0x37, 0x09, 0x11, 0x80, 0x7C, 0x08, 0x5C, 0xD5, 0xE1, 0x48,
0x4B, 0xD2, 0x68, 0xFB, 0x3F, 0x9F, 0x2B, 0x6B, 0x6C, 0x0D,
0x48, 0x1B, 0x1A, 0x80, 0xC2, 0xEB, 0x11, 0x1B, 0x37, 0x79,
0xD6, 0x8C, 0x8B, 0x72, 0x3E, 0x67, 0xA5, 0x05, 0x0E, 0x41,
0x8A, 0x9E, 0x35, 0x50, 0xB4, 0xD2, 0x40, 0x27, 0x6B, 0xFD,
0xE0, 0x64, 0x6B, 0x5B, 0x38, 0x42, 0x94, 0xB5, 0x49, 0xDA,
0xEF, 0x6E, 0x78, 0x37, 0xCD, 0x30, 0x89, 0xC3, 0x45, 0x50,
0x7B, 0x9C, 0x8C, 0xE7, 0x1C, 0x98, 0x70, 0x71, 0x5D, 0x79,
0x5F, 0xEF, 0xE8, 0x94, 0x85, 0x53, 0x3E, 0xEF, 0xA3, 0x2C,
0xCE, 0x1A, 0xAB, 0x7D, 0xD6, 0x5E, 0x14, 0xCD, 0x51, 0x54,
0x89, 0x9D, 0x77, 0xE4, 0xF8, 0x22, 0xF0, 0x35, 0x10, 0x75,
0x05, 0x71, 0x51, 0x4F, 0x8C, 0x4C, 0x5C, 0x0D, 0x2C, 0x2C,
0xBE, 0x6C, 0x34, 0xEE, 0x12, 0x82, 0x87, 0x03, 0x19, 0x06,
0x12, 0xA8, 0xAA, 0xF4, 0x0D, 0x3C, 0x49, 0xCC, 0x70, 0x5A,
0xD8, 0x32, 0xEE, 0x32, 0x50, 0x85, 0x70, 0xE8, 0x18, 0xFD,
0x74, 0x80, 0x53, 0x32, 0x57, 0xEE, 0x50, 0xC9, 0xAE, 0xEB,
0xAE, 0xB6, 0x22, 0x32, 0x16, 0x6B, 0x8C, 0x59, 0xDA, 0xEE,
0x1D, 0x33, 0xDF, 0x4C, 0xA2, 0x3D
};
static unsigned char dsaq_2048[] = {
0xAD, 0x2D, 0x6E, 0x17, 0xB0, 0xF3, 0xEB, 0xC7, 0xB8, 0xEE,
0x95, 0x78, 0xF2, 0x17, 0xF5, 0x33, 0x01, 0x67, 0xBC, 0xDE,
0x93, 0xFF, 0xEE, 0x40, 0xE8, 0x7F, 0xF1, 0x93, 0x6D, 0x4B,
0x87, 0x13
};
static unsigned char dsag_2048[] = {
0x66, 0x6F, 0xDA, 0x63, 0xA5, 0x8E, 0xD2, 0x4C, 0xD5, 0x45,
0x2D, 0x76, 0x5D, 0x5F, 0xCD, 0x4A, 0xB4, 0x1A, 0x42, 0x35,
0x86, 0x3A, 0x6F, 0xA9, 0xFA, 0x27, 0xAB, 0xDE, 0x03, 0x21,
0x36, 0x0A, 0x07, 0x29, 0xC9, 0x2F, 0x6D, 0x49, 0xA8, 0xF7,
0xC6, 0xF4, 0x92, 0xD7, 0x73, 0xC1, 0xD8, 0x76, 0x0E, 0x61,
0xA7, 0x0B, 0x6E, 0x96, 0xB8, 0xC8, 0xCB, 0x38, 0x35, 0x12,
0x20, 0x79, 0xA5, 0x08, 0x28, 0x35, 0x5C, 0xBC, 0x52, 0x16,
0xAF, 0x52, 0xBA, 0x0F, 0xC3, 0xB1, 0x63, 0x12, 0x27, 0x0B,
0x74, 0xA4, 0x47, 0x43, 0xD6, 0x30, 0xB8, 0x9C, 0x2E, 0x40,
0x14, 0xCD, 0x99, 0x7F, 0xE8, 0x8E, 0x37, 0xB0, 0xA9, 0x3F,
0x54, 0xE9, 0x66, 0x22, 0x61, 0x4C, 0xF8, 0x49, 0x03, 0x57,
0x14, 0x32, 0x1D, 0x37, 0x3D, 0xE2, 0x92, 0xF8, 0x8E, 0xA0,
0x6A, 0x66, 0x63, 0xF0, 0xB0, 0x6E, 0x07, 0x2B, 0x3D, 0xBF,
0xD0, 0x84, 0x6A, 0xAA, 0x1F, 0x30, 0x77, 0x65, 0xE5, 0xFC,
0xF5, 0xEC, 0x55, 0xCE, 0x73, 0xDB, 0xBE, 0xA7, 0x8D, 0x3A,
0x9F, 0x7A, 0xED, 0x4F, 0xAF, 0xA2, 0x80, 0x4C, 0x30, 0x9E,
0x28, 0x49, 0x65, 0x40, 0xF0, 0x03, 0x45, 0x56, 0x99, 0xA2,
0x93, 0x1B, 0x9C, 0x46, 0xDE, 0xBD, 0xA8, 0xAB, 0x5F, 0x90,
0x3F, 0xB7, 0x3F, 0xD4, 0x6F, 0x8D, 0x5A, 0x30, 0xE1, 0xD4,
0x63, 0x3A, 0x6A, 0x7C, 0x8F, 0x24, 0xFC, 0xD9, 0x14, 0x28,
0x09, 0xE4, 0x84, 0x4E, 0x17, 0x43, 0x56, 0xB8, 0xD4, 0x4B,
0xA2, 0x29, 0x45, 0xD3, 0x13, 0xF0, 0xC2, 0x76, 0x9B, 0x01,
0xA0, 0x80, 0x6E, 0x93, 0x63, 0x5E, 0x87, 0x24, 0x20, 0x2A,
0xFF, 0xBB, 0x9F, 0xA8, 0x99, 0x6C, 0xA7, 0x9A, 0x00, 0xB9,
0x7D, 0xDA, 0x66, 0xC9, 0xC0, 0x72, 0x72, 0x22, 0x0F, 0x1A,
0xCC, 0x23, 0xD9, 0xB7, 0x5F, 0x1B
};
DSA *dsa = DSA_new();
BIGNUM *p, *q, *g;
if (dsa == NULL)
return NULL;
if (!DSA_set0_pqg(dsa, p = BN_bin2bn(dsap_2048, sizeof(dsap_2048), NULL),
q = BN_bin2bn(dsaq_2048, sizeof(dsaq_2048), NULL),
g = BN_bin2bn(dsag_2048, sizeof(dsag_2048), NULL))) {
DSA_free(dsa);
BN_free(p);
BN_free(q);
BN_free(g);
return NULL;
}
return dsa;
}
static int genkeys(void)
{
if (!TEST_ptr(dsakey = load_dsa_params()))
return 0;
if (!TEST_int_eq(DSA_generate_key(dsakey), 1))
return 0;
return 1;
}
static int sign_and_verify(int len)
{
/*
* Per FIPS 186-4, the hash is recommended to be the same length as q.
* If the hash is longer than q, the leftmost N bits are used; if the hash
* is shorter, then we left-pad (see appendix C.2.1).
*/
size_t sigLength;
int digestlen = BN_num_bytes(DSA_get0_q(dsakey));
int ok = 0;
unsigned char *dataToSign = OPENSSL_malloc(len);
unsigned char *paddedData = OPENSSL_malloc(digestlen);
unsigned char *signature = NULL;
EVP_PKEY_CTX *ctx = NULL;
EVP_PKEY *pkey = NULL;
if (!TEST_ptr(dataToSign) ||
!TEST_ptr(paddedData) ||
!TEST_int_eq(RAND_bytes(dataToSign, len), 1))
goto end;
memset(paddedData, 0, digestlen);
if (len > digestlen)
memcpy(paddedData, dataToSign, digestlen);
else
memcpy(paddedData + digestlen - len, dataToSign, len);
if (!TEST_ptr(pkey = EVP_PKEY_new()))
goto end;
EVP_PKEY_set1_DSA(pkey, dsakey);
if (!TEST_ptr(ctx = EVP_PKEY_CTX_new(pkey, NULL)))
goto end;
if (!TEST_int_eq(EVP_PKEY_sign_init(ctx), 1))
goto end;
if (EVP_PKEY_sign(ctx, NULL, &sigLength, dataToSign, len) != 1) {
TEST_error("Failed to get signature length, len=%d", len);
goto end;
}
if (!TEST_ptr(signature = OPENSSL_malloc(sigLength)))
goto end;
if (EVP_PKEY_sign(ctx, signature, &sigLength, dataToSign, len) != 1) {
TEST_error("Failed to sign, len=%d", len);
goto end;
}
/* Check that the signature is okay via the EVP interface */
if (!TEST_int_eq(EVP_PKEY_verify_init(ctx), 1))
goto end;
/* ... using the same data we just signed */
if (EVP_PKEY_verify(ctx, signature, sigLength, dataToSign, len) != 1) {
TEST_error("EVP verify with unpadded length %d failed\n", len);
goto end;
}
/* ... padding/truncating the data to the appropriate digest size */
if (EVP_PKEY_verify(ctx, signature, sigLength, paddedData, digestlen) != 1) {
TEST_error("EVP verify with length %d failed\n", len);
goto end;
}
/* Verify again using the raw DSA interface */
if (DSA_verify(0, dataToSign, len, signature, sigLength, dsakey) != 1) {
TEST_error("Verification with unpadded data failed, len=%d", len);
goto end;
}
if (DSA_verify(0, paddedData, digestlen, signature, sigLength, dsakey) != 1) {
TEST_error("verify with length %d failed\n", len);
goto end;
}
ok = 1;
end:
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
OPENSSL_free(signature);
OPENSSL_free(paddedData);
OPENSSL_free(dataToSign);
return ok;
}
static int dsa_exact_size_test(void) {
/*
* For a 2048-bit p, q should be either 224 or 256 bits per the table in
* FIPS 186-4 4.2.
*/
return sign_and_verify(224 / 8) && sign_and_verify(256 / 8);
}
static int dsa_small_digest_test(void) {
return sign_and_verify(16) && sign_and_verify(1);
}
static int dsa_large_digest_test(void) {
return sign_and_verify(33) && sign_and_verify(64);
}
void cleanup_tests(void)
{
DSA_free(dsakey);
}
#endif /* OPENSSL_NO_DSA */
int setup_tests(void)
{
#ifndef OPENSSL_NO_DSA
if (!genkeys())
return 0;
ADD_TEST(dsa_exact_size_test);
ADD_TEST(dsa_small_digest_test);
ADD_TEST(dsa_large_digest_test);
#endif
return 1;
}
| 8,730 | 33.646825 | 82 | c |
openssl | openssl-master/test/dsatest.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
*/
/*
* DSA low level APIs are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <openssl/bn.h>
#include <openssl/dsa.h>
#include <openssl/evp.h>
#include <openssl/core_names.h>
#include "testutil.h"
#include "internal/nelem.h"
#ifndef OPENSSL_NO_DSA
static int dsa_cb(int p, int n, BN_GENCB *arg);
static unsigned char out_p[] = {
0x8d, 0xf2, 0xa4, 0x94, 0x49, 0x22, 0x76, 0xaa,
0x3d, 0x25, 0x75, 0x9b, 0xb0, 0x68, 0x69, 0xcb,
0xea, 0xc0, 0xd8, 0x3a, 0xfb, 0x8d, 0x0c, 0xf7,
0xcb, 0xb8, 0x32, 0x4f, 0x0d, 0x78, 0x82, 0xe5,
0xd0, 0x76, 0x2f, 0xc5, 0xb7, 0x21, 0x0e, 0xaf,
0xc2, 0xe9, 0xad, 0xac, 0x32, 0xab, 0x7a, 0xac,
0x49, 0x69, 0x3d, 0xfb, 0xf8, 0x37, 0x24, 0xc2,
0xec, 0x07, 0x36, 0xee, 0x31, 0xc8, 0x02, 0x91,
};
static unsigned char out_q[] = {
0xc7, 0x73, 0x21, 0x8c, 0x73, 0x7e, 0xc8, 0xee,
0x99, 0x3b, 0x4f, 0x2d, 0xed, 0x30, 0xf4, 0x8e,
0xda, 0xce, 0x91, 0x5f,
};
static unsigned char out_g[] = {
0x62, 0x6d, 0x02, 0x78, 0x39, 0xea, 0x0a, 0x13,
0x41, 0x31, 0x63, 0xa5, 0x5b, 0x4c, 0xb5, 0x00,
0x29, 0x9d, 0x55, 0x22, 0x95, 0x6c, 0xef, 0xcb,
0x3b, 0xff, 0x10, 0xf3, 0x99, 0xce, 0x2c, 0x2e,
0x71, 0xcb, 0x9d, 0xe5, 0xfa, 0x24, 0xba, 0xbf,
0x58, 0xe5, 0xb7, 0x95, 0x21, 0x92, 0x5c, 0x9c,
0xc4, 0x2e, 0x9f, 0x6f, 0x46, 0x4b, 0x08, 0x8c,
0xc5, 0x72, 0xaf, 0x53, 0xe6, 0xd7, 0x88, 0x02,
};
static int dsa_test(void)
{
BN_GENCB *cb;
DSA *dsa = NULL;
int counter, ret = 0, i, j;
unsigned char buf[256];
unsigned long h;
unsigned char sig[256];
unsigned int siglen;
const BIGNUM *p = NULL, *q = NULL, *g = NULL;
/*
* seed, out_p, out_q, out_g are taken from the updated Appendix 5 to FIPS
* PUB 186 and also appear in Appendix 5 to FIPS PIB 186-1
*/
static unsigned char seed[20] = {
0xd5, 0x01, 0x4e, 0x4b, 0x60, 0xef, 0x2b, 0xa8,
0xb6, 0x21, 0x1b, 0x40, 0x62, 0xba, 0x32, 0x24,
0xe0, 0x42, 0x7d, 0xd3,
};
static const unsigned char str1[] = "12345678901234567890";
if (!TEST_ptr(cb = BN_GENCB_new()))
goto end;
BN_GENCB_set(cb, dsa_cb, NULL);
if (!TEST_ptr(dsa = DSA_new())
|| !TEST_true(DSA_generate_parameters_ex(dsa, 512, seed, 20,
&counter, &h, cb)))
goto end;
if (!TEST_int_eq(counter, 105))
goto end;
if (!TEST_int_eq(h, 2))
goto end;
DSA_get0_pqg(dsa, &p, &q, &g);
i = BN_bn2bin(q, buf);
j = sizeof(out_q);
if (!TEST_int_eq(i, j) || !TEST_mem_eq(buf, i, out_q, i))
goto end;
i = BN_bn2bin(p, buf);
j = sizeof(out_p);
if (!TEST_int_eq(i, j) || !TEST_mem_eq(buf, i, out_p, i))
goto end;
i = BN_bn2bin(g, buf);
j = sizeof(out_g);
if (!TEST_int_eq(i, j) || !TEST_mem_eq(buf, i, out_g, i))
goto end;
if (!TEST_true(DSA_generate_key(dsa)))
goto end;
if (!TEST_true(DSA_sign(0, str1, 20, sig, &siglen, dsa)))
goto end;
if (TEST_int_gt(DSA_verify(0, str1, 20, sig, siglen, dsa), 0))
ret = 1;
end:
DSA_free(dsa);
BN_GENCB_free(cb);
return ret;
}
static int dsa_cb(int p, int n, BN_GENCB *arg)
{
static int ok = 0, num = 0;
if (p == 0)
num++;
if (p == 2)
ok++;
if (!ok && (p == 0) && (num > 1)) {
TEST_error("dsa_cb error");
return 0;
}
return 1;
}
# define P 0
# define Q 1
# define G 2
# define SEED 3
# define PCOUNT 4
# define GINDEX 5
# define HCOUNT 6
# define GROUP 7
static int dsa_keygen_test(void)
{
int ret = 0;
EVP_PKEY *param_key = NULL, *key = NULL;
EVP_PKEY_CTX *pg_ctx = NULL, *kg_ctx = NULL;
BIGNUM *p_in = NULL, *q_in = NULL, *g_in = NULL;
BIGNUM *p_out = NULL, *q_out = NULL, *g_out = NULL;
int gindex_out = 0, pcount_out = 0, hcount_out = 0;
unsigned char seed_out[32];
char group_out[32];
size_t len = 0;
const OSSL_PARAM *settables = NULL;
static const unsigned char seed_data[] = {
0xa6, 0xf5, 0x28, 0x8c, 0x50, 0x77, 0xa5, 0x68,
0x6d, 0x3a, 0xf5, 0xf1, 0xc6, 0x4c, 0xdc, 0x35,
0x95, 0x26, 0x3f, 0x03, 0xdc, 0x00, 0x3f, 0x44,
0x7b, 0x2a, 0xc7, 0x29
};
static const unsigned char expected_p[]= {
0xdb, 0x47, 0x07, 0xaf, 0xf0, 0x06, 0x49, 0x55,
0xc9, 0xbb, 0x09, 0x41, 0xb8, 0xdb, 0x1f, 0xbc,
0xa8, 0xed, 0x12, 0x06, 0x7f, 0x88, 0x49, 0xb8,
0xc9, 0x12, 0x87, 0x21, 0xbb, 0x08, 0x6c, 0xbd,
0xf1, 0x89, 0xef, 0x84, 0xd9, 0x7a, 0x93, 0xe8,
0x45, 0x40, 0x81, 0xec, 0x37, 0x27, 0x1a, 0xa4,
0x22, 0x51, 0x99, 0xf0, 0xde, 0x04, 0xdb, 0xea,
0xa1, 0xf9, 0x37, 0x83, 0x80, 0x96, 0x36, 0x53,
0xf6, 0xae, 0x14, 0x73, 0x33, 0x0f, 0xdf, 0x0b,
0xf9, 0x2f, 0x08, 0x46, 0x31, 0xf9, 0x66, 0xcd,
0x5a, 0xeb, 0x6c, 0xf3, 0xbb, 0x74, 0xf3, 0x88,
0xf0, 0x31, 0x5c, 0xa4, 0xc8, 0x0f, 0x86, 0xf3,
0x0f, 0x9f, 0xc0, 0x8c, 0x57, 0xe4, 0x7f, 0x95,
0xb3, 0x62, 0xc8, 0x4e, 0xae, 0xf3, 0xd8, 0x14,
0xcc, 0x47, 0xc2, 0x4b, 0x4f, 0xef, 0xaf, 0xcd,
0xcf, 0xb2, 0xbb, 0xe8, 0xbe, 0x08, 0xca, 0x15,
0x90, 0x59, 0x35, 0xef, 0x35, 0x1c, 0xfe, 0xeb,
0x33, 0x2e, 0x25, 0x22, 0x57, 0x9c, 0x55, 0x23,
0x0c, 0x6f, 0xed, 0x7c, 0xb6, 0xc7, 0x36, 0x0b,
0xcb, 0x2b, 0x6a, 0x21, 0xa1, 0x1d, 0x55, 0x77,
0xd9, 0x91, 0xcd, 0xc1, 0xcd, 0x3d, 0x82, 0x16,
0x9c, 0xa0, 0x13, 0xa5, 0x83, 0x55, 0x3a, 0x73,
0x7e, 0x2c, 0x44, 0x3e, 0x70, 0x2e, 0x50, 0x91,
0x6e, 0xca, 0x3b, 0xef, 0xff, 0x85, 0x35, 0x70,
0xff, 0x61, 0x0c, 0xb1, 0xb2, 0xb7, 0x94, 0x6f,
0x65, 0xa4, 0x57, 0x62, 0xef, 0x21, 0x83, 0x0f,
0x3e, 0x71, 0xae, 0x7d, 0xe4, 0xad, 0xfb, 0xe3,
0xdd, 0xd6, 0x03, 0xda, 0x9a, 0xd8, 0x8f, 0x2d,
0xbb, 0x90, 0x87, 0xf8, 0xdb, 0xdc, 0xec, 0x71,
0xf2, 0xdb, 0x0b, 0x8e, 0xfc, 0x1a, 0x7e, 0x79,
0xb1, 0x1b, 0x0d, 0xfc, 0x70, 0xec, 0x85, 0xc2,
0xc5, 0xba, 0xb9, 0x69, 0x3f, 0x88, 0xbc, 0xcb
};
static const unsigned char expected_q[]= {
0x99, 0xb6, 0xa0, 0xee, 0xb3, 0xa6, 0x99, 0x1a,
0xb6, 0x67, 0x8d, 0xc1, 0x2b, 0x9b, 0xce, 0x2b,
0x01, 0x72, 0x5a, 0x65, 0x76, 0x3d, 0x93, 0x69,
0xe2, 0x56, 0xae, 0xd7
};
static const unsigned char expected_g[]= {
0x63, 0xf8, 0xb6, 0xee, 0x2a, 0x27, 0xaf, 0x4f,
0x4c, 0xf6, 0x08, 0x28, 0x87, 0x4a, 0xe7, 0x1f,
0x45, 0x46, 0x27, 0x52, 0x3b, 0x7f, 0x6f, 0xd2,
0x29, 0xcb, 0xe8, 0x11, 0x19, 0x25, 0x35, 0x76,
0x99, 0xcb, 0x4f, 0x1b, 0xe0, 0xed, 0x32, 0x9e,
0x05, 0xb5, 0xbe, 0xd7, 0xf6, 0x5a, 0xb2, 0xf6,
0x0e, 0x0c, 0x7e, 0xf5, 0xe1, 0x05, 0xfe, 0xda,
0xaf, 0x0f, 0x27, 0x1e, 0x40, 0x2a, 0xf7, 0xa7,
0x23, 0x49, 0x2c, 0xd9, 0x1b, 0x0a, 0xbe, 0xff,
0xc7, 0x7c, 0x7d, 0x60, 0xca, 0xa3, 0x19, 0xc3,
0xb7, 0xe4, 0x43, 0xb0, 0xf5, 0x75, 0x44, 0x90,
0x46, 0x47, 0xb1, 0xa6, 0x48, 0x0b, 0x21, 0x8e,
0xee, 0x75, 0xe6, 0x3d, 0xa7, 0xd3, 0x7b, 0x31,
0xd1, 0xd2, 0x9d, 0xe2, 0x8a, 0xfc, 0x57, 0xfd,
0x8a, 0x10, 0x31, 0xeb, 0x87, 0x36, 0x3f, 0x65,
0x72, 0x23, 0x2c, 0xd3, 0xd6, 0x17, 0xa5, 0x62,
0x58, 0x65, 0x57, 0x6a, 0xd4, 0xa8, 0xfe, 0xec,
0x57, 0x76, 0x0c, 0xb1, 0x4c, 0x93, 0xed, 0xb0,
0xb4, 0xf9, 0x45, 0xb3, 0x3e, 0xdd, 0x47, 0xf1,
0xfb, 0x7d, 0x25, 0x79, 0x3d, 0xfc, 0xa7, 0x39,
0x90, 0x68, 0x6a, 0x6b, 0xae, 0xf2, 0x6e, 0x64,
0x8c, 0xfb, 0xb8, 0xdd, 0x76, 0x4e, 0x4a, 0x69,
0x8c, 0x97, 0x15, 0x77, 0xb2, 0x67, 0xdc, 0xeb,
0x4a, 0x40, 0x6b, 0xb9, 0x47, 0x8f, 0xa6, 0xab,
0x6e, 0x98, 0xc0, 0x97, 0x9a, 0x0c, 0xea, 0x00,
0xfd, 0x56, 0x1a, 0x74, 0x9a, 0x32, 0x6b, 0xfe,
0xbd, 0xdf, 0x6c, 0x82, 0x54, 0x53, 0x4d, 0x70,
0x65, 0xe3, 0x8b, 0x37, 0xb8, 0xe4, 0x70, 0x08,
0xb7, 0x3b, 0x30, 0x27, 0xaf, 0x1c, 0x77, 0xf3,
0x62, 0xd4, 0x9a, 0x59, 0xba, 0xd1, 0x6e, 0x89,
0x5c, 0x34, 0x9a, 0xa1, 0xb7, 0x4f, 0x7d, 0x8c,
0xdc, 0xbc, 0x74, 0x25, 0x5e, 0xbf, 0x77, 0x46
};
int expected_c = 1316;
int expected_h = 2;
if (!TEST_ptr(p_in = BN_bin2bn(expected_p, sizeof(expected_p), NULL))
|| !TEST_ptr(q_in = BN_bin2bn(expected_q, sizeof(expected_q), NULL))
|| !TEST_ptr(g_in = BN_bin2bn(expected_g, sizeof(expected_g), NULL)))
goto end;
if (!TEST_ptr(pg_ctx = EVP_PKEY_CTX_new_from_name(NULL, "DSA", NULL))
|| !TEST_int_gt(EVP_PKEY_paramgen_init(pg_ctx), 0)
|| !TEST_ptr_null(EVP_PKEY_CTX_gettable_params(pg_ctx))
|| !TEST_ptr(settables = EVP_PKEY_CTX_settable_params(pg_ctx))
|| !TEST_ptr(OSSL_PARAM_locate_const(settables,
OSSL_PKEY_PARAM_FFC_PBITS))
|| !TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_type(pg_ctx, "fips186_4"))
|| !TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_bits(pg_ctx, 2048))
|| !TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_q_bits(pg_ctx, 224))
|| !TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_seed(pg_ctx, seed_data,
sizeof(seed_data)))
|| !TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_md_props(pg_ctx, "SHA256",
""))
|| !TEST_int_gt(EVP_PKEY_generate(pg_ctx, ¶m_key), 0)
|| !TEST_ptr(kg_ctx = EVP_PKEY_CTX_new_from_pkey(NULL, param_key, NULL))
|| !TEST_int_gt(EVP_PKEY_keygen_init(kg_ctx), 0)
|| !TEST_int_gt(EVP_PKEY_generate(kg_ctx, &key), 0))
goto end;
if (!TEST_true(EVP_PKEY_get_bn_param(key, OSSL_PKEY_PARAM_FFC_P, &p_out))
|| !TEST_BN_eq(p_in, p_out)
|| !TEST_true(EVP_PKEY_get_bn_param(key, OSSL_PKEY_PARAM_FFC_Q, &q_out))
|| !TEST_BN_eq(q_in, q_out)
|| !TEST_true(EVP_PKEY_get_bn_param(key, OSSL_PKEY_PARAM_FFC_G, &g_out))
|| !TEST_BN_eq(g_in, g_out)
|| !TEST_true(EVP_PKEY_get_octet_string_param(
key, OSSL_PKEY_PARAM_FFC_SEED, seed_out,
sizeof(seed_out), &len))
|| !TEST_mem_eq(seed_out, len, seed_data, sizeof(seed_data))
|| !TEST_true(EVP_PKEY_get_int_param(key, OSSL_PKEY_PARAM_FFC_GINDEX,
&gindex_out))
|| !TEST_int_eq(gindex_out, -1)
|| !TEST_true(EVP_PKEY_get_int_param(key, OSSL_PKEY_PARAM_FFC_H,
&hcount_out))
|| !TEST_int_eq(hcount_out, expected_h)
|| !TEST_true(EVP_PKEY_get_int_param(key,
OSSL_PKEY_PARAM_FFC_PCOUNTER,
&pcount_out))
|| !TEST_int_eq(pcount_out, expected_c)
|| !TEST_false(EVP_PKEY_get_utf8_string_param(key,
OSSL_PKEY_PARAM_GROUP_NAME,
group_out,
sizeof(group_out), &len)))
goto end;
ret = 1;
end:
BN_free(p_in);
BN_free(q_in);
BN_free(g_in);
BN_free(p_out);
BN_free(q_out);
BN_free(g_out);
EVP_PKEY_free(param_key);
EVP_PKEY_free(key);
EVP_PKEY_CTX_free(kg_ctx);
EVP_PKEY_CTX_free(pg_ctx);
return ret;
}
static int test_dsa_default_paramgen_validate(int i)
{
int ret;
EVP_PKEY_CTX *gen_ctx = NULL;
EVP_PKEY_CTX *check_ctx = NULL;
EVP_PKEY *params = NULL;
ret = TEST_ptr(gen_ctx = EVP_PKEY_CTX_new_from_name(NULL, "DSA", NULL))
&& TEST_int_gt(EVP_PKEY_paramgen_init(gen_ctx), 0)
&& (i == 0
|| TEST_true(EVP_PKEY_CTX_set_dsa_paramgen_bits(gen_ctx, 512)))
&& TEST_int_gt(EVP_PKEY_generate(gen_ctx, ¶ms), 0)
&& TEST_ptr(check_ctx = EVP_PKEY_CTX_new_from_pkey(NULL, params, NULL))
&& TEST_int_gt(EVP_PKEY_param_check(check_ctx), 0);
EVP_PKEY_free(params);
EVP_PKEY_CTX_free(check_ctx);
EVP_PKEY_CTX_free(gen_ctx);
return ret;
}
static int test_dsa_sig_infinite_loop(void)
{
int ret = 0;
DSA *dsa = NULL;
BIGNUM *p = NULL, *q = NULL, *g = NULL, *priv = NULL, *pub = NULL, *priv2 = NULL;
BIGNUM *badq = NULL, *badpriv = NULL;
const unsigned char msg[] = { 0x00 };
unsigned int signature_len;
unsigned char signature[64];
static unsigned char out_priv[] = {
0x17, 0x00, 0xb2, 0x8d, 0xcb, 0x24, 0xc9, 0x98,
0xd0, 0x7f, 0x1f, 0x83, 0x1a, 0xa1, 0xc4, 0xa4,
0xf8, 0x0f, 0x7f, 0x12
};
static unsigned char out_pub[] = {
0x04, 0x72, 0xee, 0x8d, 0xaa, 0x4d, 0x89, 0x60,
0x0e, 0xb2, 0xd4, 0x38, 0x84, 0xa2, 0x2a, 0x60,
0x5f, 0x67, 0xd7, 0x9e, 0x24, 0xdd, 0xe8, 0x50,
0xf2, 0x23, 0x71, 0x55, 0x53, 0x94, 0x0d, 0x6b,
0x2e, 0xcd, 0x30, 0xda, 0x6f, 0x1e, 0x2c, 0xcf,
0x59, 0xbe, 0x05, 0x6c, 0x07, 0x0e, 0xc6, 0x38,
0x05, 0xcb, 0x0c, 0x44, 0x0a, 0x08, 0x13, 0xb6,
0x0f, 0x14, 0xde, 0x4a, 0xf6, 0xed, 0x4e, 0xc3
};
if (!TEST_ptr(p = BN_bin2bn(out_p, sizeof(out_p), NULL))
|| !TEST_ptr(q = BN_bin2bn(out_q, sizeof(out_q), NULL))
|| !TEST_ptr(g = BN_bin2bn(out_g, sizeof(out_g), NULL))
|| !TEST_ptr(pub = BN_bin2bn(out_pub, sizeof(out_pub), NULL))
|| !TEST_ptr(priv = BN_bin2bn(out_priv, sizeof(out_priv), NULL))
|| !TEST_ptr(priv2 = BN_dup(priv))
|| !TEST_ptr(badq = BN_new())
|| !TEST_true(BN_set_word(badq, 1))
|| !TEST_ptr(badpriv = BN_new())
|| !TEST_true(BN_set_word(badpriv, 0))
|| !TEST_ptr(dsa = DSA_new()))
goto err;
if (!TEST_true(DSA_set0_pqg(dsa, p, q, g)))
goto err;
p = q = g = NULL;
if (!TEST_true(DSA_set0_key(dsa, pub, priv)))
goto err;
pub = priv = NULL;
if (!TEST_int_le(DSA_size(dsa), sizeof(signature)))
goto err;
/* Test passing signature as NULL */
if (!TEST_true(DSA_sign(0, msg, sizeof(msg), NULL, &signature_len, dsa)))
goto err;
if (!TEST_true(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa)))
goto err;
/* Test using a private key of zero fails - this causes an infinite loop without the retry test */
if (!TEST_true(DSA_set0_key(dsa, NULL, badpriv)))
goto err;
badpriv = NULL;
if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa)))
goto err;
/* Restore private and set a bad q - this caused an infinite loop in the setup */
if (!TEST_true(DSA_set0_key(dsa, NULL, priv2)))
goto err;
priv2 = NULL;
if (!TEST_true(DSA_set0_pqg(dsa, NULL, badq, NULL)))
goto err;
badq = NULL;
if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa)))
goto err;
ret = 1;
err:
BN_free(badq);
BN_free(badpriv);
BN_free(pub);
BN_free(priv);
BN_free(priv2);
BN_free(g);
BN_free(q);
BN_free(p);
DSA_free(dsa);
return ret;
}
static int test_dsa_sig_neg_param(void)
{
int ret = 0, setpqg = 0;
DSA *dsa = NULL;
BIGNUM *p = NULL, *q = NULL, *g = NULL, *priv = NULL, *pub = NULL;
const unsigned char msg[] = { 0x00 };
unsigned int signature_len;
unsigned char signature[64];
static unsigned char out_priv[] = {
0x17, 0x00, 0xb2, 0x8d, 0xcb, 0x24, 0xc9, 0x98,
0xd0, 0x7f, 0x1f, 0x83, 0x1a, 0xa1, 0xc4, 0xa4,
0xf8, 0x0f, 0x7f, 0x12
};
static unsigned char out_pub[] = {
0x04, 0x72, 0xee, 0x8d, 0xaa, 0x4d, 0x89, 0x60,
0x0e, 0xb2, 0xd4, 0x38, 0x84, 0xa2, 0x2a, 0x60,
0x5f, 0x67, 0xd7, 0x9e, 0x24, 0xdd, 0xe8, 0x50,
0xf2, 0x23, 0x71, 0x55, 0x53, 0x94, 0x0d, 0x6b,
0x2e, 0xcd, 0x30, 0xda, 0x6f, 0x1e, 0x2c, 0xcf,
0x59, 0xbe, 0x05, 0x6c, 0x07, 0x0e, 0xc6, 0x38,
0x05, 0xcb, 0x0c, 0x44, 0x0a, 0x08, 0x13, 0xb6,
0x0f, 0x14, 0xde, 0x4a, 0xf6, 0xed, 0x4e, 0xc3
};
if (!TEST_ptr(p = BN_bin2bn(out_p, sizeof(out_p), NULL))
|| !TEST_ptr(q = BN_bin2bn(out_q, sizeof(out_q), NULL))
|| !TEST_ptr(g = BN_bin2bn(out_g, sizeof(out_g), NULL))
|| !TEST_ptr(pub = BN_bin2bn(out_pub, sizeof(out_pub), NULL))
|| !TEST_ptr(priv = BN_bin2bn(out_priv, sizeof(out_priv), NULL))
|| !TEST_ptr(dsa = DSA_new()))
goto err;
if (!TEST_true(DSA_set0_pqg(dsa, p, q, g)))
goto err;
setpqg = 1;
if (!TEST_true(DSA_set0_key(dsa, pub, priv)))
goto err;
pub = priv = NULL;
BN_set_negative(p, 1);
if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa)))
goto err;
BN_set_negative(p, 0);
BN_set_negative(q, 1);
if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa)))
goto err;
BN_set_negative(q, 0);
BN_set_negative(g, 1);
if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa)))
goto err;
BN_set_negative(p, 1);
BN_set_negative(q, 1);
BN_set_negative(g, 1);
if (!TEST_false(DSA_sign(0, msg, sizeof(msg), signature, &signature_len, dsa)))
goto err;
ret = 1;
err:
BN_free(pub);
BN_free(priv);
if (setpqg == 0) {
BN_free(g);
BN_free(q);
BN_free(p);
}
DSA_free(dsa);
return ret;
}
#endif /* OPENSSL_NO_DSA */
int setup_tests(void)
{
#ifndef OPENSSL_NO_DSA
ADD_TEST(dsa_test);
ADD_TEST(dsa_keygen_test);
ADD_TEST(test_dsa_sig_infinite_loop);
ADD_TEST(test_dsa_sig_neg_param);
ADD_ALL_TESTS(test_dsa_default_paramgen_validate, 2);
#endif
return 1;
}
| 18,300 | 35.456175 | 102 | c |
openssl | openssl-master/test/dtls_mtu_test.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 <string.h>
#include <openssl/dtls1.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include "helpers/ssltestlib.h"
#include "testutil.h"
/* for SSL_READ_ETM() */
#include "../ssl/ssl_local.h"
static int debug = 0;
static unsigned int clnt_psk_callback(SSL *ssl, const char *hint,
char *ident, unsigned int max_ident_len,
unsigned char *psk,
unsigned int max_psk_len)
{
BIO_snprintf(ident, max_ident_len, "psk");
if (max_psk_len > 20)
max_psk_len = 20;
memset(psk, 0x5a, max_psk_len);
return max_psk_len;
}
static unsigned int srvr_psk_callback(SSL *ssl, const char *identity,
unsigned char *psk,
unsigned int max_psk_len)
{
if (max_psk_len > 20)
max_psk_len = 20;
memset(psk, 0x5a, max_psk_len);
return max_psk_len;
}
static int mtu_test(SSL_CTX *ctx, const char *cs, int no_etm)
{
SSL *srvr_ssl = NULL, *clnt_ssl = NULL;
BIO *sc_bio = NULL;
int i;
size_t s;
size_t mtus[30];
unsigned char buf[600];
int rv = 0;
SSL_CONNECTION *clnt_sc;
memset(buf, 0x5a, sizeof(buf));
if (!TEST_true(create_ssl_objects(ctx, ctx, &srvr_ssl, &clnt_ssl,
NULL, NULL)))
goto end;
if (no_etm)
SSL_set_options(srvr_ssl, SSL_OP_NO_ENCRYPT_THEN_MAC);
if (!TEST_true(SSL_set_cipher_list(srvr_ssl, cs))
|| !TEST_true(SSL_set_cipher_list(clnt_ssl, cs))
|| !TEST_ptr(sc_bio = SSL_get_rbio(srvr_ssl))
|| !TEST_true(create_ssl_connection(clnt_ssl, srvr_ssl,
SSL_ERROR_NONE)))
goto end;
if (debug)
TEST_info("Channel established");
/* For record MTU values between 500 and 539, call DTLS_get_data_mtu()
* to query the payload MTU which will fit. */
for (i = 0; i < 30; i++) {
SSL_set_mtu(clnt_ssl, 500 + i);
mtus[i] = DTLS_get_data_mtu(clnt_ssl);
if (debug)
TEST_info("%s%s MTU for record mtu %d = %lu",
cs, no_etm ? "-noEtM" : "",
500 + i, (unsigned long)mtus[i]);
if (!TEST_size_t_ne(mtus[i], 0)) {
TEST_info("Cipher %s MTU %d", cs, 500 + i);
goto end;
}
}
/* Now get out of the way */
SSL_set_mtu(clnt_ssl, 1000);
/*
* Now for all values in the range of payload MTUs, send a payload of
* that size and see what actual record size we end up with.
*/
for (s = mtus[0]; s <= mtus[29]; s++) {
size_t reclen;
if (!TEST_int_eq(SSL_write(clnt_ssl, buf, s), (int)s))
goto end;
reclen = BIO_read(sc_bio, buf, sizeof(buf));
if (debug)
TEST_info("record %zu for payload %zu", reclen, s);
for (i = 0; i < 30; i++) {
/* DTLS_get_data_mtu() with record MTU 500+i returned mtus[i] ... */
if (!TEST_false(s <= mtus[i] && reclen > (size_t)(500 + i))) {
/*
* We sent a packet smaller than or equal to mtus[j] and
* that made a record *larger* than the record MTU 500+j!
*/
TEST_error("%s: s=%lu, mtus[i]=%lu, reclen=%lu, i=%d",
cs, (unsigned long)s, (unsigned long)mtus[i],
(unsigned long)reclen, 500 + i);
goto end;
}
if (!TEST_false(s > mtus[i] && reclen <= (size_t)(500 + i))) {
/*
* We sent a *larger* packet than mtus[i] and that *still*
* fits within the record MTU 500+i, so DTLS_get_data_mtu()
* was overly pessimistic.
*/
TEST_error("%s: s=%lu, mtus[i]=%lu, reclen=%lu, i=%d",
cs, (unsigned long)s, (unsigned long)mtus[i],
(unsigned long)reclen, 500 + i);
goto end;
}
}
}
if (!TEST_ptr(clnt_sc = SSL_CONNECTION_FROM_SSL_ONLY(clnt_ssl)))
goto end;
rv = 1;
if (SSL_READ_ETM(clnt_sc))
rv = 2;
end:
SSL_free(clnt_ssl);
SSL_free(srvr_ssl);
return rv;
}
static int run_mtu_tests(void)
{
SSL_CTX *ctx = NULL;
STACK_OF(SSL_CIPHER) *ciphers;
int i, ret = 0;
if (!TEST_ptr(ctx = SSL_CTX_new(DTLS_method())))
goto end;
SSL_CTX_set_psk_server_callback(ctx, srvr_psk_callback);
SSL_CTX_set_psk_client_callback(ctx, clnt_psk_callback);
SSL_CTX_set_security_level(ctx, 0);
/*
* We only care about iterating over each enc/mac; we don't want to
* repeat the test for each auth/kx variant. So keep life simple and
* only do (non-DH) PSK.
*/
if (!TEST_true(SSL_CTX_set_cipher_list(ctx, "PSK")))
goto end;
ciphers = SSL_CTX_get_ciphers(ctx);
for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(ciphers, i);
const char *cipher_name = SSL_CIPHER_get_name(cipher);
/* As noted above, only one test for each enc/mac variant. */
if (!HAS_PREFIX(cipher_name, "PSK-"))
continue;
if (!TEST_int_gt(ret = mtu_test(ctx, cipher_name, 0), 0))
break;
TEST_info("%s OK", cipher_name);
if (ret == 1)
continue;
/* mtu_test() returns 2 if it used Encrypt-then-MAC */
if (!TEST_int_gt(ret = mtu_test(ctx, cipher_name, 1), 0))
break;
TEST_info("%s without EtM OK", cipher_name);
}
end:
SSL_CTX_free(ctx);
return ret;
}
static int test_server_mtu_larger_than_max_fragment_length(void)
{
SSL_CTX *ctx = NULL;
SSL *srvr_ssl = NULL, *clnt_ssl = NULL;
int rv = 0;
if (!TEST_ptr(ctx = SSL_CTX_new(DTLS_method())))
goto end;
SSL_CTX_set_psk_server_callback(ctx, srvr_psk_callback);
SSL_CTX_set_psk_client_callback(ctx, clnt_psk_callback);
#ifndef OPENSSL_NO_DH
if (!TEST_true(SSL_CTX_set_dh_auto(ctx, 1)))
goto end;
#endif
if (!TEST_true(create_ssl_objects(ctx, ctx, &srvr_ssl, &clnt_ssl,
NULL, NULL)))
goto end;
SSL_set_options(srvr_ssl, SSL_OP_NO_QUERY_MTU);
if (!TEST_true(DTLS_set_link_mtu(srvr_ssl, 1500)))
goto end;
SSL_set_tlsext_max_fragment_length(clnt_ssl,
TLSEXT_max_fragment_length_512);
if (!TEST_true(create_ssl_connection(srvr_ssl, clnt_ssl,
SSL_ERROR_NONE)))
goto end;
rv = 1;
end:
SSL_free(clnt_ssl);
SSL_free(srvr_ssl);
SSL_CTX_free(ctx);
return rv;
}
int setup_tests(void)
{
ADD_TEST(run_mtu_tests);
ADD_TEST(test_server_mtu_larger_than_max_fragment_length);
return 1;
}
void cleanup_tests(void)
{
bio_s_mempacket_test_free();
}
| 7,392 | 29.052846 | 80 | c |
openssl | openssl-master/test/dtlstest.c | /*
* Copyright 2016-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 <string.h>
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include "helpers/ssltestlib.h"
#include "testutil.h"
static char *cert = NULL;
static char *privkey = NULL;
static unsigned int timer_cb_count;
#define NUM_TESTS 2
#define DUMMY_CERT_STATUS_LEN 12
static unsigned char certstatus[] = {
SSL3_RT_HANDSHAKE, /* Content type */
0xfe, 0xfd, /* Record version */
0, 1, /* Epoch */
0, 0, 0, 0, 0, 0x0f, /* Record sequence number */
0, DTLS1_HM_HEADER_LENGTH + DUMMY_CERT_STATUS_LEN - 2,
SSL3_MT_CERTIFICATE_STATUS, /* Cert Status handshake message type */
0, 0, DUMMY_CERT_STATUS_LEN, /* Message len */
0, 5, /* Message sequence */
0, 0, 0, /* Fragment offset */
0, 0, DUMMY_CERT_STATUS_LEN - 2, /* Fragment len */
0x80, 0x80, 0x80, 0x80, 0x80,
0x80, 0x80, 0x80, 0x80, 0x80 /* Dummy data */
};
#define RECORD_SEQUENCE 10
static const char dummy_cookie[] = "0123456";
static int generate_cookie_cb(SSL *ssl, unsigned char *cookie,
unsigned int *cookie_len)
{
memcpy(cookie, dummy_cookie, sizeof(dummy_cookie));
*cookie_len = sizeof(dummy_cookie);
return 1;
}
static int verify_cookie_cb(SSL *ssl, const unsigned char *cookie,
unsigned int cookie_len)
{
return TEST_mem_eq(cookie, cookie_len, dummy_cookie, sizeof(dummy_cookie));
}
static unsigned int timer_cb(SSL *s, unsigned int timer_us)
{
++timer_cb_count;
if (timer_us == 0)
return 50000;
else
return 2 * timer_us;
}
static int test_dtls_unprocessed(int testidx)
{
SSL_CTX *sctx = NULL, *cctx = NULL;
SSL *serverssl1 = NULL, *clientssl1 = NULL;
BIO *c_to_s_fbio, *c_to_s_mempacket;
int testresult = 0;
timer_cb_count = 0;
if (!TEST_true(create_ssl_ctx_pair(NULL, DTLS_server_method(),
DTLS_client_method(),
DTLS1_VERSION, 0,
&sctx, &cctx, cert, privkey)))
return 0;
#ifndef OPENSSL_NO_DTLS1_2
if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES128-SHA")))
goto end;
#else
/* Default sigalgs are SHA1 based in <DTLS1.2 which is in security level 0 */
if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "AES128-SHA:@SECLEVEL=0"))
|| !TEST_true(SSL_CTX_set_cipher_list(cctx,
"AES128-SHA:@SECLEVEL=0")))
goto end;
#endif
c_to_s_fbio = BIO_new(bio_f_tls_dump_filter());
if (!TEST_ptr(c_to_s_fbio))
goto end;
/* BIO is freed by create_ssl_connection on error */
if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl1, &clientssl1,
NULL, c_to_s_fbio)))
goto end;
DTLS_set_timer_cb(clientssl1, timer_cb);
if (testidx == 1)
certstatus[RECORD_SEQUENCE] = 0xff;
/*
* Inject a dummy record from the next epoch. In test 0, this should never
* get used because the message sequence number is too big. In test 1 we set
* the record sequence number to be way off in the future.
*/
c_to_s_mempacket = SSL_get_wbio(clientssl1);
c_to_s_mempacket = BIO_next(c_to_s_mempacket);
mempacket_test_inject(c_to_s_mempacket, (char *)certstatus,
sizeof(certstatus), 1, INJECT_PACKET_IGNORE_REC_SEQ);
/*
* Create the connection. We use "create_bare_ssl_connection" here so that
* we can force the connection to not do "SSL_read" once partly connected.
* We don't want to accidentally read the dummy records we injected because
* they will fail to decrypt.
*/
if (!TEST_true(create_bare_ssl_connection(serverssl1, clientssl1,
SSL_ERROR_NONE, 0, 0)))
goto end;
if (timer_cb_count == 0) {
printf("timer_callback was not called.\n");
goto end;
}
testresult = 1;
end:
SSL_free(serverssl1);
SSL_free(clientssl1);
SSL_CTX_free(sctx);
SSL_CTX_free(cctx);
return testresult;
}
/* One record for the cookieless initial ClientHello */
#define CLI_TO_SRV_COOKIE_EXCH 1
/*
* In a resumption handshake we use 2 records for the initial ClientHello in
* this test because we are using a very small MTU and the ClientHello is
* bigger than in the non resumption case.
*/
#define CLI_TO_SRV_RESUME_COOKIE_EXCH 2
#define SRV_TO_CLI_COOKIE_EXCH 1
#define CLI_TO_SRV_EPOCH_0_RECS 3
#define CLI_TO_SRV_EPOCH_1_RECS 1
#if !defined(OPENSSL_NO_EC) || !defined(OPENSSL_NO_DH)
# define SRV_TO_CLI_EPOCH_0_RECS 10
#else
/*
* In this case we have no ServerKeyExchange message, because we don't have
* ECDHE or DHE. When it is present it gets fragmented into 3 records in this
* test.
*/
# define SRV_TO_CLI_EPOCH_0_RECS 9
#endif
#define SRV_TO_CLI_EPOCH_1_RECS 1
#define TOTAL_FULL_HAND_RECORDS \
(CLI_TO_SRV_COOKIE_EXCH + SRV_TO_CLI_COOKIE_EXCH + \
CLI_TO_SRV_EPOCH_0_RECS + CLI_TO_SRV_EPOCH_1_RECS + \
SRV_TO_CLI_EPOCH_0_RECS + SRV_TO_CLI_EPOCH_1_RECS)
#define CLI_TO_SRV_RESUME_EPOCH_0_RECS 3
#define CLI_TO_SRV_RESUME_EPOCH_1_RECS 1
#define SRV_TO_CLI_RESUME_EPOCH_0_RECS 2
#define SRV_TO_CLI_RESUME_EPOCH_1_RECS 1
#define TOTAL_RESUME_HAND_RECORDS \
(CLI_TO_SRV_RESUME_COOKIE_EXCH + SRV_TO_CLI_COOKIE_EXCH + \
CLI_TO_SRV_RESUME_EPOCH_0_RECS + CLI_TO_SRV_RESUME_EPOCH_1_RECS + \
SRV_TO_CLI_RESUME_EPOCH_0_RECS + SRV_TO_CLI_RESUME_EPOCH_1_RECS)
#define TOTAL_RECORDS (TOTAL_FULL_HAND_RECORDS + TOTAL_RESUME_HAND_RECORDS)
/*
* We are assuming a ServerKeyExchange message is sent in this test. If we don't
* have either DH or EC, then it won't be
*/
#if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_EC)
static int test_dtls_drop_records(int idx)
{
SSL_CTX *sctx = NULL, *cctx = NULL;
SSL *serverssl = NULL, *clientssl = NULL;
BIO *c_to_s_fbio, *mempackbio;
int testresult = 0;
int epoch = 0;
SSL_SESSION *sess = NULL;
int cli_to_srv_cookie, cli_to_srv_epoch0, cli_to_srv_epoch1;
int srv_to_cli_epoch0;
if (!TEST_true(create_ssl_ctx_pair(NULL, DTLS_server_method(),
DTLS_client_method(),
DTLS1_VERSION, 0,
&sctx, &cctx, cert, privkey)))
return 0;
#ifdef OPENSSL_NO_DTLS1_2
/* Default sigalgs are SHA1 based in <DTLS1.2 which is in security level 0 */
if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
|| !TEST_true(SSL_CTX_set_cipher_list(cctx,
"DEFAULT:@SECLEVEL=0")))
goto end;
#endif
if (!TEST_true(SSL_CTX_set_dh_auto(sctx, 1)))
goto end;
SSL_CTX_set_options(sctx, SSL_OP_COOKIE_EXCHANGE);
SSL_CTX_set_cookie_generate_cb(sctx, generate_cookie_cb);
SSL_CTX_set_cookie_verify_cb(sctx, verify_cookie_cb);
if (idx >= TOTAL_FULL_HAND_RECORDS) {
/* We're going to do a resumption handshake. Get a session first. */
if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
NULL, NULL))
|| !TEST_true(create_ssl_connection(serverssl, clientssl,
SSL_ERROR_NONE))
|| !TEST_ptr(sess = SSL_get1_session(clientssl)))
goto end;
SSL_shutdown(clientssl);
SSL_shutdown(serverssl);
SSL_free(serverssl);
SSL_free(clientssl);
serverssl = clientssl = NULL;
cli_to_srv_epoch0 = CLI_TO_SRV_RESUME_EPOCH_0_RECS;
cli_to_srv_epoch1 = CLI_TO_SRV_RESUME_EPOCH_1_RECS;
srv_to_cli_epoch0 = SRV_TO_CLI_RESUME_EPOCH_0_RECS;
cli_to_srv_cookie = CLI_TO_SRV_RESUME_COOKIE_EXCH;
idx -= TOTAL_FULL_HAND_RECORDS;
} else {
cli_to_srv_epoch0 = CLI_TO_SRV_EPOCH_0_RECS;
cli_to_srv_epoch1 = CLI_TO_SRV_EPOCH_1_RECS;
srv_to_cli_epoch0 = SRV_TO_CLI_EPOCH_0_RECS;
cli_to_srv_cookie = CLI_TO_SRV_COOKIE_EXCH;
}
c_to_s_fbio = BIO_new(bio_f_tls_dump_filter());
if (!TEST_ptr(c_to_s_fbio))
goto end;
/* BIO is freed by create_ssl_connection on error */
if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
NULL, c_to_s_fbio)))
goto end;
if (sess != NULL) {
if (!TEST_true(SSL_set_session(clientssl, sess)))
goto end;
}
DTLS_set_timer_cb(clientssl, timer_cb);
DTLS_set_timer_cb(serverssl, timer_cb);
/* Work out which record to drop based on the test number */
if (idx >= cli_to_srv_cookie + cli_to_srv_epoch0 + cli_to_srv_epoch1) {
mempackbio = SSL_get_wbio(serverssl);
idx -= cli_to_srv_cookie + cli_to_srv_epoch0 + cli_to_srv_epoch1;
if (idx >= SRV_TO_CLI_COOKIE_EXCH + srv_to_cli_epoch0) {
epoch = 1;
idx -= SRV_TO_CLI_COOKIE_EXCH + srv_to_cli_epoch0;
}
} else {
mempackbio = SSL_get_wbio(clientssl);
if (idx >= cli_to_srv_cookie + cli_to_srv_epoch0) {
epoch = 1;
idx -= cli_to_srv_cookie + cli_to_srv_epoch0;
}
mempackbio = BIO_next(mempackbio);
}
BIO_ctrl(mempackbio, MEMPACKET_CTRL_SET_DROP_EPOCH, epoch, NULL);
BIO_ctrl(mempackbio, MEMPACKET_CTRL_SET_DROP_REC, idx, NULL);
if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
goto end;
if (sess != NULL && !TEST_true(SSL_session_reused(clientssl)))
goto end;
/* If the test did what we planned then it should have dropped a record */
if (!TEST_int_eq((int)BIO_ctrl(mempackbio, MEMPACKET_CTRL_GET_DROP_REC, 0,
NULL), -1))
goto end;
testresult = 1;
end:
SSL_SESSION_free(sess);
SSL_free(serverssl);
SSL_free(clientssl);
SSL_CTX_free(sctx);
SSL_CTX_free(cctx);
return testresult;
}
#endif /* !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_EC) */
static int test_cookie(void)
{
SSL_CTX *sctx = NULL, *cctx = NULL;
SSL *serverssl = NULL, *clientssl = NULL;
int testresult = 0;
if (!TEST_true(create_ssl_ctx_pair(NULL, DTLS_server_method(),
DTLS_client_method(),
DTLS1_VERSION, 0,
&sctx, &cctx, cert, privkey)))
return 0;
SSL_CTX_set_options(sctx, SSL_OP_COOKIE_EXCHANGE);
SSL_CTX_set_cookie_generate_cb(sctx, generate_cookie_cb);
SSL_CTX_set_cookie_verify_cb(sctx, verify_cookie_cb);
#ifdef OPENSSL_NO_DTLS1_2
/* Default sigalgs are SHA1 based in <DTLS1.2 which is in security level 0 */
if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
|| !TEST_true(SSL_CTX_set_cipher_list(cctx,
"DEFAULT:@SECLEVEL=0")))
goto end;
#endif
if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
NULL, NULL))
|| !TEST_true(create_ssl_connection(serverssl, clientssl,
SSL_ERROR_NONE)))
goto end;
testresult = 1;
end:
SSL_free(serverssl);
SSL_free(clientssl);
SSL_CTX_free(sctx);
SSL_CTX_free(cctx);
return testresult;
}
static int test_dtls_duplicate_records(void)
{
SSL_CTX *sctx = NULL, *cctx = NULL;
SSL *serverssl = NULL, *clientssl = NULL;
int testresult = 0;
if (!TEST_true(create_ssl_ctx_pair(NULL, DTLS_server_method(),
DTLS_client_method(),
DTLS1_VERSION, 0,
&sctx, &cctx, cert, privkey)))
return 0;
#ifdef OPENSSL_NO_DTLS1_2
/* Default sigalgs are SHA1 based in <DTLS1.2 which is in security level 0 */
if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
|| !TEST_true(SSL_CTX_set_cipher_list(cctx,
"DEFAULT:@SECLEVEL=0")))
goto end;
#endif
if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
NULL, NULL)))
goto end;
DTLS_set_timer_cb(clientssl, timer_cb);
DTLS_set_timer_cb(serverssl, timer_cb);
BIO_ctrl(SSL_get_wbio(clientssl), MEMPACKET_CTRL_SET_DUPLICATE_REC, 1, NULL);
BIO_ctrl(SSL_get_wbio(serverssl), MEMPACKET_CTRL_SET_DUPLICATE_REC, 1, NULL);
if (!TEST_true(create_ssl_connection(serverssl, clientssl, SSL_ERROR_NONE)))
goto end;
testresult = 1;
end:
SSL_free(serverssl);
SSL_free(clientssl);
SSL_CTX_free(sctx);
SSL_CTX_free(cctx);
return testresult;
}
/*
* Test just sending a Finished message as the first message. Should fail due
* to an unexpected message.
*/
static int test_just_finished(void)
{
int testresult = 0, ret;
SSL_CTX *sctx = NULL;
SSL *serverssl = NULL;
BIO *rbio = NULL, *wbio = NULL, *sbio = NULL;
unsigned char buf[] = {
/* Record header */
SSL3_RT_HANDSHAKE, /* content type */
(DTLS1_2_VERSION >> 8) & 0xff, /* protocol version hi byte */
DTLS1_2_VERSION & 0xff, /* protocol version lo byte */
0, 0, /* epoch */
0, 0, 0, 0, 0, 0, /* record sequence */
0, DTLS1_HM_HEADER_LENGTH + SHA_DIGEST_LENGTH, /* record length */
/* Message header */
SSL3_MT_FINISHED, /* message type */
0, 0, SHA_DIGEST_LENGTH, /* message length */
0, 0, /* message sequence */
0, 0, 0, /* fragment offset */
0, 0, SHA_DIGEST_LENGTH, /* fragment length */
/* Message body */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
if (!TEST_true(create_ssl_ctx_pair(NULL, DTLS_server_method(),
NULL, 0, 0,
&sctx, NULL, cert, privkey)))
return 0;
#ifdef OPENSSL_NO_DTLS1_2
/* DTLSv1 is not allowed at the default security level */
if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0")))
goto end;
#endif
serverssl = SSL_new(sctx);
rbio = BIO_new(BIO_s_mem());
wbio = BIO_new(BIO_s_mem());
if (!TEST_ptr(serverssl) || !TEST_ptr(rbio) || !TEST_ptr(wbio))
goto end;
sbio = rbio;
SSL_set0_rbio(serverssl, rbio);
SSL_set0_wbio(serverssl, wbio);
rbio = wbio = NULL;
DTLS_set_timer_cb(serverssl, timer_cb);
if (!TEST_int_eq(BIO_write(sbio, buf, sizeof(buf)), sizeof(buf)))
goto end;
/* We expect the attempt to process the message to fail */
if (!TEST_int_le(ret = SSL_accept(serverssl), 0))
goto end;
/* Check that we got the error we were expecting */
if (!TEST_int_eq(SSL_get_error(serverssl, ret), SSL_ERROR_SSL))
goto end;
if (!TEST_int_eq(ERR_GET_REASON(ERR_get_error()), SSL_R_UNEXPECTED_MESSAGE))
goto end;
testresult = 1;
end:
BIO_free(rbio);
BIO_free(wbio);
SSL_free(serverssl);
SSL_CTX_free(sctx);
return testresult;
}
/*
* Test that swapping later records before Finished or CCS still works
* Test 0: Test receiving a handshake record early from next epoch on server side
* Test 1: Test receiving a handshake record early from next epoch on client side
* Test 2: Test receiving an app data record early from next epoch on client side
* Test 3: Test receiving an app data before Finished on client side
*/
static int test_swap_records(int idx)
{
SSL_CTX *sctx = NULL, *cctx = NULL;
SSL *sssl = NULL, *cssl = NULL;
int testresult = 0;
BIO *bio;
char msg[] = { 0x00, 0x01, 0x02, 0x03 };
char buf[10];
if (!TEST_true(create_ssl_ctx_pair(NULL, DTLS_server_method(),
DTLS_client_method(),
DTLS1_VERSION, 0,
&sctx, &cctx, cert, privkey)))
return 0;
#ifndef OPENSSL_NO_DTLS1_2
if (!TEST_true(SSL_CTX_set_cipher_list(cctx, "AES128-SHA")))
goto end;
#else
/* Default sigalgs are SHA1 based in <DTLS1.2 which is in security level 0 */
if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "AES128-SHA:@SECLEVEL=0"))
|| !TEST_true(SSL_CTX_set_cipher_list(cctx,
"AES128-SHA:@SECLEVEL=0")))
goto end;
#endif
if (!TEST_true(create_ssl_objects(sctx, cctx, &sssl, &cssl,
NULL, NULL)))
goto end;
/* Send flight 1: ClientHello */
if (!TEST_int_le(SSL_connect(cssl), 0))
goto end;
/* Recv flight 1, send flight 2: ServerHello, Certificate, ServerHelloDone */
if (!TEST_int_le(SSL_accept(sssl), 0))
goto end;
/* Recv flight 2, send flight 3: ClientKeyExchange, CCS, Finished */
if (!TEST_int_le(SSL_connect(cssl), 0))
goto end;
if (idx == 0) {
/* Swap Finished and CCS within the datagram */
bio = SSL_get_wbio(cssl);
if (!TEST_ptr(bio)
|| !TEST_true(mempacket_swap_epoch(bio)))
goto end;
}
/* Recv flight 3, send flight 4: datagram 0(NST, CCS) datagram 1(Finished) */
if (!TEST_int_gt(SSL_accept(sssl), 0))
goto end;
/* Send flight 4 (cont'd): datagram 2(app data) */
if (!TEST_int_eq(SSL_write(sssl, msg, sizeof(msg)), (int)sizeof(msg)))
goto end;
bio = SSL_get_wbio(sssl);
if (!TEST_ptr(bio))
goto end;
if (idx == 1) {
/* Finished comes before NST/CCS */
if (!TEST_true(mempacket_move_packet(bio, 0, 1)))
goto end;
} else if (idx == 2) {
/* App data comes before NST/CCS */
if (!TEST_true(mempacket_move_packet(bio, 0, 2)))
goto end;
} else if (idx == 3) {
/* App data comes before Finished */
bio = SSL_get_wbio(sssl);
if (!TEST_true(mempacket_move_packet(bio, 1, 2)))
goto end;
}
/*
* Recv flight 4 (datagram 1): NST, CCS, + flight 5: app data
* + flight 4 (datagram 2): Finished
*/
if (!TEST_int_gt(SSL_connect(cssl), 0))
goto end;
if (idx == 0 || idx == 1) {
/* App data was not received early, so it should not be pending */
if (!TEST_int_eq(SSL_pending(cssl), 0)
|| !TEST_false(SSL_has_pending(cssl)))
goto end;
} else {
/* We received the app data early so it should be buffered already */
if (!TEST_int_eq(SSL_pending(cssl), (int)sizeof(msg))
|| !TEST_true(SSL_has_pending(cssl)))
goto end;
}
/*
* Recv flight 5 (app data)
*/
if (!TEST_int_eq(SSL_read(cssl, buf, sizeof(buf)), (int)sizeof(msg)))
goto end;
testresult = 1;
end:
SSL_free(cssl);
SSL_free(sssl);
SSL_CTX_free(cctx);
SSL_CTX_free(sctx);
return testresult;
}
/* Confirm that we can create a connections using DTLSv1_listen() */
static int test_listen(void)
{
SSL_CTX *sctx = NULL, *cctx = NULL;
SSL *serverssl = NULL, *clientssl = NULL;
int testresult = 0;
if (!TEST_true(create_ssl_ctx_pair(NULL, DTLS_server_method(),
DTLS_client_method(),
DTLS1_VERSION, 0,
&sctx, &cctx, cert, privkey)))
return 0;
#ifdef OPENSSL_NO_DTLS1_2
/* Default sigalgs are SHA1 based in <DTLS1.2 which is in security level 0 */
if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "DEFAULT:@SECLEVEL=0"))
|| !TEST_true(SSL_CTX_set_cipher_list(cctx,
"DEFAULT:@SECLEVEL=0")))
goto end;
#endif
SSL_CTX_set_cookie_generate_cb(sctx, generate_cookie_cb);
SSL_CTX_set_cookie_verify_cb(sctx, verify_cookie_cb);
if (!TEST_true(create_ssl_objects(sctx, cctx, &serverssl, &clientssl,
NULL, NULL)))
goto end;
DTLS_set_timer_cb(clientssl, timer_cb);
DTLS_set_timer_cb(serverssl, timer_cb);
/*
* The last parameter to create_bare_ssl_connection() requests that
* DTLSv1_listen() is used.
*/
if (!TEST_true(create_bare_ssl_connection(serverssl, clientssl,
SSL_ERROR_NONE, 1, 1)))
goto end;
testresult = 1;
end:
SSL_free(serverssl);
SSL_free(clientssl);
SSL_CTX_free(sctx);
SSL_CTX_free(cctx);
return testresult;
}
OPT_TEST_DECLARE_USAGE("certfile privkeyfile\n")
int setup_tests(void)
{
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
if (!TEST_ptr(cert = test_get_argument(0))
|| !TEST_ptr(privkey = test_get_argument(1)))
return 0;
ADD_ALL_TESTS(test_dtls_unprocessed, NUM_TESTS);
#if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_EC)
ADD_ALL_TESTS(test_dtls_drop_records, TOTAL_RECORDS);
#endif
ADD_TEST(test_cookie);
ADD_TEST(test_dtls_duplicate_records);
ADD_TEST(test_just_finished);
ADD_ALL_TESTS(test_swap_records, 4);
ADD_TEST(test_listen);
return 1;
}
void cleanup_tests(void)
{
bio_f_tls_dump_filter_free();
bio_s_mempacket_test_free();
}
| 21,887 | 31.668657 | 81 | c |
openssl | openssl-master/test/dtlsv1listentest.c | /*
* Copyright 2016-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 <string.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/conf.h>
#include "internal/nelem.h"
#include "testutil.h"
#ifndef OPENSSL_NO_SOCK
/* Just a ClientHello without a cookie */
static const unsigned char clienthello_nocookie[] = {
0x16, /* Handshake */
0xFE, 0xFF, /* DTLSv1.0 */
0x00, 0x00, /* Epoch */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Record sequence number */
0x00, 0x3A, /* Record Length */
0x01, /* ClientHello */
0x00, 0x00, 0x2E, /* Message length */
0x00, 0x00, /* Message sequence */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x2E, /* Fragment length */
0xFE, 0xFD, /* DTLSv1.2 */
0xCA, 0x18, 0x9F, 0x76, 0xEC, 0x57, 0xCE, 0xE5, 0xB3, 0xAB, 0x79, 0x90,
0xAD, 0xAC, 0x6E, 0xD1, 0x58, 0x35, 0x03, 0x97, 0x16, 0x10, 0x82, 0x56,
0xD8, 0x55, 0xFF, 0xE1, 0x8A, 0xA3, 0x2E, 0xF6, /* Random */
0x00, /* Session id len */
0x00, /* Cookie len */
0x00, 0x04, /* Ciphersuites len */
0x00, 0x2f, /* AES128-SHA */
0x00, 0xff, /* Empty reneg info SCSV */
0x01, /* Compression methods len */
0x00, /* Null compression */
0x00, 0x00 /* Extensions len */
};
/* First fragment of a ClientHello without a cookie */
static const unsigned char clienthello_nocookie_frag[] = {
0x16, /* Handshake */
0xFE, 0xFF, /* DTLSv1.0 */
0x00, 0x00, /* Epoch */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Record sequence number */
0x00, 0x30, /* Record Length */
0x01, /* ClientHello */
0x00, 0x00, 0x2E, /* Message length */
0x00, 0x00, /* Message sequence */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x24, /* Fragment length */
0xFE, 0xFD, /* DTLSv1.2 */
0xCA, 0x18, 0x9F, 0x76, 0xEC, 0x57, 0xCE, 0xE5, 0xB3, 0xAB, 0x79, 0x90,
0xAD, 0xAC, 0x6E, 0xD1, 0x58, 0x35, 0x03, 0x97, 0x16, 0x10, 0x82, 0x56,
0xD8, 0x55, 0xFF, 0xE1, 0x8A, 0xA3, 0x2E, 0xF6, /* Random */
0x00, /* Session id len */
0x00 /* Cookie len */
};
/* First fragment of a ClientHello which is too short */
static const unsigned char clienthello_nocookie_short[] = {
0x16, /* Handshake */
0xFE, 0xFF, /* DTLSv1.0 */
0x00, 0x00, /* Epoch */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Record sequence number */
0x00, 0x2F, /* Record Length */
0x01, /* ClientHello */
0x00, 0x00, 0x2E, /* Message length */
0x00, 0x00, /* Message sequence */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x23, /* Fragment length */
0xFE, 0xFD, /* DTLSv1.2 */
0xCA, 0x18, 0x9F, 0x76, 0xEC, 0x57, 0xCE, 0xE5, 0xB3, 0xAB, 0x79, 0x90,
0xAD, 0xAC, 0x6E, 0xD1, 0x58, 0x35, 0x03, 0x97, 0x16, 0x10, 0x82, 0x56,
0xD8, 0x55, 0xFF, 0xE1, 0x8A, 0xA3, 0x2E, 0xF6, /* Random */
0x00 /* Session id len */
};
/* Second fragment of a ClientHello */
static const unsigned char clienthello_2ndfrag[] = {
0x16, /* Handshake */
0xFE, 0xFF, /* DTLSv1.0 */
0x00, 0x00, /* Epoch */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Record sequence number */
0x00, 0x38, /* Record Length */
0x01, /* ClientHello */
0x00, 0x00, 0x2E, /* Message length */
0x00, 0x00, /* Message sequence */
0x00, 0x00, 0x02, /* Fragment offset */
0x00, 0x00, 0x2C, /* Fragment length */
/* Version skipped - sent in first fragment */
0xCA, 0x18, 0x9F, 0x76, 0xEC, 0x57, 0xCE, 0xE5, 0xB3, 0xAB, 0x79, 0x90,
0xAD, 0xAC, 0x6E, 0xD1, 0x58, 0x35, 0x03, 0x97, 0x16, 0x10, 0x82, 0x56,
0xD8, 0x55, 0xFF, 0xE1, 0x8A, 0xA3, 0x2E, 0xF6, /* Random */
0x00, /* Session id len */
0x00, /* Cookie len */
0x00, 0x04, /* Ciphersuites len */
0x00, 0x2f, /* AES128-SHA */
0x00, 0xff, /* Empty reneg info SCSV */
0x01, /* Compression methods len */
0x00, /* Null compression */
0x00, 0x00 /* Extensions len */
};
/* A ClientHello with a good cookie */
static const unsigned char clienthello_cookie[] = {
0x16, /* Handshake */
0xFE, 0xFF, /* DTLSv1.0 */
0x00, 0x00, /* Epoch */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Record sequence number */
0x00, 0x4E, /* Record Length */
0x01, /* ClientHello */
0x00, 0x00, 0x42, /* Message length */
0x00, 0x00, /* Message sequence */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x42, /* Fragment length */
0xFE, 0xFD, /* DTLSv1.2 */
0xCA, 0x18, 0x9F, 0x76, 0xEC, 0x57, 0xCE, 0xE5, 0xB3, 0xAB, 0x79, 0x90,
0xAD, 0xAC, 0x6E, 0xD1, 0x58, 0x35, 0x03, 0x97, 0x16, 0x10, 0x82, 0x56,
0xD8, 0x55, 0xFF, 0xE1, 0x8A, 0xA3, 0x2E, 0xF6, /* Random */
0x00, /* Session id len */
0x14, /* Cookie len */
0x00, 0x01, 0x02, 0x03, 0x04, 005, 0x06, 007, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, /* Cookie */
0x00, 0x04, /* Ciphersuites len */
0x00, 0x2f, /* AES128-SHA */
0x00, 0xff, /* Empty reneg info SCSV */
0x01, /* Compression methods len */
0x00, /* Null compression */
0x00, 0x00 /* Extensions len */
};
/* A fragmented ClientHello with a good cookie */
static const unsigned char clienthello_cookie_frag[] = {
0x16, /* Handshake */
0xFE, 0xFF, /* DTLSv1.0 */
0x00, 0x00, /* Epoch */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Record sequence number */
0x00, 0x44, /* Record Length */
0x01, /* ClientHello */
0x00, 0x00, 0x42, /* Message length */
0x00, 0x00, /* Message sequence */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x38, /* Fragment length */
0xFE, 0xFD, /* DTLSv1.2 */
0xCA, 0x18, 0x9F, 0x76, 0xEC, 0x57, 0xCE, 0xE5, 0xB3, 0xAB, 0x79, 0x90,
0xAD, 0xAC, 0x6E, 0xD1, 0x58, 0x35, 0x03, 0x97, 0x16, 0x10, 0x82, 0x56,
0xD8, 0x55, 0xFF, 0xE1, 0x8A, 0xA3, 0x2E, 0xF6, /* Random */
0x00, /* Session id len */
0x14, /* Cookie len */
0x00, 0x01, 0x02, 0x03, 0x04, 005, 0x06, 007, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13 /* Cookie */
};
/* A ClientHello with a bad cookie */
static const unsigned char clienthello_badcookie[] = {
0x16, /* Handshake */
0xFE, 0xFF, /* DTLSv1.0 */
0x00, 0x00, /* Epoch */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Record sequence number */
0x00, 0x4E, /* Record Length */
0x01, /* ClientHello */
0x00, 0x00, 0x42, /* Message length */
0x00, 0x00, /* Message sequence */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x42, /* Fragment length */
0xFE, 0xFD, /* DTLSv1.2 */
0xCA, 0x18, 0x9F, 0x76, 0xEC, 0x57, 0xCE, 0xE5, 0xB3, 0xAB, 0x79, 0x90,
0xAD, 0xAC, 0x6E, 0xD1, 0x58, 0x35, 0x03, 0x97, 0x16, 0x10, 0x82, 0x56,
0xD8, 0x55, 0xFF, 0xE1, 0x8A, 0xA3, 0x2E, 0xF6, /* Random */
0x00, /* Session id len */
0x14, /* Cookie len */
0x01, 0x01, 0x02, 0x03, 0x04, 005, 0x06, 007, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, /* Cookie */
0x00, 0x04, /* Ciphersuites len */
0x00, 0x2f, /* AES128-SHA */
0x00, 0xff, /* Empty reneg info SCSV */
0x01, /* Compression methods len */
0x00, /* Null compression */
0x00, 0x00 /* Extensions len */
};
/* A fragmented ClientHello with the fragment boundary mid cookie */
static const unsigned char clienthello_cookie_short[] = {
0x16, /* Handshake */
0xFE, 0xFF, /* DTLSv1.0 */
0x00, 0x00, /* Epoch */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Record sequence number */
0x00, 0x43, /* Record Length */
0x01, /* ClientHello */
0x00, 0x00, 0x42, /* Message length */
0x00, 0x00, /* Message sequence */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x37, /* Fragment length */
0xFE, 0xFD, /* DTLSv1.2 */
0xCA, 0x18, 0x9F, 0x76, 0xEC, 0x57, 0xCE, 0xE5, 0xB3, 0xAB, 0x79, 0x90,
0xAD, 0xAC, 0x6E, 0xD1, 0x58, 0x35, 0x03, 0x97, 0x16, 0x10, 0x82, 0x56,
0xD8, 0x55, 0xFF, 0xE1, 0x8A, 0xA3, 0x2E, 0xF6, /* Random */
0x00, /* Session id len */
0x14, /* Cookie len */
0x00, 0x01, 0x02, 0x03, 0x04, 005, 0x06, 007, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12 /* Cookie */
};
/* Bad record - too short */
static const unsigned char record_short[] = {
0x16, /* Handshake */
0xFE, 0xFF, /* DTLSv1.0 */
0x00, 0x00, /* Epoch */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00 /* Record sequence number */
};
static const unsigned char verify[] = {
0x16, /* Handshake */
0xFE, 0xFF, /* DTLSv1.0 */
0x00, 0x00, /* Epoch */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Record sequence number */
0x00, 0x23, /* Record Length */
0x03, /* HelloVerifyRequest */
0x00, 0x00, 0x17, /* Message length */
0x00, 0x00, /* Message sequence */
0x00, 0x00, 0x00, /* Fragment offset */
0x00, 0x00, 0x17, /* Fragment length */
0xFE, 0xFF, /* DTLSv1.0 */
0x14, /* Cookie len */
0x00, 0x01, 0x02, 0x03, 0x04, 005, 0x06, 007, 0x08, 0x09, 0x0A, 0x0B, 0x0C,
0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13 /* Cookie */
};
typedef struct {
const unsigned char *in;
unsigned int inlen;
/*
* GOOD == positive return value from DTLSv1_listen, no output yet
* VERIFY == 0 return value, HelloVerifyRequest sent
* DROP == 0 return value, no output
*/
enum {GOOD, VERIFY, DROP} outtype;
} tests;
static tests testpackets[9] = {
{ clienthello_nocookie, sizeof(clienthello_nocookie), VERIFY },
{ clienthello_nocookie_frag, sizeof(clienthello_nocookie_frag), VERIFY },
{ clienthello_nocookie_short, sizeof(clienthello_nocookie_short), DROP },
{ clienthello_2ndfrag, sizeof(clienthello_2ndfrag), DROP },
{ clienthello_cookie, sizeof(clienthello_cookie), GOOD },
{ clienthello_cookie_frag, sizeof(clienthello_cookie_frag), GOOD },
{ clienthello_badcookie, sizeof(clienthello_badcookie), VERIFY },
{ clienthello_cookie_short, sizeof(clienthello_cookie_short), DROP },
{ record_short, sizeof(record_short), DROP }
};
# define COOKIE_LEN 20
static int cookie_gen(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len)
{
unsigned int i;
for (i = 0; i < COOKIE_LEN; i++, cookie++)
*cookie = i;
*cookie_len = COOKIE_LEN;
return 1;
}
static int cookie_verify(SSL *ssl, const unsigned char *cookie,
unsigned int cookie_len)
{
unsigned int i;
if (cookie_len != COOKIE_LEN)
return 0;
for (i = 0; i < COOKIE_LEN; i++, cookie++) {
if (*cookie != i)
return 0;
}
return 1;
}
static int dtls_listen_test(int i)
{
SSL_CTX *ctx = NULL;
SSL *ssl = NULL;
BIO *outbio = NULL;
BIO *inbio = NULL;
BIO_ADDR *peer = NULL;
tests *tp = &testpackets[i];
char *data;
long datalen;
int ret, success = 0;
if (!TEST_ptr(ctx = SSL_CTX_new(DTLS_server_method()))
|| !TEST_ptr(peer = BIO_ADDR_new()))
goto err;
SSL_CTX_set_cookie_generate_cb(ctx, cookie_gen);
SSL_CTX_set_cookie_verify_cb(ctx, cookie_verify);
/* Create an SSL object and set the BIO */
if (!TEST_ptr(ssl = SSL_new(ctx))
|| !TEST_ptr(outbio = BIO_new(BIO_s_mem())))
goto err;
SSL_set0_wbio(ssl, outbio);
/* Set Non-blocking IO behaviour */
if (!TEST_ptr(inbio = BIO_new_mem_buf((char *)tp->in, tp->inlen)))
goto err;
BIO_set_mem_eof_return(inbio, -1);
SSL_set0_rbio(ssl, inbio);
/* Process the incoming packet */
if (!TEST_int_ge(ret = DTLSv1_listen(ssl, peer), 0))
goto err;
datalen = BIO_get_mem_data(outbio, &data);
if (tp->outtype == VERIFY) {
if (!TEST_int_eq(ret, 0)
|| !TEST_mem_eq(data, datalen, verify, sizeof(verify)))
goto err;
} else if (datalen == 0) {
if (!TEST_true((ret == 0 && tp->outtype == DROP)
|| (ret == 1 && tp->outtype == GOOD)))
goto err;
} else {
TEST_info("Test %d: unexpected data output", i);
goto err;
}
(void)BIO_reset(outbio);
inbio = NULL;
SSL_set0_rbio(ssl, NULL);
success = 1;
err:
/* Also frees up outbio */
SSL_free(ssl);
SSL_CTX_free(ctx);
BIO_free(inbio);
OPENSSL_free(peer);
return success;
}
#endif
int setup_tests(void)
{
#ifndef OPENSSL_NO_SOCK
ADD_ALL_TESTS(dtls_listen_test, (int)OSSL_NELEM(testpackets));
#endif
return 1;
}
| 12,617 | 34.24581 | 80 | c |
openssl | openssl-master/test/ec_internal_test.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
*/
/*
* Low level APIs are deprecated for public use, but still ok for internal use.
*/
#include "internal/deprecated.h"
#include "internal/nelem.h"
#include "testutil.h"
#include <openssl/ec.h>
#include "ec_local.h"
#include <openssl/objects.h>
static size_t crv_len = 0;
static EC_builtin_curve *curves = NULL;
/* sanity checks field_inv function pointer in EC_METHOD */
static int group_field_tests(const EC_GROUP *group, BN_CTX *ctx)
{
BIGNUM *a = NULL, *b = NULL, *c = NULL;
int ret = 0;
if (group->meth->field_inv == NULL || group->meth->field_mul == NULL)
return 1;
BN_CTX_start(ctx);
a = BN_CTX_get(ctx);
b = BN_CTX_get(ctx);
if (!TEST_ptr(c = BN_CTX_get(ctx))
/* 1/1 = 1 */
|| !TEST_true(group->meth->field_inv(group, b, BN_value_one(), ctx))
|| !TEST_true(BN_is_one(b))
/* (1/a)*a = 1 */
|| !TEST_true(BN_rand(a, BN_num_bits(group->field) - 1,
BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY))
|| !TEST_true(group->meth->field_inv(group, b, a, ctx))
|| (group->meth->field_encode &&
!TEST_true(group->meth->field_encode(group, a, a, ctx)))
|| (group->meth->field_encode &&
!TEST_true(group->meth->field_encode(group, b, b, ctx)))
|| !TEST_true(group->meth->field_mul(group, c, a, b, ctx))
|| (group->meth->field_decode &&
!TEST_true(group->meth->field_decode(group, c, c, ctx)))
|| !TEST_true(BN_is_one(c)))
goto err;
/* 1/0 = error */
BN_zero(a);
if (!TEST_false(group->meth->field_inv(group, b, a, ctx))
|| !TEST_true(ERR_GET_LIB(ERR_peek_last_error()) == ERR_LIB_EC)
|| !TEST_true(ERR_GET_REASON(ERR_peek_last_error()) ==
EC_R_CANNOT_INVERT)
/* 1/p = error */
|| !TEST_false(group->meth->field_inv(group, b, group->field, ctx))
|| !TEST_true(ERR_GET_LIB(ERR_peek_last_error()) == ERR_LIB_EC)
|| !TEST_true(ERR_GET_REASON(ERR_peek_last_error()) ==
EC_R_CANNOT_INVERT))
goto err;
ERR_clear_error();
ret = 1;
err:
BN_CTX_end(ctx);
return ret;
}
/* wrapper for group_field_tests for explicit curve params and EC_METHOD */
static int field_tests(const EC_METHOD *meth, const unsigned char *params,
int len)
{
BN_CTX *ctx = NULL;
BIGNUM *p = NULL, *a = NULL, *b = NULL;
EC_GROUP *group = NULL;
int ret = 0;
if (!TEST_ptr(ctx = BN_CTX_new()))
return 0;
BN_CTX_start(ctx);
p = BN_CTX_get(ctx);
a = BN_CTX_get(ctx);
if (!TEST_ptr(b = BN_CTX_get(ctx))
|| !TEST_ptr(group = EC_GROUP_new(meth))
|| !TEST_true(BN_bin2bn(params, len, p))
|| !TEST_true(BN_bin2bn(params + len, len, a))
|| !TEST_true(BN_bin2bn(params + 2 * len, len, b))
|| !TEST_true(EC_GROUP_set_curve(group, p, a, b, ctx))
|| !group_field_tests(group, ctx))
goto err;
ret = 1;
err:
BN_CTX_end(ctx);
BN_CTX_free(ctx);
if (group != NULL)
EC_GROUP_free(group);
return ret;
}
/* NIST prime curve P-256 */
static const unsigned char params_p256[] = {
/* p */
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
/* a */
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC,
/* b */
0x5A, 0xC6, 0x35, 0xD8, 0xAA, 0x3A, 0x93, 0xE7, 0xB3, 0xEB, 0xBD, 0x55,
0x76, 0x98, 0x86, 0xBC, 0x65, 0x1D, 0x06, 0xB0, 0xCC, 0x53, 0xB0, 0xF6,
0x3B, 0xCE, 0x3C, 0x3E, 0x27, 0xD2, 0x60, 0x4B
};
#ifndef OPENSSL_NO_EC2M
/* NIST binary curve B-283 */
static const unsigned char params_b283[] = {
/* p */
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0xA1,
/* a */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
/* b */
0x02, 0x7B, 0x68, 0x0A, 0xC8, 0xB8, 0x59, 0x6D, 0xA5, 0xA4, 0xAF, 0x8A,
0x19, 0xA0, 0x30, 0x3F, 0xCA, 0x97, 0xFD, 0x76, 0x45, 0x30, 0x9F, 0xA2,
0xA5, 0x81, 0x48, 0x5A, 0xF6, 0x26, 0x3E, 0x31, 0x3B, 0x79, 0xA2, 0xF5
};
#endif
/* test EC_GFp_simple_method directly */
static int field_tests_ecp_simple(void)
{
TEST_info("Testing EC_GFp_simple_method()\n");
return field_tests(EC_GFp_simple_method(), params_p256,
sizeof(params_p256) / 3);
}
/* test EC_GFp_mont_method directly */
static int field_tests_ecp_mont(void)
{
TEST_info("Testing EC_GFp_mont_method()\n");
return field_tests(EC_GFp_mont_method(), params_p256,
sizeof(params_p256) / 3);
}
#ifndef OPENSSL_NO_EC2M
/* test EC_GF2m_simple_method directly */
static int field_tests_ec2_simple(void)
{
TEST_info("Testing EC_GF2m_simple_method()\n");
return field_tests(EC_GF2m_simple_method(), params_b283,
sizeof(params_b283) / 3);
}
#endif
/* test default method for a named curve */
static int field_tests_default(int n)
{
BN_CTX *ctx = NULL;
EC_GROUP *group = NULL;
int nid = curves[n].nid;
int ret = 0;
TEST_info("Testing curve %s\n", OBJ_nid2sn(nid));
if (!TEST_ptr(group = EC_GROUP_new_by_curve_name(nid))
|| !TEST_ptr(ctx = BN_CTX_new())
|| !group_field_tests(group, ctx))
goto err;
ret = 1;
err:
if (group != NULL)
EC_GROUP_free(group);
if (ctx != NULL)
BN_CTX_free(ctx);
return ret;
}
#ifndef OPENSSL_NO_EC_NISTP_64_GCC_128
/*
* Tests a point known to cause an incorrect underflow in an old version of
* ecp_nist521.c
*/
static int underflow_test(void)
{
BN_CTX *ctx = NULL;
EC_GROUP *grp = NULL;
EC_POINT *P = NULL, *Q = NULL, *R = NULL;
BIGNUM *x1 = NULL, *y1 = NULL, *z1 = NULL, *x2 = NULL, *y2 = NULL;
BIGNUM *k = NULL;
int testresult = 0;
const char *x1str =
"1534f0077fffffe87e9adcfe000000000000000000003e05a21d2400002e031b1f4"
"b80000c6fafa4f3c1288798d624a247b5e2ffffffffffffffefe099241900004";
const char *p521m1 =
"1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe";
ctx = BN_CTX_new();
if (!TEST_ptr(ctx))
return 0;
BN_CTX_start(ctx);
x1 = BN_CTX_get(ctx);
y1 = BN_CTX_get(ctx);
z1 = BN_CTX_get(ctx);
x2 = BN_CTX_get(ctx);
y2 = BN_CTX_get(ctx);
k = BN_CTX_get(ctx);
if (!TEST_ptr(k))
goto err;
grp = EC_GROUP_new_by_curve_name(NID_secp521r1);
P = EC_POINT_new(grp);
Q = EC_POINT_new(grp);
R = EC_POINT_new(grp);
if (!TEST_ptr(grp) || !TEST_ptr(P) || !TEST_ptr(Q) || !TEST_ptr(R))
goto err;
if (!TEST_int_gt(BN_hex2bn(&x1, x1str), 0)
|| !TEST_int_gt(BN_hex2bn(&y1, p521m1), 0)
|| !TEST_int_gt(BN_hex2bn(&z1, p521m1), 0)
|| !TEST_int_gt(BN_hex2bn(&k, "02"), 0)
|| !TEST_true(ossl_ec_GFp_simple_set_Jprojective_coordinates_GFp(grp, P, x1,
y1, z1, ctx))
|| !TEST_true(EC_POINT_mul(grp, Q, NULL, P, k, ctx))
|| !TEST_true(EC_POINT_get_affine_coordinates(grp, Q, x1, y1, ctx))
|| !TEST_true(EC_POINT_dbl(grp, R, P, ctx))
|| !TEST_true(EC_POINT_get_affine_coordinates(grp, R, x2, y2, ctx)))
goto err;
if (!TEST_int_eq(BN_cmp(x1, x2), 0)
|| !TEST_int_eq(BN_cmp(y1, y2), 0))
goto err;
testresult = 1;
err:
BN_CTX_end(ctx);
EC_POINT_free(P);
EC_POINT_free(Q);
EC_POINT_free(R);
EC_GROUP_free(grp);
BN_CTX_free(ctx);
return testresult;
}
#endif
/*
* Tests behavior of the EC_KEY_set_private_key
*/
static int set_private_key(void)
{
EC_KEY *key = NULL, *aux_key = NULL;
int testresult = 0;
key = EC_KEY_new_by_curve_name(NID_secp224r1);
aux_key = EC_KEY_new_by_curve_name(NID_secp224r1);
if (!TEST_ptr(key)
|| !TEST_ptr(aux_key)
|| !TEST_int_eq(EC_KEY_generate_key(key), 1)
|| !TEST_int_eq(EC_KEY_generate_key(aux_key), 1))
goto err;
/* Test setting a valid private key */
if (!TEST_int_eq(EC_KEY_set_private_key(key, aux_key->priv_key), 1))
goto err;
/* Test compliance with legacy behavior for NULL private keys */
if (!TEST_int_eq(EC_KEY_set_private_key(key, NULL), 0)
|| !TEST_ptr_null(key->priv_key))
goto err;
testresult = 1;
err:
EC_KEY_free(key);
EC_KEY_free(aux_key);
return testresult;
}
/*
* Tests behavior of the decoded_from_explicit_params flag and API
*/
static int decoded_flag_test(void)
{
EC_GROUP *grp;
EC_GROUP *grp_copy = NULL;
ECPARAMETERS *ecparams = NULL;
ECPKPARAMETERS *ecpkparams = NULL;
EC_KEY *key = NULL;
unsigned char *encodedparams = NULL;
const unsigned char *encp;
int encodedlen;
int testresult = 0;
/* Test EC_GROUP_new not setting the flag */
grp = EC_GROUP_new(EC_GFp_simple_method());
if (!TEST_ptr(grp)
|| !TEST_int_eq(grp->decoded_from_explicit_params, 0))
goto err;
EC_GROUP_free(grp);
/* Test EC_GROUP_new_by_curve_name not setting the flag */
grp = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
if (!TEST_ptr(grp)
|| !TEST_int_eq(grp->decoded_from_explicit_params, 0))
goto err;
/* Test EC_GROUP_new_from_ecparameters not setting the flag */
if (!TEST_ptr(ecparams = EC_GROUP_get_ecparameters(grp, NULL))
|| !TEST_ptr(grp_copy = EC_GROUP_new_from_ecparameters(ecparams))
|| !TEST_int_eq(grp_copy->decoded_from_explicit_params, 0))
goto err;
EC_GROUP_free(grp_copy);
grp_copy = NULL;
ECPARAMETERS_free(ecparams);
ecparams = NULL;
/* Test EC_GROUP_new_from_ecpkparameters not setting the flag */
if (!TEST_int_eq(EC_GROUP_get_asn1_flag(grp), OPENSSL_EC_NAMED_CURVE)
|| !TEST_ptr(ecpkparams = EC_GROUP_get_ecpkparameters(grp, NULL))
|| !TEST_ptr(grp_copy = EC_GROUP_new_from_ecpkparameters(ecpkparams))
|| !TEST_int_eq(grp_copy->decoded_from_explicit_params, 0)
|| !TEST_ptr(key = EC_KEY_new())
/* Test EC_KEY_decoded_from_explicit_params on key without a group */
|| !TEST_int_eq(EC_KEY_decoded_from_explicit_params(key), -1)
|| !TEST_int_eq(EC_KEY_set_group(key, grp_copy), 1)
/* Test EC_KEY_decoded_from_explicit_params negative case */
|| !TEST_int_eq(EC_KEY_decoded_from_explicit_params(key), 0))
goto err;
EC_GROUP_free(grp_copy);
grp_copy = NULL;
ECPKPARAMETERS_free(ecpkparams);
ecpkparams = NULL;
/* Test d2i_ECPKParameters with named params not setting the flag */
if (!TEST_int_gt(encodedlen = i2d_ECPKParameters(grp, &encodedparams), 0)
|| !TEST_ptr(encp = encodedparams)
|| !TEST_ptr(grp_copy = d2i_ECPKParameters(NULL, &encp, encodedlen))
|| !TEST_int_eq(grp_copy->decoded_from_explicit_params, 0))
goto err;
EC_GROUP_free(grp_copy);
grp_copy = NULL;
OPENSSL_free(encodedparams);
encodedparams = NULL;
/* Asn1 flag stays set to explicit with EC_GROUP_new_from_ecpkparameters */
EC_GROUP_set_asn1_flag(grp, OPENSSL_EC_EXPLICIT_CURVE);
if (!TEST_ptr(ecpkparams = EC_GROUP_get_ecpkparameters(grp, NULL))
|| !TEST_ptr(grp_copy = EC_GROUP_new_from_ecpkparameters(ecpkparams))
|| !TEST_int_eq(EC_GROUP_get_asn1_flag(grp_copy), OPENSSL_EC_EXPLICIT_CURVE)
|| !TEST_int_eq(grp_copy->decoded_from_explicit_params, 0))
goto err;
EC_GROUP_free(grp_copy);
grp_copy = NULL;
/* Test d2i_ECPKParameters with explicit params setting the flag */
if (!TEST_int_gt(encodedlen = i2d_ECPKParameters(grp, &encodedparams), 0)
|| !TEST_ptr(encp = encodedparams)
|| !TEST_ptr(grp_copy = d2i_ECPKParameters(NULL, &encp, encodedlen))
|| !TEST_int_eq(EC_GROUP_get_asn1_flag(grp_copy), OPENSSL_EC_EXPLICIT_CURVE)
|| !TEST_int_eq(grp_copy->decoded_from_explicit_params, 1)
|| !TEST_int_eq(EC_KEY_set_group(key, grp_copy), 1)
/* Test EC_KEY_decoded_from_explicit_params positive case */
|| !TEST_int_eq(EC_KEY_decoded_from_explicit_params(key), 1))
goto err;
testresult = 1;
err:
EC_KEY_free(key);
EC_GROUP_free(grp);
EC_GROUP_free(grp_copy);
ECPARAMETERS_free(ecparams);
ECPKPARAMETERS_free(ecpkparams);
OPENSSL_free(encodedparams);
return testresult;
}
static
int ecpkparams_i2d2i_test(int n)
{
EC_GROUP *g1 = NULL, *g2 = NULL;
FILE *fp = NULL;
int nid = curves[n].nid;
int testresult = 0;
/* create group */
if (!TEST_ptr(g1 = EC_GROUP_new_by_curve_name(nid)))
goto end;
/* encode params to file */
if (!TEST_ptr(fp = fopen("params.der", "wb"))
|| !TEST_true(i2d_ECPKParameters_fp(fp, g1)))
goto end;
/* flush and close file */
if (!TEST_int_eq(fclose(fp), 0)) {
fp = NULL;
goto end;
}
fp = NULL;
/* decode params from file */
if (!TEST_ptr(fp = fopen("params.der", "rb"))
|| !TEST_ptr(g2 = d2i_ECPKParameters_fp(fp, NULL)))
goto end;
testresult = 1; /* PASS */
end:
if (fp != NULL)
fclose(fp);
EC_GROUP_free(g1);
EC_GROUP_free(g2);
return testresult;
}
int setup_tests(void)
{
crv_len = EC_get_builtin_curves(NULL, 0);
if (!TEST_ptr(curves = OPENSSL_malloc(sizeof(*curves) * crv_len))
|| !TEST_true(EC_get_builtin_curves(curves, crv_len)))
return 0;
ADD_TEST(field_tests_ecp_simple);
ADD_TEST(field_tests_ecp_mont);
#ifndef OPENSSL_NO_EC2M
ADD_TEST(field_tests_ec2_simple);
#endif
ADD_ALL_TESTS(field_tests_default, crv_len);
#ifndef OPENSSL_NO_EC_NISTP_64_GCC_128
ADD_TEST(underflow_test);
#endif
ADD_TEST(set_private_key);
ADD_TEST(decoded_flag_test);
ADD_ALL_TESTS(ecpkparams_i2d2i_test, crv_len);
return 1;
}
void cleanup_tests(void)
{
OPENSSL_free(curves);
}
| 14,909 | 31.203024 | 90 | c |
openssl | openssl-master/test/ecdsatest.c | /*
* Copyright 2002-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2002, 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
*/
/*
* Low level APIs are deprecated for public use, but still ok for internal use.
*/
#include "internal/deprecated.h"
#include <openssl/opensslconf.h> /* To see if OPENSSL_NO_EC is defined */
#include "testutil.h"
#ifndef OPENSSL_NO_EC
# include <openssl/evp.h>
# include <openssl/bn.h>
# include <openssl/ec.h>
# include <openssl/rand.h>
# include "internal/nelem.h"
# include "ecdsatest.h"
static fake_random_generate_cb fbytes;
static const char *numbers[2];
static size_t crv_len = 0;
static EC_builtin_curve *curves = NULL;
static OSSL_PROVIDER *fake_rand = NULL;
static int fbytes(unsigned char *buf, size_t num, ossl_unused const char *name,
EVP_RAND_CTX *ctx)
{
int ret = 0;
static int fbytes_counter = 0;
BIGNUM *tmp = NULL;
fake_rand_set_callback(ctx, NULL);
if (!TEST_ptr(tmp = BN_new())
|| !TEST_int_lt(fbytes_counter, OSSL_NELEM(numbers))
|| !TEST_true(BN_hex2bn(&tmp, numbers[fbytes_counter]))
/* tmp might need leading zeros so pad it out */
|| !TEST_int_le(BN_num_bytes(tmp), num)
|| !TEST_int_gt(BN_bn2binpad(tmp, buf, num), 0))
goto err;
fbytes_counter = (fbytes_counter + 1) % OSSL_NELEM(numbers);
ret = 1;
err:
BN_free(tmp);
return ret;
}
/*-
* This function hijacks the RNG to feed it the chosen ECDSA key and nonce.
* The ECDSA KATs are from:
* - the X9.62 draft (4)
* - NIST CAVP (720)
*
* It uses the low-level ECDSA_sign_setup instead of EVP to control the RNG.
* NB: This is not how applications should use ECDSA; this is only for testing.
*
* Tests the library can successfully:
* - generate public keys that matches those KATs
* - create ECDSA signatures that match those KATs
* - accept those signatures as valid
*/
static int x9_62_tests(int n)
{
int nid, md_nid, ret = 0;
const char *r_in = NULL, *s_in = NULL, *tbs = NULL;
unsigned char *pbuf = NULL, *qbuf = NULL, *message = NULL;
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int dgst_len = 0;
long q_len, msg_len = 0;
size_t p_len;
EVP_MD_CTX *mctx = NULL;
EC_KEY *key = NULL;
ECDSA_SIG *signature = NULL;
BIGNUM *r = NULL, *s = NULL;
BIGNUM *kinv = NULL, *rp = NULL;
const BIGNUM *sig_r = NULL, *sig_s = NULL;
nid = ecdsa_cavs_kats[n].nid;
md_nid = ecdsa_cavs_kats[n].md_nid;
r_in = ecdsa_cavs_kats[n].r;
s_in = ecdsa_cavs_kats[n].s;
tbs = ecdsa_cavs_kats[n].msg;
numbers[0] = ecdsa_cavs_kats[n].d;
numbers[1] = ecdsa_cavs_kats[n].k;
TEST_info("ECDSA KATs for curve %s", OBJ_nid2sn(nid));
#ifdef FIPS_MODULE
if (EC_curve_nid2nist(nid) == NULL)
return TEST_skip("skip non approved curves");
#endif /* FIPS_MODULE */
if (!TEST_ptr(mctx = EVP_MD_CTX_new())
/* get the message digest */
|| !TEST_ptr(message = OPENSSL_hexstr2buf(tbs, &msg_len))
|| !TEST_true(EVP_DigestInit_ex(mctx, EVP_get_digestbynid(md_nid), NULL))
|| !TEST_true(EVP_DigestUpdate(mctx, message, msg_len))
|| !TEST_true(EVP_DigestFinal_ex(mctx, digest, &dgst_len))
/* create the key */
|| !TEST_ptr(key = EC_KEY_new_by_curve_name(nid))
/* load KAT variables */
|| !TEST_ptr(r = BN_new())
|| !TEST_ptr(s = BN_new())
|| !TEST_true(BN_hex2bn(&r, r_in))
|| !TEST_true(BN_hex2bn(&s, s_in)))
goto err;
/* public key must match KAT */
fake_rand_set_callback(RAND_get0_private(NULL), &fbytes);
if (!TEST_true(EC_KEY_generate_key(key))
|| !TEST_true(p_len = EC_KEY_key2buf(key, POINT_CONVERSION_UNCOMPRESSED,
&pbuf, NULL))
|| !TEST_ptr(qbuf = OPENSSL_hexstr2buf(ecdsa_cavs_kats[n].Q, &q_len))
|| !TEST_int_eq(q_len, p_len)
|| !TEST_mem_eq(qbuf, q_len, pbuf, p_len))
goto err;
/* create the signature via ECDSA_sign_setup to avoid use of ECDSA nonces */
fake_rand_set_callback(RAND_get0_private(NULL), &fbytes);
if (!TEST_true(ECDSA_sign_setup(key, NULL, &kinv, &rp))
|| !TEST_ptr(signature = ECDSA_do_sign_ex(digest, dgst_len,
kinv, rp, key))
/* verify the signature */
|| !TEST_int_eq(ECDSA_do_verify(digest, dgst_len, signature, key), 1))
goto err;
/* compare the created signature with the expected signature */
ECDSA_SIG_get0(signature, &sig_r, &sig_s);
if (!TEST_BN_eq(sig_r, r)
|| !TEST_BN_eq(sig_s, s))
goto err;
ret = 1;
err:
OPENSSL_free(message);
OPENSSL_free(pbuf);
OPENSSL_free(qbuf);
EC_KEY_free(key);
ECDSA_SIG_free(signature);
BN_free(r);
BN_free(s);
EVP_MD_CTX_free(mctx);
BN_clear_free(kinv);
BN_clear_free(rp);
return ret;
}
/*-
* Positive and negative ECDSA testing through EVP interface:
* - EVP_DigestSign (this is the one-shot version)
* - EVP_DigestVerify
*
* Tests the library can successfully:
* - create a key
* - create a signature
* - accept that signature
* - reject that signature with a different public key
* - reject that signature if its length is not correct
* - reject that signature after modifying the message
* - accept that signature after un-modifying the message
* - reject that signature after modifying the signature
* - accept that signature after un-modifying the signature
*/
static int set_sm2_id(EVP_MD_CTX *mctx, EVP_PKEY *pkey)
{
/* With the SM2 key type, the SM2 ID is mandatory */
static const char sm2_id[] = { 1, 2, 3, 4, 'l', 'e', 't', 't', 'e', 'r' };
EVP_PKEY_CTX *pctx;
if (!TEST_ptr(pctx = EVP_MD_CTX_get_pkey_ctx(mctx))
|| !TEST_int_gt(EVP_PKEY_CTX_set1_id(pctx, sm2_id, sizeof(sm2_id)), 0))
return 0;
return 1;
}
static int test_builtin(int n, int as)
{
EC_KEY *eckey_neg = NULL, *eckey = NULL;
unsigned char dirt, offset, tbs[128];
unsigned char *sig = NULL;
EVP_PKEY *pkey_neg = NULL, *pkey = NULL, *dup_pk = NULL;
EVP_MD_CTX *mctx = NULL;
size_t sig_len;
int nid, ret = 0;
int temp;
nid = curves[n].nid;
/* skip built-in curves where ord(G) is not prime */
if (nid == NID_ipsec4 || nid == NID_ipsec3) {
TEST_info("skipped: ECDSA unsupported for curve %s", OBJ_nid2sn(nid));
return 1;
}
/*
* skip SM2 curve if 'as' is equal to EVP_PKEY_EC or, skip all curves
* except SM2 curve if 'as' is equal to EVP_PKEY_SM2
*/
if (nid == NID_sm2 && as == EVP_PKEY_EC) {
TEST_info("skipped: EC key type unsupported for curve %s",
OBJ_nid2sn(nid));
return 1;
} else if (nid != NID_sm2 && as == EVP_PKEY_SM2) {
TEST_info("skipped: SM2 key type unsupported for curve %s",
OBJ_nid2sn(nid));
return 1;
}
TEST_info("testing ECDSA for curve %s as %s key type", OBJ_nid2sn(nid),
as == EVP_PKEY_EC ? "EC" : "SM2");
if (!TEST_ptr(mctx = EVP_MD_CTX_new())
/* get some random message data */
|| !TEST_int_gt(RAND_bytes(tbs, sizeof(tbs)), 0)
/* real key */
|| !TEST_ptr(eckey = EC_KEY_new_by_curve_name(nid))
|| !TEST_true(EC_KEY_generate_key(eckey))
|| !TEST_ptr(pkey = EVP_PKEY_new())
|| !TEST_true(EVP_PKEY_assign_EC_KEY(pkey, eckey))
/* fake key for negative testing */
|| !TEST_ptr(eckey_neg = EC_KEY_new_by_curve_name(nid))
|| !TEST_true(EC_KEY_generate_key(eckey_neg))
|| !TEST_ptr(pkey_neg = EVP_PKEY_new())
|| !TEST_false(EVP_PKEY_assign_EC_KEY(pkey_neg, NULL))
|| !TEST_true(EVP_PKEY_assign_EC_KEY(pkey_neg, eckey_neg)))
goto err;
if (!TEST_ptr(dup_pk = EVP_PKEY_dup(pkey))
|| !TEST_int_eq(EVP_PKEY_eq(pkey, dup_pk), 1))
goto err;
temp = ECDSA_size(eckey);
if (!TEST_int_ge(temp, 0)
|| !TEST_ptr(sig = OPENSSL_malloc(sig_len = (size_t)temp))
/* create a signature */
|| !TEST_true(EVP_DigestSignInit(mctx, NULL, NULL, NULL, pkey))
|| (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
|| !TEST_true(EVP_DigestSign(mctx, sig, &sig_len, tbs, sizeof(tbs)))
|| !TEST_int_le(sig_len, ECDSA_size(eckey))
|| !TEST_true(EVP_MD_CTX_reset(mctx))
/* negative test, verify with wrong key, 0 return */
|| !TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey_neg))
|| (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey_neg))
|| !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 0)
|| !TEST_true(EVP_MD_CTX_reset(mctx))
/* negative test, verify with wrong signature length, -1 return */
|| !TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
|| (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
|| !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len - 1, tbs, sizeof(tbs)), -1)
|| !TEST_true(EVP_MD_CTX_reset(mctx))
/* positive test, verify with correct key, 1 return */
|| !TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
|| (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
|| !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 1)
|| !TEST_true(EVP_MD_CTX_reset(mctx)))
goto err;
/* muck with the message, test it fails with 0 return */
tbs[0] ^= 1;
if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
|| (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
|| !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 0)
|| !TEST_true(EVP_MD_CTX_reset(mctx)))
goto err;
/* un-muck and test it verifies */
tbs[0] ^= 1;
if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
|| (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
|| !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 1)
|| !TEST_true(EVP_MD_CTX_reset(mctx)))
goto err;
/*-
* Muck with the ECDSA signature. The DER encoding is one of:
* - 30 LL 02 ..
* - 30 81 LL 02 ..
*
* - Sometimes this mucks with the high level DER sequence wrapper:
* in that case, DER-parsing of the whole signature should fail.
*
* - Sometimes this mucks with the DER-encoding of ECDSA.r:
* in that case, DER-parsing of ECDSA.r should fail.
*
* - Sometimes this mucks with the DER-encoding of ECDSA.s:
* in that case, DER-parsing of ECDSA.s should fail.
*
* - Sometimes this mucks with ECDSA.r:
* in that case, the signature verification should fail.
*
* - Sometimes this mucks with ECDSA.s:
* in that case, the signature verification should fail.
*
* The usual case is changing the integer value of ECDSA.r or ECDSA.s.
* Because the ratio of DER overhead to signature bytes is small.
* So most of the time it will be one of the last two cases.
*
* In any case, EVP_PKEY_verify should not return 1 for valid.
*/
offset = tbs[0] % sig_len;
dirt = tbs[1] ? tbs[1] : 1;
sig[offset] ^= dirt;
if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
|| (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
|| !TEST_int_ne(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 1)
|| !TEST_true(EVP_MD_CTX_reset(mctx)))
goto err;
/* un-muck and test it verifies */
sig[offset] ^= dirt;
if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
|| (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
|| !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 1)
|| !TEST_true(EVP_MD_CTX_reset(mctx)))
goto err;
ret = 1;
err:
EVP_PKEY_free(pkey);
EVP_PKEY_free(pkey_neg);
EVP_PKEY_free(dup_pk);
EVP_MD_CTX_free(mctx);
OPENSSL_free(sig);
return ret;
}
static int test_builtin_as_ec(int n)
{
return test_builtin(n, EVP_PKEY_EC);
}
# ifndef OPENSSL_NO_SM2
static int test_builtin_as_sm2(int n)
{
return test_builtin(n, EVP_PKEY_SM2);
}
# endif
static int test_ecdsa_sig_NULL(void)
{
int ret;
unsigned int siglen;
unsigned char dgst[128] = { 0 };
EC_KEY *eckey = NULL;
ret = TEST_ptr(eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1))
&& TEST_int_eq(EC_KEY_generate_key(eckey), 1)
&& TEST_int_eq(ECDSA_sign(0, dgst, sizeof(dgst), NULL, &siglen, eckey), 1)
&& TEST_int_gt(siglen, 0);
EC_KEY_free(eckey);
return ret;
}
#endif /* OPENSSL_NO_EC */
int setup_tests(void)
{
#ifdef OPENSSL_NO_EC
TEST_note("Elliptic curves are disabled.");
#else
fake_rand = fake_rand_start(NULL);
if (fake_rand == NULL)
return 0;
/* get a list of all internal curves */
crv_len = EC_get_builtin_curves(NULL, 0);
if (!TEST_ptr(curves = OPENSSL_malloc(sizeof(*curves) * crv_len))
|| !TEST_true(EC_get_builtin_curves(curves, crv_len))) {
fake_rand_finish(fake_rand);
return 0;
}
ADD_ALL_TESTS(test_builtin_as_ec, crv_len);
ADD_TEST(test_ecdsa_sig_NULL);
# ifndef OPENSSL_NO_SM2
ADD_ALL_TESTS(test_builtin_as_sm2, crv_len);
# endif
ADD_ALL_TESTS(x9_62_tests, OSSL_NELEM(ecdsa_cavs_kats));
#endif
return 1;
}
void cleanup_tests(void)
{
#ifndef OPENSSL_NO_EC
fake_rand_finish(fake_rand);
OPENSSL_free(curves);
#endif
}
| 13,830 | 33.5775 | 87 | c |
openssl | openssl-master/test/ecstresstest.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 may obtain a copy of the License at
* https://www.openssl.org/source/license.html
* or in the file LICENSE in the source distribution.
*/
#include "internal/nelem.h"
#include "testutil.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define NUM_REPEATS "1000000"
static ossl_intmax_t num_repeats;
static int print_mode = 0;
#ifndef OPENSSL_NO_EC
# include <openssl/ec.h>
# include <openssl/err.h>
# include <openssl/obj_mac.h>
# include <openssl/objects.h>
# include <openssl/rand.h>
# include <openssl/bn.h>
# include <openssl/opensslconf.h>
static const char *kP256DefaultResult =
"A1E24B223B8E81BC1FFF99BAFB909EDB895FACDE7D6DA5EF5E7B3255FB378E0F";
/*
* Perform a deterministic walk on the curve, by starting from |point| and
* using the X-coordinate of the previous point as the next scalar for
* point multiplication.
* Returns the X-coordinate of the end result or NULL on error.
*/
static BIGNUM *walk_curve(const EC_GROUP *group, EC_POINT *point,
ossl_intmax_t num)
{
BIGNUM *scalar = NULL;
ossl_intmax_t i;
if (!TEST_ptr(scalar = BN_new())
|| !TEST_true(EC_POINT_get_affine_coordinates(group, point, scalar,
NULL, NULL)))
goto err;
for (i = 0; i < num; i++) {
if (!TEST_true(EC_POINT_mul(group, point, NULL, point, scalar, NULL))
|| !TEST_true(EC_POINT_get_affine_coordinates(group, point,
scalar,
NULL, NULL)))
goto err;
}
return scalar;
err:
BN_free(scalar);
return NULL;
}
static int test_curve(void)
{
EC_GROUP *group = NULL;
EC_POINT *point = NULL;
BIGNUM *result = NULL, *expected_result = NULL;
int ret = 0;
/*
* We currently hard-code P-256, though adaptation to other curves.
* would be straightforward.
*/
if (!TEST_ptr(group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1))
|| !TEST_ptr(point = EC_POINT_dup(EC_GROUP_get0_generator(group),
group))
|| !TEST_ptr(result = walk_curve(group, point, num_repeats)))
return 0;
if (print_mode) {
BN_print(bio_out, result);
BIO_printf(bio_out, "\n");
ret = 1;
} else {
if (!TEST_true(BN_hex2bn(&expected_result, kP256DefaultResult))
|| !TEST_ptr(expected_result)
|| !TEST_BN_eq(result, expected_result))
goto err;
ret = 1;
}
err:
EC_GROUP_free(group);
EC_POINT_free(point);
BN_free(result);
BN_free(expected_result);
return ret;
}
#endif
typedef enum OPTION_choice {
OPT_ERR = -1,
OPT_EOF = 0,
OPT_NUM_REPEATS,
OPT_TEST_ENUM
} OPTION_CHOICE;
const OPTIONS *test_get_options(void)
{
static const OPTIONS test_options[] = {
OPT_TEST_OPTIONS_DEFAULT_USAGE,
{ "num", OPT_NUM_REPEATS, 'M', "Number of repeats" },
{ NULL }
};
return test_options;
}
/*
* Stress test the curve. If the '-num' argument is given, runs the loop
* |num| times and prints the resulting X-coordinate. Otherwise runs the test
* the default number of times and compares against the expected result.
*/
int setup_tests(void)
{
OPTION_CHOICE o;
if (!opt_intmax(NUM_REPEATS, &num_repeats)) {
TEST_error("Cannot parse " NUM_REPEATS);
return 0;
}
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_NUM_REPEATS:
if (!opt_intmax(opt_arg(), &num_repeats)
|| num_repeats < 0)
return 0;
print_mode = 1;
break;
case OPT_TEST_CASES:
break;
default:
case OPT_ERR:
return 0;
}
}
#ifndef OPENSSL_NO_EC
ADD_TEST(test_curve);
#endif
return 1;
}
| 4,217 | 25.866242 | 79 | c |
openssl | openssl-master/test/enginetest.c | /*
* Copyright 2000-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
*/
/* We need to use some deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/e_os2.h>
# include "testutil.h"
#ifndef OPENSSL_NO_ENGINE
# include <openssl/buffer.h>
# include <openssl/crypto.h>
# include <openssl/engine.h>
# include <openssl/rsa.h>
# include <openssl/err.h>
# include <openssl/x509.h>
# include <openssl/pem.h>
static void display_engine_list(void)
{
ENGINE *h;
int loop;
loop = 0;
for (h = ENGINE_get_first(); h != NULL; h = ENGINE_get_next(h)) {
TEST_info("#%d: id = \"%s\", name = \"%s\"",
loop++, ENGINE_get_id(h), ENGINE_get_name(h));
}
/*
* ENGINE_get_first() increases the struct_ref counter, so we must call
* ENGINE_free() to decrease it again
*/
ENGINE_free(h);
}
#define NUMTOADD 512
static int test_engines(void)
{
ENGINE *block[NUMTOADD];
char *eid[NUMTOADD];
char *ename[NUMTOADD];
char buf[256];
ENGINE *ptr;
int loop;
int to_return = 0;
ENGINE *new_h1 = NULL;
ENGINE *new_h2 = NULL;
ENGINE *new_h3 = NULL;
ENGINE *new_h4 = NULL;
memset(block, 0, sizeof(block));
if (!TEST_ptr(new_h1 = ENGINE_new())
|| !TEST_true(ENGINE_set_id(new_h1, "test_id0"))
|| !TEST_true(ENGINE_set_name(new_h1, "First test item"))
|| !TEST_ptr(new_h2 = ENGINE_new())
|| !TEST_true(ENGINE_set_id(new_h2, "test_id1"))
|| !TEST_true(ENGINE_set_name(new_h2, "Second test item"))
|| !TEST_ptr(new_h3 = ENGINE_new())
|| !TEST_true(ENGINE_set_id(new_h3, "test_id2"))
|| !TEST_true(ENGINE_set_name(new_h3, "Third test item"))
|| !TEST_ptr(new_h4 = ENGINE_new())
|| !TEST_true(ENGINE_set_id(new_h4, "test_id3"))
|| !TEST_true(ENGINE_set_name(new_h4, "Fourth test item")))
goto end;
TEST_info("Engines:");
display_engine_list();
if (!TEST_true(ENGINE_add(new_h1)))
goto end;
TEST_info("Engines:");
display_engine_list();
ptr = ENGINE_get_first();
if (!TEST_true(ENGINE_remove(ptr)))
goto end;
ENGINE_free(ptr);
TEST_info("Engines:");
display_engine_list();
if (!TEST_true(ENGINE_add(new_h3))
|| !TEST_true(ENGINE_add(new_h2)))
goto end;
TEST_info("Engines:");
display_engine_list();
if (!TEST_true(ENGINE_remove(new_h2)))
goto end;
TEST_info("Engines:");
display_engine_list();
if (!TEST_true(ENGINE_add(new_h4)))
goto end;
TEST_info("Engines:");
display_engine_list();
/* Should fail. */
if (!TEST_false(ENGINE_add(new_h3)))
goto end;
ERR_clear_error();
/* Should fail. */
if (!TEST_false(ENGINE_remove(new_h2)))
goto end;
ERR_clear_error();
if (!TEST_true(ENGINE_remove(new_h3)))
goto end;
TEST_info("Engines:");
display_engine_list();
if (!TEST_true(ENGINE_remove(new_h4)))
goto end;
TEST_info("Engines:");
display_engine_list();
/*
* At this point, we should have an empty list, unless some hardware
* support engine got added. However, since we don't allow the config
* file to be loaded and don't otherwise load any built in engines,
* that is unlikely. Still, we check, if for nothing else, then to
* notify that something is a little off (and might mean that |new_h1|
* wasn't unloaded when it should have)
*/
if ((ptr = ENGINE_get_first()) != NULL) {
if (!ENGINE_remove(ptr))
TEST_info("Remove failed - probably no hardware support present");
}
ENGINE_free(ptr);
TEST_info("Engines:");
display_engine_list();
if (!TEST_true(ENGINE_add(new_h1))
|| !TEST_true(ENGINE_remove(new_h1)))
goto end;
TEST_info("About to beef up the engine-type list");
for (loop = 0; loop < NUMTOADD; loop++) {
sprintf(buf, "id%d", loop);
eid[loop] = OPENSSL_strdup(buf);
sprintf(buf, "Fake engine type %d", loop);
ename[loop] = OPENSSL_strdup(buf);
if (!TEST_ptr(block[loop] = ENGINE_new())
|| !TEST_true(ENGINE_set_id(block[loop], eid[loop]))
|| !TEST_true(ENGINE_set_name(block[loop], ename[loop])))
goto end;
}
for (loop = 0; loop < NUMTOADD; loop++) {
if (!TEST_true(ENGINE_add(block[loop]))) {
test_note("Adding stopped at %d, (%s,%s)",
loop, ENGINE_get_id(block[loop]),
ENGINE_get_name(block[loop]));
goto cleanup_loop;
}
}
cleanup_loop:
TEST_info("About to empty the engine-type list");
while ((ptr = ENGINE_get_first()) != NULL) {
if (!TEST_true(ENGINE_remove(ptr)))
goto end;
ENGINE_free(ptr);
}
for (loop = 0; loop < NUMTOADD; loop++) {
OPENSSL_free(eid[loop]);
OPENSSL_free(ename[loop]);
}
to_return = 1;
end:
ENGINE_free(new_h1);
ENGINE_free(new_h2);
ENGINE_free(new_h3);
ENGINE_free(new_h4);
for (loop = 0; loop < NUMTOADD; loop++)
ENGINE_free(block[loop]);
return to_return;
}
/* Test EVP_PKEY method */
static EVP_PKEY_METHOD *test_rsa = NULL;
static int called_encrypt = 0;
/* Test function to check operation has been redirected */
static int test_encrypt(EVP_PKEY_CTX *ctx, unsigned char *sig,
size_t *siglen, const unsigned char *tbs, size_t tbslen)
{
called_encrypt = 1;
return 1;
}
static int test_pkey_meths(ENGINE *e, EVP_PKEY_METHOD **pmeth,
const int **pnids, int nid)
{
static const int rnid = EVP_PKEY_RSA;
if (pmeth == NULL) {
*pnids = &rnid;
return 1;
}
if (nid == EVP_PKEY_RSA) {
*pmeth = test_rsa;
return 1;
}
*pmeth = NULL;
return 0;
}
/* Return a test EVP_PKEY value */
static EVP_PKEY *get_test_pkey(void)
{
static unsigned char n[] =
"\x00\xAA\x36\xAB\xCE\x88\xAC\xFD\xFF\x55\x52\x3C\x7F\xC4\x52\x3F"
"\x90\xEF\xA0\x0D\xF3\x77\x4A\x25\x9F\x2E\x62\xB4\xC5\xD9\x9C\xB5"
"\xAD\xB3\x00\xA0\x28\x5E\x53\x01\x93\x0E\x0C\x70\xFB\x68\x76\x93"
"\x9C\xE6\x16\xCE\x62\x4A\x11\xE0\x08\x6D\x34\x1E\xBC\xAC\xA0\xA1"
"\xF5";
static unsigned char e[] = "\x11";
RSA *rsa = RSA_new();
EVP_PKEY *pk = EVP_PKEY_new();
if (rsa == NULL || pk == NULL || !EVP_PKEY_assign_RSA(pk, rsa)) {
RSA_free(rsa);
EVP_PKEY_free(pk);
return NULL;
}
if (!RSA_set0_key(rsa, BN_bin2bn(n, sizeof(n)-1, NULL),
BN_bin2bn(e, sizeof(e)-1, NULL), NULL)) {
EVP_PKEY_free(pk);
return NULL;
}
return pk;
}
static int test_redirect(void)
{
const unsigned char pt[] = "Hello World\n";
unsigned char *tmp = NULL;
size_t len;
EVP_PKEY_CTX *ctx = NULL;
ENGINE *e = NULL;
EVP_PKEY *pkey = NULL;
int to_return = 0;
if (!TEST_ptr(pkey = get_test_pkey()))
goto err;
len = EVP_PKEY_get_size(pkey);
if (!TEST_ptr(tmp = OPENSSL_malloc(len)))
goto err;
if (!TEST_ptr(ctx = EVP_PKEY_CTX_new(pkey, NULL)))
goto err;
TEST_info("EVP_PKEY_encrypt test: no redirection");
/* Encrypt some data: should succeed but not be redirected */
if (!TEST_int_gt(EVP_PKEY_encrypt_init(ctx), 0)
|| !TEST_int_gt(EVP_PKEY_encrypt(ctx, tmp, &len, pt, sizeof(pt)), 0)
|| !TEST_false(called_encrypt))
goto err;
EVP_PKEY_CTX_free(ctx);
ctx = NULL;
/* Create a test ENGINE */
if (!TEST_ptr(e = ENGINE_new())
|| !TEST_true(ENGINE_set_id(e, "Test redirect engine"))
|| !TEST_true(ENGINE_set_name(e, "Test redirect engine")))
goto err;
/*
* Try to create a context for this engine and test key.
* Try setting test key engine. Both should fail because the
* engine has no public key methods.
*/
if (!TEST_ptr_null(ctx = EVP_PKEY_CTX_new(pkey, e))
|| !TEST_int_le(EVP_PKEY_set1_engine(pkey, e), 0))
goto err;
/* Setup an empty test EVP_PKEY_METHOD and set callback to return it */
if (!TEST_ptr(test_rsa = EVP_PKEY_meth_new(EVP_PKEY_RSA, 0)))
goto err;
ENGINE_set_pkey_meths(e, test_pkey_meths);
/* Getting a context for test ENGINE should now succeed */
if (!TEST_ptr(ctx = EVP_PKEY_CTX_new(pkey, e)))
goto err;
/* Encrypt should fail because operation is not supported */
if (!TEST_int_le(EVP_PKEY_encrypt_init(ctx), 0))
goto err;
EVP_PKEY_CTX_free(ctx);
ctx = NULL;
/* Add test encrypt operation to method */
EVP_PKEY_meth_set_encrypt(test_rsa, 0, test_encrypt);
TEST_info("EVP_PKEY_encrypt test: redirection via EVP_PKEY_CTX_new()");
if (!TEST_ptr(ctx = EVP_PKEY_CTX_new(pkey, e)))
goto err;
/* Encrypt some data: should succeed and be redirected */
if (!TEST_int_gt(EVP_PKEY_encrypt_init(ctx), 0)
|| !TEST_int_gt(EVP_PKEY_encrypt(ctx, tmp, &len, pt, sizeof(pt)), 0)
|| !TEST_true(called_encrypt))
goto err;
EVP_PKEY_CTX_free(ctx);
ctx = NULL;
called_encrypt = 0;
/* Create context with default engine: should not be redirected */
if (!TEST_ptr(ctx = EVP_PKEY_CTX_new(pkey, NULL))
|| !TEST_int_gt(EVP_PKEY_encrypt_init(ctx), 0)
|| !TEST_int_gt(EVP_PKEY_encrypt(ctx, tmp, &len, pt, sizeof(pt)), 0)
|| !TEST_false(called_encrypt))
goto err;
EVP_PKEY_CTX_free(ctx);
ctx = NULL;
/* Set engine explicitly for test key */
if (!TEST_true(EVP_PKEY_set1_engine(pkey, e)))
goto err;
TEST_info("EVP_PKEY_encrypt test: redirection via EVP_PKEY_set1_engine()");
/* Create context with default engine: should be redirected now */
if (!TEST_ptr(ctx = EVP_PKEY_CTX_new(pkey, NULL))
|| !TEST_int_gt(EVP_PKEY_encrypt_init(ctx), 0)
|| !TEST_int_gt(EVP_PKEY_encrypt(ctx, tmp, &len, pt, sizeof(pt)), 0)
|| !TEST_true(called_encrypt))
goto err;
to_return = 1;
err:
EVP_PKEY_CTX_free(ctx);
EVP_PKEY_free(pkey);
ENGINE_free(e);
OPENSSL_free(tmp);
return to_return;
}
static int test_x509_dup_w_engine(void)
{
ENGINE *e = NULL;
X509 *cert = NULL, *dupcert = NULL;
X509_PUBKEY *pubkey, *duppubkey = NULL;
int ret = 0;
BIO *b = NULL;
RSA_METHOD *rsameth = NULL;
if (!TEST_ptr(b = BIO_new_file(test_get_argument(0), "r"))
|| !TEST_ptr(cert = PEM_read_bio_X509(b, NULL, NULL, NULL)))
goto err;
/* Dup without an engine */
if (!TEST_ptr(dupcert = X509_dup(cert)))
goto err;
X509_free(dupcert);
dupcert = NULL;
if (!TEST_ptr(pubkey = X509_get_X509_PUBKEY(cert))
|| !TEST_ptr(duppubkey = X509_PUBKEY_dup(pubkey))
|| !TEST_ptr_ne(duppubkey, pubkey)
|| !TEST_ptr_ne(X509_PUBKEY_get0(duppubkey), X509_PUBKEY_get0(pubkey)))
goto err;
X509_PUBKEY_free(duppubkey);
duppubkey = NULL;
X509_free(cert);
cert = NULL;
/* Create a test ENGINE */
if (!TEST_ptr(e = ENGINE_new())
|| !TEST_true(ENGINE_set_id(e, "Test dummy engine"))
|| !TEST_true(ENGINE_set_name(e, "Test dummy engine")))
goto err;
if (!TEST_ptr(rsameth = RSA_meth_dup(RSA_get_default_method())))
goto err;
ENGINE_set_RSA(e, rsameth);
if (!TEST_true(ENGINE_set_default_RSA(e)))
goto err;
if (!TEST_int_ge(BIO_seek(b, 0), 0)
|| !TEST_ptr(cert = PEM_read_bio_X509(b, NULL, NULL, NULL)))
goto err;
/* Dup with an engine set on the key */
if (!TEST_ptr(dupcert = X509_dup(cert)))
goto err;
if (!TEST_ptr(pubkey = X509_get_X509_PUBKEY(cert))
|| !TEST_ptr(duppubkey = X509_PUBKEY_dup(pubkey))
|| !TEST_ptr_ne(duppubkey, pubkey)
|| !TEST_ptr_ne(X509_PUBKEY_get0(duppubkey), X509_PUBKEY_get0(pubkey)))
goto err;
ret = 1;
err:
X509_free(cert);
X509_free(dupcert);
X509_PUBKEY_free(duppubkey);
if (e != NULL) {
ENGINE_unregister_RSA(e);
ENGINE_free(e);
}
RSA_meth_free(rsameth);
BIO_free(b);
return ret;
}
#endif
int global_init(void)
{
/*
* If the config file gets loaded, the dynamic engine will be loaded,
* and that interferes with our test above.
*/
return OPENSSL_init_crypto(OPENSSL_INIT_NO_LOAD_CONFIG, NULL);
}
OPT_TEST_DECLARE_USAGE("certfile\n")
int setup_tests(void)
{
#ifdef OPENSSL_NO_ENGINE
TEST_note("No ENGINE support");
#else
int n;
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
n = test_get_argument_count();
if (n == 0)
return 0;
ADD_TEST(test_engines);
ADD_TEST(test_redirect);
ADD_TEST(test_x509_dup_w_engine);
#endif
return 1;
}
| 13,345 | 27.639485 | 80 | c |
openssl | openssl-master/test/errtest.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 <string.h>
#include <openssl/opensslconf.h>
#include <openssl/err.h>
#include <openssl/macros.h>
#include "testutil.h"
#if defined(OPENSSL_SYS_WINDOWS)
# include <windows.h>
#else
# include <errno.h>
#endif
#ifndef OPENSSL_NO_DEPRECATED_3_0
# define IS_HEX(ch) ((ch >= '0' && ch <='9') || (ch >= 'A' && ch <='F'))
static int test_print_error_format(void)
{
/* Variables used to construct an error line */
char *lib;
const char *func = OPENSSL_FUNC;
char *reason;
# ifdef OPENSSL_NO_ERR
char reasonbuf[255];
# endif
# ifndef OPENSSL_NO_FILENAMES
const char *file = OPENSSL_FILE;
const int line = OPENSSL_LINE;
# else
const char *file = "";
const int line = 0;
# endif
/* The format for OpenSSL error lines */
const char *expected_format = ":error:%08lX:%s:%s:%s:%s:%d";
/*-
* ^^ ^^ ^^ ^^ ^^
* "library" name --------------------------++ || || || ||
* function name ------------------------------++ || || ||
* reason string (system error string) -----------++ || ||
* file name ----------------------------------------++ ||
* line number -----------------------------------------++
*/
char expected[512];
char *out = NULL, *p = NULL;
int ret = 0, len;
BIO *bio = NULL;
const int syserr = EPERM;
unsigned long errorcode;
unsigned long reasoncode;
/*
* We set a mark here so we can clear the system error that we generate
* with ERR_PUT_error(). That is, after all, just a simulation to verify
* ERR_print_errors() output, not a real error.
*/
ERR_set_mark();
ERR_PUT_error(ERR_LIB_SYS, 0, syserr, file, line);
errorcode = ERR_peek_error();
reasoncode = ERR_GET_REASON(errorcode);
if (!TEST_int_eq(reasoncode, syserr)) {
ERR_pop_to_mark();
goto err;
}
# if !defined(OPENSSL_NO_ERR)
# if defined(OPENSSL_NO_AUTOERRINIT)
lib = "lib(2)";
# else
lib = "system library";
# endif
reason = strerror(syserr);
# else
lib = "lib(2)";
BIO_snprintf(reasonbuf, sizeof(reasonbuf), "reason(%lu)", reasoncode);
reason = reasonbuf;
# endif
BIO_snprintf(expected, sizeof(expected), expected_format,
errorcode, lib, func, reason, file, line);
if (!TEST_ptr(bio = BIO_new(BIO_s_mem())))
goto err;
ERR_print_errors(bio);
if (!TEST_int_gt(len = BIO_get_mem_data(bio, &out), 0))
goto err;
/* Skip over the variable thread id at the start of the string */
for (p = out; *p != ':' && *p != 0; ++p) {
if (!TEST_true(IS_HEX(*p)))
goto err;
}
if (!TEST_true(*p != 0)
|| !TEST_strn_eq(expected, p, strlen(expected)))
goto err;
ret = 1;
err:
BIO_free(bio);
return ret;
}
#endif
/* Test that querying the error queue preserves the OS error. */
static int preserves_system_error(void)
{
#if defined(OPENSSL_SYS_WINDOWS)
SetLastError(ERROR_INVALID_FUNCTION);
ERR_get_error();
return TEST_int_eq(GetLastError(), ERROR_INVALID_FUNCTION);
#else
errno = EINVAL;
ERR_get_error();
return TEST_int_eq(errno, EINVAL);
#endif
}
/* Test that calls to ERR_add_error_[v]data append */
static int vdata_appends(void)
{
const char *data;
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
ERR_add_error_data(1, "hello ");
ERR_add_error_data(1, "world");
ERR_peek_error_data(&data, NULL);
return TEST_str_eq(data, "hello world");
}
static int raised_error(void)
{
const char *f, *data;
int l;
unsigned long e;
/*
* When OPENSSL_NO_ERR or OPENSSL_NO_FILENAMES, no file name or line
* number is saved, so no point checking them.
*/
#if !defined(OPENSSL_NO_FILENAMES) && !defined(OPENSSL_NO_ERR)
const char *file;
int line;
file = __FILE__;
line = __LINE__ + 2; /* The error is generated on the ERR_raise_data line */
#endif
ERR_raise_data(ERR_LIB_NONE, ERR_R_INTERNAL_ERROR,
"calling exit()");
if (!TEST_ulong_ne(e = ERR_get_error_all(&f, &l, NULL, &data, NULL), 0)
|| !TEST_int_eq(ERR_GET_REASON(e), ERR_R_INTERNAL_ERROR)
#if !defined(OPENSSL_NO_FILENAMES) && !defined(OPENSSL_NO_ERR)
|| !TEST_int_eq(l, line)
|| !TEST_str_eq(f, file)
#endif
|| !TEST_str_eq(data, "calling exit()"))
return 0;
return 1;
}
static int test_marks(void)
{
unsigned long mallocfail, shouldnot;
/* Set an initial error */
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
mallocfail = ERR_peek_last_error();
if (!TEST_ulong_gt(mallocfail, 0))
return 0;
/* Setting and clearing a mark should not affect the error */
if (!TEST_true(ERR_set_mark())
|| !TEST_true(ERR_pop_to_mark())
|| !TEST_ulong_eq(mallocfail, ERR_peek_last_error())
|| !TEST_true(ERR_set_mark())
|| !TEST_true(ERR_clear_last_mark())
|| !TEST_ulong_eq(mallocfail, ERR_peek_last_error()))
return 0;
/* Test popping errors */
if (!TEST_true(ERR_set_mark()))
return 0;
ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
if (!TEST_ulong_ne(mallocfail, ERR_peek_last_error())
|| !TEST_true(ERR_pop_to_mark())
|| !TEST_ulong_eq(mallocfail, ERR_peek_last_error()))
return 0;
/* Nested marks should also work */
if (!TEST_true(ERR_set_mark())
|| !TEST_true(ERR_set_mark()))
return 0;
ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
if (!TEST_ulong_ne(mallocfail, ERR_peek_last_error())
|| !TEST_true(ERR_pop_to_mark())
|| !TEST_true(ERR_pop_to_mark())
|| !TEST_ulong_eq(mallocfail, ERR_peek_last_error()))
return 0;
if (!TEST_true(ERR_set_mark()))
return 0;
ERR_raise(ERR_LIB_CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
shouldnot = ERR_peek_last_error();
if (!TEST_ulong_ne(mallocfail, shouldnot)
|| !TEST_true(ERR_set_mark()))
return 0;
ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
if (!TEST_ulong_ne(shouldnot, ERR_peek_last_error())
|| !TEST_true(ERR_pop_to_mark())
|| !TEST_ulong_eq(shouldnot, ERR_peek_last_error())
|| !TEST_true(ERR_pop_to_mark())
|| !TEST_ulong_eq(mallocfail, ERR_peek_last_error()))
return 0;
/* Setting and clearing a mark should not affect the errors on the stack */
if (!TEST_true(ERR_set_mark()))
return 0;
ERR_raise(ERR_LIB_CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
if (!TEST_true(ERR_clear_last_mark())
|| !TEST_ulong_eq(shouldnot, ERR_peek_last_error()))
return 0;
/*
* Popping where no mark has been set should pop everything - but return
* a failure result
*/
if (!TEST_false(ERR_pop_to_mark())
|| !TEST_ulong_eq(0, ERR_peek_last_error()))
return 0;
/* Clearing where there is no mark should fail */
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
if (!TEST_false(ERR_clear_last_mark())
/* "get" the last error to remove it */
|| !TEST_ulong_eq(mallocfail, ERR_get_error())
|| !TEST_ulong_eq(0, ERR_peek_last_error()))
return 0;
/*
* Setting a mark where there are no errors in the stack should fail.
* NOTE: This is somewhat surprising behaviour but is historically how this
* function behaves. In practice we typically set marks without first
* checking whether there is anything on the stack - but we also don't
* tend to check the success of this function. It turns out to work anyway
* because although setting a mark with no errors fails, a subsequent call
* to ERR_pop_to_mark() or ERR_clear_last_mark() will do the right thing
* anyway (even though they will report a failure result).
*/
if (!TEST_false(ERR_set_mark()))
return 0;
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
if (!TEST_true(ERR_set_mark()))
return 0;
ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
ERR_raise(ERR_LIB_CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
/* Should be able to "pop" past 2 errors */
if (!TEST_true(ERR_pop_to_mark())
|| !TEST_ulong_eq(mallocfail, ERR_peek_last_error()))
return 0;
if (!TEST_true(ERR_set_mark()))
return 0;
ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
ERR_raise(ERR_LIB_CRYPTO, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
/* Should be able to "clear" past 2 errors */
if (!TEST_true(ERR_clear_last_mark())
|| !TEST_ulong_eq(shouldnot, ERR_peek_last_error()))
return 0;
/* Clear remaining errors from last test */
ERR_clear_error();
return 1;
}
static int test_clear_error(void)
{
int flags = -1;
const char *data = NULL;
int res = 0;
/* Raise an error with data and clear it */
ERR_raise_data(0, 0, "hello %s", "world");
ERR_peek_error_data(&data, &flags);
if (!TEST_str_eq(data, "hello world")
|| !TEST_int_eq(flags, ERR_TXT_STRING | ERR_TXT_MALLOCED))
goto err;
ERR_clear_error();
/* Raise a new error without data */
ERR_raise(0, 0);
ERR_peek_error_data(&data, &flags);
if (!TEST_str_eq(data, "")
|| !TEST_int_eq(flags, ERR_TXT_MALLOCED))
goto err;
ERR_clear_error();
/* Raise a new error with data */
ERR_raise_data(0, 0, "goodbye %s world", "cruel");
ERR_peek_error_data(&data, &flags);
if (!TEST_str_eq(data, "goodbye cruel world")
|| !TEST_int_eq(flags, ERR_TXT_STRING | ERR_TXT_MALLOCED))
goto err;
ERR_clear_error();
/*
* Raise a new error without data to check that the malloced storage
* is freed properly
*/
ERR_raise(0, 0);
ERR_peek_error_data(&data, &flags);
if (!TEST_str_eq(data, "")
|| !TEST_int_eq(flags, ERR_TXT_MALLOCED))
goto err;
ERR_clear_error();
res = 1;
err:
ERR_clear_error();
return res;
}
static int test_save_restore(void)
{
ERR_STATE *es;
int res = 0, i, flags = -1;
unsigned long mallocfail, interr;
static const char testdata[] = "test data";
const char *data = NULL;
if (!TEST_ptr(es = OSSL_ERR_STATE_new()))
goto err;
ERR_raise(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE);
mallocfail = ERR_peek_last_error();
if (!TEST_ulong_gt(mallocfail, 0))
goto err;
ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR, testdata);
interr = ERR_peek_last_error();
if (!TEST_ulong_ne(mallocfail, ERR_peek_last_error()))
goto err;
OSSL_ERR_STATE_save(es);
if (!TEST_ulong_eq(ERR_peek_last_error(), 0))
goto err;
for (i = 0; i < 2; i++) {
OSSL_ERR_STATE_restore(es);
if (!TEST_ulong_eq(ERR_peek_last_error(), interr))
goto err;
ERR_peek_last_error_data(&data, &flags);
if (!TEST_str_eq(data, testdata)
|| !TEST_int_eq(flags, ERR_TXT_STRING | ERR_TXT_MALLOCED))
goto err;
/* restore again to duplicate the entries */
OSSL_ERR_STATE_restore(es);
/* verify them all */
if (!TEST_ulong_eq(ERR_get_error_all(NULL, NULL, NULL,
&data, &flags), mallocfail)
|| !TEST_int_ne(flags, ERR_TXT_STRING | ERR_TXT_MALLOCED))
goto err;
if (!TEST_ulong_eq(ERR_get_error_all(NULL, NULL, NULL,
&data, &flags), interr)
|| !TEST_str_eq(data, testdata)
|| !TEST_int_eq(flags, ERR_TXT_STRING | ERR_TXT_MALLOCED))
goto err;
if (!TEST_ulong_eq(ERR_get_error_all(NULL, NULL, NULL,
&data, &flags), mallocfail)
|| !TEST_int_ne(flags, ERR_TXT_STRING | ERR_TXT_MALLOCED))
goto err;
if (!TEST_ulong_eq(ERR_get_error_all(NULL, NULL, NULL,
&data, &flags), interr)
|| !TEST_str_eq(data, testdata)
|| !TEST_int_eq(flags, ERR_TXT_STRING | ERR_TXT_MALLOCED))
goto err;
if (!TEST_ulong_eq(ERR_get_error(), 0))
goto err;
}
res = 1;
err:
OSSL_ERR_STATE_free(es);
return res;
}
int setup_tests(void)
{
ADD_TEST(preserves_system_error);
ADD_TEST(vdata_appends);
ADD_TEST(raised_error);
#ifndef OPENSSL_NO_DEPRECATED_3_0
ADD_TEST(test_print_error_format);
#endif
ADD_TEST(test_marks);
ADD_TEST(test_save_restore);
ADD_TEST(test_clear_error);
return 1;
}
| 13,054 | 29.936019 | 80 | c |
openssl | openssl-master/test/event_queue_test.c | /*
* Copyright 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/event_queue.h"
#include "internal/nelem.h"
#include "testutil.h"
static OSSL_TIME cur_time = { 100 };
OSSL_TIME ossl_time_now(void)
{
return cur_time;
}
#define PAYLOAD(s) s, strlen(s) + 1
static int event_test(void)
{
int res = 0;
size_t len = 0;
OSSL_EVENT *e1, *e2, e3, *e4 = NULL, *ep = NULL;
OSSL_EVENT_QUEUE *q = NULL;
void *p;
static char payload[] = "payload";
/* Create an event queue and add some events */
if (!TEST_ptr(q = ossl_event_queue_new())
|| !TEST_ptr(e1 = ossl_event_queue_add_new(q, 1, 10,
ossl_ticks2time(1100),
"ctx 1",
PAYLOAD(payload)))
|| !TEST_ptr(e2 = ossl_event_queue_add_new(q, 2, 5,
ossl_ticks2time(1100),
"ctx 2",
PAYLOAD("data")))
|| !TEST_true(ossl_event_queue_add(q, &e3, 3, 20,
ossl_ticks2time(1200), "ctx 3",
PAYLOAD("more data")))
|| !TEST_ptr(e4 = ossl_event_queue_add_new(q, 2, 5,
ossl_ticks2time(1150),
"ctx 2",
PAYLOAD("data")))
/* Verify some event details */
|| !TEST_uint_eq(ossl_event_get_type(e1), 1)
|| !TEST_uint_eq(ossl_event_get_priority(e1), 10)
|| !TEST_uint64_t_eq(ossl_time2ticks(ossl_event_get_when(e1))
, 1100)
|| !TEST_str_eq(ossl_event_get0_ctx(e1), "ctx 1")
|| !TEST_ptr(p = ossl_event_get0_payload(e1, &len))
|| !TEST_str_eq((char *)p, payload)
|| !TEST_uint64_t_eq(ossl_time2ticks(ossl_event_time_until(&e3)),
1100)
|| !TEST_uint64_t_eq(ossl_time2ticks(ossl_event_queue_time_until_next(q)),
1000)
/* Modify an event's time */
|| !TEST_true(ossl_event_queue_postpone_until(q, e1,
ossl_ticks2time(1200)))
|| !TEST_uint64_t_eq(ossl_time2ticks(ossl_event_get_when(e1)), 1200)
|| !TEST_true(ossl_event_queue_remove(q, e4)))
goto err;
ossl_event_free(e4);
/* Execute the queue */
cur_time = ossl_ticks2time(1000);
if (!TEST_true(ossl_event_queue_get1_next_event(q, &ep))
|| !TEST_ptr_null(ep))
goto err;
cur_time = ossl_ticks2time(1100);
if (!TEST_true(ossl_event_queue_get1_next_event(q, &ep))
|| !TEST_ptr_eq(ep, e2))
goto err;
ossl_event_free(ep);
ep = e2 = NULL;
if (!TEST_true(ossl_event_queue_get1_next_event(q, &ep))
|| !TEST_ptr_null(ep))
goto err;
cur_time = ossl_ticks2time(1250);
if (!TEST_true(ossl_event_queue_get1_next_event(q, &ep))
|| !TEST_ptr_eq(ep, &e3))
goto err;
ossl_event_free(ep);
ep = NULL;
if (!TEST_true(ossl_event_queue_get1_next_event(q, &ep))
|| !TEST_ptr_eq(ep, e1))
goto err;
ossl_event_free(ep);
ep = e1 = NULL;
if (!TEST_true(ossl_event_queue_get1_next_event(q, &ep))
|| !TEST_ptr_null(ep))
goto err;
res = 1;
err:
ossl_event_free(ep);
ossl_event_queue_free(q);
return res;
}
int setup_tests(void)
{
ADD_TEST(event_test);
return 1;
}
| 4,095 | 35.247788 | 86 | c |
openssl | openssl-master/test/evp_fetch_prov_test.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
*/
/*
* SHA256 low level APIs are deprecated for public use, but still ok for
* internal use. Note, that due to symbols not being exported, only the
* #defines can be accessed. In this case SHA256_CBLOCK.
*/
#include "internal/deprecated.h"
#include <string.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
#include <openssl/provider.h>
#include "internal/sizes.h"
#include "testutil.h"
static char *config_file = NULL;
static char *alg = "digest";
static int use_default_ctx = 0;
static char *fetch_property = NULL;
static int expected_fetch_result = 1;
typedef enum OPTION_choice {
OPT_ERR = -1,
OPT_EOF = 0,
OPT_ALG_FETCH_TYPE,
OPT_FETCH_PROPERTY,
OPT_FETCH_FAILURE,
OPT_USE_DEFAULTCTX,
OPT_CONFIG_FILE,
OPT_TEST_ENUM
} OPTION_CHOICE;
const OPTIONS *test_get_options(void)
{
static const OPTIONS test_options[] = {
OPT_TEST_OPTIONS_WITH_EXTRA_USAGE("[provname...]\n"),
{ "config", OPT_CONFIG_FILE, '<', "The configuration file to use for the libctx" },
{ "type", OPT_ALG_FETCH_TYPE, 's', "The fetch type to test" },
{ "property", OPT_FETCH_PROPERTY, 's', "The fetch property e.g. provider=fips" },
{ "fetchfail", OPT_FETCH_FAILURE, '-', "fetch is expected to fail" },
{ "defaultctx", OPT_USE_DEFAULTCTX, '-',
"Use the default context if this is set" },
{ OPT_HELP_STR, 1, '-', "file\tProvider names to explicitly load\n" },
{ NULL }
};
return test_options;
}
static int calculate_digest(const EVP_MD *md, const char *msg, size_t len,
const unsigned char *exptd)
{
unsigned char out[SHA256_DIGEST_LENGTH];
EVP_MD_CTX *ctx;
int ret = 0;
if (!TEST_ptr(ctx = EVP_MD_CTX_new())
|| !TEST_true(EVP_DigestInit_ex(ctx, md, NULL))
|| !TEST_true(EVP_DigestUpdate(ctx, msg, len))
|| !TEST_true(EVP_DigestFinal_ex(ctx, out, NULL))
|| !TEST_mem_eq(out, SHA256_DIGEST_LENGTH, exptd,
SHA256_DIGEST_LENGTH)
|| !TEST_true(md == EVP_MD_CTX_get0_md(ctx)))
goto err;
ret = 1;
err:
EVP_MD_CTX_free(ctx);
return ret;
}
static int load_providers(OSSL_LIB_CTX **libctx, OSSL_PROVIDER *prov[])
{
OSSL_LIB_CTX *ctx = NULL;
int ret = 0;
size_t i;
ctx = OSSL_LIB_CTX_new();
if (!TEST_ptr(ctx))
goto err;
if (!TEST_true(OSSL_LIB_CTX_load_config(ctx, config_file)))
goto err;
if (test_get_argument_count() > 2)
goto err;
for (i = 0; i < test_get_argument_count(); ++i) {
char *provname = test_get_argument(i);
prov[i] = OSSL_PROVIDER_load(ctx, provname);
if (!TEST_ptr(prov[i]))
goto err;
}
ret = 1;
*libctx = ctx;
err:
if (ret == 0)
OSSL_LIB_CTX_free(ctx);
return ret;
}
static void unload_providers(OSSL_LIB_CTX **libctx, OSSL_PROVIDER *prov[])
{
if (prov[0] != NULL)
OSSL_PROVIDER_unload(prov[0]);
if (prov[1] != NULL)
OSSL_PROVIDER_unload(prov[1]);
/* Not normally needed, but we would like to test that
* OPENSSL_thread_stop_ex() behaves as expected.
*/
if (libctx != NULL && *libctx != NULL) {
OPENSSL_thread_stop_ex(*libctx);
OSSL_LIB_CTX_free(*libctx);
}
}
static X509_ALGOR *make_algor(int nid)
{
X509_ALGOR *algor;
if (!TEST_ptr(algor = X509_ALGOR_new())
|| !TEST_true(X509_ALGOR_set0(algor, OBJ_nid2obj(nid),
V_ASN1_UNDEF, NULL))) {
X509_ALGOR_free(algor);
return NULL;
}
return algor;
}
/*
* Test EVP_MD_fetch()
*/
static int test_md(const EVP_MD *md)
{
const char testmsg[] = "Hello world";
const unsigned char exptd[] = {
0x27, 0x51, 0x8b, 0xa9, 0x68, 0x30, 0x11, 0xf6, 0xb3, 0x96, 0x07, 0x2c,
0x05, 0xf6, 0x65, 0x6d, 0x04, 0xf5, 0xfb, 0xc3, 0x78, 0x7c, 0xf9, 0x24,
0x90, 0xec, 0x60, 0x6e, 0x50, 0x92, 0xe3, 0x26
};
return TEST_ptr(md)
&& TEST_true(EVP_MD_is_a(md, "SHA256"))
&& TEST_true(calculate_digest(md, testmsg, sizeof(testmsg), exptd))
&& TEST_int_eq(EVP_MD_get_size(md), SHA256_DIGEST_LENGTH)
&& TEST_int_eq(EVP_MD_get_block_size(md), SHA256_CBLOCK);
}
static int test_implicit_EVP_MD_fetch(void)
{
OSSL_LIB_CTX *ctx = NULL;
OSSL_PROVIDER *prov[2] = {NULL, NULL};
int ret = 0;
ret = (use_default_ctx == 0 || load_providers(&ctx, prov))
&& test_md(EVP_sha256());
unload_providers(&ctx, prov);
return ret;
}
static int test_explicit_EVP_MD_fetch(const char *id)
{
OSSL_LIB_CTX *ctx = NULL;
EVP_MD *md = NULL;
OSSL_PROVIDER *prov[2] = {NULL, NULL};
int ret = 0;
if (use_default_ctx == 0 && !load_providers(&ctx, prov))
goto err;
md = EVP_MD_fetch(ctx, id, fetch_property);
if (expected_fetch_result != 0) {
if (!test_md(md))
goto err;
/* Also test EVP_MD_up_ref() while we're doing this */
if (!TEST_true(EVP_MD_up_ref(md)))
goto err;
/* Ref count should now be 2. Release first one here */
EVP_MD_free(md);
} else {
if (!TEST_ptr_null(md))
goto err;
}
ret = 1;
err:
EVP_MD_free(md);
unload_providers(&ctx, prov);
return ret;
}
static int test_explicit_EVP_MD_fetch_by_name(void)
{
return test_explicit_EVP_MD_fetch("SHA256");
}
/*
* idx 0: Allow names from OBJ_obj2txt()
* idx 1: Force an OID in text form from OBJ_obj2txt()
*/
static int test_explicit_EVP_MD_fetch_by_X509_ALGOR(int idx)
{
int ret = 0;
X509_ALGOR *algor = make_algor(NID_sha256);
const ASN1_OBJECT *obj;
char id[OSSL_MAX_NAME_SIZE] = { 0 };
if (algor == NULL)
return 0;
X509_ALGOR_get0(&obj, NULL, NULL, algor);
switch (idx) {
case 0:
if (!TEST_int_gt(OBJ_obj2txt(id, sizeof(id), obj, 0), 0))
goto end;
break;
case 1:
if (!TEST_int_gt(OBJ_obj2txt(id, sizeof(id), obj, 1), 0))
goto end;
break;
}
ret = test_explicit_EVP_MD_fetch(id);
end:
X509_ALGOR_free(algor);
return ret;
}
/*
* Test EVP_CIPHER_fetch()
*/
static int encrypt_decrypt(const EVP_CIPHER *cipher, const unsigned char *msg,
size_t len)
{
int ret = 0, ctlen, ptlen;
EVP_CIPHER_CTX *ctx = NULL;
unsigned char key[128 / 8];
unsigned char ct[64], pt[64];
memset(key, 0, sizeof(key));
if (!TEST_ptr(ctx = EVP_CIPHER_CTX_new())
|| !TEST_true(EVP_CipherInit_ex(ctx, cipher, NULL, key, NULL, 1))
|| !TEST_true(EVP_CipherUpdate(ctx, ct, &ctlen, msg, len))
|| !TEST_true(EVP_CipherFinal_ex(ctx, ct, &ctlen))
|| !TEST_true(EVP_CipherInit_ex(ctx, cipher, NULL, key, NULL, 0))
|| !TEST_true(EVP_CipherUpdate(ctx, pt, &ptlen, ct, ctlen))
|| !TEST_true(EVP_CipherFinal_ex(ctx, pt, &ptlen))
|| !TEST_mem_eq(pt, ptlen, msg, len))
goto err;
ret = 1;
err:
EVP_CIPHER_CTX_free(ctx);
return ret;
}
static int test_cipher(const EVP_CIPHER *cipher)
{
const unsigned char testmsg[] = "Hello world";
return TEST_ptr(cipher)
&& TEST_true(encrypt_decrypt(cipher, testmsg, sizeof(testmsg)));
}
static int test_implicit_EVP_CIPHER_fetch(void)
{
OSSL_LIB_CTX *ctx = NULL;
OSSL_PROVIDER *prov[2] = {NULL, NULL};
int ret = 0;
ret = (use_default_ctx == 0 || load_providers(&ctx, prov))
&& test_cipher(EVP_aes_128_cbc());
unload_providers(&ctx, prov);
return ret;
}
static int test_explicit_EVP_CIPHER_fetch(const char *id)
{
OSSL_LIB_CTX *ctx = NULL;
EVP_CIPHER *cipher = NULL;
OSSL_PROVIDER *prov[2] = {NULL, NULL};
int ret = 0;
if (use_default_ctx == 0 && !load_providers(&ctx, prov))
goto err;
cipher = EVP_CIPHER_fetch(ctx, id, fetch_property);
if (expected_fetch_result != 0) {
if (!test_cipher(cipher))
goto err;
if (!TEST_true(EVP_CIPHER_up_ref(cipher)))
goto err;
/* Ref count should now be 2. Release first one here */
EVP_CIPHER_free(cipher);
} else {
if (!TEST_ptr_null(cipher))
goto err;
}
ret = 1;
err:
EVP_CIPHER_free(cipher);
unload_providers(&ctx, prov);
return ret;
}
static int test_explicit_EVP_CIPHER_fetch_by_name(void)
{
return test_explicit_EVP_CIPHER_fetch("AES-128-CBC");
}
/*
* idx 0: Allow names from OBJ_obj2txt()
* idx 1: Force an OID in text form from OBJ_obj2txt()
*/
static int test_explicit_EVP_CIPHER_fetch_by_X509_ALGOR(int idx)
{
int ret = 0;
X509_ALGOR *algor = make_algor(NID_aes_128_cbc);
const ASN1_OBJECT *obj;
char id[OSSL_MAX_NAME_SIZE] = { 0 };
if (algor == NULL)
return 0;
X509_ALGOR_get0(&obj, NULL, NULL, algor);
switch (idx) {
case 0:
if (!TEST_int_gt(OBJ_obj2txt(id, sizeof(id), obj, 0), 0))
goto end;
break;
case 1:
if (!TEST_int_gt(OBJ_obj2txt(id, sizeof(id), obj, 1), 0))
goto end;
break;
}
ret = test_explicit_EVP_CIPHER_fetch(id);
end:
X509_ALGOR_free(algor);
return ret;
}
int setup_tests(void)
{
OPTION_CHOICE o;
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_CONFIG_FILE:
config_file = opt_arg();
break;
case OPT_ALG_FETCH_TYPE:
alg = opt_arg();
break;
case OPT_FETCH_PROPERTY:
fetch_property = opt_arg();
break;
case OPT_FETCH_FAILURE:
expected_fetch_result = 0;
break;
case OPT_USE_DEFAULTCTX:
use_default_ctx = 1;
break;
case OPT_TEST_CASES:
break;
default:
case OPT_ERR:
return 0;
}
}
if (strcmp(alg, "digest") == 0) {
ADD_TEST(test_implicit_EVP_MD_fetch);
ADD_TEST(test_explicit_EVP_MD_fetch_by_name);
ADD_ALL_TESTS_NOSUBTEST(test_explicit_EVP_MD_fetch_by_X509_ALGOR, 2);
} else {
ADD_TEST(test_implicit_EVP_CIPHER_fetch);
ADD_TEST(test_explicit_EVP_CIPHER_fetch_by_name);
ADD_ALL_TESTS_NOSUBTEST(test_explicit_EVP_CIPHER_fetch_by_X509_ALGOR, 2);
}
return 1;
}
| 10,684 | 26.188295 | 91 | c |
openssl | openssl-master/test/evp_pkey_dparams_test.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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "internal/nelem.h"
#include <openssl/crypto.h>
#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/ec.h>
#include "testutil.h"
#if defined(OPENSSL_NO_DH) && defined(OPENSSL_NO_DSA) && defined(OPENSSL_NO_EC)
# define OPENSSL_NO_KEYPARAMS
#endif
#ifndef OPENSSL_NO_KEYPARAMS
struct pubkey {
int bad;
const unsigned char *key_bin;
size_t key_bin_len;
};
# ifndef OPENSSL_NO_DH
static const unsigned char dhparam_bin[] = {
0x30,0x82,0x01,0x08,0x02,0x82,0x01,0x01,0x00,0xc0,0xd1,0x2e,0x14,0x18,0xbd,0x03,
0xfd,0x39,0xe1,0x99,0xf4,0x93,0x06,0x2d,0x49,0xc6,0xb5,0xb9,0xf0,0x91,0xcb,0x2f,
0x48,0x54,0x79,0x7d,0xc4,0x65,0x11,0x55,0xf7,0x99,0xde,0x42,0x83,0x84,0xc0,0xf8,
0x88,0x89,0xa0,0xff,0xff,0x7d,0xe8,0xef,0x9e,0xbc,0xf7,0x1d,0x70,0x6d,0x3a,0x33,
0x49,0x28,0xa1,0xa3,0xe1,0x41,0xc4,0x8b,0x91,0xf9,0xf2,0xb6,0xe2,0x77,0x79,0x38,
0x7d,0x21,0xb3,0xdf,0x79,0x9c,0x5e,0x65,0x16,0x00,0x16,0x82,0xb2,0x36,0x46,0x21,
0xac,0xaf,0x86,0xc7,0xe3,0x10,0x44,0x48,0xfb,0xbd,0xad,0x4e,0x11,0x73,0x4c,0x25,
0xb0,0x8c,0x1c,0x1e,0x8e,0x58,0x50,0x5e,0x43,0x89,0xe4,0xd9,0x34,0xf8,0x3b,0xcc,
0x36,0x2c,0x1b,0xb3,0xb2,0x77,0x0c,0xa5,0x96,0xc1,0x8a,0x38,0xd4,0xe3,0x9c,0x2a,
0xde,0x49,0x46,0xc7,0xd4,0xa2,0x47,0xc9,0x0a,0xbd,0x84,0xd4,0x1c,0xbc,0xb6,0x19,
0x04,0x94,0x64,0xfa,0x8a,0x11,0x9c,0x5f,0x4a,0x4c,0x0f,0x58,0x81,0x02,0xbf,0xcf,
0x87,0x27,0x2b,0xae,0x8e,0xe2,0x61,0x7a,0xdb,0xba,0x23,0x39,0x25,0x44,0xdc,0x22,
0x75,0xc3,0x28,0xd9,0x12,0x33,0x84,0x32,0xd4,0x5d,0xd9,0x77,0xf8,0x04,0x90,0x38,
0x0a,0xec,0x84,0x93,0x43,0xce,0xe7,0x07,0x42,0x7d,0x2d,0xe0,0x21,0x3b,0x19,0x22,
0xa7,0x8f,0x50,0x31,0xda,0xd0,0x0d,0xd3,0x0b,0xdb,0xad,0xed,0x94,0x92,0xff,0x83,
0x06,0x7f,0x7f,0xd7,0x7b,0x42,0x5b,0xba,0x93,0x7a,0xeb,0x43,0x5f,0xce,0x59,0x26,
0xe8,0x76,0xdc,0xee,0xe2,0xbe,0x36,0x7a,0x83,0x02,0x01,0x02
};
static const unsigned char dhkey_1[] = {
0x7a, 0x49, 0xcb, 0xc3, 0x25, 0x67, 0x7a, 0x61,
0xd0, 0x60, 0x81, 0x0f, 0xf6, 0xbd, 0x38, 0x82,
0xe7, 0x38, 0x8c, 0xe9, 0xd1, 0x04, 0x33, 0xbf,
0x8a, 0x03, 0x63, 0xb3, 0x05, 0x04, 0xb5, 0x1f,
0xba, 0x9f, 0x1a, 0x5f, 0x31, 0x3e, 0x96, 0x79,
0x88, 0x7d, 0x3f, 0x59, 0x6d, 0x3b, 0xf3, 0x2f,
0xf2, 0xa6, 0x43, 0x48, 0x64, 0x5a, 0x6a, 0x32,
0x1f, 0x24, 0x37, 0x62, 0x54, 0x3a, 0x7d, 0xab,
0x26, 0x77, 0x7c, 0xec, 0x57, 0x3c, 0xa4, 0xbd,
0x96, 0x9d, 0xaa, 0x3b, 0x0e, 0x9a, 0x55, 0x7e,
0x1d, 0xb4, 0x47, 0x5b, 0xea, 0x20, 0x3c, 0x6d,
0xbe, 0xd6, 0x70, 0x7d, 0xa8, 0x9e, 0x84, 0xb4,
0x03, 0x52, 0xf2, 0x08, 0x4c, 0x98, 0xd3, 0x4f,
0x58, 0xb3, 0xdf, 0xb4, 0xe6, 0xdc, 0x2c, 0x43,
0x55, 0xd1, 0xce, 0x2a, 0xb3, 0xfc, 0xe0, 0x29,
0x97, 0xd8, 0xd8, 0x62, 0xc6, 0x87, 0x0a, 0x1b,
0xfd, 0x72, 0x74, 0xe0, 0xa9, 0xfb, 0xfa, 0x91,
0xf2, 0xc1, 0x09, 0x93, 0xea, 0x63, 0xf6, 0x9a,
0x4b, 0xdf, 0x4e, 0xdf, 0x6b, 0xf9, 0xeb, 0xf6,
0x66, 0x3c, 0xfd, 0x6f, 0x68, 0xcb, 0xdb, 0x6e,
0x40, 0x65, 0xf7, 0xf2, 0x46, 0xe5, 0x0d, 0x9a,
0xd9, 0x6f, 0xcf, 0x28, 0x22, 0x8f, 0xca, 0x0b,
0x30, 0xa0, 0x9e, 0xa5, 0x13, 0xba, 0x72, 0x7f,
0x85, 0x3d, 0x02, 0x9c, 0x97, 0x8e, 0x6f, 0xea,
0x6d, 0x35, 0x4e, 0xd1, 0x78, 0x7d, 0x73, 0x60,
0x92, 0xa9, 0x12, 0xf4, 0x2a, 0xac, 0x17, 0x97,
0xf3, 0x7b, 0x79, 0x08, 0x69, 0xd1, 0x9e, 0xb5,
0xf8, 0x2a, 0x0a, 0x2b, 0x00, 0x7b, 0x16, 0x8d,
0x41, 0x82, 0x3a, 0x72, 0x58, 0x57, 0x80, 0x65,
0xae, 0x17, 0xbc, 0x3a, 0x5b, 0x7e, 0x5c, 0x2d,
0xae, 0xb2, 0xc2, 0x26, 0x20, 0x9a, 0xaa, 0x57,
0x4b, 0x7d, 0x43, 0x41, 0x96, 0x3f, 0xf0, 0x0d
};
/* smaller but still valid key */
static const unsigned char dhkey_2[] = {
0x73, 0xb2, 0x22, 0x91, 0x27, 0xb9, 0x45, 0xb0,
0xfd, 0x17, 0x66, 0x79, 0x9b, 0x32, 0x71, 0x92,
0x97, 0x1d, 0x70, 0x02, 0x37, 0x70, 0x79, 0x63,
0xed, 0x11, 0x22, 0xe9, 0xe6, 0xf8, 0xeb, 0xd7,
0x90, 0x00, 0xe6, 0x5c, 0x47, 0x02, 0xfb, 0x13,
0xca, 0x29, 0x14, 0x1e, 0xf4, 0x61, 0x58, 0xf6,
0xaa, 0xbb, 0xcf, 0xa7, 0x82, 0x9a, 0x9e, 0x7c,
0x4a, 0x05, 0x42, 0xed, 0x55, 0xd8, 0x08, 0x37,
0x06, 0x49, 0x9b, 0xda, 0xb3, 0xb9, 0xc9, 0xc0,
0x56, 0x26, 0xda, 0x60, 0x1d, 0xbc, 0x06, 0x0b,
0xb0, 0x94, 0x4b, 0x4e, 0x95, 0xf9, 0xb4, 0x2f,
0x4e, 0xad, 0xf8, 0xab, 0x2d, 0x19, 0xa2, 0xe6,
0x6d, 0x11, 0xfd, 0x9b, 0x5a, 0x2a, 0xb0, 0x81,
0x42, 0x4d, 0x86, 0x76, 0xd5, 0x9e, 0xaf, 0xf9,
0x6f, 0x79, 0xab, 0x1d, 0xfe, 0xd8, 0xc8, 0xba,
0xb6, 0xce, 0x03, 0x61, 0x48, 0x53, 0xd8, 0x0b,
0x83, 0xf0, 0xb0, 0x46, 0xa0, 0xea, 0x46, 0x60,
0x7a, 0x39, 0x4e, 0x46, 0x6a, 0xbb, 0x07, 0x6c,
0x8c, 0x7d, 0xb7, 0x7d, 0x5b, 0xe5, 0x24, 0xa5,
0xab, 0x41, 0x8a, 0xc4, 0x63, 0xf9, 0xce, 0x20,
0x6f, 0x58, 0x4f, 0x0e, 0x42, 0x82, 0x9e, 0x17,
0x53, 0xa6, 0xd6, 0x42, 0x3e, 0x80, 0x66, 0x6f,
0x2a, 0x1c, 0x30, 0x08, 0x01, 0x99, 0x5a, 0x4f,
0x72, 0x16, 0xed, 0xb0, 0xd6, 0x8c, 0xf0, 0x7a,
0x33, 0x15, 0xc4, 0x95, 0x65, 0xba, 0x11, 0x37,
0xa0, 0xcc, 0xe7, 0x45, 0x65, 0x4f, 0x17, 0x0a,
0x2c, 0x62, 0xc0, 0x65, 0x3b, 0x65, 0x2a, 0x56,
0xf7, 0x29, 0x8a, 0x9b, 0x1b, 0xbb, 0x0c, 0x40,
0xcd, 0x66, 0x4b, 0x4f, 0x2f, 0xba, 0xdb, 0x59,
0x93, 0x6d, 0x34, 0xf3, 0x8d, 0xde, 0x68, 0x99,
0x78, 0xfc, 0xac, 0x95, 0xd9, 0xa3, 0x74, 0xe6,
0x24, 0x96, 0x98, 0x6f, 0x64, 0x71, 0x76
};
/* 1 is not a valid key */
static const unsigned char dhkey_3[] = {
0x01
};
# endif
# ifndef OPENSSL_NO_DSA
static const unsigned char dsaparam_bin[] = {
0x30,0x82,0x02,0x28,0x02,0x82,0x01,0x01,0x00,0xf2,0x85,0x01,0xa5,0xb9,0x56,0x65,
0x19,0xff,0x9a,0x7d,0xf9,0x90,0xd6,0xaa,0x73,0xac,0xf7,0x94,0xfa,0x8a,0x64,0x6d,
0xa0,0x01,0x42,0xe5,0x45,0xfc,0x53,0x72,0xb0,0x7c,0xe6,0x3b,0xfb,0x09,0x33,0x41,
0x27,0xbd,0x00,0xb5,0x18,0x87,0x62,0xa8,0x2b,0xfc,0xd0,0x52,0x4a,0x14,0x2d,0xaa,
0x36,0xc6,0xf3,0xa9,0xe3,0x90,0x1b,0x74,0xdf,0x0a,0x6d,0x33,0xba,0xf4,0x32,0x6d,
0xba,0x36,0x68,0x1d,0x83,0x36,0x50,0xc6,0x62,0xc0,0x40,0x67,0x0e,0xf6,0x22,0x00,
0x62,0x1b,0x76,0x72,0x62,0x5f,0xa0,0xdf,0x38,0xb1,0x1d,0x26,0x70,0x9b,0x84,0x64,
0xbb,0x16,0x15,0xc2,0x66,0xb9,0x97,0xd0,0x07,0xf1,0x4b,0x70,0x02,0x03,0xf1,0xd2,
0x03,0xdb,0x78,0x8b,0xb4,0xda,0x6f,0x3c,0xe2,0x31,0xa8,0x1c,0x99,0xea,0x9c,0x75,
0x28,0x96,0x82,0x16,0x77,0xac,0x79,0x32,0x61,0x87,0xec,0xb7,0xb4,0xc3,0xea,0x12,
0x62,0x1f,0x08,0xb8,0x16,0xab,0xcc,0xef,0x28,0xdf,0x06,0x07,0xbe,0xb0,0xdc,0x78,
0x83,0x8a,0x70,0x80,0x34,0xe6,0x91,0xe3,0xd3,0x92,0xd9,0xf4,0x56,0x53,0x52,0xb7,
0x35,0xf6,0x2a,0xec,0x4b,0xcb,0xa2,0x3c,0xc3,0x0c,0x94,0xa7,0x4e,0x1c,0x42,0x9c,
0x72,0x99,0x60,0x8c,0xfe,0xfb,0x60,0x57,0x75,0xf5,0x23,0x11,0x12,0xba,0x97,0xcd,
0xad,0x5a,0x0b,0xa6,0x1f,0x6a,0x48,0x2e,0x8d,0xda,0x95,0xc6,0x0e,0x14,0xde,0xf7,
0x22,0x55,0xa8,0x6b,0x25,0xdf,0xa2,0xab,0x33,0x65,0x56,0xfc,0x78,0x4f,0x62,0xdf,
0x48,0xdd,0xce,0x8b,0xe1,0x76,0xf4,0xf6,0x7f,0x02,0x1d,0x00,0xac,0xb0,0xb8,0x92,
0x3b,0x6b,0x61,0xcf,0x36,0x6d,0xf2,0x1e,0x5d,0xe0,0x7b,0xf5,0x73,0x48,0xa3,0x8b,
0x86,0x9e,0x88,0xce,0x40,0xf8,0x27,0x6d,0x02,0x82,0x01,0x00,0x77,0x6b,0x89,0xd6,
0x8f,0x3d,0xce,0x52,0x30,0x74,0xb2,0xa1,0x13,0x96,0xd5,0x92,0xf2,0xf1,0x6b,0x10,
0x31,0x0b,0xf3,0x69,0xaa,0xbf,0x4b,0x6c,0xcb,0x3f,0x6d,0x58,0x76,0x44,0x09,0xf9,
0x28,0xef,0xa0,0xe4,0x55,0x77,0x57,0xe0,0xfb,0xcc,0x9a,0x6a,0x2c,0x90,0xec,0x72,
0x24,0x0b,0x43,0xc5,0xbc,0x31,0xed,0x1a,0x46,0x2c,0x76,0x42,0x9e,0xc0,0x82,0xfc,
0xff,0xf9,0x7e,0xe2,0x1f,0x39,0xf3,0x3b,0xdb,0x27,0x36,0xe7,0xf5,0x3b,0xc2,0x23,
0xb6,0xd0,0xcf,0x5b,0x85,0x2e,0x1b,0x00,0x5b,0x31,0xaa,0x72,0x8f,0x37,0xee,0x56,
0x71,0xc4,0xfd,0x3c,0x8d,0xfa,0x5b,0xab,0xb1,0xa9,0x52,0x76,0xa0,0xe4,0xe3,0x78,
0x83,0x64,0x5d,0xd7,0x6c,0xec,0x9b,0x40,0x65,0xe2,0x0a,0x11,0x19,0x60,0xdd,0xce,
0x29,0x9f,0xc6,0x1d,0x0a,0xab,0x8e,0x59,0x25,0xc5,0x0b,0x9c,0x02,0x45,0xba,0x99,
0x74,0x22,0x1d,0xc1,0x57,0xca,0x50,0x8c,0x5e,0xdf,0xd8,0x5d,0x43,0xae,0x06,0x28,
0x29,0x82,0xf6,0x5a,0xa9,0x51,0xa2,0x04,0x1d,0xbf,0x88,0x15,0x98,0xce,0x8a,0xb4,
0x3b,0xe5,0x30,0x29,0xce,0x0c,0x9b,0xf8,0xdb,0xbf,0x06,0x9f,0xd0,0x59,0x18,0xd4,
0x0b,0x94,0xbf,0xe9,0x67,0x6b,0x9e,0xf0,0x72,0xc6,0xbf,0x79,0x8f,0x1e,0xa3,0x95,
0x24,0xe3,0xcb,0x58,0xb5,0x67,0xd3,0xae,0x79,0xb0,0x28,0x9c,0x9a,0xd0,0xa4,0xe7,
0x22,0x15,0xc1,0x8b,0x04,0xb9,0x8a,0xa8,0xb7,0x1b,0x62,0x44,0xc6,0xef,0x4b,0x74,
0xd0,0xfd,0xa9,0xb4,0x4e,0xdd,0x7d,0x38,0x60,0xd1,0x40,0xcd
};
# endif
# ifndef OPENSSL_NO_EC
static const unsigned char ecparam_bin[] = {
0x06,0x08,0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x07
};
static const unsigned char eckey_1[] = {
0x04, 0xc8, 0x65, 0x45, 0x63, 0x73, 0xe5, 0x0a,
0x61, 0x1d, 0xcf, 0x60, 0x76, 0x2c, 0xe7, 0x36,
0x0b, 0x76, 0xc2, 0x92, 0xfc, 0xa4, 0x56, 0xee,
0xc2, 0x62, 0x05, 0x00, 0x80, 0xe4, 0x4f, 0x07,
0x3b, 0xf4, 0x59, 0xb8, 0xc3, 0xb3, 0x1f, 0x77,
0x36, 0x16, 0x4c, 0x72, 0x2a, 0xc0, 0x89, 0x89,
0xd6, 0x16, 0x14, 0xee, 0x2f, 0x5a, 0xde, 0x9e,
0x83, 0xc5, 0x78, 0xd0, 0x0b, 0x69, 0xb4, 0xb9,
0xf1
};
/* a modified key */
static const unsigned char eckey_2[] = {
0x04, 0xc8, 0x65, 0x45, 0x63, 0x73, 0xe5, 0x0a,
0x61, 0x1d, 0xcf, 0x60, 0x76, 0x2c, 0xe7, 0x36,
0x0b, 0x77, 0xc2, 0x92, 0xfc, 0xa4, 0x56, 0xee,
0xc2, 0x62, 0x05, 0x00, 0x80, 0xe4, 0x4f, 0x07,
0x3b, 0xf4, 0x59, 0xb8, 0xc3, 0xb3, 0x1f, 0x77,
0x36, 0x16, 0x4c, 0x72, 0x2a, 0xc0, 0x89, 0x89,
0xd6, 0x16, 0x14, 0xee, 0x2f, 0x5a, 0xde, 0x9e,
0x83, 0xc5, 0x78, 0xd0, 0x0b, 0x69, 0xb4, 0xb9,
0xf1
};
/* an added byte */
static const unsigned char eckey_3[] = {
0x04, 0xc8, 0x65, 0x45, 0x63, 0x73, 0xe5, 0x0a,
0x61, 0x1d, 0xcf, 0x60, 0x76, 0x2c, 0xe7, 0x36,
0x0b, 0x76, 0xc2, 0x92, 0xfc, 0xa4, 0x56, 0xee,
0xc2, 0x62, 0x05, 0x00, 0x80, 0xe4, 0x4f, 0x07,
0x3b, 0xf4, 0x59, 0xb8, 0xc3, 0xb3, 0x1f, 0x77,
0x36, 0x16, 0x4c, 0x72, 0x2a, 0xc0, 0x89, 0x89,
0xd6, 0x16, 0x14, 0xee, 0x2f, 0x5a, 0xde, 0x9e,
0x83, 0xc5, 0x78, 0xd0, 0x0b, 0x69, 0xb4, 0xb9,
0xf1, 0xaa
};
# endif
#define NUM_KEYS 10
static const struct {
int type;
const unsigned char *param_bin;
size_t param_bin_len;
struct pubkey keys[NUM_KEYS];
} pkey_params [] = {
# ifndef OPENSSL_NO_DH
{ EVP_PKEY_DH, dhparam_bin, sizeof(dhparam_bin),
{ { 0, dhkey_1, sizeof(dhkey_1) },
{ 0, dhkey_2, sizeof(dhkey_2) },
{ 1, dhkey_3, sizeof(dhkey_3) },
{ 1, dhkey_1, 0 },
{ 1, dhparam_bin, sizeof(dhparam_bin) }
}
},
# endif
# ifndef OPENSSL_NO_DSA
{ EVP_PKEY_DSA, dsaparam_bin, sizeof(dsaparam_bin) },
# endif
# ifndef OPENSSL_NO_EC
{ EVP_PKEY_EC, ecparam_bin, sizeof(ecparam_bin),
{ { 0, eckey_1, sizeof(eckey_1) },
{ 1, eckey_2, sizeof(eckey_2) },
{ 1, eckey_3, sizeof(eckey_3) },
{ 1, eckey_1, 0 },
{ 1, eckey_1, sizeof(eckey_1) - 1 }
}
}
# endif
};
static int params_bio_test(int id)
{
int ret, out_len;
BIO *in = NULL, *out = NULL;
EVP_PKEY *in_key = NULL, *out_key = NULL;
unsigned char *out_bin;
int type = pkey_params[id].type;
ret = TEST_ptr(in = BIO_new_mem_buf(pkey_params[id].param_bin,
(int)pkey_params[id].param_bin_len))
/* Load in pkey params from binary */
&& TEST_ptr(d2i_KeyParams_bio(type, &in_key, in))
&& TEST_ptr(out = BIO_new(BIO_s_mem()))
/* Save pkey params to binary */
&& TEST_int_gt(i2d_KeyParams_bio(out, in_key), 0)
/* test the output binary is the expected value */
&& TEST_int_gt(out_len = BIO_get_mem_data(out, &out_bin), 0)
&& TEST_mem_eq(pkey_params[id].param_bin,
(int)pkey_params[id].param_bin_len,
out_bin, out_len);
BIO_free(in);
BIO_free(out);
EVP_PKEY_free(in_key);
EVP_PKEY_free(out_key);
return ret;
}
static int set_enc_pubkey_test(int id)
{
int ret, i;
BIO *in = NULL;
EVP_PKEY *in_key = NULL;
int type = pkey_params[id].type;
const struct pubkey *keys = pkey_params[id].keys;
if (keys[0].key_bin == NULL)
return TEST_skip("Not applicable test");
ret = TEST_ptr(in = BIO_new_mem_buf(pkey_params[id].param_bin,
(int)pkey_params[id].param_bin_len))
/* Load in pkey params from binary */
&& TEST_ptr(d2i_KeyParams_bio(type, &in_key, in));
for (i = 0; ret && i < NUM_KEYS && keys[i].key_bin != NULL; i++) {
if (keys[i].bad) {
ERR_set_mark();
ret = ret
&& TEST_int_le(EVP_PKEY_set1_encoded_public_key(in_key,
keys[i].key_bin,
keys[i].key_bin_len),
0);
ERR_pop_to_mark();
} else {
ret = ret
&& TEST_int_gt(EVP_PKEY_set1_encoded_public_key(in_key,
keys[i].key_bin,
keys[i].key_bin_len),
0);
}
if (!ret)
TEST_info("Test key index #%d", i);
}
BIO_free(in);
EVP_PKEY_free(in_key);
return ret;
}
#endif
int setup_tests(void)
{
#ifdef OPENSSL_NO_KEYPARAMS
TEST_note("No DH/DSA/EC support");
#else
ADD_ALL_TESTS(params_bio_test, OSSL_NELEM(pkey_params));
ADD_ALL_TESTS(set_enc_pubkey_test, OSSL_NELEM(pkey_params));
#endif
return 1;
}
| 13,870 | 41.68 | 85 | c |
openssl | openssl-master/test/exdatatest.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 <string.h>
#include <stdlib.h>
#include <openssl/crypto.h>
#include "testutil.h"
static long saved_argl;
static void *saved_argp;
static int saved_idx;
static int saved_idx2;
static int saved_idx3;
static int gbl_result;
/*
* SIMPLE EX_DATA IMPLEMENTATION
* Apps explicitly set/get ex_data as needed
*/
static void exnew(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
int idx, long argl, void *argp)
{
if (!TEST_int_eq(idx, saved_idx)
|| !TEST_long_eq(argl, saved_argl)
|| !TEST_ptr_eq(argp, saved_argp)
|| !TEST_ptr_null(ptr))
gbl_result = 0;
}
static int exdup(CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from,
void **from_d, int idx, long argl, void *argp)
{
if (!TEST_int_eq(idx, saved_idx)
|| !TEST_long_eq(argl, saved_argl)
|| !TEST_ptr_eq(argp, saved_argp)
|| !TEST_ptr(from_d))
gbl_result = 0;
return 1;
}
static void exfree(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
int idx, long argl, void *argp)
{
if (!TEST_int_eq(idx, saved_idx)
|| !TEST_long_eq(argl, saved_argl)
|| !TEST_ptr_eq(argp, saved_argp))
gbl_result = 0;
}
/*
* PRE-ALLOCATED EX_DATA IMPLEMENTATION
* Extended data structure is allocated in exnew2/freed in exfree2
* Data is stored inside extended data structure
*/
typedef struct myobj_ex_data_st {
char *hello;
int new;
int dup;
} MYOBJ_EX_DATA;
static void exnew2(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
int idx, long argl, void *argp)
{
MYOBJ_EX_DATA *ex_data = OPENSSL_zalloc(sizeof(*ex_data));
if (!TEST_true(idx == saved_idx2 || idx == saved_idx3)
|| !TEST_long_eq(argl, saved_argl)
|| !TEST_ptr_eq(argp, saved_argp)
|| !TEST_ptr_null(ptr)
|| !TEST_ptr(ex_data)
|| !TEST_true(CRYPTO_set_ex_data(ad, idx, ex_data))) {
gbl_result = 0;
OPENSSL_free(ex_data);
} else {
ex_data->new = 1;
}
}
static int exdup2(CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from,
void **from_d, int idx, long argl, void *argp)
{
MYOBJ_EX_DATA **update_ex_data = (MYOBJ_EX_DATA**)from_d;
MYOBJ_EX_DATA *ex_data = NULL;
if (!TEST_true(idx == saved_idx2 || idx == saved_idx3)
|| !TEST_long_eq(argl, saved_argl)
|| !TEST_ptr_eq(argp, saved_argp)
|| !TEST_ptr(from_d)
|| !TEST_ptr(*update_ex_data)
|| !TEST_ptr(ex_data = CRYPTO_get_ex_data(to, idx))
|| !TEST_true(ex_data->new)) {
gbl_result = 0;
} else {
/* Copy hello over */
ex_data->hello = (*update_ex_data)->hello;
/* indicate this is a dup */
ex_data->dup = 1;
/* Keep my original ex_data */
*update_ex_data = ex_data;
}
return 1;
}
static void exfree2(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
int idx, long argl, void *argp)
{
MYOBJ_EX_DATA *ex_data = CRYPTO_get_ex_data(ad, idx);
if (!TEST_true(idx == saved_idx2 || idx == saved_idx3)
|| !TEST_long_eq(argl, saved_argl)
|| !TEST_ptr_eq(argp, saved_argp)
|| !TEST_true(CRYPTO_set_ex_data(ad, idx, NULL)))
gbl_result = 0;
OPENSSL_free(ex_data);
}
typedef struct myobj_st {
CRYPTO_EX_DATA ex_data;
int id;
int st;
} MYOBJ;
static MYOBJ *MYOBJ_new(void)
{
static int count = 0;
MYOBJ *obj = OPENSSL_malloc(sizeof(*obj));
if (obj != NULL) {
obj->id = ++count;
obj->st = CRYPTO_new_ex_data(CRYPTO_EX_INDEX_APP, obj, &obj->ex_data);
}
return obj;
}
static void MYOBJ_sethello(MYOBJ *obj, char *cp)
{
obj->st = CRYPTO_set_ex_data(&obj->ex_data, saved_idx, cp);
if (!TEST_int_eq(obj->st, 1))
gbl_result = 0;
}
static char *MYOBJ_gethello(MYOBJ *obj)
{
return CRYPTO_get_ex_data(&obj->ex_data, saved_idx);
}
static void MYOBJ_sethello2(MYOBJ *obj, char *cp)
{
MYOBJ_EX_DATA* ex_data = CRYPTO_get_ex_data(&obj->ex_data, saved_idx2);
if (TEST_ptr(ex_data))
ex_data->hello = cp;
else
obj->st = gbl_result = 0;
}
static char *MYOBJ_gethello2(MYOBJ *obj)
{
MYOBJ_EX_DATA* ex_data = CRYPTO_get_ex_data(&obj->ex_data, saved_idx2);
if (TEST_ptr(ex_data))
return ex_data->hello;
obj->st = gbl_result = 0;
return NULL;
}
static void MYOBJ_allochello3(MYOBJ *obj, char *cp)
{
MYOBJ_EX_DATA* ex_data = NULL;
if (TEST_ptr_null(ex_data = CRYPTO_get_ex_data(&obj->ex_data, saved_idx3))
&& TEST_true(CRYPTO_alloc_ex_data(CRYPTO_EX_INDEX_APP, obj,
&obj->ex_data, saved_idx3))
&& TEST_ptr(ex_data = CRYPTO_get_ex_data(&obj->ex_data, saved_idx3)))
ex_data->hello = cp;
else
obj->st = gbl_result = 0;
}
static char *MYOBJ_gethello3(MYOBJ *obj)
{
MYOBJ_EX_DATA* ex_data = CRYPTO_get_ex_data(&obj->ex_data, saved_idx3);
if (TEST_ptr(ex_data))
return ex_data->hello;
obj->st = gbl_result = 0;
return NULL;
}
static void MYOBJ_free(MYOBJ *obj)
{
if (obj != NULL) {
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_APP, obj, &obj->ex_data);
OPENSSL_free(obj);
}
}
static MYOBJ *MYOBJ_dup(MYOBJ *in)
{
MYOBJ *obj = MYOBJ_new();
if (obj != NULL)
obj->st |= CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_APP, &obj->ex_data,
&in->ex_data);
return obj;
}
static int test_exdata(void)
{
MYOBJ *t1 = NULL, *t2 = NULL, *t3 = NULL;
MYOBJ_EX_DATA *ex_data = NULL;
const char *cp;
char *p;
int res = 0;
gbl_result = 1;
if (!TEST_ptr(p = OPENSSL_strdup("hello world")))
return 0;
saved_argl = 21;
if (!TEST_ptr(saved_argp = OPENSSL_malloc(1)))
goto err;
saved_idx = CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_APP,
saved_argl, saved_argp,
exnew, exdup, exfree);
saved_idx2 = CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_APP,
saved_argl, saved_argp,
exnew2, exdup2, exfree2);
t1 = MYOBJ_new();
t2 = MYOBJ_new();
if (!TEST_int_eq(t1->st, 1) || !TEST_int_eq(t2->st, 1))
goto err;
if (!TEST_ptr(CRYPTO_get_ex_data(&t1->ex_data, saved_idx2)))
goto err;
/*
* saved_idx3 differs from other indexes by being created after the exdata
* was initialized.
*/
saved_idx3 = CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_APP,
saved_argl, saved_argp,
exnew2, exdup2, exfree2);
if (!TEST_ptr_null(CRYPTO_get_ex_data(&t1->ex_data, saved_idx3)))
goto err;
MYOBJ_sethello(t1, p);
cp = MYOBJ_gethello(t1);
if (!TEST_ptr_eq(cp, p))
goto err;
MYOBJ_sethello2(t1, p);
cp = MYOBJ_gethello2(t1);
if (!TEST_ptr_eq(cp, p))
goto err;
MYOBJ_allochello3(t1, p);
cp = MYOBJ_gethello3(t1);
if (!TEST_ptr_eq(cp, p))
goto err;
cp = MYOBJ_gethello(t2);
if (!TEST_ptr_null(cp))
goto err;
cp = MYOBJ_gethello2(t2);
if (!TEST_ptr_null(cp))
goto err;
t3 = MYOBJ_dup(t1);
if (!TEST_int_eq(t3->st, 1))
goto err;
ex_data = CRYPTO_get_ex_data(&t3->ex_data, saved_idx2);
if (!TEST_ptr(ex_data))
goto err;
if (!TEST_int_eq(ex_data->dup, 1))
goto err;
cp = MYOBJ_gethello(t3);
if (!TEST_ptr_eq(cp, p))
goto err;
cp = MYOBJ_gethello2(t3);
if (!TEST_ptr_eq(cp, p))
goto err;
cp = MYOBJ_gethello3(t3);
if (!TEST_ptr_eq(cp, p))
goto err;
if (gbl_result)
res = 1;
err:
MYOBJ_free(t1);
MYOBJ_free(t2);
MYOBJ_free(t3);
OPENSSL_free(saved_argp);
saved_argp = NULL;
OPENSSL_free(p);
return res;
}
int setup_tests(void)
{
ADD_TEST(test_exdata);
return 1;
}
| 8,296 | 24.928125 | 78 | c |
openssl | openssl-master/test/exptest.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 <string.h>
#include "internal/nelem.h"
#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include "testutil.h"
#define NUM_BITS (BN_BITS2 * 4)
#define BN_print_var(v) test_output_bignum(#v, v)
/*
* Test that r == 0 in test_exp_mod_zero(). Returns one on success,
* returns zero and prints debug output otherwise.
*/
static int a_is_zero_mod_one(const char *method, const BIGNUM *r,
const BIGNUM *a)
{
if (!BN_is_zero(r)) {
TEST_error("%s failed: a ** 0 mod 1 = r (should be 0)", method);
BN_print_var(a);
BN_print_var(r);
return 0;
}
return 1;
}
/*
* test_mod_exp_zero tests that x**0 mod 1 == 0. It returns zero on success.
*/
static int test_mod_exp_zero(void)
{
BIGNUM *a = NULL, *p = NULL, *m = NULL;
BIGNUM *r = NULL;
BN_ULONG one_word = 1;
BN_CTX *ctx = BN_CTX_new();
int ret = 0, failed = 0;
BN_MONT_CTX *mont = NULL;
if (!TEST_ptr(m = BN_new())
|| !TEST_ptr(a = BN_new())
|| !TEST_ptr(p = BN_new())
|| !TEST_ptr(r = BN_new()))
goto err;
BN_one(m);
BN_one(a);
BN_zero(p);
if (!TEST_true(BN_rand(a, 1024, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY)))
goto err;
if (!TEST_true(BN_mod_exp(r, a, p, m, ctx)))
goto err;
if (!TEST_true(a_is_zero_mod_one("BN_mod_exp", r, a)))
failed = 1;
if (!TEST_true(BN_mod_exp_recp(r, a, p, m, ctx)))
goto err;
if (!TEST_true(a_is_zero_mod_one("BN_mod_exp_recp", r, a)))
failed = 1;
if (!TEST_true(BN_mod_exp_simple(r, a, p, m, ctx)))
goto err;
if (!TEST_true(a_is_zero_mod_one("BN_mod_exp_simple", r, a)))
failed = 1;
if (!TEST_true(BN_mod_exp_mont(r, a, p, m, ctx, NULL)))
goto err;
if (!TEST_true(a_is_zero_mod_one("BN_mod_exp_mont", r, a)))
failed = 1;
if (!TEST_true(BN_mod_exp_mont_consttime(r, a, p, m, ctx, NULL)))
goto err;
if (!TEST_true(a_is_zero_mod_one("BN_mod_exp_mont_consttime", r, a)))
failed = 1;
if (!TEST_ptr(mont = BN_MONT_CTX_new()))
goto err;
ERR_set_mark();
/* mont is not set but passed in */
if (!TEST_false(BN_mod_exp_mont_consttime(r, p, a, m, ctx, mont)))
goto err;
if (!TEST_false(BN_mod_exp_mont(r, p, a, m, ctx, mont)))
goto err;
ERR_pop_to_mark();
if (!TEST_true(BN_MONT_CTX_set(mont, m, ctx)))
goto err;
/* we compute 0 ** a mod 1 here, to execute code that uses mont */
if (!TEST_true(BN_mod_exp_mont_consttime(r, p, a, m, ctx, mont)))
goto err;
if (!TEST_true(a_is_zero_mod_one("BN_mod_exp_mont_consttime", r, a)))
failed = 1;
if (!TEST_true(BN_mod_exp_mont(r, p, a, m, ctx, mont)))
goto err;
if (!TEST_true(a_is_zero_mod_one("BN_mod_exp_mont", r, a)))
failed = 1;
/*
* A different codepath exists for single word multiplication
* in non-constant-time only.
*/
if (!TEST_true(BN_mod_exp_mont_word(r, one_word, p, m, ctx, NULL)))
goto err;
if (!TEST_BN_eq_zero(r)) {
TEST_error("BN_mod_exp_mont_word failed: "
"1 ** 0 mod 1 = r (should be 0)");
BN_print_var(r);
goto err;
}
ret = !failed;
err:
BN_free(r);
BN_free(a);
BN_free(p);
BN_free(m);
BN_MONT_CTX_free(mont);
BN_CTX_free(ctx);
return ret;
}
static int test_mod_exp(int round)
{
BN_CTX *ctx;
unsigned char c;
int ret = 0;
BIGNUM *r_mont = NULL;
BIGNUM *r_mont_const = NULL;
BIGNUM *r_recp = NULL;
BIGNUM *r_simple = NULL;
BIGNUM *a = NULL;
BIGNUM *b = NULL;
BIGNUM *m = NULL;
if (!TEST_ptr(ctx = BN_CTX_new()))
goto err;
if (!TEST_ptr(r_mont = BN_new())
|| !TEST_ptr(r_mont_const = BN_new())
|| !TEST_ptr(r_recp = BN_new())
|| !TEST_ptr(r_simple = BN_new())
|| !TEST_ptr(a = BN_new())
|| !TEST_ptr(b = BN_new())
|| !TEST_ptr(m = BN_new()))
goto err;
if (!TEST_int_gt(RAND_bytes(&c, 1), 0))
goto err;
c = (c % BN_BITS) - BN_BITS2;
if (!TEST_true(BN_rand(a, NUM_BITS + c, BN_RAND_TOP_ONE,
BN_RAND_BOTTOM_ANY)))
goto err;
if (!TEST_int_gt(RAND_bytes(&c, 1), 0))
goto err;
c = (c % BN_BITS) - BN_BITS2;
if (!TEST_true(BN_rand(b, NUM_BITS + c, BN_RAND_TOP_ONE,
BN_RAND_BOTTOM_ANY)))
goto err;
if (!TEST_int_gt(RAND_bytes(&c, 1), 0))
goto err;
c = (c % BN_BITS) - BN_BITS2;
if (!TEST_true(BN_rand(m, NUM_BITS + c, BN_RAND_TOP_ONE,
BN_RAND_BOTTOM_ODD)))
goto err;
if (!TEST_true(BN_mod(a, a, m, ctx))
|| !TEST_true(BN_mod(b, b, m, ctx))
|| !TEST_true(BN_mod_exp_mont(r_mont, a, b, m, ctx, NULL))
|| !TEST_true(BN_mod_exp_recp(r_recp, a, b, m, ctx))
|| !TEST_true(BN_mod_exp_simple(r_simple, a, b, m, ctx))
|| !TEST_true(BN_mod_exp_mont_consttime(r_mont_const, a, b, m, ctx, NULL)))
goto err;
if (!TEST_BN_eq(r_simple, r_mont)
|| !TEST_BN_eq(r_simple, r_recp)
|| !TEST_BN_eq(r_simple, r_mont_const)) {
if (BN_cmp(r_simple, r_mont) != 0)
TEST_info("simple and mont results differ");
if (BN_cmp(r_simple, r_mont_const) != 0)
TEST_info("simple and mont const time results differ");
if (BN_cmp(r_simple, r_recp) != 0)
TEST_info("simple and recp results differ");
BN_print_var(a);
BN_print_var(b);
BN_print_var(m);
BN_print_var(r_simple);
BN_print_var(r_recp);
BN_print_var(r_mont);
BN_print_var(r_mont_const);
goto err;
}
ret = 1;
err:
BN_free(r_mont);
BN_free(r_mont_const);
BN_free(r_recp);
BN_free(r_simple);
BN_free(a);
BN_free(b);
BN_free(m);
BN_CTX_free(ctx);
return ret;
}
static int test_mod_exp_x2(int idx)
{
BN_CTX *ctx;
int ret = 0;
BIGNUM *r_mont_const_x2_1 = NULL;
BIGNUM *r_mont_const_x2_2 = NULL;
BIGNUM *r_simple1 = NULL;
BIGNUM *r_simple2 = NULL;
BIGNUM *a1 = NULL;
BIGNUM *b1 = NULL;
BIGNUM *m1 = NULL;
BIGNUM *a2 = NULL;
BIGNUM *b2 = NULL;
BIGNUM *m2 = NULL;
int factor_size = 0;
if (idx <= 100)
factor_size = 1024;
else if (idx <= 200)
factor_size = 1536;
else if (idx <= 300)
factor_size = 2048;
if (!TEST_ptr(ctx = BN_CTX_new()))
goto err;
if (!TEST_ptr(r_mont_const_x2_1 = BN_new())
|| !TEST_ptr(r_mont_const_x2_2 = BN_new())
|| !TEST_ptr(r_simple1 = BN_new())
|| !TEST_ptr(r_simple2 = BN_new())
|| !TEST_ptr(a1 = BN_new())
|| !TEST_ptr(b1 = BN_new())
|| !TEST_ptr(m1 = BN_new())
|| !TEST_ptr(a2 = BN_new())
|| !TEST_ptr(b2 = BN_new())
|| !TEST_ptr(m2 = BN_new()))
goto err;
BN_rand(a1, factor_size, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY);
BN_rand(b1, factor_size, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY);
BN_rand(m1, factor_size, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD);
BN_rand(a2, factor_size, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY);
BN_rand(b2, factor_size, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY);
BN_rand(m2, factor_size, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ODD);
if (!TEST_true(BN_mod(a1, a1, m1, ctx))
|| !TEST_true(BN_mod(b1, b1, m1, ctx))
|| !TEST_true(BN_mod(a2, a2, m2, ctx))
|| !TEST_true(BN_mod(b2, b2, m2, ctx))
|| !TEST_true(BN_mod_exp_simple(r_simple1, a1, b1, m1, ctx))
|| !TEST_true(BN_mod_exp_simple(r_simple2, a2, b2, m2, ctx))
|| !TEST_true(BN_mod_exp_mont_consttime_x2(r_mont_const_x2_1, a1, b1, m1, NULL,
r_mont_const_x2_2, a2, b2, m2, NULL,
ctx)))
goto err;
if (!TEST_BN_eq(r_simple1, r_mont_const_x2_1)
|| !TEST_BN_eq(r_simple2, r_mont_const_x2_2)) {
if (BN_cmp(r_simple1, r_mont_const_x2_1) != 0)
TEST_info("simple and mont const time x2 (#1) results differ");
if (BN_cmp(r_simple2, r_mont_const_x2_2) != 0)
TEST_info("simple and mont const time x2 (#2) results differ");
BN_print_var(a1);
BN_print_var(b1);
BN_print_var(m1);
BN_print_var(a2);
BN_print_var(b2);
BN_print_var(m2);
BN_print_var(r_simple1);
BN_print_var(r_simple2);
BN_print_var(r_mont_const_x2_1);
BN_print_var(r_mont_const_x2_2);
goto err;
}
ret = 1;
err:
BN_free(r_mont_const_x2_1);
BN_free(r_mont_const_x2_2);
BN_free(r_simple1);
BN_free(r_simple2);
BN_free(a1);
BN_free(b1);
BN_free(m1);
BN_free(a2);
BN_free(b2);
BN_free(m2);
BN_CTX_free(ctx);
return ret;
}
int setup_tests(void)
{
ADD_TEST(test_mod_exp_zero);
ADD_ALL_TESTS(test_mod_exp, 200);
ADD_ALL_TESTS(test_mod_exp_x2, 300);
return 1;
}
| 9,512 | 27.061947 | 87 | c |
openssl | openssl-master/test/ext_internal_test.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 "internal/nelem.h"
#include "../ssl/ssl_local.h"
#include "../ssl/statem/statem_local.h"
#include "testutil.h"
#define EXT_ENTRY(name) { TLSEXT_IDX_##name, TLSEXT_TYPE_##name, #name }
#define EXT_EXCEPTION(name) { TLSEXT_IDX_##name, TLSEXT_TYPE_invalid, #name }
#define EXT_END(name) { TLSEXT_IDX_##name, TLSEXT_TYPE_out_of_range, #name }
typedef struct {
size_t idx;
unsigned int type;
char *name;
} EXT_LIST;
/* The order here does matter! */
static EXT_LIST ext_list[] = {
EXT_ENTRY(renegotiate),
EXT_ENTRY(server_name),
EXT_ENTRY(max_fragment_length),
#ifndef OPENSSL_NO_SRP
EXT_ENTRY(srp),
#else
EXT_EXCEPTION(srp),
#endif
EXT_ENTRY(ec_point_formats),
EXT_ENTRY(supported_groups),
EXT_ENTRY(session_ticket),
#ifndef OPENSSL_NO_OCSP
EXT_ENTRY(status_request),
#else
EXT_EXCEPTION(status_request),
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
EXT_ENTRY(next_proto_neg),
#else
EXT_EXCEPTION(next_proto_neg),
#endif
EXT_ENTRY(application_layer_protocol_negotiation),
#ifndef OPENSSL_NO_SRTP
EXT_ENTRY(use_srtp),
#else
EXT_EXCEPTION(use_srtp),
#endif
EXT_ENTRY(encrypt_then_mac),
#ifndef OPENSSL_NO_CT
EXT_ENTRY(signed_certificate_timestamp),
#else
EXT_EXCEPTION(signed_certificate_timestamp),
#endif
EXT_ENTRY(extended_master_secret),
EXT_ENTRY(signature_algorithms_cert),
EXT_ENTRY(post_handshake_auth),
EXT_ENTRY(client_cert_type),
EXT_ENTRY(server_cert_type),
EXT_ENTRY(signature_algorithms),
EXT_ENTRY(supported_versions),
EXT_ENTRY(psk_kex_modes),
EXT_ENTRY(key_share),
EXT_ENTRY(cookie),
EXT_ENTRY(cryptopro_bug),
EXT_ENTRY(compress_certificate),
EXT_ENTRY(early_data),
EXT_ENTRY(certificate_authorities),
EXT_ENTRY(padding),
EXT_ENTRY(psk),
EXT_END(num_builtins)
};
static int test_extension_list(void)
{
size_t n = OSSL_NELEM(ext_list);
size_t i;
unsigned int type;
int retval = 1;
for (i = 0; i < n; i++) {
if (!TEST_size_t_eq(i, ext_list[i].idx)) {
retval = 0;
TEST_error("TLSEXT_IDX_%s=%zd, found at=%zd\n",
ext_list[i].name, ext_list[i].idx, i);
}
type = ossl_get_extension_type(ext_list[i].idx);
if (!TEST_uint_eq(type, ext_list[i].type)) {
retval = 0;
TEST_error("TLSEXT_IDX_%s=%zd expected=0x%05X got=0x%05X",
ext_list[i].name, ext_list[i].idx, ext_list[i].type,
type);
}
}
return retval;
}
int setup_tests(void)
{
ADD_TEST(test_extension_list);
return 1;
}
| 2,966 | 26.220183 | 77 | c |
openssl | openssl-master/test/fake_rsaprov.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 may obtain a copy of the License at
* https://www.openssl.org/source/license.html
* or in the file LICENSE in the source distribution.
*/
#include <string.h>
#include <openssl/core_names.h>
#include <openssl/core_object.h>
#include <openssl/rand.h>
#include <openssl/provider.h>
#include "testutil.h"
#include "fake_rsaprov.h"
static OSSL_FUNC_keymgmt_new_fn fake_rsa_keymgmt_new;
static OSSL_FUNC_keymgmt_free_fn fake_rsa_keymgmt_free;
static OSSL_FUNC_keymgmt_has_fn fake_rsa_keymgmt_has;
static OSSL_FUNC_keymgmt_query_operation_name_fn fake_rsa_keymgmt_query;
static OSSL_FUNC_keymgmt_import_fn fake_rsa_keymgmt_import;
static OSSL_FUNC_keymgmt_import_types_fn fake_rsa_keymgmt_imptypes;
static OSSL_FUNC_keymgmt_export_fn fake_rsa_keymgmt_export;
static OSSL_FUNC_keymgmt_export_types_fn fake_rsa_keymgmt_exptypes;
static OSSL_FUNC_keymgmt_load_fn fake_rsa_keymgmt_load;
static int has_selection;
static int imptypes_selection;
static int exptypes_selection;
static int query_id;
struct fake_rsa_keydata {
int selection;
int status;
};
static void *fake_rsa_keymgmt_new(void *provctx)
{
struct fake_rsa_keydata *key;
if (!TEST_ptr(key = OPENSSL_zalloc(sizeof(struct fake_rsa_keydata))))
return NULL;
/* clear test globals */
has_selection = 0;
imptypes_selection = 0;
exptypes_selection = 0;
query_id = 0;
return key;
}
static void fake_rsa_keymgmt_free(void *keydata)
{
OPENSSL_free(keydata);
}
static int fake_rsa_keymgmt_has(const void *key, int selection)
{
/* record global for checking */
has_selection = selection;
return 1;
}
static const char *fake_rsa_keymgmt_query(int id)
{
/* record global for checking */
query_id = id;
return "RSA";
}
static int fake_rsa_keymgmt_import(void *keydata, int selection,
const OSSL_PARAM *p)
{
struct fake_rsa_keydata *fake_rsa_key = keydata;
/* key was imported */
fake_rsa_key->status = 1;
return 1;
}
static unsigned char fake_rsa_n[] =
"\x00\xAA\x36\xAB\xCE\x88\xAC\xFD\xFF\x55\x52\x3C\x7F\xC4\x52\x3F"
"\x90\xEF\xA0\x0D\xF3\x77\x4A\x25\x9F\x2E\x62\xB4\xC5\xD9\x9C\xB5"
"\xAD\xB3\x00\xA0\x28\x5E\x53\x01\x93\x0E\x0C\x70\xFB\x68\x76\x93"
"\x9C\xE6\x16\xCE\x62\x4A\x11\xE0\x08\x6D\x34\x1E\xBC\xAC\xA0\xA1"
"\xF5";
static unsigned char fake_rsa_e[] = "\x11";
static unsigned char fake_rsa_d[] =
"\x0A\x03\x37\x48\x62\x64\x87\x69\x5F\x5F\x30\xBC\x38\xB9\x8B\x44"
"\xC2\xCD\x2D\xFF\x43\x40\x98\xCD\x20\xD8\xA1\x38\xD0\x90\xBF\x64"
"\x79\x7C\x3F\xA7\xA2\xCD\xCB\x3C\xD1\xE0\xBD\xBA\x26\x54\xB4\xF9"
"\xDF\x8E\x8A\xE5\x9D\x73\x3D\x9F\x33\xB3\x01\x62\x4A\xFD\x1D\x51";
static unsigned char fake_rsa_p[] =
"\x00\xD8\x40\xB4\x16\x66\xB4\x2E\x92\xEA\x0D\xA3\xB4\x32\x04\xB5"
"\xCF\xCE\x33\x52\x52\x4D\x04\x16\xA5\xA4\x41\xE7\x00\xAF\x46\x12"
"\x0D";
static unsigned char fake_rsa_q[] =
"\x00\xC9\x7F\xB1\xF0\x27\xF4\x53\xF6\x34\x12\x33\xEA\xAA\xD1\xD9"
"\x35\x3F\x6C\x42\xD0\x88\x66\xB1\xD0\x5A\x0F\x20\x35\x02\x8B\x9D"
"\x89";
static unsigned char fake_rsa_dmp1[] =
"\x59\x0B\x95\x72\xA2\xC2\xA9\xC4\x06\x05\x9D\xC2\xAB\x2F\x1D\xAF"
"\xEB\x7E\x8B\x4F\x10\xA7\x54\x9E\x8E\xED\xF5\xB4\xFC\xE0\x9E\x05";
static unsigned char fake_rsa_dmq1[] =
"\x00\x8E\x3C\x05\x21\xFE\x15\xE0\xEA\x06\xA3\x6F\xF0\xF1\x0C\x99"
"\x52\xC3\x5B\x7A\x75\x14\xFD\x32\x38\xB8\x0A\xAD\x52\x98\x62\x8D"
"\x51";
static unsigned char fake_rsa_iqmp[] =
"\x36\x3F\xF7\x18\x9D\xA8\xE9\x0B\x1D\x34\x1F\x71\xD0\x9B\x76\xA8"
"\xA9\x43\xE1\x1D\x10\xB2\x4D\x24\x9F\x2D\xEA\xFE\xF8\x0C\x18\x26";
OSSL_PARAM *fake_rsa_key_params(int priv)
{
if (priv) {
OSSL_PARAM params[] = {
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_N, fake_rsa_n,
sizeof(fake_rsa_n) -1),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_E, fake_rsa_e,
sizeof(fake_rsa_e) -1),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_D, fake_rsa_d,
sizeof(fake_rsa_d) -1),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_FACTOR1, fake_rsa_p,
sizeof(fake_rsa_p) -1),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_FACTOR2, fake_rsa_q,
sizeof(fake_rsa_q) -1),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_EXPONENT1, fake_rsa_dmp1,
sizeof(fake_rsa_dmp1) -1),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_EXPONENT2, fake_rsa_dmq1,
sizeof(fake_rsa_dmq1) -1),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_COEFFICIENT1, fake_rsa_iqmp,
sizeof(fake_rsa_iqmp) -1),
OSSL_PARAM_END
};
return OSSL_PARAM_dup(params);
} else {
OSSL_PARAM params[] = {
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_N, fake_rsa_n,
sizeof(fake_rsa_n) -1),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_E, fake_rsa_e,
sizeof(fake_rsa_e) -1),
OSSL_PARAM_END
};
return OSSL_PARAM_dup(params);
}
}
static int fake_rsa_keymgmt_export(void *keydata, int selection,
OSSL_CALLBACK *param_callback, void *cbarg)
{
OSSL_PARAM *params = NULL;
int ret;
if (selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY)
return 0;
if (!TEST_ptr(params = fake_rsa_key_params(0)))
return 0;
ret = param_callback(params, cbarg);
OSSL_PARAM_free(params);
return ret;
}
static const OSSL_PARAM fake_rsa_import_key_types[] = {
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_N, NULL, 0),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_E, NULL, 0),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_D, NULL, 0),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_FACTOR1, NULL, 0),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_FACTOR2, NULL, 0),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_EXPONENT1, NULL, 0),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_EXPONENT2, NULL, 0),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_COEFFICIENT1, NULL, 0),
OSSL_PARAM_END
};
static const OSSL_PARAM *fake_rsa_keymgmt_imptypes(int selection)
{
/* record global for checking */
imptypes_selection = selection;
return fake_rsa_import_key_types;
}
static const OSSL_PARAM fake_rsa_export_key_types[] = {
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_N, NULL, 0),
OSSL_PARAM_BN(OSSL_PKEY_PARAM_RSA_E, NULL, 0),
OSSL_PARAM_END
};
static const OSSL_PARAM *fake_rsa_keymgmt_exptypes(int selection)
{
/* record global for checking */
exptypes_selection = selection;
return fake_rsa_export_key_types;
}
static void *fake_rsa_keymgmt_load(const void *reference, size_t reference_sz)
{
struct fake_rsa_keydata *key = NULL;
if (reference_sz != sizeof(*key))
return NULL;
key = *(struct fake_rsa_keydata **)reference;
if (key->status != 1)
return NULL;
/* detach the reference */
*(struct fake_rsa_keydata **)reference = NULL;
return key;
}
static void *fake_rsa_gen_init(void *provctx, int selection,
const OSSL_PARAM params[])
{
unsigned char *gctx = NULL;
if (!TEST_ptr(gctx = OPENSSL_malloc(1)))
return NULL;
*gctx = 1;
return gctx;
}
static void *fake_rsa_gen(void *genctx, OSSL_CALLBACK *osslcb, void *cbarg)
{
unsigned char *gctx = genctx;
static const unsigned char inited[] = { 1 };
struct fake_rsa_keydata *keydata;
if (!TEST_ptr(gctx)
|| !TEST_mem_eq(gctx, sizeof(*gctx), inited, sizeof(inited)))
return NULL;
if (!TEST_ptr(keydata = fake_rsa_keymgmt_new(NULL)))
return NULL;
keydata->status = 2;
return keydata;
}
static void fake_rsa_gen_cleanup(void *genctx)
{
OPENSSL_free(genctx);
}
static const OSSL_DISPATCH fake_rsa_keymgmt_funcs[] = {
{ OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))fake_rsa_keymgmt_new },
{ OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))fake_rsa_keymgmt_free} ,
{ OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))fake_rsa_keymgmt_has },
{ OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME,
(void (*)(void))fake_rsa_keymgmt_query },
{ OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))fake_rsa_keymgmt_import },
{ OSSL_FUNC_KEYMGMT_IMPORT_TYPES,
(void (*)(void))fake_rsa_keymgmt_imptypes },
{ OSSL_FUNC_KEYMGMT_EXPORT, (void (*)(void))fake_rsa_keymgmt_export },
{ OSSL_FUNC_KEYMGMT_EXPORT_TYPES,
(void (*)(void))fake_rsa_keymgmt_exptypes },
{ OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))fake_rsa_keymgmt_load },
{ OSSL_FUNC_KEYMGMT_GEN_INIT, (void (*)(void))fake_rsa_gen_init },
{ OSSL_FUNC_KEYMGMT_GEN, (void (*)(void))fake_rsa_gen },
{ OSSL_FUNC_KEYMGMT_GEN_CLEANUP, (void (*)(void))fake_rsa_gen_cleanup },
OSSL_DISPATCH_END
};
static const OSSL_ALGORITHM fake_rsa_keymgmt_algs[] = {
{ "RSA:rsaEncryption", "provider=fake-rsa", fake_rsa_keymgmt_funcs, "Fake RSA Key Management" },
{ NULL, NULL, NULL, NULL }
};
static OSSL_FUNC_signature_newctx_fn fake_rsa_sig_newctx;
static OSSL_FUNC_signature_freectx_fn fake_rsa_sig_freectx;
static OSSL_FUNC_signature_sign_init_fn fake_rsa_sig_sign_init;
static OSSL_FUNC_signature_sign_fn fake_rsa_sig_sign;
static void *fake_rsa_sig_newctx(void *provctx, const char *propq)
{
unsigned char *sigctx = OPENSSL_zalloc(1);
TEST_ptr(sigctx);
return sigctx;
}
static void fake_rsa_sig_freectx(void *sigctx)
{
OPENSSL_free(sigctx);
}
static int fake_rsa_sig_sign_init(void *ctx, void *provkey,
const OSSL_PARAM params[])
{
unsigned char *sigctx = ctx;
struct fake_rsa_keydata *keydata = provkey;
/* we must have a ctx */
if (!TEST_ptr(sigctx))
return 0;
/* we must have some initialized key */
if (!TEST_ptr(keydata) || !TEST_int_gt(keydata->status, 0))
return 0;
/* record that sign init was called */
*sigctx = 1;
return 1;
}
static int fake_rsa_sig_sign(void *ctx, unsigned char *sig,
size_t *siglen, size_t sigsize,
const unsigned char *tbs, size_t tbslen)
{
unsigned char *sigctx = ctx;
/* we must have a ctx and init was called upon it */
if (!TEST_ptr(sigctx) || !TEST_int_eq(*sigctx, 1))
return 0;
*siglen = 256;
/* record that the real sign operation was called */
if (sig != NULL) {
if (!TEST_int_ge(sigsize, *siglen))
return 0;
*sigctx = 2;
/* produce a fake signature */
memset(sig, 'a', *siglen);
}
return 1;
}
#define FAKE_DGSTSGN_SIGN 0x01
#define FAKE_DGSTSGN_VERIFY 0x02
#define FAKE_DGSTSGN_UPDATED 0x04
#define FAKE_DGSTSGN_FINALISED 0x08
#define FAKE_DGSTSGN_NO_DUP 0xA0
static void *fake_rsa_sig_dupctx(void *ctx)
{
unsigned char *sigctx = ctx;
unsigned char *newctx;
if ((*sigctx & FAKE_DGSTSGN_NO_DUP) != 0)
return NULL;
if (!TEST_ptr(newctx = OPENSSL_zalloc(1)))
return NULL;
*newctx = *sigctx;
return newctx;
}
static int fake_rsa_dgstsgnvfy_init(void *ctx, unsigned char type,
void *provkey, const OSSL_PARAM params[])
{
unsigned char *sigctx = ctx;
struct fake_rsa_keydata *keydata = provkey;
/* we must have a ctx */
if (!TEST_ptr(sigctx))
return 0;
/* we must have some initialized key */
if (!TEST_ptr(keydata) || !TEST_int_gt(keydata->status, 0))
return 0;
/* record that sign/verify init was called */
*sigctx = type;
if (params) {
const OSSL_PARAM *p;
int dup;
p = OSSL_PARAM_locate_const(params, "NO_DUP");
if (p != NULL) {
if (OSSL_PARAM_get_int(p, &dup)) {
*sigctx |= FAKE_DGSTSGN_NO_DUP;
}
}
}
return 1;
}
static int fake_rsa_dgstsgn_init(void *ctx, const char *mdname,
void *provkey, const OSSL_PARAM params[])
{
return fake_rsa_dgstsgnvfy_init(ctx, FAKE_DGSTSGN_SIGN, provkey, params);
}
static int fake_rsa_dgstvfy_init(void *ctx, const char *mdname,
void *provkey, const OSSL_PARAM params[])
{
return fake_rsa_dgstsgnvfy_init(ctx, FAKE_DGSTSGN_VERIFY, provkey, params);
}
static int fake_rsa_dgstsgnvfy_update(void *ctx, const unsigned char *data,
size_t datalen)
{
unsigned char *sigctx = ctx;
/* we must have a ctx */
if (!TEST_ptr(sigctx))
return 0;
if (*sigctx == 0 || (*sigctx & FAKE_DGSTSGN_FINALISED) != 0)
return 0;
*sigctx |= FAKE_DGSTSGN_UPDATED;
return 1;
}
static int fake_rsa_dgstsgnvfy_final(void *ctx, unsigned char *sig,
size_t *siglen, size_t sigsize)
{
unsigned char *sigctx = ctx;
/* we must have a ctx */
if (!TEST_ptr(sigctx))
return 0;
if (*sigctx == 0 || (*sigctx & FAKE_DGSTSGN_FINALISED) != 0)
return 0;
if ((*sigctx & FAKE_DGSTSGN_SIGN) != 0 && (siglen == NULL))
return 0;
if ((*sigctx & FAKE_DGSTSGN_VERIFY) != 0 && (siglen != NULL))
return 0;
/* this is sign op */
if (siglen) {
*siglen = 256;
/* record that the real sign operation was called */
if (sig != NULL) {
if (!TEST_int_ge(sigsize, *siglen))
return 0;
/* produce a fake signature */
memset(sig, 'a', *siglen);
}
}
/* simulate inability to duplicate context and finalise it */
if ((*sigctx & FAKE_DGSTSGN_NO_DUP) != 0) {
*sigctx |= FAKE_DGSTSGN_FINALISED;
}
return 1;
}
static int fake_rsa_dgstvfy_final(void *ctx, unsigned char *sig,
size_t siglen)
{
return fake_rsa_dgstsgnvfy_final(ctx, sig, NULL, siglen);
}
static int fake_rsa_dgstsgn(void *ctx, unsigned char *sig, size_t *siglen,
size_t sigsize, const unsigned char *tbs,
size_t tbslen)
{
if (!fake_rsa_dgstsgnvfy_update(ctx, tbs, tbslen))
return 0;
return fake_rsa_dgstsgnvfy_final(ctx, sig, siglen, sigsize);
}
static int fake_rsa_dgstvfy(void *ctx, unsigned char *sig, size_t siglen,
const unsigned char *tbv, size_t tbvlen)
{
if (!fake_rsa_dgstsgnvfy_update(ctx, tbv, tbvlen))
return 0;
return fake_rsa_dgstvfy_final(ctx, sig, siglen);
}
static const OSSL_DISPATCH fake_rsa_sig_funcs[] = {
{ OSSL_FUNC_SIGNATURE_NEWCTX, (void (*)(void))fake_rsa_sig_newctx },
{ OSSL_FUNC_SIGNATURE_FREECTX, (void (*)(void))fake_rsa_sig_freectx },
{ OSSL_FUNC_SIGNATURE_SIGN_INIT, (void (*)(void))fake_rsa_sig_sign_init },
{ OSSL_FUNC_SIGNATURE_SIGN, (void (*)(void))fake_rsa_sig_sign },
{ OSSL_FUNC_SIGNATURE_DUPCTX, (void (*)(void))fake_rsa_sig_dupctx },
{ OSSL_FUNC_SIGNATURE_DIGEST_SIGN_INIT,
(void (*)(void))fake_rsa_dgstsgn_init },
{ OSSL_FUNC_SIGNATURE_DIGEST_SIGN_UPDATE,
(void (*)(void))fake_rsa_dgstsgnvfy_update },
{ OSSL_FUNC_SIGNATURE_DIGEST_SIGN_FINAL,
(void (*)(void))fake_rsa_dgstsgnvfy_final },
{ OSSL_FUNC_SIGNATURE_DIGEST_SIGN,
(void (*)(void))fake_rsa_dgstsgn },
{ OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_INIT,
(void (*)(void))fake_rsa_dgstvfy_init },
{ OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_UPDATE,
(void (*)(void))fake_rsa_dgstsgnvfy_update },
{ OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_FINAL,
(void (*)(void))fake_rsa_dgstvfy_final },
{ OSSL_FUNC_SIGNATURE_DIGEST_VERIFY,
(void (*)(void))fake_rsa_dgstvfy },
OSSL_DISPATCH_END
};
static const OSSL_ALGORITHM fake_rsa_sig_algs[] = {
{ "RSA:rsaEncryption", "provider=fake-rsa", fake_rsa_sig_funcs, "Fake RSA Signature" },
{ NULL, NULL, NULL, NULL }
};
static OSSL_FUNC_store_open_fn fake_rsa_st_open;
static OSSL_FUNC_store_settable_ctx_params_fn fake_rsa_st_settable_ctx_params;
static OSSL_FUNC_store_set_ctx_params_fn fake_rsa_st_set_ctx_params;
static OSSL_FUNC_store_load_fn fake_rsa_st_load;
static OSSL_FUNC_store_eof_fn fake_rsa_st_eof;
static OSSL_FUNC_store_close_fn fake_rsa_st_close;
static const char fake_rsa_scheme[] = "fake_rsa:";
static void *fake_rsa_st_open(void *provctx, const char *uri)
{
unsigned char *storectx = NULL;
/* First check whether the uri is ours */
if (strncmp(uri, fake_rsa_scheme, sizeof(fake_rsa_scheme) - 1) != 0)
return NULL;
storectx = OPENSSL_zalloc(1);
if (!TEST_ptr(storectx))
return NULL;
TEST_info("fake_rsa_open called");
return storectx;
}
static const OSSL_PARAM *fake_rsa_st_settable_ctx_params(void *provctx)
{
static const OSSL_PARAM known_settable_ctx_params[] = {
OSSL_PARAM_END
};
return known_settable_ctx_params;
}
static int fake_rsa_st_set_ctx_params(void *loaderctx,
const OSSL_PARAM params[])
{
return 1;
}
static int fake_rsa_st_load(void *loaderctx,
OSSL_CALLBACK *object_cb, void *object_cbarg,
OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
{
unsigned char *storectx = loaderctx;
OSSL_PARAM params[4];
int object_type = OSSL_OBJECT_PKEY;
struct fake_rsa_keydata *key = NULL;
int rv = 0;
switch (*storectx) {
case 0:
/* Construct a new key using our keymgmt functions */
if (!TEST_ptr(key = fake_rsa_keymgmt_new(NULL)))
break;
if (!TEST_int_gt(fake_rsa_keymgmt_import(key, 0, NULL), 0))
break;
params[0] =
OSSL_PARAM_construct_int(OSSL_OBJECT_PARAM_TYPE, &object_type);
params[1] =
OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_TYPE,
"RSA", 0);
/* The address of the key becomes the octet string */
params[2] =
OSSL_PARAM_construct_octet_string(OSSL_OBJECT_PARAM_REFERENCE,
&key, sizeof(*key));
params[3] = OSSL_PARAM_construct_end();
rv = object_cb(params, object_cbarg);
*storectx = 1;
break;
case 2:
TEST_info("fake_rsa_load() called in error state");
break;
default:
TEST_info("fake_rsa_load() called in eof state");
break;
}
TEST_info("fake_rsa_load called - rv: %d", rv);
if (rv == 0) {
fake_rsa_keymgmt_free(key);
*storectx = 2;
}
return rv;
}
static int fake_rsa_st_eof(void *loaderctx)
{
unsigned char *storectx = loaderctx;
/* just one key for now in the fake_rsa store */
return *storectx != 0;
}
static int fake_rsa_st_close(void *loaderctx)
{
OPENSSL_free(loaderctx);
return 1;
}
static const OSSL_DISPATCH fake_rsa_store_funcs[] = {
{ OSSL_FUNC_STORE_OPEN, (void (*)(void))fake_rsa_st_open },
{ OSSL_FUNC_STORE_SETTABLE_CTX_PARAMS,
(void (*)(void))fake_rsa_st_settable_ctx_params },
{ OSSL_FUNC_STORE_SET_CTX_PARAMS, (void (*)(void))fake_rsa_st_set_ctx_params },
{ OSSL_FUNC_STORE_LOAD, (void (*)(void))fake_rsa_st_load },
{ OSSL_FUNC_STORE_EOF, (void (*)(void))fake_rsa_st_eof },
{ OSSL_FUNC_STORE_CLOSE, (void (*)(void))fake_rsa_st_close },
OSSL_DISPATCH_END,
};
static const OSSL_ALGORITHM fake_rsa_store_algs[] = {
{ "fake_rsa", "provider=fake-rsa", fake_rsa_store_funcs },
{ NULL, NULL, NULL }
};
static const OSSL_ALGORITHM *fake_rsa_query(void *provctx,
int operation_id,
int *no_cache)
{
*no_cache = 0;
switch (operation_id) {
case OSSL_OP_SIGNATURE:
return fake_rsa_sig_algs;
case OSSL_OP_KEYMGMT:
return fake_rsa_keymgmt_algs;
case OSSL_OP_STORE:
return fake_rsa_store_algs;
}
return NULL;
}
/* Functions we provide to the core */
static const OSSL_DISPATCH fake_rsa_method[] = {
{ OSSL_FUNC_PROVIDER_TEARDOWN, (void (*)(void))OSSL_LIB_CTX_free },
{ OSSL_FUNC_PROVIDER_QUERY_OPERATION, (void (*)(void))fake_rsa_query },
OSSL_DISPATCH_END
};
static int fake_rsa_provider_init(const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in,
const OSSL_DISPATCH **out, void **provctx)
{
if (!TEST_ptr(*provctx = OSSL_LIB_CTX_new()))
return 0;
*out = fake_rsa_method;
return 1;
}
OSSL_PROVIDER *fake_rsa_start(OSSL_LIB_CTX *libctx)
{
OSSL_PROVIDER *p;
if (!TEST_true(OSSL_PROVIDER_add_builtin(libctx, "fake-rsa",
fake_rsa_provider_init))
|| !TEST_ptr(p = OSSL_PROVIDER_try_load(libctx, "fake-rsa", 1)))
return NULL;
return p;
}
void fake_rsa_finish(OSSL_PROVIDER *p)
{
OSSL_PROVIDER_unload(p);
}
| 21,059 | 29.477569 | 100 | c |
openssl | openssl-master/test/fake_rsaprov.h | /*
* 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_dispatch.h>
/* Fake RSA provider implementation */
OSSL_PROVIDER *fake_rsa_start(OSSL_LIB_CTX *libctx);
void fake_rsa_finish(OSSL_PROVIDER *p);
OSSL_PARAM *fake_rsa_key_params(int priv);
| 543 | 33 | 74 | h |
openssl | openssl-master/test/fatalerrtest.c | /*
* Copyright 2017-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/ssl.h>
#include <openssl/err.h>
#include "helpers/ssltestlib.h"
#include "testutil.h"
#include <string.h>
static char *cert = NULL;
static char *privkey = NULL;
static int test_fatalerr(void)
{
SSL_CTX *sctx = NULL, *cctx = NULL;
SSL *sssl = NULL, *cssl = NULL;
const char *msg = "Dummy";
BIO *wbio = NULL;
int ret = 0, len;
char buf[80];
unsigned char dummyrec[] = {
0x17, 0x03, 0x03, 0x00, 0x05, 'D', 'u', 'm', 'm', 'y'
};
if (!TEST_true(create_ssl_ctx_pair(NULL, TLS_method(), TLS_method(),
TLS1_VERSION, 0,
&sctx, &cctx, cert, privkey)))
goto err;
/*
* Deliberately set the cipher lists for client and server to be different
* to force a handshake failure.
*/
if (!TEST_true(SSL_CTX_set_cipher_list(sctx, "AES128-SHA"))
|| !TEST_true(SSL_CTX_set_cipher_list(cctx, "AES256-SHA"))
|| !TEST_true(SSL_CTX_set_ciphersuites(sctx,
"TLS_AES_128_GCM_SHA256"))
|| !TEST_true(SSL_CTX_set_ciphersuites(cctx,
"TLS_AES_256_GCM_SHA384"))
|| !TEST_true(create_ssl_objects(sctx, cctx, &sssl, &cssl, NULL,
NULL)))
goto err;
wbio = SSL_get_wbio(cssl);
if (!TEST_ptr(wbio)) {
printf("Unexpected NULL bio received\n");
goto err;
}
/* Connection should fail */
if (!TEST_false(create_ssl_connection(sssl, cssl, SSL_ERROR_NONE)))
goto err;
ERR_clear_error();
/* Inject a plaintext record from client to server */
if (!TEST_int_gt(BIO_write(wbio, dummyrec, sizeof(dummyrec)), 0))
goto err;
/* SSL_read()/SSL_write should fail because of a previous fatal error */
if (!TEST_int_le(len = SSL_read(sssl, buf, sizeof(buf) - 1), 0)) {
buf[len] = '\0';
TEST_error("Unexpected success reading data: %s\n", buf);
goto err;
}
if (!TEST_int_le(SSL_write(sssl, msg, strlen(msg)), 0))
goto err;
ret = 1;
err:
SSL_free(sssl);
SSL_free(cssl);
SSL_CTX_free(sctx);
SSL_CTX_free(cctx);
return ret;
}
OPT_TEST_DECLARE_USAGE("certfile privkeyfile\n")
int setup_tests(void)
{
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
if (!TEST_ptr(cert = test_get_argument(0))
|| !TEST_ptr(privkey = test_get_argument(1)))
return 0;
ADD_TEST(test_fatalerr);
return 1;
}
| 2,964 | 28.068627 | 78 | c |
openssl | openssl-master/test/filterprov.c | /*
* Copyright 2020-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
*/
/*
* A filtering provider for test purposes. We pass all calls through to the
* default provider except where we want other behaviour for a test.
*/
#include <string.h>
#include <openssl/core.h>
#include <openssl/provider.h>
#include <openssl/crypto.h>
#include "testutil.h"
#include "filterprov.h"
#define MAX_FILTERS 10
#define MAX_ALG_FILTERS 5
struct filter_prov_globals_st {
OSSL_LIB_CTX *libctx;
OSSL_PROVIDER *deflt;
struct {
int operation;
OSSL_ALGORITHM alg[MAX_ALG_FILTERS + 1];
} dispatch[MAX_FILTERS];
int num_dispatch;
int no_cache;
unsigned long int query_count;
int error;
};
static struct filter_prov_globals_st ourglobals;
static struct filter_prov_globals_st *get_globals(void)
{
/*
* Ideally we'd like to store this in the OSSL_LIB_CTX so that we can have
* more than one instance of the filter provider at a time. But for now we
* just make it simple.
*/
return &ourglobals;
}
static OSSL_FUNC_provider_gettable_params_fn filter_gettable_params;
static OSSL_FUNC_provider_get_params_fn filter_get_params;
static OSSL_FUNC_provider_query_operation_fn filter_query;
static OSSL_FUNC_provider_unquery_operation_fn filter_unquery;
static OSSL_FUNC_provider_teardown_fn filter_teardown;
static const OSSL_PARAM *filter_gettable_params(void *provctx)
{
struct filter_prov_globals_st *globs = get_globals();
return OSSL_PROVIDER_gettable_params(globs->deflt);
}
static int filter_get_params(void *provctx, OSSL_PARAM params[])
{
struct filter_prov_globals_st *globs = get_globals();
return OSSL_PROVIDER_get_params(globs->deflt, params);
}
static int filter_get_capabilities(void *provctx, const char *capability,
OSSL_CALLBACK *cb, void *arg)
{
struct filter_prov_globals_st *globs = get_globals();
return OSSL_PROVIDER_get_capabilities(globs->deflt, capability, cb, arg);
}
static const OSSL_ALGORITHM *filter_query(void *provctx,
int operation_id,
int *no_cache)
{
struct filter_prov_globals_st *globs = get_globals();
int i;
globs->query_count++;
for (i = 0; i < globs->num_dispatch; i++) {
if (globs->dispatch[i].operation == operation_id) {
*no_cache = globs->no_cache;
return globs->dispatch[i].alg;
}
}
/* No filter set, so pass it down to the chained provider */
return OSSL_PROVIDER_query_operation(globs->deflt, operation_id, no_cache);
}
static void filter_unquery(void *provctx, int operation_id,
const OSSL_ALGORITHM *algs)
{
struct filter_prov_globals_st *globs = get_globals();
int i;
if (!TEST_ulong_gt(globs->query_count, 0))
globs->error = 1;
else
globs->query_count--;
for (i = 0; i < globs->num_dispatch; i++)
if (globs->dispatch[i].alg == algs)
return;
OSSL_PROVIDER_unquery_operation(globs->deflt, operation_id, algs);
}
static void filter_teardown(void *provctx)
{
struct filter_prov_globals_st *globs = get_globals();
OSSL_PROVIDER_unload(globs->deflt);
OSSL_LIB_CTX_free(globs->libctx);
memset(globs, 0, sizeof(*globs));
}
/* Functions we provide to the core */
static const OSSL_DISPATCH filter_dispatch_table[] = {
{ OSSL_FUNC_PROVIDER_GETTABLE_PARAMS, (void (*)(void))filter_gettable_params },
{ OSSL_FUNC_PROVIDER_GET_PARAMS, (void (*)(void))filter_get_params },
{ OSSL_FUNC_PROVIDER_QUERY_OPERATION, (void (*)(void))filter_query },
{ OSSL_FUNC_PROVIDER_UNQUERY_OPERATION, (void (*)(void))filter_unquery },
{ OSSL_FUNC_PROVIDER_GET_CAPABILITIES, (void (*)(void))filter_get_capabilities },
{ OSSL_FUNC_PROVIDER_TEARDOWN, (void (*)(void))filter_teardown },
OSSL_DISPATCH_END
};
int filter_provider_init(const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in,
const OSSL_DISPATCH **out,
void **provctx)
{
memset(&ourglobals, 0, sizeof(ourglobals));
ourglobals.libctx = OSSL_LIB_CTX_new();
if (ourglobals.libctx == NULL)
goto err;
ourglobals.deflt = OSSL_PROVIDER_load(ourglobals.libctx, "default");
if (ourglobals.deflt == NULL)
goto err;
*provctx = OSSL_PROVIDER_get0_provider_ctx(ourglobals.deflt);
*out = filter_dispatch_table;
return 1;
err:
OSSL_PROVIDER_unload(ourglobals.deflt);
OSSL_LIB_CTX_free(ourglobals.libctx);
return 0;
}
/*
* Set a filter for the given operation id. The filter string is a colon
* separated list of algorithms that will be made available by this provider.
* Anything not in the filter will be suppressed. If a filter is not set for
* a given operation id then all algorithms are made available.
*/
int filter_provider_set_filter(int operation, const char *filterstr)
{
int no_cache = 0;
int algnum = 0, last = 0, ret = 0;
struct filter_prov_globals_st *globs = get_globals();
size_t namelen;
char *filterstrtmp = OPENSSL_strdup(filterstr);
char *name, *sep;
const OSSL_ALGORITHM *provalgs = OSSL_PROVIDER_query_operation(globs->deflt,
operation,
&no_cache);
const OSSL_ALGORITHM *algs;
if (filterstrtmp == NULL)
goto err;
/* Nothing to filter */
if (provalgs == NULL)
goto err;
if (globs->num_dispatch >= MAX_FILTERS)
goto err;
for (name = filterstrtmp; !last; name = (sep == NULL ? NULL : sep + 1)) {
sep = strstr(name, ":");
if (sep != NULL)
*sep = '\0';
else
last = 1;
namelen = strlen(name);
for (algs = provalgs; algs->algorithm_names != NULL; algs++) {
const char *found = strstr(algs->algorithm_names, name);
if (found == NULL)
continue;
if (found[namelen] != '\0' && found[namelen] != ':')
continue;
if (found != algs->algorithm_names && found[-1] != ':')
continue;
/* We found a match */
if (algnum >= MAX_ALG_FILTERS)
goto err;
globs->dispatch[globs->num_dispatch].alg[algnum++] = *algs;
break;
}
if (algs->algorithm_names == NULL) {
/* No match found */
goto err;
}
}
globs->dispatch[globs->num_dispatch].operation = operation;
globs->no_cache = no_cache;
globs->num_dispatch++;
ret = 1;
err:
OSSL_PROVIDER_unquery_operation(globs->deflt, operation, provalgs);
OPENSSL_free(filterstrtmp);
return ret;
}
/*
* Test if a filter provider is in a clean finishing state.
* If it is return 1, otherwise return 0.
*/
int filter_provider_check_clean_finish(void)
{
struct filter_prov_globals_st *globs = get_globals();
return TEST_ulong_eq(globs->query_count, 0) && !globs->error;
}
| 7,425 | 30.07113 | 85 | c |
openssl | openssl-master/test/filterprov.h | /*
* 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_dispatch.h>
OSSL_provider_init_fn filter_provider_init;
int filter_provider_set_filter(int operation, const char *name);
int filter_provider_check_clean_finish(void);
| 523 | 33.933333 | 74 | h |
openssl | openssl-master/test/fips_version_test.c | /*
* Copyright 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/evp.h>
#include <openssl/provider.h>
#include "testutil.h"
static OSSL_LIB_CTX *libctx = NULL;
static OSSL_PROVIDER *libprov = NULL;
typedef enum OPTION_choice {
OPT_ERR = -1,
OPT_EOF = 0,
OPT_CONFIG_FILE,
OPT_TEST_ENUM
} OPTION_CHOICE;
const OPTIONS *test_get_options(void)
{
static const OPTIONS test_options[] = {
OPT_TEST_OPTIONS_DEFAULT_USAGE,
{ "config", OPT_CONFIG_FILE, '<',
"The configuration file to use for the libctx" },
{ NULL }
};
return test_options;
}
static int test_fips_version(int n)
{
const char *version = test_get_argument(n);
if (!TEST_ptr(version))
return 0;
return TEST_int_eq(fips_provider_version_match(libctx, version), 1);
}
int setup_tests(void)
{
char *config_file = NULL;
OPTION_CHOICE o;
int n;
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_CONFIG_FILE:
config_file = opt_arg();
break;
case OPT_TEST_CASES:
break;
default:
case OPT_ERR:
return 0;
}
}
if (!test_get_libctx(&libctx, NULL, config_file, &libprov, NULL))
return 0;
n = test_get_argument_count();
if (n == 0)
return 0;
ADD_ALL_TESTS(test_fips_version, n);
return 1;
}
void cleanup_tests(void)
{
OSSL_PROVIDER_unload(libprov);
OSSL_LIB_CTX_free(libctx);
}
| 1,766 | 21.367089 | 74 | c |
openssl | openssl-master/test/gmdifftest.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 <openssl/crypto.h>
#include "testutil.h"
#define SECS_PER_DAY (24 * 60 * 60)
/*
* Time checking test code. Check times are identical for a wide range of
* offsets. This should be run on a machine with 64 bit time_t or it will
* trigger the very errors the routines fix.
*/
static int check_time(long offset)
{
struct tm tm1, tm2, o1;
int off_day, off_sec;
long toffset;
time_t t1, t2;
time(&t1);
t2 = t1 + offset;
OPENSSL_gmtime(&t2, &tm2);
OPENSSL_gmtime(&t1, &tm1);
o1 = tm1;
if (!TEST_true(OPENSSL_gmtime_adj(&tm1, 0, offset))
|| !TEST_int_eq(tm1.tm_year, tm2.tm_year)
|| !TEST_int_eq(tm1.tm_mon, tm2.tm_mon)
|| !TEST_int_eq(tm1.tm_mday, tm2.tm_mday)
|| !TEST_int_eq(tm1.tm_hour, tm2.tm_hour)
|| !TEST_int_eq(tm1.tm_min, tm2.tm_min)
|| !TEST_int_eq(tm1.tm_sec, tm2.tm_sec)
|| !TEST_true(OPENSSL_gmtime_diff(&off_day, &off_sec, &o1, &tm1)))
return 0;
toffset = (long)off_day * SECS_PER_DAY + off_sec;
if (!TEST_long_eq(offset, toffset))
return 0;
return 1;
}
static int test_gmtime(int offset)
{
return check_time(offset)
&& check_time(-offset)
&& check_time(offset * 1000L)
&& check_time(-offset * 1000L)
&& check_time(offset * 1000000L)
&& check_time(-offset * 1000000L);
}
int setup_tests(void)
{
if (sizeof(time_t) < 8)
TEST_info("Skipping; time_t is less than 64-bits");
else
ADD_ALL_TESTS_NOSUBTEST(test_gmtime, 1000);
return 1;
}
| 1,908 | 27.073529 | 74 | c |
openssl | openssl-master/test/hexstr_test.c | /*
* Copyright 2020-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 may obtain a copy of the License at
* https://www.openssl.org/source/license.html
* or in the file LICENSE in the source distribution.
*/
/*
* This program tests the use of OSSL_PARAM, currently in raw form.
*/
#include "internal/nelem.h"
#include "internal/cryptlib.h"
#include "testutil.h"
struct testdata
{
const char *in;
const unsigned char *expected;
size_t expected_len;
const char sep;
};
static const unsigned char test_1[] = { 0xAB, 0xCD, 0xEF, 0xF1 };
static const unsigned char test_2[] = { 0xAB, 0xCD, 0xEF, 0x76, 0x00 };
static struct testdata tbl_testdata[] = {
{
"AB:CD:EF:F1",
test_1, sizeof(test_1),
':',
},
{
"AB:CD:EF:76:00",
test_2, sizeof(test_2),
':',
},
{
"AB_CD_EF_F1",
test_1, sizeof(test_1),
'_',
},
{
"AB_CD_EF_76_00",
test_2, sizeof(test_2),
'_',
},
{
"ABCDEFF1",
test_1, sizeof(test_1),
'\0',
},
{
"ABCDEF7600",
test_2, sizeof(test_2),
'\0',
},
};
static int test_hexstr_sep_to_from(int test_index)
{
int ret = 0;
long len = 0;
unsigned char *buf = NULL;
char *out = NULL;
struct testdata *test = &tbl_testdata[test_index];
if (!TEST_ptr(buf = ossl_hexstr2buf_sep(test->in, &len, test->sep))
|| !TEST_mem_eq(buf, len, test->expected, test->expected_len)
|| !TEST_ptr(out = ossl_buf2hexstr_sep(buf, len, test->sep))
|| !TEST_str_eq(out, test->in))
goto err;
ret = 1;
err:
OPENSSL_free(buf);
OPENSSL_free(out);
return ret;
}
static int test_hexstr_to_from(int test_index)
{
int ret = 0;
long len = 0;
unsigned char *buf = NULL;
char *out = NULL;
struct testdata *test = &tbl_testdata[test_index];
if (test->sep != '_') {
if (!TEST_ptr(buf = OPENSSL_hexstr2buf(test->in, &len))
|| !TEST_mem_eq(buf, len, test->expected, test->expected_len)
|| !TEST_ptr(out = OPENSSL_buf2hexstr(buf, len)))
goto err;
if (test->sep == ':') {
if (!TEST_str_eq(out, test->in))
goto err;
} else if (!TEST_str_ne(out, test->in)) {
goto err;
}
} else {
if (!TEST_ptr_null(buf = OPENSSL_hexstr2buf(test->in, &len)))
goto err;
}
ret = 1;
err:
OPENSSL_free(buf);
OPENSSL_free(out);
return ret;
}
static int test_hexstr_ex_to_from(int test_index)
{
size_t len = 0;
char out[64];
unsigned char buf[64];
struct testdata *test = &tbl_testdata[test_index];
return TEST_true(OPENSSL_hexstr2buf_ex(buf, sizeof(buf), &len, test->in, ':'))
&& TEST_mem_eq(buf, len, test->expected, test->expected_len)
&& TEST_true(OPENSSL_buf2hexstr_ex(out, sizeof(out), NULL, buf, len,
':'))
&& TEST_str_eq(out, test->in);
}
int setup_tests(void)
{
ADD_ALL_TESTS(test_hexstr_sep_to_from, OSSL_NELEM(tbl_testdata));
ADD_ALL_TESTS(test_hexstr_to_from, OSSL_NELEM(tbl_testdata));
ADD_ALL_TESTS(test_hexstr_ex_to_from, 2);
return 1;
}
| 3,384 | 24.074074 | 82 | c |
openssl | openssl-master/test/hmactest.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
*/
/*
* HMAC 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 <stdlib.h>
#include "internal/nelem.h"
# include <openssl/hmac.h>
# include <openssl/sha.h>
# ifndef OPENSSL_NO_MD5
# include <openssl/md5.h>
# endif
# ifdef CHARSET_EBCDIC
# include <openssl/ebcdic.h>
# endif
#include "testutil.h"
# ifndef OPENSSL_NO_MD5
static struct test_st {
const char key[16];
int key_len;
const unsigned char data[64];
int data_len;
const char *digest;
} test[8] = {
{
"", 0, "More text test vectors to stuff up EBCDIC machines :-)", 54,
"e9139d1e6ee064ef8cf514fc7dc83e86",
},
{
"\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b",
16, "Hi There", 8,
"9294727a3638bb1c13f48ef8158bfc9d",
},
{
"Jefe", 4, "what do ya want for nothing?", 28,
"750c783e6ab0b503eaa86e310a5db738",
},
{
"\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa",
16, {
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd
}, 50, "56be34521d144c88dbb8c733f0e8b3f6",
},
{
"", 0, "My test data", 12,
"61afdecb95429ef494d61fdee15990cabf0826fc"
},
{
"", 0, "My test data", 12,
"2274b195d90ce8e03406f4b526a47e0787a88a65479938f1a5baa3ce0f079776"
},
{
"123456", 6, "My test data", 12,
"bab53058ae861a7f191abe2d0145cbb123776a6369ee3f9d79ce455667e411dd"
},
{
"12345", 5, "My test data again", 18,
"a12396ceddd2a85f4c656bc1e0aa50c78cffde3e"
}
};
# endif
static char *pt(unsigned char *md, unsigned int len);
# ifndef OPENSSL_NO_MD5
static int test_hmac_md5(int idx)
{
char *p;
# ifdef CHARSET_EBCDIC
ebcdic2ascii(test[0].data, test[0].data, test[0].data_len);
ebcdic2ascii(test[1].data, test[1].data, test[1].data_len);
ebcdic2ascii(test[2].key, test[2].key, test[2].key_len);
ebcdic2ascii(test[2].data, test[2].data, test[2].data_len);
# endif
p = pt(HMAC(EVP_md5(),
test[idx].key, test[idx].key_len,
test[idx].data, test[idx].data_len, NULL, NULL),
MD5_DIGEST_LENGTH);
return TEST_ptr(p) && TEST_str_eq(p, test[idx].digest);
}
# endif
static int test_hmac_bad(void)
{
HMAC_CTX *ctx = NULL;
int ret = 0;
ctx = HMAC_CTX_new();
if (!TEST_ptr(ctx)
|| !TEST_ptr_null(HMAC_CTX_get_md(ctx))
|| !TEST_false(HMAC_Init_ex(ctx, NULL, 0, NULL, NULL))
|| !TEST_false(HMAC_Update(ctx, test[4].data, test[4].data_len))
|| !TEST_false(HMAC_Init_ex(ctx, NULL, 0, EVP_sha1(), NULL))
|| !TEST_false(HMAC_Update(ctx, test[4].data, test[4].data_len)))
goto err;
ret = 1;
err:
HMAC_CTX_free(ctx);
return ret;
}
static int test_hmac_run(void)
{
char *p;
HMAC_CTX *ctx = NULL;
unsigned char buf[EVP_MAX_MD_SIZE];
unsigned int len;
int ret = 0;
if (!TEST_ptr(ctx = HMAC_CTX_new()))
return 0;
HMAC_CTX_reset(ctx);
if (!TEST_ptr(ctx)
|| !TEST_ptr_null(HMAC_CTX_get_md(ctx))
|| !TEST_false(HMAC_Init_ex(ctx, NULL, 0, NULL, NULL))
|| !TEST_false(HMAC_Update(ctx, test[4].data, test[4].data_len))
|| !TEST_false(HMAC_Init_ex(ctx, test[4].key, -1, EVP_sha1(), NULL)))
goto err;
if (!TEST_true(HMAC_Init_ex(ctx, test[4].key, test[4].key_len, EVP_sha1(), NULL))
|| !TEST_true(HMAC_Update(ctx, test[4].data, test[4].data_len))
|| !TEST_true(HMAC_Final(ctx, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_ptr(p) || !TEST_str_eq(p, test[4].digest))
goto err;
if (!TEST_false(HMAC_Init_ex(ctx, NULL, 0, EVP_sha256(), NULL)))
goto err;
if (!TEST_true(HMAC_Init_ex(ctx, test[5].key, test[5].key_len, EVP_sha256(), NULL))
|| !TEST_ptr_eq(HMAC_CTX_get_md(ctx), EVP_sha256())
|| !TEST_true(HMAC_Update(ctx, test[5].data, test[5].data_len))
|| !TEST_true(HMAC_Final(ctx, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_ptr(p) || !TEST_str_eq(p, test[5].digest))
goto err;
if (!TEST_true(HMAC_Init_ex(ctx, test[6].key, test[6].key_len, NULL, NULL))
|| !TEST_true(HMAC_Update(ctx, test[6].data, test[6].data_len))
|| !TEST_true(HMAC_Final(ctx, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_ptr(p) || !TEST_str_eq(p, test[6].digest))
goto err;
/* Test reusing a key */
if (!TEST_true(HMAC_Init_ex(ctx, NULL, 0, NULL, NULL))
|| !TEST_true(HMAC_Update(ctx, test[6].data, test[6].data_len))
|| !TEST_true(HMAC_Final(ctx, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_ptr(p) || !TEST_str_eq(p, test[6].digest))
goto err;
/*
* Test reusing a key where the digest is provided again but is the same as
* last time
*/
if (!TEST_true(HMAC_Init_ex(ctx, NULL, 0, EVP_sha256(), NULL))
|| !TEST_true(HMAC_Update(ctx, test[6].data, test[6].data_len))
|| !TEST_true(HMAC_Final(ctx, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_ptr(p) || !TEST_str_eq(p, test[6].digest))
goto err;
ret = 1;
err:
HMAC_CTX_free(ctx);
return ret;
}
static int test_hmac_single_shot(void)
{
char *p;
/* Test single-shot with NULL key. */
p = pt(HMAC(EVP_sha1(), NULL, 0, test[4].data, test[4].data_len,
NULL, NULL), SHA_DIGEST_LENGTH);
if (!TEST_ptr(p) || !TEST_str_eq(p, test[4].digest))
return 0;
return 1;
}
static int test_hmac_copy(void)
{
char *p;
HMAC_CTX *ctx = NULL, *ctx2 = NULL;
unsigned char buf[EVP_MAX_MD_SIZE];
unsigned int len;
int ret = 0;
ctx = HMAC_CTX_new();
ctx2 = HMAC_CTX_new();
if (!TEST_ptr(ctx) || !TEST_ptr(ctx2))
goto err;
if (!TEST_true(HMAC_Init_ex(ctx, test[7].key, test[7].key_len, EVP_sha1(), NULL))
|| !TEST_true(HMAC_Update(ctx, test[7].data, test[7].data_len))
|| !TEST_true(HMAC_CTX_copy(ctx2, ctx))
|| !TEST_true(HMAC_Final(ctx2, buf, &len)))
goto err;
p = pt(buf, len);
if (!TEST_ptr(p) || !TEST_str_eq(p, test[7].digest))
goto err;
ret = 1;
err:
HMAC_CTX_free(ctx2);
HMAC_CTX_free(ctx);
return ret;
}
static int test_hmac_copy_uninited(void)
{
const unsigned char key[24] = {0};
const unsigned char ct[166] = {0};
EVP_PKEY *pkey = NULL;
EVP_MD_CTX *ctx = NULL;
EVP_MD_CTX *ctx_tmp = NULL;
int res = 0;
if (!TEST_ptr(ctx = EVP_MD_CTX_new())
|| !TEST_ptr(pkey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL,
key, sizeof(key)))
|| !TEST_true(EVP_DigestSignInit(ctx, NULL, EVP_sha1(), NULL, pkey))
|| !TEST_ptr(ctx_tmp = EVP_MD_CTX_new())
|| !TEST_true(EVP_MD_CTX_copy(ctx_tmp, ctx)))
goto err;
EVP_MD_CTX_free(ctx);
ctx = ctx_tmp;
ctx_tmp = NULL;
if (!TEST_true(EVP_DigestSignUpdate(ctx, ct, sizeof(ct))))
goto err;
res = 1;
err:
EVP_MD_CTX_free(ctx);
EVP_MD_CTX_free(ctx_tmp);
EVP_PKEY_free(pkey);
return res;
}
# ifndef OPENSSL_NO_MD5
static char *pt(unsigned char *md, unsigned int len)
{
unsigned int i;
static char buf[80];
if (md == NULL)
return NULL;
for (i = 0; i < len; i++)
sprintf(&(buf[i * 2]), "%02x", md[i]);
return buf;
}
# endif
int setup_tests(void)
{
ADD_ALL_TESTS(test_hmac_md5, 4);
ADD_TEST(test_hmac_single_shot);
ADD_TEST(test_hmac_bad);
ADD_TEST(test_hmac_run);
ADD_TEST(test_hmac_copy);
ADD_TEST(test_hmac_copy_uninited);
return 1;
}
| 8,445 | 26.874587 | 87 | c |
openssl | openssl-master/test/http_test.c | /*
* Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright Siemens AG 2020
*
* 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/http.h>
#include <openssl/pem.h>
#include <openssl/x509v3.h>
#include <string.h>
#include "testutil.h"
static const ASN1_ITEM *x509_it = NULL;
static X509 *x509 = NULL;
#define RPATH "/path/result.crt"
typedef struct {
BIO *out;
const char *content_type;
const char *txt;
char version;
int keep_alive;
} server_args;
/*-
* Pretty trivial HTTP mock server:
* For POST, copy request headers+body from mem BIO |in| as response to |out|.
* For GET, redirect to RPATH unless already there, else use |content_type| and
* respond with |txt| if not NULL, else with |rsp| of ASN1 type |it|.
* Response hdr has HTTP version 1.|version| and |keep_alive| (unless implicit).
*/
static int mock_http_server(BIO *in, BIO *out, char version, int keep_alive,
const char *content_type, const char *txt,
ASN1_VALUE *rsp, const ASN1_ITEM *it)
{
const char *req, *path;
long count = BIO_get_mem_data(in, (unsigned char **)&req);
const char *hdr = (char *)req;
int len;
int is_get = count >= 4 && CHECK_AND_SKIP_PREFIX(hdr, "GET ");
/* first line should contain "(GET|POST) <path> HTTP/1.x" */
if (!is_get
&& !(TEST_true(count >= 5 && CHECK_AND_SKIP_PREFIX(hdr, "POST "))))
return 0;
path = hdr;
hdr = strchr(hdr, ' ');
if (hdr == NULL)
return 0;
len = strlen("HTTP/1.");
if (!TEST_strn_eq(++hdr, "HTTP/1.", len))
return 0;
hdr += len;
/* check for HTTP version 1.0 .. 1.1 */
if (!TEST_char_le('0', *hdr) || !TEST_char_le(*hdr++, '1'))
return 0;
if (!TEST_char_eq(*hdr++, '\r') || !TEST_char_eq(*hdr++, '\n'))
return 0;
count -= (hdr - req);
if (count < 0 || out == NULL)
return 0;
if (!HAS_PREFIX(path, RPATH)) {
if (!is_get)
return 0;
return BIO_printf(out, "HTTP/1.%c 301 Moved Permanently\r\n"
"Location: %s\r\n\r\n",
version, RPATH) > 0; /* same server */
}
if (BIO_printf(out, "HTTP/1.%c 200 OK\r\n", version) <= 0)
return 0;
if ((version == '0') == keep_alive) /* otherwise, default */
if (BIO_printf(out, "Connection: %s\r\n",
version == '0' ? "keep-alive" : "close") <= 0)
return 0;
if (is_get) { /* construct new header and body */
if (txt != NULL)
len = strlen(txt);
else if ((len = ASN1_item_i2d(rsp, NULL, it)) <= 0)
return 0;
if (BIO_printf(out, "Content-Type: %s\r\n"
"Content-Length: %d\r\n\r\n", content_type, len) <= 0)
return 0;
if (txt != NULL)
return BIO_puts(out, txt);
return ASN1_item_i2d_bio(it, out, rsp);
} else {
if (CHECK_AND_SKIP_PREFIX(hdr, "Connection: ")) {
/* skip req Connection header */
hdr = strstr(hdr, "\r\n");
if (hdr == NULL)
return 0;
hdr += 2;
}
/* echo remaining request header and body */
return BIO_write(out, hdr, count) == count;
}
}
static long http_bio_cb_ex(BIO *bio, int oper, const char *argp, size_t len,
int cmd, long argl, int ret, size_t *processed)
{
server_args *args = (server_args *)BIO_get_callback_arg(bio);
if (oper == (BIO_CB_CTRL | BIO_CB_RETURN) && cmd == BIO_CTRL_FLUSH)
ret = mock_http_server(bio, args->out, args->version, args->keep_alive,
args->content_type, args->txt,
(ASN1_VALUE *)x509, x509_it);
return ret;
}
#define text1 "test\n"
#define text2 "more\n"
#define REAL_SERVER_URL "http://httpbin.org/"
#define DOCTYPE_HTML "<!DOCTYPE html>\n"
static int test_http_method(int do_get, int do_txt)
{
BIO *wbio = BIO_new(BIO_s_mem());
BIO *rbio = BIO_new(BIO_s_mem());
server_args mock_args = { NULL, NULL, NULL, '0', 0 };
BIO *req, *rsp;
STACK_OF(CONF_VALUE) *headers = NULL;
const char *content_type;
int res = 0;
int real_server = do_txt && 0; /* remove "&& 0" for using real server */
if (do_txt) {
content_type = "text/plain";
req = BIO_new(BIO_s_mem());
if (req == NULL
|| BIO_puts(req, text1) != sizeof(text1) - 1
|| BIO_puts(req, text2) != sizeof(text2) - 1) {
BIO_free(req);
req = NULL;
}
mock_args.txt = text1;
} else {
content_type = "application/x-x509-ca-cert";
req = ASN1_item_i2d_mem_bio(x509_it, (ASN1_VALUE *)x509);
mock_args.txt = NULL;
}
if (wbio == NULL || rbio == NULL || req == NULL)
goto err;
mock_args.out = rbio;
mock_args.content_type = content_type;
BIO_set_callback_ex(wbio, http_bio_cb_ex);
BIO_set_callback_arg(wbio, (char *)&mock_args);
rsp = do_get ?
OSSL_HTTP_get(real_server ? REAL_SERVER_URL :
do_txt ? RPATH : "/will-be-redirected",
NULL /* proxy */, NULL /* no_proxy */,
real_server ? NULL : wbio,
real_server ? NULL : rbio,
NULL /* bio_update_fn */, NULL /* arg */,
0 /* buf_size */, headers,
real_server ? "text/html; charset=utf-8": content_type,
!do_txt /* expect_asn1 */,
OSSL_HTTP_DEFAULT_MAX_RESP_LEN, 0 /* timeout */)
: OSSL_HTTP_transfer(NULL, NULL /* host */, NULL /* port */, RPATH,
0 /* use_ssl */,NULL /* proxy */, NULL /* no_pr */,
wbio, rbio, NULL /* bio_fn */, NULL /* arg */,
0 /* buf_size */, headers, content_type,
req, content_type, !do_txt /* expect_asn1 */,
OSSL_HTTP_DEFAULT_MAX_RESP_LEN, 0 /* timeout */,
0 /* keep_alive */);
if (rsp != NULL) {
if (do_get && real_server) {
char rtext[sizeof(DOCTYPE_HTML)];
res = TEST_int_eq(BIO_gets(rsp, rtext, sizeof(rtext)),
sizeof(DOCTYPE_HTML) - 1)
&& TEST_str_eq(rtext, DOCTYPE_HTML);
} else if (do_txt) {
char rtext[sizeof(text1) + 1 /* more space than needed */];
res = TEST_int_eq(BIO_gets(rsp, rtext, sizeof(rtext)),
sizeof(text1) - 1)
&& TEST_str_eq(rtext, text1);
} else {
X509 *rcert = d2i_X509_bio(rsp, NULL);
res = TEST_ptr(rcert) && TEST_int_eq(X509_cmp(x509, rcert), 0);
X509_free(rcert);
}
BIO_free(rsp);
}
err:
BIO_free(req);
BIO_free(wbio);
BIO_free(rbio);
sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
return res;
}
static int test_http_keep_alive(char version, int keep_alive, int kept_alive)
{
BIO *wbio = BIO_new(BIO_s_mem());
BIO *rbio = BIO_new(BIO_s_mem());
BIO *rsp;
const char *const content_type = "application/x-x509-ca-cert";
server_args mock_args = { NULL, NULL, NULL, '0', 0 };
OSSL_HTTP_REQ_CTX *rctx = NULL;
int i, res = 0;
if (wbio == NULL || rbio == NULL)
goto err;
mock_args.out = rbio;
mock_args.content_type = content_type;
mock_args.version = version;
mock_args.keep_alive = kept_alive;
BIO_set_callback_ex(wbio, http_bio_cb_ex);
BIO_set_callback_arg(wbio, (char *)&mock_args);
for (res = 1, i = 1; res && i <= 2; i++) {
rsp = OSSL_HTTP_transfer(&rctx, NULL /* server */, NULL /* port */,
RPATH, 0 /* use_ssl */,
NULL /* proxy */, NULL /* no_proxy */,
wbio, rbio, NULL /* bio_update_fn */, NULL,
0 /* buf_size */, NULL /* headers */,
NULL /* content_type */, NULL /* req => GET */,
content_type, 0 /* ASN.1 not expected */,
0 /* max_resp_len */, 0 /* timeout */,
keep_alive);
if (keep_alive == 2 && kept_alive == 0)
res = res && TEST_ptr_null(rsp)
&& TEST_int_eq(OSSL_HTTP_is_alive(rctx), 0);
else
res = res && TEST_ptr(rsp)
&& TEST_int_eq(OSSL_HTTP_is_alive(rctx), keep_alive > 0);
BIO_free(rsp);
(void)BIO_reset(rbio); /* discard response contents */
keep_alive = 0;
}
OSSL_HTTP_close(rctx, res);
err:
BIO_free(wbio);
BIO_free(rbio);
return res;
}
static int test_http_url_ok(const char *url, int exp_ssl, const char *exp_host,
const char *exp_port, const char *exp_path)
{
char *user, *host, *port, *path, *query, *frag;
int exp_num, num, ssl;
int res;
if (!TEST_int_eq(sscanf(exp_port, "%d", &exp_num), 1))
return 0;
res = TEST_true(OSSL_HTTP_parse_url(url, &ssl, &user, &host, &port, &num,
&path, &query, &frag))
&& TEST_str_eq(host, exp_host)
&& TEST_str_eq(port, exp_port)
&& TEST_int_eq(num, exp_num)
&& TEST_str_eq(path, exp_path)
&& TEST_int_eq(ssl, exp_ssl);
if (res && *user != '\0')
res = TEST_str_eq(user, "user:pass");
if (res && *frag != '\0')
res = TEST_str_eq(frag, "fr");
if (res && *query != '\0')
res = TEST_str_eq(query, "q");
OPENSSL_free(user);
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(path);
OPENSSL_free(query);
OPENSSL_free(frag);
return res;
}
static int test_http_url_path_query_ok(const char *url, const char *exp_path_qu)
{
char *host, *path;
int res;
res = TEST_true(OSSL_HTTP_parse_url(url, NULL, NULL, &host, NULL, NULL,
&path, NULL, NULL))
&& TEST_str_eq(host, "host")
&& TEST_str_eq(path, exp_path_qu);
OPENSSL_free(host);
OPENSSL_free(path);
return res;
}
static int test_http_url_dns(void)
{
return test_http_url_ok("host:65535/path", 0, "host", "65535", "/path");
}
static int test_http_url_path_query(void)
{
return test_http_url_path_query_ok("http://usr@host:1/p?q=x#frag", "/p?q=x")
&& test_http_url_path_query_ok("http://host?query#frag", "/?query")
&& test_http_url_path_query_ok("http://host:9999#frag", "/");
}
static int test_http_url_userinfo_query_fragment(void)
{
return test_http_url_ok("user:pass@host/p?q#fr", 0, "host", "80", "/p");
}
static int test_http_url_ipv4(void)
{
return test_http_url_ok("https://1.2.3.4/p/q", 1, "1.2.3.4", "443", "/p/q");
}
static int test_http_url_ipv6(void)
{
return test_http_url_ok("http://[FF01::101]:6", 0, "[FF01::101]", "6", "/");
}
static int test_http_url_invalid(const char *url)
{
char *host = "1", *port = "1", *path = "1";
int num = 1, ssl = 1;
int res;
res = TEST_false(OSSL_HTTP_parse_url(url, &ssl, NULL, &host, &port, &num,
&path, NULL, NULL))
&& TEST_ptr_null(host)
&& TEST_ptr_null(port)
&& TEST_ptr_null(path);
if (!res) {
OPENSSL_free(host);
OPENSSL_free(port);
OPENSSL_free(path);
}
return res;
}
static int test_http_url_invalid_prefix(void)
{
return test_http_url_invalid("htttps://1.2.3.4:65535/pkix");
}
static int test_http_url_invalid_port(void)
{
return test_http_url_invalid("https://1.2.3.4:65536/pkix");
}
static int test_http_url_invalid_path(void)
{
return test_http_url_invalid("https://[FF01::101]pkix");
}
static int test_http_get_txt(void)
{
return test_http_method(1 /* GET */, 1);
}
static int test_http_post_txt(void)
{
return test_http_method(0 /* POST */, 1);
}
static int test_http_get_x509(void)
{
return test_http_method(1 /* GET */, 0); /* includes redirection */
}
static int test_http_post_x509(void)
{
return test_http_method(0 /* POST */, 0);
}
static int test_http_keep_alive_0_no_no(void)
{
return test_http_keep_alive('0', 0, 0);
}
static int test_http_keep_alive_1_no_no(void)
{
return test_http_keep_alive('1', 0, 0);
}
static int test_http_keep_alive_0_prefer_yes(void)
{
return test_http_keep_alive('0', 1, 1);
}
static int test_http_keep_alive_1_prefer_yes(void)
{
return test_http_keep_alive('1', 1, 1);
}
static int test_http_keep_alive_0_require_yes(void)
{
return test_http_keep_alive('0', 2, 1);
}
static int test_http_keep_alive_1_require_yes(void)
{
return test_http_keep_alive('1', 2, 1);
}
static int test_http_keep_alive_0_require_no(void)
{
return test_http_keep_alive('0', 2, 0);
}
static int test_http_keep_alive_1_require_no(void)
{
return test_http_keep_alive('1', 2, 0);
}
void cleanup_tests(void)
{
X509_free(x509);
}
OPT_TEST_DECLARE_USAGE("cert.pem\n")
int setup_tests(void)
{
if (!test_skip_common_options())
return 0;
x509_it = ASN1_ITEM_rptr(X509);
if (!TEST_ptr((x509 = load_cert_pem(test_get_argument(0), NULL))))
return 0;
ADD_TEST(test_http_url_dns);
ADD_TEST(test_http_url_path_query);
ADD_TEST(test_http_url_userinfo_query_fragment);
ADD_TEST(test_http_url_ipv4);
ADD_TEST(test_http_url_ipv6);
ADD_TEST(test_http_url_invalid_prefix);
ADD_TEST(test_http_url_invalid_port);
ADD_TEST(test_http_url_invalid_path);
ADD_TEST(test_http_get_txt);
ADD_TEST(test_http_post_txt);
ADD_TEST(test_http_get_x509);
ADD_TEST(test_http_post_x509);
ADD_TEST(test_http_keep_alive_0_no_no);
ADD_TEST(test_http_keep_alive_1_no_no);
ADD_TEST(test_http_keep_alive_0_prefer_yes);
ADD_TEST(test_http_keep_alive_1_prefer_yes);
ADD_TEST(test_http_keep_alive_0_require_yes);
ADD_TEST(test_http_keep_alive_1_require_yes);
ADD_TEST(test_http_keep_alive_0_require_no);
ADD_TEST(test_http_keep_alive_1_require_no);
return 1;
}
| 14,493 | 30.785088 | 80 | c |
openssl | openssl-master/test/ideatest.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
*/
/*
* IDEA low level APIs are deprecated for public use, but still ok for internal
* use where we're using them to implement the higher level EVP interface, as is
* the case here.
*/
#include "internal/deprecated.h"
#include <string.h>
#include "internal/nelem.h"
#include "testutil.h"
#ifndef OPENSSL_NO_IDEA
# include <openssl/idea.h>
static const unsigned char k[16] = {
0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04,
0x00, 0x05, 0x00, 0x06, 0x00, 0x07, 0x00, 0x08
};
static const unsigned char in[8] = { 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03 };
static const unsigned char c[8] = { 0x11, 0xFB, 0xED, 0x2B, 0x01, 0x98, 0x6D, 0xE5 };
static unsigned char out[80];
static const unsigned char text[] = "Hello to all people out there";
static const unsigned char cfb_key[16] = {
0xe1, 0xf0, 0xc3, 0xd2, 0xa5, 0xb4, 0x87, 0x96,
0x69, 0x78, 0x4b, 0x5a, 0x2d, 0x3c, 0x0f, 0x1e,
};
static const unsigned char cfb_iv[80] =
{ 0x34, 0x12, 0x78, 0x56, 0xab, 0x90, 0xef, 0xcd };
static unsigned char cfb_buf1[40], cfb_buf2[40], cfb_tmp[8];
# define CFB_TEST_SIZE 24
static const unsigned char plain[CFB_TEST_SIZE] = {
0x4e, 0x6f, 0x77, 0x20, 0x69, 0x73,
0x20, 0x74, 0x68, 0x65, 0x20, 0x74,
0x69, 0x6d, 0x65, 0x20, 0x66, 0x6f,
0x72, 0x20, 0x61, 0x6c, 0x6c, 0x20
};
static const unsigned char cfb_cipher64[CFB_TEST_SIZE] = {
0x59, 0xD8, 0xE2, 0x65, 0x00, 0x58, 0x6C, 0x3F,
0x2C, 0x17, 0x25, 0xD0, 0x1A, 0x38, 0xB7, 0x2A,
0x39, 0x61, 0x37, 0xDC, 0x79, 0xFB, 0x9F, 0x45
/*- 0xF9,0x78,0x32,0xB5,0x42,0x1A,0x6B,0x38,
0x9A,0x44,0xD6,0x04,0x19,0x43,0xC4,0xD9,
0x3D,0x1E,0xAE,0x47,0xFC,0xCF,0x29,0x0B,*/
};
static int test_idea_ecb(void)
{
IDEA_KEY_SCHEDULE key, dkey;
IDEA_set_encrypt_key(k, &key);
IDEA_ecb_encrypt(in, out, &key);
if (!TEST_mem_eq(out, IDEA_BLOCK, c, sizeof(c)))
return 0;
IDEA_set_decrypt_key(&key, &dkey);
IDEA_ecb_encrypt(c, out, &dkey);
return TEST_mem_eq(out, IDEA_BLOCK, in, sizeof(in));
}
static int test_idea_cbc(void)
{
IDEA_KEY_SCHEDULE key, dkey;
unsigned char iv[IDEA_BLOCK];
const size_t text_len = sizeof(text);
IDEA_set_encrypt_key(k, &key);
IDEA_set_decrypt_key(&key, &dkey);
memcpy(iv, k, sizeof(iv));
IDEA_cbc_encrypt(text, out, text_len, &key, iv, 1);
memcpy(iv, k, sizeof(iv));
IDEA_cbc_encrypt(out, out, IDEA_BLOCK, &dkey, iv, 0);
IDEA_cbc_encrypt(&out[8], &out[8], text_len - 8, &dkey, iv, 0);
return TEST_mem_eq(text, text_len, out, text_len);
}
static int test_idea_cfb64(void)
{
IDEA_KEY_SCHEDULE eks, dks;
int n;
IDEA_set_encrypt_key(cfb_key, &eks);
IDEA_set_decrypt_key(&eks, &dks);
memcpy(cfb_tmp, cfb_iv, sizeof(cfb_tmp));
n = 0;
IDEA_cfb64_encrypt(plain, cfb_buf1, (long)12, &eks,
cfb_tmp, &n, IDEA_ENCRYPT);
IDEA_cfb64_encrypt(&plain[12], &cfb_buf1[12],
(long)CFB_TEST_SIZE - 12, &eks,
cfb_tmp, &n, IDEA_ENCRYPT);
if (!TEST_mem_eq(cfb_cipher64, CFB_TEST_SIZE, cfb_buf1, CFB_TEST_SIZE))
return 0;
memcpy(cfb_tmp, cfb_iv, sizeof(cfb_tmp));
n = 0;
IDEA_cfb64_encrypt(cfb_buf1, cfb_buf2, (long)13, &eks,
cfb_tmp, &n, IDEA_DECRYPT);
IDEA_cfb64_encrypt(&cfb_buf1[13], &cfb_buf2[13],
(long)CFB_TEST_SIZE - 13, &eks,
cfb_tmp, &n, IDEA_DECRYPT);
return TEST_mem_eq(plain, CFB_TEST_SIZE, cfb_buf2, CFB_TEST_SIZE);
}
#endif
int setup_tests(void)
{
#ifndef OPENSSL_NO_IDEA
ADD_TEST(test_idea_ecb);
ADD_TEST(test_idea_cbc);
ADD_TEST(test_idea_cfb64);
#endif
return 1;
}
| 4,009 | 30.574803 | 87 | c |
openssl | openssl-master/test/igetest.c | /*
* Copyright 2006-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
*/
/* The AES_ige_* functions are deprecated, so we suppress warnings about them */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <openssl/crypto.h>
#include <openssl/aes.h>
#include <openssl/rand.h>
#include <stdio.h>
#include <string.h>
#include "internal/nelem.h"
#include "testutil.h"
#ifndef OPENSSL_NO_DEPRECATED_3_0
# define TEST_SIZE 128
# define BIG_TEST_SIZE 10240
# if BIG_TEST_SIZE < TEST_SIZE
# error BIG_TEST_SIZE is smaller than TEST_SIZE
# endif
static unsigned char rkey[16];
static unsigned char rkey2[16];
static unsigned char plaintext[BIG_TEST_SIZE];
static unsigned char saved_iv[AES_BLOCK_SIZE * 4];
# define MAX_VECTOR_SIZE 64
struct ige_test {
const unsigned char key[16];
const unsigned char iv[32];
const unsigned char in[MAX_VECTOR_SIZE];
const unsigned char out[MAX_VECTOR_SIZE];
const size_t length;
const int encrypt;
};
static struct ige_test const ige_test_vectors[] = {
{{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, /* key */
{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f}, /* iv */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* in */
{0x1a, 0x85, 0x19, 0xa6, 0x55, 0x7b, 0xe6, 0x52,
0xe9, 0xda, 0x8e, 0x43, 0xda, 0x4e, 0xf4, 0x45,
0x3c, 0xf4, 0x56, 0xb4, 0xca, 0x48, 0x8a, 0xa3,
0x83, 0xc7, 0x9c, 0x98, 0xb3, 0x47, 0x97, 0xcb}, /* out */
32, AES_ENCRYPT}, /* test vector 0 */
{{0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20,
0x61, 0x6e, 0x20, 0x69, 0x6d, 0x70, 0x6c, 0x65}, /* key */
{0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f,
0x6e, 0x20, 0x6f, 0x66, 0x20, 0x49, 0x47, 0x45,
0x20, 0x6d, 0x6f, 0x64, 0x65, 0x20, 0x66, 0x6f,
0x72, 0x20, 0x4f, 0x70, 0x65, 0x6e, 0x53, 0x53}, /* iv */
{0x4c, 0x2e, 0x20, 0x4c, 0x65, 0x74, 0x27, 0x73,
0x20, 0x68, 0x6f, 0x70, 0x65, 0x20, 0x42, 0x65,
0x6e, 0x20, 0x67, 0x6f, 0x74, 0x20, 0x69, 0x74,
0x20, 0x72, 0x69, 0x67, 0x68, 0x74, 0x21, 0x0a}, /* in */
{0x99, 0x70, 0x64, 0x87, 0xa1, 0xcd, 0xe6, 0x13,
0xbc, 0x6d, 0xe0, 0xb6, 0xf2, 0x4b, 0x1c, 0x7a,
0xa4, 0x48, 0xc8, 0xb9, 0xc3, 0x40, 0x3e, 0x34,
0x67, 0xa8, 0xca, 0xd8, 0x93, 0x40, 0xf5, 0x3b}, /* out */
32, AES_DECRYPT}, /* test vector 1 */
};
struct bi_ige_test {
const unsigned char key1[32];
const unsigned char key2[32];
const unsigned char iv[64];
const unsigned char in[MAX_VECTOR_SIZE];
const unsigned char out[MAX_VECTOR_SIZE];
const size_t keysize;
const size_t length;
const int encrypt;
};
static struct bi_ige_test const bi_ige_test_vectors[] = {
{{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, /* key1 */
{0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f}, /* key2 */
{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f}, /* iv */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* in */
{0x14, 0x40, 0x6f, 0xae, 0xa2, 0x79, 0xf2, 0x56,
0x1f, 0x86, 0xeb, 0x3b, 0x7d, 0xff, 0x53, 0xdc,
0x4e, 0x27, 0x0c, 0x03, 0xde, 0x7c, 0xe5, 0x16,
0x6a, 0x9c, 0x20, 0x33, 0x9d, 0x33, 0xfe, 0x12}, /* out */
16, 32, AES_ENCRYPT}, /* test vector 0 */
{{0x58, 0x0a, 0x06, 0xe9, 0x97, 0x07, 0x59, 0x5c,
0x9e, 0x19, 0xd2, 0xa7, 0xbb, 0x40, 0x2b, 0x7a,
0xc7, 0xd8, 0x11, 0x9e, 0x4c, 0x51, 0x35, 0x75,
0x64, 0x28, 0x0f, 0x23, 0xad, 0x74, 0xac, 0x37}, /* key1 */
{0xd1, 0x80, 0xa0, 0x31, 0x47, 0xa3, 0x11, 0x13,
0x86, 0x26, 0x9e, 0x6d, 0xff, 0xaf, 0x72, 0x74,
0x5b, 0xa2, 0x35, 0x81, 0xd2, 0xa6, 0x3d, 0x21,
0x67, 0x7b, 0x58, 0xa8, 0x18, 0xf9, 0x72, 0xe4}, /* key2 */
{0x80, 0x3d, 0xbd, 0x4c, 0xe6, 0x7b, 0x06, 0xa9,
0x53, 0x35, 0xd5, 0x7e, 0x71, 0xc1, 0x70, 0x70,
0x74, 0x9a, 0x00, 0x28, 0x0c, 0xbf, 0x6c, 0x42,
0x9b, 0xa4, 0xdd, 0x65, 0x11, 0x77, 0x7c, 0x67,
0xfe, 0x76, 0x0a, 0xf0, 0xd5, 0xc6, 0x6e, 0x6a,
0xe7, 0x5e, 0x4c, 0xf2, 0x7e, 0x9e, 0xf9, 0x20,
0x0e, 0x54, 0x6f, 0x2d, 0x8a, 0x8d, 0x7e, 0xbd,
0x48, 0x79, 0x37, 0x99, 0xff, 0x27, 0x93, 0xa3}, /* iv */
{0xf1, 0x54, 0x3d, 0xca, 0xfe, 0xb5, 0xef, 0x1c,
0x4f, 0xa6, 0x43, 0xf6, 0xe6, 0x48, 0x57, 0xf0,
0xee, 0x15, 0x7f, 0xe3, 0xe7, 0x2f, 0xd0, 0x2f,
0x11, 0x95, 0x7a, 0x17, 0x00, 0xab, 0xa7, 0x0b,
0xbe, 0x44, 0x09, 0x9c, 0xcd, 0xac, 0xa8, 0x52,
0xa1, 0x8e, 0x7b, 0x75, 0xbc, 0xa4, 0x92, 0x5a,
0xab, 0x46, 0xd3, 0x3a, 0xa0, 0xd5, 0x35, 0x1c,
0x55, 0xa4, 0xb3, 0xa8, 0x40, 0x81, 0xa5, 0x0b}, /* in */
{0x42, 0xe5, 0x28, 0x30, 0x31, 0xc2, 0xa0, 0x23,
0x68, 0x49, 0x4e, 0xb3, 0x24, 0x59, 0x92, 0x79,
0xc1, 0xa5, 0xcc, 0xe6, 0x76, 0x53, 0xb1, 0xcf,
0x20, 0x86, 0x23, 0xe8, 0x72, 0x55, 0x99, 0x92,
0x0d, 0x16, 0x1c, 0x5a, 0x2f, 0xce, 0xcb, 0x51,
0xe2, 0x67, 0xfa, 0x10, 0xec, 0xcd, 0x3d, 0x67,
0xa5, 0xe6, 0xf7, 0x31, 0x26, 0xb0, 0x0d, 0x76,
0x5e, 0x28, 0xdc, 0x7f, 0x01, 0xc5, 0xa5, 0x4c}, /* out */
32, 64, AES_ENCRYPT}, /* test vector 1 */
};
static int test_ige_vectors(int n)
{
const struct ige_test *const v = &ige_test_vectors[n];
AES_KEY key;
unsigned char buf[MAX_VECTOR_SIZE];
unsigned char iv[AES_BLOCK_SIZE * 2];
int testresult = 1;
if (!TEST_int_le(v->length, MAX_VECTOR_SIZE))
return 0;
if (v->encrypt == AES_ENCRYPT)
AES_set_encrypt_key(v->key, 8 * sizeof(v->key), &key);
else
AES_set_decrypt_key(v->key, 8 * sizeof(v->key), &key);
memcpy(iv, v->iv, sizeof(iv));
AES_ige_encrypt(v->in, buf, v->length, &key, iv, v->encrypt);
if (!TEST_mem_eq(v->out, v->length, buf, v->length)) {
TEST_info("IGE test vector %d failed", n);
test_output_memory("key", v->key, sizeof(v->key));
test_output_memory("iv", v->iv, sizeof(v->iv));
test_output_memory("in", v->in, v->length);
testresult = 0;
}
/* try with in == out */
memcpy(iv, v->iv, sizeof(iv));
memcpy(buf, v->in, v->length);
AES_ige_encrypt(buf, buf, v->length, &key, iv, v->encrypt);
if (!TEST_mem_eq(v->out, v->length, buf, v->length)) {
TEST_info("IGE test vector %d failed (with in == out)", n);
test_output_memory("key", v->key, sizeof(v->key));
test_output_memory("iv", v->iv, sizeof(v->iv));
test_output_memory("in", v->in, v->length);
testresult = 0;
}
return testresult;
}
static int test_bi_ige_vectors(int n)
{
const struct bi_ige_test *const v = &bi_ige_test_vectors[n];
AES_KEY key1;
AES_KEY key2;
unsigned char buf[MAX_VECTOR_SIZE];
if (!TEST_int_le(v->length, MAX_VECTOR_SIZE))
return 0;
if (v->encrypt == AES_ENCRYPT) {
AES_set_encrypt_key(v->key1, 8 * v->keysize, &key1);
AES_set_encrypt_key(v->key2, 8 * v->keysize, &key2);
} else {
AES_set_decrypt_key(v->key1, 8 * v->keysize, &key1);
AES_set_decrypt_key(v->key2, 8 * v->keysize, &key2);
}
AES_bi_ige_encrypt(v->in, buf, v->length, &key1, &key2, v->iv,
v->encrypt);
if (!TEST_mem_eq(v->out, v->length, buf, v->length)) {
test_output_memory("key 1", v->key1, sizeof(v->key1));
test_output_memory("key 2", v->key2, sizeof(v->key2));
test_output_memory("iv", v->iv, sizeof(v->iv));
test_output_memory("in", v->in, v->length);
return 0;
}
return 1;
}
static int test_ige_enc_dec(void)
{
AES_KEY key;
unsigned char iv[AES_BLOCK_SIZE * 4];
unsigned char ciphertext[BIG_TEST_SIZE];
unsigned char checktext[BIG_TEST_SIZE];
memcpy(iv, saved_iv, sizeof(iv));
AES_set_encrypt_key(rkey, 8 * sizeof(rkey), &key);
AES_ige_encrypt(plaintext, ciphertext, TEST_SIZE, &key, iv, AES_ENCRYPT);
AES_set_decrypt_key(rkey, 8 * sizeof(rkey), &key);
memcpy(iv, saved_iv, sizeof(iv));
AES_ige_encrypt(ciphertext, checktext, TEST_SIZE, &key, iv, AES_DECRYPT);
return TEST_mem_eq(checktext, TEST_SIZE, plaintext, TEST_SIZE);
}
static int test_ige_enc_chaining(void)
{
AES_KEY key;
unsigned char iv[AES_BLOCK_SIZE * 4];
unsigned char ciphertext[BIG_TEST_SIZE];
unsigned char checktext[BIG_TEST_SIZE];
AES_set_encrypt_key(rkey, 8 * sizeof(rkey), &key);
memcpy(iv, saved_iv, sizeof(iv));
AES_ige_encrypt(plaintext, ciphertext, TEST_SIZE / 2, &key, iv,
AES_ENCRYPT);
AES_ige_encrypt(plaintext + TEST_SIZE / 2,
ciphertext + TEST_SIZE / 2, TEST_SIZE / 2,
&key, iv, AES_ENCRYPT);
AES_set_decrypt_key(rkey, 8 * sizeof(rkey), &key);
memcpy(iv, saved_iv, sizeof(iv));
AES_ige_encrypt(ciphertext, checktext, TEST_SIZE, &key, iv, AES_DECRYPT);
return TEST_mem_eq(checktext, TEST_SIZE, plaintext, TEST_SIZE);
}
static int test_ige_dec_chaining(void)
{
AES_KEY key;
unsigned char iv[AES_BLOCK_SIZE * 4];
unsigned char ciphertext[BIG_TEST_SIZE];
unsigned char checktext[BIG_TEST_SIZE];
AES_set_encrypt_key(rkey, 8 * sizeof(rkey), &key);
memcpy(iv, saved_iv, sizeof(iv));
AES_ige_encrypt(plaintext, ciphertext, TEST_SIZE / 2, &key, iv,
AES_ENCRYPT);
AES_ige_encrypt(plaintext + TEST_SIZE / 2,
ciphertext + TEST_SIZE / 2, TEST_SIZE / 2,
&key, iv, AES_ENCRYPT);
AES_set_decrypt_key(rkey, 8 * sizeof(rkey), &key);
memcpy(iv, saved_iv, sizeof(iv));
AES_ige_encrypt(ciphertext, checktext, TEST_SIZE / 2, &key, iv,
AES_DECRYPT);
AES_ige_encrypt(ciphertext + TEST_SIZE / 2,
checktext + TEST_SIZE / 2, TEST_SIZE / 2, &key, iv,
AES_DECRYPT);
return TEST_mem_eq(checktext, TEST_SIZE, plaintext, TEST_SIZE);
}
static int test_ige_garble_forwards(void)
{
AES_KEY key;
unsigned char iv[AES_BLOCK_SIZE * 4];
unsigned char ciphertext[BIG_TEST_SIZE];
unsigned char checktext[BIG_TEST_SIZE];
unsigned int n;
int testresult = 1;
const size_t ctsize = sizeof(checktext);
size_t matches;
AES_set_encrypt_key(rkey, 8 * sizeof(rkey), &key);
memcpy(iv, saved_iv, sizeof(iv));
AES_ige_encrypt(plaintext, ciphertext, sizeof(plaintext), &key, iv,
AES_ENCRYPT);
/* corrupt halfway through */
++ciphertext[sizeof(ciphertext) / 2];
AES_set_decrypt_key(rkey, 8 * sizeof(rkey), &key);
memcpy(iv, saved_iv, sizeof(iv));
AES_ige_encrypt(ciphertext, checktext, sizeof(checktext), &key, iv,
AES_DECRYPT);
matches = 0;
for (n = 0; n < sizeof(checktext); ++n)
if (checktext[n] == plaintext[n])
++matches;
/* Fail if there is more than 51% matching bytes */
if (!TEST_size_t_le(matches, ctsize / 2 + ctsize / 100))
testresult = 0;
/* Fail if the garble goes backwards */
if (!TEST_size_t_gt(matches, ctsize / 2))
testresult = 0;
return testresult;
}
static int test_bi_ige_enc_dec(void)
{
AES_KEY key, key2;
unsigned char iv[AES_BLOCK_SIZE * 4];
unsigned char ciphertext[BIG_TEST_SIZE];
unsigned char checktext[BIG_TEST_SIZE];
memcpy(iv, saved_iv, sizeof(iv));
AES_set_encrypt_key(rkey, 8 * sizeof(rkey), &key);
AES_set_encrypt_key(rkey2, 8 * sizeof(rkey2), &key2);
AES_bi_ige_encrypt(plaintext, ciphertext, TEST_SIZE, &key, &key2, iv,
AES_ENCRYPT);
AES_set_decrypt_key(rkey, 8 * sizeof(rkey), &key);
AES_set_decrypt_key(rkey2, 8 * sizeof(rkey2), &key2);
AES_bi_ige_encrypt(ciphertext, checktext, TEST_SIZE, &key, &key2, iv,
AES_DECRYPT);
return TEST_mem_eq(checktext, TEST_SIZE, plaintext, TEST_SIZE);
}
static int test_bi_ige_garble1(void)
{
AES_KEY key, key2;
unsigned char iv[AES_BLOCK_SIZE * 4];
unsigned char ciphertext[BIG_TEST_SIZE];
unsigned char checktext[BIG_TEST_SIZE];
unsigned int n;
size_t matches;
memcpy(iv, saved_iv, sizeof(iv));
AES_set_encrypt_key(rkey, 8 * sizeof(rkey), &key);
AES_set_encrypt_key(rkey2, 8 * sizeof(rkey2), &key2);
AES_ige_encrypt(plaintext, ciphertext, sizeof(plaintext), &key, iv,
AES_ENCRYPT);
/* corrupt halfway through */
++ciphertext[sizeof(ciphertext) / 2];
AES_set_decrypt_key(rkey, 8 * sizeof(rkey), &key);
AES_set_decrypt_key(rkey2, 8 * sizeof(rkey2), &key2);
AES_ige_encrypt(ciphertext, checktext, sizeof(checktext), &key, iv,
AES_DECRYPT);
matches = 0;
for (n = 0; n < sizeof(checktext); ++n)
if (checktext[n] == plaintext[n])
++matches;
/* Fail if there is more than 1% matching bytes */
return TEST_size_t_le(matches, sizeof(checktext) / 100);
}
static int test_bi_ige_garble2(void)
{
AES_KEY key, key2;
unsigned char iv[AES_BLOCK_SIZE * 4];
unsigned char ciphertext[BIG_TEST_SIZE];
unsigned char checktext[BIG_TEST_SIZE];
unsigned int n;
size_t matches;
memcpy(iv, saved_iv, sizeof(iv));
AES_set_encrypt_key(rkey, 8 * sizeof(rkey), &key);
AES_set_encrypt_key(rkey2, 8 * sizeof(rkey2), &key2);
AES_ige_encrypt(plaintext, ciphertext, sizeof(plaintext), &key, iv,
AES_ENCRYPT);
/* corrupt right at the end */
++ciphertext[sizeof(ciphertext) - 1];
AES_set_decrypt_key(rkey, 8 * sizeof(rkey), &key);
AES_set_decrypt_key(rkey2, 8 * sizeof(rkey2), &key2);
AES_ige_encrypt(ciphertext, checktext, sizeof(checktext), &key, iv,
AES_DECRYPT);
matches = 0;
for (n = 0; n < sizeof(checktext); ++n)
if (checktext[n] == plaintext[n])
++matches;
/* Fail if there is more than 1% matching bytes */
return TEST_size_t_le(matches, sizeof(checktext) / 100);
}
static int test_bi_ige_garble3(void)
{
AES_KEY key, key2;
unsigned char iv[AES_BLOCK_SIZE * 4];
unsigned char ciphertext[BIG_TEST_SIZE];
unsigned char checktext[BIG_TEST_SIZE];
unsigned int n;
size_t matches;
memcpy(iv, saved_iv, sizeof(iv));
AES_set_encrypt_key(rkey, 8 * sizeof(rkey), &key);
AES_set_encrypt_key(rkey2, 8 * sizeof(rkey2), &key2);
AES_ige_encrypt(plaintext, ciphertext, sizeof(plaintext), &key, iv,
AES_ENCRYPT);
/* corrupt right at the start */
++ciphertext[0];
AES_set_decrypt_key(rkey, 8 * sizeof(rkey), &key);
AES_set_decrypt_key(rkey2, 8 * sizeof(rkey2), &key2);
AES_ige_encrypt(ciphertext, checktext, sizeof(checktext), &key, iv,
AES_DECRYPT);
matches = 0;
for (n = 0; n < sizeof(checktext); ++n)
if (checktext[n] == plaintext[n])
++matches;
/* Fail if there is more than 1% matching bytes */
return TEST_size_t_le(matches, sizeof(checktext) / 100);
}
#endif
int setup_tests(void)
{
#ifndef OPENSSL_NO_DEPRECATED_3_0
RAND_bytes(rkey, sizeof(rkey));
RAND_bytes(rkey2, sizeof(rkey2));
RAND_bytes(plaintext, sizeof(plaintext));
RAND_bytes(saved_iv, sizeof(saved_iv));
ADD_TEST(test_ige_enc_dec);
ADD_TEST(test_ige_enc_chaining);
ADD_TEST(test_ige_dec_chaining);
ADD_TEST(test_ige_garble_forwards);
ADD_TEST(test_bi_ige_enc_dec);
ADD_TEST(test_bi_ige_garble1);
ADD_TEST(test_bi_ige_garble2);
ADD_TEST(test_bi_ige_garble3);
ADD_ALL_TESTS(test_ige_vectors, OSSL_NELEM(ige_test_vectors));
ADD_ALL_TESTS(test_bi_ige_vectors, OSSL_NELEM(bi_ige_test_vectors));
#endif
return 1;
}
| 16,787 | 35.259179 | 80 | c |
openssl | openssl-master/test/keymgmt_internal_test.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
*/
/*
* RSA low level APIs are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include <string.h>
#include <openssl/bio.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/provider.h>
#include <openssl/core_names.h>
#include "internal/core.h"
#include "internal/nelem.h"
#include "crypto/evp.h" /* For the internal API */
#include "testutil.h"
typedef struct {
OSSL_LIB_CTX *ctx1;
OSSL_PROVIDER *prov1;
OSSL_LIB_CTX *ctx2;
OSSL_PROVIDER *prov2;
} FIXTURE;
/* Collected arguments */
static const char *cert_filename = NULL;
static void tear_down(FIXTURE *fixture)
{
if (fixture != NULL) {
OSSL_PROVIDER_unload(fixture->prov1);
OSSL_PROVIDER_unload(fixture->prov2);
OSSL_LIB_CTX_free(fixture->ctx1);
OSSL_LIB_CTX_free(fixture->ctx2);
OPENSSL_free(fixture);
}
}
static FIXTURE *set_up(const char *testcase_name)
{
FIXTURE *fixture;
if (!TEST_ptr(fixture = OPENSSL_zalloc(sizeof(*fixture)))
|| !TEST_ptr(fixture->ctx1 = OSSL_LIB_CTX_new())
|| !TEST_ptr(fixture->prov1 = OSSL_PROVIDER_load(fixture->ctx1,
"default"))
|| !TEST_ptr(fixture->ctx2 = OSSL_LIB_CTX_new())
|| !TEST_ptr(fixture->prov2 = OSSL_PROVIDER_load(fixture->ctx2,
"default"))) {
tear_down(fixture);
return NULL;
}
return fixture;
}
/* Array indexes */
#define N 0
#define E 1
#define D 2
#define P 3
#define Q 4
#define F3 5 /* Extra factor */
#define DP 6
#define DQ 7
#define E3 8 /* Extra exponent */
#define QINV 9
#define C2 10 /* Extra coefficient */
/*
* We have to do this because OSSL_PARAM_get_ulong() can't handle params
* holding data that isn't exactly sizeof(uint32_t) or sizeof(uint64_t),
* and because the other end deals with BIGNUM, the resulting param might
* be any size. In this particular test, we know that the expected data
* fits within an unsigned long, and we want to get the data in that form
* to make testing of values easier.
*/
static int get_ulong_via_BN(const OSSL_PARAM *p, unsigned long *goal)
{
BIGNUM *n = NULL;
int ret = 1; /* Ever so hopeful */
if (!TEST_true(OSSL_PARAM_get_BN(p, &n))
|| !TEST_int_ge(BN_bn2nativepad(n, (unsigned char *)goal, sizeof(*goal)), 0))
ret = 0;
BN_free(n);
return ret;
}
static int export_cb(const OSSL_PARAM *params, void *arg)
{
unsigned long *keydata = arg;
const OSSL_PARAM *p = NULL;
if (keydata == NULL)
return 0;
if (!TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_N))
|| !TEST_true(get_ulong_via_BN(p, &keydata[N]))
|| !TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_E))
|| !TEST_true(get_ulong_via_BN(p, &keydata[E]))
|| !TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_D))
|| !TEST_true(get_ulong_via_BN(p, &keydata[D])))
return 0;
if (!TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_FACTOR1))
|| !TEST_true(get_ulong_via_BN(p, &keydata[P]))
|| !TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_FACTOR2))
|| !TEST_true(get_ulong_via_BN(p, &keydata[Q]))
|| !TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_FACTOR3))
|| !TEST_true(get_ulong_via_BN(p, &keydata[F3])))
return 0;
if (!TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_EXPONENT1))
|| !TEST_true(get_ulong_via_BN(p, &keydata[DP]))
|| !TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_EXPONENT2))
|| !TEST_true(get_ulong_via_BN(p, &keydata[DQ]))
|| !TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_EXPONENT3))
|| !TEST_true(get_ulong_via_BN(p, &keydata[E3])))
return 0;
if (!TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_COEFFICIENT1))
|| !TEST_true(get_ulong_via_BN(p, &keydata[QINV]))
|| !TEST_ptr(p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_RSA_COEFFICIENT2))
|| !TEST_true(get_ulong_via_BN(p, &keydata[C2])))
return 0;
return 1;
}
static int test_pass_rsa(FIXTURE *fixture)
{
size_t i;
int ret = 0;
RSA *rsa = NULL;
BIGNUM *bn1 = NULL, *bn2 = NULL, *bn3 = NULL;
EVP_PKEY *pk = NULL, *dup_pk = NULL;
EVP_KEYMGMT *km = NULL, *km1 = NULL, *km2 = NULL, *km3 = NULL;
void *provkey = NULL, *provkey2 = NULL;
BIGNUM *bn_primes[1] = { NULL };
BIGNUM *bn_exps[1] = { NULL };
BIGNUM *bn_coeffs[1] = { NULL };
/*
* 32-bit RSA key, extracted from this command,
* executed with OpenSSL 1.0.2:
* An extra factor was added just for testing purposes.
*
* openssl genrsa 32 | openssl rsa -text
*/
static BN_ULONG expected[] = {
0xbc747fc5, /* N */
0x10001, /* E */
0x7b133399, /* D */
0xe963, /* P */
0xceb7, /* Q */
1, /* F3 */
0x8599, /* DP */
0xbd87, /* DQ */
2, /* E3 */
0xcc3b, /* QINV */
3, /* C3 */
0 /* Extra, should remain zero */
};
static unsigned long keydata[OSSL_NELEM(expected)] = { 0, };
if (!TEST_ptr(rsa = RSA_new()))
goto err;
if (!TEST_ptr(bn1 = BN_new())
|| !TEST_true(BN_set_word(bn1, expected[N]))
|| !TEST_ptr(bn2 = BN_new())
|| !TEST_true(BN_set_word(bn2, expected[E]))
|| !TEST_ptr(bn3 = BN_new())
|| !TEST_true(BN_set_word(bn3, expected[D]))
|| !TEST_true(RSA_set0_key(rsa, bn1, bn2, bn3)))
goto err;
if (!TEST_ptr(bn1 = BN_new())
|| !TEST_true(BN_set_word(bn1, expected[P]))
|| !TEST_ptr(bn2 = BN_new())
|| !TEST_true(BN_set_word(bn2, expected[Q]))
|| !TEST_true(RSA_set0_factors(rsa, bn1, bn2)))
goto err;
if (!TEST_ptr(bn1 = BN_new())
|| !TEST_true(BN_set_word(bn1, expected[DP]))
|| !TEST_ptr(bn2 = BN_new())
|| !TEST_true(BN_set_word(bn2, expected[DQ]))
|| !TEST_ptr(bn3 = BN_new())
|| !TEST_true(BN_set_word(bn3, expected[QINV]))
|| !TEST_true(RSA_set0_crt_params(rsa, bn1, bn2, bn3)))
goto err;
bn1 = bn2 = bn3 = NULL;
if (!TEST_ptr(bn_primes[0] = BN_new())
|| !TEST_true(BN_set_word(bn_primes[0], expected[F3]))
|| !TEST_ptr(bn_exps[0] = BN_new())
|| !TEST_true(BN_set_word(bn_exps[0], expected[E3]))
|| !TEST_ptr(bn_coeffs[0] = BN_new())
|| !TEST_true(BN_set_word(bn_coeffs[0], expected[C2]))
|| !TEST_true(RSA_set0_multi_prime_params(rsa, bn_primes, bn_exps,
bn_coeffs, 1)))
goto err;
if (!TEST_ptr(pk = EVP_PKEY_new())
|| !TEST_true(EVP_PKEY_assign_RSA(pk, rsa)))
goto err;
rsa = NULL;
if (!TEST_ptr(km1 = EVP_KEYMGMT_fetch(fixture->ctx1, "RSA", NULL))
|| !TEST_ptr(km2 = EVP_KEYMGMT_fetch(fixture->ctx2, "RSA", NULL))
|| !TEST_ptr(km3 = EVP_KEYMGMT_fetch(fixture->ctx1, "RSA-PSS", NULL))
|| !TEST_ptr_ne(km1, km2))
goto err;
while (dup_pk == NULL) {
ret = 0;
km = km3;
/* Check that we can't export an RSA key into an RSA-PSS keymanager */
if (!TEST_ptr_null(provkey2 = evp_pkey_export_to_provider(pk, NULL,
&km,
NULL)))
goto err;
if (!TEST_ptr(provkey = evp_pkey_export_to_provider(pk, NULL, &km1,
NULL))
|| !TEST_true(evp_keymgmt_export(km2, provkey,
OSSL_KEYMGMT_SELECT_KEYPAIR,
&export_cb, keydata)))
goto err;
/*
* At this point, the hope is that keydata will have all the numbers
* from the key.
*/
for (i = 0; i < OSSL_NELEM(expected); i++) {
int rv = TEST_int_eq(expected[i], keydata[i]);
if (!rv)
TEST_info("i = %zu", i);
else
ret++;
}
ret = (ret == OSSL_NELEM(expected));
if (!ret || !TEST_ptr(dup_pk = EVP_PKEY_dup(pk)))
goto err;
ret = TEST_int_eq(EVP_PKEY_eq(pk, dup_pk), 1);
EVP_PKEY_free(pk);
pk = dup_pk;
if (!ret)
goto err;
}
err:
RSA_free(rsa);
BN_free(bn1);
BN_free(bn2);
BN_free(bn3);
EVP_PKEY_free(pk);
EVP_KEYMGMT_free(km1);
EVP_KEYMGMT_free(km2);
EVP_KEYMGMT_free(km3);
return ret;
}
static int (*tests[])(FIXTURE *) = {
test_pass_rsa
};
static int test_pass_key(int n)
{
SETUP_TEST_FIXTURE(FIXTURE, set_up);
EXECUTE_TEST(tests[n], tear_down);
return result;
}
static int test_evp_pkey_export_to_provider(int n)
{
OSSL_LIB_CTX *libctx = NULL;
OSSL_PROVIDER *prov = NULL;
X509 *cert = NULL;
BIO *bio = NULL;
X509_PUBKEY *pubkey = NULL;
EVP_KEYMGMT *keymgmt = NULL;
EVP_PKEY *pkey = NULL;
void *keydata = NULL;
int ret = 0;
if (!TEST_ptr(libctx = OSSL_LIB_CTX_new())
|| !TEST_ptr(prov = OSSL_PROVIDER_load(libctx, "default")))
goto end;
if ((bio = BIO_new_file(cert_filename, "r")) == NULL) {
TEST_error("Couldn't open '%s' for reading\n", cert_filename);
TEST_openssl_errors();
goto end;
}
if ((cert = PEM_read_bio_X509(bio, NULL, NULL, NULL)) == NULL) {
TEST_error("'%s' doesn't appear to be a X.509 certificate in PEM format\n",
cert_filename);
TEST_openssl_errors();
goto end;
}
pubkey = X509_get_X509_PUBKEY(cert);
pkey = X509_PUBKEY_get0(pubkey);
if (n == 0) {
if (!TEST_ptr(keydata = evp_pkey_export_to_provider(pkey, NULL,
NULL, NULL)))
goto end;
} else if (n == 1) {
if (!TEST_ptr(keydata = evp_pkey_export_to_provider(pkey, NULL,
&keymgmt, NULL)))
goto end;
} else {
keymgmt = EVP_KEYMGMT_fetch(libctx, "RSA", NULL);
if (!TEST_ptr(keydata = evp_pkey_export_to_provider(pkey, NULL,
&keymgmt, NULL)))
goto end;
}
ret = 1;
end:
BIO_free(bio);
X509_free(cert);
EVP_KEYMGMT_free(keymgmt);
OSSL_PROVIDER_unload(prov);
OSSL_LIB_CTX_free(libctx);
return ret;
}
int setup_tests(void)
{
if (!TEST_ptr(cert_filename = test_get_argument(0)))
return 0;
ADD_ALL_TESTS(test_pass_key, 1);
ADD_ALL_TESTS(test_evp_pkey_export_to_provider, 3);
return 1;
}
| 11,723 | 31.657382 | 91 | c |
openssl | openssl-master/test/lhash_test.c | /*
* Copyright 2017-2020 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2017, 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
*/
#include <stdio.h>
#include <string.h>
#include <openssl/opensslconf.h>
#include <openssl/lhash.h>
#include <openssl/err.h>
#include <openssl/crypto.h>
#include "internal/nelem.h"
#include "testutil.h"
/*
* The macros below generate unused functions which error out one of the clang
* builds. We disable this check here.
*/
#ifdef __clang__
#pragma clang diagnostic ignored "-Wunused-function"
#endif
DEFINE_LHASH_OF_EX(int);
static int int_tests[] = { 65537, 13, 1, 3, -5, 6, 7, 4, -10, -12, -14, 22, 9,
-17, 16, 17, -23, 35, 37, 173, 11 };
static const unsigned int n_int_tests = OSSL_NELEM(int_tests);
static short int_found[OSSL_NELEM(int_tests)];
static short int_not_found;
static unsigned long int int_hash(const int *p)
{
return 3 & *p; /* To force collisions */
}
static int int_cmp(const int *p, const int *q)
{
return *p != *q;
}
static int int_find(int n)
{
unsigned int i;
for (i = 0; i < n_int_tests; i++)
if (int_tests[i] == n)
return i;
return -1;
}
static void int_doall(int *v)
{
const int n = int_find(*v);
if (n < 0)
int_not_found++;
else
int_found[n]++;
}
static void int_doall_arg(int *p, short *f)
{
const int n = int_find(*p);
if (n < 0)
int_not_found++;
else
f[n]++;
}
IMPLEMENT_LHASH_DOALL_ARG(int, short);
static int test_int_lhash(void)
{
static struct {
int data;
int null;
} dels[] = {
{ 65537, 0 },
{ 173, 0 },
{ 999, 1 },
{ 37, 0 },
{ 1, 0 },
{ 34, 1 }
};
const unsigned int n_dels = OSSL_NELEM(dels);
LHASH_OF(int) *h = lh_int_new(&int_hash, &int_cmp);
unsigned int i;
int testresult = 0, j, *p;
if (!TEST_ptr(h))
goto end;
/* insert */
for (i = 0; i < n_int_tests; i++)
if (!TEST_ptr_null(lh_int_insert(h, int_tests + i))) {
TEST_info("int insert %d", i);
goto end;
}
/* num_items */
if (!TEST_int_eq(lh_int_num_items(h), n_int_tests))
goto end;
/* retrieve */
for (i = 0; i < n_int_tests; i++)
if (!TEST_int_eq(*lh_int_retrieve(h, int_tests + i), int_tests[i])) {
TEST_info("lhash int retrieve value %d", i);
goto end;
}
for (i = 0; i < n_int_tests; i++)
if (!TEST_ptr_eq(lh_int_retrieve(h, int_tests + i), int_tests + i)) {
TEST_info("lhash int retrieve address %d", i);
goto end;
}
j = 1;
if (!TEST_ptr_eq(lh_int_retrieve(h, &j), int_tests + 2))
goto end;
/* replace */
j = 13;
if (!TEST_ptr(p = lh_int_insert(h, &j)))
goto end;
if (!TEST_ptr_eq(p, int_tests + 1))
goto end;
if (!TEST_ptr_eq(lh_int_retrieve(h, int_tests + 1), &j))
goto end;
/* do_all */
memset(int_found, 0, sizeof(int_found));
int_not_found = 0;
lh_int_doall(h, &int_doall);
if (!TEST_int_eq(int_not_found, 0)) {
TEST_info("lhash int doall encountered a not found condition");
goto end;
}
for (i = 0; i < n_int_tests; i++)
if (!TEST_int_eq(int_found[i], 1)) {
TEST_info("lhash int doall %d", i);
goto end;
}
/* do_all_arg */
memset(int_found, 0, sizeof(int_found));
int_not_found = 0;
lh_int_doall_short(h, int_doall_arg, int_found);
if (!TEST_int_eq(int_not_found, 0)) {
TEST_info("lhash int doall arg encountered a not found condition");
goto end;
}
for (i = 0; i < n_int_tests; i++)
if (!TEST_int_eq(int_found[i], 1)) {
TEST_info("lhash int doall arg %d", i);
goto end;
}
/* delete */
for (i = 0; i < n_dels; i++) {
const int b = lh_int_delete(h, &dels[i].data) == NULL;
if (!TEST_int_eq(b ^ dels[i].null, 0)) {
TEST_info("lhash int delete %d", i);
goto end;
}
}
/* error */
if (!TEST_int_eq(lh_int_error(h), 0))
goto end;
testresult = 1;
end:
lh_int_free(h);
return testresult;
}
static unsigned long int stress_hash(const int *p)
{
return *p;
}
static int test_stress(void)
{
LHASH_OF(int) *h = lh_int_new(&stress_hash, &int_cmp);
const unsigned int n = 2500000;
unsigned int i;
int testresult = 0, *p;
if (!TEST_ptr(h))
goto end;
/* insert */
for (i = 0; i < n; i++) {
p = OPENSSL_malloc(sizeof(i));
if (!TEST_ptr(p)) {
TEST_info("lhash stress out of memory %d", i);
goto end;
}
*p = 3 * i + 1;
lh_int_insert(h, p);
}
/* num_items */
if (!TEST_int_eq(lh_int_num_items(h), n))
goto end;
/* delete in a different order */
for (i = 0; i < n; i++) {
const int j = (7 * i + 4) % n * 3 + 1;
if (!TEST_ptr(p = lh_int_delete(h, &j))) {
TEST_info("lhash stress delete %d\n", i);
goto end;
}
if (!TEST_int_eq(*p, j)) {
TEST_info("lhash stress bad value %d", i);
goto end;
}
OPENSSL_free(p);
}
testresult = 1;
end:
lh_int_free(h);
return testresult;
}
int setup_tests(void)
{
ADD_TEST(test_int_lhash);
ADD_TEST(test_stress);
return 1;
}
| 5,785 | 23.108333 | 78 | c |
openssl | openssl-master/test/list_test.c | /*
* Copyright 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 <string.h>
#include <openssl/opensslconf.h>
#include <openssl/err.h>
#include <openssl/crypto.h>
#include "internal/list.h"
#include "internal/nelem.h"
#include "testutil.h"
typedef struct testl_st TESTL;
struct testl_st {
int n;
OSSL_LIST_MEMBER(fizz, TESTL);
OSSL_LIST_MEMBER(buzz, TESTL);
};
DEFINE_LIST_OF(fizz, TESTL);
DEFINE_LIST_OF(buzz, TESTL);
static int test_fizzbuzz(void)
{
OSSL_LIST(fizz) a;
OSSL_LIST(buzz) b;
TESTL elem[20];
const int nelem = OSSL_NELEM(elem);
int i, na = 0, nb = 0;
ossl_list_fizz_init(&a);
ossl_list_buzz_init(&b);
if (!TEST_true(ossl_list_fizz_is_empty(&a)))
return 0;
for (i = 1; i < nelem; i++) {
ossl_list_fizz_init_elem(elem + i);
ossl_list_buzz_init_elem(elem + i);
elem[i].n = i;
if (i % 3 == 0) {
ossl_list_fizz_insert_tail(&a, elem + i);
na++;
}
if (i % 5 == 0) {
ossl_list_buzz_insert_head(&b, elem + i);
nb++;
}
}
if (!TEST_false(ossl_list_fizz_is_empty(&a))
|| !TEST_size_t_eq(ossl_list_fizz_num(&a), na)
|| !TEST_size_t_eq(ossl_list_buzz_num(&b), nb)
|| !TEST_ptr(ossl_list_fizz_head(&a))
|| !TEST_ptr(ossl_list_fizz_tail(&a))
|| !TEST_ptr(ossl_list_buzz_head(&b))
|| !TEST_ptr(ossl_list_buzz_tail(&b))
|| !TEST_int_eq(ossl_list_fizz_head(&a)->n, 3)
|| !TEST_int_eq(ossl_list_fizz_tail(&a)->n, na * 3)
|| !TEST_int_eq(ossl_list_buzz_head(&b)->n, nb * 5)
|| !TEST_int_eq(ossl_list_buzz_tail(&b)->n, 5))
return 0;
ossl_list_fizz_remove(&a, ossl_list_fizz_head(&a));
ossl_list_buzz_remove(&b, ossl_list_buzz_tail(&b));
if (!TEST_size_t_eq(ossl_list_fizz_num(&a), --na)
|| !TEST_size_t_eq(ossl_list_buzz_num(&b), --nb)
|| !TEST_ptr(ossl_list_fizz_head(&a))
|| !TEST_ptr(ossl_list_buzz_tail(&b))
|| !TEST_int_eq(ossl_list_fizz_head(&a)->n, 6)
|| !TEST_int_eq(ossl_list_buzz_tail(&b)->n, 10)
|| !TEST_ptr(ossl_list_fizz_next(ossl_list_fizz_head(&a)))
|| !TEST_ptr(ossl_list_fizz_prev(ossl_list_fizz_tail(&a)))
|| !TEST_int_eq(ossl_list_fizz_next(ossl_list_fizz_head(&a))->n, 9)
|| !TEST_int_eq(ossl_list_fizz_prev(ossl_list_fizz_tail(&a))->n, 15))
return 0;
return 1;
}
typedef struct int_st INTL;
struct int_st {
int n;
OSSL_LIST_MEMBER(int, INTL);
};
DEFINE_LIST_OF(int, INTL);
static int test_insert(void)
{
INTL *c, *d;
OSSL_LIST(int) l;
INTL elem[20];
size_t i;
int n = 1;
ossl_list_int_init(&l);
for (i = 0; i < OSSL_NELEM(elem); i++) {
ossl_list_int_init_elem(elem + i);
elem[i].n = i;
}
/* Check various insert options - head, tail, middle */
ossl_list_int_insert_head(&l, elem + 3); /* 3 */
ossl_list_int_insert_tail(&l, elem + 6); /* 3 6 */
ossl_list_int_insert_before(&l, elem + 6, elem + 5); /* 3 5 6 */
ossl_list_int_insert_before(&l, elem + 3, elem + 1); /* 1 3 5 6 */
ossl_list_int_insert_after(&l, elem + 1, elem + 2); /* 1 2 3 5 6 */
ossl_list_int_insert_after(&l, elem + 6, elem + 7); /* 1 2 3 5 6 7 */
ossl_list_int_insert_after(&l, elem + 3, elem + 4); /* 1 2 3 4 5 6 7 */
if (!TEST_size_t_eq(ossl_list_int_num(&l), 7))
return 0;
c = ossl_list_int_head(&l);
d = ossl_list_int_tail(&l);
while (c != NULL && d != NULL) {
if (!TEST_int_eq(c->n, n) || !TEST_int_eq(d->n, 8 - n))
return 0;
c = ossl_list_int_next(c);
d = ossl_list_int_prev(d);
n++;
}
if (!TEST_ptr_null(c) || !TEST_ptr_null(d))
return 0;
/* Check removing head, tail and middle */
ossl_list_int_remove(&l, elem + 1); /* 2 3 4 5 6 7 */
ossl_list_int_remove(&l, elem + 6); /* 2 3 4 5 7 */
ossl_list_int_remove(&l, elem + 7); /* 2 3 4 5 */
n = 2;
c = ossl_list_int_head(&l);
d = ossl_list_int_tail(&l);
while (c != NULL && d != NULL) {
if (!TEST_int_eq(c->n, n) || !TEST_int_eq(d->n, 7 - n))
return 0;
c = ossl_list_int_next(c);
d = ossl_list_int_prev(d);
n++;
}
if (!TEST_ptr_null(c) || !TEST_ptr_null(d))
return 0;
/* Check removing the head of a two element list works */
ossl_list_int_remove(&l, elem + 2); /* 3 4 5 */
ossl_list_int_remove(&l, elem + 4); /* 3 5 */
ossl_list_int_remove(&l, elem + 3); /* 5 */
if (!TEST_ptr(ossl_list_int_head(&l))
|| !TEST_ptr(ossl_list_int_tail(&l))
|| !TEST_int_eq(ossl_list_int_head(&l)->n, 5)
|| !TEST_int_eq(ossl_list_int_tail(&l)->n, 5))
return 0;
/* Check removing the tail of a two element list works */
ossl_list_int_insert_head(&l, elem); /* 0 5 */
ossl_list_int_remove(&l, elem + 5); /* 0 */
if (!TEST_ptr(ossl_list_int_head(&l))
|| !TEST_ptr(ossl_list_int_tail(&l))
|| !TEST_int_eq(ossl_list_int_head(&l)->n, 0)
|| !TEST_int_eq(ossl_list_int_tail(&l)->n, 0))
return 0;
/* Check removing the only element works */
ossl_list_int_remove(&l, elem);
if (!TEST_ptr_null(ossl_list_int_head(&l))
|| !TEST_ptr_null(ossl_list_int_tail(&l)))
return 0;
return 1;
}
int setup_tests(void)
{
ADD_TEST(test_fizzbuzz);
ADD_TEST(test_insert);
return 1;
}
| 6,056 | 32.464088 | 81 | c |
openssl | openssl-master/test/localetest.c | /*
* Copyright 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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/x509.h>
#include "testutil.h"
#include "testutil/output.h"
#ifndef OPENSSL_NO_LOCALE
# include <locale.h>
# ifdef OPENSSL_SYS_MACOSX
# include <xlocale.h>
# endif
int setup_tests(void)
{
const unsigned char der_bytes[] = {
0x30, 0x82, 0x03, 0x09, 0x30, 0x82, 0x01, 0xf1, 0xa0, 0x03, 0x02, 0x01,
0x02, 0x02, 0x14, 0x08, 0xe0, 0x8c, 0xd3, 0xf3, 0xbf, 0x2c, 0xf2, 0x0d,
0x0a, 0x75, 0xd1, 0xe8, 0xea, 0xbe, 0x70, 0x61, 0xd9, 0x67, 0xf9, 0x30,
0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b,
0x05, 0x00, 0x30, 0x14, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04,
0x03, 0x0c, 0x09, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, 0x73, 0x74,
0x30, 0x1e, 0x17, 0x0d, 0x32, 0x32, 0x30, 0x34, 0x31, 0x31, 0x31, 0x34,
0x31, 0x39, 0x35, 0x37, 0x5a, 0x17, 0x0d, 0x32, 0x32, 0x30, 0x35, 0x31,
0x31, 0x31, 0x34, 0x31, 0x39, 0x35, 0x37, 0x5a, 0x30, 0x14, 0x31, 0x12,
0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x09, 0x6c, 0x6f, 0x63,
0x61, 0x6c, 0x68, 0x6f, 0x73, 0x74, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d,
0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05,
0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82,
0x01, 0x01, 0x00, 0xc3, 0x1f, 0x5c, 0x56, 0x46, 0x8d, 0x69, 0xb6, 0x48,
0x3c, 0xbf, 0xe2, 0x0f, 0xa7, 0x4a, 0x44, 0x72, 0x74, 0x36, 0xfe, 0xe8,
0x2f, 0x10, 0x4a, 0xe9, 0x46, 0x45, 0x72, 0x5e, 0x48, 0xdd, 0x75, 0xab,
0xd9, 0x63, 0x91, 0x37, 0x93, 0x46, 0x28, 0x7e, 0x45, 0x94, 0x4b, 0x8a,
0xd5, 0x05, 0x2b, 0x9a, 0x01, 0x96, 0x30, 0xde, 0xcc, 0x14, 0x2d, 0x06,
0x09, 0x1b, 0x7d, 0x50, 0x14, 0x99, 0x36, 0x6b, 0x97, 0x6e, 0xc9, 0xb1,
0x69, 0x70, 0xcd, 0x9b, 0x74, 0x24, 0x9a, 0xe2, 0xd4, 0xc0, 0x1e, 0xbc,
0xec, 0xf6, 0x7a, 0xbb, 0xa0, 0x53, 0x93, 0xf8, 0x68, 0x9a, 0x18, 0xa1,
0xa1, 0x5c, 0x47, 0x93, 0xd1, 0x4c, 0x36, 0x8c, 0x00, 0xb3, 0x66, 0xda,
0xf1, 0x05, 0xb2, 0x3a, 0xad, 0x7e, 0x4b, 0xf3, 0xd3, 0x93, 0xfa, 0x59,
0x09, 0x9c, 0x60, 0x37, 0x69, 0x61, 0xe8, 0x5a, 0x33, 0xc6, 0xb2, 0x1a,
0xba, 0x36, 0xe2, 0xb3, 0x58, 0xe9, 0x73, 0x01, 0x2d, 0x36, 0x48, 0x36,
0x94, 0xe4, 0xb2, 0xa4, 0x5b, 0xdf, 0x3d, 0x5f, 0x62, 0x9f, 0xd9, 0xf3,
0x24, 0x0c, 0xf0, 0x2f, 0x71, 0x44, 0x79, 0x13, 0x70, 0x95, 0xa7, 0xbe,
0xea, 0x0a, 0x08, 0x0a, 0xa6, 0x4b, 0xe9, 0x58, 0x6b, 0xa4, 0xc2, 0xed,
0x74, 0x1e, 0xb0, 0x3b, 0x59, 0xd5, 0xe6, 0xdb, 0x8f, 0x58, 0x6a, 0xa3,
0x7d, 0x52, 0x40, 0xec, 0x72, 0xb7, 0xba, 0x7e, 0x30, 0x9d, 0x12, 0x57,
0xf2, 0x48, 0xae, 0x80, 0x0d, 0x0a, 0xf4, 0xfd, 0x24, 0xed, 0xd8, 0x05,
0xb2, 0x96, 0x44, 0x02, 0x3e, 0x6e, 0x25, 0xb0, 0xc4, 0x93, 0xda, 0xfe,
0x78, 0xd9, 0xbb, 0xd2, 0x71, 0x69, 0x70, 0x7f, 0xba, 0xf7, 0xb0, 0x4f,
0x14, 0xf7, 0x98, 0x71, 0x01, 0x6c, 0xec, 0x6f, 0x76, 0x03, 0x59, 0xff,
0xe2, 0xba, 0x8d, 0xd9, 0x21, 0x08, 0xb3, 0x02, 0x03, 0x01, 0x00, 0x01,
0xa3, 0x53, 0x30, 0x51, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04,
0x16, 0x04, 0x14, 0x59, 0xb8, 0x6e, 0x1a, 0x72, 0xe9, 0x27, 0x1e, 0xbf,
0x80, 0x87, 0x0f, 0xa9, 0xd0, 0x06, 0x6a, 0x11, 0x30, 0x77, 0x8e, 0x30,
0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14,
0x59, 0xb8, 0x6e, 0x1a, 0x72, 0xe9, 0x27, 0x1e, 0xbf, 0x80, 0x87, 0x0f,
0xa9, 0xd0, 0x06, 0x6a, 0x11, 0x30, 0x77, 0x8e, 0x30, 0x0f, 0x06, 0x03,
0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01,
0xff, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01,
0x01, 0x0b, 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x98, 0x76, 0x9e,
0x3c, 0xfc, 0x3f, 0x58, 0xe8, 0xf2, 0x1f, 0x2e, 0x11, 0xa2, 0x59, 0xfa,
0x27, 0xb5, 0xec, 0x9d, 0x97, 0x05, 0x06, 0x2c, 0x95, 0xa5, 0x28, 0x88,
0x86, 0xeb, 0x4e, 0x8a, 0x62, 0xe9, 0x87, 0x78, 0xd8, 0x18, 0x22, 0x4e,
0xb1, 0x8d, 0x46, 0x4a, 0x4c, 0x6e, 0x7c, 0x53, 0x62, 0x2c, 0xf2, 0x7a,
0x95, 0xa0, 0x1a, 0x30, 0x18, 0x6a, 0x31, 0x6f, 0x3f, 0x55, 0x25, 0x9f,
0x67, 0x60, 0x68, 0x99, 0x0f, 0x41, 0x09, 0xc8, 0xe2, 0x04, 0x33, 0x22,
0x1a, 0xe9, 0xf3, 0xae, 0xce, 0xb6, 0x83, 0x64, 0x78, 0x66, 0x14, 0xc9,
0x54, 0xc8, 0x34, 0x70, 0x96, 0xaf, 0x16, 0xcd, 0xb8, 0xdf, 0x81, 0x7e,
0xf0, 0xa6, 0x7d, 0xc1, 0x13, 0xb2, 0x76, 0x3a, 0xd5, 0x7e, 0x68, 0x8c,
0xd5, 0x00, 0x70, 0x82, 0x23, 0x7e, 0x5e, 0xc9, 0x31, 0x2f, 0x33, 0x54,
0xaa, 0xaf, 0xcd, 0xe9, 0x38, 0x9a, 0x23, 0x53, 0xad, 0x4e, 0x72, 0xa7,
0x6f, 0x47, 0x60, 0xc9, 0xd3, 0x06, 0x9b, 0x7a, 0x21, 0xc6, 0xe9, 0xdb,
0x3c, 0xaa, 0xc0, 0x21, 0x29, 0x5f, 0x44, 0x6a, 0x45, 0x90, 0x73, 0x5e,
0x6d, 0x78, 0x82, 0xcb, 0x42, 0xe6, 0xba, 0x67, 0xb2, 0xe6, 0xa2, 0x15,
0x04, 0xea, 0x69, 0xae, 0x3e, 0xc0, 0x0c, 0x10, 0x99, 0xec, 0xa9, 0xb0,
0x7e, 0xe8, 0x94, 0xe2, 0xf3, 0xaf, 0xf7, 0x9f, 0x65, 0xe7, 0xd7, 0xe2,
0x49, 0xfa, 0x52, 0x7d, 0xb5, 0xfd, 0xa0, 0xa5, 0xe0, 0x49, 0xa7, 0x3d,
0x94, 0x20, 0x2d, 0xec, 0x8c, 0x22, 0xa5, 0xa4, 0x43, 0xfa, 0x7e, 0xd0,
0x50, 0x21, 0xb8, 0x67, 0x18, 0x44, 0x69, 0x8f, 0xdd, 0x47, 0x41, 0xc6,
0x35, 0xe0, 0xe9, 0x2e, 0x41, 0xa9, 0x6f, 0x41, 0xee, 0xb9, 0xbd, 0x45,
0xf3, 0x88, 0xc1, 0x23, 0x35, 0x96, 0xba, 0xf8, 0xcd, 0x4b, 0x83, 0x73,
0x5f
};
char str1[] = "SubjectPublicKeyInfo", str2[] = "subjectpublickeyinfo";
int res;
X509 *cert = NULL;
X509_PUBKEY *cert_pubkey = NULL;
const unsigned char *p = der_bytes;
if (setlocale(LC_ALL, "") == NULL)
return TEST_skip("Cannot set the locale necessary for test");
res = strcasecmp(str1, str2);
TEST_note("Case-insensitive comparison via strcasecmp in current locale %s\n", res ? "failed" : "succeeded");
if (!TEST_false(OPENSSL_strcasecmp(str1, str2)))
return 0;
cert = d2i_X509(NULL, &p, sizeof(der_bytes));
if (!TEST_ptr(cert))
return 0;
cert_pubkey = X509_get_X509_PUBKEY(cert);
if (!TEST_ptr(cert_pubkey)) {
X509_free(cert);
return 0;
}
if (!TEST_ptr(X509_PUBKEY_get0(cert_pubkey))) {
X509_free(cert);
return 0;
}
X509_free(cert);
return 1;
}
#else
int setup_tests(void)
{
return TEST_skip("Locale support not available");
}
#endif /* OPENSSL_NO_LOCALE */
void cleanup_tests(void)
{
}
| 6,514 | 46.554745 | 113 | c |
openssl | openssl-master/test/mdc2_internal_test.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
*/
/* Internal tests for the mdc2 module */
/*
* MDC2 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/mdc2.h>
#include "testutil.h"
#include "internal/nelem.h"
typedef struct {
const char *input;
const unsigned char expected[MDC2_DIGEST_LENGTH];
} TESTDATA;
/**********************************************************************
*
* Test driver
*
***/
static TESTDATA tests[] = {
{
"Now is the time for all ",
{
0x42, 0xE5, 0x0C, 0xD2, 0x24, 0xBA, 0xCE, 0xBA,
0x76, 0x0B, 0xDD, 0x2B, 0xD4, 0x09, 0x28, 0x1A
}
}
};
/**********************************************************************
*
* Test of mdc2 internal functions
*
***/
static int test_mdc2(int idx)
{
unsigned char md[MDC2_DIGEST_LENGTH];
MDC2_CTX c;
const TESTDATA testdata = tests[idx];
MDC2_Init(&c);
MDC2_Update(&c, (const unsigned char *)testdata.input,
strlen(testdata.input));
MDC2_Final(&(md[0]), &c);
if (!TEST_mem_eq(testdata.expected, MDC2_DIGEST_LENGTH,
md, MDC2_DIGEST_LENGTH)) {
TEST_info("mdc2 test %d: unexpected output", idx);
return 0;
}
return 1;
}
int setup_tests(void)
{
ADD_ALL_TESTS(test_mdc2, OSSL_NELEM(tests));
return 1;
}
| 1,753 | 21.487179 | 74 | c |
openssl | openssl-master/test/mdc2test.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
*/
/*
* MDC2 low level APIs are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include <string.h>
#include <openssl/provider.h>
#include <openssl/params.h>
#include <openssl/types.h>
#include <openssl/core_names.h>
#include "testutil.h"
#if defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_MDC2)
# define OPENSSL_NO_MDC2
#endif
#ifndef OPENSSL_NO_MDC2
# include <openssl/evp.h>
# include <openssl/mdc2.h>
# ifdef CHARSET_EBCDIC
# include <openssl/ebcdic.h>
# endif
static unsigned char pad1[16] = {
0x42, 0xE5, 0x0C, 0xD2, 0x24, 0xBA, 0xCE, 0xBA,
0x76, 0x0B, 0xDD, 0x2B, 0xD4, 0x09, 0x28, 0x1A
};
static unsigned char pad2[16] = {
0x2E, 0x46, 0x79, 0xB5, 0xAD, 0xD9, 0xCA, 0x75,
0x35, 0xD8, 0x7A, 0xFE, 0xAB, 0x33, 0xBE, 0xE2
};
static int test_mdc2(void)
{
int testresult = 0;
unsigned int pad_type = 2;
unsigned char md[MDC2_DIGEST_LENGTH];
EVP_MD_CTX *c = NULL;
static char text[] = "Now is the time for all ";
size_t tlen = strlen(text), i = 0;
OSSL_PROVIDER *prov = NULL;
OSSL_PARAM params[2];
params[i++] = OSSL_PARAM_construct_uint(OSSL_DIGEST_PARAM_PAD_TYPE,
&pad_type),
params[i++] = OSSL_PARAM_construct_end();
prov = OSSL_PROVIDER_load(NULL, "legacy");
if (!TEST_ptr(prov))
goto end;
# ifdef CHARSET_EBCDIC
ebcdic2ascii(text, text, tlen);
# endif
c = EVP_MD_CTX_new();
if (!TEST_ptr(c)
|| !TEST_true(EVP_DigestInit_ex(c, EVP_mdc2(), NULL))
|| !TEST_true(EVP_DigestUpdate(c, (unsigned char *)text, tlen))
|| !TEST_true(EVP_DigestFinal_ex(c, &(md[0]), NULL))
|| !TEST_mem_eq(md, MDC2_DIGEST_LENGTH, pad1, MDC2_DIGEST_LENGTH)
|| !TEST_true(EVP_DigestInit_ex(c, EVP_mdc2(), NULL)))
goto end;
if (!TEST_int_gt(EVP_MD_CTX_set_params(c, params), 0)
|| !TEST_true(EVP_DigestUpdate(c, (unsigned char *)text, tlen))
|| !TEST_true(EVP_DigestFinal_ex(c, &(md[0]), NULL))
|| !TEST_mem_eq(md, MDC2_DIGEST_LENGTH, pad2, MDC2_DIGEST_LENGTH))
goto end;
testresult = 1;
end:
EVP_MD_CTX_free(c);
OSSL_PROVIDER_unload(prov);
return testresult;
}
#endif
int setup_tests(void)
{
#ifndef OPENSSL_NO_MDC2
ADD_TEST(test_mdc2);
#endif
return 1;
}
| 2,669 | 26.244898 | 74 | c |
openssl | openssl-master/test/membio_test.c | /*
* Copyright 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/bio.h>
#include "testutil.h"
#ifndef OPENSSL_NO_DGRAM
static int test_dgram(void)
{
BIO *bio = BIO_new(BIO_s_dgram_mem()), *rbio = NULL;
int testresult = 0;
const char msg1[] = "12345656";
const char msg2[] = "abcdefghijklmno";
const char msg3[] = "ABCDEF";
const char msg4[] = "FEDCBA";
char buf[80];
if (!TEST_ptr(bio))
goto err;
rbio = BIO_new_mem_buf(msg1, sizeof(msg1));
if (!TEST_ptr(rbio))
goto err;
/* Setting the EOF return value on a non datagram mem BIO should be fine */
if (!TEST_int_gt(BIO_set_mem_eof_return(rbio, 0), 0))
goto err;
/* Setting the EOF return value on a datagram mem BIO should fail */
if (!TEST_int_le(BIO_set_mem_eof_return(bio, 0), 0))
goto err;
/* Write 4 dgrams */
if (!TEST_int_eq(BIO_write(bio, msg1, sizeof(msg1)), sizeof(msg1)))
goto err;
if (!TEST_int_eq(BIO_write(bio, msg2, sizeof(msg2)), sizeof(msg2)))
goto err;
if (!TEST_int_eq(BIO_write(bio, msg3, sizeof(msg3)), sizeof(msg3)))
goto err;
if (!TEST_int_eq(BIO_write(bio, msg4, sizeof(msg4)), sizeof(msg4)))
goto err;
/* Reading all 4 dgrams out again should all be the correct size */
if (!TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(msg1))
|| !TEST_mem_eq(buf, sizeof(msg1), msg1, sizeof(msg1))
|| !TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(msg2))
|| !TEST_mem_eq(buf, sizeof(msg2), msg2, sizeof(msg2))
|| !TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(msg3))
|| !TEST_mem_eq(buf, sizeof(msg3), msg3, sizeof(msg3))
|| !TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(msg4))
|| !TEST_mem_eq(buf, sizeof(msg4), msg4, sizeof(msg4)))
goto err;
/* Interleaving writes and reads should be fine */
if (!TEST_int_eq(BIO_write(bio, msg1, sizeof(msg1)), sizeof(msg1)))
goto err;
if (!TEST_int_eq(BIO_write(bio, msg2, sizeof(msg2)), sizeof(msg2)))
goto err;
if (!TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(msg1))
|| !TEST_mem_eq(buf, sizeof(msg1), msg1, sizeof(msg1)))
goto err;
if (!TEST_int_eq(BIO_write(bio, msg3, sizeof(msg3)), sizeof(msg3)))
goto err;
if (!TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(msg2))
|| !TEST_mem_eq(buf, sizeof(msg2), msg2, sizeof(msg2))
|| !TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(msg3))
|| !TEST_mem_eq(buf, sizeof(msg3), msg3, sizeof(msg3)))
goto err;
/*
* Requesting less than the available data in a dgram should not impact the
* next packet.
*/
if (!TEST_int_eq(BIO_write(bio, msg1, sizeof(msg1)), sizeof(msg1)))
goto err;
if (!TEST_int_eq(BIO_write(bio, msg2, sizeof(msg2)), sizeof(msg2)))
goto err;
if (!TEST_int_eq(BIO_read(bio, buf, /* Short buffer */ 2), 2)
|| !TEST_mem_eq(buf, 2, msg1, 2))
goto err;
if (!TEST_int_eq(BIO_read(bio, buf, sizeof(buf)), sizeof(msg2))
|| !TEST_mem_eq(buf, sizeof(msg2), msg2, sizeof(msg2)))
goto err;
/*
* Writing a zero length datagram will return zero, but no datagrams will
* be written. Attempting to read when there are no datagrams to read should
* return a negative result, but not eof. Retry flags will be set.
*/
if (!TEST_int_eq(BIO_write(bio, NULL, 0), 0)
|| !TEST_int_lt(BIO_read(bio, buf, sizeof(buf)), 0)
|| !TEST_false(BIO_eof(bio))
|| !TEST_true(BIO_should_retry(bio)))
goto err;
if (!TEST_int_eq(BIO_dgram_set_mtu(bio, 123456), 1)
|| !TEST_int_eq(BIO_dgram_get_mtu(bio), 123456))
goto err;
testresult = 1;
err:
BIO_free(rbio);
BIO_free(bio);
return testresult;
}
#endif
int setup_tests(void)
{
if (!test_skip_common_options()) {
TEST_error("Error parsing test options\n");
return 0;
}
#ifndef OPENSSL_NO_DGRAM
ADD_TEST(test_dgram);
#endif
return 1;
}
| 4,435 | 33.929134 | 80 | c |
openssl | openssl-master/test/memleaktest.c | /*
* Copyright 2016-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 <string.h>
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include "testutil.h"
/* __has_feature is a clang-ism, while __SANITIZE_ADDRESS__ is a gcc-ism */
#if defined(__has_feature)
# if __has_feature(address_sanitizer)
# define __SANITIZE_ADDRESS__ 1
# endif
#endif
/* If __SANITIZE_ADDRESS__ isn't defined, define it to be false */
/* Leak detection is not yet supported with MSVC on Windows, so */
/* set __SANITIZE_ADDRESS__ to false in this case as well. */
#if !defined(__SANITIZE_ADDRESS__) || defined(_MSC_VER)
# undef __SANITIZE_ADDRESS__
# define __SANITIZE_ADDRESS__ 0
#endif
/*
* We use a proper main function here instead of the custom main from the
* test framework to avoid CRYPTO_mem_leaks stuff.
*/
int main(int argc, char *argv[])
{
#if __SANITIZE_ADDRESS__
int exitcode = EXIT_SUCCESS;
#else
/*
* When we don't sanitize, we set the exit code to what we would expect
* to get when we are sanitizing. This makes it easy for wrapper scripts
* to detect that we get the result we expect.
*/
int exitcode = EXIT_FAILURE;
#endif
char *lost;
lost = OPENSSL_malloc(3);
if (!TEST_ptr(lost))
return EXIT_FAILURE;
strcpy(lost, "ab");
if (argv[1] && strcmp(argv[1], "freeit") == 0) {
OPENSSL_free(lost);
exitcode = EXIT_SUCCESS;
}
lost = NULL;
return exitcode;
}
| 1,729 | 26.460317 | 77 | c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.