Coverage for icloudpy/base.py: 78%

454 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-05 06:42 +0000

1"""Library base file.""" 

2 

3import base64 

4import getpass 

5import hashlib 

6import http.cookiejar as cookielib 

7import inspect 

8import json 

9import logging 

10from os import mkdir, path 

11from re import match 

12from tempfile import gettempdir 

13from uuid import uuid1 

14 

15import srp 

16from requests import Session 

17 

18from icloudpy.exceptions import ( 

19 ICloudPy2SARequiredException, 

20 ICloudPyAPIResponseException, 

21 ICloudPyFailedLoginException, 

22 ICloudPyServiceNotActivatedException, 

23) 

24from icloudpy.services import ( 

25 AccountService, 

26 CalendarService, 

27 ContactsService, 

28 DriveService, 

29 FindMyiPhoneServiceManager, 

30 PhotosService, 

31 RemindersService, 

32) 

33from icloudpy.utils import get_password_from_keyring 

34 

35LOGGER = logging.getLogger(__name__) 

36 

37HEADER_DATA = { 

38 "X-Apple-ID-Account-Country": "account_country", 

39 "X-Apple-ID-Session-Id": "session_id", 

40 "X-Apple-Session-Token": "session_token", 

41 "X-Apple-TwoSV-Trust-Token": "trust_token", 

42 "scnt": "scnt", 

43} 

44 

45 

46class ICloudPyPasswordFilter(logging.Filter): 

47 """Password log hider.""" 

48 

49 def __init__(self, password): 

50 super().__init__(password) 

51 

52 def filter(self, record): 

53 message = record.getMessage() 

54 if self.name in message: 

55 record.msg = message.replace(self.name, "*" * 8) 

56 record.args = [] 

57 

58 return True 

59 

60 

61class ICloudPySession(Session): 

62 """iCloud session.""" 

63 

64 def __init__(self, service): 

65 self.service = service 

66 Session.__init__(self) 

67 

68 def request(self, method, url, **kwargs): # pylint: disable=arguments-differ 

69 # Charge logging to the right service endpoint 

70 callee = inspect.stack()[2] 

71 module = inspect.getmodule(callee[0]) 

72 request_logger = logging.getLogger(module.__name__).getChild("http") 

73 if self.service.password_filter not in request_logger.filters: 

74 request_logger.addFilter(self.service.password_filter) 

75 

76 request_logger.debug(f"{method} {url} {kwargs.get('data', '')}") 

77 

78 has_retried = kwargs.get("retried") 

79 kwargs.pop("retried", None) 

80 response = super().request(method, url, **kwargs) 

81 

82 content_type = response.headers.get("Content-Type", "").split(";")[0] 

83 json_mimetypes = ["application/json", "text/json"] 

84 

85 for header, value in HEADER_DATA.items(): 

86 if response.headers.get(header): 

87 session_arg = value 

88 self.service.session_data.update( 

89 {session_arg: response.headers.get(header)}, 

90 ) 

91 

92 # Save session_data to file 

93 with open(self.service.session_path, "w", encoding="utf-8") as outfile: 

94 json.dump(self.service.session_data, outfile) 

95 LOGGER.debug("Saved session data to file") 

96 

97 # Save cookies to file 

98 self.cookies.save(ignore_discard=True, ignore_expires=True) 

99 LOGGER.debug("Cookies saved to %s", self.service.cookiejar_path) 

100 

101 if not response.ok and (content_type not in json_mimetypes or response.status_code in [421, 450, 500]): 

102 try: 

103 # pylint: disable=W0212 

104 fmip_url = self.service._get_webservice_url("findme") 

105 if has_retried is None and response.status_code == 450 and fmip_url in url: 

106 # Handle re-authentication for Find My iPhone 

107 LOGGER.debug("Re-authenticating Find My iPhone service") 

108 try: 

109 self.service.authenticate(True, "find") 

110 except ICloudPyAPIResponseException: 

111 LOGGER.debug("Re-authentication failed") 

112 kwargs["retried"] = True 

113 return self.request(method, url, **kwargs) 

114 except Exception: 

115 pass 

116 

117 if has_retried is None and response.status_code in [421, 450, 500]: 

