Tweaks to test setup; don't always compute coverage.
[libdcp.git] / src / decrypted_kdm.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 #include "decrypted_kdm.h"
21 #include "decrypted_kdm_key.h"
22 #include "encrypted_kdm.h"
23 #include "reel_mxf_asset.h"
24 #include "util.h"
25 #include "exceptions.h"
26 #include "cpl.h"
27 #include "mxf.h"
28 #include "signer.h"
29 #include "dcp_assert.h"
30 #include "AS_DCP.h"
31 #include "KM_util.h"
32 #include "compose.hpp"
33 #include <openssl/rsa.h>
34 #include <openssl/pem.h>
35 #include <openssl/err.h>
36
37 using std::list;
38 using std::string;
39 using std::stringstream;
40 using std::setw;
41 using std::setfill;
42 using std::hex;
43 using std::pair;
44 using boost::shared_ptr;
45 using namespace dcp;
46
47 static void
48 put (uint8_t ** d, string s)
49 {
50         memcpy (*d, s.c_str(), s.length());
51         (*d) += s.length();
52 }
53
54 static void
55 put (uint8_t ** d, uint8_t const * s, int N)
56 {
57         memcpy (*d, s, N);
58         (*d) += N;
59 }
60
61 static void
62 put_uuid (uint8_t ** d, string id)
63 {
64         id.erase (std::remove (id.begin(), id.end(), '-'));
65         for (int i = 0; i < 32; i += 2) {
66                 stringstream s;
67                 s << id[i] << id[i + 1];
68                 int h;
69                 s >> hex >> h;
70                 **d = h;
71                 (*d)++;
72         }
73 }
74
75 static string
76 get_uuid (unsigned char ** p)
77 {
78         stringstream g;
79         
80         for (int i = 0; i < 16; ++i) {
81                 g << setw(2) << setfill('0') << hex << static_cast<int> (**p);
82                 (*p)++;
83                 if (i == 3 || i == 5 || i == 7 || i == 9) {
84                         g << '-';
85                 }
86         }
87
88         return g.str ();
89 }
90
91 static string
92 get (uint8_t ** p, int N)
93 {
94         string g;
95         for (int i = 0; i < N; ++i) {
96                 g += **p;
97                 (*p)++;
98         }
99
100         return g;
101 }
102
103 DecryptedKDM::DecryptedKDM (EncryptedKDM const & kdm, string private_key)
104 {
105         /* Read the private key */
106
107         BIO* bio = BIO_new_mem_buf (const_cast<char *> (private_key.c_str ()), -1);
108         if (!bio) {
109                 throw MiscError ("could not create memory BIO");
110         }
111         
112         RSA* rsa = PEM_read_bio_RSAPrivateKey (bio, 0, 0, 0);
113         if (!rsa) {
114                 throw FileError ("could not read RSA private key file", private_key, errno);
115         }
116
117         /* Use the private key to decrypt the keys */
118
119         list<string> const encrypted_keys = kdm.keys ();
120         for (list<string>::const_iterator i = encrypted_keys.begin(); i != encrypted_keys.end(); ++i) {
121
122                 /* Decode the base-64-encoded cipher value from the KDM */
123                 unsigned char cipher_value[256];
124                 int const cipher_value_len = base64_decode (*i, cipher_value, sizeof (cipher_value));
125
126                 /* Decrypt it */
127                 unsigned char * decrypted = new unsigned char[RSA_size(rsa)];
128                 int const decrypted_len = RSA_private_decrypt (cipher_value_len, cipher_value, decrypted, rsa, RSA_PKCS1_OAEP_PADDING);
129                 if (decrypted_len == -1) {
130                         delete[] decrypted;
131                         throw MiscError (String::compose ("Could not decrypt KDM (%1)", ERR_error_string (ERR_get_error(), 0)));
132                 }
133
134                 unsigned char* p = decrypted;
135                 switch (decrypted_len) {
136                 case 134:
137                 {
138                         /* Inter-op */
139                         /* 0 is structure id (fixed sequence specified by standard) [16 bytes] */
140                         p += 16;
141                         /* 16 is is signer thumbprint [20 bytes] */
142                         p += 20;
143                         /* 36 is CPL id [16 bytes] */
144                         string const cpl_id = get_uuid (&p);
145                         /* 52 is key id [16 bytes] */
146                         string const key_id = get_uuid (&p);
147                         /* 68 is not-valid-before (a string) [25 bytes] */
148                         p += 25;
149                         /* 93 is not-valid-after (a string) [25 bytes] */
150                         p += 25;
151                         /* 118 is the key [ASDCP::KeyLen bytes] */
152                         _keys.push_back (DecryptedKDMKey ("", key_id, Key (p), cpl_id));
153                         break;
154                 }
155                 case 138:
156                 {
157                         /* SMPTE */
158                         /* 0 is structure id (fixed sequence specified by standard) [16 bytes] */
159                         p += 16;
160                         /* 16 is is signer thumbprint [20 bytes] */
161                         p += 20;
162                         /* 36 is CPL id [16 bytes] */
163                         string const cpl_id = get_uuid (&p);
164                         /* 52 is key type [4 bytes] */
165                         string const key_type = get (&p, 4);
166                         /* 56 is key id [16 bytes] */
167                         string const key_id = get_uuid (&p);
168                         /* 72 is not-valid-before (a string) [25 bytes] */
169                         p += 25;
170                         /* 97 is not-valid-after (a string) [25 bytes] */
171                         p += 25;
172                         /* 112 is the key [ASDCP::KeyLen bytes] */
173                         _keys.push_back (DecryptedKDMKey (key_type, key_id, Key (p), cpl_id));
174                         break;
175                 }
176                 default:
177                         DCP_ASSERT (false);
178                 }               
179                 
180                 delete[] decrypted;
181         }
182
183         RSA_free (rsa);
184         BIO_free (bio);
185 }
186
187 DecryptedKDM::DecryptedKDM (
188         boost::shared_ptr<const CPL> cpl,
189         Key key,
190         LocalTime not_valid_before,
191         LocalTime not_valid_after,
192         string annotation_text,
193         string content_title_text,
194         string issue_date
195         )
196         : _not_valid_before (not_valid_before)
197         , _not_valid_after (not_valid_after)
198         , _annotation_text (annotation_text)
199         , _content_title_text (content_title_text)
200         , _issue_date (issue_date)
201 {
202         /* Create DecryptedKDMKey objects for each MXF asset */
203         list<shared_ptr<const ReelAsset> > assets = cpl->reel_assets ();
204         for (list<shared_ptr<const ReelAsset> >::iterator i = assets.begin(); i != assets.end(); ++i) {
205                 /* XXX: do non-MXF assets need keys? */
206                 shared_ptr<const ReelMXFAsset> mxf = boost::dynamic_pointer_cast<const ReelMXFAsset> (*i);
207                 if (mxf) {
208                         if (mxf->key_id().empty ()) {
209                                 throw NotEncryptedError (mxf->id());
210                         }
211                         _keys.push_back (DecryptedKDMKey (mxf->key_type(), mxf->key_id(), key, cpl->id ()));
212                 }
213         }
214 }
215
216 EncryptedKDM
217 DecryptedKDM::encrypt (shared_ptr<const Signer> signer, Certificate recipient, Formulation formulation) const
218 {
219         list<pair<string, string> > key_ids;
220         list<string> keys;
221         for (list<DecryptedKDMKey>::const_iterator i = _keys.begin(); i != _keys.end(); ++i) {
222
223                 key_ids.push_back (make_pair (i->type(), i->id ()));
224
225                 /* XXX: SMPTE only */
226                 uint8_t block[138];
227                 uint8_t* p = block;
228
229                 /* Magic value specified by SMPTE S430-1-2006 */
230                 uint8_t structure_id[] = { 0xf1, 0xdc, 0x12, 0x44, 0x60, 0x16, 0x9a, 0x0e, 0x85, 0xbc, 0x30, 0x06, 0x42, 0xf8, 0x66, 0xab };
231                 put (&p, structure_id, 16);
232
233                 base64_decode (signer->certificates().leaf().thumbprint (), p, 20);
234                 p += 20;
235                 
236                 put_uuid (&p, i->cpl_id ());
237                 put (&p, i->type ());
238                 put_uuid (&p, i->id ());
239                 put (&p, _not_valid_before.as_string ());
240                 put (&p, _not_valid_after.as_string ());
241                 put (&p, i->key().value(), ASDCP::KeyLen);
242                 
243                 /* Encrypt using the projector's public key */
244                 RSA* rsa = recipient.public_key ();
245                 unsigned char encrypted[RSA_size(rsa)];
246                 int const encrypted_len = RSA_public_encrypt (p - block, block, encrypted, rsa, RSA_PKCS1_OAEP_PADDING);
247                 if (encrypted_len == -1) {
248                         throw MiscError (String::compose ("Could not encrypt KDM (%1)", ERR_error_string (ERR_get_error(), 0)));
249                 }
250                 
251                 /* Lazy overallocation */
252                 char out[encrypted_len * 2];
253                 Kumu::base64encode (encrypted, encrypted_len, out, encrypted_len * 2);
254                 int const N = strlen (out);
255                 stringstream lines;
256                 for (int i = 0; i < N; ++i) {
257                         if (i > 0 && (i % 64) == 0) {
258                                 lines << "\n";
259                         }
260                         lines << out[i];
261                 }
262                 
263                 keys.push_back (lines.str ());
264         }
265
266         string device_list_description = recipient.common_name ();
267         if (device_list_description.find (".") != string::npos) {
268                 device_list_description = device_list_description.substr (device_list_description.find (".") + 1);
269         }
270
271         return EncryptedKDM (
272                 signer,
273                 recipient,
274                 device_list_description,
275                 _keys.front().cpl_id (),
276                 _content_title_text,
277                 _not_valid_before,
278                 _not_valid_after,
279                 formulation,
280                 key_ids,
281                 keys
282                 );
283 }