all repos — flounder @ cf1bc7f98c8988285623ff592f6ee14861c12afd

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