Debian Codegraph @

crypto_test.go

raw
1 package sprig
2
3 import (
4 "crypto/x509"
5 "encoding/base64"
6 "encoding/pem"
7 "fmt"
8 "strings"
9 "testing"
10
11 "github.com/stretchr/testify/assert"
12 bcrypt_lib "golang.org/x/crypto/bcrypt"
13 )
14
15 const (
16 beginCertificate = "-----BEGIN CERTIFICATE-----"
17 endCertificate = "-----END CERTIFICATE-----"
18 )
19
20 var (
21 // fastCertKeyAlgos is the list of private key algorithms that are supported for certificate use, and
22 // are fast to generate.
23 fastCertKeyAlgos = []string{
24 "ecdsa",
25 "ed25519",
26 }
27 )
28
29 func TestSha256Sum(t *testing.T) {
30 tpl := `{{"abc" | sha256sum}}`
31 if err := runt(tpl, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); err != nil {
32 t.Error(err)
33 }
34 }
35 func TestSha1Sum(t *testing.T) {
36 tpl := `{{"abc" | sha1sum}}`
37 if err := runt(tpl, "a9993e364706816aba3e25717850c26c9cd0d89d"); err != nil {
38 t.Error(err)
39 }
40 }
41
42 func TestAdler32Sum(t *testing.T) {
43 tpl := `{{"abc" | adler32sum}}`
44 if err := runt(tpl, "38600999"); err != nil {
45 t.Error(err)
46 }
47 }
48
49 func TestBcrypt(t *testing.T) {
50 out, err := runRaw(`{{"abc" | bcrypt}}`, nil)
51 if err != nil {
52 t.Error(err)
53 }
54 if bcrypt_lib.CompareHashAndPassword([]byte(out), []byte("abc")) != nil {
55 t.Error("Generated hash is not the equivalent for password:", "abc")
56 }
57 }
58
59 type HtpasswdCred struct {
60 Username string
61 Password string
62 Valid bool
63 }
64
65 func TestHtpasswd(t *testing.T) {
66 expectations := []HtpasswdCred{
67 {Username: "myUser", Password: "myPassword", Valid: true},
68 {Username: "special'o79Cv_*qFe,)<user", Password: "special<j7+3p#6-.Jx2U:m8G;kGypassword", Valid: true},
69 {Username: "wrongus:er", Password: "doesn'tmatter", Valid: false}, // ':' isn't allowed in the username - https://tools.ietf.org/html/rfc2617#page-6
70 }
71
72 for _, credential := range expectations {
73 out, err := runRaw(`{{htpasswd .Username .Password}}`, credential)
74 if err != nil {
75 t.Error(err)
76 }
77 result := strings.Split(out, ":")
78 if 0 != strings.Compare(credential.Username, result[0]) && credential.Valid {
79 t.Error("Generated username did not match for:", credential.Username)
80 }
81 if bcrypt_lib.CompareHashAndPassword([]byte(result[1]), []byte(credential.Password)) != nil && credential.Valid {
82 t.Error("Generated hash is not the equivalent for password:", credential.Password)
83 }
84 }
85 }
86
87 func TestDerivePassword(t *testing.T) {
88 expectations := map[string]string{
89 `{{derivePassword 1 "long" "password" "user" "example.com"}}`: "ZedaFaxcZaso9*",
90 `{{derivePassword 2 "long" "password" "user" "example.com"}}`: "Fovi2@JifpTupx",
91 `{{derivePassword 1 "maximum" "password" "user" "example.com"}}`: "pf4zS1LjCg&LjhsZ7T2~",
92 `{{derivePassword 1 "medium" "password" "user" "example.com"}}`: "ZedJuz8$",
93 `{{derivePassword 1 "basic" "password" "user" "example.com"}}`: "pIS54PLs",
94 `{{derivePassword 1 "short" "password" "user" "example.com"}}`: "Zed5",
95 `{{derivePassword 1 "pin" "password" "user" "example.com"}}`: "6685",
96 }
97
98 for tpl, result := range expectations {
99 out, err := runRaw(tpl, nil)
100 if err != nil {
101 t.Error(err)
102 }
103 if 0 != strings.Compare(out, result) {
104 t.Error("Generated password does not match for", tpl)
105 }
106 }
107 }
108
109 // NOTE(bacongobbler): this test is really _slow_ because of how long it takes to compute
110 // and generate a new crypto key.
111 func TestGenPrivateKey(t *testing.T) {
112 // test that calling by default generates an RSA private key
113 tpl := `{{genPrivateKey ""}}`
114 out, err := runRaw(tpl, nil)
115 if err != nil {
116 t.Error(err)
117 }
118 if !strings.Contains(out, "RSA PRIVATE KEY") {
119 t.Error("Expected RSA PRIVATE KEY")
120 }
121 // test all acceptable arguments
122 tpl = `{{genPrivateKey "rsa"}}`
123 out, err = runRaw(tpl, nil)
124 if err != nil {
125 t.Error(err)
126 }
127 if !strings.Contains(out, "RSA PRIVATE KEY") {
128 t.Error("Expected RSA PRIVATE KEY")
129 }
130 tpl = `{{genPrivateKey "dsa"}}`
131 out, err = runRaw(tpl, nil)
132 if err != nil {
133 t.Error(err)
134 }
135 if !strings.Contains(out, "DSA PRIVATE KEY") {
136 t.Error("Expected DSA PRIVATE KEY")
137 }
138 tpl = `{{genPrivateKey "ecdsa"}}`
139 out, err = runRaw(tpl, nil)
140 if err != nil {
141 t.Error(err)
142 }
143 if !strings.Contains(out, "EC PRIVATE KEY") {
144 t.Error("Expected EC PRIVATE KEY")
145 }
146 tpl = `{{genPrivateKey "ed25519"}}`
147 out, err = runRaw(tpl, nil)
148 if err != nil {
149 t.Error(err)
150 }
151 if !strings.Contains(out, "PRIVATE KEY") {
152 t.Error("Expected PRIVATE KEY")
153 }
154 // test bad
155 tpl = `{{genPrivateKey "bad"}}`
156 out, err = runRaw(tpl, nil)
157 if err != nil {
158 t.Error(err)
159 }
160 if out != "Unknown type bad" {
161 t.Error("Expected type 'bad' to be an unknown crypto algorithm")
162 }
163 // ensure that we can base64 encode the string
164 tpl = `{{genPrivateKey "rsa" | b64enc}}`
165 _, err = runRaw(tpl, nil)
166 if err != nil {
167 t.Error(err)
168 }
169 }
170
171 func TestRandBytes(t *testing.T) {
172 tpl := `{{randBytes 12}}`
173 out, err := runRaw(tpl, nil)
174 if err != nil {
175 t.Error(err)
176 }
177
178 bytes, err := base64.StdEncoding.DecodeString(out)
179 if err != nil {
180 t.Error(err)
181 }
182 if len(bytes) != 12 {
183 t.Error("Expected 12 base64-encoded bytes")
184 }
185
186 out2, err := runRaw(tpl, nil)
187 if err != nil {
188 t.Error(err)
189 }
190
191 if out == out2 {
192 t.Error("Expected subsequent randBytes to be different")
193 }
194 }
195
196 func TestUUIDGeneration(t *testing.T) {
197 tpl := `{{uuidv4}}`
198 out, err := runRaw(tpl, nil)
199 if err != nil {
200 t.Error(err)
201 }
202
203 if len(out) != 36 {
204 t.Error("Expected UUID of length 36")
205 }
206
207 out2, err := runRaw(tpl, nil)
208 if err != nil {
209 t.Error(err)
210 }
211
212 if out == out2 {
213 t.Error("Expected subsequent UUID generations to be different")
214 }
215 }
216
217 func TestBuildCustomCert(t *testing.T) {
218 ca, _ := generateCertificateAuthority("example.com", 365)
219 tpl := fmt.Sprintf(
220 `{{- $ca := buildCustomCert "%s" "%s"}}
221 {{- $ca.Cert }}`,
222 base64.StdEncoding.EncodeToString([]byte(ca.Cert)),
223 base64.StdEncoding.EncodeToString([]byte(ca.Key)),
224 )
225 out, err := runRaw(tpl, nil)
226 if err != nil {
227 t.Error(err)
228 }
229
230 tpl2 := fmt.Sprintf(
231 `{{- $ca := buildCustomCert "%s" "%s"}}
232 {{- $ca.Cert }}`,
233 base64.StdEncoding.EncodeToString([]byte("fail")),
234 base64.StdEncoding.EncodeToString([]byte(ca.Key)),
235 )
236 out2, _ := runRaw(tpl2, nil)
237
238 assert.Equal(t, out, ca.Cert)
239 assert.NotEqual(t, out2, ca.Cert)
240 }
241
242 func TestGenCA(t *testing.T) {
243 testGenCA(t, nil)
244 }
245
246 func TestGenCAWithKey(t *testing.T) {
247 for _, keyAlgo := range fastCertKeyAlgos {
248 t.Run(keyAlgo, func(t *testing.T) {
249 testGenCA(t, &keyAlgo)
250 })
251 }
252 }
253
254 func testGenCA(t *testing.T, keyAlgo *string) {
255 const cn = "foo-ca"
256
257 var genCAExpr string
258 if keyAlgo == nil {
259 genCAExpr = "genCA"
260 } else {
261 genCAExpr = fmt.Sprintf(`genPrivateKey "%s" | genCAWithKey`, *keyAlgo)
262 }
263
264 tpl := fmt.Sprintf(
265 `{{- $ca := %s "%s" 365 }}
266 {{ $ca.Cert }}
267 `,
268 genCAExpr,
269 cn,
270 )
271 out, err := runRaw(tpl, nil)
272 if err != nil {
273 t.Error(err)
274 }
275 assert.Contains(t, out, beginCertificate)
276 assert.Contains(t, out, endCertificate)
277
278 decodedCert, _ := pem.Decode([]byte(out))
279 assert.Nil(t, err)
280 cert, err := x509.ParseCertificate(decodedCert.Bytes)
281 assert.Nil(t, err)
282
283 assert.Equal(t, cn, cert.Subject.CommonName)
284 assert.True(t, cert.IsCA)
285 }
286
287 func TestGenSelfSignedCert(t *testing.T) {
288 testGenSelfSignedCert(t, nil)
289 }
290
291 func TestGenSelfSignedCertWithKey(t *testing.T) {
292 for _, keyAlgo := range fastCertKeyAlgos {
293 t.Run(keyAlgo, func(t *testing.T) {
294 testGenSelfSignedCert(t, &keyAlgo)
295 })
296 }
297 }
298
299 func testGenSelfSignedCert(t *testing.T, keyAlgo *string) {
300 const (
301 cn = "foo.com"
302 ip1 = "10.0.0.1"
303 ip2 = "10.0.0.2"
304 dns1 = "bar.com"
305 dns2 = "bat.com"
306 )
307
308 var genSelfSignedCertExpr string
309 if keyAlgo == nil {
310 genSelfSignedCertExpr = "genSelfSignedCert"
311 } else {
312 genSelfSignedCertExpr = fmt.Sprintf(`genPrivateKey "%s" | genSelfSignedCertWithKey`, *keyAlgo)
313 }
314
315 tpl := fmt.Sprintf(
316 `{{- $cert := %s "%s" (list "%s" "%s") (list "%s" "%s") 365 }}
317 {{ $cert.Cert }}`,
318 genSelfSignedCertExpr,
319 cn,
320 ip1,
321 ip2,
322 dns1,
323 dns2,
324 )
325
326 out, err := runRaw(tpl, nil)
327 if err != nil {
328 t.Error(err)
329 }
330 assert.Contains(t, out, beginCertificate)
331 assert.Contains(t, out, endCertificate)
332
333 decodedCert, _ := pem.Decode([]byte(out))
334 assert.Nil(t, err)
335 cert, err := x509.ParseCertificate(decodedCert.Bytes)
336 assert.Nil(t, err)
337
338 assert.Equal(t, cn, cert.Subject.CommonName)
339 assert.Equal(t, 1, cert.SerialNumber.Sign())
340 assert.Equal(t, 2, len(cert.IPAddresses))
341 assert.Equal(t, ip1, cert.IPAddresses[0].String())
342 assert.Equal(t, ip2, cert.IPAddresses[1].String())
343 assert.Contains(t, cert.DNSNames, dns1)
344 assert.Contains(t, cert.DNSNames, dns2)
345 assert.False(t, cert.IsCA)
346 }
347
348 func TestGenSignedCert(t *testing.T) {
349 testGenSignedCert(t, nil, nil)
350 }
351
352 func TestGenSignedCertWithKey(t *testing.T) {
353 for _, caKeyAlgo := range fastCertKeyAlgos {
354 for _, certKeyAlgo := range fastCertKeyAlgos {
355 t.Run(fmt.Sprintf("%s-%s", caKeyAlgo, certKeyAlgo), func(t *testing.T) {
356 testGenSignedCert(t, &caKeyAlgo, &certKeyAlgo)
357 })
358 }
359 }
360 }
361
362 func testGenSignedCert(t *testing.T, caKeyAlgo, certKeyAlgo *string) {
363 const (
364 cn = "foo.com"
365 ip1 = "10.0.0.1"
366 ip2 = "10.0.0.2"
367 dns1 = "bar.com"
368 dns2 = "bat.com"
369 )
370
371 var genCAExpr, genSignedCertExpr string
372 if caKeyAlgo == nil {
373 genCAExpr = "genCA"
374 } else {
375 genCAExpr = fmt.Sprintf(`genPrivateKey "%s" | genCAWithKey`, *caKeyAlgo)
376 }
377 if certKeyAlgo == nil {
378 genSignedCertExpr = "genSignedCert"
379 } else {
380 genSignedCertExpr = fmt.Sprintf(`genPrivateKey "%s" | genSignedCertWithKey`, *certKeyAlgo)
381 }
382
383 tpl := fmt.Sprintf(
384 `{{- $ca := %s "foo" 365 }}
385 {{- $cert := %s "%s" (list "%s" "%s") (list "%s" "%s") 365 $ca }}
386 {{ $cert.Cert }}
387 `,
388 genCAExpr,
389 genSignedCertExpr,
390 cn,
391 ip1,
392 ip2,
393 dns1,
394 dns2,
395 )
396 out, err := runRaw(tpl, nil)
397 if err != nil {
398 t.Error(err)
399 }
400
401 assert.Contains(t, out, beginCertificate)
402 assert.Contains(t, out, endCertificate)
403
404 decodedCert, _ := pem.Decode([]byte(out))
405 assert.Nil(t, err)
406 cert, err := x509.ParseCertificate(decodedCert.Bytes)
407 assert.Nil(t, err)
408
409 assert.Equal(t, cn, cert.Subject.CommonName)
410 assert.Equal(t, 1, cert.SerialNumber.Sign())
411 assert.Equal(t, 2, len(cert.IPAddresses))
412 assert.Equal(t, ip1, cert.IPAddresses[0].String())
413 assert.Equal(t, ip2, cert.IPAddresses[1].String())
414 assert.Contains(t, cert.DNSNames, dns1)
415 assert.Contains(t, cert.DNSNames, dns2)
416 assert.False(t, cert.IsCA)
417 }
418
419 func TestEncryptDecryptAES(t *testing.T) {
420 tpl := `{{"plaintext" | encryptAES "secretkey" | decryptAES "secretkey"}}`
421 if err := runt(tpl, "plaintext"); err != nil {
422 t.Error(err)
423 }
424 }