2023-10-25 02:41:16 +00:00
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" .
2023-10-25 02:48:01 +00:00
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 .
2023-10-25 02:41:16 +00:00
* /
import (
"fmt"
"os"
"os/user"
"path"
)
const keyfileName = "authorized_keys2"
func quit ( msg string , code int ) {
2023-10-25 17:42:46 +00:00
// TODO print to stderr
2023-10-25 02:41:16 +00:00
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 )
}
}