gnutls.c 23.6 KB
Newer Older
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1
/*****************************************************************************
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
2
 * gnutls.c
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
3
 *****************************************************************************
4
 * Copyright (C) 2004-2011 Rémi Denis-Courmont
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
5
6
7
8
9
10
11
12
13
14
15
16
17
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
dionoea's avatar
dionoea committed
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
19
20
21
22
23
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
Rémi Denis-Courmont's avatar
Cleanup    
Rémi Denis-Courmont committed
24

25
26
27
28
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
29
#include <errno.h>
30
31
#include <sys/types.h>
#include <errno.h>
32

33
#include <sys/stat.h>
34
#ifdef WIN32
35
# include <windows.h>
36
# include <io.h>
37
# include <wincrypt.h>
38
39
#else
# include <unistd.h>
40
#endif
41
#include <fcntl.h>
42

43
44
#include <vlc_common.h>
#include <vlc_plugin.h>
45
#include <vlc_tls.h>
zorglub's avatar
zorglub committed
46
#include <vlc_charset.h>
47
#include <vlc_fs.h>
48
#include <vlc_block.h>
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
49

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
50
#include <gcrypt.h>
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
51
#include <gnutls/gnutls.h>
52
#include <gnutls/x509.h>
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
53

54
#include <vlc_gcrypt.h>
55
56
#include "dhparams.h"

57
58
#include <assert.h>

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
59
60
61
/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
62
63
static int  OpenClient  (vlc_tls_t *, int, const char *);
static void CloseClient (vlc_tls_t *);
64
65
static int  OpenServer  (vlc_object_t *);
static void CloseServer (vlc_object_t *);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
66

67
68
69
70
#define PRIORITIES_TEXT N_("TLS cipher priorities")
#define PRIORITIES_LONGTEXT N_("Ciphers, key exchange methods, " \
    "hash functions and compression methods can be selected. " \
    "Refer to GNU TLS documentation for detailed syntax.")
71
72
73
74
75
76
77
78
79
80
81
82
83
84
static const char *const priorities_values[] = {
    "PERFORMANCE",
    "NORMAL",
    "SECURE128",
    "SECURE256",
    "EXPORT",
};
static const char *const priorities_text[] = {
    N_("Performance (prioritize faster ciphers)"),
    N_("Normal"),
    N_("Secure 128-bits (exclude 256-bits ciphers)"),
    N_("Secure 256-bits (prioritize 256-bits ciphers)"),
    N_("Export (include insecure ciphers)"),
};
85

86
vlc_module_begin ()
87
88
    set_shortname( "GNU TLS" )
    set_description( N_("GNU TLS transport layer security") )
89
90
91
92
93
94
    set_capability( "tls client", 1 )
    set_callbacks( OpenClient, CloseClient )
    set_category( CAT_ADVANCED )
    set_subcategory( SUBCAT_ADVANCED_MISC )

    add_submodule ()
95
        set_description( N_("GNU TLS server") )
96
97
98
99
100
        set_capability( "tls server", 1 )
        set_category( CAT_ADVANCED )
        set_subcategory( SUBCAT_ADVANCED_MISC )
        set_callbacks( OpenServer, CloseServer )

101
102
        add_string ("gnutls-priorities", "NORMAL", PRIORITIES_TEXT,
                    PRIORITIES_LONGTEXT, false)
103
            change_string_list (priorities_values, priorities_text)
104
vlc_module_end ()
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
105

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
106
107
static vlc_mutex_t gnutls_mutex = VLC_STATIC_MUTEX;

108
109
110
111
112
/**
 * Initializes GnuTLS with proper locking.
 * @return VLC_SUCCESS on success, a VLC error code otherwise.
 */
static int gnutls_Init (vlc_object_t *p_this)
113
{
114
115
    int ret = VLC_EGENERIC;

116
    vlc_gcrypt_init (); /* GnuTLS depends on gcrypt */
117

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
118
    vlc_mutex_lock (&gnutls_mutex);
119
120
121
122
123
124
    if (gnutls_global_init ())
    {
        msg_Err (p_this, "cannot initialize GnuTLS");
        goto error;
    }

125
    const char *psz_version = gnutls_check_version ("2.0.0");
126
127
128
129
130
131
132
133
134
135
136
    if (psz_version == NULL)
    {
        msg_Err (p_this, "unsupported GnuTLS version");
        gnutls_global_deinit ();
        goto error;
    }

    msg_Dbg (p_this, "GnuTLS v%s initialized", psz_version);
    ret = VLC_SUCCESS;

error:
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
137
    vlc_mutex_unlock (&gnutls_mutex);
138
139
140
141
142
143
144
145
146
    return ret;
}


