-
Notifications
You must be signed in to change notification settings - Fork 0
/
NFAuthenticationKey.py
316 lines (276 loc) · 12.6 KB
/
NFAuthenticationKey.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# -*- coding: utf-8 -*-
"""
Copyright (C) 2020 Stefano Gottardo
SPDX-License-Identifier: GPL-3.0-only
See LICENSE.md for more information.
"""
import base64
import json
import os
import platform
import random
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import time
from datetime import datetime, timedelta
import websocket # pip install websocket-client
try: # Python 3
from urllib.request import HTTPError, URLError, urlopen
except ImportError: # Python 2
from urllib2 import HTTPError, URLError, urlopen
try: # The crypto package depends on the package installed
from Cryptodome.Cipher import AES
from Cryptodome.Util import Padding
except ImportError:
from Crypto.Cipher import AES
from Crypto.Util import Padding
IS_MACOS = platform.system().lower() == 'darwin'
# Script configuration
BROWSER_PATH = '/var/lib/flatpak/app/com.brave.Browser/x86_64/stable/b93e55dc329e9559d38fbaec574ce5c2da1fc6b2b4dece279374e6fb6765425b/files/brave/brave'
DEBUG_PORT = 9222
LOCALHOST_ADDRESS = '127.0.0.1'
URL = 'https://www.netflix.com/login'
class Main(object):
app_version = '1.1.8'
_msg_id = 0
_ws = None
def __init__(self, browser_temp_path):
show_msg('')
show_msg(TextFormat.BOLD + 'NFAuthentication Key for Linux/MacOS (Version {})'.format(self.app_version),
TextFormat.COL_LIGHT_BLUE)
show_msg('')
show_msg('Disclaimer:')
show_msg('This script and source code available on GitHub are provided "as is" without warranty of any kind, either express or implied. Use at your own risk. The use of the software is done at your own discretion and risk with the agreement that you will be solely responsible for any damage resulting from such activities and you are solely responsible for adequate data protection.',
TextFormat.COL_GREEN)
show_msg('')
browser_proc = None
try:
input_msg('Press "ENTER" key to accept the disclaimer and start, or "CTRL+C" to cancel', TextFormat.BOLD)
browser_proc = open_browser(browser_temp_path)
self.operations()
except Warning as exc:
show_msg(str(exc), TextFormat.COL_LIGHT_RED)
if browser_proc:
browser_proc.terminate()
except Exception as exc:
show_msg('An error is occurred:\r\n' + str(exc), TextFormat.COL_LIGHT_RED)
import traceback
show_msg(traceback.format_exc())
if browser_proc:
browser_proc.terminate()
finally:
try:
if self._ws:
self._ws.close()
except Exception:
pass
def operations(self):
show_msg('Establish connection with the browser... please wait')
self.get_browser_debug_endpoint()
self.ws_request('Network.enable')
self.ws_request('Page.enable')
show_msg('Opening login webpage... please wait')
self.ws_request('Page.navigate', {'url': URL})
self.ws_wait_event('Page.domContentEventFired') # Wait loading DOM (document.onDOMContentLoaded event)
show_msg('Please login in to website now ...waiting for you to finish...', TextFormat.COL_LIGHT_BLUE)
if not self.wait_user_logged():
raise Warning('You have exceeded the time available for the login. Restart the operations.')
self.ws_wait_event('Page.domContentEventFired') # Wait loading DOM (document.onDOMContentLoaded event)
# Verify that falcorCache data exist, this data exist only when logged
show_msg('Verification of data in progress... please wait')
html_page = self.ws_request('Runtime.evaluate', {'expression': 'document.documentElement.outerHTML'})['result']['value']
react_context = extract_json(html_page, 'reactContext')
if react_context is None:
# An error is happened in the reactContext extraction? try go on
show_msg('Error failed to check account membership status, try a simple check', TextFormat.COL_LIGHT_RED)
if 'falcorCache' not in html_page:
raise Warning('Error unable to find falcorCache data.')
else:
# Check the membership status
membership_status = react_context['models']['userInfo']['data']['membershipStatus']
if membership_status != 'CURRENT_MEMBER':
show_msg('The account membership status is: ' + membership_status, TextFormat.COL_LIGHT_RED)
raise Warning('Your login can not be used. The possible causes are account not confirmed/renewed/reactivacted.')
self.ws_wait_event('Page.loadEventFired') # Wait loading page (window.onload event)
show_msg('File creation in progress... please wait')
# Get all cookies
cookies = self.ws_request('Network.getAllCookies').get('cookies', [])
assert_cookies(cookies)
# Generate a random PIN for access to "NFAuthentication.key" file
pin = random.randint(1000, 9999)
# Create file data structure
data = {
'app_name': 'NFAuthenticationKey',
'app_version': self.app_version,
'app_system': 'MacOS' if IS_MACOS else 'Linux',
'app_author': 'CastagnaIT',
'timestamp': int(((datetime.utcnow() + timedelta(days=5)) - datetime(year=1970, month=1, day=1)).total_seconds()),
'data': {
'cookies': cookies
}
}
# Save the "NFAuthentication.key" file
save_data(data, pin)
# Close the browser
self.ws_request('Browser.close')
show_msg('Operations completed!\r\nThe "NFAuthentication.key" file has been saved in current folder.\r\nYour PIN protection is: {}'.format(pin),
TextFormat.COL_BLUE)
def get_browser_debug_endpoint(self):
start_time = time.time()
while time.time() - start_time < 15:
try:
endpoint = ''
data = urlopen('http://{0}:{1}/json'.format(LOCALHOST_ADDRESS, DEBUG_PORT), timeout=1).read().decode('utf-8')
if not data:
raise ValueError
session_list = json.loads(data)
for item in session_list:
if item['type'] == 'page':
endpoint = item['webSocketDebuggerUrl']
if not endpoint:
raise Warning('Chrome session page not found')
self._ws = websocket.create_connection(endpoint)
return
except (URLError, socket.timeout, ValueError): # json.JSONDecodeError inherited ValueError and available from >= py3.5
pass
raise Warning('Unable to connect with the browser')
def wait_user_logged(self):
start_time = time.time()
while time.time() - start_time < 300: # 5 min
time.sleep(1)
history_data = self.ws_request('Page.getNavigationHistory')
history_index = history_data['currentIndex']
# If the current page url is like "https://www.n*****x.com/browse" means that the user should have logged in successfully
if '/browse' in history_data['entries'][history_index]['url']:
return True
return False
@property
def msg_id(self):
self._msg_id += 1
return self._msg_id
@msg_id.setter
def msg_id(self, value):
self._msg_id = value
def ws_request(self, method, params=None):
req_id = self.msg_id
message = json.dumps({'id': req_id, 'method': method, 'params': params or {}})
self._ws.send(message)
start_time = time.time()
while True:
if time.time() - start_time > 10:
break
message = self._ws.recv()
parsed_message = json.loads(message)
if 'result' in parsed_message and parsed_message['id'] == req_id:
return parsed_message['result']
raise Warning('No data received from browser')
def ws_wait_event(self, method):
start_time = time.time()
while True:
if time.time() - start_time > 10:
break
message = self._ws.recv()
parsed_message = json.loads(message)
if 'method' in parsed_message and parsed_message['method'] == method:
return parsed_message
raise Warning('No event data received from browser')
# Helper methods
class TextFormat:
"""Terminal color codes"""
COL_BLUE = '\033[94m'
COL_GREEN = '\033[92m'
COL_LIGHT_YELLOW = '\033[93m'
COL_LIGHT_RED = '\033[91m'
COL_LIGHT_BLUE = '\033[94m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
def open_browser(browser_temp_path):
params = ['--incognito',
'--user-data-dir={}'.format(browser_temp_path),
'--remote-debugging-port={}'.format(DEBUG_PORT),
'--remote-allow-origins=*',
'--no-first-run',
'--no-default-browser-check']
dev_null = open(os.devnull, 'wb')
try:
browser_path = get_browser_path()
show_msg('Browser startup... ({}) please wait'.format(browser_path))
return subprocess.Popen([browser_path] + params, stdout=dev_null, stderr=subprocess.STDOUT)
finally:
dev_null.close()
def get_browser_path():
"""Check and return the name of the installed browser"""
if '*' not in BROWSER_PATH:
return BROWSER_PATH
if IS_MACOS:
for browser_name in ['Google Chrome', 'Chromium', 'Brave Browser']:
path = '/Applications/' + browser_name + '.app/Contents/MacOS/' + browser_name
if os.path.exists(path):
return path
else:
for browser_name in ['google-chrome', 'google-chrome-stable', 'google-chrome-unstable', 'chromium', 'chromium-browser', 'brave-browser']:
try:
path = subprocess.check_output(['which', browser_name]).decode('utf-8').strip()
if path:
return path
except subprocess.CalledProcessError:
pass
raise Warning('Browser not detected.\r\nTry check if it is installed or specify the path in the BROWSER_PATH field inside "NFAuthenticationKey.py" file')
def assert_cookies(cookies):
if not cookies:
raise Warning('Not found cookies')
login_cookies = ['nfvdid', 'SecureNetflixId', 'NetflixId']
for cookie_name in login_cookies:
if not any(cookie['name'] == cookie_name for cookie in cookies):
raise Warning('Not found cookies')
def extract_json(content, var_name):
try:
pattern = r'netflix\.{}\s*=\s*(.*?);\s*</script>'
json_array = re.findall(pattern.format(var_name), content, re.DOTALL)
json_str = json_array[0]
json_str_replace = json_str.replace(r'\"', r'\\"') # Escape \"
json_str_replace = json_str_replace.replace(r'\s', r'\\s') # Escape whitespace
json_str_replace = json_str_replace.replace(r'\r', r'\\r') # Escape return
json_str_replace = json_str_replace.replace(r'\n', r'\\n') # Escape line feed
json_str_replace = json_str_replace.replace(r'\t', r'\\t') # Escape tab
json_str_replace = json_str_replace.replace(r'\p', r'/p') # Unicode property not supported, we change slash to avoid unescape it
json_str_replace = json_str_replace.encode().decode('unicode_escape') # Decode the string as unicode
json_str_replace = re.sub(r'\\(?!["])', r'\\\\', json_str_replace) # Escape backslash (only when is not followed by double quotation marks \")
return json.loads(json_str_replace)
except Exception as exc:
return None
def save_data(data, pin):
raw = bytes(Padding.pad(data_to_pad=json.dumps(data).encode('utf-8'), block_size=16))
iv = '\x00' * 16
cipher = AES.new((str(pin) + str(pin) + str(pin) + str(pin)).encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
encrypted_data = base64.b64encode(cipher.encrypt(raw)).decode('utf-8')
file = open('NFAuthentication.key', 'w')
file.write(encrypted_data)
file.close()
def show_msg(text, text_format=None):
if text_format:
text = text_format + text + TextFormat.END
print(text)
def input_msg(text, text_format=None):
if text_format:
text = text_format + text + TextFormat.END
if sys.version_info.major == 2:
return raw_input(text)
else:
return input(text)
if __name__ == '__main__':
temp_path = tempfile.mkdtemp()
try:
Main(temp_path)
except KeyboardInterrupt:
show_msg('\r\nOperations cancelled')
finally:
try:
shutil.rmtree(temp_path)
except Exception:
pass