Use better IP parsing in x509 programs
Remove unnecessary duplicated code.
Signed-off-by: Andrzej Kurek <andrzej.kurek@arm.com>
diff --git a/programs/x509/cert_req.c b/programs/x509/cert_req.c
index fe060f3..531871b 100644
--- a/programs/x509/cert_req.c
+++ b/programs/x509/cert_req.c
@@ -116,18 +116,6 @@
mbedtls_md_type_t md_alg; /* Hash algorithm used for signature. */
} opt;
-static void ip_string_to_bytes(const char *str, uint8_t *bytes, int maxBytes)
-{
- for (int i = 0; i < maxBytes; i++) {
- bytes[i] = (uint8_t) strtoul(str, NULL, 10);
- str = strchr(str, '.');
- if (str == NULL || *str == '\0') {
- break;
- }
- str++;
- }
-}
-
int write_certificate_request(mbedtls_x509write_csr *req, const char *output_file,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng)
@@ -165,12 +153,13 @@
mbedtls_pk_context key;
char buf[1024];
int i;
- char *p, *q, *r, *r2;
+ char *p, *q, *r, *subtype_value;
mbedtls_x509write_csr req;
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
const char *pers = "csr example app";
mbedtls_x509_san_list *cur, *prev;
+ uint8_t ip[4] = { 0 };
/*
* Set to sane values
@@ -231,8 +220,6 @@
prev = NULL;
while (q != NULL) {
- uint8_t ip[4] = { 0 };
-
if ((r = strchr(q, ';')) != NULL) {
*r++ = '\0';
}
@@ -245,8 +232,8 @@
cur->next = NULL;
- if ((r2 = strchr(q, ':')) != NULL) {
- *r2++ = '\0';
+ if ((subtype_value = strchr(q, ':')) != NULL) {
+ *subtype_value++ = '\0';
}
if (strcmp(q, "URI") == 0) {
@@ -254,8 +241,12 @@
} else if (strcmp(q, "DNS") == 0) {
cur->node.type = MBEDTLS_X509_SAN_DNS_NAME;
} else if (strcmp(q, "IP") == 0) {
+ size_t ip_len = 0;
cur->node.type = MBEDTLS_X509_SAN_IP_ADDRESS;
- ip_string_to_bytes(r2, ip, 4);
+ ip_len = mbedtls_x509_crt_parse_cn_inet_pton(subtype_value, ip);
+ if (ip_len == 0) {
+ goto exit;
+ }
} else {
mbedtls_free(cur);
goto usage;
@@ -265,7 +256,7 @@
cur->node.san.unstructured_name.p = (unsigned char *) ip;
cur->node.san.unstructured_name.len = sizeof(ip);
} else {
- q = r2;
+ q = subtype_value;
cur->node.san.unstructured_name.p = (unsigned char *) q;
cur->node.san.unstructured_name.len = strlen(q);
}