| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package tls |
| 6 |
|
| 7 |
import ( |
| 8 |
"crypto/tls" |
| 9 |
"crypto/x509" |
| 10 |
"errors" |
| 11 |
"fmt" |
| 12 |
"os" |
| 13 |
) |
| 14 |
|
| 15 |
|
| 16 |
func CreateConfig(caCertFile, clientCertFile, clientKeyFile *string) (*tls.Config, error) { |
| 17 |
tlsConfig := &tls.Config{} |
| 18 |
if caCertFile != nil { |
| 19 |
caText, err := os.ReadFile(*caCertFile) |
| 20 |
if err != nil { |
| 21 |
return nil, err |
| 22 |
} |
| 23 |
certPool := x509.NewCertPool() |
| 24 |
if !certPool.AppendCertsFromPEM(caText) { |
| 25 |
return nil, errors.New("could not create certificate authority chain from certificate") |
| 26 |
} |
| 27 |
tlsConfig.RootCAs = certPool |
| 28 |
} |
| 29 |
if clientCertFile != nil || clientKeyFile != nil { |
| 30 |
if clientCertFile == nil { |
| 31 |
return nil, errors.New("client key was provided but no client certificate was provided") |
| 32 |
} |
| 33 |
if clientKeyFile == nil { |
| 34 |
return nil, errors.New("client certificate was provided but no client key was provided") |
| 35 |
} |
| 36 |
clientCert, err := tls.LoadX509KeyPair(*clientCertFile, *clientKeyFile) |
| 37 |
if err != nil { |
| 38 |
return nil, fmt.Errorf("could not use client certificate: %w", err) |
| 39 |
} |
| 40 |
tlsConfig.Certificates = []tls.Certificate{clientCert} |
| 41 |
} |
| 42 |
return tlsConfig, nil |
| 43 |
} |