-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcredentials_cmd.go
74 lines (63 loc) · 1.69 KB
/
credentials_cmd.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
package cmds
import (
"crypto/tls"
"encoding/json"
"fmt"
"github.com/aidansteele/cloudkey/iotcreds"
"github.com/go-piv/piv-go/piv"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"os"
"time"
)
func CredentialsCmd(cmd *cobra.Command, args []string) error {
roleName := os.Getenv("CLOUDKEY_ROLENAME")
if roleName == "" {
if len(args) == 1 {
roleName = args[0]
} else {
fmt.Fprintln(os.Stderr, "Must specify IAM role name as argument")
os.Exit(1)
}
}
card, _ := cmd.PersistentFlags().GetString("card")
yk, err := openCard(&card)
if err != nil {
return err
}
defer yk.Close()
cert, err := yk.Certificate(piv.SlotCardAuthentication)
if err != nil {
return errors.WithStack(err)
}
priv, err := yk.PrivateKey(piv.SlotCardAuthentication, cert.PublicKey, piv.KeyAuth{})
if err != nil {
return errors.WithStack(err)
}
certificate := tls.Certificate{
Certificate: [][]byte{cert.Raw},
PrivateKey: priv,
}
endpoint := fmt.Sprintf("https://%s", cert.Subject.Organization[0])
identity := cert.Subject.CommonName
creds, err := iotcreds.Retrieve(endpoint, roleName, identity, certificate)
if err != nil {
return err
}
j, _ := json.Marshal(credentialProcessOutput{
Version: 1,
AccessKeyId: creds.AccessKeyId,
SecretAccessKey: creds.SecretAccessKey,
SessionToken: creds.SessionToken,
Expiration: creds.Expiration.Format(time.RFC3339),
})
fmt.Println(string(j))
return nil
}
type credentialProcessOutput struct {
Version int `json:"Version"`
AccessKeyId string `json:"AccessKeyId"`
SecretAccessKey string `json:"SecretAccessKey"`
SessionToken string `json:"SessionToken"`
Expiration string `json:"Expiration"`
}