File: validate.go

package info (click to toggle)
golang-github-rhysd-go-github-selfupdate 1.2.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 348 kB
  • sloc: sh: 21; makefile: 6
file content (73 lines) | stat: -rw-r--r-- 2,016 bytes parent folder | download
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
package selfupdate

import (
	"crypto/ecdsa"
	"crypto/sha256"
	"encoding/asn1"
	"fmt"
	"math/big"
)

// Validator represents an interface which enables additional validation of releases.
type Validator interface {
	// Validate validates release bytes against an additional asset bytes.
	// See SHA2Validator or ECDSAValidator for more information.
	Validate(release, asset []byte) error
	// Suffix describes the additional file ending which is used for finding the
	// additional asset.
	Suffix() string
}

// SHA2Validator specifies a SHA256 validator for additional file validation
// before updating.
type SHA2Validator struct {
}

// Validate validates the SHA256 sum of the release against the contents of an
// additional asset file.
func (v *SHA2Validator) Validate(release, asset []byte) error {
	calculatedHash := fmt.Sprintf("%x", sha256.Sum256(release))
	hash := fmt.Sprintf("%s", asset[:sha256.BlockSize])
	if calculatedHash != hash {
		return fmt.Errorf("sha2: validation failed: hash mismatch: expected=%q, got=%q", calculatedHash, hash)
	}
	return nil
}

// Suffix returns the suffix for SHA2 validation.
func (v *SHA2Validator) Suffix() string {
	return ".sha256"
}

// ECDSAValidator specifies a ECDSA validator for additional file validation
// before updating.
type ECDSAValidator struct {
	PublicKey *ecdsa.PublicKey
}

// Validate validates the ECDSA signature the release against the signature
// contained in an additional asset file.
// additional asset file.
func (v *ECDSAValidator) Validate(input, signature []byte) error {
	h := sha256.New()
	h.Write(input)

	var rs struct {
		R *big.Int
		S *big.Int
	}
	if _, err := asn1.Unmarshal(signature, &rs); err != nil {
		return fmt.Errorf("failed to unmarshal ecdsa signature: %v", err)
	}

	if !ecdsa.Verify(v.PublicKey, h.Sum([]byte{}), rs.R, rs.S) {
		return fmt.Errorf("ecdsa: signature verification failed")
	}

	return nil
}

// Suffix returns the suffix for ECDSA validation.
func (v *ECDSAValidator) Suffix() string {
	return ".sig"
}