all repos

mugit @ cd02956

🐮 git server that your cow will love

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package ssh

import (
	"fmt"
	"log/slog"
	"slices"
	"strconv"

	securejoin "github.com/cyphar/filepath-securejoin"
	"github.com/gliderlabs/ssh"
	"olexsmir.xyz/mugit/internal/config"
	"olexsmir.xyz/mugit/internal/git"
	"olexsmir.xyz/mugit/internal/git/gitservice"

	gossh "golang.org/x/crypto/ssh"
)

type authorizedKeyType string

const authorizedKey authorizedKeyType = "authorized"

type Server struct {
	c        *config.Config
	authKeys []gossh.PublicKey
}

func NewServer(cfg *config.Config) *Server {
	return &Server{
		c:        cfg,
		authKeys: []gossh.PublicKey{},
	}
}

func (s *Server) Start() error {
	if err := s.parseAuthKeys(); err != nil {
		return err
	}

	srv := &ssh.Server{
		Addr:             ":" + strconv.Itoa(s.c.SSH.Port),
		Handler:          s.handler,
		PublicKeyHandler: s.authhandler,
	}

	if err := srv.SetOption(ssh.HostKeyFile(s.c.SSH.HostKey)); err != nil {
		// TODO: validate `gossh.ParsePrivateKey`
		return err
	}

	return srv.ListenAndServe()
}

func (s *Server) authhandler(ctx ssh.Context, key ssh.PublicKey) bool {
	fingerprint := gossh.FingerprintSHA256(key)
	if ctx.User() != "git" {
		slog.Info("non git ssh request", "user", ctx.User(), "fingerprint", fingerprint)
		return false
	}

	slog.Info("ssh request", "fingerprint", fingerprint)
	authorized := slices.ContainsFunc(s.authKeys, func(i gossh.PublicKey) bool {
		return ssh.KeysEqual(key, i)
	})
	ctx.SetValue(authorizedKey, authorized)
	return true
}

func (s *Server) handler(sess ssh.Session) {
	authorized := sess.Context().Value(authorizedKey).(bool)

	cmd := sess.Command()
	if len(cmd) < 2 {
		fmt.Fprintln(sess, "No command provided")
		sess.Exit(1)
		return
	}

	gitCmd := cmd[0]
	repoPath := cmd[1]
	repoPath, err := securejoin.SecureJoin(s.c.Repo.Dir, repoPath)
	if err != nil {
		slog.Error("ssh: invalid path", "err", err)
		s.repoNotFound(sess)
		return
	}

	repo, err := git.Open(repoPath, "")
	if err != nil {
		slog.Error("ssh: failed to open repo", "err", err)
		s.repoNotFound(sess)
		return
	}

	switch gitCmd {
	case "git-upload-pack":
		isPrivate, err := repo.IsPrivate()
		if err != nil {
			s.error(sess, err)
			return
		}

		if isPrivate && !authorized {
			s.repoNotFound(sess)
			return
		}

		if err := gitservice.UploadPack(repoPath, false, sess, sess); err != nil {
			s.error(sess, err)
			return
		}
		sess.Exit(0)
	case "git-receive-pack":
		if !authorized {
			s.unauthorized(sess)
			return
		}

		if err := gitservice.ReceivePack(repoPath, sess, sess, sess.Stderr()); err != nil {
			s.error(sess, err)
			return
		}
		sess.Exit(0)

	default:
		slog.Error("ssh unsupported command", "cmd", cmd)
		gitservice.PackError(sess, "Unsupported command.")
		sess.Exit(1)
	}
}

func (s *Server) parseAuthKeys() error {
	parsedKeys := make([]gossh.PublicKey, len(s.c.SSH.Keys))
	for i, key := range s.c.SSH.Keys {
		pkey, _, _, _, err := gossh.ParseAuthorizedKey([]byte(key))
		if err != nil {
			return err
		}
		parsedKeys[i] = pkey
	}
	s.authKeys = parsedKeys
	return nil
}

func (s *Server) repoNotFound(sess ssh.Session) {
	gitservice.PackError(sess, "Repository not found.")
	sess.Exit(1)
}

func (s *Server) unauthorized(sess ssh.Session) {
	gitservice.PackError(sess, "You are not authorized to push to this repository.")
	sess.Exit(1)
}

func (s *Server) error(sess ssh.Session, err error) {
	slog.Error("error on ssh side", "err", err)
	gitservice.PackError(sess, "Unexpected server error.")
	sess.Exit(1)
}