forked from biemster/FindMy
-
Notifications
You must be signed in to change notification settings - Fork 3
/
pypush_gsa_icloud.py
310 lines (263 loc) · 11.1 KB
/
pypush_gsa_icloud.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
from getpass import getpass
import plistlib as plist
import json
import uuid
import pbkdf2
import requests
import hashlib
import hmac
import base64
import locale
from datetime import datetime
import srp._pysrp as srp
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from Cryptodome.Hash import SHA256
# Created here so that it is consistent
USER_ID = uuid.uuid4()
DEVICE_ID = uuid.uuid4()
# Configure SRP library for compatibility with Apple's implementation
srp.rfc5054_enable()
srp.no_username_in_x()
# Disable SSL Warning
import urllib3
urllib3.disable_warnings()
ANISETTE_URL = 'http://localhost:6969' # https://github.com/Dadoum/anisette-v3-server
def icloud_login_mobileme(username='', password='', second_factor='sms'):
if not username:
username = input('Apple ID: ')
if not password:
password = getpass('Password: ')
g = gsa_authenticate(username, password, second_factor)
pet = g["t"]["com.apple.gs.idms.pet"]["token"]
adsid = g["adsid"]
data = {
"apple-id": username,
"delegates": {"com.apple.mobileme":{}},
"password": pet,
"client-id": str(USER_ID),
}
data = plist.dumps(data)
headers = {
"X-Apple-ADSID": adsid,
"User-Agent": "com.apple.iCloudHelper/282 CFNetwork/1408.0.4 Darwin/22.5.0",
"X-Mme-Client-Info": '<MacBookPro18,3> <Mac OS X;13.4.1;22F8> <com.apple.AOSKit/282 (com.apple.accountsd/113)>'
}
headers.update(generate_anisette_headers())
r = requests.post(
"https://setup.icloud.com/setup/iosbuddy/loginDelegates",
auth=(username, pet),
data=data,
headers=headers,
verify=False,
)
return plist.loads(r.content)
def gsa_authenticate(username, password, second_factor='sms'):
# Password is None as we'll provide it later
usr = srp.User(username, bytes(), hash_alg=srp.SHA256, ng_type=srp.NG_2048)
_, A = usr.start_authentication()
r = gsa_authenticated_request({"A2k": A, "ps": ["s2k", "s2k_fo"], "u": username, "o": "init"})
if r["sp"] != "s2k":
print(f"This implementation only supports s2k. Server returned {r['sp']}")
return
# Change the password out from under the SRP library, as we couldn't calculate it without the salt.
usr.p = encrypt_password(password, r["s"], r["i"])
M = usr.process_challenge(r["s"], r["B"])
# Make sure we processed the challenge correctly
if M is None:
print("Failed to process challenge")
return
r = gsa_authenticated_request({"c": r["c"], "M1": M, "u": username, "o": "complete"})
# Make sure that the server's session key matches our session key (and thus that they are not an imposter)
usr.verify_session(r["M2"])
if not usr.authenticated():
print("Failed to verify session")
return
spd = decrypt_cbc(usr, r["spd"])
# For some reason plistlib doesn't accept it without the header...
PLISTHEADER = b"""\
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE plist PUBLIC '-//Apple//DTD PLIST 1.0//EN' 'http://www.apple.com/DTDs/PropertyList-1.0.dtd'>
"""
spd = plist.loads(PLISTHEADER + spd)
if "au" in r["Status"] and r["Status"]["au"] in ["trustedDeviceSecondaryAuth","secondaryAuth"]:
print("2FA required, requesting code")
# Replace bytes with strings
for k, v in spd.items():
if isinstance(v, bytes):
spd[k] = base64.b64encode(v).decode()
if second_factor == 'sms':
sms_second_factor(spd["adsid"], spd["GsIdmsToken"])
elif second_factor == 'trusted_device':
trusted_second_factor(spd["adsid"], spd["GsIdmsToken"])
return gsa_authenticate(username, password)
elif "au" in r["Status"]:
print(f"Unknown auth value {r['Status']['au']}")
return
else:
return spd
def gsa_authenticated_request(parameters):
body = {
"Header": {"Version": "1.0.1"},
"Request": {"cpd": generate_cpd()},
}
body["Request"].update(parameters)
headers = {
"Content-Type": "text/x-xml-plist",
"Accept": "*/*",
"User-Agent": "akd/1.0 CFNetwork/978.0.7 Darwin/18.7.0",
"X-MMe-Client-Info": '<MacBookPro18,3> <Mac OS X;13.4.1;22F8> <com.apple.AOSKit/282 (com.apple.dt.Xcode/3594.4.19)>'
}
resp = requests.post(
"https://gsa.apple.com/grandslam/GsService2",
headers=headers,
data=plist.dumps(body),
verify=False,
timeout=5,
)
return plist.loads(resp.content)["Response"]
def generate_cpd():
cpd = {
# Many of these values are not strictly necessary, but may be tracked by Apple
"bootstrap": True, # All implementations set this to true
"icscrec": True, # Only AltServer sets this to true
"pbe": False, # All implementations explicitly set this to false
"prkgen": True, # I've also seen ckgen
"svct": "iCloud", # In certian circumstances, this can be 'iTunes' or 'iCloud'
}
cpd.update(generate_anisette_headers())
return cpd
def generate_anisette_headers():
try:
import pyprovision
from ctypes import c_ulonglong
import secrets
adi = pyprovision.ADI("./data/anisette/")
adi.provisioning_path = "./data/anisette/"
device = pyprovision.Device("./data/anisette/device.json")
if not device.initialized:
# Pretend to be a MacBook Pro
device.server_friendly_description = "<MacBookPro13,2> <macOS;13.1;22C65> <com.apple.AuthKit/1 (com.apple.dt.Xcode/3594.4.19)>"
device.unique_device_identifier = str(uuid.uuid4()).upper()
device.adi_identifier = secrets.token_hex(8).lower()
device.local_user_uuid = secrets.token_hex(32).upper()
adi.identifier = device.adi_identifier
dsid = c_ulonglong(-2).value
is_prov = adi.is_machine_provisioned(dsid)
if not is_prov:
print("provisioning...")
provisioning_session = pyprovision.ProvisioningSession(adi, device)
provisioning_session.provision(dsid)
otp = adi.request_otp(dsid)
a = {"X-Apple-I-MD": base64.b64encode(bytes(otp.one_time_password)).decode(), "X-Apple-I-MD-M": base64.b64encode(bytes(otp.machine_identifier)).decode()}
except ImportError:
print(f'pyprovision is not installed, querying {ANISETTE_URL} for an anisette server')
h = json.loads(requests.get(ANISETTE_URL, timeout=5).text)
a = {"X-Apple-I-MD": h["X-Apple-I-MD"], "X-Apple-I-MD-M": h["X-Apple-I-MD-M"]}
a.update(generate_meta_headers(user_id=USER_ID, device_id=DEVICE_ID))
return a
def generate_meta_headers(serial="0", user_id=uuid.uuid4(), device_id=uuid.uuid4()):
return {
"X-Apple-I-Client-Time": datetime.utcnow().replace(microsecond=0).isoformat() + "Z",
"X-Apple-I-TimeZone": str(datetime.utcnow().astimezone().tzinfo),
"loc": locale.getdefaultlocale()[0] or "en_US",
"X-Apple-Locale": locale.getdefaultlocale()[0] or "en_US",
"X-Apple-I-MD-RINFO": "17106176", # either 17106176 or 50660608
"X-Apple-I-MD-LU": base64.b64encode(str(user_id).upper().encode()).decode(),
"X-Mme-Device-Id": str(device_id).upper(),
"X-Apple-I-SRL-NO": serial, # Serial number
}
def encrypt_password(password, salt, iterations):
p = hashlib.sha256(password.encode("utf-8")).digest()
return pbkdf2.PBKDF2(p, salt, iterations, SHA256).read(32)
def create_session_key(usr, name):
k = usr.get_session_key()
if k is None:
raise Exception("No session key")
return hmac.new(k, name.encode(), hashlib.sha256).digest()
def decrypt_cbc(usr, data):
extra_data_key = create_session_key(usr, "extra data key:")
extra_data_iv = create_session_key(usr, "extra data iv:")
# Get only the first 16 bytes of the iv
extra_data_iv = extra_data_iv[:16]
# Decrypt with AES CBC
cipher = Cipher(algorithms.AES(extra_data_key), modes.CBC(extra_data_iv))
decryptor = cipher.decryptor()
data = decryptor.update(data) + decryptor.finalize()
# Remove PKCS#7 padding
padder = padding.PKCS7(128).unpadder()
return padder.update(data) + padder.finalize()
def trusted_second_factor(dsid, idms_token):
identity_token = base64.b64encode((dsid + ":" + idms_token).encode()).decode()
headers = {
"Content-Type": "text/x-xml-plist",
"User-Agent": "Xcode",
"Accept": "text/x-xml-plist",
"Accept-Language": "en-us",
"X-Apple-Identity-Token": identity_token,
"X-Apple-App-Info": "com.apple.gs.xcode.auth",
"X-Xcode-Version": "11.2 (11B41)",
"X-Mme-Client-Info": '<MacBookPro18,3> <Mac OS X;13.4.1;22F8> <com.apple.AOSKit/282 (com.apple.dt.Xcode/3594.4.19)>'
}
headers.update(generate_anisette_headers())
# This will trigger the 2FA prompt on trusted devices
# We don't care about the response, it's just some HTML with a form for entering the code
# Easier to just use a text prompt
requests.get(
"https://gsa.apple.com/auth/verify/trusteddevice",
headers=headers,
verify=False,
timeout=10,
)
# Prompt for the 2FA code. It's just a string like '123456', no dashes or spaces
code = getpass("Enter 2FA code: ")
headers["security-code"] = code
# Send the 2FA code to Apple
resp = requests.get(
"https://gsa.apple.com/grandslam/GsService2/validate",
headers=headers,
verify=False,
timeout=10,
)
if resp.ok:
print("2FA successful")
def sms_second_factor(dsid, idms_token):
identity_token = base64.b64encode((dsid + ":" + idms_token).encode()).decode()
# TODO: Actually do this request to get user prompt data
# a = requests.get("https://gsa.apple.com/auth", verify=False)
# This request isn't strictly necessary though,
# and most accounts should have their id 1 SMS, if not contribute ;)
headers = {
"User-Agent": "Xcode",
"Accept-Language": "en-us",
"X-Apple-Identity-Token": identity_token,
"X-Apple-App-Info": "com.apple.gs.xcode.auth",
"X-Xcode-Version": "11.2 (11B41)",
"X-Mme-Client-Info": '<MacBookPro18,3> <Mac OS X;13.4.1;22F8> <com.apple.AOSKit/282 (com.apple.dt.Xcode/3594.4.19)>'
}
headers.update(generate_anisette_headers())
# TODO: Actually get the correct id, probably in the above GET
body = {"phoneNumber":{"id":1},"mode":"sms"}
# This will send the 2FA code to the user's phone over SMS
# We don't care about the response, it's just some HTML with a form for entering the code
# Easier to just use a text prompt
t = requests.put(
"https://gsa.apple.com/auth/verify/phone/",
json=body,
headers=headers,
verify=False,
timeout=5
)
# Prompt for the 2FA code. It's just a string like '123456', no dashes or spaces
code = input("Enter 2FA code: ")
body['securityCode'] = {'code': code}
# Send the 2FA code to Apple
resp = requests.post(
"https://gsa.apple.com/auth/verify/phone/securitycode",
json=body,
headers=headers,
verify=False,
timeout=5,
)
if resp.ok:
print("2FA successful")