forked from sassoftware/relic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
registercmd.go
203 lines (189 loc) · 5.63 KB
/
registercmd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
//
// Copyright (c) SAS Institute Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package remotecmd
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/hex"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"math/big"
"os"
"path/filepath"
"time"
"github.com/sassoftware/relic/cmdline/shared"
"github.com/sassoftware/relic/config"
"github.com/sassoftware/relic/lib/certloader"
"gopkg.in/yaml.v2"
"github.com/spf13/cobra"
)
var RegisterCmd = &cobra.Command{
Use: "register",
Short: "Generate a certificate for communicating with a server",
RunE: registerCmd,
}
var (
argRemoteURL string
argCaCert string
argDirectory bool
argForce bool
)
func init() {
RemoteCmd.AddCommand(RegisterCmd)
RegisterCmd.Flags().StringVarP(&argRemoteURL, "url", "u", "", "URL of remote server to register to")
RegisterCmd.Flags().StringVarP(&argCaCert, "ca-cert", "C", "", "Path to CA certificate file (will be copied)")
RegisterCmd.Flags().BoolVarP(&argDirectory, "directory", "D", false, "Remote URL is a cluster directory")
RegisterCmd.Flags().BoolVarP(&argForce, "force", "f", false, "Overwrite existing configuration file")
}
func registerCmd(cmd *cobra.Command, args []string) error {
if argRemoteURL == "" {
return errors.New("--url and --ca-cert are required")
}
if shared.ArgConfig == "" {
shared.ArgConfig = config.DefaultConfig()
if shared.ArgConfig == "" {
return errors.New("Unable to determine default config location")
}
}
if fileExists(shared.ArgConfig) && !argForce {
fmt.Fprintf(os.Stderr, "Config file %s already exists\n", shared.ArgConfig)
return nil
}
defaultDir := filepath.Dir(shared.ArgConfig)
keyPath := filepath.Join(defaultDir, "client.pem")
if fileExists(keyPath) {
if !argForce {
return shared.Fail(fmt.Errorf("Key file %s already exists", keyPath))
}
if err := readKeyPair(keyPath); err != nil {
return shared.Fail(err)
}
} else {
if err := writeKeyPair(keyPath); err != nil {
return shared.Fail(err)
}
}
var capath string
if argCaCert != "" {
cacert, err := ioutil.ReadFile(argCaCert)
if err != nil {
return shared.Fail(fmt.Errorf("Error reading cacert: %s", err))
}
capath = filepath.Join(defaultDir, "cacert.pem")
if err := ioutil.WriteFile(capath, cacert, 0644); err != nil {
return shared.Fail(err)
}
}
if err := writeConfig(shared.ArgConfig, argRemoteURL, keyPath, capath); err != nil {
return shared.Fail(err)
}
return nil
}
func fileExists(path string) bool {
_, err := os.Lstat(path)
return err == nil
}
func writeConfig(cfgPath, url, keyPath, caPath string) error {
newConfig := &config.Config{Remote: &config.RemoteConfig{}}
if argDirectory {
newConfig.Remote.DirectoryURL = url
} else {
newConfig.Remote.URL = url
}
newConfig.Remote.CertFile = keyPath
newConfig.Remote.KeyFile = keyPath
newConfig.Remote.CaCert = caPath
cfgblob, err := yaml.Marshal(newConfig)
if err != nil {
return err
}
if err = os.MkdirAll(filepath.Dir(cfgPath), 0755); err != nil {
return err
}
return ioutil.WriteFile(cfgPath, cfgblob, 0600)
}
func writeKeyPair(keyPath string) error {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return err
}
cert, fingerprint, err := selfSign(key)
if err != nil {
return err
}
pemdata, err := serializeKey(key)
if err != nil {
return err
}
pemdata = append(pemdata, cert...)
if err = os.MkdirAll(filepath.Dir(keyPath), 0755); err != nil {
return err
}
if err = ioutil.WriteFile(keyPath, pemdata, 0600); err != nil {
return err
}
fmt.Println("New key fingerprint:", fingerprint)
return nil
}
func readKeyPair(keyPath string) error {
cert, err := certloader.LoadX509KeyPair(keyPath, keyPath)
if err != nil {
return err
}
digest := sha256.Sum256(cert.Leaf.RawSubjectPublicKeyInfo)
encoded := hex.EncodeToString(digest[:])
fmt.Println("Existing key fingerprint:", encoded)
return nil
}
func selfSign(key *ecdsa.PrivateKey) ([]byte, string, error) {
blob := make([]byte, 12)
if n, err := rand.Reader.Read(blob); err != nil || n != len(blob) {
return nil, "", errors.New("failed to make serial number")
}
hostname, _ := os.Hostname()
var template x509.Certificate
template.SerialNumber = new(big.Int).SetBytes(blob)
template.Subject.CommonName = fmt.Sprintf("self-signed cert for %s", hostname)
template.Issuer = template.Subject
template.SignatureAlgorithm = x509.ECDSAWithSHA256
template.NotBefore = time.Now().Add(time.Hour * -24)
template.NotAfter = time.Now().Add(time.Hour * 24 * 36525)
certblob, err := x509.CreateCertificate(rand.Reader, &template, &template, key.Public(), key)
if err != nil {
return nil, "", err
}
cert, err := x509.ParseCertificate(certblob)
if err != nil {
return nil, "", err
}
digest := sha256.Sum256(cert.RawSubjectPublicKeyInfo)
encoded := hex.EncodeToString(digest[:])
block := &pem.Block{Type: "CERTIFICATE", Bytes: certblob}
return pem.EncodeToMemory(block), encoded, nil
}
func serializeKey(key *ecdsa.PrivateKey) ([]byte, error) {
blob, err := x509.MarshalECPrivateKey(key)
if err != nil {
return nil, err
}
block := &pem.Block{Type: "EC PRIVATE KEY", Bytes: blob}
return pem.EncodeToMemory(block), nil
}