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 file.
5 // Package tls partially implements TLS 1.2, as specified in RFC 5246,
6 // and TLS 1.3, as specified in RFC 8446.
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.
30 // Server returns a new TLS server side connection
31 // using conn as the underlying transport.
32 // The configuration config must be non-nil and must include
33 // at least one certificate or else set GetCertificate.
34 func Server(conn net
.Conn
, config
*Config
) *Conn
{
39 c
.handshakeFn
= c
.serverHandshake
43 // Client returns a new TLS client side connection
44 // using conn as the underlying transport.
45 // The config cannot be nil: users must set either ServerName or
46 // InsecureSkipVerify in the config.
47 func Client(conn net
.Conn
, config
*Config
) *Conn
{
53 c
.handshakeFn
= c
.clientHandshake
57 // A listener implements a network listener (net.Listener) for TLS connections.
58 type listener
struct {
63 // Accept waits for and returns the next incoming TLS connection.
64 // The returned connection is of type *Conn.
65 func (l
*listener
) Accept() (net
.Conn
, error
) {
66 c
, err
:= l
.Listener
.Accept()
70 return Server(c
, l
.config
), nil
73 // NewListener creates a Listener which accepts connections from an inner
74 // Listener and wraps each connection with Server.
75 // The configuration config must be non-nil and must include
76 // at least one certificate or else set GetCertificate.
77 func NewListener(inner net
.Listener
, config
*Config
) net
.Listener
{
84 // Listen creates a TLS listener accepting connections on the
85 // given network address using net.Listen.
86 // The configuration config must be non-nil and must include
87 // at least one certificate or else set GetCertificate.
88 func Listen(network
, laddr
string, config
*Config
) (net
.Listener
, error
) {
89 if config
== nil ||
len(config
.Certificates
) == 0 &&
90 config
.GetCertificate
== nil && config
.GetConfigForClient
== nil {
91 return nil, errors
.New("tls: neither Certificates, GetCertificate, nor GetConfigForClient set in Config")
93 l
, err
:= net
.Listen(network
, laddr
)
97 return NewListener(l
, config
), nil
100 type timeoutError
struct{}
102 func (timeoutError
) Error() string { return "tls: DialWithDialer timed out" }
103 func (timeoutError
) Timeout() bool { return true }
104 func (timeoutError
) Temporary() bool { return true }
106 // DialWithDialer connects to the given network address using dialer.Dial and
107 // then initiates a TLS handshake, returning the resulting TLS connection. Any
108 // timeout or deadline given in the dialer apply to connection and TLS
109 // handshake as a whole.
111 // DialWithDialer interprets a nil configuration as equivalent to the zero
112 // configuration; see the documentation of Config for the defaults.
114 // DialWithDialer uses context.Background internally; to specify the context,
115 // use Dialer.DialContext with NetDialer set to the desired dialer.
116 func DialWithDialer(dialer
*net
.Dialer
, network
, addr
string, config
*Config
) (*Conn
, error
) {
117 return dial(context
.Background(), dialer
, network
, addr
, config
)
120 func dial(ctx context
.Context
, netDialer
*net
.Dialer
, network
, addr
string, config
*Config
) (*Conn
, error
) {
121 if netDialer
.Timeout
!= 0 {
122 var cancel context
.CancelFunc
123 ctx
, cancel
= context
.WithTimeout(ctx
, netDialer
.Timeout
)
127 if !netDialer
.Deadline
.IsZero() {
128 var cancel context
.CancelFunc
129 ctx
, cancel
= context
.WithDeadline(ctx
, netDialer
.Deadline
)
133 rawConn
, err
:= netDialer
.DialContext(ctx
, network
, addr
)
138 colonPos
:= strings
.LastIndex(addr
, ":")
142 hostname
:= addr
[:colonPos
]
145 config
= defaultConfig()
147 // If no ServerName is set, infer the ServerName
148 // from the hostname we're connecting to.
149 if config
.ServerName
== "" {
150 // Make a copy to avoid polluting argument or default.
152 c
.ServerName
= hostname
156 conn
:= Client(rawConn
, config
)
157 if err
:= conn
.HandshakeContext(ctx
); err
!= nil {
164 // Dial connects to the given network address using net.Dial
165 // and then initiates a TLS handshake, returning the resulting
167 // Dial interprets a nil configuration as equivalent to
168 // the zero configuration; see the documentation of Config
170 func Dial(network
, addr
string, config
*Config
) (*Conn
, error
) {
171 return DialWithDialer(new(net
.Dialer
), network
, addr
, config
)
174 // Dialer dials TLS connections given a configuration and a Dialer for the
175 // underlying connection.
177 // NetDialer is the optional dialer to use for the TLS connections'
178 // underlying TCP connections.
179 // A nil NetDialer is equivalent to the net.Dialer zero value.
180 NetDialer
*net
.Dialer
182 // Config is the TLS configuration to use for new connections.
183 // A nil configuration is equivalent to the zero
184 // configuration; see the documentation of Config for the
189 // Dial connects to the given network address and initiates a TLS
190 // handshake, returning the resulting TLS connection.
192 // The returned Conn, if any, will always be of type *Conn.
194 // Dial uses context.Background internally; to specify the context,
196 func (d
*Dialer
) Dial(network
, addr
string) (net
.Conn
, error
) {
197 return d
.DialContext(context
.Background(), network
, addr
)
200 func (d
*Dialer
) netDialer() *net
.Dialer
{
201 if d
.NetDialer
!= nil {
204 return new(net
.Dialer
)
207 // DialContext connects to the given network address and initiates a TLS
208 // handshake, returning the resulting TLS connection.
210 // The provided Context must be non-nil. If the context expires before
211 // the connection is complete, an error is returned. Once successfully
212 // connected, any expiration of the context will not affect the
215 // The returned Conn, if any, will always be of type *Conn.
216 func (d
*Dialer
) DialContext(ctx context
.Context
, network
, addr
string) (net
.Conn
, error
) {
217 c
, err
:= dial(ctx
, d
.netDialer(), network
, addr
, d
.Config
)
219 // Don't return c (a typed nil) in an interface.
225 // LoadX509KeyPair reads and parses a public/private key pair from a pair
226 // of files. The files must contain PEM encoded data. The certificate file
227 // may contain intermediate certificates following the leaf certificate to
228 // form a certificate chain. On successful return, Certificate.Leaf will
229 // be nil because the parsed form of the certificate is not retained.
230 func LoadX509KeyPair(certFile
, keyFile
string) (Certificate
, error
) {
231 certPEMBlock
, err
:= os
.ReadFile(certFile
)
233 return Certificate
{}, err
235 keyPEMBlock
, err
:= os
.ReadFile(keyFile
)
237 return Certificate
{}, err
239 return X509KeyPair(certPEMBlock
, keyPEMBlock
)
242 // X509KeyPair parses a public/private key pair from a pair of
243 // PEM encoded data. On successful return, Certificate.Leaf will be nil because
244 // the parsed form of the certificate is not retained.
245 func X509KeyPair(certPEMBlock
, keyPEMBlock
[]byte) (Certificate
, error
) {
246 fail
:= func(err error
) (Certificate
, error
) { return Certificate
{}, err
}
249 var skippedBlockTypes
[]string
251 var certDERBlock
*pem
.Block
252 certDERBlock
, certPEMBlock
= pem
.Decode(certPEMBlock
)
253 if certDERBlock
== nil {
256 if certDERBlock
.Type
== "CERTIFICATE" {
257 cert
.Certificate
= append(cert
.Certificate
, certDERBlock
.Bytes
)
259 skippedBlockTypes
= append(skippedBlockTypes
, certDERBlock
.Type
)
263 if len(cert
.Certificate
) == 0 {
264 if len(skippedBlockTypes
) == 0 {
265 return fail(errors
.New("tls: failed to find any PEM data in certificate input"))
267 if len(skippedBlockTypes
) == 1 && strings
.HasSuffix(skippedBlockTypes
[0], "PRIVATE KEY") {
268 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"))
270 return fail(fmt
.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes
))
273 skippedBlockTypes
= skippedBlockTypes
[:0]
274 var keyDERBlock
*pem
.Block
276 keyDERBlock
, keyPEMBlock
= pem
.Decode(keyPEMBlock
)
277 if keyDERBlock
== nil {
278 if len(skippedBlockTypes
) == 0 {
279 return fail(errors
.New("tls: failed to find any PEM data in key input"))
281 if len(skippedBlockTypes
) == 1 && skippedBlockTypes
[0] == "CERTIFICATE" {
282 return fail(errors
.New("tls: found a certificate rather than a key in the PEM for the private key"))
284 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
))
286 if keyDERBlock
.Type
== "PRIVATE KEY" || strings
.HasSuffix(keyDERBlock
.Type
, " PRIVATE KEY") {
289 skippedBlockTypes
= append(skippedBlockTypes
, keyDERBlock
.Type
)
292 // We don't need to parse the public key for TLS, but we so do anyway
293 // to check that it looks sane and matches the private key.
294 x509Cert
, err
:= x509
.ParseCertificate(cert
.Certificate
[0])
299 cert
.PrivateKey
, err
= parsePrivateKey(keyDERBlock
.Bytes
)
304 switch pub
:= x509Cert
.PublicKey
.(type) {
306 priv
, ok
:= cert
.PrivateKey
.(*rsa
.PrivateKey
)
308 return fail(errors
.New("tls: private key type does not match public key type"))
310 if pub
.N
.Cmp(priv
.N
) != 0 {
311 return fail(errors
.New("tls: private key does not match public key"))
313 case *ecdsa
.PublicKey
:
314 priv
, ok
:= cert
.PrivateKey
.(*ecdsa
.PrivateKey
)
316 return fail(errors
.New("tls: private key type does not match public key type"))
318 if pub
.X
.Cmp(priv
.X
) != 0 || pub
.Y
.Cmp(priv
.Y
) != 0 {
319 return fail(errors
.New("tls: private key does not match public key"))
321 case ed25519
.PublicKey
:
322 priv
, ok
:= cert
.PrivateKey
.(ed25519
.PrivateKey
)
324 return fail(errors
.New("tls: private key type does not match public key type"))
326 if !bytes
.Equal(priv
.Public().(ed25519
.PublicKey
), pub
) {
327 return fail(errors
.New("tls: private key does not match public key"))
330 return fail(errors
.New("tls: unknown public key algorithm"))
336 // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
337 // PKCS #1 private keys by default, while OpenSSL 1.0.0 generates PKCS #8 keys.
338 // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
339 func parsePrivateKey(der
[]byte) (crypto
.PrivateKey
, error
) {
340 if key
, err
:= x509
.ParsePKCS1PrivateKey(der
); err
== nil {
343 if key
, err
:= x509
.ParsePKCS8PrivateKey(der
); err
== nil {
344 switch key
:= key
.(type) {
345 case *rsa
.PrivateKey
, *ecdsa
.PrivateKey
, ed25519
.PrivateKey
:
348 return nil, errors
.New("tls: found unknown private key type in PKCS#8 wrapping")
351 if key
, err
:= x509
.ParseECPrivateKey(der
); err
== nil {
355 return nil, errors
.New("tls: failed to parse private key")