aboutsummaryrefslogtreecommitdiff
path: root/ks_volatile.c
blob: c8a424c0a28ba78f6ca1503aafc4c047af42c6ed (plain) (blame)
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
/*
 * ks_volatile.c
 * -------------
 * Keystore implementation in normal volatile internal memory.
 *
 * NB: This is only suitable for cases where you do not want the keystore
 *     to survive library exit, eg, for storing PKCS #11 session keys.
 *
 * Authors: Rob Austein
 * Copyright (c) 2015-2016, NORDUnet A/S All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * - Neither the name of the NORDUnet nor the names of its contributors may
 *   be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <string.h>
#include <assert.h>

#include "hal.h"
#include "hal_internal.h"

#define KEK_LENGTH (bitsToBytes(256))

#ifndef STATIC_KS_VOLATILE_SLOTS
#define STATIC_KS_VOLATILE_SLOTS HAL_STATIC_PKEY_STATE_BLOCKS
#endif

#ifndef STATIC_KS_VOLATILE_ATTRIBUTE_SPACE
#define STATIC_KS_VOLATILE_ATTRIBUTE_SPACE 4096
#endif

/*
 * In-memory keystore database.  This should also be usable for
 * mmap(), if and when we get around to rewriting that driver (and in
 * which case this driver probably ought to be renamed ks_memory).
 */

typedef struct {
  hal_key_type_t        type;
  hal_curve_name_t      curve;
  hal_key_flags_t       flags;
  hal_client_handle_t   client;
  hal_session_handle_t  session;
  size_t                der_len;
  unsigned              attributes_len;
  uint8_t               der[HAL_KS_WRAPPED_KEYSIZE + STATIC_KS_VOLATILE_ATTRIBUTE_SPACE];
} ks_key_t;

typedef struct {
  hal_ks_index_t        ksi;
  ks_key_t              *keys;
} db_t;

/*
 * "Subclass" (well, what one can do in C) of hal_ks_t.  This is
 * separate from db_t primarily to simplify things like rewriting the
 * old ks_mmap driver to piggy-back on the ks_volatile driver: we
 * wouldn't want the hal_ks_t into the mmap()ed file.
 */

typedef struct {
  hal_ks_t ks;              /* Must be first */
  db_t *db;                 /* Which memory-based keystore database */
  int per_session;          /* Whether objects are per-session */
} ks_t;

/*
 * If we also supported mmap, there would be a separate definition for
 * HAL_KS_MMAP_SLOTS above, and the bulk of the code would be under a
 * conditional testing whether either HAL_KS_*_SLOTS were nonzero.
 */

#if STATIC_KS_VOLATILE_SLOTS > 0

static ks_t volatile_ks;

static inline ks_t *ks_to_ksv(hal_ks_t *ks)
{
  return (ks_t *) ks;
}

/*
 * Check whether the current session can see a particular key.  One
 * might expect this to be based on whether the session matches, and
 * indeed it would be in a sane world, but in the world of PKCS #11,
 * keys belong to sessions, are visible to other sessions, and may
 * even be modifiable by other sessions, but softly and silently
 * vanish away when the original creating session is destroyed.
 *
 * In our terms, this means that visibility of session objects is
 * determined only by the client handle, so taking the session handle
 * as an argument here isn't really necessary, but we've flipflopped
 * on that enough times that at least for now I'd prefer to leave the
 * session handle here and not have to revise all the RPC calls again.
 * Remove it at some later date and redo the RPC calls if we manage to
 * avoid revising this yet again.
 */

static inline int key_visible_to_session(const ks_t * const ksv,
                                         const hal_client_handle_t client,
                                         const hal_session_handle_t session,
                                         const ks_key_t * const k)
{
  return !ksv->per_session || client.handle == HAL_HANDLE_NONE || k->client.handle  == client.handle;
}

static inline void *gnaw(uint8_t **mem, size_t *len, const size_t size)
{
  if (mem == NULL || *mem == NULL || len == NULL || size > *len)
    return NULL;
  void *ret = *mem;
  *mem += size;
  *len -= size;
  return ret;
}

