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