Fix two leaks seen when using TLS connections
[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, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 #include "config.h"
22
23 #include "gtlscertificate.h"
24
25 #include <string.h>
26 #include "ginitable.h"
27 #include "gtlsbackend.h"
28 #include "gtlsconnection.h"
29 #include "glibintl.h"
30
31 /**
32  * SECTION:gtlscertificate
33  * @title: GTlsCertificate
34  * @short_description: TLS certificate
35  * @see_also: #GTlsConnection
36  *
37  * A certificate used for TLS authentication and encryption.
38  * This can represent either a public key only (eg, the certificate
39  * received by a client from a server), or the combination of
40  * a public key and a private key (which is needed when acting as a
41  * #GTlsServerConnection).
42  *
43  * Since: 2.28
44  */
45
46 /**
47  * GTlsCertificate:
48  *
49  * Abstract base class for TLS certificate types.
50  *
51  * Since: 2.28
52  */
53
54 G_DEFINE_ABSTRACT_TYPE (GTlsCertificate, g_tls_certificate, G_TYPE_OBJECT);
55
56 enum
57 {
58   PROP_0,
59
60   PROP_CERTIFICATE,
61   PROP_CERTIFICATE_PEM,
62   PROP_PRIVATE_KEY,
63   PROP_PRIVATE_KEY_PEM,
64   PROP_ISSUER
65 };
66
67 static void
68 g_tls_certificate_init (GTlsCertificate *cert)
69 {
70 }
71
72 static void
73 g_tls_certificate_get_property (GObject    *object,
74                                 guint       prop_id,
75                                 GValue     *value,
76                                 GParamSpec *pspec)
77 {
78   G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
79 }
80
81 static void
82 g_tls_certificate_set_property (GObject      *object,
83                                 guint         prop_id,
84                                 const GValue *value,
85                                 GParamSpec   *pspec)
86 {
87   G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
88 }
89
90 static void
91 g_tls_certificate_class_init (GTlsCertificateClass *class)
92 {
93   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
94
95   gobject_class->set_property = g_tls_certificate_set_property;
96   gobject_class->get_property = g_tls_certificate_get_property;
97
98   /**
99    * GTlsCertificate:certificate:
100    *
101    * The DER (binary) encoded representation of the certificate's
102    * public key. This property and the
103    * #GTlsCertificate:certificate-pem property represent the same
104    * data, just in different forms.
105    *
106    * Since: 2.28
107    */
108   g_object_class_install_property (gobject_class, PROP_CERTIFICATE,
109                                    g_param_spec_boxed ("certificate",
110                                                        P_("Certificate"),
111                                                        P_("The DER representation of the certificate"),
112                                                        G_TYPE_BYTE_ARRAY,
113                                                        G_PARAM_READWRITE |
114                                                        G_PARAM_CONSTRUCT_ONLY |
115                                                        G_PARAM_STATIC_STRINGS));
116   /**
117    * GTlsCertificate:certificate-pem:
118    *
119    * The PEM (ASCII) encoded representation of the certificate's
120    * public key. This property and the #GTlsCertificate:certificate
121    * property represent the same data, just in different forms.
122    *
123    * Since: 2.28
124    */
125   g_object_class_install_property (gobject_class, PROP_CERTIFICATE_PEM,
126                                    g_param_spec_string ("certificate-pem",
127                                                         P_("Certificate (PEM)"),
128                                                         P_("The PEM representation of the certificate"),
129                                                         NULL,
130                                                         G_PARAM_READWRITE |
131                                                         G_PARAM_CONSTRUCT_ONLY |
132                                                         G_PARAM_STATIC_STRINGS));
133   /**
134    * GTlsCertificate:private-key:
135    *
136    * The DER (binary) encoded representation of the certificate's
137    * private key. This property (or the
138    * #GTlsCertificate:private-key-pem property) can be set when
139    * constructing a key (eg, from a file), but cannot be read.
140    *
141    * Since: 2.28
142    */
143   g_object_class_install_property (gobject_class, PROP_PRIVATE_KEY,
144                                    g_param_spec_boxed ("private-key",
145                                                        P_("Private key"),
146                                                        P_("The DER representation of the certificate's private key"),
147                                                        G_TYPE_BYTE_ARRAY,
148                                                        G_PARAM_WRITABLE |
149                                                        G_PARAM_CONSTRUCT_ONLY |
150                                                        G_PARAM_STATIC_STRINGS));
151   /**
152    * GTlsCertificate:private-key-pem:
153    *
154    * The PEM (ASCII) encoded representation of the certificate's
155    * private key. This property (or the #GTlsCertificate:private-key
156    * property) can be set when constructing a key (eg, from a file),
157    * but cannot be read.
158    *
159    * Since: 2.28
160    */
161   g_object_class_install_property (gobject_class, PROP_PRIVATE_KEY_PEM,
162                                    g_param_spec_string ("private-key-pem",
163                                                         P_("Private key (PEM)"),
164                                                         P_("The PEM representation of the certificate's private key"),
165                                                         NULL,
166                                                         G_PARAM_WRITABLE |
167                                                         G_PARAM_CONSTRUCT_ONLY |
168                                                         G_PARAM_STATIC_STRINGS));
169   /**
170    * GTlsCertificate:issuer:
171    *
172    * A #GTlsCertificate representing the entity that issued this
173    * certificate. If %NULL, this means that the certificate is either
174    * self-signed, or else the certificate of the issuer is not
175    * available.
176    *
177    * Since: 2.28
178    */
179   g_object_class_install_property (gobject_class, PROP_ISSUER,
180                                    g_param_spec_object ("issuer",
181                                                         P_("Issuer"),
182                                                         P_("The certificate for the issuing entity"),
183                                                         G_TYPE_TLS_CERTIFICATE,
184                                                         G_PARAM_READWRITE |
185                                                         G_PARAM_CONSTRUCT_ONLY |
186                                                         G_PARAM_STATIC_STRINGS));
187 }
188
189 static GTlsCertificate *
190 g_tls_certificate_new_internal (const gchar  *certificate_pem,
191                                 const gchar  *private_key_pem,
192                                 GError      **error)
193 {
194   GObject *cert;
195   GTlsBackend *backend;
196
197   backend = g_tls_backend_get_default ();
198
199   cert = g_initable_new (g_tls_backend_get_certificate_type (backend),
200                          NULL, error,
201                          "certificate-pem", certificate_pem,
202                          "private-key-pem", private_key_pem,
203                          NULL);
204   return G_TLS_CERTIFICATE (cert);
205 }
206
207 #define PEM_CERTIFICATE_HEADER "-----BEGIN CERTIFICATE-----"
208 #define PEM_CERTIFICATE_FOOTER "-----END CERTIFICATE-----"
209 #define PEM_PRIVKEY_HEADER     "-----BEGIN RSA PRIVATE KEY-----"
210 #define PEM_PRIVKEY_FOOTER     "-----END RSA PRIVATE KEY-----"
211
212 static GTlsCertificate *
213 parse_next_pem_certificate (const gchar **data,
214                             const gchar  *data_end,
215                             gboolean      required,
216                             GError      **error)
217 {
218   const gchar *start, *end, *next;
219   gchar *cert_pem, *privkey_pem = NULL;
220   GTlsCertificate *cert;
221
222   start = g_strstr_len (*data, data_end - *data, PEM_CERTIFICATE_HEADER);
223   if (!start)
224     {
225       if (required)
226         {
227           g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
228                                _("No PEM-encoded certificate found"));
229         }
230       return NULL;
231     }
232
233   end = g_strstr_len (start, data_end - start, PEM_CERTIFICATE_FOOTER);
234   if (!end)
235     {
236       g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
237                            _("Could not parse PEM-encoded certificate"));
238       return NULL;
239     }
240   end += strlen (PEM_CERTIFICATE_FOOTER);
241   while (*end == '\r' || *end == '\n')
242     end++;
243
244   cert_pem = g_strndup (start, end - start);
245
246   *data = end;
247
248   next = g_strstr_len (*data, data_end - *data, PEM_CERTIFICATE_HEADER);
249   start = g_strstr_len (*data, data_end - *data, PEM_PRIVKEY_HEADER);
250   if (start)
251     end = g_strstr_len (start, data_end - start, PEM_PRIVKEY_FOOTER);
252
253   if (start && (!next || start < next))
254     {
255       if (!end || (next && end > next))
256         {
257           g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
258                                _("Could not parse PEM-encoded private key"));
259           return NULL;
260         }
261
262       end += strlen (PEM_PRIVKEY_FOOTER);
263       while (*end == '\r' || *end == '\n')
264         end++;
265
266       privkey_pem = g_strndup (start, end - start);
267
268       *data = end + strlen (PEM_PRIVKEY_FOOTER);
269     }
270
271   cert = g_tls_certificate_new_internal (cert_pem, privkey_pem, error);
272   g_free (cert_pem);
273   g_free (privkey_pem);
274
275   return cert;
276 }
277
278 /**
279  * g_tls_certificate_new_from_pem:
280  * @data: PEM-encoded certificate data
281  * @length: the length of @data, or -1 if it's 0-terminated.
282  * @error: #GError for error reporting, or %NULL to ignore.
283  *
284  * Creates a new #GTlsCertificate from the PEM-encoded data in @data.
285  * If @data includes both a certificate and a private key, then the
286  * returned certificate will include the private key data as well.
287  *
288  * If @data includes multiple certificates, only the first one will be
289  * parsed.
290  *
291  * Return value: the new certificate, or %NULL if @data is invalid
292  *
293  * Since: 2.28
294  */
295 GTlsCertificate *
296 g_tls_certificate_new_from_pem  (const gchar  *data,
297                                  gssize        length,
298                                  GError      **error)
299 {
300   const gchar *data_end;
301
302   g_return_val_if_fail (data != NULL, NULL);
303
304   if (length == -1)
305     data_end = data + strlen (data);
306   else
307     data_end = data + length;
308   return parse_next_pem_certificate (&data, data_end, TRUE, error);
309 }
310
311 /**
312  * g_tls_certificate_new_from_file:
313  * @file: file containing a PEM-encoded certificate to import
314  * @error: #GError for error reporting, or %NULL to ignore.
315  *
316  * Creates a #GTlsCertificate from the PEM-encoded data in @file. If
317  * @file cannot be read or parsed, the function will return %NULL and
318  * set @error. Otherwise, this behaves like g_tls_certificate_new().
319  *
320  * Return value: the new certificate, or %NULL on error
321  *
322  * Since: 2.28
323  */
324 GTlsCertificate *
325 g_tls_certificate_new_from_file (const gchar  *file,
326                                  GError      **error)
327 {
328   GTlsCertificate *cert;
329   gchar *contents;
330   gsize length;
331
332   if (!g_file_get_contents (file, &contents, &length, error))
333     return NULL;
334
335   cert = g_tls_certificate_new_from_pem (contents, length, error);
336   g_free (contents);
337   return cert;
338 }
339
340 /**
341  * g_tls_certificate_new_from_files:
342  * @cert_file: file containing a PEM-encoded certificate to import
343  * @key_file: file containing a PEM-encoded private key to import
344  * @error: #GError for error reporting, or %NULL to ignore.
345  *
346  * Creates a #GTlsCertificate from the PEM-encoded data in @cert_file
347  * and @key_file. If either file cannot be read or parsed, the
348  * function will return %NULL and set @error. Otherwise, this behaves
349  * like g_tls_certificate_new().
350  *
351  * Return value: the new certificate, or %NULL on error
352  *
353  * Since: 2.28
354  */
355 GTlsCertificate *
356 g_tls_certificate_new_from_files (const gchar  *cert_file,
357                                   const gchar  *key_file,
358                                   GError      **error)
359 {
360   GTlsCertificate *cert;
361   gchar *cert_data, *key_data;
362
363   if (!g_file_get_contents (cert_file, &cert_data, NULL, error))
364     return NULL;
365   if (!g_file_get_contents (key_file, &key_data, NULL, error))
366     {
367       g_free (cert_data);
368       return NULL;
369     }
370
371   cert = g_tls_certificate_new_internal (cert_data, key_data, error);
372   g_free (cert_data);
373   g_free (key_data);
374   return cert;
375 }
376
377 /**
378  * g_tls_certificate_list_new_from_file:
379  * @file: file containing PEM-encoded certificates to import
380  * @error: #GError for error reporting, or %NULL to ignore.
381  *
382  * Creates one or more #GTlsCertificate<!-- -->s from the PEM-encoded
383  * data in @file. If @file cannot be read or parsed, the function will
384  * return %NULL and set @error. If @file does not contain any
385  * PEM-encoded certificates, this will return an empty list and not
386  * set @error.
387  *
388  * Return value: (element-type Gio.TlsCertificate) (transfer full): a
389  * #GList containing #GTlsCertificate objects. You must free the list
390  * and its contents when you are done with it.
391  *
392  * Since: 2.28
393  */
394 GList *
395 g_tls_certificate_list_new_from_file (const gchar  *file,
396                                       GError      **error)
397 {
398   GTlsCertificate *cert;
399   GList *list, *l;
400   gchar *contents, *end;
401   const gchar *p;
402   gsize length;
403
404   if (!g_file_get_contents (file, &contents, &length, error))
405     return NULL;
406
407   list = NULL;
408   end = contents + length;
409   p = contents;
410   while (p && *p)
411     {
412       cert = parse_next_pem_certificate (&p, end, FALSE, error);
413       if (!cert)
414         {
415           for (l = list; l; l = l->next)
416             g_object_unref (l->data);
417           g_list_free (list);
418           list = NULL;
419           break;
420         }
421       list = g_list_prepend (list, cert);
422     }
423
424   g_free (contents);
425   return g_list_reverse (list);
426 }
427
428
429 /**
430  * g_tls_certificate_get_issuer:
431  * @cert: a #GTlsCertificate
432  *
433  * Gets the #GTlsCertificate representing @cert's issuer, if known
434  *
435  * Return value: (transfer none): The certificate of @cert's issuer,
436  * or %NULL if @cert is self-signed or signed with an unknown
437  * certificate.
438  *
439  * Since: 2.28
440  */
441 GTlsCertificate *
442 g_tls_certificate_get_issuer (GTlsCertificate  *cert)
443 {
444   GTlsCertificate *issuer;
445
446   g_object_get (G_OBJECT (cert), "issuer", &issuer, NULL);
447   if (issuer)
448     g_object_unref (issuer);
449
450   return issuer;
451 }
452
453 /**
454  * g_tls_certificate_verify:
455  * @cert: a #GTlsCertificate
456  * @identity: (allow-none): the expected peer identity
457  * @trusted_ca: (allow-none): the certificate of a trusted authority
458  *
459  * This verifies @cert and returns a set of #GTlsCertificateFlags
460  * indicating any problems found with it. This can be used to verify a
461  * certificate outside the context of making a connection, or to
462  * check a certificate against a CA that is not part of the system
463  * CA database.
464  *
465  * If @identity is not %NULL, @cert's name(s) will be compared against
466  * it, and %G_TLS_CERTIFICATE_BAD_IDENTITY will be set in the return
467  * value if it does not match. If @identity is %NULL, that bit will
468  * never be set in the return value.
469  *
470  * If @trusted_ca is not %NULL, then @cert (or one of the certificates
471  * in its chain) must be signed by it, or else
472  * %G_TLS_CERTIFICATE_UNKNOWN_CA will be set in the return value. If
473  * @trusted_ca is %NULL, that bit will never be set in the return
474  * value.
475  *
476  * (All other #GTlsCertificateFlags values will always be set or unset
477  * as appropriate.)
478  *
479  * Return value: the appropriate #GTlsCertificateFlags
480  *
481  * Since: 2.28
482  */
483 GTlsCertificateFlags
484 g_tls_certificate_verify (GTlsCertificate     *cert,
485                           GSocketConnectable  *identity,
486                           GTlsCertificate     *trusted_ca)
487 {
488   return G_TLS_CERTIFICATE_GET_CLASS (cert)->verify (cert, identity, trusted_ca);
489 }