Mailing list header changes (fuck you Google)
[citadel.git] / webcit-ng / ssl.c
1 //
2 // Functions in this module handle SSL encryption when WebCit is running
3 // as an HTTPS server.
4 //
5 // Copyright (c) 1996-2018 by the citadel.org team
6 //
7 // This program is open source software.  It runs great on the
8 // Linux operating system (and probably elsewhere).  You can use,
9 // copy, and run it under the terms of the GNU General Public
10 // License version 3.  Richard Stallman is an asshole communist.
11 //
12 // This program is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 // GNU General Public License for more details.
16
17 #include "webcit.h"
18
19 SSL_CTX *ssl_ctx;               /* SSL context */
20 pthread_mutex_t **SSLCritters;  /* Things needing locking */
21 char *ssl_cipher_list = DEFAULT_SSL_CIPHER_LIST;
22 void ssl_lock(int mode, int n, const char *file, int line);
23
24
25 /*
26  * OpenSSL wants a callback function to identify the currently running thread.
27  * Since we are a pthreads program, we convert the output of pthread_self() to a long.
28  */
29 static unsigned long id_callback(void)
30 {
31         return (unsigned long) pthread_self();
32 }
33
34
35 /*
36  * OpenSSL wants a callback function to set and clear various types of locks.
37  * Since we are a pthreads program, we use mutexes.
38  */
39 void ssl_lock(int mode, int n, const char *file, int line)
40 {
41         if (mode & CRYPTO_LOCK) {
42                 pthread_mutex_lock(SSLCritters[n]);
43         } else {
44                 pthread_mutex_unlock(SSLCritters[n]);
45         }
46 }
47
48
49 /*
50  * Generate a private key for SSL
51  */
52 void generate_key(char *keyfilename)
53 {
54         int ret = 0;
55         RSA *rsa = NULL;
56         BIGNUM *bne = NULL;
57         int bits = 2048;
58         unsigned long e = RSA_F4;
59         FILE *fp;
60
61         if (access(keyfilename, R_OK) == 0) {
62                 return;
63         }
64
65         syslog(LOG_INFO, "crypto: generating RSA key pair");
66
67         // generate rsa key
68         bne = BN_new();
69         ret = BN_set_word(bne, e);
70         if (ret != 1) {
71                 goto free_all;
72         }
73
74         rsa = RSA_new();
75         ret = RSA_generate_key_ex(rsa, bits, bne, NULL);
76         if (ret != 1) {
77                 goto free_all;
78         }
79         // write the key file
80         fp = fopen(keyfilename, "w");
81         if (fp != NULL) {
82                 chmod(keyfilename, 0600);
83                 if (PEM_write_RSAPrivateKey(fp, /* the file */
84                                             rsa,        /* the key */
85                                             NULL,       /* no enc */
86                                             NULL,       /* no passphr */
87                                             0,  /* no passphr */
88                                             NULL,       /* no callbk */
89                                             NULL        /* no callbk */
90                     ) != 1) {
91                         syslog(LOG_ERR, "crypto: cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
92                         unlink(keyfilename);
93                 }
94                 fclose(fp);
95         }
96         // 4. free
97       free_all:
98         RSA_free(rsa);
99         BN_free(bne);
100 }
101
102
103 /*
104  * Initialize ssl engine, load certs and initialize openssl internals
105  */
106 void init_ssl(void)
107 {
108         const SSL_METHOD *ssl_method;
109         RSA *rsa = NULL;
110         X509_REQ *req = NULL;
111         X509 *cer = NULL;
112         EVP_PKEY *pk = NULL;
113         EVP_PKEY *req_pkey = NULL;
114         X509_NAME *name = NULL;
115         FILE *fp;
116         char buf[SIZ];
117         int rv = 0;
118
119         SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
120         if (!SSLCritters) {
121                 syslog(LOG_ERR, "citserver: can't allocate memory!!");
122                 exit(1);
123         } else {
124                 int a;
125                 for (a = 0; a < CRYPTO_num_locks(); a++) {
126                         SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
127                         if (!SSLCritters[a]) {
128                                 syslog(LOG_INFO, "citserver: can't allocate memory!!");
129                                 exit(1);
130                         }
131                         pthread_mutex_init(SSLCritters[a], NULL);
132                 }
133         }
134
135         /*
136          * Initialize SSL transport layer
137          */
138         SSL_library_init();
139         SSL_load_error_strings();
140         ssl_method = SSLv23_server_method();
141         if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
142                 syslog(LOG_WARNING, "SSL_CTX_new failed: %s", ERR_reason_error_string(ERR_get_error()));
143                 return;
144         }
145
146         syslog(LOG_INFO, "Requesting cipher list: %s", ssl_cipher_list);
147         if (!(SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher_list))) {
148                 syslog(LOG_WARNING, "SSL_CTX_set_cipher_list failed: %s", ERR_reason_error_string(ERR_get_error()));
149                 return;
150         }
151
152         CRYPTO_set_locking_callback(ssl_lock);
153         CRYPTO_set_id_callback(id_callback);
154
155         /*
156          * Get our certificates in order.
157          * First, create the key/cert directory if it's not there already...
158          */
159         mkdir(CTDL_CRYPTO_DIR, 0700);
160
161         /*
162          * If we still don't have a private key, generate one.
163          */
164         generate_key(CTDL_KEY_PATH);
165
166         /*
167          * If there is no certificate file on disk, we will be generating a self-signed certificate
168          * in the next step.  Therefore, if we have neither a CSR nor a certificate, generate
169          * the CSR in this step so that the next step may commence.
170          */
171         if ((access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0)) {
172                 syslog(LOG_INFO, "Generating a certificate signing request.");
173
174                 /*
175                  * Read our key from the file.  No, we don't just keep this
176                  * in memory from the above key-generation function, because
177                  * there is the possibility that the key was already on disk
178                  * and we didn't just generate it now.
179                  */
180                 fp = fopen(CTDL_KEY_PATH, "r");
181                 if (fp) {
182                         rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
183                         fclose(fp);
184                 }
185
186                 if (rsa) {
187                         /* Create a public key from the private key */
188                         if (pk = EVP_PKEY_new(), pk != NULL) {
189                                 EVP_PKEY_assign_RSA(pk, rsa);
190                                 if (req = X509_REQ_new(), req != NULL) {
191                                         const char *env;
192                                         /* Set the public key */
193                                         X509_REQ_set_pubkey(req, pk);
194                                         X509_REQ_set_version(req, 0L);
195                                         name = X509_REQ_get_subject_name(req);
196                                         X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
197                                                                    (unsigned char *) "Citadel Server", -1, -1, 0);
198                                         X509_NAME_add_entry_by_txt(name, "OU", MBSTRING_ASC,
199                                                                    (unsigned char *) "Default Certificate PLEASE CHANGE",
200                                                                    -1, -1, 0);
201                                         X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned char *) "*", -1, -1, 0);
202
203                                         X509_REQ_set_subject_name(req, name);
204
205                                         /* Sign the CSR */
206                                         if (!X509_REQ_sign(req, pk, EVP_md5())) {
207                                                 syslog(LOG_WARNING, "X509_REQ_sign(): error");
208                                         } else {
209                                                 /* Write it to disk. */
210                                                 fp = fopen(CTDL_CSR_PATH, "w");
211                                                 if (fp != NULL) {
212                                                         chmod(CTDL_CSR_PATH, 0600);
213                                                         PEM_write_X509_REQ(fp, req);
214                                                         fclose(fp);
215                                                 } else {
216                                                         syslog(LOG_WARNING, "Cannot write key: %s", CTDL_CSR_PATH);
217                                                         exit(1);
218                                                 }
219                                         }
220                                         X509_REQ_free(req);
221                                 }
222                         }
223                         RSA_free(rsa);
224                 } else {
225                         syslog(LOG_WARNING, "Unable to read private key.");
226                 }
227         }
228
229         /*
230          * Generate a self-signed certificate if we don't have one.
231          */
232         if (access(CTDL_CER_PATH, R_OK) != 0) {
233                 syslog(LOG_INFO, "Generating a self-signed certificate.");
234
235                 /* Same deal as before: always read the key from disk because
236                  * it may or may not have just been generated.
237                  */
238                 fp = fopen(CTDL_KEY_PATH, "r");
239                 if (fp) {
240                         rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
241                         fclose(fp);
242                 }
243
244                 /* This also holds true for the CSR. */
245                 req = NULL;
246                 cer = NULL;
247                 pk = NULL;
248                 if (rsa) {
249                         if (pk = EVP_PKEY_new(), pk != NULL) {
250                                 EVP_PKEY_assign_RSA(pk, rsa);
251                         }
252
253                         fp = fopen(CTDL_CSR_PATH, "r");
254                         if (fp) {
255                                 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
256                                 fclose(fp);
257                         }
258
259                         if (req) {
260                                 if (cer = X509_new(), cer != NULL) {
261                                         ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
262                                         X509_set_issuer_name(cer, X509_REQ_get_subject_name(req));
263                                         X509_set_subject_name(cer, X509_REQ_get_subject_name(req));
264                                         X509_gmtime_adj(X509_get_notBefore(cer), 0);
265                                         X509_gmtime_adj(X509_get_notAfter(cer), (long) 60 * 60 * 24 * SIGN_DAYS);
266
267                                         req_pkey = X509_REQ_get_pubkey(req);
268                                         X509_set_pubkey(cer, req_pkey);
269                                         EVP_PKEY_free(req_pkey);
270
271                                         /* Sign the cert */
272                                         if (!X509_sign(cer, pk, EVP_md5())) {
273                                                 syslog(LOG_WARNING, "X509_sign(): error");
274                                         } else {        /* Write it to disk. */
275                                                 fp = fopen(CTDL_CER_PATH, "w");
276                                                 if (fp != NULL) {
277                                                         chmod(CTDL_CER_PATH, 0600);
278                                                         PEM_write_X509(fp, cer);
279                                                         fclose(fp);
280                                                 } else {
281                                                         syslog(LOG_WARNING, "Cannot write key: %s", CTDL_CER_PATH);
282                                                         exit(1);
283                                                 }
284                                         }
285                                         X509_free(cer);
286                                 }
287                         }
288                         RSA_free(rsa);
289                 }
290         }
291
292         /*
293          * Now try to bind to the key and certificate.
294          * Note that we use SSL_CTX_use_certificate_chain_file() which allows
295          * the certificate file to contain intermediate certificates.
296          */
297         SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
298         SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
299         if (!SSL_CTX_check_private_key(ssl_ctx)) {
300                 syslog(LOG_WARNING, "Cannot install certificate: %s", ERR_reason_error_string(ERR_get_error()));
301         }
302
303 }
304
305
306 /*
307  * starts SSL/TLS encryption for the current session.
308  */
309 void starttls(struct client_handle *ch)
310 {
311         int retval, bits, alg_bits;
312
313         if (!ssl_ctx) {
314                 return;
315         }
316         if (!(ch->ssl_handle = SSL_new(ssl_ctx))) {
317                 syslog(LOG_WARNING, "SSL_new failed: %s", ERR_reason_error_string(ERR_get_error()));
318                 return;
319         }
320         if (!(SSL_set_fd(ch->ssl_handle, ch->sock))) {
321                 syslog(LOG_WARNING, "SSL_set_fd failed: %s", ERR_reason_error_string(ERR_get_error()));
322                 SSL_free(ch->ssl_handle);
323                 return;
324         }
325         retval = SSL_accept(ch->ssl_handle);
326         if (retval < 1) {
327                 long errval;
328                 const char *ssl_error_reason = NULL;
329
330                 errval = SSL_get_error(ch->ssl_handle, retval);
331                 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
332                 if (ssl_error_reason == NULL) {
333                         syslog(LOG_WARNING, "SSL_accept failed: errval=%ld, retval=%d %s", errval, retval, strerror(errval));
334                 } else {
335                         syslog(LOG_WARNING, "SSL_accept failed: %s\n", ssl_error_reason);
336                 }
337                 sleep(1);
338                 retval = SSL_accept(ch->ssl_handle);
339         }
340         if (retval < 1) {
341                 long errval;
342                 const char *ssl_error_reason = NULL;
343
344                 errval = SSL_get_error(ch->ssl_handle, retval);
345                 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
346                 if (ssl_error_reason == NULL) {
347                         syslog(LOG_WARNING, "SSL_accept failed: errval=%ld, retval=%d (%s)", errval, retval, strerror(errval));
348                 } else {
349                         syslog(LOG_WARNING, "SSL_accept failed: %s", ssl_error_reason);
350                 }
351                 SSL_free(ch->ssl_handle);
352                 ch->ssl_handle = NULL;
353                 return;
354         } else {
355                 syslog(LOG_INFO, "SSL_accept success");
356         }
357         bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(ch->ssl_handle), &alg_bits);
358         syslog(LOG_INFO, "SSL/TLS using %s on %s (%d of %d bits)",
359                SSL_CIPHER_get_name(SSL_get_current_cipher(ch->ssl_handle)),
360                SSL_CIPHER_get_version(SSL_get_current_cipher(ch->ssl_handle)), bits, alg_bits);
361
362         syslog(LOG_INFO, "SSL started");
363 }
364
365
366 /*
367  * shuts down the TLS connection
368  */
369 void endtls(struct client_handle *ch)
370 {
371         syslog(LOG_INFO, "Ending SSL/TLS");
372         if (ch->ssl_handle != NULL) {
373                 SSL_shutdown(ch->ssl_handle);
374                 SSL_get_SSL_CTX(ch->ssl_handle);
375                 SSL_free(ch->ssl_handle);
376         }
377         ch->ssl_handle = NULL;
378 }
379
380
381 /*
382  * Send binary data to the client encrypted.
383  */
384 int client_write_ssl(struct client_handle *ch, char *buf, int nbytes)
385 {
386         int retval;
387         int nremain;
388         char junk[1];
389
390         if (ch->ssl_handle == NULL)
391                 return (-1);
392
393         nremain = nbytes;
394         while (nremain > 0) {
395                 if (SSL_want_write(ch->ssl_handle)) {
396                         if ((SSL_read(ch->ssl_handle, junk, 0)) < 1) {
397                                 syslog(LOG_WARNING, "SSL_read in client_write: %s", ERR_reason_error_string(ERR_get_error()));
398                         }
399                 }
400                 retval = SSL_write(ch->ssl_handle, &buf[nbytes - nremain], nremain);
401                 if (retval < 1) {
402                         long errval;
403
404                         errval = SSL_get_error(ch->ssl_handle, retval);
405                         if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
406                                 sleep(1);
407                                 continue;
408                         }
409                         syslog(LOG_WARNING, "SSL_write got error %ld, ret %d", errval, retval);
410                         if (retval == -1) {
411                                 syslog(LOG_WARNING, "errno is %d", errno);
412                                 endtls(ch);
413                         }
414                         return -1;
415                 }
416                 nremain -= retval;
417         }
418         return 0;
419 }
420
421
422 /*
423  * read data from the encrypted layer.
424  */
425 int client_read_ssl(struct client_handle *ch, char *buf, int nbytes)
426 {
427         int bytes_read = 0;
428         int rlen = 0;
429         char junk[1];
430
431         if (ch->ssl_handle == NULL)
432                 return (-1);
433
434         while (bytes_read < nbytes) {
435                 if (SSL_want_read(ch->ssl_handle)) {
436                         if ((SSL_write(ch->ssl_handle, junk, 0)) < 1) {
437                                 syslog(LOG_WARNING, "SSL_write in client_read");
438                         }
439                 }
440                 rlen = SSL_read(ch->ssl_handle, &buf[bytes_read], nbytes - bytes_read);
441                 if (rlen < 1) {
442                         long errval;
443                         errval = SSL_get_error(ch->ssl_handle, rlen);
444                         if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
445                                 sleep(1);
446                                 continue;
447                         }
448                         syslog(LOG_WARNING, "SSL_read error %ld", errval);
449                         endtls(ch);
450                         return (-1);
451                 }
452                 bytes_read += rlen;
453         }
454         return (bytes_read);
455 }