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