This repository has been archived by the owner on Jul 30, 2020. It is now read-only.
/
root.go
254 lines (213 loc) · 6.69 KB
/
root.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Copyright © 2019 The Merkle County Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/cavaliercoder/grab"
"github.com/google/certificate-transparency-go/ctutil"
"github.com/google/certificate-transparency-go/loglist"
"github.com/google/certificate-transparency-go/x509"
"github.com/google/certificate-transparency-go/x509util"
"go.merklecounty.com/rget/rgetct"
"go.merklecounty.com/rget/rgethash"
"go.merklecounty.com/rget/rgetwellknown"
)
var cfgFile string
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "rget [URL]",
Short: "Get a URL and verify the contents with CT Log backed transparency",
Long: `rget is similar to other popular URL fetchers with an additional layer of security.
By using the Certificate Transparency Log infrastructure that enables third-party auditing of
the web's certificate authority infrastructure rget can give you strong guarantees that the
cryptographic hash digest of the binary you are downloading appears in a public log.
`,
Args: cobra.ExactArgs(1),
Run: get,
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
cobra.OnInitialize(initConfig)
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.rget.yaml)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Search config in home directory with name ".rget" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".rget")
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}
func validSCTs(valid, invalid int, cturl string, logs []loglist.Log) string {
var names []string
for _, l := range logs {
names = append(names, l.Description)
}
return fmt.Sprintf("validated %d/%d SCTs in logs %q ", valid, (valid + invalid), strings.Join(names, ", "))
}
func levelSCTs(valid, invalid int) (string, error) {
switch {
case valid != 0 && invalid == 0:
return "OK", nil
case valid == 0:
return "Error", errors.New("no valid SCTs")
default:
return "Warning", nil
}
}
func get(cmd *cobra.Command, args []string) {
var chain []*x509.Certificate
var valid, invalid int
durl := args[0]
// Step 1: Download the SHA256SUMS that is correct for the URL
prefix, err := rgetwellknown.SumPrefix(durl)
if err != nil {
fmt.Printf("%s\n", err)
os.Exit(1)
}
sumsURL := prefix + "SHA256SUMS"
fmt.Printf("downloading sums: %v\n", sumsURL)
response, err := http.Get(sumsURL)
var sha256file []byte
if err != nil {
fmt.Printf("%s\n", err)
os.Exit(1)
} else {
var err error
defer response.Body.Close()
sha256file, err = ioutil.ReadAll(response.Body)
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
}
}
// Step 2. Generate the CT URL from the SHA256SUMS file
domain, err := rgetwellknown.Domain(durl)
if err != nil {
fmt.Printf("wellknown domain error: %v", err)
os.Exit(1)
}
sums := rgethash.FromSHA256SumFile(string(sha256file))
cturl := "https://" + sums.Domain() + "." + domain + "." + rgetwellknown.PublicServiceHost
fmt.Printf("validating transparency URL: %v\n", cturl)
hc := &http.Client{Timeout: 30 * time.Second}
ctx := context.Background()
lf := ctutil.NewLogInfo
// TODO(philips): bump to AllLogListURL and embed into this code instead of relying on Google
llData, err := x509util.ReadFileOrURL(loglist.LogListURL, hc)
if err != nil {
fmt.Printf("Failed to read log list: %v", err)
os.Exit(1)
}
ll, err := loglist.NewFromJSON(llData)
if err != nil {
fmt.Printf("Failed to parse log list: %v", err)
os.Exit(1)
}
// _ to skip TLS extension SCTs, rget doesn't use those yet
chain, _, err = rgetct.GetSiteSCTs(ctx, cturl, hc)
if err != nil {
fmt.Printf("%s: failed to get cert chain: %v\n", cturl, err)
os.Exit(1)
}
// Check x509 chain SCTs
valid, invalid, logs := rgetct.CheckX509(ctx, lf, chain, ll, hc)
lvl, err := levelSCTs(valid, invalid)
fmt.Printf("%s: x509 SCTs: %s\n", lvl, validSCTs(valid, invalid, cturl, logs))
if err != nil {
os.Exit(1)
}
// create download request
req, err := grab.NewRequest("", durl)
if err != nil {
fmt.Printf("failed to create grab request: %v\n", err)
os.Exit(1)
}
req.NoCreateDirectories = true
req.AfterCopy = func(resp *grab.Response) (err error) {
var f *os.File
f, err = os.Open(resp.Filename)
if err != nil {
return
}
defer func() {
f.Close()
}()
h := sha256.New()
_, err = io.Copy(h, f)
if err != nil {
return err
}
fileSum := h.Sum(nil)
if !sums.SumExists(fileSum) {
mmErr := fmt.Errorf("cannot find %x in %v list", fileSum, cturl)
if err := os.Remove(resp.Filename); err != nil {
// err should be os.PathError and include file path
return fmt.Errorf(
"cannot remove downloaded file with checksum mismatch: %v",
mmErr)
}
return mmErr
}
fmt.Printf("validated file sum: %x\n", fileSum)
req.SetChecksum(sha256.New(), fileSum, true)
return
}
// download and validate file
resp := grab.DefaultClient.Do(req)
if err := resp.Err(); err != nil {
fmt.Printf("Failed to grab: %v\n", err)
os.Exit(1)
}
fmt.Println("Download validated and saved to", resp.Filename)
}