package main /* The purpose of this command is to be run via sudo as an arbitrary user by the "help" user. It is invoked as part of the "i need to add a new public key" flow from "ssh help@tilde.town". It's based on the createkeyfile helper and heavily copy pasta'd. */ import ( "fmt" "os" "os/user" "path" ) const keyfileName = "authorized_keys2" func quit(msg string, code int) { fmt.Println(msg) os.Exit(code) } func main() { username := os.Args[1] if username == "" { quit("expected username as argument", 1) } u, err := user.Current() if err != nil { quit(err.Error(), 2) } if u.Username != username { quit("that's my purse; I don't know you", 3) } sshPath := path.Join("/home", u.Username, ".ssh") keyfilePath := path.Join(sshPath, keyfileName) f, err := os.OpenFile(keyfilePath, os.O_APPEND|os.O_WRONLY, 0600) if err != nil { quit(fmt.Sprintf("failed to open %s: %s", keyfilePath, err.Error()), 5) } defer f.Close() stdin := make([]byte, 90000) // arbitrary limit n, err := os.Stdin.Read(stdin) if err != nil { quit(err.Error(), 6) } else if n == 0 { quit("nothing passed on STDIN", 7) } stdin = stdin[0:n] n, err = f.Write(stdin) if err != nil { quit(err.Error(), 9) } else if n == 0 { quit("wrote nothing to keyfile", 10) } }