Coverage Report

Created: 2026-12-01 06:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/hpn-ssh/cipher-ctr-mt-functions.c
Line
Count
Source
1
/*
2
 * OpenSSH Multi-threaded AES-CTR Cipher Provider for OpenSSL 3
3
 *
4
 * Author: Benjamin Bennett <ben@psc.edu>
5
 * Author: Mike Tasota <tasota@gmail.com>
6
 * Author: Chris Rapier <rapier@psc.edu>
7
 * Copyright (c) 2008-2022 Pittsburgh Supercomputing Center. All rights reserved.
8
 *
9
 * Based on original OpenSSH AES-CTR cipher. Small portions remain unchanged,
10
 * Copyright (c) 2003 Markus Friedl <markus@openbsd.org>
11
 *
12
 * Permission to use, copy, modify, and distribute this software for any
13
 * purpose with or without fee is hereby granted, provided that the above
14
 * copyright notice and this permission notice appear in all copies.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
17
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
18
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
19
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
20
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
21
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
22
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23
 */
24
25
#include "includes.h"
26
27
/* only for systems with OSSL 3 */
28
#ifdef WITH_OPENSSL3
29
#include <stdarg.h>
30
#include <string.h>
31
#include <openssl/evp.h>
32
#include "xmalloc.h"
33
#include <unistd.h>
34
#include "cipher-ctr-mt-functions.h"
35
#include "log.h"
36
37
/* for provider error struct */
38
#include "ossl3-provider-err.h"
39
#include "num.h"
40
41
/* note regarding threads and queues */
42
/* initially this cipher was written in a way that
43
 * the key stream was generated in a per cipher block
44
 * loop. For example, if the key stream queue length was
45
 * 16k and the cipher block size was 16 bytes it would
46
 * fill the queue 16 bytes at a time. Mitch Dorrell pointed
47
 * out that we could fill the queue in once call eliminating
48
 * loop and multiple calls to EVP_EncryptUpdate. Doing so
49
 * dramatically reduced CPU load in the threads and indicated
50
 * that we could also eliminate most of the threads and queues
51
 * as it would take far less time for a queue to ebter KQ_FULL
52
 * state. As such, we've reduced the default number of threads
53
 * and queues from 2 and 8 (respectively) to 1 and 2. We've also
54
 * elimnated the need to determine the physical number of cores on
55
 * the system and, if the user desires, can spin up more threads
56
 * using an environment variable. Additionally, queues is now fixed
57
 * at thread_count + 1.
58
 * cjr 10/19/2022 */
59
60
/*-------------------- TUNABLES --------------------*/
61
/* Number of pregen threads to use */
62
/* this is a default value. The actual number is
63
 * determined during init as a function of the number
64
 * of available cores */
65
int cipher_threads = 1;
66
67
/* Number of keystream queues */
68
/* ideally this should be large enough so that there is
69
 * always a key queue for a thread to work on
70
 * so maybe double of the number of threads. Again this
71
 * is a default and the actual value is determined in init*/
72
int numkq = 2;
73
/*-------------------- END TUNABLES --------------------*/
74
75
/* globals */
76
/* how we increment the id the structs we create */
77
long unsigned int global_struct_id = 0;
78
79
/* keep a copy of the pointers created in thread_loop to free later */
80
struct aes_mt_ctx_ptrs *evp_ptrs = NULL;
81
82
/* private functions */
83
84
/*
85
 * Add num to counter 'ctr'
86
 */
87
static void
88
ssh_ctr_add(u_char *ctr, uint32_t num, u_int len)
89
0
{
90
0
  int i;
91
0
  uint16_t n;
92
93
0
  for (n = 0, i = len - 1; i >= 0 && (num || n); i--) {
94
0
    n = ctr[i] + (num & 0xff) + n;
95
0
    num >>= 8;
96
0
    ctr[i] = n & 0xff;
97
0
    n >>= 8;
98
0
  }
99
0
}
100
101
/*
102
 * Threads may be cancelled in a pthread_cond_wait, we must free the mutex
103
 */
