1 /* GIO - GLib Input, Output and Certificateing Library
2  *
3  * Copyright (C) 2010 Red Hat, Inc.
4  *
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.
9  *
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.
14  *
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/>.
17  */
18 
19 #include "config.h"
20 
21 #include "gtlscertificate.h"
22 
23 #include <string.h>
24 #include "ginitable.h"
25 #include "gtlsbackend.h"
26 #include "gtlsconnection.h"
27 #include "glibintl.h"
28 
29 /**
30  * SECTION:gtlscertificate
31  * @title: GTlsCertificate
32  * @short_description: TLS certificate
33  * @include: gio/gio.h
34  * @see_also: #GTlsConnection
35  *
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).
41  *
42  * Since: 2.28
43  */
44 
45 /**
46  * GTlsCertificate:
47  *
48  * Abstract base class for TLS certificate types.
49  *
50  * Since: 2.28
51  */
52 
53 G_DEFINE_ABSTRACT_TYPE (GTlsCertificate, g_tls_certificate, G_TYPE_OBJECT)
54 
55 enum
56 {
57   PROP_0,
58 
59   PROP_CERTIFICATE,
60   PROP_CERTIFICATE_PEM,
61   PROP_PRIVATE_KEY,
62   PROP_PRIVATE_KEY_PEM,
63   PROP_ISSUER,
64   PROP_PKCS11_URI,
65   PROP_PRIVATE_KEY_PKCS11_URI,
66   PROP_NOT_VALID_BEFORE,
67   PROP_NOT_VALID_AFTER,
68   PROP_SUBJECT_NAME,
69   PROP_ISSUER_NAME,
70   PROP_DNS_NAMES,
71   PROP_IP_ADDRESSES,
72 };
73 
74 static void
g_tls_certificate_init(GTlsCertificate * cert)75 g_tls_certificate_init (GTlsCertificate *cert)
76 {
77 }
78 
79 static void
g_tls_certificate_get_property(GObject * object,guint prop_id,GValue * value,GParamSpec * pspec)80 g_tls_certificate_get_property (GObject    *object,
81 				guint       prop_id,
82 				GValue     *value,
83 				GParamSpec *pspec)
84 {
85   switch (prop_id)
86     {
87     case PROP_PRIVATE_KEY:
88     case PROP_PRIVATE_KEY_PEM:
89     case PROP_PKCS11_URI:
90     case PROP_PRIVATE_KEY_PKCS11_URI:
91       /* Subclasses must override this property but this allows older backends to not fatally error */
92       g_value_set_static_string (value, NULL);
93       break;
94     default:
95       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
96     }
97 }
98 
99 static void
g_tls_certificate_set_property(GObject * object,guint prop_id,const GValue * value,GParamSpec * pspec)100 g_tls_certificate_set_property (GObject      *object,
101 				guint         prop_id,
102 				const GValue *value,
103 				GParamSpec   *pspec)
104 {
105   switch (prop_id)
106     {
107     case PROP_PKCS11_URI:
108     case PROP_PRIVATE_KEY_PKCS11_URI:
109       /* Subclasses must override this property but this allows older backends to not fatally error */
110       break;
111     default:
112       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
113     }
114 }
115 
116 static void
g_tls_certificate_class_init(GTlsCertificateClass * class)117 g_tls_certificate_class_init (GTlsCertificateClass *class)
118 {
119   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
120 
121   gobject_class->set_property = g_tls_certificate_set_property;
122   gobject_class->get_property = g_tls_certificate_get_property;
123 
124   /**
125    * GTlsCertificate:certificate:
126    *
127    * The DER (binary) encoded representation of the certificate.
128    * This property and the #GTlsCertificate:certificate-pem property
129    * represent the same data, just in different forms.
130    *
131    * Since: 2.28
132    */
133   g_object_class_install_property (gobject_class, PROP_CERTIFICATE,
134 				   g_param_spec_boxed ("certificate",
135 						       P_("Certificate"),
136 						       P_("The DER representation of the certificate"),
137 						       G_TYPE_BYTE_ARRAY,
138 						       G_PARAM_READWRITE |
139 						       G_PARAM_CONSTRUCT_ONLY |
140 						       G_PARAM_STATIC_STRINGS));
141   /**
142    * GTlsCertificate:certificate-pem:
143    *
144    * The PEM (ASCII) encoded representation of the certificate.
145    * This property and the #GTlsCertificate:certificate
146    * property represent the same data, just in different forms.
147    *
148    * Since: 2.28
149    */
150   g_object_class_install_property (gobject_class, PROP_CERTIFICATE_PEM,
151 				   g_param_spec_string ("certificate-pem",
152 							P_("Certificate (PEM)"),
153 							P_("The PEM representation of the certificate"),
154 							NULL,
155 							G_PARAM_READWRITE |
156 							G_PARAM_CONSTRUCT_ONLY |
157 							G_PARAM_STATIC_STRINGS));
158   /**
159    * GTlsCertificate:private-key: (nullable)
160    *
161    * The DER (binary) encoded representation of the certificate's
162    * private key, in either [PKCS \#1 format](https://datatracker.ietf.org/doc/html/rfc8017)
163    * or unencrypted [PKCS \#8 format.](https://datatracker.ietf.org/doc/html/rfc5208)
164    * PKCS \#8 format is supported since 2.32; earlier releases only
165    * support PKCS \#1. You can use the `openssl rsa` tool to convert
166    * PKCS \#8 keys to PKCS \#1.
167    *
168    * This property (or the #GTlsCertificate:private-key-pem property)
169    * can be set when constructing a key (for example, from a file).
170    * Since GLib 2.70, it is now also readable; however, be aware that if
171    * the private key is backed by a PKCS \#11 URI – for example, if it
172    * is stored on a smartcard – then this property will be %NULL. If so,
173    * the private key must be referenced via its PKCS \#11 URI,
174    * #GTlsCertificate:private-key-pkcs11-uri. You must check both
175    * properties to see if the certificate really has a private key.
176    * When this property is read, the output format will be unencrypted
177    * PKCS \#8.
178    *
179    * Since: 2.28
180    */
181   g_object_class_install_property (gobject_class, PROP_PRIVATE_KEY,
182 				   g_param_spec_boxed ("private-key",
183 						       P_("Private key"),
184 						       P_("The DER representation of the certificate’s private key"),
185 						       G_TYPE_BYTE_ARRAY,
186 						       G_PARAM_READWRITE |
187 						       G_PARAM_CONSTRUCT_ONLY |
188 						       G_PARAM_STATIC_STRINGS));
189   /**
190    * GTlsCertificate:private-key-pem: (nullable)
191    *
192    * The PEM (ASCII) encoded representation of the certificate's
193    * private key in either [PKCS \#1 format](https://datatracker.ietf.org/doc/html/rfc8017)
194    * ("`BEGIN RSA PRIVATE KEY`") or unencrypted
195    * [PKCS \#8 format](https://datatracker.ietf.org/doc/html/rfc5208)
196    * ("`BEGIN PRIVATE KEY`"). PKCS \#8 format is supported since 2.32;
197    * earlier releases only support PKCS \#1. You can use the `openssl rsa`
198    * tool to convert PKCS \#8 keys to PKCS \#1.
199    *
200    * This property (or the #GTlsCertificate:private-key property)
201    * can be set when constructing a key (for example, from a file).
202    * Since GLib 2.70, it is now also readable; however, be aware that if
203    * the private key is backed by a PKCS \#11 URI - for example, if it
204    * is stored on a smartcard - then this property will be %NULL. If so,
205    * the private key must be referenced via its PKCS \#11 URI,
206    * #GTlsCertificate:private-key-pkcs11-uri. You must check both
207    * properties to see if the certificate really has a private key.
208    * When this property is read, the output format will be unencrypted
209    * PKCS \#8.
210    *
211    * Since: 2.28
212    */
213   g_object_class_install_property (gobject_class, PROP_PRIVATE_KEY_PEM,
214 				   g_param_spec_string ("private-key-pem",
215 							P_("Private key (PEM)"),
216 							P_("The PEM representation of the certificate’s private key"),
217 							NULL,
218 							G_PARAM_READWRITE |
219 							G_PARAM_CONSTRUCT_ONLY |
220 							G_PARAM_STATIC_STRINGS));
221   /**
222    * GTlsCertificate:issuer:
223    *
224    * A #GTlsCertificate representing the entity that issued this
225    * certificate. If %NULL, this means that the certificate is either
226    * self-signed, or else the certificate of the issuer is not
227    * available.
228    *
229    * Beware the issuer certificate may not be the same as the
230    * certificate that would actually be used to construct a valid
231    * certification path during certificate verification.
232    * [RFC 4158](https://datatracker.ietf.org/doc/html/rfc4158) explains
233    * why an issuer certificate cannot be naively assumed to be part of the
234    * the certification path (though GLib's TLS backends may not follow the
235    * path building strategies outlined in this RFC). Due to the complexity
236    * of certification path building, GLib does not provide any way to know
237    * which certification path will actually be used. Accordingly, this
238    * property cannot be used to make security-related decisions. Only
239    * GLib itself should make security decisions about TLS certificates.
240    *
241    * Since: 2.28
242    */
243   g_object_class_install_property (gobject_class, PROP_ISSUER,
244 				   g_param_spec_object ("issuer",
245 							P_("Issuer"),
246 							P_("The certificate for the issuing entity"),
247 							G_TYPE_TLS_CERTIFICATE,
248 							G_PARAM_READWRITE |
249 							G_PARAM_CONSTRUCT_ONLY |
250 							G_PARAM_STATIC_STRINGS));
251 
252   /**
253    * GTlsCertificate:pkcs11-uri: (nullable)
254    *
255    * A URI referencing the [PKCS \#11](https://docs.oasis-open.org/pkcs11/pkcs11-base/v3.0/os/pkcs11-base-v3.0-os.html)
256    * objects containing an X.509 certificate and optionally a private key.
257    *
258    * If %NULL, the certificate is either not backed by PKCS \#11 or the
259    * #GTlsBackend does not support PKCS \#11.
260    *
261    * Since: 2.68
262    */
263   g_object_class_install_property (gobject_class, PROP_PKCS11_URI,
264                                    g_param_spec_string ("pkcs11-uri",
265                                                         P_("PKCS #11 URI"),
266                                                         P_("The PKCS #11 URI"),
267                                                         NULL,
268                                                         G_PARAM_READWRITE |
269                                                           G_PARAM_CONSTRUCT_ONLY |
270                                                           G_PARAM_STATIC_STRINGS));
271 
272   /**
273    * GTlsCertificate:private-key-pkcs11-uri: (nullable)
274    *
275    * A URI referencing a [PKCS \#11](https://docs.oasis-open.org/pkcs11/pkcs11-base/v3.0/os/pkcs11-base-v3.0-os.html)
276    * object containing a private key.
277    *
278    * Since: 2.68
279    */
280   g_object_class_install_property (gobject_class, PROP_PRIVATE_KEY_PKCS11_URI,
281                                    g_param_spec_string ("private-key-pkcs11-uri",
282                                                         P_("PKCS #11 URI"),
283                                                         P_("The PKCS #11 URI for a private key"),
284                                                         NULL,
285                                                         G_PARAM_READWRITE |
286                                                           G_PARAM_CONSTRUCT_ONLY |
287                                                           G_PARAM_STATIC_STRINGS));
288 
289   /**
290    * GTlsCertificate:not-valid-before: (nullable)
291    *
292    * The time at which this cert is considered to be valid,
293    * %NULL if unavailable.
294    *
295    * Since: 2.70
296    */
297   g_object_class_install_property (gobject_class, PROP_NOT_VALID_BEFORE,
298                                    g_param_spec_boxed ("not-valid-before",
299                                                        P_("Not Valid Before"),
300                                                        P_("Cert should not be considered valid before this time."),
301                                                        G_TYPE_DATE_TIME,
302                                                        G_PARAM_READABLE |
303                                                          G_PARAM_STATIC_STRINGS));
304 
305   /**
306    * GTlsCertificate:not-valid-after: (nullable)
307    *
308    * The time at which this cert is no longer valid,
309    * %NULL if unavailable.
310    *
311    * Since: 2.70
312    */
313   g_object_class_install_property (gobject_class, PROP_NOT_VALID_AFTER,
314                                    g_param_spec_boxed ("not-valid-after",
315                                                        P_("Not Valid after"),
316                                                        P_("Cert should not be considered valid after this time."),
317                                                        G_TYPE_DATE_TIME,
318                                                        G_PARAM_READABLE |
319                                                          G_PARAM_STATIC_STRINGS));
320 
321   /**
322    * GTlsCertificate:subject-name: (nullable)
323    *
324    * The subject from the cert,
325    * %NULL if unavailable.
326    *
327    * Since: 2.70
328    */
329   g_object_class_install_property (gobject_class, PROP_SUBJECT_NAME,
330                                    g_param_spec_string ("subject-name",
331                                                         P_("Subject Name"),
332                                                         P_("The subject name from the certificate."),
333                                                         NULL,
334                                                         G_PARAM_READABLE |
335                                                           G_PARAM_STATIC_STRINGS));
336   /**
337    * GTlsCertificate:issuer-name: (nullable)
338    *
339    * The issuer from the certificate,
340    * %NULL if unavailable.
341    *
342    * Since: 2.70
343    */
344   g_object_class_install_property (gobject_class, PROP_ISSUER_NAME,
345                                    g_param_spec_string ("issuer-name",
346                                                         P_("Issuer Name"),
347                                                         P_("The issuer from the certificate."),
348                                                         NULL,
349                                                         G_PARAM_READABLE |
350                                                           G_PARAM_STATIC_STRINGS));
351 
352   /**
353    * GTlsCertificate:dns-names: (nullable) (element-type GBytes) (transfer container)
354    *
355    * The DNS names from the certificate's Subject Alternative Names (SANs),
356    * %NULL if unavailable.
357    *
358    * Since: 2.70
359    */
360   g_object_class_install_property (gobject_class, PROP_DNS_NAMES,
361                                    g_param_spec_boxed ("dns-names",
362                                                        P_("DNS Names"),
363                                                        P_("DNS Names listed on the cert."),
364                                                        G_TYPE_PTR_ARRAY,
365                                                        G_PARAM_READABLE |
366                                                          G_PARAM_STATIC_STRINGS));
367 
368   /**
369    * GTlsCertificate:ip-addresses: (nullable) (element-type GInetAddress) (transfer container)
370    *
371    * The IP addresses from the certificate's Subject Alternative Names (SANs),
372    * %NULL if unavailable.
373    *
374    * Since: 2.70
375    */
376   g_object_class_install_property (gobject_class, PROP_IP_ADDRESSES,
377                                    g_param_spec_boxed ("ip-addresses",
378                                                        P_("IP Addresses"),
379                                                        P_("IP Addresses listed on the cert."),
380                                                        G_TYPE_PTR_ARRAY,
381                                                        G_PARAM_READABLE |
382                                                          G_PARAM_STATIC_STRINGS));
383 }
384 
385 static GTlsCertificate *
g_tls_certificate_new_internal(const gchar * certificate_pem,const gchar * private_key_pem,GTlsCertificate * issuer,GError ** error)386 g_tls_certificate_new_internal (const gchar      *certificate_pem,
387 				const gchar      *private_key_pem,
388 				GTlsCertificate  *issuer,
389 				GError          **error)
390 {
391   GObject *cert;
392   GTlsBackend *backend;
393 
394   backend = g_tls_backend_get_default ();
395 
396   cert = g_initable_new (g_tls_backend_get_certificate_type (backend),
397 			 NULL, error,
398 			 "certificate-pem", certificate_pem,
399 			 "private-key-pem", private_key_pem,
400 			 "issuer", issuer,
401 			 NULL);
402 
403   return G_TLS_CERTIFICATE (cert);
404 }
405 
406 #define PEM_CERTIFICATE_HEADER     "-----BEGIN CERTIFICATE-----"
407 #define PEM_CERTIFICATE_FOOTER     "-----END CERTIFICATE-----"
408 #define PEM_PRIVKEY_HEADER_BEGIN   "-----BEGIN "
409 #define PEM_PRIVKEY_HEADER_END     "PRIVATE KEY-----"
410 #define PEM_PRIVKEY_FOOTER_BEGIN   "-----END "
411 #define PEM_PRIVKEY_FOOTER_END     "PRIVATE KEY-----"
412 #define PEM_PKCS8_ENCRYPTED_HEADER "-----BEGIN ENCRYPTED PRIVATE KEY-----"
413 
414 static gchar *
parse_private_key(const gchar * data,gsize data_len,gboolean required,GError ** error)415 parse_private_key (const gchar *data,
416 		   gsize data_len,
417 		   gboolean required,
418 		   GError **error)
419 {
420   const gchar *header_start = NULL, *header_end, *footer_start = NULL, *footer_end;
421   const gchar *data_end = data + data_len;
422 
423   header_end = g_strstr_len (data, data_len, PEM_PRIVKEY_HEADER_END);
424   if (header_end)
425     header_start = g_strrstr_len (data, header_end - data, PEM_PRIVKEY_HEADER_BEGIN);
426 
427   if (!header_start)
428     {
429       if (required)
430 	g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
431 			     _("No PEM-encoded private key found"));
432 
433       return NULL;
434     }
435 
436   header_end += strlen (PEM_PRIVKEY_HEADER_END);
437 
438   if (strncmp (header_start, PEM_PKCS8_ENCRYPTED_HEADER, header_end - header_start) == 0)
439     {
440       g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
441 			   _("Cannot decrypt PEM-encoded private key"));
442       return NULL;
443     }
444 
445   footer_end = g_strstr_len (header_end, data_len - (header_end - data), PEM_PRIVKEY_FOOTER_END);
446   if (footer_end)
447     footer_start = g_strrstr_len (header_end, footer_end - header_end, PEM_PRIVKEY_FOOTER_BEGIN);
448 
449   if (!footer_start)
450     {
451       g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
452 			   _("Could not parse PEM-encoded private key"));
453       return NULL;
454     }
455 
456   footer_end += strlen (PEM_PRIVKEY_FOOTER_END);
457 
458   while ((footer_end < data_end) && (*footer_end == '\r' || *footer_end == '\n'))
459     footer_end++;
460 
461   return g_strndup (header_start, footer_end - header_start);
462 }
463 
464 
465 static gchar *
parse_next_pem_certificate(const gchar ** data,const gchar * data_end,gboolean required,GError ** error)466 parse_next_pem_certificate (const gchar **data,
467 			    const gchar  *data_end,
468 			    gboolean      required,
469 			    GError      **error)
470 {
471   const gchar *start, *end;
472 
473   start = g_strstr_len (*data, data_end - *data, PEM_CERTIFICATE_HEADER);
474   if (!start)
475     {
476       if (required)
477 	{
478 	  g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
479 			       _("No PEM-encoded certificate found"));
480 	}
481       return NULL;
482     }
483 
484   end = g_strstr_len (start, data_end - start, PEM_CERTIFICATE_FOOTER);
485   if (!end)
486     {
487       g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
488 			   _("Could not parse PEM-encoded certificate"));
489       return NULL;
490     }
491   end += strlen (PEM_CERTIFICATE_FOOTER);
492   while ((end < data_end) && (*end == '\r' || *end == '\n'))
493     end++;
494 
495   *data = end;
496 
497   return g_strndup (start, end - start);
498 }
499 
500 static GSList *
parse_and_create_certificate_list(const gchar * data,gsize data_len,GError ** error)501 parse_and_create_certificate_list (const gchar  *data,
502                                    gsize         data_len,
503                                    GError      **error)
504 {
505   GSList *first_pem_list = NULL, *pem_list = NULL;
506   gchar *first_pem;
507   const gchar *p, *end;
508 
509   p = data;
510   end = p + data_len;
511 
512   /* Make sure we can load, at least, one certificate. */
513   first_pem = parse_next_pem_certificate (&p, end, TRUE, error);
514   if (!first_pem)
515     return NULL;
516 
517   /* Create a list with a single element. If we load more certificates
518    * below, we will concatenate the two lists at the end. */
519   first_pem_list = g_slist_prepend (first_pem_list, first_pem);
520 
521   /* If we read one certificate successfully, let's see if we can read
522    * some more. If not, we will simply return a list with the first one.
523    */
524   while (p < end && p && *p)
525     {
526       gchar *cert_pem;
527       GError *error = NULL;
528 
529       cert_pem = parse_next_pem_certificate (&p, end, FALSE, &error);
530       if (error)
531         {
532           g_slist_free_full (pem_list, g_free);
533           g_error_free (error);
534           return first_pem_list;
535         }
536       else if (!cert_pem)
537         {
538           break;
539         }
540 
541       pem_list = g_slist_prepend (pem_list, cert_pem);
542     }
543 
544   pem_list = g_slist_concat (pem_list, first_pem_list);
545 
546   return pem_list;
547 }
548 
549 static GTlsCertificate *
create_certificate_chain_from_list(GSList * pem_list,const gchar * key_pem)550 create_certificate_chain_from_list (GSList       *pem_list,
551                                     const gchar  *key_pem)
552 {
553   GTlsCertificate *cert = NULL, *issuer = NULL, *root = NULL;
554   GTlsCertificateFlags flags;
555   GSList *pem;
556 
557   pem = pem_list;
558   while (pem)
559     {
560       const gchar *key = NULL;
561 
562       /* Private key belongs only to the first certificate. */
563       if (!pem->next)
564         key = key_pem;
565 
566       /* We assume that the whole file is a certificate chain, so we use
567        * each certificate as the issuer of the next one (list is in
568        * reverse order).
569        */
570       issuer = cert;
571       cert = g_tls_certificate_new_internal (pem->data, key, issuer, NULL);
572       if (issuer)
573         g_object_unref (issuer);
574 
575       if (!cert)
576         return NULL;
577 
578       /* root will point to the last certificate in the file. */
579       if (!root)
580         root = cert;
581 
582       pem = g_slist_next (pem);
583     }
584 
585   /* Verify that the certificates form a chain. (We don't care at this
586    * point if there are other problems with it.)
587    */
588   flags = g_tls_certificate_verify (cert, NULL, root);
589   if (flags & G_TLS_CERTIFICATE_UNKNOWN_CA)
590     {
591       /* It wasn't a chain, it's just a bunch of unrelated certs. */
592       g_clear_object (&cert);
593     }
594 
595   return cert;
596 }
597 
598 static GTlsCertificate *
parse_and_create_certificate(const gchar * data,gsize data_len,const gchar * key_pem,GError ** error)599 parse_and_create_certificate (const gchar  *data,
600                               gsize         data_len,
601                               const gchar  *key_pem,
602                               GError      **error)
603 
604 {
605   GSList *pem_list;
606   GTlsCertificate *cert;
607 
608   pem_list = parse_and_create_certificate_list (data, data_len, error);
609   if (!pem_list)
610     return NULL;
611 
612   /* We don't pass the error here because, if it fails, we still want to
613    * load and return the first certificate.
614    */
615   cert = create_certificate_chain_from_list (pem_list, key_pem);
616   if (!cert)
617     {
618       GSList *last = NULL;
619 
620       /* Get the first certificate (which is the last one as the list is
621        * in reverse order).
622        */
623       last = g_slist_last (pem_list);
624 
625       cert = g_tls_certificate_new_internal (last->data, key_pem, NULL, error);
626     }
627 
628   g_slist_free_full (pem_list, g_free);
629 
630   return cert;
631 }
632 
633 /**
634  * g_tls_certificate_new_from_pem:
635  * @data: PEM-encoded certificate data
636  * @length: the length of @data, or -1 if it's 0-terminated.
637  * @error: #GError for error reporting, or %NULL to ignore.
638  *
639  * Creates a #GTlsCertificate from the PEM-encoded data in @data. If
640  * @data includes both a certificate and a private key, then the
641  * returned certificate will include the private key data as well. (See
642  * the #GTlsCertificate:private-key-pem property for information about
643  * supported formats.)
644  *
645  * The returned certificate will be the first certificate found in
646  * @data. As of GLib 2.44, if @data contains more certificates it will
647  * try to load a certificate chain. All certificates will be verified in
648  * the order found (top-level certificate should be the last one in the
649  * file) and the #GTlsCertificate:issuer property of each certificate
650  * will be set accordingly if the verification succeeds. If any
651  * certificate in the chain cannot be verified, the first certificate in
652  * the file will still be returned.
653  *
654  * Returns: the new certificate, or %NULL if @data is invalid
655  *
656  * Since: 2.28
657  */
658 GTlsCertificate *
g_tls_certificate_new_from_pem(const gchar * data,gssize length,GError ** error)659 g_tls_certificate_new_from_pem  (const gchar  *data,
660 				 gssize        length,
661 				 GError      **error)
662 {
663   GError *child_error = NULL;
664   gchar *key_pem;
665   GTlsCertificate *cert;
666 
667   g_return_val_if_fail (data != NULL, NULL);
668   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
669 
670   if (length == -1)
671     length = strlen (data);
672 
673   key_pem = parse_private_key (data, length, FALSE, &child_error);
674   if (child_error != NULL)
675     {
676       g_propagate_error (error, child_error);
677       return NULL;
678     }
679 
680   cert = parse_and_create_certificate (data, length, key_pem, error);
681   g_free (key_pem);
682 
683   return cert;
684 }
685 
686 /**
687  * g_tls_certificate_new_from_file:
688  * @file: (type filename): file containing a PEM-encoded certificate to import
689  * @error: #GError for error reporting, or %NULL to ignore.
690  *
691  * Creates a #GTlsCertificate from the PEM-encoded data in @file. The
692  * returned certificate will be the first certificate found in @file. As
693  * of GLib 2.44, if @file contains more certificates it will try to load
694  * a certificate chain. All certificates will be verified in the order
695  * found (top-level certificate should be the last one in the file) and
696  * the #GTlsCertificate:issuer property of each certificate will be set
697  * accordingly if the verification succeeds. If any certificate in the
698  * chain cannot be verified, the first certificate in the file will
699  * still be returned.
700  *
701  * If @file cannot be read or parsed, the function will return %NULL and
702  * set @error. Otherwise, this behaves like
703  * g_tls_certificate_new_from_pem().
704  *
705  * Returns: the new certificate, or %NULL on error
706  *
707  * Since: 2.28
708  */
709 GTlsCertificate *
g_tls_certificate_new_from_file(const gchar * file,GError ** error)710 g_tls_certificate_new_from_file (const gchar  *file,
711 				 GError      **error)
712 {
713   GTlsCertificate *cert;
714   gchar *contents;
715   gsize length;
716 
717   if (!g_file_get_contents (file, &contents, &length, error))
718     return NULL;
719 
720   cert = g_tls_certificate_new_from_pem (contents, length, error);
721   g_free (contents);
722   return cert;
723 }
724 
725 /**
726  * g_tls_certificate_new_from_files:
727  * @cert_file: (type filename): file containing one or more PEM-encoded
728  *     certificates to import
729  * @key_file: (type filename): file containing a PEM-encoded private key
730  *     to import
731  * @error: #GError for error reporting, or %NULL to ignore.
732  *
733  * Creates a #GTlsCertificate from the PEM-encoded data in @cert_file
734  * and @key_file. The returned certificate will be the first certificate
735  * found in @cert_file. As of GLib 2.44, if @cert_file contains more
736  * certificates it will try to load a certificate chain. All
737  * certificates will be verified in the order found (top-level
738  * certificate should be the last one in the file) and the
739  * #GTlsCertificate:issuer property of each certificate will be set
740  * accordingly if the verification succeeds. If any certificate in the
741  * chain cannot be verified, the first certificate in the file will
742  * still be returned.
743  *
744  * If either file cannot be read or parsed, the function will return
745  * %NULL and set @error. Otherwise, this behaves like
746  * g_tls_certificate_new_from_pem().
747  *
748  * Returns: the new certificate, or %NULL on error
749  *
750  * Since: 2.28
751  */
752 GTlsCertificate *
g_tls_certificate_new_from_files(const gchar * cert_file,const gchar * key_file,GError ** error)753 g_tls_certificate_new_from_files (const gchar  *cert_file,
754                                   const gchar  *key_file,
755                                   GError      **error)
756 {
757   GTlsCertificate *cert;
758   gchar *cert_data, *key_data;
759   gsize cert_len, key_len;
760   gchar *key_pem;
761 
762   if (!g_file_get_contents (key_file, &key_data, &key_len, error))
763     return NULL;
764 
765   key_pem = parse_private_key (key_data, key_len, TRUE, error);
766   g_free (key_data);
767   if (!key_pem)
768     return NULL;
769 
770   if (!g_file_get_contents (cert_file, &cert_data, &cert_len, error))
771     {
772       g_free (key_pem);
773       return NULL;
774     }
775 
776   cert = parse_and_create_certificate (cert_data, cert_len, key_pem, error);
777   g_free (cert_data);
778   g_free (key_pem);
779   return cert;
780 }
781 
782 /**
783  * g_tls_certificate_new_from_pkcs11_uris:
784  * @pkcs11_uri: A PKCS \#11 URI
785  * @private_key_pkcs11_uri: (nullable): A PKCS \#11 URI
786  * @error: #GError for error reporting, or %NULL to ignore.
787  *
788  * Creates a #GTlsCertificate from a
789  * [PKCS \#11](https://docs.oasis-open.org/pkcs11/pkcs11-base/v3.0/os/pkcs11-base-v3.0-os.html) URI.
790  *
791  * An example @pkcs11_uri would be `pkcs11:model=Model;manufacturer=Manufacture;serial=1;token=My%20Client%20Certificate;id=%01`
792  *
793  * Where the token’s layout is:
794  *
795  * |[
796  * Object 0:
797  *   URL: pkcs11:model=Model;manufacturer=Manufacture;serial=1;token=My%20Client%20Certificate;id=%01;object=private%20key;type=private
798  *   Type: Private key (RSA-2048)
799  *   ID: 01
800  *
801  * Object 1:
802  *   URL: pkcs11:model=Model;manufacturer=Manufacture;serial=1;token=My%20Client%20Certificate;id=%01;object=Certificate%20for%20Authentication;type=cert
803  *   Type: X.509 Certificate (RSA-2048)
804  *   ID: 01
805  * ]|
806  *
807  * In this case the certificate and private key would both be detected and used as expected.
808  * @pkcs_uri may also just reference an X.509 certificate object and then optionally
809  * @private_key_pkcs11_uri allows using a private key exposed under a different URI.
810  *
811  * Note that the private key is not accessed until usage and may fail or require a PIN later.
812  *
813  * Returns: (transfer full): the new certificate, or %NULL on error
814  *
815  * Since: 2.68
816  */
817 GTlsCertificate *
g_tls_certificate_new_from_pkcs11_uris(const gchar * pkcs11_uri,const gchar * private_key_pkcs11_uri,GError ** error)818 g_tls_certificate_new_from_pkcs11_uris (const gchar  *pkcs11_uri,
819                                         const gchar  *private_key_pkcs11_uri,
820                                         GError      **error)
821 {
822   GObject *cert;
823   GTlsBackend *backend;
824 
825   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
826   g_return_val_if_fail (pkcs11_uri, NULL);
827 
828   backend = g_tls_backend_get_default ();
829 
830   cert = g_initable_new (g_tls_backend_get_certificate_type (backend),
831                          NULL, error,
832                          "pkcs11-uri", pkcs11_uri,
833                          "private-key-pkcs11-uri", private_key_pkcs11_uri,
834                          NULL);
835 
836   if (cert != NULL)
837     {
838       gchar *objects_uri;
839 
840       /* Old implementations might not override this property */
841       g_object_get (cert, "pkcs11-uri", &objects_uri, NULL);
842       if (objects_uri == NULL)
843         {
844           g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, _("This GTlsBackend does not support creating PKCS #11 certificates"));
845           g_object_unref (cert);
846           return NULL;
847         }
848       g_free (objects_uri);
849     }
850 
851   return G_TLS_CERTIFICATE (cert);
852 }
853 
854 /**
855  * g_tls_certificate_list_new_from_file:
856  * @file: (type filename): file containing PEM-encoded certificates to import
857  * @error: #GError for error reporting, or %NULL to ignore.
858  *
859  * Creates one or more #GTlsCertificates from the PEM-encoded
860  * data in @file. If @file cannot be read or parsed, the function will
861  * return %NULL and set @error. If @file does not contain any
862  * PEM-encoded certificates, this will return an empty list and not
863  * set @error.
864  *
865  * Returns: (element-type Gio.TlsCertificate) (transfer full): a
866  * #GList containing #GTlsCertificate objects. You must free the list
867  * and its contents when you are done with it.
868  *
869  * Since: 2.28
870  */
871 GList *
g_tls_certificate_list_new_from_file(const gchar * file,GError ** error)872 g_tls_certificate_list_new_from_file (const gchar  *file,
873 				      GError      **error)
874 {
875   GQueue queue = G_QUEUE_INIT;
876   gchar *contents, *end;
877   const gchar *p;
878   gsize length;
879 
880   if (!g_file_get_contents (file, &contents, &length, error))
881     return NULL;
882 
883   end = contents + length;
884   p = contents;
885   while (p && *p)
886     {
887       gchar *cert_pem;
888       GTlsCertificate *cert = NULL;
889       GError *parse_error = NULL;
890 
891       cert_pem = parse_next_pem_certificate (&p, end, FALSE, &parse_error);
892       if (cert_pem)
893         {
894           cert = g_tls_certificate_new_internal (cert_pem, NULL, NULL, &parse_error);
895           g_free (cert_pem);
896         }
897       if (!cert)
898         {
899           if (parse_error)
900             {
901               g_propagate_error (error, parse_error);
902               g_list_free_full (queue.head, g_object_unref);
903               queue.head = NULL;
904             }
905           break;
906         }
907       g_queue_push_tail (&queue, cert);
908     }
909 
910   g_free (contents);
911   return queue.head;
912 }
913 
914 
915 /**
916  * g_tls_certificate_get_issuer:
917  * @cert: a #GTlsCertificate
918  *
919  * Gets the #GTlsCertificate representing @cert's issuer, if known
920  *
921  * Returns: (nullable) (transfer none): The certificate of @cert's issuer,
922  * or %NULL if @cert is self-signed or signed with an unknown
923  * certificate.
924  *
925  * Since: 2.28
926  */
927 GTlsCertificate *
g_tls_certificate_get_issuer(GTlsCertificate * cert)928 g_tls_certificate_get_issuer (GTlsCertificate  *cert)
929 {
930   GTlsCertificate *issuer;
931 
932   g_object_get (G_OBJECT (cert), "issuer", &issuer, NULL);
933   if (issuer)
934     g_object_unref (issuer);
935 
936   return issuer;
937 }
938 
939 /**
940  * g_tls_certificate_verify:
941  * @cert: a #GTlsCertificate
942  * @identity: (nullable): the expected peer identity
943  * @trusted_ca: (nullable): the certificate of a trusted authority
944  *
945  * This verifies @cert and returns a set of #GTlsCertificateFlags
946  * indicating any problems found with it. This can be used to verify a
947  * certificate outside the context of making a connection, or to
948  * check a certificate against a CA that is not part of the system
949  * CA database.
950  *
951  * If @identity is not %NULL, @cert's name(s) will be compared against
952  * it, and %G_TLS_CERTIFICATE_BAD_IDENTITY will be set in the return
953  * value if it does not match. If @identity is %NULL, that bit will
954  * never be set in the return value.
955  *
956  * If @trusted_ca is not %NULL, then @cert (or one of the certificates
957  * in its chain) must be signed by it, or else
958  * %G_TLS_CERTIFICATE_UNKNOWN_CA will be set in the return value. If
959  * @trusted_ca is %NULL, that bit will never be set in the return
960  * value.
961  *
962  * (All other #GTlsCertificateFlags values will always be set or unset
963  * as appropriate.)
964  *
965  * Because TLS session context is not used, #GTlsCertificate may not
966  * perform as many checks on the certificates as #GTlsConnection would.
967  * For example, certificate constraints cannot be honored, and some
968  * revocation checks cannot be performed. The best way to verify TLS
969  * certificates used by a TLS connection is to let #GTlsConnection
970  * handle the verification.
971  *
972  * Returns: the appropriate #GTlsCertificateFlags
973  *
974  * Since: 2.28
975  */
976 GTlsCertificateFlags
g_tls_certificate_verify(GTlsCertificate * cert,GSocketConnectable * identity,GTlsCertificate * trusted_ca)977 g_tls_certificate_verify (GTlsCertificate     *cert,
978 			  GSocketConnectable  *identity,
979 			  GTlsCertificate     *trusted_ca)
980 {
981   return G_TLS_CERTIFICATE_GET_CLASS (cert)->verify (cert, identity, trusted_ca);
982 }
983 
984 /**
985  * g_tls_certificate_is_same:
986  * @cert_one: first certificate to compare
987  * @cert_two: second certificate to compare
988  *
989  * Check if two #GTlsCertificate objects represent the same certificate.
990  * The raw DER byte data of the two certificates are checked for equality.
991  * This has the effect that two certificates may compare equal even if
992  * their #GTlsCertificate:issuer, #GTlsCertificate:private-key, or
993  * #GTlsCertificate:private-key-pem properties differ.
994  *
995  * Returns: whether the same or not
996  *
997  * Since: 2.34
998  */
999 gboolean
g_tls_certificate_is_same(GTlsCertificate * cert_one,GTlsCertificate * cert_two)1000 g_tls_certificate_is_same (GTlsCertificate     *cert_one,
1001                            GTlsCertificate     *cert_two)
1002 {
1003   GByteArray *b1, *b2;
1004   gboolean equal;
1005 
1006   g_return_val_if_fail (G_IS_TLS_CERTIFICATE (cert_one), FALSE);
1007   g_return_val_if_fail (G_IS_TLS_CERTIFICATE (cert_two), FALSE);
1008 
1009   g_object_get (cert_one, "certificate", &b1, NULL);
1010   g_object_get (cert_two, "certificate", &b2, NULL);
1011 
1012   equal = (b1->len == b2->len &&
1013            memcmp (b1->data, b2->data, b1->len) == 0);
1014 
1015   g_byte_array_unref (b1);
1016   g_byte_array_unref (b2);
1017 
1018   return equal;
1019 }
1020 
1021 
1022 /**
1023  * g_tls_certificate_get_not_valid_before:
1024  * @cert: a #GTlsCertificate
1025  *
1026  * Returns the time at which the certificate became or will become valid.
1027  *
1028  * Returns: (nullable) (transfer full): The not-valid-before date, or %NULL if it's not available.
1029  *
1030  * Since: 2.70
1031  */
1032 GDateTime *
g_tls_certificate_get_not_valid_before(GTlsCertificate * cert)1033 g_tls_certificate_get_not_valid_before (GTlsCertificate *cert)
1034 {
1035   GDateTime *not_valid_before = NULL;
1036 
1037   g_return_val_if_fail (G_IS_TLS_CERTIFICATE (cert), NULL);
1038 
1039   g_object_get (G_OBJECT (cert), "not-valid-before", &not_valid_before, NULL);
1040 
1041   return g_steal_pointer (&not_valid_before);
1042 }
1043 
1044 /**
1045  * g_tls_certificate_get_not_valid_after:
1046  * @cert: a #GTlsCertificate
1047  *
1048  * Returns the time at which the certificate became or will become invalid.
1049  *
1050  * Returns: (nullable) (transfer full): The not-valid-after date, or %NULL if it's not available.
1051  *
1052  * Since: 2.70
1053  */
1054 GDateTime *
g_tls_certificate_get_not_valid_after(GTlsCertificate * cert)1055 g_tls_certificate_get_not_valid_after (GTlsCertificate *cert)
1056 {
1057   GDateTime *not_valid_after = NULL;
1058 
1059   g_return_val_if_fail (G_IS_TLS_CERTIFICATE (cert), NULL);
1060 
1061   g_object_get (G_OBJECT (cert), "not-valid-after", &not_valid_after, NULL);
1062 
1063   return g_steal_pointer (&not_valid_after);
1064 }
1065 
1066 /**
1067  * g_tls_certificate_get_subject_name:
1068  * @cert: a #GTlsCertificate
1069  *
1070  * Returns the subject name from the certificate.
1071  *
1072  * Returns: (nullable) (transfer full): The subject name, or %NULL if it's not available.
1073  *
1074  * Since: 2.70
1075  */
1076 gchar *
g_tls_certificate_get_subject_name(GTlsCertificate * cert)1077 g_tls_certificate_get_subject_name (GTlsCertificate *cert)
1078 {
1079   gchar *subject_name = NULL;
1080 
1081   g_return_val_if_fail (G_IS_TLS_CERTIFICATE (cert), NULL);
1082 
1083   g_object_get (G_OBJECT (cert), "subject-name", &subject_name, NULL);
1084 
1085   return g_steal_pointer (&subject_name);
1086 }
1087 
1088 /**
1089  * g_tls_certificate_get_issuer_name:
1090  * @cert: a #GTlsCertificate
1091  *
1092  * Returns the issuer name from the certificate.
1093  *
1094  * Returns: (nullable) (transfer full): The issuer name, or %NULL if it's not available.
1095  *
1096  * Since: 2.70
1097  */
1098 gchar *
g_tls_certificate_get_issuer_name(GTlsCertificate * cert)1099 g_tls_certificate_get_issuer_name (GTlsCertificate *cert)
1100 {
1101   gchar *issuer_name = NULL;
1102 
1103   g_return_val_if_fail (G_IS_TLS_CERTIFICATE (cert), NULL);
1104 
1105   g_object_get (G_OBJECT (cert), "issuer-name", &issuer_name, NULL);
1106 
1107   return g_steal_pointer (&issuer_name);
1108 }
1109 
1110 /**
1111  * g_tls_certificate_get_dns_names:
1112  * @cert: a #GTlsCertificate
1113  *
1114  * Gets the value of #GTlsCertificate:dns-names.
1115  *
1116  * Returns: (nullable) (element-type GBytes) (transfer container): A #GPtrArray of
1117  * #GBytes elements, or %NULL if it's not available.
1118  *
1119  * Since: 2.70
1120  */
1121 GPtrArray *
g_tls_certificate_get_dns_names(GTlsCertificate * cert)1122 g_tls_certificate_get_dns_names (GTlsCertificate *cert)
1123 {
1124   GPtrArray *dns_names = NULL;
1125 
1126   g_return_val_if_fail (G_IS_TLS_CERTIFICATE (cert), NULL);
1127 
1128   g_object_get (G_OBJECT (cert), "dns-names", &dns_names, NULL);
1129 
1130   return g_steal_pointer (&dns_names);
1131 }
1132 
1133 /**
1134  * g_tls_certificate_get_ip_addresses:
1135  * @cert: a #GTlsCertificate
1136  *
1137  * Gets the value of #GTlsCertificate:ip-addresses.
1138  *
1139  * Returns: (nullable) (element-type GInetAddress) (transfer container): A #GPtrArray
1140  * of #GInetAddress elements, or %NULL if it's not available.
1141  *
1142  * Since: 2.70
1143  */
1144 GPtrArray *
g_tls_certificate_get_ip_addresses(GTlsCertificate * cert)1145 g_tls_certificate_get_ip_addresses (GTlsCertificate *cert)
1146 {
1147   GPtrArray *ip_addresses = NULL;
1148 
1149   g_return_val_if_fail (G_IS_TLS_CERTIFICATE (cert), NULL);
1150 
1151   g_object_get (G_OBJECT (cert), "ip-addresses", &ip_addresses, NULL);
1152 
1153   return g_steal_pointer (&ip_addresses);
1154 }
1155