static hal_error_t ks_init(const hal_ks_driver_t * const driver,
                           const int per_session,
                           ks_t *ksv,
                           uint8_t *mem,
                           size_t len)
{
  if (ksv == NULL || mem == NULL)
    return HAL_ERROR_IMPOSSIBLE;

  memset(ksv, 0, sizeof(*ksv));
  memset(mem, 0, len);

  ksv->ks.driver     = driver;
  ksv->per_session   = per_session;
  ksv->db            = gnaw(&mem, &len, sizeof(*ksv->db));
  ksv->db->ksi.index = gnaw(&mem, &len, sizeof(*ksv->db->ksi.index) * STATIC_KS_VOLATILE_SLOTS);
  ksv->db->ksi.names = gnaw(&mem, &len, sizeof(*ksv->db->ksi.names) * STATIC_KS_VOLATILE_SLOTS);
  ksv->db->keys      = gnaw(&mem, &len, sizeof(*ksv->db->keys)      * STATIC_KS_VOLATILE_SLOTS);
  ksv->db->ksi.size  = STATIC_KS_VOLATILE_SLOTS;
  ksv->db->ksi.used  = 0;

  if (ksv->db            == NULL ||
      ksv->db->ksi.index == NULL ||
      ksv->db->ksi.names == NULL ||
      ksv->db->keys      == NULL)
    return HAL_ERROR_IMPOSSIBLE;

  /*
   * Set up keystore with empty index and full free list.
   * Since this driver doesn't care about wear leveling,
   * just populate the free list in block numerical order.
   */

  for (int i = 0; i < STATIC_KS_VOLATILE_SLOTS; i++)
    ksv->db->ksi.index[i] = i;

  return hal_ks_index_setup(&ksv->db->ksi);
}

static hal_error_t ks_volatile_init(const hal_ks_driver_t * const driver)
{
  const size_t len = (sizeof(*volatile_ks.db) +
                      sizeof(*volatile_ks.db->ksi.index) * STATIC_KS_VOLATILE_SLOTS +
                      sizeof(*volatile_ks.db->ksi.names) * STATIC_KS_VOLATILE_SLOTS +
                      sizeof(*volatile_ks.db->keys)      * STATIC_KS_VOLATILE_SLOTS);

  uint8_t *mem = hal_allocate_static_memory(len);

  if (mem == NULL)
    return HAL_ERROR_ALLOCATION_FAILURE;

  return ks_init(driver, 1, &volatile_ks, mem, len);
}

static hal_error_t ks_volatile_shutdown(const hal_ks_driver_t * const driver)
{
  if (volatile_ks.ks.driver != driver)
    return HAL_ERROR_KEYSTORE_ACCESS;
  return HAL_OK;
}

static hal_error_t ks_volatile_open(const hal_ks_driver_t * const driver,
                                    hal_ks_t **ks)
{
  assert(driver != NULL && ks != NULL);
  *ks = &volatile_ks.ks;
  return HAL_OK;
}

static hal_error_t ks_volatile_close(hal_ks_t *ks)
{
  return HAL_OK;
}

static inline int acceptable_key_type(const hal_key_type_t type)
{
  switch (type) {
  case HAL_KEY_TYPE_RSA_PRIVATE:
  case HAL_KEY_TYPE_EC_PRIVATE:
  case HAL_KEY_TYPE_RSA_PUBLIC:
  case HAL_KEY_TYPE_EC_PUBLIC:
    return 1;
  default:
    return 0;
  }
}

