tlsutil.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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. SignatureAlgorithm: x509.SHA256WithRSA,
  44. }
  45. derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
  46. if err != nil {
  47. return tls.Certificate{}, fmt.Errorf("create cert: %s", err)
  48. }
  49. certOut, err := os.Create(certFile)
  50. if err != nil {
  51. return tls.Certificate{}, fmt.Errorf("save cert: %s", err)
  52. }
  53. err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
  54. if err != nil {
  55. return tls.Certificate{}, fmt.Errorf("save cert: %s", err)
  56. }
  57. err = certOut.Close()
  58. if err != nil {
  59. return tls.Certificate{}, fmt.Errorf("save cert: %s", err)
  60. }
  61. keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
  62. if err != nil {
  63. return tls.Certificate{}, fmt.Errorf("save key: %s", err)
  64. }
  65. err = pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
  66. if err != nil {
  67. return tls.Certificate{}, fmt.Errorf("save key: %s", err)
  68. }
  69. err = keyOut.Close()
  70. if err != nil {
  71. return tls.Certificate{}, fmt.Errorf("save key: %s", err)
  72. }
  73. return tls.LoadX509KeyPair(certFile, keyFile)
  74. }
  75. type DowngradingListener struct {
  76. net.Listener
  77. TLSConfig *tls.Config
  78. }
  79. func (l *DowngradingListener) Accept() (net.Conn, error) {
  80. conn, isTLS, err := l.AcceptNoWrapTLS()
  81. // We failed to identify the socket type, pretend that everything is fine,
  82. // and pass it to the underlying handler, and let them deal with it.
  83. if err == ErrIdentificationFailed {
  84. return conn, nil
  85. }
  86. if err != nil {
  87. return conn, err
  88. }
  89. if isTLS {
  90. return tls.Server(conn, l.TLSConfig), nil
  91. }
  92. return conn, nil
  93. }
  94. func (l *DowngradingListener) AcceptNoWrapTLS() (net.Conn, bool, error) {
  95. conn, err := l.Listener.Accept()
  96. if err != nil {
  97. return nil, false, err
  98. }
  99. br := bufio.NewReader(conn)
  100. conn.SetReadDeadline(time.Now().Add(1 * time.Second))
  101. bs, err := br.Peek(1)
  102. conn.SetReadDeadline(time.Time{})
  103. if err != nil {
  104. // We hit a read error here, but the Accept() call succeeded so we must not return an error.
  105. // We return the connection as is with a special error which handles this
  106. // special case in Accept().
  107. return conn, false, ErrIdentificationFailed
  108. }
  109. return &UnionedConnection{br, conn}, bs[0] == 0x16, nil
  110. }
  111. type UnionedConnection struct {
  112. io.Reader
  113. net.Conn
  114. }
  115. func (c *UnionedConnection) Read(b []byte) (n int, err error) {
  116. return c.Reader.Read(b)
  117. }