You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

keys.go 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package cmd
  4. import (
  5. "errors"
  6. "fmt"
  7. "strings"
  8. "code.gitea.io/gitea/modules/log"
  9. "code.gitea.io/gitea/modules/private"
  10. "github.com/urfave/cli/v2"
  11. )
  12. // CmdKeys represents the available keys sub-command
  13. var CmdKeys = &cli.Command{
  14. Name: "keys",
  15. Usage: "(internal) Should only be called by SSH server",
  16. Description: "Queries the Gitea database to get the authorized command for a given ssh key fingerprint",
  17. Before: PrepareConsoleLoggerLevel(log.FATAL),
  18. Action: runKeys,
  19. Flags: []cli.Flag{
  20. &cli.StringFlag{
  21. Name: "expected",
  22. Aliases: []string{"e"},
  23. Value: "git",
  24. Usage: "Expected user for whom provide key commands",
  25. },
  26. &cli.StringFlag{
  27. Name: "username",
  28. Aliases: []string{"u"},
  29. Value: "",
  30. Usage: "Username trying to log in by SSH",
  31. },
  32. &cli.StringFlag{
  33. Name: "type",
  34. Aliases: []string{"t"},
  35. Value: "",
  36. Usage: "Type of the SSH key provided to the SSH Server (requires content to be provided too)",
  37. },
  38. &cli.StringFlag{
  39. Name: "content",
  40. Aliases: []string{"k"},
  41. Value: "",
  42. Usage: "Base64 encoded content of the SSH key provided to the SSH Server (requires type to be provided too)",
  43. },
  44. },
  45. }
  46. func runKeys(c *cli.Context) error {
  47. if !c.IsSet("username") {
  48. return errors.New("No username provided")
  49. }
  50. // Check username matches the expected username
  51. if strings.TrimSpace(c.String("username")) != strings.TrimSpace(c.String("expected")) {
  52. return nil
  53. }
  54. content := ""
  55. if c.IsSet("type") && c.IsSet("content") {
  56. content = fmt.Sprintf("%s %s", strings.TrimSpace(c.String("type")), strings.TrimSpace(c.String("content")))
  57. }
  58. if content == "" {
  59. return errors.New("No key type and content provided")
  60. }
  61. ctx, cancel := installSignals()
  62. defer cancel()
  63. setup(ctx, c.Bool("debug"))
  64. authorizedString, extra := private.AuthorizedPublicKeyByContent(ctx, content)
  65. // do not use handleCliResponseExtra or cli.NewExitError, if it exists immediately, it breaks some tests like Test_CmdKeys
  66. if extra.Error != nil {
  67. return extra.Error
  68. }
  69. _, _ = fmt.Fprintln(c.App.Writer, strings.TrimSpace(authorizedString.Text))
  70. return nil
  71. }