Various KDM work.
[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_asset.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 libdcp;
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 (private_key.string().c_str(), "r");
54         if (!private_key_file) {
55                 throw FileError ("could not find RSA private key file", private_key);
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);
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         MXFMetadata mxf_metadata, XMLMetadata xml_metadata
93         )
94         : xml_kdm (new xml::DCinemaSecurityMessage)
95 {
96         xml::AuthenticatedPublic& apu = xml_kdm->authenticated_public;
97
98         /* AuthenticatedPublic */
99         
100         apu.message_type = "urn:uuid:" + make_uuid ();
101         apu.annotation_text = mxf_metadata.product_name;
102         apu.issue_date = xml_metadata.issue_date;
103         apu.signer.x509_issuer_name = signer->certificates().leaf()->issuer ();
104         apu.signer.x509_serial_number = signer->certificates().leaf()->serial ();
105         apu.recipient.x509_issuer_serial.x509_issuer_name = recipient_cert->issuer ();
106         apu.recipient.x509_issuer_serial.x509_serial_number = recipient_cert->serial ();
107         apu.recipient.x509_subject_name = recipient_cert->subject ();
108         apu.composition_playlist_id = "urn:uuid:" + cpl->id ();
109         apu.content_title_text = cpl->name ();
110         apu.content_keys_not_valid_before = ptime_to_string (not_valid_before);
111         apu.content_keys_not_valid_after = ptime_to_string (not_valid_after);
112         apu.authorized_device_info.device_list_identifier = "urn:uuid:" + make_uuid ();
113         apu.authorized_device_info.device_list_description = recipient_cert->subject ();
114         apu.authorized_device_info.device_list.push_back (recipient_cert->thumbprint ());
115         
116         list<shared_ptr<const Asset> > assets = cpl->assets ();
117         for (list<shared_ptr<const Asset> >::iterator i = assets.begin(); i != assets.end(); ++i) {
118                 /* XXX: non-MXF assets? */
119                 shared_ptr<const MXFAsset> mxf = boost::dynamic_pointer_cast<const MXFAsset> (*i);
120                 if (mxf) {
121                         apu.key_id_list.push_back (xml::TypedKeyId (mxf->key_type(), "urn:uuid:" + mxf->key_id()));
122                 }
123         }
124
125         apu.forensic_mark_flag_list.push_back ("http://www.smpte-ra.org/430-1/2006/KDM#mrkflg-picture-disable");
126         apu.forensic_mark_flag_list.push_back ("http://www.smpte-ra.org/430-1/2006/KDM#mrkflg-audio-disable");
127
128         /* AuthenticatedPrivate */
129
130         for (list<shared_ptr<const Asset> >::iterator i = assets.begin(); i != assets.end(); ++i) {
131                 /* XXX: non-MXF assets? */
132                 shared_ptr<const MXFAsset> mxf = boost::dynamic_pointer_cast<const MXFAsset> (*i);
133                 if (mxf) {
134                         xml_kdm->authenticated_private.encrypted_keys.push_back (
135                                 KDMKey (signer, cpl->id (), mxf->key_id (), not_valid_before, not_valid_after, mxf->key().get()).base64 ()
136                                 );
137                 }
138         }
139
140         /* Signature */
141
142         shared_ptr<xmlpp::Document> doc = xml_kdm->as_xml ();
143         shared_ptr<cxml::Node> root (new cxml::Node (doc->get_root_node ()));
144         xmlpp::Node* signature = root->node_child("Signature")->node();
145         signer->add_signature_value (signature, "ds");
146         xml_kdm->signature = xml::Signature (shared_ptr<cxml::Node> (new cxml::Node (signature)));
147 }
148
149 void
150 KDM::as_xml (boost::filesystem::path path) const
151 {
152         shared_ptr<xmlpp::Document> doc = xml_kdm->as_xml ();
153         doc->write_to_file_formatted (path.string(), "UTF-8");
154 }
155
156 KDMKey::KDMKey (shared_ptr<const Signer> signer, string cpl_id, string key_id, boost::posix_time::ptime from, boost::posix_time::ptime until, Key key)
157         : _cpl_id (cpl_id)
158         , _key_id (key_id)
159         , _not_valid_before (ptime_to_string (from))
160         , _not_valid_after (ptime_to_string (until))
161         , _key (key)
162 {
163         base64_decode (signer->certificates().leaf()->thumbprint (), _signer_thumbprint, 20);
164 }
165
166 KDMKey::KDMKey (uint8_t const * raw, int len)
167 {
168         switch (len) {
169         case 134:
170                 /* interop */
171                 /* [0-15] is structure id (fixed sequence specified by standard) */
172                 raw += 16;
173                 get (_signer_thumbprint, &raw, 20);
174                 _cpl_id = get_uuid (&raw);
175                 _key_id = get_uuid (&raw);
176                 _not_valid_before = get (&raw, 25);
177                 _not_valid_after = get (&raw, 25);
178                 _key = Key (raw);
179                 break;
180         case 138:
181                 /* SMPTE */
182                 /* [0-15] is structure id (fixed sequence specified by standard) */
183                 raw += 16;
184                 get (_signer_thumbprint, &raw, 20);
185                 _cpl_id = get_uuid (&raw);
186                 _key_type = get (&raw, 4);
187                 _key_id = get_uuid (&raw);
188                 _not_valid_before = get (&raw, 25);
189                 _not_valid_after = get (&raw, 25);
190                 _key = Key (raw);
191                 break;
192         default:
193                 assert (false);
194         }
195 }
196
197 KDMKey::KDMKey (KDMKey const & other)
198         : _cpl_id (other._cpl_id)
199         , _key_type (other._key_type)
200         , _key_id (other._key_id)
201         , _not_valid_before (other._not_valid_before)
202         , _not_valid_after (other._not_valid_after)
203         , _key (other._key)
204 {
205         memcpy (_signer_thumbprint, other._signer_thumbprint, 20);
206 }
207
208 KDMKey &
209 KDMKey::operator= (KDMKey const & other)
210 {
211         if (&other == this) {
212                 return *this;
213         }
214         
215         _cpl_id = other._cpl_id;
216         _key_type = other._key_type;
217         _key_id = other._key_id;
218         _not_valid_before = other._not_valid_before;
219         _not_valid_after = other._not_valid_after;
220         _key = other._key;
221         memcpy (_signer_thumbprint, other._signer_thumbprint, 20);
222
223         return *this;
224 }
225
226 string
227 KDMKey::base64 () const
228 {
229         /* XXX: SMPTE only */
230         uint8_t block[138];
231         uint8_t* p = block;
232
233         /* Magic value specified by SMPTE S430-1-2006 */
234         uint8_t structure_id[] = { 0xf1, 0xdc, 0x12, 0x44, 0x60, 0x16, 0x9a, 0x0e, 0x85, 0xbc, 0x30, 0x06, 0x42, 0xf8, 0x66, 0xab };
235         put (&p, structure_id, 16);
236         put (&p, _signer_thumbprint, 20);
237         put_uuid (&p, _cpl_id);
238         put (&p, _key_type);
239         put_uuid (&p, _key_id);
240         put (&p, _not_valid_before);
241         put (&p, _not_valid_after);
242         put (&p, _key.value(), ASDCP::KeyLen);
243
244         /* Lazy overallocation */
245         char string[138 * 2];
246         return Kumu::base64encode (block, 138, string, 138 * 2);
247 }
248
249 string
250 KDMKey::get (uint8_t const ** p, int N) const
251 {
252         string g;
253         for (int i = 0; i < N; ++i) {
254                 g += **p;
255                 (*p)++;
256         }
257
258         return g;
259 }
260
261 void
262 KDMKey::get (uint8_t* o, uint8_t const ** p, int N) const
263 {
264         memcpy (o, *p, N);
265         *p += N;
266 }
267
268 string
269 KDMKey::get_uuid (unsigned char const ** p) const
270 {
271         stringstream g;
272         
273         for (int i = 0; i < 16; ++i) {
274                 g << setw(2) << setfill('0') << hex << static_cast<int> (**p);
275                 (*p)++;
276                 if (i == 3 || i == 5 || i == 7 || i == 9) {
277                         g << '-';
278                 }
279         }
280
281         return g.str ();
282 }
283
284 void
285 KDMKey::put (uint8_t ** d, uint8_t const * s, int N) const
286 {
287         memcpy (*d, s, N);
288         (*d) += N;
289 }
290
291 void
292 KDMKey::put (uint8_t ** d, string s) const
293 {
294         memcpy (*d, s.c_str(), s.length());
295         (*d) += s.length();
296 }
297
298 void
299 KDMKey::put_uuid (uint8_t ** d, string id) const
300 {
301         id.erase (std::remove (id.begin(), id.end(), '-'));
302         for (int i = 0; i < 32; i += 2) {
303                 stringstream s;
304                 s << id[i] << id[i + 1];
305                 int h;
306                 s >> h;
307                 **d = h;
308                 (*d)++;
309         }
310 }