2 Copyright (C) 2013-2015 Carl Hetherington <cth@carlh.net>
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 /** @file src/signer_chain.cc
21 * @brief Functions to make signer chains.
24 #include "certificate_chain.h"
25 #include "exceptions.h"
27 #include "dcp_assert.h"
29 #include <openssl/sha.h>
30 #include <openssl/bio.h>
31 #include <openssl/evp.h>
32 #include <boost/filesystem.hpp>
33 #include <boost/algorithm/string.hpp>
40 using std::stringstream;
43 /** Run a shell command.
44 * @param cmd Command to run (UTF8-encoded).
50 /* We need to use CreateProcessW on Windows so that the UTF-8/16 mess
53 int const wn = MultiByteToWideChar (CP_UTF8, 0, cmd.c_str(), -1, 0, 0);
54 wchar_t* buffer = new wchar_t[wn];
55 if (MultiByteToWideChar (CP_UTF8, 0, cmd.c_str(), -1, buffer, wn) == 0) {
62 STARTUPINFOW startup_info;
63 memset (&startup_info, 0, sizeof (startup_info));
64 startup_info.cb = sizeof (startup_info);
65 PROCESS_INFORMATION process_info;
67 /* XXX: this doesn't actually seem to work; failing commands end up with
70 if (CreateProcessW (0, buffer, 0, 0, FALSE, CREATE_NO_WINDOW, 0, 0, &startup_info, &process_info)) {
71 WaitForSingleObject (process_info.hProcess, INFINITE);
73 if (GetExitCodeProcess (process_info.hProcess, &c)) {
76 CloseHandle (process_info.hProcess);
77 CloseHandle (process_info.hThread);
82 cmd += " 2> /dev/null";
83 int const r = system (cmd.c_str ());
84 int const code = WEXITSTATUS (r);
88 s << "error " << code << " in " << cmd << " within " << boost::filesystem::current_path();
89 throw dcp::MiscError (s.str());
93 /** Extract a public key from a private key and create a SHA1 digest of it.
94 * @param private_key Private key
95 * @param openssl openssl binary name (or full path if openssl is not on the system path).
96 * @return SHA1 digest of corresponding public key, with escaped / characters.
99 public_key_digest (boost::filesystem::path private_key, boost::filesystem::path openssl)
101 boost::filesystem::path public_name = private_key.string() + ".public";
103 /* Create the public key from the private key */
105 s << "\"" << openssl.string() << "\" rsa -outform PEM -pubout -in " << private_key.string() << " -out " << public_name.string ();
106 command (s.str().c_str ());
108 /* Read in the public key from the file */
111 ifstream f (public_name.string().c_str ());
113 throw dcp::MiscError ("public key not found");
120 if (line.length() >= 10 && line.substr(0, 10) == "-----BEGIN") {
122 } else if (line.length() >= 8 && line.substr(0, 8) == "-----END") {
129 /* Decode the base64 of the public key */
131 unsigned char buffer[512];
132 int const N = dcp::base64_decode (pub, buffer, 1024);
134 /* Hash it with SHA1 (without the first 24 bytes, for reasons that are not entirely clear) */
137 if (!SHA1_Init (&context)) {
138 throw dcp::MiscError ("could not init SHA1 context");
141 if (!SHA1_Update (&context, buffer + 24, N - 24)) {
142 throw dcp::MiscError ("could not update SHA1 digest");
145 unsigned char digest[SHA_DIGEST_LENGTH];
146 if (!SHA1_Final (digest, &context)) {
147 throw dcp::MiscError ("could not finish SHA1 digest");
150 char digest_base64[64];
151 string dig = Kumu::base64encode (digest, SHA_DIGEST_LENGTH, digest_base64, 64);
152 #ifdef LIBDCP_WINDOWS
153 boost::replace_all (dig, "/", "\\/");
155 boost::replace_all (dig, "/", "\\\\/");
160 boost::filesystem::path
161 dcp::make_certificate_chain (
162 boost::filesystem::path openssl,
164 string organisational_unit,
165 string root_common_name,
166 string intermediate_common_name,
167 string leaf_common_name
170 boost::filesystem::path directory = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
171 boost::filesystem::create_directories (directory);
173 boost::filesystem::path const cwd = boost::filesystem::current_path ();
174 boost::filesystem::current_path (directory);
176 string quoted_openssl = "\"" + openssl.string() + "\"";
178 command (quoted_openssl + " genrsa -out ca.key 2048");
181 ofstream f ("ca.cnf");
183 << "distinguished_name = req_distinguished_name\n"
184 << "x509_extensions = v3_ca\n"
186 << "basicConstraints = critical,CA:true,pathlen:3\n"
187 << "keyUsage = keyCertSign,cRLSign\n"
188 << "subjectKeyIdentifier = hash\n"
189 << "authorityKeyIdentifier = keyid:always,issuer:always\n"
190 << "[ req_distinguished_name ]\n"
191 << "O = Unique organization name\n"
192 << "OU = Organization unit\n"
193 << "CN = Entity and dnQualifier\n";
196 string const ca_subject = "/O=" + organisation +
197 "/OU=" + organisational_unit +
198 "/CN=" + root_common_name +
199 "/dnQualifier=" + public_key_digest ("ca.key", openssl);
204 << " req -new -x509 -sha256 -config ca.cnf -days 3650 -set_serial 5"
205 << " -subj \"" << ca_subject << "\" -key ca.key -outform PEM -out ca.self-signed.pem";
206 command (c.str().c_str());
209 command (quoted_openssl + " genrsa -out intermediate.key 2048");
212 ofstream f ("intermediate.cnf");
214 << "distinguished_name = req_distinguished_name\n"
215 << "x509_extensions = v3_ca\n"
217 << "basicConstraints = critical,CA:true,pathlen:2\n"
218 << "keyUsage = keyCertSign,cRLSign\n"
219 << "subjectKeyIdentifier = hash\n"
220 << "authorityKeyIdentifier = keyid:always,issuer:always\n"
221 << "[ req_distinguished_name ]\n"
222 << "O = Unique organization name\n"
223 << "OU = Organization unit\n"
224 << "CN = Entity and dnQualifier\n";
227 string const inter_subject = "/O=" + organisation +
228 "/OU=" + organisational_unit +
229 "/CN=" + intermediate_common_name +
230 "/dnQualifier=" + public_key_digest ("intermediate.key", openssl);
235 << " req -new -config intermediate.cnf -days 3649 -subj \"" << inter_subject << "\" -key intermediate.key -out intermediate.csr";
236 command (s.str().c_str());
242 " x509 -req -sha256 -days 3649 -CA ca.self-signed.pem -CAkey ca.key -set_serial 6"
243 " -in intermediate.csr -extfile intermediate.cnf -extensions v3_ca -out intermediate.signed.pem"
246 command (quoted_openssl + " genrsa -out leaf.key 2048");
249 ofstream f ("leaf.cnf");
251 << "distinguished_name = req_distinguished_name\n"
252 << "x509_extensions = v3_ca\n"
254 << "basicConstraints = critical,CA:false\n"
255 << "keyUsage = digitalSignature,keyEncipherment\n"
256 << "subjectKeyIdentifier = hash\n"
257 << "authorityKeyIdentifier = keyid,issuer:always\n"
258 << "[ req_distinguished_name ]\n"
259 << "O = Unique organization name\n"
260 << "OU = Organization unit\n"
261 << "CN = Entity and dnQualifier\n";
264 string const leaf_subject = "/O=" + organisation +
265 "/OU=" + organisational_unit +
266 "/CN=" + leaf_common_name +
267 "/dnQualifier=" + public_key_digest ("leaf.key", openssl);
271 s << quoted_openssl << " req -new -config leaf.cnf -days 3648 -subj \"" << leaf_subject << "\" -key leaf.key -outform PEM -out leaf.csr";
272 command (s.str().c_str());
277 " x509 -req -sha256 -days 3648 -CA intermediate.signed.pem -CAkey intermediate.key"
278 " -set_serial 7 -in leaf.csr -extfile leaf.cnf -extensions v3_ca -out leaf.signed.pem"
281 boost::filesystem::current_path (cwd);
286 /** @return Root certificate */
288 CertificateChain::root () const
290 DCP_ASSERT (!_certificates.empty());
291 return _certificates.front ();
294 /** @return Leaf certificate */
296 CertificateChain::leaf () const
298 DCP_ASSERT (_certificates.size() >= 2);
299 return _certificates.back ();
302 /** @return Certificates in order from root to leaf */
303 CertificateChain::List
304 CertificateChain::root_to_leaf () const
306 return _certificates;
309 /** @return Certificates in order from leaf to root */
310 CertificateChain::List
311 CertificateChain::leaf_to_root () const
313 List c = _certificates;
318 /** Add a certificate to the end of the chain.
319 * @param c Certificate to add.
322 CertificateChain::add (Certificate c)
324 _certificates.push_back (c);
327 /** Remove a certificate from the chain.
328 * @param c Certificate to remove.
331 CertificateChain::remove (Certificate c)
333 _certificates.remove (c);
336 /** Remove the i'th certificate in the list, as listed
340 CertificateChain::remove (int i)
342 List::iterator j = _certificates.begin ();
343 while (j != _certificates.end () && i > 0) {
348 if (j != _certificates.end ()) {
349 _certificates.erase (j);
353 /** Check to see if the chain is valid (i.e. root signs the intermediate, intermediate
354 * signs the leaf and so on).
355 * @return true if it's ok, false if not.
358 CertificateChain::valid () const
360 X509_STORE* store = X509_STORE_new ();
365 for (List::const_iterator i = _certificates.begin(); i != _certificates.end(); ++i) {
367 List::const_iterator j = i;
369 if (j == _certificates.end ()) {
373 if (!X509_STORE_add_cert (store, i->x509 ())) {
374 X509_STORE_free (store);
378 X509_STORE_CTX* ctx = X509_STORE_CTX_new ();
380 X509_STORE_free (store);
384 X509_STORE_set_flags (store, 0);
385 if (!X509_STORE_CTX_init (ctx, store, j->x509 (), 0)) {
386 X509_STORE_CTX_free (ctx);
387 X509_STORE_free (store);
391 int v = X509_verify_cert (ctx);
392 X509_STORE_CTX_free (ctx);
395 X509_STORE_free (store);
400 X509_STORE_free (store);
404 /** @return true if the chain is now in order from root to leaf,
405 * false if no correct order was found.
408 CertificateChain::attempt_reorder ()
410 List original = _certificates;
411 _certificates.sort ();
416 } while (std::next_permutation (_certificates.begin(), _certificates.end ()));
418 _certificates = original;