Spelling fixes
[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 gchar *
213 parse_private_key (const gchar *data,
214                    gsize data_len,
215                    gboolean required,
216                    GError **error)
217 {
218   const gchar *start, *end;
219
220   start = g_strstr_len (data, data_len, PEM_PRIVKEY_HEADER);
221   if (!start)
222     {
223       if (required)
224         {
225           g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
226                                _("No PEM-encoded private key found"));
227         }
228       return NULL;
229     }
230
231   end = g_strstr_len (start, data_len - (data - start), PEM_PRIVKEY_FOOTER);
232   if (!end)
233     {
234       g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
235                            _("Could not parse PEM-encoded private key"));
236       return NULL;
237     }
238   end += strlen (PEM_PRIVKEY_FOOTER);
239   while (*end == '\r' || *end == '\n')
240     end++;
241
242   return g_strndup (start, end - start);
243 }
244
245
246 gchar *
247 parse_next_pem_certificate (const gchar **data,
248                             const gchar  *data_end,
249                             gboolean      required,
250                             GError      **error)
251 {
252   const gchar *start, *end;
253
254   start = g_strstr_len (*data, data_end - *data, PEM_CERTIFICATE_HEADER);
255   if (!start)
256     {
257       if (required)
258         {
259           g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
260                                _("No PEM-encoded certificate found"));
261         }
262       return NULL;
263     }
264
265   end = g_strstr_len (start, data_end - start, PEM_CERTIFICATE_FOOTER);
266   if (!end)
267     {
268       g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
269                            _("Could not parse PEM-encoded certificate"));
270       return NULL;
271     }
272   end += strlen (PEM_CERTIFICATE_FOOTER);
273   while (*end == '\r' || *end == '\n')
274     end++;
275
276   *data = end;
277
278   return g_strndup (start, end - start);
279 }
280
281 /**
282  * g_tls_certificate_new_from_pem:
283  * @data: PEM-encoded certificate data
284  * @length: the length of @data, or -1 if it's 0-terminated.
285  * @error: #GError for error reporting, or %NULL to ignore.
286  *
287  * Creates a new #GTlsCertificate from the PEM-encoded data in @data.
288  * If @data includes both a certificate and a private key, then the
289  * returned certificate will include the private key data as well.
290  *
291  * If @data includes multiple certificates, only the first one will be
292  * parsed.
293  *
294  * Return value: the new certificate, or %NULL if @data is invalid
295  *
296  * Since: 2.28
297  */
298 GTlsCertificate *
299 g_tls_certificate_new_from_pem  (const gchar  *data,
300                                  gssize        length,
301                                  GError      **error)
302 {
303   const gchar *data_end;
304   gchar *key_pem, *cert_pem;
305   GTlsCertificate *cert;
306
307   g_return_val_if_fail (data != NULL, NULL);
308
309   if (length == -1)
310     length = strlen (data);
311
312   data_end = data + length;
313
314   key_pem = parse_private_key (data, length, FALSE, error);
315   if (error && *error)
316     return NULL;
317
318   cert_pem = parse_next_pem_certificate (&data, data_end, TRUE, error);
319   if (error && *error)
320     {
321       g_free (key_pem);
322       return NULL;
323     }
324
325   cert = g_tls_certificate_new_internal (cert_pem, key_pem, error);
326   g_free (key_pem);
327   g_free (cert_pem);
328
329   return cert;
330 }
331
332 /**
333  * g_tls_certificate_new_from_file:
334  * @file: file containing a PEM-encoded certificate to import
335  * @error: #GError for error reporting, or %NULL to ignore.
336  *
337  * Creates a #GTlsCertificate from the PEM-encoded data in @file. If
338  * @file cannot be read or parsed, the function will return %NULL and
339  * set @error. Otherwise, this behaves like g_tls_certificate_new().
340  *
341  * Return value: the new certificate, or %NULL on error
342  *
343  * Since: 2.28
344  */
345 GTlsCertificate *
346 g_tls_certificate_new_from_file (const gchar  *file,
347                                  GError      **error)
348 {
349   GTlsCertificate *cert;
350   gchar *contents;
351   gsize length;
352
353   if (!g_file_get_contents (file, &contents, &length, error))
354     return NULL;
355
356   cert = g_tls_certificate_new_from_pem (contents, length, error);
357   g_free (contents);
358   return cert;
359 }
360
361 /**
362  * g_tls_certificate_new_from_files:
363  * @cert_file: file containing a PEM-encoded certificate to import
364  * @key_file: file containing a PEM-encoded private key to import
365  * @error: #GError for error reporting, or %NULL to ignore.
366  *
367  * Creates a #GTlsCertificate from the PEM-encoded data in @cert_file
368  * and @key_file. If either file cannot be read or parsed, the
369  * function will return %NULL and set @error. Otherwise, this behaves
370  * like g_tls_certificate_new().
371  *
372  * Return value: the new certificate, or %NULL on error
373  *
374  * Since: 2.28
375  */
376 GTlsCertificate *
377 g_tls_certificate_new_from_files (const gchar  *cert_file,
378                                   const gchar  *key_file,
379                                   GError      **error)
380 {
381   GTlsCertificate *cert;
382   gchar *cert_data, *key_data;
383   gsize cert_len, key_len;
384   gchar *cert_pem, *key_pem;
385   const gchar *p;
386
387   if (!g_file_get_contents (cert_file, &cert_data, &cert_len, error))
388     return NULL;
389   p = cert_data;
390   cert_pem = parse_next_pem_certificate (&p, p + cert_len, TRUE, error);
391   g_free (cert_data);
392   if (error && *error)
393     return NULL;
394
395   if (!g_file_get_contents (key_file, &key_data, &key_len, error))
396     {
397       g_free (cert_pem);
398       return NULL;
399     }
400   key_pem = parse_private_key (key_data, key_len, TRUE, error);
401   g_free (key_data);
402   if (error && *error)
403     {
404       g_free (cert_pem);
405       return NULL;
406     }
407
408   cert = g_tls_certificate_new_internal (cert_pem, key_pem, error);
409   g_free (cert_pem);
410   g_free (key_pem);
411   return cert;
412 }
413
414 /**
415  * g_tls_certificate_list_new_from_file:
416  * @file: file containing PEM-encoded certificates to import
417  * @error: #GError for error reporting, or %NULL to ignore.
418  *
419  * Creates one or more #GTlsCertificate<!-- -->s from the PEM-encoded
420  * data in @file. If @file cannot be read or parsed, the function will
421  * return %NULL and set @error. If @file does not contain any
422  * PEM-encoded certificates, this will return an empty list and not
423  * set @error.
424  *
425  * Return value: (element-type Gio.TlsCertificate) (transfer full): a
426  * #GList containing #GTlsCertificate objects. You must free the list
427  * and its contents when you are done with it.
428  *
429  * Since: 2.28
430  */
431 GList *
432 g_tls_certificate_list_new_from_file (const gchar  *file,
433                                       GError      **error)
434 {
435   GQueue queue = G_QUEUE_INIT;
436   gchar *contents, *end;
437   const gchar *p;
438   gsize length;
439
440   if (!g_file_get_contents (file, &contents, &length, error))
441     return NULL;
442
443   end = contents + length;
444   p = contents;
445   while (p && *p)
446     {
447       gchar *cert_pem;
448       GTlsCertificate *cert = NULL;
449
450       cert_pem = parse_next_pem_certificate (&p, end, FALSE, error);
451       if (cert_pem)
452         {
453           cert = g_tls_certificate_new_internal (cert_pem, NULL, error);
454           g_free (cert_pem);
455         }
456       if (!cert)
457         {
458           g_list_free_full (queue.head, g_object_unref);
459           queue.head = NULL;
460           break;
461         }
462       g_queue_push_tail (&queue, cert);
463     }
464
465   g_free (contents);
466   return queue.head;
467 }
468
469
470 /**
471  * g_tls_certificate_get_issuer:
472  * @cert: a #GTlsCertificate
473  *
474  * Gets the #GTlsCertificate representing @cert's issuer, if known
475  *
476  * Return value: (transfer none): The certificate of @cert's issuer,
477  * or %NULL if @cert is self-signed or signed with an unknown
478  * certificate.
479  *
480  * Since: 2.28
481  */
482 GTlsCertificate *
483 g_tls_certificate_get_issuer (GTlsCertificate  *cert)
484 {
485   GTlsCertificate *issuer;
486
487   g_object_get (G_OBJECT (cert), "issuer", &issuer, NULL);
488   if (issuer)
489     g_object_unref (issuer);
490
491   return issuer;
492 }
493
494 /**
495  * g_tls_certificate_verify:
496  * @cert: a #GTlsCertificate
497  * @identity: (allow-none): the expected peer identity
498  * @trusted_ca: (allow-none): the certificate of a trusted authority
499  *
500  * This verifies @cert and returns a set of #GTlsCertificateFlags
501  * indicating any problems found with it. This can be used to verify a
502  * certificate outside the context of making a connection, or to
503  * check a certificate against a CA that is not part of the system
504  * CA database.
505  *
506  * If @identity is not %NULL, @cert's name(s) will be compared against
507  * it, and %G_TLS_CERTIFICATE_BAD_IDENTITY will be set in the return
508  * value if it does not match. If @identity is %NULL, that bit will
509  * never be set in the return value.
510  *
511  * If @trusted_ca is not %NULL, then @cert (or one of the certificates
512  * in its chain) must be signed by it, or else
513  * %G_TLS_CERTIFICATE_UNKNOWN_CA will be set in the return value. If
514  * @trusted_ca is %NULL, that bit will never be set in the return
515  * value.
516  *
517  * (All other #GTlsCertificateFlags values will always be set or unset
518  * as appropriate.)
519  *
520  * Return value: the appropriate #GTlsCertificateFlags
521  *
522  * Since: 2.28
523  */
524 GTlsCertificateFlags
525 g_tls_certificate_verify (GTlsCertificate     *cert,
526                           GSocketConnectable  *identity,
527                           GTlsCertificate     *trusted_ca)
528 {
529   return G_TLS_CERTIFICATE_GET_CLASS (cert)->verify (cert, identity, trusted_ca);
530 }