60 lines
1.2 KiB
Go
60 lines
1.2 KiB
Go
|
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. They should probably share code or be a single command but I wanted to keep things simple for now.
|
||
|
|
||
|
*/
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"os"
|
||
|
"os/user"
|
||
|
"path"
|
||
|
)
|
||
|
|
||
|
const keyfileName = "authorized_keys2"
|
||
|
|
||
|
func quit(msg string, code int) {
|
||
|
// TODO print to stderr
|
||
|
fmt.Println(msg)
|
||
|
os.Exit(code)
|
||
|
}
|
||
|
|
||
|
func main() {
|
||
|
u, err := user.Current()
|
||
|
if err != nil {
|
||
|
quit(err.Error(), 2)
|
||
|
}
|
||
|
|
||
|
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)
|
||
|
}
|
||
|
}
|