gnutls.c 31.7 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
 *****************************************************************************
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
4
 * Copyright (C) 2004-2006 Rémi Denis-Courmont
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
5
 * $Id$
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
6
 *
7
 * Authors: Rémi Denis-Courmont <rem # videolan.org>
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
8
9
10
11
12
13
14
15
16
17
18
19
20
 *
 * 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
21
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
22
23
24
25
26
 *****************************************************************************/

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

28
29
30
31
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

32
#include <vlc_common.h>
33
#include <vlc_plugin.h>
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
34
#include <errno.h>
35
#include <time.h>
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
36

37
38
39
40
41
42
43
#include <sys/types.h>
#include <errno.h>
#ifdef HAVE_DIRENT_H
# include <dirent.h>
#endif
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
44
45
46
47
48
#endif
#ifdef WIN32
# include <io.h>
#else
# include <unistd.h>
49
#endif
50
# include <fcntl.h>
51
52


53
#include <vlc_tls.h>
zorglub's avatar
zorglub committed
54
#include <vlc_charset.h>
55
#include <vlc_fs.h>
56
#include <vlc_block.h>
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
57

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
58
#include <gcrypt.h>
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
59
#include <gnutls/gnutls.h>
60
#include <gnutls/x509.h>
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
61

62
63
#include <vlc_gcrypt.h>

64
#define CACHE_TIMEOUT     3600
65
#define CACHE_SIZE          64
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
66

67
68
#include "dhparams.h"

69
70
#include <assert.h>

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
71
72
73
/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
74
75
76
77
static int  OpenClient  (vlc_object_t *);
static void CloseClient (vlc_object_t *);
static int  OpenServer  (vlc_object_t *);
static void CloseServer (vlc_object_t *);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
78

79
80
#define CACHE_TIMEOUT_TEXT N_("Expiration time for resumed TLS sessions")
#define CACHE_TIMEOUT_LONGTEXT N_( \
81
82
    "It is possible to cache the resumed TLS sessions. This is the expiration "\
    "time of the sessions stored in this cache, in seconds." )
83
84
85

#define CACHE_SIZE_TEXT N_("Number of resumed TLS sessions")
#define CACHE_SIZE_LONGTEXT N_( \
86
    "This is the maximum number of resumed TLS sessions that " \
87
88
    "the cache will hold." )

89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
vlc_module_begin ()
    set_shortname( "GnuTLS" )
    set_description( N_("GnuTLS transport layer security") )
    set_capability( "tls client", 1 )
    set_callbacks( OpenClient, CloseClient )
    set_category( CAT_ADVANCED )
    set_subcategory( SUBCAT_ADVANCED_MISC )

    add_obsolete_bool( "tls-check-cert" )
    add_obsolete_bool( "tls-check-hostname" )

    add_submodule ()
        set_description( N_("GnuTLS server") )
        set_capability( "tls server", 1 )
        set_category( CAT_ADVANCED )
        set_subcategory( SUBCAT_ADVANCED_MISC )
        set_callbacks( OpenServer, CloseServer )

        add_obsolete_integer( "gnutls-dh-bits" )
108
        add_integer( "gnutls-cache-timeout", CACHE_TIMEOUT, NULL,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
109
                    CACHE_TIMEOUT_TEXT, CACHE_TIMEOUT_LONGTEXT, true )
110
        add_integer( "gnutls-cache-size", CACHE_SIZE, NULL, CACHE_SIZE_TEXT,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
111
                    CACHE_SIZE_LONGTEXT, true )
112
vlc_module_end ()
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
113

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

116
117
118
119
120
/**
 * Initializes GnuTLS with proper locking.
 * @return VLC_SUCCESS on success, a VLC error code otherwise.
 */
static int gnutls_Init (vlc_object_t *p_this)
121
{
122
123
    int ret = VLC_EGENERIC;

124
    vlc_gcrypt_init (); /* GnuTLS depends on gcrypt */
125

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
126
    vlc_mutex_lock (&gnutls_mutex);
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
    if (gnutls_global_init ())
    {
        msg_Err (p_this, "cannot initialize GnuTLS");
        goto error;
    }

    const char *psz_version = gnutls_check_version ("1.3.3");
    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
145
    vlc_mutex_unlock (&gnutls_mutex);
146
147
148
149
150
151
152
153
154
    return ret;
}


/**
 * Deinitializes GnuTLS.
 */
