Debian Codegraph @

cmdline/verify/verify.go

raw symbols SCIP
1 //
2 // Copyright (c) SAS Institute Inc.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 package verify
18
19 import (
20 "crypto/x509"
21 "encoding/pem"
22 "errors"
23 "fmt"
24 "os"
25
26 "github.com/spf13/cobra"
27
28 "github.com/sassoftware/relic/v7/cmdline/shared"
29 "github.com/sassoftware/relic/v7/lib/certloader"
30 "github.com/sassoftware/relic/v7/lib/magic"
31 "github.com/sassoftware/relic/v7/lib/pgptools"
32 "github.com/sassoftware/relic/v7/lib/x509tools"
33 "github.com/sassoftware/relic/v7/signers"
34 )
35
36 var VerifyCmd = &cobra.Command{
37 Use: "verify",
38 Short: "Verify a signed package or executable",
39 RunE: verifyCmd,
40 }
41
42 var (
43 argNoIntegrityCheck bool
44 argNoChain bool
45 argAlsoSystem bool
46 argShowCerts bool
47 argContent string
48 argTrustedCerts []string
49 )
50
51 func init() {
52 shared.RootCmd.AddCommand(VerifyCmd)
53 VerifyCmd.Flags().BoolVar(&argNoIntegrityCheck, "no-integrity-check", false, "Bypass the integrity check of the file contents and only inspect the signature itself")
54 VerifyCmd.Flags().BoolVar(&argNoChain, "no-trust-chain", false, "Do not test whether the signing certificate is trusted")
55 VerifyCmd.Flags().BoolVar(&argAlsoSystem, "system-store", false, "When --cert is used, append rather than replace the system trust store")
56 VerifyCmd.Flags().BoolVar(&argShowCerts, "show-certs", false, "Dump certificate chain from signature")
57 VerifyCmd.Flags().StringVar(&argContent, "content", "", "Specify file containing contents for detached signatures")
58 VerifyCmd.Flags().StringArrayVar(&argTrustedCerts, "cert", nil, "Add a trusted root certificate (PEM, DER, PKCS#7, or PGP)")
59 }
60
61 func verifyCmd(cmd *cobra.Command, args []string) error {
62 if len(args) == 0 {
63 return errors.New("Expected 1 or more files")
64 }
65 opts, err := loadCerts()
66 if err != nil {
67 return err
68 }
69 rc := 0
70 for _, path := range args {
71 if err := verifyOne(path, opts); err != nil {
72 fmt.Printf("%s ERROR: %s\n", path, err)
73 rc = 1
74 }
75 }
76 if rc != 0 {
77 fmt.Fprintln(os.Stderr, "ERROR: 1 or more files did not validate")
78 }
79 os.Exit(rc)
80 return nil
81 }
82
83 func verifyOne(path string, opts signers.VerifyOpts) error {
84 f, err := shared.OpenFile(path)
85 if err != nil {
86 return err
87 }
88 defer f.Close()
89 fileType, compression := magic.DetectCompressed(f)
90 opts.FileName = path
91 opts.Compression = compression
92 if _, err := f.Seek(0, 0); err != nil {
93 return err
94 }
95 mod := signers.ByMagic(fileType)
96 if mod == nil {
97 mod = signers.ByFileName(path)
98 }
99 if mod == nil {
100 return errors.New("unknown filetype")
101 }
102 var sigs []*signers.Signature
103 if mod.VerifyStream != nil {
104 r, err2 := magic.Decompress(f, opts.Compression)
105 if err2 != nil {
106 return err
107 }
108 sigs, err = mod.VerifyStream(r, opts)
109 } else {
110 if opts.Compression != magic.CompressedNone {
111 return errors.New("cannot verify compressed file")
112 }
113 sigs, err = mod.Verify(f, opts)
114 }
115 if err != nil {
116 if _, ok := err.(pgptools.ErrNoKey); ok {
117 return fmt.Errorf("%w; use --cert to specify known keys", err)
118 }
119 return err
120 }
121 sawCerts := make(map[string]bool)
122 for _, sig := range sigs {
123 var si, pkg, ts string
124 if sig.SigInfo != "" {
125 si = " " + sig.SigInfo + ":"
126 }
127 if sig.Package != "" {
128 pkg = sig.Package + " "
129 }
130 if sig.X509Signature != nil && argShowCerts {
131 showCert(sig.X509Signature.Certificate.Raw, sawCerts)
132 for _, cert := range sig.X509Signature.Intermediates {
133 showCert(cert.Raw, sawCerts)
134 }
135 }
136 if sig.X509Signature != nil && !opts.NoChain {
137 if err := sig.X509Signature.VerifyChain(opts.TrustedPool, nil, x509.ExtKeyUsageAny); err != nil {
138 if e := new(x509.UnknownAuthorityError); errors.As(err, e) {
139 fmt.Printf("While validating certificate:\n Subject: %s\n Issuer: %s\n Serial: %X\n", x509tools.FormatSubject(e.Cert), x509tools.FormatIssuer(e.Cert), e.Cert.SerialNumber)
140 }
141 return err
142 }
143 }
144 if sig.X509Signature != nil && sig.X509Signature.CounterSignature != nil {
145 fmt.Printf("%s: OK -%s %s%s\n", path, si, pkg, sig.SignerName())
146 fmt.Printf("%s(timestamp): OK - `%s` [%s]\n", path, x509tools.FormatSubject(sig.X509Signature.CounterSignature.Certificate), sig.X509Signature.CounterSignature.SigningTime)
147 } else {
148 if !sig.CreationTime.IsZero() {
149 ts = fmt.Sprintf(" [%s]", sig.CreationTime)
150 }
151 fmt.Printf("%s: OK -%s %s%s%s\n", path, si, pkg, sig.SignerName(), ts)
152 }
153 }
154 return nil
155 }
156
157 func loadCerts() (signers.VerifyOpts, error) {
158 opts := signers.VerifyOpts{
159 NoChain: argNoChain,
160 NoDigests: argNoIntegrityCheck,
161 Content: argContent,
162 }
163 trusted, err := certloader.LoadAnyCerts(argTrustedCerts)
164 if err != nil {
165 return opts, err
166 }
167 opts.TrustedX509 = trusted.X509Certs
168 opts.TrustedPgp = trusted.PGPCerts
169 if len(opts.TrustedX509) > 0 {
170 if argAlsoSystem {
171 var err error
172 opts.TrustedPool, err = x509.SystemCertPool()
173 if err != nil {
174 return opts, err
175 }
176 } else {
177 opts.TrustedPool = x509.NewCertPool()
178 }
179 for _, cert := range opts.TrustedX509 {
180 opts.TrustedPool.AddCert(cert)
181 }
182 }
183 return opts, nil
184 }
185
186 func showCert(blob []byte, seen map[string]bool) {
187 if seen[string(blob)] {
188 return
189 }
190 seen[string(blob)] = true
191 _ = pem.Encode(os.Stdout, &pem.Block{
192 Type: "CERTIFICATE",
193 Bytes: blob,
194 })
195 }