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 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
|
package ssh
import (
"encoding/base64"
"fmt"
"net/http"
"runtime"
"strings"
"github.com/pkg/errors"
"github.com/smallstep/certificates/api"
"github.com/smallstep/certificates/authority/provisioner"
"github.com/smallstep/certificates/ca"
"github.com/smallstep/cli/command"
"github.com/smallstep/cli/config"
"github.com/smallstep/cli/crypto/sshutil"
"github.com/smallstep/cli/errs"
"github.com/smallstep/cli/flags"
"github.com/smallstep/cli/ui"
"github.com/smallstep/cli/utils/cautils"
"github.com/urfave/cli"
"golang.org/x/crypto/ssh"
)
func configCommand() cli.Command {
return cli.Command{
Name: "config",
Action: command.ActionFunc(configAction),
Usage: "configures ssh to be used with certificates",
UsageText: `**step ssh config**
[**--team**=<name>] [**--host**] [**--set**=<key=value>] [**--set-file**=<path>]
[**--dry-run**] [**--roots**] [**--federation**]
[**--force**] [**--ca-url**=<uri>] [**--root**=<file>]
[**--offline**] [**--ca-config**=<path>] [**--team-url**=<url>]`,
Description: `**step ssh config** configures SSH to be used with certificates. It also supports
flags to inspect the root certificates used to sign the certificates.
This command uses the templates defined in step-certificates to set up user and
hosts environments.
## EXAMPLES
Print the public keys used to verify user certificates:
'''
$ step ssh config --roots
'''
Print the public keys used to verify host certificates:
'''
$ step ssh config --host --roots
'''
Apply configuration templates on the user system:
'''
$ step ssh config
'''
Apply configuration templates on a host:
'''
$ step ssh config --host
'''
Apply configuration templates with custom variables:
'''
$ step ssh config --set User=joe --set Bastion=bastion.example.com
'''`,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "host",
Usage: `Configures a SSH server instead of a client.`,
},
flags.Team,
flags.TeamURL,
cli.BoolFlag{
Name: "roots",
Usage: `Prints the public keys used to verify user or host certificates.`,
},
cli.BoolFlag{
Name: "federation",
Usage: `Prints all the public keys in the federation. These keys are used to verify
user or host certificates`,
},
cli.StringSliceFlag{
Name: "set",
Usage: `The <key=value> used as a variable in the templates. Use the flag multiple
times to set multiple variables.`,
},
flags.TemplateSetFile,
flags.DryRun,
flags.CaURL,
flags.Root,
flags.Offline,
flags.CaConfig,
flags.Force,
},
}
}
type statusCoder interface {
StatusCode() int
}
func configAction(ctx *cli.Context) (recoverErr error) {
team := ctx.String("team")
isHost := ctx.Bool("host")
isRoots := ctx.Bool("roots")
isFederation := ctx.Bool("federation")
sets := ctx.StringSlice("set")
switch {
case team != "" && isHost:
return errs.IncompatibleFlagWithFlag(ctx, "roots", "host")
case team != "" && isRoots:
return errs.IncompatibleFlagWithFlag(ctx, "roots", "roots")
case team != "" && isFederation:
return errs.IncompatibleFlagWithFlag(ctx, "roots", "federation")
case team != "" && len(sets) > 0:
return errs.IncompatibleFlagWithFlag(ctx, "roots", "set")
case isRoots && isFederation:
return errs.IncompatibleFlagWithFlag(ctx, "roots", "federation")
case isRoots && len(sets) > 0:
return errs.IncompatibleFlagWithFlag(ctx, "roots", "set")
case isFederation && len(sets) > 0:
return errs.IncompatibleFlagWithFlag(ctx, "federation", "set")
}
// Bootstrap team
if team != "" {
if err := cautils.BootstrapTeam(ctx, team); err != nil {
return err
}
}
// Prepare retry function
retryFunc, err := loginOnUnauthorized(ctx)
if err != nil {
return err
}
// Initialize CA client with login if needed.
client, err := cautils.NewClient(ctx, ca.WithRetryFunc(retryFunc))
if err != nil {
return err
}
// Prints user or host keys
if isRoots || isFederation {
var roots *api.SSHRootsResponse
if isRoots {
roots, err = client.SSHRoots()
} else {
roots, err = client.SSHFederation()
}
if err != nil {
if e, ok := err.(statusCoder); ok && e.StatusCode() == http.StatusNotFound {
return errors.New("step certificates is not configured with SSH support")
}
return errors.Wrap(err, "error getting ssh public keys")
}
var keys []api.SSHPublicKey
if isHost {
if len(roots.HostKeys) == 0 {
return errors.New("step certificates is not configured with an ssh.hostKey")
}
keys = roots.HostKeys
} else {
if len(roots.UserKeys) == 0 {
return errors.New("step certificates is not configured with an ssh.userKey")
}
keys = roots.UserKeys
}
for _, key := range keys {
fmt.Printf("%s %s\n", key.Type(), base64.StdEncoding.EncodeToString(key.Marshal()))
}
return nil
}
data := map[string]string{
"GOOS": runtime.GOOS,
"StepPath": config.StepPath(),
}
if len(sets) > 0 {
for _, s := range sets {
i := strings.Index(s, "=")
if i == -1 {
return errs.InvalidFlagValue(ctx, "set", s, "")
}
data[s[:i]] = s[i+1:]
}
}
if !isHost {
// Try to get the user from a certificate
if _, ok := data["User"]; !ok {
agent, err := sshutil.DialAgent()
if err != nil {
return err
}
var opts []sshutil.AgentOption
if roots, err := client.SSHRoots(); err == nil && len(roots.UserKeys) > 0 {
userKeys := make([]ssh.PublicKey, len(roots.UserKeys))
for i, uk := range roots.UserKeys {
userKeys[i] = uk.PublicKey
}
opts = append(opts, sshutil.WithSignatureKey(userKeys))
}
if certs, err := agent.ListCertificates(opts...); err == nil && len(certs) > 0 {
if p := certs[0].ValidPrincipals; len(p) > 0 {
data["User"] = p[0]
}
}
}
// Force a user to have a username
if _, ok := data["User"]; !ok {
return errors.New("ssh certificate not found: please run `step ssh login <identity>`")
}
}
// Get configuration snippets and files
req := &api.SSHConfigRequest{
Data: data,
}
if isHost {
req.Type = provisioner.SSHHostCert
} else {
req.Type = provisioner.SSHUserCert
}
resp, err := client.SSHConfig(req)
if err != nil {
return err
}
var templates []api.Template
if isHost {
templates = resp.HostTemplates
} else {
templates = resp.UserTemplates
}
if len(templates) == 0 {
fmt.Println("No configuration changes were found.")
return nil
}
defer func() {
if rec := recover(); rec != nil {
if err, ok := rec.(error); ok {
recoverErr = err
} else {
panic(rec)
}
}
}()
if ctx.Bool("dry-run") {
for _, t := range templates {
ui.Printf("{{ \"%s\" | bold }}\n", config.StepAbs(t.Path))
fmt.Println(string(t.Content))
}
return nil
}
for _, t := range templates {
if err := t.Write(); err != nil {
return err
}
ui.Printf(`{{ "%s" | green }} {{ "%s" | bold }}`+"\n", ui.IconGood, config.StepAbs(t.Path))
}
return nil
}
|