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.

ssh_key_authorized_keys.go 4.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package asymkey
  4. import (
  5. "bufio"
  6. "context"
  7. "fmt"
  8. "io"
  9. "os"
  10. "path/filepath"
  11. "strings"
  12. "sync"
  13. "code.gitea.io/gitea/models/db"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/util"
  17. )
  18. // _____ __ .__ .__ .___
  19. // / _ \ __ ___/ |_| |__ ___________|__|_______ ____ __| _/
  20. // / /_\ \| | \ __\ | \ / _ \_ __ \ \___ // __ \ / __ |
  21. // / | \ | /| | | Y ( <_> ) | \/ |/ /\ ___// /_/ |
  22. // \____|__ /____/ |__| |___| /\____/|__| |__/_____ \\___ >____ |
  23. // \/ \/ \/ \/ \/
  24. // ____ __.
  25. // | |/ _|____ ___.__. ______
  26. // | <_/ __ < | |/ ___/
  27. // | | \ ___/\___ |\___ \
  28. // |____|__ \___ > ____/____ >
  29. // \/ \/\/ \/
  30. //
  31. // This file contains functions for creating authorized_keys files
  32. //
  33. // There is a dependence on the database within RegeneratePublicKeys however most of these functions probably belong in a module
  34. const (
  35. tplCommentPrefix = `# gitea public key`
  36. tplPublicKey = tplCommentPrefix + "\n" + `command=%s,no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty,no-user-rc,restrict %s` + "\n"
  37. )
  38. var sshOpLocker sync.Mutex
  39. func WithSSHOpLocker(f func() error) error {
  40. sshOpLocker.Lock()
  41. defer sshOpLocker.Unlock()
  42. return f()
  43. }
  44. // AuthorizedStringForKey creates the authorized keys string appropriate for the provided key
  45. func AuthorizedStringForKey(key *PublicKey) string {
  46. sb := &strings.Builder{}
  47. _ = setting.SSH.AuthorizedKeysCommandTemplateTemplate.Execute(sb, map[string]any{
  48. "AppPath": util.ShellEscape(setting.AppPath),
  49. "AppWorkPath": util.ShellEscape(setting.AppWorkPath),
  50. "CustomConf": util.ShellEscape(setting.CustomConf),
  51. "CustomPath": util.ShellEscape(setting.CustomPath),
  52. "Key": key,
  53. })
  54. return fmt.Sprintf(tplPublicKey, util.ShellEscape(sb.String()), key.Content)
  55. }
  56. // appendAuthorizedKeysToFile appends new SSH keys' content to authorized_keys file.
  57. func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
  58. // Don't need to rewrite this file if builtin SSH server is enabled.
  59. if setting.SSH.StartBuiltinServer || !setting.SSH.CreateAuthorizedKeysFile {
  60. return nil
  61. }
  62. sshOpLocker.Lock()
  63. defer sshOpLocker.Unlock()
  64. if setting.SSH.RootPath != "" {
  65. // First of ensure that the RootPath is present, and if not make it with 0700 permissions
  66. // This of course doesn't guarantee that this is the right directory for authorized_keys
  67. // but at least if it's supposed to be this directory and it doesn't exist and we're the
  68. // right user it will at least be created properly.
  69. err := os.MkdirAll(setting.SSH.RootPath, 0o700)
  70. if err != nil {
  71. log.Error("Unable to MkdirAll(%s): %v", setting.SSH.RootPath, err)
  72. return err
  73. }
  74. }
  75. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  76. f, err := os.OpenFile(fPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
  77. if err != nil {
  78. return err
  79. }
  80. defer f.Close()
  81. // Note: chmod command does not support in Windows.
  82. if !setting.IsWindows {
  83. fi, err := f.Stat()
  84. if err != nil {
  85. return err
  86. }
  87. // .ssh directory should have mode 700, and authorized_keys file should have mode 600.
  88. if fi.Mode().Perm() > 0o600 {
  89. log.Error("authorized_keys file has unusual permission flags: %s - setting to -rw-------", fi.Mode().Perm().String())
  90. if err = f.Chmod(0o600); err != nil {
  91. return err
  92. }
  93. }
  94. }
  95. for _, key := range keys {
  96. if key.Type == KeyTypePrincipal {
  97. continue
  98. }
  99. if _, err = f.WriteString(key.AuthorizedString()); err != nil {
  100. return err
  101. }
  102. }
  103. return nil
  104. }
  105. // RegeneratePublicKeys regenerates the authorized_keys file
  106. func RegeneratePublicKeys(ctx context.Context, t io.StringWriter) error {
  107. if err := db.GetEngine(ctx).Where("type != ?", KeyTypePrincipal).Iterate(new(PublicKey), func(idx int, bean any) (err error) {
  108. _, err = t.WriteString((bean.(*PublicKey)).AuthorizedString())
  109. return err
  110. }); err != nil {
  111. return err
  112. }
  113. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  114. isExist, err := util.IsExist(fPath)
  115. if err != nil {
  116. log.Error("Unable to check if %s exists. Error: %v", fPath, err)
  117. return err
  118. }
  119. if isExist {
  120. f, err := os.Open(fPath)
  121. if err != nil {
  122. return err
  123. }
  124. scanner := bufio.NewScanner(f)
  125. for scanner.Scan() {
  126. line := scanner.Text()
  127. if strings.HasPrefix(line, tplCommentPrefix) {
  128. scanner.Scan()
  129. continue
  130. }
  131. _, err = t.WriteString(line + "\n")
  132. if err != nil {
  133. f.Close()
  134. return err
  135. }
  136. }
  137. f.Close()
  138. }
  139. return nil
  140. }