summaryrefslogtreecommitdiff
path: root/internal/sshd/sshd.go
blob: 74b4bf406e874c3d355a767225cdb38bd2a19445 (plain)
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package sshd

import (
	"context"
	"encoding/base64"
	"errors"
	"fmt"
	"io/ioutil"
	"net"
	"strconv"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
	log "github.com/sirupsen/logrus"
	"gitlab.com/gitlab-org/gitlab-shell/internal/command"
	"gitlab.com/gitlab-org/gitlab-shell/internal/command/commandargs"
	"gitlab.com/gitlab-org/gitlab-shell/internal/command/readwriter"
	"gitlab.com/gitlab-org/gitlab-shell/internal/config"
	"gitlab.com/gitlab-org/gitlab-shell/internal/gitlabnet/authorizedkeys"
	"golang.org/x/crypto/ssh"
	"golang.org/x/sync/semaphore"
)

const (
	namespace     = "gitlab_shell"
	sshdSubsystem = "sshd"
)

func secondsDurationBuckets() []float64 {
	return []float64{
		0.005, /* 5ms */
		0.025, /* 25ms */
		0.1,   /* 100ms */
		0.5,   /* 500ms */
		1.0,   /* 1s */
		10.0,  /* 10s */
		30.0,  /* 30s */
		60.0,  /* 1m */
		300.0, /* 10m */
	}
}

var (
	sshdConnectionDuration = promauto.NewHistogram(
		prometheus.HistogramOpts{
			Namespace: namespace,
			Subsystem: sshdSubsystem,
			Name:      "connection_duration_seconds",
			Help:      "A histogram of latencies for connections to gitlab-shell sshd.",
			Buckets:   secondsDurationBuckets(),
		},
	)

	sshdHitMaxSessions = promauto.NewCounter(
		prometheus.CounterOpts{
			Namespace: namespace,
			Subsystem: sshdSubsystem,
			Name:      "concurrent_limited_sessions_total",
			Help:      "The number of times the concurrent sessions limit was hit in gitlab-shell sshd.",
		},
	)
)

func Run(cfg *config.Config) error {
	authorizedKeysClient, err := authorizedkeys.NewClient(cfg)
	if err != nil {
		return fmt.Errorf("failed to initialize GitLab client: %w", err)
	}

	sshListener, err := net.Listen("tcp", cfg.Server.Listen)
	if err != nil {
		return fmt.Errorf("failed to listen for connection: %w", err)
	}

	config := &ssh.ServerConfig{
		PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
			if conn.User() != cfg.User {
				return nil, errors.New("unknown user")
			}
			if key.Type() == ssh.KeyAlgoDSA {
				return nil, errors.New("DSA is prohibited")
			}
			ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
			defer cancel()
			res, err := authorizedKeysClient.GetByKey(ctx, base64.RawStdEncoding.EncodeToString(key.Marshal()))
			if err != nil {
				return nil, err
			}

			return &ssh.Permissions{
				// Record the public key used for authentication.
				Extensions: map[string]string{
					"key-id": strconv.FormatInt(res.Id, 10),
				},
			}, nil
		},
	}

	var loadedHostKeys uint
	for _, filename := range cfg.Server.HostKeyFiles {
		keyRaw, err := ioutil.ReadFile(filename)
		if err != nil {
			log.Warnf("Failed to read host key %v: %v", filename, err)
			continue
		}
		key, err := ssh.ParsePrivateKey(keyRaw)
		if err != nil {
			log.Warnf("Failed to parse host key %v: %v", filename, err)
			continue
		}
		loadedHostKeys++
		config.AddHostKey(key)
	}
	if loadedHostKeys == 0 {
		return fmt.Errorf("No host keys could be loaded, aborting")
	}

	for {
		nconn, err := sshListener.Accept()
		if err != nil {
			log.Warnf("Failed to accept connection: %v\n", err)
			continue
		}

		go handleConn(nconn, config, cfg)
	}
}

