-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathwebauth.py
More file actions
428 lines (349 loc) · 17.1 KB
/
webauth.py
File metadata and controls
428 lines (349 loc) · 17.1 KB
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
# -*- coding: utf-8 -*-
"""
This module simplifies the process of obtaining an authenticated session for steam websites.
After authentication is completed, a :class:`requests.Session` is created containing the auth cookies.
The session can be used to access ``steamcommunity.com``, ``store.steampowered.com``, and ``help.steampowered.com``.
.. warning::
A web session may expire randomly, or when you login from different IP address.
Some pages will return status code `401` when that happens.
Keep in mind if you are trying to write robust code.
.. note::
If you are using :class:`.SteamClient` take a look at :meth:`.SteamClient.get_web_session()`
.. note::
If you need to authenticate as a mobile device for things like trading confirmations
use :class:`MobileWebAuth` instead. The login process is identical, and in addition
you will get :attr:`.oauth_token`.
Example usage:
.. code:: python
import steam.webauth as wa
user = wa.WebAuth('username')
# At a console, cli_login can be used to easily perform all login steps
session = user.cli_login('password')
session.get('https://store.steampowered.com/account/history')
# Or the login steps be implemented for other situation like so
try:
user.login('password')
except (wa.CaptchaRequired, wa.LoginIncorrect) as exp:
if isinstance(exp, LoginIncorrect):
# ask for new password
else:
password = self.password
if isinstance(exp, wa.CaptchaRequired):
print user.captcha_url
# ask a human to solve captcha
else:
captcha = None
user.login(password=password, captcha=captcha)
except wa.EmailCodeRequired:
user.login(email_code='ZXC123')
except wa.TwoFactorCodeRequired:
user.login(twofactor_code='ZXC123')
user.session.get('https://store.steampowered.com/account/history/')
"""
import json
from time import time
from base64 import b64encode
from getpass import getpass
import six
import requests
from steam.steamid import SteamID
from steam.utils.web import make_requests_session, generate_session_id
from steam.core.crypto import rsa_publickey, pkcs1v15_encrypt
if six.PY2:
intBase = long
_cli_input = raw_input
else:
intBase = int
_cli_input = input
class WebAuth(object):
key = None
logged_on = False #: whether authentication has been completed successfully
session = None #: :class:`requests.Session` (with auth cookies after auth is completed)
session_id = None #: :class:`str`, session id string
captcha_gid = -1
captcha_code = ''
steam_id = None #: :class:`.SteamID` (after auth is completed)
def __init__(self, username, password=''):
self.__dict__.update(locals())
self.session = make_requests_session()
self._session_setup()
def _session_setup(self):
pass
@property
def captcha_url(self):
"""If a captch is required this property will return url to the image, or ``None``"""
if self.captcha_gid == -1:
return None
else:
return "https://steamcommunity.com/login/rendercaptcha/?gid=%s" % self.captcha_gid
def get_rsa_key(self, username):
"""Get rsa key for a given username
:param username: username
:type username: :class:`str`
:return: json response
:rtype: :class:`dict`
:raises HTTPError: any problem with http request, timeouts, 5xx, 4xx etc
"""
try:
resp = self.session.post('https://steamcommunity.com/login/getrsakey/',
timeout=15,
data={
'username': username,
'donotcache': int(time() * 1000),
},
).json()
except requests.exceptions.RequestException as e:
raise HTTPError(str(e))
return resp
def _load_key(self):
if not self.key:
resp = self.get_rsa_key(self.username)
self.key = rsa_publickey(intBase(resp['publickey_mod'], 16),
intBase(resp['publickey_exp'], 16),
)
self.timestamp = resp['timestamp']
def _send_login(self, password='', captcha='', email_code='', twofactor_code=''):
data = {
'username': self.username,
"password": b64encode(pkcs1v15_encrypt(self.key, password.encode('ascii'))),
"emailauth": email_code,
"emailsteamid": str(self.steam_id) if email_code else '',
"twofactorcode": twofactor_code,
"captchagid": self.captcha_gid,
"captcha_text": captcha,
"loginfriendlyname": "python-steam webauth",
"rsatimestamp": self.timestamp,
"remember_login": 'true',
"donotcache": int(time() * 100000),
}
try:
return self.session.post('https://steamcommunity.com/login/dologin/', data=data, timeout=15).json()
except requests.exceptions.RequestException as e:
raise HTTPError(str(e))
def _finalize_login(self, login_response):
if "transfer_parameters" in login_response and ["steamid"] in login_response['transfer_parameters']:
self.steam_id = SteamID(login_response['transfer_parameters']['steamid'])
return
elif "success" in login_response and login_response['success'] and self.session:
# If logging in with 2FA, steamid is not returned in transfer_parameters
# fetch the steamid from the cookies instead
# The first 17 chars of steamLoginSecure cookie is the steamid
steam_login_secure = self.session.cookies.get('steamLoginSecure', domain='steamcommunity.com')
id_from_cookie = steam_login_secure[:17] if steam_login_secure else None
if id_from_cookie and id_from_cookie.isdigit():
self.steam_id = SteamID(id_from_cookie)
return # Success
raise LoginIncorrect("Could not finalize login, no steamid returned")
def login(self, password='', captcha='', email_code='', twofactor_code='', language='english'):
"""Attempts web login and returns on a session with cookies set
:param password: password, if it wasn't provided on instance init
:type password: :class:`str`
:param captcha: text reponse for captcha challenge
:type captcha: :class:`str`
:param email_code: email code for steam guard
:type email_code: :class:`str`
:param twofactor_code: 2FA code for steam guard
:type twofactor_code: :class:`str`
:param language: select language for steam web pages (sets language cookie)
:type language: :class:`str`
:return: a session on success and :class:`None` otherwise
:rtype: :class:`requests.Session`, :class:`None`
:raises HTTPError: any problem with http request, timeouts, 5xx, 4xx etc
:raises LoginIncorrect: wrong username or password
:raises CaptchaRequired: when captcha is needed
:raises CaptchaRequiredLoginIncorrect: when captcha is needed and login is incorrect
:raises EmailCodeRequired: when email is needed
:raises TwoFactorCodeRequired: when 2FA is needed
"""
if self.logged_on:
return self.session
if password:
self.password = password
elif self.password:
password = self.password
else:
raise LoginIncorrect("password is not specified")
if not captcha and self.captcha_code:
captcha = self.captcha_code
self._load_key()
resp = self._send_login(password=password, captcha=captcha, email_code=email_code, twofactor_code=twofactor_code)
if resp and resp['success'] and resp['login_complete']:
self.logged_on = True
self.password = self.captcha_code = ''
self.captcha_gid = -1
for cookie in list(self.session.cookies):
for domain in ['store.steampowered.com', 'help.steampowered.com', 'steamcommunity.com']:
self.session.cookies.set(cookie.name, cookie.value, domain=domain, secure=cookie.secure)
self.session_id = generate_session_id()
for domain in ['store.steampowered.com', 'help.steampowered.com', 'steamcommunity.com']:
self.session.cookies.set('Steam_Language', language, domain=domain)
self.session.cookies.set('birthtime', '-3333', domain=domain)
self.session.cookies.set('sessionid', self.session_id, domain=domain)
self._finalize_login(resp)
return self.session
else:
if resp.get('captcha_needed', False):
self.captcha_gid = resp['captcha_gid']
self.captcha_code = ''
if resp.get('clear_password_field', False):
self.password = ''
raise CaptchaRequiredLoginIncorrect(resp['message'])
else:
raise CaptchaRequired(resp['message'])
elif resp.get('emailauth_needed', False):
self.steam_id = SteamID(resp['emailsteamid'])
raise EmailCodeRequired(resp['message'])
elif resp.get('requires_twofactor', False):
raise TwoFactorCodeRequired(resp['message'])
elif 'too many login failures' in resp.get('message', ''):
raise TooManyLoginFailures(resp['message'])
else:
self.password = ''
raise LoginIncorrect(resp['message'])
def cli_login(self, password='', captcha='', email_code='', twofactor_code='', language='english'):
"""Generates CLI prompts to perform the entire login process
:param password: password, if it wasn't provided on instance init
:type password: :class:`str`
:param captcha: text reponse for captcha challenge
:type captcha: :class:`str`
:param email_code: email code for steam guard
:type email_code: :class:`str`
:param twofactor_code: 2FA code for steam guard
:type twofactor_code: :class:`str`
:param language: select language for steam web pages (sets language cookie)
:type language: :class:`str`
:return: a session on success and :class:`None` otherwise
:rtype: :class:`requests.Session`, :class:`None`
.. code:: python
In [3]: user.cli_login()
Enter password for 'steamuser':
Solve CAPTCHA at https://steamcommunity.com/login/rendercaptcha/?gid=1111111111111111111
CAPTCHA code: 123456
Invalid password for 'steamuser'. Enter password:
Solve CAPTCHA at https://steamcommunity.com/login/rendercaptcha/?gid=2222222222222222222
CAPTCHA code: abcdef
Enter 2FA code: AB123
Out[3]: <requests.sessions.Session at 0x6fffe56bef0>
"""
# loop until successful login
while True:
try:
return self.login(password, captcha, email_code, twofactor_code, language)
except (LoginIncorrect, CaptchaRequired) as exp:
email_code = twofactor_code = ''
if isinstance(exp, LoginIncorrect):
prompt = ("Enter password for %s: " if not password else
"Invalid password for %s. Enter password: ")
password = getpass(prompt % repr(self.username))
if isinstance(exp, CaptchaRequired):
prompt = "Solve CAPTCHA at %s\nCAPTCHA code: " % self.captcha_url
captcha = _cli_input(prompt)
else:
captcha = ''
except EmailCodeRequired:
prompt = ("Enter email code: " if not email_code else
"Incorrect code. Enter email code: ")
email_code, twofactor_code = _cli_input(prompt), ''
except TwoFactorCodeRequired:
prompt = ("Enter 2FA code: " if not twofactor_code else
"Incorrect code. Enter 2FA code: ")
email_code, twofactor_code = '', _cli_input(prompt)
class MobileWebAuth(WebAuth):
"""Identical to :class:`WebAuth`, except it authenticates as a mobile device."""
oauth_token = None #: holds oauth_token after successful login
def _send_login(self, password='', captcha='', email_code='', twofactor_code=''):
data = {
'username': self.username,
"password": b64encode(pkcs1v15_encrypt(self.key, password.encode('ascii'))),
"emailauth": email_code,
"emailsteamid": str(self.steam_id) if email_code else '',
"twofactorcode": twofactor_code,
"captchagid": self.captcha_gid,
"captcha_text": captcha,
"loginfriendlyname": "python-steam webauth",
"rsatimestamp": self.timestamp,
"remember_login": 'true',
"donotcache": int(time() * 100000),
"oauth_client_id": "DE45CD61",
"oauth_scope": "read_profile write_profile read_client write_client",
}
self.session.cookies.set('mobileClientVersion', '0 (2.1.3)')
self.session.cookies.set('mobileClient', 'android')
try:
return self.session.post('https://steamcommunity.com/login/dologin/', data=data, timeout=15).json()
except requests.exceptions.RequestException as e:
raise HTTPError(str(e))
finally:
self.session.cookies.pop('mobileClientVersion', None)
self.session.cookies.pop('mobileClient', None)
def _finalize_login(self, login_response):
data = json.loads(login_response['oauth'])
self.steam_id = SteamID(data['steamid'])
self.oauth_token = data['oauth_token']
def oauth_login(self, oauth_token='', steam_id='', language='english'):
"""Attempts a mobile authenticator login using an oauth token, which can be obtained from a previously logged-in
`MobileWebAuth`
:param oauth_token: oauth token string, if it wasn't provided on instance init
:type oauth_token: :class:`str`
:param steam_id: `SteamID` of the account to log into, if it wasn't provided on instance init
:type steam_id: :class:`str` or :class:`SteamID`
:param language: select language for steam web pages (sets language cookie)
:type language: :class:`str`
:return: a session on success and :class:`None` otherwise
:rtype: :class:`requests.Session`, :class:`None`
:raises HTTPError: any problem with http request, timeouts, 5xx, 4xx etc
:raises LoginIncorrect: Invalid token or SteamID
"""
if oauth_token:
self.oauth_token = oauth_token
elif self.oauth_token:
oauth_token = self.oauth_token
else:
raise LoginIncorrect('token is not specified')
if steam_id:
self.steam_id = SteamID(steam_id)
elif not self.steam_id:
raise LoginIncorrect('steam_id is not specified')
steam_id = self.steam_id.as_64
data = {
'access_token': oauth_token
}
try:
resp = self.session.post('https://api.steampowered.com/IMobileAuthService/GetWGToken/v0001', data=data)
except requests.exceptions.RequestException as e:
raise HTTPError(str(e))
try:
resp_data = resp.json()['response']
except json.decoder.JSONDecodeError as e:
if 'Please verify your <pre>key=</pre> parameter.' in resp.text:
raise LoginIncorrect('invalid token')
else:
raise e
self.session_id = generate_session_id()
for domain in ['store.steampowered.com', 'help.steampowered.com', 'steamcommunity.com']:
self.session.cookies.set('birthtime', '-3333', domain=domain)
self.session.cookies.set('sessionid', self.session_id, domain=domain)
self.session.cookies.set('mobileClientVersion', '0 (2.1.3)', domain=domain)
self.session.cookies.set('mobileClient', 'android', domain=domain)
self.session.cookies.set('steamLogin', str(steam_id) + "%7C%7C" + resp_data['token'], domain=domain)
self.session.cookies.set('steamLoginSecure', str(steam_id) + "%7C%7C" + resp_data['token_secure'],
domain=domain, secure=True)
self.session.cookies.set('Steam_Language', language, domain=domain)
self.logged_on = True
return self.session
class WebAuthException(Exception):
pass
class HTTPError(WebAuthException):
pass
class LoginIncorrect(WebAuthException):
pass
class CaptchaRequired(WebAuthException):
pass
class CaptchaRequiredLoginIncorrect(CaptchaRequired, LoginIncorrect):
pass
class EmailCodeRequired(WebAuthException):
pass
class TwoFactorCodeRequired(WebAuthException):
pass
class TooManyLoginFailures(WebAuthException):
pass