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 6.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "bufio"
  7. "fmt"
  8. "io"
  9. "os"
  10. "path/filepath"
  11. "strings"
  12. "sync"
  13. "time"
  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 %s` + "\n"
  37. )
  38. var sshOpLocker sync.Mutex
  39. // AuthorizedStringForKey creates the authorized keys string appropriate for the provided key
  40. func AuthorizedStringForKey(key *PublicKey) string {
  41. sb := &strings.Builder{}
  42. _ = setting.SSH.AuthorizedKeysCommandTemplateTemplate.Execute(sb, map[string]interface{}{
  43. "AppPath": util.ShellEscape(setting.AppPath),
  44. "AppWorkPath": util.ShellEscape(setting.AppWorkPath),
  45. "CustomConf": util.ShellEscape(setting.CustomConf),
  46. "CustomPath": util.ShellEscape(setting.CustomPath),
  47. "Key": key,
  48. })
  49. return fmt.Sprintf(tplPublicKey, util.ShellEscape(sb.String()), key.Content)
  50. }
  51. // appendAuthorizedKeysToFile appends new SSH keys' content to authorized_keys file.
  52. func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
  53. // Don't need to rewrite this file if builtin SSH server is enabled.
  54. if setting.SSH.StartBuiltinServer || !setting.SSH.CreateAuthorizedKeysFile {
  55. return nil
  56. }
  57. sshOpLocker.Lock()
  58. defer sshOpLocker.Unlock()
  59. if setting.SSH.RootPath != "" {
  60. // First of ensure that the RootPath is present, and if not make it with 0700 permissions
  61. // This of course doesn't guarantee that this is the right directory for authorized_keys
  62. // but at least if it's supposed to be this directory and it doesn't exist and we're the
  63. // right user it will at least be created properly.
  64. err := os.MkdirAll(setting.SSH.RootPath, 0o700)
  65. if err != nil {
  66. log.Error("Unable to MkdirAll(%s): %v", setting.SSH.RootPath, err)
  67. return err
  68. }
  69. }
  70. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  71. f, err := os.OpenFile(fPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
  72. if err != nil {
  73. return err
  74. }
  75. defer f.Close()
  76. // Note: chmod command does not support in Windows.
  77. if !setting.IsWindows {
  78. fi, err := f.Stat()
  79. if err != nil {
  80. return err
  81. }
  82. // .ssh directory should have mode 700, and authorized_keys file should have mode 600.
  83. if fi.Mode().Perm() > 0o600 {
  84. log.Error("authorized_keys file has unusual permission flags: %s - setting to -rw-------", fi.Mode().Perm().String())
  85. if err = f.Chmod(0o600); err != nil {
  86. return err
  87. }
  88. }
  89. }
  90. for _, key := range keys {
  91. if key.Type == KeyTypePrincipal {
  92. continue
  93. }
  94. if _, err = f.WriteString(key.AuthorizedString()); err != nil {
  95. return err
  96. }
  97. }
  98. return nil
  99. }
  100. // RewriteAllPublicKeys removes any authorized key and rewrite all keys from database again.
  101. // Note: x.Iterate does not get latest data after insert/delete, so we have to call this function
  102. // outside any session scope independently.
  103. func RewriteAllPublicKeys() error {
  104. return rewriteAllPublicKeys(x)
  105. }
  106. func rewriteAllPublicKeys(e Engine) error {
  107. // Don't rewrite key if internal server
  108. if setting.SSH.StartBuiltinServer || !setting.SSH.CreateAuthorizedKeysFile {
  109. return nil
  110. }
  111. sshOpLocker.Lock()
  112. defer sshOpLocker.Unlock()
  113. if setting.SSH.RootPath != "" {
  114. // First of ensure that the RootPath is present, and if not make it with 0700 permissions
  115. // This of course doesn't guarantee that this is the right directory for authorized_keys
  116. // but at least if it's supposed to be this directory and it doesn't exist and we're the
  117. // right user it will at least be created properly.
  118. err := os.MkdirAll(setting.SSH.RootPath, 0o700)
  119. if err != nil {
  120. log.Error("Unable to MkdirAll(%s): %v", setting.SSH.RootPath, err)
  121. return err
  122. }
  123. }
  124. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  125. tmpPath := fPath + ".tmp"
  126. t, err := os.OpenFile(tmpPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
  127. if err != nil {
  128. return err
  129. }
  130. defer func() {
  131. t.Close()
  132. if err := util.Remove(tmpPath); err != nil {
  133. log.Warn("Unable to remove temporary authorized keys file: %s: Error: %v", tmpPath, err)
  134. }
  135. }()
  136. if setting.SSH.AuthorizedKeysBackup {
  137. isExist, err := util.IsExist(fPath)
  138. if err != nil {
  139. log.Error("Unable to check if %s exists. Error: %v", fPath, err)
  140. return err
  141. }
  142. if isExist {
  143. bakPath := fmt.Sprintf("%s_%d.gitea_bak", fPath, time.Now().Unix())
  144. if err = util.CopyFile(fPath, bakPath); err != nil {
  145. return err
  146. }
  147. }
  148. }
  149. if err := regeneratePublicKeys(e, t); err != nil {
  150. return err
  151. }
  152. t.Close()
  153. return util.Rename(tmpPath, fPath)
  154. }
  155. // RegeneratePublicKeys regenerates the authorized_keys file
  156. func RegeneratePublicKeys(t io.StringWriter) error {
  157. return regeneratePublicKeys(x, t)
  158. }
  159. func regeneratePublicKeys(e Engine, t io.StringWriter) error {
  160. if err := e.Where("type != ?", KeyTypePrincipal).Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
  161. _, err = t.WriteString((bean.(*PublicKey)).AuthorizedString())
  162. return err
  163. }); err != nil {
  164. return err
  165. }
  166. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  167. isExist, err := util.IsExist(fPath)
  168. if err != nil {
  169. log.Error("Unable to check if %s exists. Error: %v", fPath, err)
  170. return err
  171. }
  172. if isExist {
  173. f, err := os.Open(fPath)
  174. if err != nil {
  175. return err
  176. }
  177. scanner := bufio.NewScanner(f)
  178. for scanner.Scan() {
  179. line := scanner.Text()
  180. if strings.HasPrefix(line, tplCommentPrefix) {
  181. scanner.Scan()
  182. continue
  183. }
  184. _, err = t.WriteString(line + "\n")
  185. if err != nil {
  186. f.Close()
  187. return err
  188. }
  189. }
  190. f.Close()
  191. }
  192. return nil
  193. }