mtls.go58 lines, 1.7 KB
| 1 | // Package mtls is mutual TLS between our services. Each one proves who it is |
| 2 | // with a certificate from our CA, with its name in it, and checks who's |
| 3 | // calling the same way: being inside our network proves nothing. |
| 4 | package mtls |
| 5 | |
| 6 | import ( |
| 7 | "crypto/tls" |
| 8 | "crypto/x509" |
| 9 | "fmt" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | ) |
| 13 | |
| 14 | // Config is a service's credentials: its certificate and private key, and |
| 15 | // the CA that every certificate it accepts must come from. |
| 16 | type Config struct { |
| 17 | cert tls.Certificate |
| 18 | cas *x509.CertPool |
| 19 | } |
| 20 | |
| 21 | // Load reads the files in dir: ca.pem, cert.pem and key.pem. |
| 22 | func Load(dir string) (*Config, error) { |
| 23 | cert, err := tls.LoadX509KeyPair(filepath.Join(dir, "cert.pem"), filepath.Join(dir, "key.pem")) |
| 24 | if err != nil { |
| 25 | return nil, fmt.Errorf("mtls: %w", err) |
| 26 | } |
| 27 | ca, err := os.ReadFile(filepath.Join(dir, "ca.pem")) |
| 28 | if err != nil { |
| 29 | return nil, fmt.Errorf("mtls: %w", err) |
| 30 | } |
| 31 | cas := x509.NewCertPool() |
| 32 | if !cas.AppendCertsFromPEM(ca) { |
| 33 | return nil, fmt.Errorf("mtls: no certificate in %s", filepath.Join(dir, "ca.pem")) |
| 34 | } |
| 35 | return &Config{cert: cert, cas: cas}, nil |
| 36 | } |
| 37 | |
| 38 | // Server is the TLS config of an internal API: every client must show a |
| 39 | // certificate from our CA. TLS 1.3 only: we control both ends. |
| 40 | func (c *Config) Server() *tls.Config { |
| 41 | return &tls.Config{ |
| 42 | MinVersion: tls.VersionTLS13, |
| 43 | Certificates: []tls.Certificate{c.cert}, |
| 44 | ClientAuth: tls.RequireAndVerifyClientCert, |
| 45 | ClientCAs: c.cas, |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | // Client is the TLS config for calling the service called server, wherever it |
| 50 | // runs: its certificate must come from our CA, and have its name in it. |
| 51 | func (c *Config) Client(server string) *tls.Config { |
| 52 | return &tls.Config{ |
| 53 | MinVersion: tls.VersionTLS13, |
| 54 | Certificates: []tls.Certificate{c.cert}, |
| 55 | RootCAs: c.cas, |
| 56 | ServerName: server, |
| 57 | } |
| 58 | } |