11package keyfactor
22
33import (
4- "bytes"
54 "context"
6- "crypto/rand"
7- "crypto/rsa"
8- "crypto/x509"
9- "crypto/x509/pkix"
10- "encoding/asn1"
5+ b64 "encoding/base64"
116 "encoding/json"
12- "encoding/pem "
7+ "errors "
138 "fmt"
149 "io/ioutil"
15- "net"
1610 "net/http"
17- "os"
1811 "strings"
1912 "sync"
2013 "time"
2114
22- "github.com/Keyfactor/keyfactor-go-client/api"
15+ // "github.com/Keyfactor/keyfactor-go-client/api"
2316 "github.com/hashicorp/errwrap"
2417 "github.com/hashicorp/vault/sdk/framework"
25- "github.com/hashicorp/vault/sdk/helper/jsonutil"
2618 "github.com/hashicorp/vault/sdk/logical"
2719)
2820
29- var config map [string ]string
21+ // var config map[string]string
3022
3123// Factory configures and returns backend
3224func Factory (ctx context.Context , conf * logical.BackendConfig ) (logical.Backend , error ) {
3325
3426 b := backend ()
35-
36- if conf == nil {
37- return nil , fmt .Errorf ("configuration passed into backend is nil" )
27+ if err := b .Setup (ctx , conf ); err != nil {
28+ return nil , err
3829 }
39-
40- b .Backend .Setup (ctx , conf )
4130 return b , nil
4231}
4332
4433// // Store certificates by serial number
4534type keyfactorBackend struct {
4635 * framework.Backend
47- lock sync.RWMutex
48- client * api.Client
36+ lock sync.RWMutex
37+ cachedConfig * keyfactorConfig
38+ //client *api.Client
4939}
5040
5141// keyfactorBackend defines the target API keyfactorBackend
@@ -63,69 +53,55 @@ func backend() *keyfactorBackend {
6353 "role/*" ,
6454 },
6555 },
66- Paths : framework .PathAppend (),
56+ Paths : framework .PathAppend (
57+ pathConfig (& b ),
58+ pathRoles (& b ),
59+ pathCA (& b ),
60+ pathCerts (& b ),
61+ ),
6762 Secrets : []* framework.Secret {},
6863 BackendType : logical .TypeLogical ,
6964 Invalidate : b .invalidate ,
7065 }
7166 return & b
7267}
7368
74- func (b * keyfactorBackend ) initialize (ctx context.Context , req * logical.InitializationRequest ) error {
75- err := req .Storage .Delete (ctx , "/ca" )
69+ // func (b *keyfactorBackend) initialize(ctx context.Context, req *logical.InitializationRequest) error {
70+ // err := req.Storage.Delete(ctx, "/ca")
71+
72+ // if err != nil {
73+ // b.Logger().Error("Error removing previous stored ca values on init")
74+ // return err
75+ // }
76+ // //confPath := os.Getenv("KF_CONF_PATH")
77+ // //file, _ := ioutil.ReadFile(confPath)
78+ // //config = make(map[string]string)
79+ // //jsonutil.DecodeJSON(file, &config)
80+ // //b.Logger().Debug("INITIALIZE: KF_CONF_PATH = " + confPath)
81+ // //b.Logger().Debug("config file contents = ", config)
82+ // return nil
83+ // }
7684
85+ // Handle interface with Keyfactor API to enroll a certificate with given content
86+ func (b * keyfactorBackend ) submitCSR (ctx context.Context , req * logical.Request , csr string , caName string , templateName string ) ([]string , string , error ) {
87+ config , err := b .config (ctx , req .Storage )
7788 if err != nil {
78- b .Logger ().Error ("Error removing previous stored ca values on init" )
79- return err
80- }
81- confPath := os .Getenv ("KF_CONF_PATH" )
82- file , _ := ioutil .ReadFile (confPath )
83- config = make (map [string ]string )
84- jsonutil .DecodeJSON (file , & config )
85- b .Logger ().Debug ("INITIALIZE: KF_CONF_PATH = " + confPath )
86- b .Logger ().Debug ("config file contents = " , config )
87- return nil
88- }
89-
90- // Generate keypair and CSR
91- func (b * keyfactorBackend ) generateCSR (cn string , ip_sans []string , dns_sans []string ) (string , []byte ) {
92- keyBytes , _ := rsa .GenerateKey (rand .Reader , 2048 )
93- subj := pkix.Name {
94- CommonName : cn ,
95- }
96- rawSubj := subj .ToRDNSequence ()
97- asn1Subj , _ := asn1 .Marshal (rawSubj )
98- var netIPSans []net.IP
99- for i := range ip_sans {
100- netIPSans = append (netIPSans , net .ParseIP (ip_sans [i ]))
89+ return nil , "" , err
10190 }
102-
103- csrtemplate := x509.CertificateRequest {
104- RawSubject : asn1Subj ,
105- SignatureAlgorithm : x509 .SHA256WithRSA ,
106- IPAddresses : netIPSans ,
107- DNSNames : dns_sans ,
91+ if config == nil {
92+ return nil , "" , errors .New ("configuration is empty." )
10893 }
109- csrBytes , _ := x509 .CreateCertificateRequest (rand .Reader , & csrtemplate , keyBytes )
110- csrBuf := new (bytes.Buffer )
111- pem .Encode (csrBuf , & pem.Block {Type : "CERTIFICATE REQUEST" , Bytes : csrBytes })
112- return csrBuf .String (), x509 .MarshalPKCS1PrivateKey (keyBytes )
113- }
11494
115- // Handle interface with Keyfactor API to enroll a certificate with given content
116- func (b * keyfactorBackend ) submitCSR (ctx context.Context , req * logical.Request , csr string , caName string , templateName string ) ([]string , string , error ) {
117- host := config ["host" ]
118- template := config ["template" ]
119- ca := config ["CA" ]
120- creds := config ["creds" ]
95+ // host := config["host"]
96+ // template := config["template"]
97+ // ca := config["CA"]
98+ // creds := config["creds"]
12199
122- if caName != "" {
123- ca = caName
124- }
100+ ca := config .CertAuthority
101+ template := config .CertTemplate
125102
126- if templateName != "" {
127- template = templateName
128- }
103+ creds := config .Username + ":" + config .Password
104+ encCreds := b64 .StdEncoding .EncodeToString ([]byte (creds ))
129105
130106 location , _ := time .LoadLocation ("UTC" )
131107 t := time .Now ().In (location )
@@ -136,7 +112,7 @@ func (b *keyfactorBackend) submitCSR(ctx context.Context, req *logical.Request,
136112 http .DefaultClient .CloseIdleConnections ()
137113
138114 // Build request
139- url := config [ "protocol" ] + "://" + host + "/KeyfactorAPI/Enrollment/CSR"
115+ url := config . KeyfactorUrl + "/KeyfactorAPI/Enrollment/CSR"
140116 b .Logger ().Debug ("url: " + url )
141117 bodyContent := "{\" CSR\" : \" " + csr + "\" ,\" CertificateAuthority\" :\" " + ca + "\" ,\" IncludeChain\" : true, \" Metadata\" : {}, \" Timestamp\" : \" " + time + "\" ,\" Template\" : \" " + template + "\" ,\" SANs\" : {}}"
142118 payload := strings .NewReader (bodyContent )
@@ -147,11 +123,11 @@ func (b *keyfactorBackend) submitCSR(ctx context.Context, req *logical.Request,
147123 }
148124 httpReq .Header .Add ("x-keyfactor-requested-with" , "APIClient" )
149125 httpReq .Header .Add ("content-type" , "application/json" )
150- httpReq .Header .Add ("authorization" , "Basic " + creds )
126+ httpReq .Header .Add ("authorization" , "Basic " + encCreds )
151127 httpReq .Header .Add ("x-certificateformat" , "PEM" )
152128
153129 // Send request and check status
154- b .Logger ().Debug ("About to connect to " + config [ "host" ] + "for csr submission" )
130+ b .Logger ().Debug ("About to connect to " + config . KeyfactorUrl + "for csr submission" )
155131 res , err := http .DefaultClient .Do (httpReq )
156132 if err != nil {
157133 b .Logger ().Info ("CSR Enrollment failed: {{err}}" , err )
0 commit comments