tls.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. // Copyright 2023 The frp Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package transport
  15. import (
  16. "crypto/rand"
  17. "crypto/rsa"
  18. "crypto/tls"
  19. "crypto/x509"
  20. "encoding/pem"
  21. "math/big"
  22. "os"
  23. "time"
  24. )
  25. func newCustomTLSKeyPair(certfile, keyfile string) (*tls.Certificate, error) {
  26. tlsCert, err := tls.LoadX509KeyPair(certfile, keyfile)
  27. if err != nil {
  28. return nil, err
  29. }
  30. return &tlsCert, nil
  31. }
  32. func newRandomTLSKeyPair() (*tls.Certificate, error) {
  33. key, err := rsa.GenerateKey(rand.Reader, 2048)
  34. if err != nil {
  35. return nil, err
  36. }
  37. // Generate a random positive serial number with 128 bits of entropy.
  38. // RFC 5280 requires serial numbers to be positive integers (not zero).
  39. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  40. serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
  41. if err != nil {
  42. return nil, err
  43. }
  44. // Ensure serial number is positive (not zero)
  45. if serialNumber.Sign() == 0 {
  46. serialNumber = big.NewInt(1)
  47. }
  48. template := x509.Certificate{
  49. SerialNumber: serialNumber,
  50. NotBefore: time.Now().Add(-1 * time.Hour),
  51. NotAfter: time.Now().Add(365 * 24 * time.Hour * 10),
  52. }
  53. certDER, err := x509.CreateCertificate(
  54. rand.Reader,
  55. &template,
  56. &template,
  57. &key.PublicKey,
  58. key)
  59. if err != nil {
  60. return nil, err
  61. }
  62. keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
  63. certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
  64. tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
  65. if err != nil {
  66. return nil, err
  67. }
  68. return &tlsCert, nil
  69. }
  70. // Only support one ca file to add
  71. func newCertPool(caPath string) (*x509.CertPool, error) {
  72. pool := x509.NewCertPool()
  73. caCrt, err := os.ReadFile(caPath)
  74. if err != nil {
  75. return nil, err
  76. }
  77. pool.AppendCertsFromPEM(caCrt)
  78. return pool, nil
  79. }
  80. func NewServerTLSConfig(certPath, keyPath, caPath string) (*tls.Config, error) {
  81. base := &tls.Config{}
  82. if certPath == "" || keyPath == "" {
  83. // server will generate tls conf by itself
  84. cert, err := newRandomTLSKeyPair()
  85. if err != nil {
  86. return nil, err
  87. }
  88. base.Certificates = []tls.Certificate{*cert}
  89. } else {
  90. cert, err := newCustomTLSKeyPair(certPath, keyPath)
  91. if err != nil {
  92. return nil, err
  93. }
  94. base.Certificates = []tls.Certificate{*cert}
  95. }
  96. if caPath != "" {
  97. pool, err := newCertPool(caPath)
  98. if err != nil {
  99. return nil, err
  100. }
  101. base.ClientAuth = tls.RequireAndVerifyClientCert
  102. base.ClientCAs = pool
  103. }
  104. return base, nil
  105. }
  106. func NewClientTLSConfig(certPath, keyPath, caPath, serverName string) (*tls.Config, error) {
  107. base := &tls.Config{}
  108. if certPath != "" && keyPath != "" {
  109. cert, err := newCustomTLSKeyPair(certPath, keyPath)
  110. if err != nil {
  111. return nil, err
  112. }
  113. base.Certificates = []tls.Certificate{*cert}
  114. }
  115. base.ServerName = serverName
  116. if caPath != "" {
  117. pool, err := newCertPool(caPath)
  118. if err != nil {
  119. return nil, err
  120. }
  121. base.RootCAs = pool
  122. base.InsecureSkipVerify = false
  123. } else {
  124. base.InsecureSkipVerify = true
  125. }
  126. return base, nil
  127. }
  128. func NewRandomPrivateKey() ([]byte, error) {
  129. key, err := rsa.GenerateKey(rand.Reader, 2048)
  130. if err != nil {
  131. return nil, err
  132. }
  133. keyPEM := pem.EncodeToMemory(&pem.Block{
  134. Type: "RSA PRIVATE KEY",
  135. Bytes: x509.MarshalPKCS1PrivateKey(key),
  136. })
  137. return keyPEM, nil
  138. }