config.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. package dtls
  2. import (
  3. "context"
  4. "crypto/ecdsa"
  5. "crypto/ed25519"
  6. "crypto/rsa"
  7. "crypto/tls"
  8. "crypto/x509"
  9. "io"
  10. "time"
  11. "github.com/pion/dtls/v2/pkg/crypto/elliptic"
  12. "github.com/pion/logging"
  13. )
  14. const keyLogLabelTLS12 = "CLIENT_RANDOM"
  15. // Config is used to configure a DTLS client or server.
  16. // After a Config is passed to a DTLS function it must not be modified.
  17. type Config struct {
  18. // Certificates contains certificate chain to present to the other side of the connection.
  19. // Server MUST set this if PSK is non-nil
  20. // client SHOULD sets this so CertificateRequests can be handled if PSK is non-nil
  21. Certificates []tls.Certificate
  22. // CipherSuites is a list of supported cipher suites.
  23. // If CipherSuites is nil, a default list is used
  24. CipherSuites []CipherSuiteID
  25. // CustomCipherSuites is a list of CipherSuites that can be
  26. // provided by the user. This allow users to user Ciphers that are reserved
  27. // for private usage.
  28. CustomCipherSuites func() []CipherSuite
  29. // SignatureSchemes contains the signature and hash schemes that the peer requests to verify.
  30. SignatureSchemes []tls.SignatureScheme
  31. // SRTPProtectionProfiles are the supported protection profiles
  32. // Clients will send this via use_srtp and assert that the server properly responds
  33. // Servers will assert that clients send one of these profiles and will respond as needed
  34. SRTPProtectionProfiles []SRTPProtectionProfile
  35. // ClientAuth determines the server's policy for
  36. // TLS Client Authentication. The default is NoClientCert.
  37. ClientAuth ClientAuthType
  38. // RequireExtendedMasterSecret determines if the "Extended Master Secret" extension
  39. // should be disabled, requested, or required (default requested).
  40. ExtendedMasterSecret ExtendedMasterSecretType
  41. // FlightInterval controls how often we send outbound handshake messages
  42. // defaults to time.Second
  43. FlightInterval time.Duration
  44. // PSK sets the pre-shared key used by this DTLS connection
  45. // If PSK is non-nil only PSK CipherSuites will be used
  46. PSK PSKCallback
  47. PSKIdentityHint []byte
  48. // InsecureSkipVerify controls whether a client verifies the
  49. // server's certificate chain and host name.
  50. // If InsecureSkipVerify is true, TLS accepts any certificate
  51. // presented by the server and any host name in that certificate.
  52. // In this mode, TLS is susceptible to man-in-the-middle attacks.
  53. // This should be used only for testing.
  54. InsecureSkipVerify bool
  55. // InsecureHashes allows the use of hashing algorithms that are known
  56. // to be vulnerable.
  57. InsecureHashes bool
  58. // VerifyPeerCertificate, if not nil, is called after normal
  59. // certificate verification by either a client or server. It
  60. // receives the certificate provided by the peer and also a flag
  61. // that tells if normal verification has succeedded. If it returns a
  62. // non-nil error, the handshake is aborted and that error results.
  63. //
  64. // If normal verification fails then the handshake will abort before
  65. // considering this callback. If normal verification is disabled by
  66. // setting InsecureSkipVerify, or (for a server) when ClientAuth is
  67. // RequestClientCert or RequireAnyClientCert, then this callback will
  68. // be considered but the verifiedChains will always be nil.
  69. VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
  70. // VerifyConnection, if not nil, is called after normal certificate
  71. // verification/PSK and after VerifyPeerCertificate by either a TLS client
  72. // or server. If it returns a non-nil error, the handshake is aborted
  73. // and that error results.
  74. //
  75. // If normal verification fails then the handshake will abort before
  76. // considering this callback. This callback will run for all connections
  77. // regardless of InsecureSkipVerify or ClientAuth settings.
  78. VerifyConnection func(*State) error
  79. // RootCAs defines the set of root certificate authorities
  80. // that one peer uses when verifying the other peer's certificates.
  81. // If RootCAs is nil, TLS uses the host's root CA set.
  82. RootCAs *x509.CertPool
  83. // ClientCAs defines the set of root certificate authorities
  84. // that servers use if required to verify a client certificate
  85. // by the policy in ClientAuth.
  86. ClientCAs *x509.CertPool
  87. // ServerName is used to verify the hostname on the returned
  88. // certificates unless InsecureSkipVerify is given.
  89. ServerName string
  90. LoggerFactory logging.LoggerFactory
  91. // ConnectContextMaker is a function to make a context used in Dial(),
  92. // Client(), Server(), and Accept(). If nil, the default ConnectContextMaker
  93. // is used. It can be implemented as following.
  94. //
  95. // func ConnectContextMaker() (context.Context, func()) {
  96. // return context.WithTimeout(context.Background(), 30*time.Second)
  97. // }
  98. ConnectContextMaker func() (context.Context, func())
  99. // MTU is the length at which handshake messages will be fragmented to
  100. // fit within the maximum transmission unit (default is 1200 bytes)
  101. MTU int
  102. // ReplayProtectionWindow is the size of the replay attack protection window.
  103. // Duplication of the sequence number is checked in this window size.
  104. // Packet with sequence number older than this value compared to the latest
  105. // accepted packet will be discarded. (default is 64)
  106. ReplayProtectionWindow int
  107. // KeyLogWriter optionally specifies a destination for TLS master secrets
  108. // in NSS key log format that can be used to allow external programs
  109. // such as Wireshark to decrypt TLS connections.
  110. // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format.
  111. // Use of KeyLogWriter compromises security and should only be
  112. // used for debugging.
  113. KeyLogWriter io.Writer
  114. // SessionStore is the container to store session for resumption.
  115. SessionStore SessionStore
  116. // List of application protocols the peer supports, for ALPN
  117. SupportedProtocols []string
  118. // List of Elliptic Curves to use
  119. //
  120. // If an ECC ciphersuite is configured and EllipticCurves is empty
  121. // it will default to X25519, P-256, P-384 in this specific order.
  122. EllipticCurves []elliptic.Curve
  123. // GetCertificate returns a Certificate based on the given
  124. // ClientHelloInfo. It will only be called if the client supplies SNI
  125. // information or if Certificates is empty.
  126. //
  127. // If GetCertificate is nil or returns nil, then the certificate is
  128. // retrieved from NameToCertificate. If NameToCertificate is nil, the
  129. // best element of Certificates will be used.
  130. GetCertificate func(*ClientHelloInfo) (*tls.Certificate, error)
  131. // GetClientCertificate, if not nil, is called when a server requests a
  132. // certificate from a client. If set, the contents of Certificates will
  133. // be ignored.
  134. //
  135. // If GetClientCertificate returns an error, the handshake will be
  136. // aborted and that error will be returned. Otherwise
  137. // GetClientCertificate must return a non-nil Certificate. If
  138. // Certificate.Certificate is empty then no certificate will be sent to
  139. // the server. If this is unacceptable to the server then it may abort
  140. // the handshake.
  141. GetClientCertificate func(*CertificateRequestInfo) (*tls.Certificate, error)
  142. // InsecureSkipVerifyHello, if true and when acting as server, allow client to
  143. // skip hello verify phase and receive ServerHello after initial ClientHello.
  144. // This have implication on DoS attack resistance.
  145. InsecureSkipVerifyHello bool
  146. }
  147. func defaultConnectContextMaker() (context.Context, func()) {
  148. return context.WithTimeout(context.Background(), 30*time.Second)
  149. }
  150. func (c *Config) connectContextMaker() (context.Context, func()) {
  151. if c.ConnectContextMaker == nil {
  152. return defaultConnectContextMaker()
  153. }
  154. return c.ConnectContextMaker()
  155. }
  156. func (c *Config) includeCertificateSuites() bool {
  157. return c.PSK == nil || len(c.Certificates) > 0 || c.GetCertificate != nil || c.GetClientCertificate != nil
  158. }
  159. const defaultMTU = 1200 // bytes
  160. var defaultCurves = []elliptic.Curve{elliptic.X25519, elliptic.P256, elliptic.P384} //nolint:gochecknoglobals
  161. // PSKCallback is called once we have the remote's PSKIdentityHint.
  162. // If the remote provided none it will be nil
  163. type PSKCallback func([]byte) ([]byte, error)
  164. // ClientAuthType declares the policy the server will follow for
  165. // TLS Client Authentication.
  166. type ClientAuthType int
  167. // ClientAuthType enums
  168. const (
  169. NoClientCert ClientAuthType = iota
  170. RequestClientCert
  171. RequireAnyClientCert
  172. VerifyClientCertIfGiven
  173. RequireAndVerifyClientCert
  174. )
  175. // ExtendedMasterSecretType declares the policy the client and server
  176. // will follow for the Extended Master Secret extension
  177. type ExtendedMasterSecretType int
  178. // ExtendedMasterSecretType enums
  179. const (
  180. RequestExtendedMasterSecret ExtendedMasterSecretType = iota
  181. RequireExtendedMasterSecret
  182. DisableExtendedMasterSecret
  183. )
  184. func validateConfig(config *Config) error {
  185. switch {
  186. case config == nil:
  187. return errNoConfigProvided
  188. case config.PSKIdentityHint != nil && config.PSK == nil:
  189. return errIdentityNoPSK
  190. }
  191. for _, cert := range config.Certificates {
  192. if cert.Certificate == nil {
  193. return errInvalidCertificate
  194. }
  195. if cert.PrivateKey != nil {
  196. switch cert.PrivateKey.(type) {
  197. case ed25519.PrivateKey:
  198. case *ecdsa.PrivateKey:
  199. case *rsa.PrivateKey:
  200. default:
  201. return errInvalidPrivateKey
  202. }
  203. }
  204. }
  205. _, err := parseCipherSuites(config.CipherSuites, config.CustomCipherSuites, config.includeCertificateSuites(), config.PSK != nil)
  206. return err
  207. }