]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/tls-gnutls.c
e29dd3186085f6835a377ae3d9c268c490961044
[thirdparty/cups.git] / cups / tls-gnutls.c
1 /*
2 * "$Id$"
3 *
4 * TLS support code for CUPS using GNU TLS.
5 *
6 * Copyright 2007-2015 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
8 *
9 * These coded instructions, statements, and computer programs are the
10 * property of Apple Inc. and are protected by Federal copyright
11 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
12 * which should have been included with this file. If this file is
13 * file is missing or damaged, see the license at "http://www.cups.org/".
14 *
15 * This file is subject to the Apple OS-Developed Software exception.
16 */
17
18 /**** This file is included from tls.c ****/
19
20 /*
21 * Include necessary headers...
22 */
23
24 #include <sys/stat.h>
25
26
27 /*
28 * Local globals...
29 */
30
31 static int tls_auto_create = 0;
32 /* Auto-create self-signed certs? */
33 static char *tls_common_name = NULL;
34 /* Default common name */
35 static char *tls_keypath = NULL;
36 /* Server cert keychain path */
37 static _cups_mutex_t tls_mutex = _CUPS_MUTEX_INITIALIZER;
38 /* Mutex for keychain/certs */
39 static int tls_options = -1;/* Options for TLS connections */
40
41
42 /*
43 * Local functions...
44 */
45
46 static gnutls_x509_crt_t http_gnutls_create_credential(http_credential_t *credential);
47 static const char *http_gnutls_default_path(char *buffer, size_t bufsize);
48 static const char *http_gnutls_make_path(char *buffer, size_t bufsize, const char *dirname, const char *filename, const char *ext);
49 static ssize_t http_gnutls_read(gnutls_transport_ptr_t ptr, void *data, size_t length);
50 static ssize_t http_gnutls_write(gnutls_transport_ptr_t ptr, const void *data, size_t length);
51
52
53 /*
54 * 'cupsMakeServerCredentials()' - Make a self-signed certificate and private key pair.
55 *
56 * @since CUPS 2.0/OS 10.10@
57 */
58
59 int /* O - 1 on success, 0 on failure */
60 cupsMakeServerCredentials(
61 const char *path, /* I - Path to keychain/directory */
62 const char *common_name, /* I - Common name */
63 int num_alt_names, /* I - Number of subject alternate names */
64 const char **alt_names, /* I - Subject Alternate Names */
65 time_t expiration_date) /* I - Expiration date */
66 {
67 gnutls_x509_crt_t crt; /* Self-signed certificate */
68 gnutls_x509_privkey_t key; /* Encryption private key */
69 char temp[1024], /* Temporary directory name */
70 crtfile[1024], /* Certificate filename */
71 keyfile[1024]; /* Private key filename */
72 cups_lang_t *language; /* Default language info */
73 cups_file_t *fp; /* Key/cert file */
74 unsigned char buffer[8192]; /* Buffer for x509 data */
75 size_t bytes; /* Number of bytes of data */
76 unsigned char serial[4]; /* Serial number buffer */
77 time_t curtime; /* Current time */
78 int result; /* Result of GNU TLS calls */
79
80
81 DEBUG_printf(("cupsMakeServerCredentials(path=\"%s\", common_name=\"%s\", num_alt_names=%d, alt_names=%p, expiration_date=%d)", path, common_name, num_alt_names, alt_names, (int)expiration_date));
82
83 /*
84 * Filenames...
85 */
86
87 if (!path)
88 path = http_gnutls_default_path(temp, sizeof(temp));
89
90 if (!path || !common_name)
91 {
92 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
93 return (0);
94 }
95
96 http_gnutls_make_path(crtfile, sizeof(crtfile), path, common_name, "crt");
97 http_gnutls_make_path(keyfile, sizeof(keyfile), path, common_name, "key");
98
99 /*
100 * Create the encryption key...
101 */
102
103 DEBUG_puts("1cupsMakeServerCredentials: Creating key pair.");
104
105 gnutls_x509_privkey_init(&key);
106 gnutls_x509_privkey_generate(key, GNUTLS_PK_RSA, 2048, 0);
107
108 DEBUG_puts("1cupsMakeServerCredentials: Key pair created.");
109
110 /*
111 * Save it...
112 */
113
114 bytes = sizeof(buffer);
115
116 if ((result = gnutls_x509_privkey_export(key, GNUTLS_X509_FMT_PEM, buffer, &bytes)) < 0)
117 {
118 DEBUG_printf(("1cupsMakeServerCredentials: Unable to export private key: %s", gnutls_strerror(result)));
119 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, gnutls_strerror(result), 0);
120 gnutls_x509_privkey_deinit(key);
121 return (0);
122 }
123 else if ((fp = cupsFileOpen(keyfile, "w")) != NULL)
124 {
125 DEBUG_printf(("1cupsMakeServerCredentials: Writing private key to \"%s\".", keyfile));
126 cupsFileWrite(fp, (char *)buffer, bytes);
127 cupsFileClose(fp);
128 }
129 else
130 {
131 DEBUG_printf(("1cupsMakeServerCredentials: Unable to create private key file \"%s\": %s", keyfile, strerror(errno)));
132 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
133 gnutls_x509_privkey_deinit(key);
134 return (0);
135 }
136
137 /*
138 * Create the self-signed certificate...
139 */
140
141 DEBUG_puts("1cupsMakeServerCredentials: Generating self-signed X.509 certificate.");
142
143 language = cupsLangDefault();
144 curtime = time(NULL);
145 serial[0] = curtime >> 24;
146 serial[1] = curtime >> 16;
147 serial[2] = curtime >> 8;
148 serial[3] = curtime;
149
150 gnutls_x509_crt_init(&crt);
151 if (strlen(language->language) == 5)
152 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
153 language->language + 3, 2);
154 else
155 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COUNTRY_NAME, 0,
156 "US", 2);
157 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_COMMON_NAME, 0,
158 common_name, strlen(common_name));
159 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATION_NAME, 0,
160 common_name, strlen(common_name));
161 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME,
162 0, "Unknown", 7);
163 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME, 0,
164 "Unknown", 7);
165 gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_X520_LOCALITY_NAME, 0,
166 "Unknown", 7);
167 /* gnutls_x509_crt_set_dn_by_oid(crt, GNUTLS_OID_PKCS9_EMAIL, 0,
168 ServerAdmin, strlen(ServerAdmin));*/
169 gnutls_x509_crt_set_key(crt, key);
170 gnutls_x509_crt_set_serial(crt, serial, sizeof(serial));
171 gnutls_x509_crt_set_activation_time(crt, curtime);
172 gnutls_x509_crt_set_expiration_time(crt, curtime + 10 * 365 * 86400);
173 gnutls_x509_crt_set_ca_status(crt, 0);
174 if (num_alt_names > 0)
175 gnutls_x509_crt_set_subject_alternative_name(crt, GNUTLS_SAN_DNSNAME, alt_names[0]);
176 gnutls_x509_crt_set_key_purpose_oid(crt, GNUTLS_KP_TLS_WWW_SERVER, 0);
177 gnutls_x509_crt_set_key_usage(crt, GNUTLS_KEY_KEY_ENCIPHERMENT);
178 gnutls_x509_crt_set_version(crt, 3);
179
180 bytes = sizeof(buffer);
181 if (gnutls_x509_crt_get_key_id(crt, 0, buffer, &bytes) >= 0)
182 gnutls_x509_crt_set_subject_key_id(crt, buffer, bytes);
183
184 gnutls_x509_crt_sign(crt, crt, key);
185
186 /*
187 * Save it...
188 */
189
190 bytes = sizeof(buffer);
191 if ((result = gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_PEM, buffer, &bytes)) < 0)
192 {
193 DEBUG_printf(("1cupsMakeServerCredentials: Unable to export public key and X.509 certificate: %s", gnutls_strerror(result)));
194 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, gnutls_strerror(result), 0);
195 gnutls_x509_crt_deinit(crt);
196 gnutls_x509_privkey_deinit(key);
197 return (0);
198 }
199 else if ((fp = cupsFileOpen(crtfile, "w")) != NULL)
200 {
201 DEBUG_printf(("1cupsMakeServerCredentials: Writing public key and X.509 certificate to \"%s\".", crtfile));
202 cupsFileWrite(fp, (char *)buffer, bytes);
203 cupsFileClose(fp);
204 }
205 else
206 {
207 DEBUG_printf(("1cupsMakeServerCredentials: Unable to create public key and X.509 certificate file \"%s\": %s", crtfile, strerror(errno)));
208 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
209 gnutls_x509_crt_deinit(crt);
210 gnutls_x509_privkey_deinit(key);
211 return (0);
212 }
213
214 /*
215 * Cleanup...
216 */
217
218 gnutls_x509_crt_deinit(crt);
219 gnutls_x509_privkey_deinit(key);
220
221 DEBUG_puts("1cupsMakeServerCredentials: Successfully created credentials.");
222
223 return (1);
224 }
225
226
227 /*
228 * 'cupsSetServerCredentials()' - Set the default server credentials.
229 *
230 * Note: The server credentials are used by all threads in the running process.
231 * This function is threadsafe.
232 *
233 * @since CUPS 2.0/OS 10.10@
234 */
235
236 int /* O - 1 on success, 0 on failure */
237 cupsSetServerCredentials(
238 const char *path, /* I - Path to keychain/directory */
239 const char *common_name, /* I - Default common name for server */
240 int auto_create) /* I - 1 = automatically create self-signed certificates */
241 {
242 char temp[1024]; /* Default path buffer */
243
244
245 DEBUG_printf(("cupsSetServerCredentials(path=\"%s\", common_name=\"%s\", auto_create=%d)", path, common_name, auto_create));
246
247 /*
248 * Use defaults as needed...
249 */
250
251 if (!path)
252 path = http_gnutls_default_path(temp, sizeof(temp));
253
254 /*
255 * Range check input...
256 */
257
258 if (!path || !common_name)
259 {
260 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
261 return (0);
262 }
263
264 _cupsMutexLock(&tls_mutex);
265
266 /*
267 * Free old values...
268 */
269
270 if (tls_keypath)
271 _cupsStrFree(tls_keypath);
272
273 if (tls_common_name)
274 _cupsStrFree(tls_common_name);
275
276 /*
277 * Save the new values...
278 */
279
280 tls_keypath = _cupsStrAlloc(path);
281 tls_auto_create = auto_create;
282 tls_common_name = _cupsStrAlloc(common_name);
283
284 _cupsMutexUnlock(&tls_mutex);
285
286 return (1);
287 }
288
289
290 /*
291 * 'httpCopyCredentials()' - Copy the credentials associated with the peer in
292 * an encrypted connection.
293 *
294 * @since CUPS 1.5/OS X 10.7@
295 */
296
297 int /* O - Status of call (0 = success) */
298 httpCopyCredentials(
299 http_t *http, /* I - Connection to server */
300 cups_array_t **credentials) /* O - Array of credentials */
301 {
302 unsigned count; /* Number of certificates */
303 const gnutls_datum_t *certs; /* Certificates */
304
305
306 DEBUG_printf(("httpCopyCredentials(http=%p, credentials=%p)", http, credentials));
307
308 if (credentials)
309 *credentials = NULL;
310
311 if (!http || !http->tls || !credentials)
312 return (-1);
313
314 *credentials = cupsArrayNew(NULL, NULL);
315 certs = gnutls_certificate_get_peers(http->tls, &count);
316
317 DEBUG_printf(("1httpCopyCredentials: certs=%p, count=%u", certs, count));
318
319 if (certs && count)
320 {
321 while (count > 0)
322 {
323 httpAddCredential(*credentials, certs->data, certs->size);
324 certs ++;
325 count --;
326 }
327 }
328
329 return (0);
330 }
331
332
333 /*
334 * '_httpCreateCredentials()' - Create credentials in the internal format.
335 */
336
337 http_tls_credentials_t /* O - Internal credentials */
338 _httpCreateCredentials(
339 cups_array_t *credentials) /* I - Array of credentials */
340 {
341 (void)credentials;
342
343 return (NULL);
344 }
345
346
347 /*
348 * '_httpFreeCredentials()' - Free internal credentials.
349 */
350
351 void
352 _httpFreeCredentials(
353 http_tls_credentials_t credentials) /* I - Internal credentials */
354 {
355 (void)credentials;
356 }
357
358
359 /*
360 * 'httpCredentialsAreValidForName()' - Return whether the credentials are valid for the given name.
361 *
362 * @since CUPS 2.0/OS 10.10@
363 */
364
365 int /* O - 1 if valid, 0 otherwise */
366 httpCredentialsAreValidForName(
367 cups_array_t *credentials, /* I - Credentials */
368 const char *common_name) /* I - Name to check */
369 {
370 gnutls_x509_crt_t cert; /* Certificate */
371 int result = 0; /* Result */
372
373
374 cert = http_gnutls_create_credential((http_credential_t *)cupsArrayFirst(credentials));
375 if (cert)
376 {
377 result = gnutls_x509_crt_check_hostname(cert, common_name) != 0;
378 gnutls_x509_crt_deinit(cert);
379 }
380
381 return (result);
382 }
383
384
385 /*
386 * 'httpCredentialsGetTrust()' - Return the trust of credentials.
387 *
388 * @since CUPS 2.0/OS 10.10@
389 */
390
391 http_trust_t /* O - Level of trust */
392 httpCredentialsGetTrust(
393 cups_array_t *credentials, /* I - Credentials */
394 const char *common_name) /* I - Common name for trust lookup */
395 {
396 http_trust_t trust = HTTP_TRUST_OK;
397 /* Trusted? */
398 gnutls_x509_crt_t cert; /* Certificate */
399 cups_array_t *tcreds = NULL; /* Trusted credentials */
400 _cups_globals_t *cg = _cupsGlobals();
401 /* Per-thread globals */
402
403
404 if (!common_name)
405 return (HTTP_TRUST_UNKNOWN);
406
407 if ((cert = http_gnutls_create_credential((http_credential_t *)cupsArrayFirst(credentials))) == NULL)
408 return (HTTP_TRUST_UNKNOWN);
409
410 if (cg->any_root < 0)
411 _cupsSetDefaults();
412
413 /*
414 * Look this common name up in the default keychains...
415 */
416
417 httpLoadCredentials(NULL, &tcreds, common_name);
418
419 if (tcreds)
420 {
421 char credentials_str[1024], /* String for incoming credentials */
422 tcreds_str[1024]; /* String for saved credentials */
423
424 httpCredentialsString(credentials, credentials_str, sizeof(credentials_str));
425 httpCredentialsString(tcreds, tcreds_str, sizeof(tcreds_str));
426
427 if (strcmp(credentials_str, tcreds_str))
428 {
429 /*
430 * Credentials don't match, let's look at the expiration date of the new
431 * credentials and allow if the new ones have a later expiration...
432 */
433
434 if (httpCredentialsGetExpiration(credentials) <= httpCredentialsGetExpiration(tcreds) ||
435 !httpCredentialsAreValidForName(credentials, common_name))
436 {
437 /*
438 * Either the new credentials are not newly issued, or the common name
439 * does not match the issued certificate...
440 */
441
442 trust = HTTP_TRUST_INVALID;
443 }
444 else if (httpCredentialsGetExpiration(tcreds) < time(NULL))
445 {
446 /*
447 * Save the renewed credentials...
448 */
449
450 trust = HTTP_TRUST_RENEWED;
451
452 httpSaveCredentials(NULL, credentials, common_name);
453 }
454 }
455
456 httpFreeCredentials(tcreds);
457 }
458 else if (cg->validate_certs && !httpCredentialsAreValidForName(credentials, common_name))
459 trust = HTTP_TRUST_INVALID;
460
461 if (trust == HTTP_TRUST_OK && !cg->expired_certs)
462 {
463 time_t curtime; /* Current date/time */
464
465 time(&curtime);
466 if (curtime < gnutls_x509_crt_get_activation_time(cert) ||
467 curtime > gnutls_x509_crt_get_expiration_time(cert))
468 trust = HTTP_TRUST_EXPIRED;
469 }
470
471 if (trust == HTTP_TRUST_OK && !cg->any_root && cupsArrayCount(credentials) == 1)
472 trust = HTTP_TRUST_INVALID;
473
474 gnutls_x509_crt_deinit(cert);
475
476 return (trust);
477 }
478
479
480 /*
481 * 'httpCredentialsGetExpiration()' - Return the expiration date of the credentials.
482 *
483 * @since CUPS 2.0/OS 10.10@
484 */
485
486 time_t /* O - Expiration date of credentials */
487 httpCredentialsGetExpiration(
488 cups_array_t *credentials) /* I - Credentials */
489 {
490 gnutls_x509_crt_t cert; /* Certificate */
491 time_t result = 0; /* Result */
492
493
494 cert = http_gnutls_create_credential((http_credential_t *)cupsArrayFirst(credentials));
495 if (cert)
496 {
497 result = gnutls_x509_crt_get_expiration_time(cert);
498 gnutls_x509_crt_deinit(cert);
499 }
500
501 return (result);
502 }
503
504
505 /*
506 * 'httpCredentialsString()' - Return a string representing the credentials.
507 *
508 * @since CUPS 2.0/OS 10.10@
509 */
510
511 size_t /* O - Total size of credentials string */
512 httpCredentialsString(
513 cups_array_t *credentials, /* I - Credentials */
514 char *buffer, /* I - Buffer or @code NULL@ */
515 size_t bufsize) /* I - Size of buffer */
516 {
517 http_credential_t *first; /* First certificate */
518 gnutls_x509_crt_t cert; /* Certificate */
519
520
521 DEBUG_printf(("httpCredentialsString(credentials=%p, buffer=%p, bufsize=" CUPS_LLFMT ")", credentials, buffer, CUPS_LLCAST bufsize));
522
523 if (!buffer)
524 return (0);
525
526 if (buffer && bufsize > 0)
527 *buffer = '\0';
528
529 if ((first = (http_credential_t *)cupsArrayFirst(credentials)) != NULL &&
530 (cert = http_gnutls_create_credential(first)) != NULL)
531 {
532 char name[256]; /* Common name associated with cert */
533 size_t namelen; /* Length of name */
534 time_t expiration; /* Expiration date of cert */
535 _cups_md5_state_t md5_state; /* MD5 state */
536 unsigned char md5_digest[16]; /* MD5 result */
537
538 namelen = sizeof(name) - 1;
539 if (gnutls_x509_crt_get_dn_by_oid(cert, GNUTLS_OID_X520_COMMON_NAME, 0, 0, name, &namelen) >= 0)
540 name[namelen] = '\0';
541 else
542 strlcpy(name, "unknown", sizeof(name));
543
544 expiration = gnutls_x509_crt_get_expiration_time(cert);
545
546 _cupsMD5Init(&md5_state);
547 _cupsMD5Append(&md5_state, first->data, (int)first->datalen);
548 _cupsMD5Finish(&md5_state, md5_digest);
549
550 snprintf(buffer, bufsize, "%s / %s / %02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", name, httpGetDateString(expiration), md5_digest[0], md5_digest[1], md5_digest[2], md5_digest[3], md5_digest[4], md5_digest[5], md5_digest[6], md5_digest[7], md5_digest[8], md5_digest[9], md5_digest[10], md5_digest[11], md5_digest[12], md5_digest[13], md5_digest[14], md5_digest[15]);
551
552 gnutls_x509_crt_deinit(cert);
553 }
554
555 DEBUG_printf(("1httpCredentialsString: Returning \"%s\".", buffer));
556
557 return (strlen(buffer));
558 }
559
560
561 /*
562 * 'httpLoadCredentials()' - Load X.509 credentials from a keychain file.
563 *
564 * @since CUPS 2.0/OS 10.10@
565 */
566
567 int /* O - 0 on success, -1 on error */
568 httpLoadCredentials(
569 const char *path, /* I - Keychain/PKCS#12 path */
570 cups_array_t **credentials, /* IO - Credentials */
571 const char *common_name) /* I - Common name for credentials */
572 {
573 cups_file_t *fp; /* Certificate file */
574 char filename[1024], /* filename.crt */
575 temp[1024], /* Temporary string */
576 line[256]; /* Base64-encoded line */
577 unsigned char *data = NULL; /* Buffer for cert data */
578 size_t alloc_data = 0, /* Bytes allocated */
579 num_data = 0; /* Bytes used */
580 int decoded; /* Bytes decoded */
581
582
583 if (!credentials || !common_name)
584 return (-1);
585
586 if (!path)
587 path = http_gnutls_default_path(temp, sizeof(temp));
588 if (!path)
589 return (-1);
590
591 http_gnutls_make_path(filename, sizeof(filename), path, common_name, "crt");
592
593 if ((fp = cupsFileOpen(filename, "r")) == NULL)
594 return (-1);
595
596 while (cupsFileGets(fp, line, sizeof(line)))
597 {
598 if (!strcmp(line, "-----BEGIN CERTIFICATE-----"))
599 {
600 if (num_data)
601 {
602 /*
603 * Missing END CERTIFICATE...
604 */
605
606 httpFreeCredentials(*credentials);
607 *credentials = NULL;
608 break;
609 }
610 }
611 else if (!strcmp(line, "-----END CERTIFICATE-----"))
612 {
613 if (!num_data)
614 {
615 /*
616 * Missing data...
617 */
618
619 httpFreeCredentials(*credentials);
620 *credentials = NULL;
621 break;
622 }
623
624 if (!*credentials)
625 *credentials = cupsArrayNew(NULL, NULL);
626
627 if (httpAddCredential(*credentials, data, num_data))
628 {
629 httpFreeCredentials(*credentials);
630 *credentials = NULL;
631 break;
632 }
633
634 num_data = 0;
635 }
636 else
637 {
638 if (alloc_data == 0)
639 {
640 data = malloc(2048);
641 alloc_data = 2048;
642
643 if (!data)
644 break;
645 }
646 else if ((num_data + strlen(line)) >= alloc_data)
647 {
648 unsigned char *tdata = realloc(data, alloc_data + 1024);
649 /* Expanded buffer */
650
651 if (!tdata)
652 {
653 httpFreeCredentials(*credentials);
654 *credentials = NULL;
655 break;
656 }
657
658 data = tdata;
659 alloc_data += 1024;
660 }
661
662 decoded = alloc_data - num_data;
663 httpDecode64_2((char *)data + num_data, &decoded, line);
664 num_data += (size_t)decoded;
665 }
666 }
667
668 cupsFileClose(fp);
669
670 if (num_data)
671 {
672 /*
673 * Missing END CERTIFICATE...
674 */
675
676 httpFreeCredentials(*credentials);
677 *credentials = NULL;
678 }
679
680 if (data)
681 free(data);
682
683 return (*credentials ? 0 : -1);
684 }
685
686
687 /*
688 * 'httpSaveCredentials()' - Save X.509 credentials to a keychain file.
689 *
690 * @since CUPS 2.0/OS 10.10@
691 */
692
693 int /* O - -1 on error, 0 on success */
694 httpSaveCredentials(
695 const char *path, /* I - Keychain/PKCS#12 path */
696 cups_array_t *credentials, /* I - Credentials */
697 const char *common_name) /* I - Common name for credentials */
698 {
699 cups_file_t *fp; /* Certificate file */
700 char filename[1024], /* filename.crt */
701 nfilename[1024],/* filename.crt.N */
702 temp[1024], /* Temporary string */
703 line[256]; /* Base64-encoded line */
704 const unsigned char *ptr; /* Pointer into certificate */
705 ssize_t remaining; /* Bytes left */
706 http_credential_t *cred; /* Current credential */
707
708
709 if (!credentials || !common_name)
710 return (-1);
711
712 if (!path)
713 path = http_gnutls_default_path(temp, sizeof(temp));
714 if (!path)
715 return (-1);
716
717 http_gnutls_make_path(filename, sizeof(filename), path, common_name, "crt");
718 snprintf(nfilename, sizeof(nfilename), "%s.N", filename);
719
720 if ((fp = cupsFileOpen(nfilename, "w")) == NULL)
721 return (-1);
722
723 fchmod(cupsFileNumber(fp), 0600);
724
725 for (cred = (http_credential_t *)cupsArrayFirst(credentials);
726 cred;
727 cred = (http_credential_t *)cupsArrayNext(credentials))
728 {
729 cupsFilePuts(fp, "-----BEGIN CERTIFICATE-----\n");
730 for (ptr = cred->data, remaining = (ssize_t)cred->datalen; remaining > 0; remaining -= 45, ptr += 45)
731 {
732 httpEncode64_2(line, sizeof(line), (char *)ptr, remaining > 45 ? 45 : remaining);
733 cupsFilePrintf(fp, "%s\n", line);
734 }
735 cupsFilePuts(fp, "-----END CERTIFICATE-----\n");
736 }
737
738 cupsFileClose(fp);
739
740 return (rename(nfilename, filename));
741 }
742
743
744 /*
745 * 'http_gnutls_create_credential()' - Create a single credential in the internal format.
746 */
747
748 static gnutls_x509_crt_t /* O - Certificate */
749 http_gnutls_create_credential(
750 http_credential_t *credential) /* I - Credential */
751 {
752 int result; /* Result from GNU TLS */
753 gnutls_x509_crt_t cert; /* Certificate */
754 gnutls_datum_t datum; /* Data record */
755
756
757 DEBUG_printf(("3http_gnutls_create_credential(credential=%p)", credential));
758
759 if (!credential)
760 return (NULL);
761
762 if ((result = gnutls_x509_crt_init(&cert)) < 0)
763 {
764 DEBUG_printf(("4http_gnutls_create_credential: init error: %s", gnutls_strerror(result)));
765 return (NULL);
766 }
767
768 datum.data = credential->data;
769 datum.size = credential->datalen;
770
771 if ((result = gnutls_x509_crt_import(cert, &datum, GNUTLS_X509_FMT_DER)) < 0)
772 {
773 DEBUG_printf(("4http_gnutls_create_credential: import error: %s", gnutls_strerror(result)));
774
775 gnutls_x509_crt_deinit(cert);
776 return (NULL);
777 }
778
779 return (cert);
780 }
781
782
783 /*
784 * 'http_gnutls_default_path()' - Get the default credential store path.
785 */
786
787 static const char * /* O - Path or NULL on error */
788 http_gnutls_default_path(char *buffer,/* I - Path buffer */
789 size_t bufsize)/* I - Size of path buffer */
790 {
791 const char *home = getenv("HOME"); /* HOME environment variable */
792
793
794 if (getuid() && home)
795 {
796 snprintf(buffer, bufsize, "%s/.cups", home);
797 if (access(buffer, 0))
798 {
799 DEBUG_printf(("1http_gnutls_default_path: Making directory \"%s\".", buffer));
800 if (mkdir(buffer, 0700))
801 {
802 DEBUG_printf(("1http_gnutls_default_path: Failed to make directory: %s", strerror(errno)));
803 return (NULL);
804 }
805 }
806
807 snprintf(buffer, bufsize, "%s/.cups/ssl", home);
808 if (access(buffer, 0))
809 {
810 DEBUG_printf(("1http_gnutls_default_path: Making directory \"%s\".", buffer));
811 if (mkdir(buffer, 0700))
812 {
813 DEBUG_printf(("1http_gnutls_default_path: Failed to make directory: %s", strerror(errno)));
814 return (NULL);
815 }
816 }
817 }
818 else
819 strlcpy(buffer, CUPS_SERVERROOT "/ssl", bufsize);
820
821 DEBUG_printf(("1http_gnutls_default_path: Using default path \"%s\".", buffer));
822
823 return (buffer);
824 }
825
826
827 /*
828 * 'http_gnutls_make_path()' - Format a filename for a certificate or key file.
829 */
830
831 static const char * /* O - Filename */
832 http_gnutls_make_path(
833 char *buffer, /* I - Filename buffer */
834 size_t bufsize, /* I - Size of buffer */
835 const char *dirname, /* I - Directory */
836 const char *filename, /* I - Filename (usually hostname) */
837 const char *ext) /* I - Extension */
838 {
839 char *bufptr, /* Pointer into buffer */
840 *bufend = buffer + bufsize - 1; /* End of buffer */
841
842
843 snprintf(buffer, bufsize, "%s/", dirname);
844 bufptr = buffer + strlen(buffer);
845
846 while (*filename && bufptr < bufend)
847 {
848 if (_cups_isalnum(*filename) || *filename == '-' || *filename == '.')
849 *bufptr++ = *filename;
850 else
851 *bufptr++ = '_';
852
853 filename ++;
854 }
855
856 if (bufptr < bufend)
857 *bufptr++ = '.';
858
859 strlcpy(bufptr, ext, (size_t)(bufend - bufptr + 1));
860
861 return (buffer);
862 }
863
864
865 /*
866 * 'http_gnutls_read()' - Read function for the GNU TLS library.
867 */
868
869 static ssize_t /* O - Number of bytes read or -1 on error */
870 http_gnutls_read(
871 gnutls_transport_ptr_t ptr, /* I - Connection to server */
872 void *data, /* I - Buffer */
873 size_t length) /* I - Number of bytes to read */
874 {
875 http_t *http; /* HTTP connection */
876 ssize_t bytes; /* Bytes read */
877
878
879 DEBUG_printf(("6http_gnutls_read(ptr=%p, data=%p, length=%d)", ptr, data, (int)length));
880
881 http = (http_t *)ptr;
882
883 if (!http->blocking)
884 {
885 /*
886 * Make sure we have data before we read...
887 */
888
889 while (!_httpWait(http, http->wait_value, 0))
890 {
891 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
892 continue;
893
894 http->error = ETIMEDOUT;
895 return (-1);
896 }
897 }
898
899 bytes = recv(http->fd, data, length, 0);
900 DEBUG_printf(("6http_gnutls_read: bytes=%d", (int)bytes));
901 return (bytes);
902 }
903
904
905 /*
906 * 'http_gnutls_write()' - Write function for the GNU TLS library.
907 */
908
909 static ssize_t /* O - Number of bytes written or -1 on error */
910 http_gnutls_write(
911 gnutls_transport_ptr_t ptr, /* I - Connection to server */
912 const void *data, /* I - Data buffer */
913 size_t length) /* I - Number of bytes to write */
914 {
915 ssize_t bytes; /* Bytes written */
916
917
918 DEBUG_printf(("6http_gnutls_write(ptr=%p, data=%p, length=%d)", ptr, data,
919 (int)length));
920 bytes = send(((http_t *)ptr)->fd, data, length, 0);
921 DEBUG_printf(("http_gnutls_write: bytes=%d", (int)bytes));
922
923 return (bytes);
924 }
925
926
927 /*
928 * '_httpTLSInitialize()' - Initialize the TLS stack.
929 */
930
931 void
932 _httpTLSInitialize(void)
933 {
934 /*
935 * Initialize GNU TLS...
936 */
937
938 gnutls_global_init();
939 }
940
941
942 /*
943 * '_httpTLSPending()' - Return the number of pending TLS-encrypted bytes.
944 */
945
946 size_t /* O - Bytes available */
947 _httpTLSPending(http_t *http) /* I - HTTP connection */
948 {
949 return (gnutls_record_check_pending(http->tls));
950 }
951
952
953 /*
954 * '_httpTLSRead()' - Read from a SSL/TLS connection.
955 */
956
957 int /* O - Bytes read */
958 _httpTLSRead(http_t *http, /* I - Connection to server */
959 char *buf, /* I - Buffer to store data */
960 int len) /* I - Length of buffer */
961 {
962 ssize_t result; /* Return value */
963
964
965 result = gnutls_record_recv(http->tls, buf, (size_t)len);
966
967 if (result < 0 && !errno)
968 {
969 /*
970 * Convert GNU TLS error to errno value...
971 */
972
973 switch (result)
974 {
975 case GNUTLS_E_INTERRUPTED :
976 errno = EINTR;
977 break;
978
979 case GNUTLS_E_AGAIN :
980 errno = EAGAIN;
981 break;
982
983 default :
984 errno = EPIPE;
985 break;
986 }
987
988 result = -1;
989 }
990
991 return ((int)result);
992 }
993
994
995 /*
996 * '_httpTLSSetCredentials()' - Set the TLS credentials.
997 */
998
999 int /* O - Status of connection */
1000 _httpTLSSetCredentials(http_t *http) /* I - Connection to server */
1001 {
1002 (void)http;
1003
1004 return (0);
1005 }
1006
1007
1008 /*
1009 * '_httpTLSSetOptions()' - Set TLS protocol and cipher suite options.
1010 */
1011
1012 void
1013 _httpTLSSetOptions(int options) /* I - Options */
1014 {
1015 tls_options = options;
1016 }
1017
1018
1019 /*
1020 * '_httpTLSStart()' - Set up SSL/TLS support on a connection.
1021 */
1022
1023 int /* O - 0 on success, -1 on failure */
1024 _httpTLSStart(http_t *http) /* I - Connection to server */
1025 {
1026 char hostname[256], /* Hostname */
1027 *hostptr; /* Pointer into hostname */
1028 int status; /* Status of handshake */
1029 gnutls_certificate_credentials_t *credentials;
1030 /* TLS credentials */
1031 char priority_string[1024];
1032 /* Priority string */
1033
1034
1035 DEBUG_printf(("3_httpTLSStart(http=%p)", http));
1036
1037 if (tls_options < 0)
1038 {
1039 DEBUG_puts("4_httpTLSStart: Setting defaults.");
1040 _cupsSetDefaults();
1041 DEBUG_printf(("4_httpTLSStart: tls_options=%x", tls_options));
1042 }
1043
1044 if (http->mode == _HTTP_MODE_SERVER && !tls_keypath)
1045 {
1046 DEBUG_puts("4_httpTLSStart: cupsSetServerCredentials not called.");
1047 http->error = errno = EINVAL;
1048 http->status = HTTP_STATUS_ERROR;
1049 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Server credentials not set."), 1);
1050
1051 return (-1);
1052 }
1053
1054 credentials = (gnutls_certificate_credentials_t *)
1055 malloc(sizeof(gnutls_certificate_credentials_t));
1056 if (credentials == NULL)
1057 {
1058 DEBUG_printf(("8_httpStartTLS: Unable to allocate credentials: %s",
1059 strerror(errno)));
1060 http->error = errno;
1061 http->status = HTTP_STATUS_ERROR;
1062 _cupsSetHTTPError(HTTP_STATUS_ERROR);
1063
1064 return (-1);
1065 }
1066
1067 gnutls_certificate_allocate_credentials(credentials);
1068 status = gnutls_init(&http->tls, http->mode == _HTTP_MODE_CLIENT ? GNUTLS_CLIENT : GNUTLS_SERVER);
1069 if (!status)
1070 status = gnutls_set_default_priority(http->tls);
1071
1072 if (status)
1073 {
1074 http->error = EIO;
1075 http->status = HTTP_STATUS_ERROR;
1076
1077 DEBUG_printf(("4_httpTLSStart: Unable to initialize common TLS parameters: %s", gnutls_strerror(status)));
1078 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, gnutls_strerror(status), 0);
1079
1080 gnutls_deinit(http->tls);
1081 gnutls_certificate_free_credentials(*credentials);
1082 free(credentials);
1083 http->tls = NULL;
1084
1085 return (-1);
1086 }
1087
1088 if (http->mode == _HTTP_MODE_CLIENT)
1089 {
1090 /*
1091 * Client: get the hostname to use for TLS...
1092 */
1093
1094 if (httpAddrLocalhost(http->hostaddr))
1095 {
1096 strlcpy(hostname, "localhost", sizeof(hostname));
1097 }
1098 else
1099 {
1100 /*
1101 * Otherwise make sure the hostname we have does not end in a trailing dot.
1102 */
1103
1104 strlcpy(hostname, http->hostname, sizeof(hostname));
1105 if ((hostptr = hostname + strlen(hostname) - 1) >= hostname &&
1106 *hostptr == '.')
1107 *hostptr = '\0';
1108 }
1109
1110 status = gnutls_server_name_set(http->tls, GNUTLS_NAME_DNS, hostname, strlen(hostname));
1111 }
1112 else
1113 {
1114 /*
1115 * Server: get certificate and private key...
1116 */
1117
1118 char crtfile[1024], /* Certificate file */
1119 keyfile[1024]; /* Private key file */
1120 int have_creds = 0; /* Have credentials? */
1121
1122 if (http->fields[HTTP_FIELD_HOST][0])
1123 {
1124 /*
1125 * Use hostname for TLS upgrade...
1126 */
1127
1128 strlcpy(hostname, http->fields[HTTP_FIELD_HOST], sizeof(hostname));
1129 }
1130 else
1131 {
1132 /*
1133 * Resolve hostname from connection address...
1134 */
1135
1136 http_addr_t addr; /* Connection address */
1137 socklen_t addrlen; /* Length of address */
1138
1139 addrlen = sizeof(addr);
1140 if (getsockname(http->fd, (struct sockaddr *)&addr, &addrlen))
1141 {
1142 DEBUG_printf(("4_httpTLSStart: Unable to get socket address: %s", strerror(errno)));
1143 hostname[0] = '\0';
1144 }
1145 else if (httpAddrLocalhost(&addr))
1146 hostname[0] = '\0';
1147 else
1148 {
1149 httpAddrLookup(&addr, hostname, sizeof(hostname));
1150 DEBUG_printf(("4_httpTLSStart: Resolved socket address to \"%s\".", hostname));
1151 }
1152 }
1153
1154 if (isdigit(hostname[0] & 255) || hostname[0] == '[')
1155 hostname[0] = '\0'; /* Don't allow numeric addresses */
1156
1157 if (hostname[0])
1158 {
1159 http_gnutls_make_path(crtfile, sizeof(crtfile), tls_keypath, hostname, "crt");
1160 http_gnutls_make_path(keyfile, sizeof(keyfile), tls_keypath, hostname, "key");
1161
1162 have_creds = !access(crtfile, 0) && !access(keyfile, 0);
1163 }
1164 else if (tls_common_name)
1165 {
1166 http_gnutls_make_path(crtfile, sizeof(crtfile), tls_keypath, tls_common_name, "crt");
1167 http_gnutls_make_path(keyfile, sizeof(keyfile), tls_keypath, tls_common_name, "key");
1168
1169 have_creds = !access(crtfile, 0) && !access(keyfile, 0);
1170 }
1171
1172 if (!have_creds && tls_auto_create && (hostname[0] || tls_common_name))
1173 {
1174 DEBUG_printf(("4_httpTLSStart: Auto-create credentials for \"%s\".", hostname[0] ? hostname : tls_common_name));
1175
1176 if (!cupsMakeServerCredentials(tls_keypath, hostname[0] ? hostname : tls_common_name, 0, NULL, time(NULL) + 365 * 86400))
1177 {
1178 DEBUG_puts("4_httpTLSStart: cupsMakeServerCredentials failed.");
1179 http->error = errno = EINVAL;
1180 http->status = HTTP_STATUS_ERROR;
1181 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to create server credentials."), 1);
1182
1183 return (-1);
1184 }
1185 }
1186
1187 DEBUG_printf(("4_httpTLSStart: Using certificate \"%s\" and private key \"%s\".", crtfile, keyfile));
1188
1189 status = gnutls_certificate_set_x509_key_file(*credentials, crtfile, keyfile, GNUTLS_X509_FMT_PEM);
1190 }
1191
1192 if (!status)
1193 status = gnutls_credentials_set(http->tls, GNUTLS_CRD_CERTIFICATE, *credentials);
1194
1195 if (status)
1196 {
1197 http->error = EIO;
1198 http->status = HTTP_STATUS_ERROR;
1199
1200 DEBUG_printf(("4_httpTLSStart: Unable to complete client/server setup: %s", gnutls_strerror(status)));
1201 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, gnutls_strerror(status), 0);
1202
1203 gnutls_deinit(http->tls);
1204 gnutls_certificate_free_credentials(*credentials);
1205 free(credentials);
1206 http->tls = NULL;
1207
1208 return (-1);
1209 }
1210
1211 strlcpy(priority_string, "NORMAL", sizeof(priority_string));
1212
1213 if (tls_options & _HTTP_TLS_DENY_TLS10)
1214 strlcat(priority_string, ":+VERS-TLS-ALL:-VERS-TLS1.0:-VERS-SSL3.0", sizeof(priority_string));
1215 else if (tls_options & _HTTP_TLS_ALLOW_SSL3)
1216 strlcat(priority_string, ":+VERS-TLS-ALL", sizeof(priority_string));
1217 else
1218 strlcat(priority_string, ":+VERS-TLS-ALL:-VERS-SSL3.0", sizeof(priority_string));
1219
1220 if (!(tls_options & _HTTP_TLS_ALLOW_RC4))
1221 strlcat(priority_string, ":-ARCFOUR-128", sizeof(priority_string));
1222
1223 if (!(tls_options & _HTTP_TLS_ALLOW_DH))
1224 strlcat(priority_string, ":!ANON-DH", sizeof(priority_string));
1225
1226 #ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT
1227 gnutls_priority_set_direct(http->tls, priority_string, NULL);
1228
1229 #else
1230 gnutls_priority_t priority; /* Priority */
1231
1232 gnutls_priority_init(&priority, priority_string, NULL);
1233 gnutls_priority_set(http->tls, priority);
1234 gnutls_priority_deinit(priority);
1235 #endif /* HAVE_GNUTLS_PRIORITY_SET_DIRECT */
1236
1237 gnutls_transport_set_ptr(http->tls, (gnutls_transport_ptr_t)http);
1238 gnutls_transport_set_pull_function(http->tls, http_gnutls_read);
1239 #ifdef HAVE_GNUTLS_TRANSPORT_SET_PULL_TIMEOUT_FUNCTION
1240 gnutls_transport_set_pull_timeout_function(http->tls, (gnutls_pull_timeout_func)httpWait);
1241 #endif /* HAVE_GNUTLS_TRANSPORT_SET_PULL_TIMEOUT_FUNCTION */
1242 gnutls_transport_set_push_function(http->tls, http_gnutls_write);
1243
1244 while ((status = gnutls_handshake(http->tls)) != GNUTLS_E_SUCCESS)
1245 {
1246 DEBUG_printf(("5_httpStartTLS: gnutls_handshake returned %d (%s)",
1247 status, gnutls_strerror(status)));
1248
1249 if (gnutls_error_is_fatal(status))
1250 {
1251 http->error = EIO;
1252 http->status = HTTP_STATUS_ERROR;
1253
1254 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, gnutls_strerror(status), 0);
1255
1256 gnutls_deinit(http->tls);
1257 gnutls_certificate_free_credentials(*credentials);
1258 free(credentials);
1259 http->tls = NULL;
1260
1261 return (-1);
1262 }
1263 }
1264
1265 http->tls_credentials = credentials;
1266
1267 return (0);
1268 }
1269
1270
1271 /*
1272 * '_httpTLSStop()' - Shut down SSL/TLS on a connection.
1273 */
1274
1275 void
1276 _httpTLSStop(http_t *http) /* I - Connection to server */
1277 {
1278 int error; /* Error code */
1279
1280
1281 error = gnutls_bye(http->tls, http->mode == _HTTP_MODE_CLIENT ? GNUTLS_SHUT_RDWR : GNUTLS_SHUT_WR);
1282 if (error != GNUTLS_E_SUCCESS)
1283 _cupsSetError(IPP_STATUS_ERROR_INTERNAL, gnutls_strerror(errno), 0);
1284
1285 gnutls_deinit(http->tls);
1286 http->tls = NULL;
1287
1288 if (http->tls_credentials)
1289 {
1290 gnutls_certificate_free_credentials(*(http->tls_credentials));
1291 free(http->tls_credentials);
1292 http->tls_credentials = NULL;
1293 }
1294 }
1295
1296
1297 /*
1298 * '_httpTLSWrite()' - Write to a SSL/TLS connection.
1299 */
1300
1301 int /* O - Bytes written */
1302 _httpTLSWrite(http_t *http, /* I - Connection to server */
1303 const char *buf, /* I - Buffer holding data */
1304 int len) /* I - Length of buffer */
1305 {
1306 ssize_t result; /* Return value */
1307
1308
1309 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http, buf, len));
1310
1311 result = gnutls_record_send(http->tls, buf, (size_t)len);
1312
1313 if (result < 0 && !errno)
1314 {
1315 /*
1316 * Convert GNU TLS error to errno value...
1317 */
1318
1319 switch (result)
1320 {
1321 case GNUTLS_E_INTERRUPTED :
1322 errno = EINTR;
1323 break;
1324
1325 case GNUTLS_E_AGAIN :
1326 errno = EAGAIN;
1327 break;
1328
1329 default :
1330 errno = EPIPE;
1331 break;
1332 }
1333
1334 result = -1;
1335 }
1336
1337 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result));
1338
1339 return ((int)result);
1340 }
1341
1342
1343 /*
1344 * End of "$Id$".
1345 */