/**
 * Deinitializes GnuTLS.
 */
static void gnutls_Deinit (vlc_object_t *p_this)
{
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
147
    vlc_mutex_lock (&gnutls_mutex);
148
149
150

    gnutls_global_deinit ();
    msg_Dbg (p_this, "GnuTLS deinitialized");
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
151
    vlc_mutex_unlock (&gnutls_mutex);
152
}
153
154


155
156
157
158
159
static int gnutls_Error (vlc_object_t *obj, int val)
{
    switch (val)
    {
        case GNUTLS_E_AGAIN:
160
161
162
#ifdef WIN32
            WSASetLastError (WSAEWOULDBLOCK);
#else
163
            errno = EAGAIN;
164
#endif
165
            break;
166
167

        case GNUTLS_E_INTERRUPTED:
168
169
#ifdef WIN32
            WSASetLastError (WSAEINTR);
170
#else
171
            errno = EINTR;
172
#endif
173
174
175
176
            break;

        default:
            msg_Err (obj, "%s", gnutls_strerror (val));
177
#ifndef NDEBUG
178
179
180
            if (!gnutls_error_is_fatal (val))
                msg_Err (obj, "Error above should be handled");
#endif
181
182
#ifdef WIN32
            WSASetLastError (WSAECONNRESET);
183
#else
184
            errno = ECONNRESET;
185
#endif
186
187
188
    }
    return -1;
}
189
#define gnutls_Error(o, val) gnutls_Error(VLC_OBJECT(o), val)
190
191


192
struct vlc_tls_sys
193
{
194
    gnutls_session_t session;
195
196
197
    gnutls_certificate_credentials_t x509_cred;
    char *hostname;
    bool handshaked;
198
199
200
};


201
/**
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
202
 * Sends data through a TLS session.
203
 */
204
static int gnutls_Send (void *opaque, const void *buf, size_t length)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
205
{
206
207
    vlc_tls_t *session = opaque;
    vlc_tls_sys_t *sys = session->sys;
208

209
210
    int val = gnutls_record_send (sys->session, buf, length);
    return (val < 0) ? gnutls_Error (session, val) : val;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
211
212
213
}


214
/**
215
 * Receives data through a TLS session.
216
 */
217
static int gnutls_Recv (void *opaque, void *buf, size_t length)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
218
{
219
220
    vlc_tls_t *session = opaque;
    vlc_tls_sys_t *sys = session->sys;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
221

222
223
    int val = gnutls_record_recv (sys->session, buf, length);
    return (val < 0) ? gnutls_Error (session, val) : val;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
224
225
226
}


227
/**
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
228
229
 * Starts or continues the TLS handshake.
 *
Rémi Denis-Courmont's avatar
Typos    
Rémi Denis-Courmont committed
230
 * @return -1 on fatal error, 0 on successful handshake completion,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
231
232
 * 1 if more would-be blocking recv is needed,
 * 2 if more would-be blocking send is required.
233
 */
234
static int gnutls_ContinueHandshake (vlc_tls_t *session)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
235
{
236
    vlc_tls_sys_t *sys = session->sys;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
237
238
    int val;

239
#ifdef WIN32
240
    WSASetLastError (0);
241
#endif
242
243
244
    val = gnutls_handshake (sys->session);
    if ((val == GNUTLS_E_AGAIN) || (val == GNUTLS_E_INTERRUPTED))
        return 1 + gnutls_record_get_direction (sys->session);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
245

246
    if (val < 0)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
247
    {
248
#ifdef WIN32
249
        msg_Dbg (session, "Winsock error %d", WSAGetLastError ());
250
#endif
251
        msg_Err (session, "TLS handshake error: %s", gnutls_strerror (val));
252
        return -1;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
253
    }
254

255
    sys->handshaked = true;
256
257
258
    return 0;
}

259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277

typedef struct
{
    int flag;
    const char *msg;
} error_msg_t;

