-
Notifications
You must be signed in to change notification settings - Fork 5
/
tls_prf.go
280 lines (234 loc) · 9.77 KB
/
tls_prf.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
package tcpip
import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/tls"
"encoding/binary"
"encoding/hex"
"fmt"
"log"
)
// HMAC およびその擬似乱数関数
// https://www.ipa.go.jp/security/rfc/RFC5246-05JA.html
// https://atmarkit.itmedia.co.jp/ait/articles/0101/16/news002_4.html
// https://www.slideshare.net/shigeki_ohtsu/security-camp2015-tls
// https://github.com/shigeki/SecCamp2015-TLS/blob/master/MyMasterSecret.js
// データ拡張関数, あるsecretを必要なサイズまで伸長させる
func phash(secret, seed []byte, prfLength int) []byte {
result := make([]byte, prfLength)
mac := hmac.New(sha256.New, secret)
mac.Write(seed)
// A(1)
a := mac.Sum(nil)
length := 0
// 48byteになるまで計算する
for length < len(result) {
mac.Reset()
mac.Write(a)
mac.Write(seed)
b := mac.Sum(nil)
copy(result[length:], b)
length += len(b)
mac.Reset()
mac.Write(a)
a = mac.Sum(nil)
}
return result
}
// https://www.ipa.go.jp/security/rfc/RFC5246-08JA.html#081
// ClientKeyExchangeのときに生成したpremaster secretと
// ClientHelloで送ったrandom, ServerHelloで受信したrandomをもとに48byteのmaster secretを生成する
func prf(secret, label, clientServerRandom []byte, prfLength int) []byte {
var seed []byte
seed = append(seed, label...)
seed = append(seed, clientServerRandom...)
return phash(secret, seed, prfLength)
}
func CreateMasterandKeyblock(premasterBytes MasterSecretInfo) ([]byte, KeyBlock) {
var random []byte
random = append(random, premasterBytes.ClientRandom...)
random = append(random, premasterBytes.ServerRandom...)
// keyblockを作るときはServer→ClienRandomの順番
// https://www.ipa.go.jp/security/rfc/RFC5246-06JA.html#063
var keyrandom []byte
keyrandom = append(keyrandom, premasterBytes.ServerRandom...)
keyrandom = append(keyrandom, premasterBytes.ClientRandom...)
// master secretを作成する
master := prf(premasterBytes.PreMasterSecret, MasterSecretLable, random, 48)
fmt.Printf("CLIENT_RANDOM %x %x\n", premasterBytes.ClientRandom, master)
fmt.Printf("keyrandom : %x\n", keyrandom)
keyblockbyte := prf(master, KeyLable, keyrandom, 40)
keyblock := KeyBlock{
ClientWriteKey: keyblockbyte[0:16],
ServerWriteKey: keyblockbyte[16:32],
ClientWriteIV: keyblockbyte[32:36],
ServerWriteIV: keyblockbyte[36:40],
}
fmt.Printf("ClientWriteIV : %x\n", keyblock.ClientWriteIV)
fmt.Printf("ServerWriteKey : %x\n", keyblock.ClientWriteKey)
fmt.Printf("ServerWriteIV : %x\n", keyblock.ServerWriteIV)
fmt.Printf("ServerWriteKey : %x\n", keyblock.ServerWriteKey)
return master, keyblock
}
func CreateVerifyData(master, labels, handhake_messages []byte) []byte {
// これまでの全てのhandshake protocolでハッシュを計算する
hasher := sha256.New()
hasher.Write(handhake_messages)
messages := hasher.Sum(nil)
// 12byteのverify_dataをreturn
return prf(master, labels, messages, 12)
}
//func createFinishTest() {
//
// var handshake_message []byte
// handshake_message = append(handshake_message, strtoByte(clientHellostr)...)
// handshake_message = append(handshake_message, strtoByte(serverHellostr)...)
// handshake_message = append(handshake_message, strtoByte(serverCertificatestr)...)
// handshake_message = append(handshake_message, strtoByte(serveHelloDonestr)...)
// handshake_message = append(handshake_message, strtoByte(clientKeyExchagestr)...)
//
// var premasterByte []byte
// premasterByte = append(premasterByte, TLS1_2...)
// premasterByte = append(premasterByte, noRandomByte(46)...)
//
// serverrandom := strtoByte("e7084907d95b64c862825b77b73d38020d080eb924a3b7c0444f574e47524401")
//
// master := MasterSecretInfo{
// PreMasterSecret: premasterByte,
// ServerRandom: serverrandom,
// ClientRandom: noRandomByte(32),
// }
//
// // 12byteのverify_dataを作成
// verifyData, keyblock, _ := createVerifyData(master, CLientFinishedLabel, handshake_message)
// fmt.Printf("client verifyData : %x\n", verifyData)
//
// // finished messageを作成する、先頭にレコードヘッダを入れてからverify_dataを入れる
// // 作成された16byteがplaintextとなり暗号化する
// finMessage := []byte{HandshakeTypeFinished}
// finMessage = append(finMessage, UintTo3byte(uint32(len(verifyData)))...)
// finMessage = append(finMessage, verifyData...)
// fmt.Printf("finMessage : %x\n", finMessage)
//
// handshake_message = append(handshake_message, finMessage...)
// //serververifyData, _ := createVerifyData(master, ServerFinished, handshake_message)
// //fmt.Printf("server verifyData : %x\n", createServerVerifyData(masterByte, handshake_message))
//
// rheader := TLSRecordHeader{
// ContentType: []byte{ContentTypeHandShake},
// ProtocolVersion: TLS1_2,
// Length: UintTo2byte(uint16(len(finMessage))),
// }
//
// tlsinfo := TLSInfo{
// KeyBlock: keyblock,
// ClientSequenceNum: 0,
// }
//
// encryptClientMessage(toByteArr(rheader), finMessage, tlsinfo)
//}
func EncryptClientMessage(header, plaintext []byte, tlsinfo TLSInfo) []byte {
record_seq := append(header, getNonce(tlsinfo.ClientSequenceNum, 8)...)
nonce := tlsinfo.KeyBlock.ClientWriteIV
nonce = append(nonce, getNonce(tlsinfo.ClientSequenceNum, 8)...)
add := getNonce(tlsinfo.ClientSequenceNum, 8)
add = append(add, header...)
block, _ := aes.NewCipher(tlsinfo.KeyBlock.ClientWriteKey)
aesgcm, _ := cipher.NewGCM(block)
fmt.Printf("record is %x, nonce is : %x, plaintext is %x, add is %x\n", record_seq, nonce, plaintext, add)
encryptedMessage := aesgcm.Seal(record_seq, nonce, plaintext, add)
updatelength := UintTo2byte(uint16(len(encryptedMessage) - 5))
encryptedMessage[3] = updatelength[0]
encryptedMessage[4] = updatelength[1]
fmt.Printf("encrypted data is : %x\n", encryptedMessage)
return encryptedMessage
}
func DecryptServerMessage(finMessage []byte, tlsinfo TLSInfo, ctype int) []byte {
header := readByteNum(finMessage, 0, 5)
ciphertextLength := binary.BigEndian.Uint16(header[3:]) - 8
seq_nonce := readByteNum(finMessage, 5, 8)
ciphertext := readByteNum(finMessage, 13, int64(ciphertextLength))
serverkey := tlsinfo.KeyBlock.ServerWriteKey
nonce := tlsinfo.KeyBlock.ServerWriteIV
nonce = append(nonce, seq_nonce...)
block, _ := aes.NewCipher(serverkey)
aesgcm, _ := cipher.NewGCM(block)
var add []byte
add = getNonce(tlsinfo.ClientSequenceNum, 8)
add = append(add, byte(ctype))
add = append(add, TLS1_2...)
plainLength := len(ciphertext) - aesgcm.Overhead()
add = append(add, UintTo2byte(uint16(plainLength))...)
fmt.Printf("nonce is : %x, ciphertext is %x, add is %x\n", nonce, ciphertext, add)
plaintext, err := aesgcm.Open(nil, nonce, ciphertext, add)
if err != nil {
panic(err.Error())
}
return plaintext
}
func decryptFinTest() {
serverrandom := strtoByte("94d1d67fb0fe4f841e88166a1572e7787307fb2c5cd56dcb444f574e47524401")
clientrandom := noRandomByte(32)
var random []byte
// client randomeはいったん All zero
random = append(random, clientrandom...)
random = append(random, serverrandom...)
// keyblockを作るときはServer→ClienRandomの順番
// https://www.ipa.go.jp/security/rfc/RFC5246-06JA.html#063
var keyrandom []byte
keyrandom = append(keyrandom, serverrandom...)
keyrandom = append(keyrandom, clientrandom...)
var premasterByte []byte
premasterByte = append(premasterByte, TLS1_2...)
premasterByte = append(premasterByte, noRandomByte(46)...)
// master secretを作成する
master := prf(premasterByte, MasterSecretLable, random, 48)
fmt.Printf("CLIENT_RANDOM %x %x\n", clientrandom, master)
fmt.Printf("keyrandom : %x\n", keyrandom)
keyblockbyte := prf(master, KeyLable, keyrandom, 40)
keyblock := KeyBlock{
ClientWriteKey: keyblockbyte[0:16],
ServerWriteKey: keyblockbyte[16:32],
ClientWriteIV: keyblockbyte[32:36],
ServerWriteIV: keyblockbyte[36:40],
}
ciphertext := strtoByte("e40da4398ee3d35174abb36cd2c49160c19579d6aa08ccbf4684e09f93216bea")
//header := []byte{ContentTypeHandShake}
//header := append(header, TLS1_2...)
//record := strtoByte("16030300100000000000000000")
//seq_nonce := getNonce(1)
nonce := keyblock.ServerWriteIV
nonce = append(nonce, strtoByte("12355ff49c01a9b7")...)
block, _ := aes.NewCipher(keyblock.ServerWriteKey)
aesgcm, _ := cipher.NewGCM(block)
add := getNonce(0, 8)
plainLength := len(ciphertext) - aesgcm.Overhead()
add = append(add, []byte{0x16, 0x03, 0x03}...)
add = append(add, UintTo2byte(uint16(plainLength))...)
//add := strtoByte("00000000000000011703030006")
///plainLength := UintTo2byte(uint16(len(ciphertext) - aesgcm.Overhead()))
fmt.Printf("nonce is : %x, ciphertext is %x, add is %x\n", nonce, ciphertext, add)
plaintext, err := aesgcm.Open(nil, nonce, ciphertext, add)
if err != nil {
panic(err.Error())
}
fmt.Printf("decrypt is %x\n", plaintext[4:])
//fmt.Printf("AppData is %s\n", string(plaintext))
}
func decryptPremaster() {
certfile, err := tls.LoadX509KeyPair("./debug/my-tls.pem", "./debug/my-tls-key.pem")
if err != nil {
log.Fatal(err)
}
//premaster, _ := hex.DecodeString("7d4e98e480ec763ba78b36413c0c13686297aad706653f5d2582a96a5006b3fe0e1d00f9f833f39a9d5459567587fcc7f00aad553f0f2ff5aca7efd18d2ef484cac000bdf8d77b80935b1c7053cc832c6d4dcbb51c597d19c0213abb97c06cec27bcd67512f280e1211f80be4056590a11679baeae64f71af8230c34ce7562b16fcdad1d4abfc9be0ef4d10e02b9ebcfda862b99d23f407ca62d2055d9df107434a0046c4915afca067c1a8be40a8ee6ab492a78f11e805b8facaf1ad10ddaf4734b0b5453252e5c231f946682b333d3a0e31128aa6cfc38c97fb6b0eb0fed04c62b32c4f392e8e5a7faa47c0e3c151f5014fea0b34a18fc08095b6afab1519a")
premaster, _ := hex.DecodeString("baca0df460a688e44ce018b025183cc2353ae01f89755ef766eedd3ecc302888ee3b3a22962e45f48c20df15a98c0e80")
secret, err := rsa.DecryptPKCS1v15(rand.Reader, certfile.PrivateKey.(*rsa.PrivateKey), premaster)
if err != nil {
log.Fatalf("create premaster secret err : %v\n", err)
}
fmt.Printf("%x\n", secret)
}