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.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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: "This command queries the Gitea database to get the authorized command for a given ssh key fingerprint",
  16. Before: PrepareConsoleLoggerLevel(log.FATAL),
  17. Action: runKeys,
  18. Flags: []cli.Flag{
  19. &cli.StringFlag{
  20. Name: "expected",
  21. Aliases: []string{"e"},
  22. Value: "git",
  23. Usage: "Expected user for whom provide key commands",
  24. },
  25. &cli.StringFlag{
  26. Name: "username",
  27. Aliases: []string{"u"},
  28. Value: "",
  29. Usage: "Username trying to log in by SSH",
  30. },
  31. &cli.StringFlag{
  32. Name: "type",
  33. Aliases: []string{"t"},
  34. Value: "",
  35. Usage: "Type of the SSH key provided to the SSH Server (requires content to be provided too)",
  36. },
  37. &cli.StringFlag{
  38. Name: "content",
  39. Aliases: []string{"k"},
  40. Value: "",
  41. Usage: "Base64 encoded content of the SSH key provided to the SSH Server (requires type to be provided too)",
  42. },
  43. },
  44. }
  45. func runKeys(c *cli.Context) error {
  46. if !c.IsSet("username") {
  47. return errors.New("No username provided")
  48. }
  49. // Check username matches the expected username
  50. if strings.TrimSpace(c.String("username")) != strings.TrimSpace(c.String("expected")) {
  51. return nil
  52. }
  53. content := ""
  54. if c.IsSet("type") && c.IsSet("content") {
  55. content = fmt.Sprintf("%s %s", strings.TrimSpace(c.String("type")), strings.TrimSpace(c.String("content")))
  56. }
  57. if content == "" {
  58. return errors.New("No key type and content provided")
  59. }
  60. ctx, cancel := installSignals()
  61. defer cancel()
  62. setup(ctx, false)
  63. authorizedString, extra := private.AuthorizedPublicKeyByContent(ctx, content)
  64. // do not use handleCliResponseExtra or cli.NewExitError, if it exists immediately, it breaks some tests like Test_CmdKeys
  65. if extra.Error != nil {
  66. return extra.Error
  67. }
  68. _, _ = fmt.Fprintln(c.App.Writer, strings.TrimSpace(authorizedString))
  69. return nil
  70. }