static const error_msg_t cert_errors[] =
{
    { GNUTLS_CERT_INVALID,
        "Certificate could not be verified" },
    { GNUTLS_CERT_REVOKED,
        "Certificate was revoked" },
    { GNUTLS_CERT_SIGNER_NOT_FOUND,
        "Certificate's signer was not found" },
    { GNUTLS_CERT_SIGNER_NOT_CA,
        "Certificate's signer is not a CA" },
    { GNUTLS_CERT_INSECURE_ALGORITHM,
        "Insecure certificate signature algorithm" },
278
279
280
281
    { GNUTLS_CERT_NOT_ACTIVATED,
        "Certificate is not yet activated" },
    { GNUTLS_CERT_EXPIRED,
        "Certificate has expired" },
282
283
284
285
    { 0, NULL }
};


286
static int gnutls_HandshakeAndValidate (vlc_tls_t *session)
287
{
288
    vlc_tls_sys_t *sys = session->sys;
289

290
291
292
    int val = gnutls_ContinueHandshake (session);
    if (val)
        return val;
293

294
295
296
    /* certificates chain verification */
    unsigned status;

297
298
    val = gnutls_certificate_verify_peers2 (sys->session, &status);
    if (val)
299
    {
300
301
        msg_Err (session, "Certificate verification failed: %s",
                 gnutls_strerror (val));
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
302
        return -1;
303
    }
304

305
    if (status)
306
    {
307
        msg_Err (session, "TLS session: access denied (status 0x%X)", status);
308
        for (const error_msg_t *e = cert_errors; e->flag; e++)
309
        {
310
            if (status & e->flag)
311
            {
312
                msg_Err (session, "%s", e->msg);
313
314
                status &= ~e->flag;
            }
315
316
        }

317
318
319
        if (status)
            msg_Err (session,
                     "unknown certificate error (you found a bug in VLC)");
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
320
        return -1;
321
322
323
    }

    /* certificate (host)name verification */
324
    const gnutls_datum_t *data;
325
326
    data = gnutls_certificate_get_peers (sys->session, &(unsigned){0});
    if (data == NULL)
327
    {
328
        msg_Err (session, "Peer certificate not available");
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
329
        return -1;
330
331
    }

332
    gnutls_x509_crt_t cert;
333
334
    val = gnutls_x509_crt_init (&cert);
    if (val)
335
    {
336
        msg_Err (session, "X.509 fatal error: %s", gnutls_strerror (val));
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
337
        return -1;
338
339
    }

340
341
    val = gnutls_x509_crt_import (cert, data, GNUTLS_X509_FMT_DER);
    if (val)
342
    {
343
344
        msg_Err (session, "Certificate import error: %s",
                 gnutls_strerror (val));
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
345
        goto error;
346
    }
347

348
349
    if (sys->hostname != NULL
     && !gnutls_x509_crt_check_hostname (cert, sys->hostname))
350
    {
351
        msg_Err (session, "Certificate does not match \"%s\"", sys->hostname);
352
        goto error;
353
354
    }

355
    gnutls_x509_crt_deinit (cert);
356
    msg_Dbg (session, "TLS/X.509 certificate verified");
357
358
359
    return 0;

error:
360
    gnutls_x509_crt_deinit (cert);
361
    return -1;
362
363
}

364
365
366
static int
gnutls_SessionPrioritize (vlc_object_t *obj, gnutls_session_t session)
{
367
368
369
    char *priorities = var_InheritString (obj, "gnutls-priorities");
    if (unlikely(priorities == NULL))
        return VLC_ENOMEM;
370

371
372
    const char *errp;
    int val = gnutls_priority_set_direct (session, priorities, &errp);
373
374
    if (val < 0)
    {
375
        msg_Err (obj, "cannot set TLS priorities \"%s\": %s", errp,
376
                 gnutls_strerror (val));
377
        val = VLC_EGENERIC;
378
    }
379
380
381
382
    else
        val = VLC_SUCCESS;
    free (priorities);
    return val;
383
384
}

385
386
387
388
389
#ifndef WIN32
/**
 * Loads x509 credentials from a file descriptor (directory or regular file)
 * and closes the descriptor.
 */
390
391
392
static void gnutls_x509_AddFD (vlc_object_t *obj,
                               gnutls_certificate_credentials_t cred,
                               int fd, bool priv, unsigned recursion)