static void gnutls_Deinit (vlc_object_t *p_this)
{
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
155
    vlc_mutex_lock (&gnutls_mutex);
156
157
158

    gnutls_global_deinit ();
    msg_Dbg (p_this, "GnuTLS deinitialized");
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
159
    vlc_mutex_unlock (&gnutls_mutex);
160
}
161
162


163
164
165
166
167
static int gnutls_Error (vlc_object_t *obj, int val)
{
    switch (val)
    {
        case GNUTLS_E_AGAIN:
168
169
170
#ifdef WIN32
            WSASetLastError (WSAEWOULDBLOCK);
#else
171
            errno = EAGAIN;
172
#endif
173
            break;
174
175

        case GNUTLS_E_INTERRUPTED:
176
177
#ifdef WIN32
            WSASetLastError (WSAEINTR);
178
#else
179
            errno = EINTR;
180
#endif
181
182
183
184
            break;

        default:
            msg_Err (obj, "%s", gnutls_strerror (val));
185
#ifndef NDEBUG
186
187
188
            if (!gnutls_error_is_fatal (val))
                msg_Err (obj, "Error above should be handled");
#endif
189
190
#ifdef WIN32
            WSASetLastError (WSAECONNRESET);
191
#else
192
            errno = ECONNRESET;
193
#endif
194
195
196
197
198
    }
    return -1;
}


199
200
struct tls_session_sys_t
{
201
202
    gnutls_session_t session;
    char            *psz_hostname;
203
    bool       b_handshaked;
204
205
206
};


207
/**
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
208
 * Sends data through a TLS session.
209
 */
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
210
static int
211
gnutls_Send( void *p_session, const void *buf, int i_length )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
212
213
{
    int val;
214
    tls_session_sys_t *p_sys;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
215

216
217
218
    p_sys = (tls_session_sys_t *)(((tls_session_t *)p_session)->p_sys);

    val = gnutls_record_send( p_sys->session, buf, i_length );
219
    return (val < 0) ? gnutls_Error ((vlc_object_t *)p_session, val) : val;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
220
221
222
}


223
/**
224
 * Receives data through a TLS session.
225
 */
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
226
static int
227
gnutls_Recv( void *p_session, void *buf, int i_length )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
228
229
{
    int val;
230
231
232
    tls_session_sys_t *p_sys;

    p_sys = (tls_session_sys_t *)(((tls_session_t *)p_session)->p_sys);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
233

234
    val = gnutls_record_recv( p_sys->session, buf, i_length );
235
    return (val < 0) ? gnutls_Error ((vlc_object_t *)p_session, val) : val;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
236
237
238
}


239
/**
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
240
241
242
243
244
 * Starts or continues the TLS handshake.
 *
 * @return -1 on fatal error, 0 on succesful handshake completion,
 * 1 if more would-be blocking recv is needed,
 * 2 if more would-be blocking send is required.
245
 */
246
static int
247
gnutls_ContinueHandshake (tls_session_t *p_session)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
248
{
249
    tls_session_sys_t *p_sys = p_session->p_sys;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
250
251
    int val;

252
253
254
#ifdef WIN32
    WSASetLastError( 0 );
#endif
255
256
257
    val = gnutls_handshake( p_sys->session );
    if( ( val == GNUTLS_E_AGAIN ) || ( val == GNUTLS_E_INTERRUPTED ) )
        return 1 + gnutls_record_get_direction( p_sys->session );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
258
259
260

    if( val < 0 )
    {
261
262
263
#ifdef WIN32
        msg_Dbg( p_session, "Winsock error %d", WSAGetLastError( ) );
#endif
264
        msg_Err( p_session, "TLS handshake error: %s",
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
265
                 gnutls_strerror( val ) );
266
        return -1;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
267
    }
268

269
    p_sys->b_handshaked = true;
270
271
272
    return 0;
}

273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295

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" },
    { 0, NULL }
};