static hal_error_t ks_store(hal_ks_t *ks,
                            hal_pkey_slot_t *slot,
                            const uint8_t * const der, const size_t der_len)
{
  if (ks == NULL || slot == NULL || der == NULL || der_len == 0 || !acceptable_key_type(slot->type))
    return HAL_ERROR_BAD_ARGUMENTS;

  ks_t *ksv = ks_to_ksv(ks);
  hal_error_t err;
  unsigned b;

  if (ksv->db == NULL)
    return HAL_ERROR_KEYSTORE_ACCESS;

  if ((err = hal_ks_index_add(&ksv->db->ksi, &slot->name, 0, &b, &slot->hint)) != HAL_OK)
    return err;

  uint8_t kek[KEK_LENGTH];
  size_t kek_len;
  ks_key_t k;

  memset(&k, 0, sizeof(k));
  k.der_len = sizeof(k.der);
  k.type    = slot->type;
  k.curve   = slot->curve;
  k.flags   = slot->flags;
  k.client  = slot->client_handle;
  k.session = slot->session_handle;

  if ((err = hal_mkm_get_kek(kek, &kek_len, sizeof(kek))) == HAL_OK)
    err = hal_aes_keywrap(NULL, kek, kek_len, der, der_len, k.der, &k.der_len);

  memset(kek, 0, sizeof(kek));

  if (err == HAL_OK)
    ksv->db->keys[b] = k;
  else
    (void) hal_ks_index_delete(&ksv->db->ksi, &slot->name, 0, NULL, &slot->hint);

  return err;
}

static hal_error_t ks_fetch(hal_ks_t *ks,
                            hal_pkey_slot_t *slot,
                            uint8_t *der, size_t *der_len, const size_t der_max)
{
  if (ks == NULL || slot == NULL)
    return HAL_ERROR_BAD_ARGUMENTS;

  ks_t *ksv = ks_to_ksv(ks);
  hal_error_t err;
  unsigned b;

  if (ksv->db == NULL)
    return HAL_ERROR_KEYSTORE_ACCESS;

  if ((err = hal_ks_index_find(&ksv->db->ksi, &slot->name, 0, &b, &slot->hint)) != HAL_OK)
    return err;

  const ks_key_t * const k = &ksv->db->keys[b];

  if (!key_visible_to_session(ksv, slot->client_handle, slot->session_handle, k))
    return HAL_ERROR_KEY_NOT_FOUND;

  slot->type  = k->type;
  slot->curve = k->curve;
  slot->flags = k->flags;

  if (der == NULL && der_len != NULL)
    *der_len = k->der_len;

  if (der != NULL) {

    uint8_t kek[KEK_LENGTH];
    size_t kek_len, der_len_;
    hal_error_t err;

    if (der_len == NULL)
      der_len = &der_len_;

    *der_len = der_max;

    if ((err = hal_mkm_get_kek(kek, &kek_len, sizeof(kek))) == HAL_OK)
      err = hal_aes_keyunwrap(NULL, kek, kek_len, k->der, k->der_len, der, der_len);

    memset(kek, 0, sizeof(kek));

    if (err != HAL_OK)
      return err;
  }

  return HAL_OK;
}

static hal_error_t ks_delete(hal_ks_t *ks,
                             hal_pkey_slot_t *slot)
{
  if (ks == NULL || slot == NULL)
    return HAL_ERROR_BAD_ARGUMENTS;

  ks_t *ksv = ks_to_ksv(ks);
  hal_error_t err;
  unsigned b;

  if (ksv->db == NULL)
    return HAL_ERROR_KEYSTORE_ACCESS;

  if ((err = hal_ks_index_find(&ksv->db->ksi, &slot->name, 0, &b, &slot->hint)) != HAL_OK)
    return err;

  if (!key_visible_to_session(ksv, slot->client_handle, slot->session_handle, &ksv->db->keys[b]))
    return HAL_ERROR_KEY_NOT_FOUND;

  if ((err = hal_ks_index_delete(&ksv->db->ksi, &slot->name, 0, &b, &slot->hint)) != HAL_OK)
    return err;

  memset(&ksv->db->keys[b], 0, sizeof(ksv->db->keys[b]));

  return HAL_OK;
}