393
{
394
395
    DIR *dir = fdopendir (fd);
    if (dir != NULL)
396
    {
397
398
399
        if (recursion == 0)
            goto skipdir;
        recursion--;
400

401
        for (;;)
402
        {
403
404
405
            char *ent = vlc_readdir (dir);
            if (ent == NULL)
                break;
406

407
408
409
410
411
            if ((strcmp (ent, ".") == 0) || (strcmp (ent, "..") == 0))
            {
                free (ent);
                continue;
            }
412

413
414
415
416
            int nfd = vlc_openat (fd, ent, O_RDONLY);
            if (nfd != -1)
            {
                msg_Dbg (obj, "loading x509 credentials from %s...", ent);
417
                gnutls_x509_AddFD (obj, cred, nfd, priv, recursion);
418
419
420
421
            }
            else
                msg_Dbg (obj, "cannot access x509 credentials in %s", ent);
            free (ent);
ivoire's avatar
ivoire committed
422
        }
423
424
425
    skipdir:
        closedir (dir);
        return;
426
427
    }

428
429
    block_t *block = block_File (fd);
    if (block != NULL)
430
    {
431
        gnutls_datum_t data = {
432
433
434
            .data = block->p_buffer,
            .size = block->i_buffer,
        };
435
        int res = priv
436
437
438
439
440
441
442
            ? gnutls_certificate_set_x509_key_mem (cred, &data, &data,
                                                   GNUTLS_X509_FMT_PEM)
            : gnutls_certificate_set_x509_trust_mem (cred, &data,
                                                     GNUTLS_X509_FMT_PEM);
        block_Release (block);

        if (res < 0)
443
444
445
446
            msg_Warn (obj, "cannot add x509 credentials: %s",
                      gnutls_strerror (res));
        else
            msg_Dbg (obj, "added %d %s(s)", res, priv ? "key" : "certificate");
447
    }
448
449
450
451
    else
        msg_Warn (obj, "cannot read x509 credentials: %m");
    close (fd);
}
452

453
static void gnutls_x509_AddPath (vlc_object_t *obj,
454
                                 gnutls_certificate_credentials_t cred,
455
                                 const char *path, bool priv)
456
{
457
    msg_Dbg (obj, "loading x509 credentials in %s...", path);
458
459
460
461
462
463
464
    int fd = vlc_open (path, O_RDONLY);
    if (fd == -1)
    {
        msg_Warn (obj, "cannot access x509 in %s: %m", path);
        return;
    }

465
    gnutls_x509_AddFD (obj, cred, fd, priv, 5);
466
467
}
#else /* WIN32 */
468
static int
469
gnutls_loadOSCAList (vlc_object_t *p_this,
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
                     gnutls_certificate_credentials cred)
{
    HCERTSTORE hCertStore = CertOpenSystemStoreA((HCRYPTPROV)NULL, "ROOT");
    if (!hCertStore)
    {
        msg_Warn (p_this, "could not open the Cert SystemStore");
        return VLC_EGENERIC;
    }

    PCCERT_CONTEXT pCertContext = CertEnumCertificatesInStore(hCertStore, NULL);
    while( pCertContext )
    {
        gnutls_datum data = {
            .data = pCertContext->pbCertEncoded,
            .size = pCertContext->cbCertEncoded,
        };

        if(!gnutls_certificate_set_x509_trust_mem(cred, &data, GNUTLS_X509_FMT_DER))
        {
            msg_Warn (p_this, "cannot add x509 credential");
            return VLC_EGENERIC;
        }

        pCertContext = CertEnumCertificatesInStore(hCertStore, pCertContext);
    }
    return VLC_SUCCESS;
}
497
#endif /* WIN32 */
498

499
500
501
/**
 * Initializes a client-side TLS session.
 */