104
static void
105
thread_loop_cleanup(void *x)
106
0
{
107
0
  pthread_mutex_unlock((pthread_mutex_t *)x);
108
0
}
109
110
/* Check if we should exit, we are doing both cancel and exit condition
111
 * since threads can fail to notice that they have been cancelled: on OSX
112
 * natively, and on any platform when running under valgrind, whose
113
 * scheduler does not deliver a cancel to a thread parked in
114
 * pthread_cond_wait(). We want a backup to make sure that we won't hang
115
 * when the main process join()-s the cancelled thread.
116
 */
117
static void
118
thread_loop_check_exit(struct aes_mt_ctx_st *aes_mt_ctx)
119
0
{
120
0
  int exit_flag;
121
122
0
  pthread_rwlock_rdlock(&aes_mt_ctx->stop_lock);
123
0
  exit_flag = aes_mt_ctx->exit_flag;
124
0
  pthread_rwlock_unlock(&aes_mt_ctx->stop_lock);
125
126
0
  if (exit_flag)
127
0
    pthread_exit(NULL);
128
0
}
129
130
/*
131
 * Helper function to terminate the helper threads
132
 */
133
static void
134
stop_and_join_pregen_threads(struct aes_mt_ctx_st *aes_mt_ctx)
135
0
{
136
0
  int i;
137
138
  /* notify threads that they should exit */
139
0
  pthread_rwlock_wrlock(&aes_mt_ctx->stop_lock);
140
0
  aes_mt_ctx->exit_flag = 1;
141
0
  pthread_rwlock_unlock(&aes_mt_ctx->stop_lock);
142
143
  /*
144
   * Wake anything parked in pthread_cond_wait() so that it rechecks
145
   * the exit flag and leaves via thread_loop_check_exit(). Without
146
   * this a parked thread can only be removed by pthread_cancel(),
147
   * which leaves the join below blocked indefinitely whenever that
148
   * cancel is not delivered.
149
   */
150
0
  for (i = 0; i < numkq; i++) {
151
0
    pthread_mutex_lock(&aes_mt_ctx->q[i].lock);
152
0
    pthread_cond_broadcast(&aes_mt_ctx->q[i].cond);
153
0
    pthread_mutex_unlock(&aes_mt_ctx->q[i].lock);
154
0
  }
155
156
  /* Cancel pregen threads */
157
0
  for (i = 0; i < cipher_threads; i++) {
158
0
    debug_f ("Canceled %lu (%lu,%d)", aes_mt_ctx->tid[i], aes_mt_ctx->struct_id,
159
0
           aes_mt_ctx->id[i]);
160
0
    pthread_cancel(aes_mt_ctx->tid[i]);
161
0
  }
162
0
  for (i = 0; i < cipher_threads; i++) {
163
0
    if (pthread_kill(aes_mt_ctx->tid[i], 0) != 0)
164
0
      debug3("AES-CTR MT pthread_join failure: Invalid thread id %lu in %s",
165
0
             aes_mt_ctx->tid[i], __func__);
166
0
    else {
167
0
      debug_f ("Joining %lu (%lu, %d)", aes_mt_ctx->tid[i], aes_mt_ctx->struct_id,
168
0
         aes_mt_ctx->id[i]);
169
0
      pthread_join(aes_mt_ctx->tid[i], NULL);
170
      /* this finds the entry in the hash that corresponding to the
171
       * thread id. That's used to find the pointer to the cipher struct
172
       * created in thread_loop. */
173
0
      struct aes_mt_ctx_ptrs *ptr;
174
0
      HASH_FIND_INT(evp_ptrs, &aes_mt_ctx->tid[i], ptr);
175
0
      EVP_CIPHER_CTX_free(ptr->pointer);
176
0
      HASH_DEL(evp_ptrs, ptr);
177
0
      free(ptr);
178
0
                }
179
0
        }
180
0
  pthread_rwlock_destroy(&aes_mt_ctx->tid_lock);
181
0
}
182
183
/* determine the number of threads to use
184
 * Testing indicates that in most all situations the optimal number of
185
 * threads is 1 meaning 1 for inbound and 1 for outbound. The optimal
186
 * queue count has also been determined to be thread_count + 1.
187
 * note this function updates two globals - numkq and cipher_threads
188
 * it returns the value of cipher_threads but it doesn't need to */
