| 1 |
package dns |
| 2 |
|
| 3 |
import ( |
| 4 |
"crypto" |
| 5 |
"crypto/ecdsa" |
| 6 |
"crypto/ed25519" |
| 7 |
"crypto/rsa" |
| 8 |
"math/big" |
| 9 |
|
| 10 |
"codeberg.org/miekg/dns/internal/pack" |
| 11 |
) |
| 12 |
|
| 13 |
type CryptoSIG0 struct { |
| 14 |
CryptoSigner crypto.Signer |
| 15 |
PublicKey *KEY |
| 16 |
} |
| 17 |
|
| 18 |
// We need SIG0Option as well here, because the request might be needed as well. |
| 19 |
|
| 20 |
func (c CryptoSIG0) Key() *KEY { return c.PublicKey } |
| 21 |
func (c CryptoSIG0) Signer() crypto.Signer { return c.CryptoSigner } |
| 22 |
|
| 23 |
func (c CryptoSIG0) Sign(s *SIG, p []byte) ([]byte, error) { |
| 24 |
var ( |
| 25 |
off int |
| 26 |
err error |
| 27 |
) |
| 28 |
|
| 29 |
hash, ok := AlgorithmToHash[s.Algorithm] |
| 30 |
if !ok { |
| 31 |
return nil, ErrAlg |
| 32 |
} |
| 33 |
|
| 34 |
sbuf := make([]byte, s.Len()) |
| 35 |
if _, off, err = packRR(s, sbuf, 0, nil); err != nil { |
| 36 |
return nil, err |
| 37 |
} |
| 38 |
sbuf = sbuf[:off] |
| 39 |
|
| 40 |
h := hash.New() |
| 41 |
h.Write(sbuf) |
| 42 |
h.Write(p) |
| 43 |
|
| 44 |
return sign(c.Signer(), h.Sum(nil), hash, s.Algorithm) |
| 45 |
} |
| 46 |
|
| 47 |
func (c CryptoSIG0) Verify(s *SIG, p []byte) error { |
| 48 |
var ( |
| 49 |
off int |
| 50 |
err error |
| 51 |
) |
| 52 |
hash, ok := AlgorithmToHash[s.Algorithm] |
| 53 |
if !ok { |
| 54 |
return ErrAlg |
| 55 |
} |
| 56 |
|
| 57 |
signature := s.Signature |
| 58 |
s.Signature = "" // omit |
| 59 |
defer func() { s.Signature = signature }() |
| 60 |
|
| 61 |
sbuf := make([]byte, s.Len()) |
| 62 |
if _, off, err = packRR(s, sbuf, 0, nil); err != nil { |
| 63 |
return err |
| 64 |
} |
| 65 |
sbuf = sbuf[:off] |
| 66 |
|
| 67 |
h := hash.New() |
| 68 |
|
| 69 |
binarysignature, _ := pack.Base64([]byte(signature)) |
| 70 |
switch s.Algorithm { |
| 71 |
case RSASHA1, RSASHA256, RSASHA512: |
| 72 |
h.Write(sbuf) |
| 73 |
h.Write(p) |
| 74 |
return rsa.VerifyPKCS1v15(c.Key().publicKeyRSA(), hash, h.Sum(nil), binarysignature) |
| 75 |
|
| 76 |
case ECDSAP256SHA256, ECDSAP384SHA384: |
| 77 |
h.Write(sbuf) |
| 78 |
h.Write(p) |
| 79 |
r := new(big.Int).SetBytes(binarysignature[:len(binarysignature)/2]) |
| 80 |
s := new(big.Int).SetBytes(binarysignature[len(binarysignature)/2:]) |
| 81 |
if ecdsa.Verify(c.Key().publicKeyECDSA(), h.Sum(nil), r, s) { |
| 82 |
return nil |
| 83 |
} |
| 84 |
return ErrSig |
| 85 |
|
| 86 |
case ED25519: |
| 87 |
h.Write(sbuf) |
| 88 |
h.Write(p) |
| 89 |
if ed25519.Verify(c.Key().publicKeyED25519(), append(sbuf, p...), binarysignature) { |
| 90 |
return nil |
| 91 |
} |
| 92 |
return ErrSig |
| 93 |
|
| 94 |
} |
| 95 |
return ErrKeyAlg |
| 96 |
} |