/
ssh_service.go
217 lines (189 loc) · 7.2 KB
/
ssh_service.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
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
package ssh
import (
"crypto/rand"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"strings"
"time"
"github.com/infamousjoeg/cyberark-aam-pkiaas/internal/backend"
"github.com/infamousjoeg/cyberark-aam-pkiaas/internal/httperror"
"github.com/infamousjoeg/cyberark-aam-pkiaas/internal/pki"
"github.com/infamousjoeg/cyberark-aam-pkiaas/internal/types"
"golang.org/x/crypto/ssh"
)
// CreateSSHTemplate Validates the HTTP request data and creates a new SSH template based on the critera defined
// in `template` and writes it tothe storage backend
func CreateSSHTemplate(template types.SSHTemplate, storage backend.Storage) httperror.HTTPError {
err := ValidateRequestHosts(template.AllowedHosts)
if err != nil {
return httperror.SSHInvalidHost(err.Error())
}
err = ValidateRequestPrincipals(template.AllowedPrincipals)
if err != nil {
return httperror.SSHInvalidPrincipal(err.Error())
}
if strings.ToUpper(template.CertType) != "USER" && strings.ToUpper(template.CertType) != "HOST" {
return httperror.SSHInvalidCertType()
}
err = storage.CreateSSHTemplate(template)
if err != nil {
return httperror.StorageWriteFail(err.Error())
}
return httperror.HTTPError{}
}
// GetSSHTemplate Retrieves the SSH template defined by `templateName` from the storage backend and returns it
// to the HTTP controller function
func GetSSHTemplate(templateName string, storage backend.Storage) (types.SSHTemplate, httperror.HTTPError) {
template, err := storage.GetSSHTemplate(templateName)
if err != nil {
httpErr := httperror.StorageReadFail(err.Error())
return types.SSHTemplate{}, httpErr
}
return template, httperror.HTTPError{}
}
// DeleteSSHTemplate Deletes the SSH template requested by `templateName` from the storage backend
func DeleteSSHTemplate(templateName string, storage backend.Storage) httperror.HTTPError {
err := storage.DeleteSSHTemplate(templateName)
if err != nil {
return httperror.StorageDeleteFail(err.Error())
}
return httperror.HTTPError{}
}
// ListSSHTemplates Collects a list of all available SSH templates from the storage backend
func ListSSHTemplates(storage backend.Storage) (types.TemplateListResponse, httperror.HTTPError) {
templates, err := storage.ListSSHTemplates()
if err != nil {
return types.TemplateListResponse{}, httperror.StorageReadFail(err.Error())
}
respTemplates := types.TemplateListResponse{
Templates: templates,
}
return respTemplates, httperror.HTTPError{}
}
// CreateSSHCertificate Accepts a request with an authorized key public key, signs it with the intermediate CA key
// and returns the SSH certificate to the requestor
func CreateSSHCertificate(certReq types.SSHSignRequest, storage backend.Storage) (types.SSHCertificate, httperror.HTTPError) {
signingKey, err := storage.GetSigningKey()
if err != nil {
return types.SSHCertificate{}, httperror.SigningKeyReadFail(err.Error())
}
template, err := storage.GetSSHTemplate(certReq.TemplateName)
if err != nil {
return types.SSHCertificate{}, httperror.StorageReadFail(err.Error())
}
err = ValidateAllowedPrincipals(template.AllowedPrincipals, certReq.ValidPrincipals)
if err != nil {
return types.SSHCertificate{}, httperror.SSHForbiddenPrincipal(err.Error())
}
err = ValidateAllowedHosts(template.AllowedHosts, certReq.Domains)
if err != nil {
return types.SSHCertificate{}, httperror.SSHForbiddenHost(err.Error())
}
if ValidateAllowedCriticalOptions(template.PermittedCriticalOptions, certReq.CriticalOptions) != nil {
return types.SSHCertificate{}, httperror.SSHForbiddenCriticalOption(err.Error())
}
if ValidateAllowedExtensions(template.PermittedExtensions, certReq.Extensions) != nil {
return types.SSHCertificate{}, httperror.SSHForbiddenExtension(err.Error())
}
var certType uint32
if strings.ToUpper(template.CertType) == "HOST" {
certType = ssh.HostCert
}
if strings.ToUpper(template.CertType) == "USER" {
certType = ssh.UserCert
}
criticalOptions := make(map[string]string)
for _, option := range certReq.CriticalOptions {
criticalOptions[option.Option] = option.Value
}
if len(certReq.Domains) > 0 {
criticalOptions["source-address"] = strings.Join(certReq.Domains, ",")
}
extensions := make(map[string]string)
for _, extension := range certReq.Extensions {
extensions[extension] = ""
}
pubkey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(certReq.PublicKey))
if err != nil {
return types.SSHCertificate{}, httperror.ParsePublicKeyError(err.Error())
}
decodedKey, err := base64.StdEncoding.DecodeString(signingKey)
if err != nil {
return types.SSHCertificate{}, httperror.DecodeSigningKeyError(err.Error())
}
parsedKey, err := x509.ParsePKCS8PrivateKey(decodedKey)
if err != nil {
if strings.Contains(err.Error(), "ParsePKCS1PrivateKey") {
parsedKey, err = x509.ParsePKCS1PrivateKey(decodedKey)
if err != nil {
return types.SSHCertificate{}, httperror.ParseSigningKeyError(err.Error())
}
} else {
return types.SSHCertificate{}, httperror.ParseSigningKeyError(err.Error())
}
}
keyType := fmt.Sprintf("%T", parsedKey)
var blockType string
switch keyType {
case "*rsa.PrivateKey":
blockType = "RSA PRIVATE KEY"
case "*ecdsa.PrivateKey":
blockType = "EC PRIVATE KEY"
case "ed25519.PrivateKey":
blockType = "OPENSSH PRIVATE KEY"
}
pemKey := pem.EncodeToMemory(&pem.Block{Type: blockType, Bytes: decodedKey})
signer, err := ssh.ParsePrivateKey(pemKey)
if err != nil {
return types.SSHCertificate{}, httperror.ParseSigningKeyError(err.Error())
}
serialNumber, err := pki.GenerateSerialNumber(storage)
if err != nil {
return types.SSHCertificate{}, httperror.GenerateSerialFail(err.Error())
}
var ttl uint64
if certReq.TTL > template.MaxTTL {
ttl = template.MaxTTL
} else {
ttl = certReq.TTL
}
// Retrieve the intermediate CA certificate from backend and go through the necessary steps
// to convert it from a PEM-string to a usable x509.Certificate object
strCert, err := storage.GetSigningCert()
if err != nil {
return types.SSHCertificate{}, httperror.StorageReadFail(err.Error())
}
derCACert, err := base64.StdEncoding.DecodeString(strCert)
if err != nil {
return types.SSHCertificate{}, httperror.DecodeCertError(err.Error())
}
caCert, err := x509.ParseCertificate(derCACert)
if err != nil {
return types.SSHCertificate{}, httperror.ParseCertificateError(err.Error())
}
// Validate that requested certificate is within validity period of CA certificate
if caCert.NotAfter.Sub(time.Now().Add(time.Minute*time.Duration(ttl)).UTC()) < 0 {
return types.SSHCertificate{}, httperror.InvalidValidityPeriod()
}
certificate := &ssh.Certificate{
Nonce: []byte{},
Serial: serialNumber.Uint64(),
Key: pubkey,
CertType: certType,
ValidPrincipals: certReq.ValidPrincipals,
ValidBefore: uint64(time.Now().Unix()) + ttl,
SignatureKey: signer.PublicKey(),
}
if certType == ssh.UserCert {
certificate.Permissions.CriticalOptions = criticalOptions
certificate.Permissions.Extensions = extensions
}
err = certificate.SignCert(rand.Reader, signer)
if err != nil {
fmt.Println("SignCert: " + err.Error())
return types.SSHCertificate{}, httperror.CreateCertificateFail(err.Error())
}
return types.SSHCertificate{Certificate: string(ssh.MarshalAuthorizedKey(certificate))}, httperror.HTTPError{}
}