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.

1043 lines
29 KiB

10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
10 years ago
10 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
5 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "bufio"
  8. "crypto/rsa"
  9. "crypto/x509"
  10. "encoding/asn1"
  11. "encoding/base64"
  12. "encoding/binary"
  13. "encoding/pem"
  14. "errors"
  15. "fmt"
  16. "io"
  17. "io/ioutil"
  18. "math/big"
  19. "os"
  20. "path/filepath"
  21. "strings"
  22. "sync"
  23. "time"
  24. "code.gitea.io/gitea/modules/log"
  25. "code.gitea.io/gitea/modules/process"
  26. "code.gitea.io/gitea/modules/setting"
  27. "code.gitea.io/gitea/modules/timeutil"
  28. "code.gitea.io/gitea/modules/util"
  29. "github.com/unknwon/com"
  30. "golang.org/x/crypto/ssh"
  31. "xorm.io/builder"
  32. "xorm.io/xorm"
  33. )
  34. const (
  35. tplCommentPrefix = `# gitea public key`
  36. tplCommand = "%s --config=%q serv key-%d"
  37. tplPublicKey = tplCommentPrefix + "\n" + `command=%q,no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
  38. )
  39. var sshOpLocker sync.Mutex
  40. // KeyType specifies the key type
  41. type KeyType int
  42. const (
  43. // KeyTypeUser specifies the user key
  44. KeyTypeUser = iota + 1
  45. // KeyTypeDeploy specifies the deploy key
  46. KeyTypeDeploy
  47. )
  48. // PublicKey represents a user or deploy SSH public key.
  49. type PublicKey struct {
  50. ID int64 `xorm:"pk autoincr"`
  51. OwnerID int64 `xorm:"INDEX NOT NULL"`
  52. Name string `xorm:"NOT NULL"`
  53. Fingerprint string `xorm:"INDEX NOT NULL"`
  54. Content string `xorm:"TEXT NOT NULL"`
  55. Mode AccessMode `xorm:"NOT NULL DEFAULT 2"`
  56. Type KeyType `xorm:"NOT NULL DEFAULT 1"`
  57. LoginSourceID int64 `xorm:"NOT NULL DEFAULT 0"`
  58. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  59. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  60. HasRecentActivity bool `xorm:"-"`
  61. HasUsed bool `xorm:"-"`
  62. }
  63. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  64. func (key *PublicKey) AfterLoad() {
  65. key.HasUsed = key.UpdatedUnix > key.CreatedUnix
  66. key.HasRecentActivity = key.UpdatedUnix.AddDuration(7*24*time.Hour) > timeutil.TimeStampNow()
  67. }
  68. // OmitEmail returns content of public key without email address.
  69. func (key *PublicKey) OmitEmail() string {
  70. return strings.Join(strings.Split(key.Content, " ")[:2], " ")
  71. }
  72. // AuthorizedString returns formatted public key string for authorized_keys file.
  73. func (key *PublicKey) AuthorizedString() string {
  74. return fmt.Sprintf(tplPublicKey, fmt.Sprintf(tplCommand, setting.AppPath, setting.CustomConf, key.ID), key.Content)
  75. }
  76. func extractTypeFromBase64Key(key string) (string, error) {
  77. b, err := base64.StdEncoding.DecodeString(key)
  78. if err != nil || len(b) < 4 {
  79. return "", fmt.Errorf("invalid key format: %v", err)
  80. }
  81. keyLength := int(binary.BigEndian.Uint32(b))
  82. if len(b) < 4+keyLength {
  83. return "", fmt.Errorf("invalid key format: not enough length %d", keyLength)
  84. }
  85. return string(b[4 : 4+keyLength]), nil
  86. }
  87. const ssh2keyStart = "---- BEGIN SSH2 PUBLIC KEY ----"
  88. // parseKeyString parses any key string in OpenSSH or SSH2 format to clean OpenSSH string (RFC4253).
  89. func parseKeyString(content string) (string, error) {
  90. // remove whitespace at start and end
  91. content = strings.TrimSpace(content)
  92. var keyType, keyContent, keyComment string
  93. if strings.HasPrefix(content, ssh2keyStart) {
  94. // Parse SSH2 file format.
  95. // Transform all legal line endings to a single "\n".
  96. content = strings.NewReplacer("\r\n", "\n", "\r", "\n").Replace(content)
  97. lines := strings.Split(content, "\n")
  98. continuationLine := false
  99. for _, line := range lines {
  100. // Skip lines that:
  101. // 1) are a continuation of the previous line,
  102. // 2) contain ":" as that are comment lines
  103. // 3) contain "-" as that are begin and end tags
  104. if continuationLine || strings.ContainsAny(line, ":-") {
  105. continuationLine = strings.HasSuffix(line, "\\")
  106. } else {
  107. keyContent += line
  108. }
  109. }
  110. t, err := extractTypeFromBase64Key(keyContent)
  111. if err != nil {
  112. return "", fmt.Errorf("extractTypeFromBase64Key: %v", err)
  113. }
  114. keyType = t
  115. } else {
  116. if strings.Contains(content, "-----BEGIN") {
  117. // Convert PEM Keys to OpenSSH format
  118. // Transform all legal line endings to a single "\n".
  119. content = strings.NewReplacer("\r\n", "\n", "\r", "\n").Replace(content)
  120. block, _ := pem.Decode([]byte(content))
  121. if block == nil {
  122. return "", fmt.Errorf("failed to parse PEM block containing the public key")
  123. }
  124. pub, err := x509.ParsePKIXPublicKey(block.Bytes)
  125. if err != nil {
  126. var pk rsa.PublicKey
  127. _, err2 := asn1.Unmarshal(block.Bytes, &pk)
  128. if err2 != nil {
  129. return "", fmt.Errorf("failed to parse DER encoded public key as either PKIX or PEM RSA Key: %v %v", err, err2)
  130. }
  131. pub = &pk
  132. }
  133. sshKey, err := ssh.NewPublicKey(pub)
  134. if err != nil {
  135. return "", fmt.Errorf("unable to convert to ssh public key: %v", err)
  136. }
  137. content = string(ssh.MarshalAuthorizedKey(sshKey))
  138. }
  139. // Parse OpenSSH format.
  140. // Remove all newlines
  141. content = strings.NewReplacer("\r\n", "", "\n", "").Replace(content)
  142. parts := strings.SplitN(content, " ", 3)
  143. switch len(parts) {
  144. case 0:
  145. return "", errors.New("empty key")
  146. case 1:
  147. keyContent = parts[0]
  148. case 2:
  149. keyType = parts[0]
  150. keyContent = parts[1]
  151. default:
  152. keyType = parts[0]
  153. keyContent = parts[1]
  154. keyComment = parts[2]
  155. }
  156. // If keyType is not given, extract it from content. If given, validate it.
  157. t, err := extractTypeFromBase64Key(keyContent)
  158. if err != nil {
  159. return "", fmt.Errorf("extractTypeFromBase64Key: %v", err)
  160. }
  161. if len(keyType) == 0 {
  162. keyType = t
  163. } else if keyType != t {
  164. return "", fmt.Errorf("key type and content does not match: %s - %s", keyType, t)
  165. }
  166. }
  167. // Finally we need to check whether we can actually read the proposed key:
  168. _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(keyType + " " + keyContent + " " + keyComment))
  169. if err != nil {
  170. return "", fmt.Errorf("invalid ssh public key: %v", err)
  171. }
  172. return keyType + " " + keyContent + " " + keyComment, nil
  173. }
  174. // writeTmpKeyFile writes key content to a temporary file
  175. // and returns the name of that file, along with any possible errors.
  176. func writeTmpKeyFile(content string) (string, error) {
  177. tmpFile, err := ioutil.TempFile(setting.SSH.KeyTestPath, "gitea_keytest")
  178. if err != nil {
  179. return "", fmt.Errorf("TempFile: %v", err)
  180. }
  181. defer tmpFile.Close()
  182. if _, err = tmpFile.WriteString(content); err != nil {
  183. return "", fmt.Errorf("WriteString: %v", err)
  184. }
  185. return tmpFile.Name(), nil
  186. }
  187. // SSHKeyGenParsePublicKey extracts key type and length using ssh-keygen.
  188. func SSHKeyGenParsePublicKey(key string) (string, int, error) {
  189. // The ssh-keygen in Windows does not print key type, so no need go further.
  190. if setting.IsWindows {
  191. return "", 0, nil
  192. }
  193. tmpName, err := writeTmpKeyFile(key)
  194. if err != nil {
  195. return "", 0, fmt.Errorf("writeTmpKeyFile: %v", err)
  196. }
  197. defer func() {
  198. if err := util.Remove(tmpName); err != nil {
  199. log.Warn("Unable to remove temporary key file: %s: Error: %v", tmpName, err)
  200. }
  201. }()
  202. stdout, stderr, err := process.GetManager().Exec("SSHKeyGenParsePublicKey", setting.SSH.KeygenPath, "-lf", tmpName)
  203. if err != nil {
  204. return "", 0, fmt.Errorf("fail to parse public key: %s - %s", err, stderr)
  205. }
  206. if strings.Contains(stdout, "is not a public key file") {
  207. return "", 0, ErrKeyUnableVerify{stdout}
  208. }
  209. fields := strings.Split(stdout, " ")
  210. if len(fields) < 4 {
  211. return "", 0, fmt.Errorf("invalid public key line: %s", stdout)
  212. }
  213. keyType := strings.Trim(fields[len(fields)-1], "()\r\n")
  214. return strings.ToLower(keyType), com.StrTo(fields[0]).MustInt(), nil
  215. }
  216. // SSHNativeParsePublicKey extracts the key type and length using the golang SSH library.
  217. func SSHNativeParsePublicKey(keyLine string) (string, int, error) {
  218. fields := strings.Fields(keyLine)
  219. if len(fields) < 2 {
  220. return "", 0, fmt.Errorf("not enough fields in public key line: %s", keyLine)
  221. }
  222. raw, err := base64.StdEncoding.DecodeString(fields[1])
  223. if err != nil {
  224. return "", 0, err
  225. }
  226. pkey, err := ssh.ParsePublicKey(raw)
  227. if err != nil {
  228. if strings.Contains(err.Error(), "ssh: unknown key algorithm") {
  229. return "", 0, ErrKeyUnableVerify{err.Error()}
  230. }
  231. return "", 0, fmt.Errorf("ParsePublicKey: %v", err)
  232. }
  233. // The ssh library can parse the key, so next we find out what key exactly we have.
  234. switch pkey.Type() {
  235. case ssh.KeyAlgoDSA:
  236. rawPub := struct {
  237. Name string
  238. P, Q, G, Y *big.Int
  239. }{}
  240. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  241. return "", 0, err
  242. }
  243. // as per https://bugzilla.mindrot.org/show_bug.cgi?id=1647 we should never
  244. // see dsa keys != 1024 bit, but as it seems to work, we will not check here
  245. return "dsa", rawPub.P.BitLen(), nil // use P as per crypto/dsa/dsa.go (is L)
  246. case ssh.KeyAlgoRSA:
  247. rawPub := struct {
  248. Name string
  249. E *big.Int
  250. N *big.Int
  251. }{}
  252. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  253. return "", 0, err
  254. }
  255. return "rsa", rawPub.N.BitLen(), nil // use N as per crypto/rsa/rsa.go (is bits)
  256. case ssh.KeyAlgoECDSA256:
  257. return "ecdsa", 256, nil
  258. case ssh.KeyAlgoECDSA384:
  259. return "ecdsa", 384, nil
  260. case ssh.KeyAlgoECDSA521:
  261. return "ecdsa", 521, nil
  262. case ssh.KeyAlgoED25519:
  263. return "ed25519", 256, nil
  264. }
  265. return "", 0, fmt.Errorf("unsupported key length detection for type: %s", pkey.Type())
  266. }
  267. // CheckPublicKeyString checks if the given public key string is recognized by SSH.
  268. // It returns the actual public key line on success.
  269. func CheckPublicKeyString(content string) (_ string, err error) {
  270. if setting.SSH.Disabled {
  271. return "", ErrSSHDisabled{}
  272. }
  273. content, err = parseKeyString(content)
  274. if err != nil {
  275. return "", err
  276. }
  277. content = strings.TrimRight(content, "\n\r")
  278. if strings.ContainsAny(content, "\n\r") {
  279. return "", errors.New("only a single line with a single key please")
  280. }
  281. // remove any unnecessary whitespace now
  282. content = strings.TrimSpace(content)
  283. if !setting.SSH.MinimumKeySizeCheck {
  284. return content, nil
  285. }
  286. var (
  287. fnName string
  288. keyType string
  289. length int
  290. )
  291. if setting.SSH.StartBuiltinServer {
  292. fnName = "SSHNativeParsePublicKey"
  293. keyType, length, err = SSHNativeParsePublicKey(content)
  294. } else {
  295. fnName = "SSHKeyGenParsePublicKey"
  296. keyType, length, err = SSHKeyGenParsePublicKey(content)
  297. }
  298. if err != nil {
  299. return "", fmt.Errorf("%s: %v", fnName, err)
  300. }
  301. log.Trace("Key info [native: %v]: %s-%d", setting.SSH.StartBuiltinServer, keyType, length)
  302. if minLen, found := setting.SSH.MinimumKeySizes[keyType]; found && length >= minLen {
  303. return content, nil
  304. } else if found && length < minLen {
  305. return "", fmt.Errorf("key length is not enough: got %d, needs %d", length, minLen)
  306. }
  307. return "", fmt.Errorf("key type is not allowed: %s", keyType)
  308. }
  309. // appendAuthorizedKeysToFile appends new SSH keys' content to authorized_keys file.
  310. func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
  311. // Don't need to rewrite this file if builtin SSH server is enabled.
  312. if setting.SSH.StartBuiltinServer {
  313. return nil
  314. }
  315. sshOpLocker.Lock()
  316. defer sshOpLocker.Unlock()
  317. if setting.SSH.RootPath != "" {
  318. // First of ensure that the RootPath is present, and if not make it with 0700 permissions
  319. // This of course doesn't guarantee that this is the right directory for authorized_keys
  320. // but at least if it's supposed to be this directory and it doesn't exist and we're the
  321. // right user it will at least be created properly.
  322. err := os.MkdirAll(setting.SSH.RootPath, 0700)
  323. if err != nil {
  324. log.Error("Unable to MkdirAll(%s): %v", setting.SSH.RootPath, err)
  325. return err
  326. }
  327. }
  328. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  329. f, err := os.OpenFile(fPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  330. if err != nil {
  331. return err
  332. }
  333. defer f.Close()
  334. // Note: chmod command does not support in Windows.
  335. if !setting.IsWindows {
  336. fi, err := f.Stat()
  337. if err != nil {
  338. return err
  339. }
  340. // .ssh directory should have mode 700, and authorized_keys file should have mode 600.
  341. if fi.Mode().Perm() > 0600 {
  342. log.Error("authorized_keys file has unusual permission flags: %s - setting to -rw-------", fi.Mode().Perm().String())
  343. if err = f.Chmod(0600); err != nil {
  344. return err
  345. }
  346. }
  347. }
  348. for _, key := range keys {
  349. if _, err = f.WriteString(key.AuthorizedString()); err != nil {
  350. return err
  351. }
  352. }
  353. return nil
  354. }
  355. // checkKeyFingerprint only checks if key fingerprint has been used as public key,
  356. // it is OK to use same key as deploy key for multiple repositories/users.
  357. func checkKeyFingerprint(e Engine, fingerprint string) error {
  358. has, err := e.Get(&PublicKey{
  359. Fingerprint: fingerprint,
  360. })
  361. if err != nil {
  362. return err
  363. } else if has {
  364. return ErrKeyAlreadyExist{0, fingerprint, ""}
  365. }
  366. return nil
  367. }
  368. func calcFingerprintSSHKeygen(publicKeyContent string) (string, error) {
  369. // Calculate fingerprint.
  370. tmpPath, err := writeTmpKeyFile(publicKeyContent)
  371. if err != nil {
  372. return "", err
  373. }
  374. defer func() {
  375. if err := util.Remove(tmpPath); err != nil {
  376. log.Warn("Unable to remove temporary key file: %s: Error: %v", tmpPath, err)
  377. }
  378. }()
  379. stdout, stderr, err := process.GetManager().Exec("AddPublicKey", "ssh-keygen", "-lf", tmpPath)
  380. if err != nil {
  381. if strings.Contains(stderr, "is not a public key file") {
  382. return "", ErrKeyUnableVerify{stderr}
  383. }
  384. return "", fmt.Errorf("'ssh-keygen -lf %s' failed with error '%s': %s", tmpPath, err, stderr)
  385. } else if len(stdout) < 2 {
  386. return "", errors.New("not enough output for calculating fingerprint: " + stdout)
  387. }
  388. return strings.Split(stdout, " ")[1], nil
  389. }
  390. func calcFingerprintNative(publicKeyContent string) (string, error) {
  391. // Calculate fingerprint.
  392. pk, _, _, _, err := ssh.ParseAuthorizedKey([]byte(publicKeyContent))
  393. if err != nil {
  394. return "", err
  395. }
  396. return ssh.FingerprintSHA256(pk), nil
  397. }
  398. func calcFingerprint(publicKeyContent string) (string, error) {
  399. //Call the method based on configuration
  400. var (
  401. fnName, fp string
  402. err error
  403. )
  404. if setting.SSH.StartBuiltinServer {
  405. fnName = "calcFingerprintNative"
  406. fp, err = calcFingerprintNative(publicKeyContent)
  407. } else {
  408. fnName = "calcFingerprintSSHKeygen"
  409. fp, err = calcFingerprintSSHKeygen(publicKeyContent)
  410. }
  411. if err != nil {
  412. if IsErrKeyUnableVerify(err) {
  413. log.Info("%s", publicKeyContent)
  414. return "", err
  415. }
  416. return "", fmt.Errorf("%s: %v", fnName, err)
  417. }
  418. return fp, nil
  419. }
  420. func addKey(e Engine, key *PublicKey) (err error) {
  421. if len(key.Fingerprint) == 0 {
  422. key.Fingerprint, err = calcFingerprint(key.Content)
  423. if err != nil {
  424. return err
  425. }
  426. }
  427. // Save SSH key.
  428. if _, err = e.Insert(key); err != nil {
  429. return err
  430. }
  431. return appendAuthorizedKeysToFile(key)
  432. }
  433. // AddPublicKey adds new public key to database and authorized_keys file.
  434. func AddPublicKey(ownerID int64, name, content string, loginSourceID int64) (*PublicKey, error) {
  435. log.Trace(content)
  436. fingerprint, err := calcFingerprint(content)
  437. if err != nil {
  438. return nil, err
  439. }
  440. sess := x.NewSession()
  441. defer sess.Close()
  442. if err = sess.Begin(); err != nil {
  443. return nil, err
  444. }
  445. if err := checkKeyFingerprint(sess, fingerprint); err != nil {
  446. return nil, err
  447. }
  448. // Key name of same user cannot be duplicated.
  449. has, err := sess.
  450. Where("owner_id = ? AND name = ?", ownerID, name).
  451. Get(new(PublicKey))
  452. if err != nil {
  453. return nil, err
  454. } else if has {
  455. return nil, ErrKeyNameAlreadyUsed{ownerID, name}
  456. }
  457. key := &PublicKey{
  458. OwnerID: ownerID,
  459. Name: name,
  460. Fingerprint: fingerprint,
  461. Content: content,
  462. Mode: AccessModeWrite,
  463. Type: KeyTypeUser,
  464. LoginSourceID: loginSourceID,
  465. }
  466. if err = addKey(sess, key); err != nil {
  467. return nil, fmt.Errorf("addKey: %v", err)
  468. }
  469. return key, sess.Commit()
  470. }
  471. // GetPublicKeyByID returns public key by given ID.
  472. func GetPublicKeyByID(keyID int64) (*PublicKey, error) {
  473. key := new(PublicKey)
  474. has, err := x.
  475. ID(keyID).
  476. Get(key)
  477. if err != nil {
  478. return nil, err
  479. } else if !has {
  480. return nil, ErrKeyNotExist{keyID}
  481. }
  482. return key, nil
  483. }
  484. func searchPublicKeyByContentWithEngine(e Engine, content string) (*PublicKey, error) {
  485. key := new(PublicKey)
  486. has, err := e.
  487. Where("content like ?", content+"%").
  488. Get(key)
  489. if err != nil {
  490. return nil, err
  491. } else if !has {
  492. return nil, ErrKeyNotExist{}
  493. }
  494. return key, nil
  495. }
  496. // SearchPublicKeyByContent searches content as prefix (leak e-mail part)
  497. // and returns public key found.
  498. func SearchPublicKeyByContent(content string) (*PublicKey, error) {
  499. return searchPublicKeyByContentWithEngine(x, content)
  500. }
  501. // SearchPublicKey returns a list of public keys matching the provided arguments.
  502. func SearchPublicKey(uid int64, fingerprint string) ([]*PublicKey, error) {
  503. keys := make([]*PublicKey, 0, 5)
  504. cond := builder.NewCond()
  505. if uid != 0 {
  506. cond = cond.And(builder.Eq{"owner_id": uid})
  507. }
  508. if fingerprint != "" {
  509. cond = cond.And(builder.Eq{"fingerprint": fingerprint})
  510. }
  511. return keys, x.Where(cond).Find(&keys)
  512. }
  513. // ListPublicKeys returns a list of public keys belongs to given user.
  514. func ListPublicKeys(uid int64, listOptions ListOptions) ([]*PublicKey, error) {
  515. sess := x.Where("owner_id = ?", uid)
  516. if listOptions.Page != 0 {
  517. sess = listOptions.setSessionPagination(sess)
  518. keys := make([]*PublicKey, 0, listOptions.PageSize)
  519. return keys, sess.Find(&keys)
  520. }
  521. keys := make([]*PublicKey, 0, 5)
  522. return keys, sess.Find(&keys)
  523. }
  524. // ListPublicLdapSSHKeys returns a list of synchronized public ldap ssh keys belongs to given user and login source.
  525. func ListPublicLdapSSHKeys(uid int64, loginSourceID int64) ([]*PublicKey, error) {
  526. keys := make([]*PublicKey, 0, 5)
  527. return keys, x.
  528. Where("owner_id = ? AND login_source_id = ?", uid, loginSourceID).
  529. Find(&keys)
  530. }
  531. // UpdatePublicKeyUpdated updates public key use time.
  532. func UpdatePublicKeyUpdated(id int64) error {
  533. // Check if key exists before update as affected rows count is unreliable
  534. // and will return 0 affected rows if two updates are made at the same time
  535. if cnt, err := x.ID(id).Count(&PublicKey{}); err != nil {
  536. return err
  537. } else if cnt != 1 {
  538. return ErrKeyNotExist{id}
  539. }
  540. _, err := x.ID(id).Cols("updated_unix").Update(&PublicKey{
  541. UpdatedUnix: timeutil.TimeStampNow(),
  542. })
  543. if err != nil {
  544. return err
  545. }
  546. return nil
  547. }
  548. // deletePublicKeys does the actual key deletion but does not update authorized_keys file.
  549. func deletePublicKeys(e Engine, keyIDs ...int64) error {
  550. if len(keyIDs) == 0 {
  551. return nil
  552. }
  553. _, err := e.In("id", keyIDs).Delete(new(PublicKey))
  554. return err
  555. }
  556. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  557. func DeletePublicKey(doer *User, id int64) (err error) {
  558. key, err := GetPublicKeyByID(id)
  559. if err != nil {
  560. return err
  561. }
  562. // Check if user has access to delete this key.
  563. if !doer.IsAdmin && doer.ID != key.OwnerID {
  564. return ErrKeyAccessDenied{doer.ID, key.ID, "public"}
  565. }
  566. sess := x.NewSession()
  567. defer sess.Close()
  568. if err = sess.Begin(); err != nil {
  569. return err
  570. }
  571. if err = deletePublicKeys(sess, id); err != nil {
  572. return err
  573. }
  574. if err = sess.Commit(); err != nil {
  575. return err
  576. }
  577. sess.Close()
  578. return RewriteAllPublicKeys()
  579. }
  580. // RewriteAllPublicKeys removes any authorized key and rewrite all keys from database again.
  581. // Note: x.Iterate does not get latest data after insert/delete, so we have to call this function
  582. // outside any session scope independently.
  583. func RewriteAllPublicKeys() error {
  584. return rewriteAllPublicKeys(x)
  585. }
  586. func rewriteAllPublicKeys(e Engine) error {
  587. //Don't rewrite key if internal server
  588. if setting.SSH.StartBuiltinServer || !setting.SSH.CreateAuthorizedKeysFile {
  589. return nil
  590. }
  591. sshOpLocker.Lock()
  592. defer sshOpLocker.Unlock()
  593. if setting.SSH.RootPath != "" {
  594. // First of ensure that the RootPath is present, and if not make it with 0700 permissions
  595. // This of course doesn't guarantee that this is the right directory for authorized_keys
  596. // but at least if it's supposed to be this directory and it doesn't exist and we're the
  597. // right user it will at least be created properly.
  598. err := os.MkdirAll(setting.SSH.RootPath, 0700)
  599. if err != nil {
  600. log.Error("Unable to MkdirAll(%s): %v", setting.SSH.RootPath, err)
  601. return err
  602. }
  603. }
  604. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  605. tmpPath := fPath + ".tmp"
  606. t, err := os.OpenFile(tmpPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  607. if err != nil {
  608. return err
  609. }
  610. defer func() {
  611. t.Close()
  612. if err := util.Remove(tmpPath); err != nil {
  613. log.Warn("Unable to remove temporary authorized keys file: %s: Error: %v", tmpPath, err)
  614. }
  615. }()
  616. if setting.SSH.AuthorizedKeysBackup && com.IsExist(fPath) {
  617. bakPath := fmt.Sprintf("%s_%d.gitea_bak", fPath, time.Now().Unix())
  618. if err = com.Copy(fPath, bakPath); err != nil {
  619. return err
  620. }
  621. }
  622. if err := regeneratePublicKeys(e, t); err != nil {
  623. return err
  624. }
  625. t.Close()
  626. return os.Rename(tmpPath, fPath)
  627. }
  628. // RegeneratePublicKeys regenerates the authorized_keys file
  629. func RegeneratePublicKeys(t io.StringWriter) error {
  630. return regeneratePublicKeys(x, t)
  631. }
  632. func regeneratePublicKeys(e Engine, t io.StringWriter) error {
  633. err := e.Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
  634. _, err = t.WriteString((bean.(*PublicKey)).AuthorizedString())
  635. return err
  636. })
  637. if err != nil {
  638. return err
  639. }
  640. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  641. if com.IsExist(fPath) {
  642. f, err := os.Open(fPath)
  643. if err != nil {
  644. return err
  645. }
  646. scanner := bufio.NewScanner(f)
  647. for scanner.Scan() {
  648. line := scanner.Text()
  649. if strings.HasPrefix(line, tplCommentPrefix) {
  650. scanner.Scan()
  651. continue
  652. }
  653. _, err = t.WriteString(line + "\n")
  654. if err != nil {
  655. f.Close()
  656. return err
  657. }
  658. }
  659. f.Close()
  660. }
  661. return nil
  662. }
  663. // ________ .__ ____ __.
  664. // \______ \ ____ ______ | | ____ ___.__.| |/ _|____ ___.__.
  665. // | | \_/ __ \\____ \| | / _ < | || <_/ __ < | |
  666. // | ` \ ___/| |_> > |_( <_> )___ || | \ ___/\___ |
  667. // /_______ /\___ > __/|____/\____// ____||____|__ \___ > ____|
  668. // \/ \/|__| \/ \/ \/\/
  669. // DeployKey represents deploy key information and its relation with repository.
  670. type DeployKey struct {
  671. ID int64 `xorm:"pk autoincr"`
  672. KeyID int64 `xorm:"UNIQUE(s) INDEX"`
  673. RepoID int64 `xorm:"UNIQUE(s) INDEX"`
  674. Name string
  675. Fingerprint string
  676. Content string `xorm:"-"`
  677. Mode AccessMode `xorm:"NOT NULL DEFAULT 1"`
  678. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  679. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  680. HasRecentActivity bool `xorm:"-"`
  681. HasUsed bool `xorm:"-"`
  682. }
  683. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  684. func (key *DeployKey) AfterLoad() {
  685. key.HasUsed = key.UpdatedUnix > key.CreatedUnix
  686. key.HasRecentActivity = key.UpdatedUnix.AddDuration(7*24*time.Hour) > timeutil.TimeStampNow()
  687. }
  688. // GetContent gets associated public key content.
  689. func (key *DeployKey) GetContent() error {
  690. pkey, err := GetPublicKeyByID(key.KeyID)
  691. if err != nil {
  692. return err
  693. }
  694. key.Content = pkey.Content
  695. return nil
  696. }
  697. // IsReadOnly checks if the key can only be used for read operations
  698. func (key *DeployKey) IsReadOnly() bool {
  699. return key.Mode == AccessModeRead
  700. }
  701. func checkDeployKey(e Engine, keyID, repoID int64, name string) error {
  702. // Note: We want error detail, not just true or false here.
  703. has, err := e.
  704. Where("key_id = ? AND repo_id = ?", keyID, repoID).
  705. Get(new(DeployKey))
  706. if err != nil {
  707. return err
  708. } else if has {
  709. return ErrDeployKeyAlreadyExist{keyID, repoID}
  710. }
  711. has, err = e.
  712. Where("repo_id = ? AND name = ?", repoID, name).
  713. Get(new(DeployKey))
  714. if err != nil {
  715. return err
  716. } else if has {
  717. return ErrDeployKeyNameAlreadyUsed{repoID, name}
  718. }
  719. return nil
  720. }
  721. // addDeployKey adds new key-repo relation.
  722. func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string, mode AccessMode) (*DeployKey, error) {
  723. if err := checkDeployKey(e, keyID, repoID, name); err != nil {
  724. return nil, err
  725. }
  726. key := &DeployKey{
  727. KeyID: keyID,
  728. RepoID: repoID,
  729. Name: name,
  730. Fingerprint: fingerprint,
  731. Mode: mode,
  732. }
  733. _, err := e.Insert(key)
  734. return key, err
  735. }
  736. // HasDeployKey returns true if public key is a deploy key of given repository.
  737. func HasDeployKey(keyID, repoID int64) bool {
  738. has, _ := x.
  739. Where("key_id = ? AND repo_id = ?", keyID, repoID).
  740. Get(new(DeployKey))
  741. return has
  742. }
  743. // AddDeployKey add new deploy key to database and authorized_keys file.
  744. func AddDeployKey(repoID int64, name, content string, readOnly bool) (*DeployKey, error) {
  745. fingerprint, err := calcFingerprint(content)
  746. if err != nil {
  747. return nil, err
  748. }
  749. accessMode := AccessModeRead
  750. if !readOnly {
  751. accessMode = AccessModeWrite
  752. }
  753. sess := x.NewSession()
  754. defer sess.Close()
  755. if err = sess.Begin(); err != nil {
  756. return nil, err
  757. }
  758. pkey := &PublicKey{
  759. Fingerprint: fingerprint,
  760. }
  761. has, err := sess.Get(pkey)
  762. if err != nil {
  763. return nil, err
  764. }
  765. if has {
  766. if pkey.Type != KeyTypeDeploy {
  767. return nil, ErrKeyAlreadyExist{0, fingerprint, ""}
  768. }
  769. } else {
  770. // First time use this deploy key.
  771. pkey.Mode = accessMode
  772. pkey.Type = KeyTypeDeploy
  773. pkey.Content = content
  774. pkey.Name = name
  775. if err = addKey(sess, pkey); err != nil {
  776. return nil, fmt.Errorf("addKey: %v", err)
  777. }
  778. }
  779. key, err := addDeployKey(sess, pkey.ID, repoID, name, pkey.Fingerprint, accessMode)
  780. if err != nil {
  781. return nil, err
  782. }
  783. return key, sess.Commit()
  784. }
  785. // GetDeployKeyByID returns deploy key by given ID.
  786. func GetDeployKeyByID(id int64) (*DeployKey, error) {
  787. return getDeployKeyByID(x, id)
  788. }
  789. func getDeployKeyByID(e Engine, id int64) (*DeployKey, error) {
  790. key := new(DeployKey)
  791. has, err := e.ID(id).Get(key)
  792. if err != nil {
  793. return nil, err
  794. } else if !has {
  795. return nil, ErrDeployKeyNotExist{id, 0, 0}
  796. }
  797. return key, nil
  798. }
  799. // GetDeployKeyByRepo returns deploy key by given public key ID and repository ID.
  800. func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) {
  801. return getDeployKeyByRepo(x, keyID, repoID)
  802. }
  803. func getDeployKeyByRepo(e Engine, keyID, repoID int64) (*DeployKey, error) {
  804. key := &DeployKey{
  805. KeyID: keyID,
  806. RepoID: repoID,
  807. }
  808. has, err := e.Get(key)
  809. if err != nil {
  810. return nil, err
  811. } else if !has {
  812. return nil, ErrDeployKeyNotExist{0, keyID, repoID}
  813. }
  814. return key, nil
  815. }
  816. // UpdateDeployKeyCols updates deploy key information in the specified columns.
  817. func UpdateDeployKeyCols(key *DeployKey, cols ...string) error {
  818. _, err := x.ID(key.ID).Cols(cols...).Update(key)
  819. return err
  820. }
  821. // UpdateDeployKey updates deploy key information.
  822. func UpdateDeployKey(key *DeployKey) error {
  823. _, err := x.ID(key.ID).AllCols().Update(key)
  824. return err
  825. }
  826. // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed.
  827. func DeleteDeployKey(doer *User, id int64) error {
  828. sess := x.NewSession()
  829. defer sess.Close()
  830. if err := sess.Begin(); err != nil {
  831. return err
  832. }
  833. if err := deleteDeployKey(sess, doer, id); err != nil {
  834. return err
  835. }
  836. return sess.Commit()
  837. }
  838. func deleteDeployKey(sess Engine, doer *User, id int64) error {
  839. key, err := getDeployKeyByID(sess, id)
  840. if err != nil {
  841. if IsErrDeployKeyNotExist(err) {
  842. return nil
  843. }
  844. return fmt.Errorf("GetDeployKeyByID: %v", err)
  845. }
  846. // Check if user has access to delete this key.
  847. if !doer.IsAdmin {
  848. repo, err := getRepositoryByID(sess, key.RepoID)
  849. if err != nil {
  850. return fmt.Errorf("GetRepositoryByID: %v", err)
  851. }
  852. has, err := isUserRepoAdmin(sess, repo, doer)
  853. if err != nil {
  854. return fmt.Errorf("GetUserRepoPermission: %v", err)
  855. } else if !has {
  856. return ErrKeyAccessDenied{doer.ID, key.ID, "deploy"}
  857. }
  858. }
  859. if _, err = sess.ID(key.ID).Delete(new(DeployKey)); err != nil {
  860. return fmt.Errorf("delete deploy key [%d]: %v", key.ID, err)
  861. }
  862. // Check if this is the last reference to same key content.
  863. has, err := sess.
  864. Where("key_id = ?", key.KeyID).
  865. Get(new(DeployKey))
  866. if err != nil {
  867. return err
  868. } else if !has {
  869. if err = deletePublicKeys(sess, key.KeyID); err != nil {
  870. return err
  871. }
  872. // after deleted the public keys, should rewrite the public keys file
  873. if err = rewriteAllPublicKeys(sess); err != nil {
  874. return err
  875. }
  876. }
  877. return nil
  878. }
  879. // ListDeployKeys returns all deploy keys by given repository ID.
  880. func ListDeployKeys(repoID int64, listOptions ListOptions) ([]*DeployKey, error) {
  881. return listDeployKeys(x, repoID, listOptions)
  882. }
  883. func listDeployKeys(e Engine, repoID int64, listOptions ListOptions) ([]*DeployKey, error) {
  884. sess := e.Where("repo_id = ?", repoID)
  885. if listOptions.Page != 0 {
  886. sess = listOptions.setSessionPagination(sess)
  887. keys := make([]*DeployKey, 0, listOptions.PageSize)
  888. return keys, sess.Find(&keys)
  889. }
  890. keys := make([]*DeployKey, 0, 5)
  891. return keys, sess.Find(&keys)
  892. }
  893. // SearchDeployKeys returns a list of deploy keys matching the provided arguments.
  894. func SearchDeployKeys(repoID int64, keyID int64, fingerprint string) ([]*DeployKey, error) {
  895. keys := make([]*DeployKey, 0, 5)
  896. cond := builder.NewCond()
  897. if repoID != 0 {
  898. cond = cond.And(builder.Eq{"repo_id": repoID})
  899. }
  900. if keyID != 0 {
  901. cond = cond.And(builder.Eq{"key_id": keyID})
  902. }
  903. if fingerprint != "" {
  904. cond = cond.And(builder.Eq{"fingerprint": fingerprint})
  905. }
  906. return keys, x.Where(cond).Find(&keys)
  907. }