File: tls_gnutls.c

package info (click to toggle)
chrony 4.8-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,784 kB
  • sloc: ansic: 38,349; sh: 5,833; yacc: 862; makefile: 232
file content (409 lines) | stat: -rw-r--r-- 11,127 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/*
  chronyd/chronyc - Programs for keeping computer clocks accurate.

 **********************************************************************
 * Copyright (C) Miroslav Lichvar  2020-2021
 * Copyright (C) Anthony Brandon  2025
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2 of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * 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 Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 **********************************************************************

  =======================================================================

  Routines implementing TLS session handling using the gnutls library.
  */

#include "config.h"

#include "sysincl.h"

#include "tls.h"

#include "conf.h"
#include "logging.h"
#include "memory.h"
#include "util.h"

#include <gnutls/gnutls.h>
#include <gnutls/x509.h>

struct TLS_Instance_Record {
  gnutls_session_t session;
  int server;
  char *label;
  char *alpn_name;
};

/* ================================================== */

static gnutls_priority_t priority_cache;

/* ================================================== */

int
TLS_Initialise(time_t (*get_time)(time_t *t))
{
  int r = gnutls_global_init();

  if (r < 0)
    LOG_FATAL("Could not initialise %s : %s", "gnutls", gnutls_strerror(r));

  /* Prepare a priority cache for server and client NTS-KE sessions
     (the NTS specification requires TLS1.3 or later) */
  r = gnutls_priority_init2(&priority_cache,
                            "-VERS-SSL3.0:-VERS-TLS1.0:-VERS-TLS1.1:-VERS-TLS1.2:-VERS-DTLS-ALL",
                            NULL, GNUTLS_PRIORITY_INIT_DEF_APPEND);
  if (r < 0) {
    LOG(LOGS_ERR, "Could not initialise %s : %s",
        "priority cache for TLS", gnutls_strerror(r));
    gnutls_global_deinit();
    return 0;
  }

  /* Use our clock instead of the system clock in certificate verification */
  gnutls_global_set_time_function(get_time);

  return 1;
}

/* ================================================== */

void
TLS_Finalise(void)
{
  gnutls_priority_deinit(priority_cache);
  gnutls_global_deinit();
}

/* ================================================== */

TLS_Credentials
TLS_CreateCredentials(const char **certs, const char **keys, int n_certs_keys,
                      const char **trusted_certs, uint32_t *trusted_certs_ids,
                      int n_trusted_certs, uint32_t trusted_cert_set)
{
  gnutls_certificate_credentials_t credentials = NULL;
  int i, r;

  r = gnutls_certificate_allocate_credentials(&credentials);
  if (r < 0)
    goto error;

  if (certs && keys) {
    BRIEF_ASSERT(!trusted_certs && !trusted_certs_ids);

    for (i = 0; i < n_certs_keys; i++) {
      if (!UTI_CheckFilePermissions(keys[i], 0771))
        ;
      r = gnutls_certificate_set_x509_key_file(credentials, certs[i], keys[i],
                                               GNUTLS_X509_FMT_PEM);
      if (r < 0)
        goto error;
    }
  } else {
    BRIEF_ASSERT(!certs && !keys && n_certs_keys <= 0);

    if (trusted_cert_set == 0 && !CNF_GetNoSystemCert()) {
      r = gnutls_certificate_set_x509_system_trust(credentials);
      if (r < 0)
        goto error;
    }

    if (trusted_certs && trusted_certs_ids) {
      for (i = 0; i < n_trusted_certs; i++) {
        struct stat buf;

        if (trusted_certs_ids[i] != trusted_cert_set)
          continue;

        if (stat(trusted_certs[i], &buf) == 0 && S_ISDIR(buf.st_mode))
          r = gnutls_certificate_set_x509_trust_dir(credentials, trusted_certs[i],
                                                    GNUTLS_X509_FMT_PEM);
        else
          r = gnutls_certificate_set_x509_trust_file(credentials, trusted_certs[i],
                                                     GNUTLS_X509_FMT_PEM);
        if (r < 0)
          goto error;

        DEBUG_LOG("Added %d trusted certs from %s", r, trusted_certs[i]);
      }
    }
  }

  return credentials;

error:
  LOG(LOGS_ERR, "Could not set credentials : %s", gnutls_strerror(r));
  if (credentials)
    gnutls_certificate_free_credentials(credentials);
  return NULL;
}

