Asset -> MXF in some cases.
[libdcp.git] / src / kdm.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 <iomanip>
21 #include <algorithm>
22 #include <boost/algorithm/string.hpp>
23 #include <openssl/rsa.h>
24 #include <openssl/pem.h>
25 #include <openssl/err.h>
26 #include <libcxml/cxml.h>
27 #include "AS_DCP.h"
28 #include "KM_util.h"
29 #include "util.h"
30 #include "kdm.h"
31 #include "compose.hpp"
32 #include "exceptions.h"
33 #include "signer.h"
34 #include "cpl.h"
35 #include "mxf.h"
36 #include "xml/kdm_smpte.h"
37
38 using std::list;
39 using std::string;
40 using std::stringstream;
41 using std::hex;
42 using std::setw;
43 using std::setfill;
44 using std::cout;
45 using boost::shared_ptr;
46 using namespace dcp;
47
48 KDM::KDM (boost::filesystem::path kdm, boost::filesystem::path private_key)
49         : _xml_kdm (new xml::DCinemaSecurityMessage (kdm))
50 {
51         /* Read the private key */
52            
53         FILE* private_key_file = fopen_boost (private_key, "r");
54         if (!private_key_file) {
55                 throw FileError ("could not find RSA private key file", private_key, errno);
56         }
57         
58         RSA* rsa = PEM_read_RSAPrivateKey (private_key_file, 0, 0, 0);
59         fclose (private_key_file);      
60         if (!rsa) {
61                 throw FileError ("could not read RSA private key file", private_key, errno);
62         }
63
64         /* Use it to decrypt the keys */
65
66         list<string> encrypted_keys = _xml_kdm->authenticated_private.encrypted_keys;
67
68         for (list<string>::iterator i = encrypted_keys.begin(); i != encrypted_keys.end(); ++i) {
69
70                 /* Decode the base-64-encoded cipher value from the KDM */
71                 unsigned char cipher_value[256];
72                 int const cipher_value_len = base64_decode (*i, cipher_value, sizeof (cipher_value));
73
74                 /* Decrypt it */
75                 unsigned char* decrypted = new unsigned char[RSA_size(rsa)];
76                 int const decrypted_len = RSA_private_decrypt (cipher_value_len, cipher_value, decrypted, rsa, RSA_PKCS1_OAEP_PADDING);
77                 if (decrypted_len == -1) {
78                         delete[] decrypted;
79                         throw MiscError (String::compose ("Could not decrypt KDM (%1)", ERR_error_string (ERR_get_error(), 0)));
80                 }
81
82                 _keys.push_back (KDMKey (decrypted, decrypted_len));
83                 delete[] decrypted;
84         }
85
86         RSA_free (rsa);
87 }
88
89 KDM::KDM (
90         shared_ptr<const CPL> cpl, shared_ptr<const Signer> signer, shared_ptr<const Certificate> recipient_cert,
91         boost::posix_time::ptime not_valid_before, boost::posix_time::ptime not_valid_after,
92         string annotation_text, string issue_date
93         )
94         : _xml_kdm (new xml::DCinemaSecurityMessage)
95 {
96         xml::AuthenticatedPublic& apu = _xml_kdm->authenticated_public;
97
98         /* AuthenticatedPublic */
99
100         apu.message_id = "urn:uuid:" + make_uuid ();
101         apu.message_type = "http://www.smpte-ra.org/430-1/2006/KDM#kdm-key-type";
102         apu.annotation_text = annotation_text;
103         apu.issue_date = issue_date;
104         apu.signer.x509_issuer_name = signer->certificates().leaf()->issuer ();
105         apu.signer.x509_serial_number = signer->certificates().leaf()->serial ();
106         apu.recipient.x509_issuer_serial.x509_issuer_name = recipient_cert->issuer ();
107         apu.recipient.x509_issuer_serial.x509_serial_number = recipient_cert->serial ();
108         apu.recipient.x509_subject_name = recipient_cert->subject ();
109         apu.composition_playlist_id = "urn:uuid:" + cpl->id ();
110 //      apu.content_authenticator = signer->certificates().leaf()->thumbprint ();
111         apu.content_title_text = cpl->name ();
112         apu.content_keys_not_valid_before = ptime_to_string (not_valid_before);
113         apu.content_keys_not_valid_after = ptime_to_string (not_valid_after);
114         apu.authorized_device_info.device_list_identifier = "urn:uuid:" + make_uuid ();
115         string n = recipient_cert->common_name ();
116         if (n.find (".") != string::npos) {
117                 n = n.substr (n.find (".") + 1);
118         }
119         apu.authorized_device_info.device_list_description = n;
120 //      apu.authorized_device_info.device_list.push_back (recipient_cert->thumbprint ());
121
122         /* Sometimes digital_cinema_tools uses this magic thumbprint instead of that from an actual
123            recipient certificate.  KDMs delivered to City Screen appear to use the same thing.
124         */
125         apu.authorized_device_info.device_list.push_back ("2jmj7l5rSw0yVb/vlWAYkK/YBwk=");
126
127         list<shared_ptr<const ContentAsset> > assets = cpl->assets ();
128         for (list<shared_ptr<const ContentAsset> >::iterator i = assets.begin(); i != assets.end(); ++i) {
129                 /* XXX: non-MXF assets? */
130                 shared_ptr<const MXF> mxf = boost::dynamic_pointer_cast<const MXF> (*i);
131                 if (mxf) {
132                         apu.key_id_list.push_back (xml::TypedKeyId (mxf->key_type(), "urn:uuid:" + mxf->key_id()));
133                 }
134         }
135
136         apu.forensic_mark_flag_list.push_back ("http://www.smpte-ra.org/430-1/2006/KDM#mrkflg-picture-disable");
137         apu.forensic_mark_flag_list.push_back ("http://www.smpte-ra.org/430-1/2006/KDM#mrkflg-audio-disable");
138
139         /* AuthenticatedPrivate */
140
141         for (list<shared_ptr<const ContentAsset> >::iterator i = assets.begin(); i != assets.end(); ++i) {
142                 /* XXX: non-MXF assets? */
143                 shared_ptr<const MXF> mxf = boost::dynamic_pointer_cast<const MXF> (*i);
144                 if (mxf) {
145                         KDMKey kkey (
146                                         signer, cpl->id (), mxf->key_type (), mxf->key_id (),
147                                         not_valid_before, not_valid_after, mxf->key().get()
148                                 );
149
150                         _keys.push_back (kkey);
151                         _xml_kdm->authenticated_private.encrypted_keys.push_back (kkey.encrypted_base64 (recipient_cert));
152                 }
153         }
154
155         /* Signature */
156
157         shared_ptr<xmlpp::Document> doc = _xml_kdm->as_xml ();
158         shared_ptr<cxml::Node> root (new cxml::Node (doc->get_root_node ()));
159         xmlpp::Node* signature = root->node_child("Signature")->node();
160         signer->add_signature_value (signature, "ds");
161         _xml_kdm->signature = xml::Signature (shared_ptr<cxml::Node> (new cxml::Node (signature)));
162 }
163
164 KDM::KDM (KDM const & other)
165         : _keys (other._keys)
166         , _xml_kdm (new xml::DCinemaSecurityMessage (*other._xml_kdm.get()))
167 {
168
169 }
170
171 KDM &
172 KDM::operator= (KDM const & other)
173 {
174         if (this == &other) {
175                 return *this;
176         }
177
178         _keys = other._keys;
179         _xml_kdm.reset (new xml::DCinemaSecurityMessage (*other._xml_kdm.get ()));
180
181         return *this;
182 }
183      
184 void
185 KDM::as_xml (boost::filesystem::path path) const
186 {
187         shared_ptr<xmlpp::Document> doc = _xml_kdm->as_xml ();
188         /* This must *not* be the _formatted version, otherwise the signature
189            will be wrong.
190         */
191         doc->write_to_file (path.string(), "UTF-8");
192 }
193
194 string
195 KDM::as_xml () const
196 {
197         shared_ptr<xmlpp::Document> doc = _xml_kdm->as_xml ();
198         /* This must *not* be the _formatted version, otherwise the signature
199            will be wrong.
200         */
201         return doc->write_to_string ("UTF-8");
202 }
203
204 KDMKey::KDMKey (
205         shared_ptr<const Signer> signer, string cpl_id, string key_type, string key_id, boost::posix_time::ptime from, boost::posix_time::ptime until, Key key
206         )
207         : _cpl_id (cpl_id)
208         , _key_type (key_type)
209         , _key_id (key_id)
210         , _not_valid_before (ptime_to_string (from))
211         , _not_valid_after (ptime_to_string (until))
212         , _key (key)
213 {
214         base64_decode (signer->certificates().leaf()->thumbprint (), _signer_thumbprint, 20);
215 }
216
217 KDMKey::KDMKey (uint8_t const * raw, int len)
218 {
219         switch (len) {
220         case 134:
221                 /* interop */
222                 /* [0-15] is structure id (fixed sequence specified by standard) */
223                 raw += 16;
224                 get (_signer_thumbprint, &raw, 20);
225                 _cpl_id = get_uuid (&raw);
226                 _key_id = get_uuid (&raw);
227                 _not_valid_before = get (&raw, 25);
228                 _not_valid_after = get (&raw, 25);
229                 _key = Key (raw);
230                 break;
231         case 138:
232                 /* SMPTE */
233                 /* [0-15] is structure id (fixed sequence specified by standard) */
234                 raw += 16;
235                 get (_signer_thumbprint, &raw, 20);
236                 _cpl_id = get_uuid (&raw);
237                 _key_type = get (&raw, 4);
238                 _key_id = get_uuid (&raw);
239                 _not_valid_before = get (&raw, 25);
240                 _not_valid_after = get (&raw, 25);
241                 _key = Key (raw);
242                 break;
243         default:
244                 assert (false);
245         }
246 }
247
248 KDMKey::KDMKey (KDMKey const & other)
249         : _cpl_id (other._cpl_id)
250         , _key_type (other._key_type)
251         , _key_id (other._key_id)
252         , _not_valid_before (other._not_valid_before)
253         , _not_valid_after (other._not_valid_after)
254         , _key (other._key)
255 {
256         memcpy (_signer_thumbprint, other._signer_thumbprint, 20);
257 }
258
259 KDMKey &
260 KDMKey::operator= (KDMKey const & other)
261 {
262         if (&other == this) {
263                 return *this;
264         }
265
266         _cpl_id = other._cpl_id;
267         _key_type = other._key_type;
268         _key_id = other._key_id;
269         _not_valid_before = other._not_valid_before;
270         _not_valid_after = other._not_valid_after;
271         _key = other._key;
272         memcpy (_signer_thumbprint, other._signer_thumbprint, 20);
273
274         return *this;
275 }
276
277 string
278 KDMKey::encrypted_base64 (shared_ptr<const Certificate> recipient_cert) const
279 {
280         assert (_key_type.length() == 4);
281         assert (_not_valid_before.length() == 25);
282         assert (_not_valid_after.length() == 25);
283         
284         /* XXX: SMPTE only */
285         uint8_t block[138];
286         uint8_t* p = block;
287
288         /* Magic value specified by SMPTE S430-1-2006 */
289         uint8_t structure_id[] = { 0xf1, 0xdc, 0x12, 0x44, 0x60, 0x16, 0x9a, 0x0e, 0x85, 0xbc, 0x30, 0x06, 0x42, 0xf8, 0x66, 0xab };
290         put (&p, structure_id, 16);
291         put (&p, _signer_thumbprint, 20);
292         put_uuid (&p, _cpl_id);
293         put (&p, _key_type);
294         put_uuid (&p, _key_id);
295         put (&p, _not_valid_before);
296         put (&p, _not_valid_after);
297         put (&p, _key.value(), ASDCP::KeyLen);
298
299         /* Encrypt using the projector's public key */
300         RSA* rsa = recipient_cert->public_key ();
301         unsigned char encrypted[RSA_size(rsa)];
302         int const encrypted_len = RSA_public_encrypt (p - block, block, encrypted, rsa, RSA_PKCS1_OAEP_PADDING);
303         if (encrypted_len == -1) {
304                 throw MiscError (String::compose ("Could not encrypt KDM (%1)", ERR_error_string (ERR_get_error(), 0)));
305         }
306
307         /* Lazy overallocation */
308         char out[encrypted_len * 2];
309         Kumu::base64encode (encrypted, encrypted_len, out, encrypted_len * 2);
310         int const N = strlen (out);
311         stringstream lines;
312         for (int i = 0; i < N; ++i) {
313                 if (i > 0 && (i % 64) == 0) {
314                         lines << "\n";
315                 }
316                 lines << out[i];
317         }
318
319         return lines.str ();
320 }
321
322 string
323 KDMKey::get (uint8_t const ** p, int N) const
324 {
325         string g;
326         for (int i = 0; i < N; ++i) {
327                 g += **p;
328                 (*p)++;
329         }
330
331         return g;
332 }
333
334 void
335 KDMKey::get (uint8_t* o, uint8_t const ** p, int N) const
336 {
337         memcpy (o, *p, N);
338         *p += N;
339 }
340
341 string
342 KDMKey::get_uuid (unsigned char const ** p) const
343 {
344         stringstream g;
345         
346         for (int i = 0; i < 16; ++i) {
347                 g << setw(2) << setfill('0') << hex << static_cast<int> (**p);
348                 (*p)++;
349                 if (i == 3 || i == 5 || i == 7 || i == 9) {
350                         g << '-';
351                 }
352         }
353
354         return g.str ();
355 }
356
357 void
358 KDMKey::put (uint8_t ** d, uint8_t const * s, int N) const
359 {
360         memcpy (*d, s, N);
361         (*d) += N;
362 }
363
364 void
365 KDMKey::put (uint8_t ** d, string s) const
366 {
367         memcpy (*d, s.c_str(), s.length());
368         (*d) += s.length();
369 }
370
371 void
372 KDMKey::put_uuid (uint8_t ** d, string id) const
373 {
374         id.erase (std::remove (id.begin(), id.end(), '-'));
375         for (int i = 0; i < 32; i += 2) {
376                 stringstream s;
377                 s << id[i] << id[i + 1];
378                 int h;
379                 s >> hex >> h;
380                 **d = h;
381                 (*d)++;
382         }
383 }
384
385 bool
386 dcp::operator== (dcp::KDMKey const & a, dcp::KDMKey const & b)
387 {
388         if (memcmp (a._signer_thumbprint, b._signer_thumbprint, 20) != 0) {
389                 return false;
390         }
391
392         return (
393                 a._cpl_id == b._cpl_id &&
394                 a._key_type == b._key_type &&
395                 a._key_id == b._key_id &&
396                 a._not_valid_before == b._not_valid_before &&
397                 a._not_valid_after == b._not_valid_after &&
398                 a._key == b._key
399                 );
400 }