certdata2pem.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. #!/usr/bin/python
  2. # vim:set et sw=4:
  3. #
  4. # certdata2pem.py - splits certdata.txt into multiple files
  5. #
  6. # Copyright (C) 2009 Philipp Kern <pkern@debian.org>
  7. # Copyright (C) 2013 Kai Engert <kaie@redhat.com>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this program; if not, write to the Free Software
  21. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301,
  22. # USA.
  23. import base64
  24. import os.path
  25. import re
  26. import sys
  27. import textwrap
  28. import urllib.request, urllib.parse, urllib.error
  29. import subprocess
  30. objects = []
  31. def printable_serial(obj):
  32. return ".".join([str(x) for x in obj['CKA_SERIAL_NUMBER']])
  33. # Dirty file parser.
  34. in_data, in_multiline, in_obj = False, False, False
  35. field, ftype, value, binval, obj = None, None, None, bytearray(), dict()
  36. for line in open('certdata.txt', 'r'):
  37. # Ignore the file header.
  38. if not in_data:
  39. if line.startswith('BEGINDATA'):
  40. in_data = True
  41. continue
  42. # Ignore comment lines.
  43. if line.startswith('#'):
  44. continue
  45. # Empty lines are significant if we are inside an object.
  46. if in_obj and len(line.strip()) == 0:
  47. objects.append(obj)
  48. obj = dict()
  49. in_obj = False
  50. continue
  51. if len(line.strip()) == 0:
  52. continue
  53. if in_multiline:
  54. if not line.startswith('END'):
  55. if ftype == 'MULTILINE_OCTAL':
  56. line = line.strip()
  57. for i in re.finditer(r'\\([0-3][0-7][0-7])', line):
  58. integ = int(i.group(1), 8)
  59. binval.extend((integ).to_bytes(1, sys.byteorder))
  60. obj[field] = binval
  61. else:
  62. value += line
  63. obj[field] = value
  64. continue
  65. in_multiline = False
  66. continue
  67. if line.startswith('CKA_CLASS'):
  68. in_obj = True
  69. line_parts = line.strip().split(' ', 2)
  70. if len(line_parts) > 2:
  71. field, ftype = line_parts[0:2]
  72. value = ' '.join(line_parts[2:])
  73. elif len(line_parts) == 2:
  74. field, ftype = line_parts
  75. value = None
  76. else:
  77. raise NotImplementedError('line_parts < 2 not supported.\n' + line)
  78. if ftype == 'MULTILINE_OCTAL':
  79. in_multiline = True
  80. value = ""
  81. binval = bytearray()
  82. continue
  83. obj[field] = value
  84. if len(list(obj.items())) > 0:
  85. objects.append(obj)
  86. # Build up trust database.
  87. trustmap = dict()
  88. for obj in objects:
  89. if obj['CKA_CLASS'] != 'CKO_NSS_TRUST':
  90. continue
  91. key = obj['CKA_LABEL'] + printable_serial(obj)
  92. trustmap[key] = obj
  93. print(" added trust", key)
  94. # Build up cert database.
  95. certmap = dict()
  96. for obj in objects:
  97. if obj['CKA_CLASS'] != 'CKO_CERTIFICATE':
  98. continue
  99. key = obj['CKA_LABEL'] + printable_serial(obj)
  100. certmap[key] = obj
  101. print(" added cert", key)
  102. def obj_to_filename(obj):
  103. label = obj['CKA_LABEL'][1:-1]
  104. label = label.replace('/', '_')\
  105. .replace(' ', '_')\
  106. .replace('(', '=')\
  107. .replace(')', '=')\
  108. .replace(',', '_')
  109. labelbytes = bytearray()
  110. i = 0
  111. imax = len(label)
  112. while i < imax:
  113. if i < imax-3 and label[i] == '\\' and label[i+1] == 'x':
  114. labelbytes.extend(bytes.fromhex(label[i+2:i+4]))
  115. i += 4
  116. continue
  117. labelbytes.extend(str.encode(label[i]))
  118. i = i+1
  119. continue
  120. label = labelbytes.decode('utf-8')
  121. serial = printable_serial(obj)
  122. return label + ":" + serial
  123. def write_cert_ext_to_file(f, oid, value, public_key):
  124. f.write("[p11-kit-object-v1]\n")
  125. f.write("label: ");
  126. f.write(tobj['CKA_LABEL'])
  127. f.write("\n")
  128. f.write("class: x-certificate-extension\n");
  129. f.write("object-id: " + oid + "\n")
  130. f.write("value: \"" + value + "\"\n")
  131. f.write("modifiable: false\n");
  132. f.write(public_key)
  133. trust_types = {
  134. "CKA_TRUST_DIGITAL_SIGNATURE": "digital-signature",
  135. "CKA_TRUST_NON_REPUDIATION": "non-repudiation",
  136. "CKA_TRUST_KEY_ENCIPHERMENT": "key-encipherment",
  137. "CKA_TRUST_DATA_ENCIPHERMENT": "data-encipherment",
  138. "CKA_TRUST_KEY_AGREEMENT": "key-agreement",
  139. "CKA_TRUST_KEY_CERT_SIGN": "cert-sign",
  140. "CKA_TRUST_CRL_SIGN": "crl-sign",
  141. "CKA_TRUST_SERVER_AUTH": "server-auth",
  142. "CKA_TRUST_CLIENT_AUTH": "client-auth",
  143. "CKA_TRUST_CODE_SIGNING": "code-signing",
  144. "CKA_TRUST_EMAIL_PROTECTION": "email-protection",
  145. "CKA_TRUST_IPSEC_END_SYSTEM": "ipsec-end-system",
  146. "CKA_TRUST_IPSEC_TUNNEL": "ipsec-tunnel",
  147. "CKA_TRUST_IPSEC_USER": "ipsec-user",
  148. "CKA_TRUST_TIME_STAMPING": "time-stamping",
  149. "CKA_TRUST_STEP_UP_APPROVED": "step-up-approved",
  150. }
  151. legacy_trust_types = {
  152. "LEGACY_CKA_TRUST_SERVER_AUTH": "server-auth",
  153. "LEGACY_CKA_TRUST_CODE_SIGNING": "code-signing",
  154. "LEGACY_CKA_TRUST_EMAIL_PROTECTION": "email-protection",
  155. }
  156. legacy_to_real_trust_types = {
  157. "LEGACY_CKA_TRUST_SERVER_AUTH": "CKA_TRUST_SERVER_AUTH",
  158. "LEGACY_CKA_TRUST_CODE_SIGNING": "CKA_TRUST_CODE_SIGNING",
  159. "LEGACY_CKA_TRUST_EMAIL_PROTECTION": "CKA_TRUST_EMAIL_PROTECTION",
  160. }
  161. openssl_trust = {
  162. "CKA_TRUST_SERVER_AUTH": "serverAuth",
  163. "CKA_TRUST_CLIENT_AUTH": "clientAuth",
  164. "CKA_TRUST_CODE_SIGNING": "codeSigning",
  165. "CKA_TRUST_EMAIL_PROTECTION": "emailProtection",
  166. }
  167. cert_distrust_types = {
  168. "CKA_NSS_SERVER_DISTRUST_AFTER": "nss-server-distrust-after",
  169. "CKA_NSS_EMAIL_DISTRUST_AFTER": "nss-email-distrust-after",
  170. }
  171. for tobj in objects:
  172. if tobj['CKA_CLASS'] == 'CKO_NSS_TRUST':
  173. key = tobj['CKA_LABEL'] + printable_serial(tobj)
  174. print("producing trust for " + key)
  175. trustbits = []
  176. distrustbits = []
  177. openssl_trustflags = []
  178. openssl_distrustflags = []
  179. legacy_trustbits = []
  180. legacy_openssl_trustflags = []
  181. for t in list(trust_types.keys()):
  182. if t in tobj and tobj[t] == 'CKT_NSS_TRUSTED_DELEGATOR':
  183. trustbits.append(t)
  184. if t in openssl_trust:
  185. openssl_trustflags.append(openssl_trust[t])
  186. if t in tobj and tobj[t] == 'CKT_NSS_NOT_TRUSTED':
  187. distrustbits.append(t)
  188. if t in openssl_trust:
  189. openssl_distrustflags.append(openssl_trust[t])
  190. for t in list(legacy_trust_types.keys()):
  191. if t in tobj and tobj[t] == 'CKT_NSS_TRUSTED_DELEGATOR':
  192. real_t = legacy_to_real_trust_types[t]
  193. legacy_trustbits.append(real_t)
  194. if real_t in openssl_trust:
  195. legacy_openssl_trustflags.append(openssl_trust[real_t])
  196. if t in tobj and tobj[t] == 'CKT_NSS_NOT_TRUSTED':
  197. raise NotImplementedError('legacy distrust not supported.\n' + line)
  198. fname = obj_to_filename(tobj)
  199. try:
  200. obj = certmap[key]
  201. except:
  202. obj = None
  203. # optional debug code, that dumps the parsed input to files
  204. #fulldump = "dump-" + fname
  205. #dumpf = open(fulldump, 'w')
  206. #dumpf.write(str(obj));
  207. #dumpf.write(str(tobj));
  208. #dumpf.close();
  209. is_legacy = 0
  210. if 'LEGACY_CKA_TRUST_SERVER_AUTH' in tobj or 'LEGACY_CKA_TRUST_EMAIL_PROTECTION' in tobj or 'LEGACY_CKA_TRUST_CODE_SIGNING' in tobj:
  211. is_legacy = 1
  212. if obj == None:
  213. raise NotImplementedError('found legacy trust without certificate.\n' + line)
  214. legacy_fname = "legacy-default/" + fname + ".crt"
  215. f = open(legacy_fname, 'w')
  216. f.write("# alias=%s\n"%tobj['CKA_LABEL'])
  217. f.write("# trust=" + " ".join(legacy_trustbits) + "\n")
  218. if legacy_openssl_trustflags:
  219. f.write("# openssl-trust=" + " ".join(legacy_openssl_trustflags) + "\n")
  220. f.write("-----BEGIN CERTIFICATE-----\n")
  221. temp_encoded_b64 = base64.b64encode(obj['CKA_VALUE'])
  222. temp_wrapped = textwrap.wrap(temp_encoded_b64.decode(), 64)
  223. f.write("\n".join(temp_wrapped))
  224. f.write("\n-----END CERTIFICATE-----\n")
  225. f.close()
  226. if 'CKA_TRUST_SERVER_AUTH' in tobj or 'CKA_TRUST_EMAIL_PROTECTION' in tobj or 'CKA_TRUST_CODE_SIGNING' in tobj:
  227. legacy_fname = "legacy-disable/" + fname + ".crt"
  228. f = open(legacy_fname, 'w')
  229. f.write("# alias=%s\n"%tobj['CKA_LABEL'])
  230. f.write("# trust=" + " ".join(trustbits) + "\n")
  231. if openssl_trustflags:
  232. f.write("# openssl-trust=" + " ".join(openssl_trustflags) + "\n")
  233. f.write("-----BEGIN CERTIFICATE-----\n")
  234. f.write("\n".join(textwrap.wrap(base64.b64encode(obj['CKA_VALUE']), 64)))
  235. f.write("\n-----END CERTIFICATE-----\n")
  236. f.close()
  237. # don't produce p11-kit output for legacy certificates
  238. continue
  239. pk = ''
  240. cert_comment = ''
  241. if obj != None:
  242. # must extract the public key from the cert, let's use openssl
  243. cert_fname = "cert-" + fname
  244. fc = open(cert_fname, 'w')
  245. fc.write("-----BEGIN CERTIFICATE-----\n")
  246. temp_encoded_b64 = base64.b64encode(obj['CKA_VALUE'])
  247. temp_wrapped = textwrap.wrap(temp_encoded_b64.decode(), 64)
  248. fc.write("\n".join(temp_wrapped))
  249. fc.write("\n-----END CERTIFICATE-----\n")
  250. fc.close();
  251. pk_fname = "pubkey-" + fname
  252. fpkout = open(pk_fname, "w")
  253. dump_pk_command = ["openssl", "x509", "-in", cert_fname, "-noout", "-pubkey"]
  254. subprocess.call(dump_pk_command, stdout=fpkout)
  255. fpkout.close()
  256. with open (pk_fname, "r") as myfile:
  257. pk=myfile.read()
  258. # obtain certificate information suitable as a comment
  259. comment_fname = "comment-" + fname
  260. fcout = open(comment_fname, "w")
  261. comment_command = ["openssl", "x509", "-in", cert_fname, "-noout", "-text"]
  262. subprocess.call(comment_command, stdout=fcout)
  263. fcout.close()
  264. sed_command = ["sed", "--in-place", "s/^/#/", comment_fname]
  265. subprocess.call(sed_command)
  266. with open (comment_fname, "r", errors = 'replace') as myfile:
  267. cert_comment=myfile.read()
  268. fname += ".tmp-p11-kit"
  269. f = open(fname, 'w')
  270. if obj != None:
  271. is_distrusted = False
  272. has_server_trust = False
  273. has_email_trust = False
  274. has_code_trust = False
  275. if 'CKA_TRUST_SERVER_AUTH' in tobj:
  276. if tobj['CKA_TRUST_SERVER_AUTH'] == 'CKT_NSS_NOT_TRUSTED':
  277. is_distrusted = True
  278. elif tobj['CKA_TRUST_SERVER_AUTH'] == 'CKT_NSS_TRUSTED_DELEGATOR':
  279. has_server_trust = True
  280. if 'CKA_TRUST_EMAIL_PROTECTION' in tobj:
  281. if tobj['CKA_TRUST_EMAIL_PROTECTION'] == 'CKT_NSS_NOT_TRUSTED':
  282. is_distrusted = True
  283. elif tobj['CKA_TRUST_EMAIL_PROTECTION'] == 'CKT_NSS_TRUSTED_DELEGATOR':
  284. has_email_trust = True
  285. if 'CKA_TRUST_CODE_SIGNING' in tobj:
  286. if tobj['CKA_TRUST_CODE_SIGNING'] == 'CKT_NSS_NOT_TRUSTED':
  287. is_distrusted = True
  288. elif tobj['CKA_TRUST_CODE_SIGNING'] == 'CKT_NSS_TRUSTED_DELEGATOR':
  289. has_code_trust = True
  290. if is_distrusted:
  291. trust_ext_oid = "1.3.6.1.4.1.3319.6.10.1"
  292. trust_ext_value = "0.%06%0a%2b%06%01%04%01%99w%06%0a%01%04 0%1e%06%08%2b%06%01%05%05%07%03%04%06%08%2b%06%01%05%05%07%03%01%06%08%2b%06%01%05%05%07%03%03"
  293. write_cert_ext_to_file(f, trust_ext_oid, trust_ext_value, pk)
  294. trust_ext_oid = "2.5.29.37"
  295. if has_server_trust:
  296. if has_email_trust:
  297. if has_code_trust:
  298. # server + email + code
  299. trust_ext_value = "0%2a%06%03U%1d%25%01%01%ff%04 0%1e%06%08%2b%06%01%05%05%07%03%04%06%08%2b%06%01%05%05%07%03%01%06%08%2b%06%01%05%05%07%03%03"
  300. else:
  301. # server + email
  302. trust_ext_value = "0 %06%03U%1d%25%01%01%ff%04%160%14%06%08%2b%06%01%05%05%07%03%04%06%08%2b%06%01%05%05%07%03%01"
  303. else:
  304. if has_code_trust:
  305. # server + code
  306. trust_ext_value = "0 %06%03U%1d%25%01%01%ff%04%160%14%06%08%2b%06%01%05%05%07%03%01%06%08%2b%06%01%05%05%07%03%03"
  307. else:
  308. # server
  309. trust_ext_value = "0%16%06%03U%1d%25%01%01%ff%04%0c0%0a%06%08%2b%06%01%05%05%07%03%01"
  310. else:
  311. if has_email_trust:
  312. if has_code_trust:
  313. # email + code
  314. trust_ext_value = "0 %06%03U%1d%25%01%01%ff%04%160%14%06%08%2b%06%01%05%05%07%03%04%06%08%2b%06%01%05%05%07%03%03"
  315. else:
  316. # email
  317. trust_ext_value = "0%16%06%03U%1d%25%01%01%ff%04%0c0%0a%06%08%2b%06%01%05%05%07%03%04"
  318. else:
  319. if has_code_trust:
  320. # code
  321. trust_ext_value = "0%16%06%03U%1d%25%01%01%ff%04%0c0%0a%06%08%2b%06%01%05%05%07%03%03"
  322. else:
  323. # none
  324. trust_ext_value = "0%18%06%03U%1d%25%01%01%ff%04%0e0%0c%06%0a%2b%06%01%04%01%99w%06%0a%10"
  325. # no 2.5.29.37 for neutral certificates
  326. if (is_distrusted or has_server_trust or has_email_trust or has_code_trust):
  327. write_cert_ext_to_file(f, trust_ext_oid, trust_ext_value, pk)
  328. pk = ''
  329. f.write("\n")
  330. f.write("[p11-kit-object-v1]\n")
  331. f.write("label: ");
  332. f.write(tobj['CKA_LABEL'])
  333. f.write("\n")
  334. if is_distrusted:
  335. f.write("x-distrusted: true\n")
  336. elif has_server_trust or has_email_trust or has_code_trust:
  337. f.write("trusted: true\n")
  338. else:
  339. f.write("trusted: false\n")
  340. # requires p11-kit >= 0.23.4
  341. f.write("nss-mozilla-ca-policy: true\n")
  342. f.write("modifiable: false\n");
  343. # requires p11-kit >= 0.23.19
  344. for t in list(cert_distrust_types.keys()):
  345. if t in obj:
  346. value = obj[t]
  347. if value == 'CK_FALSE':
  348. value = bytearray(1)
  349. f.write(cert_distrust_types[t] + ": \"")
  350. f.write(urllib.parse.quote(value));
  351. f.write("\"\n")
  352. f.write("-----BEGIN CERTIFICATE-----\n")
  353. temp_encoded_b64 = base64.b64encode(obj['CKA_VALUE'])
  354. temp_wrapped = textwrap.wrap(temp_encoded_b64.decode(), 64)
  355. f.write("\n".join(temp_wrapped))
  356. f.write("\n-----END CERTIFICATE-----\n")
  357. f.write(cert_comment)
  358. f.write("\n")
  359. else:
  360. f.write("[p11-kit-object-v1]\n")
  361. f.write("label: ");
  362. f.write(tobj['CKA_LABEL']);
  363. f.write("\n")
  364. f.write("class: certificate\n")
  365. f.write("certificate-type: x-509\n")
  366. f.write("modifiable: false\n");
  367. f.write("issuer: \"");
  368. f.write(urllib.parse.quote(tobj['CKA_ISSUER']));
  369. f.write("\"\n")
  370. f.write("serial-number: \"");
  371. f.write(urllib.parse.quote(tobj['CKA_SERIAL_NUMBER']));
  372. f.write("\"\n")
  373. if (tobj['CKA_TRUST_SERVER_AUTH'] == 'CKT_NSS_NOT_TRUSTED') or (tobj['CKA_TRUST_EMAIL_PROTECTION'] == 'CKT_NSS_NOT_TRUSTED') or (tobj['CKA_TRUST_CODE_SIGNING'] == 'CKT_NSS_NOT_TRUSTED'):
  374. f.write("x-distrusted: true\n")
  375. f.write("\n\n")
  376. f.close()
  377. print(" -> written as '%s', trust = %s, openssl-trust = %s, distrust = %s, openssl-distrust = %s" % (fname, trustbits, openssl_trustflags, distrustbits, openssl_distrustflags))