Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a transport library. #358

Merged
merged 18 commits into from
Nov 3, 2015
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
cfssl_*
*-amd64
*-386
dist/*
cli/serve/static.rice-box.go
.coverprofile
4 changes: 2 additions & 2 deletions api/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,10 +202,10 @@ func (srv *server) Info(jsonData []byte) (*info.Resp, error) {
info.Certificate = val.(string)
}
var usages []interface{}
if val, ok := res["usages"]; ok {
if val, ok := res["usages"]; ok && val != nil {
usages = val.([]interface{})
}
if val, ok := res["expiry"]; ok {
if val, ok := res["expiry"]; ok && val != nil {
info.ExpiryString = val.(string)
}

Expand Down
16 changes: 16 additions & 0 deletions transport/ca/cert_provider.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Package ca provides the CertificateAuthority interface for the
// transport package, which provides an interface to get a CSR signed
// by some certificate authority.
package ca

// A CertificateAuthority is capable of signing certificates given
// certificate signing requests.
type CertificateAuthority interface {
// SignCSR submits a PKCS #10 certificate signing request to a
// CA for signing.
SignCSR(csrPEM []byte) (cert []byte, err error)

// CACertificate returns the certificate authority's
// certificate.
CACertificate() (cert []byte, err error)
}
285 changes: 285 additions & 0 deletions transport/ca/cfssl_provider.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,285 @@
package ca

import (
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"net"
"path/filepath"

"github.com/cloudflare/cfssl/api/client"
"github.com/cloudflare/cfssl/auth"
"github.com/cloudflare/cfssl/config"
"github.com/cloudflare/cfssl/info"
"github.com/cloudflare/cfssl/signer"
"github.com/cloudflare/cfssl/transport/core"
)

type authError struct {
authType string
}

func (err *authError) Error() string {
return fmt.Sprintf("transport: unsupported CFSSL authentication method %s", err.authType)
}

// This approach allows us to quickly add other providers later, such
// as the TPM.
var authTypes = map[string]func(config.AuthKey, []byte) (auth.Provider, error){
"standard": newStandardProvider,
}

// Create a standard provider without providing any additional data.
func newStandardProvider(ak config.AuthKey, ad []byte) (auth.Provider, error) {
return auth.New(ak.Key, ad)
}

// Create a new provider from an authentication key and possibly
// additional data.
func newProvider(ak config.AuthKey, ad []byte) (auth.Provider, error) {
// If no auth key was provided, use unauthenticated
// requests. This is useful when a local CFSSL is being used.
if ak.Type == "" && ak.Key == "" {
return nil, nil
}

f, ok := authTypes[ak.Type]
if !ok {
return nil, &authError{authType: ak.Type}
}

return f(ak, ad)
}

// ErrNoAuth is returned when a client is talking to a CFSSL remote
// that is not on a loopback address and doesn't have an
// authentication provider set.
var ErrNoAuth = errors.New("transport: authentication is required for non-local remotes")

var v4Loopback = net.IPNet{
IP: net.IP{127, 0, 0, 1},
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Threw me for a second. Maybe make it net.IP{127, 0, 0, 0}?

Mask: net.IPv4Mask(255, 0, 0, 0),
}

func ipIsLocal(ip net.IP) bool {
if ip.To4() == nil {
return ip.Equal(net.IPv6loopback)
}

return v4Loopback.Contains(ip)
}

// The only time a client should be doing unauthenticated requests is
// when a local CFSSL is being used.
func (cap *CFSSL) validateAuth() error {
// The client is using some form of authentication, and the best way
// to figure out that the auth is invalid is when it's used. Therefore,
// we'll delay checking the credentials until that time.
if cap.provider != nil {
return nil
}

hosts := cap.remote.Hosts()
for i := range hosts {
ips, err := net.LookupIP(hosts[i])
if err != nil {
return err
}

for _, ip := range ips {
if !ipIsLocal(ip) {
return ErrNoAuth
}
}
}

return nil
}

var cfsslConfigDirs = []string{
"/usr/local/cfssl",
"/etc/cfssl",
"/state/etc/cfssl",
}

// The CFSSL standard is to have a configuration file for a label as
// <config>.json.
func findLabel(label string) *config.Config {
for _, dir := range cfsslConfigDirs {
cfgFile := filepath.Join(dir, label+".json")
cfg, err := config.LoadFile(cfgFile)
if err == nil {
return cfg
}
}

return nil
}

func getProfile(cfg *config.Config, profileName string) (*config.SigningProfile, bool) {
if cfg == nil || cfg.Signing == nil || cfg.Signing.Default == nil {
return nil, false
}

var ok bool
profile := cfg.Signing.Default
if profileName != "" {
if cfg.Signing.Profiles == nil {
return nil, false
}

profile, ok = cfg.Signing.Profiles[profileName]
if !ok {
return nil, false
}
}

return profile, true
}

// loadAuth loads an authentication provider from the client config's
// explicitly set auth key.
func (cap *CFSSL) loadAuth() error {
var err error
cap.provider, err = newProvider(cap.DefaultAuth, nil)
return err
}

func getRemote(cfg *config.Config, profile *config.SigningProfile) (string, bool) {
// NB: Loading the config will validate that the remote is
// present in the config's remote section.
if profile.RemoteServer != "" {
return profile.RemoteServer, true
}

return "", false
}

func (cap *CFSSL) setRemoteAndAuth() error {
if cap.Label != "" {
cfsslConfig := findLabel(cap.Label)
profile, ok := getProfile(cfsslConfig, cap.Profile)
if ok {
remote, ok := getRemote(cfsslConfig, profile)
if ok {
cap.remote = client.NewServer(remote)
cap.provider = profile.Provider
return nil
}

// The profile may not have a remote set, but
// it may have an authentication provider.
cap.provider = profile.Provider
}
}

cap.remote = cap.DefaultRemote
if cap.provider != nil {
return nil
}
return cap.loadAuth()
}

// CFSSL provides support for signing certificates via
// CFSSL.
type CFSSL struct {
remote client.Remote
provider auth.Provider
Profile string
Label string
DefaultRemote client.Remote
DefaultAuth config.AuthKey
}

// SignCSR requests a certificate from a CFSSL signer.
func (cap *CFSSL) SignCSR(csrPEM []byte) (cert []byte, err error) {
p, _ := pem.Decode(csrPEM)
if p == nil || p.Type != "CERTIFICATE REQUEST" {
return nil, errors.New("transport: invalid PEM-encoded certificate signing request")
}

csr, err := x509.ParseCertificateRequest(p.Bytes)
if err != nil {
return nil, err
}

hosts := make([]string, 0, len(csr.DNSNames)+len(csr.IPAddresses))
copy(hosts, csr.DNSNames)

for i := range csr.IPAddresses {
hosts = append(hosts, csr.IPAddresses[i].String())
}

sreq := &signer.SignRequest{
Hosts: hosts,
Request: string(csrPEM),
Profile: cap.Profile,
Label: cap.Label,
}

out, err := json.Marshal(sreq)
if err != nil {
return nil, err
}

if cap.provider != nil {
return cap.remote.AuthSign(out, nil, cap.provider)
}

return cap.remote.Sign(out)
}

// CACertificate returns the certificate for a CFSSL CA.
func (cap *CFSSL) CACertificate() ([]byte, error) {
req := &info.Req{
Label: cap.Label,
Profile: cap.Profile,
}
out, err := json.Marshal(req)
if err != nil {
return nil, err
}

resp, err := cap.remote.Info(out)
if err != nil {
return nil, err
}

return []byte(resp.Certificate), nil
}

// NewCFSSLProvider takes the configuration information from an
// Identity (and an optional default remote), returning a CFSSL
// instance. There should be a profile in id called "cfssl", which
// should contain label and profile fields as needed.
func NewCFSSLProvider(id *core.Identity, defaultRemote client.Remote) (*CFSSL, error) {
if id == nil {
return nil, errors.New("transport: the identity hasn't been initialised. Has it been loaded from disk?")
}

cap := &CFSSL{
DefaultRemote: defaultRemote,
}

cfssl := id.Profiles["cfssl"]
if cfssl != nil {
cap.Label = cfssl["label"]
cap.Profile = cfssl["profile"]

if cap.DefaultRemote == nil {
cap.DefaultRemote = client.NewServer(cfssl["remote"])
}

cap.DefaultAuth.Type = cfssl["auth-type"]
cap.DefaultAuth.Key = cfssl["auth-key"]
}

err := cap.setRemoteAndAuth()
if err != nil {
return nil, err
}

return cap, nil
}
Loading