static hal_error_t ks_list(hal_ks_t *ks,
                           hal_client_handle_t client,
                           hal_session_handle_t session,
                           hal_pkey_info_t *result,
                           unsigned *result_len,
                           const unsigned result_max)
{
  if (ks == NULL || result == NULL || result_len == NULL)
    return HAL_ERROR_BAD_ARGUMENTS;

  ks_t *ksv = ks_to_ksv(ks);

  if (ksv->db == NULL)
    return HAL_ERROR_KEYSTORE_ACCESS;

  *result_len = 0;

  for (int i = 0; i < ksv->db->ksi.used; i++) {
    unsigned b = ksv->db->ksi.index[i];

    if (ksv->db->ksi.names[b].chunk > 0)
      continue;

    if (!key_visible_to_session(ksv, client, session, &ksv->db->keys[b]))
      continue;

    if (*result_len >= result_max)
      return HAL_ERROR_RESULT_TOO_LONG;

    result[i].name  = ksv->db->ksi.names[b].name;
    result[i].type  = ksv->db->keys[b].type;
    result[i].curve = ksv->db->keys[b].curve;
    result[i].flags = ksv->db->keys[b].flags;
    ++ *result_len;
  }

  return HAL_OK;
}

static hal_error_t ks_match(hal_ks_t *ks,
                            hal_client_handle_t client,
                            hal_session_handle_t session,
                            const hal_key_type_t type,
                            const hal_curve_name_t curve,
                            const hal_key_flags_t flags,
                            hal_rpc_pkey_attribute_t *attributes,
                            const unsigned attributes_len,
                            hal_uuid_t *result,
                            unsigned *result_len,
                            const unsigned result_max,
                            const hal_uuid_t * const previous_uuid)
{
  if (ks == NULL || attributes == NULL ||
      result == NULL || result_len == NULL || previous_uuid == NULL)
    return HAL_ERROR_BAD_ARGUMENTS;

  ks_t *ksv = ks_to_ksv(ks);

  if (ksv->db == NULL)
    return HAL_ERROR_KEYSTORE_ACCESS;

  hal_error_t err;
  int i = -1;

  *result_len = 0;

  err = hal_ks_index_find(&ksv->db->ksi, previous_uuid, 0, NULL, &i);

  if (err == HAL_ERROR_KEY_NOT_FOUND)
    i--;
  else if (err != HAL_OK)
    return err;

  while (*result_len < result_max && ++i < ksv->db->ksi.used) {

    unsigned b = ksv->db->ksi.index[i];

    if (ksv->db->ksi.names[b].chunk > 0)
      continue;

    if (type != HAL_KEY_TYPE_NONE && type != ksv->db->keys[b].type)
      continue;

    if (curve != HAL_CURVE_NONE && curve != ksv->db->keys[b].curve)
      continue;

    if (!key_visible_to_session(ksv, client, session, &ksv->db->keys[b]))
      continue;

    if (attributes_len > 0) {
      const ks_key_t * const k = &ksv->db->keys[b];
      int ok = 1;

      if (k->attributes_len == 0)
        continue;

      hal_rpc_pkey_attribute_t key_attrs[k->attributes_len];

      if ((err = hal_ks_attribute_scan(k->der + k->der_len, sizeof(k->der) - k->der_len,
                                       key_attrs, k->attributes_len, NULL)) != HAL_OK)
        return err;

      for (hal_rpc_pkey_attribute_t *required = attributes;
           ok && required < attributes + attributes_len; required++) {

        hal_rpc_pkey_attribute_t *present = key_attrs;
        while (ok && present->type != required->type)
          ok = ++present < key_attrs + k->attributes_len;

        if (ok)
          ok = (present->length == required->length &&
                !memcmp(present->value, required->value, present->length));
      }

      if (!ok)
        continue;
    }

    result[*result_len] = ksv->db->ksi.names[b].name;
    ++*result_len;
  }

  return HAL_OK;
}