118 api_error = ICloudPyAPIResponseException( 

119 response.reason, 

120 response.status_code, 

121 retry=True, 

122 ) 

123 request_logger.debug(api_error) 

124 kwargs["retried"] = True 

125 return self.request(method, url, **kwargs) 

126 

127 self._raise_error(response.status_code, response.reason) 

128 

129 if content_type not in json_mimetypes: 

130 return response 

131 

132 try: 

133 data = response.json() 

134 except: # noqa: E722 

135 request_logger.warning("Failed to parse response with JSON mimetype") 

136 return response 

137 

138 request_logger.debug(data) 

139 

140 if isinstance(data, dict): 

141 reason = data.get("errorMessage") 

142 reason = reason or data.get("reason") 

143 reason = reason or data.get("errorReason") 

144 if not reason and isinstance(data.get("error"), str): 

145 reason = data.get("error") 

146 if not reason and data.get("error"): 

147 reason = "Unknown reason" 

148 

149 code = data.get("errorCode") 

150 if not code and data.get("serverErrorCode"): 

151 code = data.get("serverErrorCode") 

152 

153 if reason: 

154 self._raise_error(code, reason) 

155 

156 return response 

157 

158 def _raise_error(self, code, reason): 

159 if self.service.requires_2sa and reason == "Missing X-APPLE-WEBAUTH-TOKEN cookie": 

160 raise ICloudPy2SARequiredException(self.service.user["apple_id"]) 

161 if code in ("ZONE_NOT_FOUND", "AUTHENTICATION_FAILED"): 

162 reason = reason + ". Please log into https://icloud.com/ to manually finish setting up your iCloud service" 

163 api_error = ICloudPyServiceNotActivatedException(reason, code) 

164 LOGGER.error(api_error) 

165 

166 raise api_error 

167 if code == "ACCESS_DENIED": 

168 reason = ( 

169 reason + ". Please wait a few minutes then try again." 

170 "The remote servers might be trying to throttle requests." 

171 ) 

172 if code in [421, 450, 500]: 

173 reason = "Authentication required for Account." 

174 

175 api_error = ICloudPyAPIResponseException(reason, code) 

176 LOGGER.error(api_error) 

177 raise api_error 

178 

179 # Public method to resolve linting error 

180 def raise_error(self, code, reason): 

181 return self._raise_error(code=code, reason=reason) 

182 

183 

184# Apple serves its sign-in widget from here, so this is the origin a browser 

185# reports when signing a challenge for it. 

186SECURITY_KEY_ORIGIN = "https://idmsa.apple.com" 

187 

188# Apple answers an accepted security key assertion with 409, alongside the 

189# ordinary success codes. 250 is its own "two-factor completed". 

190SECURITY_KEY_ACCEPTED_STATUSES = frozenset({200, 204, 250, 409}) 

191 

192 

193def _b64_decode(value): 

194 """Decode Apple's base64, which is unpadded and may use either alphabet.""" 

195 return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) 

196 

197 

198def _b64_encode(value): 

199 """Encode bytes the way Apple's own client does.""" 

200 return base64.b64encode(value).decode("ascii") 

201 

202 

203def build_security_key_assertion(response, rp_id, request_id=None): 

204 """Build the payload Apple expects from a WebAuthn assertion response. 

205 

206 ``response`` is a ``fido2`` ``AuthenticatorAssertionResponse`` or any 

207 object exposing the same ``response`` and ``raw_id`` attributes. 

208 

209 The challenge is taken from ``clientData`` rather than passed in, which 

210 keeps the value signed and the value declared in step. 

211 """ 

212 client_data = bytes(response.response.client_data) 

213 challenge = json.loads(client_data).get("challenge", "") 

214 user_handle = response.response.user_handle 

215 

216 return { 

217 "challenge": challenge.replace("-", "+").replace("_", "/"), 

218 "clientData": _b64_encode(client_data), 

219 "signatureData": _b64_encode(bytes(response.response.signature)), 

220 "authenticatorData": _b64_encode(bytes(response.response.authenticator_data)), 

221 "userHandle": _b64_encode(bytes(user_handle)).rstrip("=") if user_handle else "", 

222 "credentialID": _b64_encode(bytes(response.raw_id)), 

223 "rpId": rp_id, 

224 "requestId": request_id or "", 

225 } 