189
0
static int get_thread_count() {
190
191
0
  char * aes_threads = getenv("SSH_CIPHER_THREADS");
192
0
  debug_f ("SSH thread count is %s", aes_threads);
193
0
        if (aes_threads != NULL && strlen(aes_threads) != 0)
194
0
    cipher_threads = atoi(aes_threads);
195
0
  else
196
0
    cipher_threads = 1;
197
198
0
  if (cipher_threads < 1)
199
0
    cipher_threads = 1;
200
201
0
  if (cipher_threads > MAX_THREADS)
202
0
    cipher_threads = MAX_THREADS;
203
204
0
  numkq = cipher_threads + 1;
205
206
0
  if (numkq > MAX_NUMKQ)
207
0
    numkq = MAX_NUMKQ;
208
209
0
  debug_f ("Starting %d threads and %d queues\n", cipher_threads, numkq);
210
211
0
  return (cipher_threads);
212
0
}
213
214
215
/*
216
 * The life of a pregen thread:
217
 *    Find empty keystream queues and fill them using their counter.
218
 *    When done, update counter for the next fill.
219
 */
220
static void *
221
thread_loop(void *job)
222
0
{
223
0
  EVP_CIPHER_CTX * volatile evp_ctx;
224
0
  struct aes_mt_ctx_st *aes_mt_ctx = job;
225
0
  struct kq *q;
226
0
  struct aes_mt_ctx_ptrs *ptr;
227
0
  pthread_t first_tid;
228
0
  int outlen;
229
0
  u_char mynull[KQLEN * AES_BLOCK_SIZE];
230
0
  memset(&mynull, 0, KQLEN * AES_BLOCK_SIZE);
231
232
  /* get the thread id to see if this is the first one */
233
0
  pthread_rwlock_rdlock(&aes_mt_ctx->tid_lock);
234
0
  first_tid = aes_mt_ctx->tid[0];
235
0
  pthread_rwlock_unlock(&aes_mt_ctx->tid_lock);
236
237
  /* create the context for this thread */
238
0
  evp_ctx = EVP_CIPHER_CTX_new();
239
240
  /* keep track of the pointer for the evp in this struct
241
   * so we can free it later. So we place it in a hash indexed on the
242
   * thread id, which is available to us in the free function.
243
   * Note, the thread id isn't necessary unique across rekeys but
244
   * that's okay as they are unique during a key. */
245
0
  ptr = malloc(sizeof *ptr); /*freed in stop & prejoin */
246
0
  ptr->tid = pthread_self(); /* index for hash */
247
0
  ptr->pointer = evp_ctx;
248
0
  HASH_ADD_INT(evp_ptrs, tid, ptr);
249
250
  /* initialize the cipher ctx with the key provided
251
   * determinbe which cipher to use based on the key size */
252
0
  if (aes_mt_ctx->keylen == 256)
253
0
    EVP_EncryptInit_ex(evp_ctx, EVP_aes_256_ctr(), NULL, aes_mt_ctx->orig_key, NULL);
254
0
  else if (aes_mt_ctx->keylen == 128)
255
0
    EVP_EncryptInit_ex(evp_ctx, EVP_aes_128_ctr(), NULL, aes_mt_ctx->orig_key, NULL);
256
0
  else if (aes_mt_ctx->keylen == 192)
257
0
    EVP_EncryptInit_ex(evp_ctx, EVP_aes_192_ctr(), NULL, aes_mt_ctx->orig_key, NULL);
258
0
  else
259
0
    fatal("Invalid key length of %d in AES CTR MT. Exiting", aes_mt_ctx->keylen);
260
261
  /*
262
   * Handle the special case of startup, one thread must fill
263
   * the first KQ then mark it as draining. Lock held throughout.
264
   */
265
0
  if (pthread_equal(pthread_self(), first_tid)) {
266
    /* get the first element of the key queue struct */
267
0
    q = &aes_mt_ctx->q[0];
268
0
    pthread_mutex_lock(&q->lock);
269
    /* if we are in the INIT state then fill the queue */
270
0
    if (q->qstate == KQINIT) {
271
      /* set the initial counter */
272
0
      EVP_EncryptInit_ex(evp_ctx, NULL, NULL, NULL, q->ctr);
273
      /* encypher a block sized null string (mynull) with the key. This
274
       * returns the keystream because xoring the keystream
275
       * against null returns the keystream. Store that in the appropriate queue */
276
0
      EVP_EncryptUpdate(evp_ctx, q->keys[0], &outlen, mynull, KQLEN * AES_BLOCK_SIZE);
277
      /* Update the aes counter */
278
0
      ssh_ctr_add(q->ctr, KQLEN * numkq, AES_BLOCK_SIZE);
279
      /* since this is the first thread set it to draining */
280
0
      q->qstate = KQDRAINING;
281
0
      pthread_cond_broadcast(&q->cond);
282
0
    }
283
0
    pthread_mutex_unlock(&q->lock);
284
0
  }
285
286
  /*
287
   * Normal case is to find empty queues and fill them, skipping over
288
   * queues already filled by other threads and stopping to wait for
289
   * a draining queue to become empty.
290
   *
291
   * Multiple threads may be waiting on a draining queue and awoken
292
   * when empty. The first thread to wake will mark it as filling,
293
   * others will move on to fill, skip, or wait on the next queue.
294
   * We init qidx here because if we do it at the top of the function
295
   * we get a warning about it possibly being clobbered. The exact reason
296
   * doesn't make a lot of sense but it has to happen after the
297
   * first pthread_rwlock_rdlock(). Might have something to do with
298
   * incorrect compiler optimizations.
299
   */
300
0
  int qidx;
301
0
  for (qidx = 1;; qidx = (qidx + 1) % numkq) {
302
    /* Check if I was cancelled, also checked in cond_wait */
303
0
    pthread_testcancel();
304
305
    /* Check if we should exit as well */
306
0
    thread_loop_check_exit(aes_mt_ctx);
307
308
    /* Lock queue and block if its draining */
309
0
    q = &aes_mt_ctx->q[qidx];
310
0
    pthread_mutex_lock(&q->lock);
311
0
    pthread_cleanup_push(thread_loop_cleanup, &q->lock);
312
0
    while (q->qstate == KQDRAINING || q->qstate == KQINIT) {
313
0
      thread_loop_check_exit(aes_mt_ctx);
314
0
      pthread_cond_wait(&q->cond, &q->lock);
315
0
    }
316
0
    pthread_cleanup_pop(0);
317
318
    /* If filling or full, somebody else got it, skip */
319
0
    if (q->qstate != KQEMPTY) {
320
0
      pthread_mutex_unlock(&q->lock);
321
0
      continue;
322
0
    }
323
324
    /*
325
     * Empty, let's fill it.
326
     * Queue lock is relinquished while we do this so others
327
     * can see that it's being filled.
328
     */
329
0
    q->qstate = KQFILLING;
330
0
    pthread_cond_broadcast(&q->cond);
331
0
    pthread_mutex_unlock(&q->lock);
332
333
    /* set the initial counter */
334
0
    EVP_EncryptInit_ex(evp_ctx, NULL, NULL, NULL, q->ctr);
335
336
    /* see coresponding block above for useful comments */
337
0
    EVP_EncryptUpdate(evp_ctx, q->keys[0], &outlen, mynull, KQLEN * AES_BLOCK_SIZE);
338
339
    /* Re-lock, mark full and signal consumer */
340
0
    pthread_mutex_lock(&q->lock);
341
0
    ssh_ctr_add(q->ctr, KQLEN * numkq, AES_BLOCK_SIZE);
342
0
    q->qstate = KQFULL;
343
0
    pthread_cond_broadcast(&q->cond);
344
0
    pthread_mutex_unlock(&q->lock);
345
0
  }
346
347
0
  return NULL;
348
0
}
349
350
351
/* Our version of the EVP functions
352
 * these are public as they are used by the provider */
