This repository has been archived by the owner on Mar 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
240 lines (216 loc) · 6.34 KB
/
main.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
package main
import (
"context"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"log"
neturl "net/url"
"os"
"os/signal"
"strings"
fapi "github.com/sigstore/fulcio/pkg/api"
rekor "github.com/sigstore/rekor/pkg/generated/client"
rentries "github.com/sigstore/rekor/pkg/generated/client/entries"
rindex "github.com/sigstore/rekor/pkg/generated/client/index"
rmodels "github.com/sigstore/rekor/pkg/generated/models"
"github.com/spf13/cobra"
"golang.org/x/net/idna"
)
func main() {
var flags rootFlags
root := &cobra.Command{
Use: "sget URL",
Args: cobra.ExactArgs(1),
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
url := args[0]
u, err := neturl.Parse(url)
if err != nil {
return fmt.Errorf("parsing URL: %w", err)
}
if u.Scheme != "https" {
log.Println("URL is not HTTPS, assuming it's an OCI image reference by digest")
return fetchImage(url)
}
if pu, err := idna.Punycode.ToASCII(u.Hostname()); err != nil {
return fmt.Errorf("failed to parse URL: %w", err)
} else if strings.HasPrefix(pu, "xn--") {
return fmt.Errorf("refusing to fetch Punycode URL %q", pu)
}
// Validate digest if specified.
tmp, err := fetch(ctx, url, false)
if err != nil {
return fmt.Errorf("error getting digest for %q: %w", url, err)
}
defer os.Remove(tmp.f.Name())
gotDigest := tmp.digest
if flags.wantDigest != "" && flags.wantDigest != gotDigest {
return fmt.Errorf("digest mismatch; got %q, want %q", gotDigest, flags.wantDigest)
}
// Get Fulcio root cert.
fulcioServer, err := neturl.Parse(flags.fulcioURL)
if err != nil {
return fmt.Errorf("creating Fulcio client: %w", err)
}
fclient := fapi.NewClient(fulcioServer, fapi.WithTimeout(flags.fulcioTimeout))
fresp, err := fclient.RootCert()
if err != nil {
return fmt.Errorf("getting signing cert: %w", err)
}
fulcioRoot := x509.NewCertPool()
if !fulcioRoot.AppendCertsFromPEM(fresp.ChainPEM) {
return fmt.Errorf("failed appending Fulcio root cert")
}
// Find entries for url + digest
rclient := rekor.NewHTTPClient(nil)
iparams := rindex.NewSearchIndexParams()
iparams.SetTimeout(flags.rekorTimeout)
iparams.SetQuery(&rmodels.SearchIndex{Hash: "sha256:" + tmp.digest})
iresp, err := rclient.Index.SearchIndex(iparams)
if err != nil {
return fmt.Errorf("querying Rekor entries: %w", err)
}
if len(iresp.Payload) == 0 {
return fmt.Errorf("found no Rekor entries for URL: %s", url)
}
identities := set{}
for _, e := range iresp.Payload {
gparams := rentries.NewGetLogEntryByUUIDParams()
gparams.SetTimeout(flags.rekorTimeout)
gparams.SetEntryUUID(e)
gresp, err := rclient.Entries.GetLogEntryByUUID(gparams)
if err != nil {
return fmt.Errorf("getting Rekor entry %q: %w", e, err)
}
le := gresp.Payload[e]
leb, err := base64.StdEncoding.DecodeString(le.Body.(string))
if err != nil {
return fmt.Errorf("decoding Rekor LogEntry body: %w", err)
}
var ent struct {
Spec struct {
PublicKey []byte
}
}
if err := json.Unmarshal(leb, &ent); err != nil {
return fmt.Errorf("unmarshaling Rekor LogEntry body: %w", err)
}
// TODO: Check that the URL matches, not just the digest.
if len(ent.Spec.PublicKey) == 0 {
continue
}
block, _ := pem.Decode(ent.Spec.PublicKey)
if block == nil {
return fmt.Errorf("parsing certificate PEM; block is nil")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return fmt.Errorf("parsing certificat: %w", err)
}
// Verify cert is from Fulcio.
if _, err := cert.Verify(x509.VerifyOptions{
// THIS IS IMPORTANT: WE DO NOT CHECK TIMES HERE
// THE CERTIFICATE IS TREATED AS TRUSTED FOREVER
// WE CHECK THAT THE SIGNATURES WERE CREATED DURING THIS WINDOW
CurrentTime: cert.NotBefore,
Roots: fulcioRoot,
KeyUsages: []x509.ExtKeyUsage{
x509.ExtKeyUsageCodeSigning,
},
}); err != nil {
return fmt.Errorf("checking cert against Fulcio root: %w", err)
}
if len(cert.EmailAddresses) != 1 {
log.Printf("saw unexpected number of identities for %q: %s", e, cert.EmailAddresses)
}
for _, email := range cert.EmailAddresses {
identities.add(email)
}
}
// Collect trusted identities.
cfg, err := loadConfig()
if err != nil {
return fmt.Errorf("loading config file: %w", err)
}
trust := set{}
for _, i := range cfg.Identities {
trust.add(i)
}
if h, ok := cfg.Hosts[u.Host]; ok {
for _, i := range h.Identities {
trust.add(i)
}
}
log.Printf("Found %d identities who have signed for %s", len(identities), url)
log.Println("Signing identities:", identities) // TODO: remove
match := trust.intersect(identities)
if len(match) == 0 {
return fmt.Errorf("found no trusted identities for %s", url)
}
log.Println("Found trusted identities:", match)
var outw io.WriteCloser
switch flags.out {
case "-":
outw = os.Stdout
default:
outw, err = os.Create(flags.out)
if err != nil {
return fmt.Errorf("creating %q: %w", flags.out, err)
}
}
defer outw.Close()
// Write the contents of the temp file to stdout.
_, err = io.Copy(outw, tmp.out())
return err
},
}
flags.addFlags(root)
addSign(root)
addTrust(root)
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
if err := root.ExecuteContext(ctx); err != nil {
log.Fatal(err)
}
}
type set map[string]struct{}
func (s set) add(n string) { s[n] = struct{}{} }
func (s set) intersect(o set) set {
out := set{}
for k := range s {
if _, ok := o[k]; ok {
out[k] = struct{}{}
}
}
return out
}
func (s set) String() string {
var sb strings.Builder
first := true
for k := range s {
if !first {
sb.WriteRune(' ')
}
sb.WriteString(k)
first = false
}
return sb.String()
}
type rootFlags struct {
rekorFlags
fulcioFlags
wantDigest string
out string
}
func (f *rootFlags) addFlags(cmd *cobra.Command) {
f.rekorFlags.addFlags(cmd)
f.fulcioFlags.addFlags(cmd)
cmd.Flags().StringVar(&f.wantDigest, "digest", "", "If set, URL must have the given digest")
cmd.Flags().StringVarP(&f.out, "out", "o", "-", `File path to write to (for stdout pass "-")`)
}