-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmySoshClient.py
614 lines (536 loc) · 22.1 KB
/
mySoshClient.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
from bs4 import BeautifulSoup
import json
import os
import requests
import sys
import unicodedata
from common.utils import myprint, dumpToFile
import myGlobals as mg
import authinfo
import config
# Dictionary containing the HTTP requests to send to the server
SOSH_HTTP_REQUESTS = {
"initialPage" : {
"info" : "Conect to www.sosh.fr and get index page to retrieve idzone JS URL",
"rqst" : {
"type" : 'GET',
"url" : 'https://www.sosh.fr',
"headers" : {
"Host" : 'www.sosh.fr',
"Cookie" : 'idz_usr_seg=3|false; LPVID=RkZmE1MzdjZGIyNzFmNzM5',
},
},
"resp" : {
"code" : 200,
#"dumpResponse" : 'www.sosh.fr.html',
"updateCookies" : False,
},
"returnText" : True,
},
"login" : {
"info" : 'Initiate login process, update some cookies',
"rqst" : {
"type" : 'GET',
"url" : 'https://login.orange.fr/?service=sosh&return_url=https%3A%2F%2Fwww.sosh.fr%2F',
"headers" : {
"Accept" : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
"Host" : 'login.orange.fr',
"Referer": 'https://www.sosh.fr/',
"Cookie" : ['izclientid', 'idzone'],
},
},
"resp" : {
"code" : 200,
"updateCookies" : True,
},
"returnText" : False,
},
"username" : {
"info" : 'Continue with connection. Send username to server',
"rqst" : {
"type" : 'POST',
"url" : 'https://login.orange.fr/api/login',
"payload" : '{"login":"put-username-here","params":{"service":"sosh","return_url":"https://www.sosh.fr/"}}',
"extraCookie" : 'promoteMC=1',
"headers" : {
"Accept" : 'application/json, text/plain, */*',
"Host" : 'login.orange.fr',
"Origin" : 'https://login.orange.fr',
"Referer" : 'https://login.orange.fr/',
"Content-Type" : 'application/json;charset=UTF-8',
"Content-Length" : 'put-payload-length-here',
"Cookie" : ['xauth', 'trust', 'idzone', 'izclientid', 'datadome'],
},
},
"resp" : {
"code" : 200,
"updateCookies" : True,
},
"returnText" : False,
},
"password" : {
"info" : 'Continue with connection. Send password to server',
"rqst" : {
"type" : 'POST',
"url" : 'https://login.orange.fr/api/password',
"payload" : '{"password":"put-password-here","remember":true}',
"extraCookie" : 'promoteMC=1',
"headers" : {
"Accept" : 'application/json, text/plain, */*',
"Host" : 'login.orange.fr',
"Origin" : 'https://login.orange.fr',
"Referer" : 'https://login.orange.fr/',
"Content-Type" : 'application/json;charset=UTF-8',
"Content-Length" : 'put-payload-length-here',
"Cookie" : ['xauth', 'trust', 'idzone', 'izclientid', 'datadome'],
},
},
"resp" : {
"code" : 200,
"updateCookies" : True,
},
"returnText" : False,
},
"updateIdZone1" : {
"info" : 'Reload index page to update idzone.js URL',
"rqst" : {
"type" : 'GET',
"url" : 'https://www.sosh.fr',
"headers" : {
"Accept" : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
"Host" : 'www.sosh.fr',
"Referer": 'https://login.orange.fr/',
},
},
"resp" : {
"code" : 200,
#"dumpResponse" : 'www.sosh.fr.html',
"updateCookies" : False,
},
"returnText" : True,
},
"proposal0" : {
"info" : 'Use sso.orange.fr to get contracts info',
"rqst" : {
"type" : 'OPTIONS',
"url" : 'https://sso.orange.fr/pushms/advise/mct/1.1/proposal?targets=NEC[contract:50,transverse:50,contract_c:50,transverse_c:50]&canal=06ososh&data[canalPhysique]=web',
"headers" : {
"Host" : 'sso.orange.fr',
"Origin" : 'www.sosh.fr',
"Referer": 'https://www.sosh.fr/',
"Access-Control-Request-Method" : 'GET',
"Access-Control-Request-Headers": 'x-capping',
"Sec-Fetch-Mode" : 'cors',
"Sec-Fetch-Site" : 'cross-site',
"Sec-Fetch-Dest" : 'empty',
},
},
"resp" : {
"code" : 200,
"updateCookies" : True,
},
"returnText" : False,
},
"proposal1" : {
"info" : 'Get information about contracts',
"rqst" : {
"type" : 'GET',
"url" : 'https://sso.orange.fr/pushms/advise/mct/1.1/proposal?targets=NEC[contract:50,transverse:50,contract_c:50,transverse_c:50]&canal=06ososh&data[canalPhysique]=web',
"headers" : {
"Accept" : 'application/json',
"Host" : 'sso.orange.fr',
"Origin" : 'www.sosh.fr',
"Referer": 'https://www.sosh.fr/',
"X-Capping" : '{"display": {"NEC": {"contract": {"*":1,"DEFAULT":0,"ZZZ":0},"transverse":{"*":1,"DEFAULT":0,"ZZZ":0}}}}',
"Sec-Fetch-Mode" : 'cors',
"Sec-Fetch-Site" : 'cross-site',
"Sec-Fetch-Dest" : 'empty',
"Cookie" : ['idzone', 'izclientid', 'wassup'],
},
},
"resp" : {
"code" : 200,
"updateCookies" : True,
},
"returnText" : False,
},
"updateIdZone2" : {
"info" : 'Reload index page to update idzone.js URL',
"rqst" : {
"type" : 'GET',
"url" : 'https://www.sosh.fr/client',
"headers" : {
"Accept" : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
"Host" : 'www.sosh.fr',
"Referer": 'https://www.sosh.fr/',
"Sec-Fetch-Mode" : 'navigate',
"Sec-Fetch-Site" : 'same-origin',
"Sec-Fetch-Dest" : 'document',
},
},
"resp" : {
"code" : 200,
#"dumpResponse" : 'www.sosh.fr.html',
"updateCookies" : False,
},
"returnText" : True,
},
"telcoSecurity0" : {
"info" : 'Get Telco/Security information (to update cookies)',
"rqst" : {
"type" : 'OPTIONS',
"url" : 'https://sso-f.orange.fr/omoi_erb/portfoliomanager/contracts/users/current?filter=telco,security',
"headers" : {
"Host" : 'sso-f.orange.fr',
"Origin" : 'https://www.sosh.fr',
"Referer": 'https://www.sosh.fr/',
"Access-Control-Request-Method" : 'GET',
"Access-Control-Request-Headers": 'erable-service-id,x-orange-caller-id,x-orange-origin-id',
"Sec-Fetch-Mode" : 'cors',
"Sec-Fetch-Site" : 'cross-site',
"Sec-Fetch-Dest" : 'empty',
},
},
"resp" : {
"code" : 204,
"updateCookies" : True,
},
"returnText" : False,
},
"telcoSecurity1" : {
"info" : 'Get Telco/Security information (to update cookies)',
"rqst" : {
"type" : 'GET',
"url" : 'https://sso-f.orange.fr/omoi_erb/portfoliomanager/contracts/users/current?filter=telco,security',
"headers" : {
"Accept" : 'application/json;version=1',
"Host" : 'sso-f.orange.fr',
"Origin" : 'https://www.sosh.fr',
"Referer": 'https://www.sosh.fr/',
"X-Orange-Caller-Id" : 'WSH',
"X-Orange-Origin-Id" : 'WSH',
"Sec-Fetch-Mode" : 'cors',
"Sec-Fetch-Site" : 'cross-site',
"Sec-Fetch-Dest" : 'empty',
"Cookie" : ['idzone', 'izclientid', 'wassup', 'TS01ebed15'],
},
},
"resp" : {
"code" : 200,
"updateCookies" : True,
},
"returnText" : False,
},
"contracts0" : {
"info" : 'Finally, get contracts information from server',
"rqst" : {
"type" : 'OPTIONS',
"url" : 'https://sso-f.orange.fr/omoi_erb/suiviconso/v1.0/suiviconso/users/current/contracts/',
"headers" : {
"Host" : 'sso-f.orange.fr',
"Origin" : 'https://www.sosh.fr',
"Referer": 'https://www.sosh.fr/',
"Access-Control-Request-Method" : 'GET',
"Access-Control-Request-Headers": 'content-type,erable-service-id,x-orange-caller-id,x-orange-origin-id',
"Sec-Fetch-Mode" : 'cors',
"Sec-Fetch-Site" : 'cross-site',
"Sec-Fetch-Dest" : 'empty',
},
},
"resp" : {
"code" : 204,
"updateCookies" : True,
},
"returnText" : False,
},
"contracts1" : {
"info" : 'Finally, get contracts information from server',
"rqst" : {
"type" : 'GET',
"url" : 'https://sso-f.orange.fr/omoi_erb/suiviconso/v1.0/suiviconso/users/current/contracts/',
"headers" : {
"Accept" : '*/*',
"Host" : 'sso-f.orange.fr',
"Origin" : 'https://www.sosh.fr',
"Referer": 'https://www.sosh.fr/',
"Content-Type": 'application/json',
"X-Orange-Caller-Id": 'WSH',
"X-Orange-Origin-Id": 'WSH',
"Sec-Fetch-Mode" : 'cors',
"Sec-Fetch-Site" : 'cross-site',
"Sec-Fetch-Dest" : 'empty',
"erable-service-id": 'hpsosh',
"Cookie" : ['idzone', 'izclientid', 'wassup', 'TS01ebed15'],
},
},
"resp" : {
"code" : 200,
"updateCookies" : False,
},
"returnText" : True,
},
"_idzone" : {
"info" : 'Load idzone.js Java script to update some cookies',
"rqst" : {
"type" : 'GET',
"url" : 'put-script-url-here', # updated dynamically
"headers" : {
"Accept" : '*/*',
"Host" : 'iz4.orange.fr',
"Referer": 'https://www.sosh.fr/',
"Sec-Fetch-Mode" : 'no-cors',
"Sec-Fetch-Site" : 'cross-site',
"Sec-Fetch-Dest" : 'script',
"Cookie" : None, # updated dynamically
},
},
"resp" : {
"code" : 200,
"updateCookies" : True,
},
"returnText" : False,
},
}
####
class Sosh:
def __init__(self, userName, userPassword, session):
self._hostName = 'www.sosh.fr'
self._username = userName
self._password = userPassword
self._session = session
# Dict to save cookies from server
self._cookies = dict()
@property
def hostname(self):
return self._hostName
@property
def headers(self):
return self._headers.headers
def getContractsInformation(self):
assert(self._hostName)
assert(self._session)
assert(self._username)
assert(self._password)
# Execute "initialPage" request
respText = self._executeRequest('initialPage')
if 'ErRoR' in respText:
myprint(1, "Error when executing 'initialPage' request")
return respText
# Get idzone.js script url from response text
idzoneScript = self._getScriptUrl(respText, 'idzone.js')
# Load idzone.js to update cookies
# Patch SOSH_HTTP_REQUEST[] to update the '_idzone' request with:
# - url (from respText)
# - list of cookies (input)
SOSH_HTTP_REQUESTS["_idzone"]["rqst"]["url"] = 'https:%s' % idzoneScript
SOSH_HTTP_REQUESTS["_idzone"]["rqst"]["headers"]["Cookie"] = []
# Execute "_idzone" request
self._executeRequest('_idzone')
# Execute "login" request
self._executeRequest('login')
# Execute "username" request
# Patch SOSH_HTTP_REQUEST[] to update the 'username' request with:
# valid 'username' from config.SOSH_USERNAME
# valid Content-Length
p = SOSH_HTTP_REQUESTS["username"]["rqst"]["payload"]
myprint(2, 'Replacing %s by %s' % ("put-username-here",self._username))
np = p.replace("put-username-here", self._username)
SOSH_HTTP_REQUESTS["username"]["rqst"]["payload"] = np
contentLen = SOSH_HTTP_REQUESTS["username"]["rqst"]["headers"]["Content-Length"]
ncl = contentLen.replace('put-payload-length-here', str(len(np)))
SOSH_HTTP_REQUESTS["username"]["rqst"]["headers"]["Content-Length"] = ncl
self._executeRequest('username')
# Execute "password" request
# Patch SOSH_HTTP_REQUEST[] to update the 'password' request with:
# valid 'password' from config.SOSH_PASSWORD
# valid Content-Length
p = SOSH_HTTP_REQUESTS["password"]["rqst"]["payload"]
myprint(2, 'Replacing %s by %s' % ("put-password-here",self._password))
np = p.replace('put-password-here', self._password)
SOSH_HTTP_REQUESTS["password"]["rqst"]["payload"] = np
contentLen = SOSH_HTTP_REQUESTS["password"]["rqst"]["headers"]["Content-Length"]
ncl = contentLen.replace('put-payload-length-here', str(len(np)))
SOSH_HTTP_REQUESTS["password"]["rqst"]["headers"]["Content-Length"] = ncl
self._executeRequest('password')
# Execute "updateIdZone1" request
respText = self._executeRequest('updateIdZone1')
# Get idzone.js script url from response text
idzoneScript = self._getScriptUrl(respText, 'idzone.js')
### Load idzone.js (to update cookies) ###
# Patch SOSH_HTTP_REQUEST[] to update the '_idzone' request with:
# - url
# - list of cookies
SOSH_HTTP_REQUESTS["_idzone"]["rqst"]["url"] = 'https:%s' % idzoneScript
SOSH_HTTP_REQUESTS["_idzone"]["rqst"]["headers"]["Cookie"] = ['idzone', 'izclientid', 'wassup']
# Execute "_idzone" request
self._executeRequest('_idzone')
# Execute "proposal0" request
self._executeRequest('proposal0')
self._executeRequest('proposal1')
# Execute "updateIdZone2" request (again)
respText = self._executeRequest('updateIdZone2')
# Get idzone.js script url from response text
idzoneScript = self._getScriptUrl(respText, 'idzone.js')
### Load idzone.js (to update cookies) ###
# Patch SOSH_HTTP_REQUEST[] to update the '_idzone' request with:
# - url
# - list of cookies
SOSH_HTTP_REQUESTS["_idzone"]["rqst"]["url"] = 'https:%s' % idzoneScript
SOSH_HTTP_REQUESTS["_idzone"]["rqst"]["headers"]["Cookie"] = ['idzone', 'izclientid', 'wassup', 'TS01ebed15']
# Execute "_idzone" request
self._executeRequest('_idzone')
# Execute "telcoSecurity*" request. (NOT REQUIRED)
#self._executeRequest('telcoSecurity0')
#self._executeRequest('telcoSecurity1')
# Execute "contracts*" request
self._executeRequest('contracts0')
respText = self._executeRequest('contracts1')
# Return normalized JSON data
return(unicodedata.normalize("NFKD", respText))
# Logout from server
def logout(self):
#print('BYE BYE')
pass
def _executeRequest(self, name):
rqst = SOSH_HTTP_REQUESTS[name]
myprint(1, 'Executing request "%s": %s' % (name, rqst["info"]))
myprint(2, json.dumps(rqst, indent=4))
hdrs = Headers()
for k,v in rqst["rqst"]["headers"].items():
if k == "Cookie":
if 'str' in str(type(v)): # Cookie is a string
cookieAsString = v
else: # Cookie is a list of cookies
assert('list' in str(type(v)))
cookieAsString = self._buildCookieString(v)
# Add extra Cookie if requested
if "extraCookie" in rqst["rqst"]:
cookieAsString += rqst["rqst"]["extraCookie"]
hdrs.setHeader('Cookie', cookieAsString)
else:
hdrs.setHeader(k, v)
rqstType = rqst["rqst"]["type"]
rqstURL = rqst["rqst"]["url"]
myprint(1,'Request type: %s, Request URL: %s' % (rqstType, rqstURL))
myprint(2,'Request Headers:', json.dumps(hdrs.headers, indent=2))
errFlag = False
if rqstType == 'GET':
try:
r = self._session.get(rqstURL, headers=hdrs.headers)
except requests.exceptions.RequestException as e:
errFlag = True
elif rqstType == 'POST':
rqstPayload = rqst["rqst"]["payload"]
myprint(1,"payload=%s" % rqstPayload)
try:
r = self._session.post(rqstURL, headers=hdrs.headers, data=rqstPayload)
except requests.exceptions.RequestException as e:
errFlag = True
else: # OPTIONS
assert(rqstType == 'OPTIONS')
try:
r = self._session.options(rqstURL, headers=hdrs.headers)
except requests.exceptions.RequestException as e:
errFlag = True
if errFlag:
errorMsg = 'ErRoR while retrieving information: %s' % (e) # Dont't change the cast for ErRoR !!!!
myprint(0, errorMsg)
return errorMsg
myprint(1,'Response Code:',r.status_code)
if r.status_code != rqst["resp"]["code"]:
myprint(0,'Request %s (%s). Invalid Status Code: %d (expected %d). Reason: %s.' % (name, rqst["info"], r.status_code, rqst["resp"]["code"], r.reason))
if rqst["returnText"]:
return ''
else:
return
# Optional parameter "dumpResponse"
try:
dumpResponse = rqst["resp"]["dumpResponse"]
dumpToFile(os.path.join(mg.moduleDirPath, dumpResponse), r.text)
except:
#print('No "dumpResponse" field detected')
pass
# Update cookies
if rqst["resp"]["updateCookies"]:
self._updateCookies(r.cookies)
if rqst["returnText"]:
return r.text
def _findListResources (self, tag, attribute, soup):
l = []
for x in soup.findAll(tag):
try:
l.append(x[attribute])
except KeyError:
pass
return(l)
def _getScriptUrl(self, text, scriptName):
scriptPath = ''
soup = BeautifulSoup(text, 'html.parser')
scripts_src = self._findListResources('script', 'src', soup)
scriptUrl = [s for s in scripts_src if scriptName in s][0]
return(scriptUrl)
# Update our cookie dict
def _updateCookies(self, cookies):
#print(requests.utils.dict_from_cookiejar(self._session.cookies))
for cookie in self._session.cookies:
#print(cookie.name, cookie.value, cookie.domain)
if cookie.value == 'undefined' or cookie.value == '':
myprint(2,'Skipping cookie with undefined value %s' % (cookie.name))
continue
if cookie.name in self._cookies and self._cookies[cookie.name] != cookie.value:
myprint(1,'Updating cookie:', cookie.name)
self._cookies[cookie.name] = cookie.value
elif not cookie.name in self._cookies:
myprint(1,'Adding cookie:', cookie.name)
self._cookies[cookie.name] = cookie.value
else:
myprint(2,'Cookie not modified:', cookie.name)
# Build a string containing all cookies passed as parameter in a list
def _buildCookieString(self, cookieList):
cookieAsString = ''
for c in cookieList:
# Check if cookie exists in our dict
if c in self._cookies:
cookieAsString += '%s=%s; ' % (c, self._cookies[c])
else:
myprint(1,'Warning: Cookie %s not found.' % (c))
return(cookieAsString)
#### Class Headers
class Headers():
def __init__(self):
# Request header prototype. Updated with specific request
self._protoHeaders = {
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Pragma': 'no-cache',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36'
}
self._h = self._protoHeaders
@property
def headers(self):
return self._h
def setHeader(self, hdr, val):
self._h[hdr] = val
# Return header value if found
def getHeader(self, hdr):
try:
val = self._h[hdr]
except:
return None
return val
def getCookie(self, cookie):
for k,v in self._h.items():
if k == 'Set-Cookie':
cookies = v.split(';')
for c in cookies:
try:
cc = c.split('=')
except:
myprint(1,'Skipping %s' % cc)
continue
if cc[0] == cookie:
return cc[1]
return None