github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/gmtls/prf.go (about) 1 // Copyright 2022 s1ren@github.com/hxx258456. 2 3 /* 4 gmtls是基于`golang/go`的`tls`包实现的国密改造版本。 5 对应版权声明: thrid_licenses/github.com/golang/go/LICENSE 6 */ 7 8 package gmtls 9 10 import ( 11 "crypto" 12 "crypto/hmac" 13 "crypto/md5" 14 "crypto/sha1" 15 "crypto/sha256" 16 "crypto/sha512" 17 "errors" 18 "fmt" 19 "hash" 20 21 "github.com/hxx258456/ccgo/x509" 22 ) 23 24 // Split a premaster secret in two as specified in RFC 4346, Section 5. 25 func splitPreMasterSecret(secret []byte) (s1, s2 []byte) { 26 s1 = secret[0 : (len(secret)+1)/2] 27 s2 = secret[len(secret)/2:] 28 return 29 } 30 31 // pHash implements the P_hash function, as defined in RFC 4346, Section 5. 32 func pHash(result, secret, seed []byte, hash func() hash.Hash) { 33 h := hmac.New(hash, secret) 34 h.Write(seed) 35 a := h.Sum(nil) 36 37 j := 0 38 for j < len(result) { 39 h.Reset() 40 h.Write(a) 41 h.Write(seed) 42 b := h.Sum(nil) 43 copy(result[j:], b) 44 j += len(b) 45 46 h.Reset() 47 h.Write(a) 48 a = h.Sum(nil) 49 } 50 } 51 52 // prf10 implements the TLS 1.0 pseudo-random function, as defined in RFC 2246, Section 5. 53 func prf10(result, secret, label, seed []byte) { 54 hashSHA1 := sha1.New 55 hashMD5 := md5.New 56 57 labelAndSeed := make([]byte, len(label)+len(seed)) 58 copy(labelAndSeed, label) 59 copy(labelAndSeed[len(label):], seed) 60 61 s1, s2 := splitPreMasterSecret(secret) 62 pHash(result, s1, labelAndSeed, hashMD5) 63 result2 := make([]byte, len(result)) 64 pHash(result2, s2, labelAndSeed, hashSHA1) 65 66 for i, b := range result2 { 67 result[i] ^= b 68 } 69 } 70 71 // prf12 implements the TLS 1.2 pseudo-random function, as defined in RFC 5246, Section 5. 72 func prf12(hashFunc func() hash.Hash) func(result, secret, label, seed []byte) { 73 return func(result, secret, label, seed []byte) { 74 labelAndSeed := make([]byte, len(label)+len(seed)) 75 copy(labelAndSeed, label) 76 copy(labelAndSeed[len(label):], seed) 77 78 pHash(result, secret, labelAndSeed, hashFunc) 79 } 80 } 81 82 const ( 83 masterSecretLength = 48 // Length of a master secret in TLS 1.1. 84 finishedVerifyLength = 12 // Length of verify_data in a Finished message. 85 ) 86 87 var masterSecretLabel = []byte("master secret") 88 var keyExpansionLabel = []byte("key expansion") 89 var clientFinishedLabel = []byte("client finished") 90 var serverFinishedLabel = []byte("server finished") 91 92 func prfAndHashForVersion(version uint16, suite *cipherSuite) (func(result, secret, label, seed []byte), crypto.Hash) { 93 switch version { 94 case VersionTLS10, VersionTLS11: 95 return prf10, crypto.Hash(0) 96 case VersionTLS12: 97 if suite.flags&suiteSHA384 != 0 { 98 return prf12(sha512.New384), crypto.SHA384 99 } 100 return prf12(sha256.New), crypto.SHA256 101 default: 102 panic("unknown version") 103 } 104 } 105 106 func prfForVersion(version uint16, suite *cipherSuite) func(result, secret, label, seed []byte) { 107 prf, _ := prfAndHashForVersion(version, suite) 108 return prf 109 } 110 111 // 根据预主密钥计算主密钥 112 // 算法使用PRF函数; 113 // 使用clientRandom与serverRandom拼接起来的随机数作为种子; 114 // 115 // masterFromPreMasterSecret generates the master secret from the pre-master 116 // secret. See RFC 5246, Section 8.1. 117 func masterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret, clientRandom, serverRandom []byte) []byte { 118 seed := make([]byte, 0, len(clientRandom)+len(serverRandom)) 119 seed = append(seed, clientRandom...) 120 seed = append(seed, serverRandom...) 121 122 masterSecret := make([]byte, masterSecretLength) 123 prfForVersion(version, suite)(masterSecret, preMasterSecret, masterSecretLabel, seed) 124 return masterSecret 125 } 126 127 // 根据主密钥派生出会话密钥 128 // 算法使用PRF函数; 129 // 使用clientRandom与serverRandom拼接起来的随机数作为种子; 130 // 派生出六个会话密钥:clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV 131 // 132 // keysFromMasterSecret generates the connection keys from the master 133 // secret, given the lengths of the MAC key, cipher key and IV, as defined in 134 // RFC 2246, Section 6.3. 135 func keysFromMasterSecret(version uint16, suite *cipherSuite, masterSecret, clientRandom, serverRandom []byte, macLen, keyLen, ivLen int) (clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV []byte) { 136 seed := make([]byte, 0, len(serverRandom)+len(clientRandom)) 137 seed = append(seed, serverRandom...) 138 seed = append(seed, clientRandom...) 139 140 n := 2*macLen + 2*keyLen + 2*ivLen 141 keyMaterial := make([]byte, n) 142 prfForVersion(version, suite)(keyMaterial, masterSecret, keyExpansionLabel, seed) 143 clientMAC = keyMaterial[:macLen] 144 keyMaterial = keyMaterial[macLen:] 145 serverMAC = keyMaterial[:macLen] 146 keyMaterial = keyMaterial[macLen:] 147 clientKey = keyMaterial[:keyLen] 148 keyMaterial = keyMaterial[keyLen:] 149 serverKey = keyMaterial[:keyLen] 150 keyMaterial = keyMaterial[keyLen:] 151 clientIV = keyMaterial[:ivLen] 152 keyMaterial = keyMaterial[ivLen:] 153 serverIV = keyMaterial[:ivLen] 154 return 155 } 156 157 func newFinishedHash(version uint16, cipherSuite *cipherSuite) finishedHash { 158 var buffer []byte 159 if version >= VersionTLS12 { 160 buffer = []byte{} 161 } 162 163 prf, hash := prfAndHashForVersion(version, cipherSuite) 164 if hash != 0 { 165 return finishedHash{hash.New(), hash.New(), nil, nil, buffer, version, prf} 166 } 167 168 return finishedHash{sha1.New(), sha1.New(), md5.New(), md5.New(), buffer, version, prf} 169 } 170 171 // A finishedHash calculates the hash of a set of handshake messages suitable 172 // for including in a Finished message. 173 type finishedHash struct { 174 client hash.Hash 175 server hash.Hash 176 177 // Prior to TLS 1.2, an additional MD5 hash is required. 178 clientMD5 hash.Hash 179 serverMD5 hash.Hash 180 181 // In TLS 1.2, a full buffer is sadly required. 182 buffer []byte 183 184 version uint16 185 prf func(result, secret, label, seed []byte) 186 } 187 188 //goland:noinspection GoMixedReceiverTypes 189 func (h *finishedHash) Write(msg []byte) (n int, err error) { 190 h.client.Write(msg) 191 h.server.Write(msg) 192 193 if h.version < VersionTLS12 { 194 h.clientMD5.Write(msg) 195 h.serverMD5.Write(msg) 196 } 197 198 if h.buffer != nil { 199 h.buffer = append(h.buffer, msg...) 200 } 201 202 return len(msg), nil 203 } 204 205 //goland:noinspection GoMixedReceiverTypes 206 func (h finishedHash) Sum() []byte { 207 if h.version >= VersionTLS12 { 208 return h.client.Sum(nil) 209 } 210 211 out := make([]byte, 0, md5.Size+sha1.Size) 212 out = h.clientMD5.Sum(out) 213 return h.client.Sum(out) 214 } 215 216 // clientSum returns the contents of the verify_data member of a client's 217 // Finished message. 218 //goland:noinspection GoMixedReceiverTypes 219 func (h finishedHash) clientSum(masterSecret []byte) []byte { 220 out := make([]byte, finishedVerifyLength) 221 h.prf(out, masterSecret, clientFinishedLabel, h.Sum()) 222 return out 223 } 224 225 // serverSum returns the contents of the verify_data member of a server's 226 // Finished message. 227 func (h finishedHash) serverSum(masterSecret []byte) []byte { 228 out := make([]byte, finishedVerifyLength) 229 h.prf(out, masterSecret, serverFinishedLabel, h.Sum()) 230 return out 231 } 232 233 // hashForClientCertificate returns the handshake messages so far, pre-hashed if 234 // necessary, suitable for signing by a TLS client certificate. 235 //goland:noinspection GoMixedReceiverTypes,GoUnusedParameter 236 func (h finishedHash) hashForClientCertificate(sigType uint8, hashAlg x509.Hash, masterSecret []byte) []byte { 237 if (h.version >= VersionTLS12 || sigType == signatureEd25519) && h.buffer == nil { 238 panic("gmtls: handshake hash for a client certificate requested after discarding the handshake buffer") 239 } 240 241 if sigType == signatureEd25519 { 242 return h.buffer 243 } 244 245 if h.version >= VersionTLS12 { 246 hash := hashAlg.New() 247 hash.Write(h.buffer) 248 return hash.Sum(nil) 249 } 250 251 if sigType == signatureECDSA { 252 return h.server.Sum(nil) 253 } 254 255 return h.Sum() 256 } 257 258 // discardHandshakeBuffer is called when there is no more need to 259 // buffer the entirety of the handshake messages. 260 //goland:noinspection GoMixedReceiverTypes 261 func (h *finishedHash) discardHandshakeBuffer() { 262 h.buffer = nil 263 } 264 265 // noExportedKeyingMaterial is used as a value of 266 // ConnectionState.ekm when renegotiation is enabled and thus 267 // we wish to fail all key-material export requests. 268 //goland:noinspection GoUnusedParameter 269 func noExportedKeyingMaterial(label string, context []byte, length int) ([]byte, error) { 270 return nil, errors.New("crypto/tls: ExportKeyingMaterial is unavailable when renegotiation is enabled") 271 } 272 273 // ekmFromMasterSecret generates exported keying material as defined in RFC 5705. 274 func ekmFromMasterSecret(version uint16, suite *cipherSuite, masterSecret, clientRandom, serverRandom []byte) func(string, []byte, int) ([]byte, error) { 275 return func(label string, context []byte, length int) ([]byte, error) { 276 switch label { 277 case "client finished", "server finished", "master secret", "key expansion": 278 // These values are reserved and may not be used. 279 return nil, fmt.Errorf("crypto/tls: reserved ExportKeyingMaterial label: %s", label) 280 } 281 282 seedLen := len(serverRandom) + len(clientRandom) 283 if context != nil { 284 seedLen += 2 + len(context) 285 } 286 seed := make([]byte, 0, seedLen) 287 288 seed = append(seed, clientRandom...) 289 seed = append(seed, serverRandom...) 290 291 if context != nil { 292 if len(context) >= 1<<16 { 293 return nil, fmt.Errorf("crypto/tls: ExportKeyingMaterial context too long") 294 } 295 seed = append(seed, byte(len(context)>>8), byte(len(context))) 296 seed = append(seed, context...) 297 } 298 299 keyMaterial := make([]byte, length) 300 prfForVersion(version, suite)(keyMaterial, masterSecret, []byte(label), seed) 301 return keyMaterial, nil 302 } 303 }