/
amphora_ssh.go
221 lines (195 loc) · 5.91 KB
/
amphora_ssh.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
218
219
220
221
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package octavia
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"time"
"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/keypairs"
"github.com/openstack-k8s-operators/lib-common/modules/common/configmap"
"github.com/openstack-k8s-operators/lib-common/modules/common/helper"
"github.com/openstack-k8s-operators/lib-common/modules/common/secret"
"github.com/openstack-k8s-operators/lib-common/modules/common/util"
octaviav1 "github.com/openstack-k8s-operators/octavia-operator/api/v1beta1"
"golang.org/x/crypto/ssh"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// NovaKeyPairName stores the name of the nova keypair that holds the public SSH key for access to the amphorae
const NovaKeyPairName string = "octavia-ssh-keypair"
func generateECDSAKeys() (pubKey string, privKey string, err error) {
// generate private key
curve := elliptic.P521()
privateKey, err := ecdsa.GenerateKey(curve, rand.Reader)
if err != nil {
return "", "", err
}
// encode public key
publicKey, err := ssh.NewPublicKey(privateKey.Public())
if err != nil {
return "", "", err
}
pubBytes := ssh.MarshalAuthorizedKey(publicKey)
// encode private key
bytes, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
return "", "", err
}
privBytes := pem.EncodeToMemory(&pem.Block{
Type: "PRIVATE KEY",
Bytes: bytes,
})
return string(pubBytes), string(privBytes), nil
}
func storePrivateKeyAsSecret(
ctx context.Context,
instance *octaviav1.Octavia,
h *helper.Helper,
privKey string,
) error {
oAmpSecret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: instance.Spec.LoadBalancerSSHPrivKey,
Namespace: instance.Namespace,
},
Data: map[string][]byte{
"key": []byte(privKey),
},
}
_, _, err := secret.CreateOrPatchSecret(ctx, h, instance, oAmpSecret)
return err
}
func storePublicKeyAsConfigMap(
ctx context.Context,
instance *octaviav1.Octavia,
h *helper.Helper,
pubKey string,
) error {
cData := map[string]string{"key": pubKey}
cms := []util.Template{
{
Name: instance.Spec.LoadBalancerSSHPubKey,
Type: util.TemplateTypeNone,
InstanceType: instance.Kind,
CustomData: cData,
Namespace: instance.Namespace,
},
}
err := configmap.EnsureConfigMaps(ctx, h, instance, cms, nil)
return err
}
func uploadKeypair(
ctx context.Context,
instance *octaviav1.Octavia,
h *helper.Helper,
pubKey string) error {
osClient, err := GetOpenstackClient(ctx, instance.Namespace, h)
if err != nil {
return fmt.Errorf("Error getting openstack client: %w", err)
}
computeClient, err := GetComputeClient(osClient)
if err != nil {
return fmt.Errorf("Error getting compute client: %w", err)
}
octaviaUser, err := GetUser(osClient, instance.Spec.ServiceUser)
if err != nil {
return fmt.Errorf("Error getting user details from openstack client: %w", err)
}
listOpts := keypairs.ListOpts{
UserID: octaviaUser.ID,
}
allPages, err := keypairs.List(computeClient, listOpts).AllPages()
if err != nil {
return fmt.Errorf("Could not list keypairs: %w", err)
}
allKeyPairs, err := keypairs.ExtractKeyPairs(allPages)
if err != nil {
return fmt.Errorf("Could not extract keypairs: %w", err)
}
var keypairExists = false
for _, kp := range allKeyPairs {
if kp.Name == NovaKeyPairName {
keypairExists = true
break
}
}
if keypairExists {
deleteOpts := keypairs.DeleteOpts{
UserID: octaviaUser.ID,
}
err := keypairs.Delete(computeClient, NovaKeyPairName, deleteOpts).ExtractErr()
if err != nil {
return fmt.Errorf("Error deleting the existing SSH keypair for amphorae: %w", err)
}
}
createOpts := keypairs.CreateOpts{
Name: NovaKeyPairName,
Type: "ssh",
PublicKey: pubKey,
UserID: octaviaUser.ID,
}
_, err = keypairs.Create(computeClient, createOpts).Extract()
if err != nil {
return fmt.Errorf("Error uploading public key for SSH authentication with amphora: %w", err)
}
return nil
}
// EnsureAmpSSHConfig ensures amphora SSH configuration is set up
func EnsureAmpSSHConfig(
ctx context.Context,
instance *octaviav1.Octavia,
h *helper.Helper,
) error {
cmap, _, err := configmap.GetConfigMap(
ctx, h, instance, instance.Spec.LoadBalancerSSHPubKey, 10*time.Second)
if err == nil && cmap.Data != nil {
// Fail if config map has no data
if len(cmap.Data) == 0 || cmap.Data["key"] == "" {
return fmt.Errorf(
"ConfigMap %s exists but has no key data",
instance.Spec.LoadBalancerSSHPubKey)
}
err = uploadKeypair(ctx, instance, h, cmap.Data["key"])
if err != nil {
return err
}
} else {
if err != nil && !k8serrors.IsNotFound(err) {
return fmt.Errorf("Error retrieving config map %s - %w", instance.Spec.LoadBalancerSSHPubKey, err)
}
pubKey, privKey, err := generateECDSAKeys()
if err != nil {
return fmt.Errorf("Error while generating SSH keys for amphorae: %w", err)
}
err = storePrivateKeyAsSecret(ctx, instance, h, privKey)
if err != nil {
return fmt.Errorf("Error creating ssh key secret %s - %w",
instance.Spec.LoadBalancerSSHPrivKey, err)
}
err = storePublicKeyAsConfigMap(ctx, instance, h, pubKey)
if err != nil {
return fmt.Errorf("Error creating ssh key config map %s - %w",
instance.Spec.LoadBalancerSSHPubKey, err)
}
err = uploadKeypair(ctx, instance, h, pubKey)
if err != nil {
return err
}
}
return nil
}