]> git.sesse.net Git - vlc/blob - modules/misc/gnutls.c
gnutls: print error if key storage fails
[vlc] / modules / misc / gnutls.c
1 /*****************************************************************************
2  * gnutls.c
3  *****************************************************************************
4  * Copyright (C) 2004-2012 Rémi Denis-Courmont
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License as published by
8  * the Free Software Foundation; either version 2.1 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Öesser General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
19  *****************************************************************************/
20
21 /*****************************************************************************
22  * Preamble
23  *****************************************************************************/
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include <time.h>
30 #include <errno.h>
31 #include <assert.h>
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <vlc_tls.h>
36 #include <vlc_block.h>
37 #include <vlc_dialog.h>
38
39 #include <gnutls/gnutls.h>
40 #include <gnutls/x509.h>
41 #if (GNUTLS_VERSION_NUMBER < 0x030014)
42 # define gnutls_certificate_set_x509_system_trust(c) \
43     (c, GNUTLS_E_UNIMPLEMENTED_FEATURE)
44 #endif
45 #if (GNUTLS_VERSION_NUMBER < 0x03000D)
46 # define gnutls_verify_stored_pubkey(db,tdb,host,serv,ctype,cert,fl) \
47     (db, host, serv, ctype, cert, fl, GNUTLS_E_NO_CERTIFICATE_FOUND)
48 # define gnutls_store_pubkey(db,tdb,host,serv,ctype,cert,e,fl) \
49     (db, host, serv, ctype, cert, fl, GNUTLS_E_UNIMPLEMENTED_FEATURE)
50 #endif
51 #include "dhparams.h"
52
53 /*****************************************************************************
54  * Module descriptor
55  *****************************************************************************/
56 static int  OpenClient  (vlc_tls_creds_t *);
57 static void CloseClient (vlc_tls_creds_t *);
58 static int  OpenServer  (vlc_tls_creds_t *, const char *, const char *);
59 static void CloseServer (vlc_tls_creds_t *);
60
61 #define PRIORITIES_TEXT N_("TLS cipher priorities")
62 #define PRIORITIES_LONGTEXT N_("Ciphers, key exchange methods, " \
63     "hash functions and compression methods can be selected. " \
64     "Refer to GNU TLS documentation for detailed syntax.")
65 static const char *const priorities_values[] = {
66     "PERFORMANCE",
67     "NORMAL",
68     "SECURE128",
69     "SECURE256",
70     "EXPORT",
71 };
72 static const char *const priorities_text[] = {
73     N_("Performance (prioritize faster ciphers)"),
74     N_("Normal"),
75     N_("Secure 128-bits (exclude 256-bits ciphers)"),
76     N_("Secure 256-bits (prioritize 256-bits ciphers)"),
77     N_("Export (include insecure ciphers)"),
78 };
79
80 vlc_module_begin ()
81     set_shortname( "GNU TLS" )
82     set_description( N_("GNU TLS transport layer security") )
83     set_capability( "tls client", 1 )
84     set_callbacks( OpenClient, CloseClient )
85     set_category( CAT_ADVANCED )
86     set_subcategory( SUBCAT_ADVANCED_MISC )
87
88     add_submodule ()
89         set_description( N_("GNU TLS server") )
90         set_capability( "tls server", 1 )
91         set_category( CAT_ADVANCED )
92         set_subcategory( SUBCAT_ADVANCED_MISC )
93         set_callbacks( OpenServer, CloseServer )
94
95         add_string ("gnutls-priorities", "NORMAL", PRIORITIES_TEXT,
96                     PRIORITIES_LONGTEXT, false)
97             change_string_list (priorities_values, priorities_text)
98 vlc_module_end ()
99
100 static vlc_mutex_t gnutls_mutex = VLC_STATIC_MUTEX;
101
102 /**
103  * Initializes GnuTLS with proper locking.
104  * @return VLC_SUCCESS on success, a VLC error code otherwise.
105  */
106 static int gnutls_Init (vlc_object_t *p_this)
107 {
108     int ret = VLC_EGENERIC;
109
110     vlc_mutex_lock (&gnutls_mutex);
111     if (gnutls_global_init ())
112     {
113         msg_Err (p_this, "cannot initialize GnuTLS");
114         goto error;
115     }
116
117     const char *psz_version = gnutls_check_version ("2.6.6");
118     if (psz_version == NULL)
119     {
120         msg_Err (p_this, "unsupported GnuTLS version");
121         gnutls_global_deinit ();
122         goto error;
123     }
124
125     msg_Dbg (p_this, "GnuTLS v%s initialized", psz_version);
126     ret = VLC_SUCCESS;
127
128 error:
129     vlc_mutex_unlock (&gnutls_mutex);
130     return ret;
131 }
132
133
134 /**
135  * Deinitializes GnuTLS.
136  */
137 static void gnutls_Deinit (vlc_object_t *p_this)
138 {
139     vlc_mutex_lock (&gnutls_mutex);
140
141     gnutls_global_deinit ();
142     msg_Dbg (p_this, "GnuTLS deinitialized");
143     vlc_mutex_unlock (&gnutls_mutex);
144 }
145
146
147 static int gnutls_Error (vlc_object_t *obj, int val)
148 {
149     switch (val)
150     {
151         case GNUTLS_E_AGAIN:
152 #ifdef WIN32
153             WSASetLastError (WSAEWOULDBLOCK);
154 #else
155             errno = EAGAIN;
156 #endif
157             break;
158
159         case GNUTLS_E_INTERRUPTED:
160 #ifdef WIN32
161             WSASetLastError (WSAEINTR);
162 #else
163             errno = EINTR;
164 #endif
165             break;
166
167         default:
168             msg_Err (obj, "%s", gnutls_strerror (val));
169 #ifndef NDEBUG
170             if (!gnutls_error_is_fatal (val))
171                 msg_Err (obj, "Error above should be handled");
172 #endif
173 #ifdef WIN32
174             WSASetLastError (WSAECONNRESET);
175 #else
176             errno = ECONNRESET;
177 #endif
178     }
179     return -1;
180 }
181 #define gnutls_Error(o, val) gnutls_Error(VLC_OBJECT(o), val)
182
183 struct vlc_tls_sys
184 {
185     gnutls_session_t session;
186     bool handshaked;
187 };
188
189
190 /**
191  * Sends data through a TLS session.
192  */
193 static int gnutls_Send (void *opaque, const void *buf, size_t length)
194 {
195     vlc_tls_t *session = opaque;
196     vlc_tls_sys_t *sys = session->sys;
197
198     int val = gnutls_record_send (sys->session, buf, length);
199     return (val < 0) ? gnutls_Error (session, val) : val;
200 }
201
202
203 /**
204  * Receives data through a TLS session.
205  */
206 static int gnutls_Recv (void *opaque, void *buf, size_t length)
207 {
208     vlc_tls_t *session = opaque;
209     vlc_tls_sys_t *sys = session->sys;
210
211     int val = gnutls_record_recv (sys->session, buf, length);
212     return (val < 0) ? gnutls_Error (session, val) : val;
213 }
214
215
216 /**
217  * Starts or continues the TLS handshake.
218  *
219  * @return -1 on fatal error, 0 on successful handshake completion,
220  * 1 if more would-be blocking recv is needed,
221  * 2 if more would-be blocking send is required.
222  */
223 static int gnutls_ContinueHandshake (vlc_tls_t *session, const char *host,
224                                      const char *service)
225 {
226     vlc_tls_sys_t *sys = session->sys;
227     int val;
228
229 #ifdef WIN32
230     WSASetLastError (0);
231 #endif
232     val = gnutls_handshake (sys->session);
233     if ((val == GNUTLS_E_AGAIN) || (val == GNUTLS_E_INTERRUPTED))
234         return 1 + gnutls_record_get_direction (sys->session);
235
236     if (val < 0)
237     {
238 #ifdef WIN32
239         msg_Dbg (session, "Winsock error %d", WSAGetLastError ());
240 #endif
241         msg_Err (session, "TLS handshake error: %s", gnutls_strerror (val));
242         return -1;
243     }
244
245     sys->handshaked = true;
246     (void) host; (void) service;
247     return 0;
248 }
249
250
251 /**
252  * Looks up certificate in known hosts data base.
253  * @return 0 on success, -1 on failure.
254  */
255 static int gnutls_CertSearch (vlc_tls_t *obj, const char *host,
256                               const char *service,
257                               const gnutls_datum_t *restrict datum)
258 {
259     assert (host != NULL);
260     /* Look up mismatching certificate in store */
261     int val = gnutls_verify_stored_pubkey (NULL, NULL, host, service,
262                                            GNUTLS_CRT_X509, datum, 0);
263     switch (val)
264     {
265         case 0:
266             msg_Dbg (obj, "certificate key match for %s", host);
267             return 0;
268         case GNUTLS_E_NO_CERTIFICATE_FOUND:
269             msg_Dbg (obj, "no known certificates for %s", host);
270             break;
271         case GNUTLS_E_CERTIFICATE_KEY_MISMATCH:
272             msg_Dbg (obj, "certificate keys mismatch for %s", host);
273             break;
274         default:
275             msg_Err (obj, "certificate key match error for %s: %s", host,
276                      gnutls_strerror (val));
277             return -1;
278     }
279
280     if (dialog_Question (obj, _("Insecure site"),
281          _("You attempted to reach %s, but security certificate presented by "
282            "the server could not be verified."
283            "This problem may be caused by a configuration error "
284            "on the server or by a serious breach of network security.\n\n"
285            "If in doubt, abort now.\n"),
286                          _("Abort"), _("View certificate"), NULL, host) != 2)
287          return -1;
288
289     gnutls_x509_crt_t cert;
290     gnutls_datum_t desc;
291
292     if (gnutls_x509_crt_init (&cert))
293         return -1;
294     if (gnutls_x509_crt_import (cert, datum, GNUTLS_X509_FMT_DER)
295      || gnutls_x509_crt_print (cert, GNUTLS_CRT_PRINT_ONELINE, &desc))
296     {
297         gnutls_x509_crt_deinit (cert);
298         return -1;
299     }
300     gnutls_x509_crt_deinit (cert);
301
302     val = dialog_Question (obj, _("Insecure site"),
303          _("This is the certificate presented by %s:\n%s\n\n"
304            "If in doubt, abort now.\n"),
305                            _("Abort"), _("Accept 24 hours"),
306                            _("Accept permanently"), host, desc.data);
307     gnutls_free (desc.data);
308
309     time_t expiry = 0;
310     switch (val)
311     {
312         case 2:
313             time (&expiry);
314             expiry += 24 * 60 * 60;
315         case 3:
316             val = gnutls_store_pubkey (NULL, NULL, host, service,
317                                        GNUTLS_CRT_X509, datum, expiry, 0);
318             if (val)
319                 msg_Err (obj, "cannot store X.509 certificate: %s",
320                          gnutls_strerror (val));
321             return 0;
322     }
323     return -1;
324 }
325
326
327 static struct
328 {
329     int flag;
330     const char msg[43];
331     bool strict;
332 } cert_errs[] =
333 {
334     { GNUTLS_CERT_INVALID,
335         "Certificate could not be verified", false },
336     { GNUTLS_CERT_REVOKED,
337         "Certificate was revoked", true },
338     { GNUTLS_CERT_SIGNER_NOT_FOUND,
339         "Certificate's signer was not found", false },
340     { GNUTLS_CERT_SIGNER_NOT_CA,
341         "Certificate's signer is not a CA", true },
342     { GNUTLS_CERT_INSECURE_ALGORITHM,
343       "Insecure certificate signature algorithm", true },
344     { GNUTLS_CERT_NOT_ACTIVATED,
345         "Certificate is not yet activated", true },
346     { GNUTLS_CERT_EXPIRED,
347         "Certificate has expired", true },
348 };
349
350
351 static int gnutls_HandshakeAndValidate (vlc_tls_t *session, const char *host,
352                                         const char *service)
353 {
354     vlc_tls_sys_t *sys = session->sys;
355
356     int val = gnutls_ContinueHandshake (session, host, service);
357     if (val)
358         return val;
359
360     /* certificates chain verification */
361     unsigned status;
362
363     val = gnutls_certificate_verify_peers2 (sys->session, &status);
364     if (val)
365     {
366         msg_Err (session, "Certificate verification error: %s",
367                  gnutls_strerror (val));
368         return -1;
369     }
370
371     if (status)
372     {
373         msg_Err (session, "Certificate verification failure:");
374         for (size_t i = 0; i < sizeof (cert_errs) / sizeof (cert_errs[0]); i++)
375             if (status & cert_errs[i].flag)
376             {
377                 msg_Err (session, " * %s", cert_errs[i].msg);
378                 status &= ~cert_errs[i].flag;
379                 if (cert_errs[i].strict)
380                     val = -1;
381             }
382
383         if (status)
384         {
385             msg_Err (session, " * Unknown verification error 0x%04X", status);
386             val = -1;
387         }
388         status = -1;
389     }
390
391     /* certificate (host)name verification */
392     const gnutls_datum_t *data;
393     unsigned count;
394     data = gnutls_certificate_get_peers (sys->session, &count);
395     if (data == NULL || count == 0)
396     {
397         msg_Err (session, "Peer certificate not available");
398         return -1;
399     }
400     msg_Dbg (session, "%u certificate(s) in the list", count);
401
402     if (val || host == NULL)
403         return val;
404     if (status && gnutls_CertSearch (session, host, service, data))
405         return -1;
406
407     gnutls_x509_crt_t cert;
408     val = gnutls_x509_crt_init (&cert);
409     if (val)
410     {
411         msg_Err (session, "X.509 fatal error: %s", gnutls_strerror (val));
412         return -1;
413     }
414
415     val = gnutls_x509_crt_import (cert, data, GNUTLS_X509_FMT_DER);
416     if (val)
417     {
418         msg_Err (session, "Certificate import error: %s",
419                  gnutls_strerror (val));
420         goto error;
421     }
422
423     val = !gnutls_x509_crt_check_hostname (cert, host);
424     if (val)
425     {
426         msg_Err (session, "Certificate does not match \"%s\"", host);
427         val = gnutls_CertSearch (session, host, service, data);
428     }
429 error:
430     gnutls_x509_crt_init (&cert);
431     return val ? -1 : 0;
432 }
433
434 static int
435 gnutls_SessionPrioritize (vlc_object_t *obj, gnutls_session_t session)
436 {
437     char *priorities = var_InheritString (obj, "gnutls-priorities");
438     if (unlikely(priorities == NULL))
439         return VLC_ENOMEM;
440
441     const char *errp;
442     int val = gnutls_priority_set_direct (session, priorities, &errp);
443     if (val < 0)
444     {
445         msg_Err (obj, "cannot set TLS priorities \"%s\": %s", errp,
446                  gnutls_strerror (val));
447         val = VLC_EGENERIC;
448     }
449     else
450         val = VLC_SUCCESS;
451     free (priorities);
452     return val;
453 }
454
455
456 /**
457  * TLS credentials private data
458  */
459 struct vlc_tls_creds_sys
460 {
461     gnutls_certificate_credentials_t x509_cred;
462     gnutls_dh_params_t dh_params; /* XXX: used for server only */
463     int (*handshake) (vlc_tls_t *, const char *, const char *);
464         /* ^^ XXX: useful for server only */
465 };
466
467
468 /**
469  * Terminates TLS session and releases session data.
470  * You still have to close the socket yourself.
471  */
472 static void gnutls_SessionClose (vlc_tls_creds_t *crd, vlc_tls_t *session)
473 {
474     vlc_tls_sys_t *sys = session->sys;
475
476     if (sys->handshaked)
477         gnutls_bye (sys->session, GNUTLS_SHUT_WR);
478     gnutls_deinit (sys->session);
479
480     free (sys);
481     (void) crd;
482 }
483
484
485 /**
486  * Initializes a server-side TLS session.
487  */
488 static int gnutls_SessionOpen (vlc_tls_creds_t *crd, vlc_tls_t *session,
489                                int type, int fd)
490 {
491     vlc_tls_sys_t *sys = malloc (sizeof (*session->sys));
492     if (unlikely(sys == NULL))
493         return VLC_ENOMEM;
494
495     session->sys = sys;
496     session->sock.p_sys = session;
497     session->sock.pf_send = gnutls_Send;
498     session->sock.pf_recv = gnutls_Recv;
499     session->handshake = crd->sys->handshake;
500     sys->handshaked = false;
501
502     int val = gnutls_init (&sys->session, type);
503     if (val != 0)
504     {
505         msg_Err (session, "cannot initialize TLS session: %s",
506                  gnutls_strerror (val));
507         free (sys);
508         return VLC_EGENERIC;
509     }
510
511     if (gnutls_SessionPrioritize (VLC_OBJECT (crd), sys->session))
512         goto error;
513
514     val = gnutls_credentials_set (sys->session, GNUTLS_CRD_CERTIFICATE,
515                                   crd->sys->x509_cred);
516     if (val < 0)
517     {
518         msg_Err (session, "cannot set TLS session credentials: %s",
519                  gnutls_strerror (val));
520         goto error;
521     }
522
523     gnutls_transport_set_ptr (sys->session,
524                               (gnutls_transport_ptr_t)(intptr_t)fd);
525     return VLC_SUCCESS;
526
527 error:
528     gnutls_SessionClose (crd, session);
529     return VLC_EGENERIC;
530 }
531
532 static int gnutls_ServerSessionOpen (vlc_tls_creds_t *crd, vlc_tls_t *session,
533                                      int fd, const char *hostname)
534 {
535     int val = gnutls_SessionOpen (crd, session, GNUTLS_SERVER, fd);
536     if (val != VLC_SUCCESS)
537         return val;
538
539     if (session->handshake == gnutls_HandshakeAndValidate)
540         gnutls_certificate_server_set_request (session->sys->session,
541                                                GNUTLS_CERT_REQUIRE);
542     assert (hostname == NULL);
543     return VLC_SUCCESS;
544 }
545
546 static int gnutls_ClientSessionOpen (vlc_tls_creds_t *crd, vlc_tls_t *session,
547                                      int fd, const char *hostname)
548 {
549     int val = gnutls_SessionOpen (crd, session, GNUTLS_CLIENT, fd);
550     if (val != VLC_SUCCESS)
551         return val;
552
553     vlc_tls_sys_t *sys = session->sys;
554
555     /* minimum DH prime bits */
556     gnutls_dh_set_prime_bits (sys->session, 1024);
557
558     if (likely(hostname != NULL))
559         /* fill Server Name Indication */
560         gnutls_server_name_set (sys->session, GNUTLS_NAME_DNS,
561                                 hostname, strlen (hostname));
562
563     return VLC_SUCCESS;
564 }
565
566
567 /**
568  * Adds one or more Certificate Authorities to the trusted set.
569  *
570  * @param path (UTF-8) path to an X.509 certificates list.
571  *
572  * @return -1 on error, 0 on success.
573  */
574 static int gnutls_AddCA (vlc_tls_creds_t *crd, const char *path)
575 {
576     block_t *block = block_FilePath (path);
577     if (block == NULL)
578     {
579         msg_Err (crd, "cannot read trusted CA from %s: %m", path);
580         return VLC_EGENERIC;
581     }
582
583     gnutls_datum_t d = {
584        .data = block->p_buffer,
585        .size = block->i_buffer,
586     };
587
588     int val = gnutls_certificate_set_x509_trust_mem (crd->sys->x509_cred, &d,
589                                                      GNUTLS_X509_FMT_PEM);
590     block_Release (block);
591     if (val < 0)
592     {
593         msg_Err (crd, "cannot load trusted CA from %s: %s", path,
594                  gnutls_strerror (val));
595         return VLC_EGENERIC;
596     }
597     msg_Dbg (crd, " %d trusted CA%s added from %s", val, (val != 1) ? "s" : "",
598              path);
599
600     /* enables peer's certificate verification */
601     crd->sys->handshake = gnutls_HandshakeAndValidate;
602     return VLC_SUCCESS;
603 }
604
605
606 /**
607  * Adds a Certificates Revocation List to be sent to TLS clients.
608  *
609  * @param path (UTF-8) path of the CRL file.
610  *
611  * @return -1 on error, 0 on success.
612  */
613 static int gnutls_AddCRL (vlc_tls_creds_t *crd, const char *path)
614 {
615     block_t *block = block_FilePath (path);
616     if (block == NULL)
617     {
618         msg_Err (crd, "cannot read CRL from %s: %m", path);
619         return VLC_EGENERIC;
620     }
621
622     gnutls_datum_t d = {
623        .data = block->p_buffer,
624        .size = block->i_buffer,
625     };
626
627     int val = gnutls_certificate_set_x509_crl_mem (crd->sys->x509_cred, &d,
628                                                    GNUTLS_X509_FMT_PEM);
629     block_Release (block);
630     if (val < 0)
631     {
632         msg_Err (crd, "cannot add CRL (%s): %s", path, gnutls_strerror (val));
633         return VLC_EGENERIC;
634     }
635     msg_Dbg (crd, "%d CRL%s added from %s", val, (val != 1) ? "s" : "", path);
636     return VLC_SUCCESS;
637 }
638
639
640 /**
641  * Allocates a whole server's TLS credentials.
642  */
643 static int OpenServer (vlc_tls_creds_t *crd, const char *cert, const char *key)
644 {
645     int val;
646
647     if (gnutls_Init (VLC_OBJECT(crd)))
648         return VLC_EGENERIC;
649
650     vlc_tls_creds_sys_t *sys = malloc (sizeof (*sys));
651     if (unlikely(sys == NULL))
652         goto error;
653
654     crd->sys     = sys;
655     crd->add_CA  = gnutls_AddCA;
656     crd->add_CRL = gnutls_AddCRL;
657     crd->open    = gnutls_ServerSessionOpen;
658     crd->close   = gnutls_SessionClose;
659     /* No certificate validation by default */
660     sys->handshake  = gnutls_ContinueHandshake;
661
662     /* Sets server's credentials */
663     val = gnutls_certificate_allocate_credentials (&sys->x509_cred);
664     if (val != 0)
665     {
666         msg_Err (crd, "cannot allocate credentials: %s",
667                  gnutls_strerror (val));
668         goto error;
669     }
670
671     block_t *certblock = block_FilePath (cert);
672     if (certblock == NULL)
673     {
674         msg_Err (crd, "cannot read certificate chain from %s: %m", cert);
675         return VLC_EGENERIC;
676     }
677
678     block_t *keyblock = block_FilePath (key);
679     if (keyblock == NULL)
680     {
681         msg_Err (crd, "cannot read private key from %s: %m", key);
682         block_Release (certblock);
683         return VLC_EGENERIC;
684     }
685
686     gnutls_datum_t pub = {
687        .data = certblock->p_buffer,
688        .size = certblock->i_buffer,
689     }, priv = {
690        .data = keyblock->p_buffer,
691        .size = keyblock->i_buffer,
692     };
693
694     val = gnutls_certificate_set_x509_key_mem (sys->x509_cred, &pub, &priv,
695                                                 GNUTLS_X509_FMT_PEM);
696     block_Release (keyblock);
697     block_Release (certblock);
698     if (val < 0)
699     {
700         msg_Err (crd, "cannot load X.509 key: %s", gnutls_strerror (val));
701         gnutls_certificate_free_credentials (sys->x509_cred);
702         goto error;
703     }
704
705     /* FIXME:
706      * - support other cipher suites
707      */
708     val = gnutls_dh_params_init (&sys->dh_params);
709     if (val >= 0)
710     {
711         const gnutls_datum_t data = {
712             .data = (unsigned char *)dh_params,
713             .size = sizeof (dh_params) - 1,
714         };
715
716         val = gnutls_dh_params_import_pkcs3 (sys->dh_params, &data,
717                                              GNUTLS_X509_FMT_PEM);
718         if (val == 0)
719             gnutls_certificate_set_dh_params (sys->x509_cred,
720                                               sys->dh_params);
721     }
722     if (val < 0)
723     {
724         msg_Err (crd, "cannot initialize DHE cipher suites: %s",
725                  gnutls_strerror (val));
726     }
727
728     return VLC_SUCCESS;
729
730 error:
731     free (sys);
732     gnutls_Deinit (VLC_OBJECT(crd));
733     return VLC_EGENERIC;
734 }
735
736 /**
737  * Destroys a TLS server object.
738  */
739 static void CloseServer (vlc_tls_creds_t *crd)
740 {
741     vlc_tls_creds_sys_t *sys = crd->sys;
742
743     /* all sessions depending on the server are now deinitialized */
744     gnutls_certificate_free_credentials (sys->x509_cred);
745     gnutls_dh_params_deinit (sys->dh_params);
746     free (sys);
747
748     gnutls_Deinit (VLC_OBJECT(crd));
749 }
750
751 /**
752  * Initializes a client-side TLS credentials.
753  */
754 static int OpenClient (vlc_tls_creds_t *crd)
755 {
756     if (gnutls_Init (VLC_OBJECT(crd)))
757         return VLC_EGENERIC;
758
759     vlc_tls_creds_sys_t *sys = malloc (sizeof (*sys));
760     if (unlikely(sys == NULL))
761         goto error;
762
763     crd->sys = sys;
764     //crd->add_CA = gnutls_AddCA;
765     //crd->add_CRL = gnutls_AddCRL;
766     crd->open = gnutls_ClientSessionOpen;
767     crd->close = gnutls_SessionClose;
768     sys->handshake = gnutls_HandshakeAndValidate;
769
770     int val = gnutls_certificate_allocate_credentials (&sys->x509_cred);
771     if (val != 0)
772     {
773         msg_Err (crd, "cannot allocate credentials: %s",
774                  gnutls_strerror (val));
775         goto error;
776     }
777
778     val = gnutls_certificate_set_x509_system_trust (sys->x509_cred);
779     if (val < 0)
780         msg_Err (crd, "cannot load trusted Certificate Authorities: %s",
781                  gnutls_strerror (val));
782     else
783         msg_Dbg (crd, "loaded %d trusted CAs", val);
784
785     gnutls_certificate_set_verify_flags (sys->x509_cred,
786                                          GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
787
788     return VLC_SUCCESS;
789 error:
790     free (sys);
791     gnutls_Deinit (VLC_OBJECT(crd));
792     return VLC_EGENERIC;
793 }
794
795 static void CloseClient (vlc_tls_creds_t *crd)
796 {
797     vlc_tls_creds_sys_t *sys = crd->sys;
798
799     gnutls_certificate_free_credentials (sys->x509_cred);
800     free (sys);
801
802     gnutls_Deinit (VLC_OBJECT(crd));
803 }