Debian Codegraph @

plumbing/transport/ssh/auth_method.go

raw
1 package ssh
2
3 import (
4 "errors"
5 "fmt"
6 "os"
7 "os/user"
8 "path/filepath"
9
10 "github.com/go-git/go-git/v5/plumbing/transport"
11
12 "github.com/skeema/knownhosts"
13 sshagent "github.com/xanzy/ssh-agent"
14 "golang.org/x/crypto/ssh"
15 )
16
17 const DefaultUsername = "git"
18
19 // AuthMethod is the interface all auth methods for the ssh client
20 // must implement. The clientConfig method returns the ssh client
21 // configuration needed to establish an ssh connection.
22 type AuthMethod interface {
23 transport.AuthMethod
24 // ClientConfig should return a valid ssh.ClientConfig to be used to create
25 // a connection to the SSH server.
26 ClientConfig() (*ssh.ClientConfig, error)
27 }
28
29 // The names of the AuthMethod implementations. To be returned by the
30 // Name() method. Most git servers only allow PublicKeysName and
31 // PublicKeysCallbackName.
32 const (
33 KeyboardInteractiveName = "ssh-keyboard-interactive"
34 PasswordName = "ssh-password"
35 PasswordCallbackName = "ssh-password-callback"
36 PublicKeysName = "ssh-public-keys"
37 PublicKeysCallbackName = "ssh-public-key-callback"
38 )
39
40 // KeyboardInteractive implements AuthMethod by using a
41 // prompt/response sequence controlled by the server.
42 type KeyboardInteractive struct {
43 User string
44 Challenge ssh.KeyboardInteractiveChallenge
45 HostKeyCallbackHelper
46 }
47
48 func (a *KeyboardInteractive) Name() string {
49 return KeyboardInteractiveName
50 }
51
52 func (a *KeyboardInteractive) String() string {
53 return fmt.Sprintf("user: %s, name: %s", a.User, a.Name())
54 }
55
56 func (a *KeyboardInteractive) ClientConfig() (*ssh.ClientConfig, error) {
57 return a.SetHostKeyCallbackAndAlgorithms(&ssh.ClientConfig{
58 User: a.User,
59 Auth: []ssh.AuthMethod{
60 a.Challenge,
61 },
62 })
63 }
64
65 // Password implements AuthMethod by using the given password.
66 type Password struct {
67 User string
68 Password string
69 HostKeyCallbackHelper
70 }
71
72 func (a *Password) Name() string {
73 return PasswordName
74 }
75
76 func (a *Password) String() string {
77 return fmt.Sprintf("user: %s, name: %s", a.User, a.Name())
78 }
79
80 func (a *Password) ClientConfig() (*ssh.ClientConfig, error) {
81 return a.SetHostKeyCallbackAndAlgorithms(&ssh.ClientConfig{
82 User: a.User,
83 Auth: []ssh.AuthMethod{ssh.Password(a.Password)},
84 })
85 }
86
87 // PasswordCallback implements AuthMethod by using a callback
88 // to fetch the password.
89 type PasswordCallback struct {
90 User string
91 Callback func() (pass string, err error)
92 HostKeyCallbackHelper
93 }
94
95 func (a *PasswordCallback) Name() string {
96 return PasswordCallbackName
97 }
98
99 func (a *PasswordCallback) String() string {
100 return fmt.Sprintf("user: %s, name: %s", a.User, a.Name())
101 }
102
103 func (a *PasswordCallback) ClientConfig() (*ssh.ClientConfig, error) {
104 return a.SetHostKeyCallbackAndAlgorithms(&ssh.ClientConfig{
105 User: a.User,
106 Auth: []ssh.AuthMethod{ssh.PasswordCallback(a.Callback)},
107 })
108 }
109
110 // PublicKeys implements AuthMethod by using the given key pairs.
111 type PublicKeys struct {
112 User string
113 Signer ssh.Signer
114 HostKeyCallbackHelper
115 }
116
117 // NewPublicKeys returns a PublicKeys from a PEM encoded private key. An
118 // encryption password should be given if the pemBytes contains a password
119 // encrypted PEM block otherwise password should be empty. It supports RSA
120 // (PKCS#1), PKCS#8, DSA (OpenSSL), and ECDSA private keys.
121 func NewPublicKeys(user string, pemBytes []byte, password string) (*PublicKeys, error) {
122 signer, err := ssh.ParsePrivateKey(pemBytes)
123 if _, ok := err.(*ssh.PassphraseMissingError); ok {
124 signer, err = ssh.ParsePrivateKeyWithPassphrase(pemBytes, []byte(password))
125 }
126 if err != nil {
127 return nil, err
128 }
129 return &PublicKeys{User: user, Signer: signer}, nil
130 }
131
132 // NewPublicKeysFromFile returns a PublicKeys from a file containing a PEM
133 // encoded private key. An encryption password should be given if the pemBytes
134 // contains a password encrypted PEM block otherwise password should be empty.
135 func NewPublicKeysFromFile(user, pemFile, password string) (*PublicKeys, error) {
136 bytes, err := os.ReadFile(pemFile)
137 if err != nil {
138 return nil, err
139 }
140
141 return NewPublicKeys(user, bytes, password)
142 }
143
144 func (a *PublicKeys) Name() string {
145 return PublicKeysName
146 }
147
148 func (a *PublicKeys) String() string {
149 return fmt.Sprintf("user: %s, name: %s", a.User, a.Name())
150 }
151
152 func (a *PublicKeys) ClientConfig() (*ssh.ClientConfig, error) {
153 return a.SetHostKeyCallbackAndAlgorithms(&ssh.ClientConfig{
154 User: a.User,
155 Auth: []ssh.AuthMethod{ssh.PublicKeys(a.Signer)},
156 })
157 }
158
159 func username() (string, error) {
160 var username string
161 if user, err := user.Current(); err == nil {
162 username = user.Username
163 } else {
164 username = os.Getenv("USER")
165 }
166
167 if username == "" {
168 return "", errors.New("failed to get username")
169 }
170
171 return username, nil
172 }
173
174 // PublicKeysCallback implements AuthMethod by asking a
175 // ssh.agent.Agent to act as a signer.
176 type PublicKeysCallback struct {
177 User string
178 Callback func() (signers []ssh.Signer, err error)
179 HostKeyCallbackHelper
180 }
181
182 // NewSSHAgentAuth returns a PublicKeysCallback based on a SSH agent, it opens
183 // a pipe with the SSH agent and uses the pipe as the implementer of the public
184 // key callback function.
185 func NewSSHAgentAuth(u string) (*PublicKeysCallback, error) {
186 var err error
187 if u == "" {
188 u, err = username()
189 if err != nil {
190 return nil, err
191 }
192 }
193
194 a, _, err := sshagent.New()
195 if err != nil {
196 return nil, fmt.Errorf("error creating SSH agent: %q", err)
197 }
198
199 return &PublicKeysCallback{
200 User: u,
201 Callback: a.Signers,
202 }, nil
203 }
204
205 func (a *PublicKeysCallback) Name() string {
206 return PublicKeysCallbackName
207 }
208
209 func (a *PublicKeysCallback) String() string {
210 return fmt.Sprintf("user: %s, name: %s", a.User, a.Name())
211 }
212
213 func (a *PublicKeysCallback) ClientConfig() (*ssh.ClientConfig, error) {
214 return a.SetHostKeyCallbackAndAlgorithms(&ssh.ClientConfig{
215 User: a.User,
216 Auth: []ssh.AuthMethod{ssh.PublicKeysCallback(a.Callback)},
217 })
218 }
219
220 // NewKnownHostsCallback returns ssh.HostKeyCallback based on a file based on a
221 // known_hosts file. http://man.openbsd.org/sshd#SSH_KNOWN_HOSTS_FILE_FORMAT
222 //
223 // If list of files is empty, then it will be read from the SSH_KNOWN_HOSTS
224 // environment variable, example:
225 //
226 // /home/foo/custom_known_hosts_file:/etc/custom_known/hosts_file
227 //
228 // If SSH_KNOWN_HOSTS is not set the following file locations will be used:
229 //
230 // ~/.ssh/known_hosts
231 // /etc/ssh/ssh_known_hosts
232 func NewKnownHostsCallback(files ...string) (ssh.HostKeyCallback, error) {
233 kh, err := NewKnownHostsDb(files...)
234 if err != nil {
235 return nil, err
236 }
237 return kh.HostKeyCallback(), nil
238 }
239
240 // NewKnownHostsDb returns knownhosts.HostKeyDB based on a file based on a
241 // known_hosts file. http://man.openbsd.org/sshd#SSH_KNOWN_HOSTS_FILE_FORMAT
242 //
243 // If list of files is empty, then it will be read from the SSH_KNOWN_HOSTS
244 // environment variable, example:
245 //
246 // /home/foo/custom_known_hosts_file:/etc/custom_known/hosts_file
247 //
248 // If SSH_KNOWN_HOSTS is not set the following file locations will be used:
249 //
250 // ~/.ssh/known_hosts
251 // /etc/ssh/ssh_known_hosts
252 func NewKnownHostsDb(files ...string) (*knownhosts.HostKeyDB, error) {
253 var err error
254
255 if len(files) == 0 {
256 if files, err = getDefaultKnownHostsFiles(); err != nil {
257 return nil, err
258 }
259 }
260
261 if files, err = filterKnownHostsFiles(files...); err != nil {
262 return nil, err
263 }
264
265 return knownhosts.NewDB(files...)
266 }
267
268 func getDefaultKnownHostsFiles() ([]string, error) {
269 files := filepath.SplitList(os.Getenv("SSH_KNOWN_HOSTS"))
270 if len(files) != 0 {
271 return files, nil
272 }
273
274 homeDirPath, err := os.UserHomeDir()
275 if err != nil {
276 return nil, err
277 }
278
279 return []string{
280 filepath.Join(homeDirPath, "/.ssh/known_hosts"),
281 "/etc/ssh/ssh_known_hosts",
282 }, nil
283 }
284
285 func filterKnownHostsFiles(files ...string) ([]string, error) {
286 var out []string
287 for _, file := range files {
288 _, err := os.Stat(file)
289 if err == nil {
290 out = append(out, file)
291 continue
292 }
293
294 if !os.IsNotExist(err) {
295 return nil, err
296 }
297 }
298
299 if len(out) == 0 {
300 return nil, fmt.Errorf("unable to find any valid known_hosts file, set SSH_KNOWN_HOSTS env variable")
301 }
302
303 return out, nil
304 }
305
306 // HostKeyCallbackHelper is a helper that provides common functionality to
307 // configure HostKeyCallback and HostKeyAlgorithms into a ssh.ClientConfig.
308 type HostKeyCallbackHelper struct {
309 // HostKeyCallback is the function type used for verifying server keys.
310 // If nil, a default callback will be created using NewKnownHostsDb
311 // without argument.
312 HostKeyCallback ssh.HostKeyCallback
313
314 // HostKeyAlgorithms is a list of supported host key algorithms that will
315 // be used for host key verification.
316 HostKeyAlgorithms []string
317
318 // fallback allows for injecting the fallback call, which is called
319 // when a HostKeyCallback is not set.
320 fallback func(files ...string) (ssh.HostKeyCallback, error)
321 }
322
323 // SetHostKeyCallbackAndAlgorithms sets the field HostKeyCallback and HostKeyAlgorithms in the given cfg.
324 // If the host key callback or algorithms is empty it is left empty. It will be handled by the dial method,
325 // falling back to knownhosts.
326 func (m *HostKeyCallbackHelper) SetHostKeyCallbackAndAlgorithms(cfg *ssh.ClientConfig) (*ssh.ClientConfig, error) {
327 if cfg == nil {
328 cfg = &ssh.ClientConfig{}
329 }
330
331 if m.HostKeyCallback == nil {
332 if m.fallback == nil {
333 m.fallback = NewKnownHostsCallback
334 }
335
336 hkcb, err := m.fallback()
337 if err != nil {
338 return nil, fmt.Errorf("cannot create known hosts callback: %w", err)
339 }
340
341 cfg.HostKeyCallback = hkcb
342 cfg.HostKeyAlgorithms = m.HostKeyAlgorithms
343 return cfg, err
344 }
345
346 cfg.HostKeyCallback = m.HostKeyCallback
347 cfg.HostKeyAlgorithms = m.HostKeyAlgorithms
348 return cfg, nil
349 }
350
351 func (m *HostKeyCallbackHelper) SetHostKeyCallback(cfg *ssh.ClientConfig) (*ssh.ClientConfig, error) {
352 return m.SetHostKeyCallbackAndAlgorithms(cfg)
353 }