File: recipients.go

package info (click to toggle)
golang-github-muesli-sasquatch 0.0~git20210519.30aff9d-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 184 kB
  • sloc: makefile: 2
file content (82 lines) | stat: -rw-r--r-- 1,587 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package sasquatch

import (
	"fmt"
	"io/ioutil"

	"golang.org/x/crypto/ssh"
)

// A Recipient is a public key or other value that can encrypt an opaque file
// key to a recipient stanza.
type Recipient interface {
	Type() string
	Wrap(fileKey []byte) (*Stanza, error)
}

// FindRecipients returns all available recipients.
func FindRecipients() []Recipient {
	// from disk
	keys, err := FindSSHKeys()
	if err != nil {
		return nil
	}

	ids := []Recipient{}
	for _, key := range keys {
		key += ".pub"
		// fmt.Println("parsing", key)
		c, err := ioutil.ReadFile(key)
		if err != nil {
			// fmt.Println(err)
			continue
		}

		r, err := ParseRecipient(string(c))
		if err != nil {
			// fmt.Println(err)
			continue
		}
		ids = append(ids, r)
	}

	// from agent
	signers, err := SSHAgentSigners()
	if err != nil {
		return ids
	}

	for _, signer := range signers {
		i, err := NewChallengeRecipient(signer)
		if err != nil {
			continue
		}

		ids = append(ids, i)
	}

	return ids
}

// ParseRecipient creates a Recipient from an SSH public key.
func ParseRecipient(s string) (Recipient, error) {
	pubKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(s))
	if err != nil {
		return nil, fmt.Errorf("malformed SSH recipient: %q: %v", s, err)
	}

	var r Recipient
	switch t := pubKey.Type(); t {
	case "ssh-rsa":
		r, err = NewRSARecipient(pubKey)
	case "ssh-ed25519":
		r, err = NewEd25519Recipient(pubKey)
	default:
		return nil, fmt.Errorf("unknown SSH recipient type: %q", t)
	}
	if err != nil {
		return nil, fmt.Errorf("malformed SSH recipient: %q: %v", s, err)
	}

	return r, nil
}