Coverage Report

Created: 2026-12-01 06:37

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ntpsec/ntpd/nts_server.c
Line
Count
Source
1
/*
2
 * nts_server.c - Network Time Security (NTS) server side support
3
 * Copyright the NTPsec project contributors
4
 * SPDX-License-Identifier: BSD-2-Clause
5
 *
6
 * Section references are to
7
 * https://tools.ietf.org/html/rfc8915
8
 *
9
 */
10
#include "config.h"
11
12
#include <signal.h>
13
#include <pthread.h>
14
#include <unistd.h>
15
#include <sys/socket.h>
16
#include <sys/time.h>
17
#include <sys/resource.h>
18
19
#include <openssl/ssl.h>
20
#include <openssl/err.h>
21
#include <openssl/x509.h>
22
23
#include "ntp.h"
24
#include "ntpd.h"
25
#include "ntp_stdlib.h"
26
#include "nts.h"
27
#include "nts2.h"
28
#include "timespecops.h"
29
30
/* Beware: bind and accept take type sockaddr, but that's not big
31
 *         enough for an IPv6 address.
32
 */
33
34
static bool create_listener4(int port);
35
static bool create_listener6(int port);
36
static void* nts_ke_listener(void*);
37
static void nts_ke_request(NTS_Server_Info *nsi, SSL *ssl);
38
static void nts_ke_accept_fail(NTS_Server_Info *nsi,
39
  int code, const unsigned char *alpn);
40
41
static void nts_lock_certlock(void);
42
static void nts_unlock_certlock(void);
43
44
45
static SSL_CTX *server_ctx = NULL;
46
static int listener4_sock = -1;
47
static int listener6_sock = -1;
48
49
static void nts_ke_setup_send(BufCtl *buf, int aead,
50
       uint8_t *c2s, uint8_t *s2c, int keylen);
51
52
void log_ntske (NTS_Server_Info *nsi, NTSKE_Status status, const char *using);
53
54
/* We need a lock to protect reloading our certificate.
55
 * This seems like overkill, but it doesn't happen often. */
56
pthread_mutex_t certificate_lock = PTHREAD_MUTEX_INITIALIZER;
57
58
static int alpn_select_cb(SSL *ssl,
59
                          const unsigned char **out,
60
                          unsigned char *outlen,
61
                          const unsigned char *in,
62
                          unsigned int inlen,
63
                          void *arg)
