@@ -18,58 +18,35 @@ package system
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os/exec"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Add the provide SSH public key to the core user's list of
|
||||
// authorized keys
|
||||
func AuthorizeSSHKeys(user string, keysName string, keys []string) error {
|
||||
for i, key := range keys {
|
||||
keys[i] = strings.TrimSpace(key)
|
||||
for name, key := range keys {
|
||||
keys[name] = strings.TrimSpace(key)
|
||||
}
|
||||
|
||||
// join all keys with newlines, ensuring the resulting string
|
||||
// also ends with a newline
|
||||
joined := fmt.Sprintf("%s\n", strings.Join(keys, "\n"))
|
||||
|
||||
cmd := exec.Command("update-ssh-keys", "-u", user, "-a", keysName)
|
||||
stdin, err := cmd.StdinPipe()
|
||||
authorized_file := ""
|
||||
switch user {
|
||||
case "root":
|
||||
authorized_file = "/root/.ssh/authorized_keys"
|
||||
default:
|
||||
authorized_file = fmt.Sprintf("/home/%s/.ssh/authorized_keys", user)
|
||||
}
|
||||
|
||||
f, err := os.OpenFile(authorized_file, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
_, err = f.WriteString(joined)
|
||||
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
stderr, err := cmd.StderrPipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = cmd.Start()
|
||||
if err != nil {
|
||||
stdin.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = io.WriteString(stdin, joined)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
stdin.Close()
|
||||
stdoutBytes, _ := ioutil.ReadAll(stdout)
|
||||
stderrBytes, _ := ioutil.ReadAll(stderr)
|
||||
|
||||
err = cmd.Wait()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Call to update-ssh-keys failed with %v: %s %s", err, string(stdoutBytes), string(stderrBytes))
|
||||
}
|
||||
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
|
@@ -79,6 +79,22 @@ func CreateUser(u *config.User) error {
|
||||
output, err := exec.Command("useradd", args...).CombinedOutput()
|
||||
if err != nil {
|
||||
log.Printf("Command 'useradd %s' failed: %v\n%s", strings.Join(args, " "), err, output)
|
||||
return err
|
||||
}
|
||||
|
||||
args = []string{}
|
||||
|
||||
if u.LockPasswd {
|
||||
args = append(args, "--lock")
|
||||
} else {
|
||||
args = append(args, "--unlock")
|
||||
}
|
||||
|
||||
args = append(args, u.Name)
|
||||
|
||||
output, err = exec.Command("passwd", args...).CombinedOutput()
|
||||
if err != nil {
|
||||
log.Printf("Command 'passwd %s' failed: %v\n%s", strings.Join(args, " "), err, output)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
Reference in New Issue
Block a user