Merge branch '1.0' of ssh://main.carlh.net/home/carl/git/libdcp into 1.0
[libdcp.git] / src / encrypted_kdm.cc
1 /*
2     Copyright (C) 2013-2015 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 "encrypted_kdm.h"
21 #include "util.h"
22 #include "certificate_chain.h"
23 #include <libcxml/cxml.h>
24 #include <libxml++/document.h>
25 #include <libxml++/nodes/element.h>
26 #include <libxml/parser.h>
27 #include <boost/date_time/posix_time/posix_time.hpp>
28
29 using std::list;
30 using std::string;
31 using std::map;
32 using std::pair;
33 using boost::shared_ptr;
34 using namespace dcp;
35
36 namespace dcp {
37
38 /** Namespace for classes used to hold our data; they are internal to this .cc file */
39 namespace data {
40
41 class Signer
42 {
43 public:
44         Signer () {}
45
46         Signer (shared_ptr<const cxml::Node> node)
47                 : x509_issuer_name (node->string_child ("X509IssuerName"))
48                 , x509_serial_number (node->string_child ("X509SerialNumber"))
49         {
50
51         }
52
53         void as_xml (xmlpp::Element* node) const
54         {
55                 node->add_child("X509IssuerName", "ds")->add_child_text (x509_issuer_name);
56                 node->add_child("X509SerialNumber", "ds")->add_child_text (x509_serial_number);
57         }
58
59         string x509_issuer_name;
60         string x509_serial_number;
61 };
62
63 class X509Data
64 {
65 public:
66         X509Data () {}
67
68         X509Data (boost::shared_ptr<const cxml::Node> node)
69                 : x509_issuer_serial (Signer (node->node_child ("X509IssuerSerial")))
70                 , x509_certificate (node->string_child ("X509Certificate"))
71         {
72                 node->done ();
73         }
74
75         void as_xml (xmlpp::Element* node) const
76         {
77                 x509_issuer_serial.as_xml (node->add_child ("X509IssuerSerial", "ds"));
78                 node->add_child("X509Certificate", "ds")->add_child_text (x509_certificate);
79         }
80
81         Signer x509_issuer_serial;
82         std::string x509_certificate;
83 };
84
85 class Reference
86 {
87 public:
88         Reference () {}
89
90         Reference (string u)
91                 : uri (u)
92         {}
93
94         Reference (shared_ptr<const cxml::Node> node)
95                 : uri (node->string_attribute ("URI"))
96                 , digest_value (node->string_child ("DigestValue"))
97         {
98
99         }
100
101         void as_xml (xmlpp::Element* node) const
102         {
103                 node->set_attribute ("URI", uri);
104                 node->add_child("DigestMethod", "ds")->set_attribute ("Algorithm", "http://www.w3.org/2001/04/xmlenc#sha256");
105                 node->add_child("DigestValue", "ds")->add_child_text (digest_value);
106         }
107
108         string uri;
109         string digest_value;
110 };
111
112 class SignedInfo
113 {
114 public:
115         SignedInfo ()
116                 : authenticated_public ("#ID_AuthenticatedPublic")
117                 , authenticated_private ("#ID_AuthenticatedPrivate")
118         {}
119
120         SignedInfo (shared_ptr<const cxml::Node> node)
121         {
122                 list<shared_ptr<cxml::Node> > references = node->node_children ("Reference");
123                 for (list<shared_ptr<cxml::Node> >::const_iterator i = references.begin(); i != references.end(); ++i) {
124                         if ((*i)->string_attribute ("URI") == "#ID_AuthenticatedPublic") {
125                                 authenticated_public = Reference (*i);
126                         } else if ((*i)->string_attribute ("URI") == "#ID_AuthenticatedPrivate") {
127                                 authenticated_private = Reference (*i);
128                         }
129
130                         /* XXX: do something if we don't recognise the node */
131                 }
132         }
133
134         void as_xml (xmlpp::Element* node) const
135         {
136                 node->add_child ("CanonicalizationMethod", "ds")->set_attribute (
137                         "Algorithm", "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"
138                         );
139
140                 node->add_child ("SignatureMethod", "ds")->set_attribute (
141                         "Algorithm", "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
142                         );
143
144                 authenticated_public.as_xml (node->add_child ("Reference", "ds"));
145                 authenticated_private.as_xml (node->add_child ("Reference", "ds"));
146         }
147
148 private:
149         Reference authenticated_public;
150         Reference authenticated_private;
151 };
152
153 class Signature
154 {
155 public:
156         Signature () {}
157
158         Signature (shared_ptr<const cxml::Node> node)
159                 : signed_info (node->node_child ("SignedInfo"))
160                 , signature_value (node->string_child ("SignatureValue"))
161         {
162                 list<shared_ptr<cxml::Node> > x509_data_nodes = node->node_child("KeyInfo")->node_children ("X509Data");
163                 for (list<shared_ptr<cxml::Node> >::const_iterator i = x509_data_nodes.begin(); i != x509_data_nodes.end(); ++i) {
164                         x509_data.push_back (X509Data (*i));
165                 }
166         }
167
168         void as_xml (xmlpp::Node* node) const
169         {
170                 signed_info.as_xml (node->add_child ("SignedInfo", "ds"));
171                 node->add_child("SignatureValue", "ds")->add_child_text (signature_value);
172
173                 xmlpp::Element* key_info_node = node->add_child ("KeyInfo", "ds");
174                 for (std::list<X509Data>::const_iterator i = x509_data.begin(); i != x509_data.end(); ++i) {
175                         i->as_xml (key_info_node->add_child ("X509Data", "ds"));
176                 }
177         }
178
179         SignedInfo signed_info;
180         string signature_value;
181         list<X509Data> x509_data;
182 };
183
184 class AuthenticatedPrivate
185 {
186 public:
187         AuthenticatedPrivate () {}
188
189         AuthenticatedPrivate (shared_ptr<const cxml::Node> node)
190         {
191                 list<shared_ptr<cxml::Node> > encrypted_key_nodes = node->node_children ("EncryptedKey");
192                 for (list<shared_ptr<cxml::Node> >::const_iterator i = encrypted_key_nodes.begin(); i != encrypted_key_nodes.end(); ++i) {
193                         encrypted_key.push_back ((*i)->node_child("CipherData")->string_child ("CipherValue"));
194                 }
195         }
196
197         void as_xml (xmlpp::Element* node, map<string, xmlpp::Attribute *>& references) const
198         {
199                 references["ID_AuthenticatedPrivate"] = node->set_attribute ("Id", "ID_AuthenticatedPrivate");
200
201                 for (list<string>::const_iterator i = encrypted_key.begin(); i != encrypted_key.end(); ++i) {
202                         xmlpp::Element* encrypted_key = node->add_child ("EncryptedKey", "enc");
203                         xmlpp::Element* encryption_method = encrypted_key->add_child ("EncryptionMethod", "enc");
204                         encryption_method->set_attribute ("Algorithm", "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p");
205                         xmlpp::Element* digest_method = encryption_method->add_child ("DigestMethod", "ds");
206                         digest_method->set_attribute ("Algorithm", "http://www.w3.org/2000/09/xmldsig#sha1");
207                         xmlpp::Element* cipher_data = encrypted_key->add_child ("CipherData", "enc");
208                         cipher_data->add_child("CipherValue", "enc")->add_child_text (*i);
209                 }
210         }
211
212         list<string> encrypted_key;
213 };
214
215 class TypedKeyId
216 {
217 public:
218         TypedKeyId () {}
219
220         TypedKeyId (shared_ptr<const cxml::Node> node)
221                 : key_type (node->string_child ("KeyType"))
222                 , key_id (node->string_child ("KeyId").substr (9))
223         {
224
225         }
226
227         TypedKeyId (string type, string id)
228                 : key_type (type)
229                 , key_id (id)
230         {}
231
232         void as_xml (xmlpp::Element* node) const
233         {
234                 node->add_child("KeyType")->add_child_text (key_type);
235                 node->add_child("KeyId")->add_child_text ("urn:uuid:" + key_id);
236         }
237
238         string key_type;
239         string key_id;
240 };
241
242 class KeyIdList
243 {
244 public:
245         KeyIdList () {}
246
247         KeyIdList (shared_ptr<const cxml::Node> node)
248         {
249                 list<shared_ptr<cxml::Node> > typed_key_id_nodes = node->node_children ("TypedKeyId");
250                 for (list<shared_ptr<cxml::Node> >::const_iterator i = typed_key_id_nodes.begin(); i != typed_key_id_nodes.end(); ++i) {
251                         typed_key_id.push_back (TypedKeyId (*i));
252                 }
253         }
254
255         void as_xml (xmlpp::Element* node) const
256         {
257                 for (list<TypedKeyId>::const_iterator i = typed_key_id.begin(); i != typed_key_id.end(); ++i) {
258                         i->as_xml (node->add_child("TypedKeyId"));
259                 }
260         }
261
262         list<TypedKeyId> typed_key_id;
263 };
264
265 class AuthorizedDeviceInfo
266 {
267 public:
268         AuthorizedDeviceInfo () {}
269
270         AuthorizedDeviceInfo (shared_ptr<const cxml::Node> node)
271                 : device_list_identifier (node->string_child ("DeviceListIdentifier").substr (9))
272                 , device_list_description (node->optional_string_child ("DeviceListDescription"))
273                 , certificate_thumbprint (node->node_child("DeviceList")->string_child ("CertificateThumbprint"))
274         {
275
276         }
277
278         void as_xml (xmlpp::Element* node) const
279         {
280                 node->add_child ("DeviceListIdentifier")->add_child_text ("urn:uuid:" + device_list_identifier);
281                 if (device_list_description) {
282                         node->add_child ("DeviceListDescription")->add_child_text (device_list_description.get());
283                 }
284                 xmlpp::Element* device_list = node->add_child ("DeviceList");
285                 device_list->add_child("CertificateThumbprint")->add_child_text (certificate_thumbprint);
286         }
287
288         /** DeviceListIdentifier without the urn:uuid: prefix */
289         string device_list_identifier;
290         boost::optional<string> device_list_description;
291         string certificate_thumbprint;
292 };
293
294 class X509IssuerSerial
295 {
296 public:
297         X509IssuerSerial () {}
298
299         X509IssuerSerial (shared_ptr<const cxml::Node> node)
300                 : x509_issuer_name (node->string_child ("X509IssuerName"))
301                 , x509_serial_number (node->string_child ("X509SerialNumber"))
302         {
303
304         }
305
306         void as_xml (xmlpp::Element* node) const
307         {
308                 node->add_child("X509IssuerName", "ds")->add_child_text (x509_issuer_name);
309                 node->add_child("X509SerialNumber", "ds")->add_child_text (x509_serial_number);
310         }
311
312         string x509_issuer_name;
313         string x509_serial_number;
314 };
315
316 class Recipient
317 {
318 public:
319         Recipient () {}
320
321         Recipient (shared_ptr<const cxml::Node> node)
322                 : x509_issuer_serial (node->node_child ("X509IssuerSerial"))
323                 , x509_subject_name (node->string_child ("X509SubjectName"))
324         {
325
326         }
327
328         void as_xml (xmlpp::Element* node) const
329         {
330                 x509_issuer_serial.as_xml (node->add_child ("X509IssuerSerial"));
331                 node->add_child("X509SubjectName")->add_child_text (x509_subject_name);
332         }
333
334         X509IssuerSerial x509_issuer_serial;
335         string x509_subject_name;
336 };
337
338 class KDMRequiredExtensions
339 {
340 public:
341         KDMRequiredExtensions () {}
342
343         KDMRequiredExtensions (shared_ptr<const cxml::Node> node)
344                 : recipient (node->node_child ("Recipient"))
345                 , composition_playlist_id (node->string_child ("CompositionPlaylistId").substr (9))
346                 , content_title_text (node->string_child ("ContentTitleText"))
347                 , not_valid_before (node->string_child ("ContentKeysNotValidBefore"))
348                 , not_valid_after (node->string_child ("ContentKeysNotValidAfter"))
349                 , authorized_device_info (node->node_child ("AuthorizedDeviceInfo"))
350                 , key_id_list (node->node_child ("KeyIdList"))
351         {
352
353         }
354
355         void as_xml (xmlpp::Element* node) const
356         {
357                 node->set_attribute ("xmlns", "http://www.smpte-ra.org/schemas/430-1/2006/KDM");
358
359                 recipient.as_xml (node->add_child ("Recipient"));
360                 node->add_child("CompositionPlaylistId")->add_child_text ("urn:uuid:" + composition_playlist_id);
361                 if (content_authenticator) {
362                         node->add_child("ContentAuthenticator")->add_child_text (content_authenticator.get ());
363                 }
364                 node->add_child("ContentTitleText")->add_child_text (content_title_text);
365                 node->add_child("ContentKeysNotValidBefore")->add_child_text (not_valid_before.as_string ());
366                 node->add_child("ContentKeysNotValidAfter")->add_child_text (not_valid_after.as_string ());
367                 authorized_device_info.as_xml (node->add_child ("AuthorizedDeviceInfo"));
368                 key_id_list.as_xml (node->add_child ("KeyIdList"));
369
370                 xmlpp::Element* forensic_mark_flag_list = node->add_child ("ForensicMarkFlagList");
371                 forensic_mark_flag_list->add_child("ForensicMarkFlag")->add_child_text ("http://www.smpte-ra.org/430-1/2006/KDM#mrkflg-picture-disable");
372                 forensic_mark_flag_list->add_child("ForensicMarkFlag")->add_child_text ("http://www.smpte-ra.org/430-1/2006/KDM#mrkflg-audio-disable");
373         }
374
375         Recipient recipient;
376         string composition_playlist_id;
377         boost::optional<string> content_authenticator;
378         string content_title_text;
379         LocalTime not_valid_before;
380         LocalTime not_valid_after;
381         AuthorizedDeviceInfo authorized_device_info;
382         KeyIdList key_id_list;
383 };
384
385 class RequiredExtensions
386 {
387 public:
388         RequiredExtensions () {}
389
390         RequiredExtensions (shared_ptr<const cxml::Node> node)
391                 : kdm_required_extensions (node->node_child ("KDMRequiredExtensions"))
392         {
393
394         }
395
396         void as_xml (xmlpp::Element* node) const
397         {
398                 kdm_required_extensions.as_xml (node->add_child ("KDMRequiredExtensions"));
399         }
400
401         KDMRequiredExtensions kdm_required_extensions;
402 };
403
404 class AuthenticatedPublic
405 {
406 public:
407         AuthenticatedPublic ()
408                 : message_id (make_uuid ())
409                 , issue_date (LocalTime().as_string ())
410         {}
411
412         AuthenticatedPublic (shared_ptr<const cxml::Node> node)
413                 : message_id (node->string_child ("MessageId").substr (9))
414                 , annotation_text (node->string_child ("AnnotationText"))
415                 , issue_date (node->string_child ("IssueDate"))
416                 , signer (node->node_child ("Signer"))
417                 , required_extensions (node->node_child ("RequiredExtensions"))
418         {
419
420         }
421
422         void as_xml (xmlpp::Element* node, map<string, xmlpp::Attribute *>& references) const
423         {
424                 references["ID_AuthenticatedPublic"] = node->set_attribute ("Id", "ID_AuthenticatedPublic");
425
426                 node->add_child("MessageId")->add_child_text ("urn:uuid:" + message_id);
427                 node->add_child("MessageType")->add_child_text ("http://www.smpte-ra.org/430-1/2006/KDM#kdm-key-type");
428                 node->add_child("AnnotationText")->add_child_text (annotation_text);
429                 node->add_child("IssueDate")->add_child_text (issue_date);
430
431                 signer.as_xml (node->add_child ("Signer"));
432                 required_extensions.as_xml (node->add_child ("RequiredExtensions"));
433
434                 node->add_child ("NonCriticalExtensions");
435         }
436
437         string message_id;
438         string annotation_text;
439         string issue_date;
440         Signer signer;
441         RequiredExtensions required_extensions;
442 };
443
444 /** Class to describe our data.  We use a class hierarchy as it's a bit nicer
445  *  for XML data than a flat description.
446  */
447 class EncryptedKDMData
448 {
449 public:
450         EncryptedKDMData ()
451         {
452
453         }
454
455         EncryptedKDMData (shared_ptr<const cxml::Node> node)
456                 : authenticated_public (node->node_child ("AuthenticatedPublic"))
457                 , authenticated_private (node->node_child ("AuthenticatedPrivate"))
458                 , signature (node->node_child ("Signature"))
459         {
460
461         }
462
463         shared_ptr<xmlpp::Document> as_xml () const
464         {
465                 shared_ptr<xmlpp::Document> document (new xmlpp::Document ());
466                 xmlpp::Element* root = document->create_root_node ("DCinemaSecurityMessage", "http://www.smpte-ra.org/schemas/430-3/2006/ETM");
467                 root->set_namespace_declaration ("http://www.w3.org/2000/09/xmldsig#", "ds");
468                 root->set_namespace_declaration ("http://www.w3.org/2001/04/xmlenc#", "enc");
469                 map<string, xmlpp::Attribute *> references;
470                 authenticated_public.as_xml (root->add_child ("AuthenticatedPublic"), references);
471                 authenticated_private.as_xml (root->add_child ("AuthenticatedPrivate"), references);
472                 signature.as_xml (root->add_child ("Signature", "ds"));
473
474                 for (map<string, xmlpp::Attribute*>::const_iterator i = references.begin(); i != references.end(); ++i) {
475                         xmlAddID (0, document->cobj(), (const xmlChar *) i->first.c_str(), i->second->cobj ());
476                 }
477
478                 return document;
479         }
480
481         AuthenticatedPublic authenticated_public;
482         AuthenticatedPrivate authenticated_private;
483         Signature signature;
484 };
485
486 }
487 }
488
489 EncryptedKDM::EncryptedKDM (string s)
490 {
491         shared_ptr<cxml::Document> doc (new cxml::Document ("DCinemaSecurityMessage"));
492         doc->read_string (s);
493         _data = new data::EncryptedKDMData (doc);
494 }
495
496 EncryptedKDM::EncryptedKDM (
497         shared_ptr<const CertificateChain> signer,
498         Certificate recipient,
499         string device_list_description,
500         string cpl_id,
501         string content_title_text,
502         LocalTime not_valid_before,
503         LocalTime not_valid_after,
504         Formulation formulation,
505         list<pair<string, string> > key_ids,
506         list<string> keys
507         )
508         : _data (new data::EncryptedKDMData)
509 {
510         /* Fill our XML-ish description in with the juicy bits that the caller has given */
511
512         data::AuthenticatedPublic& aup = _data->authenticated_public;
513         aup.signer.x509_issuer_name = signer->leaf().issuer ();
514         aup.signer.x509_serial_number = signer->leaf().serial ();
515
516         data::KDMRequiredExtensions& kre = _data->authenticated_public.required_extensions.kdm_required_extensions;
517         kre.recipient.x509_issuer_serial.x509_issuer_name = recipient.issuer ();
518         kre.recipient.x509_issuer_serial.x509_serial_number = recipient.serial ();
519         kre.recipient.x509_subject_name = recipient.subject ();
520         kre.authorized_device_info.device_list_description = device_list_description;
521         kre.composition_playlist_id = cpl_id;
522         if (formulation == DCI_ANY || formulation == DCI_SPECIFIC) {
523                 kre.content_authenticator = signer->leaf().thumbprint ();
524         }
525         kre.content_title_text = content_title_text;
526         kre.not_valid_before = not_valid_before;
527         kre.not_valid_after = not_valid_after;
528         kre.authorized_device_info.device_list_identifier = make_uuid ();
529         string n = recipient.subject_common_name ();
530         if (n.find (".") != string::npos) {
531                 n = n.substr (n.find (".") + 1);
532         }
533         kre.authorized_device_info.device_list_description = n;
534
535         if (formulation == MODIFIED_TRANSITIONAL_1 || formulation == DCI_ANY) {
536                 /* Use the "assume trust" thumbprint */
537                 kre.authorized_device_info.certificate_thumbprint = "2jmj7l5rSw0yVb/vlWAYkK/YBwk=";
538         } else if (formulation == DCI_SPECIFIC) {
539                 /* Use the recipient thumbprint */
540                 kre.authorized_device_info.certificate_thumbprint = recipient.thumbprint ();
541         }
542
543         for (list<pair<string, string> >::const_iterator i = key_ids.begin(); i != key_ids.end(); ++i) {
544                 kre.key_id_list.typed_key_id.push_back (data::TypedKeyId (i->first, i->second));
545         }
546
547         _data->authenticated_private.encrypted_key = keys;
548
549         /* Read the XML so far and sign it */
550         shared_ptr<xmlpp::Document> doc = _data->as_xml ();
551         xmlpp::Node::NodeList children = doc->get_root_node()->get_children ();
552         for (xmlpp::Node::NodeList::const_iterator i = children.begin(); i != children.end(); ++i) {
553                 if ((*i)->get_name() == "Signature") {
554                         signer->add_signature_value (*i, "ds");
555                 }
556         }
557
558         /* Read the bits that add_signature_value did back into our variables */
559         shared_ptr<cxml::Node> signed_doc (new cxml::Node (doc->get_root_node ()));
560         _data->signature = data::Signature (signed_doc->node_child ("Signature"));
561 }
562
563 EncryptedKDM::EncryptedKDM (EncryptedKDM const & other)
564         : _data (new data::EncryptedKDMData (*other._data))
565 {
566
567 }
568
569 EncryptedKDM &
570 EncryptedKDM::operator= (EncryptedKDM const & other)
571 {
572         if (this == &other) {
573                 return *this;
574         }
575
576         delete _data;
577         _data = new data::EncryptedKDMData (*other._data);
578         return *this;
579 }
580
581 EncryptedKDM::~EncryptedKDM ()
582 {
583         delete _data;
584 }
585
586 void
587 EncryptedKDM::as_xml (boost::filesystem::path path) const
588 {
589         FILE* f = fopen_boost (path, "w");
590         string const x = as_xml ();
591         fwrite (x.c_str(), 1, x.length(), f);
592         fclose (f);
593 }
594
595 string
596 EncryptedKDM::as_xml () const
597 {
598         xmlpp::Document document;
599         xmlpp::Element* root = document.create_root_node ("DCinemaSecurityMessage", "http://www.smpte-ra.org/schemas/430-3/2006/ETM");
600         root->set_namespace_declaration ("http://www.w3.org/2000/09/xmldsig#", "ds");
601         root->set_namespace_declaration ("http://www.w3.org/2001/04/xmlenc#", "enc");
602
603         return _data->as_xml()->write_to_string ("UTF-8");
604 }
605
606 list<string>
607 EncryptedKDM::keys () const
608 {
609         return _data->authenticated_private.encrypted_key;
610 }