502
static int OpenClient (vlc_tls_t *session, int fd, const char *hostname)
503
{
504
    if (gnutls_Init (VLC_OBJECT(session)))
505
        return VLC_EGENERIC;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
506

507
508
    vlc_tls_sys_t *sys = malloc (sizeof (*sys));
    if (unlikely(sys == NULL))
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
509
    {
510
        gnutls_Deinit (VLC_OBJECT(session));
511
        return VLC_ENOMEM;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
512
513
    }

514
515
516
517
518
    session->sys = sys;
    session->sock.p_sys = session;
    session->sock.pf_send = gnutls_Send;
    session->sock.pf_recv = gnutls_Recv;
    sys->handshaked = false;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
519

520
521
    int val = gnutls_certificate_allocate_credentials (&sys->x509_cred);
    if (val != 0)
522
    {
523
        msg_Err (session, "cannot allocate credentials: %s",
524
                 gnutls_strerror (val));
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
525
        goto error;
526
527
    }

528
#ifndef WIN32
529
    char *userdir = config_GetUserDir (VLC_DATA_DIR);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
530
531
    if (userdir != NULL)
    {
532
        char path[strlen (userdir) + sizeof ("/ssl/private/")];
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
533
        sprintf (path, "%s/ssl", userdir);
534
        vlc_mkdir (path, 0755);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
535

536
537
538
539
        sprintf (path, "%s/ssl/certs/", userdir);
        gnutls_x509_AddPath (VLC_OBJECT(session), sys->x509_cred, path, false);
        sprintf (path, "%s/ssl/private/", userdir);
        gnutls_x509_AddPath (VLC_OBJECT(session), sys->x509_cred, path, true);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
540
541
        free (userdir);
    }
542

543
    const char *confdir = config_GetConfDir ();
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
544
    {
545
546
547
        char path[strlen (confdir)
                   + sizeof ("/ssl/certs/ca-certificates.crt")];
        sprintf (path, "%s/ssl/certs/ca-certificates.crt", confdir);
548
        gnutls_x509_AddPath (VLC_OBJECT(session), sys->x509_cred, path, false);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
549
    }
550
551
#else /* WIN32 */
    gnutls_loadOSCAList (VLC_OBJECT(session), sys->x509_cred);
552
#endif
553
554
555
    gnutls_certificate_set_verify_flags (sys->x509_cred,
                                         GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);

556
557
    session->handshake = gnutls_HandshakeAndValidate;
    /*session->_handshake = gnutls_ContinueHandshake;*/
558

559
560
    val = gnutls_init (&sys->session, GNUTLS_CLIENT);
    if (val != 0)
561
    {
562
563
564
        msg_Err (session, "cannot initialize TLS session: %s",
                 gnutls_strerror (val));
        gnutls_certificate_free_credentials (sys->x509_cred);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
565
        goto error;
566
567
    }

568
    if (gnutls_SessionPrioritize (VLC_OBJECT(session), sys->session))
569
        goto s_error;
570

571
    /* minimum DH prime bits */
572
    gnutls_dh_set_prime_bits (sys->session, 1024);
573

574
575
576
    val = gnutls_credentials_set (sys->session, GNUTLS_CRD_CERTIFICATE,
                                  sys->x509_cred);
    if (val < 0)
577
    {
578
579
        msg_Err (session, "cannot set TLS session credentials: %s",
                 gnutls_strerror (val));
580
        goto s_error;
581
582
    }

583
584
585
586
587
588
589
590
591
592
593
    /* server name */
    if (likely(hostname != NULL))
    {
        /* fill Server Name Indication */
        gnutls_server_name_set (sys->session, GNUTLS_NAME_DNS,
                                hostname, strlen (hostname));
        /* keep hostname to match CNAME after handshake */
        sys->hostname = strdup (hostname);
        if (unlikely(sys->hostname == NULL))
            goto s_error;
    }
594
    else
595
        sys->hostname = NULL;
596

597
598
    gnutls_transport_set_ptr (sys->session,
                              (gnutls_transport_ptr_t)(intptr_t)fd);
599
    return VLC_SUCCESS;
600

601
s_error:
602
603
    gnutls_deinit (sys->session);
    gnutls_certificate_free_credentials (sys->x509_cred);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
604
error:
605
606
    gnutls_Deinit (VLC_OBJECT(session));
    free (sys);
607
608
    return VLC_EGENERIC;
}
609

610

611
static void CloseClient (vlc_tls_t *session)
612
{
613
    vlc_tls_sys_t *sys = session->sys;
614

615
616
617
    if (sys->handshaked)
        gnutls_bye (sys->session, GNUTLS_SHUT_WR);
    gnutls_deinit (sys->session);
618
    /* credentials must be free'd *after* gnutls_deinit() */
619
    gnutls_certificate_free_credentials (sys->x509_cred);
620

621
622
623
    gnutls_Deinit (VLC_OBJECT(session));
    free (sys->hostname);
    free (sys);
624
625
626
}


627
628
629
/**
 * Server-side TLS
 */
630
struct vlc_tls_creds_sys
631
{
632
633
    gnutls_certificate_credentials_t x509_cred;
    gnutls_dh_params_t               dh_params;
634
    int                            (*handshake) (vlc_tls_t *);
635
636
637
638
639
640
641
};


