ci: update meson
[glib.git] / gio / gtlscertificate.c
blob9e497c58bb6e2d050a1098fb3a339eaf6ac7063d
1 /* GIO - GLib Input, Output and Certificateing Library
3 * Copyright (C) 2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 #include "config.h"
21 #include "gtlscertificate.h"
23 #include <string.h>
24 #include "ginitable.h"
25 #include "gtlsbackend.h"
26 #include "gtlsconnection.h"
27 #include "glibintl.h"
29 /**
30 * SECTION:gtlscertificate
31 * @title: GTlsCertificate
32 * @short_description: TLS certificate
33 * @include: gio/gio.h
34 * @see_also: #GTlsConnection
36 * A certificate used for TLS authentication and encryption.
37 * This can represent either a certificate only (eg, the certificate
38 * received by a client from a server), or the combination of
39 * a certificate and a private key (which is needed when acting as a
40 * #GTlsServerConnection).
42 * Since: 2.28
45 /**
46 * GTlsCertificate:
48 * Abstract base class for TLS certificate types.
50 * Since: 2.28
53 G_DEFINE_ABSTRACT_TYPE (GTlsCertificate, g_tls_certificate, G_TYPE_OBJECT)
55 enum
57 PROP_0,
59 PROP_CERTIFICATE,
60 PROP_CERTIFICATE_PEM,
61 PROP_PRIVATE_KEY,
62 PROP_PRIVATE_KEY_PEM,
63 PROP_ISSUER
66 static void
67 g_tls_certificate_init (GTlsCertificate *cert)
71 static void
72 g_tls_certificate_get_property (GObject *object,
73 guint prop_id,
74 GValue *value,
75 GParamSpec *pspec)
77 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
80 static void
81 g_tls_certificate_set_property (GObject *object,
82 guint prop_id,
83 const GValue *value,
84 GParamSpec *pspec)
86 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
89 static void
90 g_tls_certificate_class_init (GTlsCertificateClass *class)
92 GObjectClass *gobject_class = G_OBJECT_CLASS (class);
94 gobject_class->set_property = g_tls_certificate_set_property;
95 gobject_class->get_property = g_tls_certificate_get_property;
97 /**
98 * GTlsCertificate:certificate:
100 * The DER (binary) encoded representation of the certificate.
101 * This property and the #GTlsCertificate:certificate-pem property
102 * represent the same data, just in different forms.
104 * Since: 2.28
106 g_object_class_install_property (gobject_class, PROP_CERTIFICATE,
107 g_param_spec_boxed ("certificate",
108 P_("Certificate"),
109 P_("The DER representation of the certificate"),
110 G_TYPE_BYTE_ARRAY,
111 G_PARAM_READWRITE |
112 G_PARAM_CONSTRUCT_ONLY |
113 G_PARAM_STATIC_STRINGS));
115 * GTlsCertificate:certificate-pem:
117 * The PEM (ASCII) encoded representation of the certificate.
118 * This property and the #GTlsCertificate:certificate
119 * property represent the same data, just in different forms.
121 * Since: 2.28
123 g_object_class_install_property (gobject_class, PROP_CERTIFICATE_PEM,
124 g_param_spec_string ("certificate-pem",
125 P_("Certificate (PEM)"),
126 P_("The PEM representation of the certificate"),
127 NULL,
128 G_PARAM_READWRITE |
129 G_PARAM_CONSTRUCT_ONLY |
130 G_PARAM_STATIC_STRINGS));
132 * GTlsCertificate:private-key:
134 * The DER (binary) encoded representation of the certificate's
135 * private key, in either PKCS#1 format or unencrypted PKCS#8
136 * format. This property (or the #GTlsCertificate:private-key-pem
137 * property) can be set when constructing a key (eg, from a file),
138 * but cannot be read.
140 * PKCS#8 format is supported since 2.32; earlier releases only
141 * support PKCS#1. You can use the `openssl rsa`
142 * tool to convert PKCS#8 keys to PKCS#1.
144 * Since: 2.28
146 g_object_class_install_property (gobject_class, PROP_PRIVATE_KEY,
147 g_param_spec_boxed ("private-key",
148 P_("Private key"),
149 P_("The DER representation of the certificate’s private key"),
150 G_TYPE_BYTE_ARRAY,
151 G_PARAM_WRITABLE |
152 G_PARAM_CONSTRUCT_ONLY |
153 G_PARAM_STATIC_STRINGS));
155 * GTlsCertificate:private-key-pem:
157 * The PEM (ASCII) encoded representation of the certificate's
158 * private key in either PKCS#1 format ("`BEGIN RSA PRIVATE
159 * KEY`") or unencrypted PKCS#8 format ("`BEGIN
160 * PRIVATE KEY`"). This property (or the
161 * #GTlsCertificate:private-key property) can be set when
162 * constructing a key (eg, from a file), but cannot be read.
164 * PKCS#8 format is supported since 2.32; earlier releases only
165 * support PKCS#1. You can use the `openssl rsa`
166 * tool to convert PKCS#8 keys to PKCS#1.
168 * Since: 2.28
170 g_object_class_install_property (gobject_class, PROP_PRIVATE_KEY_PEM,
171 g_param_spec_string ("private-key-pem",
172 P_("Private key (PEM)"),
173 P_("The PEM representation of the certificate’s private key"),
174 NULL,
175 G_PARAM_WRITABLE |
176 G_PARAM_CONSTRUCT_ONLY |
177 G_PARAM_STATIC_STRINGS));
179 * GTlsCertificate:issuer:
181 * A #GTlsCertificate representing the entity that issued this
182 * certificate. If %NULL, this means that the certificate is either
183 * self-signed, or else the certificate of the issuer is not
184 * available.
186 * Since: 2.28
188 g_object_class_install_property (gobject_class, PROP_ISSUER,
189 g_param_spec_object ("issuer",
190 P_("Issuer"),
191 P_("The certificate for the issuing entity"),
192 G_TYPE_TLS_CERTIFICATE,
193 G_PARAM_READWRITE |
194 G_PARAM_CONSTRUCT_ONLY |
195 G_PARAM_STATIC_STRINGS));
198 static GTlsCertificate *
199 g_tls_certificate_new_internal (const gchar *certificate_pem,
200 const gchar *private_key_pem,
201 GTlsCertificate *issuer,
202 GError **error)
204 GObject *cert;
205 GTlsBackend *backend;
207 backend = g_tls_backend_get_default ();
209 cert = g_initable_new (g_tls_backend_get_certificate_type (backend),
210 NULL, error,
211 "certificate-pem", certificate_pem,
212 "private-key-pem", private_key_pem,
213 "issuer", issuer,
214 NULL);
216 return G_TLS_CERTIFICATE (cert);
219 #define PEM_CERTIFICATE_HEADER "-----BEGIN CERTIFICATE-----"
220 #define PEM_CERTIFICATE_FOOTER "-----END CERTIFICATE-----"
221 #define PEM_PKCS1_PRIVKEY_HEADER "-----BEGIN RSA PRIVATE KEY-----"
222 #define PEM_PKCS1_PRIVKEY_FOOTER "-----END RSA PRIVATE KEY-----"
223 #define PEM_PKCS8_PRIVKEY_HEADER "-----BEGIN PRIVATE KEY-----"
224 #define PEM_PKCS8_PRIVKEY_FOOTER "-----END PRIVATE KEY-----"
225 #define PEM_PKCS8_ENCRYPTED_HEADER "-----BEGIN ENCRYPTED PRIVATE KEY-----"
226 #define PEM_PKCS8_ENCRYPTED_FOOTER "-----END ENCRYPTED PRIVATE KEY-----"
228 static gchar *
229 parse_private_key (const gchar *data,
230 gsize data_len,
231 gboolean required,
232 GError **error)
234 const gchar *start, *end, *footer;
236 start = g_strstr_len (data, data_len, PEM_PKCS1_PRIVKEY_HEADER);
237 if (start)
238 footer = PEM_PKCS1_PRIVKEY_FOOTER;
239 else
241 start = g_strstr_len (data, data_len, PEM_PKCS8_PRIVKEY_HEADER);
242 if (start)
243 footer = PEM_PKCS8_PRIVKEY_FOOTER;
244 else
246 start = g_strstr_len (data, data_len, PEM_PKCS8_ENCRYPTED_HEADER);
247 if (start)
249 g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
250 _("Cannot decrypt PEM-encoded private key"));
252 else if (required)
254 g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
255 _("No PEM-encoded private key found"));
257 return NULL;
261 end = g_strstr_len (start, data_len - (data - start), footer);
262 if (!end)
264 g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
265 _("Could not parse PEM-encoded private key"));
266 return NULL;
268 end += strlen (footer);
269 while (*end == '\r' || *end == '\n')
270 end++;
272 return g_strndup (start, end - start);
276 static gchar *
277 parse_next_pem_certificate (const gchar **data,
278 const gchar *data_end,
279 gboolean required,
280 GError **error)
282 const gchar *start, *end;
284 start = g_strstr_len (*data, data_end - *data, PEM_CERTIFICATE_HEADER);
285 if (!start)
287 if (required)
289 g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
290 _("No PEM-encoded certificate found"));
292 return NULL;
295 end = g_strstr_len (start, data_end - start, PEM_CERTIFICATE_FOOTER);
296 if (!end)
298 g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
299 _("Could not parse PEM-encoded certificate"));
300 return NULL;
302 end += strlen (PEM_CERTIFICATE_FOOTER);
303 while (*end == '\r' || *end == '\n')
304 end++;
306 *data = end;
308 return g_strndup (start, end - start);
311 static GSList *
312 parse_and_create_certificate_list (const gchar *data,
313 gsize data_len,
314 GError **error)
316 GSList *first_pem_list = NULL, *pem_list = NULL;
317 gchar *first_pem;
318 const gchar *p, *end;
320 p = data;
321 end = p + data_len;
323 /* Make sure we can load, at least, one certificate. */
324 first_pem = parse_next_pem_certificate (&p, end, TRUE, error);
325 if (!first_pem)
326 return NULL;
328 /* Create a list with a single element. If we load more certificates
329 * below, we will concatenate the two lists at the end. */
330 first_pem_list = g_slist_prepend (first_pem_list, first_pem);
332 /* If we read one certificate successfully, let's see if we can read
333 * some more. If not, we will simply return a list with the first one.
335 while (p && *p)
337 gchar *cert_pem;
338 GError *error = NULL;
340 cert_pem = parse_next_pem_certificate (&p, end, FALSE, &error);
341 if (error)
343 g_slist_free_full (pem_list, g_free);
344 g_error_free (error);
345 return first_pem_list;
347 else if (!cert_pem)
349 break;
352 pem_list = g_slist_prepend (pem_list, cert_pem);
355 pem_list = g_slist_concat (pem_list, first_pem_list);
357 return pem_list;
360 static GTlsCertificate *
361 create_certificate_chain_from_list (GSList *pem_list,
362 const gchar *key_pem)
364 GTlsCertificate *cert = NULL, *issuer = NULL, *root = NULL;
365 GTlsCertificateFlags flags;
366 GSList *pem;
368 pem = pem_list;
369 while (pem)
371 const gchar *key = NULL;
373 /* Private key belongs only to the first certificate. */
374 if (!pem->next)
375 key = key_pem;
377 /* We assume that the whole file is a certificate chain, so we use
378 * each certificate as the issuer of the next one (list is in
379 * reverse order).
381 issuer = cert;
382 cert = g_tls_certificate_new_internal (pem->data, key, issuer, NULL);
383 if (issuer)
384 g_object_unref (issuer);
386 if (!cert)
387 return NULL;
389 /* root will point to the last certificate in the file. */
390 if (!root)
391 root = cert;
393 pem = g_slist_next (pem);
396 /* Verify that the certificates form a chain. (We don't care at this
397 * point if there are other problems with it.)
399 flags = g_tls_certificate_verify (cert, NULL, root);
400 if (flags & G_TLS_CERTIFICATE_UNKNOWN_CA)
402 /* It wasn't a chain, it's just a bunch of unrelated certs. */
403 g_clear_object (&cert);
406 return cert;
409 static GTlsCertificate *
410 parse_and_create_certificate (const gchar *data,
411 gsize data_len,
412 const gchar *key_pem,
413 GError **error)
416 GSList *pem_list;
417 GTlsCertificate *cert;
419 pem_list = parse_and_create_certificate_list (data, data_len, error);
420 if (!pem_list)
421 return NULL;
423 /* We don't pass the error here because, if it fails, we still want to
424 * load and return the first certificate.
426 cert = create_certificate_chain_from_list (pem_list, key_pem);
427 if (!cert)
429 GSList *last = NULL;
431 /* Get the first certificate (which is the last one as the list is
432 * in reverse order).
434 last = g_slist_last (pem_list);
436 cert = g_tls_certificate_new_internal (last->data, key_pem, NULL, error);
439 g_slist_free_full (pem_list, g_free);
441 return cert;
445 * g_tls_certificate_new_from_pem:
446 * @data: PEM-encoded certificate data
447 * @length: the length of @data, or -1 if it's 0-terminated.
448 * @error: #GError for error reporting, or %NULL to ignore.
450 * Creates a #GTlsCertificate from the PEM-encoded data in @data. If
451 * @data includes both a certificate and a private key, then the
452 * returned certificate will include the private key data as well. (See
453 * the #GTlsCertificate:private-key-pem property for information about
454 * supported formats.)
456 * The returned certificate will be the first certificate found in
457 * @data. As of GLib 2.44, if @data contains more certificates it will
458 * try to load a certificate chain. All certificates will be verified in
459 * the order found (top-level certificate should be the last one in the
460 * file) and the #GTlsCertificate:issuer property of each certificate
461 * will be set accordingly if the verification succeeds. If any
462 * certificate in the chain cannot be verified, the first certificate in
463 * the file will still be returned.
465 * Returns: the new certificate, or %NULL if @data is invalid
467 * Since: 2.28
469 GTlsCertificate *
470 g_tls_certificate_new_from_pem (const gchar *data,
471 gssize length,
472 GError **error)
474 GError *child_error = NULL;
475 gchar *key_pem;
476 GTlsCertificate *cert;
478 g_return_val_if_fail (data != NULL, NULL);
479 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
481 if (length == -1)
482 length = strlen (data);
484 key_pem = parse_private_key (data, length, FALSE, &child_error);
485 if (child_error != NULL)
487 g_propagate_error (error, child_error);
488 return NULL;
491 cert = parse_and_create_certificate (data, length, key_pem, error);
492 g_free (key_pem);
494 return cert;
498 * g_tls_certificate_new_from_file:
499 * @file: (type filename): file containing a PEM-encoded certificate to import
500 * @error: #GError for error reporting, or %NULL to ignore.
502 * Creates a #GTlsCertificate from the PEM-encoded data in @file. The
503 * returned certificate will be the first certificate found in @file. As
504 * of GLib 2.44, if @file contains more certificates it will try to load
505 * a certificate chain. All certificates will be verified in the order
506 * found (top-level certificate should be the last one in the file) and
507 * the #GTlsCertificate:issuer property of each certificate will be set
508 * accordingly if the verification succeeds. If any certificate in the
509 * chain cannot be verified, the first certificate in the file will
510 * still be returned.
512 * If @file cannot be read or parsed, the function will return %NULL and
513 * set @error. Otherwise, this behaves like
514 * g_tls_certificate_new_from_pem().
516 * Returns: the new certificate, or %NULL on error
518 * Since: 2.28
520 GTlsCertificate *
521 g_tls_certificate_new_from_file (const gchar *file,
522 GError **error)
524 GTlsCertificate *cert;
525 gchar *contents;
526 gsize length;
528 if (!g_file_get_contents (file, &contents, &length, error))
529 return NULL;
531 cert = g_tls_certificate_new_from_pem (contents, length, error);
532 g_free (contents);
533 return cert;
537 * g_tls_certificate_new_from_files:
538 * @cert_file: (type filename): file containing one or more PEM-encoded
539 * certificates to import
540 * @key_file: (type filename): file containing a PEM-encoded private key
541 * to import
542 * @error: #GError for error reporting, or %NULL to ignore.
544 * Creates a #GTlsCertificate from the PEM-encoded data in @cert_file
545 * and @key_file. The returned certificate will be the first certificate
546 * found in @cert_file. As of GLib 2.44, if @cert_file contains more
547 * certificates it will try to load a certificate chain. All
548 * certificates will be verified in the order found (top-level
549 * certificate should be the last one in the file) and the
550 * #GTlsCertificate:issuer property of each certificate will be set
551 * accordingly if the verification succeeds. If any certificate in the
552 * chain cannot be verified, the first certificate in the file will
553 * still be returned.
555 * If either file cannot be read or parsed, the function will return
556 * %NULL and set @error. Otherwise, this behaves like
557 * g_tls_certificate_new_from_pem().
559 * Returns: the new certificate, or %NULL on error
561 * Since: 2.28
563 GTlsCertificate *
564 g_tls_certificate_new_from_files (const gchar *cert_file,
565 const gchar *key_file,
566 GError **error)
568 GTlsCertificate *cert;
569 gchar *cert_data, *key_data;
570 gsize cert_len, key_len;
571 gchar *key_pem;
573 if (!g_file_get_contents (key_file, &key_data, &key_len, error))
574 return NULL;
576 key_pem = parse_private_key (key_data, key_len, TRUE, error);
577 g_free (key_data);
578 if (!key_pem)
579 return NULL;
581 if (!g_file_get_contents (cert_file, &cert_data, &cert_len, error))
583 g_free (key_pem);
584 return NULL;
587 cert = parse_and_create_certificate (cert_data, cert_len, key_pem, error);
588 g_free (cert_data);
589 g_free (key_pem);
590 return cert;
594 * g_tls_certificate_list_new_from_file:
595 * @file: (type filename): file containing PEM-encoded certificates to import
596 * @error: #GError for error reporting, or %NULL to ignore.
598 * Creates one or more #GTlsCertificates from the PEM-encoded
599 * data in @file. If @file cannot be read or parsed, the function will
600 * return %NULL and set @error. If @file does not contain any
601 * PEM-encoded certificates, this will return an empty list and not
602 * set @error.
604 * Returns: (element-type Gio.TlsCertificate) (transfer full): a
605 * #GList containing #GTlsCertificate objects. You must free the list
606 * and its contents when you are done with it.
608 * Since: 2.28
610 GList *
611 g_tls_certificate_list_new_from_file (const gchar *file,
612 GError **error)
614 GQueue queue = G_QUEUE_INIT;
615 gchar *contents, *end;
616 const gchar *p;
617 gsize length;
619 if (!g_file_get_contents (file, &contents, &length, error))
620 return NULL;
622 end = contents + length;
623 p = contents;
624 while (p && *p)
626 gchar *cert_pem;
627 GTlsCertificate *cert = NULL;
628 GError *parse_error = NULL;
630 cert_pem = parse_next_pem_certificate (&p, end, FALSE, &parse_error);
631 if (cert_pem)
633 cert = g_tls_certificate_new_internal (cert_pem, NULL, NULL, &parse_error);
634 g_free (cert_pem);
636 if (!cert)
638 if (parse_error)
640 g_propagate_error (error, parse_error);
641 g_list_free_full (queue.head, g_object_unref);
642 queue.head = NULL;
644 break;
646 g_queue_push_tail (&queue, cert);
649 g_free (contents);
650 return queue.head;
655 * g_tls_certificate_get_issuer:
656 * @cert: a #GTlsCertificate
658 * Gets the #GTlsCertificate representing @cert's issuer, if known
660 * Returns: (transfer none): The certificate of @cert's issuer,
661 * or %NULL if @cert is self-signed or signed with an unknown
662 * certificate.
664 * Since: 2.28
666 GTlsCertificate *
667 g_tls_certificate_get_issuer (GTlsCertificate *cert)
669 GTlsCertificate *issuer;
671 g_object_get (G_OBJECT (cert), "issuer", &issuer, NULL);
672 if (issuer)
673 g_object_unref (issuer);
675 return issuer;
679 * g_tls_certificate_verify:
680 * @cert: a #GTlsCertificate
681 * @identity: (nullable): the expected peer identity
682 * @trusted_ca: (nullable): the certificate of a trusted authority
684 * This verifies @cert and returns a set of #GTlsCertificateFlags
685 * indicating any problems found with it. This can be used to verify a
686 * certificate outside the context of making a connection, or to
687 * check a certificate against a CA that is not part of the system
688 * CA database.
690 * If @identity is not %NULL, @cert's name(s) will be compared against
691 * it, and %G_TLS_CERTIFICATE_BAD_IDENTITY will be set in the return
692 * value if it does not match. If @identity is %NULL, that bit will
693 * never be set in the return value.
695 * If @trusted_ca is not %NULL, then @cert (or one of the certificates
696 * in its chain) must be signed by it, or else
697 * %G_TLS_CERTIFICATE_UNKNOWN_CA will be set in the return value. If
698 * @trusted_ca is %NULL, that bit will never be set in the return
699 * value.
701 * (All other #GTlsCertificateFlags values will always be set or unset
702 * as appropriate.)
704 * Returns: the appropriate #GTlsCertificateFlags
706 * Since: 2.28
708 GTlsCertificateFlags
709 g_tls_certificate_verify (GTlsCertificate *cert,
710 GSocketConnectable *identity,
711 GTlsCertificate *trusted_ca)
713 return G_TLS_CERTIFICATE_GET_CLASS (cert)->verify (cert, identity, trusted_ca);
717 * g_tls_certificate_is_same:
718 * @cert_one: first certificate to compare
719 * @cert_two: second certificate to compare
721 * Check if two #GTlsCertificate objects represent the same certificate.
722 * The raw DER byte data of the two certificates are checked for equality.
723 * This has the effect that two certificates may compare equal even if
724 * their #GTlsCertificate:issuer, #GTlsCertificate:private-key, or
725 * #GTlsCertificate:private-key-pem properties differ.
727 * Returns: whether the same or not
729 * Since: 2.34
731 gboolean
732 g_tls_certificate_is_same (GTlsCertificate *cert_one,
733 GTlsCertificate *cert_two)
735 GByteArray *b1, *b2;
736 gboolean equal;
738 g_return_val_if_fail (G_IS_TLS_CERTIFICATE (cert_one), FALSE);
739 g_return_val_if_fail (G_IS_TLS_CERTIFICATE (cert_two), FALSE);
741 g_object_get (cert_one, "certificate", &b1, NULL);
742 g_object_get (cert_two, "certificate", &b2, NULL);
744 equal = (b1->len == b2->len &&
745 memcmp (b1->data, b2->data, b1->len) == 0);
747 g_byte_array_unref (b1);
748 g_byte_array_unref (b2);
750 return equal;