226 

227 

228class ICloudPyService: 

229 """ 

230 A base authentication class for the iCloud service. Handles the 

231 authentication required to access iCloud services. 

232 

233 Usage: 

234 from src import ICloudPyService 

235 icloudpy = ICloudPyService('username@apple.com', 'password') 

236 icloudpy.iphone.location() 

237 """ 

238 

239 def __init__( 

240 self, 

241 apple_id, 

242 password=None, 

243 cookie_directory=None, 

244 verify=True, 

245 client_id=None, 

246 with_family=True, 

247 auth_endpoint="https://idmsa.apple.com/appleauth/auth", 

248 # For China, use "https://www.icloud.com.cn" 

249 home_endpoint="https://www.icloud.com", 

250 # For China, use "https://setup.icloud.com.cn/setup/ws/1" 

251 setup_endpoint="https://setup.icloud.com/setup/ws/1", 

252 photos_require_finished_index=True, 

253 ): 

254 if password is None: 

255 password = get_password_from_keyring(apple_id) 

256 

257 self.user = {"accountName": apple_id, "password": password} 

258 self.data = {} 

259 self.params = {} 

260 self.client_id = client_id or (f"auth-{str(uuid1()).lower()}") 

261 self.with_family = with_family 

262 self.auth_endpoint = auth_endpoint 

263 self.home_endpoint = home_endpoint 

264 self.setup_endpoint = setup_endpoint 

265 # False opens Photos while Apple is still indexing a library; see 

266 # PhotoLibrary for what that means for its listings. 

267 self.photos_require_finished_index = photos_require_finished_index 

268 

269 self.password_filter = ICloudPyPasswordFilter(password) 

270 LOGGER.addFilter(self.password_filter) 

271 

272 if cookie_directory: 

273 self._cookie_directory = path.expanduser(path.normpath(cookie_directory)) 

274 if not path.exists(self._cookie_directory): 

275 mkdir(self._cookie_directory, 0o700) 

276 else: 

277 topdir = path.join(gettempdir(), "icloudpy") 

278 self._cookie_directory = path.join(topdir, getpass.getuser()) 

279 if not path.exists(topdir): 

280 mkdir(topdir, 0o777) 

281 if not path.exists(self._cookie_directory): 

282 mkdir(self._cookie_directory, 0o700) 

283 

284 LOGGER.debug("Using session file %s", self.session_path) 

285 

286 self.session_data = {} 

287 try: 

288 with open(self.session_path, encoding="utf-8") as session_f: 

289 self.session_data = json.load(session_f) 

290 except: # noqa: E722 

291 LOGGER.info("Session file does not exist") 

292 if self.session_data.get("client_id"): 

293 self.client_id = self.session_data.get("client_id") 

294 self.params["clientId"] = self.client_id 

295 else: 

296 self.session_data.update({"client_id": self.client_id}) 

297 self.params["clientId"] = self.client_id 

298 

299 self.session = ICloudPySession(self) 

300 self.session.verify = verify 

301 self.session.headers.update( 

302 {"Origin": self.home_endpoint, "Referer": f"{self.home_endpoint}/"}, 

303 ) 

304 

305 cookiejar_path = self.cookiejar_path 

306 self.session.cookies = cookielib.LWPCookieJar(filename=cookiejar_path) 

307 if path.exists(cookiejar_path): 

308 try: 

309 self.session.cookies.load(ignore_discard=True, ignore_expires=True) 

310 LOGGER.debug("Read cookies from %s", cookiejar_path) 

311 except: # noqa: E722 

312 # Most likely a pickled cookiejar from earlier versions. 

313 # The cookiejar will get replaced with a valid one after 

314 # successful authentication. 

315 LOGGER.warning("Failed to read cookiejar %s", cookiejar_path) 

316 

317 self.authenticate() 

318 

319 self._drive = None 

320 self._photos = None 

321 

322 def authenticate(self, force_refresh=False, service=None): 

323 """ 

324 Handles authentication, and persists cookies so that 

325 subsequent logins will not cause additional e-mails from Apple. 

326 """ 

