Search code examples
linuxsecuritygomount

Programatically mount network location securely in Linux with Go


In Linux I can mount a network location programatically with Go like this:

func main() {
  var user, pass string
  fmt.Println("username:")
  fmt.Scanln(&user) // ignore errors for brevity
  fmt.Println("password:")
  fmt.Scanln(&pass)

  cmd := exec.Command("mount", "-t", "cifs", "-o", "username="+user+",password="+pass, "//server/dir", "media/dir")
  cmd.Run()
}

The problems:

  1. I can't run this without elevating privileges with sudo
  2. Username and password will be provided by the user. This seems very unsafe. Can anyone confirm on the safety or danger of this approach?

Here's a similar approach with variables:

cmd := exec.Command("mount", "-t", "cifs", "-o", "username=$USER,password=$PASS", "//server/dir", "media/dir")
cmd.Env = []string{"USER="+user, "PASS="+pass}
cmd.Run()

That does not work. It seems that exec.Command() function escapes the dollar sign, so the values in the env variables aren't replaced there. So this seems to indicate some type of safety or escaping going on here.

Editing the etc/fstab file would allow me to run mount without sudo but then I'd need sudo to edit the fstab file, so back to square one.


Solution

  • We can use gvfs to mount shares in userspace, which means we don't need to elevate privileges with sudo. The gio command can be used for this.

    The code snippet below excludes error handling for brevity:

    cmd := exec.Command("gio", "mount", "smb://server/share")
    inPipe, _ := cmd.StdinPipe()
    cmd.Start()
    
    // Get credentials whichever way you find best, including scanning the Stdin.
    // Concatenate them together with line breaks in between and a line break at the end.
    auth := "Username\nDomain\nPassword\n"
    inPipe.Write([]byte(auth))
    
    // Wait for the command to finish.
    cmd.Wait()
    

    Scanning the Stdin seems to be an acceptable way to capture credentials, since that's how the gio command works.