Debian Codegraph @

command/crypto/hash/hash.go

raw symbols SCIP
1 package hash
2
3 import (
4 "crypto/md5"
5 "crypto/sha1"
6 "crypto/sha256"
7 "crypto/sha512"
8 "crypto/subtle"
9 "encoding/binary"
10 "encoding/hex"
11 "fmt"
12 "hash"
13 "io"
14 "io/ioutil"
15 "os"
16 "path"
17 "strings"
18
19 "github.com/pkg/errors"
20 "github.com/smallstep/cli/errs"
21 "github.com/urfave/cli"
22 )
23
24 type hashConstructor func() hash.Hash
25
26 // Command returns the jwk subcommand.
27 func Command() cli.Command {
28 return cli.Command{
29 Name: "hash",
30 Usage: "generate and check hashes of files and directories",
31 UsageText: "step crypto hash <subcommand> [arguments] [global-flags] [subcommand-flags]",
32 Description: `**step crypto hash** command group provides facilities for generating and
33 checking hashes of files and directories.
34
35 ## EXAMPLES
36
37 SHA-256 digest and compare of a file:
38 '''
39 $ step crypto hash digest foo.crt
40 1d14bfeab8532f0fca6220f6a870d069496798e92520c4437e13b9921a3cb7f3 foo.crt
41
42 $ step crypto hash compare 1d14bfeab8532f0fca6220f6a870d069496798e92520c4437e13b9921a3cb7f3 foo.crt
43 ok
44 '''
45
46 SHA-1 digest and compare of a directory:
47 '''
48 $ step crypto hash digest --alg sha1 config/
49 d419284e29382983683c294f9593183f7e00961b config/
50
51 $ step crypto hash compare --alg sha1 d419284e29382983683c294f9593183f7e00961b config
52 ok
53 '''
54
55 MD5 of a file:
56 '''
57 $ step crypto hash digest --alg md5 --insecure foo.crt
58 a2c5dae8eae7d116019f0478e8b0a35a foo.crt
59 '''
60
61 SHA-512/256 of a list of files:
62 '''
63 $ find . -type f | xargs step crypto hash digest --alg sha512-256
64 '''
65
66 Compare a previously created checksum file:
67 '''
68 $ find path -type f | xargs step crypto hash digest --alg sha512-256 \> checksums.txt
69
70 $ cat checksums.txt | xargs -n 2 step crypto hash compare --alg sha512-256
71 '''`,
72 Subcommands: cli.Commands{
73 digestCommand(),
74 compareCommand(),
75 },
76 }
77 }
78
79 func digestCommand() cli.Command {
80 return cli.Command{
81 Name: "digest",
82 Action: cli.ActionFunc(digestAction),
83 Usage: "generate a hash digest of a file or directory",
84 UsageText: `**step crypto hash digest** <file-or-directory>...
85 [**--alg**=<algorithm>]`,
86 Description: `**step crypto hash digest** generates a hash digest for a given file or
87 directory. For a file, the output is the same as tools like 'shasum'. For
88 directories, the tool computes a hash tree and outputs a single hash digest.
89
90 For examples, see **step help crypto hash**.
91
92 ## POSITIONAL ARGUMENTS
93
94 <file-or-directory>
95 : The path to a file or directory to hash.`,
96 Flags: []cli.Flag{
97 cli.StringFlag{
98 Name: "alg",
99 Value: "sha256",
100 Usage: `The hash algorithm to use.
101
102 : <algorithm> must be one of:
103
104 **sha1** (or sha)
105 : SHA-1 produces a 160-bit hash value
106
107 **sha224**
108 : SHA-224 produces a 224-bit hash value
109
110 **sha256** (default)
111 : SHA-256 produces a 256-bit hash value
112
113 **sha384**
114 : SHA-384 produces a 384-bit hash value
115
116 **sha512**
117 : SHA-512 produces a 512-bit hash value
118
119 **sha512-224**
120 : SHA-512/224 uses SHA-512 and truncates the output to 224 bits
121
122 **sha512-256**
123 : SHA-512/256 uses SHA-512 and truncates the output to 256 bits
124
125 **md5** (requires --insecure)
126 : MD5 produces a 128-bit hash value
127 `,
128 },
129 cli.BoolFlag{
130 Name: "insecure",
131 Hidden: true,
132 },
133 },
134 }
135 }
136
137 func compareCommand() cli.Command {
138 return cli.Command{
139 Name: "compare",
140 Action: cli.ActionFunc(compareAction),
141 Usage: "verify the hash digest for a file or directory matches an expected value",
142 UsageText: `**step crypto hash compare** <hash> <file-or-directory>
143 [--alg ALGORITHM]`,
144 Description: `**step crypto hash compare** verifies that the expected hash value matches the
145 computed hash value for a file or directory.
146
147 For examples, see **step help crypto hash**.
148
149 ## POSITIONAL ARGUMENTS
150
151 <hash>
152 : The expected hash digest
153
154 <file-or-directory>
155 : The path to a file or directory to hash.`,
156 Flags: []cli.Flag{
157 cli.StringFlag{
158 Name: "alg",
159 Value: "sha256",
160 Usage: `The hash algorithm to use.
161
162 : <algorithm> must be one of:
163
164 **sha1** (or sha)
165 : SHA-1 produces a 160-bit hash value
166
167 **sha224**
168 : SHA-224 produces a 224-bit hash value
169
170 **sha256** (default)
171 : SHA-256 produces a 256-bit hash value
172
173 **sha384**
174 : SHA-384 produces a 384-bit hash value
175
176 **sha512**
177 : SHA-512 produces a 512-bit hash value
178
179 **sha512-224**
180 : SHA-512/224 produces a 224-bit hash value
181
182 **sha512-256**
183 : SHA-512/256 produces a 256-bit hash value
184
185 **md5** (requires --insecure)
186 : MD5 produces a 128-bit hash value
187 `,
188 },
189 cli.BoolFlag{
190 Name: "insecure",
191 Hidden: true,
192 },
193 },
194 }
195 }
196
197 func digestAction(ctx *cli.Context) error {
198 if ctx.NArg() == 0 {
199 return errs.TooFewArguments(ctx)
200 }
201
202 hc, err := getHash(ctx, ctx.String("alg"), ctx.Bool("insecure"))
203 if err != nil {
204 return err
205 }
206
207 for _, filename := range ctx.Args() {
208 var st os.FileInfo
209 st, err = os.Stat(filename)
210 if err != nil {
211 return errs.FileError(err, filename)
212 }
213
214 var sum []byte
215 if st.IsDir() {
216 sum, err = hashDir(hc, filename)
217 } else {
218 sum, err = hashFile(hc(), filename)
219 }
220 if err != nil {
221 return err
222 }
223
224 fmt.Printf("%x %s\n", sum, filename)
225 }
226
227 return err
228 }
229
230 func compareAction(ctx *cli.Context) error {
231 if err := errs.NumberOfArguments(ctx, 2); err != nil {
232 return err
233 }
234
235 hc, err := getHash(ctx, ctx.String("alg"), ctx.Bool("insecure"))
236 if err != nil {
237 return err
238 }
239
240 hashStr := ctx.Args().Get(0)
241 hashBytes, err := hex.DecodeString(hashStr)
242 if err != nil {
243 return errs.Wrap(err, "error decoding %s", hashStr)
244 }
245
246 filename := ctx.Args().Get(1)
247 st, err := os.Stat(filename)
248 if err != nil {
249 return errs.FileError(err, filename)
250 }
251
252 var sum []byte
253 if st.IsDir() {
254 sum, err = hashDir(hc, filename)
255 } else {
256 sum, err = hashFile(hc(), filename)
257 }
258 if err != nil {
259 return err
260 }
261
262 // TODO: should add the filename?
263 // fmt.Printf("%s: ok\n", filename)
264 if subtle.ConstantTimeCompare(sum, hashBytes) == 1 {
265 fmt.Println("ok")
266 return nil
267 }
268
269 return errors.New("fail")
270 }
271
272 // getHash returns a new hash constructor for the given algorithm. MD5
273 // algorithm can only be used if the insecure flag is passed.
274 func getHash(ctx *cli.Context, alg string, insecure bool) (hashConstructor, error) {
275 switch strings.ToLower(alg) {
276 case "sha", "sha1":
277 return func() hash.Hash { return sha1.New() }, nil
278 case "sha224":
279 return func() hash.Hash { return sha256.New224() }, nil
280 case "sha256":
281 return func() hash.Hash { return sha256.New() }, nil
282 case "sha384":
283 return func() hash.Hash { return sha512.New384() }, nil
284 case "sha512":
285 return func() hash.Hash { return sha512.New() }, nil
286 case "sha512-224":
287 return func() hash.Hash { return sha512.New512_224() }, nil
288 case "sha512-256":
289 return func() hash.Hash { return sha512.New512_256() }, nil
290 case "md5":
291 if insecure {
292 return func() hash.Hash { return md5.New() }, nil
293 }
294 return nil, errs.FlagValueInsecure(ctx, "alg", alg)
295 default:
296 return nil, errs.InvalidFlagValue(ctx, "alg", alg, "")
297 }
298 }
299
300 // hashFile returns the hash of the given file using the given hash function.
301 func hashFile(h hash.Hash, filename string) ([]byte, error) {
302 f, err := os.Open(filename)
303 if err != nil {
304 return nil, errs.FileError(err, filename)
305 }
306
307 if _, err := io.Copy(h, f); err != nil {
308 return nil, errs.FileError(err, filename)
309 }
310
311 return h.Sum(nil), nil
312 }
313
314 // hashDir creates a hash of a directory adding the following data to the
315 // hash:
316 // 1. Add directory mode bits to the hash
317 // 2. For each file/directory in directory:
318 // 2.1 If file: add file mode bits and sum
319 // 2.2 If directory: do hashDir and add sum
320 // 3. return sum
321 func hashDir(hc hashConstructor, dirname string) ([]byte, error) {
322 // ReadDir returns the entries sorted by filename
323 files, err := ioutil.ReadDir(dirname)
324 if err != nil {
325 return nil, errs.FileError(err, dirname)
326 }
327 st, err := os.Stat(dirname)
328 if err != nil {
329 return nil, errs.FileError(err, dirname)
330 }
331
332 var sum []byte
333 mode := make([]byte, 4)
334
335 // calculate sum of contents and mode
336 h := hc()
337 binary.LittleEndian.PutUint32(mode, uint32(st.Mode()))
338 h.Write(mode)
339 for _, fi := range files {
340 name := path.Join(dirname, fi.Name())
341 switch {
342 case fi.IsDir():
343 sum, err = hashDir(hc, name)
344 case fi.Mode()&os.ModeSymlink != 0:
345 binary.LittleEndian.PutUint32(mode, uint32(fi.Mode()))
346 h.Write(mode)
347 sum, err = hashSymlink(hc, name)
348 default:
349 binary.LittleEndian.PutUint32(mode, uint32(fi.Mode()))
350 h.Write(mode)
351 sum, err = hashFile(hc(), name)
352 }
353 if err != nil {
354 return nil, err
355 }
356 h.Write(sum)
357 }
358
359 return h.Sum(nil), nil
360 }
361
362 func hashSymlink(hc hashConstructor, symname string) ([]byte, error) {
363 fullname, err := os.Readlink(symname)
364 if err != nil {
365 return nil, errs.FileError(err, symname)
366 }
367 if !path.IsAbs(fullname) {
368 fullname = path.Join(path.Dir(symname), fullname)
369 }
370
371 // Fails if the link points to a file that does not exist.
372 // TODO: Should we ignore it?
373 st, err := os.Stat(fullname)
374 if err != nil {
375 return nil, errs.FileError(err, fullname)
376 }
377 switch {
378 case st.Mode()&os.ModeSymlink != 0:
379 return hashSymlink(hc, fullname)
380 case st.IsDir():
381 return hashDir(hc, fullname)
382 default:
383 return hashFile(hc(), fullname)
384 }
385 }