Alternative TLS implementation in Go
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

290 lines
8.4 KiB

  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/hmac"
  7. "crypto/rc4"
  8. "crypto/rsa"
  9. "crypto/subtle"
  10. "crypto/x509"
  11. "io"
  12. "os"
  13. )
  14. func (c *Conn) clientHandshake() os.Error {
  15. finishedHash := newFinishedHash()
  16. if c.config == nil {
  17. c.config = defaultConfig()
  18. }
  19. hello := &clientHelloMsg{
  20. vers: maxVersion,
  21. cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA},
  22. compressionMethods: []uint8{compressionNone},
  23. random: make([]byte, 32),
  24. ocspStapling: true,
  25. serverName: c.config.ServerName,
  26. }
  27. t := uint32(c.config.Time())
  28. hello.random[0] = byte(t >> 24)
  29. hello.random[1] = byte(t >> 16)
  30. hello.random[2] = byte(t >> 8)
  31. hello.random[3] = byte(t)
  32. _, err := io.ReadFull(c.config.Rand, hello.random[4:])
  33. if err != nil {
  34. c.sendAlert(alertInternalError)
  35. return os.ErrorString("short read from Rand")
  36. }
  37. finishedHash.Write(hello.marshal())
  38. c.writeRecord(recordTypeHandshake, hello.marshal())
  39. msg, err := c.readHandshake()
  40. if err != nil {
  41. return err
  42. }
  43. serverHello, ok := msg.(*serverHelloMsg)
  44. if !ok {
  45. return c.sendAlert(alertUnexpectedMessage)
  46. }
  47. finishedHash.Write(serverHello.marshal())
  48. vers, ok := mutualVersion(serverHello.vers)
  49. if !ok {
  50. c.sendAlert(alertProtocolVersion)
  51. }
  52. c.vers = vers
  53. c.haveVers = true
  54. if serverHello.cipherSuite != TLS_RSA_WITH_RC4_128_SHA ||
  55. serverHello.compressionMethod != compressionNone {
  56. return c.sendAlert(alertUnexpectedMessage)
  57. }
  58. msg, err = c.readHandshake()
  59. if err != nil {
  60. return err
  61. }
  62. certMsg, ok := msg.(*certificateMsg)
  63. if !ok || len(certMsg.certificates) == 0 {
  64. return c.sendAlert(alertUnexpectedMessage)
  65. }
  66. finishedHash.Write(certMsg.marshal())
  67. certs := make([]*x509.Certificate, len(certMsg.certificates))
  68. for i, asn1Data := range certMsg.certificates {
  69. cert, err := x509.ParseCertificate(asn1Data)
  70. if err != nil {
  71. c.sendAlert(alertBadCertificate)
  72. return os.ErrorString("failed to parse certificate from server: " + err.String())
  73. }
  74. certs[i] = cert
  75. }
  76. for i := 1; i < len(certs); i++ {
  77. if !certs[i].BasicConstraintsValid || !certs[i].IsCA {
  78. c.sendAlert(alertBadCertificate)
  79. return os.ErrorString("intermediate certificate does not have CA bit set")
  80. }
  81. // KeyUsage status flags are ignored. From Engineering
  82. // Security, Peter Gutmann:
  83. // A European government CA marked its signing certificates as
  84. // being valid for encryption only, but no-one noticed. Another
  85. // European CA marked its signature keys as not being valid for
  86. // signatures. A different CA marked its own trusted root
  87. // certificate as being invalid for certificate signing.
  88. // Another national CA distributed a certificate to be used to
  89. // encrypt data for the country’s tax authority that was marked
  90. // as only being usable for digital signatures but not for
  91. // encryption. Yet another CA reversed the order of the bit
  92. // flags in the keyUsage due to confusion over encoding
  93. // endianness, essentially setting a random keyUsage in
  94. // certificates that it issued. Another CA created a
  95. // self-invalidating certificate by adding a certificate policy
  96. // statement stipulating that the certificate had to be used
  97. // strictly as specified in the keyUsage, and a keyUsage
  98. // containing a flag indicating that the RSA encryption key
  99. // could only be used for Diffie-Hellman key agreement.
  100. if err := certs[i-1].CheckSignatureFrom(certs[i]); err != nil {
  101. c.sendAlert(alertBadCertificate)
  102. return os.ErrorString("could not validate certificate signature: " + err.String())
  103. }
  104. }
  105. // TODO(rsc): Find certificates for OS X 10.6.
  106. if c.config.RootCAs != nil {
  107. root := c.config.RootCAs.FindParent(certs[len(certs)-1])
  108. if root == nil {
  109. c.sendAlert(alertBadCertificate)
  110. return os.ErrorString("could not find root certificate for chain")
  111. }
  112. if err := certs[len(certs)-1].CheckSignatureFrom(root); err != nil {
  113. c.sendAlert(alertBadCertificate)
  114. return os.ErrorString("could not validate signature from expected root: " + err.String())
  115. }
  116. }
  117. pub, ok := certs[0].PublicKey.(*rsa.PublicKey)
  118. if !ok {
  119. return c.sendAlert(alertUnsupportedCertificate)
  120. }
  121. c.peerCertificates = certs
  122. if serverHello.certStatus {
  123. msg, err = c.readHandshake()
  124. if err != nil {
  125. return err
  126. }
  127. cs, ok := msg.(*certificateStatusMsg)
  128. if !ok {
  129. return c.sendAlert(alertUnexpectedMessage)
  130. }
  131. finishedHash.Write(cs.marshal())
  132. if cs.statusType == statusTypeOCSP {
  133. c.ocspResponse = cs.response
  134. }
  135. }
  136. msg, err = c.readHandshake()
  137. if err != nil {
  138. return err
  139. }
  140. transmitCert := false
  141. certReq, ok := msg.(*certificateRequestMsg)
  142. if ok {
  143. // We only accept certificates with RSA keys.
  144. rsaAvail := false
  145. for _, certType := range certReq.certificateTypes {
  146. if certType == certTypeRSASign {
  147. rsaAvail = true
  148. break
  149. }
  150. }
  151. // For now, only send a certificate back if the server gives us an
  152. // empty list of certificateAuthorities.
  153. //
  154. // RFC 4346 on the certificateAuthorities field:
  155. // A list of the distinguished names of acceptable certificate
  156. // authorities. These distinguished names may specify a desired
  157. // distinguished name for a root CA or for a subordinate CA; thus,
  158. // this message can be used to describe both known roots and a
  159. // desired authorization space. If the certificate_authorities
  160. // list is empty then the client MAY send any certificate of the
  161. // appropriate ClientCertificateType, unless there is some
  162. // external arrangement to the contrary.
  163. if rsaAvail && len(certReq.certificateAuthorities) == 0 {
  164. transmitCert = true
  165. }
  166. finishedHash.Write(certReq.marshal())
  167. msg, err = c.readHandshake()
  168. if err != nil {
  169. return err
  170. }
  171. }
  172. shd, ok := msg.(*serverHelloDoneMsg)
  173. if !ok {
  174. return c.sendAlert(alertUnexpectedMessage)
  175. }
  176. finishedHash.Write(shd.marshal())
  177. var cert *x509.Certificate
  178. if transmitCert {
  179. certMsg = new(certificateMsg)
  180. if len(c.config.Certificates) > 0 {
  181. cert, err = x509.ParseCertificate(c.config.Certificates[0].Certificate[0])
  182. if err == nil && cert.PublicKeyAlgorithm == x509.RSA {
  183. certMsg.certificates = c.config.Certificates[0].Certificate
  184. } else {
  185. cert = nil
  186. }
  187. }
  188. finishedHash.Write(certMsg.marshal())
  189. c.writeRecord(recordTypeHandshake, certMsg.marshal())
  190. }
  191. ckx := new(clientKeyExchangeMsg)
  192. preMasterSecret := make([]byte, 48)
  193. preMasterSecret[0] = byte(hello.vers >> 8)
  194. preMasterSecret[1] = byte(hello.vers)
  195. _, err = io.ReadFull(c.config.Rand, preMasterSecret[2:])
  196. if err != nil {
  197. return c.sendAlert(alertInternalError)
  198. }
  199. ckx.ciphertext, err = rsa.EncryptPKCS1v15(c.config.Rand, pub, preMasterSecret)
  200. if err != nil {
  201. return c.sendAlert(alertInternalError)
  202. }
  203. finishedHash.Write(ckx.marshal())
  204. c.writeRecord(recordTypeHandshake, ckx.marshal())
  205. if cert != nil {
  206. certVerify := new(certificateVerifyMsg)
  207. var digest [36]byte
  208. copy(digest[0:16], finishedHash.serverMD5.Sum())
  209. copy(digest[16:36], finishedHash.serverSHA1.Sum())
  210. signed, err := rsa.SignPKCS1v15(c.config.Rand, c.config.Certificates[0].PrivateKey, rsa.HashMD5SHA1, digest[0:])
  211. if err != nil {
  212. return c.sendAlert(alertInternalError)
  213. }
  214. certVerify.signature = signed
  215. finishedHash.Write(certVerify.marshal())
  216. c.writeRecord(recordTypeHandshake, certVerify.marshal())
  217. }
  218. suite := cipherSuites[0]
  219. masterSecret, clientMAC, serverMAC, clientKey, serverKey :=
  220. keysFromPreMasterSecret11(preMasterSecret, hello.random, serverHello.random, suite.hashLength, suite.cipherKeyLength)
  221. cipher, _ := rc4.NewCipher(clientKey)
  222. c.out.prepareCipherSpec(cipher, hmac.NewSHA1(clientMAC))
  223. c.writeRecord(recordTypeChangeCipherSpec, []byte{1})
  224. finished := new(finishedMsg)
  225. finished.verifyData = finishedHash.clientSum(masterSecret)
  226. finishedHash.Write(finished.marshal())
  227. c.writeRecord(recordTypeHandshake, finished.marshal())
  228. cipher2, _ := rc4.NewCipher(serverKey)
  229. c.in.prepareCipherSpec(cipher2, hmac.NewSHA1(serverMAC))
  230. c.readRecord(recordTypeChangeCipherSpec)
  231. if c.err != nil {
  232. return c.err
  233. }
  234. msg, err = c.readHandshake()
  235. if err != nil {
  236. return err
  237. }
  238. serverFinished, ok := msg.(*finishedMsg)
  239. if !ok {
  240. return c.sendAlert(alertUnexpectedMessage)
  241. }
  242. verify := finishedHash.serverSum(masterSecret)
  243. if len(verify) != len(serverFinished.verifyData) ||
  244. subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 {
  245. return c.sendAlert(alertHandshakeFailure)
  246. }
  247. c.handshakeComplete = true
  248. c.cipherSuite = TLS_RSA_WITH_RC4_128_SHA
  249. return nil
  250. }