296
static int
297
gnutls_HandshakeAndValidate( tls_session_t *session )
298
{
299
300
301
    int val = gnutls_ContinueHandshake( session );
    if( val )
        return val;
302

303
    tls_session_sys_t *p_sys = (tls_session_sys_t *)(session->p_sys);
304

305
306
307
308
309
310
311
312
    /* certificates chain verification */
    unsigned status;
    val = gnutls_certificate_verify_peers2( p_sys->session, &status );

    if( val )
    {
        msg_Err( session, "Certificate verification failed: %s",
                 gnutls_strerror( val ) );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
313
        return -1;
314
    }
315

316
317
318
319
    if( status )
    {
        msg_Err( session, "TLS session: access denied" );
        for( const error_msg_t *e = cert_errors; e->flag; e++ )
320
        {
321
322
            if( status & e->flag )
            {
323
                msg_Err( session, "%s", e->msg );
324
325
                status &= ~e->flag;
            }
326
327
328
        }

        if( status )
329
330
331
            msg_Err( session,
                     "unknown certificate error (you found a bug in VLC)" );

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
332
        return -1;
333
334
335
    }

    /* certificate (host)name verification */
336
337
    const gnutls_datum_t *data;
    data = gnutls_certificate_get_peers (p_sys->session, &(unsigned){0});
338
339
340
    if( data == NULL )
    {
        msg_Err( session, "Peer certificate not available" );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
341
        return -1;
342
343
    }

344
    gnutls_x509_crt_t cert;
345
346
347
348
    val = gnutls_x509_crt_init( &cert );
    if( val )
    {
        msg_Err( session, "x509 fatal error: %s", gnutls_strerror( val ) );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
349
        return -1;
350
351
352
353
354
355
356
    }

    val = gnutls_x509_crt_import( cert, data, GNUTLS_X509_FMT_DER );
    if( val )
    {
        msg_Err( session, "Certificate import error: %s",
                 gnutls_strerror( val ) );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
357
        goto error;
358
    }
359

360
361
    assert( p_sys->psz_hostname != NULL );
    if ( !gnutls_x509_crt_check_hostname( cert, p_sys->psz_hostname ) )
362
    {
363
364
365
        msg_Err( session, "Certificate does not match \"%s\"",
                 p_sys->psz_hostname );
        goto error;
366
367
368
369
370
    }

    if( gnutls_x509_crt_get_expiration_time( cert ) < time( NULL ) )
    {
        msg_Err( session, "Certificate expired" );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
371
        goto error;
372
373
    }

374
375
376
    if( gnutls_x509_crt_get_activation_time( cert ) > time ( NULL ) )
    {
        msg_Err( session, "Certificate not yet valid" );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
377
        goto error;
378
379
380
381
382
383
384
    }

    gnutls_x509_crt_deinit( cert );
    msg_Dbg( session, "TLS/x509 certificate verified" );
    return 0;

error:
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
385
    gnutls_x509_crt_deinit( cert );
386
    return -1;
387
388
}

389
/**
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
390
 * Sets the operating system file descriptor backend for the TLS sesison.
391
392
393
 *
 * @param fd stream socket already connected with the peer.
 */
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
394
395
static void
gnutls_SetFD (tls_session_t *p_session, int fd)
396
{
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
397
    gnutls_transport_set_ptr (p_session->p_sys->session,
398
                              (gnutls_transport_ptr_t)(intptr_t)fd);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
399
400
}

401
402
typedef int (*tls_prio_func) (gnutls_session_t, const int *);

403
static int
404
405
406
gnutls_SetPriority (vlc_object_t *restrict obj, const char *restrict name,
                    tls_prio_func func, gnutls_session_t session,
                    const int *restrict values)
407
{
408
    int val = func (session, values);
409
410
    if (val < 0)
    {
411
        msg_Err (obj, "cannot set %s priorities: %s", name,
412
413
414
                 gnutls_strerror (val));
        return VLC_EGENERIC;
    }
415
416
    return VLC_SUCCESS;
}
417

418
419
420
421

