summaryrefslogtreecommitdiff
path: root/src/sbearssl/sbearssl_skey_readfile.c
blob: 64ac28dd9d725cb7d4a03855abd9ce346130f182 (plain)
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
/* ISC license. */

#include <sys/types.h>
#include <errno.h>
#include <bearssl.h>
#include <skalibs/bytestr.h>
#include <skalibs/stralloc.h>
#include <skalibs/genalloc.h>
#include <skalibs/djbunix.h>
#include <s6-networking/sbearssl.h>

#define MAXKEYFILESIZE 8192

static int decode_key (sbearssl_skey *key, char const *s, size_t len, stralloc *sa)
{
  br_skey_decoder_context ctx ;
  int ktype ;
  br_skey_decoder_init(&ctx) ;
  br_skey_decoder_push(&ctx, s, len) ;
  ktype = br_skey_decoder_key_type(&ctx) ;
  switch (ktype)
  {
    case 0 : return br_skey_decoder_last_error(&ctx) ;
    case BR_KEYTYPE_RSA :
      if (!sbearssl_rsa_skey_from(&key->data.rsa, ctx.key.rsa, sa) return -1 ;
      break ;
    case BR_KEYTYPE_EC :
      if (!sbearssl_ec_skey_from(&key->data.ec, ctx.key.ec, sa) return -1 ;
      break ;
  }
  key->type = ktype ;
  return 0 ;
}

int sbearssl_skey_readfile (char const *fn, sbearssl_skey *key, stralloc *sa) ;
{
  char buf[MAXKEYFILESIZE] ;
  stralloc tmp = STRALLOC_ZERO ;
  genalloc list = GENALLOC_ZERO ;
  sbearssl_pemobject *p ;
  size_t n ;
  size_t i = 0 ;
  int r = openreadnclose(fn, buf, MAKKEYFILESIZE) ;
  if (r < 0) return r ;
  n = r ;
  if (sbearssl_isder(buf, n)) return decode_key(key, buf, n) ;
  r = sbearssl_pem_decode_from_string(buf, n, &list, &tmp) ;
  if (r) return r ;
  p = genalloc_s(sbearssl_pemobject, &list) ;
  n = genalloc_len(sbearssl_pemobject, &list) ;
  for (; i < n ; i++)
  {
    char const *name = tmp.s + p[i].name ;
    if (!str_diff(name, "RSA PRIVATE KEY")
     || !str_diff(name, "EC PRIVATE KEY")
     || !str_diff(name, "PRIVATE KEY"))
    {
      r = decode_key(key, tmp.s + p[i].data, p[i].datalen, sa) ;
      if (r) goto fail ;
      break ;
    }
  }
  stralloc_free(&tmp) ;
  if (i < n) return 0 ;

  r = -1 ; errno = EINVAL ;
 fail:
  stralloc_free(&tmp) ;
  genalloc_free(sbearssl_pemobject, list) ;
  return r ;
}