/
add_key.go
212 lines (185 loc) · 5.21 KB
/
add_key.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package client
import (
"encoding/json"
"fmt"
"net/http"
"time"
"os"
"bytes"
"net/url"
"io/ioutil"
"github.com/SierraSoftworks/inki/crypto"
log "github.com/Sirupsen/logrus"
"github.com/urfave/cli"
"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/clearsign"
"golang.org/x/crypto/ssh/terminal"
)
var addKeyCommand = cli.Command{
Name: "add",
Usage: "Adds an SSH key to the Inki key server",
UsageText: "user@inki-server",
Flags: []cli.Flag{
cli.StringFlag{
Name: "pgp-key, p",
Usage: "The PGP private key you wish to use to sign this request",
},
cli.StringFlag{
Name: "file, f",
Usage: "The SSH public key file which you would like to submit",
},
cli.DurationFlag{
Name: "expire, x",
Usage: "The amount of time that the key should be valid for",
Value: time.Hour,
},
},
Before: func(c *cli.Context) error {
log.SetOutput(os.Stderr)
return nil
},
Action: func(c *cli.Context) error {
if c.NArg() < 1 {
return fmt.Errorf("Missing user and host argument")
}
u, err := url.Parse(c.Args().First())
if err != nil {
log.WithError(err).Error("Failed to parse host URL")
return fmt.Errorf("Failed to parse user and host argument")
}
if u.User == nil || u.User.String() == "" {
log.Error("Host URL did not contain a username")
return fmt.Errorf("Host address did not contain a username")
}
if u.Scheme == "" {
u.Scheme = "http"
}
keyData := bytes.NewBuffer([]byte{})
if c.IsSet("file") {
kd, err := ioutil.ReadFile(c.String("file"))
if err != nil {
log.
WithError(err).
WithField("file", c.String("file")).
Debug("Failed to open key file for reading")
return fmt.Errorf("Failed to read key file")
}
keyData = bytes.NewBuffer(kd)
} else {
_, err := keyData.ReadFrom(os.Stdin)
if err != nil {
log.
WithError(err).
Debug("Failed to read key data from stdin")
return fmt.Errorf("Failed to read key from stdin")
}
}
key := &crypto.Key{
User: u.User.Username(),
PublicKey: keyData.String(),
Expires: time.Now().Add(c.Duration("expire")),
}
p, err := ioutil.ReadFile(c.String("pgp-key"))
if err != nil {
log.
WithError(err).
WithField("file", c.String("pgp-key")).
Debug("Failed to read the pgp-key file")
return fmt.Errorf("Failed to read the pgp-key you provided")
}
kr, err := openpgp.ReadArmoredKeyRing(bytes.NewBuffer(p))
if err != nil {
log.WithError(err).
WithField("file", c.String("pgp-key")).
Debug("Failed to decode the pgp-key file")
return fmt.Errorf("Failed to decode the pgp-key you provided")
}
pk := kr[0].PrivateKey
if pk.Encrypted {
if !c.IsSet("file") {
log.
Debug("Private key is encrypted and stdin has been used to read the SSH key")
return fmt.Errorf("Private key is encrypted and stdin was used to read the SSH key")
}
fmt.Print("Enter PGP key password: ")
pw, err := terminal.ReadPassword(int(os.Stdin.Fd()))
fmt.Println()
if err != nil {
log.
WithError(err).
Debug("Failed to request password from user")
return fmt.Errorf("Failed to request password input")
}
err = pk.Decrypt(pw)
if err != nil {
log.
WithError(err).
Debug("Failed to decrypt the PGP private key")
return fmt.Errorf("Failed to decrypt the PGP private key, please check that your password is correct")
}
}
reqData := bytes.NewBuffer([]byte{})
reqStream, err := clearsign.Encode(reqData, pk, nil)
if err != nil {
log.
WithError(err).
Debug("Failed to prepare signing packet")
return fmt.Errorf("Failed to prepare signing packet")
}
err = json.NewEncoder(reqStream).Encode(key)
if err != nil {
log.
WithError(err).
Debug("Failed to encode key request")
return fmt.Errorf("Failed to encode key request")
}
reqStream.Close()
url := fmt.Sprintf("%s://%s/api/v1/keys", u.Scheme, u.Host)
req, err := http.NewRequest("POST", url, reqData)
if err != nil {
log.
WithError(err).
Debug("Failed to prepare request")
return fmt.Errorf("Failed to prepare request to server")
}
log.WithFields(log.Fields{
"user": u.User.Username(),
"key": key.PublicKey,
"expire": key.Expires,
}).Info("Submitting new key for user")
res, err := http.DefaultClient.Do(req)
if err != nil {
log.
WithError(err).
WithFields(log.Fields{
"server": u.Host,
}).
Debug("Failed to send key request to server")
return fmt.Errorf("Request to send key request to server '%s'", u.Host)
}
if res.StatusCode != 200 {
log.
WithFields(log.Fields{
"server": u.Host,
"status": res.StatusCode,
}).
Debug("Failed to send key request to server")
return fmt.Errorf("Failed to send key request to server: %s", res.Status)
}
keys := []crypto.Key{}
if err := json.NewDecoder(res.Body).Decode(&keys); err != nil {
log.
WithError(err).
Debug("Failed to parse response from server")
return fmt.Errorf("Failed to parse response from server")
}
fmt.Println("Added keys:")
for _, k := range keys {
fmt.Printf(" - Username: %s\n", k.User)
fmt.Printf(" Fingerprint: %s\n", k.Fingerprint())
fmt.Printf(" Expires: %s\n", k.Expires)
fmt.Println()
}
return nil
},
}