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