1 /*
2 ** SQLCipher
3 ** http://sqlcipher.net
4 **
5 ** Copyright (c) 2008 - 2013, ZETETIC LLC
6 ** All rights reserved.
7 **
8 ** Redistribution and use in source and binary forms, with or without
9 ** modification, are permitted provided that the following conditions are met:
10 **     * Redistributions of source code must retain the above copyright
11 **       notice, this list of conditions and the following disclaimer.
12 **     * Redistributions in binary form must reproduce the above copyright
13 **       notice, this list of conditions and the following disclaimer in the
14 **       documentation and/or other materials provided with the distribution.
15 **     * Neither the name of the ZETETIC LLC nor the
16 **       names of its contributors may be used to endorse or promote products
17 **       derived from this software without specific prior written permission.
18 **
19 ** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
20 ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 ** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
23 ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26 ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 **
30 */
31 /* BEGIN SQLCIPHER */
32 #ifdef SQLITE_HAS_CODEC
33 #ifdef SQLCIPHER_CRYPTO_OPENSSL
34 #include "sqliteInt.h"
35 #include "crypto.h"
36 #include "sqlcipher.h"
37 #include <openssl/rand.h>
38 #include <openssl/evp.h>
39 #include <openssl/hmac.h>
40 #include <openssl/err.h>
41 
42 typedef struct {
43   EVP_CIPHER *evp_cipher;
44 } openssl_ctx;
45 
46 static unsigned int openssl_external_init = 0;
47 static unsigned int openssl_init_count = 0;
48 static sqlite3_mutex* openssl_rand_mutex = NULL;
49 
50 #if OPENSSL_VERSION_NUMBER < 0x10100000L || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000)
HMAC_CTX_new(void)51 static HMAC_CTX *HMAC_CTX_new(void)
52 {
53   HMAC_CTX *ctx = OPENSSL_malloc(sizeof(*ctx));
54   if (ctx != NULL) {
55     HMAC_CTX_init(ctx);
56   }
57   return ctx;
58 }
59 
60 // Per 1.1.0 (https://wiki.openssl.org/index.php/1.1_API_Changes)
61 // HMAC_CTX_free should call HMAC_CTX_cleanup, then EVP_MD_CTX_Cleanup.
62 // HMAC_CTX_cleanup internally calls EVP_MD_CTX_cleanup so these
63 // calls are not needed.
HMAC_CTX_free(HMAC_CTX * ctx)64 static void HMAC_CTX_free(HMAC_CTX *ctx)
65 {
66   if (ctx != NULL) {
67     HMAC_CTX_cleanup(ctx);
68     OPENSSL_free(ctx);
69   }
70 }
71 #endif
72 
sqlcipher_openssl_add_random(void * ctx,void * buffer,int length)73 static int sqlcipher_openssl_add_random(void *ctx, void *buffer, int length) {
74 #ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND
75   CODEC_TRACE_MUTEX("sqlcipher_openssl_add_random: entering openssl_rand_mutex %p\n", openssl_rand_mutex);
76   sqlite3_mutex_enter(openssl_rand_mutex);
77   CODEC_TRACE_MUTEX("sqlcipher_openssl_add_random: entered openssl_rand_mutex %p\n", openssl_rand_mutex);
78 #endif
79   RAND_add(buffer, length, 0);
80 #ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND
81   CODEC_TRACE_MUTEX("sqlcipher_openssl_add_random: leaving openssl_rand_mutex %p\n", openssl_rand_mutex);
82   sqlite3_mutex_leave(openssl_rand_mutex);
83   CODEC_TRACE_MUTEX("sqlcipher_openssl_add_random: left openssl_rand_mutex %p\n", openssl_rand_mutex);
84 #endif
85   return SQLITE_OK;
86 }
87 
88 /* activate and initialize sqlcipher. Most importantly, this will automatically
89    intialize OpenSSL's EVP system if it hasn't already be externally. Note that
90    this function may be called multiple times as new codecs are intiialized.
91    Thus it performs some basic counting to ensure that only the last and final
92    sqlcipher_openssl_deactivate() will free the EVP structures.
93 */
sqlcipher_openssl_activate(void * ctx)94 static int sqlcipher_openssl_activate(void *ctx) {
95   /* initialize openssl and increment the internal init counter
96      but only if it hasn't been initalized outside of SQLCipher by this program
97      e.g. on startup */
98   CODEC_TRACE_MUTEX("sqlcipher_openssl_activate: entering static master mutex");
99   sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
100   CODEC_TRACE_MUTEX("sqlcipher_openssl_activate: entered static master mutex");
101 
102   if(openssl_init_count == 0 && EVP_get_cipherbyname(CIPHER) != NULL) {
103     /* if openssl has not yet been initialized by this library, but
104        a call to get_cipherbyname works, then the openssl library
105        has been initialized externally already. */
106     openssl_external_init = 1;
107   }
108 
109 #ifdef SQLCIPHER_FIPS
110   if(!FIPS_mode()){
111     if(!FIPS_mode_set(1)){
112       ERR_load_crypto_strings();
113       ERR_print_errors_fp(stderr);
114     }
115   }
116 #endif
117 
118   if(openssl_init_count == 0 && openssl_external_init == 0)  {
119     /* if the library was not externally initialized, then should be now */
120 #if OPENSSL_VERSION_NUMBER < 0x10100000L || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000)
121     OpenSSL_add_all_algorithms();
122 #endif
123   }
124 
125 #ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND
126   if(openssl_rand_mutex == NULL) {
127     /* allocate a mutex to guard against concurrent calls to RAND_bytes() */
128     CODEC_TRACE_MUTEX("sqlcipher_openssl_activate: allocating openssl_rand_mutex");
129     openssl_rand_mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
130     CODEC_TRACE_MUTEX("sqlcipher_openssl_activate: allocated openssl_rand_mutex %p", openssl_rand_mutex);
131   }
132 #endif
133 
134   openssl_init_count++;
135   CODEC_TRACE_MUTEX("sqlcipher_openssl_activate: leaving static master mutex");
136   sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
137   CODEC_TRACE_MUTEX("sqlcipher_openssl_activate: left static master mutex");
138   return SQLITE_OK;
139 }
140 
141 /* deactivate SQLCipher, most imporantly decremeting the activation count and
142    freeing the EVP structures on the final deactivation to ensure that
143    OpenSSL memory is cleaned up */
sqlcipher_openssl_deactivate(void * ctx)144 static int sqlcipher_openssl_deactivate(void *ctx) {
145   CODEC_TRACE_MUTEX("sqlcipher_openssl_deactivate: entering static master mutex");
146   sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
147   CODEC_TRACE_MUTEX("sqlcipher_openssl_deactivate: entered static master mutex");
148   openssl_init_count--;
149 
150   if(openssl_init_count == 0) {
151     if(openssl_external_init == 0) {
152     /* if OpenSSL hasn't be initialized externally, and the counter reaches zero
153        after it's decremented, release EVP memory
154        Note: this code will only be reached if OpensSSL_add_all_algorithms()
155        is called by SQLCipher internally. This should prevent SQLCipher from
156        "cleaning up" openssl when it was initialized externally by the program */
157 #if OPENSSL_VERSION_NUMBER < 0x10100000L || (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000)
158       EVP_cleanup();
159 #endif
160     } else {
161       openssl_external_init = 0;
162     }
163 #ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND
164     CODEC_TRACE_MUTEX("sqlcipher_openssl_deactivate: freeing openssl_rand_mutex %p", openssl_rand_mutex);
165     sqlite3_mutex_free(openssl_rand_mutex);
166     CODEC_TRACE_MUTEX("sqlcipher_openssl_deactivate: freed openssl_rand_mutex %p", openssl_rand_mutex);
167     openssl_rand_mutex = NULL;
168 #endif
169   }
170   CODEC_TRACE_MUTEX("sqlcipher_openssl_deactivate: leaving static master mutex");
171   sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
172   CODEC_TRACE_MUTEX("sqlcipher_openssl_deactivate: left static master mutex");
173   return SQLITE_OK;
174 }
175 
sqlcipher_openssl_get_provider_name(void * ctx)176 static const char* sqlcipher_openssl_get_provider_name(void *ctx) {
177   return "openssl";
178 }
179 
sqlcipher_openssl_get_provider_version(void * ctx)180 static const char* sqlcipher_openssl_get_provider_version(void *ctx) {
181   return OPENSSL_VERSION_TEXT;
182 }
183 
184 /* generate a defined number of random bytes */
sqlcipher_openssl_random(void * ctx,void * buffer,int length)185 static int sqlcipher_openssl_random (void *ctx, void *buffer, int length) {
186   int rc = 0;
187   /* concurrent calls to RAND_bytes can cause a crash under some openssl versions when a
188      naive application doesn't use CRYPTO_set_locking_callback and
189      CRYPTO_THREADID_set_callback to ensure openssl thread safety.
190      This is simple workaround to prevent this common crash
191      but a more proper solution is that applications setup platform-appropriate
192      thread saftey in openssl externally */
193 #ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND
194   CODEC_TRACE_MUTEX("sqlcipher_openssl_random: entering openssl_rand_mutex %p", openssl_rand_mutex);
195   sqlite3_mutex_enter(openssl_rand_mutex);
196   CODEC_TRACE_MUTEX("sqlcipher_openssl_random: entered openssl_rand_mutex %p", openssl_rand_mutex);
197 #endif
198   rc = RAND_bytes((unsigned char *)buffer, length);
199 #ifndef SQLCIPHER_OPENSSL_NO_MUTEX_RAND
200   CODEC_TRACE_MUTEX("sqlcipher_openssl_random: leaving openssl_rand_mutex %p", openssl_rand_mutex);
201   sqlite3_mutex_leave(openssl_rand_mutex);
202   CODEC_TRACE_MUTEX("sqlcipher_openssl_random: left openssl_rand_mutex %p", openssl_rand_mutex);
203 #endif
204   return (rc == 1) ? SQLITE_OK : SQLITE_ERROR;
205 }
206 
sqlcipher_openssl_hmac(void * ctx,unsigned char * hmac_key,int key_sz,unsigned char * in,int in_sz,unsigned char * in2,int in2_sz,unsigned char * out)207 static int sqlcipher_openssl_hmac(void *ctx, unsigned char *hmac_key, int key_sz, unsigned char *in, int in_sz, unsigned char *in2, int in2_sz, unsigned char *out) {
208   unsigned int outlen;
209   HMAC_CTX* hctx = HMAC_CTX_new();
210   if(hctx == NULL || in == NULL) return SQLITE_ERROR;
211   HMAC_Init_ex(hctx, hmac_key, key_sz, EVP_sha1(), NULL);
212   HMAC_Update(hctx, in, in_sz);
213   if(in2 != NULL) HMAC_Update(hctx, in2, in2_sz);
214   HMAC_Final(hctx, out, &outlen);
215   HMAC_CTX_free(hctx);
216   return SQLITE_OK;
217 }
218 
sqlcipher_openssl_kdf(void * ctx,const unsigned char * pass,int pass_sz,unsigned char * salt,int salt_sz,int workfactor,int key_sz,unsigned char * key)219 static int sqlcipher_openssl_kdf(void *ctx, const unsigned char *pass, int pass_sz, unsigned char* salt, int salt_sz, int workfactor, int key_sz, unsigned char *key) {
220   PKCS5_PBKDF2_HMAC_SHA1((const char *)pass, pass_sz, salt, salt_sz, workfactor, key_sz, key);
221   return SQLITE_OK;
222 }
223 
sqlcipher_openssl_cipher(void * ctx,int mode,unsigned char * key,int key_sz,unsigned char * iv,unsigned char * in,int in_sz,unsigned char * out)224 static int sqlcipher_openssl_cipher(void *ctx, int mode, unsigned char *key, int key_sz, unsigned char *iv, unsigned char *in, int in_sz, unsigned char *out) {
225   int tmp_csz, csz;
226   EVP_CIPHER_CTX* ectx = EVP_CIPHER_CTX_new();
227   if(ectx == NULL) return SQLITE_ERROR;
228   EVP_CipherInit_ex(ectx, ((openssl_ctx *)ctx)->evp_cipher, NULL, NULL, NULL, mode);
229   EVP_CIPHER_CTX_set_padding(ectx, 0); // no padding
230   EVP_CipherInit_ex(ectx, NULL, NULL, key, iv, mode);
231   EVP_CipherUpdate(ectx, out, &tmp_csz, in, in_sz);
232   csz = tmp_csz;
233   out += tmp_csz;
234   EVP_CipherFinal_ex(ectx, out, &tmp_csz);
235   csz += tmp_csz;
236   EVP_CIPHER_CTX_free(ectx);
237   assert(in_sz == csz);
238   return SQLITE_OK;
239 }
240 
sqlcipher_openssl_set_cipher(void * ctx,const char * cipher_name)241 static int sqlcipher_openssl_set_cipher(void *ctx, const char *cipher_name) {
242   openssl_ctx *o_ctx = (openssl_ctx *)ctx;
243   EVP_CIPHER* cipher = (EVP_CIPHER *) EVP_get_cipherbyname(cipher_name);
244   if(cipher != NULL) {
245     o_ctx->evp_cipher = cipher;
246   }
247   return cipher != NULL ? SQLITE_OK : SQLITE_ERROR;
248 }
249 
sqlcipher_openssl_get_cipher(void * ctx)250 static const char* sqlcipher_openssl_get_cipher(void *ctx) {
251   return EVP_CIPHER_name(((openssl_ctx *)ctx)->evp_cipher);
252 }
253 
sqlcipher_openssl_get_key_sz(void * ctx)254 static int sqlcipher_openssl_get_key_sz(void *ctx) {
255   return EVP_CIPHER_key_length(((openssl_ctx *)ctx)->evp_cipher);
256 }
257 
sqlcipher_openssl_get_iv_sz(void * ctx)258 static int sqlcipher_openssl_get_iv_sz(void *ctx) {
259   return EVP_CIPHER_iv_length(((openssl_ctx *)ctx)->evp_cipher);
260 }
261 
sqlcipher_openssl_get_block_sz(void * ctx)262 static int sqlcipher_openssl_get_block_sz(void *ctx) {
263   return EVP_CIPHER_block_size(((openssl_ctx *)ctx)->evp_cipher);
264 }
265 
sqlcipher_openssl_get_hmac_sz(void * ctx)266 static int sqlcipher_openssl_get_hmac_sz(void *ctx) {
267   return EVP_MD_size(EVP_sha1());
268 }
269 
sqlcipher_openssl_ctx_copy(void * target_ctx,void * source_ctx)270 static int sqlcipher_openssl_ctx_copy(void *target_ctx, void *source_ctx) {
271   memcpy(target_ctx, source_ctx, sizeof(openssl_ctx));
272   return SQLITE_OK;
273 }
274 
sqlcipher_openssl_ctx_cmp(void * c1,void * c2)275 static int sqlcipher_openssl_ctx_cmp(void *c1, void *c2) {
276   return ((openssl_ctx *)c1)->evp_cipher == ((openssl_ctx *)c2)->evp_cipher;
277 }
278 
sqlcipher_openssl_ctx_init(void ** ctx)279 static int sqlcipher_openssl_ctx_init(void **ctx) {
280   *ctx = sqlcipher_malloc(sizeof(openssl_ctx));
281   if(*ctx == NULL) return SQLITE_NOMEM;
282   sqlcipher_openssl_activate(*ctx);
283   return SQLITE_OK;
284 }
285 
sqlcipher_openssl_ctx_free(void ** ctx)286 static int sqlcipher_openssl_ctx_free(void **ctx) {
287   sqlcipher_openssl_deactivate(*ctx);
288   sqlcipher_free(*ctx, sizeof(openssl_ctx));
289   return SQLITE_OK;
290 }
291 
sqlcipher_openssl_fips_status(void * ctx)292 static int sqlcipher_openssl_fips_status(void *ctx) {
293 #ifdef SQLCIPHER_FIPS
294   return FIPS_mode();
295 #else
296   return 0;
297 #endif
298 }
299 
sqlcipher_openssl_setup(sqlcipher_provider * p)300 int sqlcipher_openssl_setup(sqlcipher_provider *p) {
301   p->activate = sqlcipher_openssl_activate;
302   p->deactivate = sqlcipher_openssl_deactivate;
303   p->get_provider_name = sqlcipher_openssl_get_provider_name;
304   p->random = sqlcipher_openssl_random;
305   p->hmac = sqlcipher_openssl_hmac;
306   p->kdf = sqlcipher_openssl_kdf;
307   p->cipher = sqlcipher_openssl_cipher;
308   p->set_cipher = sqlcipher_openssl_set_cipher;
309   p->get_cipher = sqlcipher_openssl_get_cipher;
310   p->get_key_sz = sqlcipher_openssl_get_key_sz;
311   p->get_iv_sz = sqlcipher_openssl_get_iv_sz;
312   p->get_block_sz = sqlcipher_openssl_get_block_sz;
313   p->get_hmac_sz = sqlcipher_openssl_get_hmac_sz;
314   p->ctx_copy = sqlcipher_openssl_ctx_copy;
315   p->ctx_cmp = sqlcipher_openssl_ctx_cmp;
316   p->ctx_init = sqlcipher_openssl_ctx_init;
317   p->ctx_free = sqlcipher_openssl_ctx_free;
318   p->add_random = sqlcipher_openssl_add_random;
319   p->fips_status = sqlcipher_openssl_fips_status;
320   p->get_provider_version = sqlcipher_openssl_get_provider_version;
321   return SQLITE_OK;
322 }
323 
324 #endif
325 #endif
326 /* END SQLCIPHER */
327