all repos — flounder @ 6a448532723ac8abf673b4964260d8f4a4ed2fb2

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	"crypto/rand"
  7	"crypto/rsa"
  8	"crypto/x509"
  9	"encoding/pem"
 10	"fmt"
 11	"io"
 12	"io/ioutil"
 13	"log"
 14	"net"
 15	"os"
 16	"path"
 17	"path/filepath"
 18	"runtime/debug"
 19	"time"
 20
 21	"github.com/pkg/sftp"
 22	"golang.org/x/crypto/ssh"
 23)
 24
 25type Connection struct {
 26	User string
 27}
 28
 29func (con *Connection) Fileread(request *sftp.Request) (io.ReaderAt, error) {
 30	// check user perms -- cant read others hidden files
 31	userDir := getUserDirectory(con.User) // NOTE -- not cross platform
 32	fullpath := path.Join(userDir, filepath.Clean(request.Filepath))
 33	f, err := os.OpenFile(fullpath, os.O_RDONLY, 0)
 34	if err != nil {
 35		return nil, err
 36	}
 37	return f, nil
 38}
 39
 40func (con *Connection) Filewrite(request *sftp.Request) (io.WriterAt, error) {
 41	// check user perms -- cant write others files
 42	userDir := getUserDirectory(con.User) // NOTE -- not cross platform
 43	fullpath := path.Join(userDir, filepath.Clean(request.Filepath))
 44	f, err := os.OpenFile(fullpath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
 45	if err != nil {
 46		return nil, err
 47	}
 48	return f, nil
 49}
 50
 51func (conn *Connection) Filelist(request *sftp.Request) (sftp.ListerAt, error) {
 52	userDir := getUserDirectory(conn.User) // NOTE -- not cross platform
 53	fullpath := path.Join(userDir, filepath.Clean(request.Filepath))
 54	switch request.Method {
 55	case "List":
 56		f, err := os.Open(fullpath)
 57		if err != nil {
 58			return nil, err
 59		}
 60		fileInfo, err := f.Readdir(-1)
 61		if err != nil {
 62			return nil, err
 63		}
 64		return listerat(fileInfo), nil
 65	case "Stat":
 66		stat, err := os.Stat(fullpath)
 67		if err != nil {
 68			return nil, err
 69		}
 70		return listerat([]os.FileInfo{stat}), nil
 71	}
 72	return nil, fmt.Errorf("Invalid command")
 73}
 74
 75func (conn *Connection) Filecmd(request *sftp.Request) error {
 76	// remove, rename, setstat? find out
 77	userDir := getUserDirectory(conn.User) // NOTE -- not cross platform
 78	fullpath := path.Join(userDir, filepath.Clean(request.Filepath))
 79	var err error
 80	switch request.Method {
 81	case "Remove":
 82		err = os.Remove(fullpath)
 83	case "Mkdir":
 84		err = os.Mkdir(fullpath, 0755)
 85	}
 86	if err != nil {
 87		return err
 88	}
 89	// Rename, Mkdir
 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	if !c.EnableSFTP {
108		return
109	}
110	// An SSH server is represented by a ServerConfig, which holds
111	// certificate details and handles authentication of ServerConns.
112	config := &ssh.ServerConfig{
113		PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
114			// Should use constant-time compare (or better, salt+hash) in
115			// a production setting.
116			if isOkUsername(c.User()) != nil { // extra check, probably unnecessary
117				return nil, fmt.Errorf("Invalid username")
118			}
119			_, _, err := checkLogin(c.User(), string(pass))
120			// TODO maybe give admin extra permissions?
121			if err != nil {
122				return nil, fmt.Errorf("password rejected for %q", c.User())
123			} else {
124				log.Printf("Login: %s\n", c.User())
125				return nil, nil
126			}
127		},
128	}
129
130	// TODO generate key automatically
131	if _, err := os.Stat(c.HostKeyPath); os.IsNotExist(err) {
132		// path/to/whatever does not exist
133		log.Println("Host key not found, generating host key")
134		err := GenerateRSAKeys()
135		if err != nil {
136			log.Fatal(err)
137		}
138	}
139
140	privateBytes, err := ioutil.ReadFile(c.HostKeyPath)
141	if err != nil {
142		log.Fatal("Failed to load private key", err)
143	}
144
145	private, err := ssh.ParsePrivateKey(privateBytes)
146	if err != nil {
147		log.Fatal("Failed to parse private key", err)
148	}
149
150	config.AddHostKey(private)
151
152	listener, err := net.Listen("tcp", "0.0.0.0:2024")
153	if err != nil {
154		log.Fatal("failed to listen for connection", err)
155	}
156
157	log.Printf("SFTP server listening on %v\n", listener.Addr())
158
159	for {
160		conn, err := listener.Accept()
161		if err != nil {
162			log.Fatal(err)
163		}
164		go acceptInboundConnection(conn, config)
165	}
166}
167
168func acceptInboundConnection(conn net.Conn, config *ssh.ServerConfig) {
169	defer func() {
170		if r := recover(); r != nil {
171			log.Printf("panic in AcceptInboundConnection: %#v stack strace: %v", r, string(debug.Stack()))
172		}
173	}()
174	ipAddr := GetIPFromRemoteAddress(conn.RemoteAddr().String())
175	log.Println("Request from IP " + ipAddr)
176	limiter := getVisitor(ipAddr)
177	if limiter.Allow() == false {
178		conn.Close()
179		return
180	}
181	// Before beginning a handshake must be performed on the incoming net.Conn
182	// we'll set a Deadline for handshake to complete, the default is 2 minutes as OpenSSH
183	conn.SetDeadline(time.Now().Add(2 * time.Minute))
184
185	// Before use, a handshake must be performed on the incoming net.Conn.
186	sconn, chans, reqs, err := ssh.NewServerConn(conn, config)
187	if err != nil {
188		log.Printf("failed to accept an incoming connection: %v", err)
189		return
190	}
191	log.Println("login detected:", sconn.User())
192	fmt.Fprintf(os.Stderr, "SSH server established\n")
193	// handshake completed so remove the deadline, we'll use IdleTimeout configuration from now on
194	conn.SetDeadline(time.Time{})
195
196	defer conn.Close()
197
198	// The incoming Request channel must be serviced.
199	go ssh.DiscardRequests(reqs)
200
201	// Service the incoming Channel channel.
202	channelCounter := int64(0)
203	for newChannel := range chans {
204		// Channels have a type, depending on the application level
205		// protocol intended. In the case of an SFTP session, this is "subsystem"
206		// with a payload string of "<length=4>sftp"
207		fmt.Fprintf(os.Stderr, "Incoming channel: %s\n", newChannel.ChannelType())
208		if newChannel.ChannelType() != "session" {
209			newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
210			fmt.Fprintf(os.Stderr, "Unknown channel type: %s\n", newChannel.ChannelType())
211			continue
212		}
213		channel, requests, err := newChannel.Accept()
214		if err != nil {
215			log.Println("could not accept channel.", err)
216			continue
217		}
218
219		channelCounter++
220		fmt.Fprintf(os.Stderr, "Channel accepted\n")
221
222		// Sessions have out-of-band requests such as "shell",
223		// "pty-req" and "env".  Here we handle only the
224		// "subsystem" request.
225		go func(in <-chan *ssh.Request) {
226			for req := range in {
227				fmt.Fprintf(os.Stderr, "Request: %v\n", req.Type)
228				ok := false
229				switch req.Type {
230				case "subsystem":
231					fmt.Fprintf(os.Stderr, "Subsystem: %s\n", req.Payload[4:])
232					if string(req.Payload[4:]) == "sftp" {
233						ok = true
234					}
235				}
236				fmt.Fprintf(os.Stderr, " - accepted: %v\n", ok)
237				req.Reply(ok, nil)
238			}
239		}(requests)
240		connection := Connection{sconn.User()}
241		root := buildHandlers(&connection)
242		server := sftp.NewRequestServer(channel, root)
243		if err := server.Serve(); err == io.EOF {
244			server.Close()
245			log.Println("sftp client exited session.")
246		} else if err != nil {
247			log.Println("sftp server completed with error:", err)
248			return
249		}
250	}
251}
252
253// GenerateRSAKeys generate rsa private and public keys and write the
254// private key to specified file and the public key to the specified
255// file adding the .pub suffix
256func GenerateRSAKeys() error {
257	key, err := rsa.GenerateKey(rand.Reader, 4096)
258	if err != nil {
259		return err
260	}
261
262	o, err := os.OpenFile(c.HostKeyPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
263	if err != nil {
264		return err
265	}
266	defer o.Close()
267
268	priv := &pem.Block{
269		Type:  "RSA PRIVATE KEY",
270		Bytes: x509.MarshalPKCS1PrivateKey(key),
271	}
272
273	if err := pem.Encode(o, priv); err != nil {
274		return err
275	}
276
277	pub, err := ssh.NewPublicKey(&key.PublicKey)
278	if err != nil {
279		return err
280	}
281	return ioutil.WriteFile(c.HostKeyPath+".pub", ssh.MarshalAuthorizedKey(pub), 0600)
282}
283
284type listerat []os.FileInfo
285
286// Modeled after strings.Reader's ReadAt() implementation
287func (f listerat) ListAt(ls []os.FileInfo, offset int64) (int, error) {
288	var n int
289	if offset >= int64(len(f)) {
290		return 0, io.EOF
291	}
292	n = copy(ls, f[offset:])
293	if n < len(ls) {
294		return n, io.EOF
295	}
296	return n, nil
297}