Quote openssl -subj strings.
[libdcp.git] / src / certificate_chain.cc
1 /*
2     Copyright (C) 2013-2014 Carl Hetherington <cth@carlh.net>
3
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.
8
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.
13
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.
17
18 */
19
20 /** @file  src/signer_chain.cc
21  *  @brief Functions to make signer chains.
22  */
23
24 #include "certificate_chain.h"
25 #include "exceptions.h"
26 #include "util.h"
27 #include "KM_util.h"
28 #include <openssl/sha.h>
29 #include <openssl/bio.h>
30 #include <openssl/evp.h>
31 #include <boost/filesystem.hpp>
32 #include <boost/algorithm/string.hpp>
33 #include <fstream>
34 #include <sstream>
35
36 using std::string;
37 using std::ofstream;
38 using std::ifstream;
39 using std::stringstream;
40 using std::cout;
41
42 /** Run a shell command.
43  *  @param cmd Command to run (UTF8-encoded).
44  */
45 static void
46 command (string cmd)
47 {
48 #ifdef LIBDCP_WINDOWS
49         /* We need to use CreateProcessW on Windows so that the UTF-8/16 mess
50            is handled correctly.
51         */
52         int const wn = MultiByteToWideChar (CP_UTF8, 0, cmd.c_str(), -1, 0, 0);
53         wchar_t* buffer = new wchar_t[wn];
54         if (MultiByteToWideChar (CP_UTF8, 0, cmd.c_str(), -1, buffer, wn) == 0) {
55                 delete[] buffer;
56                 return;
57         }
58
59         int code = 1;
60
61         STARTUPINFOW startup_info;
62         memset (&startup_info, 0, sizeof (startup_info));
63         startup_info.cb = sizeof (startup_info);
64         PROCESS_INFORMATION process_info;
65
66         /* XXX: this doesn't actually seem to work; failing commands end up with
67            a return code of 0
68         */
69         if (CreateProcessW (0, buffer, 0, 0, FALSE, CREATE_NO_WINDOW, 0, 0, &startup_info, &process_info)) {
70                 WaitForSingleObject (process_info.hProcess, INFINITE);
71                 DWORD c;
72                 if (GetExitCodeProcess (process_info.hProcess, &c)) {
73                         code = c;
74                 }
75                 CloseHandle (process_info.hProcess);
76                 CloseHandle (process_info.hThread);
77         }
78
79         delete[] buffer;
80 #else
81         cmd += " 2> /dev/null";
82         int const r = system (cmd.c_str ());
83         int const code = WEXITSTATUS (r);
84 #endif
85         if (code) {
86                 stringstream s;
87                 s << "error " << code << " in " << cmd << " within " << boost::filesystem::current_path();
88                 throw dcp::MiscError (s.str());
89         }
90 }
91
92 /** Extract a public key from a private key and create a SHA1 digest of it.
93  *  @param private_key Private key
94  *  @param openssl openssl binary name (or full path if openssl is not on the system path).
95  *  @return SHA1 digest of corresponding public key, with escaped / characters.
96  */
97 static string
98 public_key_digest (boost::filesystem::path private_key, boost::filesystem::path openssl)
99 {
100         boost::filesystem::path public_name = private_key.string() + ".public";
101
102         /* Create the public key from the private key */
103         stringstream s;
104         s << "\"" << openssl.string() << "\" rsa -outform PEM -pubout -in " << private_key.string() << " -out " << public_name.string ();
105         command (s.str().c_str ());
106
107         /* Read in the public key from the file */
108
109         string pub;
110         ifstream f (public_name.string().c_str ());
111         if (!f.good ()) {
112                 throw dcp::MiscError ("public key not found");
113         }
114
115         bool read = false;
116         while (f.good ()) {
117                 string line;
118                 getline (f, line);
119                 if (line.length() >= 10 && line.substr(0, 10) == "-----BEGIN") {
120                         read = true;
121                 } else if (line.length() >= 8 && line.substr(0, 8) == "-----END") {
122                         break;
123                 } else if (read) {
124                         pub += line;
125                 }
126         }
127
128         /* Decode the base64 of the public key */
129                 
130         unsigned char buffer[512];
131         int const N = dcp::base64_decode (pub, buffer, 1024);
132
133         /* Hash it with SHA1 (without the first 24 bytes, for reasons that are not entirely clear) */
134
135         SHA_CTX context;
136         if (!SHA1_Init (&context)) {
137                 throw dcp::MiscError ("could not init SHA1 context");
138         }
139
140         if (!SHA1_Update (&context, buffer + 24, N - 24)) {
141                 throw dcp::MiscError ("could not update SHA1 digest");
142         }
143
144         unsigned char digest[SHA_DIGEST_LENGTH];
145         if (!SHA1_Final (digest, &context)) {
146                 throw dcp::MiscError ("could not finish SHA1 digest");
147         }
148
149         char digest_base64[64];
150         string dig = Kumu::base64encode (digest, SHA_DIGEST_LENGTH, digest_base64, 64);
151 #ifdef LIBDCP_WINDOWS
152         boost::replace_all (dig, "/", "\\/");
153 #else   
154         boost::replace_all (dig, "/", "\\\\/");
155 #endif  
156         return dig;
157 }
158
159 boost::filesystem::path
160 dcp::make_certificate_chain (
161         boost::filesystem::path openssl,
162         string organisation,
163         string organisational_unit,
164         string root_common_name,
165         string intermediate_common_name,
166         string leaf_common_name
167         )
168 {
169         boost::filesystem::path directory = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
170         boost::filesystem::create_directories (directory);
171         
172         boost::filesystem::path const cwd = boost::filesystem::current_path ();
173         boost::filesystem::current_path (directory);
174
175         string quoted_openssl = "\"" + openssl.string() + "\"";
176
177         command (quoted_openssl + " genrsa -out ca.key 2048");
178
179         {
180                 ofstream f ("ca.cnf");
181                 f << "[ req ]\n"
182                   << "distinguished_name = req_distinguished_name\n"
183                   << "x509_extensions   = v3_ca\n"
184                   << "[ v3_ca ]\n"
185                   << "basicConstraints = critical,CA:true,pathlen:3\n"
186                   << "keyUsage = keyCertSign,cRLSign\n"
187                   << "subjectKeyIdentifier = hash\n"
188                   << "authorityKeyIdentifier = keyid:always,issuer:always\n"
189                   << "[ req_distinguished_name ]\n"
190                   << "O = Unique organization name\n"
191                   << "OU = Organization unit\n"
192                   << "CN = Entity and dnQualifier\n";
193         }
194
195         string const ca_subject = "/O=" + organisation +
196                 "/OU=" + organisational_unit +
197                 "/CN=" + root_common_name +
198                 "/dnQualifier=" + public_key_digest ("ca.key", openssl);
199
200         {
201                 stringstream c;
202                 c << quoted_openssl
203                   << " req -new -x509 -sha256 -config ca.cnf -days 3650 -set_serial 5"
204                   << " -subj \"" << ca_subject << "\" -key ca.key -outform PEM -out ca.self-signed.pem";
205                 command (c.str().c_str());
206         }
207
208         command (quoted_openssl + " genrsa -out intermediate.key 2048");
209
210         {
211                 ofstream f ("intermediate.cnf");
212                 f << "[ default ]\n"
213                   << "distinguished_name = req_distinguished_name\n"
214                   << "x509_extensions = v3_ca\n"
215                   << "[ v3_ca ]\n"
216                   << "basicConstraints = critical,CA:true,pathlen:2\n"
217                   << "keyUsage = keyCertSign,cRLSign\n"
218                   << "subjectKeyIdentifier = hash\n"
219                   << "authorityKeyIdentifier = keyid:always,issuer:always\n"
220                   << "[ req_distinguished_name ]\n"
221                   << "O = Unique organization name\n"
222                   << "OU = Organization unit\n"
223                   << "CN = Entity and dnQualifier\n";
224         }
225                 
226         string const inter_subject = "/O=" + organisation +
227                 "/OU=" + organisational_unit +
228                 "/CN=" + intermediate_common_name +
229                 "/dnQualifier=" + public_key_digest ("intermediate.key", openssl);
230
231         {
232                 stringstream s;
233                 s << quoted_openssl
234                   << " req -new -config intermediate.cnf -days 3649 -subj \"" << inter_subject << "\" -key intermediate.key -out intermediate.csr";
235                 command (s.str().c_str());
236         }
237
238         
239         command (
240                 quoted_openssl +
241                 " x509 -req -sha256 -days 3649 -CA ca.self-signed.pem -CAkey ca.key -set_serial 6"
242                 " -in intermediate.csr -extfile intermediate.cnf -extensions v3_ca -out intermediate.signed.pem"
243                 );
244
245         command (quoted_openssl + " genrsa -out leaf.key 2048");
246
247         {
248                 ofstream f ("leaf.cnf");
249                 f << "[ default ]\n"
250                   << "distinguished_name = req_distinguished_name\n"
251                   << "x509_extensions   = v3_ca\n"
252                   << "[ v3_ca ]\n"
253                   << "basicConstraints = critical,CA:false\n"
254                   << "keyUsage = digitalSignature,keyEncipherment\n"
255                   << "subjectKeyIdentifier = hash\n"
256                   << "authorityKeyIdentifier = keyid,issuer:always\n"
257                   << "[ req_distinguished_name ]\n"
258                   << "O = Unique organization name\n"
259                   << "OU = Organization unit\n"
260                   << "CN = Entity and dnQualifier\n";
261         }
262
263         string const leaf_subject = "/O=" + organisation +
264                 "/OU=" + organisational_unit +
265                 "/CN=" + leaf_common_name +
266                 "/dnQualifier=" + public_key_digest ("leaf.key", openssl);
267
268         {
269                 stringstream s;
270                 s << quoted_openssl << " req -new -config leaf.cnf -days 3648 -subj \"" << leaf_subject << "\" -key leaf.key -outform PEM -out leaf.csr";
271                 command (s.str().c_str());
272         }
273
274         command (
275                 quoted_openssl +
276                 " x509 -req -sha256 -days 3648 -CA intermediate.signed.pem -CAkey intermediate.key"
277                 " -set_serial 7 -in leaf.csr -extfile leaf.cnf -extensions v3_ca -out leaf.signed.pem"
278                 );
279
280         boost::filesystem::current_path (cwd);
281
282         return directory;
283 }