Fix minor mem leak in test case
[platform/upstream/glib.git] / gio / gtlscertificate.c
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 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 };
65
66 static void
67 g_tls_certificate_init (GTlsCertificate *cert)
68 {
69 }
70
71 static void
72 g_tls_certificate_get_property (GObject    *object,
73                                 guint       prop_id,
74                                 GValue     *value,
75                                 GParamSpec *pspec)
76 {
77   G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
78 }
79
80 static void
81 g_tls_certificate_set_property (GObject      *object,
82                                 guint         prop_id,
83                                 const GValue *value,
84                                 GParamSpec   *pspec)
85 {
86   G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
87 }
88
89 static void
90 g_tls_certificate_class_init (GTlsCertificateClass *class)
91 {
92   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
93
94   gobject_class->set_property = g_tls_certificate_set_property;
95   gobject_class->get_property = g_tls_certificate_get_property;
96
97   /**
98    * GTlsCertificate:certificate:
99    *
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.
103    *
104    * Since: 2.28
105    */
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));
114   /**
115    * GTlsCertificate:certificate-pem:
116    *
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.
120    *
121    * Since: 2.28
122    */
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));
131   /**
132    * GTlsCertificate:private-key:
133    *
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.
139    *
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.
143    *
144    * Since: 2.28
145    */
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));
154   /**
155    * GTlsCertificate:private-key-pem:
156    *
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.
163    *
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.
167    *
168    * Since: 2.28
169    */
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));
178   /**
179    * GTlsCertificate:issuer:
180    *
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.
185    *
186    * Since: 2.28
187    */
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));
196 }
197
198 static GTlsCertificate *
199 g_tls_certificate_new_internal (const gchar  *certificate_pem,
200                                 const gchar  *private_key_pem,
201                                 GError      **error)
202 {
203   GObject *cert;
204   GTlsBackend *backend;
205
206   backend = g_tls_backend_get_default ();
207
208   cert = g_initable_new (g_tls_backend_get_certificate_type (backend),
209                          NULL, error,
210                          "certificate-pem", certificate_pem,
211                          "private-key-pem", private_key_pem,
212                          NULL);
213   return G_TLS_CERTIFICATE (cert);
214 }
215
216 #define PEM_CERTIFICATE_HEADER     "-----BEGIN CERTIFICATE-----"
217 #define PEM_CERTIFICATE_FOOTER     "-----END CERTIFICATE-----"
218 #define PEM_PKCS1_PRIVKEY_HEADER   "-----BEGIN RSA PRIVATE KEY-----"
219 #define PEM_PKCS1_PRIVKEY_FOOTER   "-----END RSA PRIVATE KEY-----"
220 #define PEM_PKCS8_PRIVKEY_HEADER   "-----BEGIN PRIVATE KEY-----"
221 #define PEM_PKCS8_PRIVKEY_FOOTER   "-----END PRIVATE KEY-----"
222 #define PEM_PKCS8_ENCRYPTED_HEADER "-----BEGIN ENCRYPTED PRIVATE KEY-----"
223 #define PEM_PKCS8_ENCRYPTED_FOOTER "-----END ENCRYPTED PRIVATE KEY-----"
224
225 static gchar *
226 parse_private_key (const gchar *data,
227                    gsize data_len,
228                    gboolean required,
229                    GError **error)
230 {
231   const gchar *start, *end, *footer;
232
233   start = g_strstr_len (data, data_len, PEM_PKCS1_PRIVKEY_HEADER);
234   if (start)
235     footer = PEM_PKCS1_PRIVKEY_FOOTER;
236   else
237     {
238       start = g_strstr_len (data, data_len, PEM_PKCS8_PRIVKEY_HEADER);
239       if (start)
240         footer = PEM_PKCS8_PRIVKEY_FOOTER;
241       else
242         {
243           start = g_strstr_len (data, data_len, PEM_PKCS8_ENCRYPTED_HEADER);
244           if (start)
245             {
246               g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
247                                    _("Cannot decrypt PEM-encoded private key"));
248             }
249           else if (required)
250             {
251               g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
252                                    _("No PEM-encoded private key found"));
253             }
254           return NULL;
255         }
256     }
257
258   end = g_strstr_len (start, data_len - (data - start), footer);
259   if (!end)
260     {
261       g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
262                            _("Could not parse PEM-encoded private key"));
263       return NULL;
264     }
265   end += strlen (footer);
266   while (*end == '\r' || *end == '\n')
267     end++;
268
269   return g_strndup (start, end - start);
270 }
271
272
273 static gchar *
274 parse_next_pem_certificate (const gchar **data,
275                             const gchar  *data_end,
276                             gboolean      required,
277                             GError      **error)
278 {
279   const gchar *start, *end;
280
281   start = g_strstr_len (*data, data_end - *data, PEM_CERTIFICATE_HEADER);
282   if (!start)
283     {
284       if (required)
285         {
286           g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
287                                _("No PEM-encoded certificate found"));
288         }
289       return NULL;
290     }
291
292   end = g_strstr_len (start, data_end - start, PEM_CERTIFICATE_FOOTER);
293   if (!end)
294     {
295       g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
296                            _("Could not parse PEM-encoded certificate"));
297       return NULL;
298     }
299   end += strlen (PEM_CERTIFICATE_FOOTER);
300   while (*end == '\r' || *end == '\n')
301     end++;
302
303   *data = end;
304
305   return g_strndup (start, end - start);
306 }
307
308 /**
309  * g_tls_certificate_new_from_pem:
310  * @data: PEM-encoded certificate data
311  * @length: the length of @data, or -1 if it's 0-terminated.
312  * @error: #GError for error reporting, or %NULL to ignore.
313  *
314  * Creates a new #GTlsCertificate from the PEM-encoded data in @data.
315  * If @data includes both a certificate and a private key, then the
316  * returned certificate will include the private key data as well. (See
317  * the #GTlsCertificate:private-key-pem property for information about
318  * supported formats.)
319  *
320  * If @data includes multiple certificates, only the first one will be
321  * parsed.
322  *
323  * Returns: the new certificate, or %NULL if @data is invalid
324  *
325  * Since: 2.28
326  */
327 GTlsCertificate *
328 g_tls_certificate_new_from_pem  (const gchar  *data,
329                                  gssize        length,
330                                  GError      **error)
331 {
332   const gchar *data_end;
333   gchar *key_pem, *cert_pem;
334   GTlsCertificate *cert;
335
336   g_return_val_if_fail (data != NULL, NULL);
337
338   if (length == -1)
339     length = strlen (data);
340
341   data_end = data + length;
342
343   key_pem = parse_private_key (data, length, FALSE, error);
344   if (error && *error)
345     return NULL;
346
347   cert_pem = parse_next_pem_certificate (&data, data_end, TRUE, error);
348   if (error && *error)
349     {
350       g_free (key_pem);
351       return NULL;
352     }
353
354   cert = g_tls_certificate_new_internal (cert_pem, key_pem, error);
355   g_free (key_pem);
356   g_free (cert_pem);
357
358   return cert;
359 }
360
361 /**
362  * g_tls_certificate_new_from_file:
363  * @file: file containing a PEM-encoded certificate to import
364  * @error: #GError for error reporting, or %NULL to ignore.
365  *
366  * Creates a #GTlsCertificate from the PEM-encoded data in @file. If
367  * @file cannot be read or parsed, the function will return %NULL and
368  * set @error. Otherwise, this behaves like
369  * g_tls_certificate_new_from_pem().
370  *
371  * Returns: the new certificate, or %NULL on error
372  *
373  * Since: 2.28
374  */
375 GTlsCertificate *
376 g_tls_certificate_new_from_file (const gchar  *file,
377                                  GError      **error)
378 {
379   GTlsCertificate *cert;
380   gchar *contents;
381   gsize length;
382
383   if (!g_file_get_contents (file, &contents, &length, error))
384     return NULL;
385
386   cert = g_tls_certificate_new_from_pem (contents, length, error);
387   g_free (contents);
388   return cert;
389 }
390
391 /**
392  * g_tls_certificate_new_from_files:
393  * @cert_file: file containing a PEM-encoded certificate to import
394  * @key_file: file containing a PEM-encoded private key to import
395  * @error: #GError for error reporting, or %NULL to ignore.
396  *
397  * Creates a #GTlsCertificate from the PEM-encoded data in @cert_file
398  * and @key_file. If either file cannot be read or parsed, the
399  * function will return %NULL and set @error. Otherwise, this behaves
400  * like g_tls_certificate_new_from_pem().
401  *
402  * Returns: the new certificate, or %NULL on error
403  *
404  * Since: 2.28
405  */
406 GTlsCertificate *
407 g_tls_certificate_new_from_files (const gchar  *cert_file,
408                                   const gchar  *key_file,
409                                   GError      **error)
410 {
411   GTlsCertificate *cert;
412   gchar *cert_data, *key_data;
413   gsize cert_len, key_len;
414   gchar *cert_pem, *key_pem;
415   const gchar *p;
416
417   if (!g_file_get_contents (cert_file, &cert_data, &cert_len, error))
418     return NULL;
419   p = cert_data;
420   cert_pem = parse_next_pem_certificate (&p, p + cert_len, TRUE, error);
421   g_free (cert_data);
422   if (error && *error)
423     return NULL;
424
425   if (!g_file_get_contents (key_file, &key_data, &key_len, error))
426     {
427       g_free (cert_pem);
428       return NULL;
429     }
430   key_pem = parse_private_key (key_data, key_len, TRUE, error);
431   g_free (key_data);
432   if (error && *error)
433     {
434       g_free (cert_pem);
435       return NULL;
436     }
437
438   cert = g_tls_certificate_new_internal (cert_pem, key_pem, error);
439   g_free (cert_pem);
440   g_free (key_pem);
441   return cert;
442 }
443
444 /**
445  * g_tls_certificate_list_new_from_file:
446  * @file: file containing PEM-encoded certificates to import
447  * @error: #GError for error reporting, or %NULL to ignore.
448  *
449  * Creates one or more #GTlsCertificates from the PEM-encoded
450  * data in @file. If @file cannot be read or parsed, the function will
451  * return %NULL and set @error. If @file does not contain any
452  * PEM-encoded certificates, this will return an empty list and not
453  * set @error.
454  *
455  * Returns: (element-type Gio.TlsCertificate) (transfer full): a
456  * #GList containing #GTlsCertificate objects. You must free the list
457  * and its contents when you are done with it.
458  *
459  * Since: 2.28
460  */
461 GList *
462 g_tls_certificate_list_new_from_file (const gchar  *file,
463                                       GError      **error)
464 {
465   GQueue queue = G_QUEUE_INIT;
466   gchar *contents, *end;
467   const gchar *p;
468   gsize length;
469
470   if (!g_file_get_contents (file, &contents, &length, error))
471     return NULL;
472
473   end = contents + length;
474   p = contents;
475   while (p && *p)
476     {
477       gchar *cert_pem;
478       GTlsCertificate *cert = NULL;
479       GError *parse_error = NULL;
480
481       cert_pem = parse_next_pem_certificate (&p, end, FALSE, &parse_error);
482       if (cert_pem)
483         {
484           cert = g_tls_certificate_new_internal (cert_pem, NULL, &parse_error);
485           g_free (cert_pem);
486         }
487       if (!cert)
488         {
489           if (parse_error)
490             {
491               g_propagate_error (error, parse_error);
492               g_list_free_full (queue.head, g_object_unref);
493               queue.head = NULL;
494             }
495           break;
496         }
497       g_queue_push_tail (&queue, cert);
498     }
499
500   g_free (contents);
501   return queue.head;
502 }
503
504
505 /**
506  * g_tls_certificate_get_issuer:
507  * @cert: a #GTlsCertificate
508  *
509  * Gets the #GTlsCertificate representing @cert's issuer, if known
510  *
511  * Returns: (transfer none): The certificate of @cert's issuer,
512  * or %NULL if @cert is self-signed or signed with an unknown
513  * certificate.
514  *
515  * Since: 2.28
516  */
517 GTlsCertificate *
518 g_tls_certificate_get_issuer (GTlsCertificate  *cert)
519 {
520   GTlsCertificate *issuer;
521
522   g_object_get (G_OBJECT (cert), "issuer", &issuer, NULL);
523   if (issuer)
524     g_object_unref (issuer);
525
526   return issuer;
527 }
528
529 /**
530  * g_tls_certificate_verify:
531  * @cert: a #GTlsCertificate
532  * @identity: (allow-none): the expected peer identity
533  * @trusted_ca: (allow-none): the certificate of a trusted authority
534  *
535  * This verifies @cert and returns a set of #GTlsCertificateFlags
536  * indicating any problems found with it. This can be used to verify a
537  * certificate outside the context of making a connection, or to
538  * check a certificate against a CA that is not part of the system
539  * CA database.
540  *
541  * If @identity is not %NULL, @cert's name(s) will be compared against
542  * it, and %G_TLS_CERTIFICATE_BAD_IDENTITY will be set in the return
543  * value if it does not match. If @identity is %NULL, that bit will
544  * never be set in the return value.
545  *
546  * If @trusted_ca is not %NULL, then @cert (or one of the certificates
547  * in its chain) must be signed by it, or else
548  * %G_TLS_CERTIFICATE_UNKNOWN_CA will be set in the return value. If
549  * @trusted_ca is %NULL, that bit will never be set in the return
550  * value.
551  *
552  * (All other #GTlsCertificateFlags values will always be set or unset
553  * as appropriate.)
554  *
555  * Returns: the appropriate #GTlsCertificateFlags
556  *
557  * Since: 2.28
558  */
559 GTlsCertificateFlags
560 g_tls_certificate_verify (GTlsCertificate     *cert,
561                           GSocketConnectable  *identity,
562                           GTlsCertificate     *trusted_ca)
563 {
564   return G_TLS_CERTIFICATE_GET_CLASS (cert)->verify (cert, identity, trusted_ca);
565 }
566
567 /**
568  * g_tls_certificate_is_same:
569  * @cert_one: first certificate to compare
570  * @cert_two: second certificate to compare
571  *
572  * Check if two #GTlsCertificate objects represent the same certificate.
573  * The raw DER byte data of the two certificates are checked for equality.
574  * This has the effect that two certificates may compare equal even if
575  * their #GTlsCertificate:issuer, #GTlsCertificate:private-key, or
576  * #GTlsCertificate:private-key-pem properties differ.
577  *
578  * Returns: whether the same or not
579  *
580  * Since: 2.34
581  */
582 gboolean
583 g_tls_certificate_is_same (GTlsCertificate     *cert_one,
584                            GTlsCertificate     *cert_two)
585 {
586   GByteArray *b1, *b2;
587   gboolean equal;
588
589   g_return_val_if_fail (G_IS_TLS_CERTIFICATE (cert_one), FALSE);
590   g_return_val_if_fail (G_IS_TLS_CERTIFICATE (cert_two), FALSE);
591
592   g_object_get (cert_one, "certificate", &b1, NULL);
593   g_object_get (cert_two, "certificate", &b2, NULL);
594
595   equal = (b1->len == b2->len &&
596            memcmp (b1->data, b2->data, b1->len) == 0);
597
598   g_byte_array_unref (b1);
599   g_byte_array_unref (b2);
600
601   return equal;
602 }