327 

328 login_successful = False 

329 if self.session_data.get("session_token") and not force_refresh: 

330 LOGGER.debug("Checking session token validity") 

331 try: 

332 self.data = self._validate_token() 

333 login_successful = True 

334 except ICloudPyAPIResponseException: 

335 LOGGER.debug("Invalid authentication token, will log in from scratch.") 

336 

337 if not login_successful and service is not None: 

338 app = self.data["apps"][service] 

339 if "canLaunchWithOneFactor" in app and app["canLaunchWithOneFactor"] is True: 

340 LOGGER.debug( 

341 "Authenticating as %s for %s", 

342 self.user["accountName"], 

343 service, 

344 ) 

345 

346 try: 

347 self._authenticate_with_credentials_service(service) 

348 login_successful = True 

349 except Exception as error: 

350 LOGGER.debug( 

351 "Could not log into service. Attempting brand new login. %s", 

352 str(error), 

353 ) 

354 

355 if not login_successful: 

356 LOGGER.debug("Authenticating as %s", self.user["accountName"]) 

357 

358 headers = self._get_auth_headers() 

359 

360 if self.session_data.get("scnt"): 

361 headers["scnt"] = self.session_data.get("scnt") 

362 

363 if self.session_data.get("session_id"): 

364 headers["X-Apple-ID-Session-Id"] = self.session_data.get("session_id") 

365 

366 class SrpPassword: 

367 def __init__(self, password: str): 

368 self.password = password 

369 

370 def set_encrypt_info( 

371 self, 

372 salt: bytes, 

373 iterations: int, 

374 key_length: int, 

375 ): 

376 self.salt = salt 

377 self.iterations = iterations 

378 self.key_length = key_length 

379 

380 def encode(self): 

381 password_hash = hashlib.sha256( 

382 self.password.encode("utf-8"), 

383 ).digest() 

384 return hashlib.pbkdf2_hmac( 

385 "sha256", 

386 password_hash, 

387 salt, 

388 iterations, 

389 key_length, 

390 ) 

391 

392 srp_password = SrpPassword(self.user["password"]) 

393 srp.rfc5054_enable() 

394 srp.no_username_in_x() 

395 usr = srp.User( 

396 self.user["accountName"], 

397 srp_password, 

398 hash_alg=srp.SHA256, 

399 ng_type=srp.NG_2048, 

400 ) 

401 

402 uname, a_bytes = usr.start_authentication() 

403 

404 data = { 

405 "a": base64.b64encode(a_bytes).decode(), 

406 "accountName": uname, 

407 "protocols": ["s2k", "s2k_fo"], 

408 } 

409 

410 try: 

411 response = self.session.post( 

412 f"{self.auth_endpoint}/signin/init", 

413 data=json.dumps(data), 

414 headers=headers, 

415 ) 

416 response.raise_for_status() 

417 except ICloudPyAPIResponseException as error: 

418 msg = "Failed to initiate srp authentication." 

419 raise ICloudPyFailedLoginException(msg, error) from error 

420 

421 body = response.json() 

422 

423 salt = base64.b64decode(body["salt"]) 

424 b = base64.b64decode(body["b"]) 

425 c = body["c"] 

426 iterations = body["iteration"] 

427 key_length = 32 

428 srp_password.set_encrypt_info(salt, iterations, key_length) 

429 

430 m1 = usr.process_challenge(salt, b) 

431 m2 = usr.H_AMK 

432 

433 data = { 

434 "accountName": uname, 

435 "c": c, 

436 "m1": base64.b64encode(m1).decode(), 

437 "m2": base64.b64encode(m2).decode(), 

438 "rememberMe": True, 

439 "trustTokens": [], 

440 } 

441 

442 if self.session_data.get("trust_token"): 

443 data["trustTokens"] = [self.session_data.get("trust_token")] 

444 

445 try: 

446 self.session.post( 

447 f"{self.auth_endpoint}/signin/complete", 

448 params={"isRememberMeEnabled": "true"}, 

449 data=json.dumps(data), 

450 headers=headers, 

451 ) 

452 except ICloudPyAPIResponseException as error: 