353
354
/* instantiate the cipher context.
355
 * in this we create the EVP ctx and the AES ctx, setup the AES ctx
356
 * initialize the EVP and then attach the AES ctx to the EVP ctx.
357
 * The *only* difference between aes_mt_newctx_256|192|128 is the
358
 * keylength of the cipher used in EVP_CipherInit
359
 * parameters: provider context
360
 * returns: EVP context
361
 */
362
/* honestly the way this works makes me think that there has to be
363
 * a better way of doing this however, I've yet to find one that doesn't
364
 * involve more madness. I think that's mostly becase I don't understand
365
 * how params work properly. I feel like I shoudl be able to use them
366
 * to specify the key length but... also, I'd think I'd be able to
367
 * set aes_mt_ctx_st->keylen to the keylength but that doesn't seem to
368
 * work either. That said, this does work even if it's a bit clunky.
369
 * -cjr 09/08/2022 */
370
void *aes_mt_newctx_256(void *provctx)
371
0
{
372
0
  struct aes_mt_ctx_st *aes_mt_ctx = malloc(sizeof(*aes_mt_ctx));
373
0
  EVP_CIPHER_CTX *evp_ctx = EVP_CIPHER_CTX_new();
374
375
0
  if ((aes_mt_ctx != NULL) && (evp_ctx != NULL)) {
376
0
    get_thread_count(); /* update cipher_threads and numkq */
377
0
    pthread_rwlock_init(&aes_mt_ctx->tid_lock, NULL);
378
0
    pthread_rwlock_init(&aes_mt_ctx->stop_lock, NULL);
379
0
    aes_mt_ctx->exit_flag = 0;
380
381
0
    aes_mt_ctx->state = HAVE_NONE;
382
383
    /* initialize the mutexs and conditions for each lock in our struct */
384
0
    for (int i = 0; i < numkq; i++) {
385
0
      pthread_mutex_init(&aes_mt_ctx->q[i].lock, NULL);
386
0
      pthread_cond_init(&aes_mt_ctx->q[i].cond, NULL);
387
0
    }
388
0
    aes_mt_ctx->provctx = provctx;
389
0
    EVP_CipherInit(evp_ctx, EVP_aes_256_ctr(), NULL, NULL, 0);
390
0
    EVP_CIPHER_CTX_set_app_data(evp_ctx, aes_mt_ctx);
391
0
    return evp_ctx;
392
0
  }
393
0
  return NULL;
394
0
}
395
396
void *aes_mt_newctx_192(void *provctx)
397
0
{
398
0
  struct aes_mt_ctx_st *aes_mt_ctx = malloc(sizeof(*aes_mt_ctx));
399
0
  EVP_CIPHER_CTX *evp_ctx = EVP_CIPHER_CTX_new();
400
401
0
  if ((aes_mt_ctx != NULL) && (evp_ctx != NULL)) {
402
0
    get_thread_count(); /* update cipher_threads and numkq */
403
0
    pthread_rwlock_init(&aes_mt_ctx->tid_lock, NULL);
404
0
    pthread_rwlock_init(&aes_mt_ctx->stop_lock, NULL);
405
0
    aes_mt_ctx->exit_flag = 0;
406
407
0
    aes_mt_ctx->state = HAVE_NONE;
408
409
    /* initialize the mutexs and conditions for each lock in our struct */
410
0
    for (int i = 0; i < numkq; i++) {
411
0
      pthread_mutex_init(&aes_mt_ctx->q[i].lock, NULL);
412
0
      pthread_cond_init(&aes_mt_ctx->q[i].cond, NULL);
413
0
    }
414
0
    aes_mt_ctx->provctx = provctx;
415
0
    EVP_CipherInit(evp_ctx, EVP_aes_192_ctr(), NULL, NULL, 0);
416
0
    EVP_CIPHER_CTX_set_app_data(evp_ctx, aes_mt_ctx);
417
0
    return evp_ctx;
418
0
  }
419
0
  return NULL;
420
0
}
421
422
void *aes_mt_newctx_128(void *provctx)
423
0
{
424
0
  struct aes_mt_ctx_st *aes_mt_ctx = malloc(sizeof(*aes_mt_ctx));
425
0
  EVP_CIPHER_CTX *evp_ctx = EVP_CIPHER_CTX_new();
426
427
0
  if ((aes_mt_ctx != NULL) && (evp_ctx != NULL)) {
428
0
    get_thread_count(); /* update cipher_threads and numkq */
429
0
    pthread_rwlock_init(&aes_mt_ctx->tid_lock, NULL);
430
0
    pthread_rwlock_init(&aes_mt_ctx->stop_lock, NULL);
431
0
    aes_mt_ctx->exit_flag = 0;
432
433
0
    aes_mt_ctx->state = HAVE_NONE;
434
435
    /* initialize the mutexs and conditions for each lock in our struct */
436
0
    for (int i = 0; i < numkq; i++) {
437
0
      pthread_mutex_init(&aes_mt_ctx->q[i].lock, NULL);
438
0
      pthread_cond_init(&aes_mt_ctx->q[i].cond, NULL);
439
0
    }
440
0
    aes_mt_ctx->provctx = provctx;
441
0
    EVP_CipherInit(evp_ctx, EVP_aes_128_ctr(), NULL, NULL, 0);
442
0
    EVP_CIPHER_CTX_set_app_data(evp_ctx, aes_mt_ctx);
443
0
    return evp_ctx;
444
0
  }
445
0
  return NULL;
446
0
}
447
448
/* this function expects a void but we need the actual context
449
 * to get the app_data.
450
 */
