all repos

mugit @ 1db697aa5fe1475e6047e8ab4b21673c8c95cd80

🐮 git server that your cow will love

mugit/internal/ssh/ssh.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
ssh: make sure there's no shell injections with SSH_ORIGINAL_COMMAND, 1 month ago
1
package ssh
2
3
import (
4
	"context"
5
	"errors"
6
	"fmt"
7
	"io"
8
	"strings"
9
10
	"olexsmir.xyz/mugit/internal/config"
11
	"olexsmir.xyz/mugit/internal/git"
12
13
	gossh "golang.org/x/crypto/ssh"
14
)
15
16
type Shell struct {
17
	cfg *config.Config
18
19
	keys []gossh.PublicKey
20
}
21
22
func NewShell(cfg *config.Config) (*Shell, error) {
23
	parsedKeys := make([]gossh.PublicKey, len(cfg.SSH.Keys))
24
	for i, key := range cfg.SSH.Keys {
25
		pkey, _, _, _, err := gossh.ParseAuthorizedKey([]byte(key))
26
		if err != nil {
27
			return nil, err
28
		}
29
		parsedKeys[i] = pkey
30
	}
31
32
	return &Shell{
33
		cfg:  cfg,
34
		keys: parsedKeys,
35
	}, nil
36
}
37
38
func (s *Shell) HandleCommand(ctx context.Context, cmd string, stdin io.Reader, stdout, stderr io.Writer) error {
39
	gitCmd, repoName, err := s.parseCommand(cmd)
40
	if err != nil {
41
		return s.replyWithGitError(stderr, "access denied: invalid command", err)
42
	}
43
44
	repoPath, err := git.ResolvePath(s.cfg.Repo.Dir, git.ResolveName(repoName))
45
	if err != nil {
46
		return s.replyWithGitError(stderr, "access denied", err)
47
	}
48
49
	repo, err := git.Open(repoPath, "")
50
	if err != nil {
51
		if !errors.Is(err, git.ErrRepoNotFound) || gitCmd != "git-receive-pack" {
52
			return s.replyWithGitError(stderr, "repository not found", err)
53
		}
54
55
		// SSH Git clients display informational messages from stderr; stdout must remain protocol-only for git-receive-pack.
56
		if ierr := s.replyWithGitInfo(stderr, "auto-initializing "+repoName); ierr != nil {
57
			return ierr
58
		}
59
60
		if ierr := git.Init(repoPath); ierr != nil {
61
			return s.replyWithGitError(stderr, "failed to init repo", ierr)
62
		}
63
64
		repo, err = git.Open(repoPath, "")
65
		if err != nil {
66
			return s.replyWithGitError(stderr, "failed to open initialized repo", err)
67
		}
68
	}
69
70
	switch gitCmd {
71
	case "git-upload-pack":
72
		err = repo.UploadPack(ctx, false, "", stdin, stdout)
73
	case "git-upload-archive":
74
		err = repo.UploadArchive(ctx, stdin, stdout)
75
	case "git-receive-pack":
76
		err = repo.ReceivePack(ctx, stdin, stdout, stderr)
77
	default:
78
		msg := "access denied: invalid git command"
79
		return s.replyWithGitError(stderr, msg, errors.New(msg))
80
	}
81
82
	if err != nil {
83
		return err
84
	}
85
86
	return nil
87
}
88
89
func (s *Shell) AuthorizedKeys(executablePath string) string {
90
	var out strings.Builder
91
	for _, key := range s.cfg.SSH.Keys {
92
		fmt.Fprintf(&out, `command="%s shell",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s`+"\n",
93
			executablePath, key)
94
	}
95
	return out.String()
96
}
97
98
var validCommands = map[string]bool{
99
	"git-upload-pack":    true,
100
	"git-upload-archive": true,
101
	"git-receive-pack":   true,
102
}
103
104
func (s *Shell) parseCommand(cmd string) (gitCmd, repoName string, err error) {
105
	cmdParts := strings.Fields(cmd)
106
	if len(cmdParts) != 2 {
107
		return "", "", fmt.Errorf("invalid command: expected 'git-cmd repo', got %q", cmd)
108
	}
109
110
	gitCmd = cmdParts[0]
111
	if !validCommands[gitCmd] {
112
		return "", "", fmt.Errorf("invalid command: disallowed command")
113
	}
114
115
	repoName = strings.Trim(cmdParts[1], "'\"")
116
	if repoName == "" {
117
		return "", "", fmt.Errorf("invalid command: empty repository name")
118
	}
119
120
	return gitCmd, repoName, nil
121
}
122
123
func (s *Shell) replyWithGitError(stderr io.Writer, msg string, cause error) error {
124
	if _, err := fmt.Fprintf(stderr, "error: %s\n", msg); err != nil {
125
		return err
126
	}
127
128
	return cause
129
}
130
131
func (s *Shell) replyWithGitInfo(msgOut io.Writer, msg string) error {
132
	_, err := fmt.Fprintf(msgOut, "info: %s\n", msg)
133
	return err
134
}