453 msg = "Invalid email/password combination." 

454 raise ICloudPyFailedLoginException(msg, error) from error 

455 

456 self._authenticate_with_token() 

457 

458 self._webservices = self.data["webservices"] 

459 

460 LOGGER.debug("Authentication completed successfully") 

461 

462 def _authenticate_with_token(self): 

463 """Authenticate using session token.""" 

464 data = { 

465 "accountCountryCode": self.session_data.get("account_country"), 

466 "dsWebAuthToken": self.session_data.get("session_token"), 

467 "extended_login": True, 

468 "trustToken": self.session_data.get("trust_token", ""), 

469 } 

470 

471 try: 

472 req = self.session.post( 

473 f"{self.setup_endpoint}/accountLogin", 

474 data=json.dumps(data), 

475 ) 

476 self.data = req.json() 

477 except ICloudPyAPIResponseException as error: 

478 msg = "Invalid authentication token." 

479 raise ICloudPyFailedLoginException(msg, error) from error 

480 

481 def _authenticate_with_credentials_service(self, service): 

482 """Authenticate to a specific service using credentials.""" 

483 data = { 

484 "appName": service, 

485 "apple_id": self.user["accountName"], 

486 "password": self.user["password"], 

487 } 

488 

489 try: 

490 self.session.post( 

491 f"{self.setup_endpoint}/accountLogin", 

492 data=json.dumps(data), 

493 ) 

494 

495 self.data = self._validate_token() 

496 except ICloudPyAPIResponseException as error: 

497 msg = "Invalid email/password combination." 

498 raise ICloudPyFailedLoginException(msg, error) from error 

499 

500 def _validate_token(self): 

501 """Checks if the current access token is still valid.""" 

502 LOGGER.debug("Checking session token validity") 

503 try: 

504 req = self.session.post(f"{self.setup_endpoint}/validate", data="null") 

505 LOGGER.debug("Session token is still valid") 

506 return req.json() 

507 except ICloudPyAPIResponseException as err: 

508 LOGGER.debug("Invalid authentication token") 

509 raise err 

510 

511 def _get_auth_headers(self, overrides=None): 

512 headers = { 

513 "Accept": "application/json, text/javascript", 

514 "Content-Type": "application/json", 

515 "X-Apple-OAuth-Client-Id": "d39ba9916b7251055b22c7f910e2ea796ee65e98b2ddecea8f5dde8d9d1a815d", 

516 "X-Apple-OAuth-Client-Type": "firstPartyAuth", 

517 "X-Apple-OAuth-Redirect-URI": "https://www.icloud.com", 

518 "X-Apple-OAuth-Require-Grant-Code": "true", 

519 "X-Apple-OAuth-Response-Mode": "web_message", 

520 "X-Apple-OAuth-Response-Type": "code", 

521 "X-Apple-OAuth-State": self.client_id, 

522 "X-Apple-Widget-Key": "d39ba9916b7251055b22c7f910e2ea796ee65e98b2ddecea8f5dde8d9d1a815d", 

523 } 

524 if overrides: 

525 headers.update(overrides) 

526 return headers 

527 

528 @property 

529 def cookiejar_path(self): 

530 """Get path for cookiejar file.""" 

531 return path.join( 

532 self._cookie_directory, 

533 "".join([c for c in self.user.get("accountName") if match(r"\w", c)]), 

534 ) 

535 

536 @property 

537 def session_path(self): 

538 """Get path for session data file.""" 

539 return path.join( 

540 self._cookie_directory, 

541 "".join([c for c in self.user.get("accountName") if match(r"\w", c)]) + ".session", 

542 ) 

543 

544 @property 

545 def requires_2sa(self): 

546 """Returns True if two-step authentication is required.""" 

547 return self.data.get("dsInfo", {}).get("hsaVersion", 0) >= 1 and ( 

548 self.data.get("hsaChallengeRequired", False) or not self.is_trusted_session 

549 ) 

550 

551 @property 

552 def requires_2fa(self): 

553 """Returns True if two-factor authentication is required.""" 

554 return self.data["dsInfo"].get("hsaVersion", 0) == 2 and ( 

555 self.data.get("hsaChallengeRequired", False) or not self.is_trusted_session 

556 ) 

