2 * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
11 #include "internal/cryptlib.h"
12 #include <openssl/objects.h>
13 #include <openssl/x509.h>
14 #include <openssl/buffer.h>
15 #include "internal/x509_int.h"
18 * Limit to ensure we don't overflow: much greater than
19 * anything encountered in practice.
22 #define NAME_ONELINE_MAX (1024 * 1024)
24 char *X509_NAME_oneline(const X509_NAME *a, char *buf, int len)
26 const X509_NAME_ENTRY *ne;
28 int n, lold, l, l1, l2, num, j, type;
33 static const char hex[17] = "0123456789ABCDEF";
37 unsigned char ebcdic_buf[1024];
41 if ((b = BUF_MEM_new()) == NULL)
43 if (!BUF_MEM_grow(b, 200))
47 } else if (len == 0) {
55 strncpy(buf, "NO X509_NAME", len);
60 len--; /* space for '\0' */
62 for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
63 ne = sk_X509_NAME_ENTRY_value(a->entries, i);
64 n = OBJ_obj2nid(ne->object);
65 if ((n == NID_undef) || ((s = OBJ_nid2sn(n)) == NULL)) {
66 i2t_ASN1_OBJECT(tmp_buf, sizeof(tmp_buf), ne->object);
71 type = ne->value->type;
72 num = ne->value->length;
73 if (num > NAME_ONELINE_MAX) {
74 X509err(X509_F_X509_NAME_ONELINE, X509_R_NAME_TOO_LONG);
79 if (type == V_ASN1_GENERALSTRING ||
80 type == V_ASN1_VISIBLESTRING ||
81 type == V_ASN1_PRINTABLESTRING ||
82 type == V_ASN1_TELETEXSTRING ||
83 type == V_ASN1_IA5STRING) {
84 if (num > (int)sizeof(ebcdic_buf))
85 num = sizeof(ebcdic_buf);
86 ascii2ebcdic(ebcdic_buf, q, num);
91 if ((type == V_ASN1_GENERALSTRING) && ((num % 4) == 0)) {
92 gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 0;
93 for (j = 0; j < num; j++)
97 if (gs_doit[0] | gs_doit[1] | gs_doit[2])
98 gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1;
100 gs_doit[0] = gs_doit[1] = gs_doit[2] = 0;
104 gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1;
106 for (l2 = j = 0; j < num; j++) {
110 #ifndef CHARSET_EBCDIC
111 if ((q[j] < ' ') || (q[j] > '~'))
114 if ((os_toascii[q[j]] < os_toascii[' ']) ||
115 (os_toascii[q[j]] > os_toascii['~']))
121 l += 1 + l1 + 1 + l2;
122 if (l > NAME_ONELINE_MAX) {
123 X509err(X509_F_X509_NAME_ONELINE, X509_R_NAME_TOO_LONG);
127 if (!BUF_MEM_grow(b, l + 1))
129 p = &(b->data[lold]);
130 } else if (l > len) {
135 memcpy(p, s, (unsigned int)l1);
139 #ifndef CHARSET_EBCDIC /* q was assigned above already. */
143 for (j = 0; j < num; j++) {
146 #ifndef CHARSET_EBCDIC
148 if ((n < ' ') || (n > '~')) {
151 *(p++) = hex[(n >> 4) & 0x0f];
152 *(p++) = hex[n & 0x0f];
156 n = os_toascii[q[j]];
157 if ((n < os_toascii[' ']) || (n > os_toascii['~'])) {
160 *(p++) = hex[(n >> 4) & 0x0f];
161 *(p++) = hex[n & 0x0f];
177 X509err(X509_F_X509_NAME_ONELINE, ERR_R_MALLOC_FAILURE);