static int
gnutls_SessionPrioritize (vlc_object_t *obj, gnutls_session_t session)
{
422
    /* Note that ordering matters (on the client side) */
423
    static const int protos[] =
424
    {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
425
        /*GNUTLS_TLS1_2, as of GnuTLS 2.6.5, still not ratified */
426
427
428
429
430
431
432
        GNUTLS_TLS1_1,
        GNUTLS_TLS1_0,
        GNUTLS_SSL3,
        0
    };
    static const int comps[] =
    {
433
        GNUTLS_COMP_DEFLATE,
434
435
436
        GNUTLS_COMP_NULL,
        0
    };
437
438
    static const int macs[] =
    {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
439
440
441
        GNUTLS_MAC_SHA512,
        GNUTLS_MAC_SHA384,
        GNUTLS_MAC_SHA256,
442
443
444
445
446
447
448
449
450
451
452
453
454
        GNUTLS_MAC_SHA1,
        GNUTLS_MAC_RMD160, // RIPEMD
        GNUTLS_MAC_MD5,
        //GNUTLS_MAC_MD2,
        //GNUTLS_MAC_NULL,
        0
    };
    static const int ciphers[] =
    {
        GNUTLS_CIPHER_AES_256_CBC,
        GNUTLS_CIPHER_AES_128_CBC,
        GNUTLS_CIPHER_3DES_CBC,
        GNUTLS_CIPHER_ARCFOUR_128,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
455
        // TODO? Camellia ciphers?
456
457
458
459
460
461
        //GNUTLS_CIPHER_DES_CBC,
        //GNUTLS_CIPHER_ARCFOUR_40,
        //GNUTLS_CIPHER_RC2_40_CBC,
        //GNUTLS_CIPHER_NULL,
        0
    };
462
463
464
465
466
467
468
469
470
471
472
473
474
475
    static const int kx[] =
    {
        GNUTLS_KX_DHE_RSA,
        GNUTLS_KX_DHE_DSS,
        GNUTLS_KX_RSA,
        //GNUTLS_KX_RSA_EXPORT,
        //GNUTLS_KX_DHE_PSK, TODO
        //GNUTLS_KX_PSK,     TODO
        //GNUTLS_KX_SRP_RSA, TODO
        //GNUTLS_KX_SRP_DSS, TODO
        //GNUTLS_KX_SRP,     TODO
        //GNUTLS_KX_ANON_DH,
        0
    };
476
477
478
479
480
481
    static const int cert_types[] =
    {
        GNUTLS_CRT_X509,
        //GNUTLS_CRT_OPENPGP, TODO
        0
    };
482

483
    int val = gnutls_set_default_priority (session);
484
485
    if (val < 0)
    {
486
        msg_Err (obj, "cannot set default TLS priorities: %s",
487
488
489
490
                 gnutls_strerror (val));
        return VLC_EGENERIC;
    }

491
492
    if (gnutls_SetPriority (obj, "protocols",
                            gnutls_protocol_set_priority, session, protos)
493
     || gnutls_SetPriority (obj, "compression algorithms",
494
                            gnutls_compression_set_priority, session, comps)
495
     || gnutls_SetPriority (obj, "MAC algorithms",
496
497
498
                            gnutls_mac_set_priority, session, macs)
     || gnutls_SetPriority (obj, "ciphers",
                            gnutls_cipher_set_priority, session, ciphers)
499
500
     || gnutls_SetPriority (obj, "key exchange algorithms",
                            gnutls_kx_set_priority, session, kx)
501
502
503
504
505
     || gnutls_SetPriority (obj, "certificate types",
                            gnutls_certificate_type_set_priority, session,
                            cert_types))
        return VLC_EGENERIC;

506
507
508
509
    return VLC_SUCCESS;
}


510
511
static int
gnutls_Addx509File( vlc_object_t *p_this,
512
                    gnutls_certificate_credentials_t cred,
513
                    const char *psz_path, bool b_priv );
514

515
static int
516
gnutls_Addx509Directory( vlc_object_t *p_this,
517
                         gnutls_certificate_credentials_t cred,
518
                         const char *psz_dirname,
519
                         bool b_priv )
520
521
522
523
524
525
{
    DIR* dir;

    if( *psz_dirname == '\0' )
        psz_dirname = ".";

526
    dir = vlc_opendir( psz_dirname );
527
528
    if( dir == NULL )
    {
529
530
531
532
533
534
535
536
        if (errno != ENOENT)
        {
            msg_Err (p_this, "cannot open directory (%s): %m", psz_dirname);
            return VLC_EGENERIC;
        }

        msg_Dbg (p_this, "creating empty certificate directory: %s",
                 psz_dirname);
537
        vlc_mkdir (psz_dirname, b_priv ? 0700 : 0755);
538
        return VLC_SUCCESS;
539
    }
540
541
542
543
544
545
546
547
548
549
550
#ifdef S_ISLNK
    else
    {
        struct stat st1, st2;
        int fd = dirfd( dir );

        /*
         * Gets stats for the directory path, checks that it is not a
         * symbolic link (to avoid possibly infinite recursion), and verifies
         * that the inode is still the same, to avoid TOCTOU race condition.
         */
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
551
        if( ( fd == -1)
552
         || fstat( fd, &st1 ) || vlc_lstat( psz_dirname, &st2 )
553
554
         || S_ISLNK( st2.st_mode ) || ( st1.st_ino != st2.st_ino ) )
        {
555
            closedir( dir );
556
557
558
559
            return VLC_EGENERIC;
        }
    }
#endif
560

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
561
    for (;;)
562
    {
563
        char *ent = vlc_readdir (dir);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
564
565
        if (ent == NULL)
            break;
566

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
567
        if ((strcmp (ent, ".") == 0) || (strcmp (ent, "..") == 0))
ivoire's avatar
ivoire committed
568
569
        {
            free( ent );
570
            continue;
ivoire's avatar
ivoire committed
571
        }
572

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
573
574
575
        char path[strlen (psz_dirname) + strlen (ent) + 2];
        sprintf (path, "%s"DIR_SEP"%s", psz_dirname, ent);
        free (ent);
576

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
577
        gnutls_Addx509File( p_this, cred, path, b_priv );
578
579
    }

580
    closedir( dir );
581
582
583
584
585
586
587
    return VLC_SUCCESS;
}


