forked from stoggi/sshrimp
/
main.go
169 lines (148 loc) 路 4.88 KB
/
main.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
package main
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"math"
"math/big"
"regexp"
"time"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-lambda-go/lambdacontext"
"github.com/gazzenger/sshrimp/internal/config"
"github.com/gazzenger/sshrimp/internal/identity"
"github.com/gazzenger/sshrimp/internal/signer"
"golang.org/x/crypto/ssh"
)
// HandleRequest handles a request to sign an SSH public key verified by an OpenIDConnect id_token
func HandleRequest(ctx context.Context, event signer.SSHrimpEvent) (*signer.SSHrimpResult, error) {
// Make sure we are running in a lambda context, to get the requestid and ARN
lambdaContext, ok := lambdacontext.FromContext(ctx)
if !ok {
return nil, fmt.Errorf("lambdacontext not in ctx")
}
// Load the configuration file, if not exsits, exit.
c := config.NewSSHrimp()
if err := c.Read(config.GetPath()); err != nil {
return nil, err
}
// Validate the user supplied public key
publicKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(event.PublicKey))
if err != nil {
return nil, fmt.Errorf("unable to parse public key: %v", err)
}
// Validate the user supplied identity token with the loaded configuration
i, err := identity.NewIdentity(c)
username, roles, err := i.Validate(event.Token)
if err != nil {
return nil, err
}
// Validate and add force commands or source address options
criticalOptions := make(map[string]string)
if regexp.MustCompile(c.CertificateAuthority.ForceCommandRegex).MatchString(event.ForceCommand) {
if event.ForceCommand != "" {
criticalOptions["force-command"] = event.ForceCommand
}
} else {
return nil, errors.New("forcecommand validation failed")
}
if regexp.MustCompile(c.CertificateAuthority.SourceAddressRegex).MatchString(event.SourceAddress) {
if event.SourceAddress != "" {
criticalOptions["source-address"] = event.SourceAddress
}
} else {
return nil, errors.New("sourceaddress validation failed")
}
// Generate a random nonce for the certificate
bytes := make([]byte, 32)
nonce := make([]byte, len(bytes)*2)
if _, err := rand.Read(bytes); err != nil {
return nil, err
}
hex.Encode(nonce, bytes)
// Generate a random serial number
serial, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
if err != nil {
return nil, err
}
// Validate and set the certificate valid and expire times
now := time.Now()
validAfterOffset, err := time.ParseDuration(c.CertificateAuthority.ValidAfterOffset)
if err != nil {
return nil, err
}
validBeforeOffset, err := time.ParseDuration(c.CertificateAuthority.ValidBeforeOffset)
if err != nil {
return nil, err
}
validAfter := now.Add(validAfterOffset)
validBefore := now.Add(validBeforeOffset)
// Convert the extensions slice to a map
extensions := make(map[string]string, len(c.CertificateAuthority.Extensions))
for _, extension := range c.CertificateAuthority.Extensions {
extensions[extension] = ""
}
// Create a key ID to be added to the certificate. Follows BLESS Key ID format
// https://github.com/Netflix/bless
keyID := fmt.Sprintf("request[%s] for[%s] from[%s] command[%s] ssh_key[%s] ca[%s] valid_to[%s]",
lambdaContext.AwsRequestID,
username,
event.SourceAddress,
event.ForceCommand,
ssh.FingerprintSHA256(publicKey),
lambdaContext.InvokedFunctionArn,
validBefore.Format("2006/01/02 15:04:05"),
)
// Merge username with additional principal roles
principals := make([]string, len(roles)+1)
principals[0] = username
for i, v := range roles {
principals[i+1] = v
}
//check for any defined provisioning user
if c.CertificateAuthority.ProvisioningUser != "" {
// Add additional roles for the provisioning account
principals = append(principals, c.CertificateAuthority.ProvisioningUser)
}
// Create the certificate struct with all our configured alues
certificate := ssh.Certificate{
Nonce: nonce,
Key: publicKey,
Serial: serial.Uint64(),
CertType: ssh.UserCert,
KeyId: keyID,
ValidPrincipals: principals,
Permissions: ssh.Permissions{
CriticalOptions: criticalOptions,
Extensions: extensions,
},
ValidAfter: uint64(validAfter.Unix()),
ValidBefore: uint64(validBefore.Unix()),
}
// Setup our Certificate Authority signer backed by KMS
kmsSigner := signer.NewKMSSigner(c.CertificateAuthority.KeyAlias)
sshAlgorithmSigner, err := signer.NewAlgorithmSignerFromSigner(kmsSigner, ssh.SigAlgoRSASHA2256)
if err != nil {
return nil, err
}
// Sign the certificate!!
if err := certificate.SignCert(rand.Reader, sshAlgorithmSigner); err != nil {
return nil, err
}
// Extract the public key (certificate) to return to the user
pubkey, err := ssh.ParsePublicKey(certificate.Marshal())
if err != nil {
return nil, err
}
// Success!
return &signer.SSHrimpResult{
Certificate: string(ssh.MarshalAuthorizedKey(pubkey)),
ErrorMessage: "",
ErrorType: "",
}, nil
}
func main() {
lambda.Start(HandleRequest)
}