86 lines
1.9 KiB
Go
86 lines
1.9 KiB
Go
package main
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"encoding/json"
|
||
|
|
"fmt"
|
||
|
|
"os"
|
||
|
|
"path/filepath"
|
||
|
|
|
||
|
|
"golang.org/x/term"
|
||
|
|
|
||
|
|
"lanrdp/internal/protocol"
|
||
|
|
)
|
||
|
|
|
||
|
|
type config struct {
|
||
|
|
PasswordHash string `json:"password_hash"`
|
||
|
|
Port int `json:"port,omitempty"`
|
||
|
|
}
|
||
|
|
|
||
|
|
func configPath(dataDir string) string {
|
||
|
|
return filepath.Join(dataDir, "config.json")
|
||
|
|
}
|
||
|
|
|
||
|
|
func loadConfig(dataDir string) (*config, error) {
|
||
|
|
data, err := os.ReadFile(configPath(dataDir))
|
||
|
|
if os.IsNotExist(err) {
|
||
|
|
return nil, nil
|
||
|
|
}
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
var c config
|
||
|
|
if err := json.Unmarshal(data, &c); err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
return &c, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
func saveConfig(dataDir string, c *config) error {
|
||
|
|
if err := os.MkdirAll(dataDir, 0o700); err != nil {
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
data, err := json.MarshalIndent(c, "", " ")
|
||
|
|
if err != nil {
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
return os.WriteFile(configPath(dataDir), data, 0o600)
|
||
|
|
}
|
||
|
|
|
||
|
|
// firstRunSetup interactively asks the operator to set a passphrase for
|
||
|
|
// this host and persists its Argon2id hash. It never writes the plaintext
|
||
|
|
// passphrase to disk.
|
||
|
|
func firstRunSetup(dataDir string) (*config, error) {
|
||
|
|
fmt.Println("No passphrase configured yet for this host.")
|
||
|
|
for {
|
||
|
|
fmt.Print("Set a passphrase (min 8 characters): ")
|
||
|
|
pw1, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||
|
|
fmt.Println()
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("reading passphrase: %w", err)
|
||
|
|
}
|
||
|
|
if len(pw1) < 8 {
|
||
|
|
fmt.Println("Too short, try again.")
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
fmt.Print("Confirm passphrase: ")
|
||
|
|
pw2, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||
|
|
fmt.Println()
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("reading passphrase: %w", err)
|
||
|
|
}
|
||
|
|
if string(pw1) != string(pw2) {
|
||
|
|
fmt.Println("Passphrases did not match, try again.")
|
||
|
|
continue
|
||
|
|
}
|
||
|
|
hash, err := protocol.HashPassword(string(pw1))
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
c := &config{PasswordHash: hash}
|
||
|
|
if err := saveConfig(dataDir, c); err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
fmt.Println("Passphrase saved.")
|
||
|
|
return c, nil
|
||
|
|
}
|
||
|
|
}
|