Write encryption test all to the right place. Some more XML writes unformatted to...
[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 c)
39 {
40         int const r = system (c.c_str ());
41 #ifdef LIBDCP_WINDOWS   
42         if (r) {
43 #else
44         if (WEXITSTATUS (r)) {
45 #endif          
46                 stringstream s;
47                 s << "error in " << c << "\n";
48                 throw libdcp::MiscError (s.str());
49         }
50 }
51
52 /** Extract a public key from a private key and create a SHA1 digest of it.
53  *  @param key Private key
54  *  @param openssl openssl binary name (or full path if openssl is not on the system path).
55  *  @return SHA1 digest of corresponding public key, with escaped / characters.
56  */
57         
58 static string
59 public_key_digest (boost::filesystem::path private_key, boost::filesystem::path openssl)
60 {
61         boost::filesystem::path public_name = private_key.string() + ".public";
62         
63         /* Create the public key from the private key */
64         stringstream s;
65         s << openssl.string() << " rsa -outform PEM -pubout -in " << private_key.string() << " > " << public_name.string ();
66         command (s.str().c_str ());
67
68         /* Read in the public key from the file */
69
70         string pub;
71         ifstream f (public_name.string().c_str ());
72
73         bool read = false;
74         while (1) {
75                 string line;
76                 getline (f, line);
77                 if (line.length() >= 10 && line.substr(0, 10) == "-----BEGIN") {
78                         read = true;
79                 } else if (line.length() >= 8 && line.substr(0, 8) == "-----END") {
80                         break;
81                 } else if (read) {
82                         pub += line;
83                 }
84         }
85
86         /* Decode the base64 of the public key */
87                 
88         unsigned char buffer[512];
89         int const N = libdcp::base64_decode (pub, buffer, 1024);
90
91         /* Hash it with SHA1 (without the first 24 bytes, for reasons that are not entirely clear) */
92
93         SHA_CTX context;
94         if (!SHA1_Init (&context)) {
95                 throw libdcp::MiscError ("could not init SHA1 context");
96         }
97
98         if (!SHA1_Update (&context, buffer + 24, N - 24)) {
99                 throw libdcp::MiscError ("could not update SHA1 digest");
100         }
101
102         unsigned char digest[SHA_DIGEST_LENGTH];
103         if (!SHA1_Final (digest, &context)) {
104                 throw libdcp::MiscError ("could not finish SHA1 digest");
105         }
106
107         char digest_base64[64];
108         string dig = Kumu::base64encode (digest, SHA_DIGEST_LENGTH, digest_base64, 64);
109 #ifdef LIBDCP_WINDOWS
110         boost::replace_all (dig, "/", "\\/");
111 #else   
112         boost::replace_all (dig, "/", "\\\\/");
113 #endif  
114         return dig;
115 }
116
117 void
118 libdcp::make_signer_chain (boost::filesystem::path directory, boost::filesystem::path openssl)
119 {
120         boost::filesystem::path const cwd = boost::filesystem::current_path ();
121
122         boost::filesystem::current_path (directory);
123         command (openssl.string() + " genrsa -out ca.key 2048");
124
125         {
126                 ofstream f ("ca.cnf");
127                 f << "[ req ]\n"
128                   << "distinguished_name = req_distinguished_name\n"
129                   << "x509_extensions   = v3_ca\n"
130                   << "[ v3_ca ]\n"
131                   << "basicConstraints = critical,CA:true,pathlen:3\n"
132                   << "keyUsage = keyCertSign,cRLSign\n"
133                   << "subjectKeyIdentifier = hash\n"
134                   << "authorityKeyIdentifier = keyid:always,issuer:always\n"
135                   << "[ req_distinguished_name ]\n"
136                   << "O = Unique organization name\n"
137                   << "OU = Organization unit\n"
138                   << "CN = Entity and dnQualifier\n";
139         }
140
141         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);
142
143         {
144                 stringstream c;
145                 c << openssl.string()
146                   << " req -new -x509 -sha256 -config ca.cnf -days 3650 -set_serial 5"
147                   << " -subj " << ca_subject << " -key ca.key -outform PEM -out ca.self-signed.pem";
148                 command (c.str().c_str());
149         }
150
151         command (openssl.string() + " genrsa -out intermediate.key 2048");
152
153         {
154                 ofstream f ("intermediate.cnf");
155                 f << "[ default ]\n"
156                   << "distinguished_name = req_distinguished_name\n"
157                   << "x509_extensions = v3_ca\n"
158                   << "[ v3_ca ]\n"
159                   << "basicConstraints = critical,CA:true,pathlen:2\n"
160                   << "keyUsage = keyCertSign,cRLSign\n"
161                   << "subjectKeyIdentifier = hash\n"
162                   << "authorityKeyIdentifier = keyid:always,issuer:always\n"
163                   << "[ req_distinguished_name ]\n"
164                   << "O = Unique organization name\n"
165                   << "OU = Organization unit\n"
166                   << "CN = Entity and dnQualifier\n";
167         }
168                 
169         string const inter_subject = "/O=example.org/OU=example.org/CN=.smpte-430-2.INTERMEDIATE.NOT_FOR_PRODUCTION/dnQualifier="
170                 + public_key_digest ("intermediate.key", openssl);
171
172         {
173                 stringstream s;
174                 s << openssl.string() << " req -new -config intermediate.cnf -days 3649 -subj " << inter_subject << " -key intermediate.key -out intermediate.csr";
175                 command (s.str().c_str());
176         }
177
178         
179         command (
180                 openssl.string() +
181                 " x509 -req -sha256 -days 3649 -CA ca.self-signed.pem -CAkey ca.key -set_serial 6"
182                 " -in intermediate.csr -extfile intermediate.cnf -extensions v3_ca -out intermediate.signed.pem"
183                 );
184
185         command (openssl.string() + " genrsa -out leaf.key 2048");
186
187         {
188                 ofstream f ("leaf.cnf");
189                 f << "[ default ]\n"
190                   << "distinguished_name = req_distinguished_name\n"
191                   << "x509_extensions   = v3_ca\n"
192                   << "[ v3_ca ]\n"
193                   << "basicConstraints = critical,CA:false\n"
194                   << "keyUsage = digitalSignature,keyEncipherment\n"
195                   << "subjectKeyIdentifier = hash\n"
196                   << "authorityKeyIdentifier = keyid,issuer:always\n"
197                   << "[ req_distinguished_name ]\n"
198                   << "O = Unique organization name\n"
199                   << "OU = Organization unit\n"
200                   << "CN = Entity and dnQualifier\n";
201         }
202
203         string const leaf_subject = "/O=example.org/OU=example.org/CN=CS.smpte-430-2.LEAF.NOT_FOR_PRODUCTION/dnQualifier="
204                 + public_key_digest ("leaf.key", openssl);
205
206         {
207                 stringstream s;
208                 s << openssl.string() << " req -new -config leaf.cnf -days 3648 -subj " << leaf_subject << " -key leaf.key -outform PEM -out leaf.csr";
209                 command (s.str().c_str());
210         }
211
212         command (
213                 openssl.string() +
214                 " x509 -req -sha256 -days 3648 -CA intermediate.signed.pem -CAkey intermediate.key"
215                 " -set_serial 7 -in leaf.csr -extfile leaf.cnf -extensions v3_ca -out leaf.signed.pem"
216                 );
217
218         boost::filesystem::current_path (cwd);
219 }