451
void aes_mt_freectx(void *vevp_ctx)
452
0
{
453
0
  EVP_CIPHER_CTX *evp_ctx = vevp_ctx;
454
0
  struct aes_mt_ctx_st *aes_mt_ctx;
455
456
0
  if ((aes_mt_ctx = EVP_CIPHER_CTX_get_app_data(evp_ctx)) != NULL) {
457
0
    stop_and_join_pregen_threads(aes_mt_ctx);
458
459
0
    memset(aes_mt_ctx, 0, sizeof(*aes_mt_ctx));
460
0
    free(aes_mt_ctx);
461
0
    EVP_CIPHER_CTX_set_app_data(evp_ctx, NULL);
462
0
  }
463
0
  EVP_CIPHER_CTX_free(evp_ctx);
464
0
}
465
466
/* this function takes the EVP context, gets the AES context
467
 * and starts the various threads we need */
468
int aes_mt_start_threads(void *vevp_ctx, const u_char *key,
469
       size_t keylen, const u_char *iv,
470
       size_t ivlen, const OSSL_PARAM *ossl_params)
471
0
{
472
0
  EVP_CIPHER_CTX *evp_ctx = vevp_ctx;
473
0
  struct aes_mt_ctx_st *aes_mt_ctx;
474
475
476
  /* get the initial state of aes_mt_ctx (our cipher stream struct) */
477
0
  if ((aes_mt_ctx = EVP_CIPHER_CTX_get_app_data(evp_ctx)) == NULL) {
478
0
    fatal("Missing AES MT context data!");
479
0
  }
480
481
  /* we are initializing but the current structure already
482
   * has an IV and key so we want to kill the existing key data
483
   * and start over. This is important when we need to rekey the data stream */
484
0
  if (aes_mt_ctx->state == (HAVE_KEY | HAVE_IV)) {
485
    /* tell the pregen threads to exit */
486
0
    stop_and_join_pregen_threads(aes_mt_ctx);
487
488
    /* reset the exit flag */
489
0
    aes_mt_ctx->exit_flag = 0;
490
491
    /* Start over getting key & iv */
492
0
    aes_mt_ctx->state = HAVE_NONE;
493
0
  }
494
495
  /* set the initial key for this key stream queue */
496
0
  if (key != NULL) {
497
0
    aes_mt_ctx->keylen = EVP_CIPHER_CTX_key_length(evp_ctx) * 8;
498
0
    aes_mt_ctx->orig_key = key;
499
0
    aes_mt_ctx->state |= HAVE_KEY;
500
0
  }
501
502
  /* set the IV */
503
0
  if (iv != NULL) {
504
    /* init the counter this is just a 16byte uchar */
505
0
    memcpy(aes_mt_ctx->aes_counter, iv, AES_BLOCK_SIZE);
506
0
    aes_mt_ctx->state |= HAVE_IV;
507
0
  }
508
509
0
  if (aes_mt_ctx->state == (HAVE_KEY | HAVE_IV)) {
510
    /* Clear queues */
511
    /* set the first key in the key queue to the current counter */
512
0
    memcpy(aes_mt_ctx->q[0].ctr, aes_mt_ctx->aes_counter, AES_BLOCK_SIZE);
513
    /* indicate that it needs to be initialized */
514
0
    aes_mt_ctx->q[0].qstate = KQINIT;
515
    /* for each of the remaining queues set the first counter to the
516
     * counter and then add the size of the queue to the counter */
517
0
    for (int i = 1; i < numkq; i++) {
518
0
      memcpy(aes_mt_ctx->q[i].ctr, aes_mt_ctx->aes_counter, AES_BLOCK_SIZE);
519
0
      ssh_ctr_add(aes_mt_ctx->q[i].ctr, i * KQLEN, AES_BLOCK_SIZE);
520
0
      aes_mt_ctx->q[i].qstate = KQEMPTY;
521
0
    }
522
0
    aes_mt_ctx->qidx = 0;
523
0
    aes_mt_ctx->ridx = 0;
524
0
    aes_mt_ctx->struct_id = global_struct_id++;
525
526
    /* Start threads. Make sure we have enough stack space (under alpine)
527
    * and aren't using more than we need (linux). This can be as low as
528
    * 512KB but that's a minimum. 1024KB gives us a little headroom if we
529
    * need it */
530
0
#define STACK_SIZE (1024 * 1024)
531
0
                pthread_attr_t attr;
532
0
                pthread_attr_init(&attr);
533
0
                pthread_attr_setstacksize(&attr, STACK_SIZE);
534
0
    for (int i = 0; i < cipher_threads; i++) {
535
0
      pthread_rwlock_wrlock(&aes_mt_ctx->tid_lock);
536
0
      if (pthread_create(&aes_mt_ctx->tid[i], &attr, thread_loop, aes_mt_ctx) != 0)
537
0
        fatal ("AES-CTR MT Could not create thread in %s", __func__);
538
0
      else {
539
0
        aes_mt_ctx->id[i] = i;
540
0
        debug_f ("AES-CTR MT spawned a thread with id %lu (%lu, %d)",
541
0
           aes_mt_ctx->tid[i], aes_mt_ctx->struct_id,
542
0
           aes_mt_ctx->id[i]);
543
0
      }
544
0
      pthread_rwlock_unlock(&aes_mt_ctx->tid_lock);
545
0
    }
546
0
    pthread_mutex_lock(&aes_mt_ctx->q[0].lock);
547
    // wait for all of the threads to be initialized
548
0
    while (aes_mt_ctx->q[0].qstate == KQINIT)
549
0
      pthread_cond_wait(&aes_mt_ctx->q[0].cond, &aes_mt_ctx->q[0].lock);
550
0
    pthread_mutex_unlock(&aes_mt_ctx->q[0].lock);
551
0
  }
552
0
  return 1;
553
0
}
554
555
/* this should correspond to ssh_aes_ctr
556
 * OSSL_CORE_MAKE_FUNC(int, cipher_cipher,
557
 *                     (void *cctx,
558
 *                     unsigned char *out, size_t *outl, size_t outsize,
559
 *                     const unsigned char *in, size_t inl))
560
 */
