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