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/apps/lib/vms_term_sock.c | /*
* Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright 2016 VMS Software, Inc. 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 __VMS
# define OPENSSL_SYS_VMS
# pragma message disable DOLLARID
# include <openssl/opensslconf.h>
# if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
/*
* On VMS, you need to define this to get the declaration of fileno(). The
* value 2 is to make sure no function defined in POSIX-2 is left undefined.
*/
# define _POSIX_C_SOURCE 2
# endif
# include <stdio.h>
# undef _POSIX_C_SOURCE
# include <sys/types.h>
# include <sys/socket.h>
# include <netinet/in.h>
# include <inet.h>
# include <unistd.h>
# include <string.h>
# include <errno.h>
# include <starlet.h>
# include <iodef.h>
# ifdef __alpha
# include <iosbdef.h>
# else
typedef struct _iosb { /* Copied from IOSBDEF.H for Alpha */
# pragma __nomember_alignment
__union {
__struct {
unsigned short int iosb$w_status; /* Final I/O status */
__union {
__struct { /* 16-bit byte count variant */
unsigned short int iosb$w_bcnt; /* 16-bit byte count */
__union {
unsigned int iosb$l_dev_depend; /* 32-bit device dependent info */
unsigned int iosb$l_pid; /* 32-bit pid */
} iosb$r_l;
} iosb$r_bcnt_16;
__struct { /* 32-bit byte count variant */
unsigned int iosb$l_bcnt; /* 32-bit byte count (unaligned) */
unsigned short int iosb$w_dev_depend_high; /* 16-bit device dependent info */
} iosb$r_bcnt_32;
} iosb$r_devdepend;
} iosb$r_io_64;
__struct {
__union {
unsigned int iosb$l_getxxi_status; /* Final GETxxI status */
unsigned int iosb$l_reg_status; /* Final $Registry status */
} iosb$r_l_status;
unsigned int iosb$l_reserved; /* Reserved field */
} iosb$r_get_64;
} iosb$r_io_get;
} IOSB;
# if !defined(__VAXC)
# define iosb$w_status iosb$r_io_get.iosb$r_io_64.iosb$w_status
# define iosb$w_bcnt iosb$r_io_get.iosb$r_io_64.iosb$r_devdepend.iosb$r_bcnt_16.iosb$w_bcnt
# define iosb$r_l iosb$r_io_get.iosb$r_io_64.iosb$r_devdepend.iosb$r_bcnt_16.iosb$r_l
# define iosb$l_dev_depend iosb$r_l.iosb$l_dev_depend
# define iosb$l_pid iosb$r_l.iosb$l_pid
# define iosb$l_bcnt iosb$r_io_get.iosb$r_io_64.iosb$r_devdepend.iosb$r_bcnt_32.iosb$l_bcnt
# define iosb$w_dev_depend_high iosb$r_io_get.iosb$r_io_64.iosb$r_devdepend.iosb$r_bcnt_32.iosb$w_dev_depend_high
# define iosb$l_getxxi_status iosb$r_io_get.iosb$r_get_64.iosb$r_l_status.iosb$l_getxxi_status
# define iosb$l_reg_status iosb$r_io_get.iosb$r_get_64.iosb$r_l_status.iosb$l_reg_status
# endif /* #if !defined(__VAXC) */
# endif /* End of IOSBDEF */
# include <efndef.h>
# include <stdlib.h>
# include <ssdef.h>
# include <time.h>
# include <stdarg.h>
# include <descrip.h>
# include "vms_term_sock.h"
# ifdef __alpha
static struct _iosb TerminalDeviceIosb;
# else
IOSB TerminalDeviceIosb;
# endif
static char TerminalDeviceBuff[255 + 2];
static int TerminalSocketPair[2] = {0, 0};
static unsigned short TerminalDeviceChan = 0;
static int CreateSocketPair (int, int, int, int *);
static void SocketPairTimeoutAst (int);
static int TerminalDeviceAst (int);
static void LogMessage (char *, ...);
/*
** Socket Pair Timeout Value (must be 0-59 seconds)
*/
# define SOCKET_PAIR_TIMEOUT_VALUE 20
/*
** Socket Pair Timeout Block which is passed to timeout AST
*/
typedef struct _SocketPairTimeoutBlock {
unsigned short SockChan1;
unsigned short SockChan2;
} SPTB;
# ifdef TERM_SOCK_TEST
/*----------------------------------------------------------------------------*/
/* */
/*----------------------------------------------------------------------------*/
int main (int argc, char *argv[], char *envp[])
{
char TermBuff[80];
int TermSock,
status,
len;
LogMessage ("Enter 'q' or 'Q' to quit ...");
while (OPENSSL_strcasecmp (TermBuff, "Q")) {
/*
** Create the terminal socket
*/
status = TerminalSocket (TERM_SOCK_CREATE, &TermSock);
if (status != TERM_SOCK_SUCCESS)
exit (1);
/*
** Process the terminal input
*/
LogMessage ("Waiting on terminal I/O ...\n");
len = recv (TermSock, TermBuff, sizeof(TermBuff), 0) ;
TermBuff[len] = '\0';
LogMessage ("Received terminal I/O [%s]", TermBuff);
/*
** Delete the terminal socket
*/
status = TerminalSocket (TERM_SOCK_DELETE, &TermSock);
if (status != TERM_SOCK_SUCCESS)
exit (1);
}
return 1;
}
# endif
/*----------------------------------------------------------------------------*/
/* */
/*----------------------------------------------------------------------------*/
int TerminalSocket (int FunctionCode, int *ReturnSocket)
{
int status;
$DESCRIPTOR (TerminalDeviceDesc, "SYS$COMMAND");
/*
** Process the requested function code
*/
switch (FunctionCode) {
case TERM_SOCK_CREATE:
/*
** Create a socket pair
*/
status = CreateSocketPair (AF_INET, SOCK_STREAM, 0, TerminalSocketPair);
if (status == -1) {
LogMessage ("TerminalSocket: CreateSocketPair () - %08X", status);
if (TerminalSocketPair[0])
close (TerminalSocketPair[0]);
if (TerminalSocketPair[1])
close (TerminalSocketPair[1]);
return TERM_SOCK_FAILURE;
}
/*
** Assign a channel to the terminal device
*/
status = sys$assign (&TerminalDeviceDesc,
&TerminalDeviceChan,
0, 0, 0);
if (! (status & 1)) {
LogMessage ("TerminalSocket: SYS$ASSIGN () - %08X", status);
close (TerminalSocketPair[0]);
close (TerminalSocketPair[1]);
return TERM_SOCK_FAILURE;
}
/*
** Queue an async IO to the terminal device
*/
status = sys$qio (EFN$C_ENF,
TerminalDeviceChan,
IO$_READVBLK,
&TerminalDeviceIosb,
TerminalDeviceAst,
0,
TerminalDeviceBuff,
sizeof(TerminalDeviceBuff) - 2,
0, 0, 0, 0);
if (! (status & 1)) {
LogMessage ("TerminalSocket: SYS$QIO () - %08X", status);
close (TerminalSocketPair[0]);
close (TerminalSocketPair[1]);
return TERM_SOCK_FAILURE;
}
/*
** Return the input side of the socket pair
*/
*ReturnSocket = TerminalSocketPair[1];
break;
case TERM_SOCK_DELETE:
/*
** Cancel any pending IO on the terminal channel
*/
status = sys$cancel (TerminalDeviceChan);
if (! (status & 1)) {
LogMessage ("TerminalSocket: SYS$CANCEL () - %08X", status);
close (TerminalSocketPair[0]);
close (TerminalSocketPair[1]);
return TERM_SOCK_FAILURE;
}
/*
** Deassign the terminal channel
*/
status = sys$dassgn (TerminalDeviceChan);
if (! (status & 1)) {
LogMessage ("TerminalSocket: SYS$DASSGN () - %08X", status);
close (TerminalSocketPair[0]);
close (TerminalSocketPair[1]);
return TERM_SOCK_FAILURE;
}
/*
** Close the terminal socket pair
*/
close (TerminalSocketPair[0]);
close (TerminalSocketPair[1]);
/*
** Return the initialized socket
*/
*ReturnSocket = 0;
break;
default:
/*
** Invalid function code
*/
LogMessage ("TerminalSocket: Invalid Function Code - %d", FunctionCode);
return TERM_SOCK_FAILURE;
break;
}
/*
** Return success
*/
return TERM_SOCK_SUCCESS;
}
/*----------------------------------------------------------------------------*/
/* */
/*----------------------------------------------------------------------------*/
static int CreateSocketPair (int SocketFamily,
int SocketType,
int SocketProtocol,
int *SocketPair)
{
struct dsc$descriptor AscTimeDesc = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, NULL};
static const char* LocalHostAddr = {"127.0.0.1"};
unsigned short TcpAcceptChan = 0,
TcpDeviceChan = 0;
unsigned long BinTimeBuff[2];
struct sockaddr_in sin;
char AscTimeBuff[32];
short LocalHostPort;
int status;
unsigned int slen;
# ifdef __alpha
struct _iosb iosb;
# else
IOSB iosb;
# endif
int SockDesc1 = 0,
SockDesc2 = 0;
SPTB sptb;
$DESCRIPTOR (TcpDeviceDesc, "TCPIP$DEVICE");
/*
** Create a socket
*/
SockDesc1 = socket (SocketFamily, SocketType, 0);
if (SockDesc1 < 0) {
LogMessage ("CreateSocketPair: socket () - %d", errno);
return -1;
}
/*
** Initialize the socket information
*/
slen = sizeof(sin);
memset ((char *) &sin, 0, slen);
sin.sin_family = SocketFamily;
sin.sin_addr.s_addr = inet_addr (LocalHostAddr);
sin.sin_port = 0;
/*
** Bind the socket to the local IP
*/
status = bind (SockDesc1, (struct sockaddr *) &sin, slen);
if (status < 0) {
LogMessage ("CreateSocketPair: bind () - %d", errno);
close (SockDesc1);
return -1;
}
/*
** Get the socket name so we can save the port number
*/
status = getsockname (SockDesc1, (struct sockaddr *) &sin, &slen);
if (status < 0) {
LogMessage ("CreateSocketPair: getsockname () - %d", errno);
close (SockDesc1);
return -1;
} else
LocalHostPort = sin.sin_port;
/*
** Setup a listen for the socket
*/
listen (SockDesc1, 5);
/*
** Get the binary (64-bit) time of the specified timeout value
*/
sprintf (AscTimeBuff, "0 0:0:%02d.00", SOCKET_PAIR_TIMEOUT_VALUE);
AscTimeDesc.dsc$w_length = strlen (AscTimeBuff);
AscTimeDesc.dsc$a_pointer = AscTimeBuff;
status = sys$bintim (&AscTimeDesc, BinTimeBuff);
if (! (status & 1)) {
LogMessage ("CreateSocketPair: SYS$BINTIM () - %08X", status);
close (SockDesc1);
return -1;
}
/*
** Assign another channel to the TCP/IP device for the accept.
** This is the channel that ends up being connected to.
*/
status = sys$assign (&TcpDeviceDesc, &TcpDeviceChan, 0, 0, 0);
if (! (status & 1)) {
LogMessage ("CreateSocketPair: SYS$ASSIGN () - %08X", status);
close (SockDesc1);
return -1;
}
/*
** Get the channel of the first socket for the accept
*/
TcpAcceptChan = decc$get_sdc (SockDesc1);
/*
** Perform the accept using $QIO so we can do this asynchronously
*/
status = sys$qio (EFN$C_ENF,
TcpAcceptChan,
IO$_ACCESS | IO$M_ACCEPT,
&iosb,
0, 0, 0, 0, 0,
&TcpDeviceChan,
0, 0);
if (! (status & 1)) {
LogMessage ("CreateSocketPair: SYS$QIO () - %08X", status);
close (SockDesc1);
sys$dassgn (TcpDeviceChan);
return -1;
}
/*
** Create the second socket to do the connect
*/
SockDesc2 = socket (SocketFamily, SocketType, 0);
if (SockDesc2 < 0) {
LogMessage ("CreateSocketPair: socket () - %d", errno);
sys$cancel (TcpAcceptChan);
close (SockDesc1);
sys$dassgn (TcpDeviceChan);
return (-1) ;
}
/*
** Setup the Socket Pair Timeout Block
*/
sptb.SockChan1 = TcpAcceptChan;
sptb.SockChan2 = decc$get_sdc (SockDesc2);
/*
** Before we block on the connect, set a timer that can cancel I/O on our
** two sockets if it never connects.
*/
status = sys$setimr (EFN$C_ENF,
BinTimeBuff,
SocketPairTimeoutAst,
&sptb,
0);
if (! (status & 1)) {
LogMessage ("CreateSocketPair: SYS$SETIMR () - %08X", status);
sys$cancel (TcpAcceptChan);
close (SockDesc1);
close (SockDesc2);
sys$dassgn (TcpDeviceChan);
return -1;
}
/*
** Now issue the connect
*/
memset ((char *) &sin, 0, sizeof(sin)) ;
sin.sin_family = SocketFamily;
sin.sin_addr.s_addr = inet_addr (LocalHostAddr) ;
sin.sin_port = LocalHostPort ;
status = connect (SockDesc2, (struct sockaddr *) &sin, sizeof(sin));
if (status < 0) {
LogMessage ("CreateSocketPair: connect () - %d", errno);
sys$cantim (&sptb, 0);
sys$cancel (TcpAcceptChan);
close (SockDesc1);
close (SockDesc2);
sys$dassgn (TcpDeviceChan);
return -1;
}
/*
** Wait for the asynch $QIO to finish. Note that if the I/O was aborted
** (SS$_ABORT), then we probably canceled it from the AST routine - so log
** a timeout.
*/
status = sys$synch (EFN$C_ENF, &iosb);
if (! (iosb.iosb$w_status & 1)) {
if (iosb.iosb$w_status == SS$_ABORT)
LogMessage ("CreateSocketPair: SYS$QIO(iosb) timeout");
else {
LogMessage ("CreateSocketPair: SYS$QIO(iosb) - %d",
iosb.iosb$w_status);
sys$cantim (&sptb, 0);
}
close (SockDesc1);
close (SockDesc2);
sys$dassgn (TcpDeviceChan);
return -1;
}
/*
** Here we're successfully connected, so cancel the timer, convert the
** I/O channel to a socket fd, close the listener socket and return the
** connected pair.
*/
sys$cantim (&sptb, 0);
close (SockDesc1) ;
SocketPair[0] = SockDesc2 ;
SocketPair[1] = socket_fd (TcpDeviceChan);
return (0) ;
}
/*----------------------------------------------------------------------------*/
/* */
/*----------------------------------------------------------------------------*/
static void SocketPairTimeoutAst (int astparm)
{
SPTB *sptb = (SPTB *) astparm;
sys$cancel (sptb->SockChan2); /* Cancel the connect() */
sys$cancel (sptb->SockChan1); /* Cancel the accept() */
return;
}
/*----------------------------------------------------------------------------*/
/* */
/*----------------------------------------------------------------------------*/
static int TerminalDeviceAst (int astparm)
{
int status;
/*
** Terminate the terminal buffer
*/
TerminalDeviceBuff[TerminalDeviceIosb.iosb$w_bcnt] = '\0';
strcat (TerminalDeviceBuff, "\n");
/*
** Send the data read from the terminal device through the socket pair
*/
send (TerminalSocketPair[0], TerminalDeviceBuff,
TerminalDeviceIosb.iosb$w_bcnt + 1, 0);
/*
** Queue another async IO to the terminal device
*/
status = sys$qio (EFN$C_ENF,
TerminalDeviceChan,
IO$_READVBLK,
&TerminalDeviceIosb,
TerminalDeviceAst,
0,
TerminalDeviceBuff,
sizeof(TerminalDeviceBuff) - 1,
0, 0, 0, 0);
/*
** Return status
*/
return status;
}
/*----------------------------------------------------------------------------*/
/* */
/*----------------------------------------------------------------------------*/
static void LogMessage (char *msg, ...)
{
char *Month[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
static unsigned int pid = 0;
va_list args;
time_t CurTime;
struct tm *LocTime;
char MsgBuff[256];
/*
** Get the process pid
*/
if (pid == 0)
pid = getpid ();
/*
** Convert the current time into local time
*/
CurTime = time (NULL);
LocTime = localtime (&CurTime);
/*
** Format the message buffer
*/
sprintf (MsgBuff, "%02d-%s-%04d %02d:%02d:%02d [%08X] %s\n",
LocTime->tm_mday, Month[LocTime->tm_mon],
(LocTime->tm_year + 1900), LocTime->tm_hour, LocTime->tm_min,
LocTime->tm_sec, pid, msg);
/*
** Get any variable arguments and add them to the print of the message
** buffer
*/
va_start (args, msg);
vfprintf (stderr, MsgBuff, args);
va_end (args);
/*
** Flush standard error output
*/
fsync (fileno (stderr));
return;
}
#endif
| 17,784 | 29.04223 | 115 | c |
openssl | openssl-master/apps/lib/win32_init.c | /*
* Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#if defined(CP_UTF8)
static UINT saved_cp;
static int newargc;
static char **newargv;
static void cleanup(void)
{
int i;
SetConsoleOutputCP(saved_cp);
for (i = 0; i < newargc; i++)
free(newargv[i]);
free(newargv);
}
/*
* Incrementally [re]allocate newargv and keep it NULL-terminated.
*/
static int validate_argv(int argc)
{
static int size = 0;
if (argc >= size) {
char **ptr;
while (argc >= size)
size += 64;
ptr = realloc(newargv, size * sizeof(newargv[0]));
if (ptr == NULL)
return 0;
(newargv = ptr)[argc] = NULL;
} else {
newargv[argc] = NULL;
}
return 1;
}
static int process_glob(WCHAR *wstr, int wlen)
{
int i, slash, udlen;
WCHAR saved_char;
WIN32_FIND_DATAW data;
HANDLE h;
/*
* Note that we support wildcard characters only in filename part
* of the path, and not in directories. Windows users are used to
* this, that's why recursive glob processing is not implemented.
*/
/*
* Start by looking for last slash or backslash, ...
*/
for (slash = 0, i = 0; i < wlen; i++)
if (wstr[i] == L'/' || wstr[i] == L'\\')
slash = i + 1;
/*
* ... then look for asterisk or question mark in the file name.
*/
for (i = slash; i < wlen; i++)
if (wstr[i] == L'*' || wstr[i] == L'?')
break;
if (i == wlen)
return 0; /* definitely not a glob */
saved_char = wstr[wlen];
wstr[wlen] = L'\0';
h = FindFirstFileW(wstr, &data);
wstr[wlen] = saved_char;
if (h == INVALID_HANDLE_VALUE)
return 0; /* not a valid glob, just pass... */
if (slash)
udlen = WideCharToMultiByte(CP_UTF8, 0, wstr, slash,
NULL, 0, NULL, NULL);
else
udlen = 0;
do {
int uflen;
char *arg;
/*
* skip over . and ..
*/
if (data.cFileName[0] == L'.') {
if ((data.cFileName[1] == L'\0') ||
(data.cFileName[1] == L'.' && data.cFileName[2] == L'\0'))
continue;
}
if (!validate_argv(newargc + 1))
break;
/*
* -1 below means "scan for trailing '\0' *and* count it",
* so that |uflen| covers even trailing '\0'.
*/
uflen = WideCharToMultiByte(CP_UTF8, 0, data.cFileName, -1,
NULL, 0, NULL, NULL);
arg = malloc(udlen + uflen);
if (arg == NULL)
break;
if (udlen)
WideCharToMultiByte(CP_UTF8, 0, wstr, slash,
arg, udlen, NULL, NULL);
WideCharToMultiByte(CP_UTF8, 0, data.cFileName, -1,
arg + udlen, uflen, NULL, NULL);
newargv[newargc++] = arg;
} while (FindNextFileW(h, &data));
CloseHandle(h);
return 1;
}
void win32_utf8argv(int *argc, char **argv[])
{
const WCHAR *wcmdline;
WCHAR *warg, *wend, *p;
int wlen, ulen, valid = 1;
char *arg;
if (GetEnvironmentVariableW(L"OPENSSL_WIN32_UTF8", NULL, 0) == 0)
return;
newargc = 0;
newargv = NULL;
if (!validate_argv(newargc))
return;
wcmdline = GetCommandLineW();
if (wcmdline == NULL) return;
/*
* make a copy of the command line, since we might have to modify it...
*/
wlen = wcslen(wcmdline);
p = _alloca((wlen + 1) * sizeof(WCHAR));
wcscpy(p, wcmdline);
while (*p != L'\0') {
int in_quote = 0;
if (*p == L' ' || *p == L'\t') {
p++; /* skip over whitespace */
continue;
}
/*
* Note: because we may need to fiddle with the number of backslashes,
* the argument string is copied into itself. This is safe because
* the number of characters will never expand.
*/
warg = wend = p;
while (*p != L'\0'
&& (in_quote || (*p != L' ' && *p != L'\t'))) {
switch (*p) {
case L'\\':
/*
* Microsoft documentation on how backslashes are treated
* is:
*
* + Backslashes are interpreted literally, unless they
* immediately precede a double quotation mark.
* + If an even number of backslashes is followed by a double
* quotation mark, one backslash is placed in the argv array
* for every pair of backslashes, and the double quotation
* mark is interpreted as a string delimiter.
* + If an odd number of backslashes is followed by a double
* quotation mark, one backslash is placed in the argv array
* for every pair of backslashes, and the double quotation
* mark is "escaped" by the remaining backslash, causing a
* literal double quotation mark (") to be placed in argv.
*
* Ref: https://msdn.microsoft.com/en-us/library/17w5ykft.aspx
*
* Though referred page doesn't mention it, multiple qouble
* quotes are also special. Pair of double quotes in quoted
* string is counted as single double quote.
*/
{
const WCHAR *q = p;
int i;
while (*p == L'\\')
p++;
if (*p == L'"') {
int i;
for (i = (p - q) / 2; i > 0; i--)
*wend++ = L'\\';
/*
* if odd amount of backslashes before the quote,
* said quote is part of the argument, not a delimiter
*/
if ((p - q) % 2 == 1)
*wend++ = *p++;
} else {
for (i = p - q; i > 0; i--)
*wend++ = L'\\';
}
}
break;
case L'"':
/*
* Without the preceding backslash (or when preceded with an
* even number of backslashes), the double quote is a simple
* string delimiter and just slightly change the parsing state
*/
if (in_quote && p[1] == L'"')
*wend++ = *p++;
else
in_quote = !in_quote;
p++;
break;
default:
/*
* Any other non-delimiter character is just taken verbatim
*/
*wend++ = *p++;
}
}
wlen = wend - warg;
if (wlen == 0 || !process_glob(warg, wlen)) {
if (!validate_argv(newargc + 1)) {
valid = 0;
break;
}
ulen = 0;
if (wlen > 0) {
ulen = WideCharToMultiByte(CP_UTF8, 0, warg, wlen,
NULL, 0, NULL, NULL);
if (ulen <= 0)
continue;
}
arg = malloc(ulen + 1);
if (arg == NULL) {
valid = 0;
break;
}
if (wlen > 0)
WideCharToMultiByte(CP_UTF8, 0, warg, wlen,
arg, ulen, NULL, NULL);
arg[ulen] = '\0';
newargv[newargc++] = arg;
}
}
if (valid) {
saved_cp = GetConsoleOutputCP();
SetConsoleOutputCP(CP_UTF8);
*argc = newargc;
*argv = newargv;
atexit(cleanup);
} else if (newargv != NULL) {
int i;
for (i = 0; i < newargc; i++)
free(newargv[i]);
free(newargv);
newargc = 0;
newargv = NULL;
}
return;
}
#else
void win32_utf8argv(int *argc, char **argv[])
{ return; }
#endif
| 8,608 | 26.951299 | 78 | c |
openssl | openssl-master/crypto/LPdir_nyi.c | /*
* Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* This file is dual-licensed and is also available under the following
* terms:
*
* Copyright (c) 2004, Richard Levitte <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef LPDIR_H
# include "LPdir.h"
#endif
struct LP_dir_context_st {
void *dummy;
};
const char *LP_find_file(LP_DIR_CTX **ctx, const char *directory)
{
errno = EINVAL;
return 0;
}
int LP_find_file_end(LP_DIR_CTX **ctx)
{
errno = EINVAL;
return 0;
}
| 2,077 | 35.45614 | 77 | c |
openssl | openssl-master/crypto/LPdir_unix.c | /*
* Copyright 2004-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* This file is dual-licensed and is also available under the following
* terms:
*
* Copyright (c) 2004, 2018, Richard Levitte <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stddef.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#ifndef LPDIR_H
# include "LPdir.h"
#endif
#ifdef __VMS
# include <ctype.h>
#endif
/*
* The POSIX macro for the maximum number of characters in a file path is
* NAME_MAX. However, some operating systems use PATH_MAX instead.
* Therefore, it seems natural to first check for PATH_MAX and use that, and
* if it doesn't exist, use NAME_MAX.
*/
#if defined(PATH_MAX)
# define LP_ENTRY_SIZE PATH_MAX
#elif defined(NAME_MAX)
# define LP_ENTRY_SIZE NAME_MAX
#endif
/*
* Of course, there's the possibility that neither PATH_MAX nor NAME_MAX
* exist. It's also possible that NAME_MAX exists but is define to a very
* small value (HP-UX offers 14), so we need to check if we got a result, and
* if it meets a minimum standard, and create or change it if not.
*/
#if !defined(LP_ENTRY_SIZE) || LP_ENTRY_SIZE<255
# undef LP_ENTRY_SIZE
# define LP_ENTRY_SIZE 255
#endif
struct LP_dir_context_st {
DIR *dir;
char entry_name[LP_ENTRY_SIZE + 1];
#ifdef __VMS
int expect_file_generations;
char previous_entry_name[LP_ENTRY_SIZE + 1];
#endif
};
const char *LP_find_file(LP_DIR_CTX **ctx, const char *directory)
{
struct dirent *direntry = NULL;
if (ctx == NULL || directory == NULL) {
errno = EINVAL;
return 0;
}
errno = 0;
if (*ctx == NULL) {
*ctx = malloc(sizeof(**ctx));
if (*ctx == NULL) {
errno = ENOMEM;
return 0;
}
memset(*ctx, 0, sizeof(**ctx));
#ifdef __VMS
{
char c = directory[strlen(directory) - 1];
if (c == ']' || c == '>' || c == ':')
(*ctx)->expect_file_generations = 1;
}
#endif
(*ctx)->dir = opendir(directory);
if ((*ctx)->dir == NULL) {
int save_errno = errno; /* Probably not needed, but I'm paranoid */
free(*ctx);
*ctx = NULL;
errno = save_errno;
return 0;
}
}
#ifdef __VMS
strncpy((*ctx)->previous_entry_name, (*ctx)->entry_name,
sizeof((*ctx)->previous_entry_name));
again:
#endif
direntry = readdir((*ctx)->dir);
if (direntry == NULL) {
return 0;
}
OPENSSL_strlcpy((*ctx)->entry_name, direntry->d_name,
sizeof((*ctx)->entry_name));
#ifdef __VMS
if ((*ctx)->expect_file_generations) {
char *p = (*ctx)->entry_name + strlen((*ctx)->entry_name);
while (p > (*ctx)->entry_name && isdigit((unsigned char)p[-1]))
p--;
if (p > (*ctx)->entry_name && p[-1] == ';')
p[-1] = '\0';
if (OPENSSL_strcasecmp((*ctx)->entry_name,
(*ctx)->previous_entry_name) == 0)
goto again;
}
#endif
return (*ctx)->entry_name;
}
int LP_find_file_end(LP_DIR_CTX **ctx)
{
if (ctx != NULL && *ctx != NULL) {
int ret = closedir((*ctx)->dir);
free(*ctx);
switch (ret) {
case 0:
return 1;
case -1:
return 0;
default:
break;
}
}
errno = EINVAL;
return 0;
}
| 5,056 | 28.747059 | 79 | c |
openssl | openssl-master/crypto/LPdir_vms.c | /*
* Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* This file is dual-licensed and is also available under the following
* terms:
*
* Copyright (c) 2004, Richard Levitte <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <descrip.h>
#include <namdef.h>
#include <rmsdef.h>
#include <libfildef.h>
#include <lib$routines.h>
#include <strdef.h>
#include <str$routines.h>
#include <stsdef.h>
#ifndef LPDIR_H
# include "LPdir.h"
#endif
#include "vms_rms.h"
/* Some compiler options hide EVMSERR. */
#ifndef EVMSERR
# define EVMSERR 65535 /* error for non-translatable VMS errors */
#endif
struct LP_dir_context_st {
unsigned long VMS_context;
char filespec[NAMX_MAXRSS + 1];
char result[NAMX_MAXRSS + 1];
struct dsc$descriptor_d filespec_dsc;
struct dsc$descriptor_d result_dsc;
};
const char *LP_find_file(LP_DIR_CTX **ctx, const char *directory)
{
int status;
char *p, *r;
size_t l;
unsigned long flags = 0;
/* Arrange 32-bit pointer to (copied) string storage, if needed. */
#if __INITIAL_POINTER_SIZE == 64
# pragma pointer_size save
# pragma pointer_size 32
char *ctx_filespec_32p;
# pragma pointer_size restore
char ctx_filespec_32[NAMX_MAXRSS + 1];
#endif /* __INITIAL_POINTER_SIZE == 64 */
#ifdef NAML$C_MAXRSS
flags |= LIB$M_FIL_LONG_NAMES;
#endif
if (ctx == NULL || directory == NULL) {
errno = EINVAL;
return 0;
}
errno = 0;
if (*ctx == NULL) {
size_t filespeclen = strlen(directory);
char *filespec = NULL;
if (filespeclen == 0) {
errno = ENOENT;
return 0;
}
/* MUST be a VMS directory specification! Let's estimate if it is. */
if (directory[filespeclen - 1] != ']'
&& directory[filespeclen - 1] != '>'
&& directory[filespeclen - 1] != ':') {
errno = EINVAL;
return 0;
}
filespeclen += 4; /* "*.*;" */
if (filespeclen > NAMX_MAXRSS) {
errno = ENAMETOOLONG;
return 0;
}
*ctx = malloc(sizeof(**ctx));
if (*ctx == NULL) {
errno = ENOMEM;
return 0;
}
memset(*ctx, 0, sizeof(**ctx));
strcpy((*ctx)->filespec, directory);
strcat((*ctx)->filespec, "*.*;");
/* Arrange 32-bit pointer to (copied) string storage, if needed. */
#if __INITIAL_POINTER_SIZE == 64
# define CTX_FILESPEC ctx_filespec_32p
/* Copy the file name to storage with a 32-bit pointer. */
ctx_filespec_32p = ctx_filespec_32;
strcpy(ctx_filespec_32p, (*ctx)->filespec);
#else /* __INITIAL_POINTER_SIZE == 64 */
# define CTX_FILESPEC (*ctx)->filespec
#endif /* __INITIAL_POINTER_SIZE == 64 [else] */
(*ctx)->filespec_dsc.dsc$w_length = filespeclen;
(*ctx)->filespec_dsc.dsc$b_dtype = DSC$K_DTYPE_T;
(*ctx)->filespec_dsc.dsc$b_class = DSC$K_CLASS_S;
(*ctx)->filespec_dsc.dsc$a_pointer = CTX_FILESPEC;
}
(*ctx)->result_dsc.dsc$w_length = 0;
(*ctx)->result_dsc.dsc$b_dtype = DSC$K_DTYPE_T;
(*ctx)->result_dsc.dsc$b_class = DSC$K_CLASS_D;
(*ctx)->result_dsc.dsc$a_pointer = 0;
status = lib$find_file(&(*ctx)->filespec_dsc, &(*ctx)->result_dsc,
&(*ctx)->VMS_context, 0, 0, 0, &flags);
if (status == RMS$_NMF) {
errno = 0;
vaxc$errno = status;
return NULL;
}
if (!$VMS_STATUS_SUCCESS(status)) {
errno = EVMSERR;
vaxc$errno = status;
return NULL;
}
/*
* Quick, cheap and dirty way to discard any device and directory, since
* we only want file names
*/
l = (*ctx)->result_dsc.dsc$w_length;
p = (*ctx)->result_dsc.dsc$a_pointer;
r = p;
for (; *p; p++) {
if (*p == '^' && p[1] != '\0') { /* Take care of ODS-5 escapes */
p++;
} else if (*p == ':' || *p == '>' || *p == ']') {
l -= p + 1 - r;
r = p + 1;
} else if (*p == ';') {
l = p - r;
break;
}
}
strncpy((*ctx)->result, r, l);
(*ctx)->result[l] = '\0';
str$free1_dx(&(*ctx)->result_dsc);
return (*ctx)->result;
}
int LP_find_file_end(LP_DIR_CTX **ctx)
{
if (ctx != NULL && *ctx != NULL) {
int status = lib$find_file_end(&(*ctx)->VMS_context);
free(*ctx);
if (!$VMS_STATUS_SUCCESS(status)) {
errno = EVMSERR;
vaxc$errno = status;
return 0;
}
return 1;
}
errno = EINVAL;
return 0;
}
| 6,334 | 29.456731 | 78 | c |
openssl | openssl-master/crypto/LPdir_win.c | /*
* Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* This file is dual-licensed and is also available under the following
* terms:
*
* Copyright (c) 2004, Richard Levitte <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <windows.h>
#include <tchar.h>
#include "internal/numbers.h"
#ifndef LPDIR_H
# include "LPdir.h"
#endif
/*
* We're most likely overcautious here, but let's reserve for broken WinCE
* headers and explicitly opt for UNICODE call. Keep in mind that our WinCE
* builds are compiled with -DUNICODE [as well as -D_UNICODE].
*/
#if defined(LP_SYS_WINCE) && !defined(FindFirstFile)
# define FindFirstFile FindFirstFileW
#endif
#if defined(LP_SYS_WINCE) && !defined(FindNextFile)
# define FindNextFile FindNextFileW
#endif
#ifndef NAME_MAX
# define NAME_MAX 255
#endif
#ifdef CP_UTF8
# define CP_DEFAULT CP_UTF8
#else
# define CP_DEFAULT CP_ACP
#endif
struct LP_dir_context_st {
WIN32_FIND_DATA ctx;
HANDLE handle;
char entry_name[NAME_MAX + 1];
};
const char *LP_find_file(LP_DIR_CTX **ctx, const char *directory)
{
if (ctx == NULL || directory == NULL) {
errno = EINVAL;
return 0;
}
errno = 0;
if (*ctx == NULL) {
size_t dirlen = strlen(directory);
if (dirlen == 0 || dirlen > INT_MAX - 3) {
errno = ENOENT;
return 0;
}
*ctx = malloc(sizeof(**ctx));
if (*ctx == NULL) {
errno = ENOMEM;
return 0;
}
memset(*ctx, 0, sizeof(**ctx));
if (sizeof(TCHAR) != sizeof(char)) {
TCHAR *wdir = NULL;
/* len_0 denotes string length *with* trailing 0 */
size_t index = 0, len_0 = dirlen + 1;
#ifdef LP_MULTIBYTE_AVAILABLE
int sz = 0;
UINT cp;
do {
# ifdef CP_UTF8
if ((sz = MultiByteToWideChar((cp = CP_UTF8), 0,
directory, len_0,
NULL, 0)) > 0 ||
GetLastError() != ERROR_NO_UNICODE_TRANSLATION)
break;
# endif
sz = MultiByteToWideChar((cp = CP_ACP), 0,
directory, len_0,
NULL, 0);
} while (0);
if (sz > 0) {
/*
* allocate two additional characters in case we need to
* concatenate asterisk, |sz| covers trailing '\0'!
*/
wdir = _alloca((sz + 2) * sizeof(TCHAR));
if (!MultiByteToWideChar(cp, 0, directory, len_0,
(WCHAR *)wdir, sz)) {
free(*ctx);
*ctx = NULL;
errno = EINVAL;
return 0;
}
} else
#endif
{
sz = len_0;
/*
* allocate two additional characters in case we need to
* concatenate asterisk, |sz| covers trailing '\0'!
*/
wdir = _alloca((sz + 2) * sizeof(TCHAR));
for (index = 0; index < len_0; index++)
wdir[index] = (TCHAR)directory[index];
}
sz--; /* wdir[sz] is trailing '\0' now */
if (wdir[sz - 1] != TEXT('*')) {
if (wdir[sz - 1] != TEXT('/') && wdir[sz - 1] != TEXT('\\'))
_tcscpy(wdir + sz, TEXT("/*"));
else
_tcscpy(wdir + sz, TEXT("*"));
}
(*ctx)->handle = FindFirstFile(wdir, &(*ctx)->ctx);
} else {
if (directory[dirlen - 1] != '*') {
char *buf = _alloca(dirlen + 3);
strcpy(buf, directory);
if (buf[dirlen - 1] != '/' && buf[dirlen - 1] != '\\')
strcpy(buf + dirlen, "/*");
else
strcpy(buf + dirlen, "*");
directory = buf;
}
(*ctx)->handle = FindFirstFile((TCHAR *)directory, &(*ctx)->ctx);
}
if ((*ctx)->handle == INVALID_HANDLE_VALUE) {
free(*ctx);
*ctx = NULL;
errno = EINVAL;
return 0;
}
} else {
if (FindNextFile((*ctx)->handle, &(*ctx)->ctx) == FALSE) {
return 0;
}
}
if (sizeof(TCHAR) != sizeof(char)) {
TCHAR *wdir = (*ctx)->ctx.cFileName;
size_t index, len_0 = 0;
while (wdir[len_0] && len_0 < (sizeof((*ctx)->entry_name) - 1))
len_0++;
len_0++;
#ifdef LP_MULTIBYTE_AVAILABLE
if (!WideCharToMultiByte(CP_DEFAULT, 0, (WCHAR *)wdir, len_0,
(*ctx)->entry_name,
sizeof((*ctx)->entry_name), NULL, 0))
#endif
for (index = 0; index < len_0; index++)
(*ctx)->entry_name[index] = (char)wdir[index];
} else
strncpy((*ctx)->entry_name, (const char *)(*ctx)->ctx.cFileName,
sizeof((*ctx)->entry_name) - 1);
(*ctx)->entry_name[sizeof((*ctx)->entry_name) - 1] = '\0';
return (*ctx)->entry_name;
}
int LP_find_file_end(LP_DIR_CTX **ctx)
{
if (ctx != NULL && *ctx != NULL) {
FindClose((*ctx)->handle);
free(*ctx);
*ctx = NULL;
return 1;
}
errno = EINVAL;
return 0;
}
| 7,047 | 31.781395 | 77 | c |
openssl | openssl-master/crypto/LPdir_win32.c | /*
* Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* This file is dual-licensed and is also available under the following
* terms:
*
* Copyright (c) 2004, Richard Levitte <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define LP_SYS_WIN32
#define LP_MULTIBYTE_AVAILABLE
#include "LPdir_win.c"
| 1,896 | 44.166667 | 74 | c |
openssl | openssl-master/crypto/LPdir_wince.c | /*
* Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* This file is dual-licensed and is also available under the following
* terms:
*
* Copyright (c) 2004, Richard Levitte <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define LP_SYS_WINCE
/*
* We might want to define LP_MULTIBYTE_AVAILABLE here. It's currently under
* investigation what the exact conditions would be
*/
#include "LPdir_win.c"
| 2,002 | 43.511111 | 77 | c |
openssl | openssl-master/crypto/arm_arch.h | /*
* Copyright 2011-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_CRYPTO_ARM_ARCH_H
# define OSSL_CRYPTO_ARM_ARCH_H
# if !defined(__ARM_ARCH__)
# if defined(__CC_ARM)
# define __ARM_ARCH__ __TARGET_ARCH_ARM
# if defined(__BIG_ENDIAN)
# define __ARMEB__
# else
# define __ARMEL__
# endif
# elif defined(__GNUC__)
# if defined(__aarch64__)
# define __ARM_ARCH__ 8
/*
* Why doesn't gcc define __ARM_ARCH__? Instead it defines
* bunch of below macros. See all_architectures[] table in
* gcc/config/arm/arm.c. On a side note it defines
* __ARMEL__/__ARMEB__ for little-/big-endian.
*/
# elif defined(__ARM_ARCH)
# define __ARM_ARCH__ __ARM_ARCH
# elif defined(__ARM_ARCH_8A__)
# define __ARM_ARCH__ 8
# elif defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || \
defined(__ARM_ARCH_7R__)|| defined(__ARM_ARCH_7M__) || \
defined(__ARM_ARCH_7EM__)
# define __ARM_ARCH__ 7
# elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || \
defined(__ARM_ARCH_6K__)|| defined(__ARM_ARCH_6M__) || \
defined(__ARM_ARCH_6Z__)|| defined(__ARM_ARCH_6ZK__) || \
defined(__ARM_ARCH_6T2__)
# define __ARM_ARCH__ 6
# elif defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5T__) || \
defined(__ARM_ARCH_5E__)|| defined(__ARM_ARCH_5TE__) || \
defined(__ARM_ARCH_5TEJ__)
# define __ARM_ARCH__ 5
# elif defined(__ARM_ARCH_4__) || defined(__ARM_ARCH_4T__)
# define __ARM_ARCH__ 4
# else
# error "unsupported ARM architecture"
# endif
# endif
# endif
# if !defined(__ARM_MAX_ARCH__)
# define __ARM_MAX_ARCH__ __ARM_ARCH__
# endif
# if __ARM_MAX_ARCH__<__ARM_ARCH__
# error "__ARM_MAX_ARCH__ can't be less than __ARM_ARCH__"
# elif __ARM_MAX_ARCH__!=__ARM_ARCH__
# if __ARM_ARCH__<7 && __ARM_MAX_ARCH__>=7 && defined(__ARMEB__)
# error "can't build universal big-endian binary"
# endif
# endif
# ifndef __ASSEMBLER__
extern unsigned int OPENSSL_armcap_P;
extern unsigned int OPENSSL_arm_midr;
extern unsigned int OPENSSL_armv8_rsa_neonized;
# endif
# define ARMV7_NEON (1<<0)
# define ARMV7_TICK (1<<1)
# define ARMV8_AES (1<<2)
# define ARMV8_SHA1 (1<<3)
# define ARMV8_SHA256 (1<<4)
# define ARMV8_PMULL (1<<5)
# define ARMV8_SHA512 (1<<6)
# define ARMV8_CPUID (1<<7)
# define ARMV8_RNG (1<<8)
# define ARMV8_SM3 (1<<9)
# define ARMV8_SM4 (1<<10)
# define ARMV8_SHA3 (1<<11)
# define ARMV8_UNROLL8_EOR3 (1<<12)
# define ARMV8_SVE (1<<13)
# define ARMV8_SVE2 (1<<14)
/*
* MIDR_EL1 system register
*
* 63___ _ ___32_31___ _ ___24_23_____20_19_____16_15__ _ __4_3_______0
* | | | | | | |
* |RES0 | Implementer | Variant | Arch | PartNum |Revision|
* |____ _ _____|_____ _ _____|_________|_______ _|____ _ ___|________|
*
*/
# define ARM_CPU_IMP_ARM 0x41
# define HISI_CPU_IMP 0x48
# define ARM_CPU_PART_CORTEX_A72 0xD08
# define ARM_CPU_PART_N1 0xD0C
# define ARM_CPU_PART_V1 0xD40
# define ARM_CPU_PART_N2 0xD49
# define HISI_CPU_PART_KP920 0xD01
# define ARM_CPU_PART_V2 0xD4F
# define MIDR_PARTNUM_SHIFT 4
# define MIDR_PARTNUM_MASK (0xfffU << MIDR_PARTNUM_SHIFT)
# define MIDR_PARTNUM(midr) \
(((midr) & MIDR_PARTNUM_MASK) >> MIDR_PARTNUM_SHIFT)
# define MIDR_IMPLEMENTER_SHIFT 24
# define MIDR_IMPLEMENTER_MASK (0xffU << MIDR_IMPLEMENTER_SHIFT)
# define MIDR_IMPLEMENTER(midr) \
(((midr) & MIDR_IMPLEMENTER_MASK) >> MIDR_IMPLEMENTER_SHIFT)
# define MIDR_ARCHITECTURE_SHIFT 16
# define MIDR_ARCHITECTURE_MASK (0xfU << MIDR_ARCHITECTURE_SHIFT)
# define MIDR_ARCHITECTURE(midr) \
(((midr) & MIDR_ARCHITECTURE_MASK) >> MIDR_ARCHITECTURE_SHIFT)
# define MIDR_CPU_MODEL_MASK \
(MIDR_IMPLEMENTER_MASK | \
MIDR_PARTNUM_MASK | \
MIDR_ARCHITECTURE_MASK)
# define MIDR_CPU_MODEL(imp, partnum) \
(((imp) << MIDR_IMPLEMENTER_SHIFT) | \
(0xfU << MIDR_ARCHITECTURE_SHIFT) | \
((partnum) << MIDR_PARTNUM_SHIFT))
# define MIDR_IS_CPU_MODEL(midr, imp, partnum) \
(((midr) & MIDR_CPU_MODEL_MASK) == MIDR_CPU_MODEL(imp, partnum))
#if defined(__ASSEMBLER__)
/*
* Support macros for
* - Armv8.3-A Pointer Authentication and
* - Armv8.5-A Branch Target Identification
* features which require emitting a .note.gnu.property section with the
* appropriate architecture-dependent feature bits set.
* Read more: "ELF for the Arm® 64-bit Architecture"
*/
# if defined(__ARM_FEATURE_BTI_DEFAULT) && __ARM_FEATURE_BTI_DEFAULT == 1
# define GNU_PROPERTY_AARCH64_BTI (1 << 0) /* Has Branch Target Identification */
# define AARCH64_VALID_CALL_TARGET hint #34 /* BTI 'c' */
# else
# define GNU_PROPERTY_AARCH64_BTI 0 /* No Branch Target Identification */
# define AARCH64_VALID_CALL_TARGET
# endif
# if defined(__ARM_FEATURE_PAC_DEFAULT) && \
(__ARM_FEATURE_PAC_DEFAULT & 1) == 1 /* Signed with A-key */
# define GNU_PROPERTY_AARCH64_POINTER_AUTH \
(1 << 1) /* Has Pointer Authentication */
# define AARCH64_SIGN_LINK_REGISTER hint #25 /* PACIASP */
# define AARCH64_VALIDATE_LINK_REGISTER hint #29 /* AUTIASP */
# elif defined(__ARM_FEATURE_PAC_DEFAULT) && \
(__ARM_FEATURE_PAC_DEFAULT & 2) == 2 /* Signed with B-key */
# define GNU_PROPERTY_AARCH64_POINTER_AUTH \
(1 << 1) /* Has Pointer Authentication */
# define AARCH64_SIGN_LINK_REGISTER hint #27 /* PACIBSP */
# define AARCH64_VALIDATE_LINK_REGISTER hint #31 /* AUTIBSP */
# else
# define GNU_PROPERTY_AARCH64_POINTER_AUTH 0 /* No Pointer Authentication */
# if GNU_PROPERTY_AARCH64_BTI != 0
# define AARCH64_SIGN_LINK_REGISTER AARCH64_VALID_CALL_TARGET
# else
# define AARCH64_SIGN_LINK_REGISTER
# endif
# define AARCH64_VALIDATE_LINK_REGISTER
# endif
# if GNU_PROPERTY_AARCH64_POINTER_AUTH != 0 || GNU_PROPERTY_AARCH64_BTI != 0
.pushsection .note.gnu.property, "a";
.balign 8;
.long 4;
.long 0x10;
.long 0x5;
.asciz "GNU";
.long 0xc0000000; /* GNU_PROPERTY_AARCH64_FEATURE_1_AND */
.long 4;
.long (GNU_PROPERTY_AARCH64_POINTER_AUTH | GNU_PROPERTY_AARCH64_BTI);
.long 0;
.popsection;
# endif
# endif /* defined __ASSEMBLER__ */
# define IS_CPU_SUPPORT_UNROLL8_EOR3() \
(OPENSSL_armcap_P & ARMV8_UNROLL8_EOR3)
#endif
| 6,919 | 33.949495 | 85 | h |
openssl | openssl-master/crypto/armcap.c | /*
* Copyright 2011-2023 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/crypto.h>
#ifdef __APPLE__
#include <sys/sysctl.h>
#else
#include <setjmp.h>
#include <signal.h>
#endif
#include "internal/cryptlib.h"
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
#include "arm_arch.h"
unsigned int OPENSSL_armcap_P = 0;
unsigned int OPENSSL_arm_midr = 0;
unsigned int OPENSSL_armv8_rsa_neonized = 0;
#ifdef _WIN32
void OPENSSL_cpuid_setup(void)
{
OPENSSL_armcap_P |= ARMV7_NEON;
OPENSSL_armv8_rsa_neonized = 1;
if (IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE)) {
// These are all covered by one call in Windows
OPENSSL_armcap_P |= ARMV8_AES;
OPENSSL_armcap_P |= ARMV8_PMULL;
OPENSSL_armcap_P |= ARMV8_SHA1;
OPENSSL_armcap_P |= ARMV8_SHA256;
}
}
uint32_t OPENSSL_rdtsc(void)
{
return 0;
}
#elif __ARM_MAX_ARCH__ < 7
void OPENSSL_cpuid_setup(void)
{
}
uint32_t OPENSSL_rdtsc(void)
{
return 0;
}
#else /* !_WIN32 && __ARM_MAX_ARCH__ >= 7 */
/* 3 ways of handling things here: __APPLE__, getauxval() or SIGILL detect */
/* First determine if getauxval() is available (OSSL_IMPLEMENT_GETAUXVAL) */
# if defined(__GNUC__) && __GNUC__>=2
void OPENSSL_cpuid_setup(void) __attribute__ ((constructor));
# endif
# if defined(__GLIBC__) && defined(__GLIBC_PREREQ)
# if __GLIBC_PREREQ(2, 16)
# include <sys/auxv.h>
# define OSSL_IMPLEMENT_GETAUXVAL
# endif
# elif defined(__ANDROID_API__)
/* see https://developer.android.google.cn/ndk/guides/cpu-features */
# if __ANDROID_API__ >= 18
# include <sys/auxv.h>
# define OSSL_IMPLEMENT_GETAUXVAL
# endif
# endif
# if defined(__FreeBSD__)
# include <sys/param.h>
# if __FreeBSD_version >= 1200000
# include <sys/auxv.h>
# define OSSL_IMPLEMENT_GETAUXVAL
static unsigned long getauxval(unsigned long key)
{
unsigned long val = 0ul;
if (elf_aux_info((int)key, &val, sizeof(val)) != 0)
return 0ul;
return val;
}
# endif
# endif
/*
* Android: according to https://developer.android.com/ndk/guides/cpu-features,
* getauxval is supported starting with API level 18
*/
# if defined(__ANDROID__) && defined(__ANDROID_API__) && __ANDROID_API__ >= 18
# include <sys/auxv.h>
# define OSSL_IMPLEMENT_GETAUXVAL
# endif
/*
* ARM puts the feature bits for Crypto Extensions in AT_HWCAP2, whereas
* AArch64 used AT_HWCAP.
*/
# ifndef AT_HWCAP
# define AT_HWCAP 16
# endif
# ifndef AT_HWCAP2
# define AT_HWCAP2 26
# endif
# if defined(__arm__) || defined (__arm)
# define OSSL_HWCAP AT_HWCAP
# define OSSL_HWCAP_NEON (1 << 12)
# define OSSL_HWCAP_CE AT_HWCAP2
# define OSSL_HWCAP_CE_AES (1 << 0)
# define OSSL_HWCAP_CE_PMULL (1 << 1)
# define OSSL_HWCAP_CE_SHA1 (1 << 2)
# define OSSL_HWCAP_CE_SHA256 (1 << 3)
# elif defined(__aarch64__)
# define OSSL_HWCAP AT_HWCAP
# define OSSL_HWCAP_NEON (1 << 1)
# define OSSL_HWCAP_CE AT_HWCAP
# define OSSL_HWCAP_CE_AES (1 << 3)
# define OSSL_HWCAP_CE_PMULL (1 << 4)
# define OSSL_HWCAP_CE_SHA1 (1 << 5)
# define OSSL_HWCAP_CE_SHA256 (1 << 6)
# define OSSL_HWCAP_CPUID (1 << 11)
# define OSSL_HWCAP_SHA3 (1 << 17)
# define OSSL_HWCAP_CE_SM3 (1 << 18)
# define OSSL_HWCAP_CE_SM4 (1 << 19)
# define OSSL_HWCAP_CE_SHA512 (1 << 21)
# define OSSL_HWCAP_SVE (1 << 22)
/* AT_HWCAP2 */
# define OSSL_HWCAP2 26
# define OSSL_HWCAP2_SVE2 (1 << 1)
# define OSSL_HWCAP2_RNG (1 << 16)
# endif
uint32_t _armv7_tick(void);
uint32_t OPENSSL_rdtsc(void)
{
if (OPENSSL_armcap_P & ARMV7_TICK)
return _armv7_tick();
else
return 0;
}
# ifdef __aarch64__
size_t OPENSSL_rndr_asm(unsigned char *buf, size_t len);
size_t OPENSSL_rndrrs_asm(unsigned char *buf, size_t len);
size_t OPENSSL_rndr_bytes(unsigned char *buf, size_t len);
size_t OPENSSL_rndrrs_bytes(unsigned char *buf, size_t len);
static size_t OPENSSL_rndr_wrapper(size_t (*func)(unsigned char *, size_t), unsigned char *buf, size_t len)
{
size_t buffer_size = 0;
int i;
for (i = 0; i < 8; i++) {
buffer_size = func(buf, len);
if (buffer_size == len)
break;
usleep(5000); /* 5000 microseconds (5 milliseconds) */
}
return buffer_size;
}
size_t OPENSSL_rndr_bytes(unsigned char *buf, size_t len)
{
return OPENSSL_rndr_wrapper(OPENSSL_rndr_asm, buf, len);
}
size_t OPENSSL_rndrrs_bytes(unsigned char *buf, size_t len)
{
return OPENSSL_rndr_wrapper(OPENSSL_rndrrs_asm, buf, len);
}
# endif
# if !defined(__APPLE__) && !defined(OSSL_IMPLEMENT_GETAUXVAL)
static sigset_t all_masked;
static sigjmp_buf ill_jmp;
static void ill_handler(int sig)
{
siglongjmp(ill_jmp, sig);
}
/*
* Following subroutines could have been inlined, but not all
* ARM compilers support inline assembler, and we'd then have to
* worry about the compiler optimising out the detection code...
*/
void _armv7_neon_probe(void);
void _armv8_aes_probe(void);
void _armv8_sha1_probe(void);
void _armv8_sha256_probe(void);
void _armv8_pmull_probe(void);
# ifdef __aarch64__
void _armv8_sm3_probe(void);
void _armv8_sm4_probe(void);
void _armv8_sha512_probe(void);
void _armv8_eor3_probe(void);
void _armv8_sve_probe(void);
void _armv8_sve2_probe(void);
void _armv8_rng_probe(void);
# endif
# endif /* !__APPLE__ && !OSSL_IMPLEMENT_GETAUXVAL */
/* We only call _armv8_cpuid_probe() if (OPENSSL_armcap_P & ARMV8_CPUID) != 0 */
unsigned int _armv8_cpuid_probe(void);
# if defined(__APPLE__)
/*
* Checks the specified integer sysctl, returning `value` if it's 1, otherwise returning 0.
*/
static unsigned int sysctl_query(const char *name, unsigned int value)
{
unsigned int sys_value = 0;
size_t len = sizeof(sys_value);
return (sysctlbyname(name, &sys_value, &len, NULL, 0) == 0 && sys_value == 1) ? value : 0;
}
# elif !defined(OSSL_IMPLEMENT_GETAUXVAL)
/*
* Calls a provided probe function, which may SIGILL. If it doesn't, return `value`, otherwise return 0.
*/
static unsigned int arm_probe_for(void (*probe)(void), volatile unsigned int value)
{
if (sigsetjmp(ill_jmp, 1) == 0) {
probe();
return value;
} else {
/* The probe function gave us SIGILL */
return 0;
}
}
# endif
void OPENSSL_cpuid_setup(void)
{
const char *e;
# if !defined(__APPLE__) && !defined(OSSL_IMPLEMENT_GETAUXVAL)
struct sigaction ill_oact, ill_act;
sigset_t oset;
# endif
static int trigger = 0;
if (trigger)
return;
trigger = 1;
OPENSSL_armcap_P = 0;
if ((e = getenv("OPENSSL_armcap"))) {
OPENSSL_armcap_P = (unsigned int)strtoul(e, NULL, 0);
return;
}
# if defined(__APPLE__)
# if !defined(__aarch64__)
/*
* Capability probing by catching SIGILL appears to be problematic
* on iOS. But since Apple universe is "monocultural", it's actually
* possible to simply set pre-defined processor capability mask.
*/
if (1) {
OPENSSL_armcap_P = ARMV7_NEON;
return;
}
# else
{
/*
* From
* https://github.com/llvm/llvm-project/blob/412237dcd07e5a2afbb1767858262a5f037149a3/llvm/lib/Target/AArch64/AArch64.td#L719
* all of these have been available on 64-bit Apple Silicon from the
* beginning (the A7).
*/
OPENSSL_armcap_P |= ARMV7_NEON | ARMV8_PMULL | ARMV8_AES | ARMV8_SHA1 | ARMV8_SHA256;
/* More recent extensions are indicated by sysctls */
OPENSSL_armcap_P |= sysctl_query("hw.optional.armv8_2_sha512", ARMV8_SHA512);
OPENSSL_armcap_P |= sysctl_query("hw.optional.armv8_2_sha3", ARMV8_SHA3);
if (OPENSSL_armcap_P & ARMV8_SHA3) {
char uarch[64];
size_t len = sizeof(uarch);
if ((sysctlbyname("machdep.cpu.brand_string", uarch, &len, NULL, 0) == 0) &&
((strncmp(uarch, "Apple M1", 8) == 0) ||
(strncmp(uarch, "Apple M2", 8) == 0))) {
OPENSSL_armcap_P |= ARMV8_UNROLL8_EOR3;
}
}
}
# endif /* __aarch64__ */
# elif defined(OSSL_IMPLEMENT_GETAUXVAL)
if (getauxval(OSSL_HWCAP) & OSSL_HWCAP_NEON) {
unsigned long hwcap = getauxval(OSSL_HWCAP_CE);
OPENSSL_armcap_P |= ARMV7_NEON;
if (hwcap & OSSL_HWCAP_CE_AES)
OPENSSL_armcap_P |= ARMV8_AES;
if (hwcap & OSSL_HWCAP_CE_PMULL)
OPENSSL_armcap_P |= ARMV8_PMULL;
if (hwcap & OSSL_HWCAP_CE_SHA1)
OPENSSL_armcap_P |= ARMV8_SHA1;
if (hwcap & OSSL_HWCAP_CE_SHA256)
OPENSSL_armcap_P |= ARMV8_SHA256;
# ifdef __aarch64__
if (hwcap & OSSL_HWCAP_CE_SM4)
OPENSSL_armcap_P |= ARMV8_SM4;
if (hwcap & OSSL_HWCAP_CE_SHA512)
OPENSSL_armcap_P |= ARMV8_SHA512;
if (hwcap & OSSL_HWCAP_CPUID)
OPENSSL_armcap_P |= ARMV8_CPUID;
if (hwcap & OSSL_HWCAP_CE_SM3)
OPENSSL_armcap_P |= ARMV8_SM3;
if (hwcap & OSSL_HWCAP_SHA3)
OPENSSL_armcap_P |= ARMV8_SHA3;
# endif
}
# ifdef __aarch64__
if (getauxval(OSSL_HWCAP) & OSSL_HWCAP_SVE)
OPENSSL_armcap_P |= ARMV8_SVE;
if (getauxval(OSSL_HWCAP2) & OSSL_HWCAP2_SVE2)
OPENSSL_armcap_P |= ARMV8_SVE2;
if (getauxval(OSSL_HWCAP2) & OSSL_HWCAP2_RNG)
OPENSSL_armcap_P |= ARMV8_RNG;
# endif
# else /* !__APPLE__ && !OSSL_IMPLEMENT_GETAUXVAL */
/* If all else fails, do brute force SIGILL-based feature detection */
sigfillset(&all_masked);
sigdelset(&all_masked, SIGILL);
sigdelset(&all_masked, SIGTRAP);
sigdelset(&all_masked, SIGFPE);
sigdelset(&all_masked, SIGBUS);
sigdelset(&all_masked, SIGSEGV);
memset(&ill_act, 0, sizeof(ill_act));
ill_act.sa_handler = ill_handler;
ill_act.sa_mask = all_masked;
sigprocmask(SIG_SETMASK, &ill_act.sa_mask, &oset);
sigaction(SIGILL, &ill_act, &ill_oact);
OPENSSL_armcap_P |= arm_probe_for(_armv7_neon_probe, ARMV7_NEON);
if (OPENSSL_armcap_P & ARMV7_NEON) {
OPENSSL_armcap_P |= arm_probe_for(_armv8_pmull_probe, ARMV8_PMULL | ARMV8_AES);
if (!(OPENSSL_armcap_P & ARMV8_AES)) {
OPENSSL_armcap_P |= arm_probe_for(_armv8_aes_probe, ARMV8_AES);
}
OPENSSL_armcap_P |= arm_probe_for(_armv8_sha1_probe, ARMV8_SHA1);
OPENSSL_armcap_P |= arm_probe_for(_armv8_sha256_probe, ARMV8_SHA256);
# if defined(__aarch64__)
OPENSSL_armcap_P |= arm_probe_for(_armv8_sm3_probe, ARMV8_SM3);
OPENSSL_armcap_P |= arm_probe_for(_armv8_sm4_probe, ARMV8_SM4);
OPENSSL_armcap_P |= arm_probe_for(_armv8_sha512_probe, ARMV8_SHA512);
OPENSSL_armcap_P |= arm_probe_for(_armv8_eor3_probe, ARMV8_SHA3);
# endif
}
# ifdef __aarch64__
OPENSSL_armcap_P |= arm_probe_for(_armv8_sve_probe, ARMV8_SVE);
OPENSSL_armcap_P |= arm_probe_for(_armv8_sve2_probe, ARMV8_SVE2);
OPENSSL_armcap_P |= arm_probe_for(_armv8_rng_probe, ARMV8_RNG);
# endif
/*
* Probing for ARMV7_TICK is known to produce unreliable results,
* so we only use the feature when the user explicitly enables it
* with OPENSSL_armcap.
*/
sigaction(SIGILL, &ill_oact, NULL);
sigprocmask(SIG_SETMASK, &oset, NULL);
# endif /* __APPLE__, OSSL_IMPLEMENT_GETAUXVAL */
# ifdef __aarch64__
if (OPENSSL_armcap_P & ARMV8_CPUID)
OPENSSL_arm_midr = _armv8_cpuid_probe();
if ((MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_ARM, ARM_CPU_PART_CORTEX_A72) ||
MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_ARM, ARM_CPU_PART_N1)) &&
(OPENSSL_armcap_P & ARMV7_NEON)) {
OPENSSL_armv8_rsa_neonized = 1;
}
if ((MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_ARM, ARM_CPU_PART_V1) ||
MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_ARM, ARM_CPU_PART_N2) ||
MIDR_IS_CPU_MODEL(OPENSSL_arm_midr, ARM_CPU_IMP_ARM, ARM_CPU_PART_V2)) &&
(OPENSSL_armcap_P & ARMV8_SHA3))
OPENSSL_armcap_P |= ARMV8_UNROLL8_EOR3;
# endif
}
#endif /* _WIN32, __ARM_MAX_ARCH__ >= 7 */
| 12,693 | 28.868235 | 133 | c |
openssl | openssl-master/crypto/asn1_dsa.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
*/
/*
* A simple ASN.1 DER encoder/decoder for DSA-Sig-Value and ECDSA-Sig-Value.
*
* DSA-Sig-Value ::= SEQUENCE {
* r INTEGER,
* s INTEGER
* }
*
* ECDSA-Sig-Value ::= SEQUENCE {
* r INTEGER,
* s INTEGER
* }
*/
#include <openssl/crypto.h>
#include <openssl/bn.h>
#include "crypto/asn1_dsa.h"
#include "internal/packet.h"
#define ID_SEQUENCE 0x30
#define ID_INTEGER 0x02
/*
* Outputs the encoding of the length octets for a DER value with a content
* length of cont_len bytes to pkt. The maximum supported content length is
* 65535 (0xffff) bytes.
*
* Returns 1 on success or 0 on error.
*/
int ossl_encode_der_length(WPACKET *pkt, size_t cont_len)
{
if (cont_len > 0xffff)
return 0; /* Too large for supported length encodings */
if (cont_len > 0xff) {
if (!WPACKET_put_bytes_u8(pkt, 0x82)
|| !WPACKET_put_bytes_u16(pkt, cont_len))
return 0;
} else {
if (cont_len > 0x7f
&& !WPACKET_put_bytes_u8(pkt, 0x81))
return 0;
if (!WPACKET_put_bytes_u8(pkt, cont_len))
return 0;
}
return 1;
}
/*
* Outputs the DER encoding of a positive ASN.1 INTEGER to pkt.
*
* Results in an error if n is negative or too large.
*
* Returns 1 on success or 0 on error.
*/
int ossl_encode_der_integer(WPACKET *pkt, const BIGNUM *n)
{
unsigned char *bnbytes;
size_t cont_len;
if (BN_is_negative(n))
return 0;
/*
* Calculate the ASN.1 INTEGER DER content length for n.
* This is the number of whole bytes required to represent n (i.e. rounded
* down), plus one.
* If n is zero then the content is a single zero byte (length = 1).
* If the number of bits of n is a multiple of 8 then an extra zero padding
* byte is included to ensure that the value is still treated as positive
* in the INTEGER two's complement representation.
*/
cont_len = BN_num_bits(n) / 8 + 1;
if (!WPACKET_start_sub_packet(pkt)
|| !WPACKET_put_bytes_u8(pkt, ID_INTEGER)
|| !ossl_encode_der_length(pkt, cont_len)
|| !WPACKET_allocate_bytes(pkt, cont_len, &bnbytes)
|| !WPACKET_close(pkt))
return 0;
if (bnbytes != NULL
&& BN_bn2binpad(n, bnbytes, (int)cont_len) != (int)cont_len)
return 0;
return 1;
}
/*
* Outputs the DER encoding of a DSA-Sig-Value or ECDSA-Sig-Value to pkt. pkt
* may be initialised with a NULL buffer which enables pkt to be used to
* calculate how many bytes would be needed.
*
* Returns 1 on success or 0 on error.
*/
int ossl_encode_der_dsa_sig(WPACKET *pkt, const BIGNUM *r, const BIGNUM *s)
{
WPACKET tmppkt, *dummypkt;
size_t cont_len;
int isnull = WPACKET_is_null_buf(pkt);
if (!WPACKET_start_sub_packet(pkt))
return 0;
if (!isnull) {
if (!WPACKET_init_null(&tmppkt, 0))
return 0;
dummypkt = &tmppkt;
} else {
/* If the input packet has a NULL buffer, we don't need a dummy packet */
dummypkt = pkt;
}
/* Calculate the content length */
if (!ossl_encode_der_integer(dummypkt, r)
|| !ossl_encode_der_integer(dummypkt, s)
|| !WPACKET_get_length(dummypkt, &cont_len)
|| (!isnull && !WPACKET_finish(dummypkt))) {
if (!isnull)
WPACKET_cleanup(dummypkt);
return 0;
}
/* Add the tag and length bytes */
if (!WPACKET_put_bytes_u8(pkt, ID_SEQUENCE)
|| !ossl_encode_der_length(pkt, cont_len)
/*
* Really encode the integers. We already wrote to the main pkt
* if it had a NULL buffer, so don't do it again
*/
|| (!isnull && !ossl_encode_der_integer(pkt, r))
|| (!isnull && !ossl_encode_der_integer(pkt, s))
|| !WPACKET_close(pkt))
return 0;
return 1;
}
/*
* Decodes the DER length octets in pkt and initialises subpkt with the
* following bytes of that length.
*
* Returns 1 on success or 0 on failure.
*/
int ossl_decode_der_length(PACKET *pkt, PACKET *subpkt)
{
unsigned int byte;
if (!PACKET_get_1(pkt, &byte))
return 0;
if (byte < 0x80)
return PACKET_get_sub_packet(pkt, subpkt, (size_t)byte);
if (byte == 0x81)
return PACKET_get_length_prefixed_1(pkt, subpkt);
if (byte == 0x82)
return PACKET_get_length_prefixed_2(pkt, subpkt);
/* Too large, invalid, or not DER. */
return 0;
}
/*
* Decodes a single ASN.1 INTEGER value from pkt, which must be DER encoded,
* and updates n with the decoded value.
*
* The BIGNUM, n, must have already been allocated by calling BN_new().
* pkt must not be NULL.
*
* An attempt to consume more than len bytes results in an error.
* Returns 1 on success or 0 on error.
*
* If the PACKET is supposed to only contain a single INTEGER value with no
* trailing garbage then it is up to the caller to verify that all bytes
* were consumed.
*/
int ossl_decode_der_integer(PACKET *pkt, BIGNUM *n)
{
PACKET contpkt, tmppkt;
unsigned int tag, tmp;
/* Check we have an integer and get the content bytes */
if (!PACKET_get_1(pkt, &tag)
|| tag != ID_INTEGER
|| !ossl_decode_der_length(pkt, &contpkt))
return 0;
/* Peek ahead at the first bytes to check for proper encoding */
tmppkt = contpkt;
/* The INTEGER must be positive */
if (!PACKET_get_1(&tmppkt, &tmp)
|| (tmp & 0x80) != 0)
return 0;
/* If there a zero padding byte the next byte must have the msb set */
if (PACKET_remaining(&tmppkt) > 0 && tmp == 0) {
if (!PACKET_get_1(&tmppkt, &tmp)
|| (tmp & 0x80) == 0)
return 0;
}
if (BN_bin2bn(PACKET_data(&contpkt),
(int)PACKET_remaining(&contpkt), n) == NULL)
return 0;
return 1;
}
/*
* Decodes a single DSA-Sig-Value or ECDSA-Sig-Value from *ppin, which must be
* DER encoded, updates r and s with the decoded values, and increments *ppin
* past the data that was consumed.
*
* The BIGNUMs, r and s, must have already been allocated by calls to BN_new().
* ppin and *ppin must not be NULL.
*
* An attempt to consume more than len bytes results in an error.
* Returns the number of bytes of input consumed or 0 if an error occurs.
*
* If the buffer is supposed to only contain a single [EC]DSA-Sig-Value with no
* trailing garbage then it is up to the caller to verify that all bytes
* were consumed.
*/
size_t ossl_decode_der_dsa_sig(BIGNUM *r, BIGNUM *s,
const unsigned char **ppin, size_t len)
{
size_t consumed;
PACKET pkt, contpkt;
unsigned int tag;
if (!PACKET_buf_init(&pkt, *ppin, len)
|| !PACKET_get_1(&pkt, &tag)
|| tag != ID_SEQUENCE
|| !ossl_decode_der_length(&pkt, &contpkt)
|| !ossl_decode_der_integer(&contpkt, r)
|| !ossl_decode_der_integer(&contpkt, s)
|| PACKET_remaining(&contpkt) != 0)
return 0;
consumed = PACKET_data(&pkt) - *ppin;
*ppin += consumed;
return consumed;
}
| 7,543 | 28.818182 | 81 | c |
openssl | openssl-master/crypto/bsearch.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 <stddef.h>
#include "internal/cryptlib.h"
const void *ossl_bsearch(const void *key, const void *base, int num,
int size, int (*cmp) (const void *, const void *),
int flags)
{
const char *base_ = base;
int l, h, i = 0, c = 0;
const char *p = NULL;
if (num == 0)
return NULL;
l = 0;
h = num;
while (l < h) {
i = (l + h) / 2;
p = &(base_[i * size]);
c = (*cmp) (key, p);
if (c < 0)
h = i;
else if (c > 0)
l = i + 1;
else
break;
}
if (c != 0 && !(flags & OSSL_BSEARCH_VALUE_ON_NOMATCH))
p = NULL;
else if (c == 0 && (flags & OSSL_BSEARCH_FIRST_VALUE_ON_MATCH)) {
while (i > 0 && (*cmp) (key, &(base_[(i - 1) * size])) == 0)
i--;
p = &(base_[i * size]);
}
return p;
}
| 1,232 | 26.4 | 75 | c |
openssl | openssl-master/crypto/context.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 "crypto/cryptlib.h"
#include <openssl/conf.h>
#include "internal/thread_once.h"
#include "internal/property.h"
#include "internal/core.h"
#include "internal/bio.h"
#include "internal/provider.h"
#include "internal/decoder.h"
#include "crypto/context.h"
struct ossl_lib_ctx_st {
CRYPTO_RWLOCK *lock, *rand_crngt_lock;
OSSL_EX_DATA_GLOBAL global;
void *property_string_data;
void *evp_method_store;
void *provider_store;
void *namemap;
void *property_defns;
void *global_properties;
void *drbg;
void *drbg_nonce;
#ifndef FIPS_MODULE
void *provider_conf;
void *bio_core;
void *child_provider;
OSSL_METHOD_STORE *decoder_store;
void *decoder_cache;
OSSL_METHOD_STORE *encoder_store;
OSSL_METHOD_STORE *store_loader_store;
void *self_test_cb;
#endif
#if defined(OPENSSL_THREADS)
void *threads;
#endif
void *rand_crngt;
#ifdef FIPS_MODULE
void *thread_event_handler;
void *fips_prov;
#endif
unsigned int ischild:1;
};
int ossl_lib_ctx_write_lock(OSSL_LIB_CTX *ctx)
{
return CRYPTO_THREAD_write_lock(ossl_lib_ctx_get_concrete(ctx)->lock);
}
int ossl_lib_ctx_read_lock(OSSL_LIB_CTX *ctx)
{
return CRYPTO_THREAD_read_lock(ossl_lib_ctx_get_concrete(ctx)->lock);
}
int ossl_lib_ctx_unlock(OSSL_LIB_CTX *ctx)
{
return CRYPTO_THREAD_unlock(ossl_lib_ctx_get_concrete(ctx)->lock);
}
int ossl_lib_ctx_is_child(OSSL_LIB_CTX *ctx)
{
ctx = ossl_lib_ctx_get_concrete(ctx);
if (ctx == NULL)
return 0;
return ctx->ischild;
}
static void context_deinit_objs(OSSL_LIB_CTX *ctx);
static int context_init(OSSL_LIB_CTX *ctx)
{
int exdata_done = 0;
ctx->lock = CRYPTO_THREAD_lock_new();
if (ctx->lock == NULL)
return 0;
ctx->rand_crngt_lock = CRYPTO_THREAD_lock_new();
if (ctx->rand_crngt_lock == NULL)
goto err;
/* Initialize ex_data. */
if (!ossl_do_ex_data_init(ctx))
goto err;
exdata_done = 1;
/* P2. We want evp_method_store to be cleaned up before the provider store */
ctx->evp_method_store = ossl_method_store_new(ctx);
if (ctx->evp_method_store == NULL)
goto err;
#ifndef FIPS_MODULE
/* P2. Must be freed before the provider store is freed */
ctx->provider_conf = ossl_prov_conf_ctx_new(ctx);
if (ctx->provider_conf == NULL)
goto err;
#endif
/* P2. */
ctx->drbg = ossl_rand_ctx_new(ctx);
if (ctx->drbg == NULL)
goto err;
#ifndef FIPS_MODULE
/*
* P2. We want decoder_store/decoder_cache to be cleaned up before the
* provider store
*/
ctx->decoder_store = ossl_method_store_new(ctx);
if (ctx->decoder_store == NULL)
goto err;
ctx->decoder_cache = ossl_decoder_cache_new(ctx);
if (ctx->decoder_cache == NULL)
goto err;
/* P2. We want encoder_store to be cleaned up before the provider store */
ctx->encoder_store = ossl_method_store_new(ctx);
if (ctx->encoder_store == NULL)
goto err;
/* P2. We want loader_store to be cleaned up before the provider store */
ctx->store_loader_store = ossl_method_store_new(ctx);
if (ctx->store_loader_store == NULL)
goto err;
#endif
/* P1. Needs to be freed before the child provider data is freed */
ctx->provider_store = ossl_provider_store_new(ctx);
if (ctx->provider_store == NULL)
goto err;
/* Default priority. */
ctx->property_string_data = ossl_property_string_data_new(ctx);
if (ctx->property_string_data == NULL)
goto err;
ctx->namemap = ossl_stored_namemap_new(ctx);
if (ctx->namemap == NULL)
goto err;
ctx->property_defns = ossl_property_defns_new(ctx);
if (ctx->property_defns == NULL)
goto err;
ctx->global_properties = ossl_ctx_global_properties_new(ctx);
if (ctx->global_properties == NULL)
goto err;
#ifndef FIPS_MODULE
ctx->bio_core = ossl_bio_core_globals_new(ctx);
if (ctx->bio_core == NULL)
goto err;
#endif
ctx->drbg_nonce = ossl_prov_drbg_nonce_ctx_new(ctx);
if (ctx->drbg_nonce == NULL)
goto err;
#ifndef FIPS_MODULE
ctx->self_test_cb = ossl_self_test_set_callback_new(ctx);
if (ctx->self_test_cb == NULL)
goto err;
#endif
#ifdef FIPS_MODULE
ctx->thread_event_handler = ossl_thread_event_ctx_new(ctx);
if (ctx->thread_event_handler == NULL)
goto err;
ctx->fips_prov = ossl_fips_prov_ossl_ctx_new(ctx);
if (ctx->fips_prov == NULL)
goto err;
#endif
#ifndef OPENSSL_NO_THREAD_POOL
ctx->threads = ossl_threads_ctx_new(ctx);
if (ctx->threads == NULL)
goto err;
#endif
/* Low priority. */
#ifndef FIPS_MODULE
ctx->child_provider = ossl_child_prov_ctx_new(ctx);
if (ctx->child_provider == NULL)
goto err;
#endif
/* Everything depends on properties, so we also pre-initialise that */
if (!ossl_property_parse_init(ctx))
goto err;
return 1;
err:
context_deinit_objs(ctx);
if (exdata_done)
ossl_crypto_cleanup_all_ex_data_int(ctx);
CRYPTO_THREAD_lock_free(ctx->rand_crngt_lock);
CRYPTO_THREAD_lock_free(ctx->lock);
memset(ctx, '\0', sizeof(*ctx));
return 0;
}
static void context_deinit_objs(OSSL_LIB_CTX *ctx)
{
/* P2. We want evp_method_store to be cleaned up before the provider store */
if (ctx->evp_method_store != NULL) {
ossl_method_store_free(ctx->evp_method_store);
ctx->evp_method_store = NULL;
}
/* P2. */
if (ctx->drbg != NULL) {
ossl_rand_ctx_free(ctx->drbg);
ctx->drbg = NULL;
}
#ifndef FIPS_MODULE
/* P2. */
if (ctx->provider_conf != NULL) {
ossl_prov_conf_ctx_free(ctx->provider_conf);
ctx->provider_conf = NULL;
}
/*
* P2. We want decoder_store/decoder_cache to be cleaned up before the
* provider store
*/
if (ctx->decoder_store != NULL) {
ossl_method_store_free(ctx->decoder_store);
ctx->decoder_store = NULL;
}
if (ctx->decoder_cache != NULL) {
ossl_decoder_cache_free(ctx->decoder_cache);
ctx->decoder_cache = NULL;
}
/* P2. We want encoder_store to be cleaned up before the provider store */
if (ctx->encoder_store != NULL) {
ossl_method_store_free(ctx->encoder_store);
ctx->encoder_store = NULL;
}
/* P2. We want loader_store to be cleaned up before the provider store */
if (ctx->store_loader_store != NULL) {
ossl_method_store_free(ctx->store_loader_store);
ctx->store_loader_store = NULL;
}
#endif
/* P1. Needs to be freed before the child provider data is freed */
if (ctx->provider_store != NULL) {
ossl_provider_store_free(ctx->provider_store);
ctx->provider_store = NULL;
}
/* Default priority. */
if (ctx->property_string_data != NULL) {
ossl_property_string_data_free(ctx->property_string_data);
ctx->property_string_data = NULL;
}
if (ctx->namemap != NULL) {
ossl_stored_namemap_free(ctx->namemap);
ctx->namemap = NULL;
}
if (ctx->property_defns != NULL) {
ossl_property_defns_free(ctx->property_defns);
ctx->property_defns = NULL;
}
if (ctx->global_properties != NULL) {
ossl_ctx_global_properties_free(ctx->global_properties);
ctx->global_properties = NULL;
}
#ifndef FIPS_MODULE
if (ctx->bio_core != NULL) {
ossl_bio_core_globals_free(ctx->bio_core);
ctx->bio_core = NULL;
}
#endif
if (ctx->drbg_nonce != NULL) {
ossl_prov_drbg_nonce_ctx_free(ctx->drbg_nonce);
ctx->drbg_nonce = NULL;
}
#ifndef FIPS_MODULE
if (ctx->self_test_cb != NULL) {
ossl_self_test_set_callback_free(ctx->self_test_cb);
ctx->self_test_cb = NULL;
}
#endif
if (ctx->rand_crngt != NULL) {
ossl_rand_crng_ctx_free(ctx->rand_crngt);
ctx->rand_crngt = NULL;
}
#ifdef FIPS_MODULE
if (ctx->thread_event_handler != NULL) {
ossl_thread_event_ctx_free(ctx->thread_event_handler);
ctx->thread_event_handler = NULL;
}
if (ctx->fips_prov != NULL) {
ossl_fips_prov_ossl_ctx_free(ctx->fips_prov);
ctx->fips_prov = NULL;
}
#endif
#ifndef OPENSSL_NO_THREAD_POOL
if (ctx->threads != NULL) {
ossl_threads_ctx_free(ctx->threads);
ctx->threads = NULL;
}
#endif
/* Low priority. */
#ifndef FIPS_MODULE
if (ctx->child_provider != NULL) {
ossl_child_prov_ctx_free(ctx->child_provider);
ctx->child_provider = NULL;
}
#endif
}
static int context_deinit(OSSL_LIB_CTX *ctx)
{
if (ctx == NULL)
return 1;
ossl_ctx_thread_stop(ctx);
context_deinit_objs(ctx);
ossl_crypto_cleanup_all_ex_data_int(ctx);
CRYPTO_THREAD_lock_free(ctx->rand_crngt_lock);
CRYPTO_THREAD_lock_free(ctx->lock);
ctx->rand_crngt_lock = NULL;
ctx->lock = NULL;
return 1;
}
#ifndef FIPS_MODULE
/* The default default context */
static OSSL_LIB_CTX default_context_int;
static CRYPTO_ONCE default_context_init = CRYPTO_ONCE_STATIC_INIT;
static CRYPTO_THREAD_LOCAL default_context_thread_local;
static int default_context_inited = 0;
DEFINE_RUN_ONCE_STATIC(default_context_do_init)
{
if (!CRYPTO_THREAD_init_local(&default_context_thread_local, NULL))
goto err;
if (!context_init(&default_context_int))
goto deinit_thread;
default_context_inited = 1;
return 1;
deinit_thread:
CRYPTO_THREAD_cleanup_local(&default_context_thread_local);
err:
return 0;
}
void ossl_lib_ctx_default_deinit(void)
{
if (!default_context_inited)
return;
context_deinit(&default_context_int);
CRYPTO_THREAD_cleanup_local(&default_context_thread_local);
default_context_inited = 0;
}
static OSSL_LIB_CTX *get_thread_default_context(void)
{
if (!RUN_ONCE(&default_context_init, default_context_do_init))
return NULL;
return CRYPTO_THREAD_get_local(&default_context_thread_local);
}
static OSSL_LIB_CTX *get_default_context(void)
{
OSSL_LIB_CTX *current_defctx = get_thread_default_context();
if (current_defctx == NULL)
current_defctx = &default_context_int;
return current_defctx;
}
static int set_default_context(OSSL_LIB_CTX *defctx)
{
if (defctx == &default_context_int)
defctx = NULL;
return CRYPTO_THREAD_set_local(&default_context_thread_local, defctx);
}
#endif
OSSL_LIB_CTX *OSSL_LIB_CTX_new(void)
{
OSSL_LIB_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
if (ctx != NULL && !context_init(ctx)) {
OPENSSL_free(ctx);
ctx = NULL;
}
return ctx;
}
#ifndef FIPS_MODULE
OSSL_LIB_CTX *OSSL_LIB_CTX_new_from_dispatch(const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in)
{
OSSL_LIB_CTX *ctx = OSSL_LIB_CTX_new();
if (ctx == NULL)
return NULL;
if (!ossl_bio_init_core(ctx, in)) {
OSSL_LIB_CTX_free(ctx);
return NULL;
}
return ctx;
}
OSSL_LIB_CTX *OSSL_LIB_CTX_new_child(const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in)
{
OSSL_LIB_CTX *ctx = OSSL_LIB_CTX_new_from_dispatch(handle, in);
if (ctx == NULL)
return NULL;
if (!ossl_provider_init_as_child(ctx, handle, in)) {
OSSL_LIB_CTX_free(ctx);
return NULL;
}
ctx->ischild = 1;
return ctx;
}
int OSSL_LIB_CTX_load_config(OSSL_LIB_CTX *ctx, const char *config_file)
{
return CONF_modules_load_file_ex(ctx, config_file, NULL, 0) > 0;
}
#endif
void OSSL_LIB_CTX_free(OSSL_LIB_CTX *ctx)
{
if (ossl_lib_ctx_is_default(ctx))
return;
#ifndef FIPS_MODULE
if (ctx->ischild)
ossl_provider_deinit_child(ctx);
#endif
context_deinit(ctx);
OPENSSL_free(ctx);
}
#ifndef FIPS_MODULE
OSSL_LIB_CTX *OSSL_LIB_CTX_get0_global_default(void)
{
if (!RUN_ONCE(&default_context_init, default_context_do_init))
return NULL;
return &default_context_int;
}
OSSL_LIB_CTX *OSSL_LIB_CTX_set0_default(OSSL_LIB_CTX *libctx)
{
OSSL_LIB_CTX *current_defctx;
if ((current_defctx = get_default_context()) != NULL) {
if (libctx != NULL)
set_default_context(libctx);
return current_defctx;
}
return NULL;
}
void ossl_release_default_drbg_ctx(void)
{
/* early release of the DRBG in global default libctx */
if (default_context_int.drbg != NULL) {
ossl_rand_ctx_free(default_context_int.drbg);
default_context_int.drbg = NULL;
}
}
#endif
OSSL_LIB_CTX *ossl_lib_ctx_get_concrete(OSSL_LIB_CTX *ctx)
{
#ifndef FIPS_MODULE
if (ctx == NULL)
return get_default_context();
#endif
return ctx;
}
int ossl_lib_ctx_is_default(OSSL_LIB_CTX *ctx)
{
#ifndef FIPS_MODULE
if (ctx == NULL || ctx == get_default_context())
return 1;
#endif
return 0;
}
int ossl_lib_ctx_is_global_default(OSSL_LIB_CTX *ctx)
{
#ifndef FIPS_MODULE
if (ossl_lib_ctx_get_concrete(ctx) == &default_context_int)
return 1;
#endif
return 0;
}
void *ossl_lib_ctx_get_data(OSSL_LIB_CTX *ctx, int index)
{
void *p;
ctx = ossl_lib_ctx_get_concrete(ctx);
if (ctx == NULL)
return NULL;
switch (index) {
case OSSL_LIB_CTX_PROPERTY_STRING_INDEX:
return ctx->property_string_data;
case OSSL_LIB_CTX_EVP_METHOD_STORE_INDEX:
return ctx->evp_method_store;
case OSSL_LIB_CTX_PROVIDER_STORE_INDEX:
return ctx->provider_store;
case OSSL_LIB_CTX_NAMEMAP_INDEX:
return ctx->namemap;
case OSSL_LIB_CTX_PROPERTY_DEFN_INDEX:
return ctx->property_defns;
case OSSL_LIB_CTX_GLOBAL_PROPERTIES:
return ctx->global_properties;
case OSSL_LIB_CTX_DRBG_INDEX:
return ctx->drbg;
case OSSL_LIB_CTX_DRBG_NONCE_INDEX:
return ctx->drbg_nonce;
#ifndef FIPS_MODULE
case OSSL_LIB_CTX_PROVIDER_CONF_INDEX:
return ctx->provider_conf;
case OSSL_LIB_CTX_BIO_CORE_INDEX:
return ctx->bio_core;
case OSSL_LIB_CTX_CHILD_PROVIDER_INDEX:
return ctx->child_provider;
case OSSL_LIB_CTX_DECODER_STORE_INDEX:
return ctx->decoder_store;
case OSSL_LIB_CTX_DECODER_CACHE_INDEX:
return ctx->decoder_cache;
case OSSL_LIB_CTX_ENCODER_STORE_INDEX:
return ctx->encoder_store;
case OSSL_LIB_CTX_STORE_LOADER_STORE_INDEX:
return ctx->store_loader_store;
case OSSL_LIB_CTX_SELF_TEST_CB_INDEX:
return ctx->self_test_cb;
#endif
#ifndef OPENSSL_NO_THREAD_POOL
case OSSL_LIB_CTX_THREAD_INDEX:
return ctx->threads;
#endif
case OSSL_LIB_CTX_RAND_CRNGT_INDEX: {
/*
* rand_crngt must be lazily initialized because it calls into
* libctx, so must not be called from context_init, else a deadlock
* will occur.
*
* We use a separate lock because code called by the instantiation
* of rand_crngt is liable to try and take the libctx lock.
*/
if (CRYPTO_THREAD_read_lock(ctx->rand_crngt_lock) != 1)
return NULL;
if (ctx->rand_crngt == NULL) {
CRYPTO_THREAD_unlock(ctx->rand_crngt_lock);
if (CRYPTO_THREAD_write_lock(ctx->rand_crngt_lock) != 1)
return NULL;
if (ctx->rand_crngt == NULL)
ctx->rand_crngt = ossl_rand_crng_ctx_new(ctx);
}
p = ctx->rand_crngt;
CRYPTO_THREAD_unlock(ctx->rand_crngt_lock);
return p;
}
#ifdef FIPS_MODULE
case OSSL_LIB_CTX_THREAD_EVENT_HANDLER_INDEX:
return ctx->thread_event_handler;
case OSSL_LIB_CTX_FIPS_PROV_INDEX:
return ctx->fips_prov;
#endif
default:
return NULL;
}
}
OSSL_EX_DATA_GLOBAL *ossl_lib_ctx_get_ex_data_global(OSSL_LIB_CTX *ctx)
{
ctx = ossl_lib_ctx_get_concrete(ctx);
if (ctx == NULL)
return NULL;
return &ctx->global;
}
const char *ossl_lib_ctx_get_descriptor(OSSL_LIB_CTX *libctx)
{
#ifdef FIPS_MODULE
return "FIPS internal library context";
#else
if (ossl_lib_ctx_is_global_default(libctx))
return "Global default library context";
if (ossl_lib_ctx_is_default(libctx))
return "Thread-local default library context";
return "Non-default library context";
#endif
}
| 16,693 | 24.487023 | 81 | c |
openssl | openssl-master/crypto/core_algorithm.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/core.h>
#include <openssl/core_dispatch.h>
#include "internal/core.h"
#include "internal/property.h"
#include "internal/provider.h"
struct algorithm_data_st {
OSSL_LIB_CTX *libctx;
int operation_id; /* May be zero for finding them all */
int (*pre)(OSSL_PROVIDER *, int operation_id, int no_store, void *data,
int *result);
int (*reserve_store)(int no_store, void *data);
void (*fn)(OSSL_PROVIDER *, const OSSL_ALGORITHM *, int no_store,
void *data);
int (*unreserve_store)(void *data);
int (*post)(OSSL_PROVIDER *, int operation_id, int no_store, void *data,
int *result);
void *data;
};
/*
* Process one OSSL_ALGORITHM array, for the operation |cur_operation|,
* by constructing methods for all its implementations and adding those
* to the appropriate method store.
* Which method store is appropriate is given by |no_store| ("permanent"
* if 0, temporary if 1) and other data in |data->data|.
*
* Returns:
* -1 to quit adding algorithm implementations immediately
* 0 if not successful, but adding should continue
* 1 if successful so far, and adding should continue
*/
static int algorithm_do_map(OSSL_PROVIDER *provider, const OSSL_ALGORITHM *map,
int cur_operation, int no_store, void *cbdata)
{
struct algorithm_data_st *data = cbdata;
int ret = 0;
if (!data->reserve_store(no_store, data->data))
/* Error, bail out! */
return -1;
/* Do we fulfill pre-conditions? */
if (data->pre == NULL) {
/* If there is no pre-condition function, assume "yes" */
ret = 1;
} else if (!data->pre(provider, cur_operation, no_store, data->data,
&ret)) {
/* Error, bail out! */
ret = -1;
goto end;
}
/*
* If pre-condition not fulfilled don't add this set of implementations,
* but do continue with the next. This simply means that another thread
* got to it first.
*/
if (ret == 0) {
ret = 1;
goto end;
}
if (map != NULL) {
const OSSL_ALGORITHM *thismap;
for (thismap = map; thismap->algorithm_names != NULL; thismap++)
data->fn(provider, thismap, no_store, data->data);
}
/* Do we fulfill post-conditions? */
if (data->post == NULL) {
/* If there is no post-condition function, assume "yes" */
ret = 1;
} else if (!data->post(provider, cur_operation, no_store, data->data,
&ret)) {
/* Error, bail out! */
ret = -1;
}
end:
data->unreserve_store(data->data);
return ret;
}
/*
* Given a provider, process one operation given by |data->operation_id|, or
* if that's zero, process all known operations.
* For each such operation, query the associated OSSL_ALGORITHM array from
* the provider, then process that array with |algorithm_do_map()|.
*/
static int algorithm_do_this(OSSL_PROVIDER *provider, void *cbdata)
{
struct algorithm_data_st *data = cbdata;
int first_operation = 1;
int last_operation = OSSL_OP__HIGHEST;
int cur_operation;
int ok = 1;
if (data->operation_id != 0)
first_operation = last_operation = data->operation_id;
for (cur_operation = first_operation;
cur_operation <= last_operation;
cur_operation++) {
int no_store = 0; /* Assume caching is ok */
const OSSL_ALGORITHM *map = NULL;
int ret = 0;
map = ossl_provider_query_operation(provider, cur_operation,
&no_store);
ret = algorithm_do_map(provider, map, cur_operation, no_store, data);
ossl_provider_unquery_operation(provider, cur_operation, map);
if (ret < 0)
/* Hard error, bail out immediately! */
return 0;
/* If post-condition not fulfilled, set general failure */
if (!ret)
ok = 0;
}
return ok;
}
void ossl_algorithm_do_all(OSSL_LIB_CTX *libctx, int operation_id,
OSSL_PROVIDER *provider,
int (*pre)(OSSL_PROVIDER *, int operation_id,
int no_store, void *data, int *result),
int (*reserve_store)(int no_store, void *data),
void (*fn)(OSSL_PROVIDER *provider,
const OSSL_ALGORITHM *algo,
int no_store, void *data),
int (*unreserve_store)(void *data),
int (*post)(OSSL_PROVIDER *, int operation_id,
int no_store, void *data, int *result),
void *data)
{
struct algorithm_data_st cbdata = { 0, };
cbdata.libctx = libctx;
cbdata.operation_id = operation_id;
cbdata.pre = pre;
cbdata.reserve_store = reserve_store;
cbdata.fn = fn;
cbdata.unreserve_store = unreserve_store;
cbdata.post = post;
cbdata.data = data;
if (provider == NULL) {
ossl_provider_doall_activated(libctx, algorithm_do_this, &cbdata);
} else {
OSSL_LIB_CTX *libctx2 = ossl_provider_libctx(provider);
/*
* If a provider is given, its library context MUST match the library
* context we're passed. If this turns out not to be true, there is
* a programming error in the functions up the call stack.
*/
if (!ossl_assert(ossl_lib_ctx_get_concrete(libctx)
== ossl_lib_ctx_get_concrete(libctx2)))
return;
cbdata.libctx = libctx2;
algorithm_do_this(provider, &cbdata);
}
}
char *ossl_algorithm_get1_first_name(const OSSL_ALGORITHM *algo)
{
const char *first_name_end = NULL;
size_t first_name_len = 0;
char *ret;
if (algo->algorithm_names == NULL)
return NULL;
first_name_end = strchr(algo->algorithm_names, ':');
if (first_name_end == NULL)
first_name_len = strlen(algo->algorithm_names);
else
first_name_len = first_name_end - algo->algorithm_names;
ret = OPENSSL_strndup(algo->algorithm_names, first_name_len);
return ret;
}
| 6,639 | 32.535354 | 79 | c |
openssl | openssl-master/crypto/core_fetch.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 <stddef.h>
#include <openssl/core.h>
#include "internal/cryptlib.h"
#include "internal/core.h"
#include "internal/property.h"
#include "internal/provider.h"
struct construct_data_st {
OSSL_LIB_CTX *libctx;
OSSL_METHOD_STORE *store;
int operation_id;
int force_store;
OSSL_METHOD_CONSTRUCT_METHOD *mcm;
void *mcm_data;
};
static int is_temporary_method_store(int no_store, void *cbdata)
{
struct construct_data_st *data = cbdata;
return no_store && !data->force_store;
}
static int ossl_method_construct_reserve_store(int no_store, void *cbdata)
{
struct construct_data_st *data = cbdata;
if (is_temporary_method_store(no_store, data) && data->store == NULL) {
/*
* If we have been told not to store the method "permanently", we
* ask for a temporary store, and store the method there.
* The owner of |data->mcm| is completely responsible for managing
* that temporary store.
*/
if ((data->store = data->mcm->get_tmp_store(data->mcm_data)) == NULL)
return 0;
}
return data->mcm->lock_store(data->store, data->mcm_data);
}
static int ossl_method_construct_unreserve_store(void *cbdata)
{
struct construct_data_st *data = cbdata;
return data->mcm->unlock_store(data->store, data->mcm_data);
}
static int ossl_method_construct_precondition(OSSL_PROVIDER *provider,
int operation_id, int no_store,
void *cbdata, int *result)
{
if (!ossl_assert(result != NULL)) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
/* Assume that no bits are set */
*result = 0;
/* No flag bits for temporary stores */
if (!is_temporary_method_store(no_store, cbdata)
&& !ossl_provider_test_operation_bit(provider, operation_id, result))
return 0;
/*
* The result we get tells if methods have already been constructed.
* However, we want to tell whether construction should happen (true)
* or not (false), which is the opposite of what we got.
*/
*result = !*result;
return 1;
}
static int ossl_method_construct_postcondition(OSSL_PROVIDER *provider,
int operation_id, int no_store,
void *cbdata, int *result)
{
if (!ossl_assert(result != NULL)) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
*result = 1;
/* No flag bits for temporary stores */
return is_temporary_method_store(no_store, cbdata)
|| ossl_provider_set_operation_bit(provider, operation_id);
}
static void ossl_method_construct_this(OSSL_PROVIDER *provider,
const OSSL_ALGORITHM *algo,
int no_store, void *cbdata)
{
struct construct_data_st *data = cbdata;
void *method = NULL;
if ((method = data->mcm->construct(algo, provider, data->mcm_data))
== NULL)
return;
/*
* Note regarding putting the method in stores:
*
* we don't need to care if it actually got in or not here.
* If it didn't get in, it will simply not be available when
* ossl_method_construct() tries to get it from the store.
*
* It is *expected* that the put function increments the refcnt
* of the passed method.
*/
data->mcm->put(data->store, method, provider, algo->algorithm_names,
algo->property_definition, data->mcm_data);
/* refcnt-- because we're dropping the reference */
data->mcm->destruct(method, data->mcm_data);
}
void *ossl_method_construct(OSSL_LIB_CTX *libctx, int operation_id,
OSSL_PROVIDER **provider_rw, int force_store,
OSSL_METHOD_CONSTRUCT_METHOD *mcm, void *mcm_data)
{
void *method = NULL;
OSSL_PROVIDER *provider = provider_rw != NULL ? *provider_rw : NULL;
struct construct_data_st cbdata;
/*
* We might be tempted to try to look into the method store without
* constructing to see if we can find our method there already.
* Unfortunately that does not work well if the query contains
* optional properties as newly loaded providers can match them better.
* We trust that ossl_method_construct_precondition() and
* ossl_method_construct_postcondition() make sure that the
* ossl_algorithm_do_all() does very little when methods from
* a provider have already been constructed.
*/
cbdata.store = NULL;
cbdata.force_store = force_store;
cbdata.mcm = mcm;
cbdata.mcm_data = mcm_data;
ossl_algorithm_do_all(libctx, operation_id, provider,
ossl_method_construct_precondition,
ossl_method_construct_reserve_store,
ossl_method_construct_this,
ossl_method_construct_unreserve_store,
ossl_method_construct_postcondition,
&cbdata);
/* If there is a temporary store, try there first */
if (cbdata.store != NULL)
method = mcm->get(cbdata.store, (const OSSL_PROVIDER **)provider_rw,
mcm_data);
/* If no method was found yet, try the global store */
if (method == NULL)
method = mcm->get(NULL, (const OSSL_PROVIDER **)provider_rw, mcm_data);
return method;
}
| 5,884 | 33.215116 | 79 | c |
openssl | openssl-master/crypto/core_namemap.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 "internal/namemap.h"
#include <openssl/lhash.h>
#include "crypto/lhash.h" /* ossl_lh_strcasehash */
#include "internal/tsan_assist.h"
#include "internal/sizes.h"
#include "crypto/context.h"
/*-
* The namenum entry
* =================
*/
typedef struct {
char *name;
int number;
} NAMENUM_ENTRY;
DEFINE_LHASH_OF_EX(NAMENUM_ENTRY);
/*-
* The namemap itself
* ==================
*/
struct ossl_namemap_st {
/* Flags */
unsigned int stored:1; /* If 1, it's stored in a library context */
CRYPTO_RWLOCK *lock;
LHASH_OF(NAMENUM_ENTRY) *namenum; /* Name->number mapping */
TSAN_QUALIFIER int max_number; /* Current max number */
};
/* LHASH callbacks */
static unsigned long namenum_hash(const NAMENUM_ENTRY *n)
{
return ossl_lh_strcasehash(n->name);
}
static int namenum_cmp(const NAMENUM_ENTRY *a, const NAMENUM_ENTRY *b)
{
return OPENSSL_strcasecmp(a->name, b->name);
}
static void namenum_free(NAMENUM_ENTRY *n)
{
if (n != NULL)
OPENSSL_free(n->name);
OPENSSL_free(n);
}
/* OSSL_LIB_CTX_METHOD functions for a namemap stored in a library context */
void *ossl_stored_namemap_new(OSSL_LIB_CTX *libctx)
{
OSSL_NAMEMAP *namemap = ossl_namemap_new();
if (namemap != NULL)
namemap->stored = 1;
return namemap;
}
void ossl_stored_namemap_free(void *vnamemap)
{
OSSL_NAMEMAP *namemap = vnamemap;
if (namemap != NULL) {
/* Pretend it isn't stored, or ossl_namemap_free() will do nothing */
namemap->stored = 0;
ossl_namemap_free(namemap);
}
}
/*-
* API functions
* =============
*/
int ossl_namemap_empty(OSSL_NAMEMAP *namemap)
{
#ifdef TSAN_REQUIRES_LOCKING
/* No TSAN support */
int rv;
if (namemap == NULL)
return 1;
if (!CRYPTO_THREAD_read_lock(namemap->lock))
return -1;
rv = namemap->max_number == 0;
CRYPTO_THREAD_unlock(namemap->lock);
return rv;
#else
/* Have TSAN support */
return namemap == NULL || tsan_load(&namemap->max_number) == 0;
#endif
}
typedef struct doall_names_data_st {
int number;
const char **names;
int found;
} DOALL_NAMES_DATA;
static void do_name(const NAMENUM_ENTRY *namenum, DOALL_NAMES_DATA *data)
{
if (namenum->number == data->number)
data->names[data->found++] = namenum->name;
}
IMPLEMENT_LHASH_DOALL_ARG_CONST(NAMENUM_ENTRY, DOALL_NAMES_DATA);
/*
* Call the callback for all names in the namemap with the given number.
* A return value 1 means that the callback was called for all names. A
* return value of 0 means that the callback was not called for any names.
*/
int ossl_namemap_doall_names(const OSSL_NAMEMAP *namemap, int number,
void (*fn)(const char *name, void *data),
void *data)
{
DOALL_NAMES_DATA cbdata;
size_t num_names;
int i;
cbdata.number = number;
cbdata.found = 0;
if (namemap == NULL)
return 0;
/*
* We collect all the names first under a read lock. Subsequently we call
* the user function, so that we're not holding the read lock when in user
* code. This could lead to deadlocks.
*/
if (!CRYPTO_THREAD_read_lock(namemap->lock))
return 0;
num_names = lh_NAMENUM_ENTRY_num_items(namemap->namenum);
if (num_names == 0) {
CRYPTO_THREAD_unlock(namemap->lock);
return 0;
}
cbdata.names = OPENSSL_malloc(sizeof(*cbdata.names) * num_names);
if (cbdata.names == NULL) {
CRYPTO_THREAD_unlock(namemap->lock);
return 0;
}
lh_NAMENUM_ENTRY_doall_DOALL_NAMES_DATA(namemap->namenum, do_name,
&cbdata);
CRYPTO_THREAD_unlock(namemap->lock);
for (i = 0; i < cbdata.found; i++)
fn(cbdata.names[i], data);
OPENSSL_free(cbdata.names);
return 1;
}
/* This function is not thread safe, the namemap must be locked */
static int namemap_name2num(const OSSL_NAMEMAP *namemap,
const char *name)
{
NAMENUM_ENTRY *namenum_entry, namenum_tmpl;
namenum_tmpl.name = (char *)name;
namenum_tmpl.number = 0;
namenum_entry =
lh_NAMENUM_ENTRY_retrieve(namemap->namenum, &namenum_tmpl);
return namenum_entry != NULL ? namenum_entry->number : 0;
}
int ossl_namemap_name2num(const OSSL_NAMEMAP *namemap, const char *name)
{
int number;
#ifndef FIPS_MODULE
if (namemap == NULL)
namemap = ossl_namemap_stored(NULL);
#endif
if (namemap == NULL)
return 0;
if (!CRYPTO_THREAD_read_lock(namemap->lock))
return 0;
number = namemap_name2num(namemap, name);
CRYPTO_THREAD_unlock(namemap->lock);
return number;
}
int ossl_namemap_name2num_n(const OSSL_NAMEMAP *namemap,
const char *name, size_t name_len)
{
char *tmp;
int ret;
if (name == NULL || (tmp = OPENSSL_strndup(name, name_len)) == NULL)
return 0;
ret = ossl_namemap_name2num(namemap, tmp);
OPENSSL_free(tmp);
return ret;
}
struct num2name_data_st {
size_t idx; /* Countdown */
const char *name; /* Result */
};
static void do_num2name(const char *name, void *vdata)
{
struct num2name_data_st *data = vdata;
if (data->idx > 0)
data->idx--;
else if (data->name == NULL)
data->name = name;
}
const char *ossl_namemap_num2name(const OSSL_NAMEMAP *namemap, int number,
size_t idx)
{
struct num2name_data_st data;
data.idx = idx;
data.name = NULL;
if (!ossl_namemap_doall_names(namemap, number, do_num2name, &data))
return NULL;
return data.name;
}
/* This function is not thread safe, the namemap must be locked */
static int namemap_add_name(OSSL_NAMEMAP *namemap, int number,
const char *name)
{
NAMENUM_ENTRY *namenum = NULL;
int tmp_number;
/* If it already exists, we don't add it */
if ((tmp_number = namemap_name2num(namemap, name)) != 0)
return tmp_number;
if ((namenum = OPENSSL_zalloc(sizeof(*namenum))) == NULL)
return 0;
if ((namenum->name = OPENSSL_strdup(name)) == NULL)
goto err;
/* The tsan_counter use here is safe since we're under lock */
namenum->number =
number != 0 ? number : 1 + tsan_counter(&namemap->max_number);
(void)lh_NAMENUM_ENTRY_insert(namemap->namenum, namenum);
if (lh_NAMENUM_ENTRY_error(namemap->namenum))
goto err;
return namenum->number;
err:
namenum_free(namenum);
return 0;
}
int ossl_namemap_add_name(OSSL_NAMEMAP *namemap, int number,
const char *name)
{
int tmp_number;
#ifndef FIPS_MODULE
if (namemap == NULL)
namemap = ossl_namemap_stored(NULL);
#endif
if (name == NULL || *name == 0 || namemap == NULL)
return 0;
if (!CRYPTO_THREAD_write_lock(namemap->lock))
return 0;
tmp_number = namemap_add_name(namemap, number, name);
CRYPTO_THREAD_unlock(namemap->lock);
return tmp_number;
}
int ossl_namemap_add_names(OSSL_NAMEMAP *namemap, int number,
const char *names, const char separator)
{
char *tmp, *p, *q, *endp;
/* Check that we have a namemap */
if (!ossl_assert(namemap != NULL)) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if ((tmp = OPENSSL_strdup(names)) == NULL)
return 0;
if (!CRYPTO_THREAD_write_lock(namemap->lock)) {
OPENSSL_free(tmp);
return 0;
}
/*
* Check that no name is an empty string, and that all names have at
* most one numeric identity together.
*/
for (p = tmp; *p != '\0'; p = q) {
int this_number;
size_t l;
if ((q = strchr(p, separator)) == NULL) {
l = strlen(p); /* offset to \0 */
q = p + l;
} else {
l = q - p; /* offset to the next separator */
*q++ = '\0';
}
if (*p == '\0') {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_BAD_ALGORITHM_NAME);
number = 0;
goto end;
}
this_number = namemap_name2num(namemap, p);
if (number == 0) {
number = this_number;
} else if (this_number != 0 && this_number != number) {
ERR_raise_data(ERR_LIB_CRYPTO, CRYPTO_R_CONFLICTING_NAMES,
"\"%s\" has an existing different identity %d (from \"%s\")",
p, this_number, names);
number = 0;
goto end;
}
}
endp = p;
/* Now that we have checked, register all names */
for (p = tmp; p < endp; p = q) {
int this_number;
q = p + strlen(p) + 1;
this_number = namemap_add_name(namemap, number, p);
if (number == 0) {
number = this_number;
} else if (this_number != number) {
ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR,
"Got number %d when expecting %d",
this_number, number);
number = 0;
goto end;
}
}
end:
CRYPTO_THREAD_unlock(namemap->lock);
OPENSSL_free(tmp);
return number;
}
/*-
* Pre-population
* ==============
*/
#ifndef FIPS_MODULE
#include <openssl/evp.h>
/* Creates an initial namemap with names found in the legacy method db */
static void get_legacy_evp_names(int base_nid, int nid, const char *pem_name,
void *arg)
{
int num = 0;
ASN1_OBJECT *obj;
if (base_nid != NID_undef) {
num = ossl_namemap_add_name(arg, num, OBJ_nid2sn(base_nid));
num = ossl_namemap_add_name(arg, num, OBJ_nid2ln(base_nid));
}
if (nid != NID_undef) {
num = ossl_namemap_add_name(arg, num, OBJ_nid2sn(nid));
num = ossl_namemap_add_name(arg, num, OBJ_nid2ln(nid));
if ((obj = OBJ_nid2obj(nid)) != NULL) {
char txtoid[OSSL_MAX_NAME_SIZE];
if (OBJ_obj2txt(txtoid, sizeof(txtoid), obj, 1) > 0)
num = ossl_namemap_add_name(arg, num, txtoid);
}
}
if (pem_name != NULL)
num = ossl_namemap_add_name(arg, num, pem_name);
}
static void get_legacy_cipher_names(const OBJ_NAME *on, void *arg)
{
const EVP_CIPHER *cipher = (void *)OBJ_NAME_get(on->name, on->type);
if (cipher != NULL)
get_legacy_evp_names(NID_undef, EVP_CIPHER_get_type(cipher), NULL, arg);
}
static void get_legacy_md_names(const OBJ_NAME *on, void *arg)
{
const EVP_MD *md = (void *)OBJ_NAME_get(on->name, on->type);
if (md != NULL)
get_legacy_evp_names(0, EVP_MD_get_type(md), NULL, arg);
}
static void get_legacy_pkey_meth_names(const EVP_PKEY_ASN1_METHOD *ameth,
void *arg)
{
int nid = 0, base_nid = 0, flags = 0;
const char *pem_name = NULL;
EVP_PKEY_asn1_get0_info(&nid, &base_nid, &flags, NULL, &pem_name, ameth);
if (nid != NID_undef) {
if ((flags & ASN1_PKEY_ALIAS) == 0) {
switch (nid) {
case EVP_PKEY_DHX:
/* We know that the name "DHX" is used too */
get_legacy_evp_names(0, nid, "DHX", arg);
/* FALLTHRU */
default:
get_legacy_evp_names(0, nid, pem_name, arg);
}
} else {
/*
* Treat aliases carefully, some of them are undesirable, or
* should not be treated as such for providers.
*/
switch (nid) {
case EVP_PKEY_SM2:
/*
* SM2 is a separate keytype with providers, not an alias for
* EC.
*/
get_legacy_evp_names(0, nid, pem_name, arg);
break;
default:
/* Use the short name of the base nid as the common reference */
get_legacy_evp_names(base_nid, nid, pem_name, arg);
}
}
}
}
#endif
/*-
* Constructors / destructors
* ==========================
*/
OSSL_NAMEMAP *ossl_namemap_stored(OSSL_LIB_CTX *libctx)
{
#ifndef FIPS_MODULE
int nms;
#endif
OSSL_NAMEMAP *namemap =
ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_NAMEMAP_INDEX);
if (namemap == NULL)
return NULL;
#ifndef FIPS_MODULE
nms = ossl_namemap_empty(namemap);
if (nms < 0) {
/*
* Could not get lock to make the count, so maybe internal objects
* weren't added. This seems safest.
*/
return NULL;
}
if (nms == 1) {
int i, end;
/* Before pilfering, we make sure the legacy database is populated */
OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
| OPENSSL_INIT_ADD_ALL_DIGESTS, NULL);
OBJ_NAME_do_all(OBJ_NAME_TYPE_CIPHER_METH,
get_legacy_cipher_names, namemap);
OBJ_NAME_do_all(OBJ_NAME_TYPE_MD_METH,
get_legacy_md_names, namemap);
/* We also pilfer data from the legacy EVP_PKEY_ASN1_METHODs */
for (i = 0, end = EVP_PKEY_asn1_get_count(); i < end; i++)
get_legacy_pkey_meth_names(EVP_PKEY_asn1_get0(i), namemap);
}
#endif
return namemap;
}
OSSL_NAMEMAP *ossl_namemap_new(void)
{
OSSL_NAMEMAP *namemap;
if ((namemap = OPENSSL_zalloc(sizeof(*namemap))) != NULL
&& (namemap->lock = CRYPTO_THREAD_lock_new()) != NULL
&& (namemap->namenum =
lh_NAMENUM_ENTRY_new(namenum_hash, namenum_cmp)) != NULL)
return namemap;
ossl_namemap_free(namemap);
return NULL;
}
void ossl_namemap_free(OSSL_NAMEMAP *namemap)
{
if (namemap == NULL || namemap->stored)
return;
lh_NAMENUM_ENTRY_doall(namemap->namenum, namenum_free);
lh_NAMENUM_ENTRY_free(namemap->namenum);
CRYPTO_THREAD_lock_free(namemap->lock);
OPENSSL_free(namemap);
}
| 14,374 | 25.81903 | 88 | c |
openssl | openssl-master/crypto/cpt_err.c | /*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/err.h>
#include <openssl/cryptoerr.h>
#include "crypto/cryptoerr.h"
#ifndef OPENSSL_NO_ERR
static const ERR_STRING_DATA CRYPTO_str_reasons[] = {
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_BAD_ALGORITHM_NAME),
"bad algorithm name"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_CONFLICTING_NAMES),
"conflicting names"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_HEX_STRING_TOO_SHORT),
"hex string too short"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_ILLEGAL_HEX_DIGIT),
"illegal hex digit"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_INSUFFICIENT_DATA_SPACE),
"insufficient data space"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_INSUFFICIENT_PARAM_SIZE),
"insufficient param size"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_INSUFFICIENT_SECURE_DATA_SPACE),
"insufficient secure data space"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_INTEGER_OVERFLOW),
"integer overflow"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_INVALID_NEGATIVE_VALUE),
"invalid negative value"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_INVALID_NULL_ARGUMENT),
"invalid null argument"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_INVALID_OSSL_PARAM_TYPE),
"invalid ossl param type"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_NO_PARAMS_TO_MERGE),
"no params to merge"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_NO_SPACE_FOR_TERMINATING_NULL),
"no space for terminating null"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_ODD_NUMBER_OF_DIGITS),
"odd number of digits"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_PARAM_CANNOT_BE_REPRESENTED_EXACTLY),
"param cannot be represented exactly"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_PARAM_NOT_INTEGER_TYPE),
"param not integer type"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_PARAM_OF_INCOMPATIBLE_TYPE),
"param of incompatible type"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_PARAM_UNSIGNED_INTEGER_NEGATIVE_VALUE_UNSUPPORTED),
"param unsigned integer negative value unsupported"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_PARAM_UNSUPPORTED_FLOATING_POINT_FORMAT),
"param unsupported floating point format"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_PARAM_VALUE_TOO_LARGE_FOR_DESTINATION),
"param value too large for destination"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_PROVIDER_ALREADY_EXISTS),
"provider already exists"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_PROVIDER_SECTION_ERROR),
"provider section error"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_RANDOM_SECTION_ERROR),
"random section error"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_SECURE_MALLOC_FAILURE),
"secure malloc failure"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_STRING_TOO_LONG), "string too long"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_TOO_MANY_BYTES), "too many bytes"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_TOO_MANY_RECORDS),
"too many records"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_TOO_SMALL_BUFFER),
"too small buffer"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_UNKNOWN_NAME_IN_RANDOM_SECTION),
"unknown name in random section"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, CRYPTO_R_ZERO_LENGTH_NUMBER),
"zero length number"},
{0, NULL}
};
#endif
int ossl_err_load_CRYPTO_strings(void)
{
#ifndef OPENSSL_NO_ERR
if (ERR_reason_error_string(CRYPTO_str_reasons[0].error) == NULL)
ERR_load_strings_const(CRYPTO_str_reasons);
#endif
return 1;
}
| 3,791 | 41.606742 | 93 | c |
openssl | openssl-master/crypto/cpuid.c | /*
* Copyright 1998-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/e_os.h"
#include "crypto/cryptlib.h"
#if defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
defined(__x86_64) || defined(__x86_64__) || \
defined(_M_AMD64) || defined(_M_X64)
extern unsigned int OPENSSL_ia32cap_P[4];
# if defined(OPENSSL_CPUID_OBJ)
/*
* Purpose of these minimalistic and character-type-agnostic subroutines
* is to break dependency on MSVCRT (on Windows) and locale. This makes
* OPENSSL_cpuid_setup safe to use as "constructor". "Character-type-
* agnostic" means that they work with either wide or 8-bit characters,
* exploiting the fact that first 127 characters can be simply casted
* between the sets, while the rest would be simply rejected by ossl_is*
* subroutines.
*/
# ifdef _WIN32
typedef WCHAR variant_char;
static variant_char *ossl_getenv(const char *name)
{
/*
* Since we pull only one environment variable, it's simpler to
* to just ignore |name| and use equivalent wide-char L-literal.
* As well as to ignore excessively long values...
*/
static WCHAR value[48];
DWORD len = GetEnvironmentVariableW(L"OPENSSL_ia32cap", value, 48);
return (len > 0 && len < 48) ? value : NULL;
}
# else
typedef char variant_char;
# define ossl_getenv getenv
# endif
# include "crypto/ctype.h"
static int todigit(variant_char c)
{
if (ossl_isdigit(c))
return c - '0';
else if (ossl_isxdigit(c))
return ossl_tolower(c) - 'a' + 10;
/* return largest base value to make caller terminate the loop */
return 16;
}
static uint64_t ossl_strtouint64(const variant_char *str)
{
uint64_t ret = 0;
unsigned int digit, base = 10;
if (*str == '0') {
base = 8, str++;
if (ossl_tolower(*str) == 'x')
base = 16, str++;
}
while ((digit = todigit(*str++)) < base)
ret = ret * base + digit;
return ret;
}
static variant_char *ossl_strchr(const variant_char *str, char srch)
{ variant_char c;
while ((c = *str)) {
if (c == srch)
return (variant_char *)str;
str++;
}
return NULL;
}
# define OPENSSL_CPUID_SETUP
typedef uint64_t IA32CAP;
void OPENSSL_cpuid_setup(void)
{
static int trigger = 0;
IA32CAP OPENSSL_ia32_cpuid(unsigned int *);
IA32CAP vec;
const variant_char *env;
if (trigger)
return;
trigger = 1;
if ((env = ossl_getenv("OPENSSL_ia32cap")) != NULL) {
int off = (env[0] == '~') ? 1 : 0;
vec = ossl_strtouint64(env + off);
if (off) {
IA32CAP mask = vec;
vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P) & ~mask;
if (mask & (1<<24)) {
/*
* User disables FXSR bit, mask even other capabilities
* that operate exclusively on XMM, so we don't have to
* double-check all the time. We mask PCLMULQDQ, AMD XOP,
* AES-NI and AVX. Formally speaking we don't have to
* do it in x86_64 case, but we can safely assume that
* x86_64 users won't actually flip this flag.
*/
vec &= ~((IA32CAP)(1<<1|1<<11|1<<25|1<<28) << 32);
}
} else if (env[0] == ':') {
vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
}
if ((env = ossl_strchr(env, ':')) != NULL) {
IA32CAP vecx;
env++;
off = (env[0] == '~') ? 1 : 0;
vecx = ossl_strtouint64(env + off);
if (off) {
OPENSSL_ia32cap_P[2] &= ~(unsigned int)vecx;
OPENSSL_ia32cap_P[3] &= ~(unsigned int)(vecx >> 32);
} else {
OPENSSL_ia32cap_P[2] = (unsigned int)vecx;
OPENSSL_ia32cap_P[3] = (unsigned int)(vecx >> 32);
}
} else {
OPENSSL_ia32cap_P[2] = 0;
OPENSSL_ia32cap_P[3] = 0;
}
} else {
vec = OPENSSL_ia32_cpuid(OPENSSL_ia32cap_P);
}
/*
* |(1<<10) sets a reserved bit to signal that variable
* was initialized already... This is to avoid interference
* with cpuid snippets in ELF .init segment.
*/
OPENSSL_ia32cap_P[0] = (unsigned int)vec | (1 << 10);
OPENSSL_ia32cap_P[1] = (unsigned int)(vec >> 32);
}
# else
unsigned int OPENSSL_ia32cap_P[4];
# endif
#endif
#ifndef OPENSSL_CPUID_OBJ
# ifndef OPENSSL_CPUID_SETUP
void OPENSSL_cpuid_setup(void)
{
}
# endif
/*
* The rest are functions that are defined in the same assembler files as
* the CPUID functionality.
*/
/*
* The volatile is used to to ensure that the compiler generates code that reads
* all values from the array and doesn't try to optimize this away. The standard
* doesn't actually require this behavior if the original data pointed to is
* not volatile, but compilers do this in practice anyway.
*
* There are also assembler versions of this function.
*/
# undef CRYPTO_memcmp
int CRYPTO_memcmp(const void * in_a, const void * in_b, size_t len)
{
size_t i;
const volatile unsigned char *a = in_a;
const volatile unsigned char *b = in_b;
unsigned char x = 0;
for (i = 0; i < len; i++)
x |= a[i] ^ b[i];
return x;
}
/*
* For systems that don't provide an instruction counter register or equivalent.
*/
uint32_t OPENSSL_rdtsc(void)
{
return 0;
}
size_t OPENSSL_instrument_bus(unsigned int *out, size_t cnt)
{
return 0;
}
size_t OPENSSL_instrument_bus2(unsigned int *out, size_t cnt, size_t max)
{
return 0;
}
#endif
| 5,895 | 26.423256 | 80 | c |
openssl | openssl-master/crypto/cryptlib.c | /*
* Copyright 1998-2022 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
*/
#include "internal/e_os.h"
#include "crypto/cryptlib.h"
#include <openssl/safestack.h>
#if defined(_WIN32) && !defined(OPENSSL_SYS_UEFI)
# include <tchar.h>
# include <signal.h>
# ifdef __WATCOMC__
# if defined(_UNICODE) || defined(__UNICODE__)
# define _vsntprintf _vsnwprintf
# else
# define _vsntprintf _vsnprintf
# endif
# endif
# ifdef _MSC_VER
# define alloca _alloca
# endif
# if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
# ifdef OPENSSL_SYS_WIN_CORE
int OPENSSL_isservice(void)
{
/* OneCore API cannot interact with GUI */
return 1;
}
# else
int OPENSSL_isservice(void)
{
HWINSTA h;
DWORD len;
WCHAR *name;
static union {
void *p;
FARPROC f;
} _OPENSSL_isservice = {
NULL
};
if (_OPENSSL_isservice.p == NULL) {
HANDLE mod = GetModuleHandle(NULL);
FARPROC f = NULL;
if (mod != NULL)
f = GetProcAddress(mod, "_OPENSSL_isservice");
if (f == NULL)
_OPENSSL_isservice.p = (void *)-1;
else
_OPENSSL_isservice.f = f;
}
if (_OPENSSL_isservice.p != (void *)-1)
return (*_OPENSSL_isservice.f) ();
h = GetProcessWindowStation();
if (h == NULL)
return -1;
if (GetUserObjectInformationW(h, UOI_NAME, NULL, 0, &len) ||
GetLastError() != ERROR_INSUFFICIENT_BUFFER)
return -1;
if (len > 512)
return -1; /* paranoia */
len++, len &= ~1; /* paranoia */
name = (WCHAR *)alloca(len + sizeof(WCHAR));
if (!GetUserObjectInformationW(h, UOI_NAME, name, len, &len))
return -1;
len++, len &= ~1; /* paranoia */
name[len / sizeof(WCHAR)] = L'\0'; /* paranoia */
# if 1
/*
* This doesn't cover "interactive" services [working with real
* WinSta0's] nor programs started non-interactively by Task Scheduler
* [those are working with SAWinSta].
*/
if (wcsstr(name, L"Service-0x"))
return 1;
# else
/* This covers all non-interactive programs such as services. */
if (!wcsstr(name, L"WinSta0"))
return 1;
# endif
else
return 0;
}
# endif
# else
int OPENSSL_isservice(void)
{
return 0;
}
# endif
void OPENSSL_showfatal(const char *fmta, ...)
{
va_list ap;
TCHAR buf[256];
const TCHAR *fmt;
/*
* First check if it's a console application, in which case the
* error message would be printed to standard error.
* Windows CE does not have a concept of a console application,
* so we need to guard the check.
*/
# ifdef STD_ERROR_HANDLE
HANDLE h;
if ((h = GetStdHandle(STD_ERROR_HANDLE)) != NULL &&
GetFileType(h) != FILE_TYPE_UNKNOWN) {
/* must be console application */
int len;
DWORD out;
va_start(ap, fmta);
len = _vsnprintf((char *)buf, sizeof(buf), fmta, ap);
WriteFile(h, buf, len < 0 ? sizeof(buf) : (DWORD) len, &out, NULL);
va_end(ap);
return;
}
# endif
if (sizeof(TCHAR) == sizeof(char))
fmt = (const TCHAR *)fmta;
else
do {
int keepgoing;
size_t len_0 = strlen(fmta) + 1, i;
WCHAR *fmtw;
fmtw = (WCHAR *)alloca(len_0 * sizeof(WCHAR));
if (fmtw == NULL) {
fmt = (const TCHAR *)L"no stack?";
break;
}
if (!MultiByteToWideChar(CP_ACP, 0, fmta, len_0, fmtw, len_0))
for (i = 0; i < len_0; i++)
fmtw[i] = (WCHAR)fmta[i];
for (i = 0; i < len_0; i++) {
if (fmtw[i] == L'%')
do {
keepgoing = 0;
switch (fmtw[i + 1]) {
case L'0':
case L'1':
case L'2':
case L'3':
case L'4':
case L'5':
case L'6':
case L'7':
case L'8':
case L'9':
case L'.':
case L'*':
case L'-':
i++;
keepgoing = 1;
break;
case L's':
fmtw[i + 1] = L'S';
break;
case L'S':
fmtw[i + 1] = L's';
break;
case L'c':
fmtw[i + 1] = L'C';
break;
case L'C':
fmtw[i + 1] = L'c';
break;
}
} while (keepgoing);
}
fmt = (const TCHAR *)fmtw;
} while (0);
va_start(ap, fmta);
_vsntprintf(buf, OSSL_NELEM(buf) - 1, fmt, ap);
buf[OSSL_NELEM(buf) - 1] = _T('\0');
va_end(ap);
# if defined(_WIN32_WINNT) && _WIN32_WINNT>=0x0333
# ifdef OPENSSL_SYS_WIN_CORE
/* ONECORE is always NONGUI and NT >= 0x0601 */
# if !defined(NDEBUG)
/*
* We are in a situation where we tried to report a critical
* error and this failed for some reason. As a last resort,
* in debug builds, send output to the debugger or any other
* tool like DebugView which can monitor the output.
*/
OutputDebugString(buf);
# endif
# else
/* this -------------v--- guards NT-specific calls */
if (check_winnt() && OPENSSL_isservice() > 0) {
HANDLE hEventLog = RegisterEventSource(NULL, _T("OpenSSL"));
if (hEventLog != NULL) {
const TCHAR *pmsg = buf;
if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, 0, 0, NULL,
1, 0, &pmsg, NULL)) {
# if !defined(NDEBUG)
/*
* We are in a situation where we tried to report a critical
* error and this failed for some reason. As a last resort,
* in debug builds, send output to the debugger or any other
* tool like DebugView which can monitor the output.
*/
OutputDebugString(pmsg);
# endif
}
(void)DeregisterEventSource(hEventLog);
}
} else {
MessageBox(NULL, buf, _T("OpenSSL: FATAL"), MB_OK | MB_ICONERROR);
}
# endif
# else
MessageBox(NULL, buf, _T("OpenSSL: FATAL"), MB_OK | MB_ICONERROR);
# endif
}
#else
void OPENSSL_showfatal(const char *fmta, ...)
{
#ifndef OPENSSL_NO_STDIO
va_list ap;
va_start(ap, fmta);
vfprintf(stderr, fmta, ap);
va_end(ap);
#endif
}
int OPENSSL_isservice(void)
{
return 0;
}
#endif
void OPENSSL_die(const char *message, const char *file, int line)
{
OPENSSL_showfatal("%s:%d: OpenSSL internal error: %s\n",
file, line, message);
#if !defined(_WIN32) || defined(OPENSSL_SYS_UEFI)
abort();
#else
/*
* Win32 abort() customarily shows a dialog, but we just did that...
*/
# if !defined(_WIN32_WCE)
raise(SIGABRT);
# endif
_exit(3);
#endif
}
#if defined(__TANDEM) && defined(OPENSSL_VPROC)
/*
* Define a VPROC function for HP NonStop build crypto library.
* This is used by platform version identification tools.
* Do not inline this procedure or make it static.
*/
# define OPENSSL_VPROC_STRING_(x) x##_CRYPTO
# define OPENSSL_VPROC_STRING(x) OPENSSL_VPROC_STRING_(x)
# define OPENSSL_VPROC_FUNC OPENSSL_VPROC_STRING(OPENSSL_VPROC)
void OPENSSL_VPROC_FUNC(void) {}
#endif /* __TANDEM */
| 8,134 | 27.745583 | 76 | c |
openssl | openssl-master/crypto/ctype.c | /*
* Copyright 2017-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 <stdio.h>
#include "crypto/ctype.h"
#include <openssl/ebcdic.h>
/*
* Define the character classes for each character in the seven bit ASCII
* character set. This is independent of the host's character set, characters
* are converted to ASCII before being used as an index in to this table.
* Characters outside of the seven bit ASCII range are detected before indexing.
*/
static const unsigned short ctype_char_map[128] = {
/* 00 nul */ CTYPE_MASK_cntrl,
/* 01 soh */ CTYPE_MASK_cntrl,
/* 02 stx */ CTYPE_MASK_cntrl,
/* 03 etx */ CTYPE_MASK_cntrl,
/* 04 eot */ CTYPE_MASK_cntrl,
/* 05 enq */ CTYPE_MASK_cntrl,
/* 06 ack */ CTYPE_MASK_cntrl,
/* 07 \a */ CTYPE_MASK_cntrl,
/* 08 \b */ CTYPE_MASK_cntrl,
/* 09 \t */ CTYPE_MASK_blank | CTYPE_MASK_cntrl | CTYPE_MASK_space,
/* 0A \n */ CTYPE_MASK_cntrl | CTYPE_MASK_space,
/* 0B \v */ CTYPE_MASK_cntrl | CTYPE_MASK_space,
/* 0C \f */ CTYPE_MASK_cntrl | CTYPE_MASK_space,
/* 0D \r */ CTYPE_MASK_cntrl | CTYPE_MASK_space,
/* 0E so */ CTYPE_MASK_cntrl,
/* 0F si */ CTYPE_MASK_cntrl,
/* 10 dle */ CTYPE_MASK_cntrl,
/* 11 dc1 */ CTYPE_MASK_cntrl,
/* 12 dc2 */ CTYPE_MASK_cntrl,
/* 13 dc3 */ CTYPE_MASK_cntrl,
/* 14 dc4 */ CTYPE_MASK_cntrl,
/* 15 nak */ CTYPE_MASK_cntrl,
/* 16 syn */ CTYPE_MASK_cntrl,
/* 17 etb */ CTYPE_MASK_cntrl,
/* 18 can */ CTYPE_MASK_cntrl,
/* 19 em */ CTYPE_MASK_cntrl,
/* 1A sub */ CTYPE_MASK_cntrl,
/* 1B esc */ CTYPE_MASK_cntrl,
/* 1C fs */ CTYPE_MASK_cntrl,
/* 1D gs */ CTYPE_MASK_cntrl,
/* 1E rs */ CTYPE_MASK_cntrl,
/* 1F us */ CTYPE_MASK_cntrl,
/* 20 */ CTYPE_MASK_blank | CTYPE_MASK_print | CTYPE_MASK_space
| CTYPE_MASK_asn1print,
/* 21 ! */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 22 " */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 23 # */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 24 $ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 25 % */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 26 & */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 27 ' */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct
| CTYPE_MASK_asn1print,
/* 28 ( */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct
| CTYPE_MASK_asn1print,
/* 29 ) */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct
| CTYPE_MASK_asn1print,
/* 2A * */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 2B + */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 2C , */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct
| CTYPE_MASK_asn1print,
/* 2D - */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct
| CTYPE_MASK_asn1print,
/* 2E . */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct
| CTYPE_MASK_asn1print,
/* 2F / */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 30 0 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 31 1 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 32 2 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 33 3 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 34 4 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 35 5 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 36 6 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 37 7 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 38 8 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 39 9 */ CTYPE_MASK_digit | CTYPE_MASK_graph | CTYPE_MASK_print
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 3A : */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct
| CTYPE_MASK_asn1print,
/* 3B ; */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 3C < */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 3D = */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 3E > */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 3F ? */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct
| CTYPE_MASK_asn1print,
/* 40 @ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 41 A */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 42 B */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 43 C */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 44 D */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 45 E */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 46 F */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 47 G */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 48 H */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 49 I */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 4A J */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 4B K */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 4C L */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 4D M */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 4E N */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 4F O */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 50 P */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 51 Q */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 52 R */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 53 S */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 54 T */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 55 U */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 56 V */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 57 W */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 58 X */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 59 Y */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 5A Z */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_upper
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 5B [ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 5C \ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 5D ] */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 5E ^ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 5F _ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 60 ` */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 61 a */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 62 b */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 63 c */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 64 d */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 65 e */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 66 f */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_xdigit | CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 67 g */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 68 h */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 69 i */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 6A j */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 6B k */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 6C l */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 6D m */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 6E n */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 6F o */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 70 p */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 71 q */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 72 r */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 73 s */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 74 t */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 75 u */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 76 v */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 77 w */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 78 x */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 79 y */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 7A z */ CTYPE_MASK_graph | CTYPE_MASK_lower | CTYPE_MASK_print
| CTYPE_MASK_base64 | CTYPE_MASK_asn1print,
/* 7B { */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 7C | */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 7D } */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 7E ~ */ CTYPE_MASK_graph | CTYPE_MASK_print | CTYPE_MASK_punct,
/* 7F del */ CTYPE_MASK_cntrl
};
#ifdef CHARSET_EBCDIC
int ossl_toascii(int c)
{
if (c < -128 || c > 256 || c == EOF)
return c;
/*
* Adjust negatively signed characters.
* This is not required for ASCII because any character that sign extends
* is not seven bit and all of the checks are on the seven bit characters.
* I.e. any check must fail on sign extension.
*/
if (c < 0)
c += 256;
return os_toascii[c];
}
int ossl_fromascii(int c)
{
if (c < -128 || c > 256 || c == EOF)
return c;
if (c < 0)
c += 256;
return os_toebcdic[c];
}
#endif
int ossl_ctype_check(int c, unsigned int mask)
{
const int max = sizeof(ctype_char_map) / sizeof(*ctype_char_map);
const int a = ossl_toascii(c);
return a >= 0 && a < max && (ctype_char_map[a] & mask) != 0;
}
/*
* Implement some of the simpler functions directly to avoid the overhead of
* accessing memory via ctype_char_map[].
*/
#define ASCII_IS_DIGIT(c) (c >= 0x30 && c <= 0x39)
#define ASCII_IS_UPPER(c) (c >= 0x41 && c <= 0x5A)
#define ASCII_IS_LOWER(c) (c >= 0x61 && c <= 0x7A)
int ossl_isdigit(int c)
{
int a = ossl_toascii(c);
return ASCII_IS_DIGIT(a);
}
int ossl_isupper(int c)
{
int a = ossl_toascii(c);
return ASCII_IS_UPPER(a);
}
int ossl_islower(int c)
{
int a = ossl_toascii(c);
return ASCII_IS_LOWER(a);
}
#if defined(CHARSET_EBCDIC) && !defined(CHARSET_EBCDIC_TEST)
static const int case_change = 0x40;
#else
static const int case_change = 0x20;
#endif
int ossl_tolower(int c)
{
int a = ossl_toascii(c);
return ASCII_IS_UPPER(a) ? c ^ case_change : c;
}
int ossl_toupper(int c)
{
int a = ossl_toascii(c);
return ASCII_IS_LOWER(a) ? c ^ case_change : c;
}
int ossl_ascii_isdigit(int c)
{
return ASCII_IS_DIGIT(c);
}
| 15,308 | 47.754777 | 80 | c |
openssl | openssl-master/crypto/cversion.c | /*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/cryptlib.h"
#include "buildinf.h"
unsigned long OpenSSL_version_num(void)
{
return OPENSSL_VERSION_NUMBER;
}
unsigned int OPENSSL_version_major(void)
{
return OPENSSL_VERSION_MAJOR;
}
unsigned int OPENSSL_version_minor(void)
{
return OPENSSL_VERSION_MINOR;
}
unsigned int OPENSSL_version_patch(void)
{
return OPENSSL_VERSION_PATCH;
}
const char *OPENSSL_version_pre_release(void)
{
return OPENSSL_VERSION_PRE_RELEASE;
}
const char *OPENSSL_version_build_metadata(void)
{
return OPENSSL_VERSION_BUILD_METADATA;
}
extern char ossl_cpu_info_str[];
const char *OpenSSL_version(int t)
{
switch (t) {
case OPENSSL_VERSION:
return OPENSSL_VERSION_TEXT;
case OPENSSL_VERSION_STRING:
return OPENSSL_VERSION_STR;
case OPENSSL_FULL_VERSION_STRING:
return OPENSSL_FULL_VERSION_STR;
case OPENSSL_BUILT_ON:
return DATE;
case OPENSSL_CFLAGS:
return compiler_flags;
case OPENSSL_PLATFORM:
return PLATFORM;
case OPENSSL_DIR:
#ifdef OPENSSLDIR
return "OPENSSLDIR: \"" OPENSSLDIR "\"";
#else
return "OPENSSLDIR: N/A";
#endif
case OPENSSL_ENGINES_DIR:
#ifdef ENGINESDIR
return "ENGINESDIR: \"" ENGINESDIR "\"";
#else
return "ENGINESDIR: N/A";
#endif
case OPENSSL_MODULES_DIR:
#ifdef MODULESDIR
return "MODULESDIR: \"" MODULESDIR "\"";
#else
return "MODULESDIR: N/A";
#endif
case OPENSSL_CPU_INFO:
if (OPENSSL_info(OPENSSL_INFO_CPU_SETTINGS) != NULL)
return ossl_cpu_info_str;
else
return "CPUINFO: N/A";
}
return "not available";
}
| 1,989 | 21.873563 | 74 | c |
openssl | openssl-master/crypto/der_writer.c | /*
* Copyright 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 <stdlib.h>
#include <string.h>
#include "internal/cryptlib.h"
#include "internal/der.h"
#include "crypto/bn.h"
static int int_start_context(WPACKET *pkt, int tag)
{
if (tag < 0)
return 1;
if (!ossl_assert(tag <= 30))
return 0;
return WPACKET_start_sub_packet(pkt);
}
static int int_end_context(WPACKET *pkt, int tag)
{
/*
* If someone set the flag WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH on this
* sub-packet and this sub-packet has nothing written to it, the DER length
* will not be written, and the total written size will be unchanged before
* and after WPACKET_close(). We use size1 and size2 to determine if
* anything was written, and only write our tag if it has.
*
*/
size_t size1, size2;
if (tag < 0)
return 1;
if (!ossl_assert(tag <= 30))
return 0;
/* Context specific are normally (?) constructed */
tag |= DER_F_CONSTRUCTED | DER_C_CONTEXT;
return WPACKET_get_total_written(pkt, &size1)
&& WPACKET_close(pkt)
&& WPACKET_get_total_written(pkt, &size2)
&& (size1 == size2 || WPACKET_put_bytes_u8(pkt, tag));
}
int ossl_DER_w_precompiled(WPACKET *pkt, int tag,
const unsigned char *precompiled,
size_t precompiled_n)
{
return int_start_context(pkt, tag)
&& WPACKET_memcpy(pkt, precompiled, precompiled_n)
&& int_end_context(pkt, tag);
}
int ossl_DER_w_boolean(WPACKET *pkt, int tag, int b)
{
return int_start_context(pkt, tag)
&& WPACKET_start_sub_packet(pkt)
&& (!b || WPACKET_put_bytes_u8(pkt, 0xFF))
&& !WPACKET_close(pkt)
&& !WPACKET_put_bytes_u8(pkt, DER_P_BOOLEAN)
&& int_end_context(pkt, tag);
}
int ossl_DER_w_octet_string(WPACKET *pkt, int tag,
const unsigned char *data, size_t data_n)
{
return int_start_context(pkt, tag)
&& WPACKET_start_sub_packet(pkt)
&& WPACKET_memcpy(pkt, data, data_n)
&& WPACKET_close(pkt)
&& WPACKET_put_bytes_u8(pkt, DER_P_OCTET_STRING)
&& int_end_context(pkt, tag);
}
int ossl_DER_w_octet_string_uint32(WPACKET *pkt, int tag, uint32_t value)
{
unsigned char tmp[4] = { 0, 0, 0, 0 };
unsigned char *pbuf = tmp + (sizeof(tmp) - 1);
while (value > 0) {
*pbuf-- = (value & 0xFF);
value >>= 8;
}
return ossl_DER_w_octet_string(pkt, tag, tmp, sizeof(tmp));
}
static int int_der_w_integer(WPACKET *pkt, int tag,
int (*put_bytes)(WPACKET *pkt, const void *v,
unsigned int *top_byte),
const void *v)
{
unsigned int top_byte = 0;
return int_start_context(pkt, tag)
&& WPACKET_start_sub_packet(pkt)
&& put_bytes(pkt, v, &top_byte)
&& ((top_byte & 0x80) == 0 || WPACKET_put_bytes_u8(pkt, 0))
&& WPACKET_close(pkt)
&& WPACKET_put_bytes_u8(pkt, DER_P_INTEGER)
&& int_end_context(pkt, tag);
}
static int int_put_bytes_uint32(WPACKET *pkt, const void *v,
unsigned int *top_byte)
{
const uint32_t *value = v;
uint32_t tmp = *value;
size_t n = 0;
while (tmp != 0) {
n++;
*top_byte = (tmp & 0xFF);
tmp >>= 8;
}
if (n == 0)
n = 1;
return WPACKET_put_bytes__(pkt, *value, n);
}
/* For integers, we only support unsigned values for now */
int ossl_DER_w_uint32(WPACKET *pkt, int tag, uint32_t v)
{
return int_der_w_integer(pkt, tag, int_put_bytes_uint32, &v);
}
static int int_put_bytes_bn(WPACKET *pkt, const void *v,
unsigned int *top_byte)
{
unsigned char *p = NULL;
size_t n = BN_num_bytes(v);
/* The BIGNUM limbs are in LE order */
*top_byte =
((bn_get_words(v) [(n - 1) / BN_BYTES]) >> (8 * ((n - 1) % BN_BYTES)))
& 0xFF;
if (!WPACKET_allocate_bytes(pkt, n, &p))
return 0;
if (p != NULL)
BN_bn2bin(v, p);
return 1;
}
int ossl_DER_w_bn(WPACKET *pkt, int tag, const BIGNUM *v)
{
if (v == NULL || BN_is_negative(v))
return 0;
if (BN_is_zero(v))
return ossl_DER_w_uint32(pkt, tag, 0);
return int_der_w_integer(pkt, tag, int_put_bytes_bn, v);
}
int ossl_DER_w_null(WPACKET *pkt, int tag)
{
return int_start_context(pkt, tag)
&& WPACKET_start_sub_packet(pkt)
&& WPACKET_close(pkt)
&& WPACKET_put_bytes_u8(pkt, DER_P_NULL)
&& int_end_context(pkt, tag);
}
/* Constructed things need a start and an end */
int ossl_DER_w_begin_sequence(WPACKET *pkt, int tag)
{
return int_start_context(pkt, tag)
&& WPACKET_start_sub_packet(pkt);
}
int ossl_DER_w_end_sequence(WPACKET *pkt, int tag)
{
/*
* If someone set the flag WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH on this
* sub-packet and this sub-packet has nothing written to it, the DER length
* will not be written, and the total written size will be unchanged before
* and after WPACKET_close(). We use size1 and size2 to determine if
* anything was written, and only write our tag if it has.
*
* Because we know that int_end_context() needs to do the same check,
* we reproduce this flag if the written length was unchanged, or we will
* have an erroneous context tag.
*/
size_t size1, size2;
return WPACKET_get_total_written(pkt, &size1)
&& WPACKET_close(pkt)
&& WPACKET_get_total_written(pkt, &size2)
&& (size1 == size2
? WPACKET_set_flags(pkt, WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH)
: WPACKET_put_bytes_u8(pkt, DER_F_CONSTRUCTED | DER_P_SEQUENCE))
&& int_end_context(pkt, tag);
}
| 6,107 | 29.54 | 79 | c |
openssl | openssl-master/crypto/deterministic_nonce.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/bn.h>
#include <openssl/evp.h>
#include <openssl/core_names.h>
#include <openssl/kdf.h>
#include "internal/deterministic_nonce.h"
/*
* Convert a Bit String to an Integer (See RFC 6979 Section 2.3.2)
*
* Params:
* out The returned Integer as a BIGNUM
* qlen_bits The maximum size of the returned integer in bits. The returned
* Integer is shifted right if inlen is larger than qlen_bits..
* in, inlen The input Bit String (in bytes).
* Returns: 1 if successful, or 0 otherwise.
*/
static int bits2int(BIGNUM *out, int qlen_bits,
const unsigned char *in, size_t inlen)
{
int blen_bits = inlen * 8;
int shift;
if (BN_bin2bn(in, (int)inlen, out) == NULL)
return 0;
shift = blen_bits - qlen_bits;
if (shift > 0)
return BN_rshift(out, out, shift);
return 1;
}
/*
* Convert an Integer to an Octet String (See RFC 6979 2.3.3).
* The value is zero padded if required.
*
* Params:
* out The returned Octet String
* num The input Integer
* rlen The required size of the returned Octet String in bytes
* Returns: 1 if successful, or 0 otherwise.
*/
static int int2octets(unsigned char *out, const BIGNUM *num, int rlen)
{
return BN_bn2binpad(num, out, rlen) >= 0;
}
/*
* Convert a Bit String to an Octet String (See RFC 6979 Section 2.3.4)
*
* Params:
* out The returned octet string.
* q The modulus
* qlen_bits The length of q in bits
* rlen The value of qlen_bits rounded up to the nearest 8 bits.
* in, inlen The input bit string (in bytes)
* Returns: 1 if successful, or 0 otherwise.
*/
static int bits2octets(unsigned char *out, const BIGNUM *q, int qlen_bits,
int rlen, const unsigned char *in, size_t inlen)
{
int ret = 0;
BIGNUM *z = BN_new();
if (z == NULL
|| !bits2int(z, qlen_bits, in, inlen))
goto err;
/* z2 = z1 mod q (Do a simple subtract, since z1 < 2^qlen_bits) */
if (BN_cmp(z, q) >= 0
&& !BN_usub(z, z, q))
goto err;
ret = int2octets(out, z, rlen);
err:
BN_free(z);
return ret;
}
/*
* Setup a KDF HMAC_DRBG object using fixed entropy and nonce data.
*
* Params:
* digestname The digest name for the HMAC
* entropy, entropylen A fixed input entropy buffer
* nonce, noncelen A fixed input nonce buffer
* libctx, propq Are used for fetching algorithms
*
* Returns: The created KDF HMAC_DRBG object if successful, or NULL otherwise.
*/
static EVP_KDF_CTX *kdf_setup(const char *digestname,
const unsigned char *entropy, size_t entropylen,
const unsigned char *nonce, size_t noncelen,
OSSL_LIB_CTX *libctx, const char *propq)
{
EVP_KDF_CTX *ctx = NULL;
EVP_KDF *kdf = NULL;
OSSL_PARAM params[5], *p;
kdf = EVP_KDF_fetch(libctx, "HMAC-DRBG-KDF", propq);
ctx = EVP_KDF_CTX_new(kdf);
EVP_KDF_free(kdf);
if (ctx == NULL)
goto err;
p = params;
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
(char *)digestname, 0);
if (propq != NULL)
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_PROPERTIES,
(char *)propq, 0);
*p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_HMACDRBG_ENTROPY,
(void *)entropy, entropylen);
*p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_HMACDRBG_NONCE,
(void *)nonce, noncelen);
*p = OSSL_PARAM_construct_end();
if (EVP_KDF_CTX_set_params(ctx, params) <= 0)
goto err;
return ctx;
err:
EVP_KDF_CTX_free(ctx);
return NULL;
}
/*
* Generate a Deterministic nonce 'k' for DSA/ECDSA as defined in
* RFC 6979 Section 3.3. "Alternate Description of the Generation of k"
*
* Params:
* out Returns the generated deterministic nonce 'k'
* q A large prime number used for modulus operations for DSA and ECDSA.
* priv The private key in the range [1, q-1]
* hm, hmlen The digested message buffer in bytes
* digestname The digest name used for signing. It is used as the HMAC digest.
* libctx, propq Used for fetching algorithms
*
* Returns: 1 if successful, or 0 otherwise.
*/
int ossl_gen_deterministic_nonce_rfc6979(BIGNUM *out, const BIGNUM *q,
const BIGNUM *priv,
const unsigned char *hm, size_t hmlen,
const char *digestname,
OSSL_LIB_CTX *libctx,
const char *propq)
{
EVP_KDF_CTX *kdfctx = NULL;
int ret = 0, rlen = 0, qlen_bits = 0;
unsigned char *entropyx = NULL, *nonceh = NULL, *T = NULL;
size_t allocsz = 0;
if (out == NULL)
return 0;
qlen_bits = BN_num_bits(q);
if (qlen_bits == 0)
return 0;
/* Note rlen used here is in bytes since the input values are byte arrays */
rlen = (qlen_bits + 7) / 8;
allocsz = 3 * rlen;
/* Use a single alloc for the buffers T, nonceh and entropyx */
T = (unsigned char *)OPENSSL_zalloc(allocsz);
if (T == NULL)
return 0;
nonceh = T + rlen;
entropyx = nonceh + rlen;
if (!int2octets(entropyx, priv, rlen)
|| !bits2octets(nonceh, q, qlen_bits, rlen, hm, hmlen))
goto end;
kdfctx = kdf_setup(digestname, entropyx, rlen, nonceh, rlen, libctx, propq);
if (kdfctx == NULL)
goto end;
do {
if (!EVP_KDF_derive(kdfctx, T, rlen, NULL)
|| !bits2int(out, qlen_bits, T, rlen))
goto end;
} while (BN_is_zero(out) || BN_is_one(out) || BN_cmp(out, q) >= 0);
ret = 1;
end:
EVP_KDF_CTX_free(kdfctx);
OPENSSL_clear_free(T, allocsz);
return ret;
}
| 6,334 | 30.834171 | 82 | c |
openssl | openssl-master/crypto/dllmain.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 "internal/e_os.h"
#include "crypto/cryptlib.h"
#if defined(_WIN32) || defined(__CYGWIN__)
# ifdef __CYGWIN__
/* pick DLL_[PROCESS|THREAD]_[ATTACH|DETACH] definitions */
# include <windows.h>
/*
* this has side-effect of _WIN32 getting defined, which otherwise is
* mutually exclusive with __CYGWIN__...
*/
# endif
/*
* All we really need to do is remove the 'error' state when a thread
* detaches
*/
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved);
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
switch (fdwReason) {
case DLL_PROCESS_ATTACH:
OPENSSL_cpuid_setup();
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
OPENSSL_thread_stop();
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#endif
| 1,207 | 24.702128 | 77 | c |
openssl | openssl-master/crypto/ebcdic.c | /*
* Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
# include <openssl/e_os2.h>
#ifndef CHARSET_EBCDIC
NON_EMPTY_TRANSLATION_UNIT
#else
# include <openssl/ebcdic.h>
# ifdef CHARSET_EBCDIC_TEST
/*
* Here we're looking to test the EBCDIC code on an ASCII system so we don't do
* any translation in these tables at all.
*/
/* The ebcdic-to-ascii table: */
const unsigned char os_toascii[256] = {
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,
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f,
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
};
/* The ascii-to-ebcdic table: */
const unsigned char os_toebcdic[256] = {
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,
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f,
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
};
# elif defined(_OSD_POSIX)
/*
* "BS2000 OSD" is a POSIX subsystem on a main frame. It is made by Siemens
* AG, Germany, for their BS2000 mainframe machines. Within the POSIX
* subsystem, the same character set was chosen as in "native BS2000", namely
* EBCDIC. (EDF04)
*
* The name "ASCII" in these routines is misleading: actually, conversion is
* not between EBCDIC and ASCII, but EBCDIC(EDF04) and ISO-8859.1; that means
* that (western european) national characters are preserved.
*
* This table is identical to the one used by rsh/rcp/ftp and other POSIX
* tools.
*/
/* Here's the bijective ebcdic-to-ascii table: */
const unsigned char os_toascii[256] = {
/*
* 00
*/ 0x00, 0x01, 0x02, 0x03, 0x85, 0x09, 0x86, 0x7f,
0x87, 0x8d, 0x8e, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* ................ */
/*
* 10
*/ 0x10, 0x11, 0x12, 0x13, 0x8f, 0x0a, 0x08, 0x97,
0x18, 0x19, 0x9c, 0x9d, 0x1c, 0x1d, 0x1e, 0x1f, /* ................ */
/*
* 20
*/ 0x80, 0x81, 0x82, 0x83, 0x84, 0x92, 0x17, 0x1b,
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x05, 0x06, 0x07, /* ................ */
/*
* 30
*/ 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04,
0x98, 0x99, 0x9a, 0x9b, 0x14, 0x15, 0x9e, 0x1a, /* ................ */
/*
* 40
*/ 0x20, 0xa0, 0xe2, 0xe4, 0xe0, 0xe1, 0xe3, 0xe5,
0xe7, 0xf1, 0x60, 0x2e, 0x3c, 0x28, 0x2b, 0x7c, /* .........`.<(+| */
/*
* 50
*/ 0x26, 0xe9, 0xea, 0xeb, 0xe8, 0xed, 0xee, 0xef,
0xec, 0xdf, 0x21, 0x24, 0x2a, 0x29, 0x3b, 0x9f, /* &.........!$*);. */
/*
* 60
*/ 0x2d, 0x2f, 0xc2, 0xc4, 0xc0, 0xc1, 0xc3, 0xc5,
0xc7, 0xd1, 0x5e, 0x2c, 0x25, 0x5f, 0x3e, 0x3f, /*-/........^,%_>?*/
/*
* 70
*/ 0xf8, 0xc9, 0xca, 0xcb, 0xc8, 0xcd, 0xce, 0xcf,
0xcc, 0xa8, 0x3a, 0x23, 0x40, 0x27, 0x3d, 0x22, /* ..........:#@'=" */
/*
* 80
*/ 0xd8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0xab, 0xbb, 0xf0, 0xfd, 0xfe, 0xb1, /* .abcdefghi...... */
/*
* 90
*/ 0xb0, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,
0x71, 0x72, 0xaa, 0xba, 0xe6, 0xb8, 0xc6, 0xa4, /* .jklmnopqr...... */
/*
* a0
*/ 0xb5, 0xaf, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
0x79, 0x7a, 0xa1, 0xbf, 0xd0, 0xdd, 0xde, 0xae, /* ..stuvwxyz...... */
/*
* b0
*/ 0xa2, 0xa3, 0xa5, 0xb7, 0xa9, 0xa7, 0xb6, 0xbc,
0xbd, 0xbe, 0xac, 0x5b, 0x5c, 0x5d, 0xb4, 0xd7, /* ...........[\].. */
/*
* c0
*/ 0xf9, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
0x48, 0x49, 0xad, 0xf4, 0xf6, 0xf2, 0xf3, 0xf5, /* .ABCDEFGHI...... */
/*
* d0
*/ 0xa6, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50,
0x51, 0x52, 0xb9, 0xfb, 0xfc, 0xdb, 0xfa, 0xff, /* .JKLMNOPQR...... */
/*
* e0
*/ 0xd9, 0xf7, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
0x59, 0x5a, 0xb2, 0xd4, 0xd6, 0xd2, 0xd3, 0xd5, /* ..STUVWXYZ...... */
/*
* f0
*/ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0xb3, 0x7b, 0xdc, 0x7d, 0xda, 0x7e /* 0123456789.{.}.~ */
};
/* The ascii-to-ebcdic table: */
const unsigned char os_toebcdic[256] = {
/*
* 00
*/ 0x00, 0x01, 0x02, 0x03, 0x37, 0x2d, 0x2e, 0x2f,
0x16, 0x05, 0x15, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* ................ */
/*
* 10
*/ 0x10, 0x11, 0x12, 0x13, 0x3c, 0x3d, 0x32, 0x26,
0x18, 0x19, 0x3f, 0x27, 0x1c, 0x1d, 0x1e, 0x1f, /* ................ */
/*
* 20
*/ 0x40, 0x5a, 0x7f, 0x7b, 0x5b, 0x6c, 0x50, 0x7d,
0x4d, 0x5d, 0x5c, 0x4e, 0x6b, 0x60, 0x4b, 0x61, /* !"#$%&'()*+,-./ */
/*
* 30
*/ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
0xf8, 0xf9, 0x7a, 0x5e, 0x4c, 0x7e, 0x6e, 0x6f, /* 0123456789:;<=>? */
/*
* 40
*/ 0x7c, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
0xc8, 0xc9, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, /* @ABCDEFGHIJKLMNO */
/*
* 50
*/ 0xd7, 0xd8, 0xd9, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6,
0xe7, 0xe8, 0xe9, 0xbb, 0xbc, 0xbd, 0x6a, 0x6d, /* PQRSTUVWXYZ[\]^_ */
/*
* 60
*/ 0x4a, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, /* `abcdefghijklmno */
/*
* 70
*/ 0x97, 0x98, 0x99, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6,
0xa7, 0xa8, 0xa9, 0xfb, 0x4f, 0xfd, 0xff, 0x07, /* pqrstuvwxyz{|}~. */
/*
* 80
*/ 0x20, 0x21, 0x22, 0x23, 0x24, 0x04, 0x06, 0x08,
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x09, 0x0a, 0x14, /* ................ */
/*
* 90
*/ 0x30, 0x31, 0x25, 0x33, 0x34, 0x35, 0x36, 0x17,
0x38, 0x39, 0x3a, 0x3b, 0x1a, 0x1b, 0x3e, 0x5f, /* ................ */
/*
* a0
*/ 0x41, 0xaa, 0xb0, 0xb1, 0x9f, 0xb2, 0xd0, 0xb5,
0x79, 0xb4, 0x9a, 0x8a, 0xba, 0xca, 0xaf, 0xa1, /* ................ */
/*
* b0
*/ 0x90, 0x8f, 0xea, 0xfa, 0xbe, 0xa0, 0xb6, 0xb3,
0x9d, 0xda, 0x9b, 0x8b, 0xb7, 0xb8, 0xb9, 0xab, /* ................ */
/*
* c0
*/ 0x64, 0x65, 0x62, 0x66, 0x63, 0x67, 0x9e, 0x68,
0x74, 0x71, 0x72, 0x73, 0x78, 0x75, 0x76, 0x77, /* ................ */
/*
* d0
*/ 0xac, 0x69, 0xed, 0xee, 0xeb, 0xef, 0xec, 0xbf,
0x80, 0xe0, 0xfe, 0xdd, 0xfc, 0xad, 0xae, 0x59, /* ................ */
/*
* e0
*/ 0x44, 0x45, 0x42, 0x46, 0x43, 0x47, 0x9c, 0x48,
0x54, 0x51, 0x52, 0x53, 0x58, 0x55, 0x56, 0x57, /* ................ */
/*
* f0
*/ 0x8c, 0x49, 0xcd, 0xce, 0xcb, 0xcf, 0xcc, 0xe1,
0x70, 0xc0, 0xde, 0xdb, 0xdc, 0x8d, 0x8e, 0xdf /* ................ */
};
# else /*_OSD_POSIX*/
/*
* This code does basic character mapping for IBM's TPF and OS/390 operating
* systems. It is a modified version of the BS2000 table.
*
* Bijective EBCDIC (character set IBM-1047) to US-ASCII table: This table is
* bijective - there are no ambiguous or duplicate characters.
*/
const unsigned char os_toascii[256] = {
0x00, 0x01, 0x02, 0x03, 0x85, 0x09, 0x86, 0x7f, /* 00-0f: */
0x87, 0x8d, 0x8e, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* ................ */
0x10, 0x11, 0x12, 0x13, 0x8f, 0x0a, 0x08, 0x97, /* 10-1f: */
0x18, 0x19, 0x9c, 0x9d, 0x1c, 0x1d, 0x1e, 0x1f, /* ................ */
0x80, 0x81, 0x82, 0x83, 0x84, 0x92, 0x17, 0x1b, /* 20-2f: */
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x05, 0x06, 0x07, /* ................ */
0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, /* 30-3f: */
0x98, 0x99, 0x9a, 0x9b, 0x14, 0x15, 0x9e, 0x1a, /* ................ */
0x20, 0xa0, 0xe2, 0xe4, 0xe0, 0xe1, 0xe3, 0xe5, /* 40-4f: */
0xe7, 0xf1, 0xa2, 0x2e, 0x3c, 0x28, 0x2b, 0x7c, /* ...........<(+| */
0x26, 0xe9, 0xea, 0xeb, 0xe8, 0xed, 0xee, 0xef, /* 50-5f: */
0xec, 0xdf, 0x21, 0x24, 0x2a, 0x29, 0x3b, 0x5e, /* &.........!$*);^ */
0x2d, 0x2f, 0xc2, 0xc4, 0xc0, 0xc1, 0xc3, 0xc5, /* 60-6f: */
0xc7, 0xd1, 0xa6, 0x2c, 0x25, 0x5f, 0x3e, 0x3f, /* -/.........,%_>? */
0xf8, 0xc9, 0xca, 0xcb, 0xc8, 0xcd, 0xce, 0xcf, /* 70-7f: */
0xcc, 0x60, 0x3a, 0x23, 0x40, 0x27, 0x3d, 0x22, /* .........`:#@'=" */
0xd8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, /* 80-8f: */
0x68, 0x69, 0xab, 0xbb, 0xf0, 0xfd, 0xfe, 0xb1, /* .abcdefghi...... */
0xb0, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, /* 90-9f: */
0x71, 0x72, 0xaa, 0xba, 0xe6, 0xb8, 0xc6, 0xa4, /* .jklmnopqr...... */
0xb5, 0x7e, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, /* a0-af: */
0x79, 0x7a, 0xa1, 0xbf, 0xd0, 0x5b, 0xde, 0xae, /* .~stuvwxyz...[.. */
0xac, 0xa3, 0xa5, 0xb7, 0xa9, 0xa7, 0xb6, 0xbc, /* b0-bf: */
0xbd, 0xbe, 0xdd, 0xa8, 0xaf, 0x5d, 0xb4, 0xd7, /* .............].. */
0x7b, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, /* c0-cf: */
0x48, 0x49, 0xad, 0xf4, 0xf6, 0xf2, 0xf3, 0xf5, /* {ABCDEFGHI...... */
0x7d, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, /* d0-df: */
0x51, 0x52, 0xb9, 0xfb, 0xfc, 0xf9, 0xfa, 0xff, /* }JKLMNOPQR...... */
0x5c, 0xf7, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, /* e0-ef: */
0x59, 0x5a, 0xb2, 0xd4, 0xd6, 0xd2, 0xd3, 0xd5, /* \.STUVWXYZ...... */
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, /* f0-ff: */
0x38, 0x39, 0xb3, 0xdb, 0xdc, 0xd9, 0xda, 0x9f /* 0123456789...... */
};
/*
* The US-ASCII to EBCDIC (character set IBM-1047) table: This table is
* bijective (no ambiguous or duplicate characters)
*/
const unsigned char os_toebcdic[256] = {
0x00, 0x01, 0x02, 0x03, 0x37, 0x2d, 0x2e, 0x2f, /* 00-0f: */
0x16, 0x05, 0x15, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* ................ */
0x10, 0x11, 0x12, 0x13, 0x3c, 0x3d, 0x32, 0x26, /* 10-1f: */
0x18, 0x19, 0x3f, 0x27, 0x1c, 0x1d, 0x1e, 0x1f, /* ................ */
0x40, 0x5a, 0x7f, 0x7b, 0x5b, 0x6c, 0x50, 0x7d, /* 20-2f: */
0x4d, 0x5d, 0x5c, 0x4e, 0x6b, 0x60, 0x4b, 0x61, /* !"#$%&'()*+,-./ */
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* 30-3f: */
0xf8, 0xf9, 0x7a, 0x5e, 0x4c, 0x7e, 0x6e, 0x6f, /* 0123456789:;<=>? */
0x7c, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, /* 40-4f: */
0xc8, 0xc9, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, /* @ABCDEFGHIJKLMNO */
0xd7, 0xd8, 0xd9, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, /* 50-5f: */
0xe7, 0xe8, 0xe9, 0xad, 0xe0, 0xbd, 0x5f, 0x6d, /* PQRSTUVWXYZ[\]^_ */
0x79, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 60-6f: */
0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, /* `abcdefghijklmno */
0x97, 0x98, 0x99, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, /* 70-7f: */
0xa7, 0xa8, 0xa9, 0xc0, 0x4f, 0xd0, 0xa1, 0x07, /* pqrstuvwxyz{|}~. */
0x20, 0x21, 0x22, 0x23, 0x24, 0x04, 0x06, 0x08, /* 80-8f: */
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x09, 0x0a, 0x14, /* ................ */
0x30, 0x31, 0x25, 0x33, 0x34, 0x35, 0x36, 0x17, /* 90-9f: */
0x38, 0x39, 0x3a, 0x3b, 0x1a, 0x1b, 0x3e, 0xff, /* ................ */
0x41, 0xaa, 0x4a, 0xb1, 0x9f, 0xb2, 0x6a, 0xb5, /* a0-af: */
0xbb, 0xb4, 0x9a, 0x8a, 0xb0, 0xca, 0xaf, 0xbc, /* ................ */
0x90, 0x8f, 0xea, 0xfa, 0xbe, 0xa0, 0xb6, 0xb3, /* b0-bf: */
0x9d, 0xda, 0x9b, 0x8b, 0xb7, 0xb8, 0xb9, 0xab, /* ................ */
0x64, 0x65, 0x62, 0x66, 0x63, 0x67, 0x9e, 0x68, /* c0-cf: */
0x74, 0x71, 0x72, 0x73, 0x78, 0x75, 0x76, 0x77, /* ................ */
0xac, 0x69, 0xed, 0xee, 0xeb, 0xef, 0xec, 0xbf, /* d0-df: */
0x80, 0xfd, 0xfe, 0xfb, 0xfc, 0xba, 0xae, 0x59, /* ................ */
0x44, 0x45, 0x42, 0x46, 0x43, 0x47, 0x9c, 0x48, /* e0-ef: */
0x54, 0x51, 0x52, 0x53, 0x58, 0x55, 0x56, 0x57, /* ................ */
0x8c, 0x49, 0xcd, 0xce, 0xcb, 0xcf, 0xcc, 0xe1, /* f0-ff: */
0x70, 0xdd, 0xde, 0xdb, 0xdc, 0x8d, 0x8e, 0xdf /* ................ */
};
# endif/*_OSD_POSIX*/
/*
* Translate a memory block from EBCDIC (host charset) to ASCII (net charset)
* dest and srce may be identical, or separate memory blocks, but should not
* overlap. These functions intentionally have an interface compatible to
* memcpy(3).
*/
void *ebcdic2ascii(void *dest, const void *srce, size_t count)
{
unsigned char *udest = dest;
const unsigned char *usrce = srce;
while (count-- != 0) {
*udest++ = os_toascii[*usrce++];
}
return dest;
}
void *ascii2ebcdic(void *dest, const void *srce, size_t count)
{
unsigned char *udest = dest;
const unsigned char *usrce = srce;
while (count-- != 0) {
*udest++ = os_toebcdic[*usrce++];
}
return dest;
}
#endif
| 15,334 | 41.361878 | 79 | c |
openssl | openssl-master/crypto/ex_data.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 <stdlib.h>
#include "crypto/cryptlib.h"
#include "internal/thread_once.h"
int ossl_do_ex_data_init(OSSL_LIB_CTX *ctx)
{
OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ctx);
if (global == NULL)
return 0;
global->ex_data_lock = CRYPTO_THREAD_lock_new();
return global->ex_data_lock != NULL;
}
/*
* Return the EX_CALLBACKS from the |ex_data| array that corresponds to
* a given class. On success, *holds the lock.*
* The |global| parameter is assumed to be non null (checked by the caller).
* If |read| is 1 then a read lock is obtained. Otherwise it is a write lock.
*/
static EX_CALLBACKS *get_and_lock(OSSL_EX_DATA_GLOBAL *global, int class_index,
int read)
{
EX_CALLBACKS *ip;
if (class_index < 0 || class_index >= CRYPTO_EX_INDEX__COUNT) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT);
return NULL;
}
if (global->ex_data_lock == NULL) {
/*
* If we get here, someone (who?) cleaned up the lock, so just
* treat it as an error.
*/
return NULL;
}
if (read) {
if (!CRYPTO_THREAD_read_lock(global->ex_data_lock))
return NULL;
} else {
if (!CRYPTO_THREAD_write_lock(global->ex_data_lock))
return NULL;
}
ip = &global->ex_data[class_index];
return ip;
}
static void cleanup_cb(EX_CALLBACK *funcs)
{
OPENSSL_free(funcs);
}
/*
* Release all "ex_data" state to prevent memory leaks. This can't be made
* thread-safe without overhauling a lot of stuff, and shouldn't really be
* called under potential race-conditions anyway (it's for program shutdown
* after all).
*/
void ossl_crypto_cleanup_all_ex_data_int(OSSL_LIB_CTX *ctx)
{
int i;
OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ctx);
if (global == NULL)
return;
for (i = 0; i < CRYPTO_EX_INDEX__COUNT; ++i) {
EX_CALLBACKS *ip = &global->ex_data[i];
sk_EX_CALLBACK_pop_free(ip->meth, cleanup_cb);
ip->meth = NULL;
}
CRYPTO_THREAD_lock_free(global->ex_data_lock);
global->ex_data_lock = NULL;
}
/*
* Unregister a new index by replacing the callbacks with no-ops.
* Any in-use instances are leaked.
*/
static void dummy_new(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx,
long argl, void *argp)
{
}
static void dummy_free(void *parent, void *ptr, CRYPTO_EX_DATA *ad, int idx,
long argl, void *argp)
{
}
static int dummy_dup(CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from,
void **from_d, int idx,
long argl, void *argp)
{
return 1;
}
int ossl_crypto_free_ex_index_ex(OSSL_LIB_CTX *ctx, int class_index, int idx)
{
EX_CALLBACKS *ip;
EX_CALLBACK *a;
int toret = 0;
OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ctx);
if (global == NULL)
return 0;
ip = get_and_lock(global, class_index, 0);
if (ip == NULL)
return 0;
if (idx < 0 || idx >= sk_EX_CALLBACK_num(ip->meth))
goto err;
a = sk_EX_CALLBACK_value(ip->meth, idx);
if (a == NULL)
goto err;
a->new_func = dummy_new;
a->dup_func = dummy_dup;
a->free_func = dummy_free;
toret = 1;
err:
CRYPTO_THREAD_unlock(global->ex_data_lock);
return toret;
}
int CRYPTO_free_ex_index(int class_index, int idx)
{
return ossl_crypto_free_ex_index_ex(NULL, class_index, idx);
}
/*
* Register a new index.
*/
int ossl_crypto_get_ex_new_index_ex(OSSL_LIB_CTX *ctx, int class_index,
long argl, void *argp,
CRYPTO_EX_new *new_func,
CRYPTO_EX_dup *dup_func,
CRYPTO_EX_free *free_func,
int priority)
{
int toret = -1;
EX_CALLBACK *a;
EX_CALLBACKS *ip;
OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ctx);
if (global == NULL)
return -1;
ip = get_and_lock(global, class_index, 0);
if (ip == NULL)
return -1;
if (ip->meth == NULL) {
ip->meth = sk_EX_CALLBACK_new_null();
/* We push an initial value on the stack because the SSL
* "app_data" routines use ex_data index zero. See RT 3710. */
if (ip->meth == NULL
|| !sk_EX_CALLBACK_push(ip->meth, NULL)) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB);
goto err;
}
}
a = (EX_CALLBACK *)OPENSSL_malloc(sizeof(*a));
if (a == NULL)
goto err;
a->argl = argl;
a->argp = argp;
a->new_func = new_func;
a->dup_func = dup_func;
a->free_func = free_func;
a->priority = priority;
if (!sk_EX_CALLBACK_push(ip->meth, NULL)) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB);
OPENSSL_free(a);
goto err;
}
toret = sk_EX_CALLBACK_num(ip->meth) - 1;
(void)sk_EX_CALLBACK_set(ip->meth, toret, a);
err:
CRYPTO_THREAD_unlock(global->ex_data_lock);
return toret;
}
int CRYPTO_get_ex_new_index(int class_index, long argl, void *argp,
CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func,
CRYPTO_EX_free *free_func)
{
return ossl_crypto_get_ex_new_index_ex(NULL, class_index, argl, argp,
new_func, dup_func, free_func, 0);
}
/*
* Initialise a new CRYPTO_EX_DATA for use in a particular class - including
* calling new() callbacks for each index in the class used by this variable
* Thread-safe by copying a class's array of "EX_CALLBACK" entries
* in the lock, then using them outside the lock. Note this only applies
* to the global "ex_data" state (ie. class definitions), not 'ad' itself.
*/
int ossl_crypto_new_ex_data_ex(OSSL_LIB_CTX *ctx, int class_index, void *obj,
CRYPTO_EX_DATA *ad)
{
int mx, i;
void *ptr;
EX_CALLBACK **storage = NULL;
EX_CALLBACK *stack[10];
EX_CALLBACKS *ip;
OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ctx);
if (global == NULL)
return 0;
ip = get_and_lock(global, class_index, 1);
if (ip == NULL)
return 0;
ad->ctx = ctx;
ad->sk = NULL;
mx = sk_EX_CALLBACK_num(ip->meth);
if (mx > 0) {
if (mx < (int)OSSL_NELEM(stack))
storage = stack;
else
storage = OPENSSL_malloc(sizeof(*storage) * mx);
if (storage != NULL)
for (i = 0; i < mx; i++)
storage[i] = sk_EX_CALLBACK_value(ip->meth, i);
}
CRYPTO_THREAD_unlock(global->ex_data_lock);
if (mx > 0 && storage == NULL)
return 0;
for (i = 0; i < mx; i++) {
if (storage[i] != NULL && storage[i]->new_func != NULL) {
ptr = CRYPTO_get_ex_data(ad, i);
storage[i]->new_func(obj, ptr, ad, i,
storage[i]->argl, storage[i]->argp);
}
}
if (storage != stack)
OPENSSL_free(storage);
return 1;
}
int CRYPTO_new_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad)
{
return ossl_crypto_new_ex_data_ex(NULL, class_index, obj, ad);
}
/*
* Duplicate a CRYPTO_EX_DATA variable - including calling dup() callbacks
* for each index in the class used by this variable
*/
int CRYPTO_dup_ex_data(int class_index, CRYPTO_EX_DATA *to,
const CRYPTO_EX_DATA *from)
{
int mx, j, i;
void *ptr;
EX_CALLBACK *stack[10];
EX_CALLBACK **storage = NULL;
EX_CALLBACKS *ip;
int toret = 0;
OSSL_EX_DATA_GLOBAL *global;
to->ctx = from->ctx;
if (from->sk == NULL)
/* Nothing to copy over */
return 1;
global = ossl_lib_ctx_get_ex_data_global(from->ctx);
if (global == NULL)
return 0;
ip = get_and_lock(global, class_index, 1);
if (ip == NULL)
return 0;
mx = sk_EX_CALLBACK_num(ip->meth);
j = sk_void_num(from->sk);
if (j < mx)
mx = j;
if (mx > 0) {
if (mx < (int)OSSL_NELEM(stack))
storage = stack;
else
storage = OPENSSL_malloc(sizeof(*storage) * mx);
if (storage != NULL)
for (i = 0; i < mx; i++)
storage[i] = sk_EX_CALLBACK_value(ip->meth, i);
}
CRYPTO_THREAD_unlock(global->ex_data_lock);
if (mx == 0)
return 1;
if (storage == NULL)
return 0;
/*
* Make sure the ex_data stack is at least |mx| elements long to avoid
* issues in the for loop that follows; so go get the |mx|'th element
* (if it does not exist CRYPTO_get_ex_data() returns NULL), and assign
* to itself. This is normally a no-op; but ensures the stack is the
* proper size
*/
if (!CRYPTO_set_ex_data(to, mx - 1, CRYPTO_get_ex_data(to, mx - 1)))
goto err;
for (i = 0; i < mx; i++) {
ptr = CRYPTO_get_ex_data(from, i);
if (storage[i] != NULL && storage[i]->dup_func != NULL)
if (!storage[i]->dup_func(to, from, &ptr, i,
storage[i]->argl, storage[i]->argp))
goto err;
CRYPTO_set_ex_data(to, i, ptr);
}
toret = 1;
err:
if (storage != stack)
OPENSSL_free(storage);
return toret;
}
struct ex_callback_entry {
const EX_CALLBACK *excb;
int index;
};
static int ex_callback_compare(const void *a, const void *b)
{
const struct ex_callback_entry *ap = (const struct ex_callback_entry *)a;
const struct ex_callback_entry *bp = (const struct ex_callback_entry *)b;
if (ap->excb == bp->excb)
return 0;
if (ap->excb == NULL)
return 1;
if (bp->excb == NULL)
return -1;
if (ap->excb->priority == bp->excb->priority)
return 0;
return ap->excb->priority > bp->excb->priority ? -1 : 1;
}
/*
* Cleanup a CRYPTO_EX_DATA variable - including calling free() callbacks for
* each index in the class used by this variable
*/
void CRYPTO_free_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad)
{
int mx, i;
EX_CALLBACKS *ip;
void *ptr;
const EX_CALLBACK *f;
struct ex_callback_entry stack[10];
struct ex_callback_entry *storage = NULL;
OSSL_EX_DATA_GLOBAL *global = ossl_lib_ctx_get_ex_data_global(ad->ctx);
if (global == NULL)
goto err;
ip = get_and_lock(global, class_index, 1);
if (ip == NULL)
goto err;
mx = sk_EX_CALLBACK_num(ip->meth);
if (mx > 0) {
if (mx < (int)OSSL_NELEM(stack))
storage = stack;
else
storage = OPENSSL_malloc(sizeof(*storage) * mx);
if (storage != NULL)
for (i = 0; i < mx; i++) {
storage[i].excb = sk_EX_CALLBACK_value(ip->meth, i);
storage[i].index = i;
}
}
CRYPTO_THREAD_unlock(global->ex_data_lock);
if (storage != NULL) {
/* Sort according to priority. High priority first */
qsort(storage, mx, sizeof(*storage), ex_callback_compare);
for (i = 0; i < mx; i++) {
f = storage[i].excb;
if (f != NULL && f->free_func != NULL) {
ptr = CRYPTO_get_ex_data(ad, storage[i].index);
f->free_func(obj, ptr, ad, storage[i].index, f->argl, f->argp);
}
}
}
if (storage != stack)
OPENSSL_free(storage);
err:
sk_void_free(ad->sk);
ad->sk = NULL;
ad->ctx = NULL;
}
/*
* Allocate a given CRYPTO_EX_DATA item using the class specific allocation
* function
*/
int CRYPTO_alloc_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad,
int idx)
{
void *curval;
curval = CRYPTO_get_ex_data(ad, idx);
/* Already there, no need to allocate */
if (curval != NULL)
return 1;
return ossl_crypto_alloc_ex_data_intern(class_index, obj, ad, idx);
}
int ossl_crypto_alloc_ex_data_intern(int class_index, void *obj,
CRYPTO_EX_DATA *ad, int idx)
{
EX_CALLBACK *f;
EX_CALLBACKS *ip;
OSSL_EX_DATA_GLOBAL *global;
global = ossl_lib_ctx_get_ex_data_global(ad->ctx);
if (global == NULL)
return 0;
ip = get_and_lock(global, class_index, 1);
if (ip == NULL)
return 0;
f = sk_EX_CALLBACK_value(ip->meth, idx);
CRYPTO_THREAD_unlock(global->ex_data_lock);
/*
* This should end up calling CRYPTO_set_ex_data(), which allocates
* everything necessary to support placing the new data in the right spot.
*/
if (f->new_func == NULL)
return 0;
f->new_func(obj, NULL, ad, idx, f->argl, f->argp);
return 1;
}
/*
* For a given CRYPTO_EX_DATA variable, set the value corresponding to a
* particular index in the class used by this variable
*/
int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int idx, void *val)
{
int i;
if (ad->sk == NULL) {
if ((ad->sk = sk_void_new_null()) == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB);
return 0;
}
}
for (i = sk_void_num(ad->sk); i <= idx; ++i) {
if (!sk_void_push(ad->sk, NULL)) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_CRYPTO_LIB);
return 0;
}
}
if (sk_void_set(ad->sk, idx, val) != val) {
/* Probably the index is out of bounds */
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT);
return 0;
}
return 1;
}
/*
* For a given CRYPTO_EX_DATA_ variable, get the value corresponding to a
* particular index in the class used by this variable
*/
void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int idx)
{
if (ad->sk == NULL || idx >= sk_void_num(ad->sk))
return NULL;
return sk_void_value(ad->sk, idx);
}
OSSL_LIB_CTX *ossl_crypto_ex_data_get_ossl_lib_ctx(const CRYPTO_EX_DATA *ad)
{
return ad->ctx;
}
| 14,302 | 27.211045 | 79 | c |
openssl | openssl-master/crypto/getenv.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
*/
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include <stdlib.h>
#include "internal/cryptlib.h"
#include "internal/e_os.h"
char *ossl_safe_getenv(const char *name)
{
#if defined(_WIN32) && defined(CP_UTF8) && !defined(_WIN32_WCE)
if (GetEnvironmentVariableW(L"OPENSSL_WIN32_UTF8", NULL, 0) != 0) {
char *val = NULL;
int vallen = 0;
WCHAR *namew = NULL;
WCHAR *valw = NULL;
DWORD envlen = 0;
DWORD dwFlags = MB_ERR_INVALID_CHARS;
int rsize, fsize;
UINT curacp;
curacp = GetACP();
/*
* For the code pages listed below, dwFlags must be set to 0.
* Otherwise, the function fails with ERROR_INVALID_FLAGS.
*/
if (curacp == 50220 || curacp == 50221 || curacp == 50222 ||
curacp == 50225 || curacp == 50227 || curacp == 50229 ||
(57002 <= curacp && curacp <=57011) || curacp == 65000 ||
curacp == 42)
dwFlags = 0;
/* query for buffer len */
rsize = MultiByteToWideChar(curacp, dwFlags, name, -1, NULL, 0);
/* if name is valid string and can be converted to wide string */
if (rsize > 0)
namew = _malloca(rsize * sizeof(WCHAR));
if (NULL != namew) {
/* convert name to wide string */
fsize = MultiByteToWideChar(curacp, dwFlags, name, -1, namew, rsize);
/* if conversion is ok, then determine value string size in wchars */
if (fsize > 0)
envlen = GetEnvironmentVariableW(namew, NULL, 0);
}
if (envlen > 0)
valw = _malloca(envlen * sizeof(WCHAR));
if (NULL != valw) {
/* if can get env value as wide string */
if (GetEnvironmentVariableW(namew, valw, envlen) < envlen) {
/* determine value string size in utf-8 */
vallen = WideCharToMultiByte(CP_UTF8, 0, valw, -1, NULL, 0,
NULL, NULL);
}
}
if (vallen > 0)
val = OPENSSL_malloc(vallen);
if (NULL != val) {
/* convert value string from wide to utf-8 */
if (WideCharToMultiByte(CP_UTF8, 0, valw, -1, val, vallen,
NULL, NULL) == 0) {
OPENSSL_free(val);
val = NULL;
}
}
if (NULL != namew)
_freea(namew);
if (NULL != valw)
_freea(valw);
return val;
}
#endif
#if defined(__GLIBC__) && defined(__GLIBC_PREREQ)
# if __GLIBC_PREREQ(2, 17)
# define SECURE_GETENV
return secure_getenv(name);
# endif
#endif
#ifndef SECURE_GETENV
if (OPENSSL_issetugid())
return NULL;
return getenv(name);
#endif
}
| 3,136 | 29.163462 | 81 | c |
openssl | openssl-master/crypto/info.c | /*
* Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/crypto.h>
#include "crypto/rand.h"
#include "crypto/dso_conf.h"
#include "internal/thread_once.h"
#include "internal/cryptlib.h"
#include "internal/e_os.h"
#include "buildinf.h"
#if defined(__arm__) || defined(__arm) || defined(__aarch64__)
# include "arm_arch.h"
# define CPU_INFO_STR_LEN 128
#elif defined(__s390__) || defined(__s390x__)
# include "s390x_arch.h"
# define CPU_INFO_STR_LEN 2048
#else
# define CPU_INFO_STR_LEN 128
#endif
/* extern declaration to avoid warning */
extern char ossl_cpu_info_str[];
static char *seed_sources = NULL;
char ossl_cpu_info_str[CPU_INFO_STR_LEN] = "";
#define CPUINFO_PREFIX "CPUINFO: "
static CRYPTO_ONCE init_info = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(init_info_strings)
{
#if defined(OPENSSL_CPUID_OBJ)
# if defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
defined(__x86_64) || defined(__x86_64__) || \
defined(_M_AMD64) || defined(_M_X64)
const char *env;
BIO_snprintf(ossl_cpu_info_str, sizeof(ossl_cpu_info_str),
CPUINFO_PREFIX "OPENSSL_ia32cap=0x%llx:0x%llx",
(unsigned long long)OPENSSL_ia32cap_P[0] |
(unsigned long long)OPENSSL_ia32cap_P[1] << 32,
(unsigned long long)OPENSSL_ia32cap_P[2] |
(unsigned long long)OPENSSL_ia32cap_P[3] << 32);
if ((env = getenv("OPENSSL_ia32cap")) != NULL)
BIO_snprintf(ossl_cpu_info_str + strlen(ossl_cpu_info_str),
sizeof(ossl_cpu_info_str) - strlen(ossl_cpu_info_str),
" env:%s", env);
# elif defined(__arm__) || defined(__arm) || defined(__aarch64__)
const char *env;
BIO_snprintf(ossl_cpu_info_str, sizeof(ossl_cpu_info_str),
CPUINFO_PREFIX "OPENSSL_armcap=0x%x", OPENSSL_armcap_P);
if ((env = getenv("OPENSSL_armcap")) != NULL)
BIO_snprintf(ossl_cpu_info_str + strlen(ossl_cpu_info_str),
sizeof(ossl_cpu_info_str) - strlen(ossl_cpu_info_str),
" env:%s", env);
# elif defined(__s390__) || defined(__s390x__)
const char *env;
BIO_snprintf(ossl_cpu_info_str, sizeof(ossl_cpu_info_str),
CPUINFO_PREFIX "OPENSSL_s390xcap="
"stfle:0x%llx:0x%llx:0x%llx:0x%llx:"
"kimd:0x%llx:0x%llx:"
"klmd:0x%llx:0x%llx:"
"km:0x%llx:0x%llx:"
"kmc:0x%llx:0x%llx:"
"kmac:0x%llx:0x%llx:"
"kmctr:0x%llx:0x%llx:"
"kmo:0x%llx:0x%llx:"
"kmf:0x%llx:0x%llx:"
"prno:0x%llx:0x%llx:"
"kma:0x%llx:0x%llx:"
"pcc:0x%llx:0x%llx:"
"kdsa:0x%llx:0x%llx",
OPENSSL_s390xcap_P.stfle[0], OPENSSL_s390xcap_P.stfle[1],
OPENSSL_s390xcap_P.stfle[2], OPENSSL_s390xcap_P.stfle[3],
OPENSSL_s390xcap_P.kimd[0], OPENSSL_s390xcap_P.kimd[1],
OPENSSL_s390xcap_P.klmd[0], OPENSSL_s390xcap_P.klmd[1],
OPENSSL_s390xcap_P.km[0], OPENSSL_s390xcap_P.km[1],
OPENSSL_s390xcap_P.kmc[0], OPENSSL_s390xcap_P.kmc[1],
OPENSSL_s390xcap_P.kmac[0], OPENSSL_s390xcap_P.kmac[1],
OPENSSL_s390xcap_P.kmctr[0], OPENSSL_s390xcap_P.kmctr[1],
OPENSSL_s390xcap_P.kmo[0], OPENSSL_s390xcap_P.kmo[1],
OPENSSL_s390xcap_P.kmf[0], OPENSSL_s390xcap_P.kmf[1],
OPENSSL_s390xcap_P.prno[0], OPENSSL_s390xcap_P.prno[1],
OPENSSL_s390xcap_P.kma[0], OPENSSL_s390xcap_P.kma[1],
OPENSSL_s390xcap_P.pcc[0], OPENSSL_s390xcap_P.pcc[1],
OPENSSL_s390xcap_P.kdsa[0], OPENSSL_s390xcap_P.kdsa[1]);
if ((env = getenv("OPENSSL_s390xcap")) != NULL)
BIO_snprintf(ossl_cpu_info_str + strlen(ossl_cpu_info_str),
sizeof(ossl_cpu_info_str) - strlen(ossl_cpu_info_str),
" env:%s", env);
# endif
#endif
{
static char seeds[512] = "";
#define add_seeds_string(str) \
do { \
if (seeds[0] != '\0') \
OPENSSL_strlcat(seeds, " ", sizeof(seeds)); \
OPENSSL_strlcat(seeds, str, sizeof(seeds)); \
} while (0)
#define add_seeds_stringlist(label, strlist) \
do { \
add_seeds_string(label "("); \
{ \
const char *dev[] = { strlist, NULL }; \
const char **p; \
int first = 1; \
\
for (p = dev; *p != NULL; p++) { \
if (!first) \
OPENSSL_strlcat(seeds, " ", sizeof(seeds)); \
first = 0; \
OPENSSL_strlcat(seeds, *p, sizeof(seeds)); \
} \
} \
OPENSSL_strlcat(seeds, ")", sizeof(seeds)); \
} while (0)
#ifdef OPENSSL_RAND_SEED_NONE
add_seeds_string("none");
#endif
#ifdef OPENSSL_RAND_SEED_RDTSC
add_seeds_string("rdtsc");
#endif
#ifdef OPENSSL_RAND_SEED_RDCPU
# ifdef __aarch64__
add_seeds_string("rndr ( rndrrs rndr )");
# else
add_seeds_string("rdrand ( rdseed rdrand )");
# endif
#endif
#ifdef OPENSSL_RAND_SEED_LIBRANDOM
add_seeds_string("C-library-random");
#endif
#ifdef OPENSSL_RAND_SEED_GETRANDOM
add_seeds_string("getrandom-syscall");
#endif
#ifdef OPENSSL_RAND_SEED_DEVRANDOM
add_seeds_stringlist("random-device", DEVRANDOM);
#endif
#ifdef OPENSSL_RAND_SEED_EGD
add_seeds_stringlist("EGD", DEVRANDOM_EGD);
#endif
#ifdef OPENSSL_RAND_SEED_OS
add_seeds_string("os-specific");
#endif
seed_sources = seeds;
}
return 1;
}
const char *OPENSSL_info(int t)
{
/*
* We don't care about the result. Worst case scenario, the strings
* won't be initialised, i.e. remain NULL, which means that the info
* isn't available anyway...
*/
(void)RUN_ONCE(&init_info, init_info_strings);
switch (t) {
case OPENSSL_INFO_CONFIG_DIR:
return OPENSSLDIR;
case OPENSSL_INFO_ENGINES_DIR:
return ENGINESDIR;
case OPENSSL_INFO_MODULES_DIR:
return MODULESDIR;
case OPENSSL_INFO_DSO_EXTENSION:
return DSO_EXTENSION;
case OPENSSL_INFO_DIR_FILENAME_SEPARATOR:
#if defined(_WIN32)
return "\\";
#elif defined(__VMS)
return "";
#else /* Assume POSIX */
return "/";
#endif
case OPENSSL_INFO_LIST_SEPARATOR:
{
static const char list_sep[] = { LIST_SEPARATOR_CHAR, '\0' };
return list_sep;
}
case OPENSSL_INFO_SEED_SOURCE:
return seed_sources;
case OPENSSL_INFO_CPU_SETTINGS:
/*
* If successfully initialized, ossl_cpu_info_str will start
* with CPUINFO_PREFIX, if failed it will be an empty string.
* Strip away the CPUINFO_PREFIX which we don't need here.
*/
if (ossl_cpu_info_str[0] != '\0')
return ossl_cpu_info_str + strlen(CPUINFO_PREFIX);
break;
default:
break;
}
/* Not an error */
return NULL;
}
| 8,211 | 37.735849 | 75 | c |
openssl | openssl-master/crypto/init.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 to use some engine deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include "internal/e_os.h"
#include "crypto/cryptlib.h"
#include <openssl/err.h>
#include "crypto/rand.h"
#include "internal/bio.h"
#include <openssl/evp.h>
#include "crypto/evp.h"
#include "internal/conf.h"
#include "crypto/async.h"
#include "crypto/engine.h"
#include "internal/comp.h"
#include "internal/err.h"
#include "crypto/err.h"
#include "crypto/objects.h"
#include <stdlib.h>
#include <assert.h>
#include "internal/thread_once.h"
#include "crypto/dso_conf.h"
#include "internal/dso.h"
#include "crypto/store.h"
#include <openssl/cmp_util.h> /* for OSSL_CMP_log_close() */
#include <openssl/trace.h>
#include "crypto/ctype.h"
static int stopped = 0;
static uint64_t optsdone = 0;
typedef struct ossl_init_stop_st OPENSSL_INIT_STOP;
struct ossl_init_stop_st {
void (*handler)(void);
OPENSSL_INIT_STOP *next;
};
static OPENSSL_INIT_STOP *stop_handlers = NULL;
/* Guards access to the optsdone variable on platforms without atomics */
static CRYPTO_RWLOCK *optsdone_lock = NULL;
/* Guards simultaneous INIT_LOAD_CONFIG calls with non-NULL settings */
static CRYPTO_RWLOCK *init_lock = NULL;
static CRYPTO_THREAD_LOCAL in_init_config_local;
static CRYPTO_ONCE base = CRYPTO_ONCE_STATIC_INIT;
static int base_inited = 0;
DEFINE_RUN_ONCE_STATIC(ossl_init_base)
{
/* no need to init trace */
OSSL_TRACE(INIT, "ossl_init_base: setting up stop handlers\n");
#ifndef OPENSSL_NO_CRYPTO_MDEBUG
ossl_malloc_setup_failures();
#endif
if ((optsdone_lock = CRYPTO_THREAD_lock_new()) == NULL
|| (init_lock = CRYPTO_THREAD_lock_new()) == NULL)
goto err;
OPENSSL_cpuid_setup();
if (!ossl_init_thread())
goto err;
if (!CRYPTO_THREAD_init_local(&in_init_config_local, NULL))
goto err;
base_inited = 1;
return 1;
err:
OSSL_TRACE(INIT, "ossl_init_base failed!\n");
CRYPTO_THREAD_lock_free(optsdone_lock);
optsdone_lock = NULL;
CRYPTO_THREAD_lock_free(init_lock);
init_lock = NULL;
return 0;
}
static CRYPTO_ONCE register_atexit = CRYPTO_ONCE_STATIC_INIT;
#if !defined(OPENSSL_SYS_UEFI) && defined(_WIN32)
static int win32atexit(void)
{
OPENSSL_cleanup();
return 0;
}
#endif
DEFINE_RUN_ONCE_STATIC(ossl_init_register_atexit)
{
#ifdef OPENSSL_INIT_DEBUG
fprintf(stderr, "OPENSSL_INIT: ossl_init_register_atexit()\n");
#endif
#ifndef OPENSSL_SYS_UEFI
# if defined(_WIN32) && !defined(__BORLANDC__)
/* We use _onexit() in preference because it gets called on DLL unload */
if (_onexit(win32atexit) == NULL)
return 0;
# else
if (atexit(OPENSSL_cleanup) != 0)
return 0;
# endif
#endif
return 1;
}
DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_register_atexit,
ossl_init_register_atexit)
{
#ifdef OPENSSL_INIT_DEBUG
fprintf(stderr, "OPENSSL_INIT: ossl_init_no_register_atexit ok!\n");
#endif
/* Do nothing in this case */
return 1;
}
static CRYPTO_ONCE load_crypto_nodelete = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_load_crypto_nodelete)
{
OSSL_TRACE(INIT, "ossl_init_load_crypto_nodelete()\n");
#if !defined(OPENSSL_USE_NODELETE) \
&& !defined(OPENSSL_NO_PINSHARED)
# if defined(DSO_WIN32) && !defined(_WIN32_WCE)
{
HMODULE handle = NULL;
BOOL ret;
/* We don't use the DSO route for WIN32 because there is a better way */
ret = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
| GET_MODULE_HANDLE_EX_FLAG_PIN,
(void *)&base_inited, &handle);
OSSL_TRACE1(INIT,
"ossl_init_load_crypto_nodelete: "
"obtained DSO reference? %s\n",
(ret == TRUE ? "No!" : "Yes."));
return (ret == TRUE) ? 1 : 0;
}
# elif !defined(DSO_NONE)
/*
* Deliberately leak a reference to ourselves. This will force the library
* to remain loaded until the atexit() handler is run at process exit.
*/
{
DSO *dso;
void *err;
if (!err_shelve_state(&err))
return 0;
dso = DSO_dsobyaddr(&base_inited, DSO_FLAG_NO_UNLOAD_ON_FREE);
/*
* In case of No!, it is uncertain our exit()-handlers can still be
* called. After dlclose() the whole library might have been unloaded
* already.
*/
OSSL_TRACE1(INIT, "obtained DSO reference? %s\n",
(dso == NULL ? "No!" : "Yes."));
DSO_free(dso);
err_unshelve_state(err);
}
# endif
#endif
return 1;
}
static CRYPTO_ONCE load_crypto_strings = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_load_crypto_strings)
{
int ret = 1;
/*
* OPENSSL_NO_AUTOERRINIT is provided here to prevent at compile time
* pulling in all the error strings during static linking
*/
#if !defined(OPENSSL_NO_ERR) && !defined(OPENSSL_NO_AUTOERRINIT)
OSSL_TRACE(INIT, "ossl_err_load_crypto_strings()\n");
ret = ossl_err_load_crypto_strings();
#endif
return ret;
}
DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_load_crypto_strings,
ossl_init_load_crypto_strings)
{
/* Do nothing in this case */
return 1;
}
static CRYPTO_ONCE add_all_ciphers = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_add_all_ciphers)
{
/*
* OPENSSL_NO_AUTOALGINIT is provided here to prevent at compile time
* pulling in all the ciphers during static linking
*/
#ifndef OPENSSL_NO_AUTOALGINIT
OSSL_TRACE(INIT, "openssl_add_all_ciphers_int()\n");
openssl_add_all_ciphers_int();
#endif
return 1;
}
DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_add_all_ciphers,
ossl_init_add_all_ciphers)
{
/* Do nothing */
return 1;
}
static CRYPTO_ONCE add_all_digests = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_add_all_digests)
{
/*
* OPENSSL_NO_AUTOALGINIT is provided here to prevent at compile time
* pulling in all the ciphers during static linking
*/
#ifndef OPENSSL_NO_AUTOALGINIT
OSSL_TRACE(INIT, "openssl_add_all_digests()\n");
openssl_add_all_digests_int();
#endif
return 1;
}
DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_add_all_digests,
ossl_init_add_all_digests)
{
/* Do nothing */
return 1;
}
static CRYPTO_ONCE config = CRYPTO_ONCE_STATIC_INIT;
static int config_inited = 0;
static const OPENSSL_INIT_SETTINGS *conf_settings = NULL;
DEFINE_RUN_ONCE_STATIC(ossl_init_config)
{
int ret = ossl_config_int(NULL);
config_inited = 1;
return ret;
}
DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_config_settings, ossl_init_config)
{
int ret = ossl_config_int(conf_settings);
config_inited = 1;
return ret;
}
DEFINE_RUN_ONCE_STATIC_ALT(ossl_init_no_config, ossl_init_config)
{
OSSL_TRACE(INIT, "ossl_no_config_int()\n");
ossl_no_config_int();
config_inited = 1;
return 1;
}
static CRYPTO_ONCE async = CRYPTO_ONCE_STATIC_INIT;
static int async_inited = 0;
DEFINE_RUN_ONCE_STATIC(ossl_init_async)
{
OSSL_TRACE(INIT, "async_init()\n");
if (!async_init())
return 0;
async_inited = 1;
return 1;
}
#ifndef OPENSSL_NO_ENGINE
static CRYPTO_ONCE engine_openssl = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_engine_openssl)
{
OSSL_TRACE(INIT, "engine_load_openssl_int()\n");
engine_load_openssl_int();
return 1;
}
# ifndef OPENSSL_NO_RDRAND
static CRYPTO_ONCE engine_rdrand = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_engine_rdrand)
{
OSSL_TRACE(INIT, "engine_load_rdrand_int()\n");
engine_load_rdrand_int();
return 1;
}
# endif
static CRYPTO_ONCE engine_dynamic = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_engine_dynamic)
{
OSSL_TRACE(INIT, "engine_load_dynamic_int()\n");
engine_load_dynamic_int();
return 1;
}
# ifndef OPENSSL_NO_STATIC_ENGINE
# ifndef OPENSSL_NO_DEVCRYPTOENG
static CRYPTO_ONCE engine_devcrypto = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_engine_devcrypto)
{
OSSL_TRACE(INIT, "engine_load_devcrypto_int()\n");
engine_load_devcrypto_int();
return 1;
}
# endif
# if !defined(OPENSSL_NO_PADLOCKENG)
static CRYPTO_ONCE engine_padlock = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_engine_padlock)
{
OSSL_TRACE(INIT, "engine_load_padlock_int()\n");
engine_load_padlock_int();
return 1;
}
# endif
# if defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_NO_CAPIENG)
static CRYPTO_ONCE engine_capi = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_engine_capi)
{
OSSL_TRACE(INIT, "engine_load_capi_int()\n");
engine_load_capi_int();
return 1;
}
# endif
# if !defined(OPENSSL_NO_AFALGENG)
static CRYPTO_ONCE engine_afalg = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_init_engine_afalg)
{
OSSL_TRACE(INIT, "engine_load_afalg_int()\n");
engine_load_afalg_int();
return 1;
}
# endif
# endif
#endif
void OPENSSL_cleanup(void)
{
OPENSSL_INIT_STOP *currhandler, *lasthandler;
/*
* At some point we should consider looking at this function with a view to
* moving most/all of this into onfree handlers in OSSL_LIB_CTX.
*/
/* If we've not been inited then no need to deinit */
if (!base_inited)
return;
/* Might be explicitly called and also by atexit */
if (stopped)
return;
stopped = 1;
/*
* Thread stop may not get automatically called by the thread library for
* the very last thread in some situations, so call it directly.
*/
OPENSSL_thread_stop();
currhandler = stop_handlers;
while (currhandler != NULL) {
currhandler->handler();
lasthandler = currhandler;
currhandler = currhandler->next;
OPENSSL_free(lasthandler);
}
stop_handlers = NULL;
CRYPTO_THREAD_lock_free(optsdone_lock);
optsdone_lock = NULL;
CRYPTO_THREAD_lock_free(init_lock);
init_lock = NULL;
CRYPTO_THREAD_cleanup_local(&in_init_config_local);
/*
* We assume we are single-threaded for this function, i.e. no race
* conditions for the various "*_inited" vars below.
*/
#ifndef OPENSSL_NO_COMP
OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_comp_zlib_cleanup()\n");
ossl_comp_zlib_cleanup();
OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_comp_brotli_cleanup()\n");
ossl_comp_brotli_cleanup();
OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_comp_zstd_cleanup()\n");
ossl_comp_zstd_cleanup();
#endif
if (async_inited) {
OSSL_TRACE(INIT, "OPENSSL_cleanup: async_deinit()\n");
async_deinit();
}
/*
* Note that cleanup order is important:
* - ossl_rand_cleanup_int could call an ENGINE's RAND cleanup function so
* must be called before engine_cleanup_int()
* - ENGINEs use CRYPTO_EX_DATA and therefore, must be cleaned up
* before the ex data handlers are wiped during default ossl_lib_ctx deinit.
* - ossl_config_modules_free() can end up in ENGINE code so must be called
* before engine_cleanup_int()
* - ENGINEs and additional EVP algorithms might use added OIDs names so
* ossl_obj_cleanup_int() must be called last
*/
OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_rand_cleanup_int()\n");
ossl_rand_cleanup_int();
OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_config_modules_free()\n");
ossl_config_modules_free();
#ifndef OPENSSL_NO_ENGINE
OSSL_TRACE(INIT, "OPENSSL_cleanup: engine_cleanup_int()\n");
engine_cleanup_int();
#endif
#ifndef OPENSSL_NO_DEPRECATED_3_0
OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_store_cleanup_int()\n");
ossl_store_cleanup_int();
#endif
OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_lib_ctx_default_deinit()\n");
ossl_lib_ctx_default_deinit();
ossl_cleanup_thread();
OSSL_TRACE(INIT, "OPENSSL_cleanup: bio_cleanup()\n");
bio_cleanup();
OSSL_TRACE(INIT, "OPENSSL_cleanup: evp_cleanup_int()\n");
evp_cleanup_int();
OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_obj_cleanup_int()\n");
ossl_obj_cleanup_int();
OSSL_TRACE(INIT, "OPENSSL_cleanup: err_int()\n");
err_cleanup();
OSSL_TRACE(INIT, "OPENSSL_cleanup: CRYPTO_secure_malloc_done()\n");
CRYPTO_secure_malloc_done();
#ifndef OPENSSL_NO_CMP
OSSL_TRACE(INIT, "OPENSSL_cleanup: OSSL_CMP_log_close()\n");
OSSL_CMP_log_close();
#endif
OSSL_TRACE(INIT, "OPENSSL_cleanup: ossl_trace_cleanup()\n");
ossl_trace_cleanup();
base_inited = 0;
}
/*
* If this function is called with a non NULL settings value then it must be
* called prior to any threads making calls to any OpenSSL functions,
* i.e. passing a non-null settings value is assumed to be single-threaded.
*/
int OPENSSL_init_crypto(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings)
{
uint64_t tmp;
int aloaddone = 0;
/* Applications depend on 0 being returned when cleanup was already done */
if (stopped) {
if (!(opts & OPENSSL_INIT_BASE_ONLY))
ERR_raise(ERR_LIB_CRYPTO, ERR_R_INIT_FAIL);
return 0;
}
/*
* We ignore failures from this function. It is probably because we are
* on a platform that doesn't support lockless atomic loads (we may not
* have created optsdone_lock yet so we can't use it). This is just an
* optimisation to skip the full checks in this function if we don't need
* to, so we carry on regardless in the event of failure.
*
* There could be a race here with other threads, so that optsdone has not
* been updated yet, even though the options have in fact been initialised.
* This doesn't matter - it just means we will run the full function
* unnecessarily - but all the critical code is contained in RUN_ONCE
* functions anyway so we are safe.
*/
if (CRYPTO_atomic_load(&optsdone, &tmp, NULL)) {
if ((tmp & opts) == opts)
return 1;
aloaddone = 1;
}
/*
* At some point we should look at this function with a view to moving
* most/all of this into OSSL_LIB_CTX.
*
* When the caller specifies OPENSSL_INIT_BASE_ONLY, that should be the
* *only* option specified. With that option we return immediately after
* doing the requested limited initialization. Note that
* err_shelve_state() called by us via ossl_init_load_crypto_nodelete()
* re-enters OPENSSL_init_crypto() with OPENSSL_INIT_BASE_ONLY, but with
* base already initialized this is a harmless NOOP.
*
* If we remain the only caller of err_shelve_state() the recursion should
* perhaps be removed, but if in doubt, it can be left in place.
*/
if (!RUN_ONCE(&base, ossl_init_base))
return 0;
if (opts & OPENSSL_INIT_BASE_ONLY)
return 1;
/*
* optsdone_lock should definitely be set up now, so we can now repeat the
* same check from above but be sure that it will work even on platforms
* without lockless CRYPTO_atomic_load
*/
if (!aloaddone) {
if (!CRYPTO_atomic_load(&optsdone, &tmp, optsdone_lock))
return 0;
if ((tmp & opts) == opts)
return 1;
}
/*
* Now we don't always set up exit handlers, the INIT_BASE_ONLY calls
* should not have the side-effect of setting up exit handlers, and
* therefore, this code block is below the INIT_BASE_ONLY-conditioned early
* return above.
*/
if ((opts & OPENSSL_INIT_NO_ATEXIT) != 0) {
if (!RUN_ONCE_ALT(®ister_atexit, ossl_init_no_register_atexit,
ossl_init_register_atexit))
return 0;
} else if (!RUN_ONCE(®ister_atexit, ossl_init_register_atexit)) {
return 0;
}
if (!RUN_ONCE(&load_crypto_nodelete, ossl_init_load_crypto_nodelete))
return 0;
if ((opts & OPENSSL_INIT_NO_LOAD_CRYPTO_STRINGS)
&& !RUN_ONCE_ALT(&load_crypto_strings,
ossl_init_no_load_crypto_strings,
ossl_init_load_crypto_strings))
return 0;
if ((opts & OPENSSL_INIT_LOAD_CRYPTO_STRINGS)
&& !RUN_ONCE(&load_crypto_strings, ossl_init_load_crypto_strings))
return 0;
if ((opts & OPENSSL_INIT_NO_ADD_ALL_CIPHERS)
&& !RUN_ONCE_ALT(&add_all_ciphers, ossl_init_no_add_all_ciphers,
ossl_init_add_all_ciphers))
return 0;
if ((opts & OPENSSL_INIT_ADD_ALL_CIPHERS)
&& !RUN_ONCE(&add_all_ciphers, ossl_init_add_all_ciphers))
return 0;
if ((opts & OPENSSL_INIT_NO_ADD_ALL_DIGESTS)
&& !RUN_ONCE_ALT(&add_all_digests, ossl_init_no_add_all_digests,
ossl_init_add_all_digests))
return 0;
if ((opts & OPENSSL_INIT_ADD_ALL_DIGESTS)
&& !RUN_ONCE(&add_all_digests, ossl_init_add_all_digests))
return 0;
if ((opts & OPENSSL_INIT_ATFORK)
&& !openssl_init_fork_handlers())
return 0;
if ((opts & OPENSSL_INIT_NO_LOAD_CONFIG)
&& !RUN_ONCE_ALT(&config, ossl_init_no_config, ossl_init_config))
return 0;
if (opts & OPENSSL_INIT_LOAD_CONFIG) {
int loading = CRYPTO_THREAD_get_local(&in_init_config_local) != NULL;
/* If called recursively from OBJ_ calls, just skip it. */
if (!loading) {
int ret;
if (!CRYPTO_THREAD_set_local(&in_init_config_local, (void *)-1))
return 0;
if (settings == NULL) {
ret = RUN_ONCE(&config, ossl_init_config);
} else {
if (!CRYPTO_THREAD_write_lock(init_lock))
return 0;
conf_settings = settings;
ret = RUN_ONCE_ALT(&config, ossl_init_config_settings,
ossl_init_config);
conf_settings = NULL;
CRYPTO_THREAD_unlock(init_lock);
}
if (ret <= 0)
return 0;
}
}
if ((opts & OPENSSL_INIT_ASYNC)
&& !RUN_ONCE(&async, ossl_init_async))
return 0;
#ifndef OPENSSL_NO_ENGINE
if ((opts & OPENSSL_INIT_ENGINE_OPENSSL)
&& !RUN_ONCE(&engine_openssl, ossl_init_engine_openssl))
return 0;
# ifndef OPENSSL_NO_RDRAND
if ((opts & OPENSSL_INIT_ENGINE_RDRAND)
&& !RUN_ONCE(&engine_rdrand, ossl_init_engine_rdrand))
return 0;
# endif
if ((opts & OPENSSL_INIT_ENGINE_DYNAMIC)
&& !RUN_ONCE(&engine_dynamic, ossl_init_engine_dynamic))
return 0;
# ifndef OPENSSL_NO_STATIC_ENGINE
# ifndef OPENSSL_NO_DEVCRYPTOENG
if ((opts & OPENSSL_INIT_ENGINE_CRYPTODEV)
&& !RUN_ONCE(&engine_devcrypto, ossl_init_engine_devcrypto))
return 0;
# endif
# if !defined(OPENSSL_NO_PADLOCKENG)
if ((opts & OPENSSL_INIT_ENGINE_PADLOCK)
&& !RUN_ONCE(&engine_padlock, ossl_init_engine_padlock))
return 0;
# endif
# if defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_NO_CAPIENG)
if ((opts & OPENSSL_INIT_ENGINE_CAPI)
&& !RUN_ONCE(&engine_capi, ossl_init_engine_capi))
return 0;
# endif
# if !defined(OPENSSL_NO_AFALGENG)
if ((opts & OPENSSL_INIT_ENGINE_AFALG)
&& !RUN_ONCE(&engine_afalg, ossl_init_engine_afalg))
return 0;
# endif
# endif
if (opts & (OPENSSL_INIT_ENGINE_ALL_BUILTIN
| OPENSSL_INIT_ENGINE_OPENSSL
| OPENSSL_INIT_ENGINE_AFALG)) {
ENGINE_register_all_complete();
}
#endif
if (!CRYPTO_atomic_or(&optsdone, opts, &tmp, optsdone_lock))
return 0;
return 1;
}
int OPENSSL_atexit(void (*handler)(void))
{
OPENSSL_INIT_STOP *newhand;
#if !defined(OPENSSL_USE_NODELETE)\
&& !defined(OPENSSL_NO_PINSHARED)
{
# if defined(DSO_WIN32) && !defined(_WIN32_WCE)
HMODULE handle = NULL;
BOOL ret;
union {
void *sym;
void (*func)(void);
} handlersym;
handlersym.func = handler;
/*
* We don't use the DSO route for WIN32 because there is a better
* way
*/
ret = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
| GET_MODULE_HANDLE_EX_FLAG_PIN,
handlersym.sym, &handle);
if (!ret)
return 0;
# elif !defined(DSO_NONE)
/*
* Deliberately leak a reference to the handler. This will force the
* library/code containing the handler to remain loaded until we run the
* atexit handler. If -znodelete has been used then this is
* unnecessary.
*/
DSO *dso = NULL;
union {
void *sym;
void (*func)(void);
} handlersym;
handlersym.func = handler;
ERR_set_mark();
dso = DSO_dsobyaddr(handlersym.sym, DSO_FLAG_NO_UNLOAD_ON_FREE);
/* See same code above in ossl_init_base() for an explanation. */
OSSL_TRACE1(INIT,
"atexit: obtained DSO reference? %s\n",
(dso == NULL ? "No!" : "Yes."));
DSO_free(dso);
ERR_pop_to_mark();
# endif
}
#endif
if ((newhand = OPENSSL_malloc(sizeof(*newhand))) == NULL)
return 0;
newhand->handler = handler;
newhand->next = stop_handlers;
stop_handlers = newhand;
return 1;
}
| 21,824 | 29.186722 | 80 | c |
openssl | openssl-master/crypto/initthread.c | /*
* Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/crypto.h>
#include <openssl/core_dispatch.h>
#include "crypto/cryptlib.h"
#include "prov/providercommon.h"
#include "internal/thread_once.h"
#include "crypto/context.h"
#ifdef FIPS_MODULE
#include "prov/provider_ctx.h"
/*
* Thread aware code may want to be told about thread stop events. We register
* to hear about those thread stop events when we see a new thread has started.
* We call the ossl_init_thread_start function to do that. In the FIPS provider
* we have our own copy of ossl_init_thread_start, which cascades notifications
* about threads stopping from libcrypto to all the code in the FIPS provider
* that needs to know about it.
*
* The FIPS provider tells libcrypto about which threads it is interested in
* by calling "c_thread_start" which is a function pointer created during
* provider initialisation (i.e. OSSL_init_provider).
*/
extern OSSL_FUNC_core_thread_start_fn *c_thread_start;
#endif
typedef struct thread_event_handler_st THREAD_EVENT_HANDLER;
struct thread_event_handler_st {
#ifndef FIPS_MODULE
const void *index;
#endif
void *arg;
OSSL_thread_stop_handler_fn handfn;
THREAD_EVENT_HANDLER *next;
};
#ifndef FIPS_MODULE
DEFINE_SPECIAL_STACK_OF(THREAD_EVENT_HANDLER_PTR, THREAD_EVENT_HANDLER *)
typedef struct global_tevent_register_st GLOBAL_TEVENT_REGISTER;
struct global_tevent_register_st {
STACK_OF(THREAD_EVENT_HANDLER_PTR) *skhands;
CRYPTO_RWLOCK *lock;
};
static GLOBAL_TEVENT_REGISTER *glob_tevent_reg = NULL;
static CRYPTO_ONCE tevent_register_runonce = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(create_global_tevent_register)
{
glob_tevent_reg = OPENSSL_zalloc(sizeof(*glob_tevent_reg));
if (glob_tevent_reg == NULL)
return 0;
glob_tevent_reg->skhands = sk_THREAD_EVENT_HANDLER_PTR_new_null();
glob_tevent_reg->lock = CRYPTO_THREAD_lock_new();
if (glob_tevent_reg->skhands == NULL || glob_tevent_reg->lock == NULL) {
sk_THREAD_EVENT_HANDLER_PTR_free(glob_tevent_reg->skhands);
CRYPTO_THREAD_lock_free(glob_tevent_reg->lock);
OPENSSL_free(glob_tevent_reg);
glob_tevent_reg = NULL;
return 0;
}
return 1;
}
static GLOBAL_TEVENT_REGISTER *get_global_tevent_register(void)
{
if (!RUN_ONCE(&tevent_register_runonce, create_global_tevent_register))
return NULL;
return glob_tevent_reg;
}
#endif
#ifndef FIPS_MODULE
static int init_thread_push_handlers(THREAD_EVENT_HANDLER **hands);
static void init_thread_remove_handlers(THREAD_EVENT_HANDLER **handsin);
static void init_thread_destructor(void *hands);
static int init_thread_deregister(void *arg, int all);
#endif
static void init_thread_stop(void *arg, THREAD_EVENT_HANDLER **hands);
static THREAD_EVENT_HANDLER **
init_get_thread_local(CRYPTO_THREAD_LOCAL *local, int alloc, int keep)
{
THREAD_EVENT_HANDLER **hands = CRYPTO_THREAD_get_local(local);
if (alloc) {
if (hands == NULL) {
if ((hands = OPENSSL_zalloc(sizeof(*hands))) == NULL)
return NULL;
if (!CRYPTO_THREAD_set_local(local, hands)) {
OPENSSL_free(hands);
return NULL;
}
#ifndef FIPS_MODULE
if (!init_thread_push_handlers(hands)) {
CRYPTO_THREAD_set_local(local, NULL);
OPENSSL_free(hands);
return NULL;
}
#endif
}
} else if (!keep) {
CRYPTO_THREAD_set_local(local, NULL);
}
return hands;
}
#ifndef FIPS_MODULE
/*
* Since per-thread-specific-data destructors are not universally
* available, i.e. not on Windows, only below CRYPTO_THREAD_LOCAL key
* is assumed to have destructor associated. And then an effort is made
* to call this single destructor on non-pthread platform[s].
*
* Initial value is "impossible". It is used as guard value to shortcut
* destructor for threads terminating before libcrypto is initialized or
* after it's de-initialized. Access to the key doesn't have to be
* serialized for the said threads, because they didn't use libcrypto
* and it doesn't matter if they pick "impossible" or dereference real
* key value and pull NULL past initialization in the first thread that
* intends to use libcrypto.
*/
static union {
long sane;
CRYPTO_THREAD_LOCAL value;
} destructor_key = { -1 };
/*
* The thread event handler list is a thread specific linked list
* of callback functions which are invoked in list order by the
* current thread in case of certain events. (Currently, there is
* only one type of event, the 'thread stop' event.)
*
* We also keep a global reference to that linked list, so that we
* can deregister handlers if necessary before all the threads are
* stopped.
*/
static int init_thread_push_handlers(THREAD_EVENT_HANDLER **hands)
{
int ret;
GLOBAL_TEVENT_REGISTER *gtr;
gtr = get_global_tevent_register();
if (gtr == NULL)
return 0;
if (!CRYPTO_THREAD_write_lock(gtr->lock))
return 0;
ret = (sk_THREAD_EVENT_HANDLER_PTR_push(gtr->skhands, hands) != 0);
CRYPTO_THREAD_unlock(gtr->lock);
return ret;
}
static void init_thread_remove_handlers(THREAD_EVENT_HANDLER **handsin)
{
GLOBAL_TEVENT_REGISTER *gtr;
int i;
gtr = get_global_tevent_register();
if (gtr == NULL)
return;
if (!CRYPTO_THREAD_write_lock(gtr->lock))
return;
for (i = 0; i < sk_THREAD_EVENT_HANDLER_PTR_num(gtr->skhands); i++) {
THREAD_EVENT_HANDLER **hands
= sk_THREAD_EVENT_HANDLER_PTR_value(gtr->skhands, i);
if (hands == handsin) {
sk_THREAD_EVENT_HANDLER_PTR_delete(gtr->skhands, i);
CRYPTO_THREAD_unlock(gtr->lock);
return;
}
}
CRYPTO_THREAD_unlock(gtr->lock);
return;
}
static void init_thread_destructor(void *hands)
{
init_thread_stop(NULL, (THREAD_EVENT_HANDLER **)hands);
init_thread_remove_handlers(hands);
OPENSSL_free(hands);
}
int ossl_init_thread(void)
{
if (!CRYPTO_THREAD_init_local(&destructor_key.value,
init_thread_destructor))
return 0;
return 1;
}
void ossl_cleanup_thread(void)
{
init_thread_deregister(NULL, 1);
CRYPTO_THREAD_cleanup_local(&destructor_key.value);
destructor_key.sane = -1;
}
void OPENSSL_thread_stop_ex(OSSL_LIB_CTX *ctx)
{
ctx = ossl_lib_ctx_get_concrete(ctx);
/*
* It would be nice if we could figure out a way to do this on all threads
* that have used the OSSL_LIB_CTX when the context is freed. This is
* currently not possible due to the use of thread local variables.
*/
ossl_ctx_thread_stop(ctx);
}
void OPENSSL_thread_stop(void)
{
if (destructor_key.sane != -1) {
THREAD_EVENT_HANDLER **hands
= init_get_thread_local(&destructor_key.value, 0, 0);
init_thread_stop(NULL, hands);
init_thread_remove_handlers(hands);
OPENSSL_free(hands);
}
}
void ossl_ctx_thread_stop(OSSL_LIB_CTX *ctx)
{
if (destructor_key.sane != -1) {
THREAD_EVENT_HANDLER **hands
= init_get_thread_local(&destructor_key.value, 0, 1);
init_thread_stop(ctx, hands);
}
}
#else
void *ossl_thread_event_ctx_new(OSSL_LIB_CTX *libctx)
{
THREAD_EVENT_HANDLER **hands = NULL;
CRYPTO_THREAD_LOCAL *tlocal = OPENSSL_zalloc(sizeof(*tlocal));
if (tlocal == NULL)
return NULL;
if (!CRYPTO_THREAD_init_local(tlocal, NULL)) {
goto err;
}
hands = OPENSSL_zalloc(sizeof(*hands));
if (hands == NULL)
goto err;
if (!CRYPTO_THREAD_set_local(tlocal, hands))
goto err;
return tlocal;
err:
OPENSSL_free(hands);
OPENSSL_free(tlocal);
return NULL;
}
void ossl_thread_event_ctx_free(void *tlocal)
{
OPENSSL_free(tlocal);
}
static void ossl_arg_thread_stop(void *arg)
{
ossl_ctx_thread_stop((OSSL_LIB_CTX *)arg);
}
void ossl_ctx_thread_stop(OSSL_LIB_CTX *ctx)
{
THREAD_EVENT_HANDLER **hands;
CRYPTO_THREAD_LOCAL *local
= ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_THREAD_EVENT_HANDLER_INDEX);
if (local == NULL)
return;
hands = init_get_thread_local(local, 0, 0);
init_thread_stop(ctx, hands);
OPENSSL_free(hands);
}
#endif /* FIPS_MODULE */
static void init_thread_stop(void *arg, THREAD_EVENT_HANDLER **hands)
{
THREAD_EVENT_HANDLER *curr, *prev = NULL, *tmp;
#ifndef FIPS_MODULE
GLOBAL_TEVENT_REGISTER *gtr;
#endif
/* Can't do much about this */
if (hands == NULL)
return;
#ifndef FIPS_MODULE
gtr = get_global_tevent_register();
if (gtr == NULL)
return;
if (!CRYPTO_THREAD_write_lock(gtr->lock))
return;
#endif
curr = *hands;
while (curr != NULL) {
if (arg != NULL && curr->arg != arg) {
prev = curr;
curr = curr->next;
continue;
}
curr->handfn(curr->arg);
if (prev == NULL)
*hands = curr->next;
else
prev->next = curr->next;
tmp = curr;
curr = curr->next;
OPENSSL_free(tmp);
}
#ifndef FIPS_MODULE
CRYPTO_THREAD_unlock(gtr->lock);
#endif
}
int ossl_init_thread_start(const void *index, void *arg,
OSSL_thread_stop_handler_fn handfn)
{
THREAD_EVENT_HANDLER **hands;
THREAD_EVENT_HANDLER *hand;
#ifdef FIPS_MODULE
OSSL_LIB_CTX *ctx = arg;
/*
* In FIPS mode the list of THREAD_EVENT_HANDLERs is unique per combination
* of OSSL_LIB_CTX and thread. This is because in FIPS mode each
* OSSL_LIB_CTX gets informed about thread stop events individually.
*/
CRYPTO_THREAD_LOCAL *local
= ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_THREAD_EVENT_HANDLER_INDEX);
#else
/*
* Outside of FIPS mode the list of THREAD_EVENT_HANDLERs is unique per
* thread, but may hold multiple OSSL_LIB_CTXs. We only get told about
* thread stop events globally, so we have to ensure all affected
* OSSL_LIB_CTXs are informed.
*/
CRYPTO_THREAD_LOCAL *local = &destructor_key.value;
#endif
hands = init_get_thread_local(local, 1, 0);
if (hands == NULL)
return 0;
#ifdef FIPS_MODULE
if (*hands == NULL) {
/*
* We've not yet registered any handlers for this thread. We need to get
* libcrypto to tell us about later thread stop events. c_thread_start
* is a callback to libcrypto defined in fipsprov.c
*/
if (!c_thread_start(FIPS_get_core_handle(ctx), ossl_arg_thread_stop,
ctx))
return 0;
}
#endif
hand = OPENSSL_malloc(sizeof(*hand));
if (hand == NULL)
return 0;
hand->handfn = handfn;
hand->arg = arg;
#ifndef FIPS_MODULE
hand->index = index;
#endif
hand->next = *hands;
*hands = hand;
return 1;
}
#ifndef FIPS_MODULE
static int init_thread_deregister(void *index, int all)
{
GLOBAL_TEVENT_REGISTER *gtr;
int i;
gtr = get_global_tevent_register();
if (gtr == NULL)
return 0;
if (!all) {
if (!CRYPTO_THREAD_write_lock(gtr->lock))
return 0;
} else {
glob_tevent_reg = NULL;
}
for (i = 0; i < sk_THREAD_EVENT_HANDLER_PTR_num(gtr->skhands); i++) {
THREAD_EVENT_HANDLER **hands
= sk_THREAD_EVENT_HANDLER_PTR_value(gtr->skhands, i);
THREAD_EVENT_HANDLER *curr = NULL, *prev = NULL, *tmp;
if (hands == NULL) {
if (!all)
CRYPTO_THREAD_unlock(gtr->lock);
return 0;
}
curr = *hands;
while (curr != NULL) {
if (all || curr->index == index) {
if (prev != NULL)
prev->next = curr->next;
else
*hands = curr->next;
tmp = curr;
curr = curr->next;
OPENSSL_free(tmp);
continue;
}
prev = curr;
curr = curr->next;
}
if (all)
OPENSSL_free(hands);
}
if (all) {
CRYPTO_THREAD_lock_free(gtr->lock);
sk_THREAD_EVENT_HANDLER_PTR_free(gtr->skhands);
OPENSSL_free(gtr);
} else {
CRYPTO_THREAD_unlock(gtr->lock);
}
return 1;
}
int ossl_init_thread_deregister(void *index)
{
return init_thread_deregister(index, 0);
}
#endif
| 12,783 | 26.73102 | 80 | c |
openssl | openssl-master/crypto/loongarch_arch.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
*/
#ifndef OSSL_CRYPTO_LOONGARCH_ARCH_H
# define OSSL_CRYPTO_LOONGARCH_ARCH_H
extern unsigned int OPENSSL_loongarchcap_P;
# define LOONGARCH_CFG2 0x02
# define LOONGARCH_CFG2_LSX (1<<6)
# define LOONGARCH_CFG2_LASX (1<<7)
#endif
| 565 | 30.444444 | 74 | h |
openssl | openssl-master/crypto/loongarchcap.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 "loongarch_arch.h"
unsigned int OPENSSL_loongarchcap_P = 0;
void OPENSSL_cpuid_setup(void)
{
unsigned int reg;
__asm__ volatile(
"cpucfg %0, %1 \n\t"
: "+&r"(reg)
: "r"(LOONGARCH_CFG2)
);
OPENSSL_loongarchcap_P = reg;
}
| 581 | 24.304348 | 74 | c |
openssl | openssl-master/crypto/mem.c | /*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/e_os.h"
#include "internal/cryptlib.h"
#include "crypto/cryptlib.h"
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <openssl/crypto.h>
/*
* the following pointers may be changed as long as 'allow_customize' is set
*/
static int allow_customize = 1;
static CRYPTO_malloc_fn malloc_impl = CRYPTO_malloc;
static CRYPTO_realloc_fn realloc_impl = CRYPTO_realloc;
static CRYPTO_free_fn free_impl = CRYPTO_free;
#if !defined(OPENSSL_NO_CRYPTO_MDEBUG) && !defined(FIPS_MODULE)
# include "internal/tsan_assist.h"
# ifdef TSAN_REQUIRES_LOCKING
# define INCREMENT(x) /* empty */
# define LOAD(x) 0
# else /* TSAN_REQUIRES_LOCKING */
static TSAN_QUALIFIER int malloc_count;
static TSAN_QUALIFIER int realloc_count;
static TSAN_QUALIFIER int free_count;
# define INCREMENT(x) tsan_counter(&(x))
# define LOAD(x) tsan_load(&x)
# endif /* TSAN_REQUIRES_LOCKING */
static char *md_failstring;
static long md_count;
static int md_fail_percent = 0;
static int md_tracefd = -1;
static void parseit(void);
static int shouldfail(void);
# define FAILTEST() if (shouldfail()) return NULL
#else
# define INCREMENT(x) /* empty */
# define FAILTEST() /* empty */
#endif
int CRYPTO_set_mem_functions(CRYPTO_malloc_fn malloc_fn,
CRYPTO_realloc_fn realloc_fn,
CRYPTO_free_fn free_fn)
{
if (!allow_customize)
return 0;
if (malloc_fn != NULL)
malloc_impl = malloc_fn;
if (realloc_fn != NULL)
realloc_impl = realloc_fn;
if (free_fn != NULL)
free_impl = free_fn;
return 1;
}
void CRYPTO_get_mem_functions(CRYPTO_malloc_fn *malloc_fn,
CRYPTO_realloc_fn *realloc_fn,
CRYPTO_free_fn *free_fn)
{
if (malloc_fn != NULL)
*malloc_fn = malloc_impl;
if (realloc_fn != NULL)
*realloc_fn = realloc_impl;
if (free_fn != NULL)
*free_fn = free_impl;
}
#if !defined(OPENSSL_NO_CRYPTO_MDEBUG) && !defined(FIPS_MODULE)
void CRYPTO_get_alloc_counts(int *mcount, int *rcount, int *fcount)
{
if (mcount != NULL)
*mcount = LOAD(malloc_count);
if (rcount != NULL)
*rcount = LOAD(realloc_count);
if (fcount != NULL)
*fcount = LOAD(free_count);
}
/*
* Parse a "malloc failure spec" string. This likes like a set of fields
* separated by semicolons. Each field has a count and an optional failure
* percentage. For example:
* 100@0;100@25;0@0
* or 100;100@25;0
* This means 100 mallocs succeed, then next 100 fail 25% of the time, and
* all remaining (count is zero) succeed.
*/
static void parseit(void)
{
char *semi = strchr(md_failstring, ';');
char *atsign;
if (semi != NULL)
*semi++ = '\0';
/* Get the count (atol will stop at the @ if there), and percentage */
md_count = atol(md_failstring);
atsign = strchr(md_failstring, '@');
md_fail_percent = atsign == NULL ? 0 : atoi(atsign + 1);
if (semi != NULL)
md_failstring = semi;
}
/*
* Windows doesn't have random(), but it has rand()
* Some rand() implementations aren't good, but we're not
* dealing with secure randomness here.
*/
# ifdef _WIN32
# define random() rand()
# endif
/*
* See if the current malloc should fail.
*/
static int shouldfail(void)
{
int roll = (int)(random() % 100);
int shoulditfail = roll < md_fail_percent;
# ifndef _WIN32
/* suppressed on Windows as POSIX-like file descriptors are non-inheritable */
int len;
char buff[80];
if (md_tracefd > 0) {
BIO_snprintf(buff, sizeof(buff),
"%c C%ld %%%d R%d\n",
shoulditfail ? '-' : '+', md_count, md_fail_percent, roll);
len = strlen(buff);
if (write(md_tracefd, buff, len) != len)
perror("shouldfail write failed");
}
# endif
if (md_count) {
/* If we used up this one, go to the next. */
if (--md_count == 0)
parseit();
}
return shoulditfail;
}
void ossl_malloc_setup_failures(void)
{
const char *cp = getenv("OPENSSL_MALLOC_FAILURES");
if (cp != NULL && (md_failstring = strdup(cp)) != NULL)
parseit();
if ((cp = getenv("OPENSSL_MALLOC_FD")) != NULL)
md_tracefd = atoi(cp);
}
#endif
void *CRYPTO_malloc(size_t num, const char *file, int line)
{
void *ptr;
INCREMENT(malloc_count);
if (malloc_impl != CRYPTO_malloc) {
ptr = malloc_impl(num, file, line);
if (ptr != NULL || num == 0)
return ptr;
goto err;
}
if (num == 0)
return NULL;
FAILTEST();
if (allow_customize) {
/*
* Disallow customization after the first allocation. We only set this
* if necessary to avoid a store to the same cache line on every
* allocation.
*/
allow_customize = 0;
}
ptr = malloc(num);
if (ptr != NULL)
return ptr;
err:
/*
* ossl_err_get_state_int() in err.c uses CRYPTO_zalloc(num, NULL, 0) for
* ERR_STATE allocation. Prevent mem alloc error loop while reporting error.
*/
if (file != NULL || line != 0) {
ERR_new();
ERR_set_debug(file, line, NULL);
ERR_set_error(ERR_LIB_CRYPTO, ERR_R_MALLOC_FAILURE, NULL);
}
return NULL;
}
void *CRYPTO_zalloc(size_t num, const char *file, int line)
{
void *ret;
ret = CRYPTO_malloc(num, file, line);
FAILTEST();
if (ret != NULL)
memset(ret, 0, num);
return ret;
}
void *CRYPTO_realloc(void *str, size_t num, const char *file, int line)
{
INCREMENT(realloc_count);
if (realloc_impl != CRYPTO_realloc)
return realloc_impl(str, num, file, line);
FAILTEST();
if (str == NULL)
return CRYPTO_malloc(num, file, line);
if (num == 0) {
CRYPTO_free(str, file, line);
return NULL;
}
return realloc(str, num);
}
void *CRYPTO_clear_realloc(void *str, size_t old_len, size_t num,
const char *file, int line)
{
void *ret = NULL;
if (str == NULL)
return CRYPTO_malloc(num, file, line);
if (num == 0) {
CRYPTO_clear_free(str, old_len, file, line);
return NULL;
}
/* Can't shrink the buffer since memcpy below copies |old_len| bytes. */
if (num < old_len) {
OPENSSL_cleanse((char*)str + num, old_len - num);
return str;
}
ret = CRYPTO_malloc(num, file, line);
if (ret != NULL) {
memcpy(ret, str, old_len);
CRYPTO_clear_free(str, old_len, file, line);
}
return ret;
}
void CRYPTO_free(void *str, const char *file, int line)
{
INCREMENT(free_count);
if (free_impl != CRYPTO_free) {
free_impl(str, file, line);
return;
}
free(str);
}
void CRYPTO_clear_free(void *str, size_t num, const char *file, int line)
{
if (str == NULL)
return;
if (num)
OPENSSL_cleanse(str, num);
CRYPTO_free(str, file, line);
}
#if !defined(OPENSSL_NO_CRYPTO_MDEBUG)
# ifndef OPENSSL_NO_DEPRECATED_3_0
int CRYPTO_mem_ctrl(int mode)
{
(void)mode;
return -1;
}
int CRYPTO_set_mem_debug(int flag)
{
(void)flag;
return -1;
}
int CRYPTO_mem_debug_push(const char *info, const char *file, int line)
{
(void)info; (void)file; (void)line;
return 0;
}
int CRYPTO_mem_debug_pop(void)
{
return 0;
}
void CRYPTO_mem_debug_malloc(void *addr, size_t num, int flag,
const char *file, int line)
{
(void)addr; (void)num; (void)flag; (void)file; (void)line;
}
void CRYPTO_mem_debug_realloc(void *addr1, void *addr2, size_t num, int flag,
const char *file, int line)
{
(void)addr1; (void)addr2; (void)num; (void)flag; (void)file; (void)line;
}
void CRYPTO_mem_debug_free(void *addr, int flag,
const char *file, int line)
{
(void)addr; (void)flag; (void)file; (void)line;
}
int CRYPTO_mem_leaks(BIO *b)
{
(void)b;
return -1;
}
# ifndef OPENSSL_NO_STDIO
int CRYPTO_mem_leaks_fp(FILE *fp)
{
(void)fp;
return -1;
}
# endif
int CRYPTO_mem_leaks_cb(int (*cb)(const char *str, size_t len, void *u),
void *u)
{
(void)cb; (void)u;
return -1;
}
# endif
#endif
| 8,658 | 23.254902 | 80 | c |
openssl | openssl-master/crypto/mem_clr.c | /*
* Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include <openssl/crypto.h>
/*
* Pointer to memset is volatile so that compiler must de-reference
* the pointer and can't assume that it points to any function in
* particular (such as memset, which it then might further "optimize")
*/
typedef void *(*memset_t)(void *, int, size_t);
static volatile memset_t memset_func = memset;
void OPENSSL_cleanse(void *ptr, size_t len)
{
memset_func(ptr, 0, len);
}
| 773 | 28.769231 | 74 | c |
openssl | openssl-master/crypto/mem_sec.c | /*
* Copyright 2015-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright 2004-2014, Akamai Technologies. 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 is in two halves. The first half implements the public API
* to be used by external consumers, and to be used by OpenSSL to store
* data in a "secure arena." The second half implements the secure arena.
* For details on that implementation, see below (look for uppercase
* "SECURE HEAP IMPLEMENTATION").
*/
#include "internal/e_os.h"
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <string.h>
#ifndef OPENSSL_NO_SECURE_MEMORY
# if defined(_WIN32)
# include <windows.h>
# if defined(WINAPI_FAMILY_PARTITION)
# if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM)
/*
* While VirtualLock is available under the app partition (e.g. UWP),
* the headers do not define the API. Define it ourselves instead.
*/
WINBASEAPI
BOOL
WINAPI
VirtualLock(
_In_ LPVOID lpAddress,
_In_ SIZE_T dwSize
);
# endif
# endif
# endif
# include <stdlib.h>
# include <assert.h>
# if defined(OPENSSL_SYS_UNIX)
# include <unistd.h>
# endif
# include <sys/types.h>
# if defined(OPENSSL_SYS_UNIX)
# include <sys/mman.h>
# if defined(__FreeBSD__)
# define MADV_DONTDUMP MADV_NOCORE
# endif
# if !defined(MAP_CONCEAL)
# define MAP_CONCEAL 0
# endif
# endif
# if defined(OPENSSL_SYS_LINUX)
# include <sys/syscall.h>
# if defined(SYS_mlock2)
# include <linux/mman.h>
# include <errno.h>
# endif
# include <sys/param.h>
# endif
# include <sys/stat.h>
# include <fcntl.h>
#endif
#ifndef HAVE_MADVISE
# if defined(MADV_DONTDUMP)
# define HAVE_MADVISE 1
# else
# define HAVE_MADVISE 0
# endif
#endif
#if HAVE_MADVISE
# undef NO_MADVISE
#else
# define NO_MADVISE
#endif
#define CLEAR(p, s) OPENSSL_cleanse(p, s)
#ifndef PAGE_SIZE
# define PAGE_SIZE 4096
#endif
#if !defined(MAP_ANON) && defined(MAP_ANONYMOUS)
# define MAP_ANON MAP_ANONYMOUS
#endif
#ifndef OPENSSL_NO_SECURE_MEMORY
static size_t secure_mem_used;
static int secure_mem_initialized;
static CRYPTO_RWLOCK *sec_malloc_lock = NULL;
/*
* These are the functions that must be implemented by a secure heap (sh).
*/
static int sh_init(size_t size, size_t minsize);
static void *sh_malloc(size_t size);
static void sh_free(void *ptr);
static void sh_done(void);
static size_t sh_actual_size(char *ptr);
static int sh_allocated(const char *ptr);
#endif
int CRYPTO_secure_malloc_init(size_t size, size_t minsize)
{
#ifndef OPENSSL_NO_SECURE_MEMORY
int ret = 0;
if (!secure_mem_initialized) {
sec_malloc_lock = CRYPTO_THREAD_lock_new();
if (sec_malloc_lock == NULL)
return 0;
if ((ret = sh_init(size, minsize)) != 0) {
secure_mem_initialized = 1;
} else {
CRYPTO_THREAD_lock_free(sec_malloc_lock);
sec_malloc_lock = NULL;
}
}
return ret;
#else
return 0;
#endif /* OPENSSL_NO_SECURE_MEMORY */
}
int CRYPTO_secure_malloc_done(void)
{
#ifndef OPENSSL_NO_SECURE_MEMORY
if (secure_mem_used == 0) {
sh_done();
secure_mem_initialized = 0;
CRYPTO_THREAD_lock_free(sec_malloc_lock);
sec_malloc_lock = NULL;
return 1;
}
#endif /* OPENSSL_NO_SECURE_MEMORY */
return 0;
}
int CRYPTO_secure_malloc_initialized(void)
{
#ifndef OPENSSL_NO_SECURE_MEMORY
return secure_mem_initialized;
#else
return 0;
#endif /* OPENSSL_NO_SECURE_MEMORY */
}
void *CRYPTO_secure_malloc(size_t num, const char *file, int line)
{
#ifndef OPENSSL_NO_SECURE_MEMORY
void *ret = NULL;
size_t actual_size;
int reason = CRYPTO_R_SECURE_MALLOC_FAILURE;
if (!secure_mem_initialized) {
return CRYPTO_malloc(num, file, line);
}
if (!CRYPTO_THREAD_write_lock(sec_malloc_lock)) {
reason = ERR_R_CRYPTO_LIB;
goto err;
}
ret = sh_malloc(num);
actual_size = ret ? sh_actual_size(ret) : 0;
secure_mem_used += actual_size;
CRYPTO_THREAD_unlock(sec_malloc_lock);
err:
if (ret == NULL && (file != NULL || line != 0)) {
ERR_new();
ERR_set_debug(file, line, NULL);
ERR_set_error(ERR_LIB_CRYPTO, reason, NULL);
}
return ret;
#else
return CRYPTO_malloc(num, file, line);
#endif /* OPENSSL_NO_SECURE_MEMORY */
}
void *CRYPTO_secure_zalloc(size_t num, const char *file, int line)
{
#ifndef OPENSSL_NO_SECURE_MEMORY
if (secure_mem_initialized)
/* CRYPTO_secure_malloc() zeroes allocations when it is implemented */
return CRYPTO_secure_malloc(num, file, line);
#endif
return CRYPTO_zalloc(num, file, line);
}
void CRYPTO_secure_free(void *ptr, const char *file, int line)
{
#ifndef OPENSSL_NO_SECURE_MEMORY
size_t actual_size;
if (ptr == NULL)
return;
if (!CRYPTO_secure_allocated(ptr)) {
CRYPTO_free(ptr, file, line);
return;
}
if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
return;
actual_size = sh_actual_size(ptr);
CLEAR(ptr, actual_size);
secure_mem_used -= actual_size;
sh_free(ptr);
CRYPTO_THREAD_unlock(sec_malloc_lock);
#else
CRYPTO_free(ptr, file, line);
#endif /* OPENSSL_NO_SECURE_MEMORY */
}
void CRYPTO_secure_clear_free(void *ptr, size_t num,
const char *file, int line)
{
#ifndef OPENSSL_NO_SECURE_MEMORY
size_t actual_size;
if (ptr == NULL)
return;
if (!CRYPTO_secure_allocated(ptr)) {
OPENSSL_cleanse(ptr, num);
CRYPTO_free(ptr, file, line);
return;
}
if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
return;
actual_size = sh_actual_size(ptr);
CLEAR(ptr, actual_size);
secure_mem_used -= actual_size;
sh_free(ptr);
CRYPTO_THREAD_unlock(sec_malloc_lock);
#else
if (ptr == NULL)
return;
OPENSSL_cleanse(ptr, num);
CRYPTO_free(ptr, file, line);
#endif /* OPENSSL_NO_SECURE_MEMORY */
}
int CRYPTO_secure_allocated(const void *ptr)
{
#ifndef OPENSSL_NO_SECURE_MEMORY
if (!secure_mem_initialized)
return 0;
/*
* Only read accesses to the arena take place in sh_allocated() and this
* is only changed by the sh_init() and sh_done() calls which are not
* locked. Hence, it is safe to make this check without a lock too.
*/
return sh_allocated(ptr);
#else
return 0;
#endif /* OPENSSL_NO_SECURE_MEMORY */
}
size_t CRYPTO_secure_used(void)
{
#ifndef OPENSSL_NO_SECURE_MEMORY
return secure_mem_used;
#else
return 0;
#endif /* OPENSSL_NO_SECURE_MEMORY */
}
size_t CRYPTO_secure_actual_size(void *ptr)
{
#ifndef OPENSSL_NO_SECURE_MEMORY
size_t actual_size;
if (!CRYPTO_THREAD_write_lock(sec_malloc_lock))
return 0;
actual_size = sh_actual_size(ptr);
CRYPTO_THREAD_unlock(sec_malloc_lock);
return actual_size;
#else
return 0;
#endif
}
/*
* SECURE HEAP IMPLEMENTATION
*/
#ifndef OPENSSL_NO_SECURE_MEMORY
/*
* The implementation provided here uses a fixed-sized mmap() heap,
* which is locked into memory, not written to core files, and protected
* on either side by an unmapped page, which will catch pointer overruns
* (or underruns) and an attempt to read data out of the secure heap.
* Free'd memory is zero'd or otherwise cleansed.
*
* This is a pretty standard buddy allocator. We keep areas in a multiple
* of "sh.minsize" units. The freelist and bitmaps are kept separately,
* so all (and only) data is kept in the mmap'd heap.
*
* This code assumes eight-bit bytes. The numbers 3 and 7 are all over the
* place.
*/
#define ONE ((size_t)1)
# define TESTBIT(t, b) (t[(b) >> 3] & (ONE << ((b) & 7)))
# define SETBIT(t, b) (t[(b) >> 3] |= (ONE << ((b) & 7)))
# define CLEARBIT(t, b) (t[(b) >> 3] &= (0xFF & ~(ONE << ((b) & 7))))
#define WITHIN_ARENA(p) \
((char*)(p) >= sh.arena && (char*)(p) < &sh.arena[sh.arena_size])
#define WITHIN_FREELIST(p) \
((char*)(p) >= (char*)sh.freelist && (char*)(p) < (char*)&sh.freelist[sh.freelist_size])
typedef struct sh_list_st
{
struct sh_list_st *next;
struct sh_list_st **p_next;
} SH_LIST;
typedef struct sh_st
{
char* map_result;
size_t map_size;
char *arena;
size_t arena_size;
char **freelist;
ossl_ssize_t freelist_size;
size_t minsize;
unsigned char *bittable;
unsigned char *bitmalloc;
size_t bittable_size; /* size in bits */
} SH;
static SH sh;
static size_t sh_getlist(char *ptr)
{
ossl_ssize_t list = sh.freelist_size - 1;
size_t bit = (sh.arena_size + ptr - sh.arena) / sh.minsize;
for (; bit; bit >>= 1, list--) {
if (TESTBIT(sh.bittable, bit))
break;
OPENSSL_assert((bit & 1) == 0);
}
return list;
}
static int sh_testbit(char *ptr, int list, unsigned char *table)
{
size_t bit;
OPENSSL_assert(list >= 0 && list < sh.freelist_size);
OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
return TESTBIT(table, bit);
}
static void sh_clearbit(char *ptr, int list, unsigned char *table)
{
size_t bit;
OPENSSL_assert(list >= 0 && list < sh.freelist_size);
OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
OPENSSL_assert(TESTBIT(table, bit));
CLEARBIT(table, bit);
}
static void sh_setbit(char *ptr, int list, unsigned char *table)
{
size_t bit;
OPENSSL_assert(list >= 0 && list < sh.freelist_size);
OPENSSL_assert(((ptr - sh.arena) & ((sh.arena_size >> list) - 1)) == 0);
bit = (ONE << list) + ((ptr - sh.arena) / (sh.arena_size >> list));
OPENSSL_assert(bit > 0 && bit < sh.bittable_size);
OPENSSL_assert(!TESTBIT(table, bit));
SETBIT(table, bit);
}
static void sh_add_to_list(char **list, char *ptr)
{
SH_LIST *temp;
OPENSSL_assert(WITHIN_FREELIST(list));
OPENSSL_assert(WITHIN_ARENA(ptr));
temp = (SH_LIST *)ptr;
temp->next = *(SH_LIST **)list;
OPENSSL_assert(temp->next == NULL || WITHIN_ARENA(temp->next));
temp->p_next = (SH_LIST **)list;
if (temp->next != NULL) {
OPENSSL_assert((char **)temp->next->p_next == list);
temp->next->p_next = &(temp->next);
}
*list = ptr;
}
static void sh_remove_from_list(char *ptr)
{
SH_LIST *temp, *temp2;
temp = (SH_LIST *)ptr;
if (temp->next != NULL)
temp->next->p_next = temp->p_next;
*temp->p_next = temp->next;
if (temp->next == NULL)
return;
temp2 = temp->next;
OPENSSL_assert(WITHIN_FREELIST(temp2->p_next) || WITHIN_ARENA(temp2->p_next));
}
static int sh_init(size_t size, size_t minsize)
{
int ret;
size_t i;
size_t pgsize;
size_t aligned;
#if defined(_WIN32)
DWORD flOldProtect;
SYSTEM_INFO systemInfo;
#endif
memset(&sh, 0, sizeof(sh));
/* make sure size is a powers of 2 */
OPENSSL_assert(size > 0);
OPENSSL_assert((size & (size - 1)) == 0);
if (size == 0 || (size & (size - 1)) != 0)
goto err;
if (minsize <= sizeof(SH_LIST)) {
OPENSSL_assert(sizeof(SH_LIST) <= 65536);
/*
* Compute the minimum possible allocation size.
* This must be a power of 2 and at least as large as the SH_LIST
* structure.
*/
minsize = sizeof(SH_LIST) - 1;
minsize |= minsize >> 1;
minsize |= minsize >> 2;
if (sizeof(SH_LIST) > 16)
minsize |= minsize >> 4;
if (sizeof(SH_LIST) > 256)
minsize |= minsize >> 8;
minsize++;
} else {
/* make sure minsize is a powers of 2 */
OPENSSL_assert((minsize & (minsize - 1)) == 0);
if ((minsize & (minsize - 1)) != 0)
goto err;
}
sh.arena_size = size;
sh.minsize = minsize;
sh.bittable_size = (sh.arena_size / sh.minsize) * 2;
/* Prevent allocations of size 0 later on */
if (sh.bittable_size >> 3 == 0)
goto err;
sh.freelist_size = -1;
for (i = sh.bittable_size; i; i >>= 1)
sh.freelist_size++;
sh.freelist = OPENSSL_zalloc(sh.freelist_size * sizeof(char *));
OPENSSL_assert(sh.freelist != NULL);
if (sh.freelist == NULL)
goto err;
sh.bittable = OPENSSL_zalloc(sh.bittable_size >> 3);
OPENSSL_assert(sh.bittable != NULL);
if (sh.bittable == NULL)
goto err;
sh.bitmalloc = OPENSSL_zalloc(sh.bittable_size >> 3);
OPENSSL_assert(sh.bitmalloc != NULL);
if (sh.bitmalloc == NULL)
goto err;
/* Allocate space for heap, and two extra pages as guards */
#if defined(_SC_PAGE_SIZE) || defined (_SC_PAGESIZE)
{
# if defined(_SC_PAGE_SIZE)
long tmppgsize = sysconf(_SC_PAGE_SIZE);
# else
long tmppgsize = sysconf(_SC_PAGESIZE);
# endif
if (tmppgsize < 1)
pgsize = PAGE_SIZE;
else
pgsize = (size_t)tmppgsize;
}
#elif defined(_WIN32)
GetSystemInfo(&systemInfo);
pgsize = (size_t)systemInfo.dwPageSize;
#else
pgsize = PAGE_SIZE;
#endif
sh.map_size = pgsize + sh.arena_size + pgsize;
#if !defined(_WIN32)
# ifdef MAP_ANON
sh.map_result = mmap(NULL, sh.map_size,
PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE|MAP_CONCEAL, -1, 0);
# else
{
int fd;
sh.map_result = MAP_FAILED;
if ((fd = open("/dev/zero", O_RDWR)) >= 0) {
sh.map_result = mmap(NULL, sh.map_size,
PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
close(fd);
}
}
# endif
if (sh.map_result == MAP_FAILED)
goto err;
#else
sh.map_result = VirtualAlloc(NULL, sh.map_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (sh.map_result == NULL)
goto err;
#endif
sh.arena = (char *)(sh.map_result + pgsize);
sh_setbit(sh.arena, 0, sh.bittable);
sh_add_to_list(&sh.freelist[0], sh.arena);
/* Now try to add guard pages and lock into memory. */
ret = 1;
#if !defined(_WIN32)
/* Starting guard is already aligned from mmap. */
if (mprotect(sh.map_result, pgsize, PROT_NONE) < 0)
ret = 2;
#else
if (VirtualProtect(sh.map_result, pgsize, PAGE_NOACCESS, &flOldProtect) == FALSE)
ret = 2;
#endif
/* Ending guard page - need to round up to page boundary */
aligned = (pgsize + sh.arena_size + (pgsize - 1)) & ~(pgsize - 1);
#if !defined(_WIN32)
if (mprotect(sh.map_result + aligned, pgsize, PROT_NONE) < 0)
ret = 2;
#else
if (VirtualProtect(sh.map_result + aligned, pgsize, PAGE_NOACCESS, &flOldProtect) == FALSE)
ret = 2;
#endif
#if defined(OPENSSL_SYS_LINUX) && defined(MLOCK_ONFAULT) && defined(SYS_mlock2)
if (syscall(SYS_mlock2, sh.arena, sh.arena_size, MLOCK_ONFAULT) < 0) {
if (errno == ENOSYS) {
if (mlock(sh.arena, sh.arena_size) < 0)
ret = 2;
} else {
ret = 2;
}
}
#elif defined(_WIN32)
if (VirtualLock(sh.arena, sh.arena_size) == FALSE)
ret = 2;
#else
if (mlock(sh.arena, sh.arena_size) < 0)
ret = 2;
#endif
#ifndef NO_MADVISE
if (madvise(sh.arena, sh.arena_size, MADV_DONTDUMP) < 0)
ret = 2;
#endif
return ret;
err:
sh_done();
return 0;
}
static void sh_done(void)
{
OPENSSL_free(sh.freelist);
OPENSSL_free(sh.bittable);
OPENSSL_free(sh.bitmalloc);
#if !defined(_WIN32)
if (sh.map_result != MAP_FAILED && sh.map_size)
munmap(sh.map_result, sh.map_size);
#else
if (sh.map_result != NULL && sh.map_size)
VirtualFree(sh.map_result, 0, MEM_RELEASE);
#endif
memset(&sh, 0, sizeof(sh));
}
static int sh_allocated(const char *ptr)
{
return WITHIN_ARENA(ptr) ? 1 : 0;
}
static char *sh_find_my_buddy(char *ptr, int list)
{
size_t bit;
char *chunk = NULL;
bit = (ONE << list) + (ptr - sh.arena) / (sh.arena_size >> list);
bit ^= 1;
if (TESTBIT(sh.bittable, bit) && !TESTBIT(sh.bitmalloc, bit))
chunk = sh.arena + ((bit & ((ONE << list) - 1)) * (sh.arena_size >> list));
return chunk;
}
static void *sh_malloc(size_t size)
{
ossl_ssize_t list, slist;
size_t i;
char *chunk;
if (size > sh.arena_size)
return NULL;
list = sh.freelist_size - 1;
for (i = sh.minsize; i < size; i <<= 1)
list--;
if (list < 0)
return NULL;
/* try to find a larger entry to split */
for (slist = list; slist >= 0; slist--)
if (sh.freelist[slist] != NULL)
break;
if (slist < 0)
return NULL;
/* split larger entry */
while (slist != list) {
char *temp = sh.freelist[slist];
/* remove from bigger list */
OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
sh_clearbit(temp, slist, sh.bittable);
sh_remove_from_list(temp);
OPENSSL_assert(temp != sh.freelist[slist]);
/* done with bigger list */
slist++;
/* add to smaller list */
OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
sh_setbit(temp, slist, sh.bittable);
sh_add_to_list(&sh.freelist[slist], temp);
OPENSSL_assert(sh.freelist[slist] == temp);
/* split in 2 */
temp += sh.arena_size >> slist;
OPENSSL_assert(!sh_testbit(temp, slist, sh.bitmalloc));
sh_setbit(temp, slist, sh.bittable);
sh_add_to_list(&sh.freelist[slist], temp);
OPENSSL_assert(sh.freelist[slist] == temp);
OPENSSL_assert(temp-(sh.arena_size >> slist) == sh_find_my_buddy(temp, slist));
}
/* peel off memory to hand back */
chunk = sh.freelist[list];
OPENSSL_assert(sh_testbit(chunk, list, sh.bittable));
sh_setbit(chunk, list, sh.bitmalloc);
sh_remove_from_list(chunk);
OPENSSL_assert(WITHIN_ARENA(chunk));
/* zero the free list header as a precaution against information leakage */
memset(chunk, 0, sizeof(SH_LIST));
return chunk;
}
static void sh_free(void *ptr)
{
size_t list;
void *buddy;
if (ptr == NULL)
return;
OPENSSL_assert(WITHIN_ARENA(ptr));
if (!WITHIN_ARENA(ptr))
return;
list = sh_getlist(ptr);
OPENSSL_assert(sh_testbit(ptr, list, sh.bittable));
sh_clearbit(ptr, list, sh.bitmalloc);
sh_add_to_list(&sh.freelist[list], ptr);
/* Try to coalesce two adjacent free areas. */
while ((buddy = sh_find_my_buddy(ptr, list)) != NULL) {
OPENSSL_assert(ptr == sh_find_my_buddy(buddy, list));
OPENSSL_assert(ptr != NULL);
OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
sh_clearbit(ptr, list, sh.bittable);
sh_remove_from_list(ptr);
OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
sh_clearbit(buddy, list, sh.bittable);
sh_remove_from_list(buddy);
list--;
/* Zero the higher addressed block's free list pointers */
memset(ptr > buddy ? ptr : buddy, 0, sizeof(SH_LIST));
if (ptr > buddy)
ptr = buddy;
OPENSSL_assert(!sh_testbit(ptr, list, sh.bitmalloc));
sh_setbit(ptr, list, sh.bittable);
sh_add_to_list(&sh.freelist[list], ptr);
OPENSSL_assert(sh.freelist[list] == ptr);
}
}
static size_t sh_actual_size(char *ptr)
{
int list;
OPENSSL_assert(WITHIN_ARENA(ptr));
if (!WITHIN_ARENA(ptr))
return 0;
list = sh_getlist(ptr);
OPENSSL_assert(sh_testbit(ptr, list, sh.bittable));
return sh.arena_size / (ONE << list);
}
#endif /* OPENSSL_NO_SECURE_MEMORY */
| 19,956 | 25.752011 | 95 | c |
openssl | openssl-master/crypto/mips_arch.h | /*
* Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_CRYPTO_MIPS_ARCH_H
# define OSSL_CRYPTO_MIPS_ARCH_H
# if (defined(__mips_smartmips) || defined(_MIPS_ARCH_MIPS32R3) || \
defined(_MIPS_ARCH_MIPS32R5) || defined(_MIPS_ARCH_MIPS32R6)) \
&& !defined(_MIPS_ARCH_MIPS32R2)
# define _MIPS_ARCH_MIPS32R2
# endif
# if (defined(_MIPS_ARCH_MIPS64R3) || defined(_MIPS_ARCH_MIPS64R5) || \
defined(_MIPS_ARCH_MIPS64R6)) \
&& !defined(_MIPS_ARCH_MIPS64R2)
# define _MIPS_ARCH_MIPS64R2
# endif
# if defined(_MIPS_ARCH_MIPS64R6)
# define dmultu(rs,rt)
# define mflo(rd,rs,rt) dmulu rd,rs,rt
# define mfhi(rd,rs,rt) dmuhu rd,rs,rt
# elif defined(_MIPS_ARCH_MIPS32R6)
# define multu(rs,rt)
# define mflo(rd,rs,rt) mulu rd,rs,rt
# define mfhi(rd,rs,rt) muhu rd,rs,rt
# else
# define dmultu(rs,rt) dmultu rs,rt
# define multu(rs,rt) multu rs,rt
# define mflo(rd,rs,rt) mflo rd
# define mfhi(rd,rs,rt) mfhi rd
# endif
#endif
| 1,246 | 29.414634 | 74 | h |
openssl | openssl-master/crypto/o_dir.c | /*
* Copyright 2004-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 <errno.h>
/*
* The routines really come from the Levitte Programming, so to make life
* simple, let's just use the raw files and hack the symbols to fit our
* namespace.
*/
#define LP_DIR_CTX OPENSSL_DIR_CTX
#define LP_dir_context_st OPENSSL_dir_context_st
#define LP_find_file OPENSSL_DIR_read
#define LP_find_file_end OPENSSL_DIR_end
#include "internal/o_dir.h"
#define LPDIR_H
#if defined OPENSSL_SYS_UNIX || defined DJGPP \
|| (defined __VMS_VER && __VMS_VER >= 70000000)
# include "LPdir_unix.c"
#elif defined OPENSSL_SYS_VMS
# include "LPdir_vms.c"
#elif defined OPENSSL_SYS_WIN32
# include "LPdir_win32.c"
#elif defined OPENSSL_SYS_WINCE
# include "LPdir_wince.c"
#else
# include "LPdir_nyi.c"
#endif
| 1,092 | 27.763158 | 74 | c |
openssl | openssl-master/crypto/o_fopen.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
*/
# if defined(__linux) || defined(__sun) || defined(__hpux)
/*
* Following definition aliases fopen to fopen64 on above mentioned
* platforms. This makes it possible to open and sequentially access files
* larger than 2GB from 32-bit application. It does not allow one to traverse
* them beyond 2GB with fseek/ftell, but on the other hand *no* 32-bit
* platform permits that, not with fseek/ftell. Not to mention that breaking
* 2GB limit for seeking would require surgery to *our* API. But sequential
* access suffices for practical cases when you can run into large files,
* such as fingerprinting, so we can let API alone. For reference, the list
* of 32-bit platforms which allow for sequential access of large files
* without extra "magic" comprise *BSD, Darwin, IRIX...
*/
# ifndef _FILE_OFFSET_BITS
# define _FILE_OFFSET_BITS 64
# endif
# endif
#include "internal/e_os.h"
#include "internal/cryptlib.h"
#if !defined(OPENSSL_NO_STDIO)
# include <stdio.h>
# ifdef __DJGPP__
# include <unistd.h>
# endif
FILE *openssl_fopen(const char *filename, const char *mode)
{
FILE *file = NULL;
# if defined(_WIN32) && defined(CP_UTF8)
int sz, len_0 = (int)strlen(filename) + 1;
DWORD flags;
/*
* Basically there are three cases to cover: a) filename is
* pure ASCII string; b) actual UTF-8 encoded string and
* c) locale-ized string, i.e. one containing 8-bit
* characters that are meaningful in current system locale.
* If filename is pure ASCII or real UTF-8 encoded string,
* MultiByteToWideChar succeeds and _wfopen works. If
* filename is locale-ized string, chances are that
* MultiByteToWideChar fails reporting
* ERROR_NO_UNICODE_TRANSLATION, in which case we fall
* back to fopen...
*/
if ((sz = MultiByteToWideChar(CP_UTF8, (flags = MB_ERR_INVALID_CHARS),
filename, len_0, NULL, 0)) > 0 ||
(GetLastError() == ERROR_INVALID_FLAGS &&
(sz = MultiByteToWideChar(CP_UTF8, (flags = 0),
filename, len_0, NULL, 0)) > 0)
) {
WCHAR wmode[8];
WCHAR *wfilename = _alloca(sz * sizeof(WCHAR));
if (MultiByteToWideChar(CP_UTF8, flags,
filename, len_0, wfilename, sz) &&
MultiByteToWideChar(CP_UTF8, 0, mode, strlen(mode) + 1,
wmode, OSSL_NELEM(wmode)) &&
(file = _wfopen(wfilename, wmode)) == NULL &&
(errno == ENOENT || errno == EBADF)
) {
/*
* UTF-8 decode succeeded, but no file, filename
* could still have been locale-ized...
*/
file = fopen(filename, mode);
}
} else if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION) {
file = fopen(filename, mode);
}
# elif defined(__DJGPP__)
{
char *newname = NULL;
if (pathconf(filename, _PC_NAME_MAX) <= 12) { /* 8.3 file system? */
char *iterator;
char lastchar;
if ((newname = OPENSSL_malloc(strlen(filename) + 1)) == NULL)
return NULL;
for (iterator = newname, lastchar = '\0';
*filename; filename++, iterator++) {
if (lastchar == '/' && filename[0] == '.'
&& filename[1] != '.' && filename[1] != '/') {
/* Leading dots are not permitted in plain DOS. */
*iterator = '_';
} else {
*iterator = *filename;
}
lastchar = *filename;
}
*iterator = '\0';
filename = newname;
}
file = fopen(filename, mode);
OPENSSL_free(newname);
}
# else
file = fopen(filename, mode);
# endif
return file;
}
#else
void *openssl_fopen(const char *filename, const char *mode)
{
return NULL;
}
#endif
| 4,291 | 33.336 | 77 | c |
openssl | openssl-master/crypto/o_init.c | /*
* Copyright 2011-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 <openssl/err.h>
/*
* Perform any essential OpenSSL initialization operations. Currently does
* nothing.
*/
void OPENSSL_init(void)
{
return;
}
| 525 | 22.909091 | 74 | c |
openssl | openssl-master/crypto/o_str.c | /*
* Copyright 2003-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 <string.h>
#include <limits.h>
#include <openssl/crypto.h>
#include "crypto/ctype.h"
#include "internal/cryptlib.h"
#include "internal/thread_once.h"
#define DEFAULT_SEPARATOR ':'
#define CH_ZERO '\0'
char *CRYPTO_strdup(const char *str, const char* file, int line)
{
char *ret;
if (str == NULL)
return NULL;
ret = CRYPTO_malloc(strlen(str) + 1, file, line);
if (ret != NULL)
strcpy(ret, str);
return ret;
}
char *CRYPTO_strndup(const char *str, size_t s, const char* file, int line)
{
size_t maxlen;
char *ret;
if (str == NULL)
return NULL;
maxlen = OPENSSL_strnlen(str, s);
ret = CRYPTO_malloc(maxlen + 1, file, line);
if (ret) {
memcpy(ret, str, maxlen);
ret[maxlen] = CH_ZERO;
}
return ret;
}
void *CRYPTO_memdup(const void *data, size_t siz, const char* file, int line)
{
void *ret;
if (data == NULL || siz >= INT_MAX)
return NULL;
ret = CRYPTO_malloc(siz, file, line);
if (ret == NULL)
return NULL;
return memcpy(ret, data, siz);
}
size_t OPENSSL_strnlen(const char *str, size_t maxlen)
{
const char *p;
for (p = str; maxlen-- != 0 && *p != CH_ZERO; ++p) ;
return p - str;
}
size_t OPENSSL_strlcpy(char *dst, const char *src, size_t size)
{
size_t l = 0;
for (; size > 1 && *src; size--) {
*dst++ = *src++;
l++;
}
if (size)
*dst = CH_ZERO;
return l + strlen(src);
}
size_t OPENSSL_strlcat(char *dst, const char *src, size_t size)
{
size_t l = 0;
for (; size > 0 && *dst; size--, dst++)
l++;
return l + OPENSSL_strlcpy(dst, src, size);
}
int OPENSSL_hexchar2int(unsigned char c)
{
#ifdef CHARSET_EBCDIC
c = os_toebcdic[c];
#endif
switch (c) {
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'a': case 'A':
return 0x0A;
case 'b': case 'B':
return 0x0B;
case 'c': case 'C':
return 0x0C;
case 'd': case 'D':
return 0x0D;
case 'e': case 'E':
return 0x0E;
case 'f': case 'F':
return 0x0F;
}
return -1;
}
static int hexstr2buf_sep(unsigned char *buf, size_t buf_n, size_t *buflen,
const char *str, const char sep)
{
unsigned char *q;
unsigned char ch, cl;
int chi, cli;
const unsigned char *p;
size_t cnt;
for (p = (const unsigned char *)str, q = buf, cnt = 0; *p; ) {
ch = *p++;
/* A separator of CH_ZERO means there is no separator */
if (ch == sep && sep != CH_ZERO)
continue;
cl = *p++;
if (!cl) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_ODD_NUMBER_OF_DIGITS);
return 0;
}
cli = OPENSSL_hexchar2int(cl);
chi = OPENSSL_hexchar2int(ch);
if (cli < 0 || chi < 0) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_ILLEGAL_HEX_DIGIT);
return 0;
}
cnt++;
if (q != NULL) {
if (cnt > buf_n) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_SMALL_BUFFER);
return 0;
}
*q++ = (unsigned char)((chi << 4) | cli);
}
}
if (buflen != NULL)
*buflen = cnt;
return 1;
}
/*
* Given a string of hex digits convert to a buffer
*/
int OPENSSL_hexstr2buf_ex(unsigned char *buf, size_t buf_n, size_t *buflen,
const char *str, const char sep)
{
return hexstr2buf_sep(buf, buf_n, buflen, str, sep);
}
unsigned char *ossl_hexstr2buf_sep(const char *str, long *buflen,
const char sep)
{
unsigned char *buf;
size_t buf_n, tmp_buflen;
buf_n = strlen(str);
if (buf_n <= 1) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_HEX_STRING_TOO_SHORT);
return NULL;
}
buf_n /= 2;
if ((buf = OPENSSL_malloc(buf_n)) == NULL)
return NULL;
if (buflen != NULL)
*buflen = 0;
tmp_buflen = 0;
if (hexstr2buf_sep(buf, buf_n, &tmp_buflen, str, sep)) {
if (buflen != NULL)
*buflen = (long)tmp_buflen;
return buf;
}
OPENSSL_free(buf);
return NULL;
}
unsigned char *OPENSSL_hexstr2buf(const char *str, long *buflen)
{
return ossl_hexstr2buf_sep(str, buflen, DEFAULT_SEPARATOR);
}
static int buf2hexstr_sep(char *str, size_t str_n, size_t *strlength,
const unsigned char *buf, size_t buflen,
const char sep)
{
static const char hexdig[] = "0123456789ABCDEF";
const unsigned char *p;
char *q;
size_t i;
int has_sep = (sep != CH_ZERO);
size_t len = has_sep ? buflen * 3 : 1 + buflen * 2;
if (strlength != NULL)
*strlength = len;
if (str == NULL)
return 1;
if (str_n < (unsigned long)len) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_SMALL_BUFFER);
return 0;
}
q = str;
for (i = 0, p = buf; i < buflen; i++, p++) {
*q++ = hexdig[(*p >> 4) & 0xf];
*q++ = hexdig[*p & 0xf];
if (has_sep)
*q++ = sep;
}
if (has_sep)
--q;
*q = CH_ZERO;
#ifdef CHARSET_EBCDIC
ebcdic2ascii(str, str, q - str - 1);
#endif
return 1;
}
int OPENSSL_buf2hexstr_ex(char *str, size_t str_n, size_t *strlength,
const unsigned char *buf, size_t buflen,
const char sep)
{
return buf2hexstr_sep(str, str_n, strlength, buf, buflen, sep);
}
char *ossl_buf2hexstr_sep(const unsigned char *buf, long buflen, char sep)
{
char *tmp;
size_t tmp_n;
if (buflen == 0)
return OPENSSL_zalloc(1);
tmp_n = (sep != CH_ZERO) ? buflen * 3 : 1 + buflen * 2;
if ((tmp = OPENSSL_malloc(tmp_n)) == NULL)
return NULL;
if (buf2hexstr_sep(tmp, tmp_n, NULL, buf, buflen, sep))
return tmp;
OPENSSL_free(tmp);
return NULL;
}
/*
* Given a buffer of length 'len' return a OPENSSL_malloc'ed string with its
* hex representation @@@ (Contents of buffer are always kept in ASCII, also
* on EBCDIC machines)
*/
char *OPENSSL_buf2hexstr(const unsigned char *buf, long buflen)
{
return ossl_buf2hexstr_sep(buf, buflen, ':');
}
int openssl_strerror_r(int errnum, char *buf, size_t buflen)
{
#if defined(_MSC_VER) && _MSC_VER>=1400 && !defined(_WIN32_WCE)
return !strerror_s(buf, buflen, errnum);
#elif defined(_GNU_SOURCE)
char *err;
/*
* GNU strerror_r may not actually set buf.
* It can return a pointer to some (immutable) static string in which case
* buf is left unused.
*/
err = strerror_r(errnum, buf, buflen);
if (err == NULL || buflen == 0)
return 0;
/*
* If err is statically allocated, err != buf and we need to copy the data.
* If err points somewhere inside buf, OPENSSL_strlcpy can handle this,
* since src and dest are not annotated with __restrict and the function
* reads src byte for byte and writes to dest.
* If err == buf we do not have to copy anything.
*/
if (err != buf)
OPENSSL_strlcpy(buf, err, buflen);
return 1;
#elif (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) || \
(defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
/*
* We can use "real" strerror_r. The OpenSSL version differs in that it
* gives 1 on success and 0 on failure for consistency with other OpenSSL
* functions. Real strerror_r does it the other way around
*/
return !strerror_r(errnum, buf, buflen);
#else
char *err;
/* Fall back to non-thread safe strerror()...its all we can do */
if (buflen < 2)
return 0;
err = strerror(errnum);
/* Can this ever happen? */
if (err == NULL)
return 0;
OPENSSL_strlcpy(buf, err, buflen);
return 1;
#endif
}
int OPENSSL_strcasecmp(const char *s1, const char *s2)
{
int t;
while ((t = ossl_tolower(*s1) - ossl_tolower(*s2++)) == 0)
if (*s1++ == '\0')
return 0;
return t;
}
int OPENSSL_strncasecmp(const char *s1, const char *s2, size_t n)
{
int t;
size_t i;
for (i = 0; i < n; i++)
if ((t = ossl_tolower(*s1) - ossl_tolower(*s2++)) != 0)
return t;
else if (*s1++ == '\0')
return 0;
return 0;
}
| 8,945 | 23.781163 | 79 | c |
openssl | openssl-master/crypto/o_time.c | /*
* Copyright 2001-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/e_os2.h>
#include <string.h>
#include <openssl/crypto.h>
struct tm *OPENSSL_gmtime(const time_t *timer, struct tm *result)
{
struct tm *ts = NULL;
#if defined(OPENSSL_THREADS) && defined(OPENSSL_SYS_VMS)
{
/*
* On VMS, gmtime_r() takes a 32-bit pointer as second argument.
* Since we can't know that |result| is in a space that can easily
* translate to a 32-bit pointer, we must store temporarily on stack
* and copy the result. The stack is always reachable with 32-bit
* pointers.
*/
#if defined(OPENSSL_SYS_VMS) && __INITIAL_POINTER_SIZE
# pragma pointer_size save
# pragma pointer_size 32
#endif
struct tm data, *ts2 = &data;
#if defined OPENSSL_SYS_VMS && __INITIAL_POINTER_SIZE
# pragma pointer_size restore
#endif
if (gmtime_r(timer, ts2) == NULL)
return NULL;
memcpy(result, ts2, sizeof(struct tm));
ts = result;
}
#elif defined(OPENSSL_THREADS) && !defined(OPENSSL_SYS_WIN32) && !defined(OPENSSL_SYS_MACOSX)
if (gmtime_r(timer, result) == NULL)
return NULL;
ts = result;
#elif defined (OPENSSL_SYS_WINDOWS) && defined(_MSC_VER) && _MSC_VER >= 1400 && !defined(_WIN32_WCE)
if (gmtime_s(result, timer))
return NULL;
ts = result;
#else
ts = gmtime(timer);
if (ts == NULL)
return NULL;
memcpy(result, ts, sizeof(struct tm));
ts = result;
#endif
return ts;
}
/*
* Take a tm structure and add an offset to it. This avoids any OS issues
* with restricted date types and overflows which cause the year 2038
* problem.
*/
#define SECS_PER_DAY (24 * 60 * 60)
static long date_to_julian(int y, int m, int d);
static void julian_to_date(long jd, int *y, int *m, int *d);
static int julian_adj(const struct tm *tm, int off_day, long offset_sec,
long *pday, int *psec);
int OPENSSL_gmtime_adj(struct tm *tm, int off_day, long offset_sec)
{
int time_sec, time_year, time_month, time_day;
long time_jd;
/* Convert time and offset into Julian day and seconds */
if (!julian_adj(tm, off_day, offset_sec, &time_jd, &time_sec))
return 0;
/* Convert Julian day back to date */
julian_to_date(time_jd, &time_year, &time_month, &time_day);
if (time_year < 1900 || time_year > 9999)
return 0;
/* Update tm structure */
tm->tm_year = time_year - 1900;
tm->tm_mon = time_month - 1;
tm->tm_mday = time_day;
tm->tm_hour = time_sec / 3600;
tm->tm_min = (time_sec / 60) % 60;
tm->tm_sec = time_sec % 60;
return 1;
}
int OPENSSL_gmtime_diff(int *pday, int *psec,
const struct tm *from, const struct tm *to)
{
int from_sec, to_sec, diff_sec;
long from_jd, to_jd, diff_day;
if (!julian_adj(from, 0, 0, &from_jd, &from_sec))
return 0;
if (!julian_adj(to, 0, 0, &to_jd, &to_sec))
return 0;
diff_day = to_jd - from_jd;
diff_sec = to_sec - from_sec;
/* Adjust differences so both positive or both negative */
if (diff_day > 0 && diff_sec < 0) {
diff_day--;
diff_sec += SECS_PER_DAY;
}
if (diff_day < 0 && diff_sec > 0) {
diff_day++;
diff_sec -= SECS_PER_DAY;
}
if (pday)
*pday = (int)diff_day;
if (psec)
*psec = diff_sec;
return 1;
}
/* Convert tm structure and offset into julian day and seconds */
static int julian_adj(const struct tm *tm, int off_day, long offset_sec,
long *pday, int *psec)
{
int offset_hms;
long offset_day, time_jd;
int time_year, time_month, time_day;
/* split offset into days and day seconds */
offset_day = offset_sec / SECS_PER_DAY;
/* Avoid sign issues with % operator */
offset_hms = offset_sec - (offset_day * SECS_PER_DAY);
offset_day += off_day;
/* Add current time seconds to offset */
offset_hms += tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
/* Adjust day seconds if overflow */
if (offset_hms >= SECS_PER_DAY) {
offset_day++;
offset_hms -= SECS_PER_DAY;
} else if (offset_hms < 0) {
offset_day--;
offset_hms += SECS_PER_DAY;
}
/*
* Convert date of time structure into a Julian day number.
*/
time_year = tm->tm_year + 1900;
time_month = tm->tm_mon + 1;
time_day = tm->tm_mday;
time_jd = date_to_julian(time_year, time_month, time_day);
/* Work out Julian day of new date */
time_jd += offset_day;
if (time_jd < 0)
return 0;
*pday = time_jd;
*psec = offset_hms;
return 1;
}
/*
* Convert date to and from julian day Uses Fliegel & Van Flandern algorithm
*/
static long date_to_julian(int y, int m, int d)
{
return (1461 * (y + 4800 + (m - 14) / 12)) / 4 +
(367 * (m - 2 - 12 * ((m - 14) / 12))) / 12 -
(3 * ((y + 4900 + (m - 14) / 12) / 100)) / 4 + d - 32075;
}
static void julian_to_date(long jd, int *y, int *m, int *d)
{
long L = jd + 68569;
long n = (4 * L) / 146097;
long i, j;
L = L - (146097 * n + 3) / 4;
i = (4000 * (L + 1)) / 1461001;
L = L - (1461 * i) / 4 + 31;
j = (80 * L) / 2447;
*d = L - (2447 * j) / 80;
L = j / 11;
*m = j + 2 - (12 * L);
*y = 100 * (n - 49) + i + L;
}
| 5,651 | 27.119403 | 100 | c |
openssl | openssl-master/crypto/packet.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 "internal/cryptlib.h"
#include "internal/packet.h"
#if !defined OPENSSL_NO_QUIC && !defined FIPS_MODULE
# include "internal/packet_quic.h"
#endif
#include <openssl/err.h>
#define DEFAULT_BUF_SIZE 256
int WPACKET_allocate_bytes(WPACKET *pkt, size_t len, unsigned char **allocbytes)
{
if (!WPACKET_reserve_bytes(pkt, len, allocbytes))
return 0;
pkt->written += len;
pkt->curr += len;
return 1;
}
int WPACKET_sub_allocate_bytes__(WPACKET *pkt, size_t len,
unsigned char **allocbytes, size_t lenbytes)
{
if (!WPACKET_start_sub_packet_len__(pkt, lenbytes)
|| !WPACKET_allocate_bytes(pkt, len, allocbytes)
|| !WPACKET_close(pkt))
return 0;
return 1;
}
#define GETBUF(p) (((p)->staticbuf != NULL) \
? (p)->staticbuf \
: ((p)->buf != NULL \
? (unsigned char *)(p)->buf->data \
: NULL))
int WPACKET_reserve_bytes(WPACKET *pkt, size_t len, unsigned char **allocbytes)
{
/* Internal API, so should not fail */
if (!ossl_assert(pkt->subs != NULL && len != 0))
return 0;
if (pkt->maxsize - pkt->written < len)
return 0;
if (pkt->buf != NULL && (pkt->buf->length - pkt->written < len)) {
size_t newlen;
size_t reflen;
reflen = (len > pkt->buf->length) ? len : pkt->buf->length;
if (reflen > SIZE_MAX / 2) {
newlen = SIZE_MAX;
} else {
newlen = reflen * 2;
if (newlen < DEFAULT_BUF_SIZE)
newlen = DEFAULT_BUF_SIZE;
}
if (BUF_MEM_grow(pkt->buf, newlen) == 0)
return 0;
}
if (allocbytes != NULL) {
*allocbytes = WPACKET_get_curr(pkt);
if (pkt->endfirst && *allocbytes != NULL)
*allocbytes -= len;
}
return 1;
}
int WPACKET_sub_reserve_bytes__(WPACKET *pkt, size_t len,
unsigned char **allocbytes, size_t lenbytes)
{
if (pkt->endfirst && lenbytes > 0)
return 0;
if (!WPACKET_reserve_bytes(pkt, lenbytes + len, allocbytes))
return 0;
if (*allocbytes != NULL)
*allocbytes += lenbytes;
return 1;
}
static size_t maxmaxsize(size_t lenbytes)
{
if (lenbytes >= sizeof(size_t) || lenbytes == 0)
return SIZE_MAX;
return ((size_t)1 << (lenbytes * 8)) - 1 + lenbytes;
}
static int wpacket_intern_init_len(WPACKET *pkt, size_t lenbytes)
{
unsigned char *lenchars;
pkt->curr = 0;
pkt->written = 0;
if ((pkt->subs = OPENSSL_zalloc(sizeof(*pkt->subs))) == NULL)
return 0;
if (lenbytes == 0)
return 1;
pkt->subs->pwritten = lenbytes;
pkt->subs->lenbytes = lenbytes;
if (!WPACKET_allocate_bytes(pkt, lenbytes, &lenchars)) {
OPENSSL_free(pkt->subs);
pkt->subs = NULL;
return 0;
}
pkt->subs->packet_len = 0;
return 1;
}
int WPACKET_init_static_len(WPACKET *pkt, unsigned char *buf, size_t len,
size_t lenbytes)
{
size_t max = maxmaxsize(lenbytes);
/* Internal API, so should not fail */
if (!ossl_assert(buf != NULL && len > 0))
return 0;
pkt->staticbuf = buf;
pkt->buf = NULL;
pkt->maxsize = (max < len) ? max : len;
pkt->endfirst = 0;
return wpacket_intern_init_len(pkt, lenbytes);
}
int WPACKET_init_der(WPACKET *pkt, unsigned char *buf, size_t len)
{
/* Internal API, so should not fail */
if (!ossl_assert(buf != NULL && len > 0))
return 0;
pkt->staticbuf = buf;
pkt->buf = NULL;
pkt->maxsize = len;
pkt->endfirst = 1;
return wpacket_intern_init_len(pkt, 0);
}
int WPACKET_init_len(WPACKET *pkt, BUF_MEM *buf, size_t lenbytes)
{
/* Internal API, so should not fail */
if (!ossl_assert(buf != NULL))
return 0;
pkt->staticbuf = NULL;
pkt->buf = buf;
pkt->maxsize = maxmaxsize(lenbytes);
pkt->endfirst = 0;
return wpacket_intern_init_len(pkt, lenbytes);
}
int WPACKET_init(WPACKET *pkt, BUF_MEM *buf)
{
return WPACKET_init_len(pkt, buf, 0);
}
int WPACKET_init_null(WPACKET *pkt, size_t lenbytes)
{
pkt->staticbuf = NULL;
pkt->buf = NULL;
pkt->maxsize = maxmaxsize(lenbytes);
pkt->endfirst = 0;
return wpacket_intern_init_len(pkt, 0);
}
int WPACKET_init_null_der(WPACKET *pkt)
{
pkt->staticbuf = NULL;
pkt->buf = NULL;
pkt->maxsize = SIZE_MAX;
pkt->endfirst = 1;
return wpacket_intern_init_len(pkt, 0);
}
int WPACKET_set_flags(WPACKET *pkt, unsigned int flags)
{
/* Internal API, so should not fail */
if (!ossl_assert(pkt->subs != NULL))
return 0;
pkt->subs->flags = flags;
return 1;
}
/* Store the |value| of length |len| at location |data| */
static int put_value(unsigned char *data, uint64_t value, size_t len)
{
if (data == NULL)
return 1;
for (data += len - 1; len > 0; len--) {
*data = (unsigned char)(value & 0xff);
data--;
value >>= 8;
}
/* Check whether we could fit the value in the assigned number of bytes */
if (value > 0)
return 0;
return 1;
}
#if !defined OPENSSL_NO_QUIC && !defined FIPS_MODULE
static int put_quic_value(unsigned char *data, size_t value, size_t len)
{
if (data == NULL)
return 1;
/* Value too large for field. */
if (ossl_quic_vlint_encode_len(value) > len)
return 0;
ossl_quic_vlint_encode_n(data, value, len);
return 1;
}
#endif
/*
* Internal helper function used by WPACKET_close(), WPACKET_finish() and
* WPACKET_fill_lengths() to close a sub-packet and write out its length if
* necessary. If |doclose| is 0 then it goes through the motions of closing
* (i.e. it fills in all the lengths), but doesn't actually close anything.
*/
static int wpacket_intern_close(WPACKET *pkt, WPACKET_SUB *sub, int doclose)
{
size_t packlen = pkt->written - sub->pwritten;
if (packlen == 0
&& (sub->flags & WPACKET_FLAGS_NON_ZERO_LENGTH) != 0)
return 0;
if (packlen == 0
&& sub->flags & WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH) {
/* We can't handle this case. Return an error */
if (!doclose)
return 0;
/* Deallocate any bytes allocated for the length of the WPACKET */
if ((pkt->curr - sub->lenbytes) == sub->packet_len) {
pkt->written -= sub->lenbytes;
pkt->curr -= sub->lenbytes;
}
/* Don't write out the packet length */
sub->packet_len = 0;
sub->lenbytes = 0;
}
/* Write out the WPACKET length if needed */
if (sub->lenbytes > 0) {
unsigned char *buf = GETBUF(pkt);
if (buf != NULL) {
#if !defined OPENSSL_NO_QUIC && !defined FIPS_MODULE
if ((sub->flags & WPACKET_FLAGS_QUIC_VLINT) == 0) {
if (!put_value(&buf[sub->packet_len], packlen, sub->lenbytes))
return 0;
} else {
if (!put_quic_value(&buf[sub->packet_len], packlen, sub->lenbytes))
return 0;
}
#else
if (!put_value(&buf[sub->packet_len], packlen, sub->lenbytes))
return 0;
#endif
}
} else if (pkt->endfirst && sub->parent != NULL
&& (packlen != 0
|| (sub->flags
& WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH) == 0)) {
size_t tmplen = packlen;
size_t numlenbytes = 1;
while ((tmplen = tmplen >> 8) > 0)
numlenbytes++;
if (!WPACKET_put_bytes__(pkt, packlen, numlenbytes))
return 0;
if (packlen > 0x7f) {
numlenbytes |= 0x80;
if (!WPACKET_put_bytes_u8(pkt, numlenbytes))
return 0;
}
}
if (doclose) {
pkt->subs = sub->parent;
OPENSSL_free(sub);
}
return 1;
}
int WPACKET_fill_lengths(WPACKET *pkt)
{
WPACKET_SUB *sub;
if (!ossl_assert(pkt->subs != NULL))
return 0;
for (sub = pkt->subs; sub != NULL; sub = sub->parent) {
if (!wpacket_intern_close(pkt, sub, 0))
return 0;
}
return 1;
}
int WPACKET_close(WPACKET *pkt)
{
/*
* Internal API, so should not fail - but we do negative testing of this
* so no assert (otherwise the tests fail)
*/
if (pkt->subs == NULL || pkt->subs->parent == NULL)
return 0;
return wpacket_intern_close(pkt, pkt->subs, 1);
}
int WPACKET_finish(WPACKET *pkt)
{
int ret;
/*
* Internal API, so should not fail - but we do negative testing of this
* so no assert (otherwise the tests fail)
*/
if (pkt->subs == NULL || pkt->subs->parent != NULL)
return 0;
ret = wpacket_intern_close(pkt, pkt->subs, 1);
if (ret) {
OPENSSL_free(pkt->subs);
pkt->subs = NULL;
}
return ret;
}
int WPACKET_start_sub_packet_len__(WPACKET *pkt, size_t lenbytes)
{
WPACKET_SUB *sub;
unsigned char *lenchars;
/* Internal API, so should not fail */
if (!ossl_assert(pkt->subs != NULL))
return 0;
/* We don't support lenbytes greater than 0 when doing endfirst writing */
if (lenbytes > 0 && pkt->endfirst)
return 0;
if ((sub = OPENSSL_zalloc(sizeof(*sub))) == NULL)
return 0;
sub->parent = pkt->subs;
pkt->subs = sub;
sub->pwritten = pkt->written + lenbytes;
sub->lenbytes = lenbytes;
if (lenbytes == 0) {
sub->packet_len = 0;
return 1;
}
sub->packet_len = pkt->written;
if (!WPACKET_allocate_bytes(pkt, lenbytes, &lenchars))
return 0;
return 1;
}
int WPACKET_start_sub_packet(WPACKET *pkt)
{
return WPACKET_start_sub_packet_len__(pkt, 0);
}
int WPACKET_put_bytes__(WPACKET *pkt, uint64_t val, size_t size)
{
unsigned char *data;
/* Internal API, so should not fail */
if (!ossl_assert(size <= sizeof(uint64_t))
|| !WPACKET_allocate_bytes(pkt, size, &data)
|| !put_value(data, val, size))
return 0;
return 1;
}
int WPACKET_set_max_size(WPACKET *pkt, size_t maxsize)
{
WPACKET_SUB *sub;
size_t lenbytes;
/* Internal API, so should not fail */
if (!ossl_assert(pkt->subs != NULL))
return 0;
/* Find the WPACKET_SUB for the top level */
for (sub = pkt->subs; sub->parent != NULL; sub = sub->parent)
continue;
lenbytes = sub->lenbytes;
if (lenbytes == 0)
lenbytes = sizeof(pkt->maxsize);
if (maxmaxsize(lenbytes) < maxsize || maxsize < pkt->written)
return 0;
pkt->maxsize = maxsize;
return 1;
}
int WPACKET_memset(WPACKET *pkt, int ch, size_t len)
{
unsigned char *dest;
if (len == 0)
return 1;
if (!WPACKET_allocate_bytes(pkt, len, &dest))
return 0;
if (dest != NULL)
memset(dest, ch, len);
return 1;
}
int WPACKET_memcpy(WPACKET *pkt, const void *src, size_t len)
{
unsigned char *dest;
if (len == 0)
return 1;
if (!WPACKET_allocate_bytes(pkt, len, &dest))
return 0;
if (dest != NULL)
memcpy(dest, src, len);
return 1;
}
int WPACKET_sub_memcpy__(WPACKET *pkt, const void *src, size_t len,
size_t lenbytes)
{
if (!WPACKET_start_sub_packet_len__(pkt, lenbytes)
|| !WPACKET_memcpy(pkt, src, len)
|| !WPACKET_close(pkt))
return 0;
return 1;
}
int WPACKET_get_total_written(WPACKET *pkt, size_t *written)
{
/* Internal API, so should not fail */
if (!ossl_assert(written != NULL))
return 0;
*written = pkt->written;
return 1;
}
int WPACKET_get_length(WPACKET *pkt, size_t *len)
{
/* Internal API, so should not fail */
if (!ossl_assert(pkt->subs != NULL && len != NULL))
return 0;
*len = pkt->written - pkt->subs->pwritten;
return 1;
}
unsigned char *WPACKET_get_curr(WPACKET *pkt)
{
unsigned char *buf = GETBUF(pkt);
if (buf == NULL)
return NULL;
if (pkt->endfirst)
return buf + pkt->maxsize - pkt->curr;
return buf + pkt->curr;
}
int WPACKET_is_null_buf(WPACKET *pkt)
{
return pkt->buf == NULL && pkt->staticbuf == NULL;
}
void WPACKET_cleanup(WPACKET *pkt)
{
WPACKET_SUB *sub, *parent;
for (sub = pkt->subs; sub != NULL; sub = parent) {
parent = sub->parent;
OPENSSL_free(sub);
}
pkt->subs = NULL;
}
#if !defined OPENSSL_NO_QUIC && !defined FIPS_MODULE
int WPACKET_start_quic_sub_packet_bound(WPACKET *pkt, size_t max_len)
{
size_t enclen = ossl_quic_vlint_encode_len(max_len);
if (enclen == 0)
return 0;
if (WPACKET_start_sub_packet_len__(pkt, enclen) == 0)
return 0;
pkt->subs->flags |= WPACKET_FLAGS_QUIC_VLINT;
return 1;
}
int WPACKET_start_quic_sub_packet(WPACKET *pkt)
{
/*
* Assume no (sub)packet will exceed 4GiB, thus the 8-byte encoding need not
* be used.
*/
return WPACKET_start_quic_sub_packet_bound(pkt, OSSL_QUIC_VLINT_4B_MIN);
}
int WPACKET_quic_sub_allocate_bytes(WPACKET *pkt, size_t len, unsigned char **allocbytes)
{
if (!WPACKET_start_quic_sub_packet_bound(pkt, len)
|| !WPACKET_allocate_bytes(pkt, len, allocbytes)
|| !WPACKET_close(pkt))
return 0;
return 1;
}
/*
* Write a QUIC variable-length integer to the packet.
*/
int WPACKET_quic_write_vlint(WPACKET *pkt, uint64_t v)
{
unsigned char *b = NULL;
size_t enclen = ossl_quic_vlint_encode_len(v);
if (enclen == 0)
return 0;
if (WPACKET_allocate_bytes(pkt, enclen, &b) == 0)
return 0;
ossl_quic_vlint_encode(b, v);
return 1;
}
#endif
| 14,106 | 22.869712 | 89 | c |
openssl | openssl-master/crypto/param_build.c | /*
* Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include <openssl/err.h>
#include <openssl/cryptoerr.h>
#include <openssl/params.h>
#include <openssl/types.h>
#include <openssl/safestack.h>
#include "internal/param_build_set.h"
/*
* Special internal param type to indicate the end of an allocate OSSL_PARAM
* array.
*/
typedef struct {
const char *key;
int type;
int secure;
size_t size;
size_t alloc_blocks;
const BIGNUM *bn;
const void *string;
union {
/*
* These fields are never directly addressed, but their sizes are
* important so that all native types can be copied here without overrun.
*/
ossl_intmax_t i;
ossl_uintmax_t u;
double d;
} num;
} OSSL_PARAM_BLD_DEF;
DEFINE_STACK_OF(OSSL_PARAM_BLD_DEF)
struct ossl_param_bld_st {
size_t total_blocks;
size_t secure_blocks;
STACK_OF(OSSL_PARAM_BLD_DEF) *params;
};
static OSSL_PARAM_BLD_DEF *param_push(OSSL_PARAM_BLD *bld, const char *key,
int size, size_t alloc, int type,
int secure)
{
OSSL_PARAM_BLD_DEF *pd = OPENSSL_zalloc(sizeof(*pd));
if (pd == NULL)
return NULL;
pd->key = key;
pd->type = type;
pd->size = size;
pd->alloc_blocks = ossl_param_bytes_to_blocks(alloc);
if ((pd->secure = secure) != 0)
bld->secure_blocks += pd->alloc_blocks;
else
bld->total_blocks += pd->alloc_blocks;
if (sk_OSSL_PARAM_BLD_DEF_push(bld->params, pd) <= 0) {
OPENSSL_free(pd);
pd = NULL;
}
return pd;
}
static int param_push_num(OSSL_PARAM_BLD *bld, const char *key,
void *num, size_t size, int type)
{
OSSL_PARAM_BLD_DEF *pd = param_push(bld, key, size, size, type, 0);
if (pd == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (size > sizeof(pd->num)) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_MANY_BYTES);
return 0;
}
memcpy(&pd->num, num, size);
return 1;
}
OSSL_PARAM_BLD *OSSL_PARAM_BLD_new(void)
{
OSSL_PARAM_BLD *r = OPENSSL_zalloc(sizeof(OSSL_PARAM_BLD));
if (r != NULL) {
r->params = sk_OSSL_PARAM_BLD_DEF_new_null();
if (r->params == NULL) {
OPENSSL_free(r);
r = NULL;
}
}
return r;
}
static void free_all_params(OSSL_PARAM_BLD *bld)
{
int i, n = sk_OSSL_PARAM_BLD_DEF_num(bld->params);
for (i = 0; i < n; i++)
OPENSSL_free(sk_OSSL_PARAM_BLD_DEF_pop(bld->params));
}
void OSSL_PARAM_BLD_free(OSSL_PARAM_BLD *bld)
{
if (bld == NULL)
return;
free_all_params(bld);
sk_OSSL_PARAM_BLD_DEF_free(bld->params);
OPENSSL_free(bld);
}
int OSSL_PARAM_BLD_push_int(OSSL_PARAM_BLD *bld, const char *key, int num)
{
return param_push_num(bld, key, &num, sizeof(num), OSSL_PARAM_INTEGER);
}
int OSSL_PARAM_BLD_push_uint(OSSL_PARAM_BLD *bld, const char *key,
unsigned int num)
{
return param_push_num(bld, key, &num, sizeof(num),
OSSL_PARAM_UNSIGNED_INTEGER);
}
int OSSL_PARAM_BLD_push_long(OSSL_PARAM_BLD *bld, const char *key,
long int num)
{
return param_push_num(bld, key, &num, sizeof(num), OSSL_PARAM_INTEGER);
}
int OSSL_PARAM_BLD_push_ulong(OSSL_PARAM_BLD *bld, const char *key,
unsigned long int num)
{
return param_push_num(bld, key, &num, sizeof(num),
OSSL_PARAM_UNSIGNED_INTEGER);
}
int OSSL_PARAM_BLD_push_int32(OSSL_PARAM_BLD *bld, const char *key,
int32_t num)
{
return param_push_num(bld, key, &num, sizeof(num), OSSL_PARAM_INTEGER);
}
int OSSL_PARAM_BLD_push_uint32(OSSL_PARAM_BLD *bld, const char *key,
uint32_t num)
{
return param_push_num(bld, key, &num, sizeof(num),
OSSL_PARAM_UNSIGNED_INTEGER);
}
int OSSL_PARAM_BLD_push_int64(OSSL_PARAM_BLD *bld, const char *key,
int64_t num)
{
return param_push_num(bld, key, &num, sizeof(num), OSSL_PARAM_INTEGER);
}
int OSSL_PARAM_BLD_push_uint64(OSSL_PARAM_BLD *bld, const char *key,
uint64_t num)
{
return param_push_num(bld, key, &num, sizeof(num),
OSSL_PARAM_UNSIGNED_INTEGER);
}
int OSSL_PARAM_BLD_push_size_t(OSSL_PARAM_BLD *bld, const char *key,
size_t num)
{
return param_push_num(bld, key, &num, sizeof(num),
OSSL_PARAM_UNSIGNED_INTEGER);
}
int OSSL_PARAM_BLD_push_time_t(OSSL_PARAM_BLD *bld, const char *key,
time_t num)
{
return param_push_num(bld, key, &num, sizeof(num),
OSSL_PARAM_INTEGER);
}
int OSSL_PARAM_BLD_push_double(OSSL_PARAM_BLD *bld, const char *key,
double num)
{
return param_push_num(bld, key, &num, sizeof(num), OSSL_PARAM_REAL);
}
static int push_BN(OSSL_PARAM_BLD *bld, const char *key,
const BIGNUM *bn, size_t sz, int type)
{
int n, secure = 0;
OSSL_PARAM_BLD_DEF *pd;
if (!ossl_assert(type == OSSL_PARAM_UNSIGNED_INTEGER
|| type == OSSL_PARAM_INTEGER))
return 0;
if (bn != NULL) {
if (type == OSSL_PARAM_UNSIGNED_INTEGER && BN_is_negative(bn)) {
ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_UNSUPPORTED,
"Negative big numbers are unsupported for OSSL_PARAM_UNSIGNED_INTEGER");
return 0;
}
n = BN_num_bytes(bn);
if (n < 0) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_ZERO_LENGTH_NUMBER);
return 0;
}
if (sz < (size_t)n) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_SMALL_BUFFER);
return 0;
}
if (BN_get_flags(bn, BN_FLG_SECURE) == BN_FLG_SECURE)
secure = 1;
/* The BIGNUM is zero, we must transfer at least one byte */
if (sz == 0)
sz++;
}
pd = param_push(bld, key, sz, sz, type, secure);
if (pd == NULL)
return 0;
pd->bn = bn;
return 1;
}
int OSSL_PARAM_BLD_push_BN(OSSL_PARAM_BLD *bld, const char *key,
const BIGNUM *bn)
{
if (BN_is_negative(bn))
return push_BN(bld, key, bn, bn == NULL ? 0 : BN_num_bytes(bn) + 1,
OSSL_PARAM_INTEGER);
return push_BN(bld, key, bn, bn == NULL ? 0 : BN_num_bytes(bn),
OSSL_PARAM_UNSIGNED_INTEGER);
}
int OSSL_PARAM_BLD_push_BN_pad(OSSL_PARAM_BLD *bld, const char *key,
const BIGNUM *bn, size_t sz)
{
if (BN_is_negative(bn))
return push_BN(bld, key, bn, bn == NULL ? 0 : BN_num_bytes(bn),
OSSL_PARAM_INTEGER);
return push_BN(bld, key, bn, sz, OSSL_PARAM_UNSIGNED_INTEGER);
}
int OSSL_PARAM_BLD_push_utf8_string(OSSL_PARAM_BLD *bld, const char *key,
const char *buf, size_t bsize)
{
OSSL_PARAM_BLD_DEF *pd;
int secure;
if (bsize == 0) {
bsize = strlen(buf);
} else if (bsize > INT_MAX) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_STRING_TOO_LONG);
return 0;
}
secure = CRYPTO_secure_allocated(buf);
pd = param_push(bld, key, bsize, bsize + 1, OSSL_PARAM_UTF8_STRING, secure);
if (pd == NULL)
return 0;
pd->string = buf;
return 1;
}
int OSSL_PARAM_BLD_push_utf8_ptr(OSSL_PARAM_BLD *bld, const char *key,
char *buf, size_t bsize)
{
OSSL_PARAM_BLD_DEF *pd;
if (bsize == 0) {
bsize = strlen(buf);
} else if (bsize > INT_MAX) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_STRING_TOO_LONG);
return 0;
}
pd = param_push(bld, key, bsize, sizeof(buf), OSSL_PARAM_UTF8_PTR, 0);
if (pd == NULL)
return 0;
pd->string = buf;
return 1;
}
int OSSL_PARAM_BLD_push_octet_string(OSSL_PARAM_BLD *bld, const char *key,
const void *buf, size_t bsize)
{
OSSL_PARAM_BLD_DEF *pd;
int secure;
if (bsize > INT_MAX) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_STRING_TOO_LONG);
return 0;
}
secure = CRYPTO_secure_allocated(buf);
pd = param_push(bld, key, bsize, bsize, OSSL_PARAM_OCTET_STRING, secure);
if (pd == NULL)
return 0;
pd->string = buf;
return 1;
}
int OSSL_PARAM_BLD_push_octet_ptr(OSSL_PARAM_BLD *bld, const char *key,
void *buf, size_t bsize)
{
OSSL_PARAM_BLD_DEF *pd;
if (bsize > INT_MAX) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_STRING_TOO_LONG);
return 0;
}
pd = param_push(bld, key, bsize, sizeof(buf), OSSL_PARAM_OCTET_PTR, 0);
if (pd == NULL)
return 0;
pd->string = buf;
return 1;
}
static OSSL_PARAM *param_bld_convert(OSSL_PARAM_BLD *bld, OSSL_PARAM *param,
OSSL_PARAM_ALIGNED_BLOCK *blk,
OSSL_PARAM_ALIGNED_BLOCK *secure)
{
int i, num = sk_OSSL_PARAM_BLD_DEF_num(bld->params);
OSSL_PARAM_BLD_DEF *pd;
void *p;
for (i = 0; i < num; i++) {
pd = sk_OSSL_PARAM_BLD_DEF_value(bld->params, i);
param[i].key = pd->key;
param[i].data_type = pd->type;
param[i].data_size = pd->size;
param[i].return_size = OSSL_PARAM_UNMODIFIED;
if (pd->secure) {
p = secure;
secure += pd->alloc_blocks;
} else {
p = blk;
blk += pd->alloc_blocks;
}
param[i].data = p;
if (pd->bn != NULL) {
/* BIGNUM */
if (pd->type == OSSL_PARAM_UNSIGNED_INTEGER)
BN_bn2nativepad(pd->bn, (unsigned char *)p, pd->size);
else
BN_signed_bn2native(pd->bn, (unsigned char *)p, pd->size);
} else if (pd->type == OSSL_PARAM_OCTET_PTR
|| pd->type == OSSL_PARAM_UTF8_PTR) {
/* PTR */
*(const void **)p = pd->string;
} else if (pd->type == OSSL_PARAM_OCTET_STRING
|| pd->type == OSSL_PARAM_UTF8_STRING) {
if (pd->string != NULL)
memcpy(p, pd->string, pd->size);
else
memset(p, 0, pd->size);
if (pd->type == OSSL_PARAM_UTF8_STRING)
((char *)p)[pd->size] = '\0';
} else {
/* Number, but could also be a NULL BIGNUM */
if (pd->size > sizeof(pd->num))
memset(p, 0, pd->size);
else if (pd->size > 0)
memcpy(p, &pd->num, pd->size);
}
}
param[i] = OSSL_PARAM_construct_end();
return param + i;
}
OSSL_PARAM *OSSL_PARAM_BLD_to_param(OSSL_PARAM_BLD *bld)
{
OSSL_PARAM_ALIGNED_BLOCK *blk, *s = NULL;
OSSL_PARAM *params, *last;
const int num = sk_OSSL_PARAM_BLD_DEF_num(bld->params);
const size_t p_blks = ossl_param_bytes_to_blocks((1 + num) * sizeof(*params));
const size_t total = OSSL_PARAM_ALIGN_SIZE * (p_blks + bld->total_blocks);
const size_t ss = OSSL_PARAM_ALIGN_SIZE * bld->secure_blocks;
if (ss > 0) {
s = OPENSSL_secure_malloc(ss);
if (s == NULL) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_SECURE_MALLOC_FAILURE);
return NULL;
}
}
params = OPENSSL_malloc(total);
if (params == NULL) {
OPENSSL_secure_free(s);
return NULL;
}
blk = p_blks + (OSSL_PARAM_ALIGNED_BLOCK *)(params);
last = param_bld_convert(bld, params, blk, s);
ossl_param_set_secure_block(last, s, ss);
/* Reset builder for reuse */
bld->total_blocks = 0;
bld->secure_blocks = 0;
free_all_params(bld);
return params;
}
| 12,282 | 29.105392 | 99 | c |
openssl | openssl-master/crypto/param_build_set.c | /*
* Copyright 2020-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
*/
/*
* Key Management utility functions to share functionality between the export()
* and get_params() methods.
* export() uses OSSL_PARAM_BLD, and get_params() used the OSSL_PARAM[] to
* fill in parameter data for the same key and data fields.
*/
#include <openssl/core_names.h>
#include "internal/param_build_set.h"
DEFINE_SPECIAL_STACK_OF_CONST(BIGNUM_const, BIGNUM)
int ossl_param_build_set_int(OSSL_PARAM_BLD *bld, OSSL_PARAM *p,
const char *key, int num)
{
if (bld != NULL)
return OSSL_PARAM_BLD_push_int(bld, key, num);
p = OSSL_PARAM_locate(p, key);
if (p != NULL)
return OSSL_PARAM_set_int(p, num);
return 1;
}
int ossl_param_build_set_long(OSSL_PARAM_BLD *bld, OSSL_PARAM *p,
const char *key, long num)
{
if (bld != NULL)
return OSSL_PARAM_BLD_push_long(bld, key, num);
p = OSSL_PARAM_locate(p, key);
if (p != NULL)
return OSSL_PARAM_set_long(p, num);
return 1;
}
int ossl_param_build_set_utf8_string(OSSL_PARAM_BLD *bld, OSSL_PARAM *p,
const char *key, const char *buf)
{
if (bld != NULL)
return OSSL_PARAM_BLD_push_utf8_string(bld, key, buf, 0);
p = OSSL_PARAM_locate(p, key);
if (p != NULL)
return OSSL_PARAM_set_utf8_string(p, buf);
return 1;
}
int ossl_param_build_set_octet_string(OSSL_PARAM_BLD *bld, OSSL_PARAM *p,
const char *key,
const unsigned char *data,
size_t data_len)
{
if (bld != NULL)
return OSSL_PARAM_BLD_push_octet_string(bld, key, data, data_len);
p = OSSL_PARAM_locate(p, key);
if (p != NULL)
return OSSL_PARAM_set_octet_string(p, data, data_len);
return 1;
}
int ossl_param_build_set_bn_pad(OSSL_PARAM_BLD *bld, OSSL_PARAM *p,
const char *key, const BIGNUM *bn, size_t sz)
{
if (bld != NULL)
return OSSL_PARAM_BLD_push_BN_pad(bld, key, bn, sz);
p = OSSL_PARAM_locate(p, key);
if (p != NULL) {
if (sz > p->data_size) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_SMALL_BUFFER);
return 0;
}
p->data_size = sz;
return OSSL_PARAM_set_BN(p, bn);
}
return 1;
}
int ossl_param_build_set_bn(OSSL_PARAM_BLD *bld, OSSL_PARAM *p,
const char *key, const BIGNUM *bn)
{
if (bld != NULL)
return OSSL_PARAM_BLD_push_BN(bld, key, bn);
p = OSSL_PARAM_locate(p, key);
if (p != NULL)
return OSSL_PARAM_set_BN(p, bn) > 0;
return 1;
}
int ossl_param_build_set_multi_key_bn(OSSL_PARAM_BLD *bld, OSSL_PARAM *params,
const char *names[],
STACK_OF(BIGNUM_const) *stk)
{
int i, sz = sk_BIGNUM_const_num(stk);
OSSL_PARAM *p;
if (bld != NULL) {
for (i = 0; i < sz && names[i] != NULL; ++i) {
if (!OSSL_PARAM_BLD_push_BN(bld, names[i],
sk_BIGNUM_const_value(stk, i)))
return 0;
}
return 1;
}
for (i = 0; i < sz && names[i] != NULL; ++i) {
p = OSSL_PARAM_locate(params, names[i]);
if (p != NULL) {
if (!OSSL_PARAM_set_BN(p, sk_BIGNUM_const_value(stk, i)))
return 0;
}
}
return 1;
}
| 3,797 | 29.629032 | 79 | c |
openssl | openssl-master/crypto/params_dup.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 <openssl/params.h>
#include <openssl/param_build.h>
#include "internal/param_build_set.h"
#define OSSL_PARAM_ALLOCATED_END 127
#define OSSL_PARAM_MERGE_LIST_MAX 128
#define OSSL_PARAM_BUF_PUBLIC 0
#define OSSL_PARAM_BUF_SECURE 1
#define OSSL_PARAM_BUF_MAX (OSSL_PARAM_BUF_SECURE + 1)
typedef struct {
OSSL_PARAM_ALIGNED_BLOCK *alloc; /* The allocated buffer */
OSSL_PARAM_ALIGNED_BLOCK *cur; /* Current position in the allocated buf */
size_t blocks; /* Number of aligned blocks */
size_t alloc_sz; /* The size of the allocated buffer (in bytes) */
} OSSL_PARAM_BUF;
size_t ossl_param_bytes_to_blocks(size_t bytes)
{
return (bytes + OSSL_PARAM_ALIGN_SIZE - 1) / OSSL_PARAM_ALIGN_SIZE;
}
static int ossl_param_buf_alloc(OSSL_PARAM_BUF *out, size_t extra_blocks,
int is_secure)
{
size_t sz = OSSL_PARAM_ALIGN_SIZE * (extra_blocks + out->blocks);
out->alloc = is_secure ? OPENSSL_secure_zalloc(sz) : OPENSSL_zalloc(sz);
if (out->alloc == NULL)
return 0;
out->alloc_sz = sz;
out->cur = out->alloc + extra_blocks;
return 1;
}
void ossl_param_set_secure_block(OSSL_PARAM *last, void *secure_buffer,
size_t secure_buffer_sz)
{
last->key = NULL;
last->data_size = secure_buffer_sz;
last->data = secure_buffer;
last->data_type = OSSL_PARAM_ALLOCATED_END;
}
static OSSL_PARAM *ossl_param_dup(const OSSL_PARAM *src, OSSL_PARAM *dst,
OSSL_PARAM_BUF buf[OSSL_PARAM_BUF_MAX],
int *param_count)
{
const OSSL_PARAM *in;
int has_dst = (dst != NULL);
int is_secure;
size_t param_sz, blks;
for (in = src; in->key != NULL; in++) {
is_secure = CRYPTO_secure_allocated(in->data);
if (has_dst) {
*dst = *in;
dst->data = buf[is_secure].cur;
}
if (in->data_type == OSSL_PARAM_OCTET_PTR
|| in->data_type == OSSL_PARAM_UTF8_PTR) {
param_sz = sizeof(in->data);
if (has_dst)
*((const void **)dst->data) = *(const void **)in->data;
} else {
param_sz = in->data_size;
if (has_dst)
memcpy(dst->data, in->data, param_sz);
}
if (in->data_type == OSSL_PARAM_UTF8_STRING)
param_sz++; /* NULL terminator */
blks = ossl_param_bytes_to_blocks(param_sz);
if (has_dst) {
dst++;
buf[is_secure].cur += blks;
} else {
buf[is_secure].blocks += blks;
}
if (param_count != NULL)
++*param_count;
}
return dst;
}
OSSL_PARAM *OSSL_PARAM_dup(const OSSL_PARAM *src)
{
size_t param_blocks;
OSSL_PARAM_BUF buf[OSSL_PARAM_BUF_MAX];
OSSL_PARAM *last, *dst;
int param_count = 1; /* Include terminator in the count */
if (src == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
memset(buf, 0, sizeof(buf));
/* First Pass: get the param_count and block sizes required */
(void)ossl_param_dup(src, NULL, buf, ¶m_count);
param_blocks = ossl_param_bytes_to_blocks(param_count * sizeof(*src));
/*
* The allocated buffer consists of an array of OSSL_PARAM followed by
* aligned data bytes that the array elements will point to.
*/
if (!ossl_param_buf_alloc(&buf[OSSL_PARAM_BUF_PUBLIC], param_blocks, 0))
return NULL;
/* Allocate a secure memory buffer if required */
if (buf[OSSL_PARAM_BUF_SECURE].blocks > 0
&& !ossl_param_buf_alloc(&buf[OSSL_PARAM_BUF_SECURE], 0, 1)) {
OPENSSL_free(buf[OSSL_PARAM_BUF_PUBLIC].alloc);
return NULL;
}
dst = (OSSL_PARAM *)buf[OSSL_PARAM_BUF_PUBLIC].alloc;
last = ossl_param_dup(src, dst, buf, NULL);
/* Store the allocated secure memory buffer in the last param block */
ossl_param_set_secure_block(last, buf[OSSL_PARAM_BUF_SECURE].alloc,
buf[OSSL_PARAM_BUF_SECURE].alloc_sz);
return dst;
}
static int compare_params(const void *left, const void *right)
{
const OSSL_PARAM *l = *(const OSSL_PARAM **)left;
const OSSL_PARAM *r = *(const OSSL_PARAM **)right;
return OPENSSL_strcasecmp(l->key, r->key);
}
OSSL_PARAM *OSSL_PARAM_merge(const OSSL_PARAM *p1, const OSSL_PARAM *p2)
{
const OSSL_PARAM *list1[OSSL_PARAM_MERGE_LIST_MAX + 1];
const OSSL_PARAM *list2[OSSL_PARAM_MERGE_LIST_MAX + 1];
const OSSL_PARAM *p = NULL;
const OSSL_PARAM **p1cur, **p2cur;
OSSL_PARAM *params, *dst;
size_t list1_sz = 0, list2_sz = 0;
int diff;
if (p1 == NULL && p2 == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
/* Copy p1 to list1 */
if (p1 != NULL) {
for (p = p1; p->key != NULL && list1_sz < OSSL_PARAM_MERGE_LIST_MAX; p++)
list1[list1_sz++] = p;
}
list1[list1_sz] = NULL;
/* copy p2 to a list2 */
if (p2 != NULL) {
for (p = p2; p->key != NULL && list2_sz < OSSL_PARAM_MERGE_LIST_MAX; p++)
list2[list2_sz++] = p;
}
list2[list2_sz] = NULL;
if (list1_sz == 0 && list2_sz == 0) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_NO_PARAMS_TO_MERGE);
return NULL;
}
/* Sort the 2 lists */
qsort(list1, list1_sz, sizeof(OSSL_PARAM *), compare_params);
qsort(list2, list2_sz, sizeof(OSSL_PARAM *), compare_params);
/* Allocate enough space to store the merged parameters */
params = OPENSSL_zalloc((list1_sz + list2_sz + 1) * sizeof(*p1));
if (params == NULL)
return NULL;
dst = params;
p1cur = list1;
p2cur = list2;
while (1) {
/* If list1 is finished just tack list2 onto the end */
if (*p1cur == NULL) {
do {
*dst++ = **p2cur;
p2cur++;
} while (*p2cur != NULL);
break;
}
/* If list2 is finished just tack list1 onto the end */
if (*p2cur == NULL) {
do {
*dst++ = **p1cur;
p1cur++;
} while (*p1cur != NULL);
break;
}
/* consume the list element with the smaller key */
diff = OPENSSL_strcasecmp((*p1cur)->key, (*p2cur)->key);
if (diff == 0) {
/* If the keys are the same then throw away the list1 element */
*dst++ = **p2cur;
p2cur++;
p1cur++;
} else if (diff > 0) {
*dst++ = **p2cur;
p2cur++;
} else {
*dst++ = **p1cur;
p1cur++;
}
}
return params;
}
void OSSL_PARAM_free(OSSL_PARAM *params)
{
if (params != NULL) {
OSSL_PARAM *p;
for (p = params; p->key != NULL; p++)
;
if (p->data_type == OSSL_PARAM_ALLOCATED_END)
OPENSSL_secure_clear_free(p->data, p->data_size);
OPENSSL_free(params);
}
}
| 7,387 | 30.172996 | 81 | c |
openssl | openssl-master/crypto/params_from_text.c | /*
* Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/common.h" /* for HAS_PREFIX */
#include <openssl/ebcdic.h>
#include <openssl/err.h>
#include <openssl/params.h>
/*
* When processing text to params, we're trying to be smart with numbers.
* Instead of handling each specific separate integer type, we use a bignum
* and ensure that it isn't larger than the expected size, and we then make
* sure it is the expected size... if there is one given.
* (if the size can be arbitrary, then we give whatever we have)
*/
static int prepare_from_text(const OSSL_PARAM *paramdefs, const char *key,
const char *value, size_t value_n,
/* Output parameters */
const OSSL_PARAM **paramdef, int *ishex,
size_t *buf_n, BIGNUM **tmpbn, int *found)
{
const OSSL_PARAM *p;
size_t buf_bits;
int r;
/*
* ishex is used to translate legacy style string controls in hex format
* to octet string parameters.
*/
*ishex = CHECK_AND_SKIP_PREFIX(key, "hex");
p = *paramdef = OSSL_PARAM_locate_const(paramdefs, key);
if (found != NULL)
*found = p != NULL;
if (p == NULL)
return 0;
switch (p->data_type) {
case OSSL_PARAM_INTEGER:
case OSSL_PARAM_UNSIGNED_INTEGER:
if (*ishex)
r = BN_hex2bn(tmpbn, value);
else
r = BN_asc2bn(tmpbn, value);
if (r == 0 || *tmpbn == NULL)
return 0;
if (p->data_type == OSSL_PARAM_UNSIGNED_INTEGER
&& BN_is_negative(*tmpbn)) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_INVALID_NEGATIVE_VALUE);
return 0;
}
/*
* 2's complement negate, part 1
*
* BN_bn2nativepad puts the absolute value of the number in the
* buffer, i.e. if it's negative, we need to deal with it. We do
* it by subtracting 1 here and inverting the bytes in
* construct_from_text() below.
* To subtract 1 from an absolute value of a negative number we
* actually have to add 1: -3 - 1 = -4, |-3| = 3 + 1 = 4.
*/
if (p->data_type == OSSL_PARAM_INTEGER && BN_is_negative(*tmpbn)
&& !BN_add_word(*tmpbn, 1)) {
return 0;
}
buf_bits = (size_t)BN_num_bits(*tmpbn);
/*
* Compensate for cases where the most significant bit in
* the resulting OSSL_PARAM buffer will be set after the
* BN_bn2nativepad() call, as the implied sign may not be
* correct after the second part of the 2's complement
* negation has been performed.
* We fix these cases by extending the buffer by one byte
* (8 bits), which will give some padding. The second part
* of the 2's complement negation will do the rest.
*/
if (p->data_type == OSSL_PARAM_INTEGER && buf_bits % 8 == 0)
buf_bits += 8;
*buf_n = (buf_bits + 7) / 8;
/*
* A zero data size means "arbitrary size", so only do the
* range checking if a size is specified.
*/
if (p->data_size > 0) {
if (buf_bits > p->data_size * 8) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_TOO_SMALL_BUFFER);
/* Since this is a different error, we don't break */
return 0;
}
/* Change actual size to become the desired size. */
*buf_n = p->data_size;
}
break;
case OSSL_PARAM_UTF8_STRING:
if (*ishex) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT);
return 0;
}
*buf_n = strlen(value) + 1;
break;
case OSSL_PARAM_OCTET_STRING:
if (*ishex) {
*buf_n = strlen(value) >> 1;
} else {
*buf_n = value_n;
}
break;
}
return 1;
}
static int construct_from_text(OSSL_PARAM *to, const OSSL_PARAM *paramdef,
const char *value, size_t value_n, int ishex,
void *buf, size_t buf_n, BIGNUM *tmpbn)
{
if (buf == NULL)
return 0;
if (buf_n > 0) {
switch (paramdef->data_type) {
case OSSL_PARAM_INTEGER:
case OSSL_PARAM_UNSIGNED_INTEGER:
/*
{
if ((new_value = OPENSSL_malloc(new_value_n)) == NULL) {
BN_free(a);
break;
}
*/
BN_bn2nativepad(tmpbn, buf, buf_n);
/*
* 2's complement negation, part two.
*
* Because we did the first part on the BIGNUM itself, we can just
* invert all the bytes here and be done with it.
*/
if (paramdef->data_type == OSSL_PARAM_INTEGER
&& BN_is_negative(tmpbn)) {
unsigned char *cp;
size_t i = buf_n;
for (cp = buf; i-- > 0; cp++)
*cp ^= 0xFF;
}
break;
case OSSL_PARAM_UTF8_STRING:
#ifdef CHARSET_EBCDIC
ebcdic2ascii(buf, value, buf_n);
#else
strncpy(buf, value, buf_n);
#endif
/* Don't count the terminating NUL byte as data */
buf_n--;
break;
case OSSL_PARAM_OCTET_STRING:
if (ishex) {
size_t l = 0;
if (!OPENSSL_hexstr2buf_ex(buf, buf_n, &l, value, ':'))
return 0;
} else {
memcpy(buf, value, buf_n);
}
break;
}
}
*to = *paramdef;
to->data = buf;
to->data_size = buf_n;
to->return_size = OSSL_PARAM_UNMODIFIED;
return 1;
}
int OSSL_PARAM_allocate_from_text(OSSL_PARAM *to,
const OSSL_PARAM *paramdefs,
const char *key, const char *value,
size_t value_n, int *found)
{
const OSSL_PARAM *paramdef = NULL;
int ishex = 0;
void *buf = NULL;
size_t buf_n = 0;
BIGNUM *tmpbn = NULL;
int ok = 0;
if (to == NULL || paramdefs == NULL)
return 0;
if (!prepare_from_text(paramdefs, key, value, value_n,
¶mdef, &ishex, &buf_n, &tmpbn, found))
goto err;
if ((buf = OPENSSL_zalloc(buf_n > 0 ? buf_n : 1)) == NULL)
goto err;
ok = construct_from_text(to, paramdef, value, value_n, ishex,
buf, buf_n, tmpbn);
BN_free(tmpbn);
if (!ok)
OPENSSL_free(buf);
return ok;
err:
BN_free(tmpbn);
return 0;
}
| 7,112 | 30.473451 | 78 | c |
openssl | openssl-master/crypto/passphrase.c | /*
* Copyright 2020-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/err.h>
#include <openssl/ui.h>
#include <openssl/core_names.h>
#include "internal/cryptlib.h"
#include "internal/passphrase.h"
void ossl_pw_clear_passphrase_data(struct ossl_passphrase_data_st *data)
{
if (data != NULL) {
if (data->type == is_expl_passphrase)
OPENSSL_clear_free(data->_.expl_passphrase.passphrase_copy,
data->_.expl_passphrase.passphrase_len);
ossl_pw_clear_passphrase_cache(data);
memset(data, 0, sizeof(*data));
}
}
void ossl_pw_clear_passphrase_cache(struct ossl_passphrase_data_st *data)
{
OPENSSL_clear_free(data->cached_passphrase, data->cached_passphrase_len);
data->cached_passphrase = NULL;
}
int ossl_pw_set_passphrase(struct ossl_passphrase_data_st *data,
const unsigned char *passphrase,
size_t passphrase_len)
{
if (!ossl_assert(data != NULL && passphrase != NULL)) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
ossl_pw_clear_passphrase_data(data);
data->type = is_expl_passphrase;
data->_.expl_passphrase.passphrase_copy =
passphrase_len != 0 ? OPENSSL_memdup(passphrase, passphrase_len)
: OPENSSL_malloc(1);
if (data->_.expl_passphrase.passphrase_copy == NULL)
return 0;
data->_.expl_passphrase.passphrase_len = passphrase_len;
return 1;
}
int ossl_pw_set_pem_password_cb(struct ossl_passphrase_data_st *data,
pem_password_cb *cb, void *cbarg)
{
if (!ossl_assert(data != NULL && cb != NULL)) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
ossl_pw_clear_passphrase_data(data);
data->type = is_pem_password;
data->_.pem_password.password_cb = cb;
data->_.pem_password.password_cbarg = cbarg;
return 1;
}
int ossl_pw_set_ossl_passphrase_cb(struct ossl_passphrase_data_st *data,
OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg)
{
if (!ossl_assert(data != NULL && cb != NULL)) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
ossl_pw_clear_passphrase_data(data);
data->type = is_ossl_passphrase;
data->_.ossl_passphrase.passphrase_cb = cb;
data->_.ossl_passphrase.passphrase_cbarg = cbarg;
return 1;
}
int ossl_pw_set_ui_method(struct ossl_passphrase_data_st *data,
const UI_METHOD *ui_method, void *ui_data)
{
if (!ossl_assert(data != NULL && ui_method != NULL)) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
ossl_pw_clear_passphrase_data(data);
data->type = is_ui_method;
data->_.ui_method.ui_method = ui_method;
data->_.ui_method.ui_method_data = ui_data;
return 1;
}
int ossl_pw_enable_passphrase_caching(struct ossl_passphrase_data_st *data)
{
data->flag_cache_passphrase = 1;
return 1;
}
int ossl_pw_disable_passphrase_caching(struct ossl_passphrase_data_st *data)
{
data->flag_cache_passphrase = 0;
return 1;
}
/*-
* UI_METHOD processor. It differs from UI_UTIL_read_pw() like this:
*
* 1. It constructs a prompt on its own, based on |prompt_info|.
* 2. It allocates a buffer for password and verification on its own
* to compensate for NUL terminator in UI password strings.
* 3. It raises errors.
* 4. It reports back the length of the prompted pass phrase.
*/
static int do_ui_passphrase(char *pass, size_t pass_size, size_t *pass_len,
const char *prompt_info, int verify,
const UI_METHOD *ui_method, void *ui_data)
{
char *prompt = NULL, *ipass = NULL, *vpass = NULL;
int prompt_idx = -1, verify_idx = -1, res;
UI *ui = NULL;
int ret = 0;
if (!ossl_assert(pass != NULL && pass_size != 0 && pass_len != NULL)) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if ((ui = UI_new()) == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_UI_LIB);
return 0;
}
if (ui_method != NULL) {
UI_set_method(ui, ui_method);
if (ui_data != NULL)
UI_add_user_data(ui, ui_data);
}
/* Get an application constructed prompt */
prompt = UI_construct_prompt(ui, "pass phrase", prompt_info);
if (prompt == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_UI_LIB);
goto end;
}
/* Get a buffer for verification prompt */
ipass = OPENSSL_zalloc(pass_size + 1);
if (ipass == NULL)
goto end;
prompt_idx = UI_add_input_string(ui, prompt,
UI_INPUT_FLAG_DEFAULT_PWD,
ipass, 0, pass_size) - 1;
if (prompt_idx < 0) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_UI_LIB);
goto end;
}
if (verify) {
/* Get a buffer for verification prompt */
vpass = OPENSSL_zalloc(pass_size + 1);
if (vpass == NULL)
goto end;
verify_idx = UI_add_verify_string(ui, prompt,
UI_INPUT_FLAG_DEFAULT_PWD,
vpass, 0, pass_size,
ipass) - 1;
if (verify_idx < 0) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_UI_LIB);
goto end;
}
}
switch (UI_process(ui)) {
case -2:
ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERRUPTED_OR_CANCELLED);
break;
case -1:
ERR_raise(ERR_LIB_CRYPTO, ERR_R_UI_LIB);
break;
default:
res = UI_get_result_length(ui, prompt_idx);
if (res < 0) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_UI_LIB);
break;
}
*pass_len = (size_t)res;
memcpy(pass, ipass, *pass_len);
ret = 1;
break;
}
end:
OPENSSL_clear_free(vpass, pass_size + 1);
OPENSSL_clear_free(ipass, pass_size + 1);
OPENSSL_free(prompt);
UI_free(ui);
return ret;
}
/* Central pw prompting dispatcher */
int ossl_pw_get_passphrase(char *pass, size_t pass_size, size_t *pass_len,
const OSSL_PARAM params[], int verify,
struct ossl_passphrase_data_st *data)
{
const char *source = NULL;
size_t source_len = 0;
const char *prompt_info = NULL;
const UI_METHOD *ui_method = NULL;
UI_METHOD *allocated_ui_method = NULL;
void *ui_data = NULL;
const OSSL_PARAM *p = NULL;
int ret;
/* Handle explicit and cached passphrases */
if (data->type == is_expl_passphrase) {
source = data->_.expl_passphrase.passphrase_copy;
source_len = data->_.expl_passphrase.passphrase_len;
} else if (data->flag_cache_passphrase && data->cached_passphrase != NULL) {
source = data->cached_passphrase;
source_len = data->cached_passphrase_len;
}
if (source != NULL) {
if (source_len > pass_size)
source_len = pass_size;
memcpy(pass, source, source_len);
*pass_len = source_len;
return 1;
}
/* Handle the is_ossl_passphrase case... that's pretty direct */
if (data->type == is_ossl_passphrase) {
OSSL_PASSPHRASE_CALLBACK *cb = data->_.ossl_passphrase.passphrase_cb;
void *cbarg = data->_.ossl_passphrase.passphrase_cbarg;
ret = cb(pass, pass_size, pass_len, params, cbarg);
goto do_cache;
}
/* Handle the is_pem_password and is_ui_method cases */
if ((p = OSSL_PARAM_locate_const(params,
OSSL_PASSPHRASE_PARAM_INFO)) != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING) {
ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT,
"Prompt info data type incorrect");
return 0;
}
prompt_info = p->data;
}
if (data->type == is_pem_password) {
/* We use a UI wrapper for PEM */
pem_password_cb *cb = data->_.pem_password.password_cb;
ui_method = allocated_ui_method =
UI_UTIL_wrap_read_pem_callback(cb, verify);
ui_data = data->_.pem_password.password_cbarg;
if (ui_method == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_UI_LIB);
return 0;
}
} else if (data->type == is_ui_method) {
ui_method = data->_.ui_method.ui_method;
ui_data = data->_.ui_method.ui_method_data;
}
if (ui_method == NULL) {
ERR_raise_data(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT,
"No password method specified");
return 0;
}
ret = do_ui_passphrase(pass, pass_size, pass_len, prompt_info, verify,
ui_method, ui_data);
UI_destroy_method(allocated_ui_method);
do_cache:
if (ret && data->flag_cache_passphrase) {
if (data->cached_passphrase == NULL
|| *pass_len > data->cached_passphrase_len) {
void *new_cache =
OPENSSL_clear_realloc(data->cached_passphrase,
data->cached_passphrase_len,
*pass_len + 1);
if (new_cache == NULL) {
OPENSSL_cleanse(pass, *pass_len);
return 0;
}
data->cached_passphrase = new_cache;
}
memcpy(data->cached_passphrase, pass, *pass_len);
data->cached_passphrase[*pass_len] = '\0';
data->cached_passphrase_len = *pass_len;
}
return ret;
}
static int ossl_pw_get_password(char *buf, int size, int rwflag,
void *userdata, const char *info)
{
size_t password_len = 0;
OSSL_PARAM params[] = {
OSSL_PARAM_utf8_string(OSSL_PASSPHRASE_PARAM_INFO, NULL, 0),
OSSL_PARAM_END
};
params[0].data = (void *)info;
if (ossl_pw_get_passphrase(buf, (size_t)size, &password_len, params,
rwflag, userdata))
return (int)password_len;
return -1;
}
int ossl_pw_pem_password(char *buf, int size, int rwflag, void *userdata)
{
return ossl_pw_get_password(buf, size, rwflag, userdata, "PEM");
}
int ossl_pw_pvk_password(char *buf, int size, int rwflag, void *userdata)
{
return ossl_pw_get_password(buf, size, rwflag, userdata, "PVK");
}
int ossl_pw_passphrase_callback_enc(char *pass, size_t pass_size,
size_t *pass_len,
const OSSL_PARAM params[], void *arg)
{
return ossl_pw_get_passphrase(pass, pass_size, pass_len, params, 1, arg);
}
int ossl_pw_passphrase_callback_dec(char *pass, size_t pass_size,
size_t *pass_len,
const OSSL_PARAM params[], void *arg)
{
return ossl_pw_get_passphrase(pass, pass_size, pass_len, params, 0, arg);
}
| 11,292 | 31.544669 | 80 | c |
openssl | openssl-master/crypto/ppccap.c | /*
* Copyright 2009-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <setjmp.h>
#include <signal.h>
#include <unistd.h>
#if defined(__linux) || defined(_AIX)
# include <sys/utsname.h>
#endif
#if defined(_AIX53) /* defined even on post-5.3 */
# include <sys/systemcfg.h>
# if !defined(__power_set)
# define __power_set(a) (_system_configuration.implementation & (a))
# endif
#endif
#if defined(__APPLE__) && defined(__MACH__)
# include <sys/types.h>
# include <sys/sysctl.h>
#endif
#include <openssl/crypto.h>
#include "internal/cryptlib.h"
#include "crypto/ppc_arch.h"
unsigned int OPENSSL_ppccap_P = 0;
static sigset_t all_masked;
static sigjmp_buf ill_jmp;
static void ill_handler(int sig)
{
siglongjmp(ill_jmp, sig);
}
void OPENSSL_fpu_probe(void);
void OPENSSL_ppc64_probe(void);
void OPENSSL_altivec_probe(void);
void OPENSSL_crypto207_probe(void);
void OPENSSL_madd300_probe(void);
void OPENSSL_brd31_probe(void);
long OPENSSL_rdtsc_mftb(void);
long OPENSSL_rdtsc_mfspr268(void);
uint32_t OPENSSL_rdtsc(void)
{
if (OPENSSL_ppccap_P & PPC_MFTB)
return OPENSSL_rdtsc_mftb();
else if (OPENSSL_ppccap_P & PPC_MFSPR268)
return OPENSSL_rdtsc_mfspr268();
else
return 0;
}
size_t OPENSSL_instrument_bus_mftb(unsigned int *, size_t);
size_t OPENSSL_instrument_bus_mfspr268(unsigned int *, size_t);
size_t OPENSSL_instrument_bus(unsigned int *out, size_t cnt)
{
if (OPENSSL_ppccap_P & PPC_MFTB)
return OPENSSL_instrument_bus_mftb(out, cnt);
else if (OPENSSL_ppccap_P & PPC_MFSPR268)
return OPENSSL_instrument_bus_mfspr268(out, cnt);
else
return 0;
}
size_t OPENSSL_instrument_bus2_mftb(unsigned int *, size_t, size_t);
size_t OPENSSL_instrument_bus2_mfspr268(unsigned int *, size_t, size_t);
size_t OPENSSL_instrument_bus2(unsigned int *out, size_t cnt, size_t max)
{
if (OPENSSL_ppccap_P & PPC_MFTB)
return OPENSSL_instrument_bus2_mftb(out, cnt, max);
else if (OPENSSL_ppccap_P & PPC_MFSPR268)
return OPENSSL_instrument_bus2_mfspr268(out, cnt, max);
else
return 0;
}
#if defined(__GLIBC__) && defined(__GLIBC_PREREQ)
# if __GLIBC_PREREQ(2, 16)
# include <sys/auxv.h>
# define OSSL_IMPLEMENT_GETAUXVAL
# elif defined(__ANDROID_API__)
/* see https://developer.android.google.cn/ndk/guides/cpu-features */
# if __ANDROID_API__ >= 18
# include <sys/auxv.h>
# define OSSL_IMPLEMENT_GETAUXVAL
# endif
# endif
#endif
#if defined(__FreeBSD__)
# include <sys/param.h>
# if __FreeBSD_version >= 1200000
# include <sys/auxv.h>
# define OSSL_IMPLEMENT_GETAUXVAL
static unsigned long getauxval(unsigned long key)
{
unsigned long val = 0ul;
if (elf_aux_info((int)key, &val, sizeof(val)) != 0)
return 0ul;
return val;
}
# endif
#endif
/* I wish <sys/auxv.h> was universally available */
#ifndef AT_HWCAP
# define AT_HWCAP 16 /* AT_HWCAP */
#endif
#define HWCAP_PPC64 (1U << 30)
#define HWCAP_ALTIVEC (1U << 28)
#define HWCAP_FPU (1U << 27)
#define HWCAP_POWER6_EXT (1U << 9)
#define HWCAP_VSX (1U << 7)
#ifndef AT_HWCAP2
# define AT_HWCAP2 26 /* AT_HWCAP2 */
#endif
#define HWCAP_VEC_CRYPTO (1U << 25)
#define HWCAP_ARCH_3_00 (1U << 23)
#define HWCAP_ARCH_3_1 (1U << 18)
# if defined(__GNUC__) && __GNUC__>=2
__attribute__ ((constructor))
# endif
void OPENSSL_cpuid_setup(void)
{
char *e;
struct sigaction ill_oact, ill_act;
sigset_t oset;
static int trigger = 0;
if (trigger)
return;
trigger = 1;
if ((e = getenv("OPENSSL_ppccap"))) {
OPENSSL_ppccap_P = strtoul(e, NULL, 0);
return;
}
OPENSSL_ppccap_P = 0;
#if defined(_AIX)
OPENSSL_ppccap_P |= PPC_FPU;
if (sizeof(size_t) == 4) {
struct utsname uts;
# if defined(_SC_AIX_KERNEL_BITMODE)
if (sysconf(_SC_AIX_KERNEL_BITMODE) != 64)
return;
# endif
if (uname(&uts) != 0 || atoi(uts.version) < 6)
return;
}
# if defined(__power_set)
/*
* Value used in __power_set is a single-bit 1<<n one denoting
* specific processor class. Incidentally 0xffffffff<<n can be
* used to denote specific processor and its successors.
*/
if (sizeof(size_t) == 4) {
/* In 32-bit case PPC_FPU64 is always fastest [if option] */
if (__power_set(0xffffffffU<<13)) /* POWER5 and later */
OPENSSL_ppccap_P |= PPC_FPU64;
} else {
/* In 64-bit case PPC_FPU64 is fastest only on POWER6 */
if (__power_set(0x1U<<14)) /* POWER6 */
OPENSSL_ppccap_P |= PPC_FPU64;
}
if (__power_set(0xffffffffU<<14)) /* POWER6 and later */
OPENSSL_ppccap_P |= PPC_ALTIVEC;
if (__power_set(0xffffffffU<<16)) /* POWER8 and later */
OPENSSL_ppccap_P |= PPC_CRYPTO207;
if (__power_set(0xffffffffU<<17)) /* POWER9 and later */
OPENSSL_ppccap_P |= PPC_MADD300;
if (__power_set(0xffffffffU<<18)) /* POWER10 and later */
OPENSSL_ppccap_P |= PPC_BRD31;
return;
# endif
#endif
#if defined(__APPLE__) && defined(__MACH__)
OPENSSL_ppccap_P |= PPC_FPU;
{
int val;
size_t len = sizeof(val);
if (sysctlbyname("hw.optional.64bitops", &val, &len, NULL, 0) == 0) {
if (val)
OPENSSL_ppccap_P |= PPC_FPU64;
}
len = sizeof(val);
if (sysctlbyname("hw.optional.altivec", &val, &len, NULL, 0) == 0) {
if (val)
OPENSSL_ppccap_P |= PPC_ALTIVEC;
}
return;
}
#endif
#ifdef OSSL_IMPLEMENT_GETAUXVAL
{
unsigned long hwcap = getauxval(AT_HWCAP);
unsigned long hwcap2 = getauxval(AT_HWCAP2);
if (hwcap & HWCAP_FPU) {
OPENSSL_ppccap_P |= PPC_FPU;
if (sizeof(size_t) == 4) {
/* In 32-bit case PPC_FPU64 is always fastest [if option] */
if (hwcap & HWCAP_PPC64)
OPENSSL_ppccap_P |= PPC_FPU64;
} else {
/* In 64-bit case PPC_FPU64 is fastest only on POWER6 */
if (hwcap & HWCAP_POWER6_EXT)
OPENSSL_ppccap_P |= PPC_FPU64;
}
}
if (hwcap & HWCAP_ALTIVEC) {
OPENSSL_ppccap_P |= PPC_ALTIVEC;
if ((hwcap & HWCAP_VSX) && (hwcap2 & HWCAP_VEC_CRYPTO))
OPENSSL_ppccap_P |= PPC_CRYPTO207;
}
if (hwcap2 & HWCAP_ARCH_3_00) {
OPENSSL_ppccap_P |= PPC_MADD300;
}
if (hwcap2 & HWCAP_ARCH_3_1) {
OPENSSL_ppccap_P |= PPC_BRD31;
}
}
#endif
sigfillset(&all_masked);
sigdelset(&all_masked, SIGILL);
sigdelset(&all_masked, SIGTRAP);
#ifdef SIGEMT
sigdelset(&all_masked, SIGEMT);
#endif
sigdelset(&all_masked, SIGFPE);
sigdelset(&all_masked, SIGBUS);
sigdelset(&all_masked, SIGSEGV);
memset(&ill_act, 0, sizeof(ill_act));
ill_act.sa_handler = ill_handler;
ill_act.sa_mask = all_masked;
sigprocmask(SIG_SETMASK, &ill_act.sa_mask, &oset);
sigaction(SIGILL, &ill_act, &ill_oact);
#ifndef OSSL_IMPLEMENT_GETAUXVAL
if (sigsetjmp(ill_jmp, 1) == 0) {
OPENSSL_fpu_probe();
OPENSSL_ppccap_P |= PPC_FPU;
if (sizeof(size_t) == 4) {
# ifdef __linux
struct utsname uts;
if (uname(&uts) == 0 && strcmp(uts.machine, "ppc64") == 0)
# endif
if (sigsetjmp(ill_jmp, 1) == 0) {
OPENSSL_ppc64_probe();
OPENSSL_ppccap_P |= PPC_FPU64;
}
} else {
/*
* Wanted code detecting POWER6 CPU and setting PPC_FPU64
*/
}
}
if (sigsetjmp(ill_jmp, 1) == 0) {
OPENSSL_altivec_probe();
OPENSSL_ppccap_P |= PPC_ALTIVEC;
if (sigsetjmp(ill_jmp, 1) == 0) {
OPENSSL_crypto207_probe();
OPENSSL_ppccap_P |= PPC_CRYPTO207;
}
}
if (sigsetjmp(ill_jmp, 1) == 0) {
OPENSSL_madd300_probe();
OPENSSL_ppccap_P |= PPC_MADD300;
}
#endif
if (sigsetjmp(ill_jmp, 1) == 0) {
OPENSSL_rdtsc_mftb();
OPENSSL_ppccap_P |= PPC_MFTB;
} else if (sigsetjmp(ill_jmp, 1) == 0) {
OPENSSL_rdtsc_mfspr268();
OPENSSL_ppccap_P |= PPC_MFSPR268;
}
sigaction(SIGILL, &ill_oact, NULL);
sigprocmask(SIG_SETMASK, &oset, NULL);
}
| 8,840 | 26.203077 | 77 | c |
openssl | openssl-master/crypto/provider.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 <string.h>
#include <openssl/err.h>
#include <openssl/cryptoerr.h>
#include <openssl/provider.h>
#include <openssl/core_names.h>
#include "internal/provider.h"
#include "provider_local.h"
OSSL_PROVIDER *OSSL_PROVIDER_try_load(OSSL_LIB_CTX *libctx, const char *name,
int retain_fallbacks)
{
OSSL_PROVIDER *prov = NULL, *actual;
int isnew = 0;
/* Find it or create it */
if ((prov = ossl_provider_find(libctx, name, 0)) == NULL) {
if ((prov = ossl_provider_new(libctx, name, NULL, 0)) == NULL)
return NULL;
isnew = 1;
}
if (!ossl_provider_activate(prov, 1, 0)) {
ossl_provider_free(prov);
return NULL;
}
actual = prov;
if (isnew && !ossl_provider_add_to_store(prov, &actual, retain_fallbacks)) {
ossl_provider_deactivate(prov, 1);
ossl_provider_free(prov);
return NULL;
}
if (actual != prov) {
if (!ossl_provider_activate(actual, 1, 0)) {
ossl_provider_free(actual);
return NULL;
}
}
return actual;
}
OSSL_PROVIDER *OSSL_PROVIDER_load(OSSL_LIB_CTX *libctx, const char *name)
{
/* Any attempt to load a provider disables auto-loading of defaults */
if (ossl_provider_disable_fallback_loading(libctx))
return OSSL_PROVIDER_try_load(libctx, name, 0);
return NULL;
}
int OSSL_PROVIDER_unload(OSSL_PROVIDER *prov)
{
if (!ossl_provider_deactivate(prov, 1))
return 0;
ossl_provider_free(prov);
return 1;
}
const OSSL_PARAM *OSSL_PROVIDER_gettable_params(const OSSL_PROVIDER *prov)
{
return ossl_provider_gettable_params(prov);
}
int OSSL_PROVIDER_get_params(const OSSL_PROVIDER *prov, OSSL_PARAM params[])
{
return ossl_provider_get_params(prov, params);
}
const OSSL_ALGORITHM *OSSL_PROVIDER_query_operation(const OSSL_PROVIDER *prov,
int operation_id,
int *no_cache)
{
return ossl_provider_query_operation(prov, operation_id, no_cache);
}
void OSSL_PROVIDER_unquery_operation(const OSSL_PROVIDER *prov,
int operation_id,
const OSSL_ALGORITHM *algs)
{
ossl_provider_unquery_operation(prov, operation_id, algs);
}
void *OSSL_PROVIDER_get0_provider_ctx(const OSSL_PROVIDER *prov)
{
return ossl_provider_prov_ctx(prov);
}
const OSSL_DISPATCH *OSSL_PROVIDER_get0_dispatch(const OSSL_PROVIDER *prov)
{
return ossl_provider_get0_dispatch(prov);
}
int OSSL_PROVIDER_self_test(const OSSL_PROVIDER *prov)
{
return ossl_provider_self_test(prov);
}
int OSSL_PROVIDER_get_capabilities(const OSSL_PROVIDER *prov,
const char *capability,
OSSL_CALLBACK *cb,
void *arg)
{
return ossl_provider_get_capabilities(prov, capability, cb, arg);
}
int OSSL_PROVIDER_add_builtin(OSSL_LIB_CTX *libctx, const char *name,
OSSL_provider_init_fn *init_fn)
{
OSSL_PROVIDER_INFO entry;
if (name == NULL || init_fn == NULL) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
memset(&entry, 0, sizeof(entry));
entry.name = OPENSSL_strdup(name);
if (entry.name == NULL)
return 0;
entry.init = init_fn;
if (!ossl_provider_info_add_to_store(libctx, &entry)) {
ossl_provider_info_clear(&entry);
return 0;
}
return 1;
}
const char *OSSL_PROVIDER_get0_name(const OSSL_PROVIDER *prov)
{
return ossl_provider_name(prov);
}
int OSSL_PROVIDER_do_all(OSSL_LIB_CTX *ctx,
int (*cb)(OSSL_PROVIDER *provider,
void *cbdata),
void *cbdata)
{
return ossl_provider_doall_activated(ctx, cb, cbdata);
}
| 4,280 | 27.925676 | 80 | c |
openssl | openssl-master/crypto/provider_child.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 <assert.h>
#include <openssl/crypto.h>
#include <openssl/core_dispatch.h>
#include <openssl/core_names.h>
#include <openssl/provider.h>
#include <openssl/evp.h>
#include "internal/provider.h"
#include "internal/cryptlib.h"
#include "crypto/evp.h"
#include "crypto/context.h"
DEFINE_STACK_OF(OSSL_PROVIDER)
struct child_prov_globals {
const OSSL_CORE_HANDLE *handle;
const OSSL_CORE_HANDLE *curr_prov;
CRYPTO_RWLOCK *lock;
OSSL_FUNC_core_get_libctx_fn *c_get_libctx;
OSSL_FUNC_provider_register_child_cb_fn *c_provider_register_child_cb;
OSSL_FUNC_provider_deregister_child_cb_fn *c_provider_deregister_child_cb;
OSSL_FUNC_provider_name_fn *c_prov_name;
OSSL_FUNC_provider_get0_provider_ctx_fn *c_prov_get0_provider_ctx;
OSSL_FUNC_provider_get0_dispatch_fn *c_prov_get0_dispatch;
OSSL_FUNC_provider_up_ref_fn *c_prov_up_ref;
OSSL_FUNC_provider_free_fn *c_prov_free;
};
void *ossl_child_prov_ctx_new(OSSL_LIB_CTX *libctx)
{
return OPENSSL_zalloc(sizeof(struct child_prov_globals));
}
void ossl_child_prov_ctx_free(void *vgbl)
{
struct child_prov_globals *gbl = vgbl;
CRYPTO_THREAD_lock_free(gbl->lock);
OPENSSL_free(gbl);
}
static OSSL_provider_init_fn ossl_child_provider_init;
static int ossl_child_provider_init(const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in,
const OSSL_DISPATCH **out,
void **provctx)
{
OSSL_FUNC_core_get_libctx_fn *c_get_libctx = NULL;
OSSL_LIB_CTX *ctx;
struct child_prov_globals *gbl;
for (; in->function_id != 0; in++) {
switch (in->function_id) {
case OSSL_FUNC_CORE_GET_LIBCTX:
c_get_libctx = OSSL_FUNC_core_get_libctx(in);
break;
default:
/* Just ignore anything we don't understand */
break;
}
}
if (c_get_libctx == NULL)
return 0;
/*
* We need an OSSL_LIB_CTX but c_get_libctx returns OPENSSL_CORE_CTX. We are
* a built-in provider and so we can get away with this cast. Normal
* providers can't do this.
*/
ctx = (OSSL_LIB_CTX *)c_get_libctx(handle);
gbl = ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_CHILD_PROVIDER_INDEX);
if (gbl == NULL)
return 0;
*provctx = gbl->c_prov_get0_provider_ctx(gbl->curr_prov);
*out = gbl->c_prov_get0_dispatch(gbl->curr_prov);
return 1;
}
static int provider_create_child_cb(const OSSL_CORE_HANDLE *prov, void *cbdata)
{
OSSL_LIB_CTX *ctx = cbdata;
struct child_prov_globals *gbl;
const char *provname;
OSSL_PROVIDER *cprov;
int ret = 0;
gbl = ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_CHILD_PROVIDER_INDEX);
if (gbl == NULL)
return 0;
if (!CRYPTO_THREAD_write_lock(gbl->lock))
return 0;
provname = gbl->c_prov_name(prov);
/*
* We're operating under a lock so we can store the "current" provider in
* the global data.
*/
gbl->curr_prov = prov;
if ((cprov = ossl_provider_find(ctx, provname, 1)) != NULL) {
/*
* We free the newly created ref. We rely on the provider sticking around
* in the provider store.
*/
ossl_provider_free(cprov);
/*
* The provider already exists. It could be a previously created child,
* or it could have been explicitly loaded. If explicitly loaded we
* ignore it - i.e. we don't start treating it like a child.
*/
if (!ossl_provider_activate(cprov, 0, 1))
goto err;
} else {
/*
* Create it - passing 1 as final param so we don't try and recursively
* init children
*/
if ((cprov = ossl_provider_new(ctx, provname, ossl_child_provider_init,
1)) == NULL)
goto err;
if (!ossl_provider_activate(cprov, 0, 0)) {
ossl_provider_free(cprov);
goto err;
}
if (!ossl_provider_set_child(cprov, prov)
|| !ossl_provider_add_to_store(cprov, NULL, 0)) {
ossl_provider_deactivate(cprov, 0);
ossl_provider_free(cprov);
goto err;
}
}
ret = 1;
err:
CRYPTO_THREAD_unlock(gbl->lock);
return ret;
}
static int provider_remove_child_cb(const OSSL_CORE_HANDLE *prov, void *cbdata)
{
OSSL_LIB_CTX *ctx = cbdata;
struct child_prov_globals *gbl;
const char *provname;
OSSL_PROVIDER *cprov;
gbl = ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_CHILD_PROVIDER_INDEX);
if (gbl == NULL)
return 0;
provname = gbl->c_prov_name(prov);
cprov = ossl_provider_find(ctx, provname, 1);
if (cprov == NULL)
return 0;
/*
* ossl_provider_find ups the ref count, so we free it again here. We can
* rely on the provider store reference count.
*/
ossl_provider_free(cprov);
if (ossl_provider_is_child(cprov)
&& !ossl_provider_deactivate(cprov, 1))
return 0;
return 1;
}
static int provider_global_props_cb(const char *props, void *cbdata)
{
OSSL_LIB_CTX *ctx = cbdata;
return evp_set_default_properties_int(ctx, props, 0, 1);
}
int ossl_provider_init_as_child(OSSL_LIB_CTX *ctx,
const OSSL_CORE_HANDLE *handle,
const OSSL_DISPATCH *in)
{
struct child_prov_globals *gbl;
if (ctx == NULL)
return 0;
gbl = ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_CHILD_PROVIDER_INDEX);
if (gbl == NULL)
return 0;
gbl->handle = handle;
for (; in->function_id != 0; in++) {
switch (in->function_id) {
case OSSL_FUNC_CORE_GET_LIBCTX:
gbl->c_get_libctx = OSSL_FUNC_core_get_libctx(in);
break;
case OSSL_FUNC_PROVIDER_REGISTER_CHILD_CB:
gbl->c_provider_register_child_cb
= OSSL_FUNC_provider_register_child_cb(in);
break;
case OSSL_FUNC_PROVIDER_DEREGISTER_CHILD_CB:
gbl->c_provider_deregister_child_cb
= OSSL_FUNC_provider_deregister_child_cb(in);
break;
case OSSL_FUNC_PROVIDER_NAME:
gbl->c_prov_name = OSSL_FUNC_provider_name(in);
break;
case OSSL_FUNC_PROVIDER_GET0_PROVIDER_CTX:
gbl->c_prov_get0_provider_ctx
= OSSL_FUNC_provider_get0_provider_ctx(in);
break;
case OSSL_FUNC_PROVIDER_GET0_DISPATCH:
gbl->c_prov_get0_dispatch = OSSL_FUNC_provider_get0_dispatch(in);
break;
case OSSL_FUNC_PROVIDER_UP_REF:
gbl->c_prov_up_ref
= OSSL_FUNC_provider_up_ref(in);
break;
case OSSL_FUNC_PROVIDER_FREE:
gbl->c_prov_free = OSSL_FUNC_provider_free(in);
break;
default:
/* Just ignore anything we don't understand */
break;
}
}
if (gbl->c_get_libctx == NULL
|| gbl->c_provider_register_child_cb == NULL
|| gbl->c_prov_name == NULL
|| gbl->c_prov_get0_provider_ctx == NULL
|| gbl->c_prov_get0_dispatch == NULL
|| gbl->c_prov_up_ref == NULL
|| gbl->c_prov_free == NULL)
return 0;
gbl->lock = CRYPTO_THREAD_lock_new();
if (gbl->lock == NULL)
return 0;
if (!gbl->c_provider_register_child_cb(gbl->handle,
provider_create_child_cb,
provider_remove_child_cb,
provider_global_props_cb,
ctx))
return 0;
return 1;
}
void ossl_provider_deinit_child(OSSL_LIB_CTX *ctx)
{
struct child_prov_globals *gbl
= ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_CHILD_PROVIDER_INDEX);
if (gbl == NULL)
return;
gbl->c_provider_deregister_child_cb(gbl->handle);
}
/*
* ossl_provider_up_ref_parent() and ossl_provider_free_parent() do
* nothing in "self-referencing" child providers, i.e. when the parent
* of the child provider is the same as the provider where this child
* provider was created.
* This allows the teardown function in the parent provider to be called
* at the correct moment.
* For child providers in other providers, the reference count is done to
* ensure that cross referencing is recorded. These should be cleared up
* through that providers teardown, as part of freeing its child libctx.
*/
int ossl_provider_up_ref_parent(OSSL_PROVIDER *prov, int activate)
{
struct child_prov_globals *gbl;
const OSSL_CORE_HANDLE *parent_handle;
gbl = ossl_lib_ctx_get_data(ossl_provider_libctx(prov),
OSSL_LIB_CTX_CHILD_PROVIDER_INDEX);
if (gbl == NULL)
return 0;
parent_handle = ossl_provider_get_parent(prov);
if (parent_handle == gbl->handle)
return 1;
return gbl->c_prov_up_ref(parent_handle, activate);
}
int ossl_provider_free_parent(OSSL_PROVIDER *prov, int deactivate)
{
struct child_prov_globals *gbl;
const OSSL_CORE_HANDLE *parent_handle;
gbl = ossl_lib_ctx_get_data(ossl_provider_libctx(prov),
OSSL_LIB_CTX_CHILD_PROVIDER_INDEX);
if (gbl == NULL)
return 0;
parent_handle = ossl_provider_get_parent(prov);
if (parent_handle == gbl->handle)
return 1;
return gbl->c_prov_free(ossl_provider_get_parent(prov), deactivate);
}
| 9,914 | 30.277603 | 81 | c |
openssl | openssl-master/crypto/provider_conf.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 <string.h>
#include <openssl/trace.h>
#include <openssl/err.h>
#include <openssl/conf.h>
#include <openssl/safestack.h>
#include <openssl/provider.h>
#include "internal/provider.h"
#include "internal/cryptlib.h"
#include "provider_local.h"
#include "crypto/context.h"
DEFINE_STACK_OF(OSSL_PROVIDER)
/* PROVIDER config module */
typedef struct {
CRYPTO_RWLOCK *lock;
STACK_OF(OSSL_PROVIDER) *activated_providers;
} PROVIDER_CONF_GLOBAL;
void *ossl_prov_conf_ctx_new(OSSL_LIB_CTX *libctx)
{
PROVIDER_CONF_GLOBAL *pcgbl = OPENSSL_zalloc(sizeof(*pcgbl));
if (pcgbl == NULL)
return NULL;
pcgbl->lock = CRYPTO_THREAD_lock_new();
if (pcgbl->lock == NULL) {
OPENSSL_free(pcgbl);
return NULL;
}
return pcgbl;
}
void ossl_prov_conf_ctx_free(void *vpcgbl)
{
PROVIDER_CONF_GLOBAL *pcgbl = vpcgbl;
sk_OSSL_PROVIDER_pop_free(pcgbl->activated_providers,
ossl_provider_free);
OSSL_TRACE(CONF, "Cleaned up providers\n");
CRYPTO_THREAD_lock_free(pcgbl->lock);
OPENSSL_free(pcgbl);
}
static const char *skip_dot(const char *name)
{
const char *p = strchr(name, '.');
if (p != NULL)
return p + 1;
return name;
}
static int provider_conf_params(OSSL_PROVIDER *prov,
OSSL_PROVIDER_INFO *provinfo,
const char *name, const char *value,
const CONF *cnf)
{
STACK_OF(CONF_VALUE) *sect;
int ok = 1;
sect = NCONF_get_section(cnf, value);
if (sect != NULL) {
int i;
char buffer[512];
size_t buffer_len = 0;
OSSL_TRACE1(CONF, "Provider params: start section %s\n", value);
if (name != NULL) {
OPENSSL_strlcpy(buffer, name, sizeof(buffer));
OPENSSL_strlcat(buffer, ".", sizeof(buffer));
buffer_len = strlen(buffer);
}
for (i = 0; i < sk_CONF_VALUE_num(sect); i++) {
CONF_VALUE *sectconf = sk_CONF_VALUE_value(sect, i);
if (buffer_len + strlen(sectconf->name) >= sizeof(buffer))
return 0;
buffer[buffer_len] = '\0';
OPENSSL_strlcat(buffer, sectconf->name, sizeof(buffer));
if (!provider_conf_params(prov, provinfo, buffer, sectconf->value,
cnf))
return 0;
}
OSSL_TRACE1(CONF, "Provider params: finish section %s\n", value);
} else {
OSSL_TRACE2(CONF, "Provider params: %s = %s\n", name, value);
if (prov != NULL)
ok = ossl_provider_add_parameter(prov, name, value);
else
ok = ossl_provider_info_add_parameter(provinfo, name, value);
}
return ok;
}
static int prov_already_activated(const char *name,
STACK_OF(OSSL_PROVIDER) *activated)
{
int i, max;
if (activated == NULL)
return 0;
max = sk_OSSL_PROVIDER_num(activated);
for (i = 0; i < max; i++) {
OSSL_PROVIDER *tstprov = sk_OSSL_PROVIDER_value(activated, i);
if (strcmp(OSSL_PROVIDER_get0_name(tstprov), name) == 0) {
return 1;
}
}
return 0;
}
static int provider_conf_activate(OSSL_LIB_CTX *libctx, const char *name,
const char *value, const char *path,
int soft, const CONF *cnf)
{
PROVIDER_CONF_GLOBAL *pcgbl
= ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_PROVIDER_CONF_INDEX);
OSSL_PROVIDER *prov = NULL, *actual = NULL;
int ok = 0;
if (pcgbl == NULL || !CRYPTO_THREAD_write_lock(pcgbl->lock)) {
ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
return 0;
}
if (!prov_already_activated(name, pcgbl->activated_providers)) {
/*
* There is an attempt to activate a provider, so we should disable
* loading of fallbacks. Otherwise a misconfiguration could mean the
* intended provider does not get loaded. Subsequent fetches could
* then fallback to the default provider - which may be the wrong
* thing.
*/
if (!ossl_provider_disable_fallback_loading(libctx)) {
CRYPTO_THREAD_unlock(pcgbl->lock);
ERR_raise(ERR_LIB_CRYPTO, ERR_R_INTERNAL_ERROR);
return 0;
}
prov = ossl_provider_find(libctx, name, 1);
if (prov == NULL)
prov = ossl_provider_new(libctx, name, NULL, 1);
if (prov == NULL) {
CRYPTO_THREAD_unlock(pcgbl->lock);
if (soft)
ERR_clear_error();
return 0;
}
if (path != NULL)
ossl_provider_set_module_path(prov, path);
ok = provider_conf_params(prov, NULL, NULL, value, cnf);
if (ok) {
if (!ossl_provider_activate(prov, 1, 0)) {
ok = 0;
} else if (!ossl_provider_add_to_store(prov, &actual, 0)) {
ossl_provider_deactivate(prov, 1);
ok = 0;
} else if (actual != prov
&& !ossl_provider_activate(actual, 1, 0)) {
ossl_provider_free(actual);
ok = 0;
} else {
if (pcgbl->activated_providers == NULL)
pcgbl->activated_providers = sk_OSSL_PROVIDER_new_null();
if (pcgbl->activated_providers == NULL
|| !sk_OSSL_PROVIDER_push(pcgbl->activated_providers,
actual)) {
ossl_provider_deactivate(actual, 1);
ossl_provider_free(actual);
ok = 0;
} else {
ok = 1;
}
}
}
if (!ok)
ossl_provider_free(prov);
}
CRYPTO_THREAD_unlock(pcgbl->lock);
return ok;
}
static int provider_conf_load(OSSL_LIB_CTX *libctx, const char *name,
const char *value, const CONF *cnf)
{
int i;
STACK_OF(CONF_VALUE) *ecmds;
int soft = 0;
const char *path = NULL;
long activate = 0;
int ok = 0;
name = skip_dot(name);
OSSL_TRACE1(CONF, "Configuring provider %s\n", name);
/* Value is a section containing PROVIDER commands */
ecmds = NCONF_get_section(cnf, value);
if (!ecmds) {
ERR_raise_data(ERR_LIB_CRYPTO, CRYPTO_R_PROVIDER_SECTION_ERROR,
"section=%s not found", value);
return 0;
}
/* Find the needed data first */
for (i = 0; i < sk_CONF_VALUE_num(ecmds); i++) {
CONF_VALUE *ecmd = sk_CONF_VALUE_value(ecmds, i);
const char *confname = skip_dot(ecmd->name);
const char *confvalue = ecmd->value;
OSSL_TRACE2(CONF, "Provider command: %s = %s\n",
confname, confvalue);
/* First handle some special pseudo confs */
/* Override provider name to use */
if (strcmp(confname, "identity") == 0)
name = confvalue;
else if (strcmp(confname, "soft_load") == 0)
soft = 1;
/* Load a dynamic PROVIDER */
else if (strcmp(confname, "module") == 0)
path = confvalue;
else if (strcmp(confname, "activate") == 0)
activate = 1;
}
if (activate) {
ok = provider_conf_activate(libctx, name, value, path, soft, cnf);
} else {
OSSL_PROVIDER_INFO entry;
memset(&entry, 0, sizeof(entry));
ok = 1;
if (name != NULL) {
entry.name = OPENSSL_strdup(name);
if (entry.name == NULL)
ok = 0;
}
if (ok && path != NULL) {
entry.path = OPENSSL_strdup(path);
if (entry.path == NULL)
ok = 0;
}
if (ok)
ok = provider_conf_params(NULL, &entry, NULL, value, cnf);
if (ok && (entry.path != NULL || entry.parameters != NULL))
ok = ossl_provider_info_add_to_store(libctx, &entry);
if (!ok || (entry.path == NULL && entry.parameters == NULL)) {
ossl_provider_info_clear(&entry);
}
}
/*
* Even if ok is 0, we still return success. Failure to load a provider is
* not fatal. We want to continue to load the rest of the config file.
*/
return 1;
}
static int provider_conf_init(CONF_IMODULE *md, const CONF *cnf)
{
STACK_OF(CONF_VALUE) *elist;
CONF_VALUE *cval;
int i;
OSSL_TRACE1(CONF, "Loading providers module: section %s\n",
CONF_imodule_get_value(md));
/* Value is a section containing PROVIDERs to configure */
elist = NCONF_get_section(cnf, CONF_imodule_get_value(md));
if (!elist) {
ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_PROVIDER_SECTION_ERROR);
return 0;
}
for (i = 0; i < sk_CONF_VALUE_num(elist); i++) {
cval = sk_CONF_VALUE_value(elist, i);
if (!provider_conf_load(NCONF_get0_libctx((CONF *)cnf),
cval->name, cval->value, cnf))
return 0;
}
return 1;
}
void ossl_provider_add_conf_module(void)
{
OSSL_TRACE(CONF, "Adding config module 'providers'\n");
CONF_module_add("providers", provider_conf_init, NULL);
}
| 9,642 | 29.515823 | 78 | c |
openssl | openssl-master/crypto/provider_local.h | /*
* 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/core.h>
typedef struct {
char *name;
char *value;
} INFOPAIR;
DEFINE_STACK_OF(INFOPAIR)
typedef struct {
char *name;
char *path;
OSSL_provider_init_fn *init;
STACK_OF(INFOPAIR) *parameters;
unsigned int is_fallback:1;
} OSSL_PROVIDER_INFO;
extern const OSSL_PROVIDER_INFO ossl_predefined_providers[];
void ossl_provider_info_clear(OSSL_PROVIDER_INFO *info);
int ossl_provider_info_add_to_store(OSSL_LIB_CTX *libctx,
OSSL_PROVIDER_INFO *entry);
int ossl_provider_info_add_parameter(OSSL_PROVIDER_INFO *provinfo,
const char *name,
const char *value);
| 1,046 | 29.794118 | 74 | h |
openssl | openssl-master/crypto/provider_predefined.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/core.h>
#include "provider_local.h"
OSSL_provider_init_fn ossl_default_provider_init;
OSSL_provider_init_fn ossl_base_provider_init;
OSSL_provider_init_fn ossl_null_provider_init;
OSSL_provider_init_fn ossl_fips_intern_provider_init;
#ifdef STATIC_LEGACY
OSSL_provider_init_fn ossl_legacy_provider_init;
#endif
const OSSL_PROVIDER_INFO ossl_predefined_providers[] = {
#ifdef FIPS_MODULE
{ "fips", NULL, ossl_fips_intern_provider_init, NULL, 1 },
#else
{ "default", NULL, ossl_default_provider_init, NULL, 1 },
# ifdef STATIC_LEGACY
{ "legacy", NULL, ossl_legacy_provider_init, NULL, 0 },
# endif
{ "base", NULL, ossl_base_provider_init, NULL, 0 },
{ "null", NULL, ossl_null_provider_init, NULL, 0 },
#endif
{ NULL, NULL, NULL, NULL, 0 }
};
| 1,120 | 32.969697 | 74 | c |
openssl | openssl-master/crypto/punycode.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 <stddef.h>
#include <stdio.h>
#include <openssl/e_os2.h>
#include "crypto/punycode.h"
#include "internal/common.h" /* for HAS_PREFIX */
#include "internal/packet.h" /* for WPACKET */
static const unsigned int base = 36;
static const unsigned int tmin = 1;
static const unsigned int tmax = 26;
static const unsigned int skew = 38;
static const unsigned int damp = 700;
static const unsigned int initial_bias = 72;
static const unsigned int initial_n = 0x80;
static const unsigned int maxint = 0xFFFFFFFF;
static const char delimiter = '-';
#define LABEL_BUF_SIZE 512
/*-
* Pseudocode:
*
* function adapt(delta,numpoints,firsttime):
* if firsttime then let delta = delta div damp
* else let delta = delta div 2
* let delta = delta + (delta div numpoints)
* let k = 0
* while delta > ((base - tmin) * tmax) div 2 do begin
* let delta = delta div (base - tmin)
* let k = k + base
* end
* return k + (((base - tmin + 1) * delta) div (delta + skew))
*/
static int adapt(unsigned int delta, unsigned int numpoints,
unsigned int firsttime)
{
unsigned int k = 0;
delta = (firsttime) ? delta / damp : delta / 2;
delta = delta + delta / numpoints;
while (delta > ((base - tmin) * tmax) / 2) {
delta = delta / (base - tmin);
k = k + base;
}
return k + (((base - tmin + 1) * delta) / (delta + skew));
}
static ossl_inline int is_basic(unsigned int a)
{
return (a < 0x80) ? 1 : 0;
}
/*-
* code points digit-values
* ------------ ----------------------
* 41..5A (A-Z) = 0 to 25, respectively
* 61..7A (a-z) = 0 to 25, respectively
* 30..39 (0-9) = 26 to 35, respectively
*/
static ossl_inline int digit_decoded(const unsigned char a)
{
if (a >= 0x41 && a <= 0x5A)
return a - 0x41;
if (a >= 0x61 && a <= 0x7A)
return a - 0x61;
if (a >= 0x30 && a <= 0x39)
return a - 0x30 + 26;
return -1;
}
/*-
* Pseudocode:
*
* function ossl_punycode_decode
* let n = initial_n
* let i = 0
* let bias = initial_bias
* let output = an empty string indexed from 0
* consume all code points before the last delimiter (if there is one)
* and copy them to output, fail on any non-basic code point
* if more than zero code points were consumed then consume one more
* (which will be the last delimiter)
* while the input is not exhausted do begin
* let oldi = i
* let w = 1
* for k = base to infinity in steps of base do begin
* consume a code point, or fail if there was none to consume
* let digit = the code point's digit-value, fail if it has none
* let i = i + digit * w, fail on overflow
* let t = tmin if k <= bias {+ tmin}, or
* tmax if k >= bias + tmax, or k - bias otherwise
* if digit < t then break
* let w = w * (base - t), fail on overflow
* end
* let bias = adapt(i - oldi, length(output) + 1, test oldi is 0?)
* let n = n + i div (length(output) + 1), fail on overflow
* let i = i mod (length(output) + 1)
* {if n is a basic code point then fail}
* insert n into output at position i
* increment i
* end
*/
int ossl_punycode_decode(const char *pEncoded, const size_t enc_len,
unsigned int *pDecoded, unsigned int *pout_length)
{
unsigned int n = initial_n;
unsigned int i = 0;
unsigned int bias = initial_bias;
size_t processed_in = 0, written_out = 0;
unsigned int max_out = *pout_length;
unsigned int basic_count = 0;
unsigned int loop;
for (loop = 0; loop < enc_len; loop++) {
if (pEncoded[loop] == delimiter)
basic_count = loop;
}
if (basic_count > 0) {
if (basic_count > max_out)
return 0;
for (loop = 0; loop < basic_count; loop++) {
if (is_basic(pEncoded[loop]) == 0)
return 0;
pDecoded[loop] = pEncoded[loop];
written_out++;
}
processed_in = basic_count + 1;
}
for (loop = processed_in; loop < enc_len;) {
unsigned int oldi = i;
unsigned int w = 1;
unsigned int k, t;
int digit;
for (k = base;; k += base) {
if (loop >= enc_len)
return 0;
digit = digit_decoded(pEncoded[loop]);
loop++;
if (digit < 0)
return 0;
if ((unsigned int)digit > (maxint - i) / w)
return 0;
i = i + digit * w;
t = (k <= bias) ? tmin : (k >= bias + tmax) ? tmax : k - bias;
if ((unsigned int)digit < t)
break;
if (w > maxint / (base - t))
return 0;
w = w * (base - t);
}
bias = adapt(i - oldi, written_out + 1, (oldi == 0));
if (i / (written_out + 1) > maxint - n)
return 0;
n = n + i / (written_out + 1);
i %= (written_out + 1);
if (written_out >= max_out)
return 0;
memmove(pDecoded + i + 1, pDecoded + i,
(written_out - i) * sizeof(*pDecoded));
pDecoded[i] = n;
i++;
written_out++;
}
*pout_length = written_out;
return 1;
}
/*
* Encode a code point using UTF-8
* return number of bytes on success, 0 on failure
* (also produces U+FFFD, which uses 3 bytes on failure)
*/
static int codepoint2utf8(unsigned char *out, unsigned long utf)
{
if (utf <= 0x7F) {
/* Plain ASCII */
out[0] = (unsigned char)utf;
out[1] = 0;
return 1;
} else if (utf <= 0x07FF) {
/* 2-byte unicode */
out[0] = (unsigned char)(((utf >> 6) & 0x1F) | 0xC0);
out[1] = (unsigned char)(((utf >> 0) & 0x3F) | 0x80);
out[2] = 0;
return 2;
} else if (utf <= 0xFFFF) {
/* 3-byte unicode */
out[0] = (unsigned char)(((utf >> 12) & 0x0F) | 0xE0);
out[1] = (unsigned char)(((utf >> 6) & 0x3F) | 0x80);
out[2] = (unsigned char)(((utf >> 0) & 0x3F) | 0x80);
out[3] = 0;
return 3;
} else if (utf <= 0x10FFFF) {
/* 4-byte unicode */
out[0] = (unsigned char)(((utf >> 18) & 0x07) | 0xF0);
out[1] = (unsigned char)(((utf >> 12) & 0x3F) | 0x80);
out[2] = (unsigned char)(((utf >> 6) & 0x3F) | 0x80);
out[3] = (unsigned char)(((utf >> 0) & 0x3F) | 0x80);
out[4] = 0;
return 4;
} else {
/* error - use replacement character */
out[0] = (unsigned char)0xEF;
out[1] = (unsigned char)0xBF;
out[2] = (unsigned char)0xBD;
out[3] = 0;
return 0;
}
}
/*-
* Return values:
* 1 - ok
* 0 - ok but buf was too short
* -1 - bad string passed or other error
*/
int ossl_a2ulabel(const char *in, char *out, size_t outlen)
{
/*-
* Domain name has some parts consisting of ASCII chars joined with dot.
* If a part is shorter than 5 chars, it becomes U-label as is.
* If it does not start with xn--, it becomes U-label as is.
* Otherwise we try to decode it.
*/
const char *inptr = in;
int result = 1;
unsigned int i;
unsigned int buf[LABEL_BUF_SIZE]; /* It's a hostname */
WPACKET pkt;
/* Internal API, so should not fail */
if (!ossl_assert(out != NULL))
return -1;
if (!WPACKET_init_static_len(&pkt, (unsigned char *)out, outlen, 0))
return -1;
while (1) {
char *tmpptr = strchr(inptr, '.');
size_t delta = tmpptr != NULL ? (size_t)(tmpptr - inptr) : strlen(inptr);
if (!HAS_PREFIX(inptr, "xn--")) {
if (!WPACKET_memcpy(&pkt, inptr, delta))
result = 0;
} else {
unsigned int bufsize = LABEL_BUF_SIZE;
if (ossl_punycode_decode(inptr + 4, delta - 4, buf, &bufsize) <= 0) {
result = -1;
goto end;
}
for (i = 0; i < bufsize; i++) {
unsigned char seed[6];
size_t utfsize = codepoint2utf8(seed, buf[i]);
if (utfsize == 0) {
result = -1;
goto end;
}
if (!WPACKET_memcpy(&pkt, seed, utfsize))
result = 0;
}
}
if (tmpptr == NULL)
break;
if (!WPACKET_put_bytes_u8(&pkt, '.'))
result = 0;
inptr = tmpptr + 1;
}
if (!WPACKET_put_bytes_u8(&pkt, '\0'))
result = 0;
end:
WPACKET_cleanup(&pkt);
return result;
}
| 8,922 | 27.507987 | 81 | c |
openssl | openssl-master/crypto/quic_vlint.c | #include "internal/quic_vlint.h"
#include "internal/e_os.h"
#ifndef OPENSSL_NO_QUIC
void ossl_quic_vlint_encode_n(uint8_t *buf, uint64_t v, int n)
{
if (n == 1) {
buf[0] = (uint8_t)v;
} else if (n == 2) {
buf[0] = (uint8_t)(0x40 | ((v >> 8) & 0x3F));
buf[1] = (uint8_t)v;
} else if (n == 4) {
buf[0] = (uint8_t)(0x80 | ((v >> 24) & 0x3F));
buf[1] = (uint8_t)(v >> 16);
buf[2] = (uint8_t)(v >> 8);
buf[3] = (uint8_t)v;
} else {
buf[0] = (uint8_t)(0xC0 | ((v >> 56) & 0x3F));
buf[1] = (uint8_t)(v >> 48);
buf[2] = (uint8_t)(v >> 40);
buf[3] = (uint8_t)(v >> 32);
buf[4] = (uint8_t)(v >> 24);
buf[5] = (uint8_t)(v >> 16);
buf[6] = (uint8_t)(v >> 8);
buf[7] = (uint8_t)v;
}
}
void ossl_quic_vlint_encode(uint8_t *buf, uint64_t v)
{
ossl_quic_vlint_encode_n(buf, v, ossl_quic_vlint_encode_len(v));
}
uint64_t ossl_quic_vlint_decode_unchecked(const unsigned char *buf)
{
uint8_t first_byte = buf[0];
size_t sz = ossl_quic_vlint_decode_len(first_byte);
if (sz == 1)
return first_byte & 0x3F;
if (sz == 2)
return ((uint64_t)(first_byte & 0x3F) << 8)
| buf[1];
if (sz == 4)
return ((uint64_t)(first_byte & 0x3F) << 24)
| ((uint64_t)buf[1] << 16)
| ((uint64_t)buf[2] << 8)
| buf[3];
return ((uint64_t)(first_byte & 0x3F) << 56)
| ((uint64_t)buf[1] << 48)
| ((uint64_t)buf[2] << 40)
| ((uint64_t)buf[3] << 32)
| ((uint64_t)buf[4] << 24)
| ((uint64_t)buf[5] << 16)
| ((uint64_t)buf[6] << 8)
| buf[7];
}
int ossl_quic_vlint_decode(const unsigned char *buf, size_t buf_len, uint64_t *v)
{
size_t dec_len;
uint64_t x;
if (buf_len < 1)
return 0;
dec_len = ossl_quic_vlint_decode_len(buf[0]);
if (buf_len < dec_len)
return 0;
x = ossl_quic_vlint_decode_unchecked(buf);
*v = x;
return dec_len;
}
#endif
| 2,060 | 24.134146 | 81 | c |
openssl | openssl-master/crypto/riscvcap.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 <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdint.h>
#include <openssl/crypto.h>
#include "internal/cryptlib.h"
#define OPENSSL_RISCVCAP_IMPL
#include "crypto/riscv_arch.h"
static void parse_env(const char *envstr);
static void strtoupper(char *str);
uint32_t OPENSSL_rdtsc(void)
{
return 0;
}
size_t OPENSSL_instrument_bus(unsigned int *out, size_t cnt)
{
return 0;
}
size_t OPENSSL_instrument_bus2(unsigned int *out, size_t cnt, size_t max)
{
return 0;
}
static void strtoupper(char *str)
{
for (char *x = str; *x; ++x)
*x = toupper(*x);
}
/* parse_env() parses a RISC-V architecture string. An example of such a string
* is "rv64gc_zba_zbb_zbc_zbs". Currently, the rv64gc part is ignored
* and we simply search for "_[extension]" in the arch string to see if we
* should enable a given extension.
*/
#define BUFLEN 256
static void parse_env(const char *envstr)
{
char envstrupper[BUFLEN];
char buf[BUFLEN];
/* Convert env str to all uppercase */
OPENSSL_strlcpy(envstrupper, envstr, sizeof(envstrupper));
strtoupper(envstrupper);
for (size_t i = 0; i < kRISCVNumCaps; ++i) {
/* Prefix capability with underscore in preparation for search */
BIO_snprintf(buf, BUFLEN, "_%s", RISCV_capabilities[i].name);
if (strstr(envstrupper, buf) != NULL) {
/* Match, set relevant bit in OPENSSL_riscvcap_P[] */
OPENSSL_riscvcap_P[RISCV_capabilities[i].index] |=
(1 << RISCV_capabilities[i].bit_offset);
}
}
}
# if defined(__GNUC__) && __GNUC__>=2
__attribute__ ((constructor))
# endif
void OPENSSL_cpuid_setup(void)
{
char *e;
static int trigger = 0;
if (trigger != 0)
return;
trigger = 1;
if ((e = getenv("OPENSSL_riscvcap"))) {
parse_env(e);
return;
}
}
| 2,191 | 24.195402 | 79 | c |
openssl | openssl-master/crypto/s390x_arch.h | /*
* Copyright 2017-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_CRYPTO_S390X_ARCH_H
# define OSSL_CRYPTO_S390X_ARCH_H
# ifndef __ASSEMBLER__
#include "crypto/bn.h"
void s390x_kimd(const unsigned char *in, size_t len, unsigned int fc,
void *param);
void s390x_klmd(const unsigned char *in, size_t inlen, unsigned char *out,
size_t outlen, unsigned int fc, void *param);
void s390x_km(const unsigned char *in, size_t len, unsigned char *out,
unsigned int fc, void *param);
void s390x_kmac(const unsigned char *in, size_t len, unsigned int fc,
void *param);
void s390x_kmo(const unsigned char *in, size_t len, unsigned char *out,
unsigned int fc, void *param);
void s390x_kmf(const unsigned char *in, size_t len, unsigned char *out,
unsigned int fc, void *param);
void s390x_kma(const unsigned char *aad, size_t alen, const unsigned char *in,
size_t len, unsigned char *out, unsigned int fc, void *param);
int s390x_pcc(unsigned int fc, void *param);
int s390x_kdsa(unsigned int fc, void *param, const unsigned char *in,
size_t len);
void s390x_flip_endian32(unsigned char dst[32], const unsigned char src[32]);
void s390x_flip_endian64(unsigned char dst[64], const unsigned char src[64]);
int s390x_x25519_mul(unsigned char u_dst[32],
const unsigned char u_src[32],
const unsigned char d_src[32]);
int s390x_x448_mul(unsigned char u_dst[56],
const unsigned char u_src[56],
const unsigned char d_src[56]);
int s390x_ed25519_mul(unsigned char x_dst[32],
unsigned char y_dst[32],
const unsigned char x_src[32],
const unsigned char y_src[32],
const unsigned char d_src[32]);
int s390x_ed448_mul(unsigned char x_dst[57],
unsigned char y_dst[57],
const unsigned char x_src[57],
const unsigned char y_src[57],
const unsigned char d_src[57]);
/*
* The field elements of OPENSSL_s390xcap_P are the 64-bit words returned by
* the STFLE instruction followed by the 64-bit word pairs returned by
* instructions' QUERY functions. If STFLE returns fewer data or an instruction
* is not supported, the corresponding field elements are zero.
*/
struct OPENSSL_s390xcap_st {
unsigned long long stfle[4];
unsigned long long kimd[2];
unsigned long long klmd[2];
unsigned long long km[2];
unsigned long long kmc[2];
unsigned long long kmac[2];
unsigned long long kmctr[2];
unsigned long long kmo[2];
unsigned long long kmf[2];
unsigned long long prno[2];
unsigned long long kma[2];
unsigned long long pcc[2];
unsigned long long kdsa[2];
};
#if defined(__GNUC__) && defined(__linux)
__attribute__ ((visibility("hidden")))
#endif
extern struct OPENSSL_s390xcap_st OPENSSL_s390xcap_P;
#ifdef S390X_MOD_EXP
# if defined(__GNUC__) && defined(__linux)
__attribute__ ((visibility("hidden")))
# endif
extern int OPENSSL_s390xcex;
#endif
/* Max number of 64-bit words currently returned by STFLE */
# define S390X_STFLE_MAX 3
/* convert facility bit number or function code to bit mask */
# define S390X_CAPBIT(i) (1ULL << (63 - (i) % 64))
# endif
/* OPENSSL_s390xcap_P offsets [bytes] */
# define S390X_STFLE 0x00
# define S390X_KIMD 0x20
# define S390X_KLMD 0x30
# define S390X_KM 0x40
# define S390X_KMC 0x50
# define S390X_KMAC 0x60
# define S390X_KMCTR 0x70
# define S390X_KMO 0x80
# define S390X_KMF 0x90
# define S390X_PRNO 0xa0
# define S390X_KMA 0xb0
# define S390X_PCC 0xc0
# define S390X_KDSA 0xd0
/* Facility Bit Numbers */
# define S390X_MSA 17 /* message-security-assist */
# define S390X_STCKF 25 /* store-clock-fast */
# define S390X_MSA5 57 /* message-security-assist-ext. 5 */
# define S390X_MSA3 76 /* message-security-assist-ext. 3 */
# define S390X_MSA4 77 /* message-security-assist-ext. 4 */
# define S390X_VX 129 /* vector */
# define S390X_VXD 134 /* vector packed decimal */
# define S390X_VXE 135 /* vector enhancements 1 */
# define S390X_MSA8 146 /* message-security-assist-ext. 8 */
# define S390X_MSA9 155 /* message-security-assist-ext. 9 */
/* Function Codes */
/* all instructions */
# define S390X_QUERY 0
/* kimd/klmd */
# define S390X_SHA_1 1
# define S390X_SHA_256 2
# define S390X_SHA_512 3
# define S390X_SHA3_224 32
# define S390X_SHA3_256 33
# define S390X_SHA3_384 34
# define S390X_SHA3_512 35
# define S390X_KECCAK_224 32
# define S390X_KECCAK_256 33
# define S390X_KECCAK_384 34
# define S390X_KECCAK_512 35
# define S390X_SHAKE_128 36
# define S390X_SHAKE_256 37
# define S390X_GHASH 65
/* km/kmc/kmac/kmctr/kmo/kmf/kma */
# define S390X_AES_128 18
# define S390X_AES_192 19
# define S390X_AES_256 20
/* km */
# define S390X_XTS_AES_128 50
# define S390X_XTS_AES_256 52
/* prno */
# define S390X_SHA_512_DRNG 3
# define S390X_TRNG 114
/* pcc */
# define S390X_SCALAR_MULTIPLY_P256 64
# define S390X_SCALAR_MULTIPLY_P384 65
# define S390X_SCALAR_MULTIPLY_P521 66
# define S390X_SCALAR_MULTIPLY_ED25519 72
# define S390X_SCALAR_MULTIPLY_ED448 73
# define S390X_SCALAR_MULTIPLY_X25519 80
# define S390X_SCALAR_MULTIPLY_X448 81
/* kdsa */
# define S390X_ECDSA_VERIFY_P256 1
# define S390X_ECDSA_VERIFY_P384 2
# define S390X_ECDSA_VERIFY_P521 3
# define S390X_ECDSA_SIGN_P256 9
# define S390X_ECDSA_SIGN_P384 10
# define S390X_ECDSA_SIGN_P521 11
# define S390X_EDDSA_VERIFY_ED25519 32
# define S390X_EDDSA_VERIFY_ED448 36
# define S390X_EDDSA_SIGN_ED25519 40
# define S390X_EDDSA_SIGN_ED448 44
/* Register 0 Flags */
# define S390X_DECRYPT 0x80
# define S390X_KMA_LPC 0x100
# define S390X_KMA_LAAD 0x200
# define S390X_KMA_HS 0x400
# define S390X_KDSA_D 0x80
# define S390X_KLMD_PS 0x100
#endif
| 6,809 | 35.223404 | 79 | h |
openssl | openssl-master/crypto/self_test_core.c | /*
* Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/self_test.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include "internal/cryptlib.h"
#include "crypto/context.h"
typedef struct self_test_cb_st
{
OSSL_CALLBACK *cb;
void *cbarg;
} SELF_TEST_CB;
struct ossl_self_test_st
{
/* local state variables */
const char *phase;
const char *type;
const char *desc;
OSSL_CALLBACK *cb;
/* callback related variables used to pass the state back to the user */
OSSL_PARAM params[4];
void *cb_arg;
};
#ifndef FIPS_MODULE
void *ossl_self_test_set_callback_new(OSSL_LIB_CTX *ctx)
{
SELF_TEST_CB *stcb;
stcb = OPENSSL_zalloc(sizeof(*stcb));
return stcb;
}
void ossl_self_test_set_callback_free(void *stcb)
{
OPENSSL_free(stcb);
}
static SELF_TEST_CB *get_self_test_callback(OSSL_LIB_CTX *libctx)
{
return ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_SELF_TEST_CB_INDEX);
}
void OSSL_SELF_TEST_set_callback(OSSL_LIB_CTX *libctx, OSSL_CALLBACK *cb,
void *cbarg)
{
SELF_TEST_CB *stcb = get_self_test_callback(libctx);
if (stcb != NULL) {
stcb->cb = cb;
stcb->cbarg = cbarg;
}
}
void OSSL_SELF_TEST_get_callback(OSSL_LIB_CTX *libctx, OSSL_CALLBACK **cb,
void **cbarg)
{
SELF_TEST_CB *stcb = get_self_test_callback(libctx);
if (cb != NULL)
*cb = (stcb != NULL ? stcb->cb : NULL);
if (cbarg != NULL)
*cbarg = (stcb != NULL ? stcb->cbarg : NULL);
}
#endif /* FIPS_MODULE */
static void self_test_setparams(OSSL_SELF_TEST *st)
{
size_t n = 0;
if (st->cb != NULL) {
st->params[n++] =
OSSL_PARAM_construct_utf8_string(OSSL_PROV_PARAM_SELF_TEST_PHASE,
(char *)st->phase, 0);
st->params[n++] =
OSSL_PARAM_construct_utf8_string(OSSL_PROV_PARAM_SELF_TEST_TYPE,
(char *)st->type, 0);
st->params[n++] =
OSSL_PARAM_construct_utf8_string(OSSL_PROV_PARAM_SELF_TEST_DESC,
(char *)st->desc, 0);
}
st->params[n++] = OSSL_PARAM_construct_end();
}
OSSL_SELF_TEST *OSSL_SELF_TEST_new(OSSL_CALLBACK *cb, void *cbarg)
{
OSSL_SELF_TEST *ret = OPENSSL_zalloc(sizeof(*ret));
if (ret == NULL)
return NULL;
ret->cb = cb;
ret->cb_arg = cbarg;
ret->phase = "";
ret->type = "";
ret->desc = "";
self_test_setparams(ret);
return ret;
}
void OSSL_SELF_TEST_free(OSSL_SELF_TEST *st)
{
OPENSSL_free(st);
}
/* Can be used during application testing to log that a test has started. */
void OSSL_SELF_TEST_onbegin(OSSL_SELF_TEST *st, const char *type,
const char *desc)
{
if (st != NULL && st->cb != NULL) {
st->phase = OSSL_SELF_TEST_PHASE_START;
st->type = type;
st->desc = desc;
self_test_setparams(st);
(void)st->cb(st->params, st->cb_arg);
}
}
/*
* Can be used during application testing to log that a test has either
* passed or failed.
*/
void OSSL_SELF_TEST_onend(OSSL_SELF_TEST *st, int ret)
{
if (st != NULL && st->cb != NULL) {
st->phase =
(ret == 1 ? OSSL_SELF_TEST_PHASE_PASS : OSSL_SELF_TEST_PHASE_FAIL);
self_test_setparams(st);
(void)st->cb(st->params, st->cb_arg);
st->phase = OSSL_SELF_TEST_PHASE_NONE;
st->type = OSSL_SELF_TEST_TYPE_NONE;
st->desc = OSSL_SELF_TEST_DESC_NONE;
}
}
/*
* Used for failure testing.
*
* Call the applications SELF_TEST_cb() if it exists.
* If the application callback decides to return 0 then the first byte of 'bytes'
* is modified (corrupted). This is used to modify output signatures or
* ciphertext before they are verified or decrypted.
*/
int OSSL_SELF_TEST_oncorrupt_byte(OSSL_SELF_TEST *st, unsigned char *bytes)
{
if (st != NULL && st->cb != NULL) {
st->phase = OSSL_SELF_TEST_PHASE_CORRUPT;
self_test_setparams(st);
if (!st->cb(st->params, st->cb_arg)) {
bytes[0] ^= 1;
return 1;
}
}
return 0;
}
| 4,497 | 25.934132 | 81 | c |
openssl | openssl-master/crypto/sleep.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/crypto.h>
#include "internal/e_os.h"
/* system-specific variants defining OSSL_sleep() */
#if defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__)
#include <unistd.h>
void OSSL_sleep(uint64_t millis)
{
# ifdef OPENSSL_SYS_VXWORKS
struct timespec ts;
ts.tv_sec = (long int) (millis / 1000);
ts.tv_nsec = (long int) (millis % 1000) * 1000000ul;
nanosleep(&ts, NULL);
# elif defined(__TANDEM)
# if !defined(_REENTRANT)
# include <cextdecs.h(PROCESS_DELAY_)>
/* HPNS does not support usleep for non threaded apps */
PROCESS_DELAY_(millis * 1000);
# elif defined(_SPT_MODEL_)
# include <spthread.h>
# include <spt_extensions.h>
usleep(millis * 1000);
# else
usleep(millis * 1000);
# endif
# else
unsigned int s = (unsigned int)(millis / 1000);
unsigned int us = (unsigned int)((millis % 1000) * 1000);
sleep(s);
usleep(us);
# endif
}
#elif defined(_WIN32) && !defined(OPENSSL_SYS_UEFI)
# include <windows.h>
void OSSL_sleep(uint64_t millis)
{
/*
* Windows' Sleep() takes a DWORD argument, which is smaller than
* a uint64_t, so we need to limit it to 49 days, which should be enough.
*/
DWORD limited_millis = (DWORD)-1;
if (millis < limited_millis)
limited_millis = (DWORD)millis;
Sleep(limited_millis);
}
#else
/* Fallback to a busy wait */
# include "internal/time.h"
static void ossl_sleep_secs(uint64_t secs)
{
/*
* sleep() takes an unsigned int argument, which is smaller than
* a uint64_t, so it needs to be limited to 136 years which
* should be enough even for Sleeping Beauty.
*/
unsigned int limited_secs = UINT_MAX;
if (secs < limited_secs)
limited_secs = (unsigned int)secs;
sleep(limited_secs);
}
static void ossl_sleep_millis(uint64_t millis)
{
const OSSL_TIME finish
= ossl_time_add(ossl_time_now(), ossl_ms2time(millis));
while (ossl_time_compare(ossl_time_now(), finish) < 0)
/* busy wait */ ;
}
void OSSL_sleep(uint64_t millis)
{
ossl_sleep_secs(millis / 1000);
ossl_sleep_millis(millis % 1000);
}
#endif /* defined(OPENSSL_SYS_UNIX) || defined(__DJGPP__) */
| 2,505 | 25.104167 | 77 | c |
openssl | openssl-master/crypto/sparcv9cap.c | /*
* Copyright 2005-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <setjmp.h>
#include <signal.h>
#include <sys/time.h>
#include <unistd.h>
#include <openssl/bn.h>
#include "internal/cryptlib.h"
#include "crypto/sparc_arch.h"
#if defined(__GNUC__) && defined(__linux)
__attribute__ ((visibility("hidden")))
#endif
unsigned int OPENSSL_sparcv9cap_P[2] = { SPARCV9_TICK_PRIVILEGED, 0 };
unsigned long _sparcv9_rdtick(void);
void _sparcv9_vis1_probe(void);
unsigned long _sparcv9_vis1_instrument(void);
void _sparcv9_vis2_probe(void);
void _sparcv9_fmadd_probe(void);
unsigned long _sparcv9_rdcfr(void);
void _sparcv9_vis3_probe(void);
void _sparcv9_fjaesx_probe(void);
unsigned long _sparcv9_random(void);
size_t _sparcv9_vis1_instrument_bus(unsigned int *, size_t);
size_t _sparcv9_vis1_instrument_bus2(unsigned int *, size_t, size_t);
uint32_t OPENSSL_rdtsc(void)
{
if (OPENSSL_sparcv9cap_P[0] & SPARCV9_TICK_PRIVILEGED)
#if defined(__sun) && defined(__SVR4)
return gethrtime();
#else
return 0;
#endif
else
return _sparcv9_rdtick();
}
size_t OPENSSL_instrument_bus(unsigned int *out, size_t cnt)
{
if ((OPENSSL_sparcv9cap_P[0] & (SPARCV9_TICK_PRIVILEGED | SPARCV9_BLK)) ==
SPARCV9_BLK)
return _sparcv9_vis1_instrument_bus(out, cnt);
else
return 0;
}
size_t OPENSSL_instrument_bus2(unsigned int *out, size_t cnt, size_t max)
{
if ((OPENSSL_sparcv9cap_P[0] & (SPARCV9_TICK_PRIVILEGED | SPARCV9_BLK)) ==
SPARCV9_BLK)
return _sparcv9_vis1_instrument_bus2(out, cnt, max);
else
return 0;
}
static sigjmp_buf common_jmp;
static void common_handler(int sig)
{
siglongjmp(common_jmp, sig);
}
#if defined(__sun) && defined(__SVR4)
# if defined(__GNUC__) && __GNUC__>=2
extern unsigned int getisax(unsigned int vec[], unsigned int sz) __attribute__ ((weak));
# elif defined(__SUNPRO_C)
#pragma weak getisax
extern unsigned int getisax(unsigned int vec[], unsigned int sz);
# else
static unsigned int (*getisax) (unsigned int vec[], unsigned int sz) = NULL;
# endif
#endif
void OPENSSL_cpuid_setup(void)
{
char *e;
struct sigaction common_act, ill_oact, bus_oact;
sigset_t all_masked, oset;
static int trigger = 0;
if (trigger)
return;
trigger = 1;
if ((e = getenv("OPENSSL_sparcv9cap"))) {
OPENSSL_sparcv9cap_P[0] = strtoul(e, NULL, 0);
if ((e = strchr(e, ':')))
OPENSSL_sparcv9cap_P[1] = strtoul(e + 1, NULL, 0);
return;
}
#if defined(__sun) && defined(__SVR4)
if (getisax != NULL) {
unsigned int vec[2] = { 0, 0 };
if (getisax (vec,2)) {
if (vec[0]&0x00020) OPENSSL_sparcv9cap_P[0] |= SPARCV9_VIS1;
if (vec[0]&0x00040) OPENSSL_sparcv9cap_P[0] |= SPARCV9_VIS2;
if (vec[0]&0x00080) OPENSSL_sparcv9cap_P[0] |= SPARCV9_BLK;
if (vec[0]&0x00100) OPENSSL_sparcv9cap_P[0] |= SPARCV9_FMADD;
if (vec[0]&0x00400) OPENSSL_sparcv9cap_P[0] |= SPARCV9_VIS3;
if (vec[0]&0x01000) OPENSSL_sparcv9cap_P[0] |= SPARCV9_FJHPCACE;
if (vec[0]&0x02000) OPENSSL_sparcv9cap_P[0] |= SPARCV9_FJDESX;
if (vec[0]&0x08000) OPENSSL_sparcv9cap_P[0] |= SPARCV9_IMA;
if (vec[0]&0x10000) OPENSSL_sparcv9cap_P[0] |= SPARCV9_FJAESX;
if (vec[1]&0x00008) OPENSSL_sparcv9cap_P[0] |= SPARCV9_VIS4;
/* reconstruct %cfr copy */
OPENSSL_sparcv9cap_P[1] = (vec[0]>>17)&0x3ff;
OPENSSL_sparcv9cap_P[1] |= (OPENSSL_sparcv9cap_P[1]&CFR_MONTMUL)<<1;
if (vec[0]&0x20000000) OPENSSL_sparcv9cap_P[1] |= CFR_CRC32C;
if (vec[1]&0x00000020) OPENSSL_sparcv9cap_P[1] |= CFR_XMPMUL;
if (vec[1]&0x00000040)
OPENSSL_sparcv9cap_P[1] |= CFR_XMONTMUL|CFR_XMONTSQR;
/* Some heuristics */
/* all known VIS2-capable CPUs have unprivileged tick counter */
if (OPENSSL_sparcv9cap_P[0]&SPARCV9_VIS2)
OPENSSL_sparcv9cap_P[0] &= ~SPARCV9_TICK_PRIVILEGED;
OPENSSL_sparcv9cap_P[0] |= SPARCV9_PREFER_FPU;
/* detect UltraSPARC-Tx, see sparccpud.S for details... */
if ((OPENSSL_sparcv9cap_P[0]&SPARCV9_VIS1) &&
_sparcv9_vis1_instrument() >= 12)
OPENSSL_sparcv9cap_P[0] &= ~(SPARCV9_VIS1 | SPARCV9_PREFER_FPU);
}
if (sizeof(size_t) == 8)
OPENSSL_sparcv9cap_P[0] |= SPARCV9_64BIT_STACK;
return;
}
#endif
/* Initial value, fits UltraSPARC-I&II... */
OPENSSL_sparcv9cap_P[0] = SPARCV9_PREFER_FPU | SPARCV9_TICK_PRIVILEGED;
sigfillset(&all_masked);
sigdelset(&all_masked, SIGILL);
sigdelset(&all_masked, SIGTRAP);
# ifdef SIGEMT
sigdelset(&all_masked, SIGEMT);
# endif
sigdelset(&all_masked, SIGFPE);
sigdelset(&all_masked, SIGBUS);
sigdelset(&all_masked, SIGSEGV);
sigprocmask(SIG_SETMASK, &all_masked, &oset);
memset(&common_act, 0, sizeof(common_act));
common_act.sa_handler = common_handler;
common_act.sa_mask = all_masked;
sigaction(SIGILL, &common_act, &ill_oact);
sigaction(SIGBUS, &common_act, &bus_oact); /* T1 fails 16-bit ldda [on
* Linux] */
if (sigsetjmp(common_jmp, 1) == 0) {
_sparcv9_rdtick();
OPENSSL_sparcv9cap_P[0] &= ~SPARCV9_TICK_PRIVILEGED;
}
if (sigsetjmp(common_jmp, 1) == 0) {
_sparcv9_vis1_probe();
OPENSSL_sparcv9cap_P[0] |= SPARCV9_VIS1 | SPARCV9_BLK;
/* detect UltraSPARC-Tx, see sparccpud.S for details... */
if (_sparcv9_vis1_instrument() >= 12)
OPENSSL_sparcv9cap_P[0] &= ~(SPARCV9_VIS1 | SPARCV9_PREFER_FPU);
else {
_sparcv9_vis2_probe();
OPENSSL_sparcv9cap_P[0] |= SPARCV9_VIS2;
}
}
if (sigsetjmp(common_jmp, 1) == 0) {
_sparcv9_fmadd_probe();
OPENSSL_sparcv9cap_P[0] |= SPARCV9_FMADD;
}
/*
* VIS3 flag is tested independently from VIS1, unlike VIS2 that is,
* because VIS3 defines even integer instructions.
*/
if (sigsetjmp(common_jmp, 1) == 0) {
_sparcv9_vis3_probe();
OPENSSL_sparcv9cap_P[0] |= SPARCV9_VIS3;
}
if (sigsetjmp(common_jmp, 1) == 0) {
_sparcv9_fjaesx_probe();
OPENSSL_sparcv9cap_P[0] |= SPARCV9_FJAESX;
}
/*
* In wait for better solution _sparcv9_rdcfr is masked by
* VIS3 flag, because it goes to uninterruptible endless
* loop on UltraSPARC II running Solaris. Things might be
* different on Linux...
*/
if ((OPENSSL_sparcv9cap_P[0] & SPARCV9_VIS3) &&
sigsetjmp(common_jmp, 1) == 0) {
OPENSSL_sparcv9cap_P[1] = (unsigned int)_sparcv9_rdcfr();
}
sigaction(SIGBUS, &bus_oact, NULL);
sigaction(SIGILL, &ill_oact, NULL);
sigprocmask(SIG_SETMASK, &oset, NULL);
if (sizeof(size_t) == 8)
OPENSSL_sparcv9cap_P[0] |= SPARCV9_64BIT_STACK;
# ifdef __linux
else {
int ret = syscall(340);
if (ret >= 0 && ret & 1)
OPENSSL_sparcv9cap_P[0] |= SPARCV9_64BIT_STACK;
}
# endif
}
| 7,485 | 31.267241 | 88 | c |
openssl | openssl-master/crypto/sparse_array.c | /*
* Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/crypto.h>
#include <openssl/bn.h>
#include "crypto/sparse_array.h"
/*
* How many bits are used to index each level in the tree structure?
* This setting determines the number of pointers stored in each node of the
* tree used to represent the sparse array. Having more pointers reduces the
* depth of the tree but potentially wastes more memory. That is, this is a
* direct space versus time tradeoff.
*
* The default is to use four bits which means that the are 16
* pointers in each tree node.
*
* The library builder is also permitted to define other sizes in the closed
* interval [2, sizeof(ossl_uintmax_t) * 8]. Space use generally scales
* exponentially with the block size, although the implementation only
* creates enough blocks to support the largest used index. The depth is:
* ceil(log_2(largest index) / 2^{block size})
* E.g. with a block size of 4, and a largest index of 1000, the depth
* will be three.
*/
#ifndef OPENSSL_SA_BLOCK_BITS
# define OPENSSL_SA_BLOCK_BITS 4
#elif OPENSSL_SA_BLOCK_BITS < 2 || OPENSSL_SA_BLOCK_BITS > (BN_BITS2 - 1)
# error OPENSSL_SA_BLOCK_BITS is out of range
#endif
/*
* From the number of bits, work out:
* the number of pointers in a tree node;
* a bit mask to quickly extract an index and
* the maximum depth of the tree structure.
*/
#define SA_BLOCK_MAX (1 << OPENSSL_SA_BLOCK_BITS)
#define SA_BLOCK_MASK (SA_BLOCK_MAX - 1)
#define SA_BLOCK_MAX_LEVELS (((int)sizeof(ossl_uintmax_t) * 8 \
+ OPENSSL_SA_BLOCK_BITS - 1) \
/ OPENSSL_SA_BLOCK_BITS)
struct sparse_array_st {
int levels;
ossl_uintmax_t top;
size_t nelem;
void **nodes;
};
OPENSSL_SA *ossl_sa_new(void)
{
OPENSSL_SA *res = OPENSSL_zalloc(sizeof(*res));
return res;
}
static void sa_doall(const OPENSSL_SA *sa, void (*node)(void **),
void (*leaf)(ossl_uintmax_t, void *, void *), void *arg)
{
int i[SA_BLOCK_MAX_LEVELS];
void *nodes[SA_BLOCK_MAX_LEVELS];
ossl_uintmax_t idx = 0;
int l = 0;
i[0] = 0;
nodes[0] = sa->nodes;
while (l >= 0) {
const int n = i[l];
void ** const p = nodes[l];
if (n >= SA_BLOCK_MAX) {
if (p != NULL && node != NULL)
(*node)(p);
l--;
idx >>= OPENSSL_SA_BLOCK_BITS;
} else {
i[l] = n + 1;
if (p != NULL && p[n] != NULL) {
idx = (idx & ~SA_BLOCK_MASK) | n;
if (l < sa->levels - 1) {
i[++l] = 0;
nodes[l] = p[n];
idx <<= OPENSSL_SA_BLOCK_BITS;
} else if (leaf != NULL) {
(*leaf)(idx, p[n], arg);
}
}
}
}
}
static void sa_free_node(void **p)
{
OPENSSL_free(p);
}
static void sa_free_leaf(ossl_uintmax_t n, void *p, void *arg)
{
OPENSSL_free(p);
}
void ossl_sa_free(OPENSSL_SA *sa)
{
if (sa != NULL) {
sa_doall(sa, &sa_free_node, NULL, NULL);
OPENSSL_free(sa);
}
}
void ossl_sa_free_leaves(OPENSSL_SA *sa)
{
sa_doall(sa, &sa_free_node, &sa_free_leaf, NULL);
OPENSSL_free(sa);
}
/* Wrap this in a structure to avoid compiler warnings */
struct trampoline_st {
void (*func)(ossl_uintmax_t, void *);
};
static void trampoline(ossl_uintmax_t n, void *l, void *arg)
{
((const struct trampoline_st *)arg)->func(n, l);
}
void ossl_sa_doall(const OPENSSL_SA *sa, void (*leaf)(ossl_uintmax_t, void *))
{
struct trampoline_st tramp;
tramp.func = leaf;
if (sa != NULL)
sa_doall(sa, NULL, &trampoline, &tramp);
}
void ossl_sa_doall_arg(const OPENSSL_SA *sa,
void (*leaf)(ossl_uintmax_t, void *, void *),
void *arg)
{
if (sa != NULL)
sa_doall(sa, NULL, leaf, arg);
}
size_t ossl_sa_num(const OPENSSL_SA *sa)
{
return sa == NULL ? 0 : sa->nelem;
}
void *ossl_sa_get(const OPENSSL_SA *sa, ossl_uintmax_t n)
{
int level;
void **p, *r = NULL;
if (sa == NULL || sa->nelem == 0)
return NULL;
if (n <= sa->top) {
p = sa->nodes;
for (level = sa->levels - 1; p != NULL && level > 0; level--)
p = (void **)p[(n >> (OPENSSL_SA_BLOCK_BITS * level))
& SA_BLOCK_MASK];
r = p == NULL ? NULL : p[n & SA_BLOCK_MASK];
}
return r;
}
static ossl_inline void **alloc_node(void)
{
return OPENSSL_zalloc(SA_BLOCK_MAX * sizeof(void *));
}
int ossl_sa_set(OPENSSL_SA *sa, ossl_uintmax_t posn, void *val)
{
int i, level = 1;
ossl_uintmax_t n = posn;
void **p;
if (sa == NULL)
return 0;
for (level = 1; level < SA_BLOCK_MAX_LEVELS; level++)
if ((n >>= OPENSSL_SA_BLOCK_BITS) == 0)
break;
for (;sa->levels < level; sa->levels++) {
p = alloc_node();
if (p == NULL)
return 0;
p[0] = sa->nodes;
sa->nodes = p;
}
if (sa->top < posn)
sa->top = posn;
p = sa->nodes;
for (level = sa->levels - 1; level > 0; level--) {
i = (posn >> (OPENSSL_SA_BLOCK_BITS * level)) & SA_BLOCK_MASK;
if (p[i] == NULL && (p[i] = alloc_node()) == NULL)
return 0;
p = p[i];
}
p += posn & SA_BLOCK_MASK;
if (val == NULL && *p != NULL)
sa->nelem--;
else if (val != NULL && *p == NULL)
sa->nelem++;
*p = val;
return 1;
}
| 5,960 | 26.470046 | 78 | c |
openssl | openssl-master/crypto/threads_pthread.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 to use the OPENSSL_fork_*() deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <openssl/crypto.h>
#include "internal/cryptlib.h"
#if defined(__sun)
# include <atomic.h>
#endif
#if defined(__apple_build_version__) && __apple_build_version__ < 6000000
/*
* OS/X 10.7 and 10.8 had a weird version of clang which has __ATOMIC_ACQUIRE and
* __ATOMIC_ACQ_REL but which expects only one parameter for __atomic_is_lock_free()
* rather than two which has signature __atomic_is_lock_free(sizeof(_Atomic(T))).
* All of this makes impossible to use __atomic_is_lock_free here.
*
* See: https://github.com/llvm/llvm-project/commit/a4c2602b714e6c6edb98164550a5ae829b2de760
*/
#define BROKEN_CLANG_ATOMICS
#endif
#if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) && !defined(OPENSSL_SYS_WINDOWS)
# if defined(OPENSSL_SYS_UNIX)
# include <sys/types.h>
# include <unistd.h>
#endif
# include <assert.h>
# ifdef PTHREAD_RWLOCK_INITIALIZER
# define USE_RWLOCK
# endif
CRYPTO_RWLOCK *CRYPTO_THREAD_lock_new(void)
{
# ifdef USE_RWLOCK
CRYPTO_RWLOCK *lock;
if ((lock = CRYPTO_zalloc(sizeof(pthread_rwlock_t), NULL, 0)) == NULL)
/* Don't set error, to avoid recursion blowup. */
return NULL;
if (pthread_rwlock_init(lock, NULL) != 0) {
OPENSSL_free(lock);
return NULL;
}
# else
pthread_mutexattr_t attr;
CRYPTO_RWLOCK *lock;
if ((lock = CRYPTO_zalloc(sizeof(pthread_mutex_t), NULL, 0)) == NULL)
/* Don't set error, to avoid recursion blowup. */
return NULL;
/*
* We don't use recursive mutexes, but try to catch errors if we do.
*/
pthread_mutexattr_init(&attr);
# if !defined (__TANDEM) && !defined (_SPT_MODEL_)
# if !defined(NDEBUG) && !defined(OPENSSL_NO_MUTEX_ERRORCHECK)
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
# else
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
# endif
# else
/* The SPT Thread Library does not define MUTEX attributes. */
# endif
if (pthread_mutex_init(lock, &attr) != 0) {
pthread_mutexattr_destroy(&attr);
OPENSSL_free(lock);
return NULL;
}
pthread_mutexattr_destroy(&attr);
# endif
return lock;
}
__owur int CRYPTO_THREAD_read_lock(CRYPTO_RWLOCK *lock)
{
# ifdef USE_RWLOCK
if (pthread_rwlock_rdlock(lock) != 0)
return 0;
# else
if (pthread_mutex_lock(lock) != 0) {
assert(errno != EDEADLK && errno != EBUSY);
return 0;
}
# endif
return 1;
}
__owur int CRYPTO_THREAD_write_lock(CRYPTO_RWLOCK *lock)
{
# ifdef USE_RWLOCK
if (pthread_rwlock_wrlock(lock) != 0)
return 0;
# else
if (pthread_mutex_lock(lock) != 0) {
assert(errno != EDEADLK && errno != EBUSY);
return 0;
}
# endif
return 1;
}
int CRYPTO_THREAD_unlock(CRYPTO_RWLOCK *lock)
{
# ifdef USE_RWLOCK
if (pthread_rwlock_unlock(lock) != 0)
return 0;
# else
if (pthread_mutex_unlock(lock) != 0) {
assert(errno != EPERM);
return 0;
}
# endif
return 1;
}
void CRYPTO_THREAD_lock_free(CRYPTO_RWLOCK *lock)
{
if (lock == NULL)
return;
# ifdef USE_RWLOCK
pthread_rwlock_destroy(lock);
# else
pthread_mutex_destroy(lock);
# endif
OPENSSL_free(lock);
return;
}
int CRYPTO_THREAD_run_once(CRYPTO_ONCE *once, void (*init)(void))
{
if (pthread_once(once, init) != 0)
return 0;
return 1;
}
int CRYPTO_THREAD_init_local(CRYPTO_THREAD_LOCAL *key, void (*cleanup)(void *))
{
if (pthread_key_create(key, cleanup) != 0)
return 0;
return 1;
}
void *CRYPTO_THREAD_get_local(CRYPTO_THREAD_LOCAL *key)
{
return pthread_getspecific(*key);
}
int CRYPTO_THREAD_set_local(CRYPTO_THREAD_LOCAL *key, void *val)
{
if (pthread_setspecific(*key, val) != 0)
return 0;
return 1;
}
int CRYPTO_THREAD_cleanup_local(CRYPTO_THREAD_LOCAL *key)
{
if (pthread_key_delete(*key) != 0)
return 0;
return 1;
}
CRYPTO_THREAD_ID CRYPTO_THREAD_get_current_id(void)
{
return pthread_self();
}
int CRYPTO_THREAD_compare_id(CRYPTO_THREAD_ID a, CRYPTO_THREAD_ID b)
{
return pthread_equal(a, b);
}
int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock)
{
# if defined(__GNUC__) && defined(__ATOMIC_ACQ_REL) && !defined(BROKEN_CLANG_ATOMICS)
if (__atomic_is_lock_free(sizeof(*val), val)) {
*ret = __atomic_add_fetch(val, amount, __ATOMIC_ACQ_REL);
return 1;
}
# elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11))
/* This will work for all future Solaris versions. */
if (ret != NULL) {
*ret = atomic_add_int_nv((volatile unsigned int *)val, amount);
return 1;
}
# endif
if (lock == NULL || !CRYPTO_THREAD_write_lock(lock))
return 0;
*val += amount;
*ret = *val;
if (!CRYPTO_THREAD_unlock(lock))
return 0;
return 1;
}
int CRYPTO_atomic_or(uint64_t *val, uint64_t op, uint64_t *ret,
CRYPTO_RWLOCK *lock)
{
# if defined(__GNUC__) && defined(__ATOMIC_ACQ_REL) && !defined(BROKEN_CLANG_ATOMICS)
if (__atomic_is_lock_free(sizeof(*val), val)) {
*ret = __atomic_or_fetch(val, op, __ATOMIC_ACQ_REL);
return 1;
}
# elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11))
/* This will work for all future Solaris versions. */
if (ret != NULL) {
*ret = atomic_or_64_nv(val, op);
return 1;
}
# endif
if (lock == NULL || !CRYPTO_THREAD_write_lock(lock))
return 0;
*val |= op;
*ret = *val;
if (!CRYPTO_THREAD_unlock(lock))
return 0;
return 1;
}
int CRYPTO_atomic_load(uint64_t *val, uint64_t *ret, CRYPTO_RWLOCK *lock)
{
# if defined(__GNUC__) && defined(__ATOMIC_ACQUIRE) && !defined(BROKEN_CLANG_ATOMICS)
if (__atomic_is_lock_free(sizeof(*val), val)) {
__atomic_load(val, ret, __ATOMIC_ACQUIRE);
return 1;
}
# elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11))
/* This will work for all future Solaris versions. */
if (ret != NULL) {
*ret = atomic_or_64_nv(val, 0);
return 1;
}
# endif
if (lock == NULL || !CRYPTO_THREAD_read_lock(lock))
return 0;
*ret = *val;
if (!CRYPTO_THREAD_unlock(lock))
return 0;
return 1;
}
int CRYPTO_atomic_load_int(int *val, int *ret, CRYPTO_RWLOCK *lock)
{
# if defined(__GNUC__) && defined(__ATOMIC_ACQUIRE) && !defined(BROKEN_CLANG_ATOMICS)
if (__atomic_is_lock_free(sizeof(*val), val)) {
__atomic_load(val, ret, __ATOMIC_ACQUIRE);
return 1;
}
# elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11))
/* This will work for all future Solaris versions. */
if (ret != NULL) {
*ret = (int *)atomic_or_uint_nv((unsigned int *)val, 0);
return 1;
}
# endif
if (lock == NULL || !CRYPTO_THREAD_read_lock(lock))
return 0;
*ret = *val;
if (!CRYPTO_THREAD_unlock(lock))
return 0;
return 1;
}
# ifndef FIPS_MODULE
int openssl_init_fork_handlers(void)
{
return 1;
}
# endif /* FIPS_MODULE */
int openssl_get_fork_id(void)
{
return getpid();
}
#endif
| 7,566 | 23.488673 | 92 | c |
openssl | openssl-master/crypto/threads_win.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
*/
#if defined(_WIN32)
# include <windows.h>
# if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x600
# define USE_RWLOCK
# endif
#endif
/*
* VC++ 2008 or earlier x86 compilers do not have an inline implementation
* of InterlockedOr64 for 32bit and will fail to run on Windows XP 32bit.
* https://docs.microsoft.com/en-us/cpp/intrinsics/interlockedor-intrinsic-functions#requirements
* To work around this problem, we implement a manual locking mechanism for
* only VC++ 2008 or earlier x86 compilers.
*/
#if (defined(_MSC_VER) && defined(_M_IX86) && _MSC_VER <= 1600)
# define NO_INTERLOCKEDOR64
#endif
#include <openssl/crypto.h>
#if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) && defined(OPENSSL_SYS_WINDOWS)
# ifdef USE_RWLOCK
typedef struct {
SRWLOCK lock;
int exclusive;
} CRYPTO_win_rwlock;
# endif
CRYPTO_RWLOCK *CRYPTO_THREAD_lock_new(void)
{
CRYPTO_RWLOCK *lock;
# ifdef USE_RWLOCK
CRYPTO_win_rwlock *rwlock;
if ((lock = CRYPTO_zalloc(sizeof(CRYPTO_win_rwlock), NULL, 0)) == NULL)
/* Don't set error, to avoid recursion blowup. */
return NULL;
rwlock = lock;
InitializeSRWLock(&rwlock->lock);
# else
if ((lock = CRYPTO_zalloc(sizeof(CRITICAL_SECTION), NULL, 0)) == NULL)
/* Don't set error, to avoid recursion blowup. */
return NULL;
# if !defined(_WIN32_WCE)
/* 0x400 is the spin count value suggested in the documentation */
if (!InitializeCriticalSectionAndSpinCount(lock, 0x400)) {
OPENSSL_free(lock);
return NULL;
}
# else
InitializeCriticalSection(lock);
# endif
# endif
return lock;
}
__owur int CRYPTO_THREAD_read_lock(CRYPTO_RWLOCK *lock)
{
# ifdef USE_RWLOCK
CRYPTO_win_rwlock *rwlock = lock;
AcquireSRWLockShared(&rwlock->lock);
# else
EnterCriticalSection(lock);
# endif
return 1;
}
__owur int CRYPTO_THREAD_write_lock(CRYPTO_RWLOCK *lock)
{
# ifdef USE_RWLOCK
CRYPTO_win_rwlock *rwlock = lock;
AcquireSRWLockExclusive(&rwlock->lock);
rwlock->exclusive = 1;
# else
EnterCriticalSection(lock);
# endif
return 1;
}
int CRYPTO_THREAD_unlock(CRYPTO_RWLOCK *lock)
{
# ifdef USE_RWLOCK
CRYPTO_win_rwlock *rwlock = lock;
if (rwlock->exclusive) {
rwlock->exclusive = 0;
ReleaseSRWLockExclusive(&rwlock->lock);
} else {
ReleaseSRWLockShared(&rwlock->lock);
}
# else
LeaveCriticalSection(lock);
# endif
return 1;
}
void CRYPTO_THREAD_lock_free(CRYPTO_RWLOCK *lock)
{
if (lock == NULL)
return;
# ifndef USE_RWLOCK
DeleteCriticalSection(lock);
# endif
OPENSSL_free(lock);
return;
}
# define ONCE_UNINITED 0
# define ONCE_ININIT 1
# define ONCE_DONE 2
/*
* We don't use InitOnceExecuteOnce because that isn't available in WinXP which
* we still have to support.
*/
int CRYPTO_THREAD_run_once(CRYPTO_ONCE *once, void (*init)(void))
{
LONG volatile *lock = (LONG *)once;
LONG result;
if (*lock == ONCE_DONE)
return 1;
do {
result = InterlockedCompareExchange(lock, ONCE_ININIT, ONCE_UNINITED);
if (result == ONCE_UNINITED) {
init();
*lock = ONCE_DONE;
return 1;
}
} while (result == ONCE_ININIT);
return (*lock == ONCE_DONE);
}
int CRYPTO_THREAD_init_local(CRYPTO_THREAD_LOCAL *key, void (*cleanup)(void *))
{
*key = TlsAlloc();
if (*key == TLS_OUT_OF_INDEXES)
return 0;
return 1;
}
void *CRYPTO_THREAD_get_local(CRYPTO_THREAD_LOCAL *key)
{
DWORD last_error;
void *ret;
/*
* TlsGetValue clears the last error even on success, so that callers may
* distinguish it successfully returning NULL or failing. It is documented
* to never fail if the argument is a valid index from TlsAlloc, so we do
* not need to handle this.
*
* However, this error-mangling behavior interferes with the caller's use of
* GetLastError. In particular SSL_get_error queries the error queue to
* determine whether the caller should look at the OS's errors. To avoid
* destroying state, save and restore the Windows error.
*
* https://msdn.microsoft.com/en-us/library/windows/desktop/ms686812(v=vs.85).aspx
*/
last_error = GetLastError();
ret = TlsGetValue(*key);
SetLastError(last_error);
return ret;
}
int CRYPTO_THREAD_set_local(CRYPTO_THREAD_LOCAL *key, void *val)
{
if (TlsSetValue(*key, val) == 0)
return 0;
return 1;
}
int CRYPTO_THREAD_cleanup_local(CRYPTO_THREAD_LOCAL *key)
{
if (TlsFree(*key) == 0)
return 0;
return 1;
}
CRYPTO_THREAD_ID CRYPTO_THREAD_get_current_id(void)
{
return GetCurrentThreadId();
}
int CRYPTO_THREAD_compare_id(CRYPTO_THREAD_ID a, CRYPTO_THREAD_ID b)
{
return (a == b);
}
int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock)
{
*ret = (int)InterlockedExchangeAdd((long volatile *)val, (long)amount) + amount;
return 1;
}
int CRYPTO_atomic_or(uint64_t *val, uint64_t op, uint64_t *ret,
CRYPTO_RWLOCK *lock)
{
#if (defined(NO_INTERLOCKEDOR64))
if (lock == NULL || !CRYPTO_THREAD_write_lock(lock))
return 0;
*val |= op;
*ret = *val;
if (!CRYPTO_THREAD_unlock(lock))
return 0;
return 1;
#else
*ret = (uint64_t)InterlockedOr64((LONG64 volatile *)val, (LONG64)op) | op;
return 1;
#endif
}
int CRYPTO_atomic_load(uint64_t *val, uint64_t *ret, CRYPTO_RWLOCK *lock)
{
#if (defined(NO_INTERLOCKEDOR64))
if (lock == NULL || !CRYPTO_THREAD_read_lock(lock))
return 0;
*ret = *val;
if (!CRYPTO_THREAD_unlock(lock))
return 0;
return 1;
#else
*ret = (uint64_t)InterlockedOr64((LONG64 volatile *)val, 0);
return 1;
#endif
}
int CRYPTO_atomic_load_int(int *val, int *ret, CRYPTO_RWLOCK *lock)
{
#if (defined(NO_INTERLOCKEDOR64))
if (lock == NULL || !CRYPTO_THREAD_read_lock(lock))
return 0;
*ret = *val;
if (!CRYPTO_THREAD_unlock(lock))
return 0;
return 1;
#else
/* On Windows, LONG is always the same size as int. */
*ret = (int)InterlockedOr((LONG volatile *)val, 0);
return 1;
#endif
}
int openssl_init_fork_handlers(void)
{
return 0;
}
int openssl_get_fork_id(void)
{
return 0;
}
#endif
| 6,635 | 22.615658 | 97 | c |
openssl | openssl-master/crypto/time.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 <errno.h>
#include <openssl/err.h>
#include "internal/time.h"
OSSL_TIME ossl_time_now(void)
{
OSSL_TIME r;
#if defined(_WIN32) && !defined(OPENSSL_SYS_UEFI)
SYSTEMTIME st;
union {
unsigned __int64 ul;
FILETIME ft;
} now;
GetSystemTime(&st);
SystemTimeToFileTime(&st, &now.ft);
/* re-bias to 1/1/1970 */
# ifdef __MINGW32__
now.ul -= 116444736000000000ULL;
# else
now.ul -= 116444736000000000UI64;
# endif
r.t = ((uint64_t)now.ul) * (OSSL_TIME_SECOND / 10000000);
#else /* defined(_WIN32) */
struct timeval t;
if (gettimeofday(&t, NULL) < 0) {
ERR_raise_data(ERR_LIB_SYS, get_last_sys_error(),
"calling gettimeofday()");
return ossl_time_zero();
}
if (t.tv_sec <= 0)
r.t = t.tv_usec <= 0 ? 0 : t.tv_usec * OSSL_TIME_US;
else
r.t = ((uint64_t)t.tv_sec * 1000000 + t.tv_usec) * OSSL_TIME_US;
#endif /* defined(_WIN32) */
return r;
}
| 1,314 | 25.836735 | 74 | c |
openssl | openssl-master/crypto/trace.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 <string.h>
#include "internal/thread_once.h"
#include <openssl/bio.h>
#include <openssl/crypto.h>
#include <openssl/trace.h>
#include "internal/bio.h"
#include "internal/nelem.h"
#include "internal/refcount.h"
#include "crypto/cryptlib.h"
#include "crypto/ctype.h"
#ifndef OPENSSL_NO_TRACE
static CRYPTO_RWLOCK *trace_lock = NULL;
static const BIO *current_channel = NULL;
/*-
* INTERNAL TRACE CHANNEL IMPLEMENTATION
*
* For our own flexibility, all trace categories are associated with a
* BIO sink object, also called the trace channel. Instead of a BIO object,
* the application can also provide a callback function, in which case an
* internal trace channel is attached, which simply calls the registered
* callback function.
*/
static int trace_write(BIO *b, const char *buf,
size_t num, size_t *written);
static int trace_puts(BIO *b, const char *str);
static long trace_ctrl(BIO *channel, int cmd, long argl, void *argp);
static int trace_free(BIO *b);
static const BIO_METHOD trace_method = {
BIO_TYPE_SOURCE_SINK,
"trace",
trace_write,
NULL, /* old write */
NULL, /* read_ex */
NULL, /* read */
trace_puts,
NULL, /* gets */
trace_ctrl, /* ctrl */
NULL, /* create */
trace_free, /* free */
NULL, /* callback_ctrl */
};
struct trace_data_st {
OSSL_trace_cb callback;
int category;
void *data;
};
static int trace_write(BIO *channel,
const char *buf, size_t num, size_t *written)
{
struct trace_data_st *ctx = BIO_get_data(channel);
size_t cnt = ctx->callback(buf, num, ctx->category, OSSL_TRACE_CTRL_WRITE,
ctx->data);
*written = cnt;
return cnt != 0;
}
static int trace_puts(BIO *channel, const char *str)
{
size_t written;
if (trace_write(channel, str, strlen(str), &written))
return (int)written;
return EOF;
}
static long trace_ctrl(BIO *channel, int cmd, long argl, void *argp)
{
struct trace_data_st *ctx = BIO_get_data(channel);
switch (cmd) {
case OSSL_TRACE_CTRL_BEGIN:
case OSSL_TRACE_CTRL_END:
/* We know that the callback is likely to return 0 here */
ctx->callback("", 0, ctx->category, cmd, ctx->data);
return 1;
default:
break;
}
return -2; /* Unsupported */
}
static int trace_free(BIO *channel)
{
if (channel == NULL)
return 0;
OPENSSL_free(BIO_get_data(channel));
return 1;
}
#endif
/*-
* TRACE
*/
/* Helper struct and macro to get name string to number mapping */
struct trace_category_st {
const char * const name;
const int num;
};
#define TRACE_CATEGORY_(name) { #name, OSSL_TRACE_CATEGORY_##name }
static const struct trace_category_st
trace_categories[OSSL_TRACE_CATEGORY_NUM] = {
TRACE_CATEGORY_(ALL),
TRACE_CATEGORY_(TRACE),
TRACE_CATEGORY_(INIT),
TRACE_CATEGORY_(TLS),
TRACE_CATEGORY_(TLS_CIPHER),
TRACE_CATEGORY_(CONF),
TRACE_CATEGORY_(ENGINE_TABLE),
TRACE_CATEGORY_(ENGINE_REF_COUNT),
TRACE_CATEGORY_(PKCS5V2),
TRACE_CATEGORY_(PKCS12_KEYGEN),
TRACE_CATEGORY_(PKCS12_DECRYPT),
TRACE_CATEGORY_(X509V3_POLICY),
TRACE_CATEGORY_(BN_CTX),
TRACE_CATEGORY_(CMP),
TRACE_CATEGORY_(STORE),
TRACE_CATEGORY_(DECODER),
TRACE_CATEGORY_(ENCODER),
TRACE_CATEGORY_(REF_COUNT),
TRACE_CATEGORY_(HTTP),
}; /* KEEP THIS LIST IN SYNC with #define OSSL_TRACE_CATEGORY_... in trace.h */
const char *OSSL_trace_get_category_name(int num)
{
if (num < 0 || (size_t)num >= OSSL_NELEM(trace_categories))
return NULL;
/*
* Partial check that OSSL_TRACE_CATEGORY_... macros
* are synced with trace_categories array
*/
if (!ossl_assert(trace_categories[num].name != NULL)
|| !ossl_assert(trace_categories[num].num == num))
return NULL;
return trace_categories[num].name;
}
int OSSL_trace_get_category_num(const char *name)
{
size_t i;
if (name == NULL)
return -1;
for (i = 0; i < OSSL_NELEM(trace_categories); i++)
if (OPENSSL_strcasecmp(name, trace_categories[i].name) == 0)
return trace_categories[i].num;
return -1; /* not found */
}
#ifndef OPENSSL_NO_TRACE
/* We use one trace channel for each trace category */
static struct {
enum { SIMPLE_CHANNEL, CALLBACK_CHANNEL } type;
BIO *bio;
char *prefix;
char *suffix;
} trace_channels[OSSL_TRACE_CATEGORY_NUM] = {
{ 0, NULL, NULL, NULL },
};
#endif
#ifndef OPENSSL_NO_TRACE
enum {
CHANNEL,
PREFIX,
SUFFIX
};
static int trace_attach_cb(int category, int type, const void *data)
{
switch (type) {
case CHANNEL:
OSSL_TRACE2(TRACE, "Attach channel %p to category '%s'\n",
data, trace_categories[category].name);
break;
case PREFIX:
OSSL_TRACE2(TRACE, "Attach prefix \"%s\" to category '%s'\n",
(const char *)data, trace_categories[category].name);
break;
case SUFFIX:
OSSL_TRACE2(TRACE, "Attach suffix \"%s\" to category '%s'\n",
(const char *)data, trace_categories[category].name);
break;
default: /* No clue */
break;
}
return 1;
}
static int trace_detach_cb(int category, int type, const void *data)
{
switch (type) {
case CHANNEL:
OSSL_TRACE2(TRACE, "Detach channel %p from category '%s'\n",
data, trace_categories[category].name);
break;
case PREFIX:
OSSL_TRACE2(TRACE, "Detach prefix \"%s\" from category '%s'\n",
(const char *)data, trace_categories[category].name);
break;
case SUFFIX:
OSSL_TRACE2(TRACE, "Detach suffix \"%s\" from category '%s'\n",
(const char *)data, trace_categories[category].name);
break;
default: /* No clue */
break;
}
return 1;
}
static int do_ossl_trace_init(void);
static CRYPTO_ONCE trace_inited = CRYPTO_ONCE_STATIC_INIT;
DEFINE_RUN_ONCE_STATIC(ossl_trace_init)
{
return do_ossl_trace_init();
}
static int set_trace_data(int category, int type, BIO **channel,
const char **prefix, const char **suffix,
int (*attach_cb)(int, int, const void *),
int (*detach_cb)(int, int, const void *))
{
BIO *curr_channel = NULL;
char *curr_prefix = NULL;
char *curr_suffix = NULL;
/* Ensure do_ossl_trace_init() is called once */
if (!RUN_ONCE(&trace_inited, ossl_trace_init))
return 0;
curr_channel = trace_channels[category].bio;
curr_prefix = trace_channels[category].prefix;
curr_suffix = trace_channels[category].suffix;
/* Make sure to run the detach callback first on all data */
if (prefix != NULL && curr_prefix != NULL) {
detach_cb(category, PREFIX, curr_prefix);
}
if (suffix != NULL && curr_suffix != NULL) {
detach_cb(category, SUFFIX, curr_suffix);
}
if (channel != NULL && curr_channel != NULL) {
detach_cb(category, CHANNEL, curr_channel);
}
/* After detach callbacks are done, clear data where appropriate */
if (prefix != NULL && curr_prefix != NULL) {
OPENSSL_free(curr_prefix);
trace_channels[category].prefix = NULL;
}
if (suffix != NULL && curr_suffix != NULL) {
OPENSSL_free(curr_suffix);
trace_channels[category].suffix = NULL;
}
if (channel != NULL && curr_channel != NULL) {
BIO_free(curr_channel);
trace_channels[category].type = 0;
trace_channels[category].bio = NULL;
}
/* Before running callbacks are done, set new data where appropriate */
if (prefix != NULL && *prefix != NULL) {
if ((curr_prefix = OPENSSL_strdup(*prefix)) == NULL)
return 0;
trace_channels[category].prefix = curr_prefix;
}
if (suffix != NULL && *suffix != NULL) {
if ((curr_suffix = OPENSSL_strdup(*suffix)) == NULL)
return 0;
trace_channels[category].suffix = curr_suffix;
}
if (channel != NULL && *channel != NULL) {
trace_channels[category].type = type;
trace_channels[category].bio = *channel;
/*
* This must not be done before setting prefix/suffix,
* as those may fail, and then the caller is mislead to free *channel.
*/
}
/* Finally, run the attach callback on the new data */
if (channel != NULL && *channel != NULL) {
attach_cb(category, CHANNEL, *channel);
}
if (prefix != NULL && *prefix != NULL) {
attach_cb(category, PREFIX, *prefix);
}
if (suffix != NULL && *suffix != NULL) {
attach_cb(category, SUFFIX, *suffix);
}
return 1;
}
static int do_ossl_trace_init(void)
{
trace_lock = CRYPTO_THREAD_lock_new();
return trace_lock != NULL;
}
#endif
void ossl_trace_cleanup(void)
{
#ifndef OPENSSL_NO_TRACE
int category;
BIO *channel = NULL;
const char *prefix = NULL;
const char *suffix = NULL;
for (category = 0; category < OSSL_TRACE_CATEGORY_NUM; category++) {
/* We force the TRACE category to be treated last */
if (category == OSSL_TRACE_CATEGORY_TRACE)
continue;
set_trace_data(category, 0, &channel, &prefix, &suffix,
trace_attach_cb, trace_detach_cb);
}
set_trace_data(OSSL_TRACE_CATEGORY_TRACE, 0, &channel,
&prefix, &suffix,
trace_attach_cb, trace_detach_cb);
CRYPTO_THREAD_lock_free(trace_lock);
#endif
}
int OSSL_trace_set_channel(int category, BIO *channel)
{
#ifndef OPENSSL_NO_TRACE
if (category >= 0 && category < OSSL_TRACE_CATEGORY_NUM)
return set_trace_data(category, SIMPLE_CHANNEL, &channel, NULL, NULL,
trace_attach_cb, trace_detach_cb);
#endif
return 0;
}
#ifndef OPENSSL_NO_TRACE
static int trace_attach_w_callback_cb(int category, int type, const void *data)
{
switch (type) {
case CHANNEL:
OSSL_TRACE2(TRACE,
"Attach channel %p to category '%s' (with callback)\n",
data, trace_categories[category].name);
break;
case PREFIX:
OSSL_TRACE2(TRACE, "Attach prefix \"%s\" to category '%s'\n",
(const char *)data, trace_categories[category].name);
break;
case SUFFIX:
OSSL_TRACE2(TRACE, "Attach suffix \"%s\" to category '%s'\n",
(const char *)data, trace_categories[category].name);
break;
default: /* No clue */
break;
}
return 1;
}
#endif
int OSSL_trace_set_callback(int category, OSSL_trace_cb callback, void *data)
{
#ifndef OPENSSL_NO_TRACE
BIO *channel = NULL;
struct trace_data_st *trace_data = NULL;
if (category < 0 || category >= OSSL_TRACE_CATEGORY_NUM)
return 0;
if (callback != NULL) {
if ((channel = BIO_new(&trace_method)) == NULL
|| (trace_data =
OPENSSL_zalloc(sizeof(struct trace_data_st))) == NULL)
goto err;
trace_data->callback = callback;
trace_data->category = category;
trace_data->data = data;
BIO_set_data(channel, trace_data);
}
if (!set_trace_data(category, CALLBACK_CHANNEL, &channel, NULL, NULL,
trace_attach_w_callback_cb, trace_detach_cb))
goto err;
return 1;
err:
BIO_free(channel);
OPENSSL_free(trace_data);
#endif
return 0;
}
int OSSL_trace_set_prefix(int category, const char *prefix)
{
#ifndef OPENSSL_NO_TRACE
if (category >= 0 && category < OSSL_TRACE_CATEGORY_NUM)
return set_trace_data(category, 0, NULL, &prefix, NULL,
trace_attach_cb, trace_detach_cb);
#endif
return 0;
}
int OSSL_trace_set_suffix(int category, const char *suffix)
{
#ifndef OPENSSL_NO_TRACE
if (category >= 0 && category < OSSL_TRACE_CATEGORY_NUM)
return set_trace_data(category, 0, NULL, NULL, &suffix,
trace_attach_cb, trace_detach_cb);
#endif
return 0;
}
#ifndef OPENSSL_NO_TRACE
static int ossl_trace_get_category(int category)
{
if (category < 0 || category >= OSSL_TRACE_CATEGORY_NUM)
return -1;
if (trace_channels[category].bio != NULL)
return category;
return OSSL_TRACE_CATEGORY_ALL;
}
#endif
int OSSL_trace_enabled(int category)
{
int ret = 0;
#ifndef OPENSSL_NO_TRACE
category = ossl_trace_get_category(category);
if (category >= 0)
ret = trace_channels[category].bio != NULL;
#endif
return ret;
}
BIO *OSSL_trace_begin(int category)
{
BIO *channel = NULL;
#ifndef OPENSSL_NO_TRACE
char *prefix = NULL;
category = ossl_trace_get_category(category);
if (category < 0)
return NULL;
channel = trace_channels[category].bio;
prefix = trace_channels[category].prefix;
if (channel != NULL) {
if (!CRYPTO_THREAD_write_lock(trace_lock))
return NULL;
current_channel = channel;
switch (trace_channels[category].type) {
case SIMPLE_CHANNEL:
if (prefix != NULL) {
(void)BIO_puts(channel, prefix);
(void)BIO_puts(channel, "\n");
}
break;
case CALLBACK_CHANNEL:
(void)BIO_ctrl(channel, OSSL_TRACE_CTRL_BEGIN,
prefix == NULL ? 0 : strlen(prefix), prefix);
break;
}
}
#endif
return channel;
}
void OSSL_trace_end(int category, BIO * channel)
{
#ifndef OPENSSL_NO_TRACE
char *suffix = NULL;
category = ossl_trace_get_category(category);
if (category < 0)
return;
suffix = trace_channels[category].suffix;
if (channel != NULL
&& ossl_assert(channel == current_channel)) {
(void)BIO_flush(channel);
switch (trace_channels[category].type) {
case SIMPLE_CHANNEL:
if (suffix != NULL) {
(void)BIO_puts(channel, suffix);
(void)BIO_puts(channel, "\n");
}
break;
case CALLBACK_CHANNEL:
(void)BIO_ctrl(channel, OSSL_TRACE_CTRL_END,
suffix == NULL ? 0 : strlen(suffix), suffix);
break;
}
current_channel = NULL;
CRYPTO_THREAD_unlock(trace_lock);
}
#endif
}
int OSSL_trace_string(BIO *out, int text, int full,
const unsigned char *data, size_t size)
{
unsigned char buf[OSSL_TRACE_STRING_MAX + 1];
int len, i;
if (!full && size > OSSL_TRACE_STRING_MAX) {
BIO_printf(out, "[len %zu limited to %d]: ",
size, OSSL_TRACE_STRING_MAX);
len = OSSL_TRACE_STRING_MAX;
} else {
len = (int)size;
}
if (!text) { /* mask control characters while preserving newlines */
for (i = 0; i < len; i++, data++)
buf[i] = (char)*data != '\n' && ossl_iscntrl((int)*data)
? ' ' : *data;
if (len == 0 || data[-1] != '\n')
buf[len++] = '\n';
data = buf;
}
return BIO_printf(out, "%.*s", len, data);
}
| 15,844 | 27.396057 | 79 | c |
openssl | openssl-master/crypto/vms_rms.h | /*
* Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifdef NAML$C_MAXRSS
# define CC_RMS_NAMX cc$rms_naml
# define FAB_NAMX fab$l_naml
# define FAB_OR_NAML( fab, naml) naml
# define FAB_OR_NAML_DNA naml$l_long_defname
# define FAB_OR_NAML_DNS naml$l_long_defname_size
# define FAB_OR_NAML_FNA naml$l_long_filename
# define FAB_OR_NAML_FNS naml$l_long_filename_size
# define NAMX_ESA naml$l_long_expand
# define NAMX_ESL naml$l_long_expand_size
# define NAMX_ESS naml$l_long_expand_alloc
# define NAMX_NOP naml$b_nop
# define SET_NAMX_NO_SHORT_UPCASE( nam) nam.naml$v_no_short_upcase = 1
# if __INITIAL_POINTER_SIZE == 64
# define NAMX_DNA_FNA_SET(fab) fab.fab$l_dna = (__char_ptr32) -1; \
fab.fab$l_fna = (__char_ptr32) -1;
# else /* __INITIAL_POINTER_SIZE == 64 */
# define NAMX_DNA_FNA_SET(fab) fab.fab$l_dna = (char *) -1; \
fab.fab$l_fna = (char *) -1;
# endif /* __INITIAL_POINTER_SIZE == 64 [else] */
# define NAMX_MAXRSS NAML$C_MAXRSS
# define NAMX_STRUCT NAML
#else /* def NAML$C_MAXRSS */
# define CC_RMS_NAMX cc$rms_nam
# define FAB_NAMX fab$l_nam
# define FAB_OR_NAML( fab, naml) fab
# define FAB_OR_NAML_DNA fab$l_dna
# define FAB_OR_NAML_DNS fab$b_dns
# define FAB_OR_NAML_FNA fab$l_fna
# define FAB_OR_NAML_FNS fab$b_fns
# define NAMX_ESA nam$l_esa
# define NAMX_ESL nam$b_esl
# define NAMX_ESS nam$b_ess
# define NAMX_NOP nam$b_nop
# define NAMX_DNA_FNA_SET(fab)
# define NAMX_MAXRSS NAM$C_MAXRSS
# define NAMX_STRUCT NAM
# ifdef NAM$M_NO_SHORT_UPCASE
# define SET_NAMX_NO_SHORT_UPCASE( nam) naml.naml$v_no_short_upcase = 1
# else /* def NAM$M_NO_SHORT_UPCASE */
# define SET_NAMX_NO_SHORT_UPCASE( nam)
# endif /* def NAM$M_NO_SHORT_UPCASE [else] */
#endif /* def NAML$C_MAXRSS [else] */
| 2,153 | 35.508475 | 74 | h |
openssl | openssl-master/crypto/aes/aes_cbc.c | /*
* Copyright 2002-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* AES 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 <openssl/aes.h>
#include <openssl/modes.h>
void AES_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const AES_KEY *key,
unsigned char *ivec, const int enc)
{
if (enc)
CRYPTO_cbc128_encrypt(in, out, len, key, ivec,
(block128_f) AES_encrypt);
else
CRYPTO_cbc128_decrypt(in, out, len, key, ivec,
(block128_f) AES_decrypt);
}
| 1,036 | 31.40625 | 80 | c |
openssl | openssl-master/crypto/aes/aes_cfb.c | /*
* Copyright 2002-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* AES_encrypt is deprecated - but we need to use it to implement these other
* deprecated APIs.
*/
#include "internal/deprecated.h"
#include <openssl/aes.h>
#include <openssl/modes.h>
/*
* The input and output encrypted as though 128bit cfb mode is being used.
* The extra state information to record how much of the 128bit block we have
* used is contained in *num;
*/
void AES_cfb128_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, int *num, const int enc)
{
CRYPTO_cfb128_encrypt(in, out, length, key, ivec, num, enc,
(block128_f) AES_encrypt);
}
/* N.B. This expects the input to be packed, MS bit first */
void AES_cfb1_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, int *num, const int enc)
{
CRYPTO_cfb128_1_encrypt(in, out, length, key, ivec, num, enc,
(block128_f) AES_encrypt);
}
void AES_cfb8_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, int *num, const int enc)
{
CRYPTO_cfb128_8_encrypt(in, out, length, key, ivec, num, enc,
(block128_f) AES_encrypt);
}
| 1,737 | 33.76 | 77 | c |
openssl | openssl-master/crypto/aes/aes_ecb.c | /*
* Copyright 2002-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <assert.h>
/*
* AES_encrypt/AES_decrypt are deprecated - but we need to use them to implement
* AES_ecb_encrypt
*/
#include "internal/deprecated.h"
#include <openssl/aes.h>
#include "aes_local.h"
void AES_ecb_encrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key, const int enc)
{
assert(in && out && key);
assert((AES_ENCRYPT == enc) || (AES_DECRYPT == enc));
if (AES_ENCRYPT == enc)
AES_encrypt(in, out, key);
else
AES_decrypt(in, out, key);
}
| 871 | 25.424242 | 80 | c |
openssl | openssl-master/crypto/aes/aes_ige.c | /*
* Copyright 2006-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
*/
/*
* AES_encrypt/AES_decrypt are deprecated - but we need to use them to implement
* these functions
*/
#include "internal/deprecated.h"
#include "internal/cryptlib.h"
#include <openssl/aes.h>
#include "aes_local.h"
/* XXX: probably some better way to do this */
#if defined(__i386__) || defined(__x86_64__)
# define UNALIGNED_MEMOPS_ARE_FAST 1
#else
# define UNALIGNED_MEMOPS_ARE_FAST 0
#endif
#define N_WORDS (AES_BLOCK_SIZE / sizeof(unsigned long))
typedef struct {
unsigned long data[N_WORDS];
#if defined(__GNUC__) && UNALIGNED_MEMOPS_ARE_FAST
} aes_block_t __attribute((__aligned__(1)));
#else
} aes_block_t;
#endif
#if UNALIGNED_MEMOPS_ARE_FAST
# define load_block(d, s) (d) = *(const aes_block_t *)(s)
# define store_block(d, s) *(aes_block_t *)(d) = (s)
#else
# define load_block(d, s) memcpy((d).data, (s), AES_BLOCK_SIZE)
# define store_block(d, s) memcpy((d), (s).data, AES_BLOCK_SIZE)
#endif
/* N.B. The IV for this mode is _twice_ the block size */
/* Use of this function is deprecated. */
void AES_ige_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, const int enc)
{
size_t n;
size_t len = length / AES_BLOCK_SIZE;
if (length == 0)
return;
OPENSSL_assert(in && out && key && ivec);
OPENSSL_assert((AES_ENCRYPT == enc) || (AES_DECRYPT == enc));
OPENSSL_assert((length % AES_BLOCK_SIZE) == 0);
if (AES_ENCRYPT == enc) {
if (in != out &&
(UNALIGNED_MEMOPS_ARE_FAST
|| ((size_t)in | (size_t)out | (size_t)ivec) % sizeof(long) ==
0)) {
aes_block_t *ivp = (aes_block_t *) ivec;
aes_block_t *iv2p = (aes_block_t *) (ivec + AES_BLOCK_SIZE);
while (len) {
aes_block_t *inp = (aes_block_t *) in;
aes_block_t *outp = (aes_block_t *) out;
for (n = 0; n < N_WORDS; ++n)
outp->data[n] = inp->data[n] ^ ivp->data[n];
AES_encrypt((unsigned char *)outp->data,
(unsigned char *)outp->data, key);
for (n = 0; n < N_WORDS; ++n)
outp->data[n] ^= iv2p->data[n];
ivp = outp;
iv2p = inp;
--len;
in += AES_BLOCK_SIZE;
out += AES_BLOCK_SIZE;
}
memcpy(ivec, ivp->data, AES_BLOCK_SIZE);
memcpy(ivec + AES_BLOCK_SIZE, iv2p->data, AES_BLOCK_SIZE);
} else {
aes_block_t tmp, tmp2;
aes_block_t iv;
aes_block_t iv2;
load_block(iv, ivec);
load_block(iv2, ivec + AES_BLOCK_SIZE);
while (len) {
load_block(tmp, in);
for (n = 0; n < N_WORDS; ++n)
tmp2.data[n] = tmp.data[n] ^ iv.data[n];
AES_encrypt((unsigned char *)tmp2.data,
(unsigned char *)tmp2.data, key);
for (n = 0; n < N_WORDS; ++n)
tmp2.data[n] ^= iv2.data[n];
store_block(out, tmp2);
iv = tmp2;
iv2 = tmp;
--len;
in += AES_BLOCK_SIZE;
out += AES_BLOCK_SIZE;
}
memcpy(ivec, iv.data, AES_BLOCK_SIZE);
memcpy(ivec + AES_BLOCK_SIZE, iv2.data, AES_BLOCK_SIZE);
}
} else {
if (in != out &&
(UNALIGNED_MEMOPS_ARE_FAST
|| ((size_t)in | (size_t)out | (size_t)ivec) % sizeof(long) ==
0)) {
aes_block_t *ivp = (aes_block_t *) ivec;
aes_block_t *iv2p = (aes_block_t *) (ivec + AES_BLOCK_SIZE);
while (len) {
aes_block_t tmp;
aes_block_t *inp = (aes_block_t *) in;
aes_block_t *outp = (aes_block_t *) out;
for (n = 0; n < N_WORDS; ++n)
tmp.data[n] = inp->data[n] ^ iv2p->data[n];
AES_decrypt((unsigned char *)tmp.data,
(unsigned char *)outp->data, key);
for (n = 0; n < N_WORDS; ++n)
outp->data[n] ^= ivp->data[n];
ivp = inp;
iv2p = outp;
--len;
in += AES_BLOCK_SIZE;
out += AES_BLOCK_SIZE;
}
memcpy(ivec, ivp->data, AES_BLOCK_SIZE);
memcpy(ivec + AES_BLOCK_SIZE, iv2p->data, AES_BLOCK_SIZE);
} else {
aes_block_t tmp, tmp2;
aes_block_t iv;
aes_block_t iv2;
load_block(iv, ivec);
load_block(iv2, ivec + AES_BLOCK_SIZE);
while (len) {
load_block(tmp, in);
tmp2 = tmp;
for (n = 0; n < N_WORDS; ++n)
tmp.data[n] ^= iv2.data[n];
AES_decrypt((unsigned char *)tmp.data,
(unsigned char *)tmp.data, key);
for (n = 0; n < N_WORDS; ++n)
tmp.data[n] ^= iv.data[n];
store_block(out, tmp);
iv = tmp2;
iv2 = tmp;
--len;
in += AES_BLOCK_SIZE;
out += AES_BLOCK_SIZE;
}
memcpy(ivec, iv.data, AES_BLOCK_SIZE);
memcpy(ivec + AES_BLOCK_SIZE, iv2.data, AES_BLOCK_SIZE);
}
}
}
/*
* Note that its effectively impossible to do biIGE in anything other
* than a single pass, so no provision is made for chaining.
*
* NB: The implementation of AES_bi_ige_encrypt has a bug. It is supposed to use
* 2 AES keys, but in fact only one is ever used. This bug has been present
* since this code was first implemented. It is believed to have minimal
* security impact in practice and has therefore not been fixed for backwards
* compatibility reasons.
*
* Use of this function is deprecated.
*/
/* N.B. The IV for this mode is _four times_ the block size */
void AES_bi_ige_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
const AES_KEY *key2, const unsigned char *ivec,
const int enc)
{
size_t n;
size_t len = length;
unsigned char tmp[AES_BLOCK_SIZE];
unsigned char tmp2[AES_BLOCK_SIZE];
unsigned char tmp3[AES_BLOCK_SIZE];
unsigned char prev[AES_BLOCK_SIZE];
const unsigned char *iv;
const unsigned char *iv2;
OPENSSL_assert(in && out && key && ivec);
OPENSSL_assert((AES_ENCRYPT == enc) || (AES_DECRYPT == enc));
OPENSSL_assert((length % AES_BLOCK_SIZE) == 0);
if (AES_ENCRYPT == enc) {
/*
* XXX: Do a separate case for when in != out (strictly should check
* for overlap, too)
*/
/* First the forward pass */
iv = ivec;
iv2 = ivec + AES_BLOCK_SIZE;
while (len >= AES_BLOCK_SIZE) {
for (n = 0; n < AES_BLOCK_SIZE; ++n)
out[n] = in[n] ^ iv[n];
AES_encrypt(out, out, key);
for (n = 0; n < AES_BLOCK_SIZE; ++n)
out[n] ^= iv2[n];
iv = out;
memcpy(prev, in, AES_BLOCK_SIZE);
iv2 = prev;
len -= AES_BLOCK_SIZE;
in += AES_BLOCK_SIZE;
out += AES_BLOCK_SIZE;
}
/* And now backwards */
iv = ivec + AES_BLOCK_SIZE * 2;
iv2 = ivec + AES_BLOCK_SIZE * 3;
len = length;
while (len >= AES_BLOCK_SIZE) {
out -= AES_BLOCK_SIZE;
/*
* XXX: reduce copies by alternating between buffers
*/
memcpy(tmp, out, AES_BLOCK_SIZE);
for (n = 0; n < AES_BLOCK_SIZE; ++n)
out[n] ^= iv[n];
/*
* hexdump(stdout, "out ^ iv", out, AES_BLOCK_SIZE);
*/
AES_encrypt(out, out, key);
/*
* hexdump(stdout,"enc", out, AES_BLOCK_SIZE);
*/
/*
* hexdump(stdout,"iv2", iv2, AES_BLOCK_SIZE);
*/
for (n = 0; n < AES_BLOCK_SIZE; ++n)
out[n] ^= iv2[n];
/*
* hexdump(stdout,"out", out, AES_BLOCK_SIZE);
*/
iv = out;
memcpy(prev, tmp, AES_BLOCK_SIZE);
iv2 = prev;
len -= AES_BLOCK_SIZE;
}
} else {
/* First backwards */
iv = ivec + AES_BLOCK_SIZE * 2;
iv2 = ivec + AES_BLOCK_SIZE * 3;
in += length;
out += length;
while (len >= AES_BLOCK_SIZE) {
in -= AES_BLOCK_SIZE;
out -= AES_BLOCK_SIZE;
memcpy(tmp, in, AES_BLOCK_SIZE);
memcpy(tmp2, in, AES_BLOCK_SIZE);
for (n = 0; n < AES_BLOCK_SIZE; ++n)
tmp[n] ^= iv2[n];
AES_decrypt(tmp, out, key);
for (n = 0; n < AES_BLOCK_SIZE; ++n)
out[n] ^= iv[n];
memcpy(tmp3, tmp2, AES_BLOCK_SIZE);
iv = tmp3;
iv2 = out;
len -= AES_BLOCK_SIZE;
}
/* And now forwards */
iv = ivec;
iv2 = ivec + AES_BLOCK_SIZE;
len = length;
while (len >= AES_BLOCK_SIZE) {
memcpy(tmp, out, AES_BLOCK_SIZE);
memcpy(tmp2, out, AES_BLOCK_SIZE);
for (n = 0; n < AES_BLOCK_SIZE; ++n)
tmp[n] ^= iv2[n];
AES_decrypt(tmp, out, key);
for (n = 0; n < AES_BLOCK_SIZE; ++n)
out[n] ^= iv[n];
memcpy(tmp3, tmp2, AES_BLOCK_SIZE);
iv = tmp3;
iv2 = out;
len -= AES_BLOCK_SIZE;
in += AES_BLOCK_SIZE;
out += AES_BLOCK_SIZE;
}
}
}
| 10,243 | 32.92053 | 80 | c |
openssl | openssl-master/crypto/aes/aes_local.h | /*
* Copyright 2002-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_CRYPTO_AES_LOCAL_H
# define OSSL_CRYPTO_AES_LOCAL_H
# include <openssl/e_os2.h>
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64))
# define SWAP(x) (_lrotl(x, 8) & 0x00ff00ff | _lrotr(x, 8) & 0xff00ff00)
# define GETU32(p) SWAP(*((u32 *)(p)))
# define PUTU32(ct, st) { *((u32 *)(ct)) = SWAP((st)); }
# else
# define GETU32(pt) (((u32)(pt)[0] << 24) ^ ((u32)(pt)[1] << 16) ^ ((u32)(pt)[2] << 8) ^ ((u32)(pt)[3]))
# define PUTU32(ct, st) { (ct)[0] = (u8)((st) >> 24); (ct)[1] = (u8)((st) >> 16); (ct)[2] = (u8)((st) >> 8); (ct)[3] = (u8)(st); }
# endif
typedef uint64_t u64;
# ifdef AES_LONG
typedef unsigned long u32;
# else
typedef unsigned int u32;
# endif
typedef unsigned short u16;
typedef unsigned char u8;
# define MAXKC (256/32)
# define MAXKB (256/8)
# define MAXNR 14
/* This controls loop-unrolling in aes_core.c */
# undef FULL_UNROLL
#endif /* !OSSL_CRYPTO_AES_LOCAL_H */
| 1,374 | 30.25 | 132 | h |
openssl | openssl-master/crypto/aes/aes_misc.c | /*
* Copyright 2002-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/opensslv.h>
#include <openssl/aes.h>
#include "aes_local.h"
#ifndef OPENSSL_NO_DEPRECATED_3_0
const char *AES_options(void)
{
# ifdef FULL_UNROLL
return "aes(full)";
# else
return "aes(partial)";
# endif
}
#endif
| 577 | 23.083333 | 74 | c |
openssl | openssl-master/crypto/aes/aes_ofb.c | /*
* Copyright 2002-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* AES_encrypt is deprecated - but we need to use it to implement
* AES_ofb128_encrypt
*/
#include "internal/deprecated.h"
#include <openssl/aes.h>
#include <openssl/modes.h>
void AES_ofb128_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, int *num)
{
CRYPTO_ofb128_encrypt(in, out, length, key, ivec, num,
(block128_f) AES_encrypt);
}
| 818 | 30.5 | 74 | c |
openssl | openssl-master/crypto/aes/aes_wrap.c | /*
* Copyright 2008-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
*/
/*
* AES_encrypt/AES_decrypt are deprecated - but we need to use them to implement
* these functions
*/
#include "internal/deprecated.h"
#include "internal/cryptlib.h"
#include <openssl/aes.h>
#include <openssl/modes.h>
int AES_wrap_key(AES_KEY *key, const unsigned char *iv,
unsigned char *out,
const unsigned char *in, unsigned int inlen)
{
return CRYPTO_128_wrap(key, iv, out, in, inlen, (block128_f) AES_encrypt);
}
int AES_unwrap_key(AES_KEY *key, const unsigned char *iv,
unsigned char *out,
const unsigned char *in, unsigned int inlen)
{
return CRYPTO_128_unwrap(key, iv, out, in, inlen,
(block128_f) AES_decrypt);
}
| 1,076 | 30.676471 | 80 | c |
openssl | openssl-master/crypto/asn1/a_bitstr.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 <limits.h>
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include "asn1_local.h"
int ASN1_BIT_STRING_set(ASN1_BIT_STRING *x, unsigned char *d, int len)
{
return ASN1_STRING_set(x, d, len);
}
int ossl_i2c_ASN1_BIT_STRING(ASN1_BIT_STRING *a, unsigned char **pp)
{
int ret, j, bits, len;
unsigned char *p, *d;
if (a == NULL)
return 0;
len = a->length;
if (len > 0) {
if (a->flags & ASN1_STRING_FLAG_BITS_LEFT) {
bits = (int)a->flags & 0x07;
} else {
for (; len > 0; len--) {
if (a->data[len - 1])
break;
}
j = a->data[len - 1];
if (j & 0x01)
bits = 0;
else if (j & 0x02)
bits = 1;
else if (j & 0x04)
bits = 2;
else if (j & 0x08)
bits = 3;
else if (j & 0x10)
bits = 4;
else if (j & 0x20)
bits = 5;
else if (j & 0x40)
bits = 6;
else if (j & 0x80)
bits = 7;
else
bits = 0; /* should not happen */
}
} else
bits = 0;
ret = 1 + len;
if (pp == NULL)
return ret;
p = *pp;
*(p++) = (unsigned char)bits;
d = a->data;
if (len > 0) {
memcpy(p, d, len);
p += len;
p[-1] &= (0xff << bits);
}
*pp = p;
return ret;
}
ASN1_BIT_STRING *ossl_c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a,
const unsigned char **pp, long len)
{
ASN1_BIT_STRING *ret = NULL;
const unsigned char *p;
unsigned char *s;
int i = 0;
if (len < 1) {
i = ASN1_R_STRING_TOO_SHORT;
goto err;
}
if (len > INT_MAX) {
i = ASN1_R_STRING_TOO_LONG;
goto err;
}
if ((a == NULL) || ((*a) == NULL)) {
if ((ret = ASN1_BIT_STRING_new()) == NULL)
return NULL;
} else
ret = (*a);
p = *pp;
i = *(p++);
if (i > 7) {
i = ASN1_R_INVALID_BIT_STRING_BITS_LEFT;
goto err;
}
/*
* We do this to preserve the settings. If we modify the settings, via
* the _set_bit function, we will recalculate on output
*/
ossl_asn1_string_set_bits_left(ret, i);
if (len-- > 1) { /* using one because of the bits left byte */
s = OPENSSL_malloc((int)len);
if (s == NULL) {
goto err;
}
memcpy(s, p, (int)len);
s[len - 1] &= (0xff << i);
p += len;
} else
s = NULL;
ASN1_STRING_set0(ret, s, (int)len);
ret->type = V_ASN1_BIT_STRING;
if (a != NULL)
(*a) = ret;
*pp = p;
return ret;
err:
if (i != 0)
ERR_raise(ERR_LIB_ASN1, i);
if ((a == NULL) || (*a != ret))
ASN1_BIT_STRING_free(ret);
return NULL;
}
/*
* These next 2 functions from Goetz Babin-Ebell.
*/
int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value)
{
int w, v, iv;
unsigned char *c;
if (n < 0)
return 0;
w = n / 8;
v = 1 << (7 - (n & 0x07));
iv = ~v;
if (!value)
v = 0;
if (a == NULL)
return 0;
a->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07); /* clear, set on write */
if ((a->length < (w + 1)) || (a->data == NULL)) {
if (!value)
return 1; /* Don't need to set */
c = OPENSSL_clear_realloc(a->data, a->length, w + 1);
if (c == NULL)
return 0;
if (w + 1 - a->length > 0)
memset(c + a->length, 0, w + 1 - a->length);
a->data = c;
a->length = w + 1;
}
a->data[w] = ((a->data[w]) & iv) | v;
while ((a->length > 0) && (a->data[a->length - 1] == 0))
a->length--;
return 1;
}
int ASN1_BIT_STRING_get_bit(const ASN1_BIT_STRING *a, int n)
{
int w, v;
if (n < 0)
return 0;
w = n / 8;
v = 1 << (7 - (n & 0x07));
if ((a == NULL) || (a->length < (w + 1)) || (a->data == NULL))
return 0;
return ((a->data[w] & v) != 0);
}
/*
* Checks if the given bit string contains only bits specified by
* the flags vector. Returns 0 if there is at least one bit set in 'a'
* which is not specified in 'flags', 1 otherwise.
* 'len' is the length of 'flags'.
*/
int ASN1_BIT_STRING_check(const ASN1_BIT_STRING *a,
const unsigned char *flags, int flags_len)
{
int i, ok;
/* Check if there is one bit set at all. */
if (!a || !a->data)
return 1;
/*
* Check each byte of the internal representation of the bit string.
*/
ok = 1;
for (i = 0; i < a->length && ok; ++i) {
unsigned char mask = i < flags_len ? ~flags[i] : 0xff;
/* We are done if there is an unneeded bit set. */
ok = (a->data[i] & mask) == 0;
}
return ok;
}
| 5,316 | 23.389908 | 79 | c |
openssl | openssl-master/crypto/asn1/a_d2i_fp.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 <limits.h>
#include "internal/cryptlib.h"
#include "internal/numbers.h"
#include <openssl/buffer.h>
#include <openssl/asn1.h>
#include "internal/asn1.h"
#include "crypto/asn1.h"
#ifndef NO_OLD_ASN1
# ifndef OPENSSL_NO_STDIO
void *ASN1_d2i_fp(void *(*xnew) (void), d2i_of_void *d2i, FILE *in, void **x)
{
BIO *b;
void *ret;
if ((b = BIO_new(BIO_s_file())) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB);
return NULL;
}
BIO_set_fp(b, in, BIO_NOCLOSE);
ret = ASN1_d2i_bio(xnew, d2i, b, x);
BIO_free(b);
return ret;
}
# endif
void *ASN1_d2i_bio(void *(*xnew) (void), d2i_of_void *d2i, BIO *in, void **x)
{
BUF_MEM *b = NULL;
const unsigned char *p;
void *ret = NULL;
int len;
len = asn1_d2i_read_bio(in, &b);
if (len < 0)
goto err;
p = (unsigned char *)b->data;
ret = d2i(x, &p, len);
err:
BUF_MEM_free(b);
return ret;
}
#endif
void *ASN1_item_d2i_bio_ex(const ASN1_ITEM *it, BIO *in, void *x,
OSSL_LIB_CTX *libctx, const char *propq)
{
BUF_MEM *b = NULL;
const unsigned char *p;
void *ret = NULL;
int len;
if (in == NULL)
return NULL;
len = asn1_d2i_read_bio(in, &b);
if (len < 0)
goto err;
p = (const unsigned char *)b->data;
ret = ASN1_item_d2i_ex(x, &p, len, it, libctx, propq);
err:
BUF_MEM_free(b);
return ret;
}
void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *x)
{
return ASN1_item_d2i_bio_ex(it, in, x, NULL, NULL);
}
#ifndef OPENSSL_NO_STDIO
void *ASN1_item_d2i_fp_ex(const ASN1_ITEM *it, FILE *in, void *x,
OSSL_LIB_CTX *libctx, const char *propq)
{
BIO *b;
char *ret;
if ((b = BIO_new(BIO_s_file())) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB);
return NULL;
}
BIO_set_fp(b, in, BIO_NOCLOSE);
ret = ASN1_item_d2i_bio_ex(it, b, x, libctx, propq);
BIO_free(b);
return ret;
}
void *ASN1_item_d2i_fp(const ASN1_ITEM *it, FILE *in, void *x)
{
return ASN1_item_d2i_fp_ex(it, in, x, NULL, NULL);
}
#endif
#define HEADER_SIZE 8
#define ASN1_CHUNK_INITIAL_SIZE (16 * 1024)
int asn1_d2i_read_bio(BIO *in, BUF_MEM **pb)
{
BUF_MEM *b;
unsigned char *p;
int i;
size_t want = HEADER_SIZE;
uint32_t eos = 0;
size_t off = 0;
size_t len = 0;
size_t diff;
const unsigned char *q;
long slen;
int inf, tag, xclass;
b = BUF_MEM_new();
if (b == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB);
return -1;
}
ERR_set_mark();
for (;;) {
diff = len - off;
if (want >= diff) {
want -= diff;
if (len + want < len || !BUF_MEM_grow_clean(b, len + want)) {
ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB);
goto err;
}
i = BIO_read(in, &(b->data[len]), want);
if (i < 0 && diff == 0) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_NOT_ENOUGH_DATA);
goto err;
}
if (i > 0) {
if (len + i < len) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LONG);
goto err;
}
len += i;
}
}
/* else data already loaded */
p = (unsigned char *)&(b->data[off]);
q = p;
diff = len - off;
if (diff == 0)
goto err;
inf = ASN1_get_object(&q, &slen, &tag, &xclass, diff);
if (inf & 0x80) {
unsigned long e;
e = ERR_GET_REASON(ERR_peek_last_error());
if (e != ASN1_R_TOO_LONG)
goto err;
ERR_pop_to_mark();
}
i = q - p; /* header length */
off += i; /* end of data */
if (inf & 1) {
/* no data body so go round again */
if (eos == UINT32_MAX) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_HEADER_TOO_LONG);
goto err;
}
eos++;
want = HEADER_SIZE;
} else if (eos && (slen == 0) && (tag == V_ASN1_EOC)) {
/* eos value, so go back and read another header */
eos--;
if (eos == 0)
break;
else
want = HEADER_SIZE;
} else {
/* suck in slen bytes of data */
want = slen;
if (want > (len - off)) {
size_t chunk_max = ASN1_CHUNK_INITIAL_SIZE;
want -= (len - off);
if (want > INT_MAX /* BIO_read takes an int length */ ||
len + want < len) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LONG);
goto err;
}
while (want > 0) {
/*
* Read content in chunks of increasing size
* so we can return an error for EOF without
* having to allocate the entire content length
* in one go.
*/
size_t chunk = want > chunk_max ? chunk_max : want;
if (!BUF_MEM_grow_clean(b, len + chunk)) {
ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB);
goto err;
}
want -= chunk;
while (chunk > 0) {
i = BIO_read(in, &(b->data[len]), chunk);
if (i <= 0) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_NOT_ENOUGH_DATA);
goto err;
}
/*
* This can't overflow because |len+want| didn't
* overflow.
*/
len += i;
chunk -= i;
}
if (chunk_max < INT_MAX/2)
chunk_max *= 2;
}
}
if (off + slen < off) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LONG);
goto err;
}
off += slen;
if (eos == 0) {
break;
} else
want = HEADER_SIZE;
}
}
if (off > INT_MAX) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LONG);
goto err;
}
*pb = b;
return off;
err:
ERR_clear_last_mark();
BUF_MEM_free(b);
return -1;
}
| 6,884 | 26.106299 | 77 | c |
openssl | openssl-master/crypto/asn1/a_digest.c | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* We need to use some engine deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include "internal/cryptlib.h"
#include <openssl/engine.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <openssl/x509.h>
#include "crypto/x509.h"
#ifndef OPENSSL_NO_DEPRECATED_3_0
int ASN1_digest(i2d_of_void *i2d, const EVP_MD *type, char *data,
unsigned char *md, unsigned int *len)
{
int inl;
unsigned char *str, *p;
inl = i2d(data, NULL);
if (inl <= 0) {
ERR_raise(ERR_LIB_ASN1, ERR_R_INTERNAL_ERROR);
return 0;
}
if ((str = OPENSSL_malloc(inl)) == NULL)
return 0;
p = str;
i2d(data, &p);
if (!EVP_Digest(str, inl, md, len, type, NULL)) {
OPENSSL_free(str);
return 0;
}
OPENSSL_free(str);
return 1;
}
#endif
int ossl_asn1_item_digest_ex(const ASN1_ITEM *it, const EVP_MD *md, void *asn,
unsigned char *data, unsigned int *len,
OSSL_LIB_CTX *libctx, const char *propq)
{
int i, ret = 0;
unsigned char *str = NULL;
EVP_MD *fetched_md = (EVP_MD *)md;
i = ASN1_item_i2d(asn, &str, it);
if (i < 0 || str == NULL)
return 0;
if (EVP_MD_get0_provider(md) == NULL) {
#if !defined(OPENSSL_NO_ENGINE)
ENGINE *tmpeng = ENGINE_get_digest_engine(EVP_MD_get_type(md));
if (tmpeng != NULL)
ENGINE_finish(tmpeng);
else
#endif
fetched_md = EVP_MD_fetch(libctx, EVP_MD_get0_name(md), propq);
}
if (fetched_md == NULL)
goto err;
ret = EVP_Digest(str, i, data, len, fetched_md, NULL);
err:
OPENSSL_free(str);
if (fetched_md != md)
EVP_MD_free(fetched_md);
return ret;
}
int ASN1_item_digest(const ASN1_ITEM *it, const EVP_MD *md, void *asn,
unsigned char *data, unsigned int *len)
{
return ossl_asn1_item_digest_ex(it, md, asn, data, len, NULL, NULL);
}
| 2,382 | 24.623656 | 78 | c |
openssl | openssl-master/crypto/asn1/a_dup.c | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1t.h>
#ifndef NO_OLD_ASN1
void *ASN1_dup(i2d_of_void *i2d, d2i_of_void *d2i, const void *x)
{
unsigned char *b, *p;
const unsigned char *p2;
int i;
char *ret;
if (x == NULL)
return NULL;
i = i2d(x, NULL);
if (i <= 0)
return NULL;
b = OPENSSL_malloc(i + 10);
if (b == NULL)
return NULL;
p = b;
i = i2d(x, &p);
p2 = b;
ret = d2i(NULL, &p2, i);
OPENSSL_free(b);
return ret;
}
#endif
/*
* ASN1_ITEM version of dup: this follows the model above except we don't
* need to allocate the buffer. At some point this could be rewritten to
* directly dup the underlying structure instead of doing and encode and
* decode.
*/
void *ASN1_item_dup(const ASN1_ITEM *it, const void *x)
{
ASN1_aux_cb *asn1_cb = NULL;
unsigned char *b = NULL;
const unsigned char *p;
long i;
ASN1_VALUE *ret;
OSSL_LIB_CTX *libctx = NULL;
const char *propq = NULL;
if (x == NULL)
return NULL;
if (it->itype == ASN1_ITYPE_SEQUENCE || it->itype == ASN1_ITYPE_CHOICE
|| it->itype == ASN1_ITYPE_NDEF_SEQUENCE) {
const ASN1_AUX *aux = it->funcs;
asn1_cb = aux != NULL ? aux->asn1_cb : NULL;
}
if (asn1_cb != NULL) {
if (!asn1_cb(ASN1_OP_DUP_PRE, (ASN1_VALUE **)&x, it, NULL)
|| !asn1_cb(ASN1_OP_GET0_LIBCTX, (ASN1_VALUE **)&x, it, &libctx)
|| !asn1_cb(ASN1_OP_GET0_PROPQ, (ASN1_VALUE **)&x, it, &propq))
goto auxerr;
}
i = ASN1_item_i2d(x, &b, it);
if (b == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
return NULL;
}
p = b;
ret = ASN1_item_d2i_ex(NULL, &p, i, it, libctx, propq);
OPENSSL_free(b);
if (asn1_cb != NULL
&& !asn1_cb(ASN1_OP_DUP_POST, &ret, it, (void *)x))
goto auxerr;
return ret;
auxerr:
ERR_raise_data(ERR_LIB_ASN1, ASN1_R_AUX_ERROR, "Type=%s", it->sname);
return NULL;
}
| 2,369 | 23.6875 | 80 | c |
openssl | openssl-master/crypto/asn1/a_gentm.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
*/
/*
* GENERALIZEDTIME implementation. Based on UTCTIME
*/
#include <stdio.h>
#include <time.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include "asn1_local.h"
#include <openssl/asn1t.h>
IMPLEMENT_ASN1_DUP_FUNCTION(ASN1_GENERALIZEDTIME)
/* This is the primary function used to parse ASN1_GENERALIZEDTIME */
static int asn1_generalizedtime_to_tm(struct tm *tm,
const ASN1_GENERALIZEDTIME *d)
{
/* wrapper around ossl_asn1_time_to_tm */
if (d->type != V_ASN1_GENERALIZEDTIME)
return 0;
return ossl_asn1_time_to_tm(tm, d);
}
int ASN1_GENERALIZEDTIME_check(const ASN1_GENERALIZEDTIME *d)
{
return asn1_generalizedtime_to_tm(NULL, d);
}
int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str)
{
ASN1_GENERALIZEDTIME t;
t.type = V_ASN1_GENERALIZEDTIME;
t.length = strlen(str);
t.data = (unsigned char *)str;
t.flags = 0;
if (!ASN1_GENERALIZEDTIME_check(&t))
return 0;
if (s != NULL && !ASN1_STRING_copy(s, &t))
return 0;
return 1;
}
ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_set(ASN1_GENERALIZEDTIME *s,
time_t t)
{
return ASN1_GENERALIZEDTIME_adj(s, t, 0, 0);
}
ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s,
time_t t, int offset_day,
long offset_sec)
{
struct tm *ts;
struct tm data;
ts = OPENSSL_gmtime(&t, &data);
if (ts == NULL)
return NULL;
if (offset_day || offset_sec) {
if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
return NULL;
}
return ossl_asn1_time_from_tm(s, ts, V_ASN1_GENERALIZEDTIME);
}
int ASN1_GENERALIZEDTIME_print(BIO *bp, const ASN1_GENERALIZEDTIME *tm)
{
if (tm->type != V_ASN1_GENERALIZEDTIME)
return 0;
return ASN1_TIME_print(bp, tm);
}
| 2,307 | 25.528736 | 77 | c |
openssl | openssl-master/crypto/asn1/a_int.c | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include "internal/numbers.h"
#include <limits.h>
#include <openssl/asn1.h>
#include <openssl/bn.h>
#include "asn1_local.h"
ASN1_INTEGER *ASN1_INTEGER_dup(const ASN1_INTEGER *x)
{
return ASN1_STRING_dup(x);
}
int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y)
{
int neg, ret;
/* Compare signs */
neg = x->type & V_ASN1_NEG;
if (neg != (y->type & V_ASN1_NEG)) {
if (neg)
return -1;
else
return 1;
}
ret = ASN1_STRING_cmp(x, y);
if (neg)
return -ret;
else
return ret;
}
/*-
* This converts a big endian buffer and sign into its content encoding.
* This is used for INTEGER and ENUMERATED types.
* The internal representation is an ASN1_STRING whose data is a big endian
* representation of the value, ignoring the sign. The sign is determined by
* the type: if type & V_ASN1_NEG is true it is negative, otherwise positive.
*
* Positive integers are no problem: they are almost the same as the DER
* encoding, except if the first byte is >= 0x80 we need to add a zero pad.
*
* Negative integers are a bit trickier...
* The DER representation of negative integers is in 2s complement form.
* The internal form is converted by complementing each octet and finally
* adding one to the result. This can be done less messily with a little trick.
* If the internal form has trailing zeroes then they will become FF by the
* complement and 0 by the add one (due to carry) so just copy as many trailing
* zeros to the destination as there are in the source. The carry will add one
* to the last none zero octet: so complement this octet and add one and finally
* complement any left over until you get to the start of the string.
*
* Padding is a little trickier too. If the first bytes is > 0x80 then we pad
* with 0xff. However if the first byte is 0x80 and one of the following bytes
* is non-zero we pad with 0xff. The reason for this distinction is that 0x80
* followed by optional zeros isn't padded.
*/
/*
* If |pad| is zero, the operation is effectively reduced to memcpy,
* and if |pad| is 0xff, then it performs two's complement, ~dst + 1.
* Note that in latter case sequence of zeros yields itself, and so
* does 0x80 followed by any number of zeros. These properties are
* used elsewhere below...
*/
static void twos_complement(unsigned char *dst, const unsigned char *src,
size_t len, unsigned char pad)
{
unsigned int carry = pad & 1;
/* Begin at the end of the encoding */
if (len != 0) {
/*
* if len == 0 then src/dst could be NULL, and this would be undefined
* behaviour.
*/
dst += len;
src += len;
}
/* two's complement value: ~value + 1 */
while (len-- != 0) {
*(--dst) = (unsigned char)(carry += *(--src) ^ pad);
carry >>= 8;
}
}
static size_t i2c_ibuf(const unsigned char *b, size_t blen, int neg,
unsigned char **pp)
{
unsigned int pad = 0;
size_t ret, i;
unsigned char *p, pb = 0;
if (b != NULL && blen) {
ret = blen;
i = b[0];
if (!neg && (i > 127)) {
pad = 1;
pb = 0;
} else if (neg) {
pb = 0xFF;
if (i > 128) {
pad = 1;
} else if (i == 128) {
/*
* Special case [of minimal negative for given length]:
* if any other bytes non zero we pad, otherwise we don't.
*/
for (pad = 0, i = 1; i < blen; i++)
pad |= b[i];
pb = pad != 0 ? 0xffU : 0;
pad = pb & 1;
}
}
ret += pad;
} else {
ret = 1;
blen = 0; /* reduce '(b == NULL || blen == 0)' to '(blen == 0)' */
}
if (pp == NULL || (p = *pp) == NULL)
return ret;
/*
* This magically handles all corner cases, such as '(b == NULL ||
* blen == 0)', non-negative value, "negative" zero, 0x80 followed
* by any number of zeros...
*/
*p = pb;
p += pad; /* yes, p[0] can be written twice, but it's little
* price to pay for eliminated branches */
twos_complement(p, b, blen, pb);
*pp += ret;
return ret;
}
/*
* convert content octets into a big endian buffer. Returns the length
* of buffer or 0 on error: for malformed INTEGER. If output buffer is
* NULL just return length.
*/
static size_t c2i_ibuf(unsigned char *b, int *pneg,
const unsigned char *p, size_t plen)
{
int neg, pad;
/* Zero content length is illegal */
if (plen == 0) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_ZERO_CONTENT);
return 0;
}
neg = p[0] & 0x80;
if (pneg)
*pneg = neg;
/* Handle common case where length is 1 octet separately */
if (plen == 1) {
if (b != NULL) {
if (neg)
b[0] = (p[0] ^ 0xFF) + 1;
else
b[0] = p[0];
}
return 1;
}
pad = 0;
if (p[0] == 0) {
pad = 1;
} else if (p[0] == 0xFF) {
size_t i;
/*
* Special case [of "one less minimal negative" for given length]:
* if any other bytes non zero it was padded, otherwise not.
*/
for (pad = 0, i = 1; i < plen; i++)
pad |= p[i];
pad = pad != 0 ? 1 : 0;
}
/* reject illegal padding: first two octets MSB can't match */
if (pad && (neg == (p[1] & 0x80))) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_PADDING);
return 0;
}
/* skip over pad */
p += pad;
plen -= pad;
if (b != NULL)
twos_complement(b, p, plen, neg ? 0xffU : 0);
return plen;
}
int ossl_i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp)
{
return i2c_ibuf(a->data, a->length, a->type & V_ASN1_NEG, pp);
}
/* Convert big endian buffer into uint64_t, return 0 on error */
static int asn1_get_uint64(uint64_t *pr, const unsigned char *b, size_t blen)
{
size_t i;
uint64_t r;
if (blen > sizeof(*pr)) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LARGE);
return 0;
}
if (b == NULL)
return 0;
for (r = 0, i = 0; i < blen; i++) {
r <<= 8;
r |= b[i];
}
*pr = r;
return 1;
}
/*
* Write uint64_t to big endian buffer and return offset to first
* written octet. In other words it returns offset in range from 0
* to 7, with 0 denoting 8 written octets and 7 - one.
*/
static size_t asn1_put_uint64(unsigned char b[sizeof(uint64_t)], uint64_t r)
{
size_t off = sizeof(uint64_t);
do {
b[--off] = (unsigned char)r;
} while (r >>= 8);
return off;
}
/*
* Absolute value of INT64_MIN: we can't just use -INT64_MIN as gcc produces
* overflow warnings.
*/
#define ABS_INT64_MIN ((uint64_t)INT64_MAX + (-(INT64_MIN + INT64_MAX)))
/* signed version of asn1_get_uint64 */
static int asn1_get_int64(int64_t *pr, const unsigned char *b, size_t blen,
int neg)
{
uint64_t r;
if (asn1_get_uint64(&r, b, blen) == 0)
return 0;
if (neg) {
if (r <= INT64_MAX) {
/* Most significant bit is guaranteed to be clear, negation
* is guaranteed to be meaningful in platform-neutral sense. */
*pr = -(int64_t)r;
} else if (r == ABS_INT64_MIN) {
/* This never happens if INT64_MAX == ABS_INT64_MIN, e.g.
* on ones'-complement system. */
*pr = (int64_t)(0 - r);
} else {
ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_SMALL);
return 0;
}
} else {
if (r <= INT64_MAX) {
*pr = (int64_t)r;
} else {
ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LARGE);
return 0;
}
}
return 1;
}
/* Convert ASN1 INTEGER content octets to ASN1_INTEGER structure */
ASN1_INTEGER *ossl_c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp,
long len)
{
ASN1_INTEGER *ret = NULL;
size_t r;
int neg;
r = c2i_ibuf(NULL, NULL, *pp, len);
if (r == 0)
return NULL;
if ((a == NULL) || ((*a) == NULL)) {
ret = ASN1_INTEGER_new();
if (ret == NULL)
return NULL;
ret->type = V_ASN1_INTEGER;
} else
ret = *a;
if (ASN1_STRING_set(ret, NULL, r) == 0) {
ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
goto err;
}
c2i_ibuf(ret->data, &neg, *pp, len);
if (neg != 0)
ret->type |= V_ASN1_NEG;
else
ret->type &= ~V_ASN1_NEG;
*pp += len;
if (a != NULL)
(*a) = ret;
return ret;
err:
if (a == NULL || *a != ret)
ASN1_INTEGER_free(ret);
return NULL;
}
static int asn1_string_get_int64(int64_t *pr, const ASN1_STRING *a, int itype)
{
if (a == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if ((a->type & ~V_ASN1_NEG) != itype) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_WRONG_INTEGER_TYPE);
return 0;
}
return asn1_get_int64(pr, a->data, a->length, a->type & V_ASN1_NEG);
}
static int asn1_string_set_int64(ASN1_STRING *a, int64_t r, int itype)
{
unsigned char tbuf[sizeof(r)];
size_t off;
a->type = itype;
if (r < 0) {
/* Most obvious '-r' triggers undefined behaviour for most
* common INT64_MIN. Even though below '0 - (uint64_t)r' can
* appear two's-complement centric, it does produce correct/
* expected result even on one's-complement. This is because
* cast to unsigned has to change bit pattern... */
off = asn1_put_uint64(tbuf, 0 - (uint64_t)r);
a->type |= V_ASN1_NEG;
} else {
off = asn1_put_uint64(tbuf, r);
a->type &= ~V_ASN1_NEG;
}
return ASN1_STRING_set(a, tbuf + off, sizeof(tbuf) - off);
}
static int asn1_string_get_uint64(uint64_t *pr, const ASN1_STRING *a,
int itype)
{
if (a == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if ((a->type & ~V_ASN1_NEG) != itype) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_WRONG_INTEGER_TYPE);
return 0;
}
if (a->type & V_ASN1_NEG) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_NEGATIVE_VALUE);
return 0;
}
return asn1_get_uint64(pr, a->data, a->length);
}
static int asn1_string_set_uint64(ASN1_STRING *a, uint64_t r, int itype)
{
unsigned char tbuf[sizeof(r)];
size_t off;
a->type = itype;
off = asn1_put_uint64(tbuf, r);
return ASN1_STRING_set(a, tbuf + off, sizeof(tbuf) - off);
}
/*
* This is a version of d2i_ASN1_INTEGER that ignores the sign bit of ASN1
* integers: some broken software can encode a positive INTEGER with its MSB
* set as negative (it doesn't add a padding zero).
*/
ASN1_INTEGER *d2i_ASN1_UINTEGER(ASN1_INTEGER **a, const unsigned char **pp,
long length)
{
ASN1_INTEGER *ret = NULL;
const unsigned char *p;
unsigned char *s;
long len = 0;
int inf, tag, xclass;
int i = 0;
if ((a == NULL) || ((*a) == NULL)) {
if ((ret = ASN1_INTEGER_new()) == NULL)
return NULL;
ret->type = V_ASN1_INTEGER;
} else
ret = (*a);
p = *pp;
inf = ASN1_get_object(&p, &len, &tag, &xclass, length);
if (inf & 0x80) {
i = ASN1_R_BAD_OBJECT_HEADER;
goto err;
}
if (tag != V_ASN1_INTEGER) {
i = ASN1_R_EXPECTING_AN_INTEGER;
goto err;
}
if (len < 0) {
i = ASN1_R_ILLEGAL_NEGATIVE_VALUE;
goto err;
}
/*
* We must OPENSSL_malloc stuff, even for 0 bytes otherwise it signifies
* a missing NULL parameter.
*/
s = OPENSSL_malloc((int)len + 1);
if (s == NULL)
goto err;
ret->type = V_ASN1_INTEGER;
if (len) {
if ((*p == 0) && (len != 1)) {
p++;
len--;
}
memcpy(s, p, (int)len);
p += len;
}
ASN1_STRING_set0(ret, s, (int)len);
if (a != NULL)
(*a) = ret;
*pp = p;
return ret;
err:
if (i != 0)
ERR_raise(ERR_LIB_ASN1, i);
if ((a == NULL) || (*a != ret))
ASN1_INTEGER_free(ret);
return NULL;
}
static ASN1_STRING *bn_to_asn1_string(const BIGNUM *bn, ASN1_STRING *ai,
int atype)
{
ASN1_INTEGER *ret;
int len;
if (ai == NULL) {
ret = ASN1_STRING_type_new(atype);
} else {
ret = ai;
ret->type = atype;
}
if (ret == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_NESTED_ASN1_ERROR);
goto err;
}
if (BN_is_negative(bn) && !BN_is_zero(bn))
ret->type |= V_ASN1_NEG_INTEGER;
len = BN_num_bytes(bn);
if (len == 0)
len = 1;
if (ASN1_STRING_set(ret, NULL, len) == 0) {
ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
goto err;
}
/* Correct zero case */
if (BN_is_zero(bn))
ret->data[0] = 0;
else
len = BN_bn2bin(bn, ret->data);
ret->length = len;
return ret;
err:
if (ret != ai)
ASN1_INTEGER_free(ret);
return NULL;
}
static BIGNUM *asn1_string_to_bn(const ASN1_INTEGER *ai, BIGNUM *bn,
int itype)
{
BIGNUM *ret;
if ((ai->type & ~V_ASN1_NEG) != itype) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_WRONG_INTEGER_TYPE);
return NULL;
}
ret = BN_bin2bn(ai->data, ai->length, bn);
if (ret == NULL) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_BN_LIB);
return NULL;
}
if (ai->type & V_ASN1_NEG)
BN_set_negative(ret, 1);
return ret;
}
int ASN1_INTEGER_get_int64(int64_t *pr, const ASN1_INTEGER *a)
{
return asn1_string_get_int64(pr, a, V_ASN1_INTEGER);
}
int ASN1_INTEGER_set_int64(ASN1_INTEGER *a, int64_t r)
{
return asn1_string_set_int64(a, r, V_ASN1_INTEGER);
}
int ASN1_INTEGER_get_uint64(uint64_t *pr, const ASN1_INTEGER *a)
{
return asn1_string_get_uint64(pr, a, V_ASN1_INTEGER);
}
int ASN1_INTEGER_set_uint64(ASN1_INTEGER *a, uint64_t r)
{
return asn1_string_set_uint64(a, r, V_ASN1_INTEGER);
}
int ASN1_INTEGER_set(ASN1_INTEGER *a, long v)
{
return ASN1_INTEGER_set_int64(a, v);
}
long ASN1_INTEGER_get(const ASN1_INTEGER *a)
{
int i;
int64_t r;
if (a == NULL)
return 0;
i = ASN1_INTEGER_get_int64(&r, a);
if (i == 0)
return -1;
if (r > LONG_MAX || r < LONG_MIN)
return -1;
return (long)r;
}
ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai)
{
return bn_to_asn1_string(bn, ai, V_ASN1_INTEGER);
}
BIGNUM *ASN1_INTEGER_to_BN(const ASN1_INTEGER *ai, BIGNUM *bn)
{
return asn1_string_to_bn(ai, bn, V_ASN1_INTEGER);
}
int ASN1_ENUMERATED_get_int64(int64_t *pr, const ASN1_ENUMERATED *a)
{
return asn1_string_get_int64(pr, a, V_ASN1_ENUMERATED);
}
int ASN1_ENUMERATED_set_int64(ASN1_ENUMERATED *a, int64_t r)
{
return asn1_string_set_int64(a, r, V_ASN1_ENUMERATED);
}
int ASN1_ENUMERATED_set(ASN1_ENUMERATED *a, long v)
{
return ASN1_ENUMERATED_set_int64(a, v);
}
long ASN1_ENUMERATED_get(const ASN1_ENUMERATED *a)
{
int i;
int64_t r;
if (a == NULL)
return 0;
if ((a->type & ~V_ASN1_NEG) != V_ASN1_ENUMERATED)
return -1;
if (a->length > (int)sizeof(long))
return 0xffffffffL;
i = ASN1_ENUMERATED_get_int64(&r, a);
if (i == 0)
return -1;
if (r > LONG_MAX || r < LONG_MIN)
return -1;
return (long)r;
}
ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(const BIGNUM *bn, ASN1_ENUMERATED *ai)
{
return bn_to_asn1_string(bn, ai, V_ASN1_ENUMERATED);
}
BIGNUM *ASN1_ENUMERATED_to_BN(const ASN1_ENUMERATED *ai, BIGNUM *bn)
{
return asn1_string_to_bn(ai, bn, V_ASN1_ENUMERATED);
}
/* Internal functions used by x_int64.c */
int ossl_c2i_uint64_int(uint64_t *ret, int *neg,
const unsigned char **pp, long len)
{
unsigned char buf[sizeof(uint64_t)];
size_t buflen;
buflen = c2i_ibuf(NULL, NULL, *pp, len);
if (buflen == 0)
return 0;
if (buflen > sizeof(uint64_t)) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LARGE);
return 0;
}
(void)c2i_ibuf(buf, neg, *pp, len);
return asn1_get_uint64(ret, buf, buflen);
}
int ossl_i2c_uint64_int(unsigned char *p, uint64_t r, int neg)
{
unsigned char buf[sizeof(uint64_t)];
size_t off;
off = asn1_put_uint64(buf, r);
return i2c_ibuf(buf + off, sizeof(buf) - off, neg, &p);
}
| 17,079 | 25.604361 | 80 | c |
openssl | openssl-master/crypto/asn1/a_mbstr.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 "crypto/ctype.h"
#include "internal/cryptlib.h"
#include "internal/unicode.h"
#include <openssl/asn1.h>
static int traverse_string(const unsigned char *p, int len, int inform,
int (*rfunc) (unsigned long value, void *in),
void *arg);
static int in_utf8(unsigned long value, void *arg);
static int out_utf8(unsigned long value, void *arg);
static int type_str(unsigned long value, void *arg);
static int cpy_asc(unsigned long value, void *arg);
static int cpy_bmp(unsigned long value, void *arg);
static int cpy_univ(unsigned long value, void *arg);
static int cpy_utf8(unsigned long value, void *arg);
/*
* These functions take a string in UTF8, ASCII or multibyte form and a mask
* of permissible ASN1 string types. It then works out the minimal type
* (using the order Numeric < Printable < IA5 < T61 < BMP < Universal < UTF8)
* and creates a string of the correct type with the supplied data. Yes this is
* horrible: it has to be :-( The 'ncopy' form checks minimum and maximum
* size limits too.
*/
int ASN1_mbstring_copy(ASN1_STRING **out, const unsigned char *in, int len,
int inform, unsigned long mask)
{
return ASN1_mbstring_ncopy(out, in, len, inform, mask, 0, 0);
}
int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
int inform, unsigned long mask,
long minsize, long maxsize)
{
int str_type;
int ret;
char free_out;
int outform, outlen = 0;
ASN1_STRING *dest;
unsigned char *p;
int nchar;
int (*cpyfunc) (unsigned long, void *) = NULL;
if (len == -1)
len = strlen((const char *)in);
if (!mask)
mask = DIRSTRING_TYPE;
if (len < 0)
return -1;
/* First do a string check and work out the number of characters */
switch (inform) {
case MBSTRING_BMP:
if (len & 1) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_BMPSTRING_LENGTH);
return -1;
}
nchar = len >> 1;
break;
case MBSTRING_UNIV:
if (len & 3) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_UNIVERSALSTRING_LENGTH);
return -1;
}
nchar = len >> 2;
break;
case MBSTRING_UTF8:
nchar = 0;
/* This counts the characters and does utf8 syntax checking */
ret = traverse_string(in, len, MBSTRING_UTF8, in_utf8, &nchar);
if (ret < 0) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_UTF8STRING);
return -1;
}
break;
case MBSTRING_ASC:
nchar = len;
break;
default:
ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_FORMAT);
return -1;
}
if ((minsize > 0) && (nchar < minsize)) {
ERR_raise_data(ERR_LIB_ASN1, ASN1_R_STRING_TOO_SHORT,
"minsize=%ld", minsize);
return -1;
}
if ((maxsize > 0) && (nchar > maxsize)) {
ERR_raise_data(ERR_LIB_ASN1, ASN1_R_STRING_TOO_LONG,
"maxsize=%ld", maxsize);
return -1;
}
/* Now work out minimal type (if any) */
if (traverse_string(in, len, inform, type_str, &mask) < 0) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_CHARACTERS);
return -1;
}
/* Now work out output format and string type */
outform = MBSTRING_ASC;
if (mask & B_ASN1_NUMERICSTRING)
str_type = V_ASN1_NUMERICSTRING;
else if (mask & B_ASN1_PRINTABLESTRING)
str_type = V_ASN1_PRINTABLESTRING;
else if (mask & B_ASN1_IA5STRING)
str_type = V_ASN1_IA5STRING;
else if (mask & B_ASN1_T61STRING)
str_type = V_ASN1_T61STRING;
else if (mask & B_ASN1_BMPSTRING) {
str_type = V_ASN1_BMPSTRING;
outform = MBSTRING_BMP;
} else if (mask & B_ASN1_UNIVERSALSTRING) {
str_type = V_ASN1_UNIVERSALSTRING;
outform = MBSTRING_UNIV;
} else {
str_type = V_ASN1_UTF8STRING;
outform = MBSTRING_UTF8;
}
if (!out)
return str_type;
if (*out) {
free_out = 0;
dest = *out;
ASN1_STRING_set0(dest, NULL, 0);
dest->type = str_type;
} else {
free_out = 1;
dest = ASN1_STRING_type_new(str_type);
if (dest == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
return -1;
}
*out = dest;
}
/* If both the same type just copy across */
if (inform == outform) {
if (!ASN1_STRING_set(dest, in, len)) {
ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
return -1;
}
return str_type;
}
/* Work out how much space the destination will need */
switch (outform) {
case MBSTRING_ASC:
outlen = nchar;
cpyfunc = cpy_asc;
break;
case MBSTRING_BMP:
outlen = nchar << 1;
cpyfunc = cpy_bmp;
break;
case MBSTRING_UNIV:
outlen = nchar << 2;
cpyfunc = cpy_univ;
break;
case MBSTRING_UTF8:
outlen = 0;
traverse_string(in, len, inform, out_utf8, &outlen);
cpyfunc = cpy_utf8;
break;
}
if ((p = OPENSSL_malloc(outlen + 1)) == NULL) {
if (free_out)
ASN1_STRING_free(dest);
return -1;
}
dest->length = outlen;
dest->data = p;
p[outlen] = 0;
traverse_string(in, len, inform, cpyfunc, &p);
return str_type;
}
/*
* This function traverses a string and passes the value of each character to
* an optional function along with a void * argument.
*/
static int traverse_string(const unsigned char *p, int len, int inform,
int (*rfunc) (unsigned long value, void *in),
void *arg)
{
unsigned long value;
int ret;
while (len) {
if (inform == MBSTRING_ASC) {
value = *p++;
len--;
} else if (inform == MBSTRING_BMP) {
value = *p++ << 8;
value |= *p++;
len -= 2;
} else if (inform == MBSTRING_UNIV) {
value = ((unsigned long)*p++) << 24;
value |= ((unsigned long)*p++) << 16;
value |= *p++ << 8;
value |= *p++;
len -= 4;
} else {
ret = UTF8_getc(p, len, &value);
if (ret < 0)
return -1;
len -= ret;
p += ret;
}
if (rfunc) {
ret = rfunc(value, arg);
if (ret <= 0)
return ret;
}
}
return 1;
}
/* Various utility functions for traverse_string */
/* Just count number of characters */
static int in_utf8(unsigned long value, void *arg)
{
int *nchar;
if (!is_unicode_valid(value))
return -2;
nchar = arg;
(*nchar)++;
return 1;
}
/* Determine size of output as a UTF8 String */
static int out_utf8(unsigned long value, void *arg)
{
int *outlen, len;
len = UTF8_putc(NULL, -1, value);
if (len <= 0)
return len;
outlen = arg;
*outlen += len;
return 1;
}
/*
* Determine the "type" of a string: check each character against a supplied
* "mask".
*/
static int type_str(unsigned long value, void *arg)
{
unsigned long types = *((unsigned long *)arg);
const int native = value > INT_MAX ? INT_MAX : ossl_fromascii(value);
if ((types & B_ASN1_NUMERICSTRING) && !(ossl_isdigit(native)
|| native == ' '))
types &= ~B_ASN1_NUMERICSTRING;
if ((types & B_ASN1_PRINTABLESTRING) && !ossl_isasn1print(native))
types &= ~B_ASN1_PRINTABLESTRING;
if ((types & B_ASN1_IA5STRING) && !ossl_isascii(native))
types &= ~B_ASN1_IA5STRING;
if ((types & B_ASN1_T61STRING) && (value > 0xff))
types &= ~B_ASN1_T61STRING;
if ((types & B_ASN1_BMPSTRING) && (value > 0xffff))
types &= ~B_ASN1_BMPSTRING;
if ((types & B_ASN1_UTF8STRING) && !is_unicode_valid(value))
types &= ~B_ASN1_UTF8STRING;
if (!types)
return -1;
*((unsigned long *)arg) = types;
return 1;
}
/* Copy one byte per character ASCII like strings */
static int cpy_asc(unsigned long value, void *arg)
{
unsigned char **p, *q;
p = arg;
q = *p;
*q = (unsigned char)value;
(*p)++;
return 1;
}
/* Copy two byte per character BMPStrings */
static int cpy_bmp(unsigned long value, void *arg)
{
unsigned char **p, *q;
p = arg;
q = *p;
*q++ = (unsigned char)((value >> 8) & 0xff);
*q = (unsigned char)(value & 0xff);
*p += 2;
return 1;
}
/* Copy four byte per character UniversalStrings */
static int cpy_univ(unsigned long value, void *arg)
{
unsigned char **p, *q;
p = arg;
q = *p;
*q++ = (unsigned char)((value >> 24) & 0xff);
*q++ = (unsigned char)((value >> 16) & 0xff);
*q++ = (unsigned char)((value >> 8) & 0xff);
*q = (unsigned char)(value & 0xff);
*p += 4;
return 1;
}
/* Copy to a UTF8String */
static int cpy_utf8(unsigned long value, void *arg)
{
unsigned char **p;
int ret;
p = arg;
/* We already know there is enough room so pass 0xff as the length */
ret = UTF8_putc(*p, 0xff, value);
*p += ret;
return 1;
}
| 9,644 | 26.715517 | 79 | c |
openssl | openssl-master/crypto/asn1/a_object.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 <limits.h>
#include "crypto/ctype.h"
#include "internal/cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/asn1.h>
#include <openssl/objects.h>
#include <openssl/bn.h>
#include "crypto/asn1.h"
#include "asn1_local.h"
int i2d_ASN1_OBJECT(const ASN1_OBJECT *a, unsigned char **pp)
{
unsigned char *p, *allocated = NULL;
int objsize;
if ((a == NULL) || (a->data == NULL))
return 0;
objsize = ASN1_object_size(0, a->length, V_ASN1_OBJECT);
if (pp == NULL || objsize == -1)
return objsize;
if (*pp == NULL) {
if ((p = allocated = OPENSSL_malloc(objsize)) == NULL)
return 0;
} else {
p = *pp;
}
ASN1_put_object(&p, 0, a->length, V_ASN1_OBJECT, V_ASN1_UNIVERSAL);
memcpy(p, a->data, a->length);
/*
* If a new buffer was allocated, just return it back.
* If not, return the incremented buffer pointer.
*/
*pp = allocated != NULL ? allocated : p + a->length;
return objsize;
}
int a2d_ASN1_OBJECT(unsigned char *out, int olen, const char *buf, int num)
{
int i, first, len = 0, c, use_bn;
char ftmp[24], *tmp = ftmp;
int tmpsize = sizeof(ftmp);
const char *p;
unsigned long l;
BIGNUM *bl = NULL;
if (num == 0)
return 0;
else if (num == -1)
num = strlen(buf);
p = buf;
c = *(p++);
num--;
if ((c >= '0') && (c <= '2')) {
first = c - '0';
} else {
ERR_raise(ERR_LIB_ASN1, ASN1_R_FIRST_NUM_TOO_LARGE);
goto err;
}
if (num <= 0) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_MISSING_SECOND_NUMBER);
goto err;
}
c = *(p++);
num--;
for (;;) {
if (num <= 0)
break;
if ((c != '.') && (c != ' ')) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_SEPARATOR);
goto err;
}
l = 0;
use_bn = 0;
for (;;) {
if (num <= 0)
break;
num--;
c = *(p++);
if ((c == ' ') || (c == '.'))
break;
if (!ossl_isdigit(c)) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_DIGIT);
goto err;
}
if (!use_bn && l >= ((ULONG_MAX - 80) / 10L)) {
use_bn = 1;
if (bl == NULL)
bl = BN_new();
if (bl == NULL || !BN_set_word(bl, l))
goto err;
}
if (use_bn) {
if (!BN_mul_word(bl, 10L)
|| !BN_add_word(bl, c - '0'))
goto err;
} else
l = l * 10L + (long)(c - '0');
}
if (len == 0) {
if ((first < 2) && (l >= 40)) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_SECOND_NUMBER_TOO_LARGE);
goto err;
}
if (use_bn) {
if (!BN_add_word(bl, first * 40))
goto err;
} else
l += (long)first *40;
}
i = 0;
if (use_bn) {
int blsize;
blsize = BN_num_bits(bl);
blsize = (blsize + 6) / 7;
if (blsize > tmpsize) {
if (tmp != ftmp)
OPENSSL_free(tmp);
tmpsize = blsize + 32;
tmp = OPENSSL_malloc(tmpsize);
if (tmp == NULL)
goto err;
}
while (blsize--) {
BN_ULONG t = BN_div_word(bl, 0x80L);
if (t == (BN_ULONG)-1)
goto err;
tmp[i++] = (unsigned char)t;
}
} else {
for (;;) {
tmp[i++] = (unsigned char)l & 0x7f;
l >>= 7L;
if (l == 0L)
break;
}
}
if (out != NULL) {
if (len + i > olen) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_BUFFER_TOO_SMALL);
goto err;
}
while (--i > 0)
out[len++] = tmp[i] | 0x80;
out[len++] = tmp[0];
} else
len += i;
}
if (tmp != ftmp)
OPENSSL_free(tmp);
BN_free(bl);
return len;
err:
if (tmp != ftmp)
OPENSSL_free(tmp);
BN_free(bl);
return 0;
}
int i2t_ASN1_OBJECT(char *buf, int buf_len, const ASN1_OBJECT *a)
{
return OBJ_obj2txt(buf, buf_len, a, 0);
}
int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a)
{
char buf[80], *p = buf;
int i;
if ((a == NULL) || (a->data == NULL))
return BIO_write(bp, "NULL", 4);
i = i2t_ASN1_OBJECT(buf, sizeof(buf), a);
if (i > (int)(sizeof(buf) - 1)) {
if (i > INT_MAX - 1) { /* catch an integer overflow */
ERR_raise(ERR_LIB_ASN1, ASN1_R_LENGTH_TOO_LONG);
return -1;
}
if ((p = OPENSSL_malloc(i + 1)) == NULL)
return -1;
i2t_ASN1_OBJECT(p, i + 1, a);
}
if (i <= 0) {
i = BIO_write(bp, "<INVALID>", 9);
i += BIO_dump(bp, (const char *)a->data, a->length);
return i;
}
BIO_write(bp, p, i);
if (p != buf)
OPENSSL_free(p);
return i;
}
ASN1_OBJECT *d2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp,
long length)
{
const unsigned char *p;
long len;
int tag, xclass;
int inf, i;
ASN1_OBJECT *ret = NULL;
p = *pp;
inf = ASN1_get_object(&p, &len, &tag, &xclass, length);
if (inf & 0x80) {
i = ASN1_R_BAD_OBJECT_HEADER;
goto err;
}
if (tag != V_ASN1_OBJECT) {
i = ASN1_R_EXPECTING_AN_OBJECT;
goto err;
}
ret = ossl_c2i_ASN1_OBJECT(a, &p, len);
if (ret)
*pp = p;
return ret;
err:
ERR_raise(ERR_LIB_ASN1, i);
return NULL;
}
ASN1_OBJECT *ossl_c2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp,
long len)
{
ASN1_OBJECT *ret = NULL, tobj;
const unsigned char *p;
unsigned char *data;
int i, length;
/*
* Sanity check OID encoding. Need at least one content octet. MSB must
* be clear in the last octet. can't have leading 0x80 in subidentifiers,
* see: X.690 8.19.2
*/
if (len <= 0 || len > INT_MAX || pp == NULL || (p = *pp) == NULL ||
p[len - 1] & 0x80) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_OBJECT_ENCODING);
return NULL;
}
/* Now 0 < len <= INT_MAX, so the cast is safe. */
length = (int)len;
/*
* Try to lookup OID in table: these are all valid encodings so if we get
* a match we know the OID is valid.
*/
tobj.nid = NID_undef;
tobj.data = p;
tobj.length = length;
tobj.flags = 0;
i = OBJ_obj2nid(&tobj);
if (i != NID_undef) {
/*
* Return shared registered OID object: this improves efficiency
* because we don't have to return a dynamically allocated OID
* and NID lookups can use the cached value.
*/
ret = OBJ_nid2obj(i);
if (a) {
ASN1_OBJECT_free(*a);
*a = ret;
}
*pp += len;
return ret;
}
for (i = 0; i < length; i++, p++) {
if (*p == 0x80 && (!i || !(p[-1] & 0x80))) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_OBJECT_ENCODING);
return NULL;
}
}
if ((a == NULL) || ((*a) == NULL) ||
!((*a)->flags & ASN1_OBJECT_FLAG_DYNAMIC)) {
if ((ret = ASN1_OBJECT_new()) == NULL)
return NULL;
} else {
ret = (*a);
}
p = *pp;
/* detach data from object */
data = (unsigned char *)ret->data;
ret->data = NULL;
/* once detached we can change it */
if ((data == NULL) || (ret->length < length)) {
ret->length = 0;
OPENSSL_free(data);
data = OPENSSL_malloc(length);
if (data == NULL)
goto err;
ret->flags |= ASN1_OBJECT_FLAG_DYNAMIC_DATA;
}
memcpy(data, p, length);
/* If there are dynamic strings, free them here, and clear the flag */
if ((ret->flags & ASN1_OBJECT_FLAG_DYNAMIC_STRINGS) != 0) {
OPENSSL_free((char *)ret->sn);
OPENSSL_free((char *)ret->ln);
ret->flags &= ~ASN1_OBJECT_FLAG_DYNAMIC_STRINGS;
}
/* reattach data to object, after which it remains const */
ret->data = data;
ret->length = length;
ret->sn = NULL;
ret->ln = NULL;
/* ret->flags=ASN1_OBJECT_FLAG_DYNAMIC; we know it is dynamic */
p += length;
if (a != NULL)
(*a) = ret;
*pp = p;
return ret;
err:
ERR_raise(ERR_LIB_ASN1, i);
if ((a == NULL) || (*a != ret))
ASN1_OBJECT_free(ret);
return NULL;
}
ASN1_OBJECT *ASN1_OBJECT_new(void)
{
ASN1_OBJECT *ret;
ret = OPENSSL_zalloc(sizeof(*ret));
if (ret == NULL)
return NULL;
ret->flags = ASN1_OBJECT_FLAG_DYNAMIC;
return ret;
}
void ASN1_OBJECT_free(ASN1_OBJECT *a)
{
if (a == NULL)
return;
if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC_STRINGS) {
#ifndef CONST_STRICT
/*
* Disable purely for compile-time strict const checking. Doing this
* on a "real" compile will cause memory leaks
*/
OPENSSL_free((void*)a->sn);
OPENSSL_free((void*)a->ln);
#endif
a->sn = a->ln = NULL;
}
if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC_DATA) {
OPENSSL_free((void*)a->data);
a->data = NULL;
a->length = 0;
}
if (a->flags & ASN1_OBJECT_FLAG_DYNAMIC)
OPENSSL_free(a);
}
ASN1_OBJECT *ASN1_OBJECT_create(int nid, unsigned char *data, int len,
const char *sn, const char *ln)
{
ASN1_OBJECT o;
o.sn = sn;
o.ln = ln;
o.data = data;
o.nid = nid;
o.length = len;
o.flags = ASN1_OBJECT_FLAG_DYNAMIC | ASN1_OBJECT_FLAG_DYNAMIC_STRINGS |
ASN1_OBJECT_FLAG_DYNAMIC_DATA;
return OBJ_dup(&o);
}
| 10,339 | 25.927083 | 77 | c |
openssl | openssl-master/crypto/asn1/a_octet.c | /*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
ASN1_OCTET_STRING *ASN1_OCTET_STRING_dup(const ASN1_OCTET_STRING *x)
{
return ASN1_STRING_dup(x);
}
int ASN1_OCTET_STRING_cmp(const ASN1_OCTET_STRING *a,
const ASN1_OCTET_STRING *b)
{
return ASN1_STRING_cmp(a, b);
}
int ASN1_OCTET_STRING_set(ASN1_OCTET_STRING *x, const unsigned char *d,
int len)
{
return ASN1_STRING_set(x, d, len);
}
| 816 | 26.233333 | 74 | c |
openssl | openssl-master/crypto/asn1/a_print.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 "crypto/ctype.h"
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
int ASN1_PRINTABLE_type(const unsigned char *s, int len)
{
int c;
int ia5 = 0;
int t61 = 0;
if (s == NULL)
return V_ASN1_PRINTABLESTRING;
if (len < 0)
len = strlen((const char *)s);
while (len-- > 0) {
c = *(s++);
if (!ossl_isasn1print(c))
ia5 = 1;
if (!ossl_isascii(c))
t61 = 1;
}
if (t61)
return V_ASN1_T61STRING;
if (ia5)
return V_ASN1_IA5STRING;
return V_ASN1_PRINTABLESTRING;
}
int ASN1_UNIVERSALSTRING_to_string(ASN1_UNIVERSALSTRING *s)
{
int i;
unsigned char *p;
if (s->type != V_ASN1_UNIVERSALSTRING)
return 0;
if ((s->length % 4) != 0)
return 0;
p = s->data;
for (i = 0; i < s->length; i += 4) {
if ((p[0] != '\0') || (p[1] != '\0') || (p[2] != '\0'))
break;
else
p += 4;
}
if (i < s->length)
return 0;
p = s->data;
for (i = 3; i < s->length; i += 4) {
*(p++) = s->data[i];
}
*(p) = '\0';
s->length /= 4;
s->type = ASN1_PRINTABLE_type(s->data, s->length);
return 1;
}
int ASN1_STRING_print(BIO *bp, const ASN1_STRING *v)
{
int i, n;
char buf[80];
const char *p;
if (v == NULL)
return 0;
n = 0;
p = (const char *)v->data;
for (i = 0; i < v->length; i++) {
if ((p[i] > '~') || ((p[i] < ' ') &&
(p[i] != '\n') && (p[i] != '\r')))
buf[n] = '.';
else
buf[n] = p[i];
n++;
if (n >= 80) {
if (BIO_write(bp, buf, n) <= 0)
return 0;
n = 0;
}
}
if (n > 0)
if (BIO_write(bp, buf, n) <= 0)
return 0;
return 1;
}
| 2,208 | 21.773196 | 74 | c |
openssl | openssl-master/crypto/asn1/a_sign.c | /*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include "internal/cryptlib.h"
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/objects.h>
#include <openssl/buffer.h>
#include <openssl/core_names.h>
#include "crypto/asn1.h"
#include "crypto/evp.h"
#ifndef OPENSSL_NO_DEPRECATED_3_0
int ASN1_sign(i2d_of_void *i2d, X509_ALGOR *algor1, X509_ALGOR *algor2,
ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey,
const EVP_MD *type)
{
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
unsigned char *p, *buf_in = NULL, *buf_out = NULL;
int i, inl = 0, outl = 0;
size_t inll = 0, outll = 0;
X509_ALGOR *a;
if (ctx == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
goto err;
}
for (i = 0; i < 2; i++) {
if (i == 0)
a = algor1;
else
a = algor2;
if (a == NULL)
continue;
if (type->pkey_type == NID_dsaWithSHA1) {
/*
* special case: RFC 2459 tells us to omit 'parameters' with
* id-dsa-with-sha1
*/
ASN1_TYPE_free(a->parameter);
a->parameter = NULL;
} else if ((a->parameter == NULL) ||
(a->parameter->type != V_ASN1_NULL)) {
ASN1_TYPE_free(a->parameter);
if ((a->parameter = ASN1_TYPE_new()) == NULL)
goto err;
a->parameter->type = V_ASN1_NULL;
}
ASN1_OBJECT_free(a->algorithm);
a->algorithm = OBJ_nid2obj(type->pkey_type);
if (a->algorithm == NULL) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_OBJECT_TYPE);
goto err;
}
if (a->algorithm->length == 0) {
ERR_raise(ERR_LIB_ASN1,
ASN1_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD);
goto err;
}
}
inl = i2d(data, NULL);
if (inl <= 0) {
ERR_raise(ERR_LIB_ASN1, ERR_R_INTERNAL_ERROR);
goto err;
}
inll = (size_t)inl;
buf_in = OPENSSL_malloc(inll);
outll = outl = EVP_PKEY_get_size(pkey);
buf_out = OPENSSL_malloc(outll);
if (buf_in == NULL || buf_out == NULL) {
outl = 0;
goto err;
}
p = buf_in;
i2d(data, &p);
if (!EVP_SignInit_ex(ctx, type, NULL)
|| !EVP_SignUpdate(ctx, (unsigned char *)buf_in, inl)
|| !EVP_SignFinal(ctx, (unsigned char *)buf_out,
(unsigned int *)&outl, pkey)) {
outl = 0;
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
goto err;
}
ASN1_STRING_set0(signature, buf_out, outl);
buf_out = NULL;
/*
* In the interests of compatibility, I'll make sure that the bit string
* has a 'not-used bits' value of 0
*/
ossl_asn1_string_set_bits_left(signature, 0);
err:
EVP_MD_CTX_free(ctx);
OPENSSL_clear_free((char *)buf_in, inll);
OPENSSL_clear_free((char *)buf_out, outll);
return outl;
}
#endif
int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2,
ASN1_BIT_STRING *signature, const void *data,
EVP_PKEY *pkey, const EVP_MD *md)
{
return ASN1_item_sign_ex(it, algor1, algor2, signature, data, NULL, pkey,
md, NULL, NULL);
}
int ASN1_item_sign_ex(const ASN1_ITEM *it, X509_ALGOR *algor1,
X509_ALGOR *algor2, ASN1_BIT_STRING *signature,
const void *data, const ASN1_OCTET_STRING *id,
EVP_PKEY *pkey, const EVP_MD *md, OSSL_LIB_CTX *libctx,
const char *propq)
{
int rv = 0;
EVP_MD_CTX *ctx = evp_md_ctx_new_ex(pkey, id, libctx, propq);
if (ctx == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
return 0;
}
/* We can use the non _ex variant here since the pkey is already setup */
if (!EVP_DigestSignInit(ctx, NULL, md, NULL, pkey))
goto err;
rv = ASN1_item_sign_ctx(it, algor1, algor2, signature, data, ctx);
err:
EVP_PKEY_CTX_free(EVP_MD_CTX_get_pkey_ctx(ctx));
EVP_MD_CTX_free(ctx);
return rv;
}
int ASN1_item_sign_ctx(const ASN1_ITEM *it, X509_ALGOR *algor1,
X509_ALGOR *algor2, ASN1_BIT_STRING *signature,
const void *data, EVP_MD_CTX *ctx)
{
const EVP_MD *md;
EVP_PKEY *pkey;
unsigned char *buf_in = NULL, *buf_out = NULL;
size_t inl = 0, outl = 0, outll = 0;
int signid, paramtype, buf_len = 0;
int rv, pkey_id;
md = EVP_MD_CTX_get0_md(ctx);
pkey = EVP_PKEY_CTX_get0_pkey(EVP_MD_CTX_get_pkey_ctx(ctx));
if (pkey == NULL) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_CONTEXT_NOT_INITIALISED);
goto err;
}
if (pkey->ameth == NULL) {
EVP_PKEY_CTX *pctx = EVP_MD_CTX_get_pkey_ctx(ctx);
OSSL_PARAM params[2];
unsigned char aid[128];
size_t aid_len = 0;
if (pctx == NULL
|| !EVP_PKEY_CTX_IS_SIGNATURE_OP(pctx)) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_CONTEXT_NOT_INITIALISED);
goto err;
}
params[0] =
OSSL_PARAM_construct_octet_string(OSSL_SIGNATURE_PARAM_ALGORITHM_ID,
aid, sizeof(aid));
params[1] = OSSL_PARAM_construct_end();
if (EVP_PKEY_CTX_get_params(pctx, params) <= 0)
goto err;
if ((aid_len = params[0].return_size) == 0) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_DIGEST_AND_KEY_TYPE_NOT_SUPPORTED);
goto err;
}
if (algor1 != NULL) {
const unsigned char *pp = aid;
if (d2i_X509_ALGOR(&algor1, &pp, aid_len) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_INTERNAL_ERROR);
goto err;
}
}
if (algor2 != NULL) {
const unsigned char *pp = aid;
if (d2i_X509_ALGOR(&algor2, &pp, aid_len) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_INTERNAL_ERROR);
goto err;
}
}
rv = 3;
} else if (pkey->ameth->item_sign) {
rv = pkey->ameth->item_sign(ctx, it, data, algor1, algor2, signature);
if (rv == 1)
outl = signature->length;
/*-
* Return value meanings:
* <=0: error.
* 1: method does everything.
* 2: carry on as normal.
* 3: ASN1 method sets algorithm identifiers: just sign.
*/
if (rv <= 0)
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
if (rv <= 1)
goto err;
} else {
rv = 2;
}
if (rv == 2) {
if (md == NULL) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_CONTEXT_NOT_INITIALISED);
goto err;
}
pkey_id =
#ifndef OPENSSL_NO_SM2
EVP_PKEY_get_id(pkey) == NID_sm2 ? NID_sm2 :
#endif
pkey->ameth->pkey_id;
if (!OBJ_find_sigid_by_algs(&signid, EVP_MD_nid(md), pkey_id)) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_DIGEST_AND_KEY_TYPE_NOT_SUPPORTED);
goto err;
}
paramtype = pkey->ameth->pkey_flags & ASN1_PKEY_SIGPARAM_NULL ?
V_ASN1_NULL : V_ASN1_UNDEF;
if (algor1 != NULL
&& !X509_ALGOR_set0(algor1, OBJ_nid2obj(signid), paramtype, NULL))
goto err;
if (algor2 != NULL
&& !X509_ALGOR_set0(algor2, OBJ_nid2obj(signid), paramtype, NULL))
goto err;
}
buf_len = ASN1_item_i2d(data, &buf_in, it);
if (buf_len <= 0) {
outl = 0;
ERR_raise(ERR_LIB_ASN1, ERR_R_INTERNAL_ERROR);
goto err;
}
inl = buf_len;
if (!EVP_DigestSign(ctx, NULL, &outll, buf_in, inl)) {
outl = 0;
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
goto err;
}
outl = outll;
buf_out = OPENSSL_malloc(outll);
if (buf_in == NULL || buf_out == NULL) {
outl = 0;
goto err;
}
if (!EVP_DigestSign(ctx, buf_out, &outl, buf_in, inl)) {
outl = 0;
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
goto err;
}
ASN1_STRING_set0(signature, buf_out, outl);
buf_out = NULL;
/*
* In the interests of compatibility, I'll make sure that the bit string
* has a 'not-used bits' value of 0
*/
ossl_asn1_string_set_bits_left(signature, 0);
err:
OPENSSL_clear_free((char *)buf_in, inl);
OPENSSL_clear_free((char *)buf_out, outll);
return outl;
}
| 8,863 | 29.356164 | 82 | c |
openssl | openssl-master/crypto/asn1/a_strex.c | /*
* Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <string.h>
#include "internal/cryptlib.h"
#include "crypto/asn1.h"
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/asn1.h>
#include "charmap.h"
/*
* ASN1_STRING_print_ex() and X509_NAME_print_ex(). Enhanced string and name
* printing routines handling multibyte characters, RFC2253 and a host of
* other options.
*/
#define CHARTYPE_BS_ESC (ASN1_STRFLGS_ESC_2253 | CHARTYPE_FIRST_ESC_2253 | CHARTYPE_LAST_ESC_2253)
#define ESC_FLAGS (ASN1_STRFLGS_ESC_2253 | \
ASN1_STRFLGS_ESC_2254 | \
ASN1_STRFLGS_ESC_QUOTE | \
ASN1_STRFLGS_ESC_CTRL | \
ASN1_STRFLGS_ESC_MSB)
/*
* Three IO functions for sending data to memory, a BIO and a FILE
* pointer.
*/
static int send_bio_chars(void *arg, const void *buf, int len)
{
if (!arg)
return 1;
if (BIO_write(arg, buf, len) != len)
return 0;
return 1;
}
#ifndef OPENSSL_NO_STDIO
static int send_fp_chars(void *arg, const void *buf, int len)
{
if (!arg)
return 1;
if (fwrite(buf, 1, len, arg) != (unsigned int)len)
return 0;
return 1;
}
#endif
typedef int char_io (void *arg, const void *buf, int len);
/*
* This function handles display of strings, one character at a time. It is
* passed an unsigned long for each character because it could come from 2 or
* even 4 byte forms.
*/
static int do_esc_char(unsigned long c, unsigned short flags, char *do_quotes,
char_io *io_ch, void *arg)
{
unsigned short chflgs;
unsigned char chtmp;
char tmphex[HEX_SIZE(long) + 3];
if (c > 0xffffffffL)
return -1;
if (c > 0xffff) {
BIO_snprintf(tmphex, sizeof(tmphex), "\\W%08lX", c);
if (!io_ch(arg, tmphex, 10))
return -1;
return 10;
}
if (c > 0xff) {
BIO_snprintf(tmphex, sizeof(tmphex), "\\U%04lX", c);
if (!io_ch(arg, tmphex, 6))
return -1;
return 6;
}
chtmp = (unsigned char)c;
if (chtmp > 0x7f)
chflgs = flags & ASN1_STRFLGS_ESC_MSB;
else
chflgs = char_type[chtmp] & flags;
if (chflgs & CHARTYPE_BS_ESC) {
/* If we don't escape with quotes, signal we need quotes */
if (chflgs & ASN1_STRFLGS_ESC_QUOTE) {
if (do_quotes)
*do_quotes = 1;
if (!io_ch(arg, &chtmp, 1))
return -1;
return 1;
}
if (!io_ch(arg, "\\", 1))
return -1;
if (!io_ch(arg, &chtmp, 1))
return -1;
return 2;
}
if (chflgs & (ASN1_STRFLGS_ESC_CTRL
| ASN1_STRFLGS_ESC_MSB
| ASN1_STRFLGS_ESC_2254)) {
BIO_snprintf(tmphex, 11, "\\%02X", chtmp);
if (!io_ch(arg, tmphex, 3))
return -1;
return 3;
}
/*
* If we get this far and do any escaping at all must escape the escape
* character itself: backslash.
*/
if (chtmp == '\\' && (flags & ESC_FLAGS)) {
if (!io_ch(arg, "\\\\", 2))
return -1;
return 2;
}
if (!io_ch(arg, &chtmp, 1))
return -1;
return 1;
}
#define BUF_TYPE_WIDTH_MASK 0x7
#define BUF_TYPE_CONVUTF8 0x8
/*
* This function sends each character in a buffer to do_esc_char(). It
* interprets the content formats and converts to or from UTF8 as
* appropriate.
*/
static int do_buf(unsigned char *buf, int buflen,
int type, unsigned short flags, char *quotes, char_io *io_ch,
void *arg)
{
int i, outlen, len, charwidth;
unsigned short orflags;
unsigned char *p, *q;
unsigned long c;
p = buf;
q = buf + buflen;
outlen = 0;
charwidth = type & BUF_TYPE_WIDTH_MASK;
switch (charwidth) {
case 4:
if (buflen & 3) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_UNIVERSALSTRING_LENGTH);
return -1;
}
break;
case 2:
if (buflen & 1) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_BMPSTRING_LENGTH);
return -1;
}
break;
default:
break;
}
while (p != q) {
if (p == buf && flags & ASN1_STRFLGS_ESC_2253)
orflags = CHARTYPE_FIRST_ESC_2253;
else
orflags = 0;
switch (charwidth) {
case 4:
c = ((unsigned long)*p++) << 24;
c |= ((unsigned long)*p++) << 16;
c |= ((unsigned long)*p++) << 8;
c |= *p++;
break;
case 2:
c = ((unsigned long)*p++) << 8;
c |= *p++;
break;
case 1:
c = *p++;
break;
case 0:
i = UTF8_getc(p, buflen, &c);
if (i < 0)
return -1; /* Invalid UTF8String */
buflen -= i;
p += i;
break;
default:
return -1; /* invalid width */
}
if (p == q && flags & ASN1_STRFLGS_ESC_2253)
orflags = CHARTYPE_LAST_ESC_2253;
if (type & BUF_TYPE_CONVUTF8) {
unsigned char utfbuf[6];
int utflen;
utflen = UTF8_putc(utfbuf, sizeof(utfbuf), c);
for (i = 0; i < utflen; i++) {
/*
* We don't need to worry about setting orflags correctly
* because if utflen==1 its value will be correct anyway
* otherwise each character will be > 0x7f and so the
* character will never be escaped on first and last.
*/
len = do_esc_char(utfbuf[i], flags | orflags, quotes,
io_ch, arg);
if (len < 0)
return -1;
outlen += len;
}
} else {
len = do_esc_char(c, flags | orflags, quotes,
io_ch, arg);
if (len < 0)
return -1;
outlen += len;
}
}
return outlen;
}
/* This function hex dumps a buffer of characters */
static int do_hex_dump(char_io *io_ch, void *arg, unsigned char *buf,
int buflen)
{
static const char hexdig[] = "0123456789ABCDEF";
unsigned char *p, *q;
char hextmp[2];
if (arg) {
p = buf;
q = buf + buflen;
while (p != q) {
hextmp[0] = hexdig[*p >> 4];
hextmp[1] = hexdig[*p & 0xf];
if (!io_ch(arg, hextmp, 2))
return -1;
p++;
}
}
return buflen << 1;
}
/*
* "dump" a string. This is done when the type is unknown, or the flags
* request it. We can either dump the content octets or the entire DER
* encoding. This uses the RFC2253 #01234 format.
*/
static int do_dump(unsigned long lflags, char_io *io_ch, void *arg,
const ASN1_STRING *str)
{
/*
* Placing the ASN1_STRING in a temp ASN1_TYPE allows the DER encoding to
* readily obtained
*/
ASN1_TYPE t;
unsigned char *der_buf, *p;
int outlen, der_len;
if (!io_ch(arg, "#", 1))
return -1;
/* If we don't dump DER encoding just dump content octets */
if (!(lflags & ASN1_STRFLGS_DUMP_DER)) {
outlen = do_hex_dump(io_ch, arg, str->data, str->length);
if (outlen < 0)
return -1;
return outlen + 1;
}
t.type = str->type;
t.value.ptr = (char *)str;
der_len = i2d_ASN1_TYPE(&t, NULL);
if (der_len <= 0)
return -1;
if ((der_buf = OPENSSL_malloc(der_len)) == NULL)
return -1;
p = der_buf;
i2d_ASN1_TYPE(&t, &p);
outlen = do_hex_dump(io_ch, arg, der_buf, der_len);
OPENSSL_free(der_buf);
if (outlen < 0)
return -1;
return outlen + 1;
}
/*
* Lookup table to convert tags to character widths, 0 = UTF8 encoded, -1 is
* used for non string types otherwise it is the number of bytes per
* character
*/
static const signed char tag2nbyte[] = {
-1, -1, -1, -1, -1, /* 0-4 */
-1, -1, -1, -1, -1, /* 5-9 */
-1, -1, /* 10-11 */
0, /* 12 V_ASN1_UTF8STRING */
-1, -1, -1, -1, -1, /* 13-17 */
1, /* 18 V_ASN1_NUMERICSTRING */
1, /* 19 V_ASN1_PRINTABLESTRING */
1, /* 20 V_ASN1_T61STRING */
-1, /* 21 */
1, /* 22 V_ASN1_IA5STRING */
1, /* 23 V_ASN1_UTCTIME */
1, /* 24 V_ASN1_GENERALIZEDTIME */
-1, /* 25 */
1, /* 26 V_ASN1_ISO64STRING */
-1, /* 27 */
4, /* 28 V_ASN1_UNIVERSALSTRING */
-1, /* 29 */
2 /* 30 V_ASN1_BMPSTRING */
};
/*
* This is the main function, print out an ASN1_STRING taking note of various
* escape and display options. Returns number of characters written or -1 if
* an error occurred.
*/
static int do_print_ex(char_io *io_ch, void *arg, unsigned long lflags,
const ASN1_STRING *str)
{
int outlen, len;
int type;
char quotes;
unsigned short flags;
quotes = 0;
/* Keep a copy of escape flags */
flags = (unsigned short)(lflags & ESC_FLAGS);
type = str->type;
outlen = 0;
if (lflags & ASN1_STRFLGS_SHOW_TYPE) {
const char *tagname;
tagname = ASN1_tag2str(type);
outlen += strlen(tagname);
if (!io_ch(arg, tagname, outlen) || !io_ch(arg, ":", 1))
return -1;
outlen++;
}
/* Decide what to do with type, either dump content or display it */
/* Dump everything */
if (lflags & ASN1_STRFLGS_DUMP_ALL)
type = -1;
/* Ignore the string type */
else if (lflags & ASN1_STRFLGS_IGNORE_TYPE)
type = 1;
else {
/* Else determine width based on type */
if ((type > 0) && (type < 31))
type = tag2nbyte[type];
else
type = -1;
if ((type == -1) && !(lflags & ASN1_STRFLGS_DUMP_UNKNOWN))
type = 1;
}
if (type == -1) {
len = do_dump(lflags, io_ch, arg, str);
if (len < 0)
return -1;
outlen += len;
return outlen;
}
if (lflags & ASN1_STRFLGS_UTF8_CONVERT) {
/*
* Note: if string is UTF8 and we want to convert to UTF8 then we
* just interpret it as 1 byte per character to avoid converting
* twice.
*/
if (!type)
type = 1;
else
type |= BUF_TYPE_CONVUTF8;
}
len = do_buf(str->data, str->length, type, flags, "es, io_ch, NULL);
if (len < 0)
return -1;
outlen += len;
if (quotes)
outlen += 2;
if (!arg)
return outlen;
if (quotes && !io_ch(arg, "\"", 1))
return -1;
if (do_buf(str->data, str->length, type, flags, NULL, io_ch, arg) < 0)
return -1;
if (quotes && !io_ch(arg, "\"", 1))
return -1;
return outlen;
}
/* Used for line indenting: print 'indent' spaces */
static int do_indent(char_io *io_ch, void *arg, int indent)
{
int i;
for (i = 0; i < indent; i++)
if (!io_ch(arg, " ", 1))
return 0;
return 1;
}
#define FN_WIDTH_LN 25
#define FN_WIDTH_SN 10
static int do_name_ex(char_io *io_ch, void *arg, const X509_NAME *n,
int indent, unsigned long flags)
{
int i, prev = -1, orflags, cnt;
int fn_opt, fn_nid;
ASN1_OBJECT *fn;
const ASN1_STRING *val;
const X509_NAME_ENTRY *ent;
char objtmp[80];
const char *objbuf;
int outlen, len;
char *sep_dn, *sep_mv, *sep_eq;
int sep_dn_len, sep_mv_len, sep_eq_len;
if (indent < 0)
indent = 0;
outlen = indent;
if (!do_indent(io_ch, arg, indent))
return -1;
switch (flags & XN_FLAG_SEP_MASK) {
case XN_FLAG_SEP_MULTILINE:
sep_dn = "\n";
sep_dn_len = 1;
sep_mv = " + ";
sep_mv_len = 3;
break;
case XN_FLAG_SEP_COMMA_PLUS:
sep_dn = ",";
sep_dn_len = 1;
sep_mv = "+";
sep_mv_len = 1;
indent = 0;
break;
case XN_FLAG_SEP_CPLUS_SPC:
sep_dn = ", ";
sep_dn_len = 2;
sep_mv = " + ";
sep_mv_len = 3;
indent = 0;
break;
case XN_FLAG_SEP_SPLUS_SPC:
sep_dn = "; ";
sep_dn_len = 2;
sep_mv = " + ";
sep_mv_len = 3;
indent = 0;
break;
default:
return -1;
}
if (flags & XN_FLAG_SPC_EQ) {
sep_eq = " = ";
sep_eq_len = 3;
} else {
sep_eq = "=";
sep_eq_len = 1;
}
fn_opt = flags & XN_FLAG_FN_MASK;
cnt = X509_NAME_entry_count(n);
for (i = 0; i < cnt; i++) {
if (flags & XN_FLAG_DN_REV)
ent = X509_NAME_get_entry(n, cnt - i - 1);
else
ent = X509_NAME_get_entry(n, i);
if (prev != -1) {
if (prev == X509_NAME_ENTRY_set(ent)) {
if (!io_ch(arg, sep_mv, sep_mv_len))
return -1;
outlen += sep_mv_len;
} else {
if (!io_ch(arg, sep_dn, sep_dn_len))
return -1;
outlen += sep_dn_len;
if (!do_indent(io_ch, arg, indent))
return -1;
outlen += indent;
}
}
prev = X509_NAME_ENTRY_set(ent);
fn = X509_NAME_ENTRY_get_object(ent);
val = X509_NAME_ENTRY_get_data(ent);
fn_nid = OBJ_obj2nid(fn);
if (fn_opt != XN_FLAG_FN_NONE) {
int objlen, fld_len;
if ((fn_opt == XN_FLAG_FN_OID) || (fn_nid == NID_undef)) {
OBJ_obj2txt(objtmp, sizeof(objtmp), fn, 1);
fld_len = 0; /* XXX: what should this be? */
objbuf = objtmp;
} else {
if (fn_opt == XN_FLAG_FN_SN) {
fld_len = FN_WIDTH_SN;
objbuf = OBJ_nid2sn(fn_nid);
} else if (fn_opt == XN_FLAG_FN_LN) {
fld_len = FN_WIDTH_LN;
objbuf = OBJ_nid2ln(fn_nid);
} else {
fld_len = 0; /* XXX: what should this be? */
objbuf = "";
}
}
objlen = strlen(objbuf);
if (!io_ch(arg, objbuf, objlen))
return -1;
if ((objlen < fld_len) && (flags & XN_FLAG_FN_ALIGN)) {
if (!do_indent(io_ch, arg, fld_len - objlen))
return -1;
outlen += fld_len - objlen;
}
if (!io_ch(arg, sep_eq, sep_eq_len))
return -1;
outlen += objlen + sep_eq_len;
}
/*
* If the field name is unknown then fix up the DER dump flag. We
* might want to limit this further so it will DER dump on anything
* other than a few 'standard' fields.
*/
if ((fn_nid == NID_undef) && (flags & XN_FLAG_DUMP_UNKNOWN_FIELDS))
orflags = ASN1_STRFLGS_DUMP_ALL;
else
orflags = 0;
len = do_print_ex(io_ch, arg, flags | orflags, val);
if (len < 0)
return -1;
outlen += len;
}
return outlen;
}
/* Wrappers round the main functions */
int X509_NAME_print_ex(BIO *out, const X509_NAME *nm, int indent,
unsigned long flags)
{
if (flags == XN_FLAG_COMPAT)
return X509_NAME_print(out, nm, indent);
return do_name_ex(send_bio_chars, out, nm, indent, flags);
}
#ifndef OPENSSL_NO_STDIO
int X509_NAME_print_ex_fp(FILE *fp, const X509_NAME *nm, int indent,
unsigned long flags)
{
if (flags == XN_FLAG_COMPAT) {
BIO *btmp;
int ret;
btmp = BIO_new_fp(fp, BIO_NOCLOSE);
if (!btmp)
return -1;
ret = X509_NAME_print(btmp, nm, indent);
BIO_free(btmp);
return ret;
}
return do_name_ex(send_fp_chars, fp, nm, indent, flags);
}
#endif
int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str, unsigned long flags)
{
return do_print_ex(send_bio_chars, out, flags, str);
}
#ifndef OPENSSL_NO_STDIO
int ASN1_STRING_print_ex_fp(FILE *fp, const ASN1_STRING *str, unsigned long flags)
{
return do_print_ex(send_fp_chars, fp, flags, str);
}
#endif
/*
* Utility function: convert any string type to UTF8, returns number of bytes
* in output string or a negative error code
*/
int ASN1_STRING_to_UTF8(unsigned char **out, const ASN1_STRING *in)
{
ASN1_STRING stmp, *str = &stmp;
int mbflag, type, ret;
if (!in)
return -1;
type = in->type;
if ((type < 0) || (type > 30))
return -1;
mbflag = tag2nbyte[type];
if (mbflag == -1)
return -1;
mbflag |= MBSTRING_FLAG;
stmp.data = NULL;
stmp.length = 0;
stmp.flags = 0;
ret =
ASN1_mbstring_copy(&str, in->data, in->length, mbflag,
B_ASN1_UTF8STRING);
if (ret < 0)
return ret;
*out = stmp.data;
return stmp.length;
}
| 17,769 | 27.341308 | 106 | c |
openssl | openssl-master/crypto/asn1/a_strnid.c | /*
* Copyright 1999-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/objects.h>
static STACK_OF(ASN1_STRING_TABLE) *stable = NULL;
static void st_free(ASN1_STRING_TABLE *tbl);
static int sk_table_cmp(const ASN1_STRING_TABLE *const *a,
const ASN1_STRING_TABLE *const *b);
/*
* This is the global mask for the mbstring functions: this is use to mask
* out certain types (such as BMPString and UTF8String) because certain
* software (e.g. Netscape) has problems with them.
*/
static unsigned long global_mask = B_ASN1_UTF8STRING;
void ASN1_STRING_set_default_mask(unsigned long mask)
{
global_mask = mask;
}
unsigned long ASN1_STRING_get_default_mask(void)
{
return global_mask;
}
/*-
* This function sets the default to various "flavours" of configuration.
* based on an ASCII string. Currently this is:
* MASK:XXXX : a numerical mask value.
* nobmp : Don't use BMPStrings (just Printable, T61).
* pkix : PKIX recommendation in RFC2459.
* utf8only : only use UTF8Strings (RFC2459 recommendation for 2004).
* default: the default value, Printable, T61, BMP.
*/
int ASN1_STRING_set_default_mask_asc(const char *p)
{
unsigned long mask;
char *end;
if (CHECK_AND_SKIP_PREFIX(p, "MASK:")) {
if (*p == '\0')
return 0;
mask = strtoul(p, &end, 0);
if (*end)
return 0;
} else if (strcmp(p, "nombstr") == 0)
mask = ~((unsigned long)(B_ASN1_BMPSTRING | B_ASN1_UTF8STRING));
else if (strcmp(p, "pkix") == 0)
mask = ~((unsigned long)B_ASN1_T61STRING);
else if (strcmp(p, "utf8only") == 0)
mask = B_ASN1_UTF8STRING;
else if (strcmp(p, "default") == 0)
mask = 0xFFFFFFFFL;
else
return 0;
ASN1_STRING_set_default_mask(mask);
return 1;
}
/*
* The following function generates an ASN1_STRING based on limits in a
* table. Frequently the types and length of an ASN1_STRING are restricted by
* a corresponding OID. For example certificates and certificate requests.
*/
ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out,
const unsigned char *in, int inlen,
int inform, int nid)
{
ASN1_STRING_TABLE *tbl;
ASN1_STRING *str = NULL;
unsigned long mask;
int ret;
if (out == NULL)
out = &str;
tbl = ASN1_STRING_TABLE_get(nid);
if (tbl != NULL) {
mask = tbl->mask;
if (!(tbl->flags & STABLE_NO_MASK))
mask &= global_mask;
ret = ASN1_mbstring_ncopy(out, in, inlen, inform, mask,
tbl->minsize, tbl->maxsize);
} else {
ret = ASN1_mbstring_copy(out, in, inlen, inform,
DIRSTRING_TYPE & global_mask);
}
if (ret <= 0)
return NULL;
return *out;
}
/*
* Now the tables and helper functions for the string table:
*/
#include "tbl_standard.h"
static int sk_table_cmp(const ASN1_STRING_TABLE *const *a,
const ASN1_STRING_TABLE *const *b)
{
return (*a)->nid - (*b)->nid;
}
DECLARE_OBJ_BSEARCH_CMP_FN(ASN1_STRING_TABLE, ASN1_STRING_TABLE, table);
static int table_cmp(const ASN1_STRING_TABLE *a, const ASN1_STRING_TABLE *b)
{
return a->nid - b->nid;
}
IMPLEMENT_OBJ_BSEARCH_CMP_FN(ASN1_STRING_TABLE, ASN1_STRING_TABLE, table);
ASN1_STRING_TABLE *ASN1_STRING_TABLE_get(int nid)
{
int idx;
ASN1_STRING_TABLE fnd;
/* "stable" can be impacted by config, so load the config file first */
OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);
fnd.nid = nid;
if (stable != NULL) {
/* Ideally, this would be done under lock */
sk_ASN1_STRING_TABLE_sort(stable);
idx = sk_ASN1_STRING_TABLE_find(stable, &fnd);
if (idx >= 0)
return sk_ASN1_STRING_TABLE_value(stable, idx);
}
return OBJ_bsearch_table(&fnd, tbl_standard, OSSL_NELEM(tbl_standard));
}
/*
* Return a string table pointer which can be modified: either directly from
* table or a copy of an internal value added to the table.
*/
static ASN1_STRING_TABLE *stable_get(int nid)
{
ASN1_STRING_TABLE *tmp, *rv;
/* Always need a string table so allocate one if NULL */
if (stable == NULL) {
stable = sk_ASN1_STRING_TABLE_new(sk_table_cmp);
if (stable == NULL)
return NULL;
}
tmp = ASN1_STRING_TABLE_get(nid);
if (tmp != NULL && tmp->flags & STABLE_FLAGS_MALLOC)
return tmp;
if ((rv = OPENSSL_zalloc(sizeof(*rv))) == NULL)
return NULL;
if (!sk_ASN1_STRING_TABLE_push(stable, rv)) {
OPENSSL_free(rv);
return NULL;
}
if (tmp != NULL) {
rv->nid = tmp->nid;
rv->minsize = tmp->minsize;
rv->maxsize = tmp->maxsize;
rv->mask = tmp->mask;
rv->flags = tmp->flags | STABLE_FLAGS_MALLOC;
} else {
rv->nid = nid;
rv->minsize = -1;
rv->maxsize = -1;
rv->flags = STABLE_FLAGS_MALLOC;
}
return rv;
}
int ASN1_STRING_TABLE_add(int nid,
long minsize, long maxsize, unsigned long mask,
unsigned long flags)
{
ASN1_STRING_TABLE *tmp;
tmp = stable_get(nid);
if (tmp == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
return 0;
}
if (minsize >= 0)
tmp->minsize = minsize;
if (maxsize >= 0)
tmp->maxsize = maxsize;
if (mask)
tmp->mask = mask;
if (flags)
tmp->flags = STABLE_FLAGS_MALLOC | flags;
return 1;
}
void ASN1_STRING_TABLE_cleanup(void)
{
STACK_OF(ASN1_STRING_TABLE) *tmp;
tmp = stable;
if (tmp == NULL)
return;
stable = NULL;
sk_ASN1_STRING_TABLE_pop_free(tmp, st_free);
}
static void st_free(ASN1_STRING_TABLE *tbl)
{
if (tbl->flags & STABLE_FLAGS_MALLOC)
OPENSSL_free(tbl);
}
| 6,254 | 27.049327 | 77 | c |
openssl | openssl-master/crypto/asn1/a_time.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
*/
/*-
* This is an implementation of the ASN1 Time structure which is:
* Time ::= CHOICE {
* utcTime UTCTime,
* generalTime GeneralizedTime }
*/
#include <stdio.h>
#include <time.h>
#include "crypto/asn1.h"
#include "crypto/ctype.h"
#include "internal/cryptlib.h"
#include <openssl/asn1t.h>
#include "asn1_local.h"
IMPLEMENT_ASN1_MSTRING(ASN1_TIME, B_ASN1_TIME)
IMPLEMENT_ASN1_FUNCTIONS(ASN1_TIME)
IMPLEMENT_ASN1_DUP_FUNCTION(ASN1_TIME)
static int is_utc(const int year)
{
if (50 <= year && year <= 149)
return 1;
return 0;
}
static int leap_year(const int year)
{
if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
return 1;
return 0;
}
/*
* Compute the day of the week and the day of the year from the year, month
* and day. The day of the year is straightforward, the day of the week uses
* a form of Zeller's congruence. For this months start with March and are
* numbered 4 through 15.
*/
static void determine_days(struct tm *tm)
{
static const int ydays[12] = {
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
};
int y = tm->tm_year + 1900;
int m = tm->tm_mon;
int d = tm->tm_mday;
int c;
tm->tm_yday = ydays[m] + d - 1;
if (m >= 2) {
/* March and onwards can be one day further into the year */
tm->tm_yday += leap_year(y);
m += 2;
} else {
/* Treat January and February as part of the previous year */
m += 14;
y--;
}
c = y / 100;
y %= 100;
/* Zeller's congruence */
tm->tm_wday = (d + (13 * m) / 5 + y + y / 4 + c / 4 + 5 * c + 6) % 7;
}
int ossl_asn1_time_to_tm(struct tm *tm, const ASN1_TIME *d)
{
static const int min[9] = { 0, 0, 1, 1, 0, 0, 0, 0, 0 };
static const int max[9] = { 99, 99, 12, 31, 23, 59, 59, 12, 59 };
static const int mdays[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
char *a;
int n, i, i2, l, o, min_l = 11, strict = 0, end = 6, btz = 5, md;
struct tm tmp;
#if defined(CHARSET_EBCDIC)
const char upper_z = 0x5A, num_zero = 0x30, period = 0x2E, minus = 0x2D, plus = 0x2B;
#else
const char upper_z = 'Z', num_zero = '0', period = '.', minus = '-', plus = '+';
#endif
/*
* ASN1_STRING_FLAG_X509_TIME is used to enforce RFC 5280
* time string format, in which:
*
* 1. "seconds" is a 'MUST'
* 2. "Zulu" timezone is a 'MUST'
* 3. "+|-" is not allowed to indicate a timezone
*/
if (d->type == V_ASN1_UTCTIME) {
if (d->flags & ASN1_STRING_FLAG_X509_TIME) {
min_l = 13;
strict = 1;
}
} else if (d->type == V_ASN1_GENERALIZEDTIME) {
end = 7;
btz = 6;
if (d->flags & ASN1_STRING_FLAG_X509_TIME) {
min_l = 15;
strict = 1;
} else {
min_l = 13;
}
} else {
return 0;
}
l = d->length;
a = (char *)d->data;
o = 0;
memset(&tmp, 0, sizeof(tmp));
/*
* GENERALIZEDTIME is similar to UTCTIME except the year is represented
* as YYYY. This stuff treats everything as a two digit field so make
* first two fields 00 to 99
*/
if (l < min_l)
goto err;
for (i = 0; i < end; i++) {
if (!strict && (i == btz) && ((a[o] == upper_z) || (a[o] == plus) || (a[o] == minus))) {
i++;
break;
}
if (!ossl_ascii_isdigit(a[o]))
goto err;
n = a[o] - num_zero;
/* incomplete 2-digital number */
if (++o == l)
goto err;
if (!ossl_ascii_isdigit(a[o]))
goto err;
n = (n * 10) + a[o] - num_zero;
/* no more bytes to read, but we haven't seen time-zone yet */
if (++o == l)
goto err;
i2 = (d->type == V_ASN1_UTCTIME) ? i + 1 : i;
if ((n < min[i2]) || (n > max[i2]))
goto err;
switch (i2) {
case 0:
/* UTC will never be here */
tmp.tm_year = n * 100 - 1900;
break;
case 1:
if (d->type == V_ASN1_UTCTIME)
tmp.tm_year = n < 50 ? n + 100 : n;
else
tmp.tm_year += n;
break;
case 2:
tmp.tm_mon = n - 1;
break;
case 3:
/* check if tm_mday is valid in tm_mon */
if (tmp.tm_mon == 1) {
/* it's February */
md = mdays[1] + leap_year(tmp.tm_year + 1900);
} else {
md = mdays[tmp.tm_mon];
}
if (n > md)
goto err;
tmp.tm_mday = n;
determine_days(&tmp);
break;
case 4:
tmp.tm_hour = n;
break;
case 5:
tmp.tm_min = n;
break;
case 6:
tmp.tm_sec = n;
break;
}
}
/*
* Optional fractional seconds: decimal point followed by one or more
* digits.
*/
if (d->type == V_ASN1_GENERALIZEDTIME && a[o] == period) {
if (strict)
/* RFC 5280 forbids fractional seconds */
goto err;
if (++o == l)
goto err;
i = o;
while ((o < l) && ossl_ascii_isdigit(a[o]))
o++;
/* Must have at least one digit after decimal point */
if (i == o)
goto err;
/* no more bytes to read, but we haven't seen time-zone yet */
if (o == l)
goto err;
}
/*
* 'o' will never point to '\0' at this point, the only chance
* 'o' can point to '\0' is either the subsequent if or the first
* else if is true.
*/
if (a[o] == upper_z) {
o++;
} else if (!strict && ((a[o] == plus) || (a[o] == minus))) {
int offsign = a[o] == minus ? 1 : -1;
int offset = 0;
o++;
/*
* if not equal, no need to do subsequent checks
* since the following for-loop will add 'o' by 4
* and the final return statement will check if 'l'
* and 'o' are equal.
*/
if (o + 4 != l)
goto err;
for (i = end; i < end + 2; i++) {
if (!ossl_ascii_isdigit(a[o]))
goto err;
n = a[o] - num_zero;
o++;
if (!ossl_ascii_isdigit(a[o]))
goto err;
n = (n * 10) + a[o] - num_zero;
i2 = (d->type == V_ASN1_UTCTIME) ? i + 1 : i;
if ((n < min[i2]) || (n > max[i2]))
goto err;
/* if tm is NULL, no need to adjust */
if (tm != NULL) {
if (i == end)
offset = n * 3600;
else if (i == end + 1)
offset += n * 60;
}
o++;
}
if (offset && !OPENSSL_gmtime_adj(&tmp, 0, offset * offsign))
goto err;
} else {
/* not Z, or not +/- in non-strict mode */
goto err;
}
if (o == l) {
/* success, check if tm should be filled */
if (tm != NULL)
*tm = tmp;
return 1;
}
err:
return 0;
}
ASN1_TIME *ossl_asn1_time_from_tm(ASN1_TIME *s, struct tm *ts, int type)
{
char* p;
ASN1_TIME *tmps = NULL;
const size_t len = 20;
if (type == V_ASN1_UNDEF) {
if (is_utc(ts->tm_year))
type = V_ASN1_UTCTIME;
else
type = V_ASN1_GENERALIZEDTIME;
} else if (type == V_ASN1_UTCTIME) {
if (!is_utc(ts->tm_year))
goto err;
} else if (type != V_ASN1_GENERALIZEDTIME) {
goto err;
}
if (s == NULL)
tmps = ASN1_STRING_new();
else
tmps = s;
if (tmps == NULL)
return NULL;
if (!ASN1_STRING_set(tmps, NULL, len))
goto err;
tmps->type = type;
p = (char*)tmps->data;
if (type == V_ASN1_GENERALIZEDTIME)
tmps->length = BIO_snprintf(p, len, "%04d%02d%02d%02d%02d%02dZ",
ts->tm_year + 1900, ts->tm_mon + 1,
ts->tm_mday, ts->tm_hour, ts->tm_min,
ts->tm_sec);
else
tmps->length = BIO_snprintf(p, len, "%02d%02d%02d%02d%02d%02dZ",
ts->tm_year % 100, ts->tm_mon + 1,
ts->tm_mday, ts->tm_hour, ts->tm_min,
ts->tm_sec);
#ifdef CHARSET_EBCDIC
ebcdic2ascii(tmps->data, tmps->data, tmps->length);
#endif
return tmps;
err:
if (tmps != s)
ASN1_STRING_free(tmps);
return NULL;
}
ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t t)
{
return ASN1_TIME_adj(s, t, 0, 0);
}
ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, time_t t,
int offset_day, long offset_sec)
{
struct tm *ts;
struct tm data;
ts = OPENSSL_gmtime(&t, &data);
if (ts == NULL) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_ERROR_GETTING_TIME);
return NULL;
}
if (offset_day || offset_sec) {
if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
return NULL;
}
return ossl_asn1_time_from_tm(s, ts, V_ASN1_UNDEF);
}
int ASN1_TIME_check(const ASN1_TIME *t)
{
if (t->type == V_ASN1_GENERALIZEDTIME)
return ASN1_GENERALIZEDTIME_check(t);
else if (t->type == V_ASN1_UTCTIME)
return ASN1_UTCTIME_check(t);
return 0;
}
/* Convert an ASN1_TIME structure to GeneralizedTime */
ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(const ASN1_TIME *t,
ASN1_GENERALIZEDTIME **out)
{
ASN1_GENERALIZEDTIME *ret = NULL;
struct tm tm;
if (!ASN1_TIME_to_tm(t, &tm))
return NULL;
if (out != NULL)
ret = *out;
ret = ossl_asn1_time_from_tm(ret, &tm, V_ASN1_GENERALIZEDTIME);
if (out != NULL && ret != NULL)
*out = ret;
return ret;
}
int ASN1_TIME_set_string(ASN1_TIME *s, const char *str)
{
/* Try UTC, if that fails, try GENERALIZED */
if (ASN1_UTCTIME_set_string(s, str))
return 1;
return ASN1_GENERALIZEDTIME_set_string(s, str);
}
int ASN1_TIME_set_string_X509(ASN1_TIME *s, const char *str)
{
ASN1_TIME t;
struct tm tm;
int rv = 0;
t.length = strlen(str);
t.data = (unsigned char *)str;
t.flags = ASN1_STRING_FLAG_X509_TIME;
t.type = V_ASN1_UTCTIME;
if (!ASN1_TIME_check(&t)) {
t.type = V_ASN1_GENERALIZEDTIME;
if (!ASN1_TIME_check(&t))
goto out;
}
/*
* Per RFC 5280 (section 4.1.2.5.), the valid input time
* strings should be encoded with the following rules:
*
* 1. UTC: YYMMDDHHMMSSZ, if YY < 50 (20YY) --> UTC: YYMMDDHHMMSSZ
* 2. UTC: YYMMDDHHMMSSZ, if YY >= 50 (19YY) --> UTC: YYMMDDHHMMSSZ
* 3. G'd: YYYYMMDDHHMMSSZ, if YYYY >= 2050 --> G'd: YYYYMMDDHHMMSSZ
* 4. G'd: YYYYMMDDHHMMSSZ, if YYYY < 2050 --> UTC: YYMMDDHHMMSSZ
*
* Only strings of the 4th rule should be reformatted, but since a
* UTC can only present [1950, 2050), so if the given time string
* is less than 1950 (e.g. 19230419000000Z), we do nothing...
*/
if (s != NULL && t.type == V_ASN1_GENERALIZEDTIME) {
if (!ossl_asn1_time_to_tm(&tm, &t))
goto out;
if (is_utc(tm.tm_year)) {
t.length -= 2;
/*
* it's OK to let original t.data go since that's assigned
* to a piece of memory allocated outside of this function.
* new t.data would be freed after ASN1_STRING_copy is done.
*/
t.data = OPENSSL_zalloc(t.length + 1);
if (t.data == NULL)
goto out;
memcpy(t.data, str + 2, t.length);
t.type = V_ASN1_UTCTIME;
}
}
if (s == NULL || ASN1_STRING_copy((ASN1_STRING *)s, (ASN1_STRING *)&t))
rv = 1;
if (t.data != (unsigned char *)str)
OPENSSL_free(t.data);
out:
return rv;
}
int ASN1_TIME_to_tm(const ASN1_TIME *s, struct tm *tm)
{
if (s == NULL) {
time_t now_t;
time(&now_t);
memset(tm, 0, sizeof(*tm));
if (OPENSSL_gmtime(&now_t, tm) != NULL)
return 1;
return 0;
}
return ossl_asn1_time_to_tm(tm, s);
}
int ASN1_TIME_diff(int *pday, int *psec,
const ASN1_TIME *from, const ASN1_TIME *to)
{
struct tm tm_from, tm_to;
if (!ASN1_TIME_to_tm(from, &tm_from))
return 0;
if (!ASN1_TIME_to_tm(to, &tm_to))
return 0;
return OPENSSL_gmtime_diff(pday, psec, &tm_from, &tm_to);
}
static const char _asn1_mon[12][4] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
/* prints the time with the default date format (RFC 822) */
int ASN1_TIME_print(BIO *bp, const ASN1_TIME *tm)
{
return ASN1_TIME_print_ex(bp, tm, ASN1_DTFLGS_RFC822);
}
/* returns 1 on success, 0 on BIO write error or parse failure */
int ASN1_TIME_print_ex(BIO *bp, const ASN1_TIME *tm, unsigned long flags)
{
return ossl_asn1_time_print_ex(bp, tm, flags) > 0;
}
/* prints the time with the date format of ISO 8601 */
/* returns 0 on BIO write error, else -1 in case of parse failure, else 1 */
int ossl_asn1_time_print_ex(BIO *bp, const ASN1_TIME *tm, unsigned long flags)
{
char *v;
int gmt = 0, l;
struct tm stm;
const char upper_z = 0x5A, period = 0x2E;
/* ossl_asn1_time_to_tm will check the time type */
if (!ossl_asn1_time_to_tm(&stm, tm))
return BIO_write(bp, "Bad time value", 14) ? -1 : 0;
l = tm->length;
v = (char *)tm->data;
if (v[l - 1] == upper_z)
gmt = 1;
if (tm->type == V_ASN1_GENERALIZEDTIME) {
char *f = NULL;
int f_len = 0;
/*
* Try to parse fractional seconds. '14' is the place of
* 'fraction point' in a GeneralizedTime string.
*/
if (tm->length > 15 && v[14] == period) {
f = &v[14];
f_len = 1;
while (14 + f_len < l && ossl_ascii_isdigit(f[f_len]))
++f_len;
}
if ((flags & ASN1_DTFLGS_TYPE_MASK) == ASN1_DTFLGS_ISO8601) {
return BIO_printf(bp, "%4d-%02d-%02d %02d:%02d:%02d%.*s%s",
stm.tm_year + 1900, stm.tm_mon + 1,
stm.tm_mday, stm.tm_hour,
stm.tm_min, stm.tm_sec, f_len, f,
(gmt ? "Z" : "")) > 0;
}
else {
return BIO_printf(bp, "%s %2d %02d:%02d:%02d%.*s %d%s",
_asn1_mon[stm.tm_mon], stm.tm_mday, stm.tm_hour,
stm.tm_min, stm.tm_sec, f_len, f, stm.tm_year + 1900,
(gmt ? " GMT" : "")) > 0;
}
} else {
if ((flags & ASN1_DTFLGS_TYPE_MASK) == ASN1_DTFLGS_ISO8601) {
return BIO_printf(bp, "%4d-%02d-%02d %02d:%02d:%02d%s",
stm.tm_year + 1900, stm.tm_mon + 1,
stm.tm_mday, stm.tm_hour,
stm.tm_min, stm.tm_sec,
(gmt ? "Z" : "")) > 0;
}
else {
return BIO_printf(bp, "%s %2d %02d:%02d:%02d %d%s",
_asn1_mon[stm.tm_mon], stm.tm_mday, stm.tm_hour,
stm.tm_min, stm.tm_sec, stm.tm_year + 1900,
(gmt ? " GMT" : "")) > 0;
}
}
}
int ASN1_TIME_cmp_time_t(const ASN1_TIME *s, time_t t)
{
struct tm stm, ttm;
int day, sec;
if (!ASN1_TIME_to_tm(s, &stm))
return -2;
if (!OPENSSL_gmtime(&t, &ttm))
return -2;
if (!OPENSSL_gmtime_diff(&day, &sec, &ttm, &stm))
return -2;
if (day > 0 || sec > 0)
return 1;
if (day < 0 || sec < 0)
return -1;
return 0;
}
int ASN1_TIME_normalize(ASN1_TIME *t)
{
struct tm tm;
if (t == NULL || !ASN1_TIME_to_tm(t, &tm))
return 0;
return ossl_asn1_time_from_tm(t, &tm, V_ASN1_UNDEF) != NULL;
}
int ASN1_TIME_compare(const ASN1_TIME *a, const ASN1_TIME *b)
{
int day, sec;
if (!ASN1_TIME_diff(&day, &sec, b, a))
return -2;
if (day > 0 || sec > 0)
return 1;
if (day < 0 || sec < 0)
return -1;
return 0;
}
/*
* tweak for Windows
*/
#ifdef WIN32
# define timezone _timezone
#endif
#if defined(__FreeBSD__) || defined(__wasi__)
# define USE_TIMEGM
#endif
time_t ossl_asn1_string_to_time_t(const char *asn1_string)
{
ASN1_TIME *timestamp_asn1 = NULL;
struct tm *timestamp_tm = NULL;
#if defined(__DJGPP__)
char *tz = NULL;
#elif !defined(USE_TIMEGM)
time_t timestamp_local;
#endif
time_t timestamp_utc;
timestamp_asn1 = ASN1_TIME_new();
if (!ASN1_TIME_set_string(timestamp_asn1, asn1_string))
{
ASN1_TIME_free(timestamp_asn1);
return -1;
}
timestamp_tm = OPENSSL_malloc(sizeof(*timestamp_tm));
if (timestamp_tm == NULL) {
ASN1_TIME_free(timestamp_asn1);
return -1;
}
if (!(ASN1_TIME_to_tm(timestamp_asn1, timestamp_tm))) {
OPENSSL_free(timestamp_tm);
ASN1_TIME_free(timestamp_asn1);
return -1;
}
ASN1_TIME_free(timestamp_asn1);
#if defined(__DJGPP__)
/*
* This is NOT thread-safe. Do not use this method for platforms other
* than djgpp.
*/
tz = getenv("TZ");
if (tz != NULL) {
tz = OPENSSL_strdup(tz);
if (tz == NULL) {
OPENSSL_free(timestamp_tm);
return -1;
}
}
setenv("TZ", "UTC", 1);
timestamp_utc = mktime(timestamp_tm);
if (tz != NULL) {
setenv("TZ", tz, 1);
OPENSSL_free(tz);
} else {
unsetenv("TZ");
}
#elif defined(USE_TIMEGM)
timestamp_utc = timegm(timestamp_tm);
#else
timestamp_local = mktime(timestamp_tm);
timestamp_utc = timestamp_local - timezone;
#endif
OPENSSL_free(timestamp_tm);
return timestamp_utc;
}
| 18,400 | 26.670677 | 96 | c |
openssl | openssl-master/crypto/asn1/a_type.c | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1t.h>
#include <openssl/objects.h>
#include "asn1_local.h"
int ASN1_TYPE_get(const ASN1_TYPE *a)
{
if (a->type == V_ASN1_BOOLEAN
|| a->type == V_ASN1_NULL
|| a->value.ptr != NULL)
return a->type;
else
return 0;
}
void ASN1_TYPE_set(ASN1_TYPE *a, int type, void *value)
{
if (a->type != V_ASN1_BOOLEAN
&& a->type != V_ASN1_NULL
&& a->value.ptr != NULL) {
ASN1_TYPE **tmp_a = &a;
ossl_asn1_primitive_free((ASN1_VALUE **)tmp_a, NULL, 0);
}
a->type = type;
if (type == V_ASN1_BOOLEAN)
a->value.boolean = value ? 0xff : 0;
else
a->value.ptr = value;
}
int ASN1_TYPE_set1(ASN1_TYPE *a, int type, const void *value)
{
if (!value || (type == V_ASN1_BOOLEAN)) {
void *p = (void *)value;
ASN1_TYPE_set(a, type, p);
} else if (type == V_ASN1_OBJECT) {
ASN1_OBJECT *odup;
odup = OBJ_dup(value);
if (!odup)
return 0;
ASN1_TYPE_set(a, type, odup);
} else {
ASN1_STRING *sdup;
sdup = ASN1_STRING_dup(value);
if (!sdup)
return 0;
ASN1_TYPE_set(a, type, sdup);
}
return 1;
}
/* Returns 0 if they are equal, != 0 otherwise. */
int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b)
{
int result = -1;
if (!a || !b || a->type != b->type)
return -1;
switch (a->type) {
case V_ASN1_OBJECT:
result = OBJ_cmp(a->value.object, b->value.object);
break;
case V_ASN1_BOOLEAN:
result = a->value.boolean - b->value.boolean;
break;
case V_ASN1_NULL:
result = 0; /* They do not have content. */
break;
case V_ASN1_INTEGER:
case V_ASN1_ENUMERATED:
case V_ASN1_BIT_STRING:
case V_ASN1_OCTET_STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_OTHER:
default:
result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr,
(ASN1_STRING *)b->value.ptr);
break;
}
return result;
}
ASN1_TYPE *ASN1_TYPE_pack_sequence(const ASN1_ITEM *it, void *s, ASN1_TYPE **t)
{
ASN1_OCTET_STRING *oct;
ASN1_TYPE *rt;
oct = ASN1_item_pack(s, it, NULL);
if (oct == NULL)
return NULL;
if (t && *t) {
rt = *t;
} else {
rt = ASN1_TYPE_new();
if (rt == NULL) {
ASN1_OCTET_STRING_free(oct);
return NULL;
}
if (t)
*t = rt;
}
ASN1_TYPE_set(rt, V_ASN1_SEQUENCE, oct);
return rt;
}
void *ASN1_TYPE_unpack_sequence(const ASN1_ITEM *it, const ASN1_TYPE *t)
{
if (t == NULL || t->type != V_ASN1_SEQUENCE || t->value.sequence == NULL)
return NULL;
return ASN1_item_unpack(t->value.sequence, it);
}
| 3,606 | 24.94964 | 79 | c |
openssl | openssl-master/crypto/asn1/a_utctm.c | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <time.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include "asn1_local.h"
#include <openssl/asn1t.h>
IMPLEMENT_ASN1_DUP_FUNCTION(ASN1_UTCTIME)
/* This is the primary function used to parse ASN1_UTCTIME */
int ossl_asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d)
{
/* wrapper around ossl_asn1_time_to_tm */
if (d->type != V_ASN1_UTCTIME)
return 0;
return ossl_asn1_time_to_tm(tm, d);
}
int ASN1_UTCTIME_check(const ASN1_UTCTIME *d)
{
return ossl_asn1_utctime_to_tm(NULL, d);
}
/* Sets the string via simple copy without cleaning it up */
int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str)
{
ASN1_UTCTIME t;
t.type = V_ASN1_UTCTIME;
t.length = strlen(str);
t.data = (unsigned char *)str;
t.flags = 0;
if (!ASN1_UTCTIME_check(&t))
return 0;
if (s != NULL && !ASN1_STRING_copy(s, &t))
return 0;
return 1;
}
ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s, time_t t)
{
return ASN1_UTCTIME_adj(s, t, 0, 0);
}
ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t,
int offset_day, long offset_sec)
{
struct tm *ts;
struct tm data;
ts = OPENSSL_gmtime(&t, &data);
if (ts == NULL)
return NULL;
if (offset_day || offset_sec) {
if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
return NULL;
}
return ossl_asn1_time_from_tm(s, ts, V_ASN1_UTCTIME);
}
int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t)
{
struct tm stm, ttm;
int day, sec;
if (!ossl_asn1_utctime_to_tm(&stm, s))
return -2;
if (OPENSSL_gmtime(&t, &ttm) == NULL)
return -2;
if (!OPENSSL_gmtime_diff(&day, &sec, &ttm, &stm))
return -2;
if (day > 0 || sec > 0)
return 1;
if (day < 0 || sec < 0)
return -1;
return 0;
}
int ASN1_UTCTIME_print(BIO *bp, const ASN1_UTCTIME *tm)
{
if (tm->type != V_ASN1_UTCTIME)
return 0;
return ASN1_TIME_print(bp, tm);
}
| 2,386 | 22.401961 | 74 | c |
openssl | openssl-master/crypto/asn1/a_utf8.c | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include "internal/unicode.h"
#include <openssl/asn1.h>
/* UTF8 utilities */
/*-
* This parses a UTF8 string one character at a time. It is passed a pointer
* to the string and the length of the string. It sets 'value' to the value of
* the current character. It returns the number of characters read or a
* negative error code:
* -1 = string too short
* -2 = illegal character
* -3 = subsequent characters not of the form 10xxxxxx
* -4 = character encoded incorrectly (not minimal length).
*/
int UTF8_getc(const unsigned char *str, int len, unsigned long *val)
{
const unsigned char *p;
unsigned long value;
int ret;
if (len <= 0)
return 0;
p = str;
/* Check syntax and work out the encoded value (if correct) */
if ((*p & 0x80) == 0) {
value = *p++ & 0x7f;
ret = 1;
} else if ((*p & 0xe0) == 0xc0) {
if (len < 2)
return -1;
if ((p[1] & 0xc0) != 0x80)
return -3;
value = (*p++ & 0x1f) << 6;
value |= *p++ & 0x3f;
if (value < 0x80)
return -4;
ret = 2;
} else if ((*p & 0xf0) == 0xe0) {
if (len < 3)
return -1;
if (((p[1] & 0xc0) != 0x80)
|| ((p[2] & 0xc0) != 0x80))
return -3;
value = (*p++ & 0xf) << 12;
value |= (*p++ & 0x3f) << 6;
value |= *p++ & 0x3f;
if (value < 0x800)
return -4;
if (is_unicode_surrogate(value))
return -2;
ret = 3;
} else if ((*p & 0xf8) == 0xf0) {
if (len < 4)
return -1;
if (((p[1] & 0xc0) != 0x80)
|| ((p[2] & 0xc0) != 0x80)
|| ((p[3] & 0xc0) != 0x80))
return -3;
value = ((unsigned long)(*p++ & 0x7)) << 18;
value |= (*p++ & 0x3f) << 12;
value |= (*p++ & 0x3f) << 6;
value |= *p++ & 0x3f;
if (value < 0x10000)
return -4;
ret = 4;
} else
return -2;
*val = value;
return ret;
}
/*
* This takes a character 'value' and writes the UTF8 encoded value in 'str'
* where 'str' is a buffer containing 'len' characters. Returns the number of
* characters written, -1 if 'len' is too small or -2 if 'value' is out of
* range. 'str' can be set to NULL in which case it just returns the number of
* characters. It will need at most 4 characters.
*/
int UTF8_putc(unsigned char *str, int len, unsigned long value)
{
if (!str)
len = 4; /* Maximum we will need */
else if (len <= 0)
return -1;
if (value < 0x80) {
if (str)
*str = (unsigned char)value;
return 1;
}
if (value < 0x800) {
if (len < 2)
return -1;
if (str) {
*str++ = (unsigned char)(((value >> 6) & 0x1f) | 0xc0);
*str = (unsigned char)((value & 0x3f) | 0x80);
}
return 2;
}
if (value < 0x10000) {
if (is_unicode_surrogate(value))
return -2;
if (len < 3)
return -1;
if (str) {
*str++ = (unsigned char)(((value >> 12) & 0xf) | 0xe0);
*str++ = (unsigned char)(((value >> 6) & 0x3f) | 0x80);
*str = (unsigned char)((value & 0x3f) | 0x80);
}
return 3;
}
if (value < UNICODE_LIMIT) {
if (len < 4)
return -1;
if (str) {
*str++ = (unsigned char)(((value >> 18) & 0x7) | 0xf0);
*str++ = (unsigned char)(((value >> 12) & 0x3f) | 0x80);
*str++ = (unsigned char)(((value >> 6) & 0x3f) | 0x80);
*str = (unsigned char)((value & 0x3f) | 0x80);
}
return 4;
}
return -2;
}
| 4,119 | 28.855072 | 78 | c |
openssl | openssl-master/crypto/asn1/a_verify.c | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include "internal/cryptlib.h"
#include <openssl/bn.h>
#include <openssl/x509.h>
#include <openssl/objects.h>
#include <openssl/buffer.h>
#include <openssl/evp.h>
#include "crypto/asn1.h"
#include "crypto/evp.h"
#include "crypto/rsa.h"
#ifndef OPENSSL_NO_DEPRECATED_3_0
int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *a, ASN1_BIT_STRING *signature,
char *data, EVP_PKEY *pkey)
{
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
const EVP_MD *type;
unsigned char *p, *buf_in = NULL;
int ret = -1, i, inl;
if (ctx == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
goto err;
}
i = OBJ_obj2nid(a->algorithm);
type = EVP_get_digestbyname(OBJ_nid2sn(i));
if (type == NULL) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM);
goto err;
}
if (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);
goto err;
}
inl = i2d(data, NULL);
if (inl <= 0) {
ERR_raise(ERR_LIB_ASN1, ERR_R_INTERNAL_ERROR);
goto err;
}
buf_in = OPENSSL_malloc((unsigned int)inl);
if (buf_in == NULL)
goto err;
p = buf_in;
i2d(data, &p);
ret = EVP_VerifyInit_ex(ctx, type, NULL)
&& EVP_VerifyUpdate(ctx, (unsigned char *)buf_in, inl);
OPENSSL_clear_free(buf_in, (unsigned int)inl);
if (!ret) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
goto err;
}
ret = -1;
if (EVP_VerifyFinal(ctx, (unsigned char *)signature->data,
(unsigned int)signature->length, pkey) <= 0) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
ret = 0;
goto err;
}
ret = 1;
err:
EVP_MD_CTX_free(ctx);
return ret;
}
#endif
int ASN1_item_verify(const ASN1_ITEM *it, const X509_ALGOR *alg,
const ASN1_BIT_STRING *signature, const void *data,
EVP_PKEY *pkey)
{
return ASN1_item_verify_ex(it, alg, signature, data, NULL, pkey, NULL, NULL);
}
int ASN1_item_verify_ex(const ASN1_ITEM *it, const X509_ALGOR *alg,
const ASN1_BIT_STRING *signature, const void *data,
const ASN1_OCTET_STRING *id, EVP_PKEY *pkey,
OSSL_LIB_CTX *libctx, const char *propq)
{
EVP_MD_CTX *ctx;
int rv = -1;
if ((ctx = evp_md_ctx_new_ex(pkey, id, libctx, propq)) != NULL) {
rv = ASN1_item_verify_ctx(it, alg, signature, data, ctx);
EVP_PKEY_CTX_free(EVP_MD_CTX_get_pkey_ctx(ctx));
EVP_MD_CTX_free(ctx);
}
return rv;
}
int ASN1_item_verify_ctx(const ASN1_ITEM *it, const X509_ALGOR *alg,
const ASN1_BIT_STRING *signature, const void *data,
EVP_MD_CTX *ctx)
{
EVP_PKEY *pkey;
unsigned char *buf_in = NULL;
int ret = -1, inl = 0;
int mdnid, pknid;
size_t inll = 0;
pkey = EVP_PKEY_CTX_get0_pkey(EVP_MD_CTX_get_pkey_ctx(ctx));
if (pkey == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_PASSED_NULL_PARAMETER);
return -1;
}
if (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_BIT_STRING_BITS_LEFT);
return -1;
}
/* Convert signature OID into digest and public key OIDs */
if (!OBJ_find_sigid_algs(OBJ_obj2nid(alg->algorithm), &mdnid, &pknid)) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);
goto err;
}
if (mdnid == NID_undef && evp_pkey_is_legacy(pkey)) {
if (pkey->ameth == NULL || pkey->ameth->item_verify == NULL) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM);
goto err;
}
ret = pkey->ameth->item_verify(ctx, it, data, alg, signature, pkey);
/*
* Return values meaning:
* <=0: error.
* 1: method does everything.
* 2: carry on as normal, method has called EVP_DigestVerifyInit()
*/
if (ret <= 0)
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
if (ret <= 1)
goto err;
} else {
const EVP_MD *type = NULL;
/*
* We don't yet have the ability for providers to be able to handle
* X509_ALGOR style parameters. Fortunately the only one that needs this
* so far is RSA-PSS, so we just special case this for now. In some
* future version of OpenSSL we should push this to the provider.
*/
if (mdnid == NID_undef && pknid == EVP_PKEY_RSA_PSS) {
if (!EVP_PKEY_is_a(pkey, "RSA") && !EVP_PKEY_is_a(pkey, "RSA-PSS")) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_WRONG_PUBLIC_KEY_TYPE);
goto err;
}
/* This function also calls EVP_DigestVerifyInit */
if (ossl_rsa_pss_to_ctx(ctx, NULL, alg, pkey) <= 0) {
ERR_raise(ERR_LIB_ASN1, ERR_R_INTERNAL_ERROR);
goto err;
}
} else {
/* Check public key OID matches public key type */
if (!EVP_PKEY_is_a(pkey, OBJ_nid2sn(pknid))) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_WRONG_PUBLIC_KEY_TYPE);
goto err;
}
if (mdnid != NID_undef) {
type = EVP_get_digestbynid(mdnid);
if (type == NULL) {
ERR_raise_data(ERR_LIB_ASN1,
ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM,
"nid=0x%x", mdnid);
goto err;
}
}
/*
* Note that some algorithms (notably Ed25519 and Ed448) may allow
* a NULL digest value.
*/
if (!EVP_DigestVerifyInit(ctx, NULL, type, NULL, pkey)) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
ret = 0;
goto err;
}
}
}
inl = ASN1_item_i2d(data, &buf_in, it);
if (inl <= 0) {
ERR_raise(ERR_LIB_ASN1, ERR_R_INTERNAL_ERROR);
goto err;
}
if (buf_in == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
goto err;
}
inll = inl;
ret = EVP_DigestVerify(ctx, signature->data, (size_t)signature->length,
buf_in, inl);
if (ret <= 0) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
goto err;
}
ret = 1;
err:
OPENSSL_clear_free(buf_in, inll);
return ret;
}
| 6,941 | 29.991071 | 81 | c |
openssl | openssl-master/crypto/asn1/ameth_lib.c | /*
* Copyright 2006-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 engine deprecated APIs */
#define OPENSSL_SUPPRESS_DEPRECATED
#include "internal/cryptlib.h"
#include <stdio.h>
#include <openssl/asn1t.h>
#include <openssl/x509.h>
#include <openssl/engine.h>
#include "crypto/asn1.h"
#include "crypto/evp.h"
#include "standard_methods.h"
typedef int sk_cmp_fn_type(const char *const *a, const char *const *b);
static STACK_OF(EVP_PKEY_ASN1_METHOD) *app_methods = NULL;
DECLARE_OBJ_BSEARCH_CMP_FN(const EVP_PKEY_ASN1_METHOD *,
const EVP_PKEY_ASN1_METHOD *, ameth);
static int ameth_cmp(const EVP_PKEY_ASN1_METHOD *const *a,
const EVP_PKEY_ASN1_METHOD *const *b)
{
return ((*a)->pkey_id - (*b)->pkey_id);
}
IMPLEMENT_OBJ_BSEARCH_CMP_FN(const EVP_PKEY_ASN1_METHOD *,
const EVP_PKEY_ASN1_METHOD *, ameth);
int EVP_PKEY_asn1_get_count(void)
{
int num = OSSL_NELEM(standard_methods);
if (app_methods)
num += sk_EVP_PKEY_ASN1_METHOD_num(app_methods);
return num;
}
const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_get0(int idx)
{
int num = OSSL_NELEM(standard_methods);
if (idx < 0)
return NULL;
if (idx < num)
return standard_methods[idx];
idx -= num;
return sk_EVP_PKEY_ASN1_METHOD_value(app_methods, idx);
}
static const EVP_PKEY_ASN1_METHOD *pkey_asn1_find(int type)
{
EVP_PKEY_ASN1_METHOD tmp;
const EVP_PKEY_ASN1_METHOD *t = &tmp, **ret;
tmp.pkey_id = type;
if (app_methods) {
int idx;
idx = sk_EVP_PKEY_ASN1_METHOD_find(app_methods, &tmp);
if (idx >= 0)
return sk_EVP_PKEY_ASN1_METHOD_value(app_methods, idx);
}
ret = OBJ_bsearch_ameth(&t, standard_methods, OSSL_NELEM(standard_methods));
if (ret == NULL || *ret == NULL)
return NULL;
return *ret;
}
/*
* Find an implementation of an ASN1 algorithm. If 'pe' is not NULL also
* search through engines and set *pe to a functional reference to the engine
* implementing 'type' or NULL if no engine implements it.
*/
const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_find(ENGINE **pe, int type)
{
const EVP_PKEY_ASN1_METHOD *t;
for (;;) {
t = pkey_asn1_find(type);
if (!t || !(t->pkey_flags & ASN1_PKEY_ALIAS))
break;
type = t->pkey_base_id;
}
if (pe) {
#ifndef OPENSSL_NO_ENGINE
ENGINE *e;
/* type will contain the final unaliased type */
e = ENGINE_get_pkey_asn1_meth_engine(type);
if (e) {
*pe = e;
return ENGINE_get_pkey_asn1_meth(e, type);
}
#endif
*pe = NULL;
}
return t;
}
const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_find_str(ENGINE **pe,
const char *str, int len)
{
int i;
const EVP_PKEY_ASN1_METHOD *ameth = NULL;
if (len == -1)
len = strlen(str);
if (pe) {
#ifndef OPENSSL_NO_ENGINE
ENGINE *e;
ameth = ENGINE_pkey_asn1_find_str(&e, str, len);
if (ameth) {
/*
* Convert structural into functional reference
*/
if (!ENGINE_init(e))
ameth = NULL;
ENGINE_free(e);
*pe = e;
return ameth;
}
#endif
*pe = NULL;
}
for (i = EVP_PKEY_asn1_get_count(); i-- > 0; ) {
ameth = EVP_PKEY_asn1_get0(i);
if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
continue;
if ((int)strlen(ameth->pem_str) == len
&& OPENSSL_strncasecmp(ameth->pem_str, str, len) == 0)
return ameth;
}
return NULL;
}
int EVP_PKEY_asn1_add0(const EVP_PKEY_ASN1_METHOD *ameth)
{
EVP_PKEY_ASN1_METHOD tmp = { 0, };
/*
* 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 (!((ameth->pem_str == NULL
&& (ameth->pkey_flags & ASN1_PKEY_ALIAS) != 0)
|| (ameth->pem_str != NULL
&& (ameth->pkey_flags & ASN1_PKEY_ALIAS) == 0))) {
ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_INVALID_ARGUMENT);
return 0;
}
if (app_methods == NULL) {
app_methods = sk_EVP_PKEY_ASN1_METHOD_new(ameth_cmp);
if (app_methods == NULL)
return 0;
}
tmp.pkey_id = ameth->pkey_id;
if (sk_EVP_PKEY_ASN1_METHOD_find(app_methods, &tmp) >= 0) {
ERR_raise(ERR_LIB_EVP,
EVP_R_PKEY_APPLICATION_ASN1_METHOD_ALREADY_REGISTERED);
return 0;
}
if (!sk_EVP_PKEY_ASN1_METHOD_push(app_methods, ameth))
return 0;
sk_EVP_PKEY_ASN1_METHOD_sort(app_methods);
return 1;
}
int EVP_PKEY_asn1_add_alias(int to, int from)
{
EVP_PKEY_ASN1_METHOD *ameth;
ameth = EVP_PKEY_asn1_new(from, ASN1_PKEY_ALIAS, NULL, NULL);
if (ameth == NULL)
return 0;
ameth->pkey_base_id = to;
if (!EVP_PKEY_asn1_add0(ameth)) {
EVP_PKEY_asn1_free(ameth);
return 0;
}
return 1;
}
int EVP_PKEY_asn1_get0_info(int *ppkey_id, int *ppkey_base_id,
int *ppkey_flags, const char **pinfo,
const char **ppem_str,
const EVP_PKEY_ASN1_METHOD *ameth)
{
if (!ameth)
return 0;
if (ppkey_id)
*ppkey_id = ameth->pkey_id;
if (ppkey_base_id)
*ppkey_base_id = ameth->pkey_base_id;
if (ppkey_flags)
*ppkey_flags = ameth->pkey_flags;
if (pinfo)
*pinfo = ameth->info;
if (ppem_str)
*ppem_str = ameth->pem_str;
return 1;
}
const EVP_PKEY_ASN1_METHOD *EVP_PKEY_get0_asn1(const EVP_PKEY *pkey)
{
return pkey->ameth;
}
EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_new(int id, int flags,
const char *pem_str, const char *info)
{
EVP_PKEY_ASN1_METHOD *ameth = OPENSSL_zalloc(sizeof(*ameth));
if (ameth == NULL)
return NULL;
ameth->pkey_id = id;
ameth->pkey_base_id = id;
ameth->pkey_flags = flags | ASN1_PKEY_DYNAMIC;
if (info) {
ameth->info = OPENSSL_strdup(info);
if (ameth->info == NULL)
goto err;
}
if (pem_str) {
ameth->pem_str = OPENSSL_strdup(pem_str);
if (ameth->pem_str == NULL)
goto err;
}
return ameth;
err:
EVP_PKEY_asn1_free(ameth);
return NULL;
}
void EVP_PKEY_asn1_copy(EVP_PKEY_ASN1_METHOD *dst,
const EVP_PKEY_ASN1_METHOD *src)
{
int pkey_id = dst->pkey_id;
int pkey_base_id = dst->pkey_base_id;
unsigned long pkey_flags = dst->pkey_flags;
char *pem_str = dst->pem_str;
char *info = dst->info;
*dst = *src;
/* We only copy the function pointers so restore the other values */
dst->pkey_id = pkey_id;
dst->pkey_base_id = pkey_base_id;
dst->pkey_flags = pkey_flags;
dst->pem_str = pem_str;
dst->info = info;
}
void EVP_PKEY_asn1_free(EVP_PKEY_ASN1_METHOD *ameth)
{
if (ameth && (ameth->pkey_flags & ASN1_PKEY_DYNAMIC)) {
OPENSSL_free(ameth->pem_str);
OPENSSL_free(ameth->info);
OPENSSL_free(ameth);
}
}
void EVP_PKEY_asn1_set_public(EVP_PKEY_ASN1_METHOD *ameth,
int (*pub_decode) (EVP_PKEY *pk,
const X509_PUBKEY *pub),
int (*pub_encode) (X509_PUBKEY *pub,
const EVP_PKEY *pk),
int (*pub_cmp) (const EVP_PKEY *a,
const EVP_PKEY *b),
int (*pub_print) (BIO *out,
const EVP_PKEY *pkey,
int indent, ASN1_PCTX *pctx),
int (*pkey_size) (const EVP_PKEY *pk),
int (*pkey_bits) (const EVP_PKEY *pk))
{
ameth->pub_decode = pub_decode;
ameth->pub_encode = pub_encode;
ameth->pub_cmp = pub_cmp;
ameth->pub_print = pub_print;
ameth->pkey_size = pkey_size;
ameth->pkey_bits = pkey_bits;
}
void EVP_PKEY_asn1_set_private(EVP_PKEY_ASN1_METHOD *ameth,
int (*priv_decode) (EVP_PKEY *pk,
const PKCS8_PRIV_KEY_INFO
*p8inf),
int (*priv_encode) (PKCS8_PRIV_KEY_INFO *p8,
const EVP_PKEY *pk),
int (*priv_print) (BIO *out,
const EVP_PKEY *pkey,
int indent,
ASN1_PCTX *pctx))
{
ameth->priv_decode = priv_decode;
ameth->priv_encode = priv_encode;
ameth->priv_print = priv_print;
}
void EVP_PKEY_asn1_set_param(EVP_PKEY_ASN1_METHOD *ameth,
int (*param_decode) (EVP_PKEY *pkey,
const unsigned char **pder,
int derlen),
int (*param_encode) (const EVP_PKEY *pkey,
unsigned char **pder),
int (*param_missing) (const EVP_PKEY *pk),
int (*param_copy) (EVP_PKEY *to,
const EVP_PKEY *from),
int (*param_cmp) (const EVP_PKEY *a,
const EVP_PKEY *b),
int (*param_print) (BIO *out,
const EVP_PKEY *pkey,
int indent, ASN1_PCTX *pctx))
{
ameth->param_decode = param_decode;
ameth->param_encode = param_encode;
ameth->param_missing = param_missing;
ameth->param_copy = param_copy;
ameth->param_cmp = param_cmp;
ameth->param_print = param_print;
}
void EVP_PKEY_asn1_set_free(EVP_PKEY_ASN1_METHOD *ameth,
void (*pkey_free) (EVP_PKEY *pkey))
{
ameth->pkey_free = pkey_free;
}
void EVP_PKEY_asn1_set_ctrl(EVP_PKEY_ASN1_METHOD *ameth,
int (*pkey_ctrl) (EVP_PKEY *pkey, int op,
long arg1, void *arg2))
{
ameth->pkey_ctrl = pkey_ctrl;
}
void EVP_PKEY_asn1_set_security_bits(EVP_PKEY_ASN1_METHOD *ameth,
int (*pkey_security_bits) (const EVP_PKEY
*pk))
{
ameth->pkey_security_bits = pkey_security_bits;
}
void EVP_PKEY_asn1_set_item(EVP_PKEY_ASN1_METHOD *ameth,
int (*item_verify) (EVP_MD_CTX *ctx,
const ASN1_ITEM *it,
const void *data,
const X509_ALGOR *a,
const ASN1_BIT_STRING *sig,
EVP_PKEY *pkey),
int (*item_sign) (EVP_MD_CTX *ctx,
const ASN1_ITEM *it,
const void *data,
X509_ALGOR *alg1,
X509_ALGOR *alg2,
ASN1_BIT_STRING *sig))
{
ameth->item_sign = item_sign;
ameth->item_verify = item_verify;
}
void EVP_PKEY_asn1_set_siginf(EVP_PKEY_ASN1_METHOD *ameth,
int (*siginf_set) (X509_SIG_INFO *siginf,
const X509_ALGOR *alg,
const ASN1_STRING *sig))
{
ameth->siginf_set = siginf_set;
}
void EVP_PKEY_asn1_set_check(EVP_PKEY_ASN1_METHOD *ameth,
int (*pkey_check) (const EVP_PKEY *pk))
{
ameth->pkey_check = pkey_check;
}
void EVP_PKEY_asn1_set_public_check(EVP_PKEY_ASN1_METHOD *ameth,
int (*pkey_pub_check) (const EVP_PKEY *pk))
{
ameth->pkey_public_check = pkey_pub_check;
}
void EVP_PKEY_asn1_set_param_check(EVP_PKEY_ASN1_METHOD *ameth,
int (*pkey_param_check) (const EVP_PKEY *pk))
{
ameth->pkey_param_check = pkey_param_check;
}
void EVP_PKEY_asn1_set_set_priv_key(EVP_PKEY_ASN1_METHOD *ameth,
int (*set_priv_key) (EVP_PKEY *pk,
const unsigned char
*priv,
size_t len))
{
ameth->set_priv_key = set_priv_key;
}
void EVP_PKEY_asn1_set_set_pub_key(EVP_PKEY_ASN1_METHOD *ameth,
int (*set_pub_key) (EVP_PKEY *pk,
const unsigned char *pub,
size_t len))
{
ameth->set_pub_key = set_pub_key;
}
void EVP_PKEY_asn1_set_get_priv_key(EVP_PKEY_ASN1_METHOD *ameth,
int (*get_priv_key) (const EVP_PKEY *pk,
unsigned char *priv,
size_t *len))
{
ameth->get_priv_key = get_priv_key;
}
void EVP_PKEY_asn1_set_get_pub_key(EVP_PKEY_ASN1_METHOD *ameth,
int (*get_pub_key) (const EVP_PKEY *pk,
unsigned char *pub,
size_t *len))
{
ameth->get_pub_key = get_pub_key;
}
| 14,439 | 32.195402 | 80 | c |
openssl | openssl-master/crypto/asn1/asn1_err.c | /*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/err.h>
#include <openssl/asn1err.h>
#include "crypto/asn1err.h"
#ifndef OPENSSL_NO_ERR
static const ERR_STRING_DATA ASN1_str_reasons[] = {
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ADDING_OBJECT), "adding object"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ASN1_PARSE_ERROR), "asn1 parse error"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ASN1_SIG_PARSE_ERROR),
"asn1 sig parse error"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_AUX_ERROR), "aux error"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_BAD_OBJECT_HEADER), "bad object header"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_BAD_TEMPLATE), "bad template"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_BMPSTRING_IS_WRONG_LENGTH),
"bmpstring is wrong length"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_BN_LIB), "bn lib"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_BOOLEAN_IS_WRONG_LENGTH),
"boolean is wrong length"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_BUFFER_TOO_SMALL), "buffer too small"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER),
"cipher has no object identifier"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_CONTEXT_NOT_INITIALISED),
"context not initialised"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_DATA_IS_WRONG), "data is wrong"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_DECODE_ERROR), "decode error"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_DEPTH_EXCEEDED), "depth exceeded"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_DIGEST_AND_KEY_TYPE_NOT_SUPPORTED),
"digest and key type not supported"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ENCODE_ERROR), "encode error"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ERROR_GETTING_TIME),
"error getting time"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ERROR_LOADING_SECTION),
"error loading section"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ERROR_SETTING_CIPHER_PARAMS),
"error setting cipher params"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_EXPECTING_AN_INTEGER),
"expecting an integer"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_EXPECTING_AN_OBJECT),
"expecting an object"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_EXPLICIT_LENGTH_MISMATCH),
"explicit length mismatch"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED),
"explicit tag not constructed"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_FIELD_MISSING), "field missing"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_FIRST_NUM_TOO_LARGE),
"first num too large"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_HEADER_TOO_LONG), "header too long"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_BITSTRING_FORMAT),
"illegal bitstring format"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_BOOLEAN), "illegal boolean"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_CHARACTERS),
"illegal characters"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_FORMAT), "illegal format"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_HEX), "illegal hex"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_IMPLICIT_TAG),
"illegal implicit tag"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_INTEGER), "illegal integer"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_NEGATIVE_VALUE),
"illegal negative value"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_NESTED_TAGGING),
"illegal nested tagging"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_NULL), "illegal null"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_NULL_VALUE),
"illegal null value"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_OBJECT), "illegal object"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_OPTIONAL_ANY),
"illegal optional any"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE),
"illegal options on item template"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_PADDING), "illegal padding"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_TAGGED_ANY),
"illegal tagged any"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_TIME_VALUE),
"illegal time value"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ILLEGAL_ZERO_CONTENT),
"illegal zero content"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INTEGER_NOT_ASCII_FORMAT),
"integer not ascii format"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INTEGER_TOO_LARGE_FOR_LONG),
"integer too large for long"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_BIT_STRING_BITS_LEFT),
"invalid bit string bits left"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_BMPSTRING_LENGTH),
"invalid bmpstring length"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_DIGIT), "invalid digit"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_MIME_TYPE), "invalid mime type"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_MODIFIER), "invalid modifier"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_NUMBER), "invalid number"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_OBJECT_ENCODING),
"invalid object encoding"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_SCRYPT_PARAMETERS),
"invalid scrypt parameters"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_SEPARATOR), "invalid separator"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_STRING_TABLE_VALUE),
"invalid string table value"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_UNIVERSALSTRING_LENGTH),
"invalid universalstring length"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_UTF8STRING),
"invalid utf8string"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_INVALID_VALUE), "invalid value"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_LENGTH_TOO_LONG), "length too long"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_LIST_ERROR), "list error"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_MIME_NO_CONTENT_TYPE),
"mime no content type"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_MIME_PARSE_ERROR), "mime parse error"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_MIME_SIG_PARSE_ERROR),
"mime sig parse error"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_MISSING_EOC), "missing eoc"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_MISSING_SECOND_NUMBER),
"missing second number"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_MISSING_VALUE), "missing value"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_MSTRING_NOT_UNIVERSAL),
"mstring not universal"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_MSTRING_WRONG_TAG), "mstring wrong tag"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NESTED_ASN1_STRING),
"nested asn1 string"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NESTED_TOO_DEEP), "nested too deep"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NON_HEX_CHARACTERS),
"non hex characters"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NOT_ASCII_FORMAT), "not ascii format"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NOT_ENOUGH_DATA), "not enough data"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NO_CONTENT_TYPE), "no content type"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NO_MATCHING_CHOICE_TYPE),
"no matching choice type"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NO_MULTIPART_BODY_FAILURE),
"no multipart body failure"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NO_MULTIPART_BOUNDARY),
"no multipart boundary"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NO_SIG_CONTENT_TYPE),
"no sig content type"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_NULL_IS_WRONG_LENGTH),
"null is wrong length"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_OBJECT_NOT_ASCII_FORMAT),
"object not ascii format"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_ODD_NUMBER_OF_CHARS),
"odd number of chars"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_SECOND_NUMBER_TOO_LARGE),
"second number too large"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_SEQUENCE_LENGTH_MISMATCH),
"sequence length mismatch"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_SEQUENCE_NOT_CONSTRUCTED),
"sequence not constructed"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_SEQUENCE_OR_SET_NEEDS_CONFIG),
"sequence or set needs config"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_SHORT_LINE), "short line"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_SIG_INVALID_MIME_TYPE),
"sig invalid mime type"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_STREAMING_NOT_SUPPORTED),
"streaming not supported"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_STRING_TOO_LONG), "string too long"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_STRING_TOO_SHORT), "string too short"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD),
"the asn1 object identifier is not known for this md"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_TIME_NOT_ASCII_FORMAT),
"time not ascii format"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_TOO_LARGE), "too large"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_TOO_LONG), "too long"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_TOO_SMALL), "too small"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_TYPE_NOT_CONSTRUCTED),
"type not constructed"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_TYPE_NOT_PRIMITIVE),
"type not primitive"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNEXPECTED_EOC), "unexpected eoc"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH),
"universalstring is wrong length"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNKNOWN_DIGEST), "unknown digest"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNKNOWN_FORMAT), "unknown format"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM),
"unknown message digest algorithm"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNKNOWN_OBJECT_TYPE),
"unknown object type"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE),
"unknown public key type"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM),
"unknown signature algorithm"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNKNOWN_TAG), "unknown tag"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE),
"unsupported any defined by type"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNSUPPORTED_CIPHER),
"unsupported cipher"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE),
"unsupported public key type"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNSUPPORTED_TYPE), "unsupported type"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_WRONG_INTEGER_TYPE),
"wrong integer type"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_WRONG_PUBLIC_KEY_TYPE),
"wrong public key type"},
{ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_WRONG_TAG), "wrong tag"},
{0, NULL}
};
#endif
int ossl_err_load_ASN1_strings(void)
{
#ifndef OPENSSL_NO_ERR
if (ERR_reason_error_string(ASN1_str_reasons[0].error) == NULL)
ERR_load_strings_const(ASN1_str_reasons);
#endif
return 1;
}
| 10,719 | 49.328638 | 91 | c |
openssl | openssl-master/crypto/asn1/asn1_gen.c | /*
* Copyright 2002-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/cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/x509v3.h>
#define ASN1_GEN_FLAG 0x10000
#define ASN1_GEN_FLAG_IMP (ASN1_GEN_FLAG|1)
#define ASN1_GEN_FLAG_EXP (ASN1_GEN_FLAG|2)
#define ASN1_GEN_FLAG_TAG (ASN1_GEN_FLAG|3)
#define ASN1_GEN_FLAG_BITWRAP (ASN1_GEN_FLAG|4)
#define ASN1_GEN_FLAG_OCTWRAP (ASN1_GEN_FLAG|5)
#define ASN1_GEN_FLAG_SEQWRAP (ASN1_GEN_FLAG|6)
#define ASN1_GEN_FLAG_SETWRAP (ASN1_GEN_FLAG|7)
#define ASN1_GEN_FLAG_FORMAT (ASN1_GEN_FLAG|8)
#define ASN1_GEN_STR(str,val) {str, sizeof(str) - 1, val}
#define ASN1_FLAG_EXP_MAX 20
/* Maximum number of nested sequences */
#define ASN1_GEN_SEQ_MAX_DEPTH 50
/* Input formats */
/* ASCII: default */
#define ASN1_GEN_FORMAT_ASCII 1
/* UTF8 */
#define ASN1_GEN_FORMAT_UTF8 2
/* Hex */
#define ASN1_GEN_FORMAT_HEX 3
/* List of bits */
#define ASN1_GEN_FORMAT_BITLIST 4
struct tag_name_st {
const char *strnam;
int len;
int tag;
};
typedef struct {
int exp_tag;
int exp_class;
int exp_constructed;
int exp_pad;
long exp_len;
} tag_exp_type;
typedef struct {
int imp_tag;
int imp_class;
int utype;
int format;
const char *str;
tag_exp_type exp_list[ASN1_FLAG_EXP_MAX];
int exp_count;
} tag_exp_arg;
static ASN1_TYPE *generate_v3(const char *str, X509V3_CTX *cnf, int depth,
int *perr);
static int bitstr_cb(const char *elem, int len, void *bitstr);
static int asn1_cb(const char *elem, int len, void *bitstr);
static int append_exp(tag_exp_arg *arg, int exp_tag, int exp_class,
int exp_constructed, int exp_pad, int imp_ok);
static int parse_tagging(const char *vstart, int vlen, int *ptag,
int *pclass);
static ASN1_TYPE *asn1_multi(int utype, const char *section, X509V3_CTX *cnf,
int depth, int *perr);
static ASN1_TYPE *asn1_str2type(const char *str, int format, int utype);
static int asn1_str2tag(const char *tagstr, int len);
ASN1_TYPE *ASN1_generate_nconf(const char *str, CONF *nconf)
{
X509V3_CTX cnf;
if (!nconf)
return ASN1_generate_v3(str, NULL);
X509V3_set_nconf(&cnf, nconf);
return ASN1_generate_v3(str, &cnf);
}
ASN1_TYPE *ASN1_generate_v3(const char *str, X509V3_CTX *cnf)
{
int err = 0;
ASN1_TYPE *ret = generate_v3(str, cnf, 0, &err);
if (err)
ERR_raise(ERR_LIB_ASN1, err);
return ret;
}
static ASN1_TYPE *generate_v3(const char *str, X509V3_CTX *cnf, int depth,
int *perr)
{
ASN1_TYPE *ret;
tag_exp_arg asn1_tags;
tag_exp_type *etmp;
int i, len;
unsigned char *orig_der = NULL, *new_der = NULL;
const unsigned char *cpy_start;
unsigned char *p;
const unsigned char *cp;
int cpy_len;
long hdr_len = 0;
int hdr_constructed = 0, hdr_tag, hdr_class;
int r;
asn1_tags.imp_tag = -1;
asn1_tags.imp_class = -1;
asn1_tags.format = ASN1_GEN_FORMAT_ASCII;
asn1_tags.exp_count = 0;
if (CONF_parse_list(str, ',', 1, asn1_cb, &asn1_tags) != 0) {
*perr = ASN1_R_UNKNOWN_TAG;
return NULL;
}
if ((asn1_tags.utype == V_ASN1_SEQUENCE)
|| (asn1_tags.utype == V_ASN1_SET)) {
if (!cnf) {
*perr = ASN1_R_SEQUENCE_OR_SET_NEEDS_CONFIG;
return NULL;
}
if (depth >= ASN1_GEN_SEQ_MAX_DEPTH) {
*perr = ASN1_R_ILLEGAL_NESTED_TAGGING;
return NULL;
}
ret = asn1_multi(asn1_tags.utype, asn1_tags.str, cnf, depth, perr);
} else
ret = asn1_str2type(asn1_tags.str, asn1_tags.format, asn1_tags.utype);
if (!ret)
return NULL;
/* If no tagging return base type */
if ((asn1_tags.imp_tag == -1) && (asn1_tags.exp_count == 0))
return ret;
/* Generate the encoding */
cpy_len = i2d_ASN1_TYPE(ret, &orig_der);
ASN1_TYPE_free(ret);
ret = NULL;
/* Set point to start copying for modified encoding */
cpy_start = orig_der;
/* Do we need IMPLICIT tagging? */
if (asn1_tags.imp_tag != -1) {
/* If IMPLICIT we will replace the underlying tag */
/* Skip existing tag+len */
r = ASN1_get_object(&cpy_start, &hdr_len, &hdr_tag, &hdr_class,
cpy_len);
if (r & 0x80)
goto err;
/* Update copy length */
cpy_len -= cpy_start - orig_der;
/*
* For IMPLICIT tagging the length should match the original length
* and constructed flag should be consistent.
*/
if (r & 0x1) {
/* Indefinite length constructed */
hdr_constructed = 2;
hdr_len = 0;
} else
/* Just retain constructed flag */
hdr_constructed = r & V_ASN1_CONSTRUCTED;
/*
* Work out new length with IMPLICIT tag: ignore constructed because
* it will mess up if indefinite length
*/
len = ASN1_object_size(0, hdr_len, asn1_tags.imp_tag);
} else
len = cpy_len;
/* Work out length in any EXPLICIT, starting from end */
for (i = 0, etmp = asn1_tags.exp_list + asn1_tags.exp_count - 1;
i < asn1_tags.exp_count; i++, etmp--) {
/* Content length: number of content octets + any padding */
len += etmp->exp_pad;
etmp->exp_len = len;
/* Total object length: length including new header */
len = ASN1_object_size(0, len, etmp->exp_tag);
}
/* Allocate buffer for new encoding */
new_der = OPENSSL_malloc(len);
if (new_der == NULL)
goto err;
/* Generate tagged encoding */
p = new_der;
/* Output explicit tags first */
for (i = 0, etmp = asn1_tags.exp_list; i < asn1_tags.exp_count;
i++, etmp++) {
ASN1_put_object(&p, etmp->exp_constructed, etmp->exp_len,
etmp->exp_tag, etmp->exp_class);
if (etmp->exp_pad)
*p++ = 0;
}
/* If IMPLICIT, output tag */
if (asn1_tags.imp_tag != -1) {
if (asn1_tags.imp_class == V_ASN1_UNIVERSAL
&& (asn1_tags.imp_tag == V_ASN1_SEQUENCE
|| asn1_tags.imp_tag == V_ASN1_SET))
hdr_constructed = V_ASN1_CONSTRUCTED;
ASN1_put_object(&p, hdr_constructed, hdr_len,
asn1_tags.imp_tag, asn1_tags.imp_class);
}
/* Copy across original encoding */
memcpy(p, cpy_start, cpy_len);
cp = new_der;
/* Obtain new ASN1_TYPE structure */
ret = d2i_ASN1_TYPE(NULL, &cp, len);
err:
OPENSSL_free(orig_der);
OPENSSL_free(new_der);
return ret;
}
static int asn1_cb(const char *elem, int len, void *bitstr)
{
tag_exp_arg *arg = bitstr;
int i;
int utype;
int vlen = 0;
const char *p, *vstart = NULL;
int tmp_tag, tmp_class;
if (elem == NULL)
return -1;
for (i = 0, p = elem; i < len; p++, i++) {
/* Look for the ':' in name value pairs */
if (*p == ':') {
vstart = p + 1;
vlen = len - (vstart - elem);
len = p - elem;
break;
}
}
utype = asn1_str2tag(elem, len);
if (utype == -1) {
ERR_raise_data(ERR_LIB_ASN1, ASN1_R_UNKNOWN_TAG, "tag=%s", elem);
return -1;
}
/* If this is not a modifier mark end of string and exit */
if (!(utype & ASN1_GEN_FLAG)) {
arg->utype = utype;
arg->str = vstart;
/* If no value and not end of string, error */
if (!vstart && elem[len]) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_MISSING_VALUE);
return -1;
}
return 0;
}
switch (utype) {
case ASN1_GEN_FLAG_IMP:
/* Check for illegal multiple IMPLICIT tagging */
if (arg->imp_tag != -1) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_NESTED_TAGGING);
return -1;
}
if (!parse_tagging(vstart, vlen, &arg->imp_tag, &arg->imp_class))
return -1;
break;
case ASN1_GEN_FLAG_EXP:
if (!parse_tagging(vstart, vlen, &tmp_tag, &tmp_class))
return -1;
if (!append_exp(arg, tmp_tag, tmp_class, 1, 0, 0))
return -1;
break;
case ASN1_GEN_FLAG_SEQWRAP:
if (!append_exp(arg, V_ASN1_SEQUENCE, V_ASN1_UNIVERSAL, 1, 0, 1))
return -1;
break;
case ASN1_GEN_FLAG_SETWRAP:
if (!append_exp(arg, V_ASN1_SET, V_ASN1_UNIVERSAL, 1, 0, 1))
return -1;
break;
case ASN1_GEN_FLAG_BITWRAP:
if (!append_exp(arg, V_ASN1_BIT_STRING, V_ASN1_UNIVERSAL, 0, 1, 1))
return -1;
break;
case ASN1_GEN_FLAG_OCTWRAP:
if (!append_exp(arg, V_ASN1_OCTET_STRING, V_ASN1_UNIVERSAL, 0, 0, 1))
return -1;
break;
case ASN1_GEN_FLAG_FORMAT:
if (!vstart) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_FORMAT);
return -1;
}
if (HAS_PREFIX(vstart, "ASCII"))
arg->format = ASN1_GEN_FORMAT_ASCII;
else if (HAS_PREFIX(vstart, "UTF8"))
arg->format = ASN1_GEN_FORMAT_UTF8;
else if (HAS_PREFIX(vstart, "HEX"))
arg->format = ASN1_GEN_FORMAT_HEX;
else if (HAS_PREFIX(vstart, "BITLIST"))
arg->format = ASN1_GEN_FORMAT_BITLIST;
else {
ERR_raise(ERR_LIB_ASN1, ASN1_R_UNKNOWN_FORMAT);
return -1;
}
break;
}
return 1;
}
static int parse_tagging(const char *vstart, int vlen, int *ptag, int *pclass)
{
long tag_num;
char *eptr;
if (!vstart)
return 0;
tag_num = strtoul(vstart, &eptr, 10);
/* Check we haven't gone past max length: should be impossible */
if (eptr && *eptr && (eptr > vstart + vlen))
return 0;
if (tag_num < 0) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_NUMBER);
return 0;
}
*ptag = tag_num;
/* If we have non numeric characters, parse them */
if (eptr)
vlen -= eptr - vstart;
else
vlen = 0;
if (vlen) {
switch (*eptr) {
case 'U':
*pclass = V_ASN1_UNIVERSAL;
break;
case 'A':
*pclass = V_ASN1_APPLICATION;
break;
case 'P':
*pclass = V_ASN1_PRIVATE;
break;
case 'C':
*pclass = V_ASN1_CONTEXT_SPECIFIC;
break;
default:
ERR_raise_data(ERR_LIB_ASN1, ASN1_R_INVALID_MODIFIER,
"Char=%c", *eptr);
return 0;
}
} else
*pclass = V_ASN1_CONTEXT_SPECIFIC;
return 1;
}
/* Handle multiple types: SET and SEQUENCE */
static ASN1_TYPE *asn1_multi(int utype, const char *section, X509V3_CTX *cnf,
int depth, int *perr)
{
ASN1_TYPE *ret = NULL;
STACK_OF(ASN1_TYPE) *sk = NULL;
STACK_OF(CONF_VALUE) *sect = NULL;
unsigned char *der = NULL;
int derlen;
int i;
sk = sk_ASN1_TYPE_new_null();
if (!sk)
goto bad;
if (section) {
if (!cnf)
goto bad;
sect = X509V3_get_section(cnf, (char *)section);
if (!sect)
goto bad;
for (i = 0; i < sk_CONF_VALUE_num(sect); i++) {
ASN1_TYPE *typ =
generate_v3(sk_CONF_VALUE_value(sect, i)->value, cnf,
depth + 1, perr);
if (!typ)
goto bad;
if (!sk_ASN1_TYPE_push(sk, typ))
goto bad;
}
}
/*
* Now we has a STACK of the components, convert to the correct form
*/
if (utype == V_ASN1_SET)
derlen = i2d_ASN1_SET_ANY(sk, &der);
else
derlen = i2d_ASN1_SEQUENCE_ANY(sk, &der);
if (derlen < 0)
goto bad;
if ((ret = ASN1_TYPE_new()) == NULL)
goto bad;
if ((ret->value.asn1_string = ASN1_STRING_type_new(utype)) == NULL)
goto bad;
ret->type = utype;
ret->value.asn1_string->data = der;
ret->value.asn1_string->length = derlen;
der = NULL;
bad:
OPENSSL_free(der);
sk_ASN1_TYPE_pop_free(sk, ASN1_TYPE_free);
X509V3_section_free(cnf, sect);
return ret;
}
static int append_exp(tag_exp_arg *arg, int exp_tag, int exp_class,
int exp_constructed, int exp_pad, int imp_ok)
{
tag_exp_type *exp_tmp;
/* Can only have IMPLICIT if permitted */
if ((arg->imp_tag != -1) && !imp_ok) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_IMPLICIT_TAG);
return 0;
}
if (arg->exp_count == ASN1_FLAG_EXP_MAX) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_DEPTH_EXCEEDED);
return 0;
}
exp_tmp = &arg->exp_list[arg->exp_count++];
/*
* If IMPLICIT set tag to implicit value then reset implicit tag since it
* has been used.
*/
if (arg->imp_tag != -1) {
exp_tmp->exp_tag = arg->imp_tag;
exp_tmp->exp_class = arg->imp_class;
arg->imp_tag = -1;
arg->imp_class = -1;
} else {
exp_tmp->exp_tag = exp_tag;
exp_tmp->exp_class = exp_class;
}
exp_tmp->exp_constructed = exp_constructed;
exp_tmp->exp_pad = exp_pad;
return 1;
}
static int asn1_str2tag(const char *tagstr, int len)
{
unsigned int i;
static const struct tag_name_st *tntmp, tnst[] = {
ASN1_GEN_STR("BOOL", V_ASN1_BOOLEAN),
ASN1_GEN_STR("BOOLEAN", V_ASN1_BOOLEAN),
ASN1_GEN_STR("NULL", V_ASN1_NULL),
ASN1_GEN_STR("INT", V_ASN1_INTEGER),
ASN1_GEN_STR("INTEGER", V_ASN1_INTEGER),
ASN1_GEN_STR("ENUM", V_ASN1_ENUMERATED),
ASN1_GEN_STR("ENUMERATED", V_ASN1_ENUMERATED),
ASN1_GEN_STR("OID", V_ASN1_OBJECT),
ASN1_GEN_STR("OBJECT", V_ASN1_OBJECT),
ASN1_GEN_STR("UTCTIME", V_ASN1_UTCTIME),
ASN1_GEN_STR("UTC", V_ASN1_UTCTIME),
ASN1_GEN_STR("GENERALIZEDTIME", V_ASN1_GENERALIZEDTIME),
ASN1_GEN_STR("GENTIME", V_ASN1_GENERALIZEDTIME),
ASN1_GEN_STR("OCT", V_ASN1_OCTET_STRING),
ASN1_GEN_STR("OCTETSTRING", V_ASN1_OCTET_STRING),
ASN1_GEN_STR("BITSTR", V_ASN1_BIT_STRING),
ASN1_GEN_STR("BITSTRING", V_ASN1_BIT_STRING),
ASN1_GEN_STR("UNIVERSALSTRING", V_ASN1_UNIVERSALSTRING),
ASN1_GEN_STR("UNIV", V_ASN1_UNIVERSALSTRING),
ASN1_GEN_STR("IA5", V_ASN1_IA5STRING),
ASN1_GEN_STR("IA5STRING", V_ASN1_IA5STRING),
ASN1_GEN_STR("UTF8", V_ASN1_UTF8STRING),
ASN1_GEN_STR("UTF8String", V_ASN1_UTF8STRING),
ASN1_GEN_STR("BMP", V_ASN1_BMPSTRING),
ASN1_GEN_STR("BMPSTRING", V_ASN1_BMPSTRING),
ASN1_GEN_STR("VISIBLESTRING", V_ASN1_VISIBLESTRING),
ASN1_GEN_STR("VISIBLE", V_ASN1_VISIBLESTRING),
ASN1_GEN_STR("PRINTABLESTRING", V_ASN1_PRINTABLESTRING),
ASN1_GEN_STR("PRINTABLE", V_ASN1_PRINTABLESTRING),
ASN1_GEN_STR("T61", V_ASN1_T61STRING),
ASN1_GEN_STR("T61STRING", V_ASN1_T61STRING),
ASN1_GEN_STR("TELETEXSTRING", V_ASN1_T61STRING),
ASN1_GEN_STR("GeneralString", V_ASN1_GENERALSTRING),
ASN1_GEN_STR("GENSTR", V_ASN1_GENERALSTRING),
ASN1_GEN_STR("NUMERIC", V_ASN1_NUMERICSTRING),
ASN1_GEN_STR("NUMERICSTRING", V_ASN1_NUMERICSTRING),
/* Special cases */
ASN1_GEN_STR("SEQUENCE", V_ASN1_SEQUENCE),
ASN1_GEN_STR("SEQ", V_ASN1_SEQUENCE),
ASN1_GEN_STR("SET", V_ASN1_SET),
/* type modifiers */
/* Explicit tag */
ASN1_GEN_STR("EXP", ASN1_GEN_FLAG_EXP),
ASN1_GEN_STR("EXPLICIT", ASN1_GEN_FLAG_EXP),
/* Implicit tag */
ASN1_GEN_STR("IMP", ASN1_GEN_FLAG_IMP),
ASN1_GEN_STR("IMPLICIT", ASN1_GEN_FLAG_IMP),
/* OCTET STRING wrapper */
ASN1_GEN_STR("OCTWRAP", ASN1_GEN_FLAG_OCTWRAP),
/* SEQUENCE wrapper */
ASN1_GEN_STR("SEQWRAP", ASN1_GEN_FLAG_SEQWRAP),
/* SET wrapper */
ASN1_GEN_STR("SETWRAP", ASN1_GEN_FLAG_SETWRAP),
/* BIT STRING wrapper */
ASN1_GEN_STR("BITWRAP", ASN1_GEN_FLAG_BITWRAP),
ASN1_GEN_STR("FORM", ASN1_GEN_FLAG_FORMAT),
ASN1_GEN_STR("FORMAT", ASN1_GEN_FLAG_FORMAT),
};
if (len == -1)
len = strlen(tagstr);
tntmp = tnst;
for (i = 0; i < OSSL_NELEM(tnst); i++, tntmp++) {
if ((len == tntmp->len)
&& (OPENSSL_strncasecmp(tntmp->strnam, tagstr, len) == 0))
return tntmp->tag;
}
return -1;
}
static ASN1_TYPE *asn1_str2type(const char *str, int format, int utype)
{
ASN1_TYPE *atmp = NULL;
CONF_VALUE vtmp;
unsigned char *rdata;
long rdlen;
int no_unused = 1;
if ((atmp = ASN1_TYPE_new()) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
return NULL;
}
if (!str)
str = "";
switch (utype) {
case V_ASN1_NULL:
if (str && *str) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_NULL_VALUE);
goto bad_form;
}
break;
case V_ASN1_BOOLEAN:
if (format != ASN1_GEN_FORMAT_ASCII) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_NOT_ASCII_FORMAT);
goto bad_form;
}
vtmp.name = NULL;
vtmp.section = NULL;
vtmp.value = (char *)str;
if (!X509V3_get_value_bool(&vtmp, &atmp->value.boolean)) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_BOOLEAN);
goto bad_str;
}
break;
case V_ASN1_INTEGER:
case V_ASN1_ENUMERATED:
if (format != ASN1_GEN_FORMAT_ASCII) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INTEGER_NOT_ASCII_FORMAT);
goto bad_form;
}
if ((atmp->value.integer
= s2i_ASN1_INTEGER(NULL, str)) == NULL) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_INTEGER);
goto bad_str;
}
break;
case V_ASN1_OBJECT:
if (format != ASN1_GEN_FORMAT_ASCII) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_OBJECT_NOT_ASCII_FORMAT);
goto bad_form;
}
if ((atmp->value.object = OBJ_txt2obj(str, 0)) == NULL) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_OBJECT);
goto bad_str;
}
break;
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
if (format != ASN1_GEN_FORMAT_ASCII) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_TIME_NOT_ASCII_FORMAT);
goto bad_form;
}
if ((atmp->value.asn1_string = ASN1_STRING_new()) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
goto bad_str;
}
if (!ASN1_STRING_set(atmp->value.asn1_string, str, -1)) {
ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
goto bad_str;
}
atmp->value.asn1_string->type = utype;
if (!ASN1_TIME_check(atmp->value.asn1_string)) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_TIME_VALUE);
goto bad_str;
}
break;
case V_ASN1_BMPSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_IA5STRING:
case V_ASN1_T61STRING:
case V_ASN1_UTF8STRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_NUMERICSTRING:
if (format == ASN1_GEN_FORMAT_ASCII)
format = MBSTRING_ASC;
else if (format == ASN1_GEN_FORMAT_UTF8)
format = MBSTRING_UTF8;
else {
ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_FORMAT);
goto bad_form;
}
if (ASN1_mbstring_copy(&atmp->value.asn1_string, (unsigned char *)str,
-1, format, ASN1_tag2bit(utype)) <= 0) {
ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
goto bad_str;
}
break;
case V_ASN1_BIT_STRING:
case V_ASN1_OCTET_STRING:
if ((atmp->value.asn1_string = ASN1_STRING_new()) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
goto bad_form;
}
if (format == ASN1_GEN_FORMAT_HEX) {
if ((rdata = OPENSSL_hexstr2buf(str, &rdlen)) == NULL) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_HEX);
goto bad_str;
}
atmp->value.asn1_string->data = rdata;
atmp->value.asn1_string->length = rdlen;
atmp->value.asn1_string->type = utype;
} else if (format == ASN1_GEN_FORMAT_ASCII)
ASN1_STRING_set(atmp->value.asn1_string, str, -1);
else if ((format == ASN1_GEN_FORMAT_BITLIST)
&& (utype == V_ASN1_BIT_STRING)) {
if (!CONF_parse_list
(str, ',', 1, bitstr_cb, atmp->value.bit_string)) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_LIST_ERROR);
goto bad_str;
}
no_unused = 0;
} else {
ERR_raise(ERR_LIB_ASN1, ASN1_R_ILLEGAL_BITSTRING_FORMAT);
goto bad_form;
}
if ((utype == V_ASN1_BIT_STRING) && no_unused)
ossl_asn1_string_set_bits_left(atmp->value.asn1_string, 0);
break;
default:
ERR_raise(ERR_LIB_ASN1, ASN1_R_UNSUPPORTED_TYPE);
goto bad_str;
}
atmp->type = utype;
return atmp;
bad_str:
ERR_add_error_data(2, "string=", str);
bad_form:
ASN1_TYPE_free(atmp);
return NULL;
}
static int bitstr_cb(const char *elem, int len, void *bitstr)
{
long bitnum;
char *eptr;
if (!elem)
return 0;
bitnum = strtoul(elem, &eptr, 10);
if (eptr && *eptr && (eptr != elem + len))
return 0;
if (bitnum < 0) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_INVALID_NUMBER);
return 0;
}
if (!ASN1_BIT_STRING_set_bit(bitstr, bitnum, 1)) {
ERR_raise(ERR_LIB_ASN1, ERR_R_ASN1_LIB);
return 0;
}
return 1;
}
static int mask_cb(const char *elem, int len, void *arg)
{
unsigned long *pmask = arg, tmpmask;
int tag;
if (elem == NULL)
return 0;
if (len == 3 && HAS_PREFIX(elem, "DIR")) {
*pmask |= B_ASN1_DIRECTORYSTRING;
return 1;
}
tag = asn1_str2tag(elem, len);
if (!tag || (tag & ASN1_GEN_FLAG))
return 0;
tmpmask = ASN1_tag2bit(tag);
if (!tmpmask)
return 0;
*pmask |= tmpmask;
return 1;
}
int ASN1_str2mask(const char *str, unsigned long *pmask)
{
*pmask = 0;
return CONF_parse_list(str, '|', 1, mask_cb, pmask);
}
| 22,779 | 28.056122 | 78 | c |
openssl | openssl-master/crypto/asn1/asn1_item_list.c | /*
* Copyright 2000-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* We need to use the low level ASN1 items until they are removed */
#define OPENSSL_SUPPRESS_DEPRECATED
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/cms.h>
#include <openssl/dh.h>
#include <openssl/ocsp.h>
#include <openssl/pkcs7.h>
#include <openssl/pkcs12.h>
#include <openssl/rsa.h>
#include <openssl/x509v3.h>
#include "asn1_item_list.h"
const ASN1_ITEM *ASN1_ITEM_lookup(const char *name)
{
size_t i;
for (i = 0; i < OSSL_NELEM(asn1_item_list); i++) {
const ASN1_ITEM *it = ASN1_ITEM_ptr(asn1_item_list[i]);
if (strcmp(it->sname, name) == 0)
return it;
}
return NULL;
}
const ASN1_ITEM *ASN1_ITEM_get(size_t i)
{
if (i >= OSSL_NELEM(asn1_item_list))
return NULL;
return ASN1_ITEM_ptr(asn1_item_list[i]);
}
| 1,191 | 24.913043 | 74 | c |
openssl | openssl-master/crypto/asn1/asn1_item_list.h | /*
* Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
static ASN1_ITEM_EXP *asn1_item_list[] = {
ASN1_ITEM_ref(ACCESS_DESCRIPTION),
#ifndef OPENSSL_NO_RFC3779
ASN1_ITEM_ref(ASIdOrRange),
ASN1_ITEM_ref(ASIdentifierChoice),
ASN1_ITEM_ref(ASIdentifiers),
#endif
ASN1_ITEM_ref(ASN1_ANY),
ASN1_ITEM_ref(ASN1_BIT_STRING),
ASN1_ITEM_ref(ASN1_BMPSTRING),
ASN1_ITEM_ref(ASN1_BOOLEAN),
ASN1_ITEM_ref(ASN1_ENUMERATED),
ASN1_ITEM_ref(ASN1_FBOOLEAN),
ASN1_ITEM_ref(ASN1_GENERALIZEDTIME),
ASN1_ITEM_ref(ASN1_GENERALSTRING),
ASN1_ITEM_ref(ASN1_IA5STRING),
ASN1_ITEM_ref(ASN1_INTEGER),
ASN1_ITEM_ref(ASN1_NULL),
ASN1_ITEM_ref(ASN1_OBJECT),
ASN1_ITEM_ref(ASN1_OCTET_STRING_NDEF),
ASN1_ITEM_ref(ASN1_OCTET_STRING),
ASN1_ITEM_ref(ASN1_PRINTABLESTRING),
ASN1_ITEM_ref(ASN1_PRINTABLE),
ASN1_ITEM_ref(ASN1_SEQUENCE_ANY),
ASN1_ITEM_ref(ASN1_SEQUENCE),
ASN1_ITEM_ref(ASN1_SET_ANY),
ASN1_ITEM_ref(ASN1_T61STRING),
ASN1_ITEM_ref(ASN1_TBOOLEAN),
ASN1_ITEM_ref(ASN1_TIME),
ASN1_ITEM_ref(ASN1_UNIVERSALSTRING),
ASN1_ITEM_ref(ASN1_UTCTIME),
ASN1_ITEM_ref(ASN1_UTF8STRING),
ASN1_ITEM_ref(ASN1_VISIBLESTRING),
#ifndef OPENSSL_NO_RFC3779
ASN1_ITEM_ref(ASRange),
#endif
ASN1_ITEM_ref(AUTHORITY_INFO_ACCESS),
ASN1_ITEM_ref(AUTHORITY_KEYID),
ASN1_ITEM_ref(BASIC_CONSTRAINTS),
ASN1_ITEM_ref(BIGNUM),
ASN1_ITEM_ref(CBIGNUM),
ASN1_ITEM_ref(CERTIFICATEPOLICIES),
#ifndef OPENSSL_NO_CMS
ASN1_ITEM_ref(CMS_ContentInfo),
ASN1_ITEM_ref(CMS_EnvelopedData),
ASN1_ITEM_ref(CMS_ReceiptRequest),
#endif
ASN1_ITEM_ref(CRL_DIST_POINTS),
#ifndef OPENSSL_NO_DH
ASN1_ITEM_ref(DHparams),
#endif
ASN1_ITEM_ref(DIRECTORYSTRING),
ASN1_ITEM_ref(DISPLAYTEXT),
ASN1_ITEM_ref(DIST_POINT_NAME),
ASN1_ITEM_ref(DIST_POINT),
#ifndef OPENSSL_NO_EC
# ifndef OPENSSL_NO_DEPRECATED_3_0
ASN1_ITEM_ref(ECPARAMETERS),
ASN1_ITEM_ref(ECPKPARAMETERS),
# endif
#endif
ASN1_ITEM_ref(EDIPARTYNAME),
ASN1_ITEM_ref(EXTENDED_KEY_USAGE),
ASN1_ITEM_ref(GENERAL_NAMES),
ASN1_ITEM_ref(GENERAL_NAME),
ASN1_ITEM_ref(GENERAL_SUBTREE),
#ifndef OPENSSL_NO_RFC3779
ASN1_ITEM_ref(IPAddressChoice),
ASN1_ITEM_ref(IPAddressFamily),
ASN1_ITEM_ref(IPAddressOrRange),
ASN1_ITEM_ref(IPAddressRange),
#endif
ASN1_ITEM_ref(ISSUING_DIST_POINT),
#ifndef OPENSSL_NO_DEPRECATED_3_0
ASN1_ITEM_ref(LONG),
#endif
ASN1_ITEM_ref(NAME_CONSTRAINTS),
ASN1_ITEM_ref(NETSCAPE_CERT_SEQUENCE),
ASN1_ITEM_ref(NETSCAPE_SPKAC),
ASN1_ITEM_ref(NETSCAPE_SPKI),
ASN1_ITEM_ref(NOTICEREF),
#ifndef OPENSSL_NO_OCSP
ASN1_ITEM_ref(OCSP_BASICRESP),
ASN1_ITEM_ref(OCSP_CERTID),
ASN1_ITEM_ref(OCSP_CERTSTATUS),
ASN1_ITEM_ref(OCSP_CRLID),
ASN1_ITEM_ref(OCSP_ONEREQ),
ASN1_ITEM_ref(OCSP_REQINFO),
ASN1_ITEM_ref(OCSP_REQUEST),
ASN1_ITEM_ref(OCSP_RESPBYTES),
ASN1_ITEM_ref(OCSP_RESPDATA),
ASN1_ITEM_ref(OCSP_RESPID),
ASN1_ITEM_ref(OCSP_RESPONSE),
ASN1_ITEM_ref(OCSP_REVOKEDINFO),
ASN1_ITEM_ref(OCSP_SERVICELOC),
ASN1_ITEM_ref(OCSP_SIGNATURE),
ASN1_ITEM_ref(OCSP_SINGLERESP),
#endif
ASN1_ITEM_ref(OTHERNAME),
ASN1_ITEM_ref(PBE2PARAM),
ASN1_ITEM_ref(PBEPARAM),
ASN1_ITEM_ref(PBKDF2PARAM),
ASN1_ITEM_ref(PKCS12_AUTHSAFES),
ASN1_ITEM_ref(PKCS12_BAGS),
ASN1_ITEM_ref(PKCS12_MAC_DATA),
ASN1_ITEM_ref(PKCS12_SAFEBAGS),
ASN1_ITEM_ref(PKCS12_SAFEBAG),
ASN1_ITEM_ref(PKCS12),
ASN1_ITEM_ref(PKCS7_ATTR_SIGN),
ASN1_ITEM_ref(PKCS7_ATTR_VERIFY),
ASN1_ITEM_ref(PKCS7_DIGEST),
ASN1_ITEM_ref(PKCS7_ENCRYPT),
ASN1_ITEM_ref(PKCS7_ENC_CONTENT),
ASN1_ITEM_ref(PKCS7_ENVELOPE),
ASN1_ITEM_ref(PKCS7_ISSUER_AND_SERIAL),
ASN1_ITEM_ref(PKCS7_RECIP_INFO),
ASN1_ITEM_ref(PKCS7_SIGNED),
ASN1_ITEM_ref(PKCS7_SIGNER_INFO),
ASN1_ITEM_ref(PKCS7_SIGN_ENVELOPE),
ASN1_ITEM_ref(PKCS7),
ASN1_ITEM_ref(PKCS8_PRIV_KEY_INFO),
ASN1_ITEM_ref(PKEY_USAGE_PERIOD),
ASN1_ITEM_ref(POLICYINFO),
ASN1_ITEM_ref(POLICYQUALINFO),
ASN1_ITEM_ref(POLICY_CONSTRAINTS),
ASN1_ITEM_ref(POLICY_MAPPINGS),
ASN1_ITEM_ref(POLICY_MAPPING),
ASN1_ITEM_ref(PROXY_CERT_INFO_EXTENSION),
ASN1_ITEM_ref(PROXY_POLICY),
#ifndef OPENSSL_NO_DEPRECATED_3_0
ASN1_ITEM_ref(RSAPrivateKey),
ASN1_ITEM_ref(RSAPublicKey),
ASN1_ITEM_ref(RSA_OAEP_PARAMS),
ASN1_ITEM_ref(RSA_PSS_PARAMS),
#endif
#ifndef OPENSSL_NO_SCRYPT
ASN1_ITEM_ref(SCRYPT_PARAMS),
#endif
ASN1_ITEM_ref(SXNETID),
ASN1_ITEM_ref(SXNET),
ASN1_ITEM_ref(ISSUER_SIGN_TOOL),
ASN1_ITEM_ref(USERNOTICE),
ASN1_ITEM_ref(X509_ALGORS),
ASN1_ITEM_ref(X509_ALGOR),
ASN1_ITEM_ref(X509_ATTRIBUTE),
ASN1_ITEM_ref(X509_CERT_AUX),
ASN1_ITEM_ref(X509_CINF),
ASN1_ITEM_ref(X509_CRL_INFO),
ASN1_ITEM_ref(X509_CRL),
ASN1_ITEM_ref(X509_EXTENSIONS),
ASN1_ITEM_ref(X509_EXTENSION),
ASN1_ITEM_ref(X509_NAME_ENTRY),
ASN1_ITEM_ref(X509_NAME),
ASN1_ITEM_ref(X509_PUBKEY),
ASN1_ITEM_ref(X509_REQ_INFO),
ASN1_ITEM_ref(X509_REQ),
ASN1_ITEM_ref(X509_REVOKED),
ASN1_ITEM_ref(X509_SIG),
ASN1_ITEM_ref(X509_VAL),
ASN1_ITEM_ref(X509),
#ifndef OPENSSL_NO_DEPRECATED_3_0
ASN1_ITEM_ref(ZLONG),
#endif
ASN1_ITEM_ref(INT32),
ASN1_ITEM_ref(UINT32),
ASN1_ITEM_ref(ZINT32),
ASN1_ITEM_ref(ZUINT32),
ASN1_ITEM_ref(INT64),
ASN1_ITEM_ref(UINT64),
ASN1_ITEM_ref(ZINT64),
ASN1_ITEM_ref(ZUINT64),
};
| 5,762 | 30.491803 | 74 | h |
openssl | openssl-master/crypto/asn1/asn1_lib.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 <limits.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include "asn1_local.h"
static int asn1_get_length(const unsigned char **pp, int *inf, long *rl,
long max);
static void asn1_put_length(unsigned char **pp, int length);
static int _asn1_check_infinite_end(const unsigned char **p, long len)
{
/*
* If there is 0 or 1 byte left, the length check should pick things up
*/
if (len <= 0) {
return 1;
} else {
if ((len >= 2) && ((*p)[0] == 0) && ((*p)[1] == 0)) {
(*p) += 2;
return 1;
}
}
return 0;
}
int ASN1_check_infinite_end(unsigned char **p, long len)
{
return _asn1_check_infinite_end((const unsigned char **)p, len);
}
int ASN1_const_check_infinite_end(const unsigned char **p, long len)
{
return _asn1_check_infinite_end(p, len);
}
int ASN1_get_object(const unsigned char **pp, long *plength, int *ptag,
int *pclass, long omax)
{
int i, ret;
long len;
const unsigned char *p = *pp;
int tag, xclass, inf;
long max = omax;
if (omax <= 0) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_SMALL);
return 0x80;
}
ret = (*p & V_ASN1_CONSTRUCTED);
xclass = (*p & V_ASN1_PRIVATE);
i = *p & V_ASN1_PRIMITIVE_TAG;
if (i == V_ASN1_PRIMITIVE_TAG) { /* high-tag */
p++;
if (--max == 0)
goto err;
len = 0;
while (*p & 0x80) {
len <<= 7L;
len |= *(p++) & 0x7f;
if (--max == 0)
goto err;
if (len > (INT_MAX >> 7L))
goto err;
}
len <<= 7L;
len |= *(p++) & 0x7f;
tag = (int)len;
if (--max == 0)
goto err;
} else {
tag = i;
p++;
if (--max == 0)
goto err;
}
*ptag = tag;
*pclass = xclass;
if (!asn1_get_length(&p, &inf, plength, max))
goto err;
if (inf && !(ret & V_ASN1_CONSTRUCTED))
goto err;
if (*plength > (omax - (p - *pp))) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LONG);
/*
* Set this so that even if things are not long enough the values are
* set correctly
*/
ret |= 0x80;
}
*pp = p;
return ret | inf;
err:
ERR_raise(ERR_LIB_ASN1, ASN1_R_HEADER_TOO_LONG);
return 0x80;
}
/*
* Decode a length field.
* The short form is a single byte defining a length 0 - 127.
* The long form is a byte 0 - 127 with the top bit set and this indicates
* the number of following octets that contain the length. These octets
* are stored most significant digit first.
*/
static int asn1_get_length(const unsigned char **pp, int *inf, long *rl,
long max)
{
const unsigned char *p = *pp;
unsigned long ret = 0;
int i;
if (max-- < 1)
return 0;
if (*p == 0x80) {
*inf = 1;
p++;
} else {
*inf = 0;
i = *p & 0x7f;
if (*p++ & 0x80) {
if (max < i + 1)
return 0;
/* Skip leading zeroes */
while (i > 0 && *p == 0) {
p++;
i--;
}
if (i > (int)sizeof(long))
return 0;
while (i > 0) {
ret <<= 8;
ret |= *p++;
i--;
}
if (ret > LONG_MAX)
return 0;
} else {
ret = i;
}
}
*pp = p;
*rl = (long)ret;
return 1;
}
/*
* constructed == 2 for indefinite length constructed
*/
void ASN1_put_object(unsigned char **pp, int constructed, int length, int tag,
int xclass)
{
unsigned char *p = *pp;
int i, ttag;
i = (constructed) ? V_ASN1_CONSTRUCTED : 0;
i |= (xclass & V_ASN1_PRIVATE);
if (tag < 31) {
*(p++) = i | (tag & V_ASN1_PRIMITIVE_TAG);
} else {
*(p++) = i | V_ASN1_PRIMITIVE_TAG;
for (i = 0, ttag = tag; ttag > 0; i++)
ttag >>= 7;
ttag = i;
while (i-- > 0) {
p[i] = tag & 0x7f;
if (i != (ttag - 1))
p[i] |= 0x80;
tag >>= 7;
}
p += ttag;
}
if (constructed == 2)
*(p++) = 0x80;
else
asn1_put_length(&p, length);
*pp = p;
}
int ASN1_put_eoc(unsigned char **pp)
{
unsigned char *p = *pp;
*p++ = 0;
*p++ = 0;
*pp = p;
return 2;
}
static void asn1_put_length(unsigned char **pp, int length)
{
unsigned char *p = *pp;
int i, len;
if (length <= 127) {
*(p++) = (unsigned char)length;
} else {
len = length;
for (i = 0; len > 0; i++)
len >>= 8;
*(p++) = i | 0x80;
len = i;
while (i-- > 0) {
p[i] = length & 0xff;
length >>= 8;
}
p += len;
}
*pp = p;
}
int ASN1_object_size(int constructed, int length, int tag)
{
int ret = 1;
if (length < 0)
return -1;
if (tag >= 31) {
while (tag > 0) {
tag >>= 7;
ret++;
}
}
if (constructed == 2) {
ret += 3;
} else {
ret++;
if (length > 127) {
int tmplen = length;
while (tmplen > 0) {
tmplen >>= 8;
ret++;
}
}
}
if (ret >= INT_MAX - length)
return -1;
return ret + length;
}
void ossl_asn1_string_set_bits_left(ASN1_STRING *str, unsigned int num)
{
str->flags &= ~0x07;
str->flags |= ASN1_STRING_FLAG_BITS_LEFT | (num & 0x07);
}
int ASN1_STRING_copy(ASN1_STRING *dst, const ASN1_STRING *str)
{
if (str == NULL)
return 0;
dst->type = str->type;
if (!ASN1_STRING_set(dst, str->data, str->length))
return 0;
/* Copy flags but preserve embed value */
dst->flags &= ASN1_STRING_FLAG_EMBED;
dst->flags |= str->flags & ~ASN1_STRING_FLAG_EMBED;
return 1;
}
ASN1_STRING *ASN1_STRING_dup(const ASN1_STRING *str)
{
ASN1_STRING *ret;
if (!str)
return NULL;
ret = ASN1_STRING_new();
if (ret == NULL)
return NULL;
if (!ASN1_STRING_copy(ret, str)) {
ASN1_STRING_free(ret);
return NULL;
}
return ret;
}
int ASN1_STRING_set(ASN1_STRING *str, const void *_data, int len_in)
{
unsigned char *c;
const char *data = _data;
size_t len;
if (len_in < 0) {
if (data == NULL)
return 0;
len = strlen(data);
} else {
len = (size_t)len_in;
}
/*
* Verify that the length fits within an integer for assignment to
* str->length below. The additional 1 is subtracted to allow for the
* '\0' terminator even though this isn't strictly necessary.
*/
if (len > INT_MAX - 1) {
ERR_raise(ERR_LIB_ASN1, ASN1_R_TOO_LARGE);
return 0;
}
if ((size_t)str->length <= len || str->data == NULL) {
c = str->data;
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
/* No NUL terminator in fuzzing builds */
str->data = OPENSSL_realloc(c, len != 0 ? len : 1);
#else
str->data = OPENSSL_realloc(c, len + 1);
#endif
if (str->data == NULL) {
str->data = c;
return 0;
}
}
str->length = len;
if (data != NULL) {
memcpy(str->data, data, len);
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
/* Set the unused byte to something non NUL and printable. */
if (len == 0)
str->data[len] = '~';
#else
/*
* Add a NUL terminator. This should not be necessary - but we add it as
* a safety precaution
*/
str->data[len] = '\0';
#endif
}
return 1;
}
void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len)
{
OPENSSL_free(str->data);
str->data = data;
str->length = len;
}
ASN1_STRING *ASN1_STRING_new(void)
{
return ASN1_STRING_type_new(V_ASN1_OCTET_STRING);
}
ASN1_STRING *ASN1_STRING_type_new(int type)
{
ASN1_STRING *ret;
ret = OPENSSL_zalloc(sizeof(*ret));
if (ret == NULL)
return NULL;
ret->type = type;
return ret;
}
void ossl_asn1_string_embed_free(ASN1_STRING *a, int embed)
{
if (a == NULL)
return;
if (!(a->flags & ASN1_STRING_FLAG_NDEF))
OPENSSL_free(a->data);
if (embed == 0)
OPENSSL_free(a);
}
void ASN1_STRING_free(ASN1_STRING *a)
{
if (a == NULL)
return;
ossl_asn1_string_embed_free(a, a->flags & ASN1_STRING_FLAG_EMBED);
}
void ASN1_STRING_clear_free(ASN1_STRING *a)
{
if (a == NULL)
return;
if (a->data && !(a->flags & ASN1_STRING_FLAG_NDEF))
OPENSSL_cleanse(a->data, a->length);
ASN1_STRING_free(a);
}
int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b)
{
int i;
i = (a->length - b->length);
if (i == 0) {
if (a->length != 0)
i = memcmp(a->data, b->data, a->length);
if (i == 0)
return a->type - b->type;
else
return i;
} else {
return i;
}
}
int ASN1_STRING_length(const ASN1_STRING *x)
{
return x->length;
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
void ASN1_STRING_length_set(ASN1_STRING *x, int len)
{
x->length = len;
}
#endif
int ASN1_STRING_type(const ASN1_STRING *x)
{
return x->type;
}
const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *x)
{
return x->data;
}
#ifndef OPENSSL_NO_DEPRECATED_1_1_0
unsigned char *ASN1_STRING_data(ASN1_STRING *x)
{
return x->data;
}
#endif
/* |max_len| excludes NUL terminator and may be 0 to indicate no restriction */
char *ossl_sk_ASN1_UTF8STRING2text(STACK_OF(ASN1_UTF8STRING) *text,
const char *sep, size_t max_len)
{
int i;
ASN1_UTF8STRING *current;
size_t length = 0, sep_len;
char *result = NULL;
char *p;
if (sep == NULL)
sep = "";
sep_len = strlen(sep);
for (i = 0; i < sk_ASN1_UTF8STRING_num(text); i++) {
current = sk_ASN1_UTF8STRING_value(text, i);
if (i > 0)
length += sep_len;
length += ASN1_STRING_length(current);
if (max_len != 0 && length > max_len)
return NULL;
}
if ((result = OPENSSL_malloc(length + 1)) == NULL)
return NULL;
p = result;
for (i = 0; i < sk_ASN1_UTF8STRING_num(text); i++) {
current = sk_ASN1_UTF8STRING_value(text, i);
length = ASN1_STRING_length(current);
if (i > 0 && sep_len > 0) {
strncpy(p, sep, sep_len + 1); /* using + 1 to silence gcc warning */
p += sep_len;
}
strncpy(p, (const char *)ASN1_STRING_get0_data(current), length);
p += length;
}
*p = '\0';
return result;
}
| 11,215 | 22.662447 | 80 | c |
openssl | openssl-master/crypto/asn1/asn1_local.h | /*
* Copyright 2005-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* Internal ASN1 structures and functions: not for application use */
#include "crypto/asn1.h"
typedef const ASN1_VALUE const_ASN1_VALUE;
SKM_DEFINE_STACK_OF(const_ASN1_VALUE, const ASN1_VALUE, ASN1_VALUE)
int ossl_asn1_time_to_tm(struct tm *tm, const ASN1_TIME *d);
int ossl_asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d);
/* ASN1 scan context structure */
struct asn1_sctx_st {
/* The ASN1_ITEM associated with this field */
const ASN1_ITEM *it;
/* If ASN1_TEMPLATE associated with this field */
const ASN1_TEMPLATE *tt;
/* Various flags associated with field and context */
unsigned long flags;
/* If SEQUENCE OF or SET OF, field index */
int skidx;
/* ASN1 depth of field */
int depth;
/* Structure and field name */
const char *sname, *fname;
/* If a primitive type the type of underlying field */
int prim_type;
/* The field value itself */
ASN1_VALUE **field;
/* Callback to pass information to */
int (*scan_cb) (ASN1_SCTX *ctx);
/* Context specific application data */
void *app_data;
} /* ASN1_SCTX */ ;
typedef struct mime_param_st MIME_PARAM;
DEFINE_STACK_OF(MIME_PARAM)
typedef struct mime_header_st MIME_HEADER;
DEFINE_STACK_OF(MIME_HEADER)
void ossl_asn1_string_embed_free(ASN1_STRING *a, int embed);
int ossl_asn1_get_choice_selector(ASN1_VALUE **pval, const ASN1_ITEM *it);
int ossl_asn1_get_choice_selector_const(const ASN1_VALUE **pval,
const ASN1_ITEM *it);
int ossl_asn1_set_choice_selector(ASN1_VALUE **pval, int value,
const ASN1_ITEM *it);
ASN1_VALUE **ossl_asn1_get_field_ptr(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt);
const ASN1_VALUE **ossl_asn1_get_const_field_ptr(const ASN1_VALUE **pval,
const ASN1_TEMPLATE *tt);
const ASN1_TEMPLATE *ossl_asn1_do_adb(const ASN1_VALUE *val,
const ASN1_TEMPLATE *tt,
int nullerr);
int ossl_asn1_do_lock(ASN1_VALUE **pval, int op, const ASN1_ITEM *it);
void ossl_asn1_enc_init(ASN1_VALUE **pval, const ASN1_ITEM *it);
void ossl_asn1_enc_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
int ossl_asn1_enc_restore(int *len, unsigned char **out, const ASN1_VALUE **pval,
const ASN1_ITEM *it);
int ossl_asn1_enc_save(ASN1_VALUE **pval, const unsigned char *in, int inlen,
const ASN1_ITEM *it);
void ossl_asn1_item_embed_free(ASN1_VALUE **pval, const ASN1_ITEM *it, int embed);
void ossl_asn1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it, int embed);
void ossl_asn1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt);
ASN1_OBJECT *ossl_c2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp,
long length);
int ossl_i2c_ASN1_BIT_STRING(ASN1_BIT_STRING *a, unsigned char **pp);
ASN1_BIT_STRING *ossl_c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a,
const unsigned char **pp, long length);
int ossl_i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp);
ASN1_INTEGER *ossl_c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp,
long length);
/* Internal functions used by x_int64.c */
int ossl_c2i_uint64_int(uint64_t *ret, int *neg, const unsigned char **pp,
long len);
int ossl_i2c_uint64_int(unsigned char *p, uint64_t r, int neg);
ASN1_TIME *ossl_asn1_time_from_tm(ASN1_TIME *s, struct tm *ts, int type);
int ossl_asn1_item_ex_new_intern(ASN1_VALUE **pval, const ASN1_ITEM *it,
OSSL_LIB_CTX *libctx, const char *propq);
| 4,055 | 40.814433 | 82 | h |
openssl | openssl-master/crypto/asn1/asn1_parse.c | /*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/objects.h>
#include <openssl/asn1.h>
#ifndef ASN1_PARSE_MAXDEPTH
#define ASN1_PARSE_MAXDEPTH 128
#endif
static int asn1_parse2(BIO *bp, const unsigned char **pp, long length,
int offset, int depth, int indent, int dump);
static int asn1_print_info(BIO *bp, long offset, int depth, int hl, long len,
int tag, int xclass, int constructed, int indent)
{
char str[128];
const char *p;
int pop_f_prefix = 0;
long saved_indent = -1;
int i = 0;
BIO *bio = NULL;
if (constructed & V_ASN1_CONSTRUCTED)
p = "cons: ";
else
p = "prim: ";
if (constructed != (V_ASN1_CONSTRUCTED | 1)) {
if (BIO_snprintf(str, sizeof(str), "%5ld:d=%-2d hl=%ld l=%4ld %s",
offset, depth, (long)hl, len, p) <= 0)
goto err;
} else {
if (BIO_snprintf(str, sizeof(str), "%5ld:d=%-2d hl=%ld l=inf %s",
offset, depth, (long)hl, p) <= 0)
goto err;
}
if (bp != NULL) {
if (BIO_set_prefix(bp, str) <= 0) {
if ((bio = BIO_new(BIO_f_prefix())) == NULL
|| (bp = BIO_push(bio, bp)) == NULL)
goto err;
pop_f_prefix = 1;
}
saved_indent = BIO_get_indent(bp);
if (BIO_set_prefix(bp, str) <= 0 || BIO_set_indent(bp, indent) <= 0)
goto err;
}
/*
* BIO_set_prefix made a copy of |str|, so we can safely use it for
* something else, ASN.1 tag printout.
*/
p = str;
if ((xclass & V_ASN1_PRIVATE) == V_ASN1_PRIVATE)
BIO_snprintf(str, sizeof(str), "priv [ %d ] ", tag);
else if ((xclass & V_ASN1_CONTEXT_SPECIFIC) == V_ASN1_CONTEXT_SPECIFIC)
BIO_snprintf(str, sizeof(str), "cont [ %d ]", tag);
else if ((xclass & V_ASN1_APPLICATION) == V_ASN1_APPLICATION)
BIO_snprintf(str, sizeof(str), "appl [ %d ]", tag);
else if (tag > 30)
BIO_snprintf(str, sizeof(str), "<ASN1 %d>", tag);
else
p = ASN1_tag2str(tag);
i = (BIO_printf(bp, "%-18s", p) > 0);
err:
if (saved_indent >= 0)
BIO_set_indent(bp, saved_indent);
if (pop_f_prefix)
BIO_pop(bp);
BIO_free(bio);
return i;
}
int ASN1_parse(BIO *bp, const unsigned char *pp, long len, int indent)
{
return asn1_parse2(bp, &pp, len, 0, 0, indent, 0);
}
int ASN1_parse_dump(BIO *bp, const unsigned char *pp, long len, int indent,
int dump)
{
return asn1_parse2(bp, &pp, len, 0, 0, indent, dump);
}
static int asn1_parse2(BIO *bp, const unsigned char **pp, long length,
int offset, int depth, int indent, int dump)
{
const unsigned char *p, *ep, *tot, *op, *opp;
long len;
int tag, xclass, ret = 0;
int nl, hl, j, r;
ASN1_OBJECT *o = NULL;
ASN1_OCTET_STRING *os = NULL;
ASN1_INTEGER *ai = NULL;
ASN1_ENUMERATED *ae = NULL;
/* ASN1_BMPSTRING *bmp=NULL; */
int dump_indent, dump_cont = 0;
if (depth > ASN1_PARSE_MAXDEPTH) {
BIO_puts(bp, "BAD RECURSION DEPTH\n");
return 0;
}
dump_indent = 6; /* Because we know BIO_dump_indent() */
p = *pp;
tot = p + length;
while (length > 0) {
op = p;
j = ASN1_get_object(&p, &len, &tag, &xclass, length);
if (j & 0x80) {
BIO_puts(bp, "Error in encoding\n");
goto end;
}
hl = (p - op);
length -= hl;
/*
* if j == 0x21 it is a constructed indefinite length object
*/
if (!asn1_print_info(bp, (long)offset + (long)(op - *pp), depth,
hl, len, tag, xclass, j, (indent) ? depth : 0))
goto end;
if (j & V_ASN1_CONSTRUCTED) {
const unsigned char *sp = p;
ep = p + len;
if (BIO_write(bp, "\n", 1) <= 0)
goto end;
if (len > length) {
BIO_printf(bp, "length is greater than %ld\n", length);
goto end;
}
if ((j == 0x21) && (len == 0)) {
for (;;) {
r = asn1_parse2(bp, &p, (long)(tot - p),
offset + (p - *pp), depth + 1,
indent, dump);
if (r == 0)
goto end;
if ((r == 2) || (p >= tot)) {
len = p - sp;
break;
}
}
} else {
long tmp = len;
while (p < ep) {
sp = p;
r = asn1_parse2(bp, &p, tmp,
offset + (p - *pp), depth + 1,
indent, dump);
if (r == 0)
goto end;
tmp -= p - sp;
}
}
} else if (xclass != 0) {
p += len;
if (BIO_write(bp, "\n", 1) <= 0)
goto end;
} else {
nl = 0;
if ((tag == V_ASN1_PRINTABLESTRING) ||
(tag == V_ASN1_T61STRING) ||
(tag == V_ASN1_IA5STRING) ||
(tag == V_ASN1_VISIBLESTRING) ||
(tag == V_ASN1_NUMERICSTRING) ||
(tag == V_ASN1_UTF8STRING) ||
(tag == V_ASN1_UTCTIME) || (tag == V_ASN1_GENERALIZEDTIME)) {
if (BIO_write(bp, ":", 1) <= 0)
goto end;
if ((len > 0) && BIO_write(bp, (const char *)p, (int)len)
!= (int)len)
goto end;
} else if (tag == V_ASN1_OBJECT) {
opp = op;
if (d2i_ASN1_OBJECT(&o, &opp, len + hl) != NULL) {
if (BIO_write(bp, ":", 1) <= 0)
goto end;
i2a_ASN1_OBJECT(bp, o);
} else {
if (BIO_puts(bp, ":BAD OBJECT") <= 0)
goto end;
dump_cont = 1;
}
} else if (tag == V_ASN1_BOOLEAN) {
if (len != 1) {
if (BIO_puts(bp, ":BAD BOOLEAN") <= 0)
goto end;
dump_cont = 1;
}
if (len > 0)
BIO_printf(bp, ":%u", p[0]);
} else if (tag == V_ASN1_BMPSTRING) {
/* do the BMP thang */
} else if (tag == V_ASN1_OCTET_STRING) {
int i, printable = 1;
opp = op;
os = d2i_ASN1_OCTET_STRING(NULL, &opp, len + hl);
if (os != NULL && os->length > 0) {
opp = os->data;
/*
* testing whether the octet string is printable
*/
for (i = 0; i < os->length; i++) {
if (((opp[i] < ' ') &&
(opp[i] != '\n') &&
(opp[i] != '\r') &&
(opp[i] != '\t')) || (opp[i] > '~')) {
printable = 0;
break;
}
}
if (printable)
/* printable string */
{
if (BIO_write(bp, ":", 1) <= 0)
goto end;
if (BIO_write(bp, (const char *)opp, os->length) <= 0)
goto end;
} else if (!dump)
/*
* not printable => print octet string as hex dump
*/
{
if (BIO_write(bp, "[HEX DUMP]:", 11) <= 0)
goto end;
for (i = 0; i < os->length; i++) {
if (BIO_printf(bp, "%02X", opp[i]) <= 0)
goto end;
}
} else
/* print the normal dump */
{
if (!nl) {
if (BIO_write(bp, "\n", 1) <= 0)
goto end;
}
if (BIO_dump_indent(bp,
(const char *)opp,
((dump == -1 || dump >
os->
length) ? os->length : dump),
dump_indent) <= 0)
goto end;
nl = 1;
}
}
ASN1_OCTET_STRING_free(os);
os = NULL;
} else if (tag == V_ASN1_INTEGER) {
int i;
opp = op;
ai = d2i_ASN1_INTEGER(NULL, &opp, len + hl);
if (ai != NULL) {
if (BIO_write(bp, ":", 1) <= 0)
goto end;
if (ai->type == V_ASN1_NEG_INTEGER)
if (BIO_write(bp, "-", 1) <= 0)
goto end;
for (i = 0; i < ai->length; i++) {
if (BIO_printf(bp, "%02X", ai->data[i]) <= 0)
goto end;
}
if (ai->length == 0) {
if (BIO_write(bp, "00", 2) <= 0)
goto end;
}
} else {
if (BIO_puts(bp, ":BAD INTEGER") <= 0)
goto end;
dump_cont = 1;
}
ASN1_INTEGER_free(ai);
ai = NULL;
} else if (tag == V_ASN1_ENUMERATED) {
int i;
opp = op;
ae = d2i_ASN1_ENUMERATED(NULL, &opp, len + hl);
if (ae != NULL) {
if (BIO_write(bp, ":", 1) <= 0)
goto end;
if (ae->type == V_ASN1_NEG_ENUMERATED)
if (BIO_write(bp, "-", 1) <= 0)
goto end;
for (i = 0; i < ae->length; i++) {
if (BIO_printf(bp, "%02X", ae->data[i]) <= 0)
goto end;
}
if (ae->length == 0) {
if (BIO_write(bp, "00", 2) <= 0)
goto end;
}
} else {
if (BIO_puts(bp, ":BAD ENUMERATED") <= 0)
goto end;
dump_cont = 1;
}
ASN1_ENUMERATED_free(ae);
ae = NULL;
} else if (len > 0 && dump) {
if (!nl) {
if (BIO_write(bp, "\n", 1) <= 0)
goto end;
}
if (BIO_dump_indent(bp, (const char *)p,
((dump == -1 || dump > len) ? len : dump),
dump_indent) <= 0)
goto end;
nl = 1;
}
if (dump_cont) {
int i;
const unsigned char *tmp = op + hl;
if (BIO_puts(bp, ":[") <= 0)
goto end;
for (i = 0; i < len; i++) {
if (BIO_printf(bp, "%02X", tmp[i]) <= 0)
goto end;
}
if (BIO_puts(bp, "]") <= 0)
goto end;
dump_cont = 0;
}
if (!nl) {
if (BIO_write(bp, "\n", 1) <= 0)
goto end;
}
p += len;
if ((tag == V_ASN1_EOC) && (xclass == 0)) {
ret = 2; /* End of sequence */
goto end;
}
}
length -= len;
}
ret = 1;
end:
ASN1_OBJECT_free(o);
ASN1_OCTET_STRING_free(os);
ASN1_INTEGER_free(ai);
ASN1_ENUMERATED_free(ae);
*pp = p;
return ret;
}
const char *ASN1_tag2str(int tag)
{
static const char *const tag2str[] = {
/* 0-4 */
"EOC", "BOOLEAN", "INTEGER", "BIT STRING", "OCTET STRING",
/* 5-9 */
"NULL", "OBJECT", "OBJECT DESCRIPTOR", "EXTERNAL", "REAL",
/* 10-13 */
"ENUMERATED", "<ASN1 11>", "UTF8STRING", "<ASN1 13>",
/* 15-17 */
"<ASN1 14>", "<ASN1 15>", "SEQUENCE", "SET",
/* 18-20 */
"NUMERICSTRING", "PRINTABLESTRING", "T61STRING",
/* 21-24 */
"VIDEOTEXSTRING", "IA5STRING", "UTCTIME", "GENERALIZEDTIME",
/* 25-27 */
"GRAPHICSTRING", "VISIBLESTRING", "GENERALSTRING",
/* 28-30 */
"UNIVERSALSTRING", "<ASN1 29>", "BMPSTRING"
};
if ((tag == V_ASN1_NEG_INTEGER) || (tag == V_ASN1_NEG_ENUMERATED))
tag &= ~0x100;
if (tag < 0 || tag > 30)
return "(unknown)";
return tag2str[tag];
}
| 13,680 | 34.260309 | 78 | c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.