forked from yob/graval
/
ftpconn.go
388 lines (326 loc) · 9.58 KB
/
ftpconn.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package graval
import (
"bufio"
"bytes"
"crypto/rand"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"fmt"
"io"
"net"
"path/filepath"
"strings"
"sync"
"time"
)
type ftpConn struct {
conn net.Conn
controlReader *bufio.Reader
controlWriter *bufio.Writer
dataConn ftpDataSocket
dataConnMutex *sync.RWMutex
driver FTPDriver
logger *ftpLogger
passiveOpts *PassiveOpts
cryptoConfig *CryptoConfig
serverName string
sessionId string
namePrefix string
reqUser string
user string
renameFrom string
usingTls bool
usingPbsz bool
usingProt bool
restPosition int64
}
// NewftpConn constructs a new object that will handle the FTP protocol over
// an active net.TCPConn. The TCP connection should already be open before
// it is handed to this functions. driver is an instance of FTPDriver that
// will handle all auth and persistence details.
func newftpConn(tcpConn *net.TCPConn, driver FTPDriver, serverName string, passiveOpts *PassiveOpts, cryptoConfig *CryptoConfig, quiet bool) *ftpConn {
c := new(ftpConn)
c.namePrefix = "/"
c.conn = tcpConn
c.dataConnMutex = &sync.RWMutex{}
c.driver = driver
c.sessionId = newSessionId()
c.logger = newFtpLogger(c.sessionId, quiet)
c.passiveOpts = passiveOpts
c.cryptoConfig = cryptoConfig
c.serverName = serverName
c.usingTls = false
c.usingPbsz = false
c.usingProt = false
if remoteAddressDriver, ok := driver.(FTPDriverSetRemoteAddress); ok {
remoteAddressDriver.SetRemoteAddress(tcpConn.RemoteAddr())
}
if cryptoConfig.Implicit {
c.startTls()
} else {
c.setupReaderWriter()
}
return c
}
// returns a random 20 char string that can be used as a unique session ID
func newSessionId() string {
hash := sha256.New()
_, err := io.CopyN(hash, rand.Reader, 50)
if err != nil {
return "????????????????????"
}
md := hash.Sum(nil)
mdStr := hex.EncodeToString(md)
return mdStr[0:20]
}
func (ftpConn *ftpConn) setupReaderWriter() {
ftpConn.controlReader = bufio.NewReader(ftpConn.conn)
ftpConn.controlWriter = bufio.NewWriter(ftpConn.conn)
}
type BoundCommand struct {
CmdObj ftpCommand
Param string
}
// Serve starts an endless loop that reads FTP commands from the client and
// responds appropriately. terminated is a channel that will receive a true
// message when the connection closes. This loop will be running inside a
// goroutine, so use this channel to be notified when the connection can be
// cleaned up.
func (ftpConn *ftpConn) Serve() {
defer func() {
if closer, ok := ftpConn.driver.(io.Closer); ok {
closer.Close()
}
}()
ftpConn.logger.Printf("Connection Established (%s)", ftpConn.conn.RemoteAddr())
// send welcome
ftpConn.writeMessage(220, ftpConn.serverName)
// read commands
var readMutex sync.RWMutex
cmdCh := make(chan *BoundCommand, 0)
go func() {
defer func() {
if r := recover(); r != nil {
ftpConn.logger.Printf("Recovered in ftpConn Serve: %s", r)
}
ftpConn.Close()
close(cmdCh)
}()
for {
readMutex.RLock()
line, err := ftpConn.controlReader.ReadString('\n')
readMutex.RUnlock()
if err != nil {
return
} else {
cmdObj := ftpConn.receiveLine(line)
if cmdObj != nil {
if !cmdObj.CmdObj.Async() {
readMutex.Lock()
}
select {
case cmdCh <- cmdObj:
continue
case _ = <-time.After(10 * time.Second):
return
}
}
}
}
}()
for cmd := range cmdCh {
cmd.CmdObj.Execute(ftpConn, cmd.Param)
if !cmd.CmdObj.Async() {
readMutex.Unlock()
}
}
ftpConn.logger.Print("Connection Terminated")
}
// Close will manually close this connection, even if the client isn't ready.
func (ftpConn *ftpConn) Close() {
ftpConn.conn.Close()
ftpConn.dataConnMutex.RLock()
dataConn := ftpConn.dataConn
ftpConn.dataConnMutex.RUnlock()
if dataConn != nil {
ftpConn.dataConnMutex.Lock()
dataConn.Close()
ftpConn.dataConn = nil
ftpConn.dataConnMutex.Unlock()
}
}
func (ftpConn *ftpConn) receiveLine(line string) (cmd *BoundCommand) {
command, param := ftpConn.parseLine(line)
ftpConn.logger.PrintCommand(command, param)
cmdObj := commands[command]
if cmdObj == nil {
ftpConn.writeMessage(500, "Command not found")
return
}
if cmdObj.RequireParam() && param == "" {
ftpConn.writeMessage(553, "action aborted, required param missing")
return
} else if cmdObj.RequireAuth() && ftpConn.user == "" {
ftpConn.writeMessage(530, "not logged in")
return
} else {
cmd = &BoundCommand{cmdObj, param}
return
}
}
func (ftpConn *ftpConn) parseLine(line string) (string, string) {
params := strings.SplitN(strings.Trim(line, "\r\n"), " ", 2)
if len(params) > 0 {
params[0] = strings.ToUpper(params[0])
}
if len(params) == 1 {
return params[0], ""
}
return params[0], strings.TrimSpace(params[1])
}
// writeMessage will send a standard FTP response back to the client.
func (ftpConn *ftpConn) writeMessage(code int, message string) (wrote int, err error) {
ftpConn.logger.PrintResponse(code, message)
line := fmt.Sprintf("%d %s\r\n", code, message)
wrote, err = ftpConn.controlWriter.WriteString(line)
ftpConn.controlWriter.Flush()
return
}
// writeLines will send a multiline FTP response back to the client.
func (ftpConn *ftpConn) writeLines(code int, lines ...string) (wrote int, err error) {
message := strings.Join(lines, "\r\n") + "\r\n"
ftpConn.logger.PrintResponse(code, message)
wrote, err = ftpConn.controlWriter.WriteString(message)
ftpConn.controlWriter.Flush()
return
}
// buildPath takes a client supplied path or filename and generates a safe
// absolute path within their account sandbox.
//
// buildpath("/")
// => "/"
// buildpath("one.txt")
// => "/one.txt"
// buildpath("/files/two.txt")
// => "/files/two.txt"
// buildpath("files/two.txt")
// => "files/two.txt"
// buildpath("/../../../../etc/passwd")
// => "/etc/passwd"
//
// The driver implementation is responsible for deciding how to treat this path.
// Obviously they MUST NOT just read the path off disk. The probably want to
// prefix the path with something to scope the users access to a sandbox.
func (ftpConn *ftpConn) buildPath(filename string) (fullPath string) {
low := strings.ToLower(filename)
if len(filename) > 0 && filename[0:1] == "/" {
fullPath = filepath.Clean(filename)
} else if len(filename) > 0 && low != "-a" && low != "-l" && low != "-al" && low != "-la" {
fullPath = filepath.Clean(ftpConn.namePrefix + "/" + filename)
} else {
fullPath = filepath.Clean(ftpConn.namePrefix)
}
fullPath = strings.Replace(fullPath, "//", "/", -1)
return
}
// sendOutofbandReader will copy data from reader to the client via the currently
// open data socket. Assumes the socket is open and ready to be used.
func (ftpConn *ftpConn) sendOutofbandReader(reader io.Reader) {
defer func() {
ftpConn.dataConnMutex.Lock()
ftpConn.dataConn = nil
ftpConn.dataConnMutex.Unlock()
}()
dataConn, dataConnOk := ftpConn.DataConnWait(10 * time.Second)
if !dataConnOk {
ftpConn.writeMessage(425, "Can't open data connection.")
return
}
ftpConn.writeMessage(125, "Data connection already open. Transfer starting.")
// wait for 125 and 150 messages to be writen
time.Sleep(10 * time.Millisecond)
// we need an empty write for TLS connection if reader is empty
_, _ = dataConn.Write([]byte{})
_, err := io.Copy(dataConn, reader)
if err != nil {
dataConn.Close()
ftpConn.logger.Printf("sendOutofbandReader copy error %s", err)
ftpConn.writeMessage(550, "Action not taken")
return
}
// Chrome dies on localhost if we close connection to soon
time.Sleep(10 * time.Millisecond)
dataConn.Close()
ftpConn.writeMessage(226, "Transfer complete.")
}
func (ftpConn *ftpConn) DataConnWait(timeout time.Duration) (dataConn ftpDataSocket, ok bool) {
ftpConn.dataConnMutex.RLock()
dataConn = ftpConn.dataConn
ftpConn.dataConnMutex.RUnlock()
if dataConn == nil {
return nil, false
}
if dataConn.Wait(timeout) {
return dataConn, true
} else {
return nil, false
}
}
// sendOutofbandData will send a string to the client via the currently open
// data socket. Assumes the socket is open and ready to be used.
func (ftpConn *ftpConn) sendOutofbandData(data string) {
ftpConn.sendOutofbandReader(bytes.NewReader([]byte(data)))
}
func (ftpConn *ftpConn) canStartTls() bool {
return ftpConn.cryptoConfig != nil && ftpConn.cryptoConfig.TlsConfig != nil
}
func (ftpConn *ftpConn) startTls() {
if ftpConn.usingTls {
return
}
ftpConn.conn = tls.Server(ftpConn.conn, ftpConn.cryptoConfig.TlsConfig)
ftpConn.setupReaderWriter()
ftpConn.usingTls = true
return
}
func (ftpConn *ftpConn) newPassiveSocket() (socket *ftpPassiveSocket, err error) {
ftpConn.dataConnMutex.RLock()
dataConn := ftpConn.dataConn
ftpConn.dataConnMutex.RUnlock()
if dataConn != nil {
ftpConn.dataConnMutex.Lock()
dataConn.Close()
ftpConn.dataConn = nil
ftpConn.dataConnMutex.Unlock()
}
var tlsConfig *tls.Config
if ftpConn.usingProt {
tlsConfig = ftpConn.cryptoConfig.TlsConfig
}
socket, err = newPassiveSocket(ftpConn.logger, ftpConn.passiveOpts, tlsConfig)
if err == nil {
ftpConn.dataConnMutex.Lock()
ftpConn.dataConn = socket
ftpConn.dataConnMutex.Unlock()
}
return
}
func (ftpConn *ftpConn) newActiveSocket(host string, port int) (socket *ftpActiveSocket, err error) {
ftpConn.dataConnMutex.RLock()
dataConn := ftpConn.dataConn
ftpConn.dataConnMutex.RUnlock()
if dataConn != nil {
ftpConn.dataConnMutex.Lock()
dataConn.Close()
ftpConn.dataConn = nil
ftpConn.dataConnMutex.Unlock()
}
socket, err = newActiveSocket(host, port, ftpConn.logger)
if err == nil {
ftpConn.dataConnMutex.Lock()
ftpConn.dataConn = socket
ftpConn.dataConnMutex.Unlock()
}
return
}