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