/
checksum_downloader.go
214 lines (172 loc) · 5.16 KB
/
checksum_downloader.go
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package releasesjson
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"log"
"net/url"
"strings"
"github.com/hashicorp/hc-install/internal/httpclient"
"golang.org/x/crypto/openpgp"
)
type ChecksumDownloader struct {
ProductVersion *ProductVersion
Logger *log.Logger
ArmoredPublicKey string
BaseURL string
}
type ChecksumFileMap map[string]HashSum
type HashSum []byte
func (hs HashSum) Size() int {
return len(hs)
}
func (hs HashSum) String() string {
return hex.EncodeToString(hs)
}
func HashSumFromHexDigest(hexDigest string) (HashSum, error) {
sumBytes, err := hex.DecodeString(hexDigest)
if err != nil {
return nil, err
}
return HashSum(sumBytes), nil
}
func (cd *ChecksumDownloader) DownloadAndVerifyChecksums() (ChecksumFileMap, error) {
sigFilename, err := cd.findSigFilename(cd.ProductVersion)
if err != nil {
return nil, err
}
client := httpclient.NewHTTPClient()
sigURL := fmt.Sprintf("%s/%s/%s/%s", cd.BaseURL,
url.PathEscape(cd.ProductVersion.Name),
url.PathEscape(cd.ProductVersion.RawVersion),
url.PathEscape(sigFilename))
cd.Logger.Printf("downloading signature from %s", sigURL)
sigResp, err := client.Get(sigURL)
if err != nil {
return nil, err
}
if sigResp.StatusCode != 200 {
return nil, fmt.Errorf("failed to download signature from %q: %s", sigURL, sigResp.Status)
}
defer sigResp.Body.Close()
shasumsURL := fmt.Sprintf("%s/%s/%s/%s", cd.BaseURL,
url.PathEscape(cd.ProductVersion.Name),
url.PathEscape(cd.ProductVersion.RawVersion),
url.PathEscape(cd.ProductVersion.SHASUMS))
cd.Logger.Printf("downloading checksums from %s", shasumsURL)
sumsResp, err := client.Get(shasumsURL)
if err != nil {
return nil, err
}
if sumsResp.StatusCode != 200 {
return nil, fmt.Errorf("failed to download checksums from %q: %s", shasumsURL, sumsResp.Status)
}
defer sumsResp.Body.Close()
var shaSums strings.Builder
sumsReader := io.TeeReader(sumsResp.Body, &shaSums)
err = cd.verifySumsSignature(sumsReader, sigResp.Body)
if err != nil {
return nil, err
}
return fileMapFromChecksums(shaSums)
}
func fileMapFromChecksums(checksums strings.Builder) (ChecksumFileMap, error) {
csMap := make(ChecksumFileMap, 0)
lines := strings.Split(checksums.String(), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
parts := strings.Fields(line)
if len(parts) != 2 {
return nil, fmt.Errorf("unexpected checksum line format: %q", line)
}
h, err := HashSumFromHexDigest(parts[0])
if err != nil {
return nil, err
}
if h.Size() != sha256.Size {
return nil, fmt.Errorf("unexpected sha256 format (len: %d, expected: %d)",
h.Size(), sha256.Size)
}
csMap[parts[1]] = h
}
return csMap, nil
}
func compareChecksum(logger *log.Logger, r io.Reader, verifiedHashSum HashSum, filename string, expectedSize int64) error {
h := sha256.New()
// This may take a while depending on network connection as the io.Reader
// is expected to be http.Response.Body which streams the bytes
// on demand over the network.
logger.Printf("copying %q (%d bytes) to calculate checksum", filename, expectedSize)
bytesCopied, err := io.Copy(h, r)
if err != nil {
return err
}
logger.Printf("copied %d bytes of %q", bytesCopied, filename)
if expectedSize != 0 && bytesCopied != int64(expectedSize) {
return fmt.Errorf("unexpected size (downloaded: %d, expected: %d)",
bytesCopied, expectedSize)
}
calculatedSum := h.Sum(nil)
if !bytes.Equal(calculatedSum, verifiedHashSum) {
return fmt.Errorf("checksum mismatch (expected %q, calculated %q)",
verifiedHashSum,
hex.EncodeToString(calculatedSum))
}
logger.Printf("checksum matches: %q", hex.EncodeToString(calculatedSum))
return nil
}
func (cd *ChecksumDownloader) verifySumsSignature(checksums, signature io.Reader) error {
el, err := cd.keyEntityList()
if err != nil {
return err
}
_, err = openpgp.CheckDetachedSignature(el, checksums, signature)
if err != nil {
return fmt.Errorf("unable to verify checksums signature: %w", err)
}
cd.Logger.Printf("checksum signature is valid")
return nil
}
func (cd *ChecksumDownloader) findSigFilename(pv *ProductVersion) (string, error) {
sigFiles := pv.SHASUMSSigs
if len(sigFiles) == 0 {
sigFiles = []string{pv.SHASUMSSig}
}
keyIds, err := cd.pubKeyIds()
if err != nil {
return "", err
}
for _, filename := range sigFiles {
for _, keyID := range keyIds {
if strings.HasSuffix(filename, fmt.Sprintf("_SHA256SUMS.%s.sig", keyID)) {
return filename, nil
}
}
if strings.HasSuffix(filename, "_SHA256SUMS.sig") {
return filename, nil
}
}
return "", fmt.Errorf("no suitable sig file found")
}
func (cd *ChecksumDownloader) pubKeyIds() ([]string, error) {
entityList, err := cd.keyEntityList()
if err != nil {
return nil, err
}
fingerprints := make([]string, 0)
for _, entity := range entityList {
fingerprints = append(fingerprints, entity.PrimaryKey.KeyIdShortString())
}
return fingerprints, nil
}
func (cd *ChecksumDownloader) keyEntityList() (openpgp.EntityList, error) {
if cd.ArmoredPublicKey == "" {
return nil, fmt.Errorf("no public key provided")
}
return openpgp.ReadArmoredKeyRing(strings.NewReader(cd.ArmoredPublicKey))
}