gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/gmtls/key_agreement.go (about) 1 // Copyright (c) 2022 zhaochun 2 // core-gm is licensed under Mulan PSL v2. 3 // You can use this software according to the terms and conditions of the Mulan PSL v2. 4 // You may obtain a copy of Mulan PSL v2 at: 5 // http://license.coscl.org.cn/MulanPSL2 6 // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 7 // See the Mulan PSL v2 for more details. 8 9 /* 10 gmtls是基于`golang/go`的`tls`包实现的国密改造版本。 11 对应版权声明: thrid_licenses/github.com/golang/go/LICENSE 12 */ 13 14 package gmtls 15 16 import ( 17 "crypto" 18 "crypto/md5" 19 "crypto/rsa" 20 "crypto/sha1" 21 "crypto/sha256" 22 "errors" 23 "fmt" 24 "gitee.com/ks-custle/core-gm/sm3" 25 "io" 26 27 "gitee.com/ks-custle/core-gm/x509" 28 ) 29 30 // a keyAgreement implements the client and server side of a TLS key agreement 31 // protocol by generating and processing key exchange messages. 32 type keyAgreement interface { 33 // On the server side, the first two methods are called in order. 34 35 // In the case that the key agreement protocol doesn't use a 36 // ServerKeyExchange message, generateServerKeyExchange can return nil, 37 // nil. 38 generateServerKeyExchange(*Config, *Certificate, *clientHelloMsg, *serverHelloMsg) (*serverKeyExchangeMsg, error) 39 processClientKeyExchange(*Config, *Certificate, *clientKeyExchangeMsg, uint16) ([]byte, error) 40 41 // On the client side, the next two methods are called in order. 42 43 // This method may not be called if the server doesn't send a 44 // ServerKeyExchange message. 45 processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, *x509.Certificate, *serverKeyExchangeMsg) error 46 generateClientKeyExchange(*Config, *clientHelloMsg, *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) 47 } 48 49 var errClientKeyExchange = errors.New("gmtls: invalid ClientKeyExchange message") 50 var errServerKeyExchange = errors.New("gmtls: invalid ServerKeyExchange message") 51 52 // rsaKeyAgreement implements the standard TLS key agreement where the client 53 // encrypts the pre-master secret to the server's public key. 54 type rsaKeyAgreement struct{} 55 56 //goland:noinspection GoUnusedParameter 57 func (ka rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) { 58 return nil, nil 59 } 60 61 // 处理客户端密钥交换参数(rsa, tls1.2及更老版本) 62 // 63 //goland:noinspection GoUnusedParameter 64 func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) { 65 if len(ckx.ciphertext) < 2 { 66 return nil, errClientKeyExchange 67 } 68 ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1]) 69 if ciphertextLen != len(ckx.ciphertext)-2 { 70 return nil, errClientKeyExchange 71 } 72 ciphertext := ckx.ciphertext[2:] 73 74 priv, ok := cert.PrivateKey.(crypto.Decrypter) 75 if !ok { 76 return nil, errors.New("gmtls: certificate private key does not implement crypto.Decrypter") 77 } 78 // Perform constant time RSA PKCS #1 v1.5 decryption 79 preMasterSecret, err := priv.Decrypt(config.rand(), ciphertext, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: 48}) 80 if err != nil { 81 return nil, err 82 } 83 // We don't check the version number in the premaster secret. For one, 84 // by checking it, we would leak information about the validity of the 85 // encrypted pre-master secret. Secondly, it provides only a small 86 // benefit against a downgrade attack and some implementations send the 87 // wrong version anyway. See the discussion at the end of section 88 // 7.4.7.1 of RFC 4346. 89 return preMasterSecret, nil 90 } 91 92 // 处理服务端密钥交换参数(rsa, tls1.2及更老版本) 93 // 94 //goland:noinspection GoUnusedParameter 95 func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error { 96 return errors.New("gmtls: unexpected ServerKeyExchange") 97 } 98 99 func (ka rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) { 100 preMasterSecret := make([]byte, 48) 101 preMasterSecret[0] = byte(clientHello.vers >> 8) 102 preMasterSecret[1] = byte(clientHello.vers) 103 _, err := io.ReadFull(config.rand(), preMasterSecret[2:]) 104 if err != nil { 105 return nil, nil, err 106 } 107 108 rsaKey, ok := cert.PublicKey.(*rsa.PublicKey) 109 if !ok { 110 return nil, nil, errors.New("gmtls: server certificate contains incorrect key type for selected ciphersuite") 111 } 112 encrypted, err := rsa.EncryptPKCS1v15(config.rand(), rsaKey, preMasterSecret) 113 if err != nil { 114 return nil, nil, err 115 } 116 ckx := new(clientKeyExchangeMsg) 117 ckx.ciphertext = make([]byte, len(encrypted)+2) 118 ckx.ciphertext[0] = byte(len(encrypted) >> 8) 119 ckx.ciphertext[1] = byte(len(encrypted)) 120 copy(ckx.ciphertext[2:], encrypted) 121 return preMasterSecret, ckx, nil 122 } 123 124 // sm3Hash calculates a SM3 hash over the given byte slices. 125 func sm3Hash(slices [][]byte) []byte { 126 hsm3 := sm3.New() 127 for _, slice := range slices { 128 hsm3.Write(slice) 129 } 130 return hsm3.Sum(nil) 131 } 132 133 // sha256Hash calculates a SHA256 hash over the given byte slices. 134 func sha256Hash(slices [][]byte) []byte { 135 hsha256 := sha256.New() 136 for _, slice := range slices { 137 hsha256.Write(slice) 138 } 139 return hsha256.Sum(nil) 140 } 141 142 // sha1Hash calculates a SHA1 hash over the given byte slices. 143 func sha1Hash(slices [][]byte) []byte { 144 hsha1 := sha1.New() 145 for _, slice := range slices { 146 hsha1.Write(slice) 147 } 148 return hsha1.Sum(nil) 149 } 150 151 // md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the 152 // concatenation of an MD5 and SHA1 hash. 153 func md5SHA1Hash(slices [][]byte) []byte { 154 md5sha1 := make([]byte, md5.Size+sha1.Size) 155 hmd5 := md5.New() 156 for _, slice := range slices { 157 hmd5.Write(slice) 158 } 159 copy(md5sha1, hmd5.Sum(nil)) 160 copy(md5sha1[md5.Size:], sha1Hash(slices)) 161 return md5sha1 162 } 163 164 // hashForServerKeyExchange hashes the given slices and returns their digest 165 // using the given hash function (for >= TLS 1.2) or using a default based on 166 // the sigType (for earlier TLS versions). For Ed25519 signatures, which don't 167 // do pre-hashing, it returns the concatenation of the slices. 168 func hashForServerKeyExchange(sigType uint8, hashFunc x509.Hash, version uint16, slices ...[]byte) []byte { 169 if sigType == signatureEd25519 { 170 var signed []byte 171 for _, slice := range slices { 172 signed = append(signed, slice...) 173 } 174 return signed 175 } 176 // 添加国密分支 177 if version >= VersionTLS12 || version == VersionGMSSL { 178 h := hashFunc.New() 179 for _, slice := range slices { 180 h.Write(slice) 181 } 182 digest := h.Sum(nil) 183 return digest 184 } 185 switch sigType { 186 case signatureSM2: 187 return sm3Hash(slices) 188 case signatureECDSA, signatureECDSAEXT: 189 return sha256Hash(slices) 190 } 191 //if sigType == signatureECDSA { 192 // return sha1Hash(slices) 193 //} 194 return md5SHA1Hash(slices) 195 } 196 197 // ecdheKeyAgreement implements a TLS key agreement where the server 198 // generates an ephemeral EC public/private key pair and signs it. The 199 // pre-master secret is then calculated using ECDH. The signature may 200 // be ECDSA, Ed25519 or RSA. 201 type ecdheKeyAgreement struct { 202 version uint16 203 isRSA bool 204 // TODO: 需要先改造 gmtls/key_schedule.go 205 params ecdheParameters 206 207 // ckx and preMasterSecret are generated in processServerKeyExchange 208 // and returned in generateClientKeyExchange. 209 ckx *clientKeyExchangeMsg 210 preMasterSecret []byte 211 } 212 213 func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) { 214 var curveID CurveID 215 for _, c := range clientHello.supportedCurves { 216 if config.supportsCurve(c) { 217 curveID = c 218 break 219 } 220 } 221 222 if curveID == 0 { 223 return nil, errors.New("gmtls: no supported elliptic curves offered") 224 } 225 if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok { 226 return nil, errors.New("gmtls: CurvePreferences includes unsupported curve") 227 } 228 229 params, err := generateECDHEParameters(config.rand(), curveID) 230 if err != nil { 231 return nil, err 232 } 233 ka.params = params 234 235 // See RFC 4492, Section 5.4. 236 ecdhePublic := params.PublicKey() 237 serverECDHEParams := make([]byte, 1+2+1+len(ecdhePublic)) 238 serverECDHEParams[0] = 3 // named curve 239 serverECDHEParams[1] = byte(curveID >> 8) 240 serverECDHEParams[2] = byte(curveID) 241 serverECDHEParams[3] = byte(len(ecdhePublic)) 242 copy(serverECDHEParams[4:], ecdhePublic) 243 244 priv, ok := cert.PrivateKey.(crypto.Signer) 245 if !ok { 246 return nil, fmt.Errorf("gmtls: certificate private key of type %T does not implement crypto.Signer", cert.PrivateKey) 247 } 248 249 var signatureAlgorithm SignatureScheme 250 var sigType uint8 251 var sigHash x509.Hash 252 if ka.version >= VersionTLS12 { 253 signatureAlgorithm, err = selectSignatureScheme(ka.version, cert, clientHello.supportedSignatureAlgorithms) 254 if err != nil { 255 return nil, err 256 } 257 sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm) 258 if err != nil { 259 return nil, err 260 } 261 } else { 262 sigType, sigHash, err = legacyTypeAndHashFromPublicKey(priv.Public()) 263 if err != nil { 264 return nil, err 265 } 266 } 267 if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA { 268 return nil, errors.New("gmtls: certificate cannot be used with the selected cipher suite") 269 } 270 271 signed := hashForServerKeyExchange(sigType, sigHash, ka.version, clientHello.random, hello.random, serverECDHEParams) 272 273 signOpts := crypto.SignerOpts(sigHash) 274 if sigType == signatureRSAPSS { 275 signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash.HashFunc()} 276 } 277 sig, err := priv.Sign(config.rand(), signed, signOpts) 278 if err != nil { 279 return nil, errors.New("gmtls: failed to sign ECDHE parameters: " + err.Error()) 280 } 281 282 skx := new(serverKeyExchangeMsg) 283 sigAndHashLen := 0 284 if ka.version >= VersionTLS12 { 285 sigAndHashLen = 2 286 } 287 skx.key = make([]byte, len(serverECDHEParams)+sigAndHashLen+2+len(sig)) 288 copy(skx.key, serverECDHEParams) 289 k := skx.key[len(serverECDHEParams):] 290 if ka.version >= VersionTLS12 { 291 k[0] = byte(signatureAlgorithm >> 8) 292 k[1] = byte(signatureAlgorithm) 293 k = k[2:] 294 } 295 k[0] = byte(len(sig) >> 8) 296 k[1] = byte(len(sig)) 297 copy(k[2:], sig) 298 299 return skx, nil 300 } 301 302 // 处理客户端密钥交换参数(ecdhe, tls1.2) 303 // 304 //goland:noinspection GoUnusedParameter 305 func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) { 306 if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 { 307 return nil, errClientKeyExchange 308 } 309 310 preMasterSecret := ka.params.SharedKey(ckx.ciphertext[1:]) 311 if preMasterSecret == nil { 312 return nil, errClientKeyExchange 313 } 314 315 return preMasterSecret, nil 316 } 317 318 // 处理服务端密钥交换参数(ecdhe, tls1.2) 319 func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error { 320 if len(skx.key) < 4 { 321 return errServerKeyExchange 322 } 323 if skx.key[0] != 3 { // named curve 324 return errors.New("gmtls: server selected unsupported curve") 325 } 326 curveID := CurveID(skx.key[1])<<8 | CurveID(skx.key[2]) 327 328 publicLen := int(skx.key[3]) 329 if publicLen+4 > len(skx.key) { 330 return errServerKeyExchange 331 } 332 serverECDHEParams := skx.key[:4+publicLen] 333 publicKey := serverECDHEParams[4:] 334 335 sig := skx.key[4+publicLen:] 336 if len(sig) < 2 { 337 return errServerKeyExchange 338 } 339 340 if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok { 341 return errors.New("gmtls: server selected unsupported curve") 342 } 343 344 params, err := generateECDHEParameters(config.rand(), curveID) 345 if err != nil { 346 return err 347 } 348 ka.params = params 349 350 ka.preMasterSecret = params.SharedKey(publicKey) 351 if ka.preMasterSecret == nil { 352 return errServerKeyExchange 353 } 354 355 ourPublicKey := params.PublicKey() 356 ka.ckx = new(clientKeyExchangeMsg) 357 ka.ckx.ciphertext = make([]byte, 1+len(ourPublicKey)) 358 ka.ckx.ciphertext[0] = byte(len(ourPublicKey)) 359 copy(ka.ckx.ciphertext[1:], ourPublicKey) 360 361 var sigType uint8 362 var sigHash x509.Hash 363 if ka.version >= VersionTLS12 { 364 signatureAlgorithm := SignatureScheme(sig[0])<<8 | SignatureScheme(sig[1]) 365 sig = sig[2:] 366 if len(sig) < 2 { 367 return errServerKeyExchange 368 } 369 370 if !isSupportedSignatureAlgorithm(signatureAlgorithm, clientHello.supportedSignatureAlgorithms) { 371 return errors.New("gmtls: certificate used with invalid signature algorithm") 372 } 373 sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm) 374 if err != nil { 375 return err 376 } 377 } else { 378 sigType, sigHash, err = legacyTypeAndHashFromPublicKey(cert.PublicKey) 379 if err != nil { 380 return err 381 } 382 } 383 if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA { 384 return errServerKeyExchange 385 } 386 387 sigLen := int(sig[0])<<8 | int(sig[1]) 388 if sigLen+2 != len(sig) { 389 return errServerKeyExchange 390 } 391 sig = sig[2:] 392 393 signed := hashForServerKeyExchange(sigType, sigHash, ka.version, clientHello.random, serverHello.random, serverECDHEParams) 394 if err := verifyHandshakeSignature(sigType, cert.PublicKey, sigHash, signed, sig); err != nil { 395 return errors.New("gmtls: invalid signature by the server certificate: " + err.Error()) 396 } 397 return nil 398 } 399 400 //goland:noinspection GoUnusedParameter 401 func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) { 402 if ka.ckx == nil { 403 return nil, nil, errors.New("gmtls: missing ServerKeyExchange message") 404 } 405 406 return ka.preMasterSecret, ka.ckx, nil 407 }