certificate.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. //go:build !js
  4. // +build !js
  5. package webrtc
  6. import (
  7. "crypto"
  8. "crypto/ecdsa"
  9. "crypto/rand"
  10. "crypto/rsa"
  11. "crypto/x509"
  12. "crypto/x509/pkix"
  13. "encoding/base64"
  14. "encoding/pem"
  15. "fmt"
  16. "math/big"
  17. "strings"
  18. "time"
  19. "github.com/pion/dtls/v2/pkg/crypto/fingerprint"
  20. "github.com/pion/webrtc/v3/pkg/rtcerr"
  21. )
  22. // Certificate represents a x509Cert used to authenticate WebRTC communications.
  23. type Certificate struct {
  24. privateKey crypto.PrivateKey
  25. x509Cert *x509.Certificate
  26. statsID string
  27. }
  28. // NewCertificate generates a new x509 compliant Certificate to be used
  29. // by DTLS for encrypting data sent over the wire. This method differs from
  30. // GenerateCertificate by allowing to specify a template x509.Certificate to
  31. // be used in order to define certificate parameters.
  32. func NewCertificate(key crypto.PrivateKey, tpl x509.Certificate) (*Certificate, error) {
  33. var err error
  34. var certDER []byte
  35. switch sk := key.(type) {
  36. case *rsa.PrivateKey:
  37. pk := sk.Public()
  38. tpl.SignatureAlgorithm = x509.SHA256WithRSA
  39. certDER, err = x509.CreateCertificate(rand.Reader, &tpl, &tpl, pk, sk)
  40. if err != nil {
  41. return nil, &rtcerr.UnknownError{Err: err}
  42. }
  43. case *ecdsa.PrivateKey:
  44. pk := sk.Public()
  45. tpl.SignatureAlgorithm = x509.ECDSAWithSHA256
  46. certDER, err = x509.CreateCertificate(rand.Reader, &tpl, &tpl, pk, sk)
  47. if err != nil {
  48. return nil, &rtcerr.UnknownError{Err: err}
  49. }
  50. default:
  51. return nil, &rtcerr.NotSupportedError{Err: ErrPrivateKeyType}
  52. }
  53. cert, err := x509.ParseCertificate(certDER)
  54. if err != nil {
  55. return nil, &rtcerr.UnknownError{Err: err}
  56. }
  57. return &Certificate{privateKey: key, x509Cert: cert, statsID: fmt.Sprintf("certificate-%d", time.Now().UnixNano())}, nil
  58. }
  59. // Equals determines if two certificates are identical by comparing both the
  60. // secretKeys and x509Certificates.
  61. func (c Certificate) Equals(o Certificate) bool {
  62. switch cSK := c.privateKey.(type) {
  63. case *rsa.PrivateKey:
  64. if oSK, ok := o.privateKey.(*rsa.PrivateKey); ok {
  65. if cSK.N.Cmp(oSK.N) != 0 {
  66. return false
  67. }
  68. return c.x509Cert.Equal(o.x509Cert)
  69. }
  70. return false
  71. case *ecdsa.PrivateKey:
  72. if oSK, ok := o.privateKey.(*ecdsa.PrivateKey); ok {
  73. if cSK.X.Cmp(oSK.X) != 0 || cSK.Y.Cmp(oSK.Y) != 0 {
  74. return false
  75. }
  76. return c.x509Cert.Equal(o.x509Cert)
  77. }
  78. return false
  79. default:
  80. return false
  81. }
  82. }
  83. // Expires returns the timestamp after which this certificate is no longer valid.
  84. func (c Certificate) Expires() time.Time {
  85. if c.x509Cert == nil {
  86. return time.Time{}
  87. }
  88. return c.x509Cert.NotAfter
  89. }
  90. // GetFingerprints returns the list of certificate fingerprints, one of which
  91. // is computed with the digest algorithm used in the certificate signature.
  92. func (c Certificate) GetFingerprints() ([]DTLSFingerprint, error) {
  93. fingerprintAlgorithms := []crypto.Hash{crypto.SHA256}
  94. res := make([]DTLSFingerprint, len(fingerprintAlgorithms))
  95. i := 0
  96. for _, algo := range fingerprintAlgorithms {
  97. name, err := fingerprint.StringFromHash(algo)
  98. if err != nil {
  99. // nolint
  100. return nil, fmt.Errorf("%w: %v", ErrFailedToGenerateCertificateFingerprint, err)
  101. }
  102. value, err := fingerprint.Fingerprint(c.x509Cert, algo)
  103. if err != nil {
  104. // nolint
  105. return nil, fmt.Errorf("%w: %v", ErrFailedToGenerateCertificateFingerprint, err)
  106. }
  107. res[i] = DTLSFingerprint{
  108. Algorithm: name,
  109. Value: value,
  110. }
  111. }
  112. return res[:i+1], nil
  113. }
  114. // GenerateCertificate causes the creation of an X.509 certificate and
  115. // corresponding private key.
  116. func GenerateCertificate(secretKey crypto.PrivateKey) (*Certificate, error) {
  117. // Max random value, a 130-bits integer, i.e 2^130 - 1
  118. maxBigInt := new(big.Int)
  119. /* #nosec */
  120. maxBigInt.Exp(big.NewInt(2), big.NewInt(130), nil).Sub(maxBigInt, big.NewInt(1))
  121. /* #nosec */
  122. serialNumber, err := rand.Int(rand.Reader, maxBigInt)
  123. if err != nil {
  124. return nil, &rtcerr.UnknownError{Err: err}
  125. }
  126. return NewCertificate(secretKey, x509.Certificate{
  127. Issuer: pkix.Name{CommonName: generatedCertificateOrigin},
  128. NotBefore: time.Now().AddDate(0, 0, -1),
  129. NotAfter: time.Now().AddDate(0, 1, -1),
  130. SerialNumber: serialNumber,
  131. Version: 2,
  132. Subject: pkix.Name{CommonName: generatedCertificateOrigin},
  133. })
  134. }
  135. // CertificateFromX509 creates a new WebRTC Certificate from a given PrivateKey and Certificate
  136. //
  137. // This can be used if you want to share a certificate across multiple PeerConnections
  138. func CertificateFromX509(privateKey crypto.PrivateKey, certificate *x509.Certificate) Certificate {
  139. return Certificate{privateKey, certificate, fmt.Sprintf("certificate-%d", time.Now().UnixNano())}
  140. }
  141. func (c Certificate) collectStats(report *statsReportCollector) error {
  142. report.Collecting()
  143. fingerPrintAlgo, err := c.GetFingerprints()
  144. if err != nil {
  145. return err
  146. }
  147. base64Certificate := base64.RawURLEncoding.EncodeToString(c.x509Cert.Raw)
  148. stats := CertificateStats{
  149. Timestamp: statsTimestampFrom(time.Now()),
  150. Type: StatsTypeCertificate,
  151. ID: c.statsID,
  152. Fingerprint: fingerPrintAlgo[0].Value,
  153. FingerprintAlgorithm: fingerPrintAlgo[0].Algorithm,
  154. Base64Certificate: base64Certificate,
  155. IssuerCertificateID: c.x509Cert.Issuer.String(),
  156. }
  157. report.Collect(stats.ID, stats)
  158. return nil
  159. }
  160. // CertificateFromPEM creates a fresh certificate based on a string containing
  161. // pem blocks fort the private key and x509 certificate
  162. func CertificateFromPEM(pems string) (*Certificate, error) {
  163. // decode & parse the certificate
  164. block, more := pem.Decode([]byte(pems))
  165. if block == nil || block.Type != "CERTIFICATE" {
  166. return nil, errCertificatePEMFormatError
  167. }
  168. certBytes := make([]byte, base64.StdEncoding.DecodedLen(len(block.Bytes)))
  169. n, err := base64.StdEncoding.Decode(certBytes, block.Bytes)
  170. if err != nil {
  171. return nil, fmt.Errorf("failed to decode ceritifcate: %w", err)
  172. }
  173. cert, err := x509.ParseCertificate(certBytes[:n])
  174. if err != nil {
  175. return nil, fmt.Errorf("failed parsing ceritifcate: %w", err)
  176. }
  177. // decode & parse the private key
  178. block, _ = pem.Decode(more)
  179. if block == nil || block.Type != "PRIVATE KEY" {
  180. return nil, errCertificatePEMFormatError
  181. }
  182. privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
  183. if err != nil {
  184. return nil, fmt.Errorf("unable to parse private key: %w", err)
  185. }
  186. x := CertificateFromX509(privateKey, cert)
  187. return &x, nil
  188. }
  189. // PEM returns the certificate encoded as two pem block: once for the X509
  190. // certificate and the other for the private key
  191. func (c Certificate) PEM() (string, error) {
  192. // First write the X509 certificate
  193. var o strings.Builder
  194. xcertBytes := make(
  195. []byte, base64.StdEncoding.EncodedLen(len(c.x509Cert.Raw)))
  196. base64.StdEncoding.Encode(xcertBytes, c.x509Cert.Raw)
  197. err := pem.Encode(&o, &pem.Block{Type: "CERTIFICATE", Bytes: xcertBytes})
  198. if err != nil {
  199. return "", fmt.Errorf("failed to pem encode the X certificate: %w", err)
  200. }
  201. // Next write the private key
  202. privBytes, err := x509.MarshalPKCS8PrivateKey(c.privateKey)
  203. if err != nil {
  204. return "", fmt.Errorf("failed to marshal private key: %w", err)
  205. }
  206. err = pem.Encode(&o, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes})
  207. if err != nil {
  208. return "", fmt.Errorf("failed to encode private key: %w", err)
  209. }
  210. return o.String(), nil
  211. }