From 44686ad536940d3d4231c888840f4e922116b96b Mon Sep 17 00:00:00 2001 From: vilmibm Date: Wed, 25 Oct 2023 02:41:16 +0000 Subject: [PATCH] add new appendkeyfile helper --- cmd/appendkeyfile/main.go | 67 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 cmd/appendkeyfile/main.go diff --git a/cmd/appendkeyfile/main.go b/cmd/appendkeyfile/main.go new file mode 100644 index 0000000..b600ab9 --- /dev/null +++ b/cmd/appendkeyfile/main.go @@ -0,0 +1,67 @@ +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) + } +}