|
| 1 | +package armor |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/tls" |
| 5 | + "crypto/x509" |
| 6 | + "encoding/base64" |
| 7 | +) |
| 8 | + |
| 9 | +// GetConfigForClient implements the |
| 10 | +func (a *Armor) GetConfigForClient(clientHelloInfo *tls.ClientHelloInfo) (*tls.Config, error) { |
| 11 | + // Get the host from the hello info |
| 12 | + host := a.Hosts[clientHelloInfo.ServerName] |
| 13 | + if len(host.ClientCAs) == 0 { |
| 14 | + return nil, nil |
| 15 | + } |
| 16 | + |
| 17 | + // Use existing host config if exist |
| 18 | + if host.TLSConfig != nil { |
| 19 | + return host.TLSConfig, nil |
| 20 | + } |
| 21 | + |
| 22 | + // Build and save the host config |
| 23 | + host.TLSConfig = a.buildTLSConfig(clientHelloInfo, host) |
| 24 | + |
| 25 | + return host.TLSConfig, nil |
| 26 | +} |
| 27 | + |
| 28 | +func (a *Armor) buildTLSConfig(clientHelloInfo *tls.ClientHelloInfo, host *Host) *tls.Config { |
| 29 | + // Copy the configurations from the regular server |
| 30 | + tlsConfig := new(tls.Config) |
| 31 | + *tlsConfig = *a.Echo.TLSServer.TLSConfig |
| 32 | + |
| 33 | + // Set the client validation and the certification pool |
| 34 | + tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert |
| 35 | + tlsConfig.ClientCAs = a.buildClientCertPool(host) |
| 36 | + |
| 37 | + return tlsConfig |
| 38 | +} |
| 39 | + |
| 40 | +func (a *Armor) buildClientCertPool(host *Host) (certPool *x509.CertPool) { |
| 41 | + certPool = x509.NewCertPool() |
| 42 | + |
| 43 | + // Loop every CA certs given as base64 DER encoding |
| 44 | + for _, clientCAString := range host.ClientCAs { |
| 45 | + // Decode base64 |
| 46 | + derBytes, err := base64.StdEncoding.DecodeString(clientCAString) |
| 47 | + if err != nil { |
| 48 | + continue |
| 49 | + } |
| 50 | + if len(derBytes) == 0 { |
| 51 | + continue |
| 52 | + } |
| 53 | + |
| 54 | + // Parse the DER encoded certificate |
| 55 | + var caCert *x509.Certificate |
| 56 | + caCert, err = x509.ParseCertificate(derBytes) |
| 57 | + if err != nil { |
| 58 | + continue |
| 59 | + } |
| 60 | + |
| 61 | + // Add the certificate to CertPool |
| 62 | + certPool.AddCert(caCert) |
| 63 | + } |
| 64 | + |
| 65 | + return certPool |
| 66 | +} |
0 commit comments