fix(msl): Broken imports
[plugin.video.netflix.git] / resources / lib / MSL.py
1 import base64
2 import gzip
3 import json
4 import os
5 import pprint
6 import random
7 from StringIO import StringIO
8 from hmac import HMAC
9 import hashlib
10 import requests
11 import zlib
12
13 import time
14 from Crypto.PublicKey import RSA
15 from Crypto.Cipher import PKCS1_OAEP
16 from Crypto.Cipher import AES
17 from Crypto.Random import get_random_bytes
18 # from Crypto.Hash import HMAC, SHA256
19 from Crypto.Util import Padding
20 import xml.etree.ElementTree as ET
21
22 pp = pprint.PrettyPrinter(indent=4)
23
24 def base64key_decode(payload):
25     l = len(payload) % 4
26     if l == 2:
27         payload += '=='
28     elif l == 3:
29         payload += '='
30     elif l != 0:
31         raise ValueError('Invalid base64 string')
32     return base64.urlsafe_b64decode(payload.encode('utf-8'))
33
34
35 class MSL:
36     handshake_performed = False  # Is a handshake already performed and the keys loaded
37     last_drm_context = ''
38     last_playback_context = ''
39     #esn = "NFCDCH-LX-CQE0NU6PA5714R25VPLXVU2A193T36"
40     esn = "WWW-BROWSE-D7GW1G4NPXGR1F0X1H3EQGY3V1F5WE"
41     current_message_id = 0
42     session = requests.session()
43     rndm = random.SystemRandom()
44     tokens = []
45     endpoints = {
46         'manifest': 'http://www.netflix.com/api/msl/NFCDCH-LX/cadmium/manifest',
47         'license': 'http://www.netflix.com/api/msl/NFCDCH-LX/cadmium/license'
48     }
49
50     def __init__(self, email, password, kodi_helper):
51         """
52         The Constructor checks for already existing crypto Keys.
53         If they exist it will load the existing keys
54         """
55         self.email = email
56         self.password = password
57         self.kodi_helper = kodi_helper
58         try:
59             os.mkdir(self.kodi_helper.msl_data_path)
60         except OSError:
61             pass
62
63         if self.file_exists(self.kodi_helper.msl_data_path, 'msl_data.json'):
64             self.__load_msl_data()
65             self.handshake_performed = True
66         elif self.file_exists(self.kodi_helper.msl_data_path, 'rsa_key.bin'):
67             self.kodi_helper.log(msg='RSA Keys do already exist load old ones')
68             self.__load_rsa_keys()
69             self.__perform_key_handshake()
70         else:
71             self.kodi_helper.log(msg='Create new RSA Keys')
72             # Create new Key Pair and save
73             self.rsa_key = RSA.generate(2048)
74             self.__save_rsa_keys()
75             self.__perform_key_handshake()
76
77     def load_manifest(self, viewable_id):
78         manifest_request_data = {
79             'method': 'manifest',
80             'lookupType': 'PREPARE',
81             'viewableIds': [viewable_id],
82             'profiles': [
83                 'playready-h264mpl30-dash',
84                 'playready-h264mpl31-dash',
85                 'heaac-2-dash',
86                 'dfxp-ls-sdh',
87                 'simplesdh',
88                 'nflx-cmisc',
89                 'BIF240',
90                 'BIF320'
91             ],
92             'drmSystem': 'widevine',
93             'appId': '14673889385265',
94             'sessionParams': {
95                 'pinCapableClient': False,
96                 'uiplaycontext': 'null'
97             },
98             'sessionId': '14673889385265',
99             'trackId': 0,
100             'flavor': 'PRE_FETCH',
101             'secureUrls': False,
102             'supportPreviewContent': True,
103             'forceClearStreams': False,
104             'languages': ['de-DE'],
105             'clientVersion': '4.0004.899.011',
106             'uiVersion': 'akira'
107         }
108         request_data = self.__generate_msl_request_data(manifest_request_data)
109
110         resp = self.session.post(self.endpoints['manifest'], request_data)
111
112
113         try:
114             resp.json()
115             self.kodi_helper.log(msg='MANIFEST RESPONE JSON: '+resp.text)
116         except ValueError:
117             # Maybe we have a CHUNKED response
118             resp = self.__parse_chunked_msl_response(resp.text)
119             data = self.__decrypt_payload_chunk(resp['payloads'][0])
120             # pprint.pprint(data)
121             return self.__tranform_to_dash(data)
122
123
124     def get_license(self, challenge, sid):
125
126         """
127             std::time_t t = std::time(0);  // t is an integer type
128     licenseRequestData["clientTime"] = (int)t;
129     //licenseRequestData["challengeBase64"] = challengeStr;
130     licenseRequestData["licenseType"] = "STANDARD";
131     licenseRequestData["playbackContextId"] = playbackContextId;//"E1-BQFRAAELEB32o6Se-GFvjwEIbvDydEtfj6zNzEC3qwfweEPAL3gTHHT2V8rS_u1Mc3mw5BWZrUlKYIu4aArdjN8z_Z8t62E5jRjLMdCKMsVhlSJpiQx0MNW4aGqkYz-1lPh85Quo4I_mxVBG5lgd166B5NDizA8.";
132     licenseRequestData["drmContextIds"] = Json::arrayValue;
133     licenseRequestData["drmContextIds"].append(drmContextId);
134
135         :param viewable_id:
136         :param challenge:
137         :param kid:
138         :return:
139         """
140
141         license_request_data = {
142             'method': 'license',
143             'licenseType': 'STANDARD',
144             'clientVersion': '4.0004.899.011',
145             'uiVersion': 'akira',
146             'languages': ['de-DE'],
147             'playbackContextId': self.last_playback_context,
148             'drmContextIds': [self.last_drm_context],
149             'challenges': [{
150                 'dataBase64': challenge,
151                 'sessionId': sid
152             }],
153             'clientTime': int(time.time()),
154             'xid': int((int(time.time()) + 0.1612) * 1000)
155
156         }
157         request_data = self.__generate_msl_request_data(license_request_data)
158
159         resp = self.session.post(self.endpoints['license'], request_data)
160
161         try:
162             resp.json()
163             self.kodi_helper.log(msg='LICENSE RESPONE JSON: '+resp.text)
164         except ValueError:
165             # Maybe we have a CHUNKED response
166             resp = self.__parse_chunked_msl_response(resp.text)
167             data = self.__decrypt_payload_chunk(resp['payloads'][0])
168             # pprint.pprint(data)
169             if data['success'] is True:
170                 return data['result']['licenses'][0]['data']
171             else:
172                 return ''
173
174
175     def __decrypt_payload_chunk(self, payloadchunk):
176         payloadchunk = json.JSONDecoder().decode(payloadchunk)
177         encryption_envelope = json.JSONDecoder().decode(base64.standard_b64decode(payloadchunk['payload']))
178         # Decrypt the text
179         cipher = AES.new(self.encryption_key, AES.MODE_CBC, base64.standard_b64decode(encryption_envelope['iv']))
180         plaintext = cipher.decrypt(base64.standard_b64decode(encryption_envelope['ciphertext']))
181         # unpad the plaintext
182         plaintext = json.JSONDecoder().decode(Padding.unpad(plaintext, 16))
183         data = plaintext['data']
184
185         # uncompress data if compressed
186         if plaintext['compressionalgo'] == 'GZIP':
187             data = zlib.decompress(base64.standard_b64decode(data), 16 + zlib.MAX_WBITS)
188         else:
189             data = base64.standard_b64decode(data)
190
191         data = json.JSONDecoder().decode(data)[1]['payload']['data']
192         data = base64.standard_b64decode(data)
193         return json.JSONDecoder().decode(data)
194
195
196     def __tranform_to_dash(self, manifest):
197
198         self.save_file(self.kodi_helper.msl_data_path, 'manifest.json', json.dumps(manifest))
199         manifest = manifest['result']['viewables'][0]
200
201         self.last_playback_context = manifest['playbackContextId']
202         self.last_drm_context = manifest['drmContextId']
203
204         #Check for pssh
205         pssh = ''
206         if 'psshb64' in manifest:
207             if len(manifest['psshb64']) >= 1:
208                 pssh = manifest['psshb64'][0]
209
210
211
212         root = ET.Element('MPD')
213         root.attrib['xmlns'] = 'urn:mpeg:dash:schema:mpd:2011'
214         root.attrib['xmlns:cenc'] = 'urn:mpeg:cenc:2013'
215
216
217         seconds = manifest['runtime']/1000
218         duration = "PT"+str(seconds)+".00S"
219
220         period = ET.SubElement(root, 'Period', start='PT0S', duration=duration)
221
222         # One Adaption Set for Video
223         for video_track in manifest['videoTracks']:
224             video_adaption_set = ET.SubElement(period, 'AdaptationSet', mimeType='video/mp4', contentType="video")
225             # Content Protection
226             protection = ET.SubElement(video_adaption_set, 'ContentProtection',
227                           schemeIdUri='urn:uuid:EDEF8BA9-79D6-4ACE-A3C8-27DCD51D21ED')
228             if pssh is not '':
229                 ET.SubElement(protection, 'cenc:pssh').text = pssh
230
231             for downloadable in video_track['downloadables']:
232                 rep = ET.SubElement(video_adaption_set, 'Representation',
233                                     width=str(downloadable['width']),
234                                     height=str(downloadable['height']),
235                                     bandwidth=str(downloadable['bitrate']*1024),
236                                     codecs='h264',
237                                     mimeType='video/mp4')
238
239                 #BaseURL
240                 ET.SubElement(rep, 'BaseURL').text = self.__get_base_url(downloadable['urls'])
241                 # Init an Segment block
242                 segment_base = ET.SubElement(rep, 'SegmentBase', indexRange="0-60000", indexRangeExact="true")
243                 ET.SubElement(segment_base, 'Initialization', range='0-60000')
244
245
246
247         # Multiple Adaption Set for audio
248         for audio_track in manifest['audioTracks']:
249             audio_adaption_set = ET.SubElement(period, 'AdaptationSet',
250                                                lang=audio_track['bcp47'],
251                                                contentType='audio',
252                                                mimeType='audio/mp4')
253             for downloadable in audio_track['downloadables']:
254                 rep = ET.SubElement(audio_adaption_set, 'Representation',
255                                     codecs='aac',
256                                     bandwidth=str(downloadable['bitrate']*1024),
257                                     mimeType='audio/mp4')
258
259                 #AudioChannel Config
260                 ET.SubElement(rep, 'AudioChannelConfiguration',
261                               schemeIdUri='urn:mpeg:dash:23003:3:audio_channel_configuration:2011',
262                               value=str(audio_track['channelsCount']))
263
264                 #BaseURL
265                 ET.SubElement(rep, 'BaseURL').text = self.__get_base_url(downloadable['urls'])
266                 # Index range
267                 segment_base = ET.SubElement(rep, 'SegmentBase', indexRange="0-60000", indexRangeExact="true")
268                 ET.SubElement(segment_base, 'Initialization', range='0-60000')
269
270
271         xml = ET.tostring(root, encoding='utf-8', method='xml')
272         xml = xml.replace('\n', '').replace('\r', '')
273         return xml
274
275     def __get_base_url(self, urls):
276         for key in urls:
277             return urls[key]
278
279     def __parse_chunked_msl_response(self, message):
280         i = 0
281         opencount = 0
282         closecount = 0
283         header = ""
284         payloads = []
285         old_end = 0
286
287         while i < len(message):
288             if message[i] == '{':
289                 opencount = opencount + 1
290             if message[i] == '}':
291                 closecount = closecount + 1
292             if opencount == closecount:
293                 if header == "":
294                     header = message[:i]
295                     old_end = i + 1
296                 else:
297                     payloads.append(message[old_end:i + 1])
298             i += 1
299
300         return {
301             'header': header,
302             'payloads': payloads
303         }
304
305     def __generate_msl_request_data(self, data):
306         header_encryption_envelope = self.__encrypt(self.__generate_msl_header())
307         header = {
308             'headerdata': base64.standard_b64encode(header_encryption_envelope),
309             'signature': self.__sign(header_encryption_envelope),
310             'mastertoken': self.mastertoken,
311         }
312
313         # Serialize the given Data
314         serialized_data = json.dumps(data)
315         serialized_data = serialized_data.replace('"', '\\"')
316         serialized_data = '[{},{"headers":{},"path":"/cbp/cadmium-11","payload":{"data":"' + serialized_data + '"},"query":""}]\n'
317
318         compressed_data = self.__compress_data(serialized_data)
319
320         # Create FIRST Payload Chunks
321         first_payload = {
322             "messageid": self.current_message_id,
323             "data": compressed_data,
324             "compressionalgo": "GZIP",
325             "sequencenumber": 1,
326             "endofmsg": True
327         }
328         first_payload_encryption_envelope = self.__encrypt(json.dumps(first_payload))
329         first_payload_chunk = {
330             'payload': base64.standard_b64encode(first_payload_encryption_envelope),
331             'signature': self.__sign(first_payload_encryption_envelope),
332         }
333
334
335         # Create Second Payload
336         second_payload = {
337             "messageid": self.current_message_id,
338             "data": "",
339             "endofmsg": True,
340             "sequencenumber": 2
341         }
342         second_payload_encryption_envelope = self.__encrypt(json.dumps(second_payload))
343         second_payload_chunk = {
344             'payload': base64.standard_b64encode(second_payload_encryption_envelope),
345             'signature': base64.standard_b64encode(self.__sign(second_payload_encryption_envelope)),
346         }
347
348         request_data = json.dumps(header) + json.dumps(first_payload_chunk) # + json.dumps(second_payload_chunk)
349         return request_data
350
351
352
353     def __compress_data(self, data):
354         # GZIP THE DATA
355         out = StringIO()
356         with gzip.GzipFile(fileobj=out, mode="w") as f:
357             f.write(data)
358         return base64.standard_b64encode(out.getvalue())
359
360
361     def __generate_msl_header(self, is_handshake=False, is_key_request=False, compressionalgo="GZIP", encrypt=True):
362         """
363         Function that generates a MSL header dict
364         :return: The base64 encoded JSON String of the header
365         """
366         self.current_message_id = self.rndm.randint(0, pow(2, 52))
367
368         header_data = {
369             'sender': self.esn,
370             'handshake': is_handshake,
371             'nonreplayable': False,
372             'capabilities': {
373                 'languages': ["en-US"],
374                 'compressionalgos': []
375             },
376             'recipient': 'Netflix',
377             'renewable': True,
378             'messageid': self.current_message_id,
379             'timestamp': 1467733923
380         }
381
382         # Add compression algo if not empty
383         if compressionalgo is not "":
384             header_data['capabilities']['compressionalgos'].append(compressionalgo)
385
386         # If this is a keyrequest act diffrent then other requests
387         if is_key_request:
388             public_key = base64.standard_b64encode(self.rsa_key.publickey().exportKey(format='DER'))
389             header_data['keyrequestdata'] = [{
390                 'scheme': 'ASYMMETRIC_WRAPPED',
391                 'keydata': {
392                     'publickey': public_key,
393                     'mechanism': 'JWK_RSA',
394                     'keypairid': 'superKeyPair'
395                 }
396             }]
397         else:
398             if 'usertoken' in self.tokens:
399                 pass
400             else:
401                 # Auth via email and password
402                 header_data['userauthdata'] = {
403                     'scheme': 'EMAIL_PASSWORD',
404                     'authdata': {
405                         'email': self.email,
406                         'password': self.password
407                     }
408                 }
409
410         return json.dumps(header_data)
411
412
413
414     def __encrypt(self, plaintext):
415         """
416         Encrypt the given Plaintext with the encryption key
417         :param plaintext:
418         :return: Serialized JSON String of the encryption Envelope
419         """
420         iv = get_random_bytes(16)
421         encryption_envelope = {
422             'ciphertext': '',
423             'keyid': self.esn + '_' + str(self.sequence_number),
424             'sha256': 'AA==',
425             'iv': base64.standard_b64encode(iv)
426         }
427         # Padd the plaintext
428         plaintext = Padding.pad(plaintext, 16)
429         # Encrypt the text
430         cipher = AES.new(self.encryption_key, AES.MODE_CBC, iv)
431         ciphertext = cipher.encrypt(plaintext)
432         encryption_envelope['ciphertext'] = base64.standard_b64encode(ciphertext)
433         return json.dumps(encryption_envelope)
434
435     def __sign(self, text):
436         #signature = hmac.new(self.sign_key, text, hashlib.sha256).digest()
437         signature = HMAC(self.sign_key, text, hashlib.sha256).digest()
438
439
440         # hmac = HMAC.new(self.sign_key, digestmod=SHA256)
441         # hmac.update(text)
442         return base64.standard_b64encode(signature)
443
444
445     def __perform_key_handshake(self):
446
447         header = self.__generate_msl_header(is_key_request=True, is_handshake=True, compressionalgo="", encrypt=False)
448         request = {
449             'entityauthdata': {
450                 'scheme': 'NONE',
451                 'authdata': {
452                     'identity': self.esn
453                 }
454             },
455             'headerdata': base64.standard_b64encode(header),
456             'signature': '',
457         }
458         self.kodi_helper.log(msg='Key Handshake Request:')
459         self.kodi_helper.log(msg=json.dumps(request))
460
461
462         resp = self.session.post(self.endpoints['manifest'], json.dumps(request, sort_keys=True))
463         if resp.status_code == 200:
464             resp = resp.json()
465             if 'errordata' in resp:
466                 self.kodi_helper.log(msg='Key Exchange failed')
467                 self.kodi_helper.log(msg=base64.standard_b64decode(resp['errordata']))
468                 return False
469             self.__parse_crypto_keys(json.JSONDecoder().decode(base64.standard_b64decode(resp['headerdata'])))
470         else:
471             self.kodi_helper.log(msg='Key Exchange failed')
472             self.kodi_helper.log(msg=resp.text)
473
474     def __parse_crypto_keys(self, headerdata):
475         self.__set_master_token(headerdata['keyresponsedata']['mastertoken'])
476         # Init Decryption
477         encrypted_encryption_key = base64.standard_b64decode(headerdata['keyresponsedata']['keydata']['encryptionkey'])
478         encrypted_sign_key = base64.standard_b64decode(headerdata['keyresponsedata']['keydata']['hmackey'])
479         cipher_rsa = PKCS1_OAEP.new(self.rsa_key)
480
481         # Decrypt encryption key
482         encryption_key_data = json.JSONDecoder().decode(cipher_rsa.decrypt(encrypted_encryption_key))
483         self.encryption_key = base64key_decode(encryption_key_data['k'])
484
485         # Decrypt sign key
486         sign_key_data = json.JSONDecoder().decode(cipher_rsa.decrypt(encrypted_sign_key))
487         self.sign_key = base64key_decode(sign_key_data['k'])
488
489         self.__save_msl_data()
490         self.handshake_performed = True
491
492     def __load_msl_data(self):
493         msl_data = json.JSONDecoder().decode(self.load_file(self.kodi_helper.msl_data_path, 'msl_data.json'))
494         self.__set_master_token(msl_data['tokens']['mastertoken'])
495         self.encryption_key = base64.standard_b64decode(msl_data['encryption_key'])
496         self.sign_key = base64.standard_b64decode(msl_data['sign_key'])
497
498     def __save_msl_data(self):
499         """
500         Saves the keys and tokens in json file
501         :return:
502         """
503         data = {
504             "encryption_key": base64.standard_b64encode(self.encryption_key),
505             'sign_key': base64.standard_b64encode(self.sign_key),
506             'tokens': {
507                 'mastertoken': self.mastertoken
508             }
509         }
510         serialized_data = json.JSONEncoder().encode(data)
511         self.save_file(self.kodi_helper.msl_data_path, 'msl_data.json', serialized_data)
512
513     def __set_master_token(self, master_token):
514         self.mastertoken = master_token
515         self.sequence_number = json.JSONDecoder().decode(base64.standard_b64decode(master_token['tokendata']))[
516             'sequencenumber']
517
518     def __load_rsa_keys(self):
519         loaded_key = self.load_file(self.kodi_helper.msl_data_path, 'rsa_key.bin')
520         self.rsa_key = RSA.importKey(loaded_key)
521
522     def __save_rsa_keys(self):
523         self.kodi_helper.log(msg='Save RSA Keys')
524         # Get the DER Base64 of the keys
525         encrypted_key = self.rsa_key.exportKey()
526         self.save_file(self.kodi_helper.msl_data_path, 'rsa_key.bin', encrypted_key)
527
528     @staticmethod
529     def file_exists(msl_data_path, filename):
530         """
531         Checks if a given file exists
532         :param filename: The filename
533         :return: True if so
534         """
535         return os.path.isfile(msl_data_path + filename)
536
537     @staticmethod
538     def save_file(msl_data_path, filename, content):
539         """
540         Saves the given content under given filename
541         :param filename: The filename
542         :param content: The content of the file
543         """
544         with open(msl_data_path + filename, 'w') as file_:
545             file_.write(content)
546             file_.flush()
547
548     @staticmethod
549     def load_file(msl_data_path, filename):
550         """
551         Loads the content of a given filename
552         :param filename: The file to load
553         :return: The content of the file
554         """
555         with open(msl_data_path + filename) as file_:
556             file_content = file_.read()
557         return file_content