forked from robertlestak/cert-manager-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathincapsula.go
208 lines (199 loc) · 5.82 KB
/
incapsula.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
package main
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// IncapsulaSecret contains a single Incapsula API Secret
type IncapsulaSecret struct {
Name string `json:"name"`
ID string `json:"api_id"`
SiteID string `json:"site_id"`
Key string `json:"api_key"`
}
// Get retrieves a single Incapsula secret by name from k8s secrets
func (s *IncapsulaSecret) Get(ctx context.Context) error {
gopt := metav1.GetOptions{}
sc, err := k8sClient.CoreV1().Secrets(os.Getenv("SECRETS_NAMESPACE")).Get(ctx, s.Name, gopt)
if err != nil {
return err
}
s.ID = string(sc.Data["api_id"])
s.Key = string(sc.Data["api_key"])
return nil
}
// Incapsula response contains the response from Incapsula API
type IncapsulaResponse struct {
Res int `json:"res"`
ResMessage string `json:"res_message"`
}
// UploadIncapsulaCert syncs a certificate with Incapsula site
func UploadIncapsulaCert(sec *IncapsulaSecret, cert *Certificate, siteID string) error {
l := log.WithFields(
log.Fields{
"action": "UploadIncapsulaCert",
"siteID": siteID,
},
)
l.Print("UploadIncapsulaCert")
var err error
bCert := base64.StdEncoding.EncodeToString(append(cert.Certificate[:], cert.Chain[:]...))
bKey := base64.StdEncoding.EncodeToString(cert.Key)
c := http.Client{}
iurl := os.Getenv("INCAPSULA_API") + "/sites/customCertificate/upload"
data := url.Values{}
data.Set("api_id", sec.ID)
data.Set("site_id", siteID)
data.Set("api_key", sec.Key)
data.Set("certificate", bCert)
data.Set("private_key", bKey)
d := strings.NewReader(data.Encode())
l.Debugf("url=%s data=%s", iurl, data.Encode())
req, rerr := http.NewRequest("POST", iurl, d)
if rerr != nil {
l.Printf("http.NewRequest error=%v", rerr)
return rerr
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
res, serr := c.Do(req)
if serr != nil {
l.Printf("c.Do error=%v", serr)
return serr
}
defer res.Body.Close()
bd, berr := ioutil.ReadAll(res.Body)
if berr != nil {
l.Printf("ioutil.ReadAll error=%v", berr)
return berr
}
ir := &IncapsulaResponse{}
if err = json.Unmarshal(bd, ir); err != nil {
l.Printf("json.Unmarshal error=%v", err)
return err
}
l.Debugf("incapsula statusCode=%d response=%v", res.StatusCode, string(bd))
if ir.Res != 0 {
l.Printf("status=%v body=%s", res.StatusCode, string(bd))
return fmt.Errorf("incapsula upload failed, body=%s", string(bd))
}
l.Debugf("incapsula response=%v", string(bd))
return err
}
func GetIncapsulaSiteStatus(sec *IncapsulaSecret, siteID string) (string, error) {
l := log.WithFields(
log.Fields{
"action": "GetIncapsulaSiteStatus",
"siteID": siteID,
},
)
l.Print("GetIncapsulaSiteStatus")
var err error
iurl := os.Getenv("INCAPSULA_API") + "/sites/status"
c := http.Client{}
data := url.Values{}
data.Set("api_id", sec.ID)
data.Set("site_id", siteID)
data.Set("api_key", sec.Key)
data.Set("tests", "services")
d := strings.NewReader(data.Encode())
l.Debugf("url=%s data=%s", iurl, data.Encode())
req, rerr := http.NewRequest("POST", iurl, d)
if rerr != nil {
l.Printf("http.NewRequest error=%v", rerr)
return "", rerr
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
res, serr := c.Do(req)
if serr != nil {
l.Printf("c.Do error=%v", serr)
return "", serr
}
defer res.Body.Close()
bd, berr := ioutil.ReadAll(res.Body)
if berr != nil {
l.Printf("ioutil.ReadAll error=%v", berr)
return "", berr
}
ir := &IncapsulaResponse{}
if err = json.Unmarshal(bd, ir); err != nil {
l.Printf("json.Unmarshal error=%v", err)
return string(bd), err
}
l.Debugf("incapsula statusCode=%d response=%v", res.StatusCode, string(bd))
if ir.Res != 0 {
l.Printf("status=%v body=%s", res.StatusCode, string(bd))
return string(bd), fmt.Errorf("incapsula upload failed, body=%s", string(bd))
}
l.Debugf("incapsula response=%v", string(bd))
return string(bd), err
}
// IncapsulaCerts accepts a slice of Secrets and returns only those configured
// for replication to Incapsula
func IncapsulaCerts(s []corev1.Secret) []corev1.Secret {
var c []corev1.Secret
for _, v := range s {
if v.Annotations[operatorName+"/incapsula-site-id"] != "" && cacheChanged(v) {
c = append(c, v)
}
}
return c
}
// handleIncapsulaCerts handles the sync of all Incapsula-enabled certs
func handleIncapsulaCerts(ss []corev1.Secret) {
ss = IncapsulaCerts(ss)
l := log.WithFields(
log.Fields{
"action": "handleIncapsulaCerts",
},
)
l.Print("handleIncapsulaCerts")
for i, s := range ss {
l.Debugf("processing secret %s (%d/%d)", s.ObjectMeta.Name, i+1, len(ss))
is := &IncapsulaSecret{
Name: s.Annotations[operatorName+"/incapsula-secret-name"],
}
gerr := is.Get(context.Background())
if gerr != nil {
l.WithFields(log.Fields{
"siteID": s.Annotations[operatorName+"/incapsula-site-id"],
"secretName": s.Annotations[operatorName+"/incapsula-secret-name"],
}).Printf("is.Get error=%v", gerr)
continue
}
// ensure site has ssl enabled befure uploading cert
_, serr := GetIncapsulaSiteStatus(
is,
s.Annotations[operatorName+"/incapsula-site-id"],
)
if serr != nil {
l.WithFields(log.Fields{
"siteID": s.Annotations[operatorName+"/incapsula-site-id"],
"secretName": s.Annotations[operatorName+"/incapsula-secret-name"],
}).Printf("GetIncapsulaSiteStatus error=%v", serr)
continue
}
c := secretToCert(s)
uerr := UploadIncapsulaCert(
is,
c,
s.Annotations[operatorName+"/incapsula-site-id"],
)
if uerr != nil {
l.WithFields(log.Fields{
"siteID": s.Annotations[operatorName+"/incapsula-site-id"],
"secretName": s.Annotations[operatorName+"/incapsula-secret-name"],
}).Printf("UploadIncapsulaCert error=%v", uerr)
continue
}
addToCache(c)
}
}