static int
gnutls_Addx509File( vlc_object_t *p_this,
                    gnutls_certificate_credentials cred,
588
                    const char *psz_path, bool b_priv )
589
590
591
{
    struct stat st;

592
    int fd = vlc_open (psz_path, O_RDONLY);
593
594
595
596
597
    if (fd == -1)
        goto error;

    block_t *block = block_File (fd);
    if (block != NULL)
598
    {
599
600
601
602
603
604
605
606
607
608
609
610
611
612
        close (fd);

        gnutls_datum data = {
            .data = block->p_buffer,
            .size = block->i_buffer,
        };
        int res = b_priv
            ? 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)
613
        {
614
615
616
            msg_Warn (p_this, "cannot add x509 credentials (%s): %s",
                      psz_path, gnutls_strerror (res));
            return VLC_EGENERIC;
617
        }
618
619
        msg_Dbg (p_this, "added x509 credentials (%s)", psz_path);
        return VLC_SUCCESS;
620
    }
621
622
623
624
625
626
627
628
629
630
631
632
633

    if (!fstat (fd, &st) && S_ISDIR (st.st_mode))
    {
        close (fd);
        msg_Dbg (p_this, "looking recursively for x509 credentials in %s",
                 psz_path);
        return gnutls_Addx509Directory (p_this, cred, psz_path, b_priv);
    }

error:
    msg_Warn (p_this, "cannot add x509 credentials (%s): %m", psz_path);
    if (fd != -1)
        close (fd);
634
    return VLC_EGENERIC;
635
636
}

637

638
639
640
/** TLS client session data */
typedef struct tls_client_sys_t
{
641
642
    struct tls_session_sys_t         session;
    gnutls_certificate_credentials_t x509_cred;
643
644
645
} tls_client_sys_t;


646
647
648
/**
 * Initializes a client-side TLS session.
 */
