Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor systemd unit installation #23

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ install: $(BINS)
@install -dm755 $(DESTDIR)$(LIBDIR)/systemd/system
@install -dm755 $(DESTDIR)$(LIBDIR)/systemd/user
@DESTDIR=$(DESTDIR) PREFIX=$(PREFIX) bin/ssh-tpm-hostkeys --install-system-units
@TEMPLATE_BINARY=1 DESTDIR=$(DESTDIR) PREFIX=$(PREFIX) bin/ssh-tpm-agent --install-user-units --install-system
@TEMPLATE_BINARY=/usr/bin/ssh-tpm-agent DESTDIR=$(DESTDIR) PREFIX=$(PREFIX) bin/ssh-tpm-agent --install-user-units --install-system
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
@TEMPLATE_BINARY=/usr/bin/ssh-tpm-agent DESTDIR=$(DESTDIR) PREFIX=$(PREFIX) bin/ssh-tpm-agent --install-user-units --install-system
@TEMPLATE_BINARY=$(BINDIR)/ssh-tpm-agent DESTDIR=$(DESTDIR) PREFIX=$(PREFIX) bin/ssh-tpm-agent --install-user-units --install-system


.PHONY: lint
lint:
Expand Down
24 changes: 13 additions & 11 deletions agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ import (

var ErrOperationUnsupported = errors.New("operation unsupported")

var (
SSH_TPM_AGENT_ADD = "tpm-add-key"
)
var SSH_TPM_AGENT_ADD = "tpm-add-key"

type Agent struct {
mu sync.Mutex
Expand All @@ -45,7 +43,7 @@ func (a *Agent) Extension(extensionType string, contents []byte) ([]byte, error)
slog.Debug("called extensions")
switch extensionType {
case SSH_TPM_AGENT_ADD:
slog.Debug("runnning %s", extensionType)
slog.Debug("runnning extension", slog.String("type", extensionType))
return a.AddTPMKey(contents)
}
return nil, agent.ErrExtensionUnsupported
Expand Down Expand Up @@ -78,7 +76,7 @@ func (a *Agent) signers() ([]ssh.Signer, error) {
for _, agent := range a.agents {
l, err := agent.Signers()
if err != nil {
slog.Info("failed getting Signers from agent: %f", err)
slog.Info("failed getting Signers from agent", slog.String("error", err.Error()))
continue
}
signers = append(signers, l...)
Expand Down Expand Up @@ -111,7 +109,7 @@ func (a *Agent) List() ([]*agent.Key, error) {
for _, agent := range a.agents {
l, err := agent.List()
if err != nil {
slog.Info("failed getting list from agent: %v", err)
slog.Info("failed getting list from agent", slog.String("error", err.Error()))
continue
}
agentKeys = append(agentKeys, l...)
Expand Down Expand Up @@ -160,7 +158,7 @@ func (a *Agent) SignWithFlags(key ssh.PublicKey, data []byte, flags agent.Signat
for _, agent := range a.agents {
signers, err := agent.Signers()
if err != nil {
slog.Info("failed getting signers from agent: %v", err)
slog.Info("failed getting signers from agent", slog.String("error", err.Error()))
continue
}
for _, s := range signers {
Expand All @@ -181,7 +179,7 @@ func (a *Agent) Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) {

func (a *Agent) serveConn(c net.Conn) {
if err := agent.ServeAgent(a, c); err != io.EOF {
slog.Info("Agent client connection ended with error:", err)
slog.Info("Agent client connection ended unsuccessfully", slog.String("error", err.Error()))
}
}

Expand All @@ -202,17 +200,18 @@ func (a *Agent) serve() {
if err != nil {
type temporary interface {
Temporary() bool
Error() string
}
if err, ok := err.(temporary); ok && err.Temporary() {
slog.Info("Temporary Accept error, sleeping 1s:", err)
slog.Info("Temporary Accept failure, sleeping 1s", slog.String("error", err.Error()))
time.Sleep(1 * time.Second)
continue
}
select {
case <-a.quit:
return
default:
slog.Error("Failed to accept connections:", err)
slog.Error("Failed to accept connections", slog.String("error", err.Error()))
}
}
a.wg.Add(1)
Expand Down Expand Up @@ -252,14 +251,17 @@ func (a *Agent) Remove(key ssh.PublicKey) error {
slog.Debug("called remove")
return ErrOperationUnsupported
}

func (a *Agent) RemoveAll() error {
slog.Debug("called removeall")
return a.Close()
}

func (a *Agent) Lock(passphrase []byte) error {
slog.Debug("called lock")
return ErrOperationUnsupported
}

func (a *Agent) Unlock(passphrase []byte) error {
slog.Debug("called unlock")
return ErrOperationUnsupported
Expand All @@ -284,7 +286,7 @@ func LoadKeys(keyDir string) (map[string]*key.Key, error) {
}
k, err := key.DecodeKey(f)
if err != nil {
slog.Debug("%s not a TPM sealed key: %v\n", path, err)
slog.Debug("not a TPM-sealed key", slog.String("key_path", path), slog.String("error", err.Error()))
return nil
}
keys[k.Fingerprint()] = k
Expand Down
18 changes: 12 additions & 6 deletions cmd/ssh-tpm-agent/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,13 @@ func main() {
slog.SetDefault(logger)

if installUserUnits {
utils.InstallUserUnits(system)
if err := utils.InstallUserUnits(system); err != nil {
log.Fatal(err)
fmt.Println(err.Error())
os.Exit(1)
}

fmt.Println("Enable with: systemctl --user enable --now ssh-tpm-agent.socket")
os.Exit(0)
}

Expand All @@ -152,7 +158,7 @@ func main() {
}

if keyDir == "" {
keyDir = utils.GetSSHDir()
keyDir = utils.SSHDir()
}

fi, err := os.Lstat(keyDir)
Expand All @@ -161,7 +167,7 @@ func main() {
os.Exit(1)
}
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
slog.Info("Warning: %s is a symbolic link; will not follow it", keyDir)
slog.Info("Not following symbolic link", slog.String("key_directory", keyDir))
}

if term.IsTerminal(int(os.Stdin.Fd())) {
Expand Down Expand Up @@ -205,7 +211,7 @@ func main() {
slog.Info("Socket activated agent.")
} else {
os.Remove(socketPath)
if err := os.MkdirAll(filepath.Dir(socketPath), 0777); err != nil {
if err := os.MkdirAll(filepath.Dir(socketPath), 0o777); err != nil {
slog.Error("Failed to create UNIX socket folder:", err)
os.Exit(1)
}
Expand All @@ -214,15 +220,15 @@ func main() {
slog.Error("Failed to listen on UNIX socket:", err)
os.Exit(1)
}
slog.Info(fmt.Sprintf("Listening on %v", socketPath))
slog.Info("Listening on socket", slog.String("path", socketPath))
}

a := agent.NewAgent(listener,
agents,
// TPM Callback
func() (tpm transport.TPMCloser) {
// the agent will close the TPM after this is called
tpm, err := utils.GetTPM(swtpmFlag)
tpm, err := utils.TPM(swtpmFlag)
if err != nil {
log.Fatal(err)
}
Expand Down
4 changes: 3 additions & 1 deletion cmd/ssh-tpm-hostkeys/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,11 @@ func main() {
flag.Parse()

if installSystemUnits {
if err := utils.InstallSystemUnits(); err != nil {
if err := utils.InstallHostkeyUnits(); err != nil {
log.Fatal(err)
}

fmt.Println("Enable with: systemctl enable --now ssh-tpm-agent.socket")
os.Exit(0)
}
if installSshdConfig {
Expand Down
16 changes: 8 additions & 8 deletions cmd/ssh-tpm-keygen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ func main() {

flag.Parse()

tpm, err := utils.GetTPM(swtpmFlag)
tpm, err := utils.TPM(swtpmFlag)
if err != nil {
log.Fatal(err)
}
Expand All @@ -154,22 +154,22 @@ func main() {
continue
}

slog.Info(fmt.Sprintf("Generating new %s host key\n", strings.ToUpper(n)))
slog.Info("Generating new host key", slog.String("algorithm", strings.ToUpper(n)))

k, err := key.CreateKey(tpm, t, []byte(""), []byte(defaultComment))
if err != nil {
log.Fatal(err)
}

if err := os.WriteFile(pubkeyFilename, k.AuthorizedKey(), 0600); err != nil {
if err := os.WriteFile(pubkeyFilename, k.AuthorizedKey(), 0o600); err != nil {
log.Fatal(err)
}

if err := os.WriteFile(privatekeyFilename, k.Encode(), 0600); err != nil {
if err := os.WriteFile(privatekeyFilename, k.Encode(), 0o600); err != nil {
log.Fatal(err)
}

slog.Info(fmt.Sprintf("Wrote %s\n", privatekeyFilename))
slog.Info("Wrote private key", slog.String("filename", privatekeyFilename))
}
os.Exit(0)
}
Expand Down Expand Up @@ -256,7 +256,7 @@ func main() {
} else {
fmt.Printf("Generating a sealed public/private %s key pair.\n", keyType)

filename = path.Join(utils.GetSSHDir(), filename)
filename = path.Join(utils.SSHDir(), filename)
filenameInput, err := getStdin("Enter file in which to save the key (%s): ", filename)
if err != nil {
log.Fatal(err)
Expand Down Expand Up @@ -318,12 +318,12 @@ func main() {
}

if importKey == "" {
if err := os.WriteFile(pubkeyFilename, k.AuthorizedKey(), 0600); err != nil {
if err := os.WriteFile(pubkeyFilename, k.AuthorizedKey(), 0o600); err != nil {
log.Fatal(err)
}
}

if err := os.WriteFile(privatekeyFilename, k.Encode(), 0600); err != nil {
if err := os.WriteFile(privatekeyFilename, k.Encode(), 0o600); err != nil {
log.Fatal(err)
}

Expand Down
9 changes: 3 additions & 6 deletions contrib/contrib.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,14 @@ func readPath(f embed.FS, s string) map[string][]byte {
return ret
}

// Get user services
func GetUserServices() map[string][]byte {
func EmbeddedUserServices() map[string][]byte {
return readPath(services, "services/user")
}

// Get system services
func GetSystemServices() map[string][]byte {
func EmbeddedSystemServices() map[string][]byte {
return readPath(services, "services/system")
}

// Get sshd config
func GetSshdConfig() map[string][]byte {
func EmbeddedSshdConfig() map[string][]byte {
return readPath(sshd, "sshd")
}
6 changes: 3 additions & 3 deletions contrib/contrib_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,21 @@ import (
)

func TestUserServices(t *testing.T) {
m := GetUserServices()
m := EmbeddedUserServices()
if len(m) != 2 {
t.Fatalf("invalid number of entries")
}
}

func TestSystemServices(t *testing.T) {
m := GetSystemServices()
m := EmbeddedSystemServices()
if len(m) != 3 {
t.Fatalf("invalid number of entries")
}
}

func TestSshdConfig(t *testing.T) {
m := GetSshdConfig()
m := EmbeddedSshdConfig()
if len(m) != 1 {
t.Fatalf("invalid number of entries")
}
Expand Down
2 changes: 1 addition & 1 deletion contrib/services/user/ssh-tpm-agent.service
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[Unit]
ConditionEnvironment=!SSH_AGENT_PID
Description=ssh-tpm-agent socket
Description=ssh-tpm-agent service
Documentation=man:ssh-agent(1) man:ssh-add(1) man:ssh(1)
Requires=ssh-tpm-agent.socket

Expand Down
6 changes: 2 additions & 4 deletions utils/tpm.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,10 @@ func FlushHandle(tpm transport.TPM, h handle) {
flushSrk.Execute(tpm)
}

var (
swtpmPath = "/var/tmp/ssh-tpm-agent"
)
var swtpmPath = "/var/tmp/ssh-tpm-agent"

// Smaller wrapper for getting the correct TPM instance
func GetTPM(f bool) (transport.TPMCloser, error) {
func TPM(f bool) (transport.TPMCloser, error) {
var tpm transport.TPMCloser
var err error
if f || os.Getenv("SSH_TPM_AGENT_SWTPM") != "" {
Expand Down
Loading