aboutsummaryrefslogtreecommitdiff
path: root/internal/readpassword/passfile.go
blob: 73af279bb5988c9fccdcc3e7ee210424b621fe33 (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
package readpassword

import (
	"bytes"
	"os"

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

func readPassFile(passfile string) []byte {
	tlog.Info.Printf("passfile: reading from file %q", passfile)
	f, err := os.Open(passfile)
	if err != nil {
		tlog.Fatal.Printf("fatal: passfile: could not open %q: %v", passfile, err)
		os.Exit(exitcodes.ReadPassword)
	}
	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 {
		tlog.Fatal.Printf("fatal: passfile: could not read from %q: %v", passfile, err)
		os.Exit(exitcodes.ReadPassword)
	}
	buf = buf[:n]
	// Split into first line and "trailing garbage"
	lines := bytes.SplitN(buf, []byte("\n"), 2)
	if len(lines[0]) == 0 {
		tlog.Fatal.Printf("fatal: passfile: empty first line in %q", passfile)
		os.Exit(exitcodes.ReadPassword)
	}
	if len(lines[0]) > maxPasswordLen {
		tlog.Fatal.Printf("fatal: passfile: max password length (%d bytes) exceeded", maxPasswordLen)
		os.Exit(exitcodes.ReadPassword)
	}
	if len(lines) > 1 && len(lines[1]) > 0 {
		tlog.Warn.Printf("passfile: ignoring trailing garbage (%d bytes) after first line",
			len(lines[1]))
	}
	return lines[0]
}