sftp.go (view raw)
1// SFTP server for users with Flounder accounts
2// A lot of this is copied from SFTPGo, but simplified for our use case.
3package main
4
5import (
6 "fmt"
7 "io"
8 "io/ioutil"
9 "log"
10 "net"
11 "os"
12 "path"
13 "path/filepath"
14 "runtime/debug"
15 "strings"
16 "time"
17
18 "github.com/pkg/sftp"
19 "golang.org/x/crypto/ssh"
20)
21
22type Connection struct {
23 User string
24}
25
26func (con *Connection) Fileread(request *sftp.Request) (io.ReaderAt, error) {
27 // check user perms -- cant read others hidden files
28 fullpath := path.Join(c.FilesDirectory, filepath.Clean(request.Filepath))
29 f, err := os.OpenFile(fullpath, os.O_RDONLY, 0)
30 if err != nil {
31 return nil, err
32 }
33 return f, nil
34}
35
36func (con *Connection) Filewrite(request *sftp.Request) (io.WriterAt, error) {
37 // check user perms -- cant write others files
38 fullpath := path.Join(c.FilesDirectory, filepath.Clean(request.Filepath))
39 userDir := getUserDirectory(con.User) // NOTE -- not cross platform
40 if strings.HasPrefix(fullpath, userDir) {
41 f, err := os.OpenFile(fullpath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
42 if err != nil {
43 return nil, err
44 }
45 return f, nil
46 } else {
47 return nil, fmt.Errorf("Invalid permissions")
48 }
49}
50
51func (conn *Connection) Filelist(request *sftp.Request) (sftp.ListerAt, error) {
52 fullpath := path.Join(c.FilesDirectory, filepath.Clean(request.Filepath))
53 switch request.Method {
54 case "List":
55 f, err := os.Open(fullpath)
56 if err != nil {
57 return nil, err
58 }
59 fileInfo, err := f.Readdir(-1)
60 if err != nil {
61 return nil, err
62 }
63 return listerat(fileInfo), nil
64 case "Stat":
65 stat, err := os.Stat(fullpath)
66 if err != nil {
67 return nil, err
68 }
69 return listerat([]os.FileInfo{stat}), nil
70 }
71 return nil, fmt.Errorf("Invalid command")
72}
73
74func (c *Connection) Filecmd(request *sftp.Request) error {
75 // remove, rename, setstat? find out
76 return nil
77}
78
79// TODO hide hidden folders
80// Users have write persm on their files, read perms on all
81
82func buildHandlers(connection *Connection) sftp.Handlers {
83 return sftp.Handlers{
84 connection,
85 connection,
86 connection,
87 connection,
88 }
89}
90
91// Based on example server code from golang.org/x/crypto/ssh and server_standalone
92func runSFTPServer() {
93
94 // An SSH server is represented by a ServerConfig, which holds
95 // certificate details and handles authentication of ServerConns.
96 config := &ssh.ServerConfig{
97 PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
98 // Should use constant-time compare (or better, salt+hash) in
99 // a production setting.
100 if isOkUsername(c.User()) != nil { // extra check, probably unnecessary
101 return nil, fmt.Errorf("Invalid username")
102 }
103 _, _, err := checkLogin(c.User(), string(pass))
104 // TODO maybe give admin extra permissions?
105 if err != nil {
106 return nil, fmt.Errorf("password rejected for %q", c.User())
107 } else {
108 log.Printf("Login: %s\n", c.User())
109 return nil, nil
110 }
111 },
112 }
113
114 // TODO generate key automatically
115 privateBytes, err := ioutil.ReadFile("id_rsa")
116 if err != nil {
117 log.Fatal("Failed to load private key", err)
118 }
119
120 private, err := ssh.ParsePrivateKey(privateBytes)
121 if err != nil {
122 log.Fatal("Failed to parse private key", err)
123 }
124
125 config.AddHostKey(private)
126
127 listener, err := net.Listen("tcp", "0.0.0.0:2024")
128 if err != nil {
129 log.Fatal("failed to listen for connection", err)
130 }
131
132 fmt.Printf("Listening on %v\n", listener.Addr())
133
134 for {
135 conn, err := listener.Accept()
136 if err != nil {
137 log.Fatal(err)
138 }
139 go acceptInboundConnection(conn, config)
140 }
141}
142
143func acceptInboundConnection(conn net.Conn, config *ssh.ServerConfig) {
144 defer func() {
145 if r := recover(); r != nil {
146 log.Println("panic in AcceptInboundConnection: %#v stack strace: %v", r, string(debug.Stack()))
147 }
148 }()
149 ipAddr := GetIPFromRemoteAddress(conn.RemoteAddr().String())
150 fmt.Println("Request from IP " + ipAddr)
151 limiter := getVisitor(ipAddr)
152 if limiter.Allow() == false {
153 conn.Close()
154 return
155 }
156 // Before beginning a handshake must be performed on the incoming net.Conn
157 // we'll set a Deadline for handshake to complete, the default is 2 minutes as OpenSSH
158 conn.SetDeadline(time.Now().Add(2 * time.Minute))
159
160 // Before use, a handshake must be performed on the incoming net.Conn.
161 sconn, chans, reqs, err := ssh.NewServerConn(conn, config)
162 if err != nil {
163 log.Printf("failed to accept an incoming connection: %v", err)
164 return
165 }
166 log.Println("login detected:", sconn.User())
167 fmt.Fprintf(os.Stderr, "SSH server established\n")
168 // handshake completed so remove the deadline, we'll use IdleTimeout configuration from now on
169 conn.SetDeadline(time.Time{})
170
171 defer conn.Close()
172
173 // The incoming Request channel must be serviced.
174 go ssh.DiscardRequests(reqs)
175
176 // Service the incoming Channel channel.
177 channelCounter := int64(0)
178 for newChannel := range chans {
179 // Channels have a type, depending on the application level
180 // protocol intended. In the case of an SFTP session, this is "subsystem"
181 // with a payload string of "<length=4>sftp"
182 fmt.Fprintf(os.Stderr, "Incoming channel: %s\n", newChannel.ChannelType())
183 if newChannel.ChannelType() != "session" {
184 newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
185 fmt.Fprintf(os.Stderr, "Unknown channel type: %s\n", newChannel.ChannelType())
186 continue
187 }
188 channel, requests, err := newChannel.Accept()
189 if err != nil {
190 log.Println("could not accept channel.", err)
191 continue
192 }
193
194 channelCounter++
195 fmt.Fprintf(os.Stderr, "Channel accepted\n")
196
197 // Sessions have out-of-band requests such as "shell",
198 // "pty-req" and "env". Here we handle only the
199 // "subsystem" request.
200 go func(in <-chan *ssh.Request) {
201 for req := range in {
202 fmt.Fprintf(os.Stderr, "Request: %v\n", req.Type)
203 ok := false
204 switch req.Type {
205 case "subsystem":
206 fmt.Fprintf(os.Stderr, "Subsystem: %s\n", req.Payload[4:])
207 if string(req.Payload[4:]) == "sftp" {
208 ok = true
209 }
210 }
211 fmt.Fprintf(os.Stderr, " - accepted: %v\n", ok)
212 req.Reply(ok, nil)
213 }
214 }(requests)
215 connection := Connection{sconn.User()}
216 root := buildHandlers(&connection)
217 server := sftp.NewRequestServer(channel, root)
218 if err := server.Serve(); err == io.EOF {
219 server.Close()
220 log.Println("sftp client exited session.")
221 } else if err != nil {
222 log.Println("sftp server completed with error:", err)
223 return
224 }
225 }
226}
227
228type listerat []os.FileInfo
229
230// Modeled after strings.Reader's ReadAt() implementation
231func (f listerat) ListAt(ls []os.FileInfo, offset int64) (int, error) {
232 var n int
233 if offset >= int64(len(f)) {
234 return 0, io.EOF
235 }
236 n = copy(ls, f[offset:])
237 if n < len(ls) {
238 return n, io.EOF
239 }
240 return n, nil
241}