aboutsummaryrefslogtreecommitdiff
path: root/internal/readpassword/passfile.go
blob: 80bfdcef360d44fff9a0df993f826abbc4ee56c0 (plain)
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
package readpassword

import (
	"bytes"
	"fmt"
	"os"

	"github.com/rfjakob/gocryptfs/v2/internal/tlog"
)

// readPassFileConcatenate reads the first line from each file name and
// concatenates the results. The result does not contain any newlines.
func readPassFileConcatenate(passfileSlice []string) (result []byte, err error) {
	for _, e := range passfileSlice {
		add, err := readPassFile(e)
		if err != nil {
			return nil, err
		}
		result = append(result, add...)
	}
	return result, nil
}

// readPassFile reads the first line from the passed file name.
func readPassFile(passfile string) ([]byte, error) {
	tlog.Info.Printf("passfile: reading from file %q", passfile)
	f, err := os.Open(passfile)
	if err != nil {
		return nil, fmt.Errorf("fatal: passfile: could not open %q: %v", passfile, err)
	}
	defer f.Close()
	// +1 for an optional trailing newline,
	// +2 so we can detect if maxPasswordLen is exceeded.
	buf := make([]byte, maxPasswordLen+2)
	n, err := f.Read(buf)
	if err != nil {
		return nil, fmt.Errorf("fatal: passfile: could not read from %q: %v", passfile, err)
	}
	buf = buf[:n]
	// Split into first line and "trailing garbage"
	lines := bytes.SplitN(buf, []byte("\n"), 2)
	if len(lines[0]) == 0 {
		return nil, fmt.Errorf("fatal: passfile: empty first line in %q", passfile)
	}
	if len(lines[0]) > maxPasswordLen {
		return nil, fmt.Errorf("fatal: passfile: max password length (%d bytes) exceeded", maxPasswordLen)
	}
	if len(lines) > 1 && len(lines[1]) > 0 {
		tlog.Warn.Printf("warning: passfile: ignoring trailing garbage after first line")
	}
	return lines[0], nil
}