64
0
{
65
0
        static const unsigned char alpn[] = {
66
0
            'n', 't', 's', 'k', 'e', '/', '1' };
67
0
        unsigned i, len;
68
69
0
        UNUSED_ARG(ssl);
70
0
        UNUSED_ARG(arg);
71
72
0
        for (i = 0; i < inlen; i += len+1) {
73
0
                len = in[i]; // first byte is the length
74
#if 0
75
                char foo[256];
76
                strlcpy(foo, (const char*)in+i+1, len);
77
                msyslog(LOG_DEBUG, "DEBUG: alpn_select_cb:  %u, %u, %s", inlen-i, len, foo);
78
#endif
79
0
                if (len+1 > inlen-i)
80
                        // bogus arg: length overlaps end of in buffer
81
0
                        return SSL_TLSEXT_ERR_ALERT_FATAL;
82
0
                if (len == sizeof(alpn) && !memcmp(in+i+1, alpn, len)) {
83
0
                        *out = in+i+1;
84
0
                        *outlen = len;
85
0
                        return SSL_TLSEXT_ERR_OK;
86
0
                }
87
0
        }
88
89
0
        return SSL_TLSEXT_ERR_NOACK;
90
0
}
91
92
0
bool nts_server_init(void) {
93
0
        bool ok = true;
94
95
0
        msyslog(LOG_INFO, "NTSs: starting NTS-KE server listening on port %d",
96
0
                NTS_KE_PORT);
97
98
0
        server_ctx = SSL_CTX_new(TLS_server_method());
99
0
        if (NULL == server_ctx) {
100
                // Happens if no ciphers
101
0
                msyslog(LOG_INFO, "NTSs: NULL server_ctx");
102
0
                nts_log_ssl_error();
103
0
                return false;
104
0
        }
105
106
0
        SSL_CTX_set_alpn_select_cb(server_ctx, alpn_select_cb, NULL);
107
0
        SSL_CTX_set_session_cache_mode(server_ctx, SSL_SESS_CACHE_OFF);
108
0
        SSL_CTX_set_timeout(server_ctx, NTS_KE_TIMEOUT);  // session lifetime
109
110
0
        ok &= nts_load_versions(server_ctx);
111
0
        ok &= nts_load_ciphers(server_ctx);
112
0
        ok &= nts_load_ecdhcurves(server_ctx);
113
0
        ok &= nts_set_cipher_order(server_ctx);
114
115
0
        if (!ok) {
116
0
                msyslog(LOG_ERR, "NTSs: Disabling NTS-KE server");
117
0
                SSL_CTX_free(server_ctx);
118
0
                server_ctx = NULL;
119
0
                return false;
120
0
        };
121
122
0
        msyslog(LOG_INFO, "NTSs: OpenSSL security level is %d",
123
0
                SSL_CTX_get_security_level(server_ctx));
124
125
0
        msyslog(LOG_INFO, "NTSs: starting NTS-KE server listening on port %d",
126
0
                NTS_KE_PORT);
127
0
        ok &= create_listener4(NTS_KE_PORT);
128
0
        ok &= create_listener6(NTS_KE_PORT);
129
130
0
        return ok;
131
0
}
132
133
0
bool nts_server_init2(void) {
134
0
        pthread_t worker;
135
0
        sigset_t block_mask, saved_sig_mask;
136
0
        int rc;
137
0
        char errbuf[100];
138
139
0
        if (!nts_load_certificate(server_ctx)) {
140
0
                return false;
141
0
        }
142
143
0
        sigfillset(&block_mask);
144
0
        pthread_sigmask(SIG_BLOCK, &block_mask, &saved_sig_mask);
145
0
        if (listener4_sock != -1) {
146
0
                rc = pthread_create(&worker, NULL, nts_ke_listener, &listener4_sock);
147
0
                if (rc) {
148
0
                        ntp_strerror_r(errno, errbuf, sizeof(errbuf));
149
0
                        msyslog(LOG_ERR, "NTSs: nts_start_server4: error from pthread_create: %s", errbuf);
150
0
                }
151
0
        }
152
0
        if (listener6_sock != -1) {
153
0
                rc = pthread_create(&worker, NULL, nts_ke_listener, &listener6_sock);
154
0
                if (rc) {
155
0
                        ntp_strerror_r(errno, errbuf, sizeof(errbuf));
156
0
                        msyslog(LOG_ERR, "NTSs: nts_start_server6: error from pthread_create: %s", errbuf);
157
0
                }
158
0
        }
159
0
        pthread_sigmask(SIG_SETMASK, &saved_sig_mask, NULL);
160
161
0
        return true;
162
0
}
163
164
// called every hour
165
0
void nts_cert_timer(void) {
166
0
        check_cert_file();
167
0
}
168
169
// call hourly and by SIGHUP
170
0
void check_cert_file(void) {
171
0
        if (NULL == server_ctx)
172
0
                return;
173
0
        nts_lock_certlock();
174
0
        nts_reload_certificate(server_ctx);
175
0
        nts_unlock_certlock();
176
0
}
177
178
0
void nts_lock_certlock(void) {
179
0
        int err = pthread_mutex_lock(&certificate_lock);
180
0
        if (0 != err) {
181
0
                msyslog(LOG_ERR, "ERR: Can't lock certificate_lock: %d", err);
182
0
                exit(2);
183
0
        }
184
0
}
185
186
0
void nts_unlock_certlock(void) {
187
0
        int err = pthread_mutex_unlock(&certificate_lock);
188
0
        if (0 != err) {
189
0
                msyslog(LOG_ERR, "ERR: Can't unlock certificate_lock: %d", err);
190
0
                exit(2);
191
0
        }
192
0
}
193
194
195
0
void* nts_ke_listener(void* arg) {
196
0
        struct timeval timeout = {.tv_sec = NTS_KE_TIMEOUT, .tv_usec = 0};
197
0
        int sock = *(int*)arg;
198
0
        char errbuf[100];
199
0
        char usingbuf[100];
200
0
        NTS_Server_Info nsi;
201
0
        SSL *ssl;
202
0
#ifdef RUSAGE_THREAD
203
0
        struct rusage usage;
204
0
#endif
205
206
#ifdef HAVE_SECCOMP_H
207
        setup_SIGSYS_trap();   // enable trap for this thread
208
#endif
209
210
0
#ifdef RUSAGE_THREAD
211
        /* NB: start_u and start_s are from near the end of the previous cycle.
212
         * Thus usage timing includes the TCP accept and
213
         * writing the previous msyslog message.
214
         */
215
0
        getrusage(RUSAGE_THREAD, &usage);
216
0
        nsi.usr = tspec_to_d(tval_to_tspec(usage.ru_utime));
217
0
        nsi.sys = tspec_to_d(tval_to_tspec(usage.ru_stime));
218
#else
219
        nsi.usr = 0;
220
        nsi.sys = 0;
221
#endif
222
223
0
        while(1) {
224
0
                NTSKE_Status status = NTSKE_SSL_Failed;
225
0
                sockaddr_u addr;
226
0
                socklen_t len = sizeof(addr);
227
0
                const unsigned char *alpn;
228
0
                unsigned alpnlen;
229
0
                int client, err;
230
231
0
                sleep(1);                       // FIXME: log clutter/DoS
232
0
                nsi.errtxt = NULL;
233
0
                client = accept(sock, &addr.sa, &len);
234
0
                if (client < 0) {
235
                        // FIXME -- log with new code TCP
236
0
                        ntp_strerror_r(errno, errbuf, sizeof(errbuf));
237
0
                        msyslog(LOG_ERR, "NTSs: TCP accept failed: %s", errbuf);
238
0
                        if (EBADF == errno)
239
0
                                return NULL;
240
0
                        continue;
241
0
                }
242
0
                clock_gettime(CLOCK_MONOTONIC, &nsi.start);
243
0
                sockporttoa_r(&addr, nsi.hostaddr, sizeof(nsi.hostaddr));
244
245
/* This is disabled in order to reduce clutter in the log file.
246
 * The client's address is now included in the final message.
247
 * That works fine in the normal successful case.  There is one line
248
 * per connection.
249
 * The failed cases are more complicated.
250
 * The common fail case is bad guys probing which fails in SSL_accept.
251
 * That branch has its own error handling.  Again, the common cases
252
 * have one line per connection and include the client address.
253
 * Uncommon cases will include two (or more) lines.
254
 * There are many possible error messages after SSL_accept works.
255
 * In practice, they don't happen, at least not often enough to notice.
256
 * They currently get logged without the client's address.  Then they
257
 * fall into the normal (non-error) path which does include the address.
258
 * Enabling this might make strange cases easier to understand.
259
 */
260
// msyslog(LOG_INFO, "NTSs: TCP accept-ed from %s", addrbuf);
261
262
0
                err = setsockopt(client, SOL_SOCKET, SO_RCVTIMEO,
263
0
                        &timeout, sizeof(timeout));
264
0
                if (0 > err) {
265
0
                        ntp_strerror_r(errno, errbuf, sizeof(errbuf));
266
0
                        msyslog(LOG_ERR, "NTSs: can't set recv timeout: %s", errbuf);
267
0
                        close(client);
268
0
                        ntske_cnt.serves_bad++;
269
0
                        continue;
270
0
                }
271
0
                err = setsockopt(client, SOL_SOCKET, SO_SNDTIMEO,
272
0
                        &timeout, sizeof(timeout));
273
0
                if (0 > err) {
274
0
                        ntp_strerror_r(errno, errbuf, sizeof(errbuf));
275
0
                        msyslog(LOG_ERR, "NTSs: can't set send timeout: %s", errbuf);
276
0
                        close(client);
277
0
                        ntske_cnt.serves_bad++;
278
0
                        continue;
279
0
                }
280
281
                // WARN: For high volume servers, this should go in a new thread.
282
0
                nts_lock_certlock();
283
0
                ssl = SSL_new(server_ctx);
284
0
                nts_unlock_certlock();
285
0
                SSL_set_fd(ssl, client);
286
287
0
                err = SSL_accept(ssl);
288
0
                SSL_get0_alpn_selected(ssl, &alpn, &alpnlen);
289
0
                if (0 >= err || NULL == alpn) {
290
0
                        int code = SSL_get_error(ssl, err);
291
0
                        SSL_free(ssl);
292
0
                        close(client);
293
0
                        nts_ke_accept_fail(&nsi, code, alpn);
294
0
                        continue;
295
0
                }
296
297
                // Save info for final message.
298
0
                snprintf(usingbuf, sizeof(usingbuf), "%s:%s(%d)",
299
0
                        SSL_get_version(ssl),
300
0
                        SSL_get_cipher_name(ssl),
301
0
                        SSL_get_cipher_bits(ssl, NULL));
302
303
0
                status = NTSKE_Failed;
304
0
                nts_ke_request(&nsi, ssl);
305
0
                if (NULL==nsi.errtxt) status = NTSKE_OK;
306
307
0
                SSL_shutdown(ssl);
308
0
                SSL_free(ssl);
309
0
                close(client);
310
311
0
                log_ntske(&nsi, status, usingbuf);
312
0
        }
313
314
0
        return NULL;
315
0
}
316
317
/* Analyze failure from SSL_accept
318
 * print single error message for common cases.
319
 * Similar code in nts.c, nts_ssl_read() and nts_ssl_write()
320
 */
