Refactor cli argument handling

Also, add the "-config" option for storing gocryptfs.conf
outside of CIPHERDIR.
This commit is contained in:
Jakob Unterwurzacher 2015-11-14 21:25:10 +01:00
parent 6736212b29
commit 58592330dc
5 changed files with 153 additions and 114 deletions

View File

@ -23,7 +23,7 @@ gocryptfs [OPTIONS] CIPHERDIR MOUNTPOINT
Change password Change password
--------------- ---------------
gocryptfs -passwd CIPHERDIR gocryptfs -passwd [OPTIONS] CIPHERDIR
DESCRIPTION DESCRIPTION
=========== ===========

View File

@ -6,6 +6,7 @@ import (
"os" "os"
) )
// checkDirEmpty - check if "dir" exists and is an empty directory
func checkDirEmpty(dir string) error { func checkDirEmpty(dir string) error {
err := checkDir(dir) err := checkDir(dir)
if err != nil { if err != nil {
@ -21,6 +22,7 @@ func checkDirEmpty(dir string) error {
return fmt.Errorf("directory %s not empty", dir) return fmt.Errorf("directory %s not empty", dir)
} }
// checkDir - check if "dir" exists and is a directory
func checkDir(dir string) error { func checkDir(dir string) error {
fi, err := os.Stat(dir) fi, err := os.Stat(dir)
if err != nil { if err != nil {

View File

@ -9,17 +9,18 @@ import (
) )
// The child sends us USR1 if the mount was successful // The child sends us USR1 if the mount was successful
func waitForUsr1() { func exitOnUsr1() {
c := make(chan os.Signal, 1) c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGUSR1) signal.Notify(c, syscall.SIGUSR1)
<-c <-c
os.Exit(0) os.Exit(0)
} }
// daemonize - execute ourselves once again, this time with the "-f" flag, and // forkChild - execute ourselves once again, this time with the "-f" flag, and
// wait for SIGUSR1. // wait for SIGUSR1 or child exit.
func daemonize() { // This is a workaround for the missing true fork function in Go.
go waitForUsr1() func forkChild() {
go exitOnUsr1()
name := os.Args[0] name := os.Args[0]
notifyArg := fmt.Sprintf("-notifypid=%d", os.Getpid()) notifyArg := fmt.Sprintf("-notifypid=%d", os.Getpid())
newArgs := []string{"-f", notifyArg} newArgs := []string{"-f", notifyArg}
@ -30,7 +31,7 @@ func daemonize() {
c.Stdin = os.Stdin c.Stdin = os.Stdin
err := c.Start() err := c.Start()
if err != nil { if err != nil {
fmt.Printf("daemonize: starting %s failed: %v\n", name, err) fmt.Printf("forkChild: starting %s failed: %v\n", name, err)
os.Exit(1) os.Exit(1)
} }
err = c.Wait() err = c.Wait()
@ -40,7 +41,7 @@ func daemonize() {
os.Exit(waitstat.ExitStatus()) os.Exit(waitstat.ExitStatus())
} }
} }
fmt.Printf("daemonize: wait returned an unknown error: %v\n", err) fmt.Printf("forkChild: wait returned an unknown error: %v\n", err)
os.Exit(1) os.Exit(1)
} }
// The child exited with 0 - let's do the same. // The child exited with 0 - let's do the same.

245
main.go
View File

@ -36,19 +36,16 @@ const (
// GitVersion will be set by the build script "build.bash" // GitVersion will be set by the build script "build.bash"
var GitVersion = "[version not set - please compile using ./build.bash]" var GitVersion = "[version not set - please compile using ./build.bash]"
func initDir(dirArg string, plaintextNames bool) { func initDir(args *argContainer) {
dir, _ := filepath.Abs(dirArg) err := checkDirEmpty(args.cipherdir)
err := checkDirEmpty(dir)
if err != nil { if err != nil {
fmt.Printf("Invalid CIPHERDIR: %v\n", err) fmt.Printf("Invalid CIPHERDIR: %v\n", err)
os.Exit(ERREXIT_INIT) os.Exit(ERREXIT_INIT)
} }
confName := filepath.Join(dir, cryptfs.ConfDefaultName)
cryptfs.Info.Printf("Choose a password for protecting your files.\n") cryptfs.Info.Printf("Choose a password for protecting your files.\n")
password := readPasswordTwice() password := readPasswordTwice()
err = cryptfs.CreateConfFile(confName, password, plaintextNames) err = cryptfs.CreateConfFile(args.config, password, args.plaintextnames)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(ERREXIT_INIT) os.Exit(ERREXIT_INIT)
@ -58,23 +55,71 @@ func initDir(dirArg string, plaintextNames bool) {
} }
func usageText() { func usageText() {
fmt.Fprintf(os.Stderr, "Usage: %s -init [OPTIONS] CIPHERDIR\n", PROGRAM_NAME) printVersion()
fmt.Fprintf(os.Stderr, " %s [OPTIONS] CIPHERDIR MOUNTPOINT\n", PROGRAM_NAME) fmt.Printf("\n")
fmt.Fprintf(os.Stderr, "\nOptions:\n") fmt.Printf("Usage: %s -init|-passwd [OPTIONS] CIPHERDIR\n", PROGRAM_NAME)
fmt.Printf(" or %s [OPTIONS] CIPHERDIR MOUNTPOINT\n", PROGRAM_NAME)
fmt.Printf("\nOptions:\n")
flagSet.PrintDefaults() flagSet.PrintDefaults()
} }
type argContainer struct { type argContainer struct {
debug, init, zerokey, fusedebug, openssl, passwd, foreground, version, debug, init, zerokey, fusedebug, openssl, passwd, foreground, version,
plaintextnames, quiet bool plaintextnames, quiet bool
masterkey, mountpoint, cipherdir, cpuprofile string masterkey, mountpoint, cipherdir, cpuprofile, config string
notifypid int notifypid int
} }
var flagSet *flag.FlagSet var flagSet *flag.FlagSet
// loadConfig - load the config file "filename", prompting the user for the password
func loadConfig(filename string) (masterkey []byte, confFile *cryptfs.ConfFile) {
// Check if the file exists at all before prompting for a password
_, err := os.Stat(filename)
if err != nil {
fmt.Print(err)
os.Exit(ERREXIT_LOADCONF)
}
fmt.Printf("Password: ")
pw := readPassword()
cryptfs.Info.Printf("Decrypting master key... ")
cryptfs.Warn.Disable() // Silence DecryptBlock() error messages on incorrect password
masterkey, confFile, err = cryptfs.LoadConfFile(filename, pw)
cryptfs.Warn.Enable()
if err != nil {
fmt.Println(err)
fmt.Println("Wrong password.")
os.Exit(ERREXIT_LOADCONF)
}
cryptfs.Info.Printf("done.\n")
return masterkey, confFile
}
// changePassword - change the password of config file "filename"
func changePassword(filename string) {
masterkey, confFile := loadConfig(filename)
fmt.Printf("Please enter your new password.\n")
newPw := readPasswordTwice()
confFile.EncryptKey(masterkey, newPw)
err := confFile.WriteFile()
if err != nil {
fmt.Println(err)
os.Exit(ERREXIT_INIT)
}
cryptfs.Info.Printf("Password changed.\n")
os.Exit(0)
}
// printVersion - print a version string like
// "gocryptfs v0.3.1-31-g6736212-dirty; on-disk format 2"
func printVersion() {
fmt.Printf("%s %s; on-disk format %d\n", PROGRAM_NAME, GitVersion, cryptfs.HEADER_CURRENT_VERSION)
}
func main() { func main() {
runtime.GOMAXPROCS(4) runtime.GOMAXPROCS(4)
var err error
// Parse command line arguments // Parse command line arguments
var args argContainer var args argContainer
@ -93,20 +138,54 @@ func main() {
flagSet.BoolVar(&args.quiet, "q", false, "Quiet - silence informational messages") flagSet.BoolVar(&args.quiet, "q", false, "Quiet - silence informational messages")
flagSet.StringVar(&args.masterkey, "masterkey", "", "Mount with explicit master key") flagSet.StringVar(&args.masterkey, "masterkey", "", "Mount with explicit master key")
flagSet.StringVar(&args.cpuprofile, "cpuprofile", "", "Write cpu profile to specified file") flagSet.StringVar(&args.cpuprofile, "cpuprofile", "", "Write cpu profile to specified file")
flagSet.StringVar(&args.config, "config", "", "Use specified config file instead of CIPHERDIR/gocryptfs.conf")
flagSet.IntVar(&args.notifypid, "notifypid", 0, "Send USR1 to the specified process after "+ flagSet.IntVar(&args.notifypid, "notifypid", 0, "Send USR1 to the specified process after "+
"successful mount - used internally for daemonization") "successful mount - used internally for daemonization")
flagSet.Parse(os.Args[1:]) flagSet.Parse(os.Args[1:])
if args.debug {
cryptfs.Debug.Enable()
cryptfs.Debug.Printf("Debug output enabled\n")
}
// By default, let the child handle everything.
// The parent *could* handle operations that do not require backgrounding by
// itself, but that would make the code paths more complicated.
if !args.foreground {
forkChild() // does not return
}
// Getting here means we *are* the child
// "-v"
if args.version { if args.version {
fmt.Printf("%s %s; on-disk format %d\n", PROGRAM_NAME, GitVersion, cryptfs.HEADER_CURRENT_VERSION) printVersion()
os.Exit(0) os.Exit(0)
} }
// Every operation below requires CIPHERDIR. Check that we have it.
if flagSet.NArg() >= 1 {
args.cipherdir, _ = filepath.Abs(flagSet.Arg(0))
err := checkDir(args.cipherdir)
if err != nil {
fmt.Printf("Invalid CIPHERDIR: %v\n", err)
os.Exit(ERREXIT_CIPHERDIR)
}
} else {
usageText()
os.Exit(ERREXIT_USAGE)
}
// "-q"
if args.quiet { if args.quiet {
cryptfs.Info.Disable() cryptfs.Info.Disable()
} }
if !args.foreground { // "-config"
daemonize() // does not return if args.config != "" {
args.config, err = filepath.Abs(args.config)
if err != nil {
fmt.Printf("Invalid \"-config\" setting: %v\n", err)
}
cryptfs.Info.Printf("Using config file at custom location %s\n", args.config)
} else {
args.config = filepath.Join(args.cipherdir, cryptfs.ConfDefaultName)
} }
// "-cpuprofile"
if args.cpuprofile != "" { if args.cpuprofile != "" {
f, err := os.Create(args.cpuprofile) f, err := os.Create(args.cpuprofile)
if err != nil { if err != nil {
@ -117,123 +196,79 @@ func main() {
pprof.StartCPUProfile(f) pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile() defer pprof.StopCPUProfile()
} }
if args.debug { // "-openssl"
cryptfs.Debug.Enable()
cryptfs.Debug.Printf("Debug output enabled\n")
}
if args.openssl == false { if args.openssl == false {
cryptfs.Info.Printf("Openssl disabled\n") cryptfs.Info.Printf("Openssl disabled\n")
} }
// Operation flags: init, passwd or mount
// "-init"
if args.init { if args.init {
if flagSet.NArg() != 1 && args.plaintextnames == false { if flagSet.NArg() > 1 {
fmt.Printf("Usage: %s --init [--plaintextnames] CIPHERDIR\n", PROGRAM_NAME) fmt.Printf("Usage: %s -init [OPTIONS] CIPHERDIR\n", PROGRAM_NAME)
os.Exit(ERREXIT_USAGE) os.Exit(ERREXIT_USAGE)
} }
initDir(flagSet.Arg(0), args.plaintextnames) // does not return initDir(&args) // does not return
} }
// "-passwd"
if args.passwd { if args.passwd {
if flagSet.NArg() != 1 { if flagSet.NArg() > 1 {
fmt.Printf("Usage: %s --passwd CIPHERDIR\n", PROGRAM_NAME) fmt.Printf("Usage: %s -passwd [OPTIONS] CIPHERDIR\n", PROGRAM_NAME)
os.Exit(ERREXIT_USAGE) os.Exit(ERREXIT_USAGE)
} }
} else { changePassword(args.config) // does not return
// Normal mount
if flagSet.NArg() < 2 {
usageText()
os.Exit(ERREXIT_USAGE)
}
args.mountpoint, _ = filepath.Abs(flagSet.Arg(1))
err := checkDirEmpty(args.mountpoint)
if err != nil {
fmt.Printf("Invalid MOUNTPOINT: %v\n", err)
os.Exit(ERREXIT_MOUNTPOINT)
}
} }
args.cipherdir, _ = filepath.Abs(flagSet.Arg(0)) // Mount
err := checkDir(args.cipherdir) // Check mountpoint
if flagSet.NArg() < 2 {
usageText()
os.Exit(ERREXIT_USAGE)
}
args.mountpoint, err = filepath.Abs(flagSet.Arg(1))
if err != nil { if err != nil {
fmt.Printf("Invalid CIPHERDIR: %v\n", err) fmt.Printf("Invalid MOUNTPOINT: %v\n", err)
os.Exit(ERREXIT_CIPHERDIR) os.Exit(ERREXIT_MOUNTPOINT)
} }
err = checkDirEmpty(args.mountpoint)
var plaintextNames bool if err != nil {
var cf *cryptfs.ConfFile fmt.Printf("Invalid MOUNTPOINT: %v\n", err)
var currentPassword string os.Exit(ERREXIT_MOUNTPOINT)
key := make([]byte, cryptfs.KEY_LEN) }
if args.zerokey { // Get master key
cryptfs.Info.Printf("Zerokey mode active: using all-zero dummy master key.\n") var masterkey []byte
plaintextNames = args.plaintextnames if args.masterkey != "" {
} else if len(args.masterkey) > 0 { // "-masterkey"
key = parseMasterKey(args.masterkey)
cryptfs.Info.Printf("Using explicit master key.\n") cryptfs.Info.Printf("Using explicit master key.\n")
} else { masterkey = parseMasterKey(args.masterkey)
// Load config file
cfname := filepath.Join(args.cipherdir, cryptfs.ConfDefaultName)
_, err = os.Stat(cfname)
if err != nil {
fmt.Printf("Error: %s not found in CIPHERDIR\n", cryptfs.ConfDefaultName)
fmt.Printf("Please run \"%s --init %s\" first\n", os.Args[0], flagSet.Arg(0))
os.Exit(ERREXIT_LOADCONF)
}
if args.passwd == true {
fmt.Printf("Old password: ")
} else {
fmt.Printf("Password: ")
}
currentPassword = readPassword()
cryptfs.Info.Printf("Decrypting master key... ")
cryptfs.Warn.Disable() // Silence DecryptBlock() error messages on incorrect password
key, cf, err = cryptfs.LoadConfFile(cfname, currentPassword)
cryptfs.Warn.Enable()
if err != nil {
fmt.Println(err)
os.Exit(ERREXIT_LOADCONF)
}
cryptfs.Info.Printf("done.\n")
}
if args.passwd == true {
fmt.Printf("Please enter the new password.\n")
newPassword := readPasswordTwice()
if newPassword == currentPassword {
fmt.Printf("New and old passwords are identical\n")
os.Exit(ERREXIT_PASSWORD)
}
cf.EncryptKey(key, newPassword)
err := cf.WriteFile()
if err != nil {
fmt.Println(err)
os.Exit(ERREXIT_INIT)
}
cryptfs.Info.Printf("Password changed.\n")
os.Exit(0)
}
if cf != nil {
plaintextNames = cf.PlaintextNames()
}
srv := pathfsFrontend(key, args.cipherdir, args.mountpoint, args.fusedebug, args.openssl, plaintextNames)
if args.zerokey == false && len(args.masterkey) == 0 {
printMasterKey(key)
} else if args.zerokey == true {
cryptfs.Info.Printf("ZEROKEY MODE PROVIDES NO SECURITY AT ALL AND SHOULD ONLY BE USED FOR TESTING.\n")
} else if len(args.masterkey) > 0 {
cryptfs.Info.Printf("THE MASTER KEY IS VISIBLE VIA \"ps -auxwww\", ONLY USE THIS MODE FOR EMERGENCIES.\n") cryptfs.Info.Printf("THE MASTER KEY IS VISIBLE VIA \"ps -auxwww\", ONLY USE THIS MODE FOR EMERGENCIES.\n")
} else if args.zerokey {
// "-zerokey"
cryptfs.Info.Printf("Using all-zero dummy master key.\n")
cryptfs.Info.Printf("ZEROKEY MODE PROVIDES NO SECURITY AT ALL AND SHOULD ONLY BE USED FOR TESTING.\n")
masterkey = make([]byte, cryptfs.KEY_LEN)
} else {
// Load master key from config file
var confFile *cryptfs.ConfFile
masterkey, confFile = loadConfig(args.config)
printMasterKey(masterkey)
args.plaintextnames = confFile.PlaintextNames()
} }
// Initialize FUSE server
srv := pathfsFrontend(masterkey, args.cipherdir, args.mountpoint, args.fusedebug, args.openssl, args.plaintextnames)
cryptfs.Info.Println("Filesystem ready.") cryptfs.Info.Println("Filesystem ready.")
// Send USR1 notification // We are ready - send USR1 signal to our parent
if args.notifypid > 0 { if args.notifypid > 0 {
sendUsr1(args.notifypid) sendUsr1(args.notifypid)
} }
// Wait for SIGING in the background and unmount ourselves if we get it // Wait for SIGINT in the background and unmount ourselves if we get it.
// This prevents a dangling "Transport endpoint is not connected" mountpoint // This prevents a dangling "Transport endpoint is not connected" mountpoint.
handleSigint(srv, args.mountpoint) handleSigint(srv, args.mountpoint)
// Jump into server loop. Returns when it gets an umount request from the kernel. // Jump into server loop. Returns when it gets an umount request from the kernel.
srv.Serve() srv.Serve()
// main returns with code 0 // main exits with code 0
} }
// pathfsFrontend - initialize FUSE server based on go-fuse's PathFS
// Calls os.Exit on errors
func pathfsFrontend(key []byte, cipherdir string, mountpoint string, func pathfsFrontend(key []byte, cipherdir string, mountpoint string,
debug bool, openssl bool, plaintextNames bool) *fuse.Server { debug bool, openssl bool, plaintextNames bool) *fuse.Server {

View File

@ -37,7 +37,8 @@ paper and store it in a drawer.
`, hChunked) `, hChunked)
} }
// Parse a hex-encoded master key that was passed on the command line // parseMasterKey - Parse a hex-encoded master key that was passed on the command line
// Calls os.Exit on failure
func parseMasterKey(masterkey string) []byte { func parseMasterKey(masterkey string) []byte {
masterkey = strings.Replace(masterkey, "-", "", -1) masterkey = strings.Replace(masterkey, "-", "", -1)
key, err := hex.DecodeString(masterkey) key, err := hex.DecodeString(masterkey)