tlsutil.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. func NewCertificate(certFile, keyFile, tlsDefaultCommonName string, tlsRSABits int) (tls.Certificate, error) {
  24. priv, err := rsa.GenerateKey(rand.Reader, tlsRSABits)
  25. if err != nil {
  26. return tls.Certificate{}, fmt.Errorf("generate key: %s", err)
  27. }
  28. notBefore := time.Now()
  29. notAfter := time.Date(2049, 12, 31, 23, 59, 59, 0, time.UTC)
  30. template := x509.Certificate{
  31. SerialNumber: new(big.Int).SetInt64(mr.Int63()),
  32. Subject: pkix.Name{
  33. CommonName: tlsDefaultCommonName,
  34. },
  35. NotBefore: notBefore,
  36. NotAfter: notAfter,
  37. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  38. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
  39. BasicConstraintsValid: true,
  40. }
  41. derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
  42. if err != nil {
  43. return tls.Certificate{}, fmt.Errorf("create cert: %s", err)
  44. }
  45. certOut, err := os.Create(certFile)
  46. if err != nil {
  47. return tls.Certificate{}, fmt.Errorf("save cert: %s", err)
  48. }
  49. err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
  50. if err != nil {
  51. return tls.Certificate{}, fmt.Errorf("save cert: %s", err)
  52. }
  53. err = certOut.Close()
  54. if err != nil {
  55. return tls.Certificate{}, fmt.Errorf("save cert: %s", err)
  56. }
  57. keyOut, err := os.OpenFile(keyFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
  58. if err != nil {
  59. return tls.Certificate{}, fmt.Errorf("save key: %s", err)
  60. }
  61. err = pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
  62. if err != nil {
  63. return tls.Certificate{}, fmt.Errorf("save key: %s", err)
  64. }
  65. err = keyOut.Close()
  66. if err != nil {
  67. return tls.Certificate{}, fmt.Errorf("save key: %s", err)
  68. }
  69. return tls.LoadX509KeyPair(certFile, keyFile)
  70. }
  71. type DowngradingListener struct {
  72. net.Listener
  73. TLSConfig *tls.Config
  74. }
  75. func (l *DowngradingListener) Accept() (net.Conn, error) {
  76. conn, err := l.Listener.Accept()
  77. if err != nil {
  78. return nil, err
  79. }
  80. br := bufio.NewReader(conn)
  81. conn.SetReadDeadline(time.Now().Add(1 * time.Second))
  82. bs, err := br.Peek(1)
  83. conn.SetReadDeadline(time.Time{})
  84. if err != nil {
  85. // We hit a read error here, but the Accept() call succeeded so we must not return an error.
  86. // We return the connection as is and let whoever tries to use it deal with the error.
  87. return conn, nil
  88. }
  89. wrapper := &WrappedConnection{br, conn}
  90. // 0x16 is the first byte of a TLS handshake
  91. if bs[0] == 0x16 {
  92. return tls.Server(wrapper, l.TLSConfig), nil
  93. }
  94. return wrapper, nil
  95. }
  96. type WrappedConnection struct {
  97. io.Reader
  98. net.Conn
  99. }
  100. func (c *WrappedConnection) Read(b []byte) (n int, err error) {
  101. return c.Reader.Read(b)
  102. }