all repos — flounder @ 521d6b600460a4d4ebb271b50e003c9d9d8218b5

A small site builder for the Gemini protocol

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