forked from sijms/go-ora
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth_object.go
449 lines (425 loc) · 11.8 KB
/
auth_object.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
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
package go_ora
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/des"
"crypto/md5"
"crypto/rand"
"crypto/sha1"
"encoding/hex"
"errors"
"fmt"
"github.com/sijms/go-ora/network"
"strconv"
"strings"
"time"
)
// E infront of the variable means encrypted
type AuthObject struct {
EServerSessKey string
EClientSessKey string
EPassword string
ServerSessKey []byte
ClientSessKey []byte
KeyHash []byte
Salt string
VerifierType int
tcpNego *TCPNego
}
func NewAuthObject(username string, password string, tcpNego *TCPNego, session *network.Session) (*AuthObject, error) {
ret := new(AuthObject)
ret.tcpNego = tcpNego
loop := true
for loop {
messageCode, err := session.GetByte()
if err != nil {
return nil, err
}
switch messageCode {
case 4:
session.Summary, err = network.NewSummary(session)
if err != nil {
return nil, err
}
if session.HasError() {
return nil, session.GetError()
}
loop = false
case 8:
dictLen, err := session.GetInt(4, true, true)
if err != nil {
return nil, err
}
for x := 0; x < dictLen; x++ {
key, val, num, err := session.GetKeyVal()
if err != nil {
return nil, err
}
if bytes.Compare(key, []byte("AUTH_SESSKEY")) == 0 {
ret.EServerSessKey = string(val)
} else if bytes.Compare(key, []byte("AUTH_VFR_DATA")) == 0 {
ret.Salt = string(val)
ret.VerifierType = num
}
}
default:
return nil, errors.New(fmt.Sprintf("message code error: received code %d and expected code is 8", messageCode))
}
}
var key []byte
padding := false
var err error
if ret.VerifierType == 0 {
key, err = getKeyFromUserNameAndPassword(username, password)
if err != nil {
return nil, err
}
ret.ServerSessKey, err = decryptSessionKey2(key[:8], ret.EServerSessKey)
if err != nil {
return nil, err
}
ret.EPassword, err = encryptPassword2(password, ret.ServerSessKey)
if err != nil {
return nil, err
}
return ret, nil
} else if ret.VerifierType == 2361 {
key, err = getKeyFromUserNameAndPassword(username, password)
if err != nil {
return nil, err
}
} else if ret.VerifierType == 6949 {
if ret.tcpNego.ServerCompileTimeCaps[4]&2 == 0 {
padding = true
}
result, err := hex.DecodeString(ret.Salt)
if err != nil {
return nil, err
}
result = append([]byte(password), result...)
hash := sha1.New()
_, err = hash.Write(result)
if err != nil {
return nil, err
}
key = hash.Sum(nil) // 20 byte key
key = append(key, 0, 0, 0, 0) // 24 byte key
} else {
return nil, errors.New("unsupported verifier type")
}
// get the server session key
ret.ServerSessKey, err = decryptSessionKey(padding, key, ret.EServerSessKey)
if err != nil {
return nil, err
}
// generate new key for client
ret.ClientSessKey = make([]byte, len(ret.ServerSessKey))
for {
_, err = rand.Read(ret.ClientSessKey)
if err != nil {
return nil, err
}
if !bytes.Equal(ret.ClientSessKey, ret.ServerSessKey) {
break
}
}
// encrypt the client key
ret.EClientSessKey, err = EncryptSessionKey(padding, key, ret.ClientSessKey)
if err != nil {
return nil, err
}
// get the hash key form server and client session key
ret.KeyHash, err = CalculateKeysHash(ret.VerifierType, ret.ServerSessKey[16:], ret.ClientSessKey[16:])
if err != nil {
return nil, err
}
// encrypt the password
ret.EPassword, err = EncryptPassword(password, ret.KeyHash)
if err != nil {
return nil, err
}
return ret, nil
}
func (obj *AuthObject) Write(connOption *network.ConnectionOption, mode LogonMode, session *network.Session) error {
session.ResetBuffer()
keyValSize := 22
session.PutBytes(3, 0x73, 0)
if len(connOption.UserID) > 0 {
session.PutInt(1, 1, false, false)
session.PutInt(len(connOption.UserID), 4, true, true)
} else {
session.PutBytes(0, 0)
}
if len(connOption.UserID) > 0 && len(obj.EPassword) > 0 {
mode |= UserAndPass
}
session.PutUint(int(mode), 4, true, true)
session.PutUint(1, 1, false, false)
session.PutUint(keyValSize, 4, true, true)
session.PutBytes(1, 1)
if len(connOption.UserID) > 0 {
//session.PutBytes([]byte(connOption.UserID)...)
session.PutClr([]byte(connOption.UserID))
}
index := 0
if len(obj.EClientSessKey) > 0 {
session.PutKeyValString("AUTH_SESSKEY", obj.EClientSessKey, 1)
index++
}
if len(obj.EPassword) > 0 {
session.PutKeyValString("AUTH_PASSWORD", obj.EPassword, 0)
index++
}
// if newpassword encrypt and add {
// session.PutKeyValString("AUTH_NEWPASSWORD", ENewPassword, 0)
// index ++
//}
session.PutKeyValString("AUTH_TERMINAL", connOption.ClientInfo.HostName, 0)
index++
session.PutKeyValString("AUTH_PROGRAM_NM", connOption.ClientInfo.ProgramName, 0)
index++
session.PutKeyValString("AUTH_MACHINE", connOption.ClientInfo.HostName, 0)
index++
session.PutKeyValString("AUTH_PID", fmt.Sprintf("%d", connOption.ClientInfo.PID), 0)
index++
session.PutKeyValString("AUTH_SID", connOption.ClientInfo.UserName, 0)
index++
session.PutKeyValString("AUTH_CONNECT_STRING", connOption.ConnectionData(), 0)
index++
session.PutKeyValString("SESSION_CLIENT_CHARSET", strconv.Itoa(int(obj.tcpNego.ServerCharset)), 0)
index++
session.PutKeyValString("SESSION_CLIENT_LIB_TYPE", "0", 0)
index++
session.PutKeyValString("SESSION_CLIENT_DRIVER_NAME", connOption.ClientInfo.DriverName, 0)
index++
session.PutKeyValString("SESSION_CLIENT_VERSION", "1.0.0.0", 0)
index++
session.PutKeyValString("SESSION_CLIENT_LOBATTR", "1", 0)
index++
_, offset := time.Now().Zone()
tz := ""
if offset == 0 {
tz = "00:00"
} else {
hours := int8(offset / 3600)
minutes := int8((offset / 60) % 60)
if minutes < 0 {
minutes = minutes * -1
}
tz = fmt.Sprintf("%+03d:%02d", hours, minutes)
}
//if !strings.Contains(tz, ":") {
// tz += ":00"
//}
//session.PutKeyValString("AUTH_ALTER_SESSION",
// fmt.Sprintf("ALTER SESSION SET NLS_LANGUAGE='ARABIC' NLS_TERRITORY='SAUDI ARABIA' TIME_ZONE='%s'\x00", tz), 1)
session.PutKeyValString("AUTH_ALTER_SESSION",
fmt.Sprintf("ALTER SESSION SET NLS_LANGUAGE='AMERICAN' NLS_TERRITORY='AMERICA' TIME_ZONE='%s'\x00", tz), 1)
index++
//if (!string.IsNullOrEmpty(proxyClientName))
//{
// keys[index1] = this.m_authProxyClientName;
// values[index1++] = this.m_marshallingEngine.m_dbCharSetConv.ConvertStringToBytes(proxyClientName, 0, proxyClientName.Length, true);
//}
//if (sessionId != -1)
//{
// keys[index1] = this.m_authSessionId;
// values[index1++] = this.m_marshallingEngine.m_dbCharSetConv.ConvertStringToBytes(sessionId.ToString(), 0, sessionId.ToString().Length, true);
//}
//if (serialNum != -1)
//{
// keys[index1] = this.m_authSerialNum;
// values[index1++] = this.m_marshallingEngine.m_dbCharSetConv.ConvertStringToBytes(serialNum.ToString(), 0, serialNum.ToString().Length, true);
//}
// fill remaining values with zeros
for index < keyValSize {
session.PutKeyVal(nil, nil, 0)
index++
}
err := session.Write()
if err != nil {
return err
}
return nil
}
func getKeyFromUserNameAndPassword(username string, password string) ([]byte, error) {
username = strings.ToUpper(username)
password = strings.ToUpper(password)
extendString := func(str string) []byte {
ret := make([]byte, len(str)*2)
for index, char := range []byte(str) {
ret[index*2] = 0
ret[index*2+1] = char
}
return ret
}
buffer := append(extendString(username), extendString(password)...)
if len(buffer)%8 > 0 {
buffer = append(buffer, make([]byte, 8-len(buffer)%8)...)
}
key := []byte{1, 35, 69, 103, 137, 171, 205, 239}
DesEnc := func(input []byte, key []byte) ([]byte, error) {
ret := make([]byte, 8)
enc, err := des.NewCipher(key)
if err != nil {
return nil, err
}
for x := 0; x < len(input)/8; x++ {
for y := 0; y < 8; y++ {
ret[y] = uint8(int(ret[y]) ^ int(input[x*8+y]))
}
output := make([]byte, 8)
enc.Encrypt(output, ret)
copy(ret, output)
}
return ret, nil
}
key1, err := DesEnc(buffer, key)
if err != nil {
return nil, err
}
key2, err := DesEnc(buffer, key1)
if err != nil {
return nil, err
}
// function OSLogonHelper.Method1_bytearray (DecryptSessionKey)
return append(key2, make([]byte, 8)...), nil
}
func PKCS5Padding(cipherText []byte, blockSize int) []byte {
padding := blockSize - len(cipherText)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(cipherText, padtext...)
}
func decryptSessionKey(padding bool, encKey []byte, sessionKey string) ([]byte, error) {
result, err := hex.DecodeString(sessionKey)
if err != nil {
return nil, err
}
blk, err := aes.NewCipher(encKey)
if err != nil {
return nil, err
}
//if padding {
// result = PKCS5Padding(result, blk.BlockSize())
//}
enc := cipher.NewCBCDecrypter(blk, make([]byte, 16))
output := make([]byte, len(result))
enc.CryptBlocks(output, result)
cutLen := 0
if padding {
num := int(output[len(output)-1])
if num < enc.BlockSize() {
apply := true
for x := len(output) - num; x < len(output); x++ {
if output[x] != uint8(num) {
apply = false
break
}
}
if apply {
cutLen = int(output[len(output)-1])
}
}
}
return output[:len(output)-cutLen], nil
}
func decryptSessionKey2(encKey []byte, sessionKey string) ([]byte, error) {
result, err := hex.DecodeString(sessionKey)
if err != nil {
return nil, err
}
blk, err := des.NewCipher(encKey)
if err != nil {
return nil, err
}
enc := cipher.NewCBCDecrypter(blk, make([]byte, 8))
output := make([]byte, len(result))
enc.CryptBlocks(output, result)
return output, nil
}
func EncryptSessionKey(padding bool, encKey []byte, sessionKey []byte) (string, error) {
blk, err := aes.NewCipher(encKey)
if err != nil {
return "", err
}
enc := cipher.NewCBCEncrypter(blk, make([]byte, 16))
if padding {
sessionKey = PKCS5Padding(sessionKey, blk.BlockSize())
}
output := make([]byte, len(sessionKey))
enc.CryptBlocks(output, sessionKey)
return fmt.Sprintf("%X", output), nil
}
func EncryptPassword(password string, key []byte) (string, error) {
buff1 := make([]byte, 0x10)
_, err := rand.Read(buff1)
if err != nil {
return "", nil
}
buffer := append(buff1, []byte(password)...)
return EncryptSessionKey(true, key, buffer)
}
func encryptPassword2(password string, key []byte) (string, error) {
padding := 0
temp := []byte(password)
if len(password)%8 > 0 {
padding = 8 - (len(password) % 8)
temp = append(temp, bytes.Repeat([]byte{0}, padding)...)
}
blk, err := des.NewCipher(key)
if err != nil {
return "", err
}
enc := cipher.NewCBCEncrypter(blk, make([]byte, 8))
output := make([]byte, len(temp))
enc.CryptBlocks(output, temp)
encPassword := hex.EncodeToString(output)
encPassword += strconv.Itoa(padding)
// [36, -90, -28, -115, -91, 95, -80, -2]
return strings.ToUpper(encPassword), nil
}
func CalculateKeysHash(verifierType int, key1 []byte, key2 []byte) ([]byte, error) {
hash := md5.New()
switch verifierType {
case 2361:
buffer := make([]byte, 16)
for x := 0; x < 16; x++ {
buffer[x] = key1[x] ^ key2[x]
}
_, err := hash.Write(buffer)
if err != nil {
return nil, err
}
return hash.Sum(nil), nil
case 6949:
buffer := make([]byte, 24)
for x := 0; x < 24; x++ {
buffer[x] = key1[x] ^ key2[x]
}
_, err := hash.Write(buffer[:16])
if err != nil {
return nil, err
}
ret := hash.Sum(nil)
hash.Reset()
_, err = hash.Write(buffer[16:])
if err != nil {
return nil, err
}
ret = append(ret, hash.Sum(nil)...)
return ret[:24], nil
}
return nil, nil
}
func (obj *AuthObject) VerifyResponse(response string) bool {
key, err := decryptSessionKey(true, obj.KeyHash, response)
if err != nil {
fmt.Println(err)
return false
}
//fmt.Printf("%#v\n", key)
return bytes.Compare(key[16:], []byte{83, 69, 82, 86, 69, 82, 95, 84, 79, 95, 67, 76, 73, 69, 78, 84}) == 0
//KZSR_SVR_RESPONSE = new byte[16]{ (byte) 83, (byte) 69, (byte) 82, (byte) 86, (byte) 69, (byte) 82, (byte) 95, (byte) 84, (byte) 79,
//(byte) 95, (byte) 67, (byte) 76, (byte) 73, (byte) 69, (byte) 78, (byte) 84 };
}