static  hal_error_t ks_set_attribute(hal_ks_t *ks,
                                     hal_pkey_slot_t *slot,
                                     const uint32_t type,
                                     const uint8_t * const value,
                                     const size_t value_len)
{
  if (ks == NULL || slot == NULL)
    return HAL_ERROR_BAD_ARGUMENTS;

  ks_t *ksv = ks_to_ksv(ks);
  hal_error_t err;
  unsigned b;

  if (ksv->db == NULL)
    return HAL_ERROR_KEYSTORE_ACCESS;

  if ((err = hal_ks_index_find(&ksv->db->ksi, &slot->name, 0, &b, &slot->hint)) != HAL_OK)
    return err;

  ks_key_t * const k = &ksv->db->keys[b];

  if (!key_visible_to_session(ksv, slot->client_handle, slot->session_handle, k))
    return HAL_ERROR_KEY_NOT_FOUND;

  hal_rpc_pkey_attribute_t attributes[k->attributes_len + 1];
  uint8_t *bytes = k->der + k->der_len;
  size_t bytes_len = sizeof(k->der) - k->der_len;
  size_t total_len;

  err = hal_ks_attribute_scan(bytes, bytes_len, attributes, k->attributes_len, &total_len);

  if (err != HAL_OK)
    return err;

  return hal_ks_attribute_insert(bytes, bytes_len, attributes, &k->attributes_len, &total_len,
                                 type, value, value_len);
}

static  hal_error_t ks_get_attribute(hal_ks_t *ks,
                                     hal_pkey_slot_t *slot,
                                     const uint32_t type,
                                     uint8_t *value,
                                     size_t *value_len,
                                     const size_t value_max)
{
  if (ks == NULL || slot == NULL)
    return HAL_ERROR_BAD_ARGUMENTS;

  ks_t *ksv = ks_to_ksv(ks);
  hal_error_t err;
  unsigned b;

  if (ksv->db == NULL)
    return HAL_ERROR_KEYSTORE_ACCESS;

  if ((err = hal_ks_index_find(&ksv->db->ksi, &slot->name, 0, &b, &slot->hint)) != HAL_OK)
    return err;

  const ks_key_t * const k = &ksv->db->keys[b];

  if (!key_visible_to_session(ksv, slot->client_handle, slot->session_handle, k))
    return HAL_ERROR_KEY_NOT_FOUND;

  if (k->attributes_len == 0)
    return HAL_ERROR_ATTRIBUTE_NOT_FOUND;

  hal_rpc_pkey_attribute_t attributes[k->attributes_len];

  if ((err = hal_ks_attribute_scan(k->der + k->der_len, sizeof(k->der) - k->der_len,
                                   attributes, k->attributes_len, NULL)) != HAL_OK)
    return err;

  int i = 0;

  while (attributes[i].type != type)
    if (++i >= k->attributes_len)
      return HAL_ERROR_ATTRIBUTE_NOT_FOUND;

  if (attributes[i].length > value_max && value != NULL)
    return HAL_ERROR_RESULT_TOO_LONG;

  if (value != NULL)
    memcpy(value, attributes[i].value, attributes[i].length);

  if (value_len != NULL)
    *value_len = attributes[i].length;

  return HAL_OK;
}

static hal_error_t ks_delete_attribute(hal_ks_t *ks,
                                       hal_pkey_slot_t *slot,
                                       const uint32_t type)
{
  if (ks == NULL || slot == NULL)
    return HAL_ERROR_BAD_ARGUMENTS;

  ks_t *ksv = ks_to_ksv(ks);
  hal_error_t err;
  unsigned b;

  if (ksv->db == NULL)
    return HAL_ERROR_KEYSTORE_ACCESS;

  if ((err = hal_ks_index_find(&ksv->db->ksi, &slot->name, 0, &b, &slot->hint)) != HAL_OK)
    return err;

  ks_key_t * const k = &ksv->db->keys[b];

  if (!key_visible_to_session(ksv, slot->client_handle, slot->session_handle, k))
    return HAL_ERROR_KEY_NOT_FOUND;

  hal_rpc_pkey_attribute_t attributes[k->attributes_len + 1];
  uint8_t *bytes = k->der + k->der_len;
  size_t bytes_len = sizeof(k->der) - k->der_len;
  size_t total_len;

  err = hal_ks_attribute_scan(bytes, bytes_len, attributes, k->attributes_len, &total_len);

  if (err != HAL_OK)
    return err;

  return hal_ks_attribute_delete(bytes, bytes_len, attributes, &k->attributes_len, &total_len, type);
}

