├── go.mod ├── go.sum ├── notboring.go ├── LICENSE-Go ├── common_string.go ├── README.md ├── alert.go ├── generate_cert.go ├── ticket.go ├── key_schedule.go ├── prf.go ├── auth.go ├── key_agreement.go ├── LICENSE ├── handshake_client_tls13.go ├── tls.go ├── cipher_suites.go ├── handshake_server.go └── handshake_server_tls13.go /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/xtls/reality 2 | 3 | go 1.19 4 | 5 | require ( 6 | github.com/pires/go-proxyproto v0.6.2 7 | golang.org/x/crypto v0.6.0 8 | golang.org/x/sys v0.5.0 9 | ) 10 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/pires/go-proxyproto v0.6.2 h1:KAZ7UteSOt6urjme6ZldyFm4wDe/z0ZUP0Yv0Dos0d8= 2 | github.com/pires/go-proxyproto v0.6.2/go.mod h1:Odh9VFOZJCf9G8cLW5o435Xf1J95Jw9Gw5rnCjcwzAY= 3 | golang.org/x/crypto v0.6.0 h1:qfktjS5LUO+fFKeJXZ+ikTRijMmljikvG68fpMMruSc= 4 | golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58= 5 | golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= 6 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 7 | -------------------------------------------------------------------------------- /notboring.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE-Go file. 4 | 5 | //go:build !boringcrypto 6 | 7 | package reality 8 | 9 | func needFIPS() bool { return false } 10 | 11 | func supportedSignatureAlgorithms() []SignatureScheme { 12 | return defaultSupportedSignatureAlgorithms 13 | } 14 | 15 | func fipsMinVersion(c *Config) uint16 { panic("fipsMinVersion") } 16 | func fipsMaxVersion(c *Config) uint16 { panic("fipsMaxVersion") } 17 | func fipsCurvePreferences(c *Config) []CurveID { panic("fipsCurvePreferences") } 18 | func fipsCipherSuites(c *Config) []uint16 { panic("fipsCipherSuites") } 19 | 20 | var fipsSupportedSignatureAlgorithms []SignatureScheme 21 | -------------------------------------------------------------------------------- /LICENSE-Go: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009 The Go Authors. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /common_string.go: -------------------------------------------------------------------------------- 1 | // Code generated by "stringer -type=SignatureScheme,CurveID,ClientAuthType -output=common_string.go"; DO NOT EDIT. 2 | 3 | package reality 4 | 5 | import "strconv" 6 | 7 | func _() { 8 | // An "invalid array index" compiler error signifies that the constant values have changed. 9 | // Re-run the stringer command to generate them again. 10 | var x [1]struct{} 11 | _ = x[PKCS1WithSHA256-1025] 12 | _ = x[PKCS1WithSHA384-1281] 13 | _ = x[PKCS1WithSHA512-1537] 14 | _ = x[PSSWithSHA256-2052] 15 | _ = x[PSSWithSHA384-2053] 16 | _ = x[PSSWithSHA512-2054] 17 | _ = x[ECDSAWithP256AndSHA256-1027] 18 | _ = x[ECDSAWithP384AndSHA384-1283] 19 | _ = x[ECDSAWithP521AndSHA512-1539] 20 | _ = x[Ed25519-2055] 21 | _ = x[PKCS1WithSHA1-513] 22 | _ = x[ECDSAWithSHA1-515] 23 | } 24 | 25 | const ( 26 | _SignatureScheme_name_0 = "PKCS1WithSHA1" 27 | _SignatureScheme_name_1 = "ECDSAWithSHA1" 28 | _SignatureScheme_name_2 = "PKCS1WithSHA256" 29 | _SignatureScheme_name_3 = "ECDSAWithP256AndSHA256" 30 | _SignatureScheme_name_4 = "PKCS1WithSHA384" 31 | _SignatureScheme_name_5 = "ECDSAWithP384AndSHA384" 32 | _SignatureScheme_name_6 = "PKCS1WithSHA512" 33 | _SignatureScheme_name_7 = "ECDSAWithP521AndSHA512" 34 | _SignatureScheme_name_8 = "PSSWithSHA256PSSWithSHA384PSSWithSHA512Ed25519" 35 | ) 36 | 37 | var ( 38 | _SignatureScheme_index_8 = [...]uint8{0, 13, 26, 39, 46} 39 | ) 40 | 41 | func (i SignatureScheme) String() string { 42 | switch { 43 | case i == 513: 44 | return _SignatureScheme_name_0 45 | case i == 515: 46 | return _SignatureScheme_name_1 47 | case i == 1025: 48 | return _SignatureScheme_name_2 49 | case i == 1027: 50 | return _SignatureScheme_name_3 51 | case i == 1281: 52 | return _SignatureScheme_name_4 53 | case i == 1283: 54 | return _SignatureScheme_name_5 55 | case i == 1537: 56 | return _SignatureScheme_name_6 57 | case i == 1539: 58 | return _SignatureScheme_name_7 59 | case 2052 <= i && i <= 2055: 60 | i -= 2052 61 | return _SignatureScheme_name_8[_SignatureScheme_index_8[i]:_SignatureScheme_index_8[i+1]] 62 | default: 63 | return "SignatureScheme(" + strconv.FormatInt(int64(i), 10) + ")" 64 | } 65 | } 66 | func _() { 67 | // An "invalid array index" compiler error signifies that the constant values have changed. 68 | // Re-run the stringer command to generate them again. 69 | var x [1]struct{} 70 | _ = x[CurveP256-23] 71 | _ = x[CurveP384-24] 72 | _ = x[CurveP521-25] 73 | _ = x[X25519-29] 74 | } 75 | 76 | const ( 77 | _CurveID_name_0 = "CurveP256CurveP384CurveP521" 78 | _CurveID_name_1 = "X25519" 79 | ) 80 | 81 | var ( 82 | _CurveID_index_0 = [...]uint8{0, 9, 18, 27} 83 | ) 84 | 85 | func (i CurveID) String() string { 86 | switch { 87 | case 23 <= i && i <= 25: 88 | i -= 23 89 | return _CurveID_name_0[_CurveID_index_0[i]:_CurveID_index_0[i+1]] 90 | case i == 29: 91 | return _CurveID_name_1 92 | default: 93 | return "CurveID(" + strconv.FormatInt(int64(i), 10) + ")" 94 | } 95 | } 96 | func _() { 97 | // An "invalid array index" compiler error signifies that the constant values have changed. 98 | // Re-run the stringer command to generate them again. 99 | var x [1]struct{} 100 | _ = x[NoClientCert-0] 101 | _ = x[RequestClientCert-1] 102 | _ = x[RequireAnyClientCert-2] 103 | _ = x[VerifyClientCertIfGiven-3] 104 | _ = x[RequireAndVerifyClientCert-4] 105 | } 106 | 107 | const _ClientAuthType_name = "NoClientCertRequestClientCertRequireAnyClientCertVerifyClientCertIfGivenRequireAndVerifyClientCert" 108 | 109 | var _ClientAuthType_index = [...]uint8{0, 12, 29, 49, 72, 98} 110 | 111 | func (i ClientAuthType) String() string { 112 | if i < 0 || i >= ClientAuthType(len(_ClientAuthType_index)-1) { 113 | return "ClientAuthType(" + strconv.FormatInt(int64(i), 10) + ")" 114 | } 115 | return _ClientAuthType_name[_ClientAuthType_index[i]:_ClientAuthType_index[i+1]] 116 | } 117 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # REALITY 2 | 3 | ### THE NEXT FUTURE 4 | 5 | Server side implementation of REALITY protocol, a fork of package tls in Go 1.19.5. 6 | For client side, please follow https://github.com/XTLS/Xray-core/blob/main/transport/internet/reality/reality.go. 7 | 8 | TODO List: TODO 9 | 10 | ## VLESS-XTLS-uTLS-REALITY example for [Xray-core](https://github.com/XTLS/Xray-core) [中文] 11 | 12 | ```json5 13 | { 14 | "inbounds": [ // 服务端入站配置 15 | { 16 | "listen": "0.0.0.0", 17 | "port": 443, 18 | "protocol": "vless", 19 | "settings": { 20 | "clients": [ 21 | { 22 | "id": "", // 必填,执行 ./xray uuid 生成,或 1-30 字节的字符串 23 | "flow": "xtls-rprx-vision" // 选填,若有,客户端必须启用 XTLS 24 | } 25 | ], 26 | "decryption": "none" 27 | }, 28 | "streamSettings": { 29 | "network": "tcp", 30 | "security": "reality", 31 | "realitySettings": { 32 | "show": false, // 选填,若为 true,输出调试信息 33 | "dest": "example.com:443", // 必填,格式同 VLESS fallbacks 的 dest 34 | "xver": 0, // 选填,格式同 VLESS fallbacks 的 xver 35 | "serverNames": [ // 必填,客户端可用的 serverName 列表,暂不支持 * 通配符 36 | "example.com", 37 | "www.example.com" 38 | ], 39 | "privateKey": "", // 必填,执行 ./xray x25519 生成 40 | "minClientVer": "", // 选填,客户端 Xray 最低版本,格式为 x.y.z 41 | "maxClientVer": "", // 选填,客户端 Xray 最高版本,格式为 x.y.z 42 | "maxTimeDiff": 0, // 选填,允许的最大时间差,单位为毫秒 43 | "shortIds": [ // 必填,客户端可用的 shortId 列表,可用于区分不同的客户端 44 | "" // 若有此项,客户端 shortId 可为空 45 | "0123456789abcdef" // 0 到 f,长度为 2 的倍数,长度上限为 16 46 | ] 47 | } 48 | } 49 | } 50 | ] 51 | } 52 | ``` 53 | 54 | 若用 REALITY 取代 TLS,**可消除服务端 TLS 指纹特征**,仍有前向保密性等,**且证书链攻击无效,安全性超越常规 TLS** 55 | **可以指向别人的网站**,无需自己买域名、配置 TLS 服务端,更方便,**实现向中间人呈现指定 SNI 的全程真实 TLS** 56 | 57 | 通常代理用途,目标网站最低标准:**国外网站,支持 TLSv1.3 与 H2,域名非跳转用**(主域名可能被用于跳转到 www) 58 | 加分项:IP 相近(更像,且延迟低),Server Hello 后的握手消息一起加密(如 dl.google.com),有 OCSP Stapling 59 | 配置加分项:**禁回国流量,TCP/80、UDP/443 也转发**(REALITY 对外表现即为端口转发,目标 IP 冷门或许更好) 60 | 61 | **REALITY 也可以搭配 XTLS 以外的代理协议使用**,但不建议这样做,因为它们存在明显且已被针对的 TLS in TLS 特征 62 | REALITY 的下一个主要目标是“**预先构建模式**”,即提前采集目标网站特征,XTLS 的下一个主要目标是 **0-RTT** 63 | 64 | ```json5 65 | { 66 | "outbounds": [ // 客户端出站配置 67 | { 68 | "protocol": "vless", 69 | "settings": { 70 | "vnext": [ 71 | { 72 | "address": "", // 服务端的域名或 IP 73 | "port": 443, 74 | "users": [ 75 | { 76 | "id": "", // 与服务端一致 77 | "flow": "xtls-rprx-vision", // 与服务端一致 78 | "encryption": "none" 79 | } 80 | ] 81 | } 82 | ] 83 | }, 84 | "streamSettings": { 85 | "network": "tcp", 86 | "security": "reality", 87 | "realitySettings": { 88 | "show": false, // 选填,若为 true,输出调试信息 89 | "fingerprint": "chrome", // 必填,使用 uTLS 库模拟客户端 TLS 指纹 90 | "serverName": "", // 服务端 serverNames 之一 91 | "publicKey": "", // 服务端私钥对应的公钥 92 | "shortId": "", // 服务端 shortIds 之一 93 | "spiderX": "" // 爬虫初始路径与参数,建议每个客户端不同 94 | } 95 | } 96 | } 97 | ] 98 | } 99 | ``` 100 | 101 | REALITY 客户端应当收到由“**临时认证密钥**”签发的“**临时可信证书**”,但以下三种情况会收到目标网站的真证书: 102 | 103 | 1. REALITY 服务端拒绝了客户端的 Client Hello,流量被导入目标网站 104 | 2. 客户端的 Client Hello 被中间人重定向至目标网站 105 | 3. 中间人攻击,可能是目标网站帮忙,也可能是证书链攻击 106 | 107 | REALITY 客户端可以完美区分临时可信证书、真证书、无效证书,并决定下一步动作: 108 | 109 | 1. 收到临时可信证书时,连接可用,一切如常 110 | 2. 收到真证书时,进入爬虫模式 111 | 3. 收到无效证书时,TLS alert,断开连接 112 | -------------------------------------------------------------------------------- /alert.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE-Go file. 4 | 5 | package reality 6 | 7 | import "strconv" 8 | 9 | type alert uint8 10 | 11 | const ( 12 | // alert level 13 | alertLevelWarning = 1 14 | alertLevelError = 2 15 | ) 16 | 17 | const ( 18 | alertCloseNotify alert = 0 19 | alertUnexpectedMessage alert = 10 20 | alertBadRecordMAC alert = 20 21 | alertDecryptionFailed alert = 21 22 | alertRecordOverflow alert = 22 23 | alertDecompressionFailure alert = 30 24 | alertHandshakeFailure alert = 40 25 | alertBadCertificate alert = 42 26 | alertUnsupportedCertificate alert = 43 27 | alertCertificateRevoked alert = 44 28 | alertCertificateExpired alert = 45 29 | alertCertificateUnknown alert = 46 30 | alertIllegalParameter alert = 47 31 | alertUnknownCA alert = 48 32 | alertAccessDenied alert = 49 33 | alertDecodeError alert = 50 34 | alertDecryptError alert = 51 35 | alertExportRestriction alert = 60 36 | alertProtocolVersion alert = 70 37 | alertInsufficientSecurity alert = 71 38 | alertInternalError alert = 80 39 | alertInappropriateFallback alert = 86 40 | alertUserCanceled alert = 90 41 | alertNoRenegotiation alert = 100 42 | alertMissingExtension alert = 109 43 | alertUnsupportedExtension alert = 110 44 | alertCertificateUnobtainable alert = 111 45 | alertUnrecognizedName alert = 112 46 | alertBadCertificateStatusResponse alert = 113 47 | alertBadCertificateHashValue alert = 114 48 | alertUnknownPSKIdentity alert = 115 49 | alertCertificateRequired alert = 116 50 | alertNoApplicationProtocol alert = 120 51 | ) 52 | 53 | var alertText = map[alert]string{ 54 | alertCloseNotify: "close notify", 55 | alertUnexpectedMessage: "unexpected message", 56 | alertBadRecordMAC: "bad record MAC", 57 | alertDecryptionFailed: "decryption failed", 58 | alertRecordOverflow: "record overflow", 59 | alertDecompressionFailure: "decompression failure", 60 | alertHandshakeFailure: "handshake failure", 61 | alertBadCertificate: "bad certificate", 62 | alertUnsupportedCertificate: "unsupported certificate", 63 | alertCertificateRevoked: "revoked certificate", 64 | alertCertificateExpired: "expired certificate", 65 | alertCertificateUnknown: "unknown certificate", 66 | alertIllegalParameter: "illegal parameter", 67 | alertUnknownCA: "unknown certificate authority", 68 | alertAccessDenied: "access denied", 69 | alertDecodeError: "error decoding message", 70 | alertDecryptError: "error decrypting message", 71 | alertExportRestriction: "export restriction", 72 | alertProtocolVersion: "protocol version not supported", 73 | alertInsufficientSecurity: "insufficient security level", 74 | alertInternalError: "internal error", 75 | alertInappropriateFallback: "inappropriate fallback", 76 | alertUserCanceled: "user canceled", 77 | alertNoRenegotiation: "no renegotiation", 78 | alertMissingExtension: "missing extension", 79 | alertUnsupportedExtension: "unsupported extension", 80 | alertCertificateUnobtainable: "certificate unobtainable", 81 | alertUnrecognizedName: "unrecognized name", 82 | alertBadCertificateStatusResponse: "bad certificate status response", 83 | alertBadCertificateHashValue: "bad certificate hash value", 84 | alertUnknownPSKIdentity: "unknown PSK identity", 85 | alertCertificateRequired: "certificate required", 86 | alertNoApplicationProtocol: "no application protocol", 87 | } 88 | 89 | func (e alert) String() string { 90 | s, ok := alertText[e] 91 | if ok { 92 | return "tls: " + s 93 | } 94 | return "tls: alert(" + strconv.Itoa(int(e)) + ")" 95 | } 96 | 97 | func (e alert) Error() string { 98 | return e.String() 99 | } 100 | -------------------------------------------------------------------------------- /generate_cert.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE-Go file. 4 | 5 | //go:build ignore 6 | 7 | // Generate a self-signed X.509 certificate for a TLS server. Outputs to 8 | // 'cert.pem' and 'key.pem' and will overwrite existing files. 9 | 10 | package main 11 | 12 | import ( 13 | "crypto/ecdsa" 14 | "crypto/ed25519" 15 | "crypto/elliptic" 16 | "crypto/rand" 17 | "crypto/rsa" 18 | "crypto/x509" 19 | "crypto/x509/pkix" 20 | "encoding/pem" 21 | "flag" 22 | "log" 23 | "math/big" 24 | "net" 25 | "os" 26 | "strings" 27 | "time" 28 | ) 29 | 30 | var ( 31 | host = flag.String("host", "", "Comma-separated hostnames and IPs to generate a certificate for") 32 | validFrom = flag.String("start-date", "", "Creation date formatted as Jan 1 15:04:05 2011") 33 | validFor = flag.Duration("duration", 365*24*time.Hour, "Duration that certificate is valid for") 34 | isCA = flag.Bool("ca", false, "whether this cert should be its own Certificate Authority") 35 | rsaBits = flag.Int("rsa-bits", 2048, "Size of RSA key to generate. Ignored if --ecdsa-curve is set") 36 | ecdsaCurve = flag.String("ecdsa-curve", "", "ECDSA curve to use to generate a key. Valid values are P224, P256 (recommended), P384, P521") 37 | ed25519Key = flag.Bool("ed25519", false, "Generate an Ed25519 key") 38 | ) 39 | 40 | func publicKey(priv any) any { 41 | switch k := priv.(type) { 42 | case *rsa.PrivateKey: 43 | return &k.PublicKey 44 | case *ecdsa.PrivateKey: 45 | return &k.PublicKey 46 | case ed25519.PrivateKey: 47 | return k.Public().(ed25519.PublicKey) 48 | default: 49 | return nil 50 | } 51 | } 52 | 53 | func main() { 54 | flag.Parse() 55 | 56 | if len(*host) == 0 { 57 | log.Fatalf("Missing required --host parameter") 58 | } 59 | 60 | var priv any 61 | var err error 62 | switch *ecdsaCurve { 63 | case "": 64 | if *ed25519Key { 65 | _, priv, err = ed25519.GenerateKey(rand.Reader) 66 | } else { 67 | priv, err = rsa.GenerateKey(rand.Reader, *rsaBits) 68 | } 69 | case "P224": 70 | priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader) 71 | case "P256": 72 | priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 73 | case "P384": 74 | priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader) 75 | case "P521": 76 | priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader) 77 | default: 78 | log.Fatalf("Unrecognized elliptic curve: %q", *ecdsaCurve) 79 | } 80 | if err != nil { 81 | log.Fatalf("Failed to generate private key: %v", err) 82 | } 83 | 84 | // ECDSA, ED25519 and RSA subject keys should have the DigitalSignature 85 | // KeyUsage bits set in the x509.Certificate template 86 | keyUsage := x509.KeyUsageDigitalSignature 87 | // Only RSA subject keys should have the KeyEncipherment KeyUsage bits set. In 88 | // the context of TLS this KeyUsage is particular to RSA key exchange and 89 | // authentication. 90 | if _, isRSA := priv.(*rsa.PrivateKey); isRSA { 91 | keyUsage |= x509.KeyUsageKeyEncipherment 92 | } 93 | 94 | var notBefore time.Time 95 | if len(*validFrom) == 0 { 96 | notBefore = time.Now() 97 | } else { 98 | notBefore, err = time.Parse("Jan 2 15:04:05 2006", *validFrom) 99 | if err != nil { 100 | log.Fatalf("Failed to parse creation date: %v", err) 101 | } 102 | } 103 | 104 | notAfter := notBefore.Add(*validFor) 105 | 106 | serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) 107 | serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) 108 | if err != nil { 109 | log.Fatalf("Failed to generate serial number: %v", err) 110 | } 111 | 112 | template := x509.Certificate{ 113 | SerialNumber: serialNumber, 114 | Subject: pkix.Name{ 115 | Organization: []string{"Acme Co"}, 116 | }, 117 | NotBefore: notBefore, 118 | NotAfter: notAfter, 119 | 120 | KeyUsage: keyUsage, 121 | ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, 122 | BasicConstraintsValid: true, 123 | } 124 | 125 | hosts := strings.Split(*host, ",") 126 | for _, h := range hosts { 127 | if ip := net.ParseIP(h); ip != nil { 128 | template.IPAddresses = append(template.IPAddresses, ip) 129 | } else { 130 | template.DNSNames = append(template.DNSNames, h) 131 | } 132 | } 133 | 134 | if *isCA { 135 | template.IsCA = true 136 | template.KeyUsage |= x509.KeyUsageCertSign 137 | } 138 | 139 | derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv) 140 | if err != nil { 141 | log.Fatalf("Failed to create certificate: %v", err) 142 | } 143 | 144 | certOut, err := os.Create("cert.pem") 145 | if err != nil { 146 | log.Fatalf("Failed to open cert.pem for writing: %v", err) 147 | } 148 | if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil { 149 | log.Fatalf("Failed to write data to cert.pem: %v", err) 150 | } 151 | if err := certOut.Close(); err != nil { 152 | log.Fatalf("Error closing cert.pem: %v", err) 153 | } 154 | log.Print("wrote cert.pem\n") 155 | 156 | keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) 157 | if err != nil { 158 | log.Fatalf("Failed to open key.pem for writing: %v", err) 159 | return 160 | } 161 | privBytes, err := x509.MarshalPKCS8PrivateKey(priv) 162 | if err != nil { 163 | log.Fatalf("Unable to marshal private key: %v", err) 164 | } 165 | if err := pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil { 166 | log.Fatalf("Failed to write data to key.pem: %v", err) 167 | } 168 | if err := keyOut.Close(); err != nil { 169 | log.Fatalf("Error closing key.pem: %v", err) 170 | } 171 | log.Print("wrote key.pem\n") 172 | } 173 | -------------------------------------------------------------------------------- /ticket.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE-Go file. 4 | 5 | package reality 6 | 7 | import ( 8 | "bytes" 9 | "crypto/aes" 10 | "crypto/cipher" 11 | "crypto/hmac" 12 | "crypto/sha256" 13 | "crypto/subtle" 14 | "errors" 15 | "io" 16 | 17 | "golang.org/x/crypto/cryptobyte" 18 | ) 19 | 20 | // sessionState contains the information that is serialized into a session 21 | // ticket in order to later resume a connection. 22 | type sessionState struct { 23 | vers uint16 24 | cipherSuite uint16 25 | createdAt uint64 26 | masterSecret []byte // opaque master_secret<1..2^16-1>; 27 | // struct { opaque certificate<1..2^24-1> } Certificate; 28 | certificates [][]byte // Certificate certificate_list<0..2^24-1>; 29 | 30 | // usedOldKey is true if the ticket from which this session came from 31 | // was encrypted with an older key and thus should be refreshed. 32 | usedOldKey bool 33 | } 34 | 35 | func (m *sessionState) marshal() []byte { 36 | var b cryptobyte.Builder 37 | b.AddUint16(m.vers) 38 | b.AddUint16(m.cipherSuite) 39 | addUint64(&b, m.createdAt) 40 | b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { 41 | b.AddBytes(m.masterSecret) 42 | }) 43 | b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { 44 | for _, cert := range m.certificates { 45 | b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { 46 | b.AddBytes(cert) 47 | }) 48 | } 49 | }) 50 | return b.BytesOrPanic() 51 | } 52 | 53 | func (m *sessionState) unmarshal(data []byte) bool { 54 | *m = sessionState{usedOldKey: m.usedOldKey} 55 | s := cryptobyte.String(data) 56 | if ok := s.ReadUint16(&m.vers) && 57 | s.ReadUint16(&m.cipherSuite) && 58 | readUint64(&s, &m.createdAt) && 59 | readUint16LengthPrefixed(&s, &m.masterSecret) && 60 | len(m.masterSecret) != 0; !ok { 61 | return false 62 | } 63 | var certList cryptobyte.String 64 | if !s.ReadUint24LengthPrefixed(&certList) { 65 | return false 66 | } 67 | for !certList.Empty() { 68 | var cert []byte 69 | if !readUint24LengthPrefixed(&certList, &cert) { 70 | return false 71 | } 72 | m.certificates = append(m.certificates, cert) 73 | } 74 | return s.Empty() 75 | } 76 | 77 | // sessionStateTLS13 is the content of a TLS 1.3 session ticket. Its first 78 | // version (revision = 0) doesn't carry any of the information needed for 0-RTT 79 | // validation and the nonce is always empty. 80 | type sessionStateTLS13 struct { 81 | // uint8 version = 0x0304; 82 | // uint8 revision = 0; 83 | cipherSuite uint16 84 | createdAt uint64 85 | resumptionSecret []byte // opaque resumption_master_secret<1..2^8-1>; 86 | certificate Certificate // CertificateEntry certificate_list<0..2^24-1>; 87 | } 88 | 89 | func (m *sessionStateTLS13) marshal() []byte { 90 | var b cryptobyte.Builder 91 | b.AddUint16(VersionTLS13) 92 | b.AddUint8(0) // revision 93 | b.AddUint16(m.cipherSuite) 94 | addUint64(&b, m.createdAt) 95 | b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { 96 | b.AddBytes(m.resumptionSecret) 97 | }) 98 | marshalCertificate(&b, m.certificate) 99 | return b.BytesOrPanic() 100 | } 101 | 102 | func (m *sessionStateTLS13) unmarshal(data []byte) bool { 103 | *m = sessionStateTLS13{} 104 | s := cryptobyte.String(data) 105 | var version uint16 106 | var revision uint8 107 | return s.ReadUint16(&version) && 108 | version == VersionTLS13 && 109 | s.ReadUint8(&revision) && 110 | revision == 0 && 111 | s.ReadUint16(&m.cipherSuite) && 112 | readUint64(&s, &m.createdAt) && 113 | readUint8LengthPrefixed(&s, &m.resumptionSecret) && 114 | len(m.resumptionSecret) != 0 && 115 | unmarshalCertificate(&s, &m.certificate) && 116 | s.Empty() 117 | } 118 | 119 | func (c *Conn) encryptTicket(state []byte) ([]byte, error) { 120 | if len(c.ticketKeys) == 0 { 121 | return nil, errors.New("tls: internal error: session ticket keys unavailable") 122 | } 123 | 124 | encrypted := make([]byte, ticketKeyNameLen+aes.BlockSize+len(state)+sha256.Size) 125 | keyName := encrypted[:ticketKeyNameLen] 126 | iv := encrypted[ticketKeyNameLen : ticketKeyNameLen+aes.BlockSize] 127 | macBytes := encrypted[len(encrypted)-sha256.Size:] 128 | 129 | if _, err := io.ReadFull(c.config.rand(), iv); err != nil { 130 | return nil, err 131 | } 132 | key := c.ticketKeys[0] 133 | copy(keyName, key.keyName[:]) 134 | block, err := aes.NewCipher(key.aesKey[:]) 135 | if err != nil { 136 | return nil, errors.New("tls: failed to create cipher while encrypting ticket: " + err.Error()) 137 | } 138 | cipher.NewCTR(block, iv).XORKeyStream(encrypted[ticketKeyNameLen+aes.BlockSize:], state) 139 | 140 | mac := hmac.New(sha256.New, key.hmacKey[:]) 141 | mac.Write(encrypted[:len(encrypted)-sha256.Size]) 142 | mac.Sum(macBytes[:0]) 143 | 144 | return encrypted, nil 145 | } 146 | 147 | func (c *Conn) decryptTicket(encrypted []byte) (plaintext []byte, usedOldKey bool) { 148 | if len(encrypted) < ticketKeyNameLen+aes.BlockSize+sha256.Size { 149 | return nil, false 150 | } 151 | 152 | keyName := encrypted[:ticketKeyNameLen] 153 | iv := encrypted[ticketKeyNameLen : ticketKeyNameLen+aes.BlockSize] 154 | macBytes := encrypted[len(encrypted)-sha256.Size:] 155 | ciphertext := encrypted[ticketKeyNameLen+aes.BlockSize : len(encrypted)-sha256.Size] 156 | 157 | keyIndex := -1 158 | for i, candidateKey := range c.ticketKeys { 159 | if bytes.Equal(keyName, candidateKey.keyName[:]) { 160 | keyIndex = i 161 | break 162 | } 163 | } 164 | if keyIndex == -1 { 165 | return nil, false 166 | } 167 | key := &c.ticketKeys[keyIndex] 168 | 169 | mac := hmac.New(sha256.New, key.hmacKey[:]) 170 | mac.Write(encrypted[:len(encrypted)-sha256.Size]) 171 | expected := mac.Sum(nil) 172 | 173 | if subtle.ConstantTimeCompare(macBytes, expected) != 1 { 174 | return nil, false 175 | } 176 | 177 | block, err := aes.NewCipher(key.aesKey[:]) 178 | if err != nil { 179 | return nil, false 180 | } 181 | plaintext = make([]byte, len(ciphertext)) 182 | cipher.NewCTR(block, iv).XORKeyStream(plaintext, ciphertext) 183 | 184 | return plaintext, keyIndex > 0 185 | } 186 | -------------------------------------------------------------------------------- /key_schedule.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE-Go file. 4 | 5 | package reality 6 | 7 | import ( 8 | "crypto/elliptic" 9 | "crypto/hmac" 10 | "errors" 11 | "hash" 12 | "io" 13 | "math/big" 14 | 15 | "golang.org/x/crypto/cryptobyte" 16 | "golang.org/x/crypto/curve25519" 17 | "golang.org/x/crypto/hkdf" 18 | ) 19 | 20 | // This file contains the functions necessary to compute the TLS 1.3 key 21 | // schedule. See RFC 8446, Section 7. 22 | 23 | const ( 24 | resumptionBinderLabel = "res binder" 25 | clientHandshakeTrafficLabel = "c hs traffic" 26 | serverHandshakeTrafficLabel = "s hs traffic" 27 | clientApplicationTrafficLabel = "c ap traffic" 28 | serverApplicationTrafficLabel = "s ap traffic" 29 | exporterLabel = "exp master" 30 | resumptionLabel = "res master" 31 | trafficUpdateLabel = "traffic upd" 32 | ) 33 | 34 | // expandLabel implements HKDF-Expand-Label from RFC 8446, Section 7.1. 35 | func (c *cipherSuiteTLS13) expandLabel(secret []byte, label string, context []byte, length int) []byte { 36 | var hkdfLabel cryptobyte.Builder 37 | hkdfLabel.AddUint16(uint16(length)) 38 | hkdfLabel.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { 39 | b.AddBytes([]byte("tls13 ")) 40 | b.AddBytes([]byte(label)) 41 | }) 42 | hkdfLabel.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { 43 | b.AddBytes(context) 44 | }) 45 | out := make([]byte, length) 46 | n, err := hkdf.Expand(c.hash.New, secret, hkdfLabel.BytesOrPanic()).Read(out) 47 | if err != nil || n != length { 48 | panic("tls: HKDF-Expand-Label invocation failed unexpectedly") 49 | } 50 | return out 51 | } 52 | 53 | // deriveSecret implements Derive-Secret from RFC 8446, Section 7.1. 54 | func (c *cipherSuiteTLS13) deriveSecret(secret []byte, label string, transcript hash.Hash) []byte { 55 | if transcript == nil { 56 | transcript = c.hash.New() 57 | } 58 | return c.expandLabel(secret, label, transcript.Sum(nil), c.hash.Size()) 59 | } 60 | 61 | // extract implements HKDF-Extract with the cipher suite hash. 62 | func (c *cipherSuiteTLS13) extract(newSecret, currentSecret []byte) []byte { 63 | if newSecret == nil { 64 | newSecret = make([]byte, c.hash.Size()) 65 | } 66 | return hkdf.Extract(c.hash.New, newSecret, currentSecret) 67 | } 68 | 69 | // nextTrafficSecret generates the next traffic secret, given the current one, 70 | // according to RFC 8446, Section 7.2. 71 | func (c *cipherSuiteTLS13) nextTrafficSecret(trafficSecret []byte) []byte { 72 | return c.expandLabel(trafficSecret, trafficUpdateLabel, nil, c.hash.Size()) 73 | } 74 | 75 | // trafficKey generates traffic keys according to RFC 8446, Section 7.3. 76 | func (c *cipherSuiteTLS13) trafficKey(trafficSecret []byte) (key, iv []byte) { 77 | key = c.expandLabel(trafficSecret, "key", nil, c.keyLen) 78 | iv = c.expandLabel(trafficSecret, "iv", nil, aeadNonceLength) 79 | return 80 | } 81 | 82 | // finishedHash generates the Finished verify_data or PskBinderEntry according 83 | // to RFC 8446, Section 4.4.4. See sections 4.4 and 4.2.11.2 for the baseKey 84 | // selection. 85 | func (c *cipherSuiteTLS13) finishedHash(baseKey []byte, transcript hash.Hash) []byte { 86 | finishedKey := c.expandLabel(baseKey, "finished", nil, c.hash.Size()) 87 | verifyData := hmac.New(c.hash.New, finishedKey) 88 | verifyData.Write(transcript.Sum(nil)) 89 | return verifyData.Sum(nil) 90 | } 91 | 92 | // exportKeyingMaterial implements RFC5705 exporters for TLS 1.3 according to 93 | // RFC 8446, Section 7.5. 94 | func (c *cipherSuiteTLS13) exportKeyingMaterial(masterSecret []byte, transcript hash.Hash) func(string, []byte, int) ([]byte, error) { 95 | expMasterSecret := c.deriveSecret(masterSecret, exporterLabel, transcript) 96 | return func(label string, context []byte, length int) ([]byte, error) { 97 | secret := c.deriveSecret(expMasterSecret, label, nil) 98 | h := c.hash.New() 99 | h.Write(context) 100 | return c.expandLabel(secret, "exporter", h.Sum(nil), length), nil 101 | } 102 | } 103 | 104 | // ecdheParameters implements Diffie-Hellman with either NIST curves or X25519, 105 | // according to RFC 8446, Section 4.2.8.2. 106 | type ecdheParameters interface { 107 | CurveID() CurveID 108 | PublicKey() []byte 109 | SharedKey(peerPublicKey []byte) []byte 110 | } 111 | 112 | func generateECDHEParameters(rand io.Reader, curveID CurveID) (ecdheParameters, error) { 113 | if curveID == X25519 { 114 | privateKey := make([]byte, curve25519.ScalarSize) 115 | if _, err := io.ReadFull(rand, privateKey); err != nil { 116 | return nil, err 117 | } 118 | publicKey, err := curve25519.X25519(privateKey, curve25519.Basepoint) 119 | if err != nil { 120 | return nil, err 121 | } 122 | return &x25519Parameters{privateKey: privateKey, publicKey: publicKey}, nil 123 | } 124 | 125 | curve, ok := curveForCurveID(curveID) 126 | if !ok { 127 | return nil, errors.New("tls: internal error: unsupported curve") 128 | } 129 | 130 | p := &nistParameters{curveID: curveID} 131 | var err error 132 | p.privateKey, p.x, p.y, err = elliptic.GenerateKey(curve, rand) 133 | if err != nil { 134 | return nil, err 135 | } 136 | return p, nil 137 | } 138 | 139 | func curveForCurveID(id CurveID) (elliptic.Curve, bool) { 140 | switch id { 141 | case CurveP256: 142 | return elliptic.P256(), true 143 | case CurveP384: 144 | return elliptic.P384(), true 145 | case CurveP521: 146 | return elliptic.P521(), true 147 | default: 148 | return nil, false 149 | } 150 | } 151 | 152 | type nistParameters struct { 153 | privateKey []byte 154 | x, y *big.Int // public key 155 | curveID CurveID 156 | } 157 | 158 | func (p *nistParameters) CurveID() CurveID { 159 | return p.curveID 160 | } 161 | 162 | func (p *nistParameters) PublicKey() []byte { 163 | curve, _ := curveForCurveID(p.curveID) 164 | return elliptic.Marshal(curve, p.x, p.y) 165 | } 166 | 167 | func (p *nistParameters) SharedKey(peerPublicKey []byte) []byte { 168 | curve, _ := curveForCurveID(p.curveID) 169 | // Unmarshal also checks whether the given point is on the curve. 170 | x, y := elliptic.Unmarshal(curve, peerPublicKey) 171 | if x == nil { 172 | return nil 173 | } 174 | 175 | xShared, _ := curve.ScalarMult(x, y, p.privateKey) 176 | sharedKey := make([]byte, (curve.Params().BitSize+7)/8) 177 | return xShared.FillBytes(sharedKey) 178 | } 179 | 180 | type x25519Parameters struct { 181 | privateKey []byte 182 | publicKey []byte 183 | } 184 | 185 | func (p *x25519Parameters) CurveID() CurveID { 186 | return X25519 187 | } 188 | 189 | func (p *x25519Parameters) PublicKey() []byte { 190 | return p.publicKey[:] 191 | } 192 | 193 | func (p *x25519Parameters) SharedKey(peerPublicKey []byte) []byte { 194 | sharedKey, err := curve25519.X25519(p.privateKey, peerPublicKey) 195 | if err != nil { 196 | return nil 197 | } 198 | return sharedKey 199 | } 200 | -------------------------------------------------------------------------------- /prf.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE-Go file. 4 | 5 | package reality 6 | 7 | import ( 8 | "crypto" 9 | "crypto/hmac" 10 | "crypto/md5" 11 | "crypto/sha1" 12 | "crypto/sha256" 13 | "crypto/sha512" 14 | "errors" 15 | "fmt" 16 | "hash" 17 | ) 18 | 19 | // Split a premaster secret in two as specified in RFC 4346, Section 5. 20 | func splitPreMasterSecret(secret []byte) (s1, s2 []byte) { 21 | s1 = secret[0 : (len(secret)+1)/2] 22 | s2 = secret[len(secret)/2:] 23 | return 24 | } 25 | 26 | // pHash implements the P_hash function, as defined in RFC 4346, Section 5. 27 | func pHash(result, secret, seed []byte, hash func() hash.Hash) { 28 | h := hmac.New(hash, secret) 29 | h.Write(seed) 30 | a := h.Sum(nil) 31 | 32 | j := 0 33 | for j < len(result) { 34 | h.Reset() 35 | h.Write(a) 36 | h.Write(seed) 37 | b := h.Sum(nil) 38 | copy(result[j:], b) 39 | j += len(b) 40 | 41 | h.Reset() 42 | h.Write(a) 43 | a = h.Sum(nil) 44 | } 45 | } 46 | 47 | // prf10 implements the TLS 1.0 pseudo-random function, as defined in RFC 2246, Section 5. 48 | func prf10(result, secret, label, seed []byte) { 49 | hashSHA1 := sha1.New 50 | hashMD5 := md5.New 51 | 52 | labelAndSeed := make([]byte, len(label)+len(seed)) 53 | copy(labelAndSeed, label) 54 | copy(labelAndSeed[len(label):], seed) 55 | 56 | s1, s2 := splitPreMasterSecret(secret) 57 | pHash(result, s1, labelAndSeed, hashMD5) 58 | result2 := make([]byte, len(result)) 59 | pHash(result2, s2, labelAndSeed, hashSHA1) 60 | 61 | for i, b := range result2 { 62 | result[i] ^= b 63 | } 64 | } 65 | 66 | // prf12 implements the TLS 1.2 pseudo-random function, as defined in RFC 5246, Section 5. 67 | func prf12(hashFunc func() hash.Hash) func(result, secret, label, seed []byte) { 68 | return func(result, secret, label, seed []byte) { 69 | labelAndSeed := make([]byte, len(label)+len(seed)) 70 | copy(labelAndSeed, label) 71 | copy(labelAndSeed[len(label):], seed) 72 | 73 | pHash(result, secret, labelAndSeed, hashFunc) 74 | } 75 | } 76 | 77 | const ( 78 | masterSecretLength = 48 // Length of a master secret in TLS 1.1. 79 | finishedVerifyLength = 12 // Length of verify_data in a Finished message. 80 | ) 81 | 82 | var masterSecretLabel = []byte("master secret") 83 | var keyExpansionLabel = []byte("key expansion") 84 | var clientFinishedLabel = []byte("client finished") 85 | var serverFinishedLabel = []byte("server finished") 86 | 87 | func prfAndHashForVersion(version uint16, suite *cipherSuite) (func(result, secret, label, seed []byte), crypto.Hash) { 88 | switch version { 89 | case VersionTLS10, VersionTLS11: 90 | return prf10, crypto.Hash(0) 91 | case VersionTLS12: 92 | if suite.flags&suiteSHA384 != 0 { 93 | return prf12(sha512.New384), crypto.SHA384 94 | } 95 | return prf12(sha256.New), crypto.SHA256 96 | default: 97 | panic("unknown version") 98 | } 99 | } 100 | 101 | func prfForVersion(version uint16, suite *cipherSuite) func(result, secret, label, seed []byte) { 102 | prf, _ := prfAndHashForVersion(version, suite) 103 | return prf 104 | } 105 | 106 | // masterFromPreMasterSecret generates the master secret from the pre-master 107 | // secret. See RFC 5246, Section 8.1. 108 | func masterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret, clientRandom, serverRandom []byte) []byte { 109 | seed := make([]byte, 0, len(clientRandom)+len(serverRandom)) 110 | seed = append(seed, clientRandom...) 111 | seed = append(seed, serverRandom...) 112 | 113 | masterSecret := make([]byte, masterSecretLength) 114 | prfForVersion(version, suite)(masterSecret, preMasterSecret, masterSecretLabel, seed) 115 | return masterSecret 116 | } 117 | 118 | // keysFromMasterSecret generates the connection keys from the master 119 | // secret, given the lengths of the MAC key, cipher key and IV, as defined in 120 | // RFC 2246, Section 6.3. 121 | func keysFromMasterSecret(version uint16, suite *cipherSuite, masterSecret, clientRandom, serverRandom []byte, macLen, keyLen, ivLen int) (clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV []byte) { 122 | seed := make([]byte, 0, len(serverRandom)+len(clientRandom)) 123 | seed = append(seed, serverRandom...) 124 | seed = append(seed, clientRandom...) 125 | 126 | n := 2*macLen + 2*keyLen + 2*ivLen 127 | keyMaterial := make([]byte, n) 128 | prfForVersion(version, suite)(keyMaterial, masterSecret, keyExpansionLabel, seed) 129 | clientMAC = keyMaterial[:macLen] 130 | keyMaterial = keyMaterial[macLen:] 131 | serverMAC = keyMaterial[:macLen] 132 | keyMaterial = keyMaterial[macLen:] 133 | clientKey = keyMaterial[:keyLen] 134 | keyMaterial = keyMaterial[keyLen:] 135 | serverKey = keyMaterial[:keyLen] 136 | keyMaterial = keyMaterial[keyLen:] 137 | clientIV = keyMaterial[:ivLen] 138 | keyMaterial = keyMaterial[ivLen:] 139 | serverIV = keyMaterial[:ivLen] 140 | return 141 | } 142 | 143 | func newFinishedHash(version uint16, cipherSuite *cipherSuite) finishedHash { 144 | var buffer []byte 145 | if version >= VersionTLS12 { 146 | buffer = []byte{} 147 | } 148 | 149 | prf, hash := prfAndHashForVersion(version, cipherSuite) 150 | if hash != 0 { 151 | return finishedHash{hash.New(), hash.New(), nil, nil, buffer, version, prf} 152 | } 153 | 154 | return finishedHash{sha1.New(), sha1.New(), md5.New(), md5.New(), buffer, version, prf} 155 | } 156 | 157 | // A finishedHash calculates the hash of a set of handshake messages suitable 158 | // for including in a Finished message. 159 | type finishedHash struct { 160 | client hash.Hash 161 | server hash.Hash 162 | 163 | // Prior to TLS 1.2, an additional MD5 hash is required. 164 | clientMD5 hash.Hash 165 | serverMD5 hash.Hash 166 | 167 | // In TLS 1.2, a full buffer is sadly required. 168 | buffer []byte 169 | 170 | version uint16 171 | prf func(result, secret, label, seed []byte) 172 | } 173 | 174 | func (h *finishedHash) Write(msg []byte) (n int, err error) { 175 | h.client.Write(msg) 176 | h.server.Write(msg) 177 | 178 | if h.version < VersionTLS12 { 179 | h.clientMD5.Write(msg) 180 | h.serverMD5.Write(msg) 181 | } 182 | 183 | if h.buffer != nil { 184 | h.buffer = append(h.buffer, msg...) 185 | } 186 | 187 | return len(msg), nil 188 | } 189 | 190 | func (h finishedHash) Sum() []byte { 191 | if h.version >= VersionTLS12 { 192 | return h.client.Sum(nil) 193 | } 194 | 195 | out := make([]byte, 0, md5.Size+sha1.Size) 196 | out = h.clientMD5.Sum(out) 197 | return h.client.Sum(out) 198 | } 199 | 200 | // clientSum returns the contents of the verify_data member of a client's 201 | // Finished message. 202 | func (h finishedHash) clientSum(masterSecret []byte) []byte { 203 | out := make([]byte, finishedVerifyLength) 204 | h.prf(out, masterSecret, clientFinishedLabel, h.Sum()) 205 | return out 206 | } 207 | 208 | // serverSum returns the contents of the verify_data member of a server's 209 | // Finished message. 210 | func (h finishedHash) serverSum(masterSecret []byte) []byte { 211 | out := make([]byte, finishedVerifyLength) 212 | h.prf(out, masterSecret, serverFinishedLabel, h.Sum()) 213 | return out 214 | } 215 | 216 | // hashForClientCertificate returns the handshake messages so far, pre-hashed if 217 | // necessary, suitable for signing by a TLS client certificate. 218 | func (h finishedHash) hashForClientCertificate(sigType uint8, hashAlg crypto.Hash, masterSecret []byte) []byte { 219 | if (h.version >= VersionTLS12 || sigType == signatureEd25519) && h.buffer == nil { 220 | panic("tls: handshake hash for a client certificate requested after discarding the handshake buffer") 221 | } 222 | 223 | if sigType == signatureEd25519 { 224 | return h.buffer 225 | } 226 | 227 | if h.version >= VersionTLS12 { 228 | hash := hashAlg.New() 229 | hash.Write(h.buffer) 230 | return hash.Sum(nil) 231 | } 232 | 233 | if sigType == signatureECDSA { 234 | return h.server.Sum(nil) 235 | } 236 | 237 | return h.Sum() 238 | } 239 | 240 | // discardHandshakeBuffer is called when there is no more need to 241 | // buffer the entirety of the handshake messages. 242 | func (h *finishedHash) discardHandshakeBuffer() { 243 | h.buffer = nil 244 | } 245 | 246 | // noExportedKeyingMaterial is used as a value of 247 | // ConnectionState.ekm when renegotiation is enabled and thus 248 | // we wish to fail all key-material export requests. 249 | func noExportedKeyingMaterial(label string, context []byte, length int) ([]byte, error) { 250 | return nil, errors.New("crypto/tls: ExportKeyingMaterial is unavailable when renegotiation is enabled") 251 | } 252 | 253 | // ekmFromMasterSecret generates exported keying material as defined in RFC 5705. 254 | func ekmFromMasterSecret(version uint16, suite *cipherSuite, masterSecret, clientRandom, serverRandom []byte) func(string, []byte, int) ([]byte, error) { 255 | return func(label string, context []byte, length int) ([]byte, error) { 256 | switch label { 257 | case "client finished", "server finished", "master secret", "key expansion": 258 | // These values are reserved and may not be used. 259 | return nil, fmt.Errorf("crypto/tls: reserved ExportKeyingMaterial label: %s", label) 260 | } 261 | 262 | seedLen := len(serverRandom) + len(clientRandom) 263 | if context != nil { 264 | seedLen += 2 + len(context) 265 | } 266 | seed := make([]byte, 0, seedLen) 267 | 268 | seed = append(seed, clientRandom...) 269 | seed = append(seed, serverRandom...) 270 | 271 | if context != nil { 272 | if len(context) >= 1<<16 { 273 | return nil, fmt.Errorf("crypto/tls: ExportKeyingMaterial context too long") 274 | } 275 | seed = append(seed, byte(len(context)>>8), byte(len(context))) 276 | seed = append(seed, context...) 277 | } 278 | 279 | keyMaterial := make([]byte, length) 280 | prfForVersion(version, suite)(keyMaterial, masterSecret, []byte(label), seed) 281 | return keyMaterial, nil 282 | } 283 | } 284 | -------------------------------------------------------------------------------- /auth.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE-Go file. 4 | 5 | package reality 6 | 7 | import ( 8 | "bytes" 9 | "crypto" 10 | "crypto/ecdsa" 11 | "crypto/ed25519" 12 | "crypto/elliptic" 13 | "crypto/rsa" 14 | "errors" 15 | "fmt" 16 | "hash" 17 | "io" 18 | ) 19 | 20 | // verifyHandshakeSignature verifies a signature against pre-hashed 21 | // (if required) handshake contents. 22 | func verifyHandshakeSignature(sigType uint8, pubkey crypto.PublicKey, hashFunc crypto.Hash, signed, sig []byte) error { 23 | switch sigType { 24 | case signatureECDSA: 25 | pubKey, ok := pubkey.(*ecdsa.PublicKey) 26 | if !ok { 27 | return fmt.Errorf("expected an ECDSA public key, got %T", pubkey) 28 | } 29 | if !ecdsa.VerifyASN1(pubKey, signed, sig) { 30 | return errors.New("ECDSA verification failure") 31 | } 32 | case signatureEd25519: 33 | pubKey, ok := pubkey.(ed25519.PublicKey) 34 | if !ok { 35 | return fmt.Errorf("expected an Ed25519 public key, got %T", pubkey) 36 | } 37 | if !ed25519.Verify(pubKey, signed, sig) { 38 | return errors.New("Ed25519 verification failure") 39 | } 40 | case signaturePKCS1v15: 41 | pubKey, ok := pubkey.(*rsa.PublicKey) 42 | if !ok { 43 | return fmt.Errorf("expected an RSA public key, got %T", pubkey) 44 | } 45 | if err := rsa.VerifyPKCS1v15(pubKey, hashFunc, signed, sig); err != nil { 46 | return err 47 | } 48 | case signatureRSAPSS: 49 | pubKey, ok := pubkey.(*rsa.PublicKey) 50 | if !ok { 51 | return fmt.Errorf("expected an RSA public key, got %T", pubkey) 52 | } 53 | signOpts := &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash} 54 | if err := rsa.VerifyPSS(pubKey, hashFunc, signed, sig, signOpts); err != nil { 55 | return err 56 | } 57 | default: 58 | return errors.New("internal error: unknown signature type") 59 | } 60 | return nil 61 | } 62 | 63 | const ( 64 | serverSignatureContext = "TLS 1.3, server CertificateVerify\x00" 65 | clientSignatureContext = "TLS 1.3, client CertificateVerify\x00" 66 | ) 67 | 68 | var signaturePadding = []byte{ 69 | 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 70 | 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 71 | 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 72 | 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 73 | 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 74 | 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 75 | 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 76 | 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 77 | } 78 | 79 | // signedMessage returns the pre-hashed (if necessary) message to be signed by 80 | // certificate keys in TLS 1.3. See RFC 8446, Section 4.4.3. 81 | func signedMessage(sigHash crypto.Hash, context string, transcript hash.Hash) []byte { 82 | if sigHash == directSigning { 83 | b := &bytes.Buffer{} 84 | b.Write(signaturePadding) 85 | io.WriteString(b, context) 86 | b.Write(transcript.Sum(nil)) 87 | return b.Bytes() 88 | } 89 | h := sigHash.New() 90 | h.Write(signaturePadding) 91 | io.WriteString(h, context) 92 | h.Write(transcript.Sum(nil)) 93 | return h.Sum(nil) 94 | } 95 | 96 | // typeAndHashFromSignatureScheme returns the corresponding signature type and 97 | // crypto.Hash for a given TLS SignatureScheme. 98 | func typeAndHashFromSignatureScheme(signatureAlgorithm SignatureScheme) (sigType uint8, hash crypto.Hash, err error) { 99 | switch signatureAlgorithm { 100 | case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512: 101 | sigType = signaturePKCS1v15 102 | case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512: 103 | sigType = signatureRSAPSS 104 | case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512: 105 | sigType = signatureECDSA 106 | case Ed25519: 107 | sigType = signatureEd25519 108 | default: 109 | return 0, 0, fmt.Errorf("unsupported signature algorithm: %v", signatureAlgorithm) 110 | } 111 | switch signatureAlgorithm { 112 | case PKCS1WithSHA1, ECDSAWithSHA1: 113 | hash = crypto.SHA1 114 | case PKCS1WithSHA256, PSSWithSHA256, ECDSAWithP256AndSHA256: 115 | hash = crypto.SHA256 116 | case PKCS1WithSHA384, PSSWithSHA384, ECDSAWithP384AndSHA384: 117 | hash = crypto.SHA384 118 | case PKCS1WithSHA512, PSSWithSHA512, ECDSAWithP521AndSHA512: 119 | hash = crypto.SHA512 120 | case Ed25519: 121 | hash = directSigning 122 | default: 123 | return 0, 0, fmt.Errorf("unsupported signature algorithm: %v", signatureAlgorithm) 124 | } 125 | return sigType, hash, nil 126 | } 127 | 128 | // legacyTypeAndHashFromPublicKey returns the fixed signature type and crypto.Hash for 129 | // a given public key used with TLS 1.0 and 1.1, before the introduction of 130 | // signature algorithm negotiation. 131 | func legacyTypeAndHashFromPublicKey(pub crypto.PublicKey) (sigType uint8, hash crypto.Hash, err error) { 132 | switch pub.(type) { 133 | case *rsa.PublicKey: 134 | return signaturePKCS1v15, crypto.MD5SHA1, nil 135 | case *ecdsa.PublicKey: 136 | return signatureECDSA, crypto.SHA1, nil 137 | case ed25519.PublicKey: 138 | // RFC 8422 specifies support for Ed25519 in TLS 1.0 and 1.1, 139 | // but it requires holding on to a handshake transcript to do a 140 | // full signature, and not even OpenSSL bothers with the 141 | // complexity, so we can't even test it properly. 142 | return 0, 0, fmt.Errorf("tls: Ed25519 public keys are not supported before TLS 1.2") 143 | default: 144 | return 0, 0, fmt.Errorf("tls: unsupported public key: %T", pub) 145 | } 146 | } 147 | 148 | var rsaSignatureSchemes = []struct { 149 | scheme SignatureScheme 150 | minModulusBytes int 151 | maxVersion uint16 152 | }{ 153 | // RSA-PSS is used with PSSSaltLengthEqualsHash, and requires 154 | // emLen >= hLen + sLen + 2 155 | {PSSWithSHA256, crypto.SHA256.Size()*2 + 2, VersionTLS13}, 156 | {PSSWithSHA384, crypto.SHA384.Size()*2 + 2, VersionTLS13}, 157 | {PSSWithSHA512, crypto.SHA512.Size()*2 + 2, VersionTLS13}, 158 | // PKCS #1 v1.5 uses prefixes from hashPrefixes in crypto/rsa, and requires 159 | // emLen >= len(prefix) + hLen + 11 160 | // TLS 1.3 dropped support for PKCS #1 v1.5 in favor of RSA-PSS. 161 | {PKCS1WithSHA256, 19 + crypto.SHA256.Size() + 11, VersionTLS12}, 162 | {PKCS1WithSHA384, 19 + crypto.SHA384.Size() + 11, VersionTLS12}, 163 | {PKCS1WithSHA512, 19 + crypto.SHA512.Size() + 11, VersionTLS12}, 164 | {PKCS1WithSHA1, 15 + crypto.SHA1.Size() + 11, VersionTLS12}, 165 | } 166 | 167 | // signatureSchemesForCertificate returns the list of supported SignatureSchemes 168 | // for a given certificate, based on the public key and the protocol version, 169 | // and optionally filtered by its explicit SupportedSignatureAlgorithms. 170 | // 171 | // This function must be kept in sync with supportedSignatureAlgorithms. 172 | // FIPS filtering is applied in the caller, selectSignatureScheme. 173 | func signatureSchemesForCertificate(version uint16, cert *Certificate) []SignatureScheme { 174 | priv, ok := cert.PrivateKey.(crypto.Signer) 175 | if !ok { 176 | return nil 177 | } 178 | 179 | var sigAlgs []SignatureScheme 180 | switch pub := priv.Public().(type) { 181 | case *ecdsa.PublicKey: 182 | if version != VersionTLS13 { 183 | // In TLS 1.2 and earlier, ECDSA algorithms are not 184 | // constrained to a single curve. 185 | sigAlgs = []SignatureScheme{ 186 | ECDSAWithP256AndSHA256, 187 | ECDSAWithP384AndSHA384, 188 | ECDSAWithP521AndSHA512, 189 | ECDSAWithSHA1, 190 | } 191 | break 192 | } 193 | switch pub.Curve { 194 | case elliptic.P256(): 195 | sigAlgs = []SignatureScheme{ECDSAWithP256AndSHA256} 196 | case elliptic.P384(): 197 | sigAlgs = []SignatureScheme{ECDSAWithP384AndSHA384} 198 | case elliptic.P521(): 199 | sigAlgs = []SignatureScheme{ECDSAWithP521AndSHA512} 200 | default: 201 | return nil 202 | } 203 | case *rsa.PublicKey: 204 | size := pub.Size() 205 | sigAlgs = make([]SignatureScheme, 0, len(rsaSignatureSchemes)) 206 | for _, candidate := range rsaSignatureSchemes { 207 | if size >= candidate.minModulusBytes && version <= candidate.maxVersion { 208 | sigAlgs = append(sigAlgs, candidate.scheme) 209 | } 210 | } 211 | case ed25519.PublicKey: 212 | sigAlgs = []SignatureScheme{Ed25519} 213 | default: 214 | return nil 215 | } 216 | 217 | if cert.SupportedSignatureAlgorithms != nil { 218 | var filteredSigAlgs []SignatureScheme 219 | for _, sigAlg := range sigAlgs { 220 | if isSupportedSignatureAlgorithm(sigAlg, cert.SupportedSignatureAlgorithms) { 221 | filteredSigAlgs = append(filteredSigAlgs, sigAlg) 222 | } 223 | } 224 | return filteredSigAlgs 225 | } 226 | return sigAlgs 227 | } 228 | 229 | // selectSignatureScheme picks a SignatureScheme from the peer's preference list 230 | // that works with the selected certificate. It's only called for protocol 231 | // versions that support signature algorithms, so TLS 1.2 and 1.3. 232 | func selectSignatureScheme(vers uint16, c *Certificate, peerAlgs []SignatureScheme) (SignatureScheme, error) { 233 | supportedAlgs := signatureSchemesForCertificate(vers, c) 234 | if len(supportedAlgs) == 0 { 235 | return 0, unsupportedCertificateError(c) 236 | } 237 | if len(peerAlgs) == 0 && vers == VersionTLS12 { 238 | // For TLS 1.2, if the client didn't send signature_algorithms then we 239 | // can assume that it supports SHA1. See RFC 5246, Section 7.4.1.4.1. 240 | peerAlgs = []SignatureScheme{PKCS1WithSHA1, ECDSAWithSHA1} 241 | } 242 | // Pick signature scheme in the peer's preference order, as our 243 | // preference order is not configurable. 244 | for _, preferredAlg := range peerAlgs { 245 | if needFIPS() && !isSupportedSignatureAlgorithm(preferredAlg, fipsSupportedSignatureAlgorithms) { 246 | continue 247 | } 248 | if isSupportedSignatureAlgorithm(preferredAlg, supportedAlgs) { 249 | return preferredAlg, nil 250 | } 251 | } 252 | return 0, errors.New("tls: peer doesn't support any of the certificate's signature algorithms") 253 | } 254 | 255 | // unsupportedCertificateError returns a helpful error for certificates with 256 | // an unsupported private key. 257 | func unsupportedCertificateError(cert *Certificate) error { 258 | switch cert.PrivateKey.(type) { 259 | case rsa.PrivateKey, ecdsa.PrivateKey: 260 | return fmt.Errorf("tls: unsupported certificate: private key is %T, expected *%T", 261 | cert.PrivateKey, cert.PrivateKey) 262 | case *ed25519.PrivateKey: 263 | return fmt.Errorf("tls: unsupported certificate: private key is *ed25519.PrivateKey, expected ed25519.PrivateKey") 264 | } 265 | 266 | signer, ok := cert.PrivateKey.(crypto.Signer) 267 | if !ok { 268 | return fmt.Errorf("tls: certificate private key (%T) does not implement crypto.Signer", 269 | cert.PrivateKey) 270 | } 271 | 272 | switch pub := signer.Public().(type) { 273 | case *ecdsa.PublicKey: 274 | switch pub.Curve { 275 | case elliptic.P256(): 276 | case elliptic.P384(): 277 | case elliptic.P521(): 278 | default: 279 | return fmt.Errorf("tls: unsupported certificate curve (%s)", pub.Curve.Params().Name) 280 | } 281 | case *rsa.PublicKey: 282 | return fmt.Errorf("tls: certificate RSA key size too small for supported signature algorithms") 283 | case ed25519.PublicKey: 284 | default: 285 | return fmt.Errorf("tls: unsupported certificate key (%T)", pub) 286 | } 287 | 288 | if cert.SupportedSignatureAlgorithms != nil { 289 | return fmt.Errorf("tls: peer doesn't support the certificate custom signature algorithms") 290 | } 291 | 292 | return fmt.Errorf("tls: internal error: unsupported key (%T)", cert.PrivateKey) 293 | } 294 | -------------------------------------------------------------------------------- /key_agreement.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE-Go file. 4 | 5 | package reality 6 | 7 | import ( 8 | "crypto" 9 | "crypto/md5" 10 | "crypto/rsa" 11 | "crypto/sha1" 12 | "crypto/x509" 13 | "errors" 14 | "fmt" 15 | "io" 16 | ) 17 | 18 | // a keyAgreement implements the client and server side of a TLS key agreement 19 | // protocol by generating and processing key exchange messages. 20 | type keyAgreement interface { 21 | // On the server side, the first two methods are called in order. 22 | 23 | // In the case that the key agreement protocol doesn't use a 24 | // ServerKeyExchange message, generateServerKeyExchange can return nil, 25 | // nil. 26 | generateServerKeyExchange(*Config, *Certificate, *clientHelloMsg, *serverHelloMsg) (*serverKeyExchangeMsg, error) 27 | processClientKeyExchange(*Config, *Certificate, *clientKeyExchangeMsg, uint16) ([]byte, error) 28 | 29 | // On the client side, the next two methods are called in order. 30 | 31 | // This method may not be called if the server doesn't send a 32 | // ServerKeyExchange message. 33 | processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, *x509.Certificate, *serverKeyExchangeMsg) error 34 | generateClientKeyExchange(*Config, *clientHelloMsg, *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) 35 | } 36 | 37 | var errClientKeyExchange = errors.New("tls: invalid ClientKeyExchange message") 38 | var errServerKeyExchange = errors.New("tls: invalid ServerKeyExchange message") 39 | 40 | // rsaKeyAgreement implements the standard TLS key agreement where the client 41 | // encrypts the pre-master secret to the server's public key. 42 | type rsaKeyAgreement struct{} 43 | 44 | func (ka rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) { 45 | return nil, nil 46 | } 47 | 48 | func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) { 49 | if len(ckx.ciphertext) < 2 { 50 | return nil, errClientKeyExchange 51 | } 52 | ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1]) 53 | if ciphertextLen != len(ckx.ciphertext)-2 { 54 | return nil, errClientKeyExchange 55 | } 56 | ciphertext := ckx.ciphertext[2:] 57 | 58 | priv, ok := cert.PrivateKey.(crypto.Decrypter) 59 | if !ok { 60 | return nil, errors.New("tls: certificate private key does not implement crypto.Decrypter") 61 | } 62 | // Perform constant time RSA PKCS #1 v1.5 decryption 63 | preMasterSecret, err := priv.Decrypt(config.rand(), ciphertext, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: 48}) 64 | if err != nil { 65 | return nil, err 66 | } 67 | // We don't check the version number in the premaster secret. For one, 68 | // by checking it, we would leak information about the validity of the 69 | // encrypted pre-master secret. Secondly, it provides only a small 70 | // benefit against a downgrade attack and some implementations send the 71 | // wrong version anyway. See the discussion at the end of section 72 | // 7.4.7.1 of RFC 4346. 73 | return preMasterSecret, nil 74 | } 75 | 76 | func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error { 77 | return errors.New("tls: unexpected ServerKeyExchange") 78 | } 79 | 80 | func (ka rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) { 81 | preMasterSecret := make([]byte, 48) 82 | preMasterSecret[0] = byte(clientHello.vers >> 8) 83 | preMasterSecret[1] = byte(clientHello.vers) 84 | _, err := io.ReadFull(config.rand(), preMasterSecret[2:]) 85 | if err != nil { 86 | return nil, nil, err 87 | } 88 | 89 | rsaKey, ok := cert.PublicKey.(*rsa.PublicKey) 90 | if !ok { 91 | return nil, nil, errors.New("tls: server certificate contains incorrect key type for selected ciphersuite") 92 | } 93 | encrypted, err := rsa.EncryptPKCS1v15(config.rand(), rsaKey, preMasterSecret) 94 | if err != nil { 95 | return nil, nil, err 96 | } 97 | ckx := new(clientKeyExchangeMsg) 98 | ckx.ciphertext = make([]byte, len(encrypted)+2) 99 | ckx.ciphertext[0] = byte(len(encrypted) >> 8) 100 | ckx.ciphertext[1] = byte(len(encrypted)) 101 | copy(ckx.ciphertext[2:], encrypted) 102 | return preMasterSecret, ckx, nil 103 | } 104 | 105 | // sha1Hash calculates a SHA1 hash over the given byte slices. 106 | func sha1Hash(slices [][]byte) []byte { 107 | hsha1 := sha1.New() 108 | for _, slice := range slices { 109 | hsha1.Write(slice) 110 | } 111 | return hsha1.Sum(nil) 112 | } 113 | 114 | // md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the 115 | // concatenation of an MD5 and SHA1 hash. 116 | func md5SHA1Hash(slices [][]byte) []byte { 117 | md5sha1 := make([]byte, md5.Size+sha1.Size) 118 | hmd5 := md5.New() 119 | for _, slice := range slices { 120 | hmd5.Write(slice) 121 | } 122 | copy(md5sha1, hmd5.Sum(nil)) 123 | copy(md5sha1[md5.Size:], sha1Hash(slices)) 124 | return md5sha1 125 | } 126 | 127 | // hashForServerKeyExchange hashes the given slices and returns their digest 128 | // using the given hash function (for >= TLS 1.2) or using a default based on 129 | // the sigType (for earlier TLS versions). For Ed25519 signatures, which don't 130 | // do pre-hashing, it returns the concatenation of the slices. 131 | func hashForServerKeyExchange(sigType uint8, hashFunc crypto.Hash, version uint16, slices ...[]byte) []byte { 132 | if sigType == signatureEd25519 { 133 | var signed []byte 134 | for _, slice := range slices { 135 | signed = append(signed, slice...) 136 | } 137 | return signed 138 | } 139 | if version >= VersionTLS12 { 140 | h := hashFunc.New() 141 | for _, slice := range slices { 142 | h.Write(slice) 143 | } 144 | digest := h.Sum(nil) 145 | return digest 146 | } 147 | if sigType == signatureECDSA { 148 | return sha1Hash(slices) 149 | } 150 | return md5SHA1Hash(slices) 151 | } 152 | 153 | // ecdheKeyAgreement implements a TLS key agreement where the server 154 | // generates an ephemeral EC public/private key pair and signs it. The 155 | // pre-master secret is then calculated using ECDH. The signature may 156 | // be ECDSA, Ed25519 or RSA. 157 | type ecdheKeyAgreement struct { 158 | version uint16 159 | isRSA bool 160 | params ecdheParameters 161 | 162 | // ckx and preMasterSecret are generated in processServerKeyExchange 163 | // and returned in generateClientKeyExchange. 164 | ckx *clientKeyExchangeMsg 165 | preMasterSecret []byte 166 | } 167 | 168 | func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) { 169 | var curveID CurveID 170 | for _, c := range clientHello.supportedCurves { 171 | if config.supportsCurve(c) { 172 | curveID = c 173 | break 174 | } 175 | } 176 | 177 | if curveID == 0 { 178 | return nil, errors.New("tls: no supported elliptic curves offered") 179 | } 180 | if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok { 181 | return nil, errors.New("tls: CurvePreferences includes unsupported curve") 182 | } 183 | 184 | params, err := generateECDHEParameters(config.rand(), curveID) 185 | if err != nil { 186 | return nil, err 187 | } 188 | ka.params = params 189 | 190 | // See RFC 4492, Section 5.4. 191 | ecdhePublic := params.PublicKey() 192 | serverECDHEParams := make([]byte, 1+2+1+len(ecdhePublic)) 193 | serverECDHEParams[0] = 3 // named curve 194 | serverECDHEParams[1] = byte(curveID >> 8) 195 | serverECDHEParams[2] = byte(curveID) 196 | serverECDHEParams[3] = byte(len(ecdhePublic)) 197 | copy(serverECDHEParams[4:], ecdhePublic) 198 | 199 | priv, ok := cert.PrivateKey.(crypto.Signer) 200 | if !ok { 201 | return nil, fmt.Errorf("tls: certificate private key of type %T does not implement crypto.Signer", cert.PrivateKey) 202 | } 203 | 204 | var signatureAlgorithm SignatureScheme 205 | var sigType uint8 206 | var sigHash crypto.Hash 207 | if ka.version >= VersionTLS12 { 208 | signatureAlgorithm, err = selectSignatureScheme(ka.version, cert, clientHello.supportedSignatureAlgorithms) 209 | if err != nil { 210 | return nil, err 211 | } 212 | sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm) 213 | if err != nil { 214 | return nil, err 215 | } 216 | } else { 217 | sigType, sigHash, err = legacyTypeAndHashFromPublicKey(priv.Public()) 218 | if err != nil { 219 | return nil, err 220 | } 221 | } 222 | if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA { 223 | return nil, errors.New("tls: certificate cannot be used with the selected cipher suite") 224 | } 225 | 226 | signed := hashForServerKeyExchange(sigType, sigHash, ka.version, clientHello.random, hello.random, serverECDHEParams) 227 | 228 | signOpts := crypto.SignerOpts(sigHash) 229 | if sigType == signatureRSAPSS { 230 | signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} 231 | } 232 | sig, err := priv.Sign(config.rand(), signed, signOpts) 233 | if err != nil { 234 | return nil, errors.New("tls: failed to sign ECDHE parameters: " + err.Error()) 235 | } 236 | 237 | skx := new(serverKeyExchangeMsg) 238 | sigAndHashLen := 0 239 | if ka.version >= VersionTLS12 { 240 | sigAndHashLen = 2 241 | } 242 | skx.key = make([]byte, len(serverECDHEParams)+sigAndHashLen+2+len(sig)) 243 | copy(skx.key, serverECDHEParams) 244 | k := skx.key[len(serverECDHEParams):] 245 | if ka.version >= VersionTLS12 { 246 | k[0] = byte(signatureAlgorithm >> 8) 247 | k[1] = byte(signatureAlgorithm) 248 | k = k[2:] 249 | } 250 | k[0] = byte(len(sig) >> 8) 251 | k[1] = byte(len(sig)) 252 | copy(k[2:], sig) 253 | 254 | return skx, nil 255 | } 256 | 257 | func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) { 258 | if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 { 259 | return nil, errClientKeyExchange 260 | } 261 | 262 | preMasterSecret := ka.params.SharedKey(ckx.ciphertext[1:]) 263 | if preMasterSecret == nil { 264 | return nil, errClientKeyExchange 265 | } 266 | 267 | return preMasterSecret, nil 268 | } 269 | 270 | func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error { 271 | if len(skx.key) < 4 { 272 | return errServerKeyExchange 273 | } 274 | if skx.key[0] != 3 { // named curve 275 | return errors.New("tls: server selected unsupported curve") 276 | } 277 | curveID := CurveID(skx.key[1])<<8 | CurveID(skx.key[2]) 278 | 279 | publicLen := int(skx.key[3]) 280 | if publicLen+4 > len(skx.key) { 281 | return errServerKeyExchange 282 | } 283 | serverECDHEParams := skx.key[:4+publicLen] 284 | publicKey := serverECDHEParams[4:] 285 | 286 | sig := skx.key[4+publicLen:] 287 | if len(sig) < 2 { 288 | return errServerKeyExchange 289 | } 290 | 291 | if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok { 292 | return errors.New("tls: server selected unsupported curve") 293 | } 294 | 295 | params, err := generateECDHEParameters(config.rand(), curveID) 296 | if err != nil { 297 | return err 298 | } 299 | ka.params = params 300 | 301 | ka.preMasterSecret = params.SharedKey(publicKey) 302 | if ka.preMasterSecret == nil { 303 | return errServerKeyExchange 304 | } 305 | 306 | ourPublicKey := params.PublicKey() 307 | ka.ckx = new(clientKeyExchangeMsg) 308 | ka.ckx.ciphertext = make([]byte, 1+len(ourPublicKey)) 309 | ka.ckx.ciphertext[0] = byte(len(ourPublicKey)) 310 | copy(ka.ckx.ciphertext[1:], ourPublicKey) 311 | 312 | var sigType uint8 313 | var sigHash crypto.Hash 314 | if ka.version >= VersionTLS12 { 315 | signatureAlgorithm := SignatureScheme(sig[0])<<8 | SignatureScheme(sig[1]) 316 | sig = sig[2:] 317 | if len(sig) < 2 { 318 | return errServerKeyExchange 319 | } 320 | 321 | if !isSupportedSignatureAlgorithm(signatureAlgorithm, clientHello.supportedSignatureAlgorithms) { 322 | return errors.New("tls: certificate used with invalid signature algorithm") 323 | } 324 | sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm) 325 | if err != nil { 326 | return err 327 | } 328 | } else { 329 | sigType, sigHash, err = legacyTypeAndHashFromPublicKey(cert.PublicKey) 330 | if err != nil { 331 | return err 332 | } 333 | } 334 | if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA { 335 | return errServerKeyExchange 336 | } 337 | 338 | sigLen := int(sig[0])<<8 | int(sig[1]) 339 | if sigLen+2 != len(sig) { 340 | return errServerKeyExchange 341 | } 342 | sig = sig[2:] 343 | 344 | signed := hashForServerKeyExchange(sigType, sigHash, ka.version, clientHello.random, serverHello.random, serverECDHEParams) 345 | if err := verifyHandshakeSignature(sigType, cert.PublicKey, sigHash, signed, sig); err != nil { 346 | return errors.New("tls: invalid signature by the server certificate: " + err.Error()) 347 | } 348 | return nil 349 | } 350 | 351 | func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) { 352 | if ka.ckx == nil { 353 | return nil, nil, errors.New("tls: missing ServerKeyExchange message") 354 | } 355 | 356 | return ka.preMasterSecret, ka.ckx, nil 357 | } 358 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2023 RPRX. All rights reserved. 2 | 3 | Mozilla Public License Version 2.0 4 | ================================== 5 | 6 | 1. Definitions 7 | -------------- 8 | 9 | 1.1. "Contributor" 10 | means each individual or legal entity that creates, contributes to 11 | the creation of, or owns Covered Software. 12 | 13 | 1.2. "Contributor Version" 14 | means the combination of the Contributions of others (if any) used 15 | by a Contributor and that particular Contributor's Contribution. 16 | 17 | 1.3. "Contribution" 18 | means Covered Software of a particular Contributor. 19 | 20 | 1.4. "Covered Software" 21 | means Source Code Form to which the initial Contributor has attached 22 | the notice in Exhibit A, the Executable Form of such Source Code 23 | Form, and Modifications of such Source Code Form, in each case 24 | including portions thereof. 25 | 26 | 1.5. "Incompatible With Secondary Licenses" 27 | means 28 | 29 | (a) that the initial Contributor has attached the notice described 30 | in Exhibit B to the Covered Software; or 31 | 32 | (b) that the Covered Software was made available under the terms of 33 | version 1.1 or earlier of the License, but not also under the 34 | terms of a Secondary License. 35 | 36 | 1.6. "Executable Form" 37 | means any form of the work other than Source Code Form. 38 | 39 | 1.7. "Larger Work" 40 | means a work that combines Covered Software with other material, in 41 | a separate file or files, that is not Covered Software. 42 | 43 | 1.8. "License" 44 | means this document. 45 | 46 | 1.9. "Licensable" 47 | means having the right to grant, to the maximum extent possible, 48 | whether at the time of the initial grant or subsequently, any and 49 | all of the rights conveyed by this License. 50 | 51 | 1.10. "Modifications" 52 | means any of the following: 53 | 54 | (a) any file in Source Code Form that results from an addition to, 55 | deletion from, or modification of the contents of Covered 56 | Software; or 57 | 58 | (b) any new file in Source Code Form that contains any Covered 59 | Software. 60 | 61 | 1.11. "Patent Claims" of a Contributor 62 | means any patent claim(s), including without limitation, method, 63 | process, and apparatus claims, in any patent Licensable by such 64 | Contributor that would be infringed, but for the grant of the 65 | License, by the making, using, selling, offering for sale, having 66 | made, import, or transfer of either its Contributions or its 67 | Contributor Version. 68 | 69 | 1.12. "Secondary License" 70 | means either the GNU General Public License, Version 2.0, the GNU 71 | Lesser General Public License, Version 2.1, the GNU Affero General 72 | Public License, Version 3.0, or any later versions of those 73 | licenses. 74 | 75 | 1.13. "Source Code Form" 76 | means the form of the work preferred for making modifications. 77 | 78 | 1.14. "You" (or "Your") 79 | means an individual or a legal entity exercising rights under this 80 | License. For legal entities, "You" includes any entity that 81 | controls, is controlled by, or is under common control with You. For 82 | purposes of this definition, "control" means (a) the power, direct 83 | or indirect, to cause the direction or management of such entity, 84 | whether by contract or otherwise, or (b) ownership of more than 85 | fifty percent (50%) of the outstanding shares or beneficial 86 | ownership of such entity. 87 | 88 | 2. License Grants and Conditions 89 | -------------------------------- 90 | 91 | 2.1. Grants 92 | 93 | Each Contributor hereby grants You a world-wide, royalty-free, 94 | non-exclusive license: 95 | 96 | (a) under intellectual property rights (other than patent or trademark) 97 | Licensable by such Contributor to use, reproduce, make available, 98 | modify, display, perform, distribute, and otherwise exploit its 99 | Contributions, either on an unmodified basis, with Modifications, or 100 | as part of a Larger Work; and 101 | 102 | (b) under Patent Claims of such Contributor to make, use, sell, offer 103 | for sale, have made, import, and otherwise transfer either its 104 | Contributions or its Contributor Version. 105 | 106 | 2.2. Effective Date 107 | 108 | The licenses granted in Section 2.1 with respect to any Contribution 109 | become effective for each Contribution on the date the Contributor first 110 | distributes such Contribution. 111 | 112 | 2.3. Limitations on Grant Scope 113 | 114 | The licenses granted in this Section 2 are the only rights granted under 115 | this License. No additional rights or licenses will be implied from the 116 | distribution or licensing of Covered Software under this License. 117 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 118 | Contributor: 119 | 120 | (a) for any code that a Contributor has removed from Covered Software; 121 | or 122 | 123 | (b) for infringements caused by: (i) Your and any other third party's 124 | modifications of Covered Software, or (ii) the combination of its 125 | Contributions with other software (except as part of its Contributor 126 | Version); or 127 | 128 | (c) under Patent Claims infringed by Covered Software in the absence of 129 | its Contributions. 130 | 131 | This License does not grant any rights in the trademarks, service marks, 132 | or logos of any Contributor (except as may be necessary to comply with 133 | the notice requirements in Section 3.4). 134 | 135 | 2.4. Subsequent Licenses 136 | 137 | No Contributor makes additional grants as a result of Your choice to 138 | distribute the Covered Software under a subsequent version of this 139 | License (see Section 10.2) or under the terms of a Secondary License (if 140 | permitted under the terms of Section 3.3). 141 | 142 | 2.5. Representation 143 | 144 | Each Contributor represents that the Contributor believes its 145 | Contributions are its original creation(s) or it has sufficient rights 146 | to grant the rights to its Contributions conveyed by this License. 147 | 148 | 2.6. Fair Use 149 | 150 | This License is not intended to limit any rights You have under 151 | applicable copyright doctrines of fair use, fair dealing, or other 152 | equivalents. 153 | 154 | 2.7. Conditions 155 | 156 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 157 | in Section 2.1. 158 | 159 | 3. Responsibilities 160 | ------------------- 161 | 162 | 3.1. Distribution of Source Form 163 | 164 | All distribution of Covered Software in Source Code Form, including any 165 | Modifications that You create or to which You contribute, must be under 166 | the terms of this License. You must inform recipients that the Source 167 | Code Form of the Covered Software is governed by the terms of this 168 | License, and how they can obtain a copy of this License. You may not 169 | attempt to alter or restrict the recipients' rights in the Source Code 170 | Form. 171 | 172 | 3.2. Distribution of Executable Form 173 | 174 | If You distribute Covered Software in Executable Form then: 175 | 176 | (a) such Covered Software must also be made available in Source Code 177 | Form, as described in Section 3.1, and You must inform recipients of 178 | the Executable Form how they can obtain a copy of such Source Code 179 | Form by reasonable means in a timely manner, at a charge no more 180 | than the cost of distribution to the recipient; and 181 | 182 | (b) You may distribute such Executable Form under the terms of this 183 | License, or sublicense it under different terms, provided that the 184 | license for the Executable Form does not attempt to limit or alter 185 | the recipients' rights in the Source Code Form under this License. 186 | 187 | 3.3. Distribution of a Larger Work 188 | 189 | You may create and distribute a Larger Work under terms of Your choice, 190 | provided that You also comply with the requirements of this License for 191 | the Covered Software. If the Larger Work is a combination of Covered 192 | Software with a work governed by one or more Secondary Licenses, and the 193 | Covered Software is not Incompatible With Secondary Licenses, this 194 | License permits You to additionally distribute such Covered Software 195 | under the terms of such Secondary License(s), so that the recipient of 196 | the Larger Work may, at their option, further distribute the Covered 197 | Software under the terms of either this License or such Secondary 198 | License(s). 199 | 200 | 3.4. Notices 201 | 202 | You may not remove or alter the substance of any license notices 203 | (including copyright notices, patent notices, disclaimers of warranty, 204 | or limitations of liability) contained within the Source Code Form of 205 | the Covered Software, except that You may alter any license notices to 206 | the extent required to remedy known factual inaccuracies. 207 | 208 | 3.5. Application of Additional Terms 209 | 210 | You may choose to offer, and to charge a fee for, warranty, support, 211 | indemnity or liability obligations to one or more recipients of Covered 212 | Software. However, You may do so only on Your own behalf, and not on 213 | behalf of any Contributor. You must make it absolutely clear that any 214 | such warranty, support, indemnity, or liability obligation is offered by 215 | You alone, and You hereby agree to indemnify every Contributor for any 216 | liability incurred by such Contributor as a result of warranty, support, 217 | indemnity or liability terms You offer. You may include additional 218 | disclaimers of warranty and limitations of liability specific to any 219 | jurisdiction. 220 | 221 | 4. Inability to Comply Due to Statute or Regulation 222 | --------------------------------------------------- 223 | 224 | If it is impossible for You to comply with any of the terms of this 225 | License with respect to some or all of the Covered Software due to 226 | statute, judicial order, or regulation then You must: (a) comply with 227 | the terms of this License to the maximum extent possible; and (b) 228 | describe the limitations and the code they affect. Such description must 229 | be placed in a text file included with all distributions of the Covered 230 | Software under this License. Except to the extent prohibited by statute 231 | or regulation, such description must be sufficiently detailed for a 232 | recipient of ordinary skill to be able to understand it. 233 | 234 | 5. Termination 235 | -------------- 236 | 237 | 5.1. The rights granted under this License will terminate automatically 238 | if You fail to comply with any of its terms. However, if You become 239 | compliant, then the rights granted under this License from a particular 240 | Contributor are reinstated (a) provisionally, unless and until such 241 | Contributor explicitly and finally terminates Your grants, and (b) on an 242 | ongoing basis, if such Contributor fails to notify You of the 243 | non-compliance by some reasonable means prior to 60 days after You have 244 | come back into compliance. Moreover, Your grants from a particular 245 | Contributor are reinstated on an ongoing basis if such Contributor 246 | notifies You of the non-compliance by some reasonable means, this is the 247 | first time You have received notice of non-compliance with this License 248 | from such Contributor, and You become compliant prior to 30 days after 249 | Your receipt of the notice. 250 | 251 | 5.2. If You initiate litigation against any entity by asserting a patent 252 | infringement claim (excluding declaratory judgment actions, 253 | counter-claims, and cross-claims) alleging that a Contributor Version 254 | directly or indirectly infringes any patent, then the rights granted to 255 | You by any and all Contributors for the Covered Software under Section 256 | 2.1 of this License shall terminate. 257 | 258 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 259 | end user license agreements (excluding distributors and resellers) which 260 | have been validly granted by You or Your distributors under this License 261 | prior to termination shall survive termination. 262 | 263 | ************************************************************************ 264 | * * 265 | * 6. Disclaimer of Warranty * 266 | * ------------------------- * 267 | * * 268 | * Covered Software is provided under this License on an "as is" * 269 | * basis, without warranty of any kind, either expressed, implied, or * 270 | * statutory, including, without limitation, warranties that the * 271 | * Covered Software is free of defects, merchantable, fit for a * 272 | * particular purpose or non-infringing. The entire risk as to the * 273 | * quality and performance of the Covered Software is with You. * 274 | * Should any Covered Software prove defective in any respect, You * 275 | * (not any Contributor) assume the cost of any necessary servicing, * 276 | * repair, or correction. This disclaimer of warranty constitutes an * 277 | * essential part of this License. No use of any Covered Software is * 278 | * authorized under this License except under this disclaimer. * 279 | * * 280 | ************************************************************************ 281 | 282 | ************************************************************************ 283 | * * 284 | * 7. Limitation of Liability * 285 | * -------------------------- * 286 | * * 287 | * Under no circumstances and under no legal theory, whether tort * 288 | * (including negligence), contract, or otherwise, shall any * 289 | * Contributor, or anyone who distributes Covered Software as * 290 | * permitted above, be liable to You for any direct, indirect, * 291 | * special, incidental, or consequential damages of any character * 292 | * including, without limitation, damages for lost profits, loss of * 293 | * goodwill, work stoppage, computer failure or malfunction, or any * 294 | * and all other commercial damages or losses, even if such party * 295 | * shall have been informed of the possibility of such damages. This * 296 | * limitation of liability shall not apply to liability for death or * 297 | * personal injury resulting from such party's negligence to the * 298 | * extent applicable law prohibits such limitation. Some * 299 | * jurisdictions do not allow the exclusion or limitation of * 300 | * incidental or consequential damages, so this exclusion and * 301 | * limitation may not apply to You. * 302 | * * 303 | ************************************************************************ 304 | 305 | 8. Litigation 306 | ------------- 307 | 308 | Any litigation relating to this License may be brought only in the 309 | courts of a jurisdiction where the defendant maintains its principal 310 | place of business and such litigation shall be governed by laws of that 311 | jurisdiction, without reference to its conflict-of-law provisions. 312 | Nothing in this Section shall prevent a party's ability to bring 313 | cross-claims or counter-claims. 314 | 315 | 9. Miscellaneous 316 | ---------------- 317 | 318 | This License represents the complete agreement concerning the subject 319 | matter hereof. If any provision of this License is held to be 320 | unenforceable, such provision shall be reformed only to the extent 321 | necessary to make it enforceable. Any law or regulation which provides 322 | that the language of a contract shall be construed against the drafter 323 | shall not be used to construe this License against a Contributor. 324 | 325 | 10. Versions of the License 326 | --------------------------- 327 | 328 | 10.1. New Versions 329 | 330 | Mozilla Foundation is the license steward. Except as provided in Section 331 | 10.3, no one other than the license steward has the right to modify or 332 | publish new versions of this License. Each version will be given a 333 | distinguishing version number. 334 | 335 | 10.2. Effect of New Versions 336 | 337 | You may distribute the Covered Software under the terms of the version 338 | of the License under which You originally received the Covered Software, 339 | or under the terms of any subsequent version published by the license 340 | steward. 341 | 342 | 10.3. Modified Versions 343 | 344 | If you create software not governed by this License, and you want to 345 | create a new license for such software, you may create and use a 346 | modified version of this License if you rename the license and remove 347 | any references to the name of the license steward (except to note that 348 | such modified license differs from this License). 349 | 350 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 351 | Licenses 352 | 353 | If You choose to distribute Source Code Form that is Incompatible With 354 | Secondary Licenses under the terms of this version of the License, the 355 | notice described in Exhibit B of this License must be attached. 356 | 357 | Exhibit A - Source Code Form License Notice 358 | ------------------------------------------- 359 | 360 | This Source Code Form is subject to the terms of the Mozilla Public 361 | License, v. 2.0. If a copy of the MPL was not distributed with this 362 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 363 | 364 | If it is not possible or desirable to put the notice in a particular 365 | file, then You may include the notice in a location (such as a LICENSE 366 | file in a relevant directory) where a recipient would be likely to look 367 | for such a notice. 368 | 369 | You may add additional accurate notices of copyright ownership. 370 | 371 | Exhibit B - "Incompatible With Secondary Licenses" Notice 372 | --------------------------------------------------------- 373 | 374 | This Source Code Form is "Incompatible With Secondary Licenses", as 375 | defined by the Mozilla Public License, v. 2.0. 376 | -------------------------------------------------------------------------------- /handshake_client_tls13.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE-Go file. 4 | 5 | package reality 6 | 7 | import ( 8 | "bytes" 9 | "context" 10 | "crypto" 11 | "crypto/hmac" 12 | "crypto/rsa" 13 | "errors" 14 | "hash" 15 | "sync/atomic" 16 | "time" 17 | ) 18 | 19 | type clientHandshakeStateTLS13 struct { 20 | c *Conn 21 | ctx context.Context 22 | serverHello *serverHelloMsg 23 | hello *clientHelloMsg 24 | ecdheParams ecdheParameters 25 | 26 | session *ClientSessionState 27 | earlySecret []byte 28 | binderKey []byte 29 | 30 | certReq *certificateRequestMsgTLS13 31 | usingPSK bool 32 | sentDummyCCS bool 33 | suite *cipherSuiteTLS13 34 | transcript hash.Hash 35 | masterSecret []byte 36 | trafficSecret []byte // client_application_traffic_secret_0 37 | } 38 | 39 | // handshake requires hs.c, hs.hello, hs.serverHello, hs.ecdheParams, and, 40 | // optionally, hs.session, hs.earlySecret and hs.binderKey to be set. 41 | func (hs *clientHandshakeStateTLS13) handshake() error { 42 | c := hs.c 43 | 44 | if needFIPS() { 45 | return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode") 46 | } 47 | 48 | // The server must not select TLS 1.3 in a renegotiation. See RFC 8446, 49 | // sections 4.1.2 and 4.1.3. 50 | if c.handshakes > 0 { 51 | c.sendAlert(alertProtocolVersion) 52 | return errors.New("tls: server selected TLS 1.3 in a renegotiation") 53 | } 54 | 55 | // Consistency check on the presence of a keyShare and its parameters. 56 | if hs.ecdheParams == nil || len(hs.hello.keyShares) != 1 { 57 | return c.sendAlert(alertInternalError) 58 | } 59 | 60 | if err := hs.checkServerHelloOrHRR(); err != nil { 61 | return err 62 | } 63 | 64 | hs.transcript = hs.suite.hash.New() 65 | hs.transcript.Write(hs.hello.marshal()) 66 | 67 | if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) { 68 | if err := hs.sendDummyChangeCipherSpec(); err != nil { 69 | return err 70 | } 71 | if err := hs.processHelloRetryRequest(); err != nil { 72 | return err 73 | } 74 | } 75 | 76 | hs.transcript.Write(hs.serverHello.marshal()) 77 | 78 | c.buffering = true 79 | if err := hs.processServerHello(); err != nil { 80 | return err 81 | } 82 | if err := hs.sendDummyChangeCipherSpec(); err != nil { 83 | return err 84 | } 85 | if err := hs.establishHandshakeKeys(); err != nil { 86 | return err 87 | } 88 | if err := hs.readServerParameters(); err != nil { 89 | return err 90 | } 91 | if err := hs.readServerCertificate(); err != nil { 92 | return err 93 | } 94 | if err := hs.readServerFinished(); err != nil { 95 | return err 96 | } 97 | if err := hs.sendClientCertificate(); err != nil { 98 | return err 99 | } 100 | if err := hs.sendClientFinished(); err != nil { 101 | return err 102 | } 103 | if _, err := c.flush(); err != nil { 104 | return err 105 | } 106 | 107 | atomic.StoreUint32(&c.handshakeStatus, 1) 108 | 109 | return nil 110 | } 111 | 112 | // checkServerHelloOrHRR does validity checks that apply to both ServerHello and 113 | // HelloRetryRequest messages. It sets hs.suite. 114 | func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error { 115 | c := hs.c 116 | 117 | if hs.serverHello.supportedVersion == 0 { 118 | c.sendAlert(alertMissingExtension) 119 | return errors.New("tls: server selected TLS 1.3 using the legacy version field") 120 | } 121 | 122 | if hs.serverHello.supportedVersion != VersionTLS13 { 123 | c.sendAlert(alertIllegalParameter) 124 | return errors.New("tls: server selected an invalid version after a HelloRetryRequest") 125 | } 126 | 127 | if hs.serverHello.vers != VersionTLS12 { 128 | c.sendAlert(alertIllegalParameter) 129 | return errors.New("tls: server sent an incorrect legacy version") 130 | } 131 | 132 | if hs.serverHello.ocspStapling || 133 | hs.serverHello.ticketSupported || 134 | hs.serverHello.secureRenegotiationSupported || 135 | len(hs.serverHello.secureRenegotiation) != 0 || 136 | len(hs.serverHello.alpnProtocol) != 0 || 137 | len(hs.serverHello.scts) != 0 { 138 | c.sendAlert(alertUnsupportedExtension) 139 | return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3") 140 | } 141 | 142 | if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) { 143 | c.sendAlert(alertIllegalParameter) 144 | return errors.New("tls: server did not echo the legacy session ID") 145 | } 146 | 147 | if hs.serverHello.compressionMethod != compressionNone { 148 | c.sendAlert(alertIllegalParameter) 149 | return errors.New("tls: server selected unsupported compression format") 150 | } 151 | 152 | selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite) 153 | if hs.suite != nil && selectedSuite != hs.suite { 154 | c.sendAlert(alertIllegalParameter) 155 | return errors.New("tls: server changed cipher suite after a HelloRetryRequest") 156 | } 157 | if selectedSuite == nil { 158 | c.sendAlert(alertIllegalParameter) 159 | return errors.New("tls: server chose an unconfigured cipher suite") 160 | } 161 | hs.suite = selectedSuite 162 | c.cipherSuite = hs.suite.id 163 | 164 | return nil 165 | } 166 | 167 | // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility 168 | // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. 169 | func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error { 170 | if hs.sentDummyCCS { 171 | return nil 172 | } 173 | hs.sentDummyCCS = true 174 | 175 | _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) 176 | return err 177 | } 178 | 179 | // processHelloRetryRequest handles the HRR in hs.serverHello, modifies and 180 | // resends hs.hello, and reads the new ServerHello into hs.serverHello. 181 | func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error { 182 | c := hs.c 183 | 184 | // The first ClientHello gets double-hashed into the transcript upon a 185 | // HelloRetryRequest. (The idea is that the server might offload transcript 186 | // storage to the client in the cookie.) See RFC 8446, Section 4.4.1. 187 | chHash := hs.transcript.Sum(nil) 188 | hs.transcript.Reset() 189 | hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 190 | hs.transcript.Write(chHash) 191 | hs.transcript.Write(hs.serverHello.marshal()) 192 | 193 | // The only HelloRetryRequest extensions we support are key_share and 194 | // cookie, and clients must abort the handshake if the HRR would not result 195 | // in any change in the ClientHello. 196 | if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil { 197 | c.sendAlert(alertIllegalParameter) 198 | return errors.New("tls: server sent an unnecessary HelloRetryRequest message") 199 | } 200 | 201 | if hs.serverHello.cookie != nil { 202 | hs.hello.cookie = hs.serverHello.cookie 203 | } 204 | 205 | if hs.serverHello.serverShare.group != 0 { 206 | c.sendAlert(alertDecodeError) 207 | return errors.New("tls: received malformed key_share extension") 208 | } 209 | 210 | // If the server sent a key_share extension selecting a group, ensure it's 211 | // a group we advertised but did not send a key share for, and send a key 212 | // share for it this time. 213 | if curveID := hs.serverHello.selectedGroup; curveID != 0 { 214 | curveOK := false 215 | for _, id := range hs.hello.supportedCurves { 216 | if id == curveID { 217 | curveOK = true 218 | break 219 | } 220 | } 221 | if !curveOK { 222 | c.sendAlert(alertIllegalParameter) 223 | return errors.New("tls: server selected unsupported group") 224 | } 225 | if hs.ecdheParams.CurveID() == curveID { 226 | c.sendAlert(alertIllegalParameter) 227 | return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share") 228 | } 229 | if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok { 230 | c.sendAlert(alertInternalError) 231 | return errors.New("tls: CurvePreferences includes unsupported curve") 232 | } 233 | params, err := generateECDHEParameters(c.config.rand(), curveID) 234 | if err != nil { 235 | c.sendAlert(alertInternalError) 236 | return err 237 | } 238 | hs.ecdheParams = params 239 | hs.hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}} 240 | } 241 | 242 | hs.hello.raw = nil 243 | if len(hs.hello.pskIdentities) > 0 { 244 | pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite) 245 | if pskSuite == nil { 246 | return c.sendAlert(alertInternalError) 247 | } 248 | if pskSuite.hash == hs.suite.hash { 249 | // Update binders and obfuscated_ticket_age. 250 | ticketAge := uint32(c.config.time().Sub(hs.session.receivedAt) / time.Millisecond) 251 | hs.hello.pskIdentities[0].obfuscatedTicketAge = ticketAge + hs.session.ageAdd 252 | 253 | transcript := hs.suite.hash.New() 254 | transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 255 | transcript.Write(chHash) 256 | transcript.Write(hs.serverHello.marshal()) 257 | transcript.Write(hs.hello.marshalWithoutBinders()) 258 | pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)} 259 | hs.hello.updateBinders(pskBinders) 260 | } else { 261 | // Server selected a cipher suite incompatible with the PSK. 262 | hs.hello.pskIdentities = nil 263 | hs.hello.pskBinders = nil 264 | } 265 | } 266 | 267 | hs.transcript.Write(hs.hello.marshal()) 268 | if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { 269 | return err 270 | } 271 | 272 | msg, err := c.readHandshake() 273 | if err != nil { 274 | return err 275 | } 276 | 277 | serverHello, ok := msg.(*serverHelloMsg) 278 | if !ok { 279 | c.sendAlert(alertUnexpectedMessage) 280 | return unexpectedMessageError(serverHello, msg) 281 | } 282 | hs.serverHello = serverHello 283 | 284 | if err := hs.checkServerHelloOrHRR(); err != nil { 285 | return err 286 | } 287 | 288 | return nil 289 | } 290 | 291 | func (hs *clientHandshakeStateTLS13) processServerHello() error { 292 | c := hs.c 293 | 294 | if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) { 295 | c.sendAlert(alertUnexpectedMessage) 296 | return errors.New("tls: server sent two HelloRetryRequest messages") 297 | } 298 | 299 | if len(hs.serverHello.cookie) != 0 { 300 | c.sendAlert(alertUnsupportedExtension) 301 | return errors.New("tls: server sent a cookie in a normal ServerHello") 302 | } 303 | 304 | if hs.serverHello.selectedGroup != 0 { 305 | c.sendAlert(alertDecodeError) 306 | return errors.New("tls: malformed key_share extension") 307 | } 308 | 309 | if hs.serverHello.serverShare.group == 0 { 310 | c.sendAlert(alertIllegalParameter) 311 | return errors.New("tls: server did not send a key share") 312 | } 313 | if hs.serverHello.serverShare.group != hs.ecdheParams.CurveID() { 314 | c.sendAlert(alertIllegalParameter) 315 | return errors.New("tls: server selected unsupported group") 316 | } 317 | 318 | if !hs.serverHello.selectedIdentityPresent { 319 | return nil 320 | } 321 | 322 | if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) { 323 | c.sendAlert(alertIllegalParameter) 324 | return errors.New("tls: server selected an invalid PSK") 325 | } 326 | 327 | if len(hs.hello.pskIdentities) != 1 || hs.session == nil { 328 | return c.sendAlert(alertInternalError) 329 | } 330 | pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite) 331 | if pskSuite == nil { 332 | return c.sendAlert(alertInternalError) 333 | } 334 | if pskSuite.hash != hs.suite.hash { 335 | c.sendAlert(alertIllegalParameter) 336 | return errors.New("tls: server selected an invalid PSK and cipher suite pair") 337 | } 338 | 339 | hs.usingPSK = true 340 | c.didResume = true 341 | c.peerCertificates = hs.session.serverCertificates 342 | c.verifiedChains = hs.session.verifiedChains 343 | c.ocspResponse = hs.session.ocspResponse 344 | c.scts = hs.session.scts 345 | return nil 346 | } 347 | 348 | func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error { 349 | c := hs.c 350 | 351 | sharedKey := hs.ecdheParams.SharedKey(hs.serverHello.serverShare.data) 352 | if sharedKey == nil { 353 | c.sendAlert(alertIllegalParameter) 354 | return errors.New("tls: invalid server key share") 355 | } 356 | 357 | earlySecret := hs.earlySecret 358 | if !hs.usingPSK { 359 | earlySecret = hs.suite.extract(nil, nil) 360 | } 361 | handshakeSecret := hs.suite.extract(sharedKey, 362 | hs.suite.deriveSecret(earlySecret, "derived", nil)) 363 | 364 | clientSecret := hs.suite.deriveSecret(handshakeSecret, 365 | clientHandshakeTrafficLabel, hs.transcript) 366 | c.out.setTrafficSecret(hs.suite, clientSecret) 367 | serverSecret := hs.suite.deriveSecret(handshakeSecret, 368 | serverHandshakeTrafficLabel, hs.transcript) 369 | c.in.setTrafficSecret(hs.suite, serverSecret) 370 | 371 | err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret) 372 | if err != nil { 373 | c.sendAlert(alertInternalError) 374 | return err 375 | } 376 | err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret) 377 | if err != nil { 378 | c.sendAlert(alertInternalError) 379 | return err 380 | } 381 | 382 | hs.masterSecret = hs.suite.extract(nil, 383 | hs.suite.deriveSecret(handshakeSecret, "derived", nil)) 384 | 385 | return nil 386 | } 387 | 388 | func (hs *clientHandshakeStateTLS13) readServerParameters() error { 389 | c := hs.c 390 | 391 | msg, err := c.readHandshake() 392 | if err != nil { 393 | return err 394 | } 395 | 396 | encryptedExtensions, ok := msg.(*encryptedExtensionsMsg) 397 | if !ok { 398 | c.sendAlert(alertUnexpectedMessage) 399 | return unexpectedMessageError(encryptedExtensions, msg) 400 | } 401 | hs.transcript.Write(encryptedExtensions.marshal()) 402 | 403 | if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol); err != nil { 404 | c.sendAlert(alertUnsupportedExtension) 405 | return err 406 | } 407 | c.clientProtocol = encryptedExtensions.alpnProtocol 408 | 409 | return nil 410 | } 411 | 412 | func (hs *clientHandshakeStateTLS13) readServerCertificate() error { 413 | c := hs.c 414 | 415 | // Either a PSK or a certificate is always used, but not both. 416 | // See RFC 8446, Section 4.1.1. 417 | if hs.usingPSK { 418 | // Make sure the connection is still being verified whether or not this 419 | // is a resumption. Resumptions currently don't reverify certificates so 420 | // they don't call verifyServerCertificate. See Issue 31641. 421 | if c.config.VerifyConnection != nil { 422 | if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 423 | c.sendAlert(alertBadCertificate) 424 | return err 425 | } 426 | } 427 | return nil 428 | } 429 | 430 | msg, err := c.readHandshake() 431 | if err != nil { 432 | return err 433 | } 434 | 435 | certReq, ok := msg.(*certificateRequestMsgTLS13) 436 | if ok { 437 | hs.transcript.Write(certReq.marshal()) 438 | 439 | hs.certReq = certReq 440 | 441 | msg, err = c.readHandshake() 442 | if err != nil { 443 | return err 444 | } 445 | } 446 | 447 | certMsg, ok := msg.(*certificateMsgTLS13) 448 | if !ok { 449 | c.sendAlert(alertUnexpectedMessage) 450 | return unexpectedMessageError(certMsg, msg) 451 | } 452 | if len(certMsg.certificate.Certificate) == 0 { 453 | c.sendAlert(alertDecodeError) 454 | return errors.New("tls: received empty certificates message") 455 | } 456 | hs.transcript.Write(certMsg.marshal()) 457 | 458 | c.scts = certMsg.certificate.SignedCertificateTimestamps 459 | c.ocspResponse = certMsg.certificate.OCSPStaple 460 | 461 | if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil { 462 | return err 463 | } 464 | 465 | msg, err = c.readHandshake() 466 | if err != nil { 467 | return err 468 | } 469 | 470 | certVerify, ok := msg.(*certificateVerifyMsg) 471 | if !ok { 472 | c.sendAlert(alertUnexpectedMessage) 473 | return unexpectedMessageError(certVerify, msg) 474 | } 475 | 476 | // See RFC 8446, Section 4.4.3. 477 | if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) { 478 | c.sendAlert(alertIllegalParameter) 479 | return errors.New("tls: certificate used with invalid signature algorithm") 480 | } 481 | sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) 482 | if err != nil { 483 | return c.sendAlert(alertInternalError) 484 | } 485 | if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 { 486 | c.sendAlert(alertIllegalParameter) 487 | return errors.New("tls: certificate used with invalid signature algorithm") 488 | } 489 | signed := signedMessage(sigHash, serverSignatureContext, hs.transcript) 490 | if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey, 491 | sigHash, signed, certVerify.signature); err != nil { 492 | c.sendAlert(alertDecryptError) 493 | return errors.New("tls: invalid signature by the server certificate: " + err.Error()) 494 | } 495 | 496 | hs.transcript.Write(certVerify.marshal()) 497 | 498 | return nil 499 | } 500 | 501 | func (hs *clientHandshakeStateTLS13) readServerFinished() error { 502 | c := hs.c 503 | 504 | msg, err := c.readHandshake() 505 | if err != nil { 506 | return err 507 | } 508 | 509 | finished, ok := msg.(*finishedMsg) 510 | if !ok { 511 | c.sendAlert(alertUnexpectedMessage) 512 | return unexpectedMessageError(finished, msg) 513 | } 514 | 515 | expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript) 516 | if !hmac.Equal(expectedMAC, finished.verifyData) { 517 | c.sendAlert(alertDecryptError) 518 | return errors.New("tls: invalid server finished hash") 519 | } 520 | 521 | hs.transcript.Write(finished.marshal()) 522 | 523 | // Derive secrets that take context through the server Finished. 524 | 525 | hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret, 526 | clientApplicationTrafficLabel, hs.transcript) 527 | serverSecret := hs.suite.deriveSecret(hs.masterSecret, 528 | serverApplicationTrafficLabel, hs.transcript) 529 | c.in.setTrafficSecret(hs.suite, serverSecret) 530 | 531 | err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret) 532 | if err != nil { 533 | c.sendAlert(alertInternalError) 534 | return err 535 | } 536 | err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret) 537 | if err != nil { 538 | c.sendAlert(alertInternalError) 539 | return err 540 | } 541 | 542 | c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript) 543 | 544 | return nil 545 | } 546 | 547 | func (hs *clientHandshakeStateTLS13) sendClientCertificate() error { 548 | c := hs.c 549 | 550 | if hs.certReq == nil { 551 | return nil 552 | } 553 | 554 | cert, err := c.getClientCertificate(&CertificateRequestInfo{ 555 | AcceptableCAs: hs.certReq.certificateAuthorities, 556 | SignatureSchemes: hs.certReq.supportedSignatureAlgorithms, 557 | Version: c.vers, 558 | ctx: hs.ctx, 559 | }) 560 | if err != nil { 561 | return err 562 | } 563 | 564 | certMsg := new(certificateMsgTLS13) 565 | 566 | certMsg.certificate = *cert 567 | certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0 568 | certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0 569 | 570 | hs.transcript.Write(certMsg.marshal()) 571 | if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil { 572 | return err 573 | } 574 | 575 | // If we sent an empty certificate message, skip the CertificateVerify. 576 | if len(cert.Certificate) == 0 { 577 | return nil 578 | } 579 | 580 | certVerifyMsg := new(certificateVerifyMsg) 581 | certVerifyMsg.hasSignatureAlgorithm = true 582 | 583 | certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms) 584 | if err != nil { 585 | // getClientCertificate returned a certificate incompatible with the 586 | // CertificateRequestInfo supported signature algorithms. 587 | c.sendAlert(alertHandshakeFailure) 588 | return err 589 | } 590 | 591 | sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm) 592 | if err != nil { 593 | return c.sendAlert(alertInternalError) 594 | } 595 | 596 | signed := signedMessage(sigHash, clientSignatureContext, hs.transcript) 597 | signOpts := crypto.SignerOpts(sigHash) 598 | if sigType == signatureRSAPSS { 599 | signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} 600 | } 601 | sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts) 602 | if err != nil { 603 | c.sendAlert(alertInternalError) 604 | return errors.New("tls: failed to sign handshake: " + err.Error()) 605 | } 606 | certVerifyMsg.signature = sig 607 | 608 | hs.transcript.Write(certVerifyMsg.marshal()) 609 | if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil { 610 | return err 611 | } 612 | 613 | return nil 614 | } 615 | 616 | func (hs *clientHandshakeStateTLS13) sendClientFinished() error { 617 | c := hs.c 618 | 619 | finished := &finishedMsg{ 620 | verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), 621 | } 622 | 623 | hs.transcript.Write(finished.marshal()) 624 | if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil { 625 | return err 626 | } 627 | 628 | c.out.setTrafficSecret(hs.suite, hs.trafficSecret) 629 | 630 | if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil { 631 | c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret, 632 | resumptionLabel, hs.transcript) 633 | } 634 | 635 | return nil 636 | } 637 | 638 | func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error { 639 | if !c.isClient { 640 | c.sendAlert(alertUnexpectedMessage) 641 | return errors.New("tls: received new session ticket from a client") 642 | } 643 | 644 | if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil { 645 | return nil 646 | } 647 | 648 | // See RFC 8446, Section 4.6.1. 649 | if msg.lifetime == 0 { 650 | return nil 651 | } 652 | lifetime := time.Duration(msg.lifetime) * time.Second 653 | if lifetime > maxSessionTicketLifetime { 654 | c.sendAlert(alertIllegalParameter) 655 | return errors.New("tls: received a session ticket with invalid lifetime") 656 | } 657 | 658 | cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite) 659 | if cipherSuite == nil || c.resumptionSecret == nil { 660 | return c.sendAlert(alertInternalError) 661 | } 662 | 663 | // Save the resumption_master_secret and nonce instead of deriving the PSK 664 | // to do the least amount of work on NewSessionTicket messages before we 665 | // know if the ticket will be used. Forward secrecy of resumed connections 666 | // is guaranteed by the requirement for pskModeDHE. 667 | session := &ClientSessionState{ 668 | sessionTicket: msg.label, 669 | vers: c.vers, 670 | cipherSuite: c.cipherSuite, 671 | masterSecret: c.resumptionSecret, 672 | serverCertificates: c.peerCertificates, 673 | verifiedChains: c.verifiedChains, 674 | receivedAt: c.config.time(), 675 | nonce: msg.nonce, 676 | useBy: c.config.time().Add(lifetime), 677 | ageAdd: msg.ageAdd, 678 | ocspResponse: c.ocspResponse, 679 | scts: c.scts, 680 | } 681 | 682 | cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config) 683 | c.config.ClientSessionCache.Put(cacheKey, session) 684 | 685 | return nil 686 | } 687 | -------------------------------------------------------------------------------- /tls.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE-Go file. 4 | 5 | // Server side implementation of REALITY protocol, a fork of package tls in Go 1.19.5. 6 | // For client side, please follow https://github.com/XTLS/Xray-core. 7 | package reality 8 | 9 | // BUG(agl): The crypto/tls package only implements some countermeasures 10 | // against Lucky13 attacks on CBC-mode encryption, and only on SHA1 11 | // variants. See http://www.isg.rhul.ac.uk/tls/TLStiming.pdf and 12 | // https://www.imperialviolet.org/2013/02/04/luckythirteen.html. 13 | 14 | import ( 15 | "bytes" 16 | "context" 17 | "crypto" 18 | "crypto/aes" 19 | "crypto/cipher" 20 | "crypto/ecdsa" 21 | "crypto/ed25519" 22 | "crypto/rsa" 23 | "crypto/sha256" 24 | "crypto/x509" 25 | "encoding/binary" 26 | "encoding/pem" 27 | "errors" 28 | "fmt" 29 | "io" 30 | "net" 31 | "os" 32 | "runtime" 33 | "strings" 34 | "sync" 35 | "time" 36 | 37 | "github.com/pires/go-proxyproto" 38 | "golang.org/x/crypto/curve25519" 39 | "golang.org/x/crypto/hkdf" 40 | ) 41 | 42 | type ReaderConn struct { 43 | Conn net.Conn 44 | Reader *bytes.Reader 45 | Written int 46 | Closed bool 47 | } 48 | 49 | func (c *ReaderConn) Read(b []byte) (int, error) { 50 | if c.Closed { 51 | return 0, errors.New("Closed") 52 | } 53 | n, err := c.Reader.Read(b) 54 | if err == io.EOF { 55 | return n, errors.New("io.EOF") // prevent looping 56 | } 57 | return n, err 58 | } 59 | 60 | func (c *ReaderConn) Write(b []byte) (int, error) { 61 | if c.Closed { 62 | return 0, errors.New("Closed") 63 | } 64 | c.Written += len(b) 65 | return len(b), nil 66 | } 67 | 68 | func (c *ReaderConn) Close() error { 69 | c.Closed = true 70 | return nil 71 | } 72 | 73 | func (c *ReaderConn) LocalAddr() net.Addr { 74 | return c.Conn.LocalAddr() 75 | } 76 | 77 | func (c *ReaderConn) RemoteAddr() net.Addr { 78 | return c.Conn.RemoteAddr() 79 | } 80 | 81 | func (c *ReaderConn) SetDeadline(t time.Time) error { 82 | return nil 83 | } 84 | 85 | func (c *ReaderConn) SetReadDeadline(t time.Time) error { 86 | return nil 87 | } 88 | 89 | func (c *ReaderConn) SetWriteDeadline(t time.Time) error { 90 | return nil 91 | } 92 | 93 | var ( 94 | size = 8192 95 | empty = make([]byte, size) 96 | types = [7]string{ 97 | "Server Hello", 98 | "Change Cipher Spec", 99 | "Encrypted Extensions", 100 | "Certificate", 101 | "Certificate Verify", 102 | "Finished", 103 | "New Session Ticket", 104 | } 105 | ) 106 | 107 | func Value(vals ...byte) (value int) { 108 | for i, val := range vals { 109 | value |= int(val) << ((len(vals) - i - 1) * 8) 110 | } 111 | return 112 | } 113 | 114 | // Server returns a new TLS server side connection 115 | // using conn as the underlying transport. 116 | // The configuration config must be non-nil and must include 117 | // at least one certificate or else set GetCertificate. 118 | func Server(conn net.Conn, config *Config) (*Conn, error) { 119 | remoteAddr := conn.RemoteAddr().String() 120 | if config.Show { 121 | fmt.Printf("REALITY remoteAddr: %v\n", remoteAddr) 122 | } 123 | 124 | target, err := net.Dial(config.Type, config.Dest) 125 | if err != nil { 126 | conn.Close() 127 | return nil, errors.New("REALITY: failed to dial dest: " + err.Error()) 128 | } 129 | 130 | if config.Xver == 1 || config.Xver == 2 { 131 | if _, err = proxyproto.HeaderProxyFromAddrs(config.Xver, conn.RemoteAddr(), conn.LocalAddr()).WriteTo(target); err != nil { 132 | target.Close() 133 | conn.Close() 134 | return nil, errors.New("REALITY: failed to send PROXY protocol: " + err.Error()) 135 | } 136 | } 137 | 138 | underlying := conn 139 | if pc, ok := underlying.(*proxyproto.Conn); ok { 140 | underlying = pc.Raw() 141 | } 142 | 143 | hs := serverHandshakeStateTLS13{ctx: context.TODO()} 144 | 145 | c2sSaved := make([]byte, 0, size) 146 | s2cSaved := make([]byte, 0, size) 147 | 148 | copying := false 149 | handled := false 150 | 151 | waitGroup := new(sync.WaitGroup) 152 | waitGroup.Add(2) 153 | 154 | mutex := new(sync.Mutex) 155 | 156 | go func() { 157 | done := false 158 | buf := make([]byte, size) 159 | clientHelloLen := 0 160 | for { 161 | runtime.Gosched() 162 | n, err := conn.Read(buf) 163 | if n == 0 { 164 | if err != nil { 165 | target.Close() 166 | waitGroup.Done() 167 | return 168 | } 169 | continue 170 | } 171 | mutex.Lock() 172 | c2sSaved = append(c2sSaved, buf[:n]...) 173 | if _, err = target.Write(buf[:n]); err != nil { 174 | done = true 175 | break 176 | } 177 | if copying || len(c2sSaved) > size || len(s2cSaved) > 0 { // follow; too long; unexpected 178 | break 179 | } 180 | if clientHelloLen == 0 && len(c2sSaved) > recordHeaderLen { 181 | if recordType(c2sSaved[0]) != recordTypeHandshake || Value(c2sSaved[1:3]...) != VersionTLS10 || c2sSaved[5] != typeClientHello { 182 | break 183 | } 184 | clientHelloLen = recordHeaderLen + Value(c2sSaved[3:5]...) 185 | } 186 | if clientHelloLen > size { // too long 187 | break 188 | } 189 | if clientHelloLen == 0 || len(c2sSaved) < clientHelloLen { 190 | mutex.Unlock() 191 | continue 192 | } 193 | if len(c2sSaved) > clientHelloLen { // unexpected 194 | break 195 | } 196 | readerConn := &ReaderConn{ 197 | Conn: underlying, 198 | Reader: bytes.NewReader(c2sSaved), 199 | } 200 | hs.c = &Conn{ 201 | conn: readerConn, 202 | config: config, 203 | } 204 | hs.clientHello, err = hs.c.readClientHello(context.TODO()) 205 | if err != nil || readerConn.Reader.Len() > 0 || readerConn.Written > 0 || readerConn.Closed { 206 | break 207 | } 208 | if hs.c.vers != VersionTLS13 || !config.ServerNames[hs.clientHello.serverName] { 209 | break 210 | } 211 | for i, keyShare := range hs.clientHello.keyShares { 212 | if keyShare.group != X25519 || len(keyShare.data) != 32 { 213 | continue 214 | } 215 | if hs.c.AuthKey, err = curve25519.X25519(config.PrivateKey, keyShare.data); err != nil { 216 | break 217 | } 218 | if _, err = hkdf.New(sha256.New, hs.c.AuthKey, hs.clientHello.random[:20], []byte("REALITY")).Read(hs.c.AuthKey); err != nil { 219 | break 220 | } 221 | if config.Show { 222 | fmt.Printf("REALITY remoteAddr: %v\ths.clientHello.sessionId: %v\n", remoteAddr, hs.clientHello.sessionId) 223 | fmt.Printf("REALITY remoteAddr: %v\ths.c.AuthKey: %v\n", remoteAddr, hs.c.AuthKey) 224 | } 225 | block, _ := aes.NewCipher(hs.c.AuthKey) 226 | aead, _ := cipher.NewGCM(block) 227 | ciphertext := make([]byte, 32) 228 | plainText := make([]byte, 32) 229 | copy(ciphertext, hs.clientHello.sessionId) 230 | copy(hs.clientHello.sessionId, plainText) // hs.clientHello.sessionId points to hs.clientHello.raw[39:] 231 | if _, err = aead.Open(plainText[:0], hs.clientHello.random[20:], ciphertext, hs.clientHello.raw); err != nil { 232 | break 233 | } 234 | copy(hs.clientHello.sessionId, ciphertext) 235 | copy(hs.c.ClientVer[:], plainText) 236 | copy(hs.c.ClientShortId[:], plainText[8:]) 237 | plainText[0] = 0 238 | plainText[1] = 0 239 | plainText[2] = 0 240 | hs.c.ClientTime = time.Unix(int64(binary.BigEndian.Uint64(plainText)), 0) 241 | if config.Show { 242 | fmt.Printf("REALITY remoteAddr: %v\ths.c.ClientVer: %v\n", remoteAddr, hs.c.ClientVer) 243 | fmt.Printf("REALITY remoteAddr: %v\ths.c.ClientTime: %v\n", remoteAddr, hs.c.ClientTime) 244 | fmt.Printf("REALITY remoteAddr: %v\ths.c.ClientShortId: %v\n", remoteAddr, hs.c.ClientShortId) 245 | } 246 | if (config.MinClientVer == nil || Value(hs.c.ClientVer[:]...) >= Value(config.MinClientVer...)) && 247 | (config.MaxClientVer == nil || Value(hs.c.ClientVer[:]...) <= Value(config.MaxClientVer...)) && 248 | (config.MaxTimeDiff == 0 || time.Since(hs.c.ClientTime).Abs() <= config.MaxTimeDiff) && 249 | (config.ShortIds[hs.c.ClientShortId]) { 250 | hs.c.conn = underlying 251 | } 252 | hs.clientHello.keyShares[0].group = CurveID(i) 253 | break 254 | } 255 | if config.Show { 256 | fmt.Printf("REALITY remoteAddr: %v\ths.c.conn == underlying: %v\n", remoteAddr, hs.c.conn == underlying) 257 | } 258 | if hs.c.conn == underlying { 259 | done = true 260 | } 261 | break 262 | } 263 | if done { 264 | mutex.Unlock() 265 | } else { 266 | copying = true 267 | mutex.Unlock() 268 | io.Copy(target, underlying) 269 | } 270 | waitGroup.Done() 271 | }() 272 | 273 | go func() { 274 | done := false 275 | buf := make([]byte, size) 276 | handshakeLen := 0 277 | f: 278 | for { 279 | runtime.Gosched() 280 | n, err := target.Read(buf) 281 | if n == 0 { 282 | if err != nil { 283 | conn.Close() 284 | waitGroup.Done() 285 | return 286 | } 287 | continue 288 | } 289 | mutex.Lock() 290 | s2cSaved = append(s2cSaved, buf[:n]...) 291 | if hs.c == nil || hs.c.conn != underlying { 292 | if _, err = conn.Write(buf[:n]); err != nil { 293 | done = true 294 | break 295 | } 296 | if copying || len(s2cSaved) > size { // follow; too long 297 | break 298 | } 299 | mutex.Unlock() 300 | continue 301 | } 302 | done = true // special 303 | if len(s2cSaved) > size { 304 | break 305 | } 306 | for i, t := range types { 307 | if hs.c.out.handshakeLen[i] != 0 { 308 | continue 309 | } 310 | if i == 6 && len(s2cSaved) == 0 { 311 | break 312 | } 313 | if handshakeLen == 0 && len(s2cSaved) > recordHeaderLen { 314 | if Value(s2cSaved[1:3]...) != VersionTLS12 || 315 | (i == 0 && (recordType(s2cSaved[0]) != recordTypeHandshake || s2cSaved[5] != typeServerHello)) || 316 | (i == 1 && (recordType(s2cSaved[0]) != recordTypeChangeCipherSpec || s2cSaved[5] != 1)) || 317 | (i > 1 && recordType(s2cSaved[0]) != recordTypeApplicationData) { 318 | break f 319 | } 320 | handshakeLen = recordHeaderLen + Value(s2cSaved[3:5]...) 321 | } 322 | if config.Show { 323 | fmt.Printf("REALITY remoteAddr: %v\tlen(s2cSaved): %v\t%v: %v\n", remoteAddr, len(s2cSaved), t, handshakeLen) 324 | } 325 | if handshakeLen > size { // too long 326 | break f 327 | } 328 | if i == 1 && handshakeLen > 0 && handshakeLen != 6 { 329 | break f 330 | } 331 | if i == 2 && handshakeLen > 512 { 332 | hs.c.out.handshakeLen[i] = handshakeLen 333 | hs.c.out.handshakeBuf = s2cSaved[:0] 334 | break 335 | } 336 | if i == 6 && handshakeLen > 0 { 337 | hs.c.out.handshakeLen[i] = handshakeLen 338 | break 339 | } 340 | if handshakeLen == 0 || len(s2cSaved) < handshakeLen { 341 | mutex.Unlock() 342 | continue f 343 | } 344 | if i == 0 { 345 | hs.hello = new(serverHelloMsg) 346 | if !hs.hello.unmarshal(s2cSaved[recordHeaderLen:handshakeLen]) || 347 | hs.hello.vers != VersionTLS12 || hs.hello.supportedVersion != VersionTLS13 || 348 | cipherSuiteTLS13ByID(hs.hello.cipherSuite) == nil || 349 | hs.hello.serverShare.group != X25519 || len(hs.hello.serverShare.data) != 32 { 350 | break f 351 | } 352 | } 353 | hs.c.out.handshakeLen[i] = handshakeLen 354 | s2cSaved = s2cSaved[handshakeLen:] 355 | handshakeLen = 0 356 | } 357 | err = hs.handshake() 358 | if config.Show { 359 | fmt.Printf("REALITY remoteAddr: %v\ths.handshake() err: %v\n", remoteAddr, err) 360 | } 361 | if err == nil { 362 | handled = true 363 | } 364 | break 365 | } 366 | if done { 367 | mutex.Unlock() 368 | } else { 369 | copying = true 370 | mutex.Unlock() 371 | io.Copy(underlying, target) 372 | } 373 | waitGroup.Done() 374 | }() 375 | 376 | waitGroup.Wait() 377 | target.Close() 378 | if config.Show { 379 | fmt.Printf("REALITY remoteAddr: %v\thandled: %v\n", remoteAddr, handled) 380 | } 381 | if handled { 382 | return hs.c, nil 383 | } 384 | conn.Close() 385 | return nil, errors.New("REALITY: processed invalid connection") 386 | 387 | /* 388 | c := &Conn{ 389 | conn: conn, 390 | config: config, 391 | } 392 | c.handshakeFn = c.serverHandshake 393 | return c 394 | */ 395 | } 396 | 397 | // Client returns a new TLS client side connection 398 | // using conn as the underlying transport. 399 | // The config cannot be nil: users must set either ServerName or 400 | // InsecureSkipVerify in the config. 401 | func Client(conn net.Conn, config *Config) *Conn { 402 | c := &Conn{ 403 | conn: conn, 404 | config: config, 405 | isClient: true, 406 | } 407 | c.handshakeFn = c.clientHandshake 408 | return c 409 | } 410 | 411 | // A listener implements a network listener (net.Listener) for TLS connections. 412 | type listener struct { 413 | net.Listener 414 | config *Config 415 | } 416 | 417 | // Accept waits for and returns the next incoming TLS connection. 418 | // The returned connection is of type *Conn. 419 | func (l *listener) Accept() (net.Conn, error) { 420 | c, err := l.Listener.Accept() 421 | if err != nil { 422 | return nil, err 423 | } 424 | return Server(c, l.config) 425 | } 426 | 427 | // NewListener creates a Listener which accepts connections from an inner 428 | // Listener and wraps each connection with Server. 429 | // The configuration config must be non-nil and must include 430 | // at least one certificate or else set GetCertificate. 431 | func NewListener(inner net.Listener, config *Config) net.Listener { 432 | l := new(listener) 433 | l.Listener = inner 434 | l.config = config 435 | return l 436 | } 437 | 438 | // Listen creates a TLS listener accepting connections on the 439 | // given network address using net.Listen. 440 | // The configuration config must be non-nil and must include 441 | // at least one certificate or else set GetCertificate. 442 | func Listen(network, laddr string, config *Config) (net.Listener, error) { 443 | if config == nil || len(config.Certificates) == 0 && 444 | config.GetCertificate == nil && config.GetConfigForClient == nil { 445 | return nil, errors.New("tls: neither Certificates, GetCertificate, nor GetConfigForClient set in Config") 446 | } 447 | l, err := net.Listen(network, laddr) 448 | if err != nil { 449 | return nil, err 450 | } 451 | return NewListener(l, config), nil 452 | } 453 | 454 | type timeoutError struct{} 455 | 456 | func (timeoutError) Error() string { return "tls: DialWithDialer timed out" } 457 | func (timeoutError) Timeout() bool { return true } 458 | func (timeoutError) Temporary() bool { return true } 459 | 460 | // DialWithDialer connects to the given network address using dialer.Dial and 461 | // then initiates a TLS handshake, returning the resulting TLS connection. Any 462 | // timeout or deadline given in the dialer apply to connection and TLS 463 | // handshake as a whole. 464 | // 465 | // DialWithDialer interprets a nil configuration as equivalent to the zero 466 | // configuration; see the documentation of Config for the defaults. 467 | // 468 | // DialWithDialer uses context.Background internally; to specify the context, 469 | // use Dialer.DialContext with NetDialer set to the desired dialer. 470 | func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) { 471 | return dial(context.Background(), dialer, network, addr, config) 472 | } 473 | 474 | func dial(ctx context.Context, netDialer *net.Dialer, network, addr string, config *Config) (*Conn, error) { 475 | if netDialer.Timeout != 0 { 476 | var cancel context.CancelFunc 477 | ctx, cancel = context.WithTimeout(ctx, netDialer.Timeout) 478 | defer cancel() 479 | } 480 | 481 | if !netDialer.Deadline.IsZero() { 482 | var cancel context.CancelFunc 483 | ctx, cancel = context.WithDeadline(ctx, netDialer.Deadline) 484 | defer cancel() 485 | } 486 | 487 | rawConn, err := netDialer.DialContext(ctx, network, addr) 488 | if err != nil { 489 | return nil, err 490 | } 491 | 492 | colonPos := strings.LastIndex(addr, ":") 493 | if colonPos == -1 { 494 | colonPos = len(addr) 495 | } 496 | hostname := addr[:colonPos] 497 | 498 | if config == nil { 499 | config = defaultConfig() 500 | } 501 | // If no ServerName is set, infer the ServerName 502 | // from the hostname we're connecting to. 503 | if config.ServerName == "" { 504 | // Make a copy to avoid polluting argument or default. 505 | c := config.Clone() 506 | c.ServerName = hostname 507 | config = c 508 | } 509 | 510 | conn := Client(rawConn, config) 511 | if err := conn.HandshakeContext(ctx); err != nil { 512 | rawConn.Close() 513 | return nil, err 514 | } 515 | return conn, nil 516 | } 517 | 518 | // Dial connects to the given network address using net.Dial 519 | // and then initiates a TLS handshake, returning the resulting 520 | // TLS connection. 521 | // Dial interprets a nil configuration as equivalent to 522 | // the zero configuration; see the documentation of Config 523 | // for the defaults. 524 | func Dial(network, addr string, config *Config) (*Conn, error) { 525 | return DialWithDialer(new(net.Dialer), network, addr, config) 526 | } 527 | 528 | // Dialer dials TLS connections given a configuration and a Dialer for the 529 | // underlying connection. 530 | type Dialer struct { 531 | // NetDialer is the optional dialer to use for the TLS connections' 532 | // underlying TCP connections. 533 | // A nil NetDialer is equivalent to the net.Dialer zero value. 534 | NetDialer *net.Dialer 535 | 536 | // Config is the TLS configuration to use for new connections. 537 | // A nil configuration is equivalent to the zero 538 | // configuration; see the documentation of Config for the 539 | // defaults. 540 | Config *Config 541 | } 542 | 543 | // Dial connects to the given network address and initiates a TLS 544 | // handshake, returning the resulting TLS connection. 545 | // 546 | // The returned Conn, if any, will always be of type *Conn. 547 | // 548 | // Dial uses context.Background internally; to specify the context, 549 | // use DialContext. 550 | func (d *Dialer) Dial(network, addr string) (net.Conn, error) { 551 | return d.DialContext(context.Background(), network, addr) 552 | } 553 | 554 | func (d *Dialer) netDialer() *net.Dialer { 555 | if d.NetDialer != nil { 556 | return d.NetDialer 557 | } 558 | return new(net.Dialer) 559 | } 560 | 561 | // DialContext connects to the given network address and initiates a TLS 562 | // handshake, returning the resulting TLS connection. 563 | // 564 | // The provided Context must be non-nil. If the context expires before 565 | // the connection is complete, an error is returned. Once successfully 566 | // connected, any expiration of the context will not affect the 567 | // connection. 568 | // 569 | // The returned Conn, if any, will always be of type *Conn. 570 | func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) { 571 | c, err := dial(ctx, d.netDialer(), network, addr, d.Config) 572 | if err != nil { 573 | // Don't return c (a typed nil) in an interface. 574 | return nil, err 575 | } 576 | return c, nil 577 | } 578 | 579 | // LoadX509KeyPair reads and parses a public/private key pair from a pair 580 | // of files. The files must contain PEM encoded data. The certificate file 581 | // may contain intermediate certificates following the leaf certificate to 582 | // form a certificate chain. On successful return, Certificate.Leaf will 583 | // be nil because the parsed form of the certificate is not retained. 584 | func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) { 585 | certPEMBlock, err := os.ReadFile(certFile) 586 | if err != nil { 587 | return Certificate{}, err 588 | } 589 | keyPEMBlock, err := os.ReadFile(keyFile) 590 | if err != nil { 591 | return Certificate{}, err 592 | } 593 | return X509KeyPair(certPEMBlock, keyPEMBlock) 594 | } 595 | 596 | // X509KeyPair parses a public/private key pair from a pair of 597 | // PEM encoded data. On successful return, Certificate.Leaf will be nil because 598 | // the parsed form of the certificate is not retained. 599 | func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) { 600 | fail := func(err error) (Certificate, error) { return Certificate{}, err } 601 | 602 | var cert Certificate 603 | var skippedBlockTypes []string 604 | for { 605 | var certDERBlock *pem.Block 606 | certDERBlock, certPEMBlock = pem.Decode(certPEMBlock) 607 | if certDERBlock == nil { 608 | break 609 | } 610 | if certDERBlock.Type == "CERTIFICATE" { 611 | cert.Certificate = append(cert.Certificate, certDERBlock.Bytes) 612 | } else { 613 | skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type) 614 | } 615 | } 616 | 617 | if len(cert.Certificate) == 0 { 618 | if len(skippedBlockTypes) == 0 { 619 | return fail(errors.New("tls: failed to find any PEM data in certificate input")) 620 | } 621 | if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") { 622 | return fail(errors.New("tls: failed to find certificate PEM data in certificate input, but did find a private key; PEM inputs may have been switched")) 623 | } 624 | return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes)) 625 | } 626 | 627 | skippedBlockTypes = skippedBlockTypes[:0] 628 | var keyDERBlock *pem.Block 629 | for { 630 | keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock) 631 | if keyDERBlock == nil { 632 | if len(skippedBlockTypes) == 0 { 633 | return fail(errors.New("tls: failed to find any PEM data in key input")) 634 | } 635 | if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" { 636 | return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key")) 637 | } 638 | return fail(fmt.Errorf("tls: failed to find PEM block with type ending in \"PRIVATE KEY\" in key input after skipping PEM blocks of the following types: %v", skippedBlockTypes)) 639 | } 640 | if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") { 641 | break 642 | } 643 | skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type) 644 | } 645 | 646 | // We don't need to parse the public key for TLS, but we so do anyway 647 | // to check that it looks sane and matches the private key. 648 | x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) 649 | if err != nil { 650 | return fail(err) 651 | } 652 | 653 | cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes) 654 | if err != nil { 655 | return fail(err) 656 | } 657 | 658 | switch pub := x509Cert.PublicKey.(type) { 659 | case *rsa.PublicKey: 660 | priv, ok := cert.PrivateKey.(*rsa.PrivateKey) 661 | if !ok { 662 | return fail(errors.New("tls: private key type does not match public key type")) 663 | } 664 | if pub.N.Cmp(priv.N) != 0 { 665 | return fail(errors.New("tls: private key does not match public key")) 666 | } 667 | case *ecdsa.PublicKey: 668 | priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey) 669 | if !ok { 670 | return fail(errors.New("tls: private key type does not match public key type")) 671 | } 672 | if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 { 673 | return fail(errors.New("tls: private key does not match public key")) 674 | } 675 | case ed25519.PublicKey: 676 | priv, ok := cert.PrivateKey.(ed25519.PrivateKey) 677 | if !ok { 678 | return fail(errors.New("tls: private key type does not match public key type")) 679 | } 680 | if !bytes.Equal(priv.Public().(ed25519.PublicKey), pub) { 681 | return fail(errors.New("tls: private key does not match public key")) 682 | } 683 | default: 684 | return fail(errors.New("tls: unknown public key algorithm")) 685 | } 686 | 687 | return cert, nil 688 | } 689 | 690 | // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates 691 | // PKCS #1 private keys by default, while OpenSSL 1.0.0 generates PKCS #8 keys. 692 | // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three. 693 | func parsePrivateKey(der []byte) (crypto.PrivateKey, error) { 694 | if key, err := x509.ParsePKCS1PrivateKey(der); err == nil { 695 | return key, nil 696 | } 697 | if key, err := x509.ParsePKCS8PrivateKey(der); err == nil { 698 | switch key := key.(type) { 699 | case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey: 700 | return key, nil 701 | default: 702 | return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping") 703 | } 704 | } 705 | if key, err := x509.ParseECPrivateKey(der); err == nil { 706 | return key, nil 707 | } 708 | 709 | return nil, errors.New("tls: failed to parse private key") 710 | } 711 | -------------------------------------------------------------------------------- /cipher_suites.go: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE-Go file. 4 | 5 | package reality 6 | 7 | import ( 8 | "crypto" 9 | "crypto/aes" 10 | "crypto/cipher" 11 | "crypto/des" 12 | "crypto/hmac" 13 | "crypto/rc4" 14 | "crypto/sha1" 15 | "crypto/sha256" 16 | "fmt" 17 | "hash" 18 | "runtime" 19 | 20 | "golang.org/x/crypto/chacha20poly1305" 21 | "golang.org/x/sys/cpu" 22 | ) 23 | 24 | // CipherSuite is a TLS cipher suite. Note that most functions in this package 25 | // accept and expose cipher suite IDs instead of this type. 26 | type CipherSuite struct { 27 | ID uint16 28 | Name string 29 | 30 | // Supported versions is the list of TLS protocol versions that can 31 | // negotiate this cipher suite. 32 | SupportedVersions []uint16 33 | 34 | // Insecure is true if the cipher suite has known security issues 35 | // due to its primitives, design, or implementation. 36 | Insecure bool 37 | } 38 | 39 | var ( 40 | supportedUpToTLS12 = []uint16{VersionTLS10, VersionTLS11, VersionTLS12} 41 | supportedOnlyTLS12 = []uint16{VersionTLS12} 42 | supportedOnlyTLS13 = []uint16{VersionTLS13} 43 | ) 44 | 45 | // CipherSuites returns a list of cipher suites currently implemented by this 46 | // package, excluding those with security issues, which are returned by 47 | // InsecureCipherSuites. 48 | // 49 | // The list is sorted by ID. Note that the default cipher suites selected by 50 | // this package might depend on logic that can't be captured by a static list, 51 | // and might not match those returned by this function. 52 | func CipherSuites() []*CipherSuite { 53 | return []*CipherSuite{ 54 | {TLS_RSA_WITH_AES_128_CBC_SHA, "TLS_RSA_WITH_AES_128_CBC_SHA", supportedUpToTLS12, false}, 55 | {TLS_RSA_WITH_AES_256_CBC_SHA, "TLS_RSA_WITH_AES_256_CBC_SHA", supportedUpToTLS12, false}, 56 | {TLS_RSA_WITH_AES_128_GCM_SHA256, "TLS_RSA_WITH_AES_128_GCM_SHA256", supportedOnlyTLS12, false}, 57 | {TLS_RSA_WITH_AES_256_GCM_SHA384, "TLS_RSA_WITH_AES_256_GCM_SHA384", supportedOnlyTLS12, false}, 58 | 59 | {TLS_AES_128_GCM_SHA256, "TLS_AES_128_GCM_SHA256", supportedOnlyTLS13, false}, 60 | {TLS_AES_256_GCM_SHA384, "TLS_AES_256_GCM_SHA384", supportedOnlyTLS13, false}, 61 | {TLS_CHACHA20_POLY1305_SHA256, "TLS_CHACHA20_POLY1305_SHA256", supportedOnlyTLS13, false}, 62 | 63 | {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", supportedUpToTLS12, false}, 64 | {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", supportedUpToTLS12, false}, 65 | {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", supportedUpToTLS12, false}, 66 | {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", supportedUpToTLS12, false}, 67 | {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", supportedOnlyTLS12, false}, 68 | {TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", supportedOnlyTLS12, false}, 69 | {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", supportedOnlyTLS12, false}, 70 | {TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", supportedOnlyTLS12, false}, 71 | {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", supportedOnlyTLS12, false}, 72 | {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", supportedOnlyTLS12, false}, 73 | } 74 | } 75 | 76 | // InsecureCipherSuites returns a list of cipher suites currently implemented by 77 | // this package and which have security issues. 78 | // 79 | // Most applications should not use the cipher suites in this list, and should 80 | // only use those returned by CipherSuites. 81 | func InsecureCipherSuites() []*CipherSuite { 82 | // This list includes RC4, CBC_SHA256, and 3DES cipher suites. See 83 | // cipherSuitesPreferenceOrder for details. 84 | return []*CipherSuite{ 85 | {TLS_RSA_WITH_RC4_128_SHA, "TLS_RSA_WITH_RC4_128_SHA", supportedUpToTLS12, true}, 86 | {TLS_RSA_WITH_3DES_EDE_CBC_SHA, "TLS_RSA_WITH_3DES_EDE_CBC_SHA", supportedUpToTLS12, true}, 87 | {TLS_RSA_WITH_AES_128_CBC_SHA256, "TLS_RSA_WITH_AES_128_CBC_SHA256", supportedOnlyTLS12, true}, 88 | {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", supportedUpToTLS12, true}, 89 | {TLS_ECDHE_RSA_WITH_RC4_128_SHA, "TLS_ECDHE_RSA_WITH_RC4_128_SHA", supportedUpToTLS12, true}, 90 | {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", supportedUpToTLS12, true}, 91 | {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", supportedOnlyTLS12, true}, 92 | {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", supportedOnlyTLS12, true}, 93 | } 94 | } 95 | 96 | // CipherSuiteName returns the standard name for the passed cipher suite ID 97 | // (e.g. "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"), or a fallback representation 98 | // of the ID value if the cipher suite is not implemented by this package. 99 | func CipherSuiteName(id uint16) string { 100 | for _, c := range CipherSuites() { 101 | if c.ID == id { 102 | return c.Name 103 | } 104 | } 105 | for _, c := range InsecureCipherSuites() { 106 | if c.ID == id { 107 | return c.Name 108 | } 109 | } 110 | return fmt.Sprintf("0x%04X", id) 111 | } 112 | 113 | const ( 114 | // suiteECDHE indicates that the cipher suite involves elliptic curve 115 | // Diffie-Hellman. This means that it should only be selected when the 116 | // client indicates that it supports ECC with a curve and point format 117 | // that we're happy with. 118 | suiteECDHE = 1 << iota 119 | // suiteECSign indicates that the cipher suite involves an ECDSA or 120 | // EdDSA signature and therefore may only be selected when the server's 121 | // certificate is ECDSA or EdDSA. If this is not set then the cipher suite 122 | // is RSA based. 123 | suiteECSign 124 | // suiteTLS12 indicates that the cipher suite should only be advertised 125 | // and accepted when using TLS 1.2. 126 | suiteTLS12 127 | // suiteSHA384 indicates that the cipher suite uses SHA384 as the 128 | // handshake hash. 129 | suiteSHA384 130 | ) 131 | 132 | // A cipherSuite is a TLS 1.0–1.2 cipher suite, and defines the key exchange 133 | // mechanism, as well as the cipher+MAC pair or the AEAD. 134 | type cipherSuite struct { 135 | id uint16 136 | // the lengths, in bytes, of the key material needed for each component. 137 | keyLen int 138 | macLen int 139 | ivLen int 140 | ka func(version uint16) keyAgreement 141 | // flags is a bitmask of the suite* values, above. 142 | flags int 143 | cipher func(key, iv []byte, isRead bool) any 144 | mac func(key []byte) hash.Hash 145 | aead func(key, fixedNonce []byte) aead 146 | } 147 | 148 | var cipherSuites = []*cipherSuite{ // TODO: replace with a map, since the order doesn't matter. 149 | {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 32, 0, 12, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadChaCha20Poly1305}, 150 | {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 32, 0, 12, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12, nil, nil, aeadChaCha20Poly1305}, 151 | {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadAESGCM}, 152 | {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12, nil, nil, aeadAESGCM}, 153 | {TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM}, 154 | {TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM}, 155 | {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, ecdheRSAKA, suiteECDHE | suiteTLS12, cipherAES, macSHA256, nil}, 156 | {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil}, 157 | {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12, cipherAES, macSHA256, nil}, 158 | {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECSign, cipherAES, macSHA1, nil}, 159 | {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil}, 160 | {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECSign, cipherAES, macSHA1, nil}, 161 | {TLS_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, rsaKA, suiteTLS12, nil, nil, aeadAESGCM}, 162 | {TLS_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, rsaKA, suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM}, 163 | {TLS_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, rsaKA, suiteTLS12, cipherAES, macSHA256, nil}, 164 | {TLS_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil}, 165 | {TLS_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil}, 166 | {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, ecdheRSAKA, suiteECDHE, cipher3DES, macSHA1, nil}, 167 | {TLS_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, rsaKA, 0, cipher3DES, macSHA1, nil}, 168 | {TLS_RSA_WITH_RC4_128_SHA, 16, 20, 0, rsaKA, 0, cipherRC4, macSHA1, nil}, 169 | {TLS_ECDHE_RSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheRSAKA, suiteECDHE, cipherRC4, macSHA1, nil}, 170 | {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheECDSAKA, suiteECDHE | suiteECSign, cipherRC4, macSHA1, nil}, 171 | } 172 | 173 | // selectCipherSuite returns the first TLS 1.0–1.2 cipher suite from ids which 174 | // is also in supportedIDs and passes the ok filter. 175 | func selectCipherSuite(ids, supportedIDs []uint16, ok func(*cipherSuite) bool) *cipherSuite { 176 | for _, id := range ids { 177 | candidate := cipherSuiteByID(id) 178 | if candidate == nil || !ok(candidate) { 179 | continue 180 | } 181 | 182 | for _, suppID := range supportedIDs { 183 | if id == suppID { 184 | return candidate 185 | } 186 | } 187 | } 188 | return nil 189 | } 190 | 191 | // A cipherSuiteTLS13 defines only the pair of the AEAD algorithm and hash 192 | // algorithm to be used with HKDF. See RFC 8446, Appendix B.4. 193 | type cipherSuiteTLS13 struct { 194 | id uint16 195 | keyLen int 196 | aead func(key, fixedNonce []byte) aead 197 | hash crypto.Hash 198 | } 199 | 200 | var cipherSuitesTLS13 = []*cipherSuiteTLS13{ // TODO: replace with a map. 201 | {TLS_AES_128_GCM_SHA256, 16, aeadAESGCMTLS13, crypto.SHA256}, 202 | {TLS_CHACHA20_POLY1305_SHA256, 32, aeadChaCha20Poly1305, crypto.SHA256}, 203 | {TLS_AES_256_GCM_SHA384, 32, aeadAESGCMTLS13, crypto.SHA384}, 204 | } 205 | 206 | // cipherSuitesPreferenceOrder is the order in which we'll select (on the 207 | // server) or advertise (on the client) TLS 1.0–1.2 cipher suites. 208 | // 209 | // Cipher suites are filtered but not reordered based on the application and 210 | // peer's preferences, meaning we'll never select a suite lower in this list if 211 | // any higher one is available. This makes it more defensible to keep weaker 212 | // cipher suites enabled, especially on the server side where we get the last 213 | // word, since there are no known downgrade attacks on cipher suites selection. 214 | // 215 | // The list is sorted by applying the following priority rules, stopping at the 216 | // first (most important) applicable one: 217 | // 218 | // - Anything else comes before RC4 219 | // 220 | // RC4 has practically exploitable biases. See https://www.rc4nomore.com. 221 | // 222 | // - Anything else comes before CBC_SHA256 223 | // 224 | // SHA-256 variants of the CBC ciphersuites don't implement any Lucky13 225 | // countermeasures. See http://www.isg.rhul.ac.uk/tls/Lucky13.html and 226 | // https://www.imperialviolet.org/2013/02/04/luckythirteen.html. 227 | // 228 | // - Anything else comes before 3DES 229 | // 230 | // 3DES has 64-bit blocks, which makes it fundamentally susceptible to 231 | // birthday attacks. See https://sweet32.info. 232 | // 233 | // - ECDHE comes before anything else 234 | // 235 | // Once we got the broken stuff out of the way, the most important 236 | // property a cipher suite can have is forward secrecy. We don't 237 | // implement FFDHE, so that means ECDHE. 238 | // 239 | // - AEADs come before CBC ciphers 240 | // 241 | // Even with Lucky13 countermeasures, MAC-then-Encrypt CBC cipher suites 242 | // are fundamentally fragile, and suffered from an endless sequence of 243 | // padding oracle attacks. See https://eprint.iacr.org/2015/1129, 244 | // https://www.imperialviolet.org/2014/12/08/poodleagain.html, and 245 | // https://blog.cloudflare.com/yet-another-padding-oracle-in-openssl-cbc-ciphersuites/. 246 | // 247 | // - AES comes before ChaCha20 248 | // 249 | // When AES hardware is available, AES-128-GCM and AES-256-GCM are faster 250 | // than ChaCha20Poly1305. 251 | // 252 | // When AES hardware is not available, AES-128-GCM is one or more of: much 253 | // slower, way more complex, and less safe (because not constant time) 254 | // than ChaCha20Poly1305. 255 | // 256 | // We use this list if we think both peers have AES hardware, and 257 | // cipherSuitesPreferenceOrderNoAES otherwise. 258 | // 259 | // - AES-128 comes before AES-256 260 | // 261 | // The only potential advantages of AES-256 are better multi-target 262 | // margins, and hypothetical post-quantum properties. Neither apply to 263 | // TLS, and AES-256 is slower due to its four extra rounds (which don't 264 | // contribute to the advantages above). 265 | // 266 | // - ECDSA comes before RSA 267 | // 268 | // The relative order of ECDSA and RSA cipher suites doesn't matter, 269 | // as they depend on the certificate. Pick one to get a stable order. 270 | var cipherSuitesPreferenceOrder = []uint16{ 271 | // AEADs w/ ECDHE 272 | TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 273 | TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 274 | TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 275 | 276 | // CBC w/ ECDHE 277 | TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 278 | TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 279 | 280 | // AEADs w/o ECDHE 281 | TLS_RSA_WITH_AES_128_GCM_SHA256, 282 | TLS_RSA_WITH_AES_256_GCM_SHA384, 283 | 284 | // CBC w/o ECDHE 285 | TLS_RSA_WITH_AES_128_CBC_SHA, 286 | TLS_RSA_WITH_AES_256_CBC_SHA, 287 | 288 | // 3DES 289 | TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 290 | TLS_RSA_WITH_3DES_EDE_CBC_SHA, 291 | 292 | // CBC_SHA256 293 | TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 294 | TLS_RSA_WITH_AES_128_CBC_SHA256, 295 | 296 | // RC4 297 | TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, 298 | TLS_RSA_WITH_RC4_128_SHA, 299 | } 300 | 301 | var cipherSuitesPreferenceOrderNoAES = []uint16{ 302 | // ChaCha20Poly1305 303 | TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 304 | 305 | // AES-GCM w/ ECDHE 306 | TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 307 | TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 308 | 309 | // The rest of cipherSuitesPreferenceOrder. 310 | TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 311 | TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 312 | TLS_RSA_WITH_AES_128_GCM_SHA256, 313 | TLS_RSA_WITH_AES_256_GCM_SHA384, 314 | TLS_RSA_WITH_AES_128_CBC_SHA, 315 | TLS_RSA_WITH_AES_256_CBC_SHA, 316 | TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 317 | TLS_RSA_WITH_3DES_EDE_CBC_SHA, 318 | TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 319 | TLS_RSA_WITH_AES_128_CBC_SHA256, 320 | TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, 321 | TLS_RSA_WITH_RC4_128_SHA, 322 | } 323 | 324 | // disabledCipherSuites are not used unless explicitly listed in 325 | // Config.CipherSuites. They MUST be at the end of cipherSuitesPreferenceOrder. 326 | var disabledCipherSuites = []uint16{ 327 | // CBC_SHA256 328 | TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 329 | TLS_RSA_WITH_AES_128_CBC_SHA256, 330 | 331 | // RC4 332 | TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, 333 | TLS_RSA_WITH_RC4_128_SHA, 334 | } 335 | 336 | var ( 337 | defaultCipherSuitesLen = len(cipherSuitesPreferenceOrder) - len(disabledCipherSuites) 338 | defaultCipherSuites = cipherSuitesPreferenceOrder[:defaultCipherSuitesLen] 339 | ) 340 | 341 | // defaultCipherSuitesTLS13 is also the preference order, since there are no 342 | // disabled by default TLS 1.3 cipher suites. The same AES vs ChaCha20 logic as 343 | // cipherSuitesPreferenceOrder applies. 344 | var defaultCipherSuitesTLS13 = []uint16{ 345 | TLS_AES_128_GCM_SHA256, 346 | TLS_AES_256_GCM_SHA384, 347 | TLS_CHACHA20_POLY1305_SHA256, 348 | } 349 | 350 | var defaultCipherSuitesTLS13NoAES = []uint16{ 351 | TLS_CHACHA20_POLY1305_SHA256, 352 | TLS_AES_128_GCM_SHA256, 353 | TLS_AES_256_GCM_SHA384, 354 | } 355 | 356 | var ( 357 | hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ 358 | hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL 359 | // Keep in sync with crypto/aes/cipher_s390x.go. 360 | hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && 361 | (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM) 362 | 363 | hasAESGCMHardwareSupport = runtime.GOARCH == "amd64" && hasGCMAsmAMD64 || 364 | runtime.GOARCH == "arm64" && hasGCMAsmARM64 || 365 | runtime.GOARCH == "s390x" && hasGCMAsmS390X 366 | ) 367 | 368 | var aesgcmCiphers = map[uint16]bool{ 369 | // TLS 1.2 370 | TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: true, 371 | TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: true, 372 | TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: true, 373 | TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: true, 374 | // TLS 1.3 375 | TLS_AES_128_GCM_SHA256: true, 376 | TLS_AES_256_GCM_SHA384: true, 377 | } 378 | 379 | var nonAESGCMAEADCiphers = map[uint16]bool{ 380 | // TLS 1.2 381 | TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305: true, 382 | TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305: true, 383 | // TLS 1.3 384 | TLS_CHACHA20_POLY1305_SHA256: true, 385 | } 386 | 387 | // aesgcmPreferred returns whether the first known cipher in the preference list 388 | // is an AES-GCM cipher, implying the peer has hardware support for it. 389 | func aesgcmPreferred(ciphers []uint16) bool { 390 | for _, cID := range ciphers { 391 | if c := cipherSuiteByID(cID); c != nil { 392 | return aesgcmCiphers[cID] 393 | } 394 | if c := cipherSuiteTLS13ByID(cID); c != nil { 395 | return aesgcmCiphers[cID] 396 | } 397 | } 398 | return false 399 | } 400 | 401 | func cipherRC4(key, iv []byte, isRead bool) any { 402 | cipher, _ := rc4.NewCipher(key) 403 | return cipher 404 | } 405 | 406 | func cipher3DES(key, iv []byte, isRead bool) any { 407 | block, _ := des.NewTripleDESCipher(key) 408 | if isRead { 409 | return cipher.NewCBCDecrypter(block, iv) 410 | } 411 | return cipher.NewCBCEncrypter(block, iv) 412 | } 413 | 414 | func cipherAES(key, iv []byte, isRead bool) any { 415 | block, _ := aes.NewCipher(key) 416 | if isRead { 417 | return cipher.NewCBCDecrypter(block, iv) 418 | } 419 | return cipher.NewCBCEncrypter(block, iv) 420 | } 421 | 422 | // macSHA1 returns a SHA-1 based constant time MAC. 423 | func macSHA1(key []byte) hash.Hash { 424 | return hmac.New(sha1.New, key) 425 | } 426 | 427 | // macSHA256 returns a SHA-256 based MAC. This is only supported in TLS 1.2 and 428 | // is currently only used in disabled-by-default cipher suites. 429 | func macSHA256(key []byte) hash.Hash { 430 | return hmac.New(sha256.New, key) 431 | } 432 | 433 | type aead interface { 434 | cipher.AEAD 435 | 436 | // explicitNonceLen returns the number of bytes of explicit nonce 437 | // included in each record. This is eight for older AEADs and 438 | // zero for modern ones. 439 | explicitNonceLen() int 440 | } 441 | 442 | const ( 443 | aeadNonceLength = 12 444 | noncePrefixLength = 4 445 | ) 446 | 447 | // prefixNonceAEAD wraps an AEAD and prefixes a fixed portion of the nonce to 448 | // each call. 449 | type prefixNonceAEAD struct { 450 | // nonce contains the fixed part of the nonce in the first four bytes. 451 | nonce [aeadNonceLength]byte 452 | aead cipher.AEAD 453 | } 454 | 455 | func (f *prefixNonceAEAD) NonceSize() int { return aeadNonceLength - noncePrefixLength } 456 | func (f *prefixNonceAEAD) Overhead() int { return f.aead.Overhead() } 457 | func (f *prefixNonceAEAD) explicitNonceLen() int { return f.NonceSize() } 458 | 459 | func (f *prefixNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte { 460 | copy(f.nonce[4:], nonce) 461 | return f.aead.Seal(out, f.nonce[:], plaintext, additionalData) 462 | } 463 | 464 | func (f *prefixNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error) { 465 | copy(f.nonce[4:], nonce) 466 | return f.aead.Open(out, f.nonce[:], ciphertext, additionalData) 467 | } 468 | 469 | // xoredNonceAEAD wraps an AEAD by XORing in a fixed pattern to the nonce 470 | // before each call. 471 | type xorNonceAEAD struct { 472 | nonceMask [aeadNonceLength]byte 473 | aead cipher.AEAD 474 | } 475 | 476 | func (f *xorNonceAEAD) NonceSize() int { return 8 } // 64-bit sequence number 477 | func (f *xorNonceAEAD) Overhead() int { return f.aead.Overhead() } 478 | func (f *xorNonceAEAD) explicitNonceLen() int { return 0 } 479 | 480 | func (f *xorNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte { 481 | for i, b := range nonce { 482 | f.nonceMask[4+i] ^= b 483 | } 484 | result := f.aead.Seal(out, f.nonceMask[:], plaintext, additionalData) 485 | for i, b := range nonce { 486 | f.nonceMask[4+i] ^= b 487 | } 488 | 489 | return result 490 | } 491 | 492 | func (f *xorNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error) { 493 | for i, b := range nonce { 494 | f.nonceMask[4+i] ^= b 495 | } 496 | result, err := f.aead.Open(out, f.nonceMask[:], ciphertext, additionalData) 497 | for i, b := range nonce { 498 | f.nonceMask[4+i] ^= b 499 | } 500 | 501 | return result, err 502 | } 503 | 504 | func aeadAESGCM(key, noncePrefix []byte) aead { 505 | if len(noncePrefix) != noncePrefixLength { 506 | panic("tls: internal error: wrong nonce length") 507 | } 508 | aes, err := aes.NewCipher(key) 509 | if err != nil { 510 | panic(err) 511 | } 512 | aead, err := cipher.NewGCM(aes) 513 | if err != nil { 514 | panic(err) 515 | } 516 | 517 | ret := &prefixNonceAEAD{aead: aead} 518 | copy(ret.nonce[:], noncePrefix) 519 | return ret 520 | } 521 | 522 | func aeadAESGCMTLS13(key, nonceMask []byte) aead { 523 | if len(nonceMask) != aeadNonceLength { 524 | panic("tls: internal error: wrong nonce length") 525 | } 526 | aes, err := aes.NewCipher(key) 527 | if err != nil { 528 | panic(err) 529 | } 530 | aead, err := cipher.NewGCM(aes) 531 | if err != nil { 532 | panic(err) 533 | } 534 | 535 | ret := &xorNonceAEAD{aead: aead} 536 | copy(ret.nonceMask[:], nonceMask) 537 | return ret 538 | } 539 | 540 | func aeadChaCha20Poly1305(key, nonceMask []byte) aead { 541 | if len(nonceMask) != aeadNonceLength { 542 | panic("tls: internal error: wrong nonce length") 543 | } 544 | aead, err := chacha20poly1305.New(key) 545 | if err != nil { 546 | panic(err) 547 | } 548 | 549 | ret := &xorNonceAEAD{aead: aead} 550 | copy(ret.nonceMask[:], nonceMask) 551 | return ret 552 | } 553 | 554 | type constantTimeHash interface { 555 | hash.Hash 556 | ConstantTimeSum(b []byte) []byte 557 | } 558 | 559 | // cthWrapper wraps any hash.Hash that implements ConstantTimeSum, and replaces 560 | // with that all calls to Sum. It's used to obtain a ConstantTimeSum-based HMAC. 561 | type cthWrapper struct { 562 | h constantTimeHash 563 | } 564 | 565 | func (c *cthWrapper) Size() int { return c.h.Size() } 566 | func (c *cthWrapper) BlockSize() int { return c.h.BlockSize() } 567 | func (c *cthWrapper) Reset() { c.h.Reset() } 568 | func (c *cthWrapper) Write(p []byte) (int, error) { return c.h.Write(p) } 569 | func (c *cthWrapper) Sum(b []byte) []byte { return c.h.ConstantTimeSum(b) } 570 | 571 | func newConstantTimeHash(h func() hash.Hash) func() hash.Hash { 572 | return func() hash.Hash { 573 | return &cthWrapper{h().(constantTimeHash)} 574 | } 575 | } 576 | 577 | // tls10MAC implements the TLS 1.0 MAC function. RFC 2246, Section 6.2.3. 578 | func tls10MAC(h hash.Hash, out, seq, header, data, extra []byte) []byte { 579 | h.Reset() 580 | h.Write(seq) 581 | h.Write(header) 582 | h.Write(data) 583 | res := h.Sum(out) 584 | if extra != nil { 585 | h.Write(extra) 586 | } 587 | return res 588 | } 589 | 590 | func rsaKA(version uint16) keyAgreement { 591 | return rsaKeyAgreement{} 592 | } 593 | 594 | func ecdheECDSAKA(version uint16) keyAgreement { 595 | return &ecdheKeyAgreement{ 596 | isRSA: false, 597 | version: version, 598 | } 599 | } 600 | 601 | func ecdheRSAKA(version uint16) keyAgreement { 602 | return &ecdheKeyAgreement{ 603 | isRSA: true, 604 | version: version, 605 | } 606 | } 607 | 608 | // mutualCipherSuite returns a cipherSuite given a list of supported 609 | // ciphersuites and the id requested by the peer. 610 | func mutualCipherSuite(have []uint16, want uint16) *cipherSuite { 611 | for _, id := range have { 612 | if id == want { 613 | return cipherSuiteByID(id) 614 | } 615 | } 616 | return nil 617 | } 618 | 619 | func cipherSuiteByID(id uint16) *cipherSuite { 620 | for _, cipherSuite := range cipherSuites { 621 | if cipherSuite.id == id { 622 | return cipherSuite 623 | } 624 | } 625 | return nil 626 | } 627 | 628 | func mutualCipherSuiteTLS13(have []uint16, want uint16) *cipherSuiteTLS13 { 629 | for _, id := range have { 630 | if id == want { 631 | return cipherSuiteTLS13ByID(id) 632 | } 633 | } 634 | return nil 635 | } 636 | 637 | func cipherSuiteTLS13ByID(id uint16) *cipherSuiteTLS13 { 638 | for _, cipherSuite := range cipherSuitesTLS13 { 639 | if cipherSuite.id == id { 640 | return cipherSuite 641 | } 642 | } 643 | return nil 644 | } 645 | 646 | // A list of cipher suite IDs that are, or have been, implemented by this 647 | // package. 648 | // 649 | // See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml 650 | const ( 651 | // TLS 1.0 - 1.2 cipher suites. 652 | TLS_RSA_WITH_RC4_128_SHA uint16 = 0x0005 653 | TLS_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x000a 654 | TLS_RSA_WITH_AES_128_CBC_SHA uint16 = 0x002f 655 | TLS_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0035 656 | TLS_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003c 657 | TLS_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009c 658 | TLS_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009d 659 | TLS_ECDHE_ECDSA_WITH_RC4_128_SHA uint16 = 0xc007 660 | TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xc009 661 | TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xc00a 662 | TLS_ECDHE_RSA_WITH_RC4_128_SHA uint16 = 0xc011 663 | TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xc012 664 | TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0xc013 665 | TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0xc014 666 | TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xc023 667 | TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xc027 668 | TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02f 669 | TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02b 670 | TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xc030 671 | TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xc02c 672 | TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcca8 673 | TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcca9 674 | 675 | // TLS 1.3 cipher suites. 676 | TLS_AES_128_GCM_SHA256 uint16 = 0x1301 677 | TLS_AES_256_GCM_SHA384 uint16 = 0x1302 678 | TLS_CHACHA20_POLY1305_SHA256 uint16 = 0x1303 679 | 680 | // TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator 681 | // that the client is doing version fallback. See RFC 7507. 682 | TLS_FALLBACK_SCSV uint16 = 0x5600 683 | 684 | // Legacy names for the corresponding cipher suites with the correct _SHA256 685 | // suffix, retained for backward compatibility. 686 | TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305 = TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 687 | TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 = TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 688 | ) 689 | -------------------------------------------------------------------------------- /handshake_server.go: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE-Go file. 4 | 5 | package reality 6 | 7 | import ( 8 | "context" 9 | "crypto" 10 | "crypto/ecdsa" 11 | "crypto/ed25519" 12 | "crypto/rsa" 13 | "crypto/subtle" 14 | "crypto/x509" 15 | "errors" 16 | "fmt" 17 | "hash" 18 | "io" 19 | "sync/atomic" 20 | "time" 21 | ) 22 | 23 | // serverHandshakeState contains details of a server handshake in progress. 24 | // It's discarded once the handshake has completed. 25 | type serverHandshakeState struct { 26 | c *Conn 27 | ctx context.Context 28 | clientHello *clientHelloMsg 29 | hello *serverHelloMsg 30 | suite *cipherSuite 31 | ecdheOk bool 32 | ecSignOk bool 33 | rsaDecryptOk bool 34 | rsaSignOk bool 35 | sessionState *sessionState 36 | finishedHash finishedHash 37 | masterSecret []byte 38 | cert *Certificate 39 | } 40 | 41 | // serverHandshake performs a TLS handshake as a server. 42 | func (c *Conn) serverHandshake(ctx context.Context) error { 43 | clientHello, err := c.readClientHello(ctx) 44 | if err != nil { 45 | return err 46 | } 47 | 48 | if c.vers == VersionTLS13 { 49 | hs := serverHandshakeStateTLS13{ 50 | c: c, 51 | ctx: ctx, 52 | clientHello: clientHello, 53 | } 54 | return hs.handshake() 55 | } 56 | 57 | hs := serverHandshakeState{ 58 | c: c, 59 | ctx: ctx, 60 | clientHello: clientHello, 61 | } 62 | return hs.handshake() 63 | } 64 | 65 | func (hs *serverHandshakeState) handshake() error { 66 | c := hs.c 67 | 68 | if err := hs.processClientHello(); err != nil { 69 | return err 70 | } 71 | 72 | // For an overview of TLS handshaking, see RFC 5246, Section 7.3. 73 | c.buffering = true 74 | if hs.checkForResumption() { 75 | // The client has included a session ticket and so we do an abbreviated handshake. 76 | c.didResume = true 77 | if err := hs.doResumeHandshake(); err != nil { 78 | return err 79 | } 80 | if err := hs.establishKeys(); err != nil { 81 | return err 82 | } 83 | if err := hs.sendSessionTicket(); err != nil { 84 | return err 85 | } 86 | if err := hs.sendFinished(c.serverFinished[:]); err != nil { 87 | return err 88 | } 89 | if _, err := c.flush(); err != nil { 90 | return err 91 | } 92 | c.clientFinishedIsFirst = false 93 | if err := hs.readFinished(nil); err != nil { 94 | return err 95 | } 96 | } else { 97 | // The client didn't include a session ticket, or it wasn't 98 | // valid so we do a full handshake. 99 | if err := hs.pickCipherSuite(); err != nil { 100 | return err 101 | } 102 | if err := hs.doFullHandshake(); err != nil { 103 | return err 104 | } 105 | if err := hs.establishKeys(); err != nil { 106 | return err 107 | } 108 | if err := hs.readFinished(c.clientFinished[:]); err != nil { 109 | return err 110 | } 111 | c.clientFinishedIsFirst = true 112 | c.buffering = true 113 | if err := hs.sendSessionTicket(); err != nil { 114 | return err 115 | } 116 | if err := hs.sendFinished(nil); err != nil { 117 | return err 118 | } 119 | if _, err := c.flush(); err != nil { 120 | return err 121 | } 122 | } 123 | 124 | c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random) 125 | atomic.StoreUint32(&c.handshakeStatus, 1) 126 | 127 | return nil 128 | } 129 | 130 | // readClientHello reads a ClientHello message and selects the protocol version. 131 | func (c *Conn) readClientHello(ctx context.Context) (*clientHelloMsg, error) { 132 | msg, err := c.readHandshake() 133 | if err != nil { 134 | return nil, err 135 | } 136 | clientHello, ok := msg.(*clientHelloMsg) 137 | if !ok { 138 | c.sendAlert(alertUnexpectedMessage) 139 | return nil, unexpectedMessageError(clientHello, msg) 140 | } 141 | 142 | var configForClient *Config 143 | originalConfig := c.config 144 | if c.config.GetConfigForClient != nil { 145 | chi := clientHelloInfo(ctx, c, clientHello) 146 | if configForClient, err = c.config.GetConfigForClient(chi); err != nil { 147 | c.sendAlert(alertInternalError) 148 | return nil, err 149 | } else if configForClient != nil { 150 | c.config = configForClient 151 | } 152 | } 153 | c.ticketKeys = originalConfig.ticketKeys(configForClient) 154 | 155 | clientVersions := clientHello.supportedVersions 156 | if len(clientHello.supportedVersions) == 0 { 157 | clientVersions = supportedVersionsFromMax(clientHello.vers) 158 | } 159 | c.vers, ok = c.config.mutualVersion(roleServer, clientVersions) 160 | if !ok { 161 | c.sendAlert(alertProtocolVersion) 162 | return nil, fmt.Errorf("tls: client offered only unsupported versions: %x", clientVersions) 163 | } 164 | c.haveVers = true 165 | c.in.version = c.vers 166 | c.out.version = c.vers 167 | 168 | return clientHello, nil 169 | } 170 | 171 | func (hs *serverHandshakeState) processClientHello() error { 172 | c := hs.c 173 | 174 | hs.hello = new(serverHelloMsg) 175 | hs.hello.vers = c.vers 176 | 177 | foundCompression := false 178 | // We only support null compression, so check that the client offered it. 179 | for _, compression := range hs.clientHello.compressionMethods { 180 | if compression == compressionNone { 181 | foundCompression = true 182 | break 183 | } 184 | } 185 | 186 | if !foundCompression { 187 | c.sendAlert(alertHandshakeFailure) 188 | return errors.New("tls: client does not support uncompressed connections") 189 | } 190 | 191 | hs.hello.random = make([]byte, 32) 192 | serverRandom := hs.hello.random 193 | // Downgrade protection canaries. See RFC 8446, Section 4.1.3. 194 | maxVers := c.config.maxSupportedVersion(roleServer) 195 | if maxVers >= VersionTLS12 && c.vers < maxVers || testingOnlyForceDowngradeCanary { 196 | if c.vers == VersionTLS12 { 197 | copy(serverRandom[24:], downgradeCanaryTLS12) 198 | } else { 199 | copy(serverRandom[24:], downgradeCanaryTLS11) 200 | } 201 | serverRandom = serverRandom[:24] 202 | } 203 | _, err := io.ReadFull(c.config.rand(), serverRandom) 204 | if err != nil { 205 | c.sendAlert(alertInternalError) 206 | return err 207 | } 208 | 209 | if len(hs.clientHello.secureRenegotiation) != 0 { 210 | c.sendAlert(alertHandshakeFailure) 211 | return errors.New("tls: initial handshake had non-empty renegotiation extension") 212 | } 213 | 214 | hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported 215 | hs.hello.compressionMethod = compressionNone 216 | if len(hs.clientHello.serverName) > 0 { 217 | c.serverName = hs.clientHello.serverName 218 | } 219 | 220 | selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols) 221 | if err != nil { 222 | c.sendAlert(alertNoApplicationProtocol) 223 | return err 224 | } 225 | hs.hello.alpnProtocol = selectedProto 226 | c.clientProtocol = selectedProto 227 | 228 | hs.cert, err = c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello)) 229 | if err != nil { 230 | if err == errNoCertificates { 231 | c.sendAlert(alertUnrecognizedName) 232 | } else { 233 | c.sendAlert(alertInternalError) 234 | } 235 | return err 236 | } 237 | if hs.clientHello.scts { 238 | hs.hello.scts = hs.cert.SignedCertificateTimestamps 239 | } 240 | 241 | hs.ecdheOk = supportsECDHE(c.config, hs.clientHello.supportedCurves, hs.clientHello.supportedPoints) 242 | 243 | if hs.ecdheOk && len(hs.clientHello.supportedPoints) > 0 { 244 | // Although omitting the ec_point_formats extension is permitted, some 245 | // old OpenSSL version will refuse to handshake if not present. 246 | // 247 | // Per RFC 4492, section 5.1.2, implementations MUST support the 248 | // uncompressed point format. See golang.org/issue/31943. 249 | hs.hello.supportedPoints = []uint8{pointFormatUncompressed} 250 | } 251 | 252 | if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok { 253 | switch priv.Public().(type) { 254 | case *ecdsa.PublicKey: 255 | hs.ecSignOk = true 256 | case ed25519.PublicKey: 257 | hs.ecSignOk = true 258 | case *rsa.PublicKey: 259 | hs.rsaSignOk = true 260 | default: 261 | c.sendAlert(alertInternalError) 262 | return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public()) 263 | } 264 | } 265 | if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok { 266 | switch priv.Public().(type) { 267 | case *rsa.PublicKey: 268 | hs.rsaDecryptOk = true 269 | default: 270 | c.sendAlert(alertInternalError) 271 | return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public()) 272 | } 273 | } 274 | 275 | return nil 276 | } 277 | 278 | // negotiateALPN picks a shared ALPN protocol that both sides support in server 279 | // preference order. If ALPN is not configured or the peer doesn't support it, 280 | // it returns "" and no error. 281 | func negotiateALPN(serverProtos, clientProtos []string) (string, error) { 282 | if len(serverProtos) == 0 || len(clientProtos) == 0 { 283 | return "", nil 284 | } 285 | var http11fallback bool 286 | for _, s := range serverProtos { 287 | for _, c := range clientProtos { 288 | if s == c { 289 | return s, nil 290 | } 291 | if s == "h2" && c == "http/1.1" { 292 | http11fallback = true 293 | } 294 | } 295 | } 296 | // As a special case, let http/1.1 clients connect to h2 servers as if they 297 | // didn't support ALPN. We used not to enforce protocol overlap, so over 298 | // time a number of HTTP servers were configured with only "h2", but 299 | // expected to accept connections from "http/1.1" clients. See Issue 46310. 300 | if http11fallback { 301 | return "", nil 302 | } 303 | return "", fmt.Errorf("tls: client requested unsupported application protocols (%s)", clientProtos) 304 | } 305 | 306 | // supportsECDHE returns whether ECDHE key exchanges can be used with this 307 | // pre-TLS 1.3 client. 308 | func supportsECDHE(c *Config, supportedCurves []CurveID, supportedPoints []uint8) bool { 309 | supportsCurve := false 310 | for _, curve := range supportedCurves { 311 | if c.supportsCurve(curve) { 312 | supportsCurve = true 313 | break 314 | } 315 | } 316 | 317 | supportsPointFormat := false 318 | for _, pointFormat := range supportedPoints { 319 | if pointFormat == pointFormatUncompressed { 320 | supportsPointFormat = true 321 | break 322 | } 323 | } 324 | // Per RFC 8422, Section 5.1.2, if the Supported Point Formats extension is 325 | // missing, uncompressed points are supported. If supportedPoints is empty, 326 | // the extension must be missing, as an empty extension body is rejected by 327 | // the parser. See https://go.dev/issue/49126. 328 | if len(supportedPoints) == 0 { 329 | supportsPointFormat = true 330 | } 331 | 332 | return supportsCurve && supportsPointFormat 333 | } 334 | 335 | func (hs *serverHandshakeState) pickCipherSuite() error { 336 | c := hs.c 337 | 338 | preferenceOrder := cipherSuitesPreferenceOrder 339 | if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) { 340 | preferenceOrder = cipherSuitesPreferenceOrderNoAES 341 | } 342 | 343 | configCipherSuites := c.config.cipherSuites() 344 | preferenceList := make([]uint16, 0, len(configCipherSuites)) 345 | for _, suiteID := range preferenceOrder { 346 | for _, id := range configCipherSuites { 347 | if id == suiteID { 348 | preferenceList = append(preferenceList, id) 349 | break 350 | } 351 | } 352 | } 353 | 354 | hs.suite = selectCipherSuite(preferenceList, hs.clientHello.cipherSuites, hs.cipherSuiteOk) 355 | if hs.suite == nil { 356 | c.sendAlert(alertHandshakeFailure) 357 | return errors.New("tls: no cipher suite supported by both client and server") 358 | } 359 | c.cipherSuite = hs.suite.id 360 | 361 | for _, id := range hs.clientHello.cipherSuites { 362 | if id == TLS_FALLBACK_SCSV { 363 | // The client is doing a fallback connection. See RFC 7507. 364 | if hs.clientHello.vers < c.config.maxSupportedVersion(roleServer) { 365 | c.sendAlert(alertInappropriateFallback) 366 | return errors.New("tls: client using inappropriate protocol fallback") 367 | } 368 | break 369 | } 370 | } 371 | 372 | return nil 373 | } 374 | 375 | func (hs *serverHandshakeState) cipherSuiteOk(c *cipherSuite) bool { 376 | if c.flags&suiteECDHE != 0 { 377 | if !hs.ecdheOk { 378 | return false 379 | } 380 | if c.flags&suiteECSign != 0 { 381 | if !hs.ecSignOk { 382 | return false 383 | } 384 | } else if !hs.rsaSignOk { 385 | return false 386 | } 387 | } else if !hs.rsaDecryptOk { 388 | return false 389 | } 390 | if hs.c.vers < VersionTLS12 && c.flags&suiteTLS12 != 0 { 391 | return false 392 | } 393 | return true 394 | } 395 | 396 | // checkForResumption reports whether we should perform resumption on this connection. 397 | func (hs *serverHandshakeState) checkForResumption() bool { 398 | c := hs.c 399 | 400 | if c.config.SessionTicketsDisabled { 401 | return false 402 | } 403 | 404 | plaintext, usedOldKey := c.decryptTicket(hs.clientHello.sessionTicket) 405 | if plaintext == nil { 406 | return false 407 | } 408 | hs.sessionState = &sessionState{usedOldKey: usedOldKey} 409 | ok := hs.sessionState.unmarshal(plaintext) 410 | if !ok { 411 | return false 412 | } 413 | 414 | createdAt := time.Unix(int64(hs.sessionState.createdAt), 0) 415 | if c.config.time().Sub(createdAt) > maxSessionTicketLifetime { 416 | return false 417 | } 418 | 419 | // Never resume a session for a different TLS version. 420 | if c.vers != hs.sessionState.vers { 421 | return false 422 | } 423 | 424 | cipherSuiteOk := false 425 | // Check that the client is still offering the ciphersuite in the session. 426 | for _, id := range hs.clientHello.cipherSuites { 427 | if id == hs.sessionState.cipherSuite { 428 | cipherSuiteOk = true 429 | break 430 | } 431 | } 432 | if !cipherSuiteOk { 433 | return false 434 | } 435 | 436 | // Check that we also support the ciphersuite from the session. 437 | hs.suite = selectCipherSuite([]uint16{hs.sessionState.cipherSuite}, 438 | c.config.cipherSuites(), hs.cipherSuiteOk) 439 | if hs.suite == nil { 440 | return false 441 | } 442 | 443 | sessionHasClientCerts := len(hs.sessionState.certificates) != 0 444 | needClientCerts := requiresClientCert(c.config.ClientAuth) 445 | if needClientCerts && !sessionHasClientCerts { 446 | return false 447 | } 448 | if sessionHasClientCerts && c.config.ClientAuth == NoClientCert { 449 | return false 450 | } 451 | 452 | return true 453 | } 454 | 455 | func (hs *serverHandshakeState) doResumeHandshake() error { 456 | c := hs.c 457 | 458 | hs.hello.cipherSuite = hs.suite.id 459 | c.cipherSuite = hs.suite.id 460 | // We echo the client's session ID in the ServerHello to let it know 461 | // that we're doing a resumption. 462 | hs.hello.sessionId = hs.clientHello.sessionId 463 | hs.hello.ticketSupported = hs.sessionState.usedOldKey 464 | hs.finishedHash = newFinishedHash(c.vers, hs.suite) 465 | hs.finishedHash.discardHandshakeBuffer() 466 | hs.finishedHash.Write(hs.clientHello.marshal()) 467 | hs.finishedHash.Write(hs.hello.marshal()) 468 | if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { 469 | return err 470 | } 471 | 472 | if err := c.processCertsFromClient(Certificate{ 473 | Certificate: hs.sessionState.certificates, 474 | }); err != nil { 475 | return err 476 | } 477 | 478 | if c.config.VerifyConnection != nil { 479 | if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 480 | c.sendAlert(alertBadCertificate) 481 | return err 482 | } 483 | } 484 | 485 | hs.masterSecret = hs.sessionState.masterSecret 486 | 487 | return nil 488 | } 489 | 490 | func (hs *serverHandshakeState) doFullHandshake() error { 491 | c := hs.c 492 | 493 | if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 { 494 | hs.hello.ocspStapling = true 495 | } 496 | 497 | hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled 498 | hs.hello.cipherSuite = hs.suite.id 499 | 500 | hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite) 501 | if c.config.ClientAuth == NoClientCert { 502 | // No need to keep a full record of the handshake if client 503 | // certificates won't be used. 504 | hs.finishedHash.discardHandshakeBuffer() 505 | } 506 | hs.finishedHash.Write(hs.clientHello.marshal()) 507 | hs.finishedHash.Write(hs.hello.marshal()) 508 | if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { 509 | return err 510 | } 511 | 512 | certMsg := new(certificateMsg) 513 | certMsg.certificates = hs.cert.Certificate 514 | hs.finishedHash.Write(certMsg.marshal()) 515 | if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil { 516 | return err 517 | } 518 | 519 | if hs.hello.ocspStapling { 520 | certStatus := new(certificateStatusMsg) 521 | certStatus.response = hs.cert.OCSPStaple 522 | hs.finishedHash.Write(certStatus.marshal()) 523 | if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil { 524 | return err 525 | } 526 | } 527 | 528 | keyAgreement := hs.suite.ka(c.vers) 529 | skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello) 530 | if err != nil { 531 | c.sendAlert(alertHandshakeFailure) 532 | return err 533 | } 534 | if skx != nil { 535 | hs.finishedHash.Write(skx.marshal()) 536 | if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil { 537 | return err 538 | } 539 | } 540 | 541 | var certReq *certificateRequestMsg 542 | if c.config.ClientAuth >= RequestClientCert { 543 | // Request a client certificate 544 | certReq = new(certificateRequestMsg) 545 | certReq.certificateTypes = []byte{ 546 | byte(certTypeRSASign), 547 | byte(certTypeECDSASign), 548 | } 549 | if c.vers >= VersionTLS12 { 550 | certReq.hasSignatureAlgorithm = true 551 | certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms() 552 | } 553 | 554 | // An empty list of certificateAuthorities signals to 555 | // the client that it may send any certificate in response 556 | // to our request. When we know the CAs we trust, then 557 | // we can send them down, so that the client can choose 558 | // an appropriate certificate to give to us. 559 | if c.config.ClientCAs != nil { 560 | certReq.certificateAuthorities = c.config.ClientCAs.Subjects() 561 | } 562 | hs.finishedHash.Write(certReq.marshal()) 563 | if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil { 564 | return err 565 | } 566 | } 567 | 568 | helloDone := new(serverHelloDoneMsg) 569 | hs.finishedHash.Write(helloDone.marshal()) 570 | if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil { 571 | return err 572 | } 573 | 574 | if _, err := c.flush(); err != nil { 575 | return err 576 | } 577 | 578 | var pub crypto.PublicKey // public key for client auth, if any 579 | 580 | msg, err := c.readHandshake() 581 | if err != nil { 582 | return err 583 | } 584 | 585 | // If we requested a client certificate, then the client must send a 586 | // certificate message, even if it's empty. 587 | if c.config.ClientAuth >= RequestClientCert { 588 | certMsg, ok := msg.(*certificateMsg) 589 | if !ok { 590 | c.sendAlert(alertUnexpectedMessage) 591 | return unexpectedMessageError(certMsg, msg) 592 | } 593 | hs.finishedHash.Write(certMsg.marshal()) 594 | 595 | if err := c.processCertsFromClient(Certificate{ 596 | Certificate: certMsg.certificates, 597 | }); err != nil { 598 | return err 599 | } 600 | if len(certMsg.certificates) != 0 { 601 | pub = c.peerCertificates[0].PublicKey 602 | } 603 | 604 | msg, err = c.readHandshake() 605 | if err != nil { 606 | return err 607 | } 608 | } 609 | if c.config.VerifyConnection != nil { 610 | if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 611 | c.sendAlert(alertBadCertificate) 612 | return err 613 | } 614 | } 615 | 616 | // Get client key exchange 617 | ckx, ok := msg.(*clientKeyExchangeMsg) 618 | if !ok { 619 | c.sendAlert(alertUnexpectedMessage) 620 | return unexpectedMessageError(ckx, msg) 621 | } 622 | hs.finishedHash.Write(ckx.marshal()) 623 | 624 | preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers) 625 | if err != nil { 626 | c.sendAlert(alertHandshakeFailure) 627 | return err 628 | } 629 | hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random) 630 | if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil { 631 | c.sendAlert(alertInternalError) 632 | return err 633 | } 634 | 635 | // If we received a client cert in response to our certificate request message, 636 | // the client will send us a certificateVerifyMsg immediately after the 637 | // clientKeyExchangeMsg. This message is a digest of all preceding 638 | // handshake-layer messages that is signed using the private key corresponding 639 | // to the client's certificate. This allows us to verify that the client is in 640 | // possession of the private key of the certificate. 641 | if len(c.peerCertificates) > 0 { 642 | msg, err = c.readHandshake() 643 | if err != nil { 644 | return err 645 | } 646 | certVerify, ok := msg.(*certificateVerifyMsg) 647 | if !ok { 648 | c.sendAlert(alertUnexpectedMessage) 649 | return unexpectedMessageError(certVerify, msg) 650 | } 651 | 652 | var sigType uint8 653 | var sigHash crypto.Hash 654 | if c.vers >= VersionTLS12 { 655 | if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, certReq.supportedSignatureAlgorithms) { 656 | c.sendAlert(alertIllegalParameter) 657 | return errors.New("tls: client certificate used with invalid signature algorithm") 658 | } 659 | sigType, sigHash, err = typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) 660 | if err != nil { 661 | return c.sendAlert(alertInternalError) 662 | } 663 | } else { 664 | sigType, sigHash, err = legacyTypeAndHashFromPublicKey(pub) 665 | if err != nil { 666 | c.sendAlert(alertIllegalParameter) 667 | return err 668 | } 669 | } 670 | 671 | signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash, hs.masterSecret) 672 | if err := verifyHandshakeSignature(sigType, pub, sigHash, signed, certVerify.signature); err != nil { 673 | c.sendAlert(alertDecryptError) 674 | return errors.New("tls: invalid signature by the client certificate: " + err.Error()) 675 | } 676 | 677 | hs.finishedHash.Write(certVerify.marshal()) 678 | } 679 | 680 | hs.finishedHash.discardHandshakeBuffer() 681 | 682 | return nil 683 | } 684 | 685 | func (hs *serverHandshakeState) establishKeys() error { 686 | c := hs.c 687 | 688 | clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := 689 | keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) 690 | 691 | var clientCipher, serverCipher any 692 | var clientHash, serverHash hash.Hash 693 | 694 | if hs.suite.aead == nil { 695 | clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */) 696 | clientHash = hs.suite.mac(clientMAC) 697 | serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */) 698 | serverHash = hs.suite.mac(serverMAC) 699 | } else { 700 | clientCipher = hs.suite.aead(clientKey, clientIV) 701 | serverCipher = hs.suite.aead(serverKey, serverIV) 702 | } 703 | 704 | c.in.prepareCipherSpec(c.vers, clientCipher, clientHash) 705 | c.out.prepareCipherSpec(c.vers, serverCipher, serverHash) 706 | 707 | return nil 708 | } 709 | 710 | func (hs *serverHandshakeState) readFinished(out []byte) error { 711 | c := hs.c 712 | 713 | if err := c.readChangeCipherSpec(); err != nil { 714 | return err 715 | } 716 | 717 | msg, err := c.readHandshake() 718 | if err != nil { 719 | return err 720 | } 721 | clientFinished, ok := msg.(*finishedMsg) 722 | if !ok { 723 | c.sendAlert(alertUnexpectedMessage) 724 | return unexpectedMessageError(clientFinished, msg) 725 | } 726 | 727 | verify := hs.finishedHash.clientSum(hs.masterSecret) 728 | if len(verify) != len(clientFinished.verifyData) || 729 | subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 { 730 | c.sendAlert(alertHandshakeFailure) 731 | return errors.New("tls: client's Finished message is incorrect") 732 | } 733 | 734 | hs.finishedHash.Write(clientFinished.marshal()) 735 | copy(out, verify) 736 | return nil 737 | } 738 | 739 | func (hs *serverHandshakeState) sendSessionTicket() error { 740 | // ticketSupported is set in a resumption handshake if the 741 | // ticket from the client was encrypted with an old session 742 | // ticket key and thus a refreshed ticket should be sent. 743 | if !hs.hello.ticketSupported { 744 | return nil 745 | } 746 | 747 | c := hs.c 748 | m := new(newSessionTicketMsg) 749 | 750 | createdAt := uint64(c.config.time().Unix()) 751 | if hs.sessionState != nil { 752 | // If this is re-wrapping an old key, then keep 753 | // the original time it was created. 754 | createdAt = hs.sessionState.createdAt 755 | } 756 | 757 | var certsFromClient [][]byte 758 | for _, cert := range c.peerCertificates { 759 | certsFromClient = append(certsFromClient, cert.Raw) 760 | } 761 | state := sessionState{ 762 | vers: c.vers, 763 | cipherSuite: hs.suite.id, 764 | createdAt: createdAt, 765 | masterSecret: hs.masterSecret, 766 | certificates: certsFromClient, 767 | } 768 | var err error 769 | m.ticket, err = c.encryptTicket(state.marshal()) 770 | if err != nil { 771 | return err 772 | } 773 | 774 | hs.finishedHash.Write(m.marshal()) 775 | if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil { 776 | return err 777 | } 778 | 779 | return nil 780 | } 781 | 782 | func (hs *serverHandshakeState) sendFinished(out []byte) error { 783 | c := hs.c 784 | 785 | if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil { 786 | return err 787 | } 788 | 789 | finished := new(finishedMsg) 790 | finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret) 791 | hs.finishedHash.Write(finished.marshal()) 792 | if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil { 793 | return err 794 | } 795 | 796 | copy(out, finished.verifyData) 797 | 798 | return nil 799 | } 800 | 801 | // processCertsFromClient takes a chain of client certificates either from a 802 | // Certificates message or from a sessionState and verifies them. It returns 803 | // the public key of the leaf certificate. 804 | func (c *Conn) processCertsFromClient(certificate Certificate) error { 805 | certificates := certificate.Certificate 806 | certs := make([]*x509.Certificate, len(certificates)) 807 | var err error 808 | for i, asn1Data := range certificates { 809 | if certs[i], err = x509.ParseCertificate(asn1Data); err != nil { 810 | c.sendAlert(alertBadCertificate) 811 | return errors.New("tls: failed to parse client certificate: " + err.Error()) 812 | } 813 | } 814 | 815 | if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) { 816 | c.sendAlert(alertBadCertificate) 817 | return errors.New("tls: client didn't provide a certificate") 818 | } 819 | 820 | if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 { 821 | opts := x509.VerifyOptions{ 822 | Roots: c.config.ClientCAs, 823 | CurrentTime: c.config.time(), 824 | Intermediates: x509.NewCertPool(), 825 | KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, 826 | } 827 | 828 | for _, cert := range certs[1:] { 829 | opts.Intermediates.AddCert(cert) 830 | } 831 | 832 | chains, err := certs[0].Verify(opts) 833 | if err != nil { 834 | c.sendAlert(alertBadCertificate) 835 | return errors.New("tls: failed to verify client certificate: " + err.Error()) 836 | } 837 | 838 | c.verifiedChains = chains 839 | } 840 | 841 | c.peerCertificates = certs 842 | c.ocspResponse = certificate.OCSPStaple 843 | c.scts = certificate.SignedCertificateTimestamps 844 | 845 | if len(certs) > 0 { 846 | switch certs[0].PublicKey.(type) { 847 | case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey: 848 | default: 849 | c.sendAlert(alertUnsupportedCertificate) 850 | return fmt.Errorf("tls: client certificate contains an unsupported public key of type %T", certs[0].PublicKey) 851 | } 852 | } 853 | 854 | if c.config.VerifyPeerCertificate != nil { 855 | if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil { 856 | c.sendAlert(alertBadCertificate) 857 | return err 858 | } 859 | } 860 | 861 | return nil 862 | } 863 | 864 | func clientHelloInfo(ctx context.Context, c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo { 865 | supportedVersions := clientHello.supportedVersions 866 | if len(clientHello.supportedVersions) == 0 { 867 | supportedVersions = supportedVersionsFromMax(clientHello.vers) 868 | } 869 | 870 | return &ClientHelloInfo{ 871 | CipherSuites: clientHello.cipherSuites, 872 | ServerName: clientHello.serverName, 873 | SupportedCurves: clientHello.supportedCurves, 874 | SupportedPoints: clientHello.supportedPoints, 875 | SignatureSchemes: clientHello.supportedSignatureAlgorithms, 876 | SupportedProtos: clientHello.alpnProtocols, 877 | SupportedVersions: supportedVersions, 878 | Conn: c.conn, 879 | config: c.config, 880 | ctx: ctx, 881 | } 882 | } 883 | -------------------------------------------------------------------------------- /handshake_server_tls13.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE-Go file. 4 | 5 | package reality 6 | 7 | import ( 8 | "bytes" 9 | "context" 10 | "crypto" 11 | "crypto/ed25519" 12 | "crypto/hmac" 13 | "crypto/rsa" 14 | "crypto/sha512" 15 | "crypto/x509" 16 | "encoding/binary" 17 | "errors" 18 | "hash" 19 | "io" 20 | "math/big" 21 | "sync/atomic" 22 | "time" 23 | ) 24 | 25 | // maxClientPSKIdentities is the number of client PSK identities the server will 26 | // attempt to validate. It will ignore the rest not to let cheap ClientHello 27 | // messages cause too much work in session ticket decryption attempts. 28 | const maxClientPSKIdentities = 5 29 | 30 | type serverHandshakeStateTLS13 struct { 31 | c *Conn 32 | ctx context.Context 33 | clientHello *clientHelloMsg 34 | hello *serverHelloMsg 35 | sentDummyCCS bool 36 | usingPSK bool 37 | suite *cipherSuiteTLS13 38 | cert *Certificate 39 | sigAlg SignatureScheme 40 | earlySecret []byte 41 | sharedKey []byte 42 | handshakeSecret []byte 43 | masterSecret []byte 44 | trafficSecret []byte // client_application_traffic_secret_0 45 | transcript hash.Hash 46 | clientFinished []byte 47 | } 48 | 49 | func (hs *serverHandshakeStateTLS13) handshake() error { 50 | c := hs.c 51 | 52 | if needFIPS() { 53 | return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode") 54 | } 55 | 56 | // For an overview of the TLS 1.3 handshake, see RFC 8446, Section 2. 57 | /* 58 | if err := hs.processClientHello(); err != nil { 59 | return err 60 | } 61 | */ 62 | { 63 | hs.suite = cipherSuiteTLS13ByID(hs.hello.cipherSuite) 64 | c.cipherSuite = hs.suite.id 65 | hs.transcript = hs.suite.hash.New() 66 | /* 67 | // For Go 1.20 TLS 68 | key, _ := generateECDHEKey(c.config.rand(), X25519) 69 | copy(hs.hello.serverShare.data, key.PublicKey().Bytes()) 70 | peerKey, _ := key.Curve().NewPublicKey(hs.clientHello.keyShares[hs.clientHello.keyShares[0].group].data) 71 | hs.sharedKey, _ = key.ECDH(peerKey) 72 | */ 73 | // For Go 1.19 TLS 74 | params, _ := generateECDHEParameters(c.config.rand(), X25519) 75 | copy(hs.hello.serverShare.data, params.PublicKey()) 76 | hs.sharedKey = params.SharedKey(hs.clientHello.keyShares[hs.clientHello.keyShares[0].group].data) 77 | 78 | c.serverName = hs.clientHello.serverName 79 | } 80 | /* 81 | if err := hs.checkForResumption(); err != nil { 82 | return err 83 | } 84 | if err := hs.pickCertificate(); err != nil { 85 | return err 86 | } 87 | */ 88 | { 89 | certificate := x509.Certificate{SerialNumber: &big.Int{}} 90 | pub, priv, _ := ed25519.GenerateKey(c.config.rand()) 91 | signedCert, _ := x509.CreateCertificate(c.config.rand(), &certificate, &certificate, pub, priv) 92 | 93 | h := hmac.New(sha512.New, c.AuthKey) 94 | h.Write(pub) 95 | h.Sum(signedCert[:len(signedCert)-64]) 96 | 97 | hs.cert = &Certificate{ 98 | Certificate: [][]byte{signedCert}, 99 | PrivateKey: priv, 100 | } 101 | hs.sigAlg = Ed25519 102 | } 103 | c.buffering = true 104 | if err := hs.sendServerParameters(); err != nil { 105 | return err 106 | } 107 | if err := hs.sendServerCertificate(); err != nil { 108 | return err 109 | } 110 | if err := hs.sendServerFinished(); err != nil { 111 | return err 112 | } 113 | if hs.c.out.handshakeLen[6] != 0 { 114 | if _, err := c.writeRecord(recordTypeHandshake, []byte{typeNewSessionTicket}); err != nil { 115 | return err 116 | } 117 | } 118 | // Note that at this point we could start sending application data without 119 | // waiting for the client's second flight, but the application might not 120 | // expect the lack of replay protection of the ClientHello parameters. 121 | if _, err := c.flush(); err != nil { 122 | return err 123 | } 124 | if err := hs.readClientCertificate(); err != nil { 125 | return err 126 | } 127 | if err := hs.readClientFinished(); err != nil { 128 | return err 129 | } 130 | 131 | atomic.StoreUint32(&c.handshakeStatus, 1) 132 | 133 | return nil 134 | } 135 | 136 | func (hs *serverHandshakeStateTLS13) processClientHello() error { 137 | c := hs.c 138 | 139 | hs.hello = new(serverHelloMsg) 140 | 141 | // TLS 1.3 froze the ServerHello.legacy_version field, and uses 142 | // supported_versions instead. See RFC 8446, sections 4.1.3 and 4.2.1. 143 | hs.hello.vers = VersionTLS12 144 | hs.hello.supportedVersion = c.vers 145 | 146 | if len(hs.clientHello.supportedVersions) == 0 { 147 | c.sendAlert(alertIllegalParameter) 148 | return errors.New("tls: client used the legacy version field to negotiate TLS 1.3") 149 | } 150 | 151 | // Abort if the client is doing a fallback and landing lower than what we 152 | // support. See RFC 7507, which however does not specify the interaction 153 | // with supported_versions. The only difference is that with 154 | // supported_versions a client has a chance to attempt a [TLS 1.2, TLS 1.4] 155 | // handshake in case TLS 1.3 is broken but 1.2 is not. Alas, in that case, 156 | // it will have to drop the TLS_FALLBACK_SCSV protection if it falls back to 157 | // TLS 1.2, because a TLS 1.3 server would abort here. The situation before 158 | // supported_versions was not better because there was just no way to do a 159 | // TLS 1.4 handshake without risking the server selecting TLS 1.3. 160 | for _, id := range hs.clientHello.cipherSuites { 161 | if id == TLS_FALLBACK_SCSV { 162 | // Use c.vers instead of max(supported_versions) because an attacker 163 | // could defeat this by adding an arbitrary high version otherwise. 164 | if c.vers < c.config.maxSupportedVersion(roleServer) { 165 | c.sendAlert(alertInappropriateFallback) 166 | return errors.New("tls: client using inappropriate protocol fallback") 167 | } 168 | break 169 | } 170 | } 171 | 172 | if len(hs.clientHello.compressionMethods) != 1 || 173 | hs.clientHello.compressionMethods[0] != compressionNone { 174 | c.sendAlert(alertIllegalParameter) 175 | return errors.New("tls: TLS 1.3 client supports illegal compression methods") 176 | } 177 | 178 | hs.hello.random = make([]byte, 32) 179 | if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil { 180 | c.sendAlert(alertInternalError) 181 | return err 182 | } 183 | 184 | if len(hs.clientHello.secureRenegotiation) != 0 { 185 | c.sendAlert(alertHandshakeFailure) 186 | return errors.New("tls: initial handshake had non-empty renegotiation extension") 187 | } 188 | 189 | if hs.clientHello.earlyData { 190 | // See RFC 8446, Section 4.2.10 for the complicated behavior required 191 | // here. The scenario is that a different server at our address offered 192 | // to accept early data in the past, which we can't handle. For now, all 193 | // 0-RTT enabled session tickets need to expire before a Go server can 194 | // replace a server or join a pool. That's the same requirement that 195 | // applies to mixing or replacing with any TLS 1.2 server. 196 | c.sendAlert(alertUnsupportedExtension) 197 | return errors.New("tls: client sent unexpected early data") 198 | } 199 | 200 | hs.hello.sessionId = hs.clientHello.sessionId 201 | hs.hello.compressionMethod = compressionNone 202 | 203 | preferenceList := defaultCipherSuitesTLS13 204 | if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) { 205 | preferenceList = defaultCipherSuitesTLS13NoAES 206 | } 207 | for _, suiteID := range preferenceList { 208 | hs.suite = mutualCipherSuiteTLS13(hs.clientHello.cipherSuites, suiteID) 209 | if hs.suite != nil { 210 | break 211 | } 212 | } 213 | if hs.suite == nil { 214 | c.sendAlert(alertHandshakeFailure) 215 | return errors.New("tls: no cipher suite supported by both client and server") 216 | } 217 | c.cipherSuite = hs.suite.id 218 | hs.hello.cipherSuite = hs.suite.id 219 | hs.transcript = hs.suite.hash.New() 220 | 221 | // Pick the ECDHE group in server preference order, but give priority to 222 | // groups with a key share, to avoid a HelloRetryRequest round-trip. 223 | var selectedGroup CurveID 224 | var clientKeyShare *keyShare 225 | GroupSelection: 226 | for _, preferredGroup := range c.config.curvePreferences() { 227 | for _, ks := range hs.clientHello.keyShares { 228 | if ks.group == preferredGroup { 229 | selectedGroup = ks.group 230 | clientKeyShare = &ks 231 | break GroupSelection 232 | } 233 | } 234 | if selectedGroup != 0 { 235 | continue 236 | } 237 | for _, group := range hs.clientHello.supportedCurves { 238 | if group == preferredGroup { 239 | selectedGroup = group 240 | break 241 | } 242 | } 243 | } 244 | if selectedGroup == 0 { 245 | c.sendAlert(alertHandshakeFailure) 246 | return errors.New("tls: no ECDHE curve supported by both client and server") 247 | } 248 | if clientKeyShare == nil { 249 | if err := hs.doHelloRetryRequest(selectedGroup); err != nil { 250 | return err 251 | } 252 | clientKeyShare = &hs.clientHello.keyShares[0] 253 | } 254 | 255 | if _, ok := curveForCurveID(selectedGroup); selectedGroup != X25519 && !ok { 256 | c.sendAlert(alertInternalError) 257 | return errors.New("tls: CurvePreferences includes unsupported curve") 258 | } 259 | params, err := generateECDHEParameters(c.config.rand(), selectedGroup) 260 | if err != nil { 261 | c.sendAlert(alertInternalError) 262 | return err 263 | } 264 | hs.hello.serverShare = keyShare{group: selectedGroup, data: params.PublicKey()} 265 | hs.sharedKey = params.SharedKey(clientKeyShare.data) 266 | if hs.sharedKey == nil { 267 | c.sendAlert(alertIllegalParameter) 268 | return errors.New("tls: invalid client key share") 269 | } 270 | 271 | c.serverName = hs.clientHello.serverName 272 | return nil 273 | } 274 | 275 | func (hs *serverHandshakeStateTLS13) checkForResumption() error { 276 | c := hs.c 277 | 278 | if c.config.SessionTicketsDisabled { 279 | return nil 280 | } 281 | 282 | modeOK := false 283 | for _, mode := range hs.clientHello.pskModes { 284 | if mode == pskModeDHE { 285 | modeOK = true 286 | break 287 | } 288 | } 289 | if !modeOK { 290 | return nil 291 | } 292 | 293 | if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) { 294 | c.sendAlert(alertIllegalParameter) 295 | return errors.New("tls: invalid or missing PSK binders") 296 | } 297 | if len(hs.clientHello.pskIdentities) == 0 { 298 | return nil 299 | } 300 | 301 | for i, identity := range hs.clientHello.pskIdentities { 302 | if i >= maxClientPSKIdentities { 303 | break 304 | } 305 | 306 | plaintext, _ := c.decryptTicket(identity.label) 307 | if plaintext == nil { 308 | continue 309 | } 310 | sessionState := new(sessionStateTLS13) 311 | if ok := sessionState.unmarshal(plaintext); !ok { 312 | continue 313 | } 314 | 315 | createdAt := time.Unix(int64(sessionState.createdAt), 0) 316 | if c.config.time().Sub(createdAt) > maxSessionTicketLifetime { 317 | continue 318 | } 319 | 320 | // We don't check the obfuscated ticket age because it's affected by 321 | // clock skew and it's only a freshness signal useful for shrinking the 322 | // window for replay attacks, which don't affect us as we don't do 0-RTT. 323 | 324 | pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite) 325 | if pskSuite == nil || pskSuite.hash != hs.suite.hash { 326 | continue 327 | } 328 | 329 | // PSK connections don't re-establish client certificates, but carry 330 | // them over in the session ticket. Ensure the presence of client certs 331 | // in the ticket is consistent with the configured requirements. 332 | sessionHasClientCerts := len(sessionState.certificate.Certificate) != 0 333 | needClientCerts := requiresClientCert(c.config.ClientAuth) 334 | if needClientCerts && !sessionHasClientCerts { 335 | continue 336 | } 337 | if sessionHasClientCerts && c.config.ClientAuth == NoClientCert { 338 | continue 339 | } 340 | 341 | psk := hs.suite.expandLabel(sessionState.resumptionSecret, "resumption", 342 | nil, hs.suite.hash.Size()) 343 | hs.earlySecret = hs.suite.extract(psk, nil) 344 | binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil) 345 | // Clone the transcript in case a HelloRetryRequest was recorded. 346 | transcript := cloneHash(hs.transcript, hs.suite.hash) 347 | if transcript == nil { 348 | c.sendAlert(alertInternalError) 349 | return errors.New("tls: internal error: failed to clone hash") 350 | } 351 | transcript.Write(hs.clientHello.marshalWithoutBinders()) 352 | pskBinder := hs.suite.finishedHash(binderKey, transcript) 353 | if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) { 354 | c.sendAlert(alertDecryptError) 355 | return errors.New("tls: invalid PSK binder") 356 | } 357 | 358 | c.didResume = true 359 | if err := c.processCertsFromClient(sessionState.certificate); err != nil { 360 | return err 361 | } 362 | 363 | hs.hello.selectedIdentityPresent = true 364 | hs.hello.selectedIdentity = uint16(i) 365 | hs.usingPSK = true 366 | return nil 367 | } 368 | 369 | return nil 370 | } 371 | 372 | // cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler 373 | // interfaces implemented by standard library hashes to clone the state of in 374 | // to a new instance of h. It returns nil if the operation fails. 375 | func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash { 376 | // Recreate the interface to avoid importing encoding. 377 | type binaryMarshaler interface { 378 | MarshalBinary() (data []byte, err error) 379 | UnmarshalBinary(data []byte) error 380 | } 381 | marshaler, ok := in.(binaryMarshaler) 382 | if !ok { 383 | return nil 384 | } 385 | state, err := marshaler.MarshalBinary() 386 | if err != nil { 387 | return nil 388 | } 389 | out := h.New() 390 | unmarshaler, ok := out.(binaryMarshaler) 391 | if !ok { 392 | return nil 393 | } 394 | if err := unmarshaler.UnmarshalBinary(state); err != nil { 395 | return nil 396 | } 397 | return out 398 | } 399 | 400 | func (hs *serverHandshakeStateTLS13) pickCertificate() error { 401 | c := hs.c 402 | 403 | // Only one of PSK and certificates are used at a time. 404 | if hs.usingPSK { 405 | return nil 406 | } 407 | 408 | // signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3. 409 | if len(hs.clientHello.supportedSignatureAlgorithms) == 0 { 410 | return c.sendAlert(alertMissingExtension) 411 | } 412 | 413 | certificate, err := c.config.getCertificate(clientHelloInfo(hs.ctx, c, hs.clientHello)) 414 | if err != nil { 415 | if err == errNoCertificates { 416 | c.sendAlert(alertUnrecognizedName) 417 | } else { 418 | c.sendAlert(alertInternalError) 419 | } 420 | return err 421 | } 422 | hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms) 423 | if err != nil { 424 | // getCertificate returned a certificate that is unsupported or 425 | // incompatible with the client's signature algorithms. 426 | c.sendAlert(alertHandshakeFailure) 427 | return err 428 | } 429 | hs.cert = certificate 430 | 431 | return nil 432 | } 433 | 434 | // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility 435 | // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. 436 | func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error { 437 | if hs.sentDummyCCS { 438 | return nil 439 | } 440 | hs.sentDummyCCS = true 441 | 442 | _, err := hs.c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) 443 | return err 444 | } 445 | 446 | func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error { 447 | c := hs.c 448 | 449 | // The first ClientHello gets double-hashed into the transcript upon a 450 | // HelloRetryRequest. See RFC 8446, Section 4.4.1. 451 | hs.transcript.Write(hs.clientHello.marshal()) 452 | chHash := hs.transcript.Sum(nil) 453 | hs.transcript.Reset() 454 | hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) 455 | hs.transcript.Write(chHash) 456 | 457 | helloRetryRequest := &serverHelloMsg{ 458 | vers: hs.hello.vers, 459 | random: helloRetryRequestRandom, 460 | sessionId: hs.hello.sessionId, 461 | cipherSuite: hs.hello.cipherSuite, 462 | compressionMethod: hs.hello.compressionMethod, 463 | supportedVersion: hs.hello.supportedVersion, 464 | selectedGroup: selectedGroup, 465 | } 466 | 467 | hs.transcript.Write(helloRetryRequest.marshal()) 468 | if _, err := c.writeRecord(recordTypeHandshake, helloRetryRequest.marshal()); err != nil { 469 | return err 470 | } 471 | 472 | if err := hs.sendDummyChangeCipherSpec(); err != nil { 473 | return err 474 | } 475 | 476 | msg, err := c.readHandshake() 477 | if err != nil { 478 | return err 479 | } 480 | 481 | clientHello, ok := msg.(*clientHelloMsg) 482 | if !ok { 483 | c.sendAlert(alertUnexpectedMessage) 484 | return unexpectedMessageError(clientHello, msg) 485 | } 486 | 487 | if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup { 488 | c.sendAlert(alertIllegalParameter) 489 | return errors.New("tls: client sent invalid key share in second ClientHello") 490 | } 491 | 492 | if clientHello.earlyData { 493 | c.sendAlert(alertIllegalParameter) 494 | return errors.New("tls: client indicated early data in second ClientHello") 495 | } 496 | 497 | if illegalClientHelloChange(clientHello, hs.clientHello) { 498 | c.sendAlert(alertIllegalParameter) 499 | return errors.New("tls: client illegally modified second ClientHello") 500 | } 501 | 502 | hs.clientHello = clientHello 503 | return nil 504 | } 505 | 506 | // illegalClientHelloChange reports whether the two ClientHello messages are 507 | // different, with the exception of the changes allowed before and after a 508 | // HelloRetryRequest. See RFC 8446, Section 4.1.2. 509 | func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool { 510 | if len(ch.supportedVersions) != len(ch1.supportedVersions) || 511 | len(ch.cipherSuites) != len(ch1.cipherSuites) || 512 | len(ch.supportedCurves) != len(ch1.supportedCurves) || 513 | len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) || 514 | len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) || 515 | len(ch.alpnProtocols) != len(ch1.alpnProtocols) { 516 | return true 517 | } 518 | for i := range ch.supportedVersions { 519 | if ch.supportedVersions[i] != ch1.supportedVersions[i] { 520 | return true 521 | } 522 | } 523 | for i := range ch.cipherSuites { 524 | if ch.cipherSuites[i] != ch1.cipherSuites[i] { 525 | return true 526 | } 527 | } 528 | for i := range ch.supportedCurves { 529 | if ch.supportedCurves[i] != ch1.supportedCurves[i] { 530 | return true 531 | } 532 | } 533 | for i := range ch.supportedSignatureAlgorithms { 534 | if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] { 535 | return true 536 | } 537 | } 538 | for i := range ch.supportedSignatureAlgorithmsCert { 539 | if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] { 540 | return true 541 | } 542 | } 543 | for i := range ch.alpnProtocols { 544 | if ch.alpnProtocols[i] != ch1.alpnProtocols[i] { 545 | return true 546 | } 547 | } 548 | return ch.vers != ch1.vers || 549 | !bytes.Equal(ch.random, ch1.random) || 550 | !bytes.Equal(ch.sessionId, ch1.sessionId) || 551 | !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) || 552 | ch.serverName != ch1.serverName || 553 | ch.ocspStapling != ch1.ocspStapling || 554 | !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) || 555 | ch.ticketSupported != ch1.ticketSupported || 556 | !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) || 557 | ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported || 558 | !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) || 559 | ch.scts != ch1.scts || 560 | !bytes.Equal(ch.cookie, ch1.cookie) || 561 | !bytes.Equal(ch.pskModes, ch1.pskModes) 562 | } 563 | 564 | func (hs *serverHandshakeStateTLS13) sendServerParameters() error { 565 | c := hs.c 566 | 567 | hs.transcript.Write(hs.clientHello.marshal()) 568 | hs.transcript.Write(hs.hello.marshal()) 569 | if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil { 570 | return err 571 | } 572 | 573 | if err := hs.sendDummyChangeCipherSpec(); err != nil { 574 | return err 575 | } 576 | 577 | earlySecret := hs.earlySecret 578 | if earlySecret == nil { 579 | earlySecret = hs.suite.extract(nil, nil) 580 | } 581 | hs.handshakeSecret = hs.suite.extract(hs.sharedKey, 582 | hs.suite.deriveSecret(earlySecret, "derived", nil)) 583 | 584 | clientSecret := hs.suite.deriveSecret(hs.handshakeSecret, 585 | clientHandshakeTrafficLabel, hs.transcript) 586 | c.in.setTrafficSecret(hs.suite, clientSecret) 587 | serverSecret := hs.suite.deriveSecret(hs.handshakeSecret, 588 | serverHandshakeTrafficLabel, hs.transcript) 589 | c.out.setTrafficSecret(hs.suite, serverSecret) 590 | 591 | err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret) 592 | if err != nil { 593 | c.sendAlert(alertInternalError) 594 | return err 595 | } 596 | err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret) 597 | if err != nil { 598 | c.sendAlert(alertInternalError) 599 | return err 600 | } 601 | 602 | encryptedExtensions := new(encryptedExtensionsMsg) 603 | 604 | selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols) 605 | if err != nil { 606 | c.sendAlert(alertNoApplicationProtocol) 607 | return err 608 | } 609 | encryptedExtensions.alpnProtocol = selectedProto 610 | c.clientProtocol = selectedProto 611 | 612 | hs.transcript.Write(encryptedExtensions.marshal()) 613 | if _, err := c.writeRecord(recordTypeHandshake, encryptedExtensions.marshal()); err != nil { 614 | return err 615 | } 616 | 617 | return nil 618 | } 619 | 620 | func (hs *serverHandshakeStateTLS13) requestClientCert() bool { 621 | return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK 622 | } 623 | 624 | func (hs *serverHandshakeStateTLS13) sendServerCertificate() error { 625 | c := hs.c 626 | 627 | // Only one of PSK and certificates are used at a time. 628 | if hs.usingPSK { 629 | return nil 630 | } 631 | 632 | if hs.requestClientCert() { 633 | // Request a client certificate 634 | certReq := new(certificateRequestMsgTLS13) 635 | certReq.ocspStapling = true 636 | certReq.scts = true 637 | certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms() 638 | if c.config.ClientCAs != nil { 639 | certReq.certificateAuthorities = c.config.ClientCAs.Subjects() 640 | } 641 | 642 | hs.transcript.Write(certReq.marshal()) 643 | if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil { 644 | return err 645 | } 646 | } 647 | 648 | certMsg := new(certificateMsgTLS13) 649 | 650 | certMsg.certificate = *hs.cert 651 | certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0 652 | certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 653 | 654 | hs.transcript.Write(certMsg.marshal()) 655 | if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil { 656 | return err 657 | } 658 | 659 | certVerifyMsg := new(certificateVerifyMsg) 660 | certVerifyMsg.hasSignatureAlgorithm = true 661 | certVerifyMsg.signatureAlgorithm = hs.sigAlg 662 | 663 | sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg) 664 | if err != nil { 665 | return c.sendAlert(alertInternalError) 666 | } 667 | 668 | signed := signedMessage(sigHash, serverSignatureContext, hs.transcript) 669 | signOpts := crypto.SignerOpts(sigHash) 670 | if sigType == signatureRSAPSS { 671 | signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} 672 | } 673 | sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts) 674 | if err != nil { 675 | public := hs.cert.PrivateKey.(crypto.Signer).Public() 676 | if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS && 677 | rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS 678 | c.sendAlert(alertHandshakeFailure) 679 | } else { 680 | c.sendAlert(alertInternalError) 681 | } 682 | return errors.New("tls: failed to sign handshake: " + err.Error()) 683 | } 684 | certVerifyMsg.signature = sig 685 | 686 | hs.transcript.Write(certVerifyMsg.marshal()) 687 | if _, err := c.writeRecord(recordTypeHandshake, certVerifyMsg.marshal()); err != nil { 688 | return err 689 | } 690 | 691 | return nil 692 | } 693 | 694 | func (hs *serverHandshakeStateTLS13) sendServerFinished() error { 695 | c := hs.c 696 | 697 | finished := &finishedMsg{ 698 | verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), 699 | } 700 | 701 | hs.transcript.Write(finished.marshal()) 702 | if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil { 703 | return err 704 | } 705 | 706 | // Derive secrets that take context through the server Finished. 707 | 708 | hs.masterSecret = hs.suite.extract(nil, 709 | hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil)) 710 | 711 | hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret, 712 | clientApplicationTrafficLabel, hs.transcript) 713 | serverSecret := hs.suite.deriveSecret(hs.masterSecret, 714 | serverApplicationTrafficLabel, hs.transcript) 715 | c.out.setTrafficSecret(hs.suite, serverSecret) 716 | 717 | err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret) 718 | if err != nil { 719 | c.sendAlert(alertInternalError) 720 | return err 721 | } 722 | err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret) 723 | if err != nil { 724 | c.sendAlert(alertInternalError) 725 | return err 726 | } 727 | 728 | c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript) 729 | 730 | // If we did not request client certificates, at this point we can 731 | // precompute the client finished and roll the transcript forward to send 732 | // session tickets in our first flight. 733 | if !hs.requestClientCert() { 734 | if err := hs.sendSessionTickets(); err != nil { 735 | return err 736 | } 737 | } 738 | 739 | return nil 740 | } 741 | 742 | func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool { 743 | if hs.c.config.SessionTicketsDisabled { 744 | return false 745 | } 746 | 747 | // Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9. 748 | for _, pskMode := range hs.clientHello.pskModes { 749 | if pskMode == pskModeDHE { 750 | return true 751 | } 752 | } 753 | return false 754 | } 755 | 756 | func (hs *serverHandshakeStateTLS13) sendSessionTickets() error { 757 | c := hs.c 758 | 759 | hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript) 760 | finishedMsg := &finishedMsg{ 761 | verifyData: hs.clientFinished, 762 | } 763 | hs.transcript.Write(finishedMsg.marshal()) 764 | 765 | if !hs.shouldSendSessionTickets() { 766 | return nil 767 | } 768 | 769 | resumptionSecret := hs.suite.deriveSecret(hs.masterSecret, 770 | resumptionLabel, hs.transcript) 771 | 772 | m := new(newSessionTicketMsgTLS13) 773 | 774 | var certsFromClient [][]byte 775 | for _, cert := range c.peerCertificates { 776 | certsFromClient = append(certsFromClient, cert.Raw) 777 | } 778 | state := sessionStateTLS13{ 779 | cipherSuite: hs.suite.id, 780 | createdAt: uint64(c.config.time().Unix()), 781 | resumptionSecret: resumptionSecret, 782 | certificate: Certificate{ 783 | Certificate: certsFromClient, 784 | OCSPStaple: c.ocspResponse, 785 | SignedCertificateTimestamps: c.scts, 786 | }, 787 | } 788 | var err error 789 | m.label, err = c.encryptTicket(state.marshal()) 790 | if err != nil { 791 | return err 792 | } 793 | m.lifetime = uint32(maxSessionTicketLifetime / time.Second) 794 | 795 | // ticket_age_add is a random 32-bit value. See RFC 8446, section 4.6.1 796 | // The value is not stored anywhere; we never need to check the ticket age 797 | // because 0-RTT is not supported. 798 | ageAdd := make([]byte, 4) 799 | _, err = hs.c.config.rand().Read(ageAdd) 800 | if err != nil { 801 | return err 802 | } 803 | m.ageAdd = binary.LittleEndian.Uint32(ageAdd) 804 | 805 | // ticket_nonce, which must be unique per connection, is always left at 806 | // zero because we only ever send one ticket per connection. 807 | 808 | if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil { 809 | return err 810 | } 811 | 812 | return nil 813 | } 814 | 815 | func (hs *serverHandshakeStateTLS13) readClientCertificate() error { 816 | c := hs.c 817 | 818 | if !hs.requestClientCert() { 819 | // Make sure the connection is still being verified whether or not 820 | // the server requested a client certificate. 821 | if c.config.VerifyConnection != nil { 822 | if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 823 | c.sendAlert(alertBadCertificate) 824 | return err 825 | } 826 | } 827 | return nil 828 | } 829 | 830 | // If we requested a client certificate, then the client must send a 831 | // certificate message. If it's empty, no CertificateVerify is sent. 832 | 833 | msg, err := c.readHandshake() 834 | if err != nil { 835 | return err 836 | } 837 | 838 | certMsg, ok := msg.(*certificateMsgTLS13) 839 | if !ok { 840 | c.sendAlert(alertUnexpectedMessage) 841 | return unexpectedMessageError(certMsg, msg) 842 | } 843 | hs.transcript.Write(certMsg.marshal()) 844 | 845 | if err := c.processCertsFromClient(certMsg.certificate); err != nil { 846 | return err 847 | } 848 | 849 | if c.config.VerifyConnection != nil { 850 | if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { 851 | c.sendAlert(alertBadCertificate) 852 | return err 853 | } 854 | } 855 | 856 | if len(certMsg.certificate.Certificate) != 0 { 857 | msg, err = c.readHandshake() 858 | if err != nil { 859 | return err 860 | } 861 | 862 | certVerify, ok := msg.(*certificateVerifyMsg) 863 | if !ok { 864 | c.sendAlert(alertUnexpectedMessage) 865 | return unexpectedMessageError(certVerify, msg) 866 | } 867 | 868 | // See RFC 8446, Section 4.4.3. 869 | if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) { 870 | c.sendAlert(alertIllegalParameter) 871 | return errors.New("tls: client certificate used with invalid signature algorithm") 872 | } 873 | sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) 874 | if err != nil { 875 | return c.sendAlert(alertInternalError) 876 | } 877 | if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 { 878 | c.sendAlert(alertIllegalParameter) 879 | return errors.New("tls: client certificate used with invalid signature algorithm") 880 | } 881 | signed := signedMessage(sigHash, clientSignatureContext, hs.transcript) 882 | if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey, 883 | sigHash, signed, certVerify.signature); err != nil { 884 | c.sendAlert(alertDecryptError) 885 | return errors.New("tls: invalid signature by the client certificate: " + err.Error()) 886 | } 887 | 888 | hs.transcript.Write(certVerify.marshal()) 889 | } 890 | 891 | // If we waited until the client certificates to send session tickets, we 892 | // are ready to do it now. 893 | if err := hs.sendSessionTickets(); err != nil { 894 | return err 895 | } 896 | 897 | return nil 898 | } 899 | 900 | func (hs *serverHandshakeStateTLS13) readClientFinished() error { 901 | c := hs.c 902 | 903 | msg, err := c.readHandshake() 904 | if err != nil { 905 | return err 906 | } 907 | 908 | finished, ok := msg.(*finishedMsg) 909 | if !ok { 910 | c.sendAlert(alertUnexpectedMessage) 911 | return unexpectedMessageError(finished, msg) 912 | } 913 | 914 | if !hmac.Equal(hs.clientFinished, finished.verifyData) { 915 | c.sendAlert(alertDecryptError) 916 | return errors.New("tls: invalid client finished hash") 917 | } 918 | 919 | c.in.setTrafficSecret(hs.suite, hs.trafficSecret) 920 | 921 | return nil 922 | } 923 | --------------------------------------------------------------------------------