/**
 * Terminates TLS session and releases session data.
 * You still have to close the socket yourself.
 */
642
static void gnutls_SessionClose (vlc_tls_t *session)
643
{
644
    vlc_tls_sys_t *sys = session->sys;
645

646
647
648
    if (sys->handshaked)
        gnutls_bye (sys->session, GNUTLS_SHUT_WR);
    gnutls_deinit (sys->session);
649

650
651
    vlc_object_release (session);
    free (sys);
652
653
654
}


655
656
657
/**
 * Initializes a server-side TLS session.
 */
658
static vlc_tls_t *gnutls_SessionOpen (vlc_tls_creds_t *server, int fd)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
659
{
660
661
    vlc_tls_creds_sys_t *ssys = server->sys;
    int val;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
662

663
664
    vlc_tls_t *session = vlc_object_create (server, sizeof (*session));
    if (unlikely(session == NULL))
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
665
        return NULL;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
666

667
668
    vlc_tls_sys_t *sys = malloc (sizeof (*session->sys));
    if (unlikely(sys == NULL))
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
669
    {
670
        vlc_object_release (session);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
671
672
673
        return NULL;
    }

674
675
676
677
678
679
680
681
    session->sys = sys;
    session->sock.p_sys = session;
    session->sock.pf_send = gnutls_Send;
    session->sock.pf_recv = gnutls_Recv;
    session->handshake = ssys->handshake;
    session->u.close = gnutls_SessionClose;
    sys->handshaked = false;
    sys->hostname = NULL;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
682

683
684
    val = gnutls_init (&sys->session, GNUTLS_SERVER);
    if (val != 0)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
685
    {
686
687
688
689
690
        msg_Err (server, "cannot initialize TLS session: %s",
                 gnutls_strerror (val));
        free (sys);
        vlc_object_release (session);
        return NULL;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
691
    }
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
692

693
    if (gnutls_SessionPrioritize (VLC_OBJECT (server), sys->session))
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
694
        goto error;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
695

696
697
698
    val = gnutls_credentials_set (sys->session, GNUTLS_CRD_CERTIFICATE,
                                  ssys->x509_cred);
    if (val < 0)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
699
    {
700
701
        msg_Err (server, "cannot set TLS session credentials: %s",
                 gnutls_strerror (val));
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
702
        goto error;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
703
704
    }

705
706
707
    if (session->handshake == gnutls_HandshakeAndValidate)
        gnutls_certificate_server_set_request (sys->session,
                                               GNUTLS_CERT_REQUIRE);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
708

709
710
711
    gnutls_transport_set_ptr (sys->session,
                              (gnutls_transport_ptr_t)(intptr_t)fd);
    return session;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
712
713

error:
714
    gnutls_SessionClose (session);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
715
    return NULL;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
716
717
718
}


719
/**
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
720
 * Adds one or more certificate authorities.
721
 *
722
 * @param ca_path (Unicode) path to an x509 certificates list.
723
724
 *
 * @return -1 on error, 0 on success.
725
 */
726
static int gnutls_ServerAddCA (vlc_tls_creds_t *server, const char *ca_path)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
727
{
728
    vlc_tls_creds_sys_t *sys = server->sys;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
729
    const char *local_path = ToLocale (ca_path);
730

731
732
733
734
735
    int val = gnutls_certificate_set_x509_trust_file (sys->x509_cred,
                                                      local_path,
                                                      GNUTLS_X509_FMT_PEM );
    LocaleFree (local_path);
    if (val < 0)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
736
    {
737
738
        msg_Err (server, "cannot add trusted CA (%s): %s", ca_path,
                 gnutls_strerror (val));
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
739
740
        return VLC_EGENERIC;
    }
741
    msg_Dbg (server, " %d trusted CA added (%s)", val, ca_path);
742
743

    /* enables peer's certificate verification */
744
    sys->handshake = gnutls_HandshakeAndValidate;
745

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
746
747
748
749
    return VLC_SUCCESS;
}


750
/**
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
751
 * Adds a certificates revocation list to be sent to TLS clients.
752
 *
753
 * @param crl_path (Unicode) path of the CRL file.
754
755
756
 *
 * @return -1 on error, 0 on success.
 */
