tlsutil.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package tlsutil
  7. import (
  8. "bufio"
  9. "crypto/rand"
  10. "crypto/rsa"
  11. "crypto/tls"
  12. "crypto/x509"
  13. "crypto/x509/pkix"
  14. "encoding/pem"
  15. "fmt"
  16. "io"
  17. "math/big"
  18. mr "math/rand"
  19. "net"
  20. "os"
  21. "time"
  22. )
  23. var (
  24. ErrIdentificationFailed = fmt.Errorf("failed to identify socket type")
  25. )
  26. func NewCertificate(certFile, keyFile, tlsDefaultCommonName string, tlsRSABits int) (tls.Certificate, error) {
  27. priv, err := rsa.GenerateKey(rand.Reader, tlsRSABits)
  28. if err != nil {
  29. return tls.Certificate{}, fmt.Errorf("generate key: %s", err)
  30. }
  31. notBefore := time.Now()
  32. notAfter := time.Date(2049, 12, 31, 23, 59, 59, 0, time.UTC)
  33. template := x509.Certificate{
  34. SerialNumber: new(big.Int).SetInt64(mr.Int63()),
  35. Subject: pkix.Name{
  36. CommonName: tlsDefaultCommonName,
  37. },
  38. NotBefore: notBefore,
  39. NotAfter: notAfter,
  40. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  41. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
  42. BasicConstraintsValid: true,
  43. }
  44. derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
  45. if err != nil {
  46. return tls.Certificate{}, fmt.Errorf("create cert: %s", err)
  47. }
  48. certOut, err := os.Create(certFile)
  49. if err != nil {
  50. return tls.Certificate{}, fmt.Errorf("save cert: %s", err)
  51. }
  52. err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
  53. if err != nil {
  54. return tls.Certificate{}, fmt.Errorf("save cert: %s", err)
  55. }
  56. err = certOut.Close()
  57. if err != nil {
  58. return tls.Certificate{}, fmt.Errorf("save cert: %s", err)
  59. }
  60. keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
  61. if err != nil {
  62. return tls.Certificate{}, fmt.Errorf("save key: %s", err)
  63. }
  64. err = pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
  65. if err != nil {
  66. return tls.Certificate{}, fmt.Errorf("save key: %s", err)
  67. }
  68. err = keyOut.Close()
  69. if err != nil {
  70. return tls.Certificate{}, fmt.Errorf("save key: %s", err)
  71. }
  72. return tls.LoadX509KeyPair(certFile, keyFile)
  73. }
  74. type DowngradingListener struct {
  75. net.Listener
  76. TLSConfig *tls.Config
  77. }
  78. func (l *DowngradingListener) Accept() (net.Conn, error) {
  79. conn, isTLS, err := l.AcceptNoWrapTLS()
  80. // We failed to identify the socket type, pretend that everything is fine,
  81. // and pass it to the underlying handler, and let them deal with it.
  82. if err == ErrIdentificationFailed {
  83. return conn, nil
  84. }
  85. if err != nil {
  86. return conn, err
  87. }
  88. if isTLS {
  89. return tls.Server(conn, l.TLSConfig), nil
  90. }
  91. return conn, nil
  92. }
  93. func (l *DowngradingListener) AcceptNoWrapTLS() (net.Conn, bool, error) {
  94. conn, err := l.Listener.Accept()
  95. if err != nil {
  96. return nil, false, err
  97. }
  98. br := bufio.NewReader(conn)
  99. conn.SetReadDeadline(time.Now().Add(1 * time.Second))
  100. bs, err := br.Peek(1)
  101. conn.SetReadDeadline(time.Time{})
  102. if err != nil {
  103. // We hit a read error here, but the Accept() call succeeded so we must not return an error.
  104. // We return the connection as is with a special error which handles this
  105. // special case in Accept().
  106. return conn, false, ErrIdentificationFailed
  107. }
  108. return &UnionedConnection{br, conn}, bs[0] == 0x16, nil
  109. }
  110. type UnionedConnection struct {
  111. io.Reader
  112. net.Conn
  113. }
  114. func (c *UnionedConnection) Read(b []byte) (n int, err error) {
  115. return c.Reader.Read(b)
  116. }