NewTLSConfig creates a new tls.Config from the given TLSConfig.
(cfg *TLSConfig)
| 834 | |
| 835 | // NewTLSConfig creates a new tls.Config from the given TLSConfig. |
| 836 | func NewTLSConfig(cfg *TLSConfig) (*tls.Config, error) { |
| 837 | if err := cfg.Validate(); err != nil { |
| 838 | return nil, err |
| 839 | } |
| 840 | |
| 841 | tlsConfig := &tls.Config{ |
| 842 | InsecureSkipVerify: cfg.InsecureSkipVerify, |
| 843 | MinVersion: uint16(cfg.MinVersion), |
| 844 | MaxVersion: uint16(cfg.MaxVersion), |
| 845 | } |
| 846 | |
| 847 | if cfg.MaxVersion != 0 && cfg.MinVersion != 0 { |
| 848 | if cfg.MaxVersion < cfg.MinVersion { |
| 849 | return nil, fmt.Errorf("tls_config.max_version must be greater than or equal to tls_config.min_version if both are specified") |
| 850 | } |
| 851 | } |
| 852 | |
| 853 | // If a CA cert is provided then let's read it in so we can validate the |
| 854 | // scrape target's certificate properly. |
| 855 | if len(cfg.CA) > 0 { |
| 856 | if !updateRootCA(tlsConfig, []byte(cfg.CA)) { |
| 857 | return nil, fmt.Errorf("unable to use inline CA cert") |
| 858 | } |
| 859 | } else if len(cfg.CAFile) > 0 { |
| 860 | b, err := readCAFile(cfg.CAFile) |
| 861 | if err != nil { |
| 862 | return nil, err |
| 863 | } |
| 864 | if !updateRootCA(tlsConfig, b) { |
| 865 | return nil, fmt.Errorf("unable to use specified CA cert %s", cfg.CAFile) |
| 866 | } |
| 867 | } |
| 868 | |
| 869 | if len(cfg.ServerName) > 0 { |
| 870 | tlsConfig.ServerName = cfg.ServerName |
| 871 | } |
| 872 | |
| 873 | // If a client cert & key is provided then configure TLS config accordingly. |
| 874 | if cfg.usingClientCert() && cfg.usingClientKey() { |
| 875 | // Verify that client cert and key are valid. |
| 876 | if _, err := cfg.getClientCertificate(nil); err != nil { |
| 877 | return nil, err |
| 878 | } |
| 879 | tlsConfig.GetClientCertificate = cfg.getClientCertificate |
| 880 | } |
| 881 | |
| 882 | return tlsConfig, nil |
| 883 | } |
| 884 | |
| 885 | // TLSConfig configures the options for TLS connections. |
| 886 | type TLSConfig struct { |