const hal_ks_driver_t hal_ks_volatile_driver[1] = {{
  ks_volatile_init,
  ks_volatile_shutdown,
  ks_volatile_open,
  ks_volatile_close,
  ks_store,
  ks_fetch,
  ks_delete,
  ks_list,
  ks_match,
  ks_set_attribute,
  ks_get_attribute,
  ks_delete_attribute
}};

#endif /* STATIC_KS_VOLATILE_SLOTS > 0 */

/*
 * Local variables:
 * indent-tabs-mode: nil
 * End:
 */
s="w"> const driver_t *check_driver(const hal_hash_descriptor_t * const descriptor) { return descriptor == NULL ? NULL : descriptor->driver; } /* * Report whether cores are present. */ hal_error_t hal_hash_core_present(const hal_hash_descriptor_t * const descriptor) { const driver_t * const driver = check_driver(descriptor); if (driver == NULL) return HAL_ERROR_BAD_ARGUMENTS; return hal_io_expected(driver->name_addr, (const uint8_t *) driver->core_name, sizeof(driver->core_name)); } /* * Initialize hash state. */ hal_error_t hal_hash_initialize(const hal_hash_descriptor_t * const descriptor, hal_hash_state_t *opaque_state, void *state_buffer, const size_t state_length) { const driver_t * const driver = check_driver(descriptor); internal_hash_state_t *state = state_buffer; if (driver == NULL || state == NULL || opaque_state == NULL || state_length < descriptor->hash_state_length) return HAL_ERROR_BAD_ARGUMENTS; memset(state, 0, sizeof(*state)); state->descriptor = descriptor; state->driver = driver; opaque_state->state = state; return HAL_OK; } /* * Send one block to a core. */ static hal_error_t hash_write_block(const internal_hash_state_t * const state) { uint8_t ctrl_cmd[4]; hal_error_t err; assert(state != NULL && state->descriptor != NULL && state->driver != NULL); assert(state->descriptor->block_length % 4 == 0); if (debug) fprintf(stderr, "[ %s ]\n", state->block_count == 0 ? "init" : "next"); if ((err = hal_io_write(state->driver->block_addr, state->block, state->descriptor->block_length)) != HAL_OK) return err; ctrl_cmd[0] = ctrl_cmd[1] = ctrl_cmd[2] = 0; ctrl_cmd[3] = state->block_count == 0 ? CTRL_INIT : CTRL_NEXT; ctrl_cmd[3] |= state->driver->ctrl_mode; /* * Not sure why we're waiting for ready here, but it's what the old * (read: tested) code did, so keep that behavior for now. */ if ((err = hal_io_write(state->driver->ctrl_addr, ctrl_cmd, sizeof(ctrl_cmd))) != HAL_OK) return err; return hal_io_wait_valid(state->driver->status_addr); } /* * Read hash result from core. */ static hal_error_t hash_read_digest(const driver_t * const driver, uint8_t *digest, const size_t digest_length) { hal_error_t err; assert(digest != NULL && digest_length % 4 == 0); if ((err = hal_io_wait_valid(driver->status_addr)) != HAL_OK) return err; return hal_io_read(driver->digest_addr, digest, digest_length); } /* * Add data to hash. */ hal_error_t hal_hash_update(hal_hash_state_t opaque_state, /* Opaque state block */ const uint8_t * const data_buffer, /* Data to be hashed */ size_t data_buffer_length) /* Length of data_buffer */ { internal_hash_state_t *state = opaque_state.state; const uint8_t *p = data_buffer; hal_error_t err; size_t n; if (state == NULL || data_buffer == NULL) return HAL_ERROR_BAD_ARGUMENTS; if (data_buffer_length == 0) return HAL_OK; assert(state->descriptor != NULL && state->driver != NULL); assert(state->descriptor->block_length <= sizeof(state->block)); while ((n = state->descriptor->block_length - state->block_used) <= data_buffer_length) { /* * We have enough data for another complete block. */ if (debug) fprintf(stderr, "[ Full block, data_buffer_length %lu, used %lu, n %lu, msg_length %llu ]\n", (unsigned long) data_buffer_length, (unsigned long) state->block_used, (unsigned long) n, state->msg_length_low); memcpy(state->block + state->block_used, p, n); if ((state->msg_length_low += n) < n) state->msg_length_high++; state->block_used = 0; data_buffer_length -= n; p += n; if ((err = hash_write_block(state)) != HAL_OK) return err; state->block_count++; } if (data_buffer_length > 0) { /* * Data left over, but not enough for a full block, stash it. */ if (debug) fprintf(stderr, "[ Partial block, data_buffer_length %lu, used %lu, n %lu, msg_length %llu ]\n", (unsigned long) data_buffer_length, (unsigned long) state->block_used, (unsigned long) n, state->msg_length_low); assert(data_buffer_length < n); memcpy(state->block + state->block_used, p, data_buffer_length); if ((state->msg_length_low += data_buffer_length) < data_buffer_length) state->msg_length_high++; state->block_used += data_buffer_length; } return HAL_OK; } /* * Finish hash and return digest. */ hal_error_t hal_hash_finalize(hal_hash_state_t opaque_state, /* Opaque state block */ uint8_t *digest_buffer, /* Returned digest */ const size_t digest_buffer_length) /* Length of digest_buffer */ { internal_hash_state_t *state = opaque_state.state; uint64_t bit_length_high, bit_length_low; hal_error_t err; uint8_t *p; size_t n; int i; if (state == NULL || digest_buffer == NULL) return HAL_ERROR_BAD_ARGUMENTS; assert(state->descriptor != NULL && state->driver != NULL); if (digest_buffer_length < state->descriptor->digest_length) return HAL_ERROR_BAD_ARGUMENTS; assert(state->descriptor->block_length <= sizeof(state->block)); /* * Add padding, then pull result from the core */ bit_length_low = (state->msg_length_low << 3); bit_length_high = (state->msg_length_high << 3) | (state->msg_length_low >> 61); /* Initial pad byte */ assert(state->block_used < state->descriptor->block_length); state->block[state->block_used++] = 0x80; /* If not enough room for bit count, zero and push current block */ if ((n = state->descriptor->block_length - state->block_used) < state->driver->length_length) { if (debug) fprintf(stderr, "[ Overflow block, used %lu, n %lu, msg_length %llu ]\n", (unsigned long) state->block_used, (unsigned long) n, state->msg_length_low); if (n > 0) memset(state->block + state->block_used, 0, n); if ((err = hash_write_block(state)) != HAL_OK) return err; state->block_count++; state->block_used = 0; } /* Pad final block */ n = state->descriptor->block_length - state->block_used; assert(n >= state->driver->length_length); if (n > 0) memset(state->block + state->block_used, 0, n); if (debug) fprintf(stderr, "[ Final block, used %lu, n %lu, msg_length %llu ]\n", (unsigned long) state->block_used, (unsigned long) n, state->msg_length_low); p = state->block + state->descriptor->block_length; for (i = 0; (bit_length_low || bit_length_high) && i < state->driver->length_length; i++) { *--p = (uint8_t) (bit_length_low & 0xFF); bit_length_low >>= 8; if (bit_length_high) { bit_length_low |= ((bit_length_high & 0xFF) << 56); bit_length_high >>= 8; } } /* Push final block */ if ((err = hash_write_block(state)) != HAL_OK) return err; state->block_count++; /* All data pushed to core, now we just need to read back the result */ if ((err = hash_read_digest(state->driver, digest_buffer, state->descriptor->digest_length)) != HAL_OK) return err; return HAL_OK; } /* * Initialize HMAC state. */ hal_error_t hal_hmac_initialize(const hal_hash_descriptor_t * const descriptor, hal_hmac_state_t *opaque_state, void *state_buffer, const size_t state_length, const uint8_t * const key, const size_t key_length) { const driver_t * const driver = check_driver(descriptor); internal_hmac_state_t *state = state_buffer; internal_hash_state_t *h = &state->hash_state; hal_hash_state_t oh; hal_error_t err; int i; if (descriptor == NULL || driver == NULL || state == NULL || opaque_state == NULL || state_length < descriptor->hmac_state_length) return HAL_ERROR_BAD_ARGUMENTS; assert(descriptor->block_length <= sizeof(state->keybuf)); #if 0 /* * RFC 2104 frowns upon keys shorter than the digest length. * ... but most of the test vectors fail this test! */ if (key_length < descriptor->digest_length) return HAL_ERROR_UNSUPPORTED_KEY; #endif if ((err = hal_hash_initialize(descriptor, &oh, h, sizeof(*h))) != HAL_OK) return err; /* * If the supplied HMAC key is longer than the hash block length, we * need to hash the supplied HMAC key to get the real HMAC key. * Otherwise, we just use the supplied HMAC key directly. */ memset(state->keybuf, 0, sizeof(state->keybuf)); if (key_length <= descriptor->block_length) memcpy(state->keybuf, key, key_length); else if ((err = hal_hash_update(oh, key, key_length)) != HAL_OK || (err = hal_hash_finalize(oh, state->keybuf, sizeof(state->keybuf))) != HAL_OK || (err = hal_hash_initialize(descriptor, &oh, h, sizeof(*h))) != HAL_OK) return err; /* * XOR the key with the IPAD value, then start the inner hash. */ for (i = 0; i < descriptor->block_length; i++) state->keybuf[i] ^= HMAC_IPAD; if ((err = hal_hash_update(oh, state->keybuf, descriptor->block_length)) != HAL_OK) return err; /* * Prepare the key for the final hash. Since we just XORed key with * IPAD, we need to XOR with both IPAD and OPAD to get key XOR OPAD. */ for (i = 0; i < descriptor->block_length; i++) state->keybuf[i] ^= HMAC_IPAD ^ HMAC_OPAD; /* * If we had some good way of saving all of our state (including * state internal to the hash core), this would be a good place to * do it, since it might speed up algorithms like PBKDF2 which do * repeated HMAC operations using the same key. Revisit this if and * when the hash cores support such a thing. */ opaque_state->state = state; return HAL_OK; } /* * Add data to HMAC. */ hal_error_t hal_hmac_update(const hal_hmac_state_t opaque_state, const uint8_t * data, const size_t length) { internal_hmac_state_t *state = opaque_state.state; internal_hash_state_t *h = &state->hash_state; hal_hash_state_t oh = { h }; if (state == NULL || data == NULL) return HAL_ERROR_BAD_ARGUMENTS; return hal_hash_update(oh, data, length); } /* * Finish and return HMAC. */ hal_error_t hal_hmac_finalize(const hal_hmac_state_t opaque_state, uint8_t *hmac, const size_t length) { internal_hmac_state_t *state = opaque_state.state; internal_hash_state_t *h = &state->hash_state; const hal_hash_descriptor_t *descriptor; hal_hash_state_t oh = { h }; uint8_t d[HAL_MAX_HASH_DIGEST_LENGTH]; hal_error_t err; if (state == NULL || hmac == NULL) return HAL_ERROR_BAD_ARGUMENTS; descriptor = h->descriptor; assert(descriptor != NULL && descriptor->digest_length <= sizeof(d)); /* * Finish up inner hash and extract digest, then perform outer hash * to get HMAC. Key was prepared for this in hal_hmac_initialize(). */ if ((err = hal_hash_finalize(oh, d, sizeof(d))) != HAL_OK || (err = hal_hash_initialize(descriptor, &oh, h, sizeof(*h))) != HAL_OK || (err = hal_hash_update(oh, state->keybuf, descriptor->block_length)) != HAL_OK || (err = hal_hash_update(oh, d, descriptor->digest_length)) != HAL_OK || (err = hal_hash_finalize(oh, hmac, length)) != HAL_OK) return err; return HAL_OK; } /* * "Any programmer who fails to comply with the standard naming, formatting, * or commenting conventions should be shot. If it so happens that it is * inconvenient to shoot him, then he is to be politely requested to recode * his program in adherence to the above standard." * -- Michael Spier, Digital Equipment Corporation * * Local variables: * indent-tabs-mode: nil * End: */