649
static int OpenClient (vlc_object_t *obj)
650
{
651
    tls_session_t *p_session = (tls_session_t *)obj;
652
653
    int i_val;

654
655
    if (gnutls_Init (obj))
        return VLC_EGENERIC;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
656

657
658
    tls_client_sys_t *p_sys = malloc (sizeof (*p_sys));
    if (p_sys == NULL)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
659
    {
660
661
        gnutls_Deinit (obj);
        return VLC_ENOMEM;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
662
663
    }

664
    p_session->p_sys = &p_sys->session;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
665
666
667
    p_session->sock.p_sys = p_session;
    p_session->sock.pf_send = gnutls_Send;
    p_session->sock.pf_recv = gnutls_Recv;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
668
    p_session->pf_set_fd = gnutls_SetFD;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
669

670
    p_sys->session.b_handshaked = false;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
671

672
673
    i_val = gnutls_certificate_allocate_credentials (&p_sys->x509_cred);
    if (i_val != 0)
674
    {
675
676
        msg_Err (obj, "cannot allocate X509 credentials: %s",
                 gnutls_strerror (i_val));
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
677
        goto error;
678
679
    }

Erwan Tulou's avatar
Erwan Tulou committed
680
    char *userdir = config_GetUserDir ( VLC_DATA_DIR );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
681
682
683
684
    if (userdir != NULL)
    {
        char path[strlen (userdir) + sizeof ("/ssl/private")];
        sprintf (path, "%s/ssl", userdir);
685
        vlc_mkdir (path, 0755);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
686
687
688
689
690
691
692
693
694

        sprintf (path, "%s/ssl/certs", userdir);
        gnutls_Addx509Directory (VLC_OBJECT (p_session),
                                 p_sys->x509_cred, path, false);
        sprintf (path, "%s/ssl/private", userdir);
        gnutls_Addx509Directory (VLC_OBJECT (p_session), p_sys->x509_cred,
                                 path, true);
        free (userdir);
    }
695

696
    const char *confdir = config_GetConfDir ();
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
697
    {
698
699
700
        char path[strlen (confdir)
                   + sizeof ("/ssl/certs/ca-certificates.crt")];
        sprintf (path, "%s/ssl/certs/ca-certificates.crt", confdir);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
701
702
703
        gnutls_Addx509File (VLC_OBJECT (p_session),
                            p_sys->x509_cred, path, false);
    }
704
705
    p_session->pf_handshake = gnutls_HandshakeAndValidate;
    /*p_session->pf_handshake = gnutls_ContinueHandshake;*/
706

707
    i_val = gnutls_init (&p_sys->session.session, GNUTLS_CLIENT);
708
    if (i_val != 0)
709
    {
710
711
712
        msg_Err (obj, "cannot initialize TLS session: %s",
                 gnutls_strerror (i_val));
        gnutls_certificate_free_credentials (p_sys->x509_cred);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
713
        goto error;
714
715
    }

716
717
718
    if (gnutls_SessionPrioritize (VLC_OBJECT (p_session),
                                  p_sys->session.session))
        goto s_error;
719

720
721
722
    /* minimum DH prime bits */
    gnutls_dh_set_prime_bits (p_sys->session.session, 1024);

723
    i_val = gnutls_credentials_set (p_sys->session.session,
724
                                    GNUTLS_CRD_CERTIFICATE,
725
726
                                    p_sys->x509_cred);
    if (i_val < 0)
727
    {
728
729
        msg_Err (obj, "cannot set TLS session credentials: %s",
                 gnutls_strerror (i_val));
730
        goto s_error;
731
732
    }

733
    char *servername = var_GetNonEmptyString (p_session, "tls-server-name");
734
735
    if (servername == NULL )
        msg_Err (p_session, "server name missing for TLS session");
736
737
738
    else
        gnutls_server_name_set (p_sys->session.session, GNUTLS_NAME_DNS,
                                servername, strlen (servername));
739
740

    p_sys->session.psz_hostname = servername;
741

742
    return VLC_SUCCESS;
743

744
s_error:
745
746
    gnutls_deinit (p_sys->session.session);
    gnutls_certificate_free_credentials (p_sys->x509_cred);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
747
error:
748
749
750
751
    gnutls_Deinit (obj);
    free (p_sys);
    return VLC_EGENERIC;
}
752

753
754
755
756
757
758

static void CloseClient (vlc_object_t *obj)
{
    tls_session_t *client = (tls_session_t *)obj;
    tls_client_sys_t *p_sys = (tls_client_sys_t *)(client->p_sys);

759
    if (p_sys->session.b_handshaked == true)
760
761
762
763
764
765
766
767
        gnutls_bye (p_sys->session.session, GNUTLS_SHUT_WR);
    gnutls_deinit (p_sys->session.session);
    /* credentials must be free'd *after* gnutls_deinit() */
    gnutls_certificate_free_credentials (p_sys->x509_cred);

    gnutls_Deinit (obj);
    free (p_sys->session.psz_hostname);
    free (p_sys);
768
769
770
}


771
772
773
774
775
/**
 * Server-side TLS
 */
struct tls_server_sys_t
{
776
777
    gnutls_certificate_credentials_t x509_cred;
    gnutls_dh_params_t               dh_params;
778
779
780

    struct saved_session_t          *p_cache;
    struct saved_session_t          *p_store;
781
782
    int                              i_cache_size;
    vlc_mutex_t                      cache_lock;
783

784
    int                            (*pf_handshake) (tls_session_t *);
785
786
787
};


788
789
790
/**
 * TLS session resumption callbacks (server-side)
 */
791
792
793
794
795
796
797
798
799
800
801
802
803
#define MAX_SESSION_ID    32
#define MAX_SESSION_DATA  1024

typedef struct saved_session_t
{
    char id[MAX_SESSION_ID];
    char data[MAX_SESSION_DATA];

    unsigned i_idlen;
    unsigned i_datalen;
} saved_session_t;


