Trivial formatting fix
[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 certificate only (eg, the certificate
39  * received by a client from a server), or the combination of
40  * a certificate 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.
102    * This property and the #GTlsCertificate:certificate-pem property
103    * represent the same data, just in different forms.
104    *
105    * Since: 2.28
106    */
107   g_object_class_install_property (gobject_class, PROP_CERTIFICATE,
108                                    g_param_spec_boxed ("certificate",
109                                                        P_("Certificate"),
110                                                        P_("The DER representation of the certificate"),
111                                                        G_TYPE_BYTE_ARRAY,
112                                                        G_PARAM_READWRITE |
113                                                        G_PARAM_CONSTRUCT_ONLY |
114                                                        G_PARAM_STATIC_STRINGS));
115   /**
116    * GTlsCertificate:certificate-pem:
117    *
118    * The PEM (ASCII) encoded representation of the certificate.
119    * This property and the #GTlsCertificate:certificate
120    * property represent the same data, just in different forms.
121    *
122    * Since: 2.28
123    */
124   g_object_class_install_property (gobject_class, PROP_CERTIFICATE_PEM,
125                                    g_param_spec_string ("certificate-pem",
126                                                         P_("Certificate (PEM)"),
127                                                         P_("The PEM representation of the certificate"),
128                                                         NULL,
129                                                         G_PARAM_READWRITE |
130                                                         G_PARAM_CONSTRUCT_ONLY |
131                                                         G_PARAM_STATIC_STRINGS));
132   /**
133    * GTlsCertificate:private-key:
134    *
135    * The DER (binary) encoded representation of the certificate's
136    * private key, in either PKCS#1 format or unencrypted PKCS#8
137    * format. This property (or the #GTlsCertificate:private-key-pem
138    * property) can be set when constructing a key (eg, from a file),
139    * but cannot be read.
140    *
141    * PKCS#8 format is supported since 2.32; earlier releases only
142    * support PKCS#1. You can use the <literal>openssl rsa</literal>
143    * tool to convert PKCS#8 keys to PKCS#1.
144    *
145    * Since: 2.28
146    */
147   g_object_class_install_property (gobject_class, PROP_PRIVATE_KEY,
148                                    g_param_spec_boxed ("private-key",
149                                                        P_("Private key"),
150                                                        P_("The DER representation of the certificate's private key"),
151                                                        G_TYPE_BYTE_ARRAY,
152                                                        G_PARAM_WRITABLE |
153                                                        G_PARAM_CONSTRUCT_ONLY |
154                                                        G_PARAM_STATIC_STRINGS));
155   /**
156    * GTlsCertificate:private-key-pem:
157    *
158    * The PEM (ASCII) encoded representation of the certificate's
159    * private key in either PKCS#1 format ("<literal>BEGIN RSA PRIVATE
160    * KEY</literal>") or unencrypted PKCS#8 format ("<literal>BEGIN
161    * PRIVATE KEY</literal>"). This property (or the
162    * #GTlsCertificate:private-key property) can be set when
163    * constructing a key (eg, from a file), but cannot be read.
164    *
165    * PKCS#8 format is supported since 2.32; earlier releases only
166    * support PKCS#1. You can use the <literal>openssl rsa</literal>
167    * tool to convert PKCS#8 keys to PKCS#1.
168    *
169    * Since: 2.28
170    */
171   g_object_class_install_property (gobject_class, PROP_PRIVATE_KEY_PEM,
172                                    g_param_spec_string ("private-key-pem",
173                                                         P_("Private key (PEM)"),
174                                                         P_("The PEM representation of the certificate's private key"),
175                                                         NULL,
176                                                         G_PARAM_WRITABLE |
177                                                         G_PARAM_CONSTRUCT_ONLY |
178                                                         G_PARAM_STATIC_STRINGS));
179   /**
180    * GTlsCertificate:issuer:
181    *
182    * A #GTlsCertificate representing the entity that issued this
183    * certificate. If %NULL, this means that the certificate is either
184    * self-signed, or else the certificate of the issuer is not
185    * available.
186    *
187    * Since: 2.28
188    */
189   g_object_class_install_property (gobject_class, PROP_ISSUER,
190                                    g_param_spec_object ("issuer",
191                                                         P_("Issuer"),
192                                                         P_("The certificate for the issuing entity"),
193                                                         G_TYPE_TLS_CERTIFICATE,
194                                                         G_PARAM_READWRITE |
195                                                         G_PARAM_CONSTRUCT_ONLY |
196                                                         G_PARAM_STATIC_STRINGS));
197 }
198
199 static GTlsCertificate *
200 g_tls_certificate_new_internal (const gchar  *certificate_pem,
201                                 const gchar  *private_key_pem,
202                                 GError      **error)
203 {
204   GObject *cert;
205   GTlsBackend *backend;
206
207   backend = g_tls_backend_get_default ();
208
209   cert = g_initable_new (g_tls_backend_get_certificate_type (backend),
210                          NULL, error,
211                          "certificate-pem", certificate_pem,
212                          "private-key-pem", private_key_pem,
213                          NULL);
214   return G_TLS_CERTIFICATE (cert);
215 }
216
217 #define PEM_CERTIFICATE_HEADER     "-----BEGIN CERTIFICATE-----"
218 #define PEM_CERTIFICATE_FOOTER     "-----END CERTIFICATE-----"
219 #define PEM_PKCS1_PRIVKEY_HEADER   "-----BEGIN RSA PRIVATE KEY-----"
220 #define PEM_PKCS1_PRIVKEY_FOOTER   "-----END RSA PRIVATE KEY-----"
221 #define PEM_PKCS8_PRIVKEY_HEADER   "-----BEGIN PRIVATE KEY-----"
222 #define PEM_PKCS8_PRIVKEY_FOOTER   "-----END PRIVATE KEY-----"
223 #define PEM_PKCS8_ENCRYPTED_HEADER "-----BEGIN ENCRYPTED PRIVATE KEY-----"
224 #define PEM_PKCS8_ENCRYPTED_FOOTER "-----END ENCRYPTED PRIVATE KEY-----"
225
226 static gchar *
227 parse_private_key (const gchar *data,
228                    gsize data_len,
229                    gboolean required,
230                    GError **error)
231 {
232   const gchar *start, *end, *footer;
233
234   start = g_strstr_len (data, data_len, PEM_PKCS1_PRIVKEY_HEADER);
235   if (start)
236     footer = PEM_PKCS1_PRIVKEY_FOOTER;
237   else
238     {
239       start = g_strstr_len (data, data_len, PEM_PKCS8_PRIVKEY_HEADER);
240       if (start)
241         footer = PEM_PKCS8_PRIVKEY_FOOTER;
242       else
243         {
244           start = g_strstr_len (data, data_len, PEM_PKCS8_ENCRYPTED_HEADER);
245           if (start)
246             {
247               g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
248                                    _("Cannot decrypt PEM-encoded private key"));
249             }
250           else if (required)
251             {
252               g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
253                                    _("No PEM-encoded private key found"));
254             }
255           return NULL;
256         }
257     }
258
259   end = g_strstr_len (start, data_len - (data - start), footer);
260   if (!end)
261     {
262       g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
263                            _("Could not parse PEM-encoded private key"));
264       return NULL;
265     }
266   end += strlen (footer);
267   while (*end == '\r' || *end == '\n')
268     end++;
269
270   return g_strndup (start, end - start);
271 }
272
273
274 static gchar *
275 parse_next_pem_certificate (const gchar **data,
276                             const gchar  *data_end,
277                             gboolean      required,
278                             GError      **error)
279 {
280   const gchar *start, *end;
281
282   start = g_strstr_len (*data, data_end - *data, PEM_CERTIFICATE_HEADER);
283   if (!start)
284     {
285       if (required)
286         {
287           g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
288                                _("No PEM-encoded certificate found"));
289         }
290       return NULL;
291     }
292
293   end = g_strstr_len (start, data_end - start, PEM_CERTIFICATE_FOOTER);
294   if (!end)
295     {
296       g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
297                            _("Could not parse PEM-encoded certificate"));
298       return NULL;
299     }
300   end += strlen (PEM_CERTIFICATE_FOOTER);
301   while (*end == '\r' || *end == '\n')
302     end++;
303
304   *data = end;
305
306   return g_strndup (start, end - start);
307 }
308
309 /**
310  * g_tls_certificate_new_from_pem:
311  * @data: PEM-encoded certificate data
312  * @length: the length of @data, or -1 if it's 0-terminated.
313  * @error: #GError for error reporting, or %NULL to ignore.
314  *
315  * Creates a new #GTlsCertificate from the PEM-encoded data in @data.
316  * If @data includes both a certificate and a private key, then the
317  * returned certificate will include the private key data as well. (See
318  * the #GTlsCertificate:private-key-pem property for information about
319  * supported formats.)
320  *
321  * If @data includes multiple certificates, only the first one will be
322  * parsed.
323  *
324  * Return value: the new certificate, or %NULL if @data is invalid
325  *
326  * Since: 2.28
327  */
328 GTlsCertificate *
329 g_tls_certificate_new_from_pem  (const gchar  *data,
330                                  gssize        length,
331                                  GError      **error)
332 {
333   const gchar *data_end;
334   gchar *key_pem, *cert_pem;
335   GTlsCertificate *cert;
336
337   g_return_val_if_fail (data != NULL, NULL);
338
339   if (length == -1)
340     length = strlen (data);
341
342   data_end = data + length;
343
344   key_pem = parse_private_key (data, length, FALSE, error);
345   if (error && *error)
346     return NULL;
347
348   cert_pem = parse_next_pem_certificate (&data, data_end, TRUE, error);
349   if (error && *error)
350     {
351       g_free (key_pem);
352       return NULL;
353     }
354
355   cert = g_tls_certificate_new_internal (cert_pem, key_pem, error);
356   g_free (key_pem);
357   g_free (cert_pem);
358
359   return cert;
360 }
361
362 /**
363  * g_tls_certificate_new_from_file:
364  * @file: file containing a PEM-encoded certificate to import
365  * @error: #GError for error reporting, or %NULL to ignore.
366  *
367  * Creates a #GTlsCertificate from the PEM-encoded data in @file. If
368  * @file cannot be read or parsed, the function will return %NULL and
369  * set @error. Otherwise, this behaves like
370  * g_tls_certificate_new_from_pem().
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_file (const gchar  *file,
378                                  GError      **error)
379 {
380   GTlsCertificate *cert;
381   gchar *contents;
382   gsize length;
383
384   if (!g_file_get_contents (file, &contents, &length, error))
385     return NULL;
386
387   cert = g_tls_certificate_new_from_pem (contents, length, error);
388   g_free (contents);
389   return cert;
390 }
391
392 /**
393  * g_tls_certificate_new_from_files:
394  * @cert_file: file containing a PEM-encoded certificate to import
395  * @key_file: file containing a PEM-encoded private key to import
396  * @error: #GError for error reporting, or %NULL to ignore.
397  *
398  * Creates a #GTlsCertificate from the PEM-encoded data in @cert_file
399  * and @key_file. If either file cannot be read or parsed, the
400  * function will return %NULL and set @error. Otherwise, this behaves
401  * like g_tls_certificate_new_from_pem().
402  *
403  * Return value: the new certificate, or %NULL on error
404  *
405  * Since: 2.28
406  */
407 GTlsCertificate *
408 g_tls_certificate_new_from_files (const gchar  *cert_file,
409                                   const gchar  *key_file,
410                                   GError      **error)
411 {
412   GTlsCertificate *cert;
413   gchar *cert_data, *key_data;
414   gsize cert_len, key_len;
415   gchar *cert_pem, *key_pem;
416   const gchar *p;
417
418   if (!g_file_get_contents (cert_file, &cert_data, &cert_len, error))
419     return NULL;
420   p = cert_data;
421   cert_pem = parse_next_pem_certificate (&p, p + cert_len, TRUE, error);
422   g_free (cert_data);
423   if (error && *error)
424     return NULL;
425
426   if (!g_file_get_contents (key_file, &key_data, &key_len, error))
427     {
428       g_free (cert_pem);
429       return NULL;
430     }
431   key_pem = parse_private_key (key_data, key_len, TRUE, error);
432   g_free (key_data);
433   if (error && *error)
434     {
435       g_free (cert_pem);
436       return NULL;
437     }
438
439   cert = g_tls_certificate_new_internal (cert_pem, key_pem, error);
440   g_free (cert_pem);
441   g_free (key_pem);
442   return cert;
443 }
444
445 /**
446  * g_tls_certificate_list_new_from_file:
447  * @file: file containing PEM-encoded certificates to import
448  * @error: #GError for error reporting, or %NULL to ignore.
449  *
450  * Creates one or more #GTlsCertificate<!-- -->s from the PEM-encoded
451  * data in @file. If @file cannot be read or parsed, the function will
452  * return %NULL and set @error. If @file does not contain any
453  * PEM-encoded certificates, this will return an empty list and not
454  * set @error.
455  *
456  * Return value: (element-type Gio.TlsCertificate) (transfer full): a
457  * #GList containing #GTlsCertificate objects. You must free the list
458  * and its contents when you are done with it.
459  *
460  * Since: 2.28
461  */
462 GList *
463 g_tls_certificate_list_new_from_file (const gchar  *file,
464                                       GError      **error)
465 {
466   GQueue queue = G_QUEUE_INIT;
467   gchar *contents, *end;
468   const gchar *p;
469   gsize length;
470
471   if (!g_file_get_contents (file, &contents, &length, error))
472     return NULL;
473
474   end = contents + length;
475   p = contents;
476   while (p && *p)
477     {
478       gchar *cert_pem;
479       GTlsCertificate *cert = NULL;
480
481       cert_pem = parse_next_pem_certificate (&p, end, FALSE, error);
482       if (cert_pem)
483         {
484           cert = g_tls_certificate_new_internal (cert_pem, NULL, error);
485           g_free (cert_pem);
486         }
487       if (!cert)
488         {
489           g_list_free_full (queue.head, g_object_unref);
490           queue.head = NULL;
491           break;
492         }
493       g_queue_push_tail (&queue, cert);
494     }
495
496   g_free (contents);
497   return queue.head;
498 }
499
500
501 /**
502  * g_tls_certificate_get_issuer:
503  * @cert: a #GTlsCertificate
504  *
505  * Gets the #GTlsCertificate representing @cert's issuer, if known
506  *
507  * Return value: (transfer none): The certificate of @cert's issuer,
508  * or %NULL if @cert is self-signed or signed with an unknown
509  * certificate.
510  *
511  * Since: 2.28
512  */
513 GTlsCertificate *
514 g_tls_certificate_get_issuer (GTlsCertificate  *cert)
515 {
516   GTlsCertificate *issuer;
517
518   g_object_get (G_OBJECT (cert), "issuer", &issuer, NULL);
519   if (issuer)
520     g_object_unref (issuer);
521
522   return issuer;
523 }
524
525 /**
526  * g_tls_certificate_verify:
527  * @cert: a #GTlsCertificate
528  * @identity: (allow-none): the expected peer identity
529  * @trusted_ca: (allow-none): the certificate of a trusted authority
530  *
531  * This verifies @cert and returns a set of #GTlsCertificateFlags
532  * indicating any problems found with it. This can be used to verify a
533  * certificate outside the context of making a connection, or to
534  * check a certificate against a CA that is not part of the system
535  * CA database.
536  *
537  * If @identity is not %NULL, @cert's name(s) will be compared against
538  * it, and %G_TLS_CERTIFICATE_BAD_IDENTITY will be set in the return
539  * value if it does not match. If @identity is %NULL, that bit will
540  * never be set in the return value.
541  *
542  * If @trusted_ca is not %NULL, then @cert (or one of the certificates
543  * in its chain) must be signed by it, or else
544  * %G_TLS_CERTIFICATE_UNKNOWN_CA will be set in the return value. If
545  * @trusted_ca is %NULL, that bit will never be set in the return
546  * value.
547  *
548  * (All other #GTlsCertificateFlags values will always be set or unset
549  * as appropriate.)
550  *
551  * Return value: the appropriate #GTlsCertificateFlags
552  *
553  * Since: 2.28
554  */
555 GTlsCertificateFlags
556 g_tls_certificate_verify (GTlsCertificate     *cert,
557                           GSocketConnectable  *identity,
558                           GTlsCertificate     *trusted_ca)
559 {
560   return G_TLS_CERTIFICATE_GET_CLASS (cert)->verify (cert, identity, trusted_ca);
561 }
562
563 /**
564  * g_tls_certificate_is_same:
565  * @cert_one: first certificate to compare
566  * @cert_two: second certificate to compare
567  *
568  * Check if two #GTlsCertificate objects represent the same certificate.
569  * The raw DER byte data of the two certificates are checked for equality.
570  * This has the effect that two certificates may compare equal even if
571  * their #GTlsCertificate:issuer, #GTlsCertificate:private-key, or
572  * #GTlsCertificate:private-key-pem properties differ.
573  *
574  * Return value: whether the same or not
575  *
576  * Since: 2.34
577  */
578 gboolean
579 g_tls_certificate_is_same (GTlsCertificate     *cert_one,
580                            GTlsCertificate     *cert_two)
581 {
582   GByteArray *b1, *b2;
583   gboolean equal;
584
585   g_return_val_if_fail (G_IS_TLS_CERTIFICATE (cert_one), FALSE);
586   g_return_val_if_fail (G_IS_TLS_CERTIFICATE (cert_two), FALSE);
587
588   g_object_get (cert_one, "certificate", &b1, NULL);
589   g_object_get (cert_two, "certificate", &b2, NULL);
590
591   equal = (b1->len == b2->len &&
592            memcmp (b1->data, b2->data, b1->len) == 0);
593
594   g_byte_array_unref (b1);
595   g_byte_array_unref (b2);
596
597   return equal;
598 }