aboutsummaryrefslogtreecommitdiffstats
path: root/libparc/parc/security/parc_Security.c
blob: 999a41da874fab33bcad0c7bf208579198b08015 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/*
 * Copyright (c) 2017 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 *
 * June 9, 2014 add openssl multithreaded support.
 *              See http://www.openssl.org/docs/crypto/threads.html.
 *              We need to implement locking_function() and threadid_func().
 */
#include <config.h>

#include <stdio.h>
#include <stdbool.h>

#include <pthread.h>

#include <parc/assert/parc_Assert.h>

#include <parc/security/parc_Security.h>
#include <parc/algol/parc_Memory.h>

#include <openssl/opensslv.h>
#include <openssl/err.h>
#include <openssl/crypto.h>

#define OPENSSL_THREAD_DEFINES
#include <openssl/opensslconf.h>
#if !defined(OPENSSL_THREADS)
#error OpenSSL must support threads
#endif

// OPENSSL_VERSION_NUMBER = MMNNFFPPS
// MM = major NN = minor FF = fix PP = patch S = 0 (dev), 1-E (betas), F (release)
// This will require 1.0.1e release minimum version
//#if OPENSSL_VERSION_NUMBER < 0x1000105fL
#if OPENSSL_VERSION_NUMBER < 0x0009081fL
#pragma message(OPENSSL_VERSION_TEXT)
#error OpenSSL version must be at least 0.9.8 release
#endif

#ifndef _WIN32
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif

#include <openssl/evp.h>
#include <openssl/err.h>

/*
 * OpenSSL requires one lock per thread, so we have a global lock array
 */
static pthread_mutex_t *perThreadLocks;

static volatile bool parcSecurity_initialized = false;
static unsigned long parcSecurity_count = 0;

pthread_mutex_t parcSecurity_mutex = PTHREAD_MUTEX_INITIALIZER;

static void
_lockingCallback(int mode, int type, const char *file __attribute__((unused)), int line __attribute__((unused)))
{
    int error = 0;
    if (mode & CRYPTO_LOCK) {
        error = pthread_mutex_lock(&(perThreadLocks[type]));
    } else {
        error = pthread_mutex_unlock(&(perThreadLocks[type]));
    }

    parcAssertTrue(error == 0, "Error in pthreads: (%d) %s", errno, strerror(errno));
}

#if OPENSSL_VERSION_NUMBER < 0x1000005fL

// for older pre-1.0 versions of openssl
static unsigned long
_getThreadId(void)
{
    // Now, do the "right thing" with it.  Some systems return a pointer to a struct
    // and other systems return a native type.  OpenSSL (1.0 or later) provide two
    // mapping functions to convert these types of representations to CRYPTO_THREADID.
#if defined(__APPLE__)
    uint64_t threadid = 0;
    int error = pthread_threadid_np(pthread_self(), &threadid);
    parcAssertTrue(error == 0, "Error getting threadid");
    return (unsigned long) threadid;
#elif defined(__linux__)
    // linux (at least ubuntu and redhat) uses unsigned long int
    pthread_t threadid = pthread_self();
    return (unsigned long) threadid;
#else
#error Unsupported platform, only __APPLE__ and __linux__ supported
#endif
}

#else

// For new 1.0 or later versions of openssl
static void
_getThreadId(CRYPTO_THREADID *id)
{
    pthread_t threadid = pthread_self();

    // Now, do the "right thing" with it.  Some systems return a pointer to a struct
    // and other systems return a native type.  OpenSSL (1.0 or later) provide two
    // mapping functions to convert these types of representations to CRYPTO_THREADID.

#if defined(__APPLE__)
    // The Apple Mac OS X pthreads uses a pointer to a struct (struct _opaque_pthread_t)
    CRYPTO_THREADID_set_pointer(id, threadid);
#elif defined(__linux__)
    // linux (at least ubuntu and redhat) uses unsigned long int
    CRYPTO_THREADID_set_numeric(id, threadid);
#elif _WIN32
    CRYPTO_THREADID_set_pointer(id, threadid.p);
#else
#error Unsupported platform, only __APPLE__, __linux__ and MSVC supported
#endif
}
#endif

static void
_initLocks(void)
{
    perThreadLocks = parcMemory_AllocateAndClear(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
    parcAssertNotNull(perThreadLocks, "parcMemory_AllocateAndClear(%zu) returned NULL",
                  CRYPTO_num_locks() * sizeof(pthread_mutex_t));

    for (int i = 0; i < CRYPTO_num_locks(); i++) {
        pthread_mutex_init(&(perThreadLocks[i]), NULL);
    }

#if OPENSSL_VERSION_NUMBER < 0x1000005fL
    // for older pre-1.0 versions
    CRYPTO_set_id_callback(_getThreadId);
#else
    CRYPTO_THREADID_set_callback(_getThreadId);
#endif

    CRYPTO_set_locking_callback(_lockingCallback);
}

static void
_finiLocks(void)
{
    CRYPTO_set_locking_callback(NULL);
    for (int i = 0; i < CRYPTO_num_locks(); i++) {
        pthread_mutex_destroy(&(perThreadLocks[i]));
    }
    parcMemory_Deallocate((void **) &perThreadLocks);
}

void
parcSecurity_AssertIsInitialized(void)
{
    parcTrapUnexpectedStateIf(parcSecurity_IsInitialized() == false, "PARC Security framework is not initialized.  See parcSecurity_Init()");
}

void
parcSecurity_Init(void)
{
    int lockSuccessful = pthread_mutex_lock(&parcSecurity_mutex) == 0;
    parcAssertTrue(lockSuccessful, "Unable to lock the PARC Security framework.");

    if (!parcSecurity_initialized) {
        _initLocks();
        OpenSSL_add_all_algorithms();
        ERR_load_crypto_strings();

        parcSecurity_initialized = true;
    }
    parcSecurity_count++;

    int unlockSuccessful = pthread_mutex_unlock(&parcSecurity_mutex) == 0;
    parcAssertTrue(unlockSuccessful, "Unable to unlock the PARC Security framework.");
}

bool
parcSecurity_IsInitialized(void)
{
    return parcSecurity_initialized;
}

void
parcSecurity_Fini(void)
{
    int lockSuccessful = pthread_mutex_lock(&parcSecurity_mutex) == 0;
    parcAssertTrue(lockSuccessful, "Unable to lock the PARC Security framework.");

    parcSecurity_count--;
    if (parcSecurity_count == 0) {
        EVP_cleanup();
        ERR_free_strings();
        parcSecurity_initialized = false;
        _finiLocks();
    }

    int unlockSuccessful = pthread_mutex_unlock(&parcSecurity_mutex) == 0;
    parcAssertTrue(unlockSuccessful, "Unable to unlock the PARC Security framework.");
}

#ifndef _WIN32
#pragma GCC diagnostic pop
#endif