xref: /aosp_15_r20/external/webrtc/tools_webrtc/sslroots/generate_sslroots.py (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1#!/usr/bin/env vpython3
2
3# -*- coding:utf-8 -*-
4# Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
5#
6# Use of this source code is governed by a BSD-style license
7# that can be found in the LICENSE file in the root of the source
8# tree. An additional intellectual property rights grant can be found
9# in the file PATENTS.  All contributing project authors may
10# be found in the AUTHORS file in the root of the source tree.
11"""This is a tool to transform a crt file into a C/C++ header.
12
13Usage:
14python3 generate_sslroots.py certfile.pem [--verbose | -v] [--full_cert | -f]
15
16Arguments:
17  -v  Print output while running.
18  -f  Add public key and certificate name.  Default is to skip and reduce
19      generated file size.
20
21The supported cert files are:
22  - Google: https://pki.goog/roots.pem
23  - Mozilla: https://curl.se/docs/caextract.html
24"""
25
26import subprocess
27from optparse import OptionParser
28import os
29import re
30
31_GENERATED_FILE = 'ssl_roots.h'
32_PREFIX = '__generated__'
33_EXTENSION = '.crt'
34_SUBJECT_NAME_ARRAY = 'subject_name'
35_SUBJECT_NAME_VARIABLE = 'SubjectName'
36_PUBLIC_KEY_ARRAY = 'public_key'
37_PUBLIC_KEY_VARIABLE = 'PublicKey'
38_CERTIFICATE_ARRAY = 'certificate'
39_CERTIFICATE_VARIABLE = 'Certificate'
40_CERTIFICATE_SIZE_VARIABLE = 'CertificateSize'
41_INT_TYPE = 'size_t'
42_CHAR_TYPE = 'unsigned char* const'
43_VERBOSE = 'verbose'
44_MOZILLA_BUNDLE_CHECK = '## Certificate data from Mozilla as of:'
45
46
47def main():
48  """The main entrypoint."""
49  parser = OptionParser('usage %prog FILE')
50  parser.add_option('-v', '--verbose', dest='verbose', action='store_true')
51  parser.add_option('-f', '--full_cert', dest='full_cert', action='store_true')
52  options, args = parser.parse_args()
53  if len(args) < 1:
54    parser.error('No crt file specified.')
55    return
56  root_dir, bundle_type = _SplitCrt(args[0], options)
57  _GenCFiles(root_dir, options, bundle_type)
58  _Cleanup(root_dir)
59
60
61def _SplitCrt(source_file, options):
62  sub_file_blocks = []
63  label_name = ''
64  prev_line = None
65  root_dir = os.path.dirname(os.path.abspath(source_file)) + '/'
66  _PrintOutput(root_dir, options)
67  lines = None
68  with open(source_file) as f:
69    lines = f.readlines()
70  mozilla_bundle = any(l.startswith(_MOZILLA_BUNDLE_CHECK) for l in lines)
71  for line in lines:
72    if line.startswith('#'):
73      if mozilla_bundle:
74        continue
75      if line.startswith('# Label: '):
76        sub_file_blocks.append(line)
77        label = re.search(r'\".*\"', line)
78        temp_label = label.group(0)
79        end = len(temp_label) - 1
80        label_name = _SafeName(temp_label[1:end])
81    if mozilla_bundle and line.startswith('==='):
82      sub_file_blocks.append(line)
83      label_name = _SafeName(prev_line)
84    elif line.startswith('-----END CERTIFICATE-----'):
85      sub_file_blocks.append(line)
86      new_file_name = root_dir + _PREFIX + label_name + _EXTENSION
87      _PrintOutput('Generating: ' + new_file_name, options)
88      new_file = open(new_file_name, 'w')
89      for out_line in sub_file_blocks:
90        new_file.write(out_line)
91      new_file.close()
92      sub_file_blocks = []
93    else:
94      sub_file_blocks.append(line)
95    prev_line = line
96  return root_dir, 'Mozilla' if mozilla_bundle else 'Google'
97
98
99def _GenCFiles(root_dir, options, bundle_type):
100  output_header_file = open(root_dir + _GENERATED_FILE, 'w')
101  output_header_file.write(_CreateOutputHeader(bundle_type))
102  if options.full_cert:
103    subject_name_list = _CreateArraySectionHeader(_SUBJECT_NAME_VARIABLE,
104                                                  _CHAR_TYPE, options)
105    public_key_list = _CreateArraySectionHeader(_PUBLIC_KEY_VARIABLE,
106                                                _CHAR_TYPE, options)
107  certificate_list = _CreateArraySectionHeader(_CERTIFICATE_VARIABLE,
108                                               _CHAR_TYPE, options)
109  certificate_size_list = _CreateArraySectionHeader(_CERTIFICATE_SIZE_VARIABLE,
110                                                    _INT_TYPE, options)
111
112  for _, _, files in os.walk(root_dir):
113    for current_file in files:
114      if current_file.startswith(_PREFIX):
115        prefix_length = len(_PREFIX)
116        length = len(current_file) - len(_EXTENSION)
117        label = current_file[prefix_length:length]
118        filtered_output, cert_size = _CreateCertSection(root_dir, current_file,
119                                                        label, options)
120        output_header_file.write(filtered_output + '\n\n\n')
121        if options.full_cert:
122          subject_name_list += _AddLabelToArray(label, _SUBJECT_NAME_ARRAY)
123          public_key_list += _AddLabelToArray(label, _PUBLIC_KEY_ARRAY)
124        certificate_list += _AddLabelToArray(label, _CERTIFICATE_ARRAY)
125        certificate_size_list += ('  %s,\n') % (cert_size)
126
127  if options.full_cert:
128    subject_name_list += _CreateArraySectionFooter()
129    output_header_file.write(subject_name_list)
130    public_key_list += _CreateArraySectionFooter()
131    output_header_file.write(public_key_list)
132  certificate_list += _CreateArraySectionFooter()
133  output_header_file.write(certificate_list)
134  certificate_size_list += _CreateArraySectionFooter()
135  output_header_file.write(certificate_size_list)
136  output_header_file.write(_CreateOutputFooter())
137  output_header_file.close()
138
139
140def _Cleanup(root_dir):
141  for f in os.listdir(root_dir):
142    if f.startswith(_PREFIX):
143      os.remove(root_dir + f)
144
145
146def _CreateCertSection(root_dir, source_file, label, options):
147  command = 'openssl x509 -in %s%s -noout -C' % (root_dir, source_file)
148  _PrintOutput(command, options)
149  output = subprocess.getstatusoutput(command)[1]
150  decl_block = 'unsigned char .*_(%s|%s|%s)' %\
151    (_SUBJECT_NAME_ARRAY, _PUBLIC_KEY_ARRAY, _CERTIFICATE_ARRAY)
152  prog = re.compile(decl_block, re.IGNORECASE)
153  renamed_output = prog.sub('const unsigned char ' + label + r'_\1', output)
154
155  filtered_output = ''
156  cert_block = '^const unsigned char.*?};$'
157  prog2 = re.compile(cert_block, re.IGNORECASE | re.MULTILINE | re.DOTALL)
158  if not options.full_cert:
159    filtered_output = prog2.sub('', renamed_output, count=2)
160  else:
161    filtered_output = renamed_output
162
163  cert_size_block = r'\d\d\d+'
164  prog3 = re.compile(cert_size_block, re.MULTILINE | re.VERBOSE)
165  result = prog3.findall(renamed_output)
166  cert_size = result[len(result) - 1]
167
168  return filtered_output, cert_size
169
170
171def _CreateOutputHeader(bundle_type):
172  output = ('/*\n'
173            ' *  Copyright 2004 The WebRTC Project Authors. All rights '
174            'reserved.\n'
175            ' *\n'
176            ' *  Use of this source code is governed by a BSD-style license\n'
177            ' *  that can be found in the LICENSE file in the root of the '
178            'source\n'
179            ' *  tree. An additional intellectual property rights grant can be '
180            'found\n'
181            ' *  in the file PATENTS.  All contributing project authors may\n'
182            ' *  be found in the AUTHORS file in the root of the source tree.\n'
183            ' */\n\n'
184            '#ifndef RTC_BASE_SSL_ROOTS_H_\n'
185            '#define RTC_BASE_SSL_ROOTS_H_\n\n'
186            '// This file is the root certificates in C form.\n\n'
187            '// It was generated with the following script:\n'
188            '// tools_webrtc/sslroots/generate_sslroots.py'
189            ' %s_CA_bundle.pem\n\n'
190            '// clang-format off\n'
191            '// Don\'t bother formatting generated code,\n'
192            '// also it would breaks subject/issuer lines.\n\n' % bundle_type)
193  return output
194
195
196def _CreateOutputFooter():
197  return '// clang-format on\n\n#endif  // RTC_BASE_SSL_ROOTS_H_\n'
198
199
200def _CreateArraySectionHeader(type_name, type_type, options):
201  output = ('const %s kSSLCert%sList[] = {\n') % (type_type, type_name)
202  _PrintOutput(output, options)
203  return output
204
205
206def _AddLabelToArray(label, type_name):
207  return ' %s_%s,\n' % (label, type_name)
208
209
210def _CreateArraySectionFooter():
211  return '};\n\n'
212
213
214def _SafeName(original_file_name):
215  bad_chars = ' -./\\()áéíőú\r\n'
216  replacement_chars = ''
217  for _ in bad_chars:
218    replacement_chars += '_'
219  translation_table = str.maketrans(bad_chars, replacement_chars)
220  return original_file_name.translate(translation_table)
221
222
223def _PrintOutput(output, options):
224  if options.verbose:
225    print(output)
226
227
228if __name__ == '__main__':
229  main()
230