2018-12-15 17:09:38 +01:00
|
|
|
package readpassword
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2022-01-03 15:18:59 +01:00
|
|
|
"fmt"
|
2018-12-15 17:09:38 +01:00
|
|
|
"os"
|
|
|
|
|
2021-08-23 15:05:15 +02:00
|
|
|
"github.com/rfjakob/gocryptfs/v2/internal/tlog"
|
2018-12-15 17:09:38 +01:00
|
|
|
)
|
|
|
|
|
2020-05-17 19:31:04 +02:00
|
|
|
// readPassFileConcatenate reads the first line from each file name and
|
|
|
|
// concatenates the results. The result does not contain any newlines.
|
2022-01-03 15:18:59 +01:00
|
|
|
func readPassFileConcatenate(passfileSlice []string) (result []byte, err error) {
|
2020-05-17 19:31:04 +02:00
|
|
|
for _, e := range passfileSlice {
|
2022-01-03 15:18:59 +01:00
|
|
|
add, err := readPassFile(e)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
result = append(result, add...)
|
2020-05-17 19:31:04 +02:00
|
|
|
}
|
2022-01-03 15:18:59 +01:00
|
|
|
return result, nil
|
2020-05-17 19:31:04 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// readPassFile reads the first line from the passed file name.
|
2022-01-03 15:18:59 +01:00
|
|
|
func readPassFile(passfile string) ([]byte, error) {
|
2018-12-15 17:09:38 +01:00
|
|
|
tlog.Info.Printf("passfile: reading from file %q", passfile)
|
|
|
|
f, err := os.Open(passfile)
|
|
|
|
if err != nil {
|
2022-01-03 15:18:59 +01:00
|
|
|
return nil, fmt.Errorf("fatal: passfile: could not open %q: %v", passfile, err)
|
2018-12-15 17:09:38 +01:00
|
|
|
}
|
|
|
|
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 {
|
2022-01-03 15:18:59 +01:00
|
|
|
return nil, fmt.Errorf("fatal: passfile: could not read from %q: %v", passfile, err)
|
2018-12-15 17:09:38 +01:00
|
|
|
}
|
|
|
|
buf = buf[:n]
|
|
|
|
// Split into first line and "trailing garbage"
|
|
|
|
lines := bytes.SplitN(buf, []byte("\n"), 2)
|
|
|
|
if len(lines[0]) == 0 {
|
2022-01-03 15:18:59 +01:00
|
|
|
return nil, fmt.Errorf("fatal: passfile: empty first line in %q", passfile)
|
2018-12-15 17:09:38 +01:00
|
|
|
}
|
|
|
|
if len(lines[0]) > maxPasswordLen {
|
2022-01-03 15:18:59 +01:00
|
|
|
return nil, fmt.Errorf("fatal: passfile: max password length (%d bytes) exceeded", maxPasswordLen)
|
2018-12-15 17:09:38 +01:00
|
|
|
}
|
|
|
|
if len(lines) > 1 && len(lines[1]) > 0 {
|
2020-05-17 19:31:04 +02:00
|
|
|
tlog.Warn.Printf("warning: passfile: ignoring trailing garbage (%d bytes) after first line",
|
2018-12-15 17:09:38 +01:00
|
|
|
len(lines[1]))
|
|
|
|
}
|
2022-01-03 15:18:59 +01:00
|
|
|
return lines[0], nil
|
2018-12-15 17:09:38 +01:00
|
|
|
}
|