Debian Codegraph @

algorithms.go

raw symbols SCIP
1 package httpsig
2
3 import (
4 "crypto"
5 "crypto/ecdsa"
6 "crypto/hmac"
7 "crypto/rsa"
8 "crypto/sha256"
9 "crypto/sha512"
10 "crypto/subtle" // Use should trigger great care
11 "encoding/asn1"
12 "errors"
13 "fmt"
14 "hash"
15 "io"
16 "math/big"
17 "strings"
18
19 "golang.org/x/crypto/blake2b"
20 "golang.org/x/crypto/blake2s"
21 "golang.org/x/crypto/ed25519"
22 "golang.org/x/crypto/sha3"
23 "golang.org/x/crypto/ssh"
24 )
25
26 const (
27 hmacPrefix = "hmac"
28 rsaPrefix = "rsa"
29 sshPrefix = "ssh"
30 ecdsaPrefix = "ecdsa"
31 ed25519Prefix = "ed25519"
32 sha224String = "sha224"
33 sha256String = "sha256"
34 sha384String = "sha384"
35 sha512String = "sha512"
36 sha3_224String = "sha3-224"
37 sha3_256String = "sha3-256"
38 sha3_384String = "sha3-384"
39 sha3_512String = "sha3-512"
40 sha512_224String = "sha512-224"
41 sha512_256String = "sha512-256"
42 blake2s_256String = "blake2s-256"
43 blake2b_256String = "blake2b-256"
44 blake2b_384String = "blake2b-384"
45 blake2b_512String = "blake2b-512"
46 )
47
48 var blake2Algorithms = map[crypto.Hash]bool{
49 crypto.BLAKE2s_256: true,
50 crypto.BLAKE2b_256: true,
51 crypto.BLAKE2b_384: true,
52 crypto.BLAKE2b_512: true,
53 }
54
55 var hashToDef = map[crypto.Hash]struct {
56 name string
57 new func(key []byte) (hash.Hash, error) // Only MACers will accept a key
58 }{
59 // Which standard names these?
60 // The spec lists the following as a canonical reference, which is dead:
61 // http://www.iana.org/assignments/signature-algorithms
62 //
63 // Note that the forbidden hashes have an invalid 'new' function.
64 crypto.SHA224: {sha224String, func(key []byte) (hash.Hash, error) { return sha256.New224(), nil }},
65 crypto.SHA256: {sha256String, func(key []byte) (hash.Hash, error) { return sha256.New(), nil }},
66 crypto.SHA384: {sha384String, func(key []byte) (hash.Hash, error) { return sha512.New384(), nil }},
67 crypto.SHA512: {sha512String, func(key []byte) (hash.Hash, error) { return sha512.New(), nil }},
68 crypto.SHA3_224: {sha3_224String, func(key []byte) (hash.Hash, error) { return sha3.New224(), nil }},
69 crypto.SHA3_256: {sha3_256String, func(key []byte) (hash.Hash, error) { return sha3.New256(), nil }},
70 crypto.SHA3_384: {sha3_384String, func(key []byte) (hash.Hash, error) { return sha3.New384(), nil }},
71 crypto.SHA3_512: {sha3_512String, func(key []byte) (hash.Hash, error) { return sha3.New512(), nil }},
72 crypto.SHA512_224: {sha512_224String, func(key []byte) (hash.Hash, error) { return sha512.New512_224(), nil }},
73 crypto.SHA512_256: {sha512_256String, func(key []byte) (hash.Hash, error) { return sha512.New512_256(), nil }},
74 crypto.BLAKE2s_256: {blake2s_256String, func(key []byte) (hash.Hash, error) { return blake2s.New256(key) }},
75 crypto.BLAKE2b_256: {blake2b_256String, func(key []byte) (hash.Hash, error) { return blake2b.New256(key) }},
76 crypto.BLAKE2b_384: {blake2b_384String, func(key []byte) (hash.Hash, error) { return blake2b.New384(key) }},
77 crypto.BLAKE2b_512: {blake2b_512String, func(key []byte) (hash.Hash, error) { return blake2b.New512(key) }},
78 }
79
80 var stringToHash map[string]crypto.Hash
81
82 const (
83 defaultAlgorithm = RSA_SHA256
84 defaultAlgorithmHashing = sha256String
85 )
86
87 func init() {
88 stringToHash = make(map[string]crypto.Hash, len(hashToDef))
89 for k, v := range hashToDef {
90 stringToHash[v.name] = k
91 }
92 // This should guarantee that at runtime the defaultAlgorithm will not
93 // result in errors when fetching a macer or signer (see algorithms.go)
94 if ok, err := isAvailable(string(defaultAlgorithmHashing)); err != nil {
95 panic(err)
96 } else if !ok {
97 panic(fmt.Sprintf("the default httpsig algorithm is unavailable: %q", defaultAlgorithm))
98 }
99 }
100
101 func isForbiddenHash(h crypto.Hash) bool {
102 return false
103 }
104
105 // signer is an internally public type.
106 type signer interface {
107 Sign(rand io.Reader, p crypto.PrivateKey, sig []byte) ([]byte, error)
108 Verify(pub crypto.PublicKey, toHash, signature []byte) error
109 String() string
110 }
111
112 // macer is an internally public type.
113 type macer interface {
114 Sign(sig, key []byte) ([]byte, error)
115 Equal(sig, actualMAC, key []byte) (bool, error)
116 String() string
117 }
118
119 var _ macer = &hmacAlgorithm{}
120
121 type hmacAlgorithm struct {
122 fn func(key []byte) (hash.Hash, error)
123 kind crypto.Hash
124 }
125
126 func (h *hmacAlgorithm) Sign(sig, key []byte) ([]byte, error) {
127 hs, err := h.fn(key)
128 if err != nil {
129 return nil, err
130 }
131 if err = setSig(hs, sig); err != nil {
132 return nil, err
133 }
134 return hs.Sum(nil), nil
135 }
136
137 func (h *hmacAlgorithm) Equal(sig, actualMAC, key []byte) (bool, error) {
138 hs, err := h.fn(key)
139 if err != nil {
140 return false, err
141 }
142 defer hs.Reset()
143 err = setSig(hs, sig)
144 if err != nil {
145 return false, err
146 }
147 expected := hs.Sum(nil)
148 return hmac.Equal(actualMAC, expected), nil
149 }
150
151 func (h *hmacAlgorithm) String() string {
152 return fmt.Sprintf("%s-%s", hmacPrefix, hashToDef[h.kind].name)
153 }
154
155 var _ signer = &rsaAlgorithm{}
156
157 type rsaAlgorithm struct {
158 hash.Hash
159 kind crypto.Hash
160 sshSigner ssh.Signer
161 }
162
163 func (r *rsaAlgorithm) setSig(b []byte) error {
164 n, err := r.Write(b)
165 if err != nil {
166 r.Reset()
167 return err
168 } else if n != len(b) {
169 r.Reset()
170 return fmt.Errorf("could only write %d of %d bytes of signature to hash", n, len(b))
171 }
172 return nil
173 }
174
175 // Code from https://github.com/cloudtools/ssh-cert-authority/pull/49/files
176 // This interface provides a way to reach the exported, but not accessible SignWithOpts() method
177 // in x/crypto/ssh/agent. Access to this is needed to sign with more secure signing algorithms
178 type agentKeyringSigner interface {
179 SignWithOpts(rand io.Reader, data []byte, opts crypto.SignerOpts) (*ssh.Signature, error)
180 }
181
182 // A struct to wrap an SSH Signer with one that will switch to SHA256 Signatures.
183 // Replaces the call to Sign() with a call to SignWithOpts using HashFunc() algorithm.
184 type Sha256Signer struct {
185 ssh.Signer
186 }
187
188 func (s Sha256Signer) HashFunc() crypto.Hash {
189 return crypto.SHA256
190 }
191
192 func (s Sha256Signer) Sign(rand io.Reader, data []byte) (*ssh.Signature, error) {
193 if aks, ok := s.Signer.(agentKeyringSigner); !ok {
194 return nil, fmt.Errorf("ssh: can't wrap a non ssh agentKeyringSigner")
195 } else {
196 return aks.SignWithOpts(rand, data, s)
197 }
198 }
199
200 func (r *rsaAlgorithm) Sign(rand io.Reader, p crypto.PrivateKey, sig []byte) ([]byte, error) {
201 if r.sshSigner != nil {
202 var (
203 sshsig *ssh.Signature
204 err error
205 )
206 // are we using an SSH Agent
207 if _, ok := r.sshSigner.(agentKeyringSigner); ok {
208 signer := Sha256Signer{r.sshSigner}
209 sshsig, err = signer.Sign(rand, sig)
210 if err != nil {
211 return nil, err
212 }
213 } else {
214 sshsig, err = r.sshSigner.(ssh.AlgorithmSigner).SignWithAlgorithm(rand, sig, ssh.SigAlgoRSASHA2256)
215 if err != nil {
216 return nil, err
217 }
218 }
219
220 return sshsig.Blob, nil
221 }
222 defer r.Reset()
223
224 if err := r.setSig(sig); err != nil {
225 return nil, err
226 }
227 rsaK, ok := p.(*rsa.PrivateKey)
228 if !ok {
229 return nil, errors.New("crypto.PrivateKey is not *rsa.PrivateKey")
230 }
231 return rsa.SignPKCS1v15(rand, rsaK, r.kind, r.Sum(nil))
232 }
233
234 func (r *rsaAlgorithm) Verify(pub crypto.PublicKey, toHash, signature []byte) error {
235 defer r.Reset()
236 rsaK, ok := pub.(*rsa.PublicKey)
237 if !ok {
238 return errors.New("crypto.PublicKey is not *rsa.PublicKey")
239 }
240 if err := r.setSig(toHash); err != nil {
241 return err
242 }
243 return rsa.VerifyPKCS1v15(rsaK, r.kind, r.Sum(nil), signature)
244 }
245
246 func (r *rsaAlgorithm) String() string {
247 return fmt.Sprintf("%s-%s", rsaPrefix, hashToDef[r.kind].name)
248 }
249
250 var _ signer = &ed25519Algorithm{}
251
252 type ed25519Algorithm struct {
253 sshSigner ssh.Signer
254 }
255
256 func (r *ed25519Algorithm) Sign(rand io.Reader, p crypto.PrivateKey, sig []byte) ([]byte, error) {
257 if r.sshSigner != nil {
258 sshsig, err := r.sshSigner.Sign(rand, sig)
259 if err != nil {
260 return nil, err
261 }
262
263 return sshsig.Blob, nil
264 }
265 ed25519K, ok := p.(ed25519.PrivateKey)
266 if !ok {
267 return nil, errors.New("crypto.PrivateKey is not ed25519.PrivateKey")
268 }
269 return ed25519.Sign(ed25519K, sig), nil
270 }
271
272 func (r *ed25519Algorithm) Verify(pub crypto.PublicKey, toHash, signature []byte) error {
273 ed25519K, ok := pub.(ed25519.PublicKey)
274 if !ok {
275 return errors.New("crypto.PublicKey is not ed25519.PublicKey")
276 }
277
278 if ed25519.Verify(ed25519K, toHash, signature) {
279 return nil
280 }
281
282 return errors.New("ed25519 verify failed")
283 }
284
285 func (r *ed25519Algorithm) String() string {
286 return fmt.Sprintf("%s", ed25519Prefix)
287 }
288
289 var _ signer = &ecdsaAlgorithm{}
290
291 type ecdsaAlgorithm struct {
292 hash.Hash
293 kind crypto.Hash
294 }
295
296 func (r *ecdsaAlgorithm) setSig(b []byte) error {
297 n, err := r.Write(b)
298 if err != nil {
299 r.Reset()
300 return err
301 } else if n != len(b) {
302 r.Reset()
303 return fmt.Errorf("could only write %d of %d bytes of signature to hash", n, len(b))
304 }
305 return nil
306 }
307
308 type ECDSASignature struct {
309 R, S *big.Int
310 }
311
312 func (r *ecdsaAlgorithm) Sign(rand io.Reader, p crypto.PrivateKey, sig []byte) ([]byte, error) {
313 defer r.Reset()
314 if err := r.setSig(sig); err != nil {
315 return nil, err
316 }
317 ecdsaK, ok := p.(*ecdsa.PrivateKey)
318 if !ok {
319 return nil, errors.New("crypto.PrivateKey is not *ecdsa.PrivateKey")
320 }
321 R, S, err := ecdsa.Sign(rand, ecdsaK, r.Sum(nil))
322 if err != nil {
323 return nil, err
324 }
325
326 signature := ECDSASignature{R: R, S: S}
327 bytes, err := asn1.Marshal(signature)
328
329 return bytes, err
330 }
331
332 func (r *ecdsaAlgorithm) Verify(pub crypto.PublicKey, toHash, signature []byte) error {
333 defer r.Reset()
334 ecdsaK, ok := pub.(*ecdsa.PublicKey)
335 if !ok {
336 return errors.New("crypto.PublicKey is not *ecdsa.PublicKey")
337 }
338 if err := r.setSig(toHash); err != nil {
339 return err
340 }
341
342 sig := new(ECDSASignature)
343 _, err := asn1.Unmarshal(signature, sig)
344 if err != nil {
345 return err
346 }
347
348 if ecdsa.Verify(ecdsaK, r.Sum(nil), sig.R, sig.S) {
349 return nil
350 } else {
351 return errors.New("Invalid signature")
352 }
353 }
354
355 func (r *ecdsaAlgorithm) String() string {
356 return fmt.Sprintf("%s-%s", ecdsaPrefix, hashToDef[r.kind].name)
357 }
358
359 var _ macer = &blakeMacAlgorithm{}
360
361 type blakeMacAlgorithm struct {
362 fn func(key []byte) (hash.Hash, error)
363 kind crypto.Hash
364 }
365
366 func (r *blakeMacAlgorithm) Sign(sig, key []byte) ([]byte, error) {
367 hs, err := r.fn(key)
368 if err != nil {
369 return nil, err
370 }
371 if err = setSig(hs, sig); err != nil {
372 return nil, err
373 }
374 return hs.Sum(nil), nil
375 }
376
377 func (r *blakeMacAlgorithm) Equal(sig, actualMAC, key []byte) (bool, error) {
378 hs, err := r.fn(key)
379 if err != nil {
380 return false, err
381 }
382 defer hs.Reset()
383 err = setSig(hs, sig)
384 if err != nil {
385 return false, err
386 }
387 expected := hs.Sum(nil)
388 return subtle.ConstantTimeCompare(actualMAC, expected) == 1, nil
389 }
390
391 func (r *blakeMacAlgorithm) String() string {
392 return fmt.Sprintf("%s", hashToDef[r.kind].name)
393 }
394
395 func setSig(a hash.Hash, b []byte) error {
396 n, err := a.Write(b)
397 if err != nil {
398 a.Reset()
399 return err
400 } else if n != len(b) {
401 a.Reset()
402 return fmt.Errorf("could only write %d of %d bytes of signature to hash", n, len(b))
403 }
404 return nil
405 }
406
407 // IsSupportedHttpSigAlgorithm returns true if the string is supported by this
408 // library, is not a hash known to be weak, and is supported by the hardware.
409 func IsSupportedHttpSigAlgorithm(algo string) bool {
410 a, err := isAvailable(algo)
411 return a && err == nil
412 }
413
414 // isAvailable is an internally public function
415 func isAvailable(algo string) (bool, error) {
416 c, ok := stringToHash[algo]
417 if !ok {
418 return false, fmt.Errorf("no match for %q", algo)
419 }
420 if isForbiddenHash(c) {
421 return false, fmt.Errorf("forbidden hash type in %q", algo)
422 }
423 return c.Available(), nil
424 }
425
426 func newAlgorithmConstructor(algo string) (fn func(k []byte) (hash.Hash, error), c crypto.Hash, e error) {
427 ok := false
428 c, ok = stringToHash[algo]
429 if !ok {
430 e = fmt.Errorf("no match for %q", algo)
431 return
432 }
433 if isForbiddenHash(c) {
434 e = fmt.Errorf("forbidden hash type in %q", algo)
435 return
436 }
437 algoDef, ok := hashToDef[c]
438 if !ok {
439 e = fmt.Errorf("have crypto.Hash %v but no definition", c)
440 return
441 }
442 fn = func(key []byte) (hash.Hash, error) {
443 h, err := algoDef.new(key)
444 if err != nil {
445 return nil, err
446 }
447 return h, nil
448 }
449 return
450 }
451
452 func newAlgorithm(algo string, key []byte) (hash.Hash, crypto.Hash, error) {
453 fn, c, err := newAlgorithmConstructor(algo)
454 if err != nil {
455 return nil, c, err
456 }
457 h, err := fn(key)
458 return h, c, err
459 }
460
461 func signerFromSSHSigner(sshSigner ssh.Signer, s string) (signer, error) {
462 switch {
463 case strings.HasPrefix(s, rsaPrefix):
464 return &rsaAlgorithm{
465 sshSigner: sshSigner,
466 }, nil
467 case strings.HasPrefix(s, ed25519Prefix):
468 return &ed25519Algorithm{
469 sshSigner: sshSigner,
470 }, nil
471 default:
472 return nil, fmt.Errorf("no signer matching %q", s)
473 }
474 }
475
476 // signerFromString is an internally public method constructor
477 func signerFromString(s string) (signer, error) {
478 s = strings.ToLower(s)
479 isEcdsa := false
480 isEd25519 := false
481 var algo string = ""
482 if strings.HasPrefix(s, ecdsaPrefix) {
483 algo = strings.TrimPrefix(s, ecdsaPrefix+"-")
484 isEcdsa = true
485 } else if strings.HasPrefix(s, rsaPrefix) {
486 algo = strings.TrimPrefix(s, rsaPrefix+"-")
487 } else if strings.HasPrefix(s, ed25519Prefix) {
488 isEd25519 = true
489 algo = "sha512"
490 } else {
491 return nil, fmt.Errorf("no signer matching %q", s)
492 }
493 hash, cHash, err := newAlgorithm(algo, nil)
494 if err != nil {
495 return nil, err
496 }
497 if isEd25519 {
498 return &ed25519Algorithm{}, nil
499 }
500 if isEcdsa {
501 return &ecdsaAlgorithm{
502 Hash: hash,
503 kind: cHash,
504 }, nil
505 }
506 return &rsaAlgorithm{
507 Hash: hash,
508 kind: cHash,
509 }, nil
510 }
511
512 // macerFromString is an internally public method constructor
513 func macerFromString(s string) (macer, error) {
514 s = strings.ToLower(s)
515 if strings.HasPrefix(s, hmacPrefix) {
516 algo := strings.TrimPrefix(s, hmacPrefix+"-")
517 hashFn, cHash, err := newAlgorithmConstructor(algo)
518 if err != nil {
519 return nil, err
520 }
521 // Ensure below does not panic
522 _, err = hashFn(nil)
523 if err != nil {
524 return nil, err
525 }
526 return &hmacAlgorithm{
527 fn: func(key []byte) (hash.Hash, error) {
528 return hmac.New(func() hash.Hash {
529 h, e := hashFn(nil)
530 if e != nil {
531 panic(e)
532 }
533 return h
534 }, key), nil
535 },
536 kind: cHash,
537 }, nil
538 } else if bl, ok := stringToHash[s]; ok && blake2Algorithms[bl] {
539 hashFn, cHash, err := newAlgorithmConstructor(s)
540 if err != nil {
541 return nil, err
542 }
543 return &blakeMacAlgorithm{
544 fn: hashFn,
545 kind: cHash,
546 }, nil
547 } else {
548 return nil, fmt.Errorf("no MACer matching %q", s)
549 }
550 }