561
562
int aes_mt_do_cipher(void *vevp_ctx,
563
          u_char *dest, size_t *destlen, size_t destsize,
564
          const u_char *src, size_t len)
565
0
{
566
0
  typedef union {
567
0
#ifdef CIPHER_INT128_OK
568
0
    __uint128_t *u128;
569
0
#endif
570
0
    uint64_t *u64;
571
0
    uint32_t *u32;
572
0
    uint8_t *u8;
573
0
    const uint8_t *cu8;
574
0
    uintptr_t u;
575
0
  } ptrs_t;
576
0
  ptrs_t destp, srcp, bufp;
577
0
  uintptr_t align;
578
0
  struct aes_mt_ctx_st *aes_mt_ctx;
579
0
  struct kq *q, *oldq;
580
0
  int ridx;
581
0
  u_char *buf;
582
0
  EVP_CIPHER_CTX *evp_ctx = vevp_ctx;
583
0
  uint64_t src_a, key_a;
584
  
585
0
  if (len == 0)
586
0
    return 1;
587
588
0
  if ((aes_mt_ctx = EVP_CIPHER_CTX_get_app_data(evp_ctx)) == NULL)
589
0
    return 0;
590
591
0
  q = &aes_mt_ctx->q[aes_mt_ctx->qidx];
592
0
  ridx = aes_mt_ctx->ridx;
593
594
  /* src already padded to block multiple */
595
0
  srcp.cu8 = src;
596
0
  destp.u8 = dest;
597
0
  do { /* do until len is 0 */
598
0
    buf = q->keys[ridx];
599
0
    bufp.u8 = buf;
600
601
    /* figure out the alignment on the fly */
602
0
#ifdef CIPHER_UNALIGNED_OK
603
0
    align = 0;
604
#else
605
    align = destp.u | srcp.u | bufp.u;
606
#endif
607
608
    /* xor the src against the key (buf)
609
     * different systems can do all 16 bytes at once or
610
     * may need to do it in 8 or 4 bytes chunks
611
     * worst case is doing it as a loop */
612
0
#ifdef CIPHER_INT128_OK
613
    /* with GCC 13 we have having consistent seg faults
614
     * in this section of code. Since this is a critical
615
     * code path we are removing this until we have a solution
616
     * in place -cjr 02/22/24
617
     * TODO: FIX THIS
618
     */
619
    /* if ((align & 0xf) == 0) { */
620
    /*  destp.u128[0] = srcp.u128[0] ^ bufp.u128[0]; */
621
    /* } else */
622
0
#endif
623
    /* 64 bits */
624
    /* this is causing undefined behaviour in sanitizers
625
     * this is annoying because it's more efficient
626
     * but UB is not something I want to retain */
627
0
    if ((align & 0x7) == 0) {
628
      /* this should resolve the strict aliasing UB
629
       * and the performance doesn't seem to change much
630
       * but the memcpys are killing me 3-5-26 cjr*/
631
0
      memcpy(&src_a, &srcp.u64[0], sizeof(uint64_t));
632
0
      memcpy(&key_a, &bufp.u64[0], sizeof(uint64_t));
633
0
      destp.u64[0] = src_a ^ key_a;
634
0
      memcpy(&src_a, &srcp.u64[1], sizeof(uint64_t));
635
0
      memcpy(&key_a, &bufp.u64[1], sizeof(uint64_t));
636
0
      destp.u64[1] = src_a ^ key_a;
637
      /* destp.u64[0] = srcp.u64[0] ^ bufp.u64[0]; */
638
      /* destp.u64[1] = srcp.u64[1] ^ bufp.u64[1]; */
639
                /* 32 bits */
640
0
    } else
641
0
    if ((align & 0x3) == 0) {
642
0
      destp.u32[0] = srcp.u32[0] ^ bufp.u32[0];
643
0
      destp.u32[1] = srcp.u32[1] ^ bufp.u32[1];
644
0
      destp.u32[2] = srcp.u32[2] ^ bufp.u32[2];
645
0
      destp.u32[3] = srcp.u32[3] ^ bufp.u32[3];
646
0
    } else {
647
      /*1 byte at a time*/
648
0
      size_t i;
649
0
      for (i = 0; i < AES_BLOCK_SIZE; ++i)
650
0
        dest[i] = src[i] ^ buf[i];
651
0
    }
652
653
    /* inc/decrement the pointers by the block size (16)*/
654
0
    destp.u += AES_BLOCK_SIZE;
655
0
    srcp.u += AES_BLOCK_SIZE;
656
657
    /* Increment read index, switch queues on rollover */
658
0
    if ((ridx = (ridx + 1) % KQLEN) == 0) {
659
0
      oldq = q;
660
661
      /* Mark next queue draining, may need to wait */
662
0
      aes_mt_ctx->qidx = (aes_mt_ctx->qidx + 1) % numkq;
663
0
      q = &aes_mt_ctx->q[aes_mt_ctx->qidx];
664
0
      pthread_mutex_lock(&q->lock);
665
0
      while (q->qstate != KQFULL) {
666
0
        pthread_cond_wait(&q->cond, &q->lock);
667
0
      }
668
0
      q->qstate = KQDRAINING;
669
0
      pthread_cond_broadcast(&q->cond);
670
0
      pthread_mutex_unlock(&q->lock);
671
672
      /* Mark consumed queue empty and signal producers */
673
0
      pthread_mutex_lock(&oldq->lock);
674
0
      oldq->qstate = KQEMPTY;
675
0
      pthread_cond_broadcast(&oldq->cond);
676
0
      pthread_mutex_unlock(&oldq->lock);
677
0
    }
678
0
  } while (len -= AES_BLOCK_SIZE);
679
0
  aes_mt_ctx->ridx = ridx;
680
0
  return 1;
681
0
}
682
683
#endif /*WITH_OPENSSL3*/