File: verifier.go

package info (click to toggle)
golang-github-inconshreveable-go-update 0.0~git20160112.0.8152e7e+ds-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 112 kB
  • sloc: makefile: 7
file content (74 lines) | stat: -rw-r--r-- 2,127 bytes parent folder | download | duplicates (2)
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
package update

import (
	"crypto"
	"crypto/dsa"
	"crypto/ecdsa"
	"crypto/rsa"
	"encoding/asn1"
	"errors"
	"math/big"
)

// Verifier defines an interface for verfiying an update's signature with a public key.
type Verifier interface {
	VerifySignature(checksum, signature []byte, h crypto.Hash, publicKey crypto.PublicKey) error
}

type verifyFn func([]byte, []byte, crypto.Hash, crypto.PublicKey) error

func (fn verifyFn) VerifySignature(checksum []byte, signature []byte, hash crypto.Hash, publicKey crypto.PublicKey) error {
	return fn(checksum, signature, hash, publicKey)
}

// NewRSAVerifier returns a Verifier that uses the RSA algorithm to verify updates.
func NewRSAVerifier() Verifier {
	return verifyFn(func(checksum, signature []byte, hash crypto.Hash, publicKey crypto.PublicKey) error {
		key, ok := publicKey.(*rsa.PublicKey)
		if !ok {
			return errors.New("not a valid RSA public key")
		}
		return rsa.VerifyPKCS1v15(key, hash, checksum, signature)
	})
}

type rsDER struct {
	R *big.Int
	S *big.Int
}

// NewECDSAVerifier returns a Verifier that uses the ECDSA algorithm to verify updates.
func NewECDSAVerifier() Verifier {
	return verifyFn(func(checksum, signature []byte, hash crypto.Hash, publicKey crypto.PublicKey) error {
		key, ok := publicKey.(*ecdsa.PublicKey)
		if !ok {
			return errors.New("not a valid ECDSA public key")
		}
		var rs rsDER
		if _, err := asn1.Unmarshal(signature, &rs); err != nil {
			return err
		}
		if !ecdsa.Verify(key, checksum, rs.R, rs.S) {
			return errors.New("failed to verify ecsda signature")
		}
		return nil
	})
}

// NewDSAVerifier returns a Verifier that uses the DSA algorithm to verify updates.
func NewDSAVerifier() Verifier {
	return verifyFn(func(checksum, signature []byte, hash crypto.Hash, publicKey crypto.PublicKey) error {
		key, ok := publicKey.(*dsa.PublicKey)
		if !ok {
			return errors.New("not a valid DSA public key")
		}
		var rs rsDER
		if _, err := asn1.Unmarshal(signature, &rs); err != nil {
			return err
		}
		if !dsa.Verify(key, checksum, rs.R, rs.S) {
			return errors.New("failed to verify ecsda signature")
		}
		return nil
	})
}