/* ================================================== */

void
TLS_DestroyCredentials(TLS_Credentials credentials)
{
  gnutls_certificate_free_credentials((gnutls_certificate_credentials_t)credentials);
}

/* ================================================== */

TLS_Instance
TLS_CreateInstance(int server_mode, int sock_fd, const char *server_name, const char *label,
                   const char *alpn_name, TLS_Credentials credentials, int disable_time_checks)
{
  gnutls_datum_t alpn;
  unsigned int flags;
  int r;

  TLS_Instance inst = MallocNew(struct TLS_Instance_Record);

  inst->session = NULL;
  inst->server = server_mode;
  inst->label = Strdup(label);
  inst->alpn_name = Strdup(alpn_name);

  r = gnutls_init(&inst->session, GNUTLS_NONBLOCK | GNUTLS_NO_TICKETS |
                                  (server_mode ? GNUTLS_SERVER : GNUTLS_CLIENT));
  if (r < 0) {
    LOG(LOGS_ERR, "Could not %s TLS session : %s", "create", gnutls_strerror(r));
    inst->session = NULL;
    goto error;
  }

  if (!server_mode) {
    assert(server_name);

    if (!UTI_IsStringIP(server_name)) {
      r = gnutls_server_name_set(inst->session, GNUTLS_NAME_DNS, server_name,
                                 strlen(server_name));
      if (r < 0)
        goto error;
    }

    flags = 0;

    if (disable_time_checks) {
      flags |= GNUTLS_VERIFY_DISABLE_TIME_CHECKS | GNUTLS_VERIFY_DISABLE_TRUSTED_TIME_CHECKS;
      DEBUG_LOG("Disabled time checks");
    }

    gnutls_session_set_verify_cert(inst->session, server_name, flags);
  }

  r = gnutls_priority_set(inst->session, priority_cache);
  if (r < 0)
    goto error;

  r = gnutls_credentials_set(inst->session, GNUTLS_CRD_CERTIFICATE, credentials);
  if (r < 0)
    goto error;

  alpn.data = (unsigned char *)inst->alpn_name;
  alpn.size = strlen(inst->alpn_name);

  r = gnutls_alpn_set_protocols(inst->session, &alpn, 1, 0);
  if (r < 0)
    goto error;

  gnutls_transport_set_int(inst->session, sock_fd);

  return inst;

error:
  LOG(LOGS_ERR, "Could not %s TLS session : %s", "set", gnutls_strerror(r));
  TLS_DestroyInstance(inst);
  return NULL;
}

/* ================================================== */

void
TLS_DestroyInstance(TLS_Instance inst)
{
  if (inst->session)
    gnutls_deinit(inst->session);

  Free(inst->label);
  Free(inst->alpn_name);

  Free(inst);
}

/* ================================================== */

static int
check_alpn(TLS_Instance inst)
{
  gnutls_datum_t alpn;
  int length = strlen(inst->alpn_name);

  if (gnutls_alpn_get_selected_protocol(inst->session, &alpn) < 0 ||
      alpn.size != length || memcmp(alpn.data, inst->alpn_name, length) != 0)
    return 0;

  return 1;
}

/* ================================================== */

