snapshot of https://github.com/go-gitea/gitea.git (main, 2026-09-15; blobs > 131072B omitted)
Some checks failed
cache-seeder / prune (push) Has been skipped
cache-seeder / frontend (push) Failing after 3s
cache-seeder / python (push) Failing after 3s
cache-seeder / gobuild (push) Failing after 4s
cache-seeder / lint (bindata, lint-backend) (push) Failing after 3s
giteabot backport / giteabot (push) Has been skipped
giteabot / giteabot (push) Has been skipped
cache-prune / prune (push) Has been skipped
release-nightly-snapcraft / build-and-publish (ubuntu-24.04) (push) Has been cancelled
release-nightly-snapcraft / build-and-publish (ubuntu-24.04-arm) (push) Has been cancelled
release-nightly / nightly-binary (push) Has been cancelled
release-nightly / nightly-container (push) Has been cancelled
cron-renovate / cron-renovate (push) Has been skipped
Some checks failed
cache-seeder / prune (push) Has been skipped
cache-seeder / frontend (push) Failing after 3s
cache-seeder / python (push) Failing after 3s
cache-seeder / gobuild (push) Failing after 4s
cache-seeder / lint (bindata, lint-backend) (push) Failing after 3s
giteabot backport / giteabot (push) Has been skipped
giteabot / giteabot (push) Has been skipped
cache-prune / prune (push) Has been skipped
release-nightly-snapcraft / build-and-publish (ubuntu-24.04) (push) Has been cancelled
release-nightly-snapcraft / build-and-publish (ubuntu-24.04-arm) (push) Has been cancelled
release-nightly / nightly-binary (push) Has been cancelled
release-nightly / nightly-container (push) Has been cancelled
cron-renovate / cron-renovate (push) Has been skipped
This commit is contained in:
59
modules/ssh/init.go
Normal file
59
modules/ssh/init.go
Normal file
@@ -0,0 +1,59 @@
|
||||
// Copyright 2022 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gitea.dev/modules/graceful"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/util"
|
||||
)
|
||||
|
||||
// builtinUnused informs our cleanup routine that we will not be using a ssh port
|
||||
func builtinUnused() {
|
||||
graceful.GetManager().InformCleanup()
|
||||
}
|
||||
|
||||
func Init() error {
|
||||
if setting.SSH.Disabled {
|
||||
builtinUnused()
|
||||
return nil
|
||||
}
|
||||
|
||||
if setting.SSH.StartBuiltinServer {
|
||||
Listen(setting.SSH.ListenHost, setting.SSH.ListenPort, setting.SSH.ServerCiphers, setting.SSH.ServerKeyExchanges, setting.SSH.ServerMACs)
|
||||
log.Info("SSH server started on %q. Ciphers: %v, key exchange algorithms: %v, MACs: %v",
|
||||
net.JoinHostPort(setting.SSH.ListenHost, strconv.Itoa(setting.SSH.ListenPort)),
|
||||
util.Iif[any](setting.SSH.ServerCiphers == nil, "default", setting.SSH.ServerCiphers),
|
||||
util.Iif[any](setting.SSH.ServerKeyExchanges == nil, "default", setting.SSH.ServerKeyExchanges),
|
||||
util.Iif[any](setting.SSH.ServerMACs == nil, "default", setting.SSH.ServerMACs),
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
||||
builtinUnused()
|
||||
|
||||
if len(setting.SSH.TrustedUserCAKeys) > 0 && setting.SSH.AuthorizedPrincipalsEnabled {
|
||||
caKeysFileName := setting.SSH.TrustedUserCAKeysFile
|
||||
caKeysFileDir := filepath.Dir(caKeysFileName)
|
||||
|
||||
err := os.MkdirAll(caKeysFileDir, 0o700) // SSH.RootPath by default (That is `~/.ssh` in most cases)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create directory %q for ssh trusted ca keys: %w", caKeysFileDir, err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(caKeysFileName, []byte(strings.Join(setting.SSH.TrustedUserCAKeys, "\n")), 0o600); err != nil {
|
||||
return fmt.Errorf("failed to write ssh trusted ca keys to %q: %w", caKeysFileName, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
144
modules/ssh/server.go
Normal file
144
modules/ssh/server.go
Normal file
@@ -0,0 +1,144 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"gitea.dev/modules/graceful"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/setting"
|
||||
|
||||
gossh "golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
// sshServer rejects everything but the "session" channel and its "exec" and "shell" requests,
|
||||
// because pty, subsystems and forwarding are of no use to a git client.
|
||||
type sshServer struct {
|
||||
addr string
|
||||
hostSigners []gossh.Signer
|
||||
config gossh.Config
|
||||
}
|
||||
|
||||
type sshSession struct {
|
||||
gossh.Channel
|
||||
conn *gossh.ServerConn
|
||||
ctx context.Context
|
||||
rawCmd string
|
||||
env []string
|
||||
}
|
||||
|
||||
func (srv *sshServer) newServerConfig(ctx context.Context) *gossh.ServerConfig {
|
||||
config := &gossh.ServerConfig{
|
||||
Config: srv.config,
|
||||
PublicKeyCallback: func(conn gossh.ConnMetadata, key gossh.PublicKey) (*gossh.Permissions, error) {
|
||||
return publicKeyHandler(ctx, conn, key)
|
||||
},
|
||||
}
|
||||
for _, signer := range srv.hostSigners {
|
||||
config.AddHostKey(signer) // keeps only the newest key per algorithm
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
func listen(srv *sshServer) {
|
||||
gracefulServer := graceful.NewServer("tcp", srv.addr, "SSH")
|
||||
gracefulServer.PerWriteTimeout = setting.SSH.PerWriteTimeout
|
||||
gracefulServer.PerWritePerKbTimeout = setting.SSH.PerWritePerKbTimeout
|
||||
|
||||
err := gracefulServer.ListenAndServe(srv.serve, setting.SSH.UseProxyProtocol)
|
||||
if err != nil {
|
||||
select {
|
||||
case <-graceful.GetManager().IsShutdown():
|
||||
log.Error("Failed to start SSH server: %v", err)
|
||||
default:
|
||||
log.Fatal("Failed to start SSH server: %v", err)
|
||||
}
|
||||
}
|
||||
log.Info("SSH Listener: %s Closed", srv.addr)
|
||||
}
|
||||
|
||||
// serve is a graceful.ServeFunction
|
||||
func (srv *sshServer) serve(listener net.Listener) error {
|
||||
var acceptDelay time.Duration
|
||||
for {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
// out of file descriptors or an aborted handshake, both recover on their own
|
||||
if !errors.Is(err, syscall.EMFILE) && !errors.Is(err, syscall.ENFILE) && !errors.Is(err, syscall.ECONNABORTED) {
|
||||
return err
|
||||
}
|
||||
acceptDelay = min(max(2*acceptDelay, 5*time.Millisecond), time.Second)
|
||||
log.Warn("SSH: Accept failed, retrying in %s: %v", acceptDelay, err)
|
||||
time.Sleep(acceptDelay)
|
||||
continue
|
||||
}
|
||||
acceptDelay = 0
|
||||
go srv.handleConn(conn)
|
||||
}
|
||||
}
|
||||
|
||||
func (srv *sshServer) handleConn(netConn net.Conn) {
|
||||
ctx, cancel := context.WithCancel(graceful.GetManager().HammerContext())
|
||||
defer cancel()
|
||||
defer netConn.Close()
|
||||
|
||||
conn, chans, reqs, err := gossh.NewServerConn(netConn, srv.newServerConfig(ctx))
|
||||
if err != nil {
|
||||
sshConnectionFailed(netConn, err)
|
||||
return
|
||||
}
|
||||
|
||||
go gossh.DiscardRequests(reqs)
|
||||
for newChan := range chans {
|
||||
if newChan.ChannelType() != "session" {
|
||||
_ = newChan.Reject(gossh.UnknownChannelType, "unsupported channel type")
|
||||
continue
|
||||
}
|
||||
go handleSessionChannel(ctx, conn, newChan)
|
||||
}
|
||||
}
|
||||
|
||||
func handleSessionChannel(ctx context.Context, conn *gossh.ServerConn, newChan gossh.NewChannel) {
|
||||
channel, reqs, err := newChan.Accept()
|
||||
if err != nil {
|
||||
log.Error("SSH: Accept session channel: %v", err)
|
||||
return
|
||||
}
|
||||
defer channel.Close()
|
||||
|
||||
session := &sshSession{Channel: channel, conn: conn, ctx: ctx}
|
||||
for req := range reqs {
|
||||
switch req.Type {
|
||||
case "env":
|
||||
var env struct{ Key, Value string }
|
||||
if gossh.Unmarshal(req.Payload, &env) != nil {
|
||||
_ = req.Reply(false, nil)
|
||||
continue
|
||||
}
|
||||
session.env = append(session.env, env.Key+"="+env.Value)
|
||||
_ = req.Reply(true, nil)
|
||||
case "exec", "shell":
|
||||
var payload struct{ Value string } // a "shell" carries no payload, it runs "gitea serv" without a command
|
||||
if req.Type == "exec" && gossh.Unmarshal(req.Payload, &payload) != nil {
|
||||
_ = req.Reply(false, nil)
|
||||
continue
|
||||
}
|
||||
session.rawCmd = payload.Value
|
||||
_ = req.Reply(true, nil)
|
||||
go gossh.DiscardRequests(reqs) // the client keeps sending while the command runs
|
||||
status := struct{ Status uint32 }{uint32(sessionHandler(session))}
|
||||
if _, err := channel.SendRequest("exit-status", false, gossh.Marshal(&status)); err != nil {
|
||||
log.Error("SSH: Send exit-status: %v", err)
|
||||
}
|
||||
return
|
||||
default:
|
||||
_ = req.Reply(false, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
374
modules/ssh/ssh.go
Normal file
374
modules/ssh/ssh.go
Normal file
@@ -0,0 +1,374 @@
|
||||
// Copyright 2017 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
asymkey_model "gitea.dev/models/asymkey"
|
||||
"gitea.dev/modules/generate"
|
||||
"gitea.dev/modules/graceful"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/process"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/util"
|
||||
|
||||
gossh "golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
const giteaPermissionExtensionKeyID = "gitea-perm-ext-key-id"
|
||||
|
||||
func getExitStatusFromError(err error) int {
|
||||
if err == nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
exitErr, ok := errors.AsType[*exec.ExitError](err)
|
||||
if !ok {
|
||||
return 1
|
||||
}
|
||||
|
||||
waitStatus, ok := exitErr.Sys().(syscall.WaitStatus)
|
||||
if !ok {
|
||||
// This is a fallback and should at least let us return something useful
|
||||
// when running on Windows, even if it isn't completely accurate.
|
||||
if exitErr.Success() {
|
||||
return 0
|
||||
}
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
return waitStatus.ExitStatus()
|
||||
}
|
||||
|
||||
func sessionHandler(session *sshSession) int {
|
||||
// the conn permissions are the ones of the key which really authenticated, see publicKeyHandler
|
||||
keyID := session.conn.Permissions.Extensions[giteaPermissionExtensionKeyID]
|
||||
|
||||
log.Trace("SSH: Payload: %v", session.rawCmd)
|
||||
|
||||
args := []string{"--config=" + setting.CustomConf, "serv", "key-" + keyID}
|
||||
log.Trace("SSH: Arguments: %v", args)
|
||||
|
||||
ctx, cancel := context.WithCancel(session.ctx)
|
||||
defer cancel()
|
||||
|
||||
gitProtocol := ""
|
||||
for _, env := range session.env {
|
||||
if strings.HasPrefix(env, "GIT_PROTOCOL=") {
|
||||
_, gitProtocol, _ = strings.Cut(env, "=")
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
cmd := process.CommandContext(ctx, setting.AppPath, args...)
|
||||
cmd.Env = append(
|
||||
os.Environ(),
|
||||
"SSH_ORIGINAL_COMMAND="+session.rawCmd,
|
||||
"SKIP_MINWINSVC=1",
|
||||
"GIT_PROTOCOL="+gitProtocol,
|
||||
)
|
||||
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
log.Error("SSH: StdoutPipe: %v", err)
|
||||
return 1
|
||||
}
|
||||
defer stdout.Close()
|
||||
|
||||
stderr, err := cmd.StderrPipe()
|
||||
if err != nil {
|
||||
log.Error("SSH: StderrPipe: %v", err)
|
||||
return 1
|
||||
}
|
||||
defer stderr.Close()
|
||||
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
log.Error("SSH: StdinPipe: %v", err)
|
||||
return 1
|
||||
}
|
||||
defer stdin.Close()
|
||||
|
||||
wg := &sync.WaitGroup{}
|
||||
|
||||
if err = cmd.Start(); err != nil {
|
||||
log.Error("SSH: Start: %v", err)
|
||||
return 1
|
||||
}
|
||||
|
||||
go func() {
|
||||
defer stdin.Close()
|
||||
if _, err := io.Copy(stdin, session); err != nil {
|
||||
log.Error("Failed to write session to stdin. %s", err)
|
||||
}
|
||||
}()
|
||||
|
||||
wg.Go(func() {
|
||||
defer stdout.Close()
|
||||
if _, err := io.Copy(session, stdout); err != nil {
|
||||
log.Error("Failed to write stdout to session. %s", err)
|
||||
}
|
||||
})
|
||||
|
||||
wg.Go(func() {
|
||||
defer stderr.Close()
|
||||
if _, err := io.Copy(session.Stderr(), stderr); err != nil {
|
||||
log.Error("Failed to write stderr to session. %s", err)
|
||||
}
|
||||
})
|
||||
|
||||
// Ensure all the output has been written before we wait on the command
|
||||
// to exit.
|
||||
wg.Wait()
|
||||
|
||||
// Wait for the command to exit and log any errors we get
|
||||
err = cmd.Wait()
|
||||
if err != nil {
|
||||
// Cannot use errors.Is here because ExitError doesn't implement Is
|
||||
// Thus errors.Is will do equality test NOT type comparison
|
||||
if _, ok := err.(*exec.ExitError); !ok {
|
||||
log.Error("SSH: Wait: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return getExitStatusFromError(err)
|
||||
}
|
||||
|
||||
func keyPermissions(keyID int64) *gossh.Permissions {
|
||||
return &gossh.Permissions{Extensions: map[string]string{
|
||||
giteaPermissionExtensionKeyID: strconv.FormatInt(keyID, 10),
|
||||
}}
|
||||
}
|
||||
|
||||
// publicKeyHandler only offers the candidate keys, it does not verify them. x/crypto assigns the
|
||||
// returned Permissions to the ssh conn once it verified the signature for that key, so a user
|
||||
// offering keys A (with a private key) and B (without one) authenticates and is served as A.
|
||||
func publicKeyHandler(ctx context.Context, conn gossh.ConnMetadata, key gossh.PublicKey) (*gossh.Permissions, error) {
|
||||
if log.IsDebug() { // <- FingerprintSHA256 is kinda expensive so only calculate it if necessary
|
||||
log.Debug("Handle Public Key: Fingerprint: %s from %s", gossh.FingerprintSHA256(key), conn.RemoteAddr())
|
||||
}
|
||||
|
||||
if conn.User() != setting.SSH.BuiltinServerUser {
|
||||
log.Warn("Invalid SSH username %s - must use %s for all git operations via ssh", conn.User(), setting.SSH.BuiltinServerUser)
|
||||
log.Warn("Failed authentication attempt from %s", conn.RemoteAddr())
|
||||
return nil, util.ErrPermissionDenied
|
||||
}
|
||||
|
||||
// check if we have a certificate
|
||||
if cert, ok := key.(*gossh.Certificate); ok {
|
||||
if log.IsDebug() { // <- FingerprintSHA256 is kinda expensive so only calculate it if necessary
|
||||
log.Debug("Handle Certificate: %s Fingerprint: %s is a certificate", conn.RemoteAddr(), gossh.FingerprintSHA256(key))
|
||||
}
|
||||
|
||||
if len(setting.SSH.TrustedUserCAKeys) == 0 {
|
||||
log.Warn("Certificate Rejected: No trusted certificate authorities for this server")
|
||||
log.Warn("Failed authentication attempt from %s", conn.RemoteAddr())
|
||||
return nil, util.ErrPermissionDenied
|
||||
}
|
||||
|
||||
if cert.CertType != gossh.UserCert {
|
||||
log.Warn("Certificate Rejected: Not a user certificate")
|
||||
log.Warn("Failed authentication attempt from %s", conn.RemoteAddr())
|
||||
return nil, util.ErrPermissionDenied
|
||||
}
|
||||
|
||||
// look for the exact principal
|
||||
principalLoop:
|
||||
for _, principal := range cert.ValidPrincipals {
|
||||
pkey, err := asymkey_model.SearchPublicKeyByContentExact(ctx, principal)
|
||||
if err != nil {
|
||||
if asymkey_model.IsErrKeyNotExist(err) {
|
||||
log.Debug("Principal Rejected: %s Unknown Principal: %s", conn.RemoteAddr(), principal)
|
||||
continue principalLoop
|
||||
}
|
||||
log.Error("SearchPublicKeyByContentExact: %v", err)
|
||||
return nil, util.ErrPermissionDenied
|
||||
}
|
||||
|
||||
c := &gossh.CertChecker{
|
||||
IsUserAuthority: func(auth gossh.PublicKey) bool {
|
||||
marshaled := auth.Marshal()
|
||||
for _, k := range setting.SSH.TrustedUserCAKeysParsed {
|
||||
if bytes.Equal(marshaled, k.Marshal()) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
},
|
||||
}
|
||||
|
||||
// check the CA of the cert
|
||||
if !c.IsUserAuthority(cert.SignatureKey) {
|
||||
if log.IsDebug() {
|
||||
log.Debug("Principal Rejected: %s Untrusted Authority Signature Fingerprint %s for Principal: %s", conn.RemoteAddr(), gossh.FingerprintSHA256(cert.SignatureKey), principal)
|
||||
}
|
||||
continue principalLoop
|
||||
}
|
||||
|
||||
// validate the cert for this principal
|
||||
if err := c.CheckCert(principal, cert); err != nil {
|
||||
// User is presenting an invalid certificate - STOP any further processing
|
||||
log.Error("Invalid Certificate KeyID %s with Signature Fingerprint %s presented for Principal: %s from %s", cert.KeyId, gossh.FingerprintSHA256(cert.SignatureKey), principal, conn.RemoteAddr())
|
||||
log.Warn("Failed authentication attempt from %s", conn.RemoteAddr())
|
||||
|
||||
return nil, util.ErrPermissionDenied
|
||||
}
|
||||
|
||||
if log.IsDebug() { // <- FingerprintSHA256 is kinda expensive so only calculate it if necessary
|
||||
log.Debug("Successfully authenticated: %s Certificate Fingerprint: %s Principal: %s", conn.RemoteAddr(), gossh.FingerprintSHA256(key), principal)
|
||||
}
|
||||
return keyPermissions(pkey.ID), nil
|
||||
}
|
||||
|
||||
log.Warn("From %s Fingerprint: %s is a certificate, but no valid principals found", conn.RemoteAddr(), gossh.FingerprintSHA256(key))
|
||||
log.Warn("Failed authentication attempt from %s", conn.RemoteAddr())
|
||||
return nil, util.ErrPermissionDenied
|
||||
}
|
||||
|
||||
if log.IsDebug() { // <- FingerprintSHA256 is kinda expensive so only calculate it if necessary
|
||||
log.Debug("Handle Public Key: %s Fingerprint: %s is not a certificate", conn.RemoteAddr(), gossh.FingerprintSHA256(key))
|
||||
}
|
||||
|
||||
pkey, err := asymkey_model.SearchPublicKeyByContent(ctx, strings.TrimSpace(string(gossh.MarshalAuthorizedKey(key))))
|
||||
if err != nil {
|
||||
if asymkey_model.IsErrKeyNotExist(err) {
|
||||
log.Warn("Unknown public key: %s from %s", gossh.FingerprintSHA256(key), conn.RemoteAddr())
|
||||
log.Warn("Failed authentication attempt from %s", conn.RemoteAddr())
|
||||
return nil, util.ErrPermissionDenied
|
||||
}
|
||||
log.Error("SearchPublicKeyByContent: %v", err)
|
||||
return nil, util.ErrPermissionDenied
|
||||
}
|
||||
|
||||
if log.IsDebug() { // <- FingerprintSHA256 is kinda expensive so only calculate it if necessary
|
||||
log.Debug("Successfully authenticated: %s Public Key Fingerprint: %s", conn.RemoteAddr(), gossh.FingerprintSHA256(key))
|
||||
}
|
||||
return keyPermissions(pkey.ID), nil
|
||||
}
|
||||
|
||||
// sshConnectionFailed logs a failed connection
|
||||
// - this mainly exists to give a nice function name in logging
|
||||
func sshConnectionFailed(conn net.Conn, err error) {
|
||||
// Log the underlying error with a specific message
|
||||
log.Warn("Failed connection from %s with error: %v", conn.RemoteAddr(), err)
|
||||
// Log with the standard failed authentication from message for simpler fail2ban configuration
|
||||
log.Warn("Failed authentication attempt from %s", conn.RemoteAddr())
|
||||
}
|
||||
|
||||
// Listen starts an SSH server listening on given port.
|
||||
func Listen(host string, port int, ciphers, keyExchanges, macs []string) {
|
||||
hostKeyFiles := make([]string, 0, len(setting.SSH.ServerHostKeys))
|
||||
for _, key := range setting.SSH.ServerHostKeys {
|
||||
_, err := os.Stat(key)
|
||||
if err != nil {
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
log.Fatal("Unable to check if %s exists. Error: %v", setting.SSH.ServerHostKeys, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
hostKeyFiles = append(hostKeyFiles, key)
|
||||
}
|
||||
|
||||
if len(hostKeyFiles) == 0 {
|
||||
hostKeyDir := filepath.Dir(setting.SSH.ServerHostKeys[0])
|
||||
err := os.MkdirAll(hostKeyDir, os.ModePerm)
|
||||
if err != nil {
|
||||
log.Error("Failed to create dir %s: %v", hostKeyDir, err)
|
||||
}
|
||||
hostKeyFiles, err = InitDefaultHostKeys(hostKeyDir)
|
||||
if err != nil {
|
||||
log.Fatal("Failed to generate private key: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
var hostSigners []gossh.Signer
|
||||
for _, keyFile := range hostKeyFiles {
|
||||
pemBytes, err := os.ReadFile(keyFile)
|
||||
if err == nil {
|
||||
var signer gossh.Signer
|
||||
if signer, err = gossh.ParsePrivateKey(pemBytes); err == nil {
|
||||
log.Info("Adding SSH host key: %s", keyFile)
|
||||
hostSigners = append(hostSigners, signer)
|
||||
continue
|
||||
}
|
||||
}
|
||||
log.Error("Failed to load SSH host key %s: %v", keyFile, err)
|
||||
}
|
||||
|
||||
if len(hostSigners) == 0 {
|
||||
log.Fatal("No usable SSH host key, tried: %v", hostKeyFiles)
|
||||
}
|
||||
|
||||
srv := &sshServer{
|
||||
addr: net.JoinHostPort(host, strconv.Itoa(port)),
|
||||
hostSigners: hostSigners,
|
||||
config: gossh.Config{Ciphers: ciphers, KeyExchanges: keyExchanges, MACs: macs},
|
||||
}
|
||||
|
||||
go func() {
|
||||
_, _, finished := process.GetManager().AddTypedContext(graceful.GetManager().HammerContext(), "Service: Built-in SSH server", process.SystemProcessType, true)
|
||||
defer finished()
|
||||
listen(srv)
|
||||
}()
|
||||
}
|
||||
|
||||
// GenKeyPair make a pair of public and private keys for SSH access.
|
||||
// Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file.
|
||||
// Private Key generated is PEM encoded
|
||||
func GenKeyPair(keyPath string, keyType generate.SSHKeyType, bits int) error {
|
||||
publicKey, privateKeyPEM, err := generate.NewSSHKey(keyType, bits)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
public := gossh.MarshalAuthorizedKey(publicKey)
|
||||
privateKeyBuf := &bytes.Buffer{}
|
||||
err = pem.Encode(privateKeyBuf, privateKeyPEM)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = os.WriteFile(keyPath, privateKeyBuf.Bytes(), 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.WriteFile(keyPath+".pub", public, 0o644)
|
||||
}
|
||||
|
||||
// InitDefaultHostKeys mirrors how ssh-keygen -A operates
|
||||
// it runs checks if public and private keys are already defined and creates new ones if not present
|
||||
// key naming does not follow the OpenSSH convention due to existing settings being gitea.{KeyType} so generation follows gitea convention
|
||||
func InitDefaultHostKeys(path string) (keyFiles []string, _ error) {
|
||||
var errs []error
|
||||
keyTypes := []generate.SSHKeyType{generate.SSHKeyRSA, generate.SSHKeyECDSA, generate.SSHKeyED25519}
|
||||
for _, keyType := range keyTypes {
|
||||
keyPath := filepath.Join(path, "gitea."+string(keyType))
|
||||
_, errStatPriv := os.Stat(keyPath)
|
||||
if errStatPriv != nil {
|
||||
err := GenKeyPair(keyPath, keyType, 0)
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
keyFiles = append(keyFiles, keyPath)
|
||||
}
|
||||
return keyFiles, errors.Join(errs...)
|
||||
}
|
||||
124
modules/ssh/ssh_test.go
Normal file
124
modules/ssh/ssh_test.go
Normal file
@@ -0,0 +1,124 @@
|
||||
// Copyright 2025 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/ed25519"
|
||||
"crypto/rsa"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"gitea.dev/modules/generate"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
gossh "golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
func TestGenKeyPair(t *testing.T) {
|
||||
testCases := []struct {
|
||||
keyType generate.SSHKeyType
|
||||
expectedType any
|
||||
}{
|
||||
{
|
||||
keyType: generate.SSHKeyRSA,
|
||||
expectedType: &rsa.PrivateKey{},
|
||||
},
|
||||
{
|
||||
keyType: generate.SSHKeyED25519,
|
||||
expectedType: &ed25519.PrivateKey{},
|
||||
},
|
||||
{
|
||||
keyType: generate.SSHKeyECDSA,
|
||||
expectedType: &ecdsa.PrivateKey{},
|
||||
},
|
||||
}
|
||||
tmpDir := t.TempDir()
|
||||
for _, tc := range testCases {
|
||||
name := "gitea." + string(tc.keyType)
|
||||
fn := filepath.Join(tmpDir, name)
|
||||
t.Run("Generate "+name, func(t *testing.T) {
|
||||
require.NoError(t, GenKeyPair(fn, tc.keyType, 0))
|
||||
|
||||
bytes, err := os.ReadFile(fn)
|
||||
require.NoError(t, err)
|
||||
|
||||
privateKey, err := gossh.ParseRawPrivateKey(bytes)
|
||||
require.NoError(t, err)
|
||||
assert.IsType(t, tc.expectedType, privateKey)
|
||||
})
|
||||
}
|
||||
t.Run("Generate unknown key type", func(t *testing.T) {
|
||||
err := GenKeyPair(t.TempDir()+"gitea.badkey", "badkey", 0)
|
||||
require.Error(t, err)
|
||||
})
|
||||
}
|
||||
|
||||
func TestInitKeys(t *testing.T) {
|
||||
tempDir := t.TempDir()
|
||||
|
||||
keyTypes := []string{"rsa", "ecdsa", "ed25519"}
|
||||
for _, keyType := range keyTypes {
|
||||
privKeyPath := filepath.Join(tempDir, "gitea."+keyType)
|
||||
pubKeyPath := filepath.Join(tempDir, "gitea."+keyType+".pub")
|
||||
assert.NoFileExists(t, privKeyPath)
|
||||
assert.NoFileExists(t, pubKeyPath)
|
||||
}
|
||||
|
||||
// Test basic creation
|
||||
keyFiles, err := InitDefaultHostKeys(tempDir)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, keyFiles, len(keyTypes))
|
||||
|
||||
// Record file contents so regeneration can be detected
|
||||
content := map[string][]byte{}
|
||||
for _, keyType := range keyTypes {
|
||||
privKeyPath := filepath.Join(tempDir, "gitea."+keyType)
|
||||
pubKeyPath := filepath.Join(tempDir, "gitea."+keyType+".pub")
|
||||
data, err := os.ReadFile(privKeyPath)
|
||||
require.NoError(t, err)
|
||||
content[privKeyPath] = data
|
||||
|
||||
data, err = os.ReadFile(pubKeyPath)
|
||||
require.NoError(t, err)
|
||||
content[pubKeyPath] = data
|
||||
}
|
||||
|
||||
// Test recreation on missing private key and noop for missing pub key
|
||||
require.NoError(t, os.Remove(filepath.Join(tempDir, "gitea.ecdsa.pub")))
|
||||
require.NoError(t, os.Remove(filepath.Join(tempDir, "gitea.ed25519")))
|
||||
|
||||
keyFiles, err = InitDefaultHostKeys(tempDir)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, keyFiles, len(keyTypes))
|
||||
|
||||
for _, keyType := range keyTypes {
|
||||
privKeyPath := filepath.Join(tempDir, "gitea."+keyType)
|
||||
pubKeyPath := filepath.Join(tempDir, "gitea."+keyType+".pub")
|
||||
|
||||
dataPriv, err := os.ReadFile(privKeyPath)
|
||||
require.NoError(t, err)
|
||||
|
||||
switch keyType {
|
||||
case "rsa":
|
||||
// No modification to RSA key
|
||||
dataPub, err := os.ReadFile(pubKeyPath)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, content[privKeyPath], dataPriv)
|
||||
assert.Equal(t, content[pubKeyPath], dataPub)
|
||||
case "ecdsa":
|
||||
// ECDSA public key should be missing, private unchanged
|
||||
assert.Equal(t, content[privKeyPath], dataPriv)
|
||||
assert.NoFileExists(t, pubKeyPath)
|
||||
case "ed25519":
|
||||
// ed25519 private key was removed, so both keys regenerated
|
||||
dataPub, err := os.ReadFile(pubKeyPath)
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, content[privKeyPath], dataPriv)
|
||||
assert.NotEqual(t, content[pubKeyPath], dataPub)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user