forked from reconquest/shadowc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssh_keys.go
105 lines (82 loc) · 1.73 KB
/
ssh_keys.go
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"bufio"
"io"
"os"
"github.com/reconquest/hierr-go"
"golang.org/x/crypto/ssh"
)
type SSHKey struct {
Comment string
Raw string
}
type SSHKeys []*SSHKey
type AuthorizedKeys map[string]SSHKeys
type AuthorizedKeysFile struct {
path string
keys SSHKeys
}
func ReadSSHKey(key string) (*SSHKey, error) {
_, comment, _, _, err := ssh.ParseAuthorizedKey([]byte(key))
if err != nil {
return nil, hierr.Errorf(
err, "can't parse authorized key",
)
}
return &SSHKey{
Comment: comment,
Raw: key,
}, nil
}
func (key *SSHKey) GetComment() string {
return key.Comment
}
func NewAuthorizedKeysFile(path string) *AuthorizedKeysFile {
return &AuthorizedKeysFile{
path: path,
}
}
func ReadAuthorizedKeysFile(path string) (*AuthorizedKeysFile, error) {
file, err := os.Open(path)
if err != nil {
return nil, hierr.Errorf(
err, "can't open authorized keys file",
)
}
sshKeys := SSHKeys{}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
key, err := ReadSSHKey(scanner.Text())
if err != nil {
return nil, err
}
sshKeys = append(sshKeys, key)
}
return &AuthorizedKeysFile{
path: path,
keys: sshKeys,
}, nil
}
func (file *AuthorizedKeysFile) AddSSHKey(key *SSHKey) bool {
for _, existKey := range file.keys {
if existKey.Raw == key.Raw {
return false
}
}
file.keys = append(file.keys, key)
return true
}
func (file *AuthorizedKeysFile) Write(writer io.Writer) (int, error) {
totalWritten := 0
for _, key := range file.keys {
written, err := io.WriteString(writer, string(key.Raw)+"\n")
if err != nil {
return totalWritten, err
}
totalWritten += written
}
return totalWritten, nil
}
func (file *AuthorizedKeysFile) GetPath() string {
return file.path
}