557 

558 @property 

559 def is_trusted_session(self): 

560 """Returns True if the session is trusted.""" 

561 return self.data.get("hsaTrustedBrowser", False) 

562 

563 @property 

564 def trusted_devices(self): 

565 """Returns devices trusted for two-step authentication.""" 

566 request = self.session.get( 

567 f"{self.setup_endpoint}/listDevices", 

568 params=self.params, 

569 ) 

570 return request.json().get("devices") 

571 

572 def send_verification_code(self, device): 

573 """Requests that a verification code is sent to the given device.""" 

574 data = json.dumps(device) 

575 request = self.session.post( 

576 f"{self.setup_endpoint}/sendVerificationCode", 

577 params=self.params, 

578 data=data, 

579 ) 

580 return request.json().get("success", False) 

581 

582 def validate_verification_code(self, device, code): 

583 """Verifies a verification code received on a trusted device.""" 

584 device.update({"verificationCode": code, "trustBrowser": True}) 

585 data = json.dumps(device) 

586 

587 try: 

588 self.session.post( 

589 f"{self.setup_endpoint}/validateVerificationCode", 

590 params=self.params, 

591 data=data, 

592 ) 

593 except ICloudPyAPIResponseException as error: 

594 if error.code == -21669: 

595 # Wrong verification code 

596 return False 

597 raise 

598 

599 self.trust_session() 

600 

601 return not self.requires_2sa 

602 

603 def trigger_2fa_push_notification(self): 

604 """Asks Apple to push a 2FA verification code to trusted devices. 

605 

606 Apple's auth flow (changed around iOS 26 / early 2026) requires a PUT 

607 to ``/verify/trusteddevice/securitycode`` (no body) to initiate code 

608 delivery to trusted devices. Without this step, the user is prompted 

609 for a code but no code is ever pushed to any device — auth stalls. 

610 

611 Callers should invoke this method before prompting the user for the 

612 2FA code (i.e., right after ``requires_2fa`` returns True). Failure 

613 is non-fatal — a code may still arrive via SMS or another path. 

614 

615 See: https://github.com/mandarons/icloud-docker/issues/426 

616 Ported from icloud_photos_downloader PR #1335. 

617 

618 :returns: True if the push request succeeded, False otherwise. 

619 """ 

620 headers = self._get_auth_headers({"Accept": "application/json"}) 

621 

622 if self.session_data.get("scnt"): 

623 headers["scnt"] = self.session_data.get("scnt") 

624 

625 if self.session_data.get("session_id"): 

626 headers["X-Apple-ID-Session-Id"] = self.session_data.get("session_id") 

627 

628 try: 

629 response = self.session.put( 

630 f"{self.auth_endpoint}/verify/trusteddevice/securitycode", 

631 headers=headers, 

632 ) 

633 if not (200 <= response.status_code < 300): 

634 LOGGER.debug( 

635 "2FA push notification trigger returned status %s", 

636 response.status_code, 

637 ) 

638 return False 

639 LOGGER.debug("2FA push notification triggered.") 

640 return True 

641 except Exception as error: # network, SSL, or Apple API errors are all non-fatal here 

642 LOGGER.debug("Failed to trigger 2FA push notification: %s", error) 

643 return False 

644 

645 def validate_2fa_code(self, code): 

646 """Verifies a verification code received via Apple's 2FA system (HSA2).""" 

647 data = {"securityCode": {"code": code}} 

648 

649 headers = self._get_auth_headers({"Accept": "application/json"}) 

650 

651 if self.session_data.get("scnt"): 

652 headers["scnt"] = self.session_data.get("scnt") 

653 

654 if self.session_data.get("session_id"): 

655 headers["X-Apple-ID-Session-Id"] = self.session_data.get("session_id") 

656 

657 try: 

658 self.session.post( 

659 f"{self.auth_endpoint}/verify/trusteddevice/securitycode", 

660 data=json.dumps(data), 

661 headers=headers, 

662 ) 

663 except ICloudPyAPIResponseException as error: 

664 if error.code == -21669: 

665 # Wrong verification code 

666 LOGGER.error("Code verification failed.") 