804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
static int cb_store( void *p_server, gnutls_datum key, gnutls_datum data )
{
    tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;

    if( ( p_sys->i_cache_size == 0 )
     || ( key.size > MAX_SESSION_ID )
     || ( data.size > MAX_SESSION_DATA ) )
        return -1;

    vlc_mutex_lock( &p_sys->cache_lock );

    memcpy( p_sys->p_store->id, key.data, key.size);
    memcpy( p_sys->p_store->data, data.data, data.size );
    p_sys->p_store->i_idlen = key.size;
    p_sys->p_store->i_datalen = data.size;

    p_sys->p_store++;
    if( ( p_sys->p_store - p_sys->p_cache ) == p_sys->i_cache_size )
        p_sys->p_store = p_sys->p_cache;

    vlc_mutex_unlock( &p_sys->cache_lock );

    return 0;
}


static gnutls_datum cb_fetch( void *p_server, gnutls_datum key )
{
832
    static const gnutls_datum_t err_datum = { NULL, 0 };
833
834
835
836
837
838
839
840
841
842
843
844
845
    tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
    saved_session_t *p_session, *p_end;

    p_session = p_sys->p_cache;
    p_end = p_session + p_sys->i_cache_size;

    vlc_mutex_lock( &p_sys->cache_lock );

    while( p_session < p_end )
    {
        if( ( p_session->i_idlen == key.size )
         && !memcmp( p_session->id, key.data, key.size ) )
        {
846
            gnutls_datum_t data;
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897

            data.size = p_session->i_datalen;

            data.data = gnutls_malloc( data.size );
            if( data.data == NULL )
            {
                vlc_mutex_unlock( &p_sys->cache_lock );
                return err_datum;
            }

            memcpy( data.data, p_session->data, data.size );
            vlc_mutex_unlock( &p_sys->cache_lock );
            return data;
        }
        p_session++;
    }

    vlc_mutex_unlock( &p_sys->cache_lock );

    return err_datum;
}


static int cb_delete( void *p_server, gnutls_datum key )
{
    tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
    saved_session_t *p_session, *p_end;

    p_session = p_sys->p_cache;
    p_end = p_session + p_sys->i_cache_size;

    vlc_mutex_lock( &p_sys->cache_lock );

    while( p_session < p_end )
    {
        if( ( p_session->i_idlen == key.size )
         && !memcmp( p_session->id, key.data, key.size ) )
        {
            p_session->i_datalen = p_session->i_idlen = 0;
            vlc_mutex_unlock( &p_sys->cache_lock );
            return 0;
        }
        p_session++;
    }

    vlc_mutex_unlock( &p_sys->cache_lock );

    return -1;
}


898
899
900
901
902
/**
 * Terminates TLS session and releases session data.
 * You still have to close the socket yourself.
 */
static void
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
903
gnutls_SessionClose (tls_server_t *p_server, tls_session_t *p_session)
904
905
{
    tls_session_sys_t *p_sys = p_session->p_sys;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
906
    (void)p_server;
907

908
    if( p_sys->b_handshaked == true )
909
910
911
        gnutls_bye( p_sys->session, GNUTLS_SHUT_WR );
    gnutls_deinit( p_sys->session );

912
    vlc_object_release( p_session );
913
914
915
916
917

    free( p_sys );
}


