7 from StringIO import StringIO
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
22 pp = pprint.PrettyPrinter(indent=4)
24 def base64key_decode(payload):
31 raise ValueError('Invalid base64 string')
32 return base64.urlsafe_b64decode(payload.encode('utf-8'))
36 handshake_performed = False # Is a handshake already performed and the keys loaded
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()
46 'manifest': 'http://www.netflix.com/api/msl/NFCDCH-LX/cadmium/manifest',
47 'license': 'http://www.netflix.com/api/msl/NFCDCH-LX/cadmium/license'
50 def __init__(self, email, password, kodi_helper):
52 The Constructor checks for already existing crypto Keys.
53 If they exist it will load the existing keys
56 self.password = password
57 self.kodi_helper = kodi_helper
59 os.mkdir(self.kodi_helper.msl_data_path)
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()
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()
77 def load_manifest(self, viewable_id):
78 manifest_request_data = {
80 'lookupType': 'PREPARE',
81 'viewableIds': [viewable_id],
83 'playready-h264mpl30-dash',
84 'playready-h264mpl31-dash',
92 'drmSystem': 'widevine',
93 'appId': '14673889385265',
95 'pinCapableClient': False,
96 'uiplaycontext': 'null'
98 'sessionId': '14673889385265',
100 'flavor': 'PRE_FETCH',
102 'supportPreviewContent': True,
103 'forceClearStreams': False,
104 'languages': ['de-DE'],
105 'clientVersion': '4.0004.899.011',
108 request_data = self.__generate_msl_request_data(manifest_request_data)
110 resp = self.session.post(self.endpoints['manifest'], request_data)
115 self.kodi_helper.log(msg='MANIFEST RESPONE JSON: '+resp.text)
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)
124 def get_license(self, challenge, sid):
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);
141 license_request_data = {
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],
150 'dataBase64': challenge,
153 'clientTime': int(time.time()),
154 'xid': int((int(time.time()) + 0.1612) * 1000)
157 request_data = self.__generate_msl_request_data(license_request_data)
159 resp = self.session.post(self.endpoints['license'], request_data)
163 self.kodi_helper.log(msg='LICENSE RESPONE JSON: '+resp.text)
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']
175 def __decrypt_payload_chunk(self, payloadchunk):
176 payloadchunk = json.JSONDecoder().decode(payloadchunk)
177 encryption_envelope = json.JSONDecoder().decode(base64.standard_b64decode(payloadchunk['payload']))
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']
185 # uncompress data if compressed
186 if plaintext['compressionalgo'] == 'GZIP':
187 data = zlib.decompress(base64.standard_b64decode(data), 16 + zlib.MAX_WBITS)
189 data = base64.standard_b64decode(data)
191 data = json.JSONDecoder().decode(data)[1]['payload']['data']
192 data = base64.standard_b64decode(data)
193 return json.JSONDecoder().decode(data)
196 def __tranform_to_dash(self, manifest):
198 self.save_file(self.kodi_helper.msl_data_path, 'manifest.json', json.dumps(manifest))
199 manifest = manifest['result']['viewables'][0]
201 self.last_playback_context = manifest['playbackContextId']
202 self.last_drm_context = manifest['drmContextId']
206 if 'psshb64' in manifest:
207 if len(manifest['psshb64']) >= 1:
208 pssh = manifest['psshb64'][0]
212 root = ET.Element('MPD')
213 root.attrib['xmlns'] = 'urn:mpeg:dash:schema:mpd:2011'
214 root.attrib['xmlns:cenc'] = 'urn:mpeg:cenc:2013'
217 seconds = manifest['runtime']/1000
218 duration = "PT"+str(seconds)+".00S"
220 period = ET.SubElement(root, 'Period', start='PT0S', duration=duration)
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")
226 protection = ET.SubElement(video_adaption_set, 'ContentProtection',
227 schemeIdUri='urn:uuid:EDEF8BA9-79D6-4ACE-A3C8-27DCD51D21ED')
229 ET.SubElement(protection, 'cenc:pssh').text = pssh
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),
237 mimeType='video/mp4')
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')
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'],
252 mimeType='audio/mp4')
253 for downloadable in audio_track['downloadables']:
254 rep = ET.SubElement(audio_adaption_set, 'Representation',
256 bandwidth=str(downloadable['bitrate']*1024),
257 mimeType='audio/mp4')
260 ET.SubElement(rep, 'AudioChannelConfiguration',
261 schemeIdUri='urn:mpeg:dash:23003:3:audio_channel_configuration:2011',
262 value=str(audio_track['channelsCount']))
265 ET.SubElement(rep, 'BaseURL').text = self.__get_base_url(downloadable['urls'])
267 segment_base = ET.SubElement(rep, 'SegmentBase', indexRange="0-60000", indexRangeExact="true")
268 ET.SubElement(segment_base, 'Initialization', range='0-60000')
271 xml = ET.tostring(root, encoding='utf-8', method='xml')
272 xml = xml.replace('\n', '').replace('\r', '')
275 def __get_base_url(self, urls):
279 def __parse_chunked_msl_response(self, message):
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:
297 payloads.append(message[old_end:i + 1])
305 def __generate_msl_request_data(self, data):
306 header_encryption_envelope = self.__encrypt(self.__generate_msl_header())
308 'headerdata': base64.standard_b64encode(header_encryption_envelope),
309 'signature': self.__sign(header_encryption_envelope),
310 'mastertoken': self.mastertoken,
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'
318 compressed_data = self.__compress_data(serialized_data)
320 # Create FIRST Payload Chunks
322 "messageid": self.current_message_id,
323 "data": compressed_data,
324 "compressionalgo": "GZIP",
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),
335 # Create Second Payload
337 "messageid": self.current_message_id,
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)),
348 request_data = json.dumps(header) + json.dumps(first_payload_chunk) # + json.dumps(second_payload_chunk)
353 def __compress_data(self, data):
356 with gzip.GzipFile(fileobj=out, mode="w") as f:
358 return base64.standard_b64encode(out.getvalue())
361 def __generate_msl_header(self, is_handshake=False, is_key_request=False, compressionalgo="GZIP", encrypt=True):
363 Function that generates a MSL header dict
364 :return: The base64 encoded JSON String of the header
366 self.current_message_id = self.rndm.randint(0, pow(2, 52))
370 'handshake': is_handshake,
371 'nonreplayable': False,
373 'languages': ["en-US"],
374 'compressionalgos': []
376 'recipient': 'Netflix',
378 'messageid': self.current_message_id,
379 'timestamp': 1467733923
382 # Add compression algo if not empty
383 if compressionalgo is not "":
384 header_data['capabilities']['compressionalgos'].append(compressionalgo)
386 # If this is a keyrequest act diffrent then other requests
388 public_key = base64.standard_b64encode(self.rsa_key.publickey().exportKey(format='DER'))
389 header_data['keyrequestdata'] = [{
390 'scheme': 'ASYMMETRIC_WRAPPED',
392 'publickey': public_key,
393 'mechanism': 'JWK_RSA',
394 'keypairid': 'superKeyPair'
398 if 'usertoken' in self.tokens:
401 # Auth via email and password
402 header_data['userauthdata'] = {
403 'scheme': 'EMAIL_PASSWORD',
406 'password': self.password
410 return json.dumps(header_data)
414 def __encrypt(self, plaintext):
416 Encrypt the given Plaintext with the encryption key
418 :return: Serialized JSON String of the encryption Envelope
420 iv = get_random_bytes(16)
421 encryption_envelope = {
423 'keyid': self.esn + '_' + str(self.sequence_number),
425 'iv': base64.standard_b64encode(iv)
428 plaintext = Padding.pad(plaintext, 16)
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)
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()
440 # hmac = HMAC.new(self.sign_key, digestmod=SHA256)
442 return base64.standard_b64encode(signature)
445 def __perform_key_handshake(self):
447 header = self.__generate_msl_header(is_key_request=True, is_handshake=True, compressionalgo="", encrypt=False)
455 'headerdata': base64.standard_b64encode(header),
458 self.kodi_helper.log(msg='Key Handshake Request:')
459 self.kodi_helper.log(msg=json.dumps(request))
462 resp = self.session.post(self.endpoints['manifest'], json.dumps(request, sort_keys=True))
463 if resp.status_code == 200:
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']))
469 self.__parse_crypto_keys(json.JSONDecoder().decode(base64.standard_b64decode(resp['headerdata'])))
471 self.kodi_helper.log(msg='Key Exchange failed')
472 self.kodi_helper.log(msg=resp.text)
474 def __parse_crypto_keys(self, headerdata):
475 self.__set_master_token(headerdata['keyresponsedata']['mastertoken'])
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)
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'])
486 sign_key_data = json.JSONDecoder().decode(cipher_rsa.decrypt(encrypted_sign_key))
487 self.sign_key = base64key_decode(sign_key_data['k'])
489 self.__save_msl_data()
490 self.handshake_performed = True
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'])
498 def __save_msl_data(self):
500 Saves the keys and tokens in json file
504 "encryption_key": base64.standard_b64encode(self.encryption_key),
505 'sign_key': base64.standard_b64encode(self.sign_key),
507 'mastertoken': self.mastertoken
510 serialized_data = json.JSONEncoder().encode(data)
511 self.save_file(self.kodi_helper.msl_data_path, 'msl_data.json', serialized_data)
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']))[
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)
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)
529 def file_exists(msl_data_path, filename):
531 Checks if a given file exists
532 :param filename: The filename
535 return os.path.isfile(msl_data_path + filename)
538 def save_file(msl_data_path, filename, content):
540 Saves the given content under given filename
541 :param filename: The filename
542 :param content: The content of the file
544 with open(msl_data_path + filename, 'w') as file_:
549 def load_file(msl_data_path, filename):
551 Loads the content of a given filename
552 :param filename: The file to load
553 :return: The content of the file
555 with open(msl_data_path + filename) as file_:
556 file_content = file_.read()