forked from libgit2/git2go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh.go
250 lines (212 loc) · 5.87 KB
/
ssh.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
package git
/*
#include <git2.h>
#include <git2/sys/credential.h>
*/
import "C"
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/url"
"runtime"
"strings"
"unsafe"
"golang.org/x/crypto/ssh"
)
// RegisterManagedSSHTransport registers a Go-native implementation of an SSH
// transport that doesn't rely on any system libraries (e.g. libssh2).
//
// If Shutdown or ReInit are called, make sure that the smart transports are
// freed before it.
func RegisterManagedSSHTransport(protocol string) (*RegisteredSmartTransport, error) {
return NewRegisteredSmartTransport(protocol, false, sshSmartSubtransportFactory)
}
func registerManagedSSH() error {
globalRegisteredSmartTransports.Lock()
defer globalRegisteredSmartTransports.Unlock()
for _, protocol := range []string{"ssh", "ssh+git", "git+ssh"} {
if _, ok := globalRegisteredSmartTransports.transports[protocol]; ok {
continue
}
managed, err := newRegisteredSmartTransport(protocol, false, sshSmartSubtransportFactory, true)
if err != nil {
return fmt.Errorf("failed to register transport for %q: %v", protocol, err)
}
globalRegisteredSmartTransports.transports[protocol] = managed
}
return nil
}
func sshSmartSubtransportFactory(remote *Remote, transport *Transport) (SmartSubtransport, error) {
return &sshSmartSubtransport{
transport: transport,
}, nil
}
type sshSmartSubtransport struct {
transport *Transport
lastAction SmartServiceAction
client *ssh.Client
session *ssh.Session
stdin io.WriteCloser
stdout io.Reader
currentStream *sshSmartSubtransportStream
}
func (t *sshSmartSubtransport) Action(urlString string, action SmartServiceAction) (SmartSubtransportStream, error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
u, err := url.Parse(urlString)
if err != nil {
return nil, err
}
// Escape \ and '.
uPath := strings.Replace(u.Path, `\`, `\\`, -1)
uPath = strings.Replace(uPath, `'`, `\'`, -1)
// TODO: Add percentage decode similar to libgit2.
// Refer: https://github.com/libgit2/libgit2/blob/358a60e1b46000ea99ef10b4dd709e92f75ff74b/src/str.c#L455-L481
var cmd string
switch action {
case SmartServiceActionUploadpackLs, SmartServiceActionUploadpack:
if t.currentStream != nil {
if t.lastAction == SmartServiceActionUploadpackLs {
return t.currentStream, nil
}
t.Close()
}
cmd = fmt.Sprintf("git-upload-pack '%s'", uPath)
case SmartServiceActionReceivepackLs, SmartServiceActionReceivepack:
if t.currentStream != nil {
if t.lastAction == SmartServiceActionReceivepackLs {
return t.currentStream, nil
}
t.Close()
}
cmd = fmt.Sprintf("git-receive-pack '%s'", uPath)
default:
return nil, fmt.Errorf("unexpected action: %v", action)
}
cred, err := t.transport.SmartCredentials("", CredentialTypeSSHKey|CredentialTypeSSHMemory)
if err != nil {
return nil, err
}
defer cred.Free()
sshConfig, err := getSSHConfigFromCredential(cred)
if err != nil {
return nil, err
}
sshConfig.HostKeyCallback = func(hostname string, remote net.Addr, key ssh.PublicKey) error {
marshaledKey := key.Marshal()
cert := &Certificate{
Kind: CertificateHostkey,
Hostkey: HostkeyCertificate{
Kind: HostkeySHA1 | HostkeyMD5 | HostkeySHA256 | HostkeyRaw,
HashMD5: md5.Sum(marshaledKey),
HashSHA1: sha1.Sum(marshaledKey),
HashSHA256: sha256.Sum256(marshaledKey),
Hostkey: marshaledKey,
SSHPublicKey: key,
},
}
return t.transport.SmartCertificateCheck(cert, true, hostname)
}
var addr string
if u.Port() != "" {
addr = fmt.Sprintf("%s:%s", u.Hostname(), u.Port())
} else {
addr = fmt.Sprintf("%s:22", u.Hostname())
}
t.client, err = ssh.Dial("tcp", addr, sshConfig)
if err != nil {
return nil, err
}
t.session, err = t.client.NewSession()
if err != nil {
return nil, err
}
t.stdin, err = t.session.StdinPipe()
if err != nil {
return nil, err
}
t.stdout, err = t.session.StdoutPipe()
if err != nil {
return nil, err
}
if err := t.session.Start(cmd); err != nil {
return nil, err
}
t.lastAction = action
t.currentStream = &sshSmartSubtransportStream{
owner: t,
}
return t.currentStream, nil
}
func (t *sshSmartSubtransport) Close() error {
t.currentStream = nil
if t.client != nil {
t.stdin.Close()
t.session.Wait()
t.session.Close()
t.client = nil
}
return nil
}
func (t *sshSmartSubtransport) Free() {
}
type sshSmartSubtransportStream struct {
owner *sshSmartSubtransport
}
func (stream *sshSmartSubtransportStream) Read(buf []byte) (int, error) {
return stream.owner.stdout.Read(buf)
}
func (stream *sshSmartSubtransportStream) Write(buf []byte) (int, error) {
return stream.owner.stdin.Write(buf)
}
func (stream *sshSmartSubtransportStream) Free() {
}
func getSSHConfigFromCredential(cred *Credential) (*ssh.ClientConfig, error) {
switch cred.Type() {
case CredentialTypeSSHCustom:
credSSHCustom := (*C.git_credential_ssh_custom)(unsafe.Pointer(cred.ptr))
data, ok := pointerHandles.Get(credSSHCustom.payload).(*credentialSSHCustomData)
if !ok {
return nil, errors.New("unsupported custom SSH credentials")
}
return &ssh.ClientConfig{
User: C.GoString(credSSHCustom.username),
Auth: []ssh.AuthMethod{ssh.PublicKeys(data.signer)},
}, nil
}
username, _, privatekey, passphrase, err := cred.GetSSHKey()
if err != nil {
return nil, err
}
var pemBytes []byte
if cred.Type() == CredentialTypeSSHMemory {
pemBytes = []byte(privatekey)
} else {
pemBytes, err = ioutil.ReadFile(privatekey)
if err != nil {
return nil, err
}
}
var key ssh.Signer
if passphrase != "" {
key, err = ssh.ParsePrivateKeyWithPassphrase(pemBytes, []byte(passphrase))
if err != nil {
return nil, err
}
} else {
key, err = ssh.ParsePrivateKey(pemBytes)
if err != nil {
return nil, err
}
}
return &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{ssh.PublicKeys(key)},
}, nil
}