Debian Codegraph @

examples/ca/hpilo_ca

raw
1 #!/usr/bin/python
2 #
3 # (c) 2011-2016 Dennis Kaarsemaker <[email protected]>
4 # see COPYING for license details
5
6 try:
7 import ConfigParser
8 except ImportError:
9 import configparser as ConfigParser
10 import hpilo
11 import optparse
12 import os
13 import re
14 import subprocess
15 import sys
16 import time
17
18 def main():
19 usage = """%prog [options] init
20 %prog [options] sign hostname [hostname ...]"""
21 p = optparse.OptionParser(usage=usage)
22 p.add_option("-l", "--login", dest="login", default=None,
23 help="Username to access the iLO")
24 p.add_option("-p", "--password", dest="password", default=None,
25 help="Password to access the iLO")
26 p.add_option("-c", "--config", dest="config", default="~/.ilo.conf",
27 help="File containing authentication and config details", metavar="FILE")
28 p.add_option("-t", "--timeout", dest="timeout", type="int", default=60,
29 help="Timeout for iLO connections")
30 p.add_option("-P", "--protocol", dest="protocol", choices=("http","raw"), default=None,
31 help="Use the specified protocol instead of autodetecting")
32 p.add_option("-d", "--debug", dest="debug", action="count", default=0,
33 help="Output debug information, repeat to see all XML data")
34 p.add_option("-o", "--port", dest="port", type="int", default=443,
35 help="SSL port to connect to")
36 p.add_option("-s", "--openssl", dest="openssl_bin", default="/usr/bin/openssl",
37 help="Path to the openssl binary")
38 p.add_option("-u", "--upgrade", dest="upgrade", action="store_true", default=False,
39 help="Upgrade iLO firmware that is too old automatically")
40
41 opts, args = p.parse_args()
42
43 if not args or args[0] not in ('init','sign'):
44 p.print_help()
45 p.exit(1)
46
47 if not os.path.exists(os.path.expanduser(opts.config)):
48 p.error("Configuration file '%s' does not exist" % opts.config)
49
50 config = ConfigParser.ConfigParser()
51 config.read(os.path.expanduser(opts.config))
52 if not config.has_option('ca', 'path'):
53 p.error("No CA path specified in the config")
54 ca_path = os.path.expanduser(config.get('ca', 'path'))
55 os.environ['CA_PATH'] = ca_path
56 os.environ['SUBJECTALTNAME'] = ''
57 csr_params = {}
58 for key in ('country', 'state', 'locality', 'organization', 'organizational_unit'):
59 if config.has_option('ca', key):
60 csr_params[key] = config.get('ca', key)
61
62 openssl = OpenSSL(opts.openssl_bin, ca_path, csr_params)
63
64 if args[0] == 'init':
65 if len(args) > 2:
66 p.error("Too many arguments")
67 openssl.init_ca()
68 sys.exit(0)
69
70 # Do we have login information
71 login = None
72 password = None
73 if config.has_option('ilo', 'login'):
74 login = config.get('ilo', 'login')
75 if config.has_option('ilo', 'password'):
76 password = config.get('ilo', 'password')
77 if opts.login:
78 login = opts.login
79 if opts.password:
80 password = opts.password
81 if not login or not password:
82 p.error("No login details provided")
83
84 todo = args[1:]
85 for host in args[1:]:
86 if re.match(r'\d+(\.\d+){3}', host):
87 p.error("hpilo_ca only accepts fqdns, not IP addresses")
88 if '.' not in host:
89 p.error("hpilo_ca only accepts fqdns, not hostnames")
90 while todo:
91 todo = sign_certificates(todo, openssl, login, password, opts)
92 if todo:
93 print("Waiting a minute before trying %d hosts again" % len(todo))
94 what = "\|/-"
95 for i in range(60):
96 sys.stdout.write("\r%s %-2d" % (what[i%4], 60-i))
97 sys.stdout.flush()
98 time.sleep(1)
99 sys.stdout.write("\r \r")
100 sys.stdout.flush()
101
102 def sign_certificates(hosts, openssl, login, password, opts):
103 todo = []
104 for hostname in hosts:
105 if openssl.signed(hostname):
106 print("Certificate already signed, skipping")
107 continue
108
109 ilo = hpilo.Ilo(hostname, login, password, opts.timeout, opts.port)
110 ilo.debug = opts.debug
111 if opts.protocol == 'http':
112 ilo.protocol = hpilo.ILO_HTTP
113 elif opts.protocol == 'raw':
114 ilo.protocol = hpilo.ILO_RAW
115
116 print("(1/5) Checking certificate config of %s" % hostname)
117 fw_version = ilo.get_fw_version()
118 network_settings = ilo.get_network_settings()
119 if fw_version['management_processor'].lower() == 'ilo2':
120 version = fw_version['firmware_version']
121 if version < '2.06':
122 print("iLO2 firmware version %s is too old" % version)
123 if not opts.upgrade:
124 print("Please upgrade firmware to 2.06 or newer")
125 continue
126 print("Upgrading iLO firmware")
127 ilo.update_rib_firmware(version='latest', progress=print_progress)
128 todo.append(hostname)
129 continue
130 cn = ilo.get_cert_subject_info()['csr_subject_common_name']
131 if '.' not in cn:
132 ilo.cert_fqdn(use_fqdn=True)
133 cn = ilo.get_cert_subject_info()['csr_subject_common_name']
134
135 hn, dn = hostname.split('.', 1)
136 if network_settings['dns_name'] != hn or dn and network_settings['domain_name'] != dn:
137 print("Hostname misconfigured on the ilo, fixing")
138 ilo.mod_network_settings(dns_name=hn, domain_name=dn)
139 todo.append(hostname)
140 continue
141
142 print("(2/5) Retrieving certificate signing request")
143 if fw_version['management_processor'].lower() == 'ilo2':
144 csr = ilo.certificate_signing_request()
145 else:
146 params = openssl.csr_params.copy()
147 cn = '%s.%s' % (network_settings['dns_name'], network_settings['domain_name'])
148 params['common_name'] = cn
149 try:
150 csr = ilo.certificate_signing_request(**params)
151 except hpilo.IloGeneratingCSR:
152 print("Certificate request is being generated, trying again later")
153 todo.append(hostname)
154 continue
155 if not csr:
156 print("Received an empty CSR")
157 continue
158
159 print("(3/5) Signing certificate")
160 cert = openssl.sign(network_settings, csr)
161
162 print("(4/5) Uploading certificate")
163 ilo.import_certificate(cert)
164
165 print("(5/5) Resetting iLO")
166 ilo.reset_rib()
167 return todo
168
169 class OpenSSL(object):
170 def __init__(self, openssl_bin, ca_path, csr_params):
171 self.openssl_bin = openssl_bin
172 self.ca_path = ca_path
173 self.openssl_cnf = os.path.join(ca_path, 'openssl.cnf')
174 self.csr_params = csr_params
175
176 def call(self, *args, **envvars):
177 env = os.environ.copy()
178 env.update(envvars)
179 args = list(args)
180 if args[0] in ('req', 'ca'):
181 args = args[:1] + ['-config', self.openssl_cnf] + args[1:]
182 return subprocess.call([self.openssl_bin] + args, env=env)
183
184 def signed(self, hostname):
185 crt_path = os.path.join(self.ca_path, 'certs', hostname + '.crt')
186 return os.path.exists(crt_path)
187
188 def sign(self, network_settings, csr):
189 hostname = network_settings['dns_name']
190 fqdn = '%s.%s' % (network_settings['dns_name'], network_settings['domain_name'])
191 ip = network_settings['ip_address']
192 altnames = 'DNS:%s,DNS:%s,IP:%s' % (fqdn, hostname, ip)
193
194 csr_path = os.path.join(self.ca_path, 'certs', hostname + '.csr')
195 crt_path = os.path.join(self.ca_path, 'certs', hostname + '.crt')
196 fd = open(csr_path, 'w')
197 fd.write(csr)
198 fd.close()
199 self.call('ca', '-batch', '-in', csr_path, '-out', crt_path, SUBJECTALTNAME=altnames)
200 fd = open(crt_path)
201 cert = fd.read()
202 fd.close()
203 cert = cert[cert.find('-----BEGIN'):]
204 return cert
205
206 def init_ca(self):
207 if not os.path.exists(self.ca_path):
208 os.makedirs(self.ca_path)
209 if not os.path.exists(self.openssl_cnf):
210 open(self.openssl_cnf, 'w').write(self.default_openssl_cnf)
211 for dir in ('ca', 'certs', 'crl', 'archive'):
212 if not os.path.exists(os.path.join(self.ca_path, dir)):
213 os.mkdir(os.path.join(self.ca_path, dir))
214 if not os.path.exists(os.path.join(self.ca_path, 'archive', 'index')):
215 open(os.path.join(self.ca_path, 'archive', 'index'),'w').close()
216 if not os.path.exists(os.path.join(self.ca_path, 'archive', 'serial')):
217 fd = open(os.path.join(self.ca_path, 'archive', 'serial'),'w')
218 fd.write("00\n")
219 fd.close()
220 if not os.path.exists(os.path.join(self.ca_path, 'ca', 'hpilo_ca.key')):
221 self.call('genrsa', '-out', os.path.join(self.ca_path, 'ca', 'hpilo_ca.key'), '2048')
222 if not os.path.exists(os.path.join(self.ca_path, 'ca', 'hpilo_ca.crt')):
223 self.call('req', '-new', '-x509', '-days', '7300', # 20 years should be enough for everyone :-)
224 '-key', os.path.join(self.ca_path, 'ca', 'hpilo_ca.key'),
225 '-out', os.path.join(self.ca_path, 'ca', 'hpilo_ca.crt'))
226
227 default_openssl_cnf = """default_ca = hpilo_ca
228
229 [hpilo_ca]
230 dir = $ENV::CA_PATH
231 certs = $dir/certs
232 crl_dir = $dir/crl
233 private_key = $dir/ca/hpilo_ca.key
234 certificate = $dir/ca/hpilo_ca.crt
235 database = $dir/archive/index
236 new_certs_dir = $dir/archive
237 serial = $dir/archive/serial
238 crlnumber = $dir/crl/crlnumber
239 crl = $dir/crl/crl.pem
240 RANDFILE = $dir/.rand
241 x509_extensions = usr_cert
242 name_opt = ca_default
243 cert_opt = ca_default
244 default_days = 1825 # 5 years
245 default_crl_days = 30
246 default_md = sha256
247 preserve = no
248 policy = req_policy
249
250 [req_policy]
251 countryName = supplied
252 stateOrProvinceName = supplied
253 localityName = supplied
254 organizationName = supplied
255 organizationalUnitName = optional
256 commonName = supplied
257 emailAddress = optional
258
259 [req]
260 dir = $ENV::CA_PATH
261 default_bits = 2048
262 default_md = sha256
263 default_keyfile = $dir/ca/hpilo_ca.key
264 distinguished_name = req_distinguished_name
265 x509_extensions = ca_cert # The extentions to add to the self signed cert
266 string_mask = MASK:0x2002
267
268 [req_distinguished_name]
269 countryName = Country Name (2 letter code)
270 countryName_default = NL
271 countryName_min = 2
272 countryName_max = 2
273 stateOrProvinceName = State or Province Name (full name)
274 stateOrProvinceName_default = Flevoland
275 localityName = Locality Name (eg, city)
276 localityName_default = Lelystad
277 0.organizationName = Organization Name (eg, company)
278 0.organizationName_default = Kaarsemaker.net
279 commonName = Common Name (eg, your name or your server's hostname)
280 commonName_max = 64
281 commonName_default = hpilo_ca
282
283 [usr_cert]
284 basicConstraints = CA:FALSE
285 subjectKeyIdentifier = hash
286 authorityKeyIdentifier = keyid,issuer
287 nsComment = "Certificate generated by iLO CA"
288 subjectAltName = $ENV::SUBJECTALTNAME
289
290 [ca_cert]
291 basicConstraints = CA:true
292 subjectKeyIdentifier = hash
293 authorityKeyIdentifier = keyid:always,issuer:always
294 nsComment = "Certificate generated by iLO CA"
295 """
296
297 def print_progress(text):
298 if text.startswith('\r'):
299 sys.stdout.write(text)
300 sys.stdout.flush()
301 else:
302 print(text)
303
304 if __name__ == '__main__':
305 main()