321
void nts_ke_accept_fail(NTS_Server_Info *nsi,
322
0
    int code, const unsigned char *alpn) {
323
0
        unsigned long err = ERR_peek_error();
324
0
        char buff[200];
325
0
        const char *msg = NULL;
326
        // NULL==alpn if client tries TLS 1.2
327
0
        if (SSL_ERROR_NONE == code && NULL == alpn) {
328
0
                msg = "No valid ALPN";
329
0
        } else if (0 == err) {
330
0
          switch (code) {
331
0
            case SSL_ERROR_WANT_READ:
332
0
              msg = "Timeout";
333
0
              break;
334
0
            case SSL_ERROR_SYSCALL:
335
0
              if (ECONNRESET==errno) {
336
0
                msg = "Connection reset";
337
0
                break;
338
0
              }
339
0
              FALLTHRU
340
0
            default:
341
0
              ntp_strerror_r(errno, nsi->errbuf, sizeof(nsi->errbuf));
342
0
              snprintf(buff, sizeof(buff), "code %d, errno=>%d, %s",
343
0
                code, errno, nsi->errbuf);
344
0
              msg = buff;
345
0
              break;
346
0
          }
347
0
        } else {
348
0
          if (code==SSL_ERROR_SSL) {
349
0
            msg = ERR_reason_error_string(err);
350
0
            err = 0;
351
0
          } else {
352
            // Maybe we need to handle other codes
353
0
            ntp_strerror_r(errno, nsi->errbuf, sizeof(nsi->errbuf));
354
0
            snprintf(buff, sizeof(buff), "code %d, errno=>%d, %s, %lx=>%s",
355
0
              code, errno, nsi->errbuf, err, ERR_reason_error_string(err));
356
0
            err = 0;
357
0
            msg = buff;
358
0
          }
359
0
        }
360
0
        log_ntske(nsi, NTSKE_SSL_Failed, msg);
361
0
}
362
363
364
0
void nts_ke_request(NTS_Server_Info *nsi, SSL *ssl) {
365
        /* RFC 4: servers must accept 1024
366
         * Our cookies can be 104, 136, or 168 for AES_SIV_CMAC_xxx
367
         * 8*168 fits comfortably into 2K.
368
         */
369
0
        uint8_t buff[2048];
370
0
        uint8_t c2s[NTS_MAX_KEYLEN], s2c[NTS_MAX_KEYLEN];
371
0
        int keylen;
372
0
        BufCtl buf;
373
0
        int bytes_read, bytes_written;
374
0
        int used;
375
0
        enum process_result result;
376
377
0
        bytes_read = nts_ssl_read(ssl, buff, sizeof(buff), &nsi->errtxt);
378
0
        if (0 > bytes_read)
379
0
                return;
380
0
        if (0 == bytes_read) {
381
                // RFC 8915 4.1.3: Bad Request on timeout without a request.
382
                // Keep the read's error text for the log.
383
0
                const char *werrtxt = NULL;
384
385
0
                buf.next = buff;
386
0
                buf.left = sizeof(buff);
387
0
                ke_append_record_uint16(&buf, NTS_CRITICAL+nts_error,
388
0
                  nts_bad_request);
389
0
                ke_append_record_null(&buf, NTS_CRITICAL+nts_end_of_message);
390
0
                used = sizeof(buff)-buf.left;
391
0
                nts_ssl_write(ssl, buff, used, &werrtxt);
392
0
                return;
393
0
        }
394
395
0
        buf.next = buff;
396
0
        buf.left = bytes_read;
397
0
        result = nts_ke_process_receive(nsi, &buf);
398
0
        if (Process_OK != result) {
399
0
                buf.next = buff;
400
0
                buf.left = sizeof(buff);
401
                // Send what we can to show what worked to help debugging
402
0
                if (nsi->saw_aead) {
403
0
                    if (NO_AEAD != nsi->aead) {
404
0
                        ke_append_record_uint16(&buf, nts_algorithm_negotiation,
405
0
                            nsi->aead);
406
0
                    } else {
407
0
                        ke_append_record_null(&buf, nts_algorithm_negotiation);
408
0
                    }
409
0
                }
410
0
                if (nsi->saw_next_protocol) {
411
0
                    if (nsi->next_protocol_matched) {
412
0
                        ke_append_record_uint16(&buf,
413
0
                            NTS_CRITICAL+nts_next_protocol_negotiation,
414
0
                            nts_protocol_NTP);
415
0
                    } else {
416
0
                        ke_append_record_null(&buf,
417
0
                            NTS_CRITICAL+nts_next_protocol_negotiation);
418
0
                    }
419
0
                }
420
                // RFC 8915 4.1.2, 4.1.5: if nothing matched, the
421
                // empty records above are the answer, without an error
422
0
                switch (result) {
423
0
                  case Process_Critical:
424
0
                    ke_append_record_uint16(&buf, NTS_CRITICAL+nts_error,
425
0
                      nts_unrecognized_critical_section);
426
0
                    break;
427
0
                  case Process_Error:
428
0
                    ke_append_record_uint16(&buf, NTS_CRITICAL+nts_error,
429
0
                      nts_bad_request);
430
0
                    break;
431
0
                  case Process_NoMatch:
432
0
                    FALLTHRU
433
0
                  case Process_OK:  // keep compiler happy
434
0
                    break;
435
0
                  default:
436
0
                    break;
437
0
                }
438
0
                ke_append_record_null(&buf, NTS_CRITICAL+nts_end_of_message);
439
0
                used = sizeof(buff)-buf.left;
440
0
                nts_ssl_write(ssl, buff, used, &nsi->errtxt);
441
0
                return;
442
0
        }
443
444
0
        keylen = nts_get_key_length(nsi->aead);
445
0
        if (!nts_make_keys(ssl, nsi->aead, c2s, s2c, keylen)) {
446
0
                nsi->errtxt = "Can't make keys";
447
0
                buf.next = buff;
448
0
                buf.left = sizeof(buff);
449
0
                ke_append_record_uint16(&buf, NTS_CRITICAL+nts_error,
450
0
                  nts_internal_server_error);
451
0
                ke_append_record_null(&buf, NTS_CRITICAL+nts_end_of_message);
452
0
                used = sizeof(buff)-buf.left;
453
0
                nts_ssl_write(ssl, buff, used, &nsi->errtxt);
454
0
                return;
455
0
        }
456
457
0
        buf.next = buff;
458
0
        buf.left = sizeof(buff);
459
0
        nts_ke_setup_send(&buf, nsi->aead, c2s, s2c, keylen);
460
461
0
        used = sizeof(buff)-buf.left;
462
0
        bytes_written = nts_ssl_write(ssl, buff, used, &nsi->errtxt);
463
0
        if (bytes_written != used)
464
0
                return;
465
466
// FIXME: Need counters for AEAD
467
468
0
        return;
469
0
}
470
471
0
bool create_listener4(int port) {
472
0
        int sock = -1;
473
0
        sockaddr_u addr;
474
0
        int on = 1;
475
0
        int err;
476
0
        char errbuf[100];
477
478
0
        addr.sa4.sin_family = AF_INET;
479
0
        addr.sa4.sin_port = htons(port);
480
0
        addr.sa4.sin_addr.s_addr= htonl(INADDR_ANY);
481
0
        sock = socket(AF_INET, SOCK_STREAM, 0);
482
0
        if (sock < 0) {
483
0
                if (EAFNOSUPPORT == errno) {
484
0
                        msyslog(LOG_ERR, "NTSs: No IPv4 support, disabling NTS-KE listener");
485
0
                        return true;
486
0
                }
487
0
                ntp_strerror_r(errno, errbuf, sizeof(errbuf));
488
0
                msyslog(LOG_ERR, "NTSs: Can't create socket4: %s", errbuf);
489
0
                return false;
490
0
        }
491
0
        err = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
492
0
        if (0 > err) {
493
0
                ntp_strerror_r(errno, errbuf, sizeof(errbuf));
494
0
                msyslog(LOG_ERR, "NTSs: can't setsockopt4: %s", errbuf);
495
0
                close(sock);
496
0
                return false;
497
0
        }
498
0
        err = bind(sock, &addr.sa, sizeof(addr.sa4));
499
0
        if (0 > err) {
500
0
                ntp_strerror_r(errno, errbuf, sizeof(errbuf));
501
0
                msyslog(LOG_ERR, "NTSs: can't bind4: %s", errbuf);
502
0
                close(sock);
503
0
                return false;
504
0
        }
505
0
        if (listen(sock, 6) < 0) {
506
0
                ntp_strerror_r(errno, errbuf, sizeof(errbuf));
507
0
                msyslog(LOG_ERR, "NTSs: can't listen4: %s", errbuf);
508
0
                close(sock);
509
0
                return false;
510
0
        }
511
0
        msyslog(LOG_INFO, "NTSs: listen4 worked");
512
513
0
        listener4_sock = sock;
514
0
        return true;
515
0
}
516
517
0
bool create_listener6(int port) {
518
0
        int sock = -1;
519
0
        sockaddr_u addr;
520
0
        int on = 1;
521
0
        int err;
522
0
        char errbuf[100];
523
524
0
        addr.sa6.sin6_family = AF_INET6;
525
0
        addr.sa6.sin6_port = htons(port);
526
0
        addr.sa6.sin6_addr = in6addr_any;
527
0
        sock = socket(AF_INET6, SOCK_STREAM, 0);
528
0
        if (sock < 0) {
529
0
                if (EAFNOSUPPORT == errno) {
530
0
                        msyslog(LOG_ERR, "NTSs: No IPv6 support, disabling NTS-KE listener");
531
0
                        return true;
532
0
                }
533
0
                ntp_strerror_r(errno, errbuf, sizeof(errbuf));
534
0
                msyslog(LOG_ERR, "NTSs: Can't create socket6: %s", errbuf);
535
0
                return false;
536
0
        }
537
        // Hack to keep IPV6 from listening on IPV4 too
538
0
        err = setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
539
0
        if (0 > err) {
540
0
                ntp_strerror_r(errno, errbuf, sizeof(errbuf));
541
0
                msyslog(LOG_ERR, "NTSs: can't setsockopt6only: %s", errbuf);
542
0
                close(sock);
543
0
                return false;
544
0
        }
545
0
        err = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
546
0
        if (0 > err) {
547
0
                ntp_strerror_r(errno, errbuf, sizeof(errbuf));
548
0
                msyslog(LOG_ERR, "NTSs: can't setsockopt6: %s", errbuf);
549
0
                close(sock);
550
0
                return false;
551
0
        }
552
0
        err = bind(sock, &addr.sa, sizeof(addr.sa6));
553
0
        if (0 > err) {
554
0
                ntp_strerror_r(errno, errbuf, sizeof(errbuf));
555
0
                msyslog(LOG_ERR, "NTSs: can't bind6: %s", errbuf);
556
0
                close(sock);
557
0
                return false;
558
0
        }
559
0
        if (listen(sock, 6) < 0) {
560
0
                ntp_strerror_r(errno, errbuf, sizeof(errbuf));
561
0
                msyslog(LOG_ERR, "NTSs: can't listen6: %s", errbuf);
562
0
                close(sock);
563
0
                return false;
564
0
        }
565
0
        msyslog(LOG_INFO, "NTSs: listen6 worked");
566
567
0
        listener6_sock = sock;
568
0
        return true;
569
0
}
570
571
0
enum process_result nts_ke_process_receive(NTS_Server_Info *nsi, BufCtl *buf) {
572
0
        bool npn_empty = false, aead_empty = false;
573
574
0
        nsi->aead = NO_AEAD;
575
0
        nsi->saw_next_protocol = false;
576
0
        nsi->next_protocol_matched = false;
577
0
        nsi->saw_aead = false;
578
0
        while (buf->left >= NTS_KE_HDR_LNG) {
579
0
                uint16_t type, data;
580
0
                int length;
581
0
                bool critical = false;
582
0
                type = ke_next_record(buf, &length);
583
0
                if (length > buf->left) {
584
0
                        snprintf(nsi->errbuf, sizeof(nsi->errbuf),
585
0
                                "Chunk too big: 0x%x, %d, %d",
586
0
                                type, buf->left, length);
587
0
                        nsi->errtxt = nsi->errbuf;
588
0
                        return Process_Error;
589
0
                }
590
0
                if (NTS_CRITICAL & type) {
591
0
                        critical = true;
592
0
                        type &= ~NTS_CRITICAL;
593
0
                }
594
0
                if (0) // Handy for debugging but very verbose
595
0
                        msyslog(LOG_INFO, "NTSs: Record: T=%d, L=%d, C=%d", type, length, critical);
596
0
                switch (type) {
597
0
                    case nts_error:
598
0
                        if (sizeof(data) != length) {
599
0
                                snprintf(nsi->errbuf, sizeof(nsi->errbuf),
600
0
                                        "Wrong length on error: %d", length);
601
0
                                nsi->errtxt = nsi->errbuf;
602
0
                                return Process_Error;
603
0
                        }
604
0
                        data = next_uint16(buf);
605
0
                        snprintf(nsi->errbuf, sizeof(nsi->errbuf),
606
0
                                "Received error: %d", data);
607
0
                        nsi->errtxt = nsi->errbuf;
608
0
                        return Process_Error;
609
0
                    case nts_next_protocol_negotiation:
610
0
                        if (nsi->saw_next_protocol) {
611
0
                                nsi->errtxt = "NPN Duplicate";
612
0
                                return Process_Error;
613
0
                        }
614
0
                        if (length % sizeof(uint16_t) > 0) {
615
0
                                snprintf(nsi->errbuf, sizeof(nsi->errbuf),
616
0
                                        "NPN Wrong length: %d", length);
617
0
                                nsi->errtxt = nsi->errbuf;
618
0
                                return Process_Error;
619
0
                        }
620
0
                        nsi->saw_next_protocol = true;
621
0
                        npn_empty = (0 == length);
622
0
                        for (int i=0; i<length; i+=sizeof(uint16_t)) {
623
0
                                data = next_uint16(buf);
624
0
                                if (data == nts_protocol_NTP) {
625
0
                                        nsi->next_protocol_matched = true;
626
0
                                }
627
0
                        }
628
0
                        break;
629
0
                    case nts_algorithm_negotiation:
630
0
                        if (nsi->saw_aead) {
631
0
                                nsi->errtxt = "AEAD Duplicate";
632
0
                                return Process_Error;
633
0
                        }
634
0
                        if (length % sizeof(uint16_t) > 0) {
635
0
                                snprintf(nsi->errbuf, sizeof(nsi->errbuf),
636
0
                                        "AN-Wrong length: %d", length);
637
0
                                nsi->errtxt = nsi->errbuf;
638
0
                                return Process_Error;
639
0
                        }
640
0
                        nsi->saw_aead = true;
641
0
                        aead_empty = (0 == length);
642
0
                        for (int i=0; i<length; i+=sizeof(uint16_t)) {
643
0
                                data = next_uint16(buf);
644
// FIXME: config option, need bitmap or ???
645
0
                                if (0 == nts_get_key_length(data)) {
646
0
                                        if (0)  // for debugging
647
0
                                                msyslog(LOG_ERR, "NTSs: AN-Unsupported AEAN type: %d", data);
648
0
                                        continue;     // ignore types we don't support
649
0
                                }
650
0
                                if (nsi->aead != NO_AEAD)
651
0
                                        continue;     // already got one
652
0
                                nsi->aead = data;   // take this one
653
0
                        }
654
0
                        break;
655
0
                    case nts_end_of_message:
656
0
                        if ((0 != length) || !critical) {
657
0
                                snprintf(nsi->errbuf, sizeof(nsi->errbuf),
658
0
                                        "EOM-Wrong length or not Critical: %d, %d",
659
0
                                        length, critical);
660
0
                                nsi->errtxt = nsi->errbuf;
661
0
                                return Process_Error;
662
0
                        }
663
0
                        if (0 != buf->left) {
664
0
                                snprintf(nsi->errbuf, sizeof(nsi->errbuf),
665
0
                                        "EOM not at end: %d", buf->left);
666
0
                                nsi->errtxt = nsi->errbuf;
667
0
                                return Process_Error;
668
0
                        }
669
0
                        if (!nsi->saw_next_protocol) {
670
0
                                nsi->errtxt = "NPN Missing";
671
0
                                return Process_Error;
672
0
                        }
673
                        // RFC 8915 4.1.2: the request lists at least one
674
0
                        if (npn_empty) {
675
0
                                nsi->errtxt = "NPN Empty";
676
0
                                return Process_Error;
677
0
                        }
678
0
                        if (!nsi->next_protocol_matched) {
679
0
                                nsi->errtxt = "NPN No match";
680
0
                                return Process_NoMatch;
681
0
                        }
682
0
                        if (!nsi->saw_aead) {
683
0
                                nsi->errtxt = "AEAD Missing";
684
0
                                return Process_Error;
685
0
                        }
686
                        // RFC 8915 4.1.5: the request lists at least one
687
0
                        if (aead_empty) {
688
0
                                nsi->errtxt = "AEAD Empty";
689
0
                                return Process_Error;
690
0
                        }
691
0
                        if (NO_AEAD == nsi->aead) {
692
0
                                nsi->errtxt = "AEAD No match";
693
0
                                return Process_NoMatch;
694
0
                        }
695
0
                        return Process_OK;
696
0
                    case nts_warning:
697
0
                        FALLTHRU
698
0
                    case nts_new_cookie:
699
                        // RFC 8915 4.1.4, 4.1.6: clients MUST NOT send these
700
0
                        snprintf(nsi->errbuf, sizeof(nsi->errbuf),
701
0
                                "Client sent record type %d", type);
702
0
                        nsi->errtxt = nsi->errbuf;
703
0
                        return Process_Error;
704
0
                    case nts_server_negotiation:
705
0
                        FALLTHRU
706
0
                    case nts_port_negotiation:
707
                        // RFC 8915 4.1.7, 4.1.8: honoring these is
708
                        // optional, and a client SHOULD NOT, but may, set
709
                        // the Critical Bit
710
0
                        buf->next += length;
711
0
                        buf->left -= length;
712
0
                        break;
713
0
                    default:
714
0
                        if (critical) {
715
                          // This only logs the first one from a connection
716
0
                          snprintf(nsi->errbuf, sizeof(nsi->errbuf),
717
0
                                "Received strange type: T=%d, C=%d, L=%d",
718
0
                                type, critical, length);
719
0
                          nsi->errtxt = nsi->errbuf;
720
0
                          return Process_Critical;
721
0
                        }
722
                        // It might be interesting to log non-critical
723
                        // but that needs rate limiting
724
0
                        buf->next += length;
725
0
                        buf->left -= length;
726
0
                        break;
727
0
                }  // case
728
0
        }   // while
729
730
        /* If we get here, we ran off the end without finding an EOM.
731
         * nts_ssl_read() should have complained, so this check
732
         * should never happen.
733
         */
734
0
        if (buf->left > 0) {
735
0
                nsi->errtxt = "Leftovers";
736
0
                return Process_Error;
737
0
        }
738
739
0
        nsi->errtxt = "Missing EOM";
740
0
        return Process_Error;
741
742
0
}
743
744
void nts_ke_setup_send(BufCtl *buf, int aead,
745
0
       uint8_t *c2s, uint8_t *s2c, int keylen) {
746
747
        // 4.1.2 Next Protocol
748
0
        ke_append_record_uint16(buf,
749
0
                                NTS_CRITICAL+nts_next_protocol_negotiation, nts_protocol_NTP);
750
        // 4.1.5 AEAD Algorithm List
751
0
        ke_append_record_uint16(buf, nts_algorithm_negotiation, aead);
752
753
0
        if (extra_port)
754
0
                ke_append_record_uint16(buf, nts_port_negotiation, extra_port);
755
756
757
0
        for (int i=0; i<NTS_MAX_COOKIES; i++) {
758
0
                uint8_t cookie[NTS_MAX_COOKIELEN];
759
0
                int cookielen = nts_make_cookie(cookie, aead, c2s, s2c, keylen);
760
0
                ke_append_record_bytes(buf, nts_new_cookie, cookie, cookielen);
761
0
        }
762
763
        // 4.1.1: End, Critical
764
0
        ke_append_record_null(buf, NTS_CRITICAL+nts_end_of_message);
765
0
}
766
767
0
void log_ntske (NTS_Server_Info *nsi, NTSKE_Status status, const char *using) {
768
0
    struct timespec finish;
769
0
    double wall, usr, sys;
770
0
#ifdef RUSAGE_THREAD
771
0
    struct rusage usage;
772
    /* NB: nsi->usr and nsi->sys are from near the end of the previous cycle.
773
     * Thus usage timing includes the TCP accept and
774
     * writing the previous msyslog message.
775
     */
776
0
    getrusage(RUSAGE_THREAD, &usage);
777
0
    usr = tspec_to_d(tval_to_tspec(usage.ru_utime));
778
0
    sys = tspec_to_d(tval_to_tspec(usage.ru_stime));
779
#else
780
    usr = 0;
781
    sys = 0;
782
#endif
783
    clock_gettime(CLOCK_MONOTONIC, &finish);
784
0
    wall = tspec_to_d(sub_tspec(finish, nsi->start));
785
0
    record_ntske_log(status, nsi->hostaddr, using,
786
0
            wall, usr-nsi->usr, sys-nsi->sys, nsi->aead, nsi->errtxt);
787
0
#ifdef RUSAGE_THREAD
788
0
    nsi->usr = usr;
789
0
    nsi->sys = sys;
790
0
#endif
791
0
}
792
793
// end