-
Notifications
You must be signed in to change notification settings - Fork 50
/
ftp.go
122 lines (110 loc) · 2.45 KB
/
ftp.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
package flamingo
import (
"bufio"
"fmt"
"net"
"strings"
"sync"
log "github.com/sirupsen/logrus"
)
// ConfFTP holds information for a FTP server.
type ConfFTP struct {
BindPort uint16
BindHost string
RecordWriter *RecordWriter
shutdown bool
listener net.Listener
m sync.Mutex
}
// NewConfFTP creates a default configuration for the FTP capture server.
func NewConfFTP() *ConfFTP {
return &ConfFTP{
BindPort: 21,
BindHost: "[::]",
}
}
// IsShutdown checks to see if the service is shutting down.
func (c *ConfFTP) IsShutdown() bool {
c.m.Lock()
defer c.m.Unlock()
return c.shutdown
}
// Shutdown flags the service to shut down
func (c *ConfFTP) Shutdown() {
c.m.Lock()
defer c.m.Unlock()
c.listener.Close()
}
// SpawnFTP creates a new FTP capture server.
func SpawnFTP(c *ConfFTP) error {
listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", c.BindHost, c.BindPort))
if err != nil {
return err
}
log.Debugf("ftp is listening on %s:%d", c.BindHost, c.BindPort)
c.listener = listener
go ftpStart(c)
return nil
}
func ftpStart(c *ConfFTP) {
for !c.IsShutdown() {
conn, err := c.listener.Accept()
if err != nil {
continue
}
go ftpHandleConnection(c, conn)
}
}
func ftpCreateMessage(code int, msg string) string {
return fmt.Sprintf("%d %s\r\n", code, msg)
}
func ftpHandleConnection(c *ConfFTP, conn net.Conn) {
defer conn.Close()
reader := bufio.NewReader(conn)
writer := bufio.NewWriter(conn)
writer.WriteString(ftpCreateMessage(220, "Welcome to FTP server."))
writer.Flush()
var (
username string
password string
)
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
parts := strings.SplitN(strings.Trim(line, "\r\n"), " ", 2)
if len(parts) < 2 {
return
}
command := parts[0]
msg := parts[1]
switch command {
case "USER":
username = msg
writer.WriteString(ftpCreateMessage(331, "Username ok, password required"))
writer.Flush()
case "PASS":
password = msg
writer.WriteString(ftpCreateMessage(230, "Password ok, continue"))
writer.Flush()
default:
writer.WriteString(ftpCreateMessage(500, "Command not found"))
writer.Flush()
break
}
if username != "" && password != "" {
c.RecordWriter.Record(
"credential",
"ftp",
conn.RemoteAddr().String(),
map[string]string{
"username": username,
"password": password,
"_server": fmt.Sprintf("%s:%d", c.BindHost, c.BindPort),
},
)
return
}
}
}