Debian Codegraph @

command/ssh/login.go

raw symbols SCIP
1 package ssh
2
3 import (
4 "crypto"
5 "time"
6
7 "github.com/pkg/errors"
8 "github.com/smallstep/certificates/api"
9 "github.com/smallstep/certificates/authority/provisioner"
10 "github.com/smallstep/certificates/ca"
11 "github.com/smallstep/cli/command"
12 "github.com/smallstep/cli/crypto/keys"
13 "github.com/smallstep/cli/crypto/sshutil"
14 "github.com/smallstep/cli/errs"
15 "github.com/smallstep/cli/flags"
16 "github.com/smallstep/cli/ui"
17 "github.com/smallstep/cli/utils/cautils"
18 "github.com/urfave/cli"
19 "golang.org/x/crypto/ssh"
20 )
21
22 func loginCommand() cli.Command {
23 return cli.Command{
24 Name: "login",
25 Action: command.ActionFunc(loginAction),
26 Usage: "adds a SSH certificate into the authentication agent",
27 UsageText: `**step ssh login** <identity>
28 [**--token**=<token>] [**--provisioner**=<name>] [**--provisioner-password-file**=<file>]
29 [**--not-before**=<time|duration>] [**--not-after**=<time|duration>]
30 [**--set**=<key=value>] [**--set-file**=<path>]
31 [**--force**] [**--ca-url**=<uri>] [**--root**=<file>]
32 [**--offline**] [**--ca-config**=<path>]`,
33 Description: `**step ssh login** generates a new SSH key pair and send a request to [step
34 certificates](https://github.com/smallstep/certificates) to sign a user
35 certificate. This certificate will be automatically added to the SSH agent.
36
37 With a certificate servers may trust only the CA key and verify its signature on
38 a certificate rather than trusting many user keys.
39
40 ## POSITIONAL ARGUMENTS
41
42 <identity>
43 : The certificate identity. If no principals are passed we will use
44 the identity as a principal, if it has the format abc@def then the
45 principal will be abc.
46
47 ## EXAMPLES
48
49 Request a new SSH certificate and add it to the agent:
50 '''
51 $ step ssh login [email protected]
52 '''
53
54 Request a new SSH certificate valid only for 1h:
55 '''
56 $ step ssh login --not-after 1h [email protected]
57 '''`,
58 Flags: []cli.Flag{
59 flags.Token,
60 sshAddUserFlag,
61 flags.Identity,
62 flags.Provisioner,
63 flags.ProvisionerPasswordFileWithAlias,
64 flags.NotBefore,
65 flags.NotAfter,
66 flags.TemplateSet,
67 flags.TemplateSetFile,
68 flags.CaURL,
69 flags.Root,
70 flags.Offline,
71 flags.CaConfig,
72 flags.Force,
73 },
74 }
75 }
76
77 func loginAction(ctx *cli.Context) error {
78 if err := errs.MinMaxNumberOfArguments(ctx, 0, 1); err != nil {
79 return err
80 }
81
82 // Arguments
83 subject := ctx.Args().First()
84 if subject == "" {
85 if subject = ctx.String("identity"); subject == "" {
86 return errs.TooFewArguments(ctx)
87 }
88 }
89 principals := createPrincipalsFromSubject(subject)
90
91 // Flags
92 token := ctx.String("token")
93 isAddUser := ctx.Bool("add-user")
94 force := ctx.Bool("force")
95 validAfter, validBefore, err := flags.ParseTimeDuration(ctx)
96 if err != nil {
97 return err
98 }
99 templateData, err := flags.ParseTemplateData(ctx)
100 if err != nil {
101 return err
102 }
103
104 // Connect to the SSH agent.
105 // step ssh login requires an ssh agent.
106 agent, err := sshutil.DialAgent()
107 if err != nil {
108 return err
109 }
110
111 // Check for a previous key signed by the CA.
112 if !force {
113 client, err := cautils.NewClient(ctx)
114 if err != nil {
115 return err
116 }
117 opts := []sshutil.AgentOption{
118 sshutil.WithRemoveExpiredCerts(time.Now()),
119 }
120 if roots, err := client.SSHRoots(); err == nil && len(roots.UserKeys) > 0 {
121 userKeys := make([]ssh.PublicKey, len(roots.UserKeys))
122 for i, uk := range roots.UserKeys {
123 userKeys[i] = uk.PublicKey
124 }
125 opts = append(opts, sshutil.WithSignatureKey(userKeys))
126 }
127
128 // Just return if key is present
129 if _, err := agent.GetKey(subject, opts...); err == nil {
130 ui.Printf("The key %s is already present in the SSH agent.\n", subject)
131 return nil
132 }
133 }
134
135 // Do step-certificates flow
136 flow, err := cautils.NewCertificateFlow(ctx)
137 if err != nil {
138 return err
139 }
140 if len(token) == 0 {
141 // Make sure the validAfter is in the past. It avoids `Certificate
142 // invalid: not yet valid` errors if the times are not in sync
143 // perfectly.
144 if validAfter.IsZero() {
145 validAfter = provisioner.NewTimeDuration(time.Now().Add(-1 * time.Minute))
146 }
147
148 if token, err = flow.GenerateSSHToken(ctx, subject, cautils.SSHUserSignType, principals, validAfter, validBefore); err != nil {
149 return err
150 }
151 }
152
153 caClient, err := flow.GetClient(ctx, token)
154 if err != nil {
155 return err
156 }
157
158 // Generate keypair
159 pub, priv, err := keys.GenerateDefaultKeyPair()
160 if err != nil {
161 return err
162 }
163
164 sshPub, err := ssh.NewPublicKey(pub)
165 if err != nil {
166 return errors.Wrap(err, "error creating public key")
167 }
168
169 var sshAuPub ssh.PublicKey
170 var sshAuPubBytes []byte
171 var auPub, auPriv interface{}
172 if isAddUser {
173 auPub, auPriv, err = keys.GenerateDefaultKeyPair()
174 if err != nil {
175 return err
176 }
177 sshAuPub, err = ssh.NewPublicKey(auPub)
178 if err != nil {
179 return errors.Wrap(err, "error creating public key")
180 }
181 sshAuPubBytes = sshAuPub.Marshal()
182 }
183
184 version, err := caClient.Version()
185 if err != nil {
186 return err
187 }
188
189 // Generate identity certificate (x509) if necessary
190 var identityCSR api.CertificateRequest
191 var identityKey crypto.PrivateKey
192 if version.RequireClientAuthentication {
193 csr, key, err := ca.CreateIdentityRequest(subject)
194 if err != nil {
195 return err
196 }
197 identityCSR = *csr
198 identityKey = key
199 }
200
201 // NOTE: For OIDC token the principals should be completely empty. The OIDC
202 // provisioner is responsible for setting default principals by using an
203 // identity function.
204 if email, ok := tokenHasEmail(token); ok {
205 subject = email
206 }
207
208 resp, err := caClient.SSHSign(&api.SSHSignRequest{
209 PublicKey: sshPub.Marshal(),
210 OTT: token,
211 Principals: principals,
212 CertType: provisioner.SSHUserCert,
213 KeyID: subject,
214 ValidAfter: validAfter,
215 ValidBefore: validBefore,
216 AddUserPublicKey: sshAuPubBytes,
217 IdentityCSR: identityCSR,
218 TemplateData: templateData,
219 })
220 if err != nil {
221 return err
222 }
223
224 // Write x509 identity certificate
225 if version.RequireClientAuthentication {
226 if err := ca.WriteDefaultIdentity(resp.IdentityCertificate, identityKey); err != nil {
227 return err
228 }
229 }
230
231 // Attempt to add key to agent if private key defined.
232 if err := agent.AddCertificate(subject, resp.Certificate.Certificate, priv); err != nil {
233 ui.Printf(`{{ "%s" | red }} {{ "SSH Agent:" | bold }} %v`+"\n", ui.IconBad, err)
234 } else {
235 ui.PrintSelected("SSH Agent", "yes")
236 }
237 if isAddUser {
238 if resp.AddUserCertificate == nil {
239 ui.Printf(`{{ "%s" | red }} {{ "Add User Certificate:" | bold }} failed to create a provisioner certificate`+"\n", ui.IconBad)
240 } else if err := agent.AddCertificate(subject, resp.AddUserCertificate.Certificate, auPriv); err != nil {
241 ui.Printf(`{{ "%s" | red }} {{ "Add User Certificate:" | bold }} %v`+"\n", ui.IconBad, err)
242 } else {
243 ui.PrintSelected("Add User Certificate", "yes")
244 }
245 }
246
247 return nil
248 }