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