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