TLS_Status
TLS_DoHandshake(TLS_Instance inst)
{
  int r = gnutls_handshake(inst->session);

  if (r < 0) {
    if (gnutls_error_is_fatal(r)) {
      gnutls_datum_t cert_error;

      /* Get a description of verification errors */
      if (r != GNUTLS_E_CERTIFICATE_VERIFICATION_ERROR ||
          gnutls_certificate_verification_status_print(
              gnutls_session_get_verify_cert_status(inst->session),
              gnutls_certificate_type_get(inst->session), &cert_error, 0) < 0)
        cert_error.data = NULL;

      LOG(inst->server ? LOGS_DEBUG : LOGS_ERR,
          "TLS handshake with %s failed : %s%s%s", inst->label, gnutls_strerror(r),
          cert_error.data ? " " : "", cert_error.data ? (const char *)cert_error.data : "");

      if (cert_error.data)
        gnutls_free(cert_error.data);

      /* Increase the retry interval if the handshake did not fail due
         to the other end closing the connection */
      if (r != GNUTLS_E_PULL_ERROR && r != GNUTLS_E_PREMATURE_TERMINATION)
        return TLS_FAILED;

      return TLS_CLOSED;
    }

    return gnutls_record_get_direction(inst->session) ? TLS_AGAIN_OUTPUT : TLS_AGAIN_INPUT;
  }

  if (DEBUG) {
    char *description = gnutls_session_get_desc(inst->session);
    DEBUG_LOG("Handshake with %s completed %s", inst->label, description ? description : "");
    gnutls_free(description);
  }

  if (!check_alpn(inst)) {
    LOG(inst->server ? LOGS_DEBUG : LOGS_ERR, "NTS-KE not supported by %s", inst->label);
    return TLS_FAILED;
  }

  return TLS_SUCCESS;
}

/* ================================================== */

TLS_Status
TLS_Send(TLS_Instance inst, const void *data, int length, int *sent)
{
  int r;

  if (length < 0)
    return TLS_FAILED;

  r = gnutls_record_send(inst->session, data, length);

  if (r < 0) {
    if (gnutls_error_is_fatal(r)) {
      LOG(inst->server ? LOGS_DEBUG : LOGS_ERR,
          "Could not send NTS-KE message to %s : %s", inst->label, gnutls_strerror(r));
      return TLS_FAILED;
    }

    return TLS_AGAIN_OUTPUT;
  }

  *sent = r;

  return TLS_SUCCESS;
}

/* ================================================== */

TLS_Status
TLS_Receive(TLS_Instance inst, void *data, int length, int *received)
{
  int r;

  if (length < 0)
    return TLS_FAILED;

  r = gnutls_record_recv(inst->session, data, length);

  if (r < 0) {
    /* Handle a renegotiation request on both client and server as
       a protocol error */
    if (gnutls_error_is_fatal(r) || r == GNUTLS_E_REHANDSHAKE) {
      LOG(inst->server ? LOGS_DEBUG : LOGS_ERR,
          "Could not receive NTS-KE message from %s : %s", inst->label, gnutls_strerror(r));
      return TLS_FAILED;
    }

    return TLS_AGAIN_INPUT;
  }

  *received = r;

  return TLS_SUCCESS;
}

/* ================================================== */

int
TLS_CheckPending(TLS_Instance inst)
{
  return gnutls_record_check_pending(inst->session) > 0;
}

/* ================================================== */

TLS_Status
TLS_Shutdown(TLS_Instance inst)
{
  int r = gnutls_bye(inst->session, GNUTLS_SHUT_RDWR);

  if (r < 0) {
    if (gnutls_error_is_fatal(r)) {
      DEBUG_LOG("Shutdown with %s failed : %s", inst->label, gnutls_strerror(r));
      return TLS_FAILED;
    }

    return gnutls_record_get_direction(inst->session) ? TLS_AGAIN_OUTPUT : TLS_AGAIN_INPUT;
  }

  return TLS_SUCCESS;
}

/* ================================================== */

int
TLS_ExportKey(TLS_Instance inst, int label_length, const char *label, int context_length,
              const void *context, int key_length, unsigned char *key)
{
  int r;

  if (label_length < 0 || context_length < 0 || key_length < 0)
    return 0;

  r = gnutls_prf_rfc5705(inst->session, label_length, label, context_length, (char *)context,
                         key_length, (char *)key);

  return r >= 0;
}