type execRequest struct {
	Command string
}

type exitStatusReq struct {
	ExitStatus uint32
}

type envRequest struct {
	Name  string
	Value string
}

func exitSession(ch ssh.Channel, exitStatus uint32) {
	exitStatusReq := exitStatusReq{
		ExitStatus: exitStatus,
	}
	ch.CloseWrite()
	ch.SendRequest("exit-status", false, ssh.Marshal(exitStatusReq))
	ch.Close()
}

func handleConn(nconn net.Conn, sshCfg *ssh.ServerConfig, cfg *config.Config) {
	begin := time.Now()
	defer func() {
		sshdConnectionDuration.Observe(time.Since(begin).Seconds())
	}()

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	defer nconn.Close()
	conn, chans, reqs, err := ssh.NewServerConn(nconn, sshCfg)
	if err != nil {
		log.Infof("Failed to initialize SSH connection: %v", err)
		return
	}

	concurrentSessions := semaphore.NewWeighted(cfg.Server.ConcurrentSessionsLimit)

	go ssh.DiscardRequests(reqs)
	for newChannel := range chans {
		if newChannel.ChannelType() != "session" {
			newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
			continue
		}
		if !concurrentSessions.TryAcquire(1) {
			newChannel.Reject(ssh.ResourceShortage, "too many concurrent sessions")
			sshdHitMaxSessions.Inc()
			continue
		}
		ch, requests, err := newChannel.Accept()
		if err != nil {
			log.Infof("Could not accept channel: %v", err)
			concurrentSessions.Release(1)
			continue
		}

		go handleSession(ctx, concurrentSessions, ch, requests, conn, nconn, cfg)
	}
}

func handleSession(ctx context.Context, concurrentSessions *semaphore.Weighted, ch ssh.Channel, requests <-chan *ssh.Request, conn *ssh.ServerConn, nconn net.Conn, cfg *config.Config) {
	defer concurrentSessions.Release(1)

	rw := &readwriter.ReadWriter{
		Out:    ch,
		In:     ch,
		ErrOut: ch.Stderr(),
	}
	var gitProtocolVersion string

	for req := range requests {
		var execCmd string
		switch req.Type {
		case "env":
			var envRequest envRequest
			if err := ssh.Unmarshal(req.Payload, &envRequest); err != nil {
				ch.Close()
				return
			}
			var accepted bool
			if envRequest.Name == commandargs.GitProtocolEnv {
				gitProtocolVersion = envRequest.Value
				accepted = true
			}
			if req.WantReply {
				req.Reply(accepted, []byte{})
			}

		case "exec":
			var execRequest execRequest
			if err := ssh.Unmarshal(req.Payload, &execRequest); err != nil {
				ch.Close()
				return
			}
			execCmd = execRequest.Command
			fallthrough
		case "shell":
			if req.WantReply {
				req.Reply(true, []byte{})
			}
			args := &commandargs.Shell{
				GitlabKeyId:        conn.Permissions.Extensions["key-id"],
				RemoteAddr:         nconn.RemoteAddr().(*net.TCPAddr),
				GitProtocolVersion: gitProtocolVersion,
			}

			if err := args.ParseCommand(execCmd); err != nil {
				fmt.Fprintf(ch.Stderr(), "Failed to parse command: %v\n", err.Error())
				exitSession(ch, 128)
				return
			}

			cmd := command.BuildShellCommand(args, cfg, rw)
			if cmd == nil {
				fmt.Fprintf(ch.Stderr(), "Unknown command: %v\n", args.CommandType)
				exitSession(ch, 128)
				return
			}
			if err := cmd.Execute(ctx); err != nil {
				fmt.Fprintf(ch.Stderr(), "remote: ERROR: %v\n", err.Error())
				exitSession(ch, 1)
				return
			}
			exitSession(ch, 0)
			return
		default:
			if req.WantReply {
				req.Reply(false, []byte{})
			}
		}
	}
}