918
919
920
/**
 * Initializes a server-side TLS session.
 */
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
921
922
923
924
static tls_session_t *
gnutls_ServerSessionPrepare( tls_server_t *p_server )
{
    tls_session_t *p_session;
925
    tls_server_sys_t *p_server_sys;
926
    gnutls_session_t session;
927
    int i_val;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
928

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
929
930
931
    p_session = vlc_object_create( p_server, sizeof (struct tls_session_t) );
    if( p_session == NULL )
        return NULL;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
932

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
933
934
935
    p_session->p_sys = malloc( sizeof(struct tls_session_sys_t) );
    if( p_session->p_sys == NULL )
    {
936
        vlc_object_release( p_session );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
937
938
939
        return NULL;
    }

940
    p_server_sys = p_server->p_sys;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
941
942
943
    p_session->sock.p_sys = p_session;
    p_session->sock.pf_send = gnutls_Send;
    p_session->sock.pf_recv = gnutls_Recv;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
944
945
    p_session->pf_set_fd = gnutls_SetFD;
    p_session->pf_handshake = p_server_sys->pf_handshake;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
946

947
    p_session->p_sys->b_handshaked = false;
948
    p_session->p_sys->psz_hostname = NULL;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
949

950
    i_val = gnutls_init( &session, GNUTLS_SERVER );
951
    if( i_val != 0 )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
952
    {
953
        msg_Err( p_server, "cannot initialize TLS session: %s",
954
                 gnutls_strerror( i_val ) );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
955
        goto error;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
956
    }
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
957

958
    p_session->p_sys->session = session;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
959

960
    if (gnutls_SessionPrioritize (VLC_OBJECT (p_session), session))
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
961
    {
962
        gnutls_deinit( session );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
963
        goto error;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
964
965
    }

966
    i_val = gnutls_credentials_set( session, GNUTLS_CRD_CERTIFICATE,
967
                                    p_server_sys->x509_cred );
968
    if( i_val < 0 )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
969
    {
970
        msg_Err( p_server, "cannot set TLS session credentials: %s",
971
                 gnutls_strerror( i_val ) );
972
        gnutls_deinit( session );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
973
        goto error;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
974
975
    }

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
976
977
    if (p_session->pf_handshake == gnutls_HandshakeAndValidate)
        gnutls_certificate_server_set_request (session, GNUTLS_CERT_REQUIRE);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
978

979
    /* Session resumption support */
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
980
    i_val = var_InheritInteger (p_server, "gnutls-cache-timeout");
981
982
    if (i_val >= 0)
        gnutls_db_set_cache_expiration (session, i_val);
983
984
985
986
    gnutls_db_set_retrieve_function( session, cb_fetch );
    gnutls_db_set_remove_function( session, cb_delete );
    gnutls_db_set_store_function( session, cb_store );
    gnutls_db_set_ptr( session, p_server );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
987
988

    return p_session;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
989
990
991

error:
    free( p_session->p_sys );
992
    vlc_object_release( p_session );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
993
    return NULL;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
994
995
996
}


997
/**
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
998
 * Adds one or more certificate authorities.
999
1000
1001
1002
 *
 * @param psz_ca_path (Unicode) path to an x509 certificates list.
 *
 * @return -1 on error, 0 on success.
1003
 */
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1004
1005
1006
static int
gnutls_ServerAddCA( tls_server_t *p_server, const char *psz_ca_path )
{
1007
    tls_server_sys_t *p_sys;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1008
1009
    char *psz_local_path;
    int val;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1010

1011
1012
    p_sys = (tls_server_sys_t *)(p_server->p_sys);

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1013
    psz_local_path = ToLocale( psz_ca_path );
1014
    val = gnutls_certificate_set_x509_trust_file( p_sys->x509_cred,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1015
                                                  psz_local_path,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1016
                                                  GNUTLS_X509_FMT_PEM );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1017
    LocaleFree( psz_local_path );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1018
1019
    if( val < 0 )
    {
1020
        msg_Err( p_server, "cannot add trusted CA (%s): %s", psz_ca_path,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1021
                 gnutls_strerror( val ) );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1022
1023
        return VLC_EGENERIC;
    }
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1024
    msg_Dbg( p_server, " %d trusted CA added (%s)", val, psz_ca_path );
1025
1026

    /* enables peer's certificate verification */
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1027
    p_sys->pf_handshake = gnutls_HandshakeAndValidate;
1028

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1029
1030
1031
1032
    return VLC_SUCCESS;
}


1033
/**
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1034
 * Adds a certificates revocation list to be sent to TLS clients.
1035
1036
1037
1038
1039
 *
 * @param psz_crl_path (Unicode) path of the CRL file.
 *
 * @return -1 on error, 0 on success.
 */
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1040
1041
1042
1043
static int
gnutls_ServerAddCRL( tls_server_t *p_server, const char *psz_crl_path )
{
    int val;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1044
    char *psz_local_path = ToLocale( psz_crl_path );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1045
1046
1047

    val = gnutls_certificate_set_x509_crl_file( ((tls_server_sys_t *)
                                                (p_server->p_sys))->x509_cred,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1048
                                                psz_local_path,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1049
                                                GNUTLS_X509_FMT_PEM );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1050
    LocaleFree( psz_crl_path );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1051
1052
    if( val < 0 )
    {
1053
        msg_Err( p_server, "cannot add CRL (%s): %s", psz_crl_path,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1054
                 gnutls_strerror( val ) );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1055
1056
        return VLC_EGENERIC;
    }
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1057
    msg_Dbg( p_server, "%d CRL added (%s)", val, psz_crl_path );