-
Notifications
You must be signed in to change notification settings - Fork 7
/
steam_guard_account.go
290 lines (241 loc) · 8.45 KB
/
steam_guard_account.go
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
package mobileauth
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"net/http/cookiejar"
"net/url"
"regexp"
"strconv"
"strings"
)
var confIDRegex = regexp.MustCompile("data-confid=\"(\\d+)\"")
var confKeyRegex = regexp.MustCompile("data-key=\"(\\d+)\"")
var confDescRegex = regexp.MustCompile("<div>((Confirm|Trade with|Sell -) .+)</div>")
type SteamGuardAccount struct {
SharedSecret string `json:"shared_secret"`
SerialNumber string `json:"serial_number"`
RevocationCode string `json:"revocation_code"`
URI string `json:"uri"`
ServerTime int64 `json:"server_time,string"`
AccountName string `json:"account_name"`
TokenGID string `json:"token_gid"`
IdentitySecret string `json:"identity_secret"`
Secret1 string `json:"secret_1"`
Status int32 `json:"status"`
DeviceID string `json:"device_id"`
// Set to true if the authenticator has actually been applied to the account.
FullyEnrolled bool `json:"fully_enrolled"`
Session *SessionData `json:"session"`
}
func (a *SteamGuardAccount) DeactivateAuthenticator() error {
postData := url.Values{}
postData.Set("steamid", strconv.FormatUint(a.Session.SteamID, 10))
postData.Set("steamguard_scheme", "2")
postData.Set("revocation_code", a.RevocationCode)
postData.Set("access_token", a.Session.OAuthToken)
respBody, err := MobileLoginRequest(UrlTwoFactorService+"/RemoveAuthenticator/v0001", "POST", &postData, nil, nil)
if err != nil {
return err
}
r := removeAuthenticatorResponse{}
if err = json.Unmarshal(respBody, &r); err != nil {
return err
}
if r.Response == nil {
return errors.New("steam returned empty remove authenticator response")
}
if !r.Response.Success {
return errors.New("steam returned success false")
}
return nil
}
func (a *SteamGuardAccount) GenerateSteamGuardCode() (string, error) {
return a.GenerateSteamGuardCodeForTime(GetSteamTime())
}
func (a *SteamGuardAccount) GenerateSteamGuardCodeForTime(t int64) (string, error) {
if a.SharedSecret == "" {
return "", errors.New("shared secret not set")
}
// Shared secret is our key
sharedSecretBytes, err := base64.StdEncoding.DecodeString(a.SharedSecret)
if err != nil {
return "", err
}
// Time for code
t = t / 30 // TODO: why we are doing this???
timeBytes := make([]byte, 8)
binary.BigEndian.PutUint64(timeBytes, uint64(t))
// Generate hmac
hmacGenerator := hmac.New(sha1.New, sharedSecretBytes)
hmacGenerator.Write(timeBytes)
mac := hmacGenerator.Sum(nil)
// the last 4 bits of the mac say where the code starts
// (e.g. if last 4 bit are 1100, we start at byte 12)
start := int(mac[19] & 0x0f)
// extract code - 4 bytes
codeBytes := make([]byte, 4)
copy(codeBytes, mac[start:])
fullCode := binary.BigEndian.Uint32(codeBytes)
fullCode = fullCode & 0x7fffffff
// character set for authenticator code
chars := []byte{50, 51, 52, 53, 54, 55, 56, 57, 66, 67, 68, 70, 71, 72, 74, 75, 77, 78, 80, 81, 82, 84, 86, 87, 88, 89}
// build the alphanumeric code
var textCodeBytes []byte
for i := 0; i < 5; i++ {
textCodeBytes = append(textCodeBytes, chars[fullCode%uint32(len(chars))])
fullCode = fullCode / uint32(len(chars))
}
return string(textCodeBytes[:]), nil
}
func (a *SteamGuardAccount) FetchConfirmations() ([]*Confirmation, error) {
queryParams, err := a.GenerateConfirmationQueryParams("conf")
if err != nil {
return nil, fmt.Errorf("failed to generated confirmation query params: %v", err)
}
cookies, _ := cookiejar.New(nil)
a.Session.AddCookies(cookies)
respBody, err := WebRequest(UrlConfirmationService+"/conf", "GET", &queryParams, cookies, nil, nil)
if err != nil {
return nil, err
}
respString := string(respBody)
// Nothing to confirm
if strings.Contains(respString, "<div>Nothing to confirm</div>") {
return nil, nil
}
if strings.Contains(respString, "<div>There was a problem loading the confirmations page. Please try your request again later.</div>") {
return nil, errors.New("steam failed to return confirmations page, try again later")
}
// Try to parse response
confIDs := confIDRegex.FindAllStringSubmatch(respString, -1)
confKeys := confKeyRegex.FindAllStringSubmatch(respString, -1)
confDescs := confDescRegex.FindAllStringSubmatch(respString, -1)
if confIDs == nil || confKeys == nil || confDescs == nil {
return nil, errors.New("failed to parse response")
}
if len(confIDs) != len(confKeys) || len(confIDs) != len(confDescs) {
return nil, errors.New("unexpected response format: number of ids, keys and descriptions are not the same")
}
// Create confirmations slice
var confirmations []*Confirmation
for index, _ := range confIDs {
cn := &Confirmation{
ConfirmationID: confIDs[index][1],
ConfirmationKey: confKeys[index][1],
ConfirmationDescription: confDescs[index][1],
}
confirmations = append(confirmations, cn)
}
return confirmations, nil
}
func (a *SteamGuardAccount) AcceptConfirmation(cn *Confirmation) error {
return a._sendConfirmationAjax(cn, "allow")
}
func (a *SteamGuardAccount) DenyConfirmation(cn *Confirmation) error {
return a._sendConfirmationAjax(cn, "cancel")
}
// Refreshes the Steam session. Necessary to perform confirmations if your session has expired or changed.
func (a *SteamGuardAccount) RefreshSession() error {
postData := url.Values{}
postData.Set("access_token", a.Session.OAuthToken)
respBody, err := WebRequest(UrlMobileAuthService+"/GetWGToken/v0001", "POST", &postData, nil, nil, nil)
if err != nil {
return err
}
r := refreshSessionDataResponse{}
if err = json.Unmarshal(respBody, &r); err != nil {
return err
}
if r.Response == nil {
return errors.New("steam returned empty refresh session data response")
}
if r.Response.Token == "" {
return errors.New("steam returned empty token")
}
stringSteamID := strconv.FormatUint(a.Session.SteamID, 10)
token := stringSteamID + "%7C%7C" + r.Response.Token
tokenSecure := stringSteamID + "%7C%7C" + r.Response.TokenSecure
a.Session.SteamLogin = token
a.Session.SteamLoginSecure = tokenSecure
return nil
}
func (a *SteamGuardAccount) _sendConfirmationAjax(cn *Confirmation, op string) error {
queryParams, err := a.GenerateConfirmationQueryParams(op)
if err != nil {
return fmt.Errorf("failed to generated confirmation query params: %v", err)
}
queryParams.Set("op", op)
queryParams.Set("cid", cn.ConfirmationID)
queryParams.Set("ck", cn.ConfirmationKey)
cookies, _ := cookiejar.New(nil)
a.Session.AddCookies(cookies)
// TODO: do we need this???
//referer := urlConfirmationService + "/conf"
respBody, err := WebRequest(UrlConfirmationService+"/ajaxop", "GET", &queryParams, cookies, nil, nil)
if err != nil {
return err
}
r := sendConfirmationResponse{}
if err = json.Unmarshal(respBody, &r); err != nil {
return err
}
if !r.Success {
return errors.New("steam returned success false")
}
return nil
}
func (a *SteamGuardAccount) GenerateConfirmationQueryParams(tag string) (url.Values, error) {
if a.DeviceID == "" {
return nil, errors.New("Device ID is empty")
}
t := GetSteamTime()
queryParams := url.Values{}
queryParams.Set("p", a.DeviceID)
queryParams.Set("a", strconv.FormatUint(a.Session.SteamID, 10))
queryParams.Set("k", a._generateConfirmationHashForTime(t, tag))
queryParams.Set("t", strconv.FormatInt(t, 10))
queryParams.Set("m", "android")
queryParams.Set("tag", tag)
return queryParams, nil
}
func (a *SteamGuardAccount) _generateConfirmationHashForTime(t int64, tag string) string {
identitySecretBytes, err := base64.StdEncoding.DecodeString(a.IdentitySecret)
if err != nil {
// TODO: maybe we shall panic or return error up the chain
return ""
}
data := make([]byte, 8)
binary.BigEndian.PutUint64(data, uint64(t))
tagBytes := []byte(tag)
if len(tagBytes) > 32 {
// maximum tag length is 32 bytes
tagBytes = tagBytes[:32]
}
data = append(data, tagBytes...)
// Generate hmac
hmacGenerator := hmac.New(sha1.New, identitySecretBytes)
hmacGenerator.Write(data)
mac := hmacGenerator.Sum(nil)
return base64.StdEncoding.EncodeToString(mac)
}
type refreshSessionDataResponse struct {
Response *refreshSessionDataResult `json:"response"`
}
type refreshSessionDataResult struct {
Token string `json:"token"`
TokenSecure string `json:"token_secure"`
}
type removeAuthenticatorResponse struct {
Response *removeAuthenticatorResult `json:"response"`
}
type removeAuthenticatorResult struct {
Success bool `json:"success"`
}
type sendConfirmationResponse struct {
Success bool `json:"success"`
}