757
static int gnutls_ServerAddCRL (vlc_tls_creds_t *server, const char *crl_path)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
758
{
759
    vlc_tls_creds_sys_t *sys = server->sys;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
760
    const char *local_path = ToLocale (crl_path);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
761

762
763
764
765
766
    int val = gnutls_certificate_set_x509_crl_file (sys->x509_cred,
                                                    local_path,
                                                    GNUTLS_X509_FMT_PEM);
    LocaleFree (local_path);
    if (val < 0)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
767
    {
768
769
        msg_Err (server, "cannot add CRL (%s): %s", crl_path,
                 gnutls_strerror (val));
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
770
771
        return VLC_EGENERIC;
    }
772
    msg_Dbg (server, "%d CRL added (%s)", val, crl_path);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
773
774
    return VLC_SUCCESS;
}
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
775

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
776

777
/**
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
778
 * Allocates a whole server's TLS credentials.
779
 */
780
static int OpenServer (vlc_object_t *obj)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
781
{
782
    vlc_tls_creds_t *server = (vlc_tls_creds_t *)obj;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
783
784
    int val;

785
786
787
788
    if (gnutls_Init (obj))
        return VLC_EGENERIC;

    msg_Dbg (obj, "creating TLS server");
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
789

790
791
    vlc_tls_creds_sys_t *sys = malloc (sizeof (*sys));
    if (unlikely(sys == NULL))
792
        return VLC_ENOMEM;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
793

794
795
796
797
    server->sys     = sys;
    server->add_CA  = gnutls_ServerAddCA;
    server->add_CRL = gnutls_ServerAddCRL;
    server->open    = gnutls_SessionOpen;
798
    /* No certificate validation by default */
799
    sys->handshake  = gnutls_ContinueHandshake;
800

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
801
    /* Sets server's credentials */
802
803
    val = gnutls_certificate_allocate_credentials (&sys->x509_cred);
    if (val != 0)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
804
    {
805
        msg_Err (server, "cannot allocate credentials: %s",
806
                 gnutls_strerror (val));
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
807
        goto error;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
808
809
    }

810
811
812
813
814
815
816
817
818
819
    char *cert_path = var_GetNonEmptyString (obj, "tls-x509-cert");
    char *key_path = var_GetNonEmptyString (obj, "tls-x509-key");
    const char *lcert = ToLocale (cert_path);
    const char *lkey = ToLocale (key_path);
    val = gnutls_certificate_set_x509_key_file (sys->x509_cred, lcert, lkey,
                                                GNUTLS_X509_FMT_PEM);
    LocaleFree (lkey);
    LocaleFree (lcert);
    free (key_path);
    free (cert_path);
820

821
    if (val < 0)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
822
    {
823
824
825
        msg_Err (server, "cannot set certificate chain or private key: %s",
                 gnutls_strerror (val));
        gnutls_certificate_free_credentials (sys->x509_cred);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
826
        goto error;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
827
828
    }

829
    /* FIXME:
830
     * - support other cipher suites
831
     */
832
    val = gnutls_dh_params_init (&sys->dh_params);
833
834
    if (val >= 0)
    {
835
836
837
838
839
        const gnutls_datum_t data = {
            .data = (unsigned char *)dh_params,
            .size = sizeof (dh_params) - 1,
        };

840
        val = gnutls_dh_params_import_pkcs3 (sys->dh_params, &data,
841
842
                                             GNUTLS_X509_FMT_PEM);
        if (val == 0)
843
844
            gnutls_certificate_set_dh_params (sys->x509_cred,
                                              sys->dh_params);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
845
    }
846
    if (val < 0)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
847
    {
848
        msg_Err (server, "cannot initialize DHE cipher suites: %s",
849
                 gnutls_strerror (val));
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
850
851
    }

852
    return VLC_SUCCESS;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
853
854

error:
855
    free (sys);
856
    return VLC_EGENERIC;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
857
858
}

859
/**
860
 * Destroys a TLS server object.
861
 */
862
static void CloseServer (vlc_object_t *obj)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
863
{
864
865
    vlc_tls_creds_t *server = (vlc_tls_creds_t *)obj;
    vlc_tls_creds_sys_t *sys = server->sys;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
866

867
    /* all sessions depending on the server are now deinitialized */
868
869
870
    gnutls_certificate_free_credentials (sys->x509_cred);
    gnutls_dh_params_deinit (sys->dh_params);
    free (sys);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
871

872
    gnutls_Deinit (obj);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
873
}