667 return False 

668 raise 

669 

670 LOGGER.debug("Code verification successful.") 

671 

672 self.trust_session() 

673 return not self.requires_2sa 

674 

675 @property 

676 def security_key_challenge(self): 

677 """Apple's pending WebAuthn challenge, or None if it is not asking for one. 

678 

679 Returned when the account has security keys enrolled, in which case 

680 Apple issues this instead of delivering a 6-digit code. The dict 

681 carries ``challenge``, ``keyHandles`` and ``rpId``. 

682 """ 

683 headers = self._get_auth_headers({"Accept": "application/json"}) 

684 if self.session_data.get("scnt"): 

685 headers["scnt"] = self.session_data.get("scnt") 

686 if self.session_data.get("session_id"): 

687 headers["X-Apple-ID-Session-Id"] = self.session_data.get("session_id") 

688 

689 try: 

690 response = self.session.get(self.auth_endpoint, headers=headers) 

691 challenge = response.json().get("fsaChallenge") 

692 except (ICloudPyAPIResponseException, ValueError) as error: 

693 LOGGER.debug("Could not read security key challenge: %s", error) 

694 return None 

695 

696 if not (challenge and challenge.get("challenge") and challenge.get("keyHandles")): 

697 return None 

698 return challenge 

699 

700 @property 

701 def fido2_devices(self): 

702 """Attached FIDO2 devices. 

703 

704 Empty when the optional ``fido2`` package is not installed. 

705 """ 

706 try: 

707 from fido2.hid import CtapHidDevice 

708 except ImportError: 

709 LOGGER.debug("fido2 is not installed; no local devices available.") 

710 return [] 

711 return list(CtapHidDevice.list_devices()) 

712 

713 def confirm_security_key(self, assertion=None, device=None): 

714 """Complete two-factor authentication with a security key. 

715 

716 Signs the pending challenge with an attached FIDO2 device and 

717 submits the result. Pass ``assertion`` to submit one that has 

718 already been built -- by ``sign_security_key_challenge`` or by any 

719 other means -- in which case no device is used. 

720 

721 Returns True when the session no longer requires a second factor. 

722 """ 

723 if assertion is None: 

724 challenge = self.security_key_challenge 

725 if not challenge: 

726 msg = "Apple is not requesting a security key." 

727 raise ICloudPyFailedLoginException(msg) 

728 if device is None: 

729 devices = self.fido2_devices 

730 if not devices: 

731 msg = "No FIDO2 device found." 

732 raise ICloudPyFailedLoginException(msg) 

733 device = devices[0] 

734 assertion = self.sign_security_key_challenge(challenge, device) 

735 

736 headers = self._get_auth_headers({"Accept": "application/json"}) 

737 if self.session_data.get("scnt"): 

738 headers["scnt"] = self.session_data.get("scnt") 

739 if self.session_data.get("session_id"): 

740 headers["X-Apple-ID-Session-Id"] = self.session_data.get("session_id") 

741 

742 try: 

743 response = self.session.post( 

744 f"{self.auth_endpoint}/verify/security/key", 

745 data=json.dumps(assertion), 

746 headers=headers, 

747 ) 

748 status = response.status_code 

749 except ICloudPyAPIResponseException as error: 

750 status = error.code 

751 

752 if status not in SECURITY_KEY_ACCEPTED_STATUSES: 

753 LOGGER.error("Security key verification failed (%s).", status) 

754 return False 

755 

756 LOGGER.debug("Security key verification successful.") 

757 self.trust_session() 

758 return not self.requires_2sa 

759 

760 def sign_security_key_challenge(self, challenge, device): 

761 """Sign ``challenge`` with ``device`` and return the assertion payload. 

762 

763 Requires the ``fido2`` package and a physical touch on the key. The 

764 result is accepted by ``confirm_security_key``. 

765 """ 

766 from fido2.client import DefaultClientDataCollector, Fido2Client 

767 from fido2.webauthn import ( 

768 PublicKeyCredentialDescriptor, 

769 PublicKeyCredentialRequestOptions, 

770 PublicKeyCredentialType, 

771 UserVerificationRequirement, 

772 ) 

773 

774 rp_id = challenge.get("rpId") or "apple.com" 

775 client = Fido2Client( 

776 device, 

777 client_data_collector=DefaultClientDataCollector(SECURITY_KEY_ORIGIN), 

778 ) 

779 options = PublicKeyCredentialRequestOptions( 

780 challenge=_b64_decode(challenge["challenge"]), 

781 rp_id=rp_id, 

782 allow_credentials=[ 

783 PublicKeyCredentialDescriptor( 

784 id=_b64_decode(handle), 

785 type=PublicKeyCredentialType("public-key"), 

786 ) 

787 for handle in challenge["keyHandles"] 

788 ], 

789 user_verification=UserVerificationRequirement("discouraged"), 

790 ) 

791 result = client.get_assertion(options).get_response(0) 

792 return build_security_key_assertion(result, rp_id, challenge.get("requestId")) 

793 

794 def trust_session(self): 

795 """Request session trust to avoid user log in going forward.""" 

796 headers = self._get_auth_headers() 

797 

798 if self.session_data.get("scnt"): 

799 headers["scnt"] = self.session_data.get("scnt") 

800 

801 if self.session_data.get("session_id"): 

802 headers["X-Apple-ID-Session-Id"] = self.session_data.get("session_id") 

803 

804 try: 

805 self.session.get( 

806 f"{self.auth_endpoint}/2sv/trust", 

807 headers=headers, 

808 ) 

809 self._authenticate_with_token() 

810 return True 

811 except ICloudPyAPIResponseException: 

812 LOGGER.error("Session trust failed.") 

813 return False 

814 

815 def _get_webservice_url(self, ws_key): 

816 """Get webservice URL, raise an exception if not exists.""" 

817 if self._webservices.get(ws_key) is None: 

818 raise ICloudPyServiceNotActivatedException( 

819 "Webservice not available", 

820 ws_key, 

821 ) 

822 return self._webservices[ws_key]["url"] 

823 

824 @property 

825 def devices(self): 

826 """Returns all devices.""" 

827 service_root = self._get_webservice_url("findme") 

828 return FindMyiPhoneServiceManager( 

829 service_root, 

830 self.session, 

831 self.params, 

832 self.with_family, 

833 ) 

834 

835 @property 

836 def iphone(self): 

837 """Returns the iPhone.""" 

838 return self.devices[0] 

839 

840 @property 

841 def account(self): 

842 """Gets the 'Account' service.""" 

843 service_root = self._get_webservice_url("account") 

844 return AccountService(service_root, self.session, self.params) 

845 

846 @property 

847 def photos(self): 

848 """Gets the 'Photo' service.""" 

849 if not self._photos: 

850 service_root = self._get_webservice_url("ckdatabasews") 

851 self._photos = PhotosService( 

852 service_root, 

853 self.session, 

854 self.params, 

855 require_finished_index=self.photos_require_finished_index, 

856 ) 

857 return self._photos 

858 

859 @property 

860 def calendar(self): 

861 """Gets the 'Calendar' service.""" 

862 service_root = self._get_webservice_url("calendar") 

863 return CalendarService(service_root, self.session, self.params) 

864 

865 @property 

866 def contacts(self): 

867 """Gets the 'Contacts' service.""" 

868 service_root = self._get_webservice_url("contacts") 

869 return ContactsService(service_root, self.session, self.params) 

870 

871 @property 

872 def reminders(self): 

873 """Gets the 'Reminders' service.""" 

874 service_root = self._get_webservice_url("reminders") 

875 return RemindersService(service_root, self.session, self.params) 

876 

877 @property 

878 def drive(self): 

879 """Gets the 'Drive' service.""" 

880 if not self._drive: 

881 self._drive = DriveService( 

882 service_root=self._get_webservice_url("drivews"), 

883 document_root=self._get_webservice_url("docws"), 

884 session=self.session, 

885 params=self.params, 

886 ) 

887 return self._drive 

888 

889 def __unicode__(self): 

890 return f"iCloud API: {self.user.get('accountName')}" 

891 

892 def __str__(self): 

893 return self.__unicode__() 

894 

895 def __repr__(self): 

896 return f"<{str(self)}>"