Get the CSR

This commit is contained in:
2024-08-16 11:51:33 +02:00
parent 0c11703cea
commit 9966904e4d
4 changed files with 80 additions and 2 deletions

View File

@ -2,6 +2,7 @@
#include "system.h"
#include "constants.h"
#include "storage.h"
#include "dev_name.h"
#include <string.h>
#include <mbedtls/build_info.h>
@ -11,6 +12,7 @@
#include <mbedtls/ecdsa.h>
#include <mbedtls/sha256.h>
#include <mbedtls/pk.h>
#include <mbedtls/x509_csr.h>
#define ECPARAMS MBEDTLS_ECP_DP_SECP256R1
@ -80,6 +82,10 @@ bool crypto_gen_priv_key()
storage_set_priv_key(key_buff + PRV_KEY_DER_MAX_BYTES - ret, ret);
free(key_buff);
mbedtls_pk_free(&key);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
return true;
}
@ -105,6 +111,7 @@ void crypto_print_priv_key()
(unsigned int)-ret);
reboot();
}
free(key_buff);
printf("Show private key\n");
unsigned char *out = malloc(16000);
@ -119,5 +126,64 @@ void crypto_print_priv_key()
printf("%s", out);
free(out);
free(key_buff);
mbedtls_pk_free(&key);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
}
char *crypto_get_csr()
{
int ret;
unsigned char *key_buff = malloc(PRV_KEY_DER_MAX_BYTES);
size_t key_len = storage_get_priv_key(key_buff);
assert(key_len > 0);
mbedtls_pk_context key;
mbedtls_pk_init(&key);
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
seed_ctr_drbg_context(&entropy, &ctr_drbg);
printf("Parse private key (len = %d)\n", key_len);
if ((ret = mbedtls_pk_parse_key(&key, key_buff, key_len, NULL, 0, mbedtls_ctr_drbg_random, &ctr_drbg)) != 0)
{
mbedtls_printf(" failed\n ! mbedtls_pk_parse_key returned -0x%04x",
(unsigned int)-ret);
reboot();
}
free(key_buff);
// Create CSR
mbedtls_x509write_csr req;
mbedtls_x509write_csr_init(&req);
mbedtls_x509write_csr_set_md_alg(&req, MBEDTLS_MD_SHA256);
char subj[DEV_NAME_LEN + 4];
char *n = dev_name();
sprintf(subj, "CN=%s", n);
free(n);
if ((ret = mbedtls_x509write_csr_set_subject_name(&req, subj)) != 0)
{
mbedtls_printf(" failed\n ! mbedtls_x509write_csr_set_subject_name returned %d", ret);
reboot();
}
printf("Sign CSR with private key\n");
mbedtls_x509write_csr_set_key(&req, &key);
char *csr = malloc(4096);
if ((ret = mbedtls_x509write_csr_pem(&req, (u_char *)csr, 4096, mbedtls_ctr_drbg_random, &ctr_drbg)) < 0)
{
mbedtls_printf(" failed\n ! mbedtls_x509write_csr_pem returned %d", ret);
reboot();
}
mbedtls_x509write_csr_free(&req);
mbedtls_pk_free(&key);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_entropy_free(&entropy);
return csr;
}