code.gitea.io/gitea@v1.21.7/cmd/serv.go (about)

     1  // Copyright 2014 The Gogs Authors. All rights reserved.
     2  // Copyright 2016 The Gitea Authors. All rights reserved.
     3  // SPDX-License-Identifier: MIT
     4  
     5  package cmd
     6  
     7  import (
     8  	"context"
     9  	"fmt"
    10  	"net/url"
    11  	"os"
    12  	"os/exec"
    13  	"path/filepath"
    14  	"regexp"
    15  	"strconv"
    16  	"strings"
    17  	"time"
    18  	"unicode"
    19  
    20  	asymkey_model "code.gitea.io/gitea/models/asymkey"
    21  	git_model "code.gitea.io/gitea/models/git"
    22  	"code.gitea.io/gitea/models/perm"
    23  	"code.gitea.io/gitea/modules/git"
    24  	"code.gitea.io/gitea/modules/json"
    25  	"code.gitea.io/gitea/modules/log"
    26  	"code.gitea.io/gitea/modules/pprof"
    27  	"code.gitea.io/gitea/modules/private"
    28  	"code.gitea.io/gitea/modules/process"
    29  	repo_module "code.gitea.io/gitea/modules/repository"
    30  	"code.gitea.io/gitea/modules/setting"
    31  	"code.gitea.io/gitea/services/lfs"
    32  
    33  	"github.com/golang-jwt/jwt/v5"
    34  	"github.com/kballard/go-shellquote"
    35  	"github.com/urfave/cli/v2"
    36  )
    37  
    38  const (
    39  	lfsAuthenticateVerb = "git-lfs-authenticate"
    40  )
    41  
    42  // CmdServ represents the available serv sub-command.
    43  var CmdServ = &cli.Command{
    44  	Name:        "serv",
    45  	Usage:       "This command should only be called by SSH shell",
    46  	Description: "Serv provides access auth for repositories",
    47  	Before:      PrepareConsoleLoggerLevel(log.FATAL),
    48  	Action:      runServ,
    49  	Flags: []cli.Flag{
    50  		&cli.BoolFlag{
    51  			Name: "enable-pprof",
    52  		},
    53  		&cli.BoolFlag{
    54  			Name: "debug",
    55  		},
    56  	},
    57  }
    58  
    59  func setup(ctx context.Context, debug bool) {
    60  	if debug {
    61  		setupConsoleLogger(log.TRACE, false, os.Stderr)
    62  	} else {
    63  		setupConsoleLogger(log.FATAL, false, os.Stderr)
    64  	}
    65  	setting.MustInstalled()
    66  	if debug {
    67  		setting.RunMode = "dev"
    68  	}
    69  
    70  	// Check if setting.RepoRootPath exists. It could be the case that it doesn't exist, this can happen when
    71  	// `[repository]` `ROOT` is a relative path and $GITEA_WORK_DIR isn't passed to the SSH connection.
    72  	if _, err := os.Stat(setting.RepoRootPath); err != nil {
    73  		if os.IsNotExist(err) {
    74  			_ = fail(ctx, "Incorrect configuration, no repository directory.", "Directory `[repository].ROOT` %q was not found, please check if $GITEA_WORK_DIR is passed to the SSH connection or make `[repository].ROOT` an absolute value.", setting.RepoRootPath)
    75  		} else {
    76  			_ = fail(ctx, "Incorrect configuration, repository directory is inaccessible", "Directory `[repository].ROOT` %q is inaccessible. err: %v", setting.RepoRootPath, err)
    77  		}
    78  		return
    79  	}
    80  
    81  	if err := git.InitSimple(context.Background()); err != nil {
    82  		_ = fail(ctx, "Failed to init git", "Failed to init git, err: %v", err)
    83  	}
    84  }
    85  
    86  var (
    87  	allowedCommands = map[string]perm.AccessMode{
    88  		"git-upload-pack":    perm.AccessModeRead,
    89  		"git-upload-archive": perm.AccessModeRead,
    90  		"git-receive-pack":   perm.AccessModeWrite,
    91  		lfsAuthenticateVerb:  perm.AccessModeNone,
    92  	}
    93  	alphaDashDotPattern = regexp.MustCompile(`[^\w-\.]`)
    94  )
    95  
    96  // fail prints message to stdout, it's mainly used for git serv and git hook commands.
    97  // The output will be passed to git client and shown to user.
    98  func fail(ctx context.Context, userMessage, logMsgFmt string, args ...any) error {
    99  	if userMessage == "" {
   100  		userMessage = "Internal Server Error (no specific error)"
   101  	}
   102  
   103  	// There appears to be a chance to cause a zombie process and failure to read the Exit status
   104  	// if nothing is outputted on stdout.
   105  	_, _ = fmt.Fprintln(os.Stdout, "")
   106  	_, _ = fmt.Fprintln(os.Stderr, "Gitea:", userMessage)
   107  
   108  	if logMsgFmt != "" {
   109  		logMsg := fmt.Sprintf(logMsgFmt, args...)
   110  		if !setting.IsProd {
   111  			_, _ = fmt.Fprintln(os.Stderr, "Gitea:", logMsg)
   112  		}
   113  		if userMessage != "" {
   114  			if unicode.IsPunct(rune(userMessage[len(userMessage)-1])) {
   115  				logMsg = userMessage + " " + logMsg
   116  			} else {
   117  				logMsg = userMessage + ". " + logMsg
   118  			}
   119  		}
   120  		_ = private.SSHLog(ctx, true, logMsg)
   121  	}
   122  	return cli.Exit("", 1)
   123  }
   124  
   125  // handleCliResponseExtra handles the extra response from the cli sub-commands
   126  // If there is a user message it will be printed to stdout
   127  // If the command failed it will return an error (the error will be printed by cli framework)
   128  func handleCliResponseExtra(extra private.ResponseExtra) error {
   129  	if extra.UserMsg != "" {
   130  		_, _ = fmt.Fprintln(os.Stdout, extra.UserMsg)
   131  	}
   132  	if extra.HasError() {
   133  		return cli.Exit(extra.Error, 1)
   134  	}
   135  	return nil
   136  }
   137  
   138  func runServ(c *cli.Context) error {
   139  	ctx, cancel := installSignals()
   140  	defer cancel()
   141  
   142  	// FIXME: This needs to internationalised
   143  	setup(ctx, c.Bool("debug"))
   144  
   145  	if setting.SSH.Disabled {
   146  		println("Gitea: SSH has been disabled")
   147  		return nil
   148  	}
   149  
   150  	if c.NArg() < 1 {
   151  		if err := cli.ShowSubcommandHelp(c); err != nil {
   152  			fmt.Printf("error showing subcommand help: %v\n", err)
   153  		}
   154  		return nil
   155  	}
   156  
   157  	keys := strings.Split(c.Args().First(), "-")
   158  	if len(keys) != 2 || keys[0] != "key" {
   159  		return fail(ctx, "Key ID format error", "Invalid key argument: %s", c.Args().First())
   160  	}
   161  	keyID, err := strconv.ParseInt(keys[1], 10, 64)
   162  	if err != nil {
   163  		return fail(ctx, "Key ID parsing error", "Invalid key argument: %s", c.Args().Get(1))
   164  	}
   165  
   166  	cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
   167  	if len(cmd) == 0 {
   168  		key, user, err := private.ServNoCommand(ctx, keyID)
   169  		if err != nil {
   170  			return fail(ctx, "Key check failed", "Failed to check provided key: %v", err)
   171  		}
   172  		switch key.Type {
   173  		case asymkey_model.KeyTypeDeploy:
   174  			println("Hi there! You've successfully authenticated with the deploy key named " + key.Name + ", but Gitea does not provide shell access.")
   175  		case asymkey_model.KeyTypePrincipal:
   176  			println("Hi there! You've successfully authenticated with the principal " + key.Content + ", but Gitea does not provide shell access.")
   177  		default:
   178  			println("Hi there, " + user.Name + "! You've successfully authenticated with the key named " + key.Name + ", but Gitea does not provide shell access.")
   179  		}
   180  		println("If this is unexpected, please log in with password and setup Gitea under another user.")
   181  		return nil
   182  	} else if c.Bool("debug") {
   183  		log.Debug("SSH_ORIGINAL_COMMAND: %s", os.Getenv("SSH_ORIGINAL_COMMAND"))
   184  	}
   185  
   186  	words, err := shellquote.Split(cmd)
   187  	if err != nil {
   188  		return fail(ctx, "Error parsing arguments", "Failed to parse arguments: %v", err)
   189  	}
   190  
   191  	if len(words) < 2 {
   192  		if git.CheckGitVersionAtLeast("2.29") == nil {
   193  			// for AGit Flow
   194  			if cmd == "ssh_info" {
   195  				fmt.Print(`{"type":"gitea","version":1}`)
   196  				return nil
   197  			}
   198  		}
   199  		return fail(ctx, "Too few arguments", "Too few arguments in cmd: %s", cmd)
   200  	}
   201  
   202  	verb := words[0]
   203  	repoPath := words[1]
   204  	if repoPath[0] == '/' {
   205  		repoPath = repoPath[1:]
   206  	}
   207  
   208  	var lfsVerb string
   209  	if verb == lfsAuthenticateVerb {
   210  		if !setting.LFS.StartServer {
   211  			return fail(ctx, "Unknown git command", "LFS authentication request over SSH denied, LFS support is disabled")
   212  		}
   213  
   214  		if len(words) > 2 {
   215  			lfsVerb = words[2]
   216  		}
   217  	}
   218  
   219  	rr := strings.SplitN(repoPath, "/", 2)
   220  	if len(rr) != 2 {
   221  		return fail(ctx, "Invalid repository path", "Invalid repository path: %v", repoPath)
   222  	}
   223  
   224  	username := rr[0]
   225  	reponame := strings.TrimSuffix(rr[1], ".git")
   226  
   227  	// LowerCase and trim the repoPath as that's how they are stored.
   228  	// This should be done after splitting the repoPath into username and reponame
   229  	// so that username and reponame are not affected.
   230  	repoPath = strings.ToLower(strings.TrimSpace(repoPath))
   231  
   232  	if alphaDashDotPattern.MatchString(reponame) {
   233  		return fail(ctx, "Invalid repo name", "Invalid repo name: %s", reponame)
   234  	}
   235  
   236  	if c.Bool("enable-pprof") {
   237  		if err := os.MkdirAll(setting.PprofDataPath, os.ModePerm); err != nil {
   238  			return fail(ctx, "Error while trying to create PPROF_DATA_PATH", "Error while trying to create PPROF_DATA_PATH: %v", err)
   239  		}
   240  
   241  		stopCPUProfiler, err := pprof.DumpCPUProfileForUsername(setting.PprofDataPath, username)
   242  		if err != nil {
   243  			return fail(ctx, "Unable to start CPU profiler", "Unable to start CPU profile: %v", err)
   244  		}
   245  		defer func() {
   246  			stopCPUProfiler()
   247  			err := pprof.DumpMemProfileForUsername(setting.PprofDataPath, username)
   248  			if err != nil {
   249  				_ = fail(ctx, "Unable to dump Mem profile", "Unable to dump Mem Profile: %v", err)
   250  			}
   251  		}()
   252  	}
   253  
   254  	requestedMode, has := allowedCommands[verb]
   255  	if !has {
   256  		return fail(ctx, "Unknown git command", "Unknown git command %s", verb)
   257  	}
   258  
   259  	if verb == lfsAuthenticateVerb {
   260  		if lfsVerb == "upload" {
   261  			requestedMode = perm.AccessModeWrite
   262  		} else if lfsVerb == "download" {
   263  			requestedMode = perm.AccessModeRead
   264  		} else {
   265  			return fail(ctx, "Unknown LFS verb", "Unknown lfs verb %s", lfsVerb)
   266  		}
   267  	}
   268  
   269  	results, extra := private.ServCommand(ctx, keyID, username, reponame, requestedMode, verb, lfsVerb)
   270  	if extra.HasError() {
   271  		return fail(ctx, extra.UserMsg, "ServCommand failed: %s", extra.Error)
   272  	}
   273  
   274  	// LFS token authentication
   275  	if verb == lfsAuthenticateVerb {
   276  		url := fmt.Sprintf("%s%s/%s.git/info/lfs", setting.AppURL, url.PathEscape(results.OwnerName), url.PathEscape(results.RepoName))
   277  
   278  		now := time.Now()
   279  		claims := lfs.Claims{
   280  			RegisteredClaims: jwt.RegisteredClaims{
   281  				ExpiresAt: jwt.NewNumericDate(now.Add(setting.LFS.HTTPAuthExpiry)),
   282  				NotBefore: jwt.NewNumericDate(now),
   283  			},
   284  			RepoID: results.RepoID,
   285  			Op:     lfsVerb,
   286  			UserID: results.UserID,
   287  		}
   288  		token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
   289  
   290  		// Sign and get the complete encoded token as a string using the secret
   291  		tokenString, err := token.SignedString(setting.LFS.JWTSecretBytes)
   292  		if err != nil {
   293  			return fail(ctx, "Failed to sign JWT Token", "Failed to sign JWT token: %v", err)
   294  		}
   295  
   296  		tokenAuthentication := &git_model.LFSTokenResponse{
   297  			Header: make(map[string]string),
   298  			Href:   url,
   299  		}
   300  		tokenAuthentication.Header["Authorization"] = fmt.Sprintf("Bearer %s", tokenString)
   301  
   302  		enc := json.NewEncoder(os.Stdout)
   303  		err = enc.Encode(tokenAuthentication)
   304  		if err != nil {
   305  			return fail(ctx, "Failed to encode LFS json response", "Failed to encode LFS json response: %v", err)
   306  		}
   307  		return nil
   308  	}
   309  
   310  	var gitcmd *exec.Cmd
   311  	gitBinPath := filepath.Dir(git.GitExecutable) // e.g. /usr/bin
   312  	gitBinVerb := filepath.Join(gitBinPath, verb) // e.g. /usr/bin/git-upload-pack
   313  	if _, err := os.Stat(gitBinVerb); err != nil {
   314  		// if the command "git-upload-pack" doesn't exist, try to split "git-upload-pack" to use the sub-command with git
   315  		// ps: Windows only has "git.exe" in the bin path, so Windows always uses this way
   316  		verbFields := strings.SplitN(verb, "-", 2)
   317  		if len(verbFields) == 2 {
   318  			// use git binary with the sub-command part: "C:\...\bin\git.exe", "upload-pack", ...
   319  			gitcmd = exec.CommandContext(ctx, git.GitExecutable, verbFields[1], repoPath)
   320  		}
   321  	}
   322  	if gitcmd == nil {
   323  		// by default, use the verb (it has been checked above by allowedCommands)
   324  		gitcmd = exec.CommandContext(ctx, gitBinVerb, repoPath)
   325  	}
   326  
   327  	process.SetSysProcAttribute(gitcmd)
   328  	gitcmd.Dir = setting.RepoRootPath
   329  	gitcmd.Stdout = os.Stdout
   330  	gitcmd.Stdin = os.Stdin
   331  	gitcmd.Stderr = os.Stderr
   332  	gitcmd.Env = append(gitcmd.Env, os.Environ()...)
   333  	gitcmd.Env = append(gitcmd.Env,
   334  		repo_module.EnvRepoIsWiki+"="+strconv.FormatBool(results.IsWiki),
   335  		repo_module.EnvRepoName+"="+results.RepoName,
   336  		repo_module.EnvRepoUsername+"="+results.OwnerName,
   337  		repo_module.EnvPusherName+"="+results.UserName,
   338  		repo_module.EnvPusherEmail+"="+results.UserEmail,
   339  		repo_module.EnvPusherID+"="+strconv.FormatInt(results.UserID, 10),
   340  		repo_module.EnvRepoID+"="+strconv.FormatInt(results.RepoID, 10),
   341  		repo_module.EnvPRID+"="+fmt.Sprintf("%d", 0),
   342  		repo_module.EnvDeployKeyID+"="+fmt.Sprintf("%d", results.DeployKeyID),
   343  		repo_module.EnvKeyID+"="+fmt.Sprintf("%d", results.KeyID),
   344  		repo_module.EnvAppURL+"="+setting.AppURL,
   345  	)
   346  	// to avoid breaking, here only use the minimal environment variables for the "gitea serv" command.
   347  	// it could be re-considered whether to use the same git.CommonGitCmdEnvs() as "git" command later.
   348  	gitcmd.Env = append(gitcmd.Env, git.CommonCmdServEnvs()...)
   349  
   350  	if err = gitcmd.Run(); err != nil {
   351  		return fail(ctx, "Failed to execute git command", "Failed to execute git command: %v", err)
   352  	}
   353  
   354  	// Update user key activity.
   355  	if results.KeyID > 0 {
   356  		if err = private.UpdatePublicKeyInRepo(ctx, results.KeyID, results.RepoID); err != nil {
   357  			return fail(ctx, "Failed to update public key", "UpdatePublicKeyInRepo: %v", err)
   358  		}
   359  	}
   360  
   361  	return nil
   362  }