forked from francoismichel/ssh3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
314 lines (270 loc) · 8.35 KB
/
client.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package ssh3
import (
"crypto"
"encoding/base64"
"fmt"
"net/http"
"os"
"path"
"ssh3/auth"
"ssh3/util"
"strconv"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/kevinburke/ssh_config"
"github.com/rs/zerolog/log"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
type PasswordAuthMethod struct{}
type OidcAuthMethod struct {
doPKCE bool
config *auth.OIDCConfig
}
func (m *OidcAuthMethod) OIDCConfig() *auth.OIDCConfig {
return m.config
}
type PrivkeyFileAuthMethod struct {
filename string
}
type AgentAuthMethod struct {
pubkey ssh.PublicKey
}
func NewPasswordAuthMethod() *PasswordAuthMethod {
return &PasswordAuthMethod{}
}
func (m *PasswordAuthMethod) IntoIdentity(password string) Identity {
return passwordIdentity(password)
}
func NewOidcAuthMethod(doPKCE bool, config *auth.OIDCConfig) *OidcAuthMethod {
return &OidcAuthMethod{
doPKCE: doPKCE,
config: config,
}
}
func (m *OidcAuthMethod) IntoIdentity(bearerToken string) Identity {
return rawBearerTokenIdentity(bearerToken)
}
func NewPrivkeyFileAuthMethod(filename string) *PrivkeyFileAuthMethod {
return &PrivkeyFileAuthMethod{
filename: filename,
}
}
func (m *PrivkeyFileAuthMethod) Filename() string {
return m.filename
}
// IntoIdentityWithoutPassphrase returns an SSH3 identity stored on the provided path.
// It supports the same keys as ssh.ParsePrivateKey
// If the private key is encrypted, it returns an ssh.PassphraseMissingError.
func (m *PrivkeyFileAuthMethod) IntoIdentityWithoutPassphrase() (Identity, error) {
return m.intoIdentity(nil)
}
// IntoIdentityPassphrase returns a passphrase-protected private key stored on the provided path.
// It supports the same keys as ssh.ParsePrivateKey
// If the passphrase is wrong, it returns an x509.IncorrectPasswordError.
func (m *PrivkeyFileAuthMethod) IntoIdentityPassphrase(passphrase string) (Identity, error) {
return m.intoIdentity(&passphrase)
}
func (m *PrivkeyFileAuthMethod) intoIdentity(passphrase *string) (Identity, error) {
filename := m.filename
if strings.HasPrefix(filename, "~/") {
dirname, _ := os.UserHomeDir()
filename = path.Join(dirname, filename[2:])
}
pemBytes, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
var cryptoSigner crypto.Signer
var signer interface{}
var ok bool
if passphrase == nil {
signer, err = ssh.ParseRawPrivateKey(pemBytes)
} else {
signer, err = ssh.ParseRawPrivateKeyWithPassphrase(pemBytes, []byte(*passphrase))
}
if err != nil {
return nil, err
}
// transform the abstract type into a crypto.Signer that can be used with the jwt lib
if cryptoSigner, ok = signer.(crypto.Signer); !ok {
return nil, fmt.Errorf("the provided key file does not result in a crypto.Signer type")
}
signingMethod, err := util.JWTSigningMethodFromCryptoPubkey(cryptoSigner.Public())
if err != nil {
return nil, err
}
return &privkeyFileIdentity{
privkey: cryptoSigner,
signingMethod: signingMethod,
}, nil
}
func NewAgentAuthMethod(pubkey ssh.PublicKey) *AgentAuthMethod {
return &AgentAuthMethod{
pubkey: pubkey,
}
}
// A prerequisite of calling this methiod is that the provided pubkey is explicitly listed by the agent
// This can be verified beforehand by calling agent.List()
func (m *AgentAuthMethod) IntoIdentity(agent agent.ExtendedAgent) Identity {
return &agentBasedIdentity{
pubkey: m.pubkey,
agent: agent,
}
}
// a generic way to generate SSH3 identities to populate the HTTP Authorization header
type Identity interface {
SetAuthorizationHeader(req *http.Request, username string, conversation *Conversation) error
// provides an authentication name that can be used as a hint for the server in the url query params
AuthHint() string
fmt.Stringer
}
// represents private keys stored in a classical file
type privkeyFileIdentity struct {
privkey crypto.Signer
signingMethod jwt.SigningMethod
}
func (i *privkeyFileIdentity) SetAuthorizationHeader(req *http.Request, username string, conversation *Conversation) error {
bearerToken, err := buildJWTBearerToken(i.signingMethod, i.privkey, username, conversation)
if err != nil {
return err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", bearerToken))
return nil
}
func (i *privkeyFileIdentity) AuthHint() string {
return "pubkey"
}
func (i *privkeyFileIdentity) String() string {
return fmt.Sprintf("pubkey-identity: ALG=%s", i.signingMethod.Alg())
}
type agentSigningMethod struct {
Agent agent.ExtendedAgent
Key ssh.PublicKey
}
func (m *agentSigningMethod) Verify(signingString string, sig []byte, key interface{}) error {
panic("not implemented")
}
func (m *agentSigningMethod) Sign(signingString string, key interface{}) ([]byte, error) {
pk, ok := key.(ssh.PublicKey)
if !ok {
return nil, fmt.Errorf("bad key type: %T instead of ssh.PublicKey", pk)
}
signature, err := m.Agent.SignWithFlags(pk, []byte(signingString), agent.SignatureFlagRsaSha256)
if err != nil {
return nil, err
}
return signature.Blob, nil
}
func (m *agentSigningMethod) Alg() string {
switch m.Key.Type() {
case "ssh-rsa":
return "RS256"
case "ssh-ed25519":
return "EdDSA"
}
return ""
}
// represents an identity using a running SSH agent
type agentBasedIdentity struct {
pubkey ssh.PublicKey
agent agent.ExtendedAgent
}
func (i *agentBasedIdentity) SetAuthorizationHeader(req *http.Request, username string, conversation *Conversation) error {
signingMethod := &agentSigningMethod{
Agent: i.agent,
Key: i.pubkey,
}
bearerToken, err := buildJWTBearerToken(signingMethod, i.pubkey, username, conversation)
if err != nil {
return err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", bearerToken))
return nil
}
func (i *agentBasedIdentity) AuthHint() string {
return "pubkey"
}
func (i *agentBasedIdentity) String() string {
retval := "agent-identity"
if stringer, ok := i.pubkey.(fmt.Stringer); ok {
retval = fmt.Sprintf("%s: %s", retval, stringer.String())
}
return retval
}
type passwordIdentity string
func (i passwordIdentity) SetAuthorizationHeader(req *http.Request, username string, conversation *Conversation) error {
req.SetBasicAuth(username, string(i))
return nil
}
func (i passwordIdentity) AuthHint() string {
return "password"
}
func (i passwordIdentity) String() string {
return "password-identity"
}
type rawBearerTokenIdentity string
func (i rawBearerTokenIdentity) SetAuthorizationHeader(req *http.Request, username string, conversation *Conversation) error {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", string(i)))
return nil
}
func (i rawBearerTokenIdentity) AuthHint() string {
return "jwt"
}
func (i rawBearerTokenIdentity) String() string {
return "raw-bearer-identity"
}
func GetConfigForHost(host string, config *ssh_config.Config) (hostname string, port int, user string, authMethodsToTry []interface{}, err error) {
port = -1
if config == nil {
return
}
hostname, err = config.Get(host, "HostName")
if err != nil {
log.Error().Msgf("Could not get HostName from config: %s", err)
return
}
portStr, err := config.Get(host, "Port")
if err != nil {
log.Error().Msgf("Could not get Port from config: %s", err)
return
}
user, err = config.Get(host, "User")
if err != nil {
log.Error().Msgf("Could not get User from config: %s", err)
return
}
p, err := strconv.Atoi(portStr)
if err == nil {
port = p
}
identityFiles, err := config.GetAll(host, "IdentityFile")
if err != nil {
log.Error().Msgf("Could not get IdentityFiles from config: %s", err)
return
}
for _, identityFile := range identityFiles {
authMethodsToTry = append(authMethodsToTry, NewPrivkeyFileAuthMethod(identityFile))
}
return hostname, port, user, authMethodsToTry, nil
}
func buildJWTBearerToken(signingMethod jwt.SigningMethod, key interface{}, username string, conversation *Conversation) (string, error) {
convID := conversation.ConversationID()
b64ConvID := base64.StdEncoding.EncodeToString(convID[:])
token := jwt.NewWithClaims(signingMethod, jwt.MapClaims{
"iss": username,
"iat": jwt.NewNumericDate(time.Now()),
"exp": jwt.NewNumericDate(time.Now().Add(10 * time.Second)),
"sub": "ssh3",
"aud": "unused",
"client_id": fmt.Sprintf("ssh3-%s", username),
"jti": b64ConvID,
})
// the jwt lib handles "any kind" of crypto signer
signedString, err := token.SignedString(key)
if err != nil {
return "", fmt.Errorf("could not sign token: %s", err)
}
return signedString, nil
}