Skip to content

Commit

Permalink
TLS authentication working
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandrestein committed Feb 21, 2019
1 parent 65555c9 commit f6a83ac
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
3 changes: 3 additions & 0 deletions armor.go
@@ -1,6 +1,7 @@
package armor

import (
"crypto/tls"
"sync"
"time"

Expand Down Expand Up @@ -75,6 +76,8 @@ type (
Paths Paths `json:"paths"`
Plugins []plugin.Plugin `json:"-"`
Echo *echo.Echo `json:"-"`
ClientCAs []string `json:"client_ca"`
TLSConfig *tls.Config `json:"-"`
}

Path struct {
Expand Down
1 change: 1 addition & 0 deletions http.go
Expand Up @@ -49,6 +49,7 @@ func (a *Armor) NewHTTP() (h *HTTP) {
ReadTimeout: a.ReadTimeout * time.Second,
WriteTimeout: a.WriteTimeout * time.Second,
}
e.TLSServer.TLSConfig.GetConfigForClient = a.GetConfigForClient
e.AutoTLSManager.Email = a.TLS.Email
e.AutoTLSManager.Client = new(acme.Client)
if a.TLS.DirectoryURL != "" {
Expand Down
66 changes: 66 additions & 0 deletions tls.go
@@ -0,0 +1,66 @@
package armor

import (
"crypto/tls"
"crypto/x509"
"encoding/base64"
)

// GetConfigForClient implements the Config.GetClientCertificate callback
func (a *Armor) GetConfigForClient(clientHelloInfo *tls.ClientHelloInfo) (*tls.Config, error) {
// Get the host from the hello info
host := a.Hosts[clientHelloInfo.ServerName]
if len(host.ClientCAs) == 0 {
return nil, nil
}

// Use existing host config if exist
if host.TLSConfig != nil {
return host.TLSConfig, nil
}

// Build and save the host config
host.TLSConfig = a.buildTLSConfig(clientHelloInfo, host)

return host.TLSConfig, nil
}

func (a *Armor) buildTLSConfig(clientHelloInfo *tls.ClientHelloInfo, host *Host) *tls.Config {
// Copy the configurations from the regular server
tlsConfig := new(tls.Config)
*tlsConfig = *a.Echo.TLSServer.TLSConfig

// Set the client validation and the certification pool
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
tlsConfig.ClientCAs = a.buildClientCertPool(host)

return tlsConfig
}

func (a *Armor) buildClientCertPool(host *Host) (certPool *x509.CertPool) {
certPool = x509.NewCertPool()

// Loop every CA certs given as base64 DER encoding
for _, clientCAString := range host.ClientCAs {
// Decode base64
derBytes, err := base64.StdEncoding.DecodeString(clientCAString)
if err != nil {
continue
}
if len(derBytes) == 0 {
continue
}

// Parse the DER encoded certificate
var caCert *x509.Certificate
caCert, err = x509.ParseCertificate(derBytes)
if err != nil {
continue
}

// Add the certificate to CertPool
certPool.AddCert(caCert)
}

return certPool
}

0 comments on commit f6a83ac

Please sign in to comment.