-
Notifications
You must be signed in to change notification settings - Fork 2
/
account_service.go
373 lines (311 loc) · 9.5 KB
/
account_service.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
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
package logic
import (
"crypto"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"encoding/hex"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"time"
"github.com/copernet/whccommon/log"
common "github.com/copernet/whccommon/model"
"github.com/copernet/whcwallet/api/errs"
"github.com/copernet/whcwallet/config"
"github.com/copernet/whcwallet/model"
"github.com/copernet/whcwallet/model/view"
"github.com/copernet/whcwallet/util"
"github.com/gin-gonic/gin"
"github.com/hgfischer/go-otp"
"github.com/tidwall/gjson"
)
type AccountService struct{}
func (a *AccountService) ChallengeLogic(uuid string) (*view.ChallengeVO, error) {
sessionId := util.CryptoSha256(config.GetConf().Private.SessionSecret + uuid)
salt := util.CryptoSha256(config.GetConf().Private.ServerSecret + uuid)
powChallenge := util.GenSalt(16)
challenge := util.GenSalt(16)
session, exist := model.GetSessionById(sessionId)
if !exist {
session = &common.Session{
SessionID: sessionId,
Challenge: &challenge,
PChallenge: &powChallenge,
}
err := model.CreateSession(session)
if err != nil {
return nil, process(err)
}
} else {
session.Challenge, session.PChallenge = &challenge, &powChallenge
err := model.UpdateSessionById(session)
if err != nil {
return nil, process(err)
}
}
return &view.ChallengeVO{
Salt: salt,
PowChallenge: powChallenge,
Challenge: challenge,
}, nil
}
/**
Create wallet && update Session PubKey
*/
func (a *AccountService) CreateWallet(c *gin.Context, param *view.WalletCreateParam) error {
sessionId := util.CryptoSha256(config.GetConf().Private.SessionSecret + param.Uuid)
session, exist := model.GetSessionById(sessionId)
if !exist {
return errors.New(errs.UuidNotExist)
}
if failedChallenge(*session.PChallenge, param.Nonce) || failedRecaptcha(c, param.RecaptchaResp) {
return errors.New(errs.PermissionRefused)
}
wallet, exist := model.GetWalletById(param.Uuid)
if exist {
return errors.New(errs.UuidDuplicate)
}
now := time.Now()
wallet = &common.Wallet{
WalletID: param.Uuid,
LastLogin: now,
LastBackup: now,
WalletBlob: param.Wallet,
Email: param.Email,
}
// CreateWallet
err := model.CreateWallet(wallet)
if err != nil {
return process(err, param.Email)
}
//rsync send mail
go util.Mail(param,c)
// Reset session
session.PubKey, session.PChallenge = param.PublicKey, nil
//Update PublicKey
return process(model.UpdateSessionById(session))
}
func failedRecaptcha(c *gin.Context, recaptchaResp string) bool {
if recaptchaResp != "" {
data := url.Values{
"secret": {config.GetConf().Private.RecaptchaPrivate},
"response": {recaptchaResp},
}
uri := "https://www.google.com/recaptcha/api/siteverify"
res, err := http.PostForm(uri, data)
if err != nil {
log.WithCtx(c).Info("failedPost:" + err.Error())
return true
}
defer res.Body.Close()
if res.StatusCode != 200 {
log.WithCtx(c).Error("request recapthca validation failed from google")
return true
}
content, err := ioutil.ReadAll(res.Body)
if err != nil {
log.WithCtx(c).Info("failedRecaptcha:" + err.Error())
return true
}
// here using gjson package for analyzing the request result
if gjson.Get(string(content), "success").Bool() {
// render a error page if failed
return false
}
}
return false
}
func failedChallenge(pcChallenge string, nonce string) bool {
res := util.CryptoSha256(pcChallenge + nonce)
ret := res[len(res)-len(config.GetConf().Private.LoginDifficulty):] !=
config.GetConf().Private.LoginDifficulty
return ret
}
/**
update Wallet info
*/
func (a *AccountService) UpdateWallet(c *gin.Context, param view.WalletUpdateParam) error {
sessionId := util.CryptoSha256(config.GetConf().Private.SessionSecret + param.Uuid)
session, exist := model.GetSessionById(sessionId)
if !exist {
return errors.New(errs.UuidNotExist)
}
log.WithCtx(c).Infof("pemStr%s,challenge:%s,signature:%s", session.PubKey, *session.Challenge, param.Signature)
if !verifyRsaSignature(session.PubKey, *session.Challenge, param.Signature) {
return errors.New(errs.PermissionRefused)
}
if param.MfaAction != "" && param.MfaAction != Add && param.MfaAction != Del {
return errors.New(errs.MfaActionNil)
}
wallet, exist := model.GetWalletById(param.Uuid)
if !exist {
return errors.New(errs.UuidNotExist)
}
//verify mfa
if param.MfaToken != "" && param.MfaAction != "" && !UpdateMfa(wallet, param) {
log.WithCtx(c).Errorf("VerifyMfa Fail,token:%s,secret:%s", param.MfaToken, param.MfaSecret)
return errors.New(errs.PermissionRefused)
}
//Reset session
session.Challenge = nil
model.UpdateSessionById(session)
if param.Wallet != ""{
wallet.WalletBlob = param.Wallet
}
if param.Email != ""{
wallet.Email = param.Email
}
//update wallet
return process(model.UpdateWallet(wallet),param.Email)
}
func verifyRsaSignature(pemStr string, challenge string, signature string) bool {
block, _ := pem.Decode([]byte(pemStr))
pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return false
}
hash := sha1.New()
hash.Write([]byte(challenge))
sign, _ := hex.DecodeString(signature)
err = rsa.VerifyPKCS1v15(pubKey.(*rsa.PublicKey), crypto.SHA1, hash.Sum(nil), sign)
if err != nil {
return false
}
return true
}
func (a *AccountService) LoginWallet(c *gin.Context, param view.WalletLoginParam) (*view.WalletVO, error) {
sessionId := util.CryptoSha256(config.GetConf().Private.SessionSecret + param.Uuid)
session, exist := model.GetSessionById(sessionId)
if !exist {
return nil, errors.New(errs.UuidNotExist)
}
if failedChallenge(*session.PChallenge, param.Nonce) || failedRecaptcha(c, param.RecaptchaResp) {
return nil, errors.New(errs.PermissionRefused)
}
wallet, exist := model.GetWalletById(param.Uuid)
if !exist {
return nil, errors.New(errs.UuidNotExist)
}
res := &view.WalletVO{Wallet: wallet.WalletBlob, Mfa: false}
if wallet.Settings != "" {
var setting model.WalletSetting
err := json.Unmarshal([]byte(wallet.Settings), &setting)
if err != nil {
log.WithCtx(c).Errorf("Unmarshal Settings error:%s", err.Error())
return nil, errors.New(errs.PermissionRefused)
}
if setting.MfaSecret.Value != "" {
if param.Mfatoken == "" {
return nil, errors.New(errs.MfaTokenNil)
}
secret, _ := util.AesDecrypt(setting.MfaSecret.Value, []byte(config.GetConf().Private.AesSecret))
res.Mfa = VerifyMfa(param.Mfatoken, secret)
if !res.Mfa {
log.WithCtx(c).Info("VerifyMfa failed.")
return nil, errors.New(errs.PermissionRefused)
}
//AesDecrypt asq
asq := setting.Asq
asq.Value, err = util.AesDecrypt(asq.Value, []byte(config.GetConf().Private.AesSecret))
if err != nil {
log.WithCtx(c).Errorf("AesDecrypt error:%s", err.Error())
return nil, errors.New(errs.PermissionRefused)
}
var qa model.QuestionAnswer
err = json.Unmarshal([]byte(asq.Value), &qa)
if err != nil {
log.WithCtx(c).Errorf("Unmarshal asq error:%s", err.Error())
return nil, errors.New(errs.PermissionRefused)
}
res.Asq = qa.Question
}
} else if param.Mfatoken != "" {
return nil, errors.New(errs.MfaTokenNotNil)
}
//Reset session
session.PubKey, session.PChallenge = param.PublicKey, nil
err := model.UpdateSessionById(session)
if err != nil {
return nil, err
}
//Update Last Login
wallet.LastLogin = time.Now()
err = model.UpdateWallet(wallet)
if err != nil {
return nil, process(err)
}
return res, nil
}
func (a *AccountService) VerifyWallet(param view.WalletVerifyParam) error {
if param.Email != "" {
noExist := model.VerifyWalletByEmail(param.Email)
if !noExist {
return errors.New(fmt.Sprintf(errs.DuplicateEmail, param.Email))
}
}
return nil
}
func (a *AccountService) NewMfa(uuid string) *view.MfaVO {
return NewMfa(uuid)
}
const (
Add string = "add"
Del string = "del"
)
func ProvisionUri(secret string, user string, issuer string) string {
auth := "totp/"
q := make(url.Values)
q.Add("secret", secret)
if issuer != "" {
//q.Add("issuer", issuer)
auth += issuer + ":"
}
return "otpauth://" + auth + user + "?" + q.Encode()
}
func VerifyMfa(token string, secret string) bool {
totp := &otp.TOTP{
Secret: secret,
Length: uint8(otp.DefaultLength),
Period: uint8(otp.DefaultPeriod),
IsBase32Secret: true,
}
return totp.Verify(token)
}
func NewMfa(uuid string) *view.MfaVO {
secret := util.RandomBase32(16)
prov := ProvisionUri(secret, uuid, "whcwallet")
return &view.MfaVO{Secret: secret, Prov: prov}
}
func UpdateMfa(wallet *common.Wallet, param view.WalletUpdateParam) bool {
var setting model.WalletSetting
if param.MfaAction == Add {
if !VerifyMfa(param.MfaToken, param.MfaSecret) {
return false
}
sec, _ := util.AesEncrypt([]byte(param.MfaSecret), []byte(config.GetConf().Private.AesSecret))
setting.MfaSecret = model.Secret{Value: sec, CreateAt: time.Now(), UpdateAt: time.Now()}
asq := &model.QuestionAnswer{Question: param.Question, Answer: param.Answer}
data, _ := json.Marshal(asq)
asqEnc, _ := util.AesEncrypt(data, []byte(config.GetConf().Private.AesSecret))
setting.Asq = model.Secret{Value: asqEnc, CreateAt: time.Now(), UpdateAt: time.Now()}
} else {
err := json.Unmarshal([]byte(wallet.Settings), &setting)
if err != nil {
return false
}
secret, _ := util.AesDecrypt(setting.MfaSecret.Value, []byte(config.GetConf().Private.AesSecret))
if !VerifyMfa(param.MfaToken, secret) {
return false
}
setting.MfaSecret.Value = ""
setting.MfaSecret.UpdateAt = time.Now()
}
data, _ := json.Marshal(setting)
wallet.Settings = string(data)
return true
}