aboutsummaryrefslogtreecommitdiff
path: root/scripts/convert-from-csv-to-entitydb.py
blob: 411478150b072be9ebb3bce24948e98c78613963 (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
"""
Convert {parents,children,pubclients}.csv into new XML formats.

$Id$

Copyright (C) 2010  Internet Systems Consortium ("ISC")

Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
"""

import subprocess, re, os, getopt, sys, base64, urlparse
import rpki.sundial, rpki.myrpki, rpki.config

from lxml.etree import Element, SubElement, ElementTree

section_regexp  = re.compile("\s*\[\s*(.+?)\s*\]\s*$")
variable_regexp = re.compile("\s*([-a-zA-Z0-9_]+)(\s*=\s*)(.+?)\s*$")

cfg_file = "rpki.conf"
template_file = os.path.join(os.path.dirname(sys.argv[0]), "examples", "rpki.conf")
new_cfg_file = None
preserve_valid_until = False

opts, argv = getopt.getopt(sys.argv[1:], "c:hn:pt:?", ["config=", "new_config=", "preserve_valid_until", "template_config=", "help"])
for o, a in opts:
  if o in ("-h", "--help", "-?"):
    print __doc__
    sys.exit(0)
  elif o in ("-c", "--config"):
    cfg_file = a
  elif o in ("-n", "--new_config"):
    new_cfg_file = a
  elif o in ("-p", "--preserve_valid_until"):
    preserve_valid_until = True
  elif o in ("-t", "--template_config"):
    template_file = a
if argv:
  raise RuntimeError, "Unexpected arguments %r" % (argv,)
if os.path.samefile(cfg_file, template_file):
  raise RuntimeError, "Old config and template for new config can't be the same file"
if new_cfg_file is None:
  new_cfg_file = cfg_file + ".new"
if os.path.exists(new_cfg_file):
  raise RuntimeError, "%s already exists, NOT overwriting" % new_cfg_file

cfg = rpki.config.parser(cfg_file)

# These have no counterparts in new config file, just read them from old

repository_bpki_certificate = cfg.get(option = "repository_bpki_certificate", section = "myrpki")
repository_handle           = cfg.get(option = "repository_handle", section = "myrpki")
parents_csv                 = cfg.get(option = "parents_csv", section = "myrpki", default = "parents.csv")
children_csv                = cfg.get(option = "children_csv", section = "myrpki", default = "children.csv")
pubclients_csv              = cfg.get(option = "pubclients_csv", section = "myrpki", default = "pubclients.csv")
pubd_base                   = cfg.get(option = "pubd_base", section = "myirbe")

# Here we need to construct values for the new config file from the
# old one.  Basic model here is to look at whatever variables need to
# be set in the template (mostly just the [myrpki], I hope), pull
# necessary data from old config file any way we can.  Stuff that
# didn't make the jump from old config file to new we can just ignore,
# stuff that is automated via macro expansions in the new config file
# should be ok without modification.

r = {}

if cfg.has_section("myrpki"):
  for i in ("handle", "roa_csv", "prefix_csv", "asn_csv", "xml_filename"):
    r["myrpki", i] = cfg.get(section = "myrpki", option = i)
  r["myrpki", "bpki_resources_directory"] = cfg.get(option = "bpki_directory", section = "myrpki")

if cfg.has_section("myirbe"):
  r["myrpki", "bpki_servers_directory"] = cfg.get(option = "bpki_directory", section = "myirbe")
  r["myrpki", "run_rpkid"]              = True
  r["myrpki", "run_pubd"]               = cfg.getboolean(option = "want_pubd",  section = "myirbe", default = False)
  r["myrpki", "run_rootd"]              = cfg.getboolean(option = "want_rootd", section = "myirbe", default = False)
else:
  for i in ("run_rpkid", "run_pubd", "run_rootd"):
    r["myrpki", i] = False

if cfg.has_section("rpkid"):
  r["myrpki", "rpkid_server_host"] = cfg.get(option = "server-host", section = "rpkid")
  r["myrpki", "rpkid_server_port"] = cfg.get(option = "server-port", section = "rpkid")

if cfg.has_section("irdbd"):
  u = urlparse.urlparse(cfg.get(option = "https-url", section = "irdbd"))
  r["myrpki", "irdbd_server_host"] = u.hostname or "localhost"
  r["myrpki", "irdbd_server_port"] = u.port or 443

if cfg.has_section("pubd"):
  r["myrpki", "pubd_server_host"] = cfg.get(option = "server-host", section = "pubd")
  r["myrpki", "pubd_server_port"] = cfg.get(option = "server-port", section = "pubd")
  r["myrpki", "publication_base_directory"] = cfg.get(option = "publication-base", section = "pubd")

if cfg.has_section("rootd"):
  r["myrpki", "rootd_server_port"] = cfg.get(option = "server-port", section = "rootd")
  u = urlparse.urlparse(cfg.get(option = "rpki-base-uri", section = "rootd"))
  r["myrpki", "publication_rsync_server"] = u.netloc

for i in ("rpkid", "irdbd", "pubd"):
  if cfg.has_section(i):
    for j in ("sql-database", "sql-username", "sql-password"):
      r[i, j] = cfg.get(section = i, option = j)

f = open(new_cfg_file, "w")
f.write("# Automatically converted from %s using %s as a template.\n\n" % (cfg_file, template_file))
section = None
for line in open(template_file):
  m = section_regexp.match(line)
  if m:
    section = m.group(1)
  m = variable_regexp.match(line)
  if m:
    option, whitespace = m.group(1, 2)
  else:
    option = None
  if (section, option) in r:
    line = "%s%s%s\n" % (option, whitespace, r[section, option])
  f.write(line)
f.close()
print "Wrote", new_cfg_file

# Get all of these from the new config file; in theory we just set all
# of them, but we want to use values matching new config in any case.

newcfg = rpki.config.parser(new_cfg_file, "myrpki")

handle                      = newcfg.get("handle")
bpki_resources_directory    = newcfg.get("bpki_resources_directory")
bpki_servers_directory      = newcfg.get("bpki_servers_directory")
pubd_server_host            = newcfg.get("pubd_server_host")
pubd_server_port            = newcfg.get("pubd_server_port")
rpkid_server_host           = newcfg.get("rpkid_server_host")
rpkid_server_port           = newcfg.get("rpkid_server_port")
entitydb_dir                = newcfg.get("entitydb_dir", "entitydb")
  
bpki_resources_pemfile      = bpki_resources_directory + "/ca.cer"
bpki_servers_pemfile        = bpki_servers_directory + "/ca.cer"

def entitydb(*args):
  return os.path.join(entitydb_dir, *args)

# Now convert the .csv files.  It'd be nice to have XML validation
# enabled for this, so try to turn it on ourselves if the magic
# environment variable hasn't already been set.

rng_file = os.path.join(os.path.dirname(sys.argv[0]), "myrpki.rng")
if not os.getenv("MYRPKI_RNG") and os.path.exists(rng_file):
  os.putenv("MYRPKI_RNG", rng_file)

for d in map(entitydb, ("children", "parents", "repositories", "pubclients")):
  if not os.path.exists(d):
    os.makedirs(d)

one_year_from_now = str(rpki.sundial.now() + rpki.sundial.timedelta(days = 365))

if os.path.exists(children_csv):
  for child_handle, valid_until, child_resource_pemfile in rpki.myrpki.csv_reader(children_csv, columns = 3):
    try:

      e = Element("parent",
                  valid_until = valid_until if preserve_valid_until else one_year_from_now,
                  service_uri = "https://%s:%s/up-down/%s/%s" % (rpkid_server_host, rpkid_server_port, handle, child_handle),
                  child_handle = child_handle,
                  parent_handle = handle)
      rpki.myrpki.PEMElement(e, "bpki_resource_ta", bpki_resources_pemfile)
      rpki.myrpki.PEMElement(e, "bpki_server_ta",   bpki_servers_pemfile)
      rpki.myrpki.PEMElement(e, "bpki_child_ta",    child_resource_pemfile)
      rpki.myrpki.etree_write(e, entitydb("children", "%s.xml" % child_handle))

    except IOError:
      pass

if os.path.exists(parents_csv):
  for parent_handle, parent_service_uri, parent_cms_pemfile, parent_https_pemfile, parent_myhandle, parent_sia_base in rpki.myrpki.csv_reader(parents_csv, columns = 6):
    try:

      e = Element("parent",
                  valid_until = one_year_from_now,
                  service_uri = parent_service_uri,
                  child_handle = parent_myhandle,
                  parent_handle = parent_handle)
      rpki.myrpki.PEMElement(e, "bpki_resource_ta", parent_cms_pemfile)
      rpki.myrpki.PEMElement(e, "bpki_server_ta",   parent_https_pemfile)
      rpki.myrpki.PEMElement(e, "bpki_child_ta",    bpki_resources_pemfile)
      rpki.myrpki.etree_write(e, entitydb("parents", "%s.xml" % parent_handle))

      client_handle = "/".join(parent_sia_base.rstrip("/").split("/")[3:])
      assert client_handle.startswith(repository_handle)

      e = Element("repository",
                  parent_handle = parent_handle,
                  client_handle = client_handle,
                  service_uri = "%s/client/%s" % (pubd_base.rstrip("/"), client_handle),
                  sia_base = parent_sia_base,
                  type = "confirmed")
      rpki.myrpki.PEMElement(e, "bpki_server_ta", repository_bpki_certificate)
      rpki.myrpki.PEMElement(e, "bpki_client_ta", bpki_resources_pemfile)
      SubElement(e, "contact_info").text = "Automatically generated by convert-csv.py"
      rpki.myrpki.etree_write(e, entitydb("repositories", "%s.xml" % parent_handle))

    except IOError:
      pass

if os.path.exists(pubclients_csv):
  for client_handle, client_resource_pemfile, client_sia_base in rpki.myrpki.csv_reader(pubclients_csv, columns = 3):
    try:

      parent_handle = client_handle.split("/")[-2] if "/" in client_handle else handle

      e = Element("repository",
                  parent_handle = parent_handle,
                  client_handle = client_handle,
                  service_uri = "https://%s:%s/client/%s" % (pubd_server_host, pubd_server_port, client_handle),
                  sia_base = client_sia_base,
                  type = "confirmed")
      rpki.myrpki.PEMElement(e, "bpki_server_ta", bpki_servers_pemfile)
      rpki.myrpki.PEMElement(e, "bpki_client_ta", client_resource_pemfile)
      SubElement(e, "contact_info").text = "Automatically generated by convert-csv.py"
      rpki.myrpki.etree_write(e, entitydb("pubclients", "%s.xml" % client_handle.replace("/", ".")))

    except IOError:
      pass
an class="p">) return NULL; if(!(bntmp = ASN1_INTEGER_to_BN(a, NULL)) || !(strtmp = BN_bn2dec(bntmp)) ) X509V3err(X509V3_F_I2S_ASN1_INTEGER,ERR_R_MALLOC_FAILURE); BN_free(bntmp); return strtmp; } ASN1_INTEGER *s2i_ASN1_INTEGER(X509V3_EXT_METHOD *method, char *value) { BIGNUM *bn = NULL; ASN1_INTEGER *aint; int isneg, ishex; int ret; if (!value) { X509V3err(X509V3_F_S2I_ASN1_INTEGER,X509V3_R_INVALID_NULL_VALUE); return 0; } bn = BN_new(); if (value[0] == '-') { value++; isneg = 1; } else isneg = 0; if (value[0] == '0' && ((value[1] == 'x') || (value[1] == 'X'))) { value += 2; ishex = 1; } else ishex = 0; if (ishex) ret = BN_hex2bn(&bn, value); else ret = BN_dec2bn(&bn, value); if (!ret || value[ret]) { BN_free(bn); X509V3err(X509V3_F_S2I_ASN1_INTEGER,X509V3_R_BN_DEC2BN_ERROR); return 0; } if (isneg && BN_is_zero(bn)) isneg = 0; aint = BN_to_ASN1_INTEGER(bn, NULL); BN_free(bn); if (!aint) { X509V3err(X509V3_F_S2I_ASN1_INTEGER,X509V3_R_BN_TO_ASN1_INTEGER_ERROR); return 0; } if (isneg) aint->type |= V_ASN1_NEG; return aint; } int X509V3_add_value_int(const char *name, ASN1_INTEGER *aint, STACK_OF(CONF_VALUE) **extlist) { char *strtmp; int ret; if(!aint) return 1; if(!(strtmp = i2s_ASN1_INTEGER(NULL, aint))) return 0; ret = X509V3_add_value(name, strtmp, extlist); OPENSSL_free(strtmp); return ret; } int X509V3_get_value_bool(CONF_VALUE *value, int *asn1_bool) { char *btmp; if(!(btmp = value->value)) goto err; if(!strcmp(btmp, "TRUE") || !strcmp(btmp, "true") || !strcmp(btmp, "Y") || !strcmp(btmp, "y") || !strcmp(btmp, "YES") || !strcmp(btmp, "yes")) { *asn1_bool = 0xff; return 1; } else if(!strcmp(btmp, "FALSE") || !strcmp(btmp, "false") || !strcmp(btmp, "N") || !strcmp(btmp, "n") || !strcmp(btmp, "NO") || !strcmp(btmp, "no")) { *asn1_bool = 0; return 1; } err: X509V3err(X509V3_F_X509V3_GET_VALUE_BOOL,X509V3_R_INVALID_BOOLEAN_STRING); X509V3_conf_err(value); return 0; } int X509V3_get_value_int(CONF_VALUE *value, ASN1_INTEGER **aint) { ASN1_INTEGER *itmp; if(!(itmp = s2i_ASN1_INTEGER(NULL, value->value))) { X509V3_conf_err(value); return 0; } *aint = itmp; return 1; } #define HDR_NAME 1 #define HDR_VALUE 2 /*#define DEBUG*/ STACK_OF(CONF_VALUE) *X509V3_parse_list(const char *line) { char *p, *q, c; char *ntmp, *vtmp; STACK_OF(CONF_VALUE) *values = NULL; char *linebuf; int state; /* We are going to modify the line so copy it first */ linebuf = BUF_strdup(line); state = HDR_NAME; ntmp = NULL; /* Go through all characters */ for(p = linebuf, q = linebuf; (c = *p) && (c!='\r') && (c!='\n'); p++) { switch(state) { case HDR_NAME: if(c == ':') { state = HDR_VALUE; *p = 0; ntmp = strip_spaces(q); if(!ntmp) { X509V3err(X509V3_F_X509V3_PARSE_LIST, X509V3_R_INVALID_NULL_NAME); goto err; } q = p + 1; } else if(c == ',') { *p = 0; ntmp = strip_spaces(q); q = p + 1; #if 0 printf("%s\n", ntmp); #endif if(!ntmp) { X509V3err(X509V3_F_X509V3_PARSE_LIST, X509V3_R_INVALID_NULL_NAME); goto err; } X509V3_add_value(ntmp, NULL, &values); } break ; case HDR_VALUE: if(c == ',') { state = HDR_NAME; *p = 0; vtmp = strip_spaces(q); #if 0 printf("%s\n", ntmp); #endif if(!vtmp) { X509V3err(X509V3_F_X509V3_PARSE_LIST, X509V3_R_INVALID_NULL_VALUE); goto err; } X509V3_add_value(ntmp, vtmp, &values); ntmp = NULL; q = p + 1; } } } if(state == HDR_VALUE) { vtmp = strip_spaces(q); #if 0 printf("%s=%s\n", ntmp, vtmp); #endif if(!vtmp) { X509V3err(X509V3_F_X509V3_PARSE_LIST, X509V3_R_INVALID_NULL_VALUE); goto err; } X509V3_add_value(ntmp, vtmp, &values); } else { ntmp = strip_spaces(q); #if 0 printf("%s\n", ntmp); #endif if(!ntmp) { X509V3err(X509V3_F_X509V3_PARSE_LIST, X509V3_R_INVALID_NULL_NAME); goto err; } X509V3_add_value(ntmp, NULL, &values); } OPENSSL_free(linebuf); return values; err: OPENSSL_free(linebuf); sk_CONF_VALUE_pop_free(values, X509V3_conf_free); return NULL; } /* Delete leading and trailing spaces from a string */ static char *strip_spaces(char *name) { char *p, *q; /* Skip over leading spaces */ p = name; while(*p && isspace((unsigned char)*p)) p++; if(!*p) return NULL; q = p + strlen(p) - 1; while((q != p) && isspace((unsigned char)*q)) q--; if(p != q) q[1] = 0; if(!*p) return NULL; return p; } /* hex string utilities */ /* Given a buffer of length 'len' return a OPENSSL_malloc'ed string with its * hex representation * @@@ (Contents of buffer are always kept in ASCII, also on EBCDIC machines) */ char *hex_to_string(unsigned char *buffer, long len) { char *tmp, *q; unsigned char *p; int i; static char hexdig[] = "0123456789ABCDEF"; if(!buffer || !len) return NULL; if(!(tmp = OPENSSL_malloc(len * 3 + 1))) { X509V3err(X509V3_F_HEX_TO_STRING,ERR_R_MALLOC_FAILURE); return NULL; } q = tmp; for(i = 0, p = buffer; i < len; i++,p++) { *q++ = hexdig[(*p >> 4) & 0xf]; *q++ = hexdig[*p & 0xf]; *q++ = ':'; } q[-1] = 0; #ifdef CHARSET_EBCDIC ebcdic2ascii(tmp, tmp, q - tmp - 1); #endif return tmp; } /* Give a string of hex digits convert to * a buffer */ unsigned char *string_to_hex(char *str, long *len) { unsigned char *hexbuf, *q; unsigned char ch, cl, *p; if(!str) { X509V3err(X509V3_F_STRING_TO_HEX,X509V3_R_INVALID_NULL_ARGUMENT); return NULL; } if(!(hexbuf = OPENSSL_malloc(strlen(str) >> 1))) goto err; for(p = (unsigned char *)str, q = hexbuf; *p;) { ch = *p++; #ifdef CHARSET_EBCDIC ch = os_toebcdic[ch]; #endif if(ch == ':') continue; cl = *p++; #ifdef CHARSET_EBCDIC cl = os_toebcdic[cl]; #endif if(!cl) { X509V3err(X509V3_F_STRING_TO_HEX,X509V3_R_ODD_NUMBER_OF_DIGITS); OPENSSL_free(hexbuf); return NULL; } if(isupper(ch)) ch = tolower(ch); if(isupper(cl)) cl = tolower(cl); if((ch >= '0') && (ch <= '9')) ch -= '0'; else if ((ch >= 'a') && (ch <= 'f')) ch -= 'a' - 10; else goto badhex; if((cl >= '0') && (cl <= '9')) cl -= '0'; else if ((cl >= 'a') && (cl <= 'f')) cl -= 'a' - 10; else goto badhex; *q++ = (ch << 4) | cl; } if(len) *len = q - hexbuf; return hexbuf; err: if(hexbuf) OPENSSL_free(hexbuf); X509V3err(X509V3_F_STRING_TO_HEX,ERR_R_MALLOC_FAILURE); return NULL; badhex: OPENSSL_free(hexbuf); X509V3err(X509V3_F_STRING_TO_HEX,X509V3_R_ILLEGAL_HEX_DIGIT); return NULL; } /* V2I name comparison function: returns zero if 'name' matches * cmp or cmp.* */ int name_cmp(const char *name, const char *cmp) { int len, ret; char c; len = strlen(cmp); if((ret = strncmp(name, cmp, len))) return ret; c = name[len]; if(!c || (c=='.')) return 0; return 1; } static int sk_strcmp(const char * const *a, const char * const *b) { return strcmp(*a, *b); } STACK *X509_get1_email(X509 *x) { GENERAL_NAMES *gens; STACK *ret; gens = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL); ret = get_email(X509_get_subject_name(x), gens); sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free); return ret; } STACK *X509_REQ_get1_email(X509_REQ *x) { GENERAL_NAMES *gens; STACK_OF(X509_EXTENSION) *exts; STACK *ret; exts = X509_REQ_get_extensions(x); gens = X509V3_get_d2i(exts, NID_subject_alt_name, NULL, NULL); ret = get_email(X509_REQ_get_subject_name(x), gens); sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free); sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); return ret; } static STACK *get_email(X509_NAME *name, GENERAL_NAMES *gens) { STACK *ret = NULL; X509_NAME_ENTRY *ne; ASN1_IA5STRING *email; GENERAL_NAME *gen; int i; /* Now add any email address(es) to STACK */ i = -1; /* First supplied X509_NAME */ while((i = X509_NAME_get_index_by_NID(name, NID_pkcs9_emailAddress, i)) >= 0) { ne = X509_NAME_get_entry(name, i); email = X509_NAME_ENTRY_get_data(ne); if(!append_ia5(&ret, email)) return NULL; } for(i = 0; i < sk_GENERAL_NAME_num(gens); i++) { gen = sk_GENERAL_NAME_value(gens, i); if(gen->type != GEN_EMAIL) continue; if(!append_ia5(&ret, gen->d.ia5)) return NULL; } return ret; } static void str_free(void *str) { OPENSSL_free(str); } static int append_ia5(STACK **sk, ASN1_IA5STRING *email) { char *emtmp; /* First some sanity checks */ if(email->type != V_ASN1_IA5STRING) return 1; if(!email->data || !email->length) return 1; if(!*sk) *sk = sk_new(sk_strcmp); if(!*sk) return 0; /* Don't add duplicates */ if(sk_find(*sk, (char *)email->data) != -1) return 1; emtmp = BUF_strdup((char *)email->data); if(!emtmp || !sk_push(*sk, emtmp)) { X509_email_free(*sk); *sk = NULL; return 0; } return 1; } void X509_email_free(STACK *sk) { sk_pop_free(sk, str_free); } /* Convert IP addresses both IPv4 and IPv6 into an * OCTET STRING compatible with RFC3280. */ ASN1_OCTET_STRING *a2i_IPADDRESS(const char *ipasc) { unsigned char ipout[16]; ASN1_OCTET_STRING *ret; int iplen; /* If string contains a ':' assume IPv6 */ iplen = a2i_ipadd(ipout, ipasc); if (!iplen) return NULL; ret = ASN1_OCTET_STRING_new(); if (!ret) return NULL; if (!ASN1_OCTET_STRING_set(ret, ipout, iplen)) { ASN1_OCTET_STRING_free(ret); return NULL; } return ret; } ASN1_OCTET_STRING *a2i_IPADDRESS_NC(const char *ipasc) { ASN1_OCTET_STRING *ret = NULL; unsigned char ipout[32]; char *iptmp = NULL, *p; int iplen1, iplen2; p = strchr(ipasc,'/'); if (!p) return NULL; iptmp = BUF_strdup(ipasc); if (!iptmp) return NULL; p = iptmp + (p - ipasc); *p++ = 0; iplen1 = a2i_ipadd(ipout, iptmp); if (!iplen1) goto err; iplen2 = a2i_ipadd(ipout + iplen1, p); OPENSSL_free(iptmp); iptmp = NULL; if (!iplen2 || (iplen1 != iplen2)) goto err; ret = ASN1_OCTET_STRING_new(); if (!ret) goto err; if (!ASN1_OCTET_STRING_set(ret, ipout, iplen1 + iplen2)) goto err; return ret; err: if (iptmp) OPENSSL_free(iptmp); if (ret) ASN1_OCTET_STRING_free(ret); return NULL; } int a2i_ipadd(unsigned char *ipout, const char *ipasc) { /* If string contains a ':' assume IPv6 */ if (strchr(ipasc, ':')) { if (!ipv6_from_asc(ipout, ipasc)) return 0; return 16; } else { if (!ipv4_from_asc(ipout, ipasc)) return 0; return 4; } } static int ipv4_from_asc(unsigned char *v4, const char *in) { int a0, a1, a2, a3; if (sscanf(in, "%d.%d.%d.%d", &a0, &a1, &a2, &a3) != 4) return 0; if ((a0 < 0) || (a0 > 255) || (a1 < 0) || (a1 > 255) || (a2 < 0) || (a2 > 255) || (a3 < 0) || (a3 > 255)) return 0; v4[0] = a0; v4[1] = a1; v4[2] = a2; v4[3] = a3; return 1; } typedef struct { /* Temporary store for IPV6 output */ unsigned char tmp[16]; /* Total number of bytes in tmp */ int total; /* The position of a zero (corresponding to '::') */ int zero_pos; /* Number of zeroes */ int zero_cnt; } IPV6_STAT; static int ipv6_from_asc(unsigned char *v6, const char *in) { IPV6_STAT v6stat; v6stat.total = 0; v6stat.zero_pos = -1; v6stat.zero_cnt = 0; /* Treat the IPv6 representation as a list of values * separated by ':'. The presence of a '::' will parse * as one, two or three zero length elements. */ if (!CONF_parse_list(in, ':', 0, ipv6_cb, &v6stat)) return 0; /* Now for some sanity checks */ if (v6stat.zero_pos == -1) { /* If no '::' must have exactly 16 bytes */ if (v6stat.total != 16) return 0; } else { /* If '::' must have less than 16 bytes */ if (v6stat.total == 16) return 0; /* More than three zeroes is an error */ if (v6stat.zero_cnt > 3) return 0; /* Can only have three zeroes if nothing else present */ else if (v6stat.zero_cnt == 3) { if (v6stat.total > 0) return 0; } /* Can only have two zeroes if at start or end */ else if (v6stat.zero_cnt == 2) { if ((v6stat.zero_pos != 0) && (v6stat.zero_pos != v6stat.total)) return 0; } else /* Can only have one zero if *not* start or end */ { if ((v6stat.zero_pos == 0) || (v6stat.zero_pos == v6stat.total)) return 0; } } /* Format result */ /* Copy initial part */ if (v6stat.zero_pos > 0) memcpy(v6, v6stat.tmp, v6stat.zero_pos); /* Zero middle */ if (v6stat.total != 16) memset(v6 + v6stat.zero_pos, 0, 16 - v6stat.total); /* Copy final part */ if (v6stat.total != v6stat.zero_pos) memcpy(v6 + v6stat.zero_pos + 16 - v6stat.total, v6stat.tmp + v6stat.zero_pos, v6stat.total - v6stat.zero_pos); return 1; } static int ipv6_cb(const char *elem, int len, void *usr) { IPV6_STAT *s = usr; /* Error if 16 bytes written */ if (s->total == 16) return 0; if (len == 0) { /* Zero length element, corresponds to '::' */ if (s->zero_pos == -1) s->zero_pos = s->total; /* If we've already got a :: its an error */ else if (s->zero_pos != s->total) return 0; s->zero_cnt++; } else { /* If more than 4 characters could be final a.b.c.d form */ if (len > 4) { /* Need at least 4 bytes left */ if (s->total > 12) return 0; /* Must be end of string */ if (elem[len]) return 0; if (!ipv4_from_asc(s->tmp + s->total, elem)) return 0; s->total += 4; } else { if (!ipv6_hex(s->tmp + s->total, elem, len)) return 0; s->total += 2; } } return 1; } /* Convert a string of up to 4 hex digits into the corresponding * IPv6 form. */ static int ipv6_hex(unsigned char *out, const char *in, int inlen) { unsigned char c; unsigned int num = 0; if (inlen > 4) return 0; while(inlen--) { c = *in++; num <<= 4; if ((c >= '0') && (c <= '9')) num |= c - '0'; else if ((c >= 'A') && (c <= 'F')) num |= c - 'A' + 10; else if ((c >= 'a') && (c <= 'f')) num |= c - 'a' + 10; else return 0; } out[0] = num >> 8; out[1] = num & 0xff; return 1; } int X509V3_NAME_from_section(X509_NAME *nm, STACK_OF(CONF_VALUE)*dn_sk, unsigned long chtype) { CONF_VALUE *v; int i, mval; char *p, *type; if (!nm) return 0; for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) { v=sk_CONF_VALUE_value(dn_sk,i); type=v->name; /* Skip past any leading X. X: X, etc to allow for * multiple instances */ for(p = type; *p ; p++) #ifndef CHARSET_EBCDIC if ((*p == ':') || (*p == ',') || (*p == '.')) #else if ((*p == os_toascii[':']) || (*p == os_toascii[',']) || (*p == os_toascii['.'])) #endif { p++; if(*p) type = p; break; } #ifndef CHARSET_EBCDIC if (*type == '+') #else if (*type == os_toascii['+']) #endif { mval = -1; type++; } else mval = 0; if (!X509_NAME_add_entry_by_txt(nm,type, chtype, (unsigned char *) v->value,-1,-1,mval)) return 0; } return 1; }