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