You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

handshake_server.go 26 KiB

crypto/tls: decouple handshake signatures from the handshake hash. Prior to TLS 1.2, the handshake had a pleasing property that one could incrementally hash it and, from that, get the needed hashes for both the CertificateVerify and Finished messages. TLS 1.2 introduced negotiation for the signature and hash and it became possible for the handshake hash to be, say, SHA-384, but for the CertificateVerify to sign the handshake with SHA-1. The problem is that one doesn't know in advance which hashes will be needed and thus the handshake needs to be buffered. Go ignored this, always kept a single handshake hash, and any signatures over the handshake had to use that hash. However, there are a set of servers that inspect the client's offered signature hash functions and will abort the handshake if one of the server's certificates is signed with a hash function outside of that set. https://robertsspaceindustries.com/ is an example of such a server. Clearly not a lot of thought happened when that server code was written, but its out there and we have to deal with it. This change decouples the handshake hash from the CertificateVerify hash. This lays the groundwork for advertising support for SHA-384 but doesn't actually make that change in the interests of reviewability. Updating the advertised hash functions will cause changes in many of the testdata/ files and some errors might get lost in the noise. This change only needs to update four testdata/ files: one because a SHA-384-based handshake is now being signed with SHA-256 and the others because the TLS 1.2 CertificateRequest message now includes SHA-1. This change also has the effect of adding support for client-certificates in SSLv3 servers. However, SSLv3 is now disabled by default so this should be moot. It would be possible to avoid much of this change and just support SHA-384 for the ServerKeyExchange as the SKX only signs over the nonces and SKX params (a design mistake in TLS). However, that would leave Go in the odd situation where it advertised support for SHA-384, but would only use the handshake hash when signing client certificates. I fear that'll just cause problems in the future. Much of this code was written by davidben@ for the purposes of testing BoringSSL. Partly addresses #9757 Change-Id: I5137a472b6076812af387a5a69fc62c7373cd485 Reviewed-on: https://go-review.googlesource.com/9415 Run-TryBot: Adam Langley <agl@golang.org> Reviewed-by: Adam Langley <agl@golang.org>
9 years ago
crypto/tls: decouple handshake signatures from the handshake hash. Prior to TLS 1.2, the handshake had a pleasing property that one could incrementally hash it and, from that, get the needed hashes for both the CertificateVerify and Finished messages. TLS 1.2 introduced negotiation for the signature and hash and it became possible for the handshake hash to be, say, SHA-384, but for the CertificateVerify to sign the handshake with SHA-1. The problem is that one doesn't know in advance which hashes will be needed and thus the handshake needs to be buffered. Go ignored this, always kept a single handshake hash, and any signatures over the handshake had to use that hash. However, there are a set of servers that inspect the client's offered signature hash functions and will abort the handshake if one of the server's certificates is signed with a hash function outside of that set. https://robertsspaceindustries.com/ is an example of such a server. Clearly not a lot of thought happened when that server code was written, but its out there and we have to deal with it. This change decouples the handshake hash from the CertificateVerify hash. This lays the groundwork for advertising support for SHA-384 but doesn't actually make that change in the interests of reviewability. Updating the advertised hash functions will cause changes in many of the testdata/ files and some errors might get lost in the noise. This change only needs to update four testdata/ files: one because a SHA-384-based handshake is now being signed with SHA-256 and the others because the TLS 1.2 CertificateRequest message now includes SHA-1. This change also has the effect of adding support for client-certificates in SSLv3 servers. However, SSLv3 is now disabled by default so this should be moot. It would be possible to avoid much of this change and just support SHA-384 for the ServerKeyExchange as the SKX only signs over the nonces and SKX params (a design mistake in TLS). However, that would leave Go in the odd situation where it advertised support for SHA-384, but would only use the handshake hash when signing client certificates. I fear that'll just cause problems in the future. Much of this code was written by davidben@ for the purposes of testing BoringSSL. Partly addresses #9757 Change-Id: I5137a472b6076812af387a5a69fc62c7373cd485 Reviewed-on: https://go-review.googlesource.com/9415 Run-TryBot: Adam Langley <agl@golang.org> Reviewed-by: Adam Langley <agl@golang.org>
9 years ago
crypto/tls: decouple handshake signatures from the handshake hash. Prior to TLS 1.2, the handshake had a pleasing property that one could incrementally hash it and, from that, get the needed hashes for both the CertificateVerify and Finished messages. TLS 1.2 introduced negotiation for the signature and hash and it became possible for the handshake hash to be, say, SHA-384, but for the CertificateVerify to sign the handshake with SHA-1. The problem is that one doesn't know in advance which hashes will be needed and thus the handshake needs to be buffered. Go ignored this, always kept a single handshake hash, and any signatures over the handshake had to use that hash. However, there are a set of servers that inspect the client's offered signature hash functions and will abort the handshake if one of the server's certificates is signed with a hash function outside of that set. https://robertsspaceindustries.com/ is an example of such a server. Clearly not a lot of thought happened when that server code was written, but its out there and we have to deal with it. This change decouples the handshake hash from the CertificateVerify hash. This lays the groundwork for advertising support for SHA-384 but doesn't actually make that change in the interests of reviewability. Updating the advertised hash functions will cause changes in many of the testdata/ files and some errors might get lost in the noise. This change only needs to update four testdata/ files: one because a SHA-384-based handshake is now being signed with SHA-256 and the others because the TLS 1.2 CertificateRequest message now includes SHA-1. This change also has the effect of adding support for client-certificates in SSLv3 servers. However, SSLv3 is now disabled by default so this should be moot. It would be possible to avoid much of this change and just support SHA-384 for the ServerKeyExchange as the SKX only signs over the nonces and SKX params (a design mistake in TLS). However, that would leave Go in the odd situation where it advertised support for SHA-384, but would only use the handshake hash when signing client certificates. I fear that'll just cause problems in the future. Much of this code was written by davidben@ for the purposes of testing BoringSSL. Partly addresses #9757 Change-Id: I5137a472b6076812af387a5a69fc62c7373cd485 Reviewed-on: https://go-review.googlesource.com/9415 Run-TryBot: Adam Langley <agl@golang.org> Reviewed-by: Adam Langley <agl@golang.org>
9 years ago
crypto/tls: decouple handshake signatures from the handshake hash. Prior to TLS 1.2, the handshake had a pleasing property that one could incrementally hash it and, from that, get the needed hashes for both the CertificateVerify and Finished messages. TLS 1.2 introduced negotiation for the signature and hash and it became possible for the handshake hash to be, say, SHA-384, but for the CertificateVerify to sign the handshake with SHA-1. The problem is that one doesn't know in advance which hashes will be needed and thus the handshake needs to be buffered. Go ignored this, always kept a single handshake hash, and any signatures over the handshake had to use that hash. However, there are a set of servers that inspect the client's offered signature hash functions and will abort the handshake if one of the server's certificates is signed with a hash function outside of that set. https://robertsspaceindustries.com/ is an example of such a server. Clearly not a lot of thought happened when that server code was written, but its out there and we have to deal with it. This change decouples the handshake hash from the CertificateVerify hash. This lays the groundwork for advertising support for SHA-384 but doesn't actually make that change in the interests of reviewability. Updating the advertised hash functions will cause changes in many of the testdata/ files and some errors might get lost in the noise. This change only needs to update four testdata/ files: one because a SHA-384-based handshake is now being signed with SHA-256 and the others because the TLS 1.2 CertificateRequest message now includes SHA-1. This change also has the effect of adding support for client-certificates in SSLv3 servers. However, SSLv3 is now disabled by default so this should be moot. It would be possible to avoid much of this change and just support SHA-384 for the ServerKeyExchange as the SKX only signs over the nonces and SKX params (a design mistake in TLS). However, that would leave Go in the odd situation where it advertised support for SHA-384, but would only use the handshake hash when signing client certificates. I fear that'll just cause problems in the future. Much of this code was written by davidben@ for the purposes of testing BoringSSL. Partly addresses #9757 Change-Id: I5137a472b6076812af387a5a69fc62c7373cd485 Reviewed-on: https://go-review.googlesource.com/9415 Run-TryBot: Adam Langley <agl@golang.org> Reviewed-by: Adam Langley <agl@golang.org>
9 years ago
crypto/tls: decouple handshake signatures from the handshake hash. Prior to TLS 1.2, the handshake had a pleasing property that one could incrementally hash it and, from that, get the needed hashes for both the CertificateVerify and Finished messages. TLS 1.2 introduced negotiation for the signature and hash and it became possible for the handshake hash to be, say, SHA-384, but for the CertificateVerify to sign the handshake with SHA-1. The problem is that one doesn't know in advance which hashes will be needed and thus the handshake needs to be buffered. Go ignored this, always kept a single handshake hash, and any signatures over the handshake had to use that hash. However, there are a set of servers that inspect the client's offered signature hash functions and will abort the handshake if one of the server's certificates is signed with a hash function outside of that set. https://robertsspaceindustries.com/ is an example of such a server. Clearly not a lot of thought happened when that server code was written, but its out there and we have to deal with it. This change decouples the handshake hash from the CertificateVerify hash. This lays the groundwork for advertising support for SHA-384 but doesn't actually make that change in the interests of reviewability. Updating the advertised hash functions will cause changes in many of the testdata/ files and some errors might get lost in the noise. This change only needs to update four testdata/ files: one because a SHA-384-based handshake is now being signed with SHA-256 and the others because the TLS 1.2 CertificateRequest message now includes SHA-1. This change also has the effect of adding support for client-certificates in SSLv3 servers. However, SSLv3 is now disabled by default so this should be moot. It would be possible to avoid much of this change and just support SHA-384 for the ServerKeyExchange as the SKX only signs over the nonces and SKX params (a design mistake in TLS). However, that would leave Go in the odd situation where it advertised support for SHA-384, but would only use the handshake hash when signing client certificates. I fear that'll just cause problems in the future. Much of this code was written by davidben@ for the purposes of testing BoringSSL. Partly addresses #9757 Change-Id: I5137a472b6076812af387a5a69fc62c7373cd485 Reviewed-on: https://go-review.googlesource.com/9415 Run-TryBot: Adam Langley <agl@golang.org> Reviewed-by: Adam Langley <agl@golang.org>
9 years ago
crypto/tls: decouple handshake signatures from the handshake hash. Prior to TLS 1.2, the handshake had a pleasing property that one could incrementally hash it and, from that, get the needed hashes for both the CertificateVerify and Finished messages. TLS 1.2 introduced negotiation for the signature and hash and it became possible for the handshake hash to be, say, SHA-384, but for the CertificateVerify to sign the handshake with SHA-1. The problem is that one doesn't know in advance which hashes will be needed and thus the handshake needs to be buffered. Go ignored this, always kept a single handshake hash, and any signatures over the handshake had to use that hash. However, there are a set of servers that inspect the client's offered signature hash functions and will abort the handshake if one of the server's certificates is signed with a hash function outside of that set. https://robertsspaceindustries.com/ is an example of such a server. Clearly not a lot of thought happened when that server code was written, but its out there and we have to deal with it. This change decouples the handshake hash from the CertificateVerify hash. This lays the groundwork for advertising support for SHA-384 but doesn't actually make that change in the interests of reviewability. Updating the advertised hash functions will cause changes in many of the testdata/ files and some errors might get lost in the noise. This change only needs to update four testdata/ files: one because a SHA-384-based handshake is now being signed with SHA-256 and the others because the TLS 1.2 CertificateRequest message now includes SHA-1. This change also has the effect of adding support for client-certificates in SSLv3 servers. However, SSLv3 is now disabled by default so this should be moot. It would be possible to avoid much of this change and just support SHA-384 for the ServerKeyExchange as the SKX only signs over the nonces and SKX params (a design mistake in TLS). However, that would leave Go in the odd situation where it advertised support for SHA-384, but would only use the handshake hash when signing client certificates. I fear that'll just cause problems in the future. Much of this code was written by davidben@ for the purposes of testing BoringSSL. Partly addresses #9757 Change-Id: I5137a472b6076812af387a5a69fc62c7373cd485 Reviewed-on: https://go-review.googlesource.com/9415 Run-TryBot: Adam Langley <agl@golang.org> Reviewed-by: Adam Langley <agl@golang.org>
9 years ago
crypto/tls: decouple handshake signatures from the handshake hash. Prior to TLS 1.2, the handshake had a pleasing property that one could incrementally hash it and, from that, get the needed hashes for both the CertificateVerify and Finished messages. TLS 1.2 introduced negotiation for the signature and hash and it became possible for the handshake hash to be, say, SHA-384, but for the CertificateVerify to sign the handshake with SHA-1. The problem is that one doesn't know in advance which hashes will be needed and thus the handshake needs to be buffered. Go ignored this, always kept a single handshake hash, and any signatures over the handshake had to use that hash. However, there are a set of servers that inspect the client's offered signature hash functions and will abort the handshake if one of the server's certificates is signed with a hash function outside of that set. https://robertsspaceindustries.com/ is an example of such a server. Clearly not a lot of thought happened when that server code was written, but its out there and we have to deal with it. This change decouples the handshake hash from the CertificateVerify hash. This lays the groundwork for advertising support for SHA-384 but doesn't actually make that change in the interests of reviewability. Updating the advertised hash functions will cause changes in many of the testdata/ files and some errors might get lost in the noise. This change only needs to update four testdata/ files: one because a SHA-384-based handshake is now being signed with SHA-256 and the others because the TLS 1.2 CertificateRequest message now includes SHA-1. This change also has the effect of adding support for client-certificates in SSLv3 servers. However, SSLv3 is now disabled by default so this should be moot. It would be possible to avoid much of this change and just support SHA-384 for the ServerKeyExchange as the SKX only signs over the nonces and SKX params (a design mistake in TLS). However, that would leave Go in the odd situation where it advertised support for SHA-384, but would only use the handshake hash when signing client certificates. I fear that'll just cause problems in the future. Much of this code was written by davidben@ for the purposes of testing BoringSSL. Partly addresses #9757 Change-Id: I5137a472b6076812af387a5a69fc62c7373cd485 Reviewed-on: https://go-review.googlesource.com/9415 Run-TryBot: Adam Langley <agl@golang.org> Reviewed-by: Adam Langley <agl@golang.org>
9 years ago
crypto/tls: decouple handshake signatures from the handshake hash. Prior to TLS 1.2, the handshake had a pleasing property that one could incrementally hash it and, from that, get the needed hashes for both the CertificateVerify and Finished messages. TLS 1.2 introduced negotiation for the signature and hash and it became possible for the handshake hash to be, say, SHA-384, but for the CertificateVerify to sign the handshake with SHA-1. The problem is that one doesn't know in advance which hashes will be needed and thus the handshake needs to be buffered. Go ignored this, always kept a single handshake hash, and any signatures over the handshake had to use that hash. However, there are a set of servers that inspect the client's offered signature hash functions and will abort the handshake if one of the server's certificates is signed with a hash function outside of that set. https://robertsspaceindustries.com/ is an example of such a server. Clearly not a lot of thought happened when that server code was written, but its out there and we have to deal with it. This change decouples the handshake hash from the CertificateVerify hash. This lays the groundwork for advertising support for SHA-384 but doesn't actually make that change in the interests of reviewability. Updating the advertised hash functions will cause changes in many of the testdata/ files and some errors might get lost in the noise. This change only needs to update four testdata/ files: one because a SHA-384-based handshake is now being signed with SHA-256 and the others because the TLS 1.2 CertificateRequest message now includes SHA-1. This change also has the effect of adding support for client-certificates in SSLv3 servers. However, SSLv3 is now disabled by default so this should be moot. It would be possible to avoid much of this change and just support SHA-384 for the ServerKeyExchange as the SKX only signs over the nonces and SKX params (a design mistake in TLS). However, that would leave Go in the odd situation where it advertised support for SHA-384, but would only use the handshake hash when signing client certificates. I fear that'll just cause problems in the future. Much of this code was written by davidben@ for the purposes of testing BoringSSL. Partly addresses #9757 Change-Id: I5137a472b6076812af387a5a69fc62c7373cd485 Reviewed-on: https://go-review.googlesource.com/9415 Run-TryBot: Adam Langley <agl@golang.org> Reviewed-by: Adam Langley <agl@golang.org>
9 years ago
crypto/tls: decouple handshake signatures from the handshake hash. Prior to TLS 1.2, the handshake had a pleasing property that one could incrementally hash it and, from that, get the needed hashes for both the CertificateVerify and Finished messages. TLS 1.2 introduced negotiation for the signature and hash and it became possible for the handshake hash to be, say, SHA-384, but for the CertificateVerify to sign the handshake with SHA-1. The problem is that one doesn't know in advance which hashes will be needed and thus the handshake needs to be buffered. Go ignored this, always kept a single handshake hash, and any signatures over the handshake had to use that hash. However, there are a set of servers that inspect the client's offered signature hash functions and will abort the handshake if one of the server's certificates is signed with a hash function outside of that set. https://robertsspaceindustries.com/ is an example of such a server. Clearly not a lot of thought happened when that server code was written, but its out there and we have to deal with it. This change decouples the handshake hash from the CertificateVerify hash. This lays the groundwork for advertising support for SHA-384 but doesn't actually make that change in the interests of reviewability. Updating the advertised hash functions will cause changes in many of the testdata/ files and some errors might get lost in the noise. This change only needs to update four testdata/ files: one because a SHA-384-based handshake is now being signed with SHA-256 and the others because the TLS 1.2 CertificateRequest message now includes SHA-1. This change also has the effect of adding support for client-certificates in SSLv3 servers. However, SSLv3 is now disabled by default so this should be moot. It would be possible to avoid much of this change and just support SHA-384 for the ServerKeyExchange as the SKX only signs over the nonces and SKX params (a design mistake in TLS). However, that would leave Go in the odd situation where it advertised support for SHA-384, but would only use the handshake hash when signing client certificates. I fear that'll just cause problems in the future. Much of this code was written by davidben@ for the purposes of testing BoringSSL. Partly addresses #9757 Change-Id: I5137a472b6076812af387a5a69fc62c7373cd485 Reviewed-on: https://go-review.googlesource.com/9415 Run-TryBot: Adam Langley <agl@golang.org> Reviewed-by: Adam Langley <agl@golang.org>
9 years ago
crypto/tls: decouple handshake signatures from the handshake hash. Prior to TLS 1.2, the handshake had a pleasing property that one could incrementally hash it and, from that, get the needed hashes for both the CertificateVerify and Finished messages. TLS 1.2 introduced negotiation for the signature and hash and it became possible for the handshake hash to be, say, SHA-384, but for the CertificateVerify to sign the handshake with SHA-1. The problem is that one doesn't know in advance which hashes will be needed and thus the handshake needs to be buffered. Go ignored this, always kept a single handshake hash, and any signatures over the handshake had to use that hash. However, there are a set of servers that inspect the client's offered signature hash functions and will abort the handshake if one of the server's certificates is signed with a hash function outside of that set. https://robertsspaceindustries.com/ is an example of such a server. Clearly not a lot of thought happened when that server code was written, but its out there and we have to deal with it. This change decouples the handshake hash from the CertificateVerify hash. This lays the groundwork for advertising support for SHA-384 but doesn't actually make that change in the interests of reviewability. Updating the advertised hash functions will cause changes in many of the testdata/ files and some errors might get lost in the noise. This change only needs to update four testdata/ files: one because a SHA-384-based handshake is now being signed with SHA-256 and the others because the TLS 1.2 CertificateRequest message now includes SHA-1. This change also has the effect of adding support for client-certificates in SSLv3 servers. However, SSLv3 is now disabled by default so this should be moot. It would be possible to avoid much of this change and just support SHA-384 for the ServerKeyExchange as the SKX only signs over the nonces and SKX params (a design mistake in TLS). However, that would leave Go in the odd situation where it advertised support for SHA-384, but would only use the handshake hash when signing client certificates. I fear that'll just cause problems in the future. Much of this code was written by davidben@ for the purposes of testing BoringSSL. Partly addresses #9757 Change-Id: I5137a472b6076812af387a5a69fc62c7373cd485 Reviewed-on: https://go-review.googlesource.com/9415 Run-TryBot: Adam Langley <agl@golang.org> Reviewed-by: Adam Langley <agl@golang.org>
9 years ago
crypto/tls: decouple handshake signatures from the handshake hash. Prior to TLS 1.2, the handshake had a pleasing property that one could incrementally hash it and, from that, get the needed hashes for both the CertificateVerify and Finished messages. TLS 1.2 introduced negotiation for the signature and hash and it became possible for the handshake hash to be, say, SHA-384, but for the CertificateVerify to sign the handshake with SHA-1. The problem is that one doesn't know in advance which hashes will be needed and thus the handshake needs to be buffered. Go ignored this, always kept a single handshake hash, and any signatures over the handshake had to use that hash. However, there are a set of servers that inspect the client's offered signature hash functions and will abort the handshake if one of the server's certificates is signed with a hash function outside of that set. https://robertsspaceindustries.com/ is an example of such a server. Clearly not a lot of thought happened when that server code was written, but its out there and we have to deal with it. This change decouples the handshake hash from the CertificateVerify hash. This lays the groundwork for advertising support for SHA-384 but doesn't actually make that change in the interests of reviewability. Updating the advertised hash functions will cause changes in many of the testdata/ files and some errors might get lost in the noise. This change only needs to update four testdata/ files: one because a SHA-384-based handshake is now being signed with SHA-256 and the others because the TLS 1.2 CertificateRequest message now includes SHA-1. This change also has the effect of adding support for client-certificates in SSLv3 servers. However, SSLv3 is now disabled by default so this should be moot. It would be possible to avoid much of this change and just support SHA-384 for the ServerKeyExchange as the SKX only signs over the nonces and SKX params (a design mistake in TLS). However, that would leave Go in the odd situation where it advertised support for SHA-384, but would only use the handshake hash when signing client certificates. I fear that'll just cause problems in the future. Much of this code was written by davidben@ for the purposes of testing BoringSSL. Partly addresses #9757 Change-Id: I5137a472b6076812af387a5a69fc62c7373cd485 Reviewed-on: https://go-review.googlesource.com/9415 Run-TryBot: Adam Langley <agl@golang.org> Reviewed-by: Adam Langley <agl@golang.org>
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  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.
  4. package tls
  5. import (
  6. "crypto"
  7. "crypto/ecdsa"
  8. "crypto/rsa"
  9. "crypto/subtle"
  10. "crypto/x509"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "sync/atomic"
  15. )
  16. type Committer interface {
  17. Commit() error
  18. }
  19. // serverHandshakeState contains details of a server handshake in progress.
  20. // It's discarded once the handshake has completed.
  21. type serverHandshakeState struct {
  22. c *Conn
  23. suite *cipherSuite
  24. masterSecret []byte
  25. cachedClientHelloInfo *ClientHelloInfo
  26. clientHello *clientHelloMsg
  27. hello *serverHelloMsg
  28. cert *Certificate
  29. privateKey crypto.PrivateKey
  30. // A marshalled DelegatedCredential to be sent to the client in the
  31. // handshake.
  32. delegatedCredential []byte
  33. // TLS 1.0-1.2 fields
  34. ellipticOk bool
  35. ecdsaOk bool
  36. rsaDecryptOk bool
  37. rsaSignOk bool
  38. sessionState *sessionState
  39. finishedHash finishedHash
  40. certsFromClient [][]byte
  41. // TLS 1.3 fields
  42. hello13Enc *encryptedExtensionsMsg
  43. keySchedule *keySchedule13
  44. clientFinishedKey []byte
  45. hsClientCipher interface{}
  46. appClientCipher interface{}
  47. }
  48. // serverHandshake performs a TLS handshake as a server.
  49. // c.out.Mutex <= L; c.handshakeMutex <= L.
  50. func (c *Conn) serverHandshake() error {
  51. // If this is the first server handshake, we generate a random key to
  52. // encrypt the tickets with.
  53. c.config.serverInitOnce.Do(func() { c.config.serverInit(nil) })
  54. hs := serverHandshakeState{
  55. c: c,
  56. }
  57. c.in.traceErr = hs.traceErr
  58. c.out.traceErr = hs.traceErr
  59. isResume, err := hs.readClientHello()
  60. if err != nil {
  61. return err
  62. }
  63. // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
  64. // and https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-2
  65. c.buffering = true
  66. if c.vers >= VersionTLS13 {
  67. if err := hs.doTLS13Handshake(); err != nil {
  68. return err
  69. }
  70. if _, err := c.flush(); err != nil {
  71. return err
  72. }
  73. c.hs = &hs
  74. // If the client is sending early data while the server expects
  75. // it, delay the Finished check until HandshakeConfirmed() is
  76. // called or until all early data is Read(). Otherwise, complete
  77. // authenticating the client now (there is no support for
  78. // sending 0.5-RTT data to a potential unauthenticated client).
  79. if c.phase != readingEarlyData {
  80. if err := hs.readClientFinished13(false); err != nil {
  81. return err
  82. }
  83. }
  84. c.handshakeComplete = true
  85. return nil
  86. } else if isResume {
  87. // The client has included a session ticket and so we do an abbreviated handshake.
  88. if err := hs.doResumeHandshake(); err != nil {
  89. return err
  90. }
  91. if err := hs.establishKeys(); err != nil {
  92. return err
  93. }
  94. // ticketSupported is set in a resumption handshake if the
  95. // ticket from the client was encrypted with an old session
  96. // ticket key and thus a refreshed ticket should be sent.
  97. if hs.hello.ticketSupported {
  98. if err := hs.sendSessionTicket(); err != nil {
  99. return err
  100. }
  101. }
  102. if err := hs.sendFinished(c.serverFinished[:]); err != nil {
  103. return err
  104. }
  105. if _, err := c.flush(); err != nil {
  106. return err
  107. }
  108. c.clientFinishedIsFirst = false
  109. if err := hs.readFinished(nil); err != nil {
  110. return err
  111. }
  112. c.didResume = true
  113. } else {
  114. // The client didn't include a session ticket, or it wasn't
  115. // valid so we do a full handshake.
  116. if err := hs.doFullHandshake(); err != nil {
  117. return err
  118. }
  119. if err := hs.establishKeys(); err != nil {
  120. return err
  121. }
  122. if err := hs.readFinished(c.clientFinished[:]); err != nil {
  123. return err
  124. }
  125. c.clientFinishedIsFirst = true
  126. c.buffering = true
  127. if err := hs.sendSessionTicket(); err != nil {
  128. return err
  129. }
  130. if err := hs.sendFinished(nil); err != nil {
  131. return err
  132. }
  133. if _, err := c.flush(); err != nil {
  134. return err
  135. }
  136. }
  137. if c.hand.Len() > 0 {
  138. return c.sendAlert(alertUnexpectedMessage)
  139. }
  140. c.phase = handshakeConfirmed
  141. atomic.StoreInt32(&c.handshakeConfirmed, 1)
  142. c.handshakeComplete = true
  143. return nil
  144. }
  145. // readClientHello reads a ClientHello message from the client and decides
  146. // whether we will perform session resumption.
  147. func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) {
  148. c := hs.c
  149. msg, err := c.readHandshake()
  150. if err != nil {
  151. return false, err
  152. }
  153. var ok bool
  154. hs.clientHello, ok = msg.(*clientHelloMsg)
  155. if !ok {
  156. c.sendAlert(alertUnexpectedMessage)
  157. return false, unexpectedMessageError(hs.clientHello, msg)
  158. }
  159. if c.config.GetConfigForClient != nil {
  160. if newConfig, err := c.config.GetConfigForClient(hs.clientHelloInfo()); err != nil {
  161. c.out.traceErr, c.in.traceErr = nil, nil // disable tracing
  162. c.sendAlert(alertInternalError)
  163. return false, err
  164. } else if newConfig != nil {
  165. newConfig.serverInitOnce.Do(func() { newConfig.serverInit(c.config) })
  166. c.config = newConfig
  167. }
  168. }
  169. var keyShares []CurveID
  170. for _, ks := range hs.clientHello.keyShares {
  171. keyShares = append(keyShares, ks.group)
  172. }
  173. if hs.clientHello.supportedVersions != nil {
  174. c.vers, ok = c.config.pickVersion(hs.clientHello.supportedVersions)
  175. if !ok {
  176. c.sendAlert(alertProtocolVersion)
  177. return false, fmt.Errorf("tls: none of the client versions (%x) are supported", hs.clientHello.supportedVersions)
  178. }
  179. } else {
  180. c.vers, ok = c.config.mutualVersion(hs.clientHello.vers)
  181. if !ok {
  182. c.sendAlert(alertProtocolVersion)
  183. return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers)
  184. }
  185. }
  186. c.haveVers = true
  187. preferredCurves := c.config.curvePreferences()
  188. Curves:
  189. for _, curve := range hs.clientHello.supportedCurves {
  190. for _, supported := range preferredCurves {
  191. if supported == curve {
  192. hs.ellipticOk = true
  193. break Curves
  194. }
  195. }
  196. }
  197. // If present, the supported points extension must include uncompressed.
  198. // Can be absent. This behavior mirrors BoringSSL.
  199. if hs.clientHello.supportedPoints != nil {
  200. supportedPointFormat := false
  201. for _, pointFormat := range hs.clientHello.supportedPoints {
  202. if pointFormat == pointFormatUncompressed {
  203. supportedPointFormat = true
  204. break
  205. }
  206. }
  207. if !supportedPointFormat {
  208. c.sendAlert(alertHandshakeFailure)
  209. return false, errors.New("tls: client does not support uncompressed points")
  210. }
  211. }
  212. foundCompression := false
  213. // We only support null compression, so check that the client offered it.
  214. for _, compression := range hs.clientHello.compressionMethods {
  215. if compression == compressionNone {
  216. foundCompression = true
  217. break
  218. }
  219. }
  220. if !foundCompression {
  221. c.sendAlert(alertIllegalParameter)
  222. return false, errors.New("tls: client does not support uncompressed connections")
  223. }
  224. if len(hs.clientHello.compressionMethods) != 1 && c.vers >= VersionTLS13 {
  225. c.sendAlert(alertIllegalParameter)
  226. return false, errors.New("tls: 1.3 client offered compression")
  227. }
  228. if len(hs.clientHello.secureRenegotiation) != 0 {
  229. c.sendAlert(alertHandshakeFailure)
  230. return false, errors.New("tls: initial handshake had non-empty renegotiation extension")
  231. }
  232. if c.vers < VersionTLS13 {
  233. hs.hello = new(serverHelloMsg)
  234. hs.hello.vers = c.vers
  235. hs.hello.random = make([]byte, 32)
  236. _, err = io.ReadFull(c.config.rand(), hs.hello.random)
  237. if err != nil {
  238. c.sendAlert(alertInternalError)
  239. return false, err
  240. }
  241. hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported
  242. hs.hello.compressionMethod = compressionNone
  243. } else {
  244. hs.hello = new(serverHelloMsg)
  245. hs.hello13Enc = new(encryptedExtensionsMsg)
  246. hs.hello.vers = c.vers
  247. hs.hello.random = make([]byte, 32)
  248. hs.hello.sessionId = hs.clientHello.sessionId
  249. _, err = io.ReadFull(c.config.rand(), hs.hello.random)
  250. if err != nil {
  251. c.sendAlert(alertInternalError)
  252. return false, err
  253. }
  254. }
  255. if len(hs.clientHello.serverName) > 0 {
  256. c.serverName = hs.clientHello.serverName
  257. }
  258. if len(hs.clientHello.alpnProtocols) > 0 {
  259. if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback {
  260. if hs.hello != nil {
  261. hs.hello.alpnProtocol = selectedProto
  262. } else {
  263. hs.hello13Enc.alpnProtocol = selectedProto
  264. }
  265. c.clientProtocol = selectedProto
  266. }
  267. } else {
  268. // Although sending an empty NPN extension is reasonable, Firefox has
  269. // had a bug around this. Best to send nothing at all if
  270. // c.config.NextProtos is empty. See
  271. // https://golang.org/issue/5445.
  272. if hs.clientHello.nextProtoNeg && len(c.config.NextProtos) > 0 && c.vers < VersionTLS13 {
  273. hs.hello.nextProtoNeg = true
  274. hs.hello.nextProtos = c.config.NextProtos
  275. }
  276. }
  277. hs.cert, err = c.config.getCertificate(hs.clientHelloInfo())
  278. if err != nil {
  279. c.sendAlert(alertInternalError)
  280. return false, err
  281. }
  282. // Set the private key for this handshake to the certificate's secret key.
  283. hs.privateKey = hs.cert.PrivateKey
  284. if hs.clientHello.scts {
  285. hs.hello.scts = hs.cert.SignedCertificateTimestamps
  286. }
  287. // Set the private key to the DC private key if the client and server are
  288. // willing to negotiate the delegated credential extension.
  289. //
  290. // Check to see if a DelegatedCredential is available and should be used.
  291. // If one is available, the session is using TLS >= 1.2, and the client
  292. // accepts the delegated credential extension, then set the handshake
  293. // private key to the DC private key.
  294. if c.config.GetDelegatedCredential != nil && hs.clientHello.delegatedCredential && c.vers >= VersionTLS12 {
  295. dc, sk, err := c.config.GetDelegatedCredential(hs.clientHelloInfo(), c.vers)
  296. if err != nil {
  297. c.sendAlert(alertInternalError)
  298. return false, err
  299. }
  300. // Set the handshake private key.
  301. if dc != nil {
  302. hs.privateKey = sk
  303. hs.delegatedCredential = dc
  304. }
  305. }
  306. if priv, ok := hs.privateKey.(crypto.Signer); ok {
  307. switch priv.Public().(type) {
  308. case *ecdsa.PublicKey:
  309. hs.ecdsaOk = true
  310. case *rsa.PublicKey:
  311. hs.rsaSignOk = true
  312. default:
  313. c.sendAlert(alertInternalError)
  314. return false, fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public())
  315. }
  316. }
  317. if priv, ok := hs.privateKey.(crypto.Decrypter); ok {
  318. switch priv.Public().(type) {
  319. case *rsa.PublicKey:
  320. hs.rsaDecryptOk = true
  321. default:
  322. c.sendAlert(alertInternalError)
  323. return false, fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public())
  324. }
  325. }
  326. if c.vers != VersionTLS13 && hs.checkForResumption() {
  327. return true, nil
  328. }
  329. var preferenceList, supportedList []uint16
  330. if c.config.PreferServerCipherSuites {
  331. preferenceList = c.config.cipherSuites()
  332. supportedList = hs.clientHello.cipherSuites
  333. } else {
  334. preferenceList = hs.clientHello.cipherSuites
  335. supportedList = c.config.cipherSuites()
  336. }
  337. for _, id := range preferenceList {
  338. if hs.setCipherSuite(id, supportedList, c.vers) {
  339. break
  340. }
  341. }
  342. if hs.suite == nil {
  343. c.sendAlert(alertHandshakeFailure)
  344. return false, errors.New("tls: no cipher suite supported by both client and server")
  345. }
  346. // See https://tools.ietf.org/html/rfc7507.
  347. for _, id := range hs.clientHello.cipherSuites {
  348. if id == TLS_FALLBACK_SCSV {
  349. // The client is doing a fallback connection.
  350. if c.vers < c.config.maxVersion() {
  351. c.sendAlert(alertInappropriateFallback)
  352. return false, errors.New("tls: client using inappropriate protocol fallback")
  353. }
  354. break
  355. }
  356. }
  357. return false, nil
  358. }
  359. // checkForResumption reports whether we should perform resumption on this connection.
  360. func (hs *serverHandshakeState) checkForResumption() bool {
  361. c := hs.c
  362. if c.config.SessionTicketsDisabled {
  363. return false
  364. }
  365. sessionTicket := append([]uint8{}, hs.clientHello.sessionTicket...)
  366. serializedState, usedOldKey := c.decryptTicket(sessionTicket)
  367. hs.sessionState = &sessionState{usedOldKey: usedOldKey}
  368. if hs.sessionState.unmarshal(serializedState) != alertSuccess {
  369. return false
  370. }
  371. // Never resume a session for a different TLS version.
  372. if c.vers != hs.sessionState.vers {
  373. return false
  374. }
  375. cipherSuiteOk := false
  376. // Check that the client is still offering the ciphersuite in the session.
  377. for _, id := range hs.clientHello.cipherSuites {
  378. if id == hs.sessionState.cipherSuite {
  379. cipherSuiteOk = true
  380. break
  381. }
  382. }
  383. if !cipherSuiteOk {
  384. return false
  385. }
  386. // Check that we also support the ciphersuite from the session.
  387. if !hs.setCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers) {
  388. return false
  389. }
  390. sessionHasClientCerts := len(hs.sessionState.certificates) != 0
  391. needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert
  392. if needClientCerts && !sessionHasClientCerts {
  393. return false
  394. }
  395. if sessionHasClientCerts && c.config.ClientAuth == NoClientCert {
  396. return false
  397. }
  398. return true
  399. }
  400. func (hs *serverHandshakeState) doResumeHandshake() error {
  401. c := hs.c
  402. hs.hello.cipherSuite = hs.suite.id
  403. // We echo the client's session ID in the ServerHello to let it know
  404. // that we're doing a resumption.
  405. hs.hello.sessionId = hs.clientHello.sessionId
  406. hs.hello.ticketSupported = hs.sessionState.usedOldKey
  407. hs.finishedHash = newFinishedHash(c.vers, hs.suite)
  408. hs.finishedHash.discardHandshakeBuffer()
  409. hs.finishedHash.Write(hs.clientHello.marshal())
  410. hs.finishedHash.Write(hs.hello.marshal())
  411. if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
  412. return err
  413. }
  414. if len(hs.sessionState.certificates) > 0 {
  415. if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil {
  416. return err
  417. }
  418. }
  419. hs.masterSecret = hs.sessionState.masterSecret
  420. return nil
  421. }
  422. func (hs *serverHandshakeState) doFullHandshake() error {
  423. c := hs.c
  424. if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 {
  425. hs.hello.ocspStapling = true
  426. }
  427. hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled
  428. hs.hello.cipherSuite = hs.suite.id
  429. hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite)
  430. if c.config.ClientAuth == NoClientCert {
  431. // No need to keep a full record of the handshake if client
  432. // certificates won't be used.
  433. hs.finishedHash.discardHandshakeBuffer()
  434. }
  435. hs.finishedHash.Write(hs.clientHello.marshal())
  436. hs.finishedHash.Write(hs.hello.marshal())
  437. if _, err := c.writeRecord(recordTypeHandshake, hs.hello.marshal()); err != nil {
  438. return err
  439. }
  440. certMsg := new(certificateMsg)
  441. certMsg.certificates = hs.cert.Certificate
  442. hs.finishedHash.Write(certMsg.marshal())
  443. if _, err := c.writeRecord(recordTypeHandshake, certMsg.marshal()); err != nil {
  444. return err
  445. }
  446. if hs.hello.ocspStapling {
  447. certStatus := new(certificateStatusMsg)
  448. certStatus.statusType = statusTypeOCSP
  449. certStatus.response = hs.cert.OCSPStaple
  450. hs.finishedHash.Write(certStatus.marshal())
  451. if _, err := c.writeRecord(recordTypeHandshake, certStatus.marshal()); err != nil {
  452. return err
  453. }
  454. }
  455. keyAgreement := hs.suite.ka(c.vers)
  456. skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.privateKey, hs.clientHello, hs.hello)
  457. if err != nil {
  458. c.sendAlert(alertHandshakeFailure)
  459. return err
  460. }
  461. if skx != nil {
  462. hs.finishedHash.Write(skx.marshal())
  463. if _, err := c.writeRecord(recordTypeHandshake, skx.marshal()); err != nil {
  464. return err
  465. }
  466. }
  467. if c.config.ClientAuth >= RequestClientCert {
  468. // Request a client certificate
  469. certReq := new(certificateRequestMsg)
  470. certReq.certificateTypes = []byte{
  471. byte(certTypeRSASign),
  472. byte(certTypeECDSASign),
  473. }
  474. if c.vers >= VersionTLS12 {
  475. certReq.hasSignatureAndHash = true
  476. certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms
  477. }
  478. // An empty list of certificateAuthorities signals to
  479. // the client that it may send any certificate in response
  480. // to our request. When we know the CAs we trust, then
  481. // we can send them down, so that the client can choose
  482. // an appropriate certificate to give to us.
  483. if c.config.ClientCAs != nil {
  484. certReq.certificateAuthorities = c.config.ClientCAs.Subjects()
  485. }
  486. hs.finishedHash.Write(certReq.marshal())
  487. if _, err := c.writeRecord(recordTypeHandshake, certReq.marshal()); err != nil {
  488. return err
  489. }
  490. }
  491. helloDone := new(serverHelloDoneMsg)
  492. hs.finishedHash.Write(helloDone.marshal())
  493. if _, err := c.writeRecord(recordTypeHandshake, helloDone.marshal()); err != nil {
  494. return err
  495. }
  496. if _, err := c.flush(); err != nil {
  497. return err
  498. }
  499. var pub crypto.PublicKey // public key for client auth, if any
  500. msg, err := c.readHandshake()
  501. if err != nil {
  502. return err
  503. }
  504. var ok bool
  505. // If we requested a client certificate, then the client must send a
  506. // certificate message, even if it's empty.
  507. if c.config.ClientAuth >= RequestClientCert {
  508. if certMsg, ok = msg.(*certificateMsg); !ok {
  509. c.sendAlert(alertUnexpectedMessage)
  510. return unexpectedMessageError(certMsg, msg)
  511. }
  512. hs.finishedHash.Write(certMsg.marshal())
  513. if len(certMsg.certificates) == 0 {
  514. // The client didn't actually send a certificate
  515. switch c.config.ClientAuth {
  516. case RequireAnyClientCert, RequireAndVerifyClientCert:
  517. c.sendAlert(alertBadCertificate)
  518. return errors.New("tls: client didn't provide a certificate")
  519. }
  520. }
  521. pub, err = hs.processCertsFromClient(certMsg.certificates)
  522. if err != nil {
  523. return err
  524. }
  525. msg, err = c.readHandshake()
  526. if err != nil {
  527. return err
  528. }
  529. }
  530. // Get client key exchange
  531. ckx, ok := msg.(*clientKeyExchangeMsg)
  532. if !ok {
  533. c.sendAlert(alertUnexpectedMessage)
  534. return unexpectedMessageError(ckx, msg)
  535. }
  536. hs.finishedHash.Write(ckx.marshal())
  537. preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.privateKey, ckx, c.vers)
  538. if err != nil {
  539. if err == errClientKeyExchange {
  540. c.sendAlert(alertDecodeError)
  541. } else {
  542. c.sendAlert(alertInternalError)
  543. }
  544. return err
  545. }
  546. hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random)
  547. if err := c.config.writeKeyLog("CLIENT_RANDOM", hs.clientHello.random, hs.masterSecret); err != nil {
  548. c.sendAlert(alertInternalError)
  549. return err
  550. }
  551. // If we received a client cert in response to our certificate request message,
  552. // the client will send us a certificateVerifyMsg immediately after the
  553. // clientKeyExchangeMsg. This message is a digest of all preceding
  554. // handshake-layer messages that is signed using the private key corresponding
  555. // to the client's certificate. This allows us to verify that the client is in
  556. // possession of the private key of the certificate.
  557. if len(c.peerCertificates) > 0 {
  558. msg, err = c.readHandshake()
  559. if err != nil {
  560. return err
  561. }
  562. certVerify, ok := msg.(*certificateVerifyMsg)
  563. if !ok {
  564. c.sendAlert(alertUnexpectedMessage)
  565. return unexpectedMessageError(certVerify, msg)
  566. }
  567. // Determine the signature type.
  568. _, sigType, hashFunc, err := pickSignatureAlgorithm(pub, []SignatureScheme{certVerify.signatureAlgorithm}, supportedSignatureAlgorithms, c.vers)
  569. if err != nil {
  570. c.sendAlert(alertIllegalParameter)
  571. return err
  572. }
  573. var digest []byte
  574. if digest, err = hs.finishedHash.hashForClientCertificate(sigType, hashFunc, hs.masterSecret); err == nil {
  575. err = verifyHandshakeSignature(sigType, pub, hashFunc, digest, certVerify.signature)
  576. }
  577. if err != nil {
  578. c.sendAlert(alertBadCertificate)
  579. return errors.New("tls: could not validate signature of connection nonces: " + err.Error())
  580. }
  581. hs.finishedHash.Write(certVerify.marshal())
  582. }
  583. hs.finishedHash.discardHandshakeBuffer()
  584. return nil
  585. }
  586. func (hs *serverHandshakeState) establishKeys() error {
  587. c := hs.c
  588. clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV :=
  589. keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen)
  590. var clientCipher, serverCipher interface{}
  591. var clientHash, serverHash macFunction
  592. if hs.suite.aead == nil {
  593. clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */)
  594. clientHash = hs.suite.mac(c.vers, clientMAC)
  595. serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */)
  596. serverHash = hs.suite.mac(c.vers, serverMAC)
  597. } else {
  598. clientCipher = hs.suite.aead(clientKey, clientIV)
  599. serverCipher = hs.suite.aead(serverKey, serverIV)
  600. }
  601. c.in.prepareCipherSpec(c.vers, clientCipher, clientHash)
  602. c.out.prepareCipherSpec(c.vers, serverCipher, serverHash)
  603. return nil
  604. }
  605. func (hs *serverHandshakeState) readFinished(out []byte) error {
  606. c := hs.c
  607. c.readRecord(recordTypeChangeCipherSpec)
  608. if c.in.err != nil {
  609. return c.in.err
  610. }
  611. if hs.hello.nextProtoNeg {
  612. msg, err := c.readHandshake()
  613. if err != nil {
  614. return err
  615. }
  616. nextProto, ok := msg.(*nextProtoMsg)
  617. if !ok {
  618. c.sendAlert(alertUnexpectedMessage)
  619. return unexpectedMessageError(nextProto, msg)
  620. }
  621. hs.finishedHash.Write(nextProto.marshal())
  622. c.clientProtocol = nextProto.proto
  623. }
  624. msg, err := c.readHandshake()
  625. if err != nil {
  626. return err
  627. }
  628. clientFinished, ok := msg.(*finishedMsg)
  629. if !ok {
  630. c.sendAlert(alertUnexpectedMessage)
  631. return unexpectedMessageError(clientFinished, msg)
  632. }
  633. verify := hs.finishedHash.clientSum(hs.masterSecret)
  634. if len(verify) != len(clientFinished.verifyData) ||
  635. subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 {
  636. c.sendAlert(alertDecryptError)
  637. return errors.New("tls: client's Finished message is incorrect")
  638. }
  639. hs.finishedHash.Write(clientFinished.marshal())
  640. copy(out, verify)
  641. return nil
  642. }
  643. func (hs *serverHandshakeState) sendSessionTicket() error {
  644. if !hs.hello.ticketSupported {
  645. return nil
  646. }
  647. c := hs.c
  648. m := new(newSessionTicketMsg)
  649. var err error
  650. state := sessionState{
  651. vers: c.vers,
  652. cipherSuite: hs.suite.id,
  653. masterSecret: hs.masterSecret,
  654. certificates: hs.certsFromClient,
  655. }
  656. m.ticket, err = c.encryptTicket(state.marshal())
  657. if err != nil {
  658. return err
  659. }
  660. hs.finishedHash.Write(m.marshal())
  661. if _, err := c.writeRecord(recordTypeHandshake, m.marshal()); err != nil {
  662. return err
  663. }
  664. return nil
  665. }
  666. func (hs *serverHandshakeState) sendFinished(out []byte) error {
  667. c := hs.c
  668. if _, err := c.writeRecord(recordTypeChangeCipherSpec, []byte{1}); err != nil {
  669. return err
  670. }
  671. finished := new(finishedMsg)
  672. finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret)
  673. hs.finishedHash.Write(finished.marshal())
  674. if _, err := c.writeRecord(recordTypeHandshake, finished.marshal()); err != nil {
  675. return err
  676. }
  677. c.cipherSuite = hs.suite.id
  678. copy(out, finished.verifyData)
  679. return nil
  680. }
  681. // processCertsFromClient takes a chain of client certificates either from a
  682. // Certificates message or from a sessionState and verifies them. It returns
  683. // the public key of the leaf certificate.
  684. func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) {
  685. c := hs.c
  686. hs.certsFromClient = certificates
  687. certs := make([]*x509.Certificate, len(certificates))
  688. var err error
  689. for i, asn1Data := range certificates {
  690. if certs[i], err = x509.ParseCertificate(asn1Data); err != nil {
  691. c.sendAlert(alertBadCertificate)
  692. return nil, errors.New("tls: failed to parse client certificate: " + err.Error())
  693. }
  694. }
  695. if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 {
  696. opts := x509.VerifyOptions{
  697. Roots: c.config.ClientCAs,
  698. CurrentTime: c.config.time(),
  699. Intermediates: x509.NewCertPool(),
  700. KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
  701. }
  702. for _, cert := range certs[1:] {
  703. opts.Intermediates.AddCert(cert)
  704. }
  705. chains, err := certs[0].Verify(opts)
  706. if err != nil {
  707. c.sendAlert(alertBadCertificate)
  708. return nil, errors.New("tls: failed to verify client's certificate: " + err.Error())
  709. }
  710. c.verifiedChains = chains
  711. }
  712. if c.config.VerifyPeerCertificate != nil {
  713. if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil {
  714. c.sendAlert(alertBadCertificate)
  715. return nil, err
  716. }
  717. }
  718. if len(certs) == 0 {
  719. return nil, nil
  720. }
  721. var pub crypto.PublicKey
  722. switch key := certs[0].PublicKey.(type) {
  723. case *ecdsa.PublicKey, *rsa.PublicKey:
  724. pub = key
  725. default:
  726. c.sendAlert(alertUnsupportedCertificate)
  727. return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey)
  728. }
  729. c.peerCertificates = certs
  730. return pub, nil
  731. }
  732. // setCipherSuite sets a cipherSuite with the given id as the serverHandshakeState
  733. // suite if that cipher suite is acceptable to use.
  734. // It returns a bool indicating if the suite was set.
  735. func (hs *serverHandshakeState) setCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16) bool {
  736. for _, supported := range supportedCipherSuites {
  737. if id == supported {
  738. var candidate *cipherSuite
  739. for _, s := range cipherSuites {
  740. if s.id == id {
  741. candidate = s
  742. break
  743. }
  744. }
  745. if candidate == nil {
  746. continue
  747. }
  748. if version >= VersionTLS13 && candidate.flags&suiteTLS13 != 0 {
  749. hs.suite = candidate
  750. return true
  751. }
  752. if version < VersionTLS13 && candidate.flags&suiteTLS13 != 0 {
  753. continue
  754. }
  755. // Don't select a ciphersuite which we can't
  756. // support for this client.
  757. if candidate.flags&suiteECDHE != 0 {
  758. if !hs.ellipticOk {
  759. continue
  760. }
  761. if candidate.flags&suiteECDSA != 0 {
  762. if !hs.ecdsaOk {
  763. continue
  764. }
  765. } else if !hs.rsaSignOk {
  766. continue
  767. }
  768. } else if !hs.rsaDecryptOk {
  769. continue
  770. }
  771. if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 {
  772. continue
  773. }
  774. hs.suite = candidate
  775. return true
  776. }
  777. }
  778. return false
  779. }
  780. // suppVersArray is the backing array of ClientHelloInfo.SupportedVersions
  781. var suppVersArray = [...]uint16{VersionTLS12, VersionTLS11, VersionTLS10, VersionSSL30}
  782. func (hs *serverHandshakeState) clientHelloInfo() *ClientHelloInfo {
  783. if hs.cachedClientHelloInfo != nil {
  784. return hs.cachedClientHelloInfo
  785. }
  786. var supportedVersions []uint16
  787. if hs.clientHello.supportedVersions != nil {
  788. supportedVersions = hs.clientHello.supportedVersions
  789. } else if hs.clientHello.vers > VersionTLS12 {
  790. supportedVersions = suppVersArray[:]
  791. } else if hs.clientHello.vers >= VersionSSL30 {
  792. supportedVersions = suppVersArray[VersionTLS12-hs.clientHello.vers:]
  793. }
  794. var pskBinder []byte
  795. if len(hs.clientHello.psks) > 0 {
  796. pskBinder = hs.clientHello.psks[0].binder
  797. }
  798. hs.cachedClientHelloInfo = &ClientHelloInfo{
  799. CipherSuites: hs.clientHello.cipherSuites,
  800. ServerName: hs.clientHello.serverName,
  801. SupportedCurves: hs.clientHello.supportedCurves,
  802. SupportedPoints: hs.clientHello.supportedPoints,
  803. SignatureSchemes: hs.clientHello.supportedSignatureAlgorithms,
  804. SupportedProtos: hs.clientHello.alpnProtocols,
  805. SupportedVersions: supportedVersions,
  806. Conn: hs.c.conn,
  807. Offered0RTTData: hs.clientHello.earlyData,
  808. AcceptsDelegatedCredential: hs.clientHello.delegatedCredential,
  809. Fingerprint: pskBinder,
  810. }
  811. return hs.cachedClientHelloInfo
  812. }