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.

825 lines
22 KiB

10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
10 years ago
8 years ago
10 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
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. // Copyright 2014 The Gogs 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. "encoding/base64"
  8. "encoding/binary"
  9. "errors"
  10. "fmt"
  11. "io/ioutil"
  12. "math/big"
  13. "os"
  14. "path/filepath"
  15. "strings"
  16. "sync"
  17. "time"
  18. "github.com/Unknwon/com"
  19. "github.com/go-xorm/xorm"
  20. "golang.org/x/crypto/ssh"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/process"
  23. "code.gitea.io/gitea/modules/setting"
  24. "code.gitea.io/gitea/modules/util"
  25. )
  26. const (
  27. tplCommentPrefix = `# gitea public key`
  28. tplPublicKey = tplCommentPrefix + "\n" + `command="%s serv key-%d --config='%s'",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
  29. )
  30. var sshOpLocker sync.Mutex
  31. // KeyType specifies the key type
  32. type KeyType int
  33. const (
  34. // KeyTypeUser specifies the user key
  35. KeyTypeUser = iota + 1
  36. // KeyTypeDeploy specifies the deploy key
  37. KeyTypeDeploy
  38. )
  39. // PublicKey represents a user or deploy SSH public key.
  40. type PublicKey struct {
  41. ID int64 `xorm:"pk autoincr"`
  42. OwnerID int64 `xorm:"INDEX NOT NULL"`
  43. Name string `xorm:"NOT NULL"`
  44. Fingerprint string `xorm:"NOT NULL"`
  45. Content string `xorm:"TEXT NOT NULL"`
  46. Mode AccessMode `xorm:"NOT NULL DEFAULT 2"`
  47. Type KeyType `xorm:"NOT NULL DEFAULT 1"`
  48. CreatedUnix util.TimeStamp `xorm:"created"`
  49. UpdatedUnix util.TimeStamp `xorm:"updated"`
  50. HasRecentActivity bool `xorm:"-"`
  51. HasUsed bool `xorm:"-"`
  52. }
  53. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  54. func (key *PublicKey) AfterLoad() {
  55. key.HasUsed = key.UpdatedUnix > key.CreatedUnix
  56. key.HasRecentActivity = key.UpdatedUnix.AddDuration(7*24*time.Hour) > util.TimeStampNow()
  57. }
  58. // OmitEmail returns content of public key without email address.
  59. func (key *PublicKey) OmitEmail() string {
  60. return strings.Join(strings.Split(key.Content, " ")[:2], " ")
  61. }
  62. // AuthorizedString returns formatted public key string for authorized_keys file.
  63. func (key *PublicKey) AuthorizedString() string {
  64. return fmt.Sprintf(tplPublicKey, setting.AppPath, key.ID, setting.CustomConf, key.Content)
  65. }
  66. func extractTypeFromBase64Key(key string) (string, error) {
  67. b, err := base64.StdEncoding.DecodeString(key)
  68. if err != nil || len(b) < 4 {
  69. return "", fmt.Errorf("invalid key format: %v", err)
  70. }
  71. keyLength := int(binary.BigEndian.Uint32(b))
  72. if len(b) < 4+keyLength {
  73. return "", fmt.Errorf("invalid key format: not enough length %d", keyLength)
  74. }
  75. return string(b[4 : 4+keyLength]), nil
  76. }
  77. // parseKeyString parses any key string in OpenSSH or SSH2 format to clean OpenSSH string (RFC4253).
  78. func parseKeyString(content string) (string, error) {
  79. // Transform all legal line endings to a single "\n".
  80. content = strings.NewReplacer("\r\n", "\n", "\r", "\n").Replace(content)
  81. // remove trailing newline (and beginning spaces too)
  82. content = strings.TrimSpace(content)
  83. lines := strings.Split(content, "\n")
  84. var keyType, keyContent, keyComment string
  85. if len(lines) == 1 {
  86. // Parse OpenSSH format.
  87. parts := strings.SplitN(lines[0], " ", 3)
  88. switch len(parts) {
  89. case 0:
  90. return "", errors.New("empty key")
  91. case 1:
  92. keyContent = parts[0]
  93. case 2:
  94. keyType = parts[0]
  95. keyContent = parts[1]
  96. default:
  97. keyType = parts[0]
  98. keyContent = parts[1]
  99. keyComment = parts[2]
  100. }
  101. // If keyType is not given, extract it from content. If given, validate it.
  102. t, err := extractTypeFromBase64Key(keyContent)
  103. if err != nil {
  104. return "", fmt.Errorf("extractTypeFromBase64Key: %v", err)
  105. }
  106. if len(keyType) == 0 {
  107. keyType = t
  108. } else if keyType != t {
  109. return "", fmt.Errorf("key type and content does not match: %s - %s", keyType, t)
  110. }
  111. } else {
  112. // Parse SSH2 file format.
  113. continuationLine := false
  114. for _, line := range lines {
  115. // Skip lines that:
  116. // 1) are a continuation of the previous line,
  117. // 2) contain ":" as that are comment lines
  118. // 3) contain "-" as that are begin and end tags
  119. if continuationLine || strings.ContainsAny(line, ":-") {
  120. continuationLine = strings.HasSuffix(line, "\\")
  121. } else {
  122. keyContent = keyContent + line
  123. }
  124. }
  125. t, err := extractTypeFromBase64Key(keyContent)
  126. if err != nil {
  127. return "", fmt.Errorf("extractTypeFromBase64Key: %v", err)
  128. }
  129. keyType = t
  130. }
  131. return keyType + " " + keyContent + " " + keyComment, nil
  132. }
  133. // writeTmpKeyFile writes key content to a temporary file
  134. // and returns the name of that file, along with any possible errors.
  135. func writeTmpKeyFile(content string) (string, error) {
  136. tmpFile, err := ioutil.TempFile(setting.SSH.KeyTestPath, "gitea_keytest")
  137. if err != nil {
  138. return "", fmt.Errorf("TempFile: %v", err)
  139. }
  140. defer tmpFile.Close()
  141. if _, err = tmpFile.WriteString(content); err != nil {
  142. return "", fmt.Errorf("WriteString: %v", err)
  143. }
  144. return tmpFile.Name(), nil
  145. }
  146. // SSHKeyGenParsePublicKey extracts key type and length using ssh-keygen.
  147. func SSHKeyGenParsePublicKey(key string) (string, int, error) {
  148. // The ssh-keygen in Windows does not print key type, so no need go further.
  149. if setting.IsWindows {
  150. return "", 0, nil
  151. }
  152. tmpName, err := writeTmpKeyFile(key)
  153. if err != nil {
  154. return "", 0, fmt.Errorf("writeTmpKeyFile: %v", err)
  155. }
  156. defer os.Remove(tmpName)
  157. stdout, stderr, err := process.GetManager().Exec("SSHKeyGenParsePublicKey", setting.SSH.KeygenPath, "-lf", tmpName)
  158. if err != nil {
  159. return "", 0, fmt.Errorf("fail to parse public key: %s - %s", err, stderr)
  160. }
  161. if strings.Contains(stdout, "is not a public key file") {
  162. return "", 0, ErrKeyUnableVerify{stdout}
  163. }
  164. fields := strings.Split(stdout, " ")
  165. if len(fields) < 4 {
  166. return "", 0, fmt.Errorf("invalid public key line: %s", stdout)
  167. }
  168. keyType := strings.Trim(fields[len(fields)-1], "()\r\n")
  169. return strings.ToLower(keyType), com.StrTo(fields[0]).MustInt(), nil
  170. }
  171. // SSHNativeParsePublicKey extracts the key type and length using the golang SSH library.
  172. func SSHNativeParsePublicKey(keyLine string) (string, int, error) {
  173. fields := strings.Fields(keyLine)
  174. if len(fields) < 2 {
  175. return "", 0, fmt.Errorf("not enough fields in public key line: %s", keyLine)
  176. }
  177. raw, err := base64.StdEncoding.DecodeString(fields[1])
  178. if err != nil {
  179. return "", 0, err
  180. }
  181. pkey, err := ssh.ParsePublicKey(raw)
  182. if err != nil {
  183. if strings.Contains(err.Error(), "ssh: unknown key algorithm") {
  184. return "", 0, ErrKeyUnableVerify{err.Error()}
  185. }
  186. return "", 0, fmt.Errorf("ParsePublicKey: %v", err)
  187. }
  188. // The ssh library can parse the key, so next we find out what key exactly we have.
  189. switch pkey.Type() {
  190. case ssh.KeyAlgoDSA:
  191. rawPub := struct {
  192. Name string
  193. P, Q, G, Y *big.Int
  194. }{}
  195. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  196. return "", 0, err
  197. }
  198. // as per https://bugzilla.mindrot.org/show_bug.cgi?id=1647 we should never
  199. // see dsa keys != 1024 bit, but as it seems to work, we will not check here
  200. return "dsa", rawPub.P.BitLen(), nil // use P as per crypto/dsa/dsa.go (is L)
  201. case ssh.KeyAlgoRSA:
  202. rawPub := struct {
  203. Name string
  204. E *big.Int
  205. N *big.Int
  206. }{}
  207. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  208. return "", 0, err
  209. }
  210. return "rsa", rawPub.N.BitLen(), nil // use N as per crypto/rsa/rsa.go (is bits)
  211. case ssh.KeyAlgoECDSA256:
  212. return "ecdsa", 256, nil
  213. case ssh.KeyAlgoECDSA384:
  214. return "ecdsa", 384, nil
  215. case ssh.KeyAlgoECDSA521:
  216. return "ecdsa", 521, nil
  217. case ssh.KeyAlgoED25519:
  218. return "ed25519", 256, nil
  219. }
  220. return "", 0, fmt.Errorf("unsupported key length detection for type: %s", pkey.Type())
  221. }
  222. // CheckPublicKeyString checks if the given public key string is recognized by SSH.
  223. // It returns the actual public key line on success.
  224. func CheckPublicKeyString(content string) (_ string, err error) {
  225. if setting.SSH.Disabled {
  226. return "", ErrSSHDisabled{}
  227. }
  228. content, err = parseKeyString(content)
  229. if err != nil {
  230. return "", err
  231. }
  232. content = strings.TrimRight(content, "\n\r")
  233. if strings.ContainsAny(content, "\n\r") {
  234. return "", errors.New("only a single line with a single key please")
  235. }
  236. // remove any unnecessary whitespace now
  237. content = strings.TrimSpace(content)
  238. if !setting.SSH.MinimumKeySizeCheck {
  239. return content, nil
  240. }
  241. var (
  242. fnName string
  243. keyType string
  244. length int
  245. )
  246. if setting.SSH.StartBuiltinServer {
  247. fnName = "SSHNativeParsePublicKey"
  248. keyType, length, err = SSHNativeParsePublicKey(content)
  249. } else {
  250. fnName = "SSHKeyGenParsePublicKey"
  251. keyType, length, err = SSHKeyGenParsePublicKey(content)
  252. }
  253. if err != nil {
  254. return "", fmt.Errorf("%s: %v", fnName, err)
  255. }
  256. log.Trace("Key info [native: %v]: %s-%d", setting.SSH.StartBuiltinServer, keyType, length)
  257. if minLen, found := setting.SSH.MinimumKeySizes[keyType]; found && length >= minLen {
  258. return content, nil
  259. } else if found && length < minLen {
  260. return "", fmt.Errorf("key length is not enough: got %d, needs %d", length, minLen)
  261. }
  262. return "", fmt.Errorf("key type is not allowed: %s", keyType)
  263. }
  264. // appendAuthorizedKeysToFile appends new SSH keys' content to authorized_keys file.
  265. func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
  266. // Don't need to rewrite this file if builtin SSH server is enabled.
  267. if setting.SSH.StartBuiltinServer {
  268. return nil
  269. }
  270. sshOpLocker.Lock()
  271. defer sshOpLocker.Unlock()
  272. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  273. f, err := os.OpenFile(fPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  274. if err != nil {
  275. return err
  276. }
  277. defer f.Close()
  278. // Note: chmod command does not support in Windows.
  279. if !setting.IsWindows {
  280. fi, err := f.Stat()
  281. if err != nil {
  282. return err
  283. }
  284. // .ssh directory should have mode 700, and authorized_keys file should have mode 600.
  285. if fi.Mode().Perm() > 0600 {
  286. log.Error(4, "authorized_keys file has unusual permission flags: %s - setting to -rw-------", fi.Mode().Perm().String())
  287. if err = f.Chmod(0600); err != nil {
  288. return err
  289. }
  290. }
  291. }
  292. for _, key := range keys {
  293. if _, err = f.WriteString(key.AuthorizedString()); err != nil {
  294. return err
  295. }
  296. }
  297. return nil
  298. }
  299. // checkKeyFingerprint only checks if key fingerprint has been used as public key,
  300. // it is OK to use same key as deploy key for multiple repositories/users.
  301. func checkKeyFingerprint(e Engine, fingerprint string) error {
  302. has, err := e.Get(&PublicKey{
  303. Fingerprint: fingerprint,
  304. Type: KeyTypeUser,
  305. })
  306. if err != nil {
  307. return err
  308. } else if has {
  309. return ErrKeyAlreadyExist{0, fingerprint, ""}
  310. }
  311. return nil
  312. }
  313. func calcFingerprint(publicKeyContent string) (string, error) {
  314. // Calculate fingerprint.
  315. tmpPath, err := writeTmpKeyFile(publicKeyContent)
  316. if err != nil {
  317. return "", err
  318. }
  319. defer os.Remove(tmpPath)
  320. stdout, stderr, err := process.GetManager().Exec("AddPublicKey", "ssh-keygen", "-lf", tmpPath)
  321. if err != nil {
  322. return "", fmt.Errorf("'ssh-keygen -lf %s' failed with error '%s': %s", tmpPath, err, stderr)
  323. } else if len(stdout) < 2 {
  324. return "", errors.New("not enough output for calculating fingerprint: " + stdout)
  325. }
  326. return strings.Split(stdout, " ")[1], nil
  327. }
  328. func addKey(e Engine, key *PublicKey) (err error) {
  329. if len(key.Fingerprint) <= 0 {
  330. key.Fingerprint, err = calcFingerprint(key.Content)
  331. if err != nil {
  332. return err
  333. }
  334. }
  335. // Save SSH key.
  336. if _, err = e.Insert(key); err != nil {
  337. return err
  338. }
  339. return appendAuthorizedKeysToFile(key)
  340. }
  341. // AddPublicKey adds new public key to database and authorized_keys file.
  342. func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) {
  343. log.Trace(content)
  344. fingerprint, err := calcFingerprint(content)
  345. if err != nil {
  346. return nil, err
  347. }
  348. if err := checkKeyFingerprint(x, fingerprint); err != nil {
  349. return nil, err
  350. }
  351. // Key name of same user cannot be duplicated.
  352. has, err := x.
  353. Where("owner_id = ? AND name = ?", ownerID, name).
  354. Get(new(PublicKey))
  355. if err != nil {
  356. return nil, err
  357. } else if has {
  358. return nil, ErrKeyNameAlreadyUsed{ownerID, name}
  359. }
  360. sess := x.NewSession()
  361. defer sess.Close()
  362. if err = sess.Begin(); err != nil {
  363. return nil, err
  364. }
  365. key := &PublicKey{
  366. OwnerID: ownerID,
  367. Name: name,
  368. Fingerprint: fingerprint,
  369. Content: content,
  370. Mode: AccessModeWrite,
  371. Type: KeyTypeUser,
  372. }
  373. if err = addKey(sess, key); err != nil {
  374. return nil, fmt.Errorf("addKey: %v", err)
  375. }
  376. return key, sess.Commit()
  377. }
  378. // GetPublicKeyByID returns public key by given ID.
  379. func GetPublicKeyByID(keyID int64) (*PublicKey, error) {
  380. key := new(PublicKey)
  381. has, err := x.
  382. Id(keyID).
  383. Get(key)
  384. if err != nil {
  385. return nil, err
  386. } else if !has {
  387. return nil, ErrKeyNotExist{keyID}
  388. }
  389. return key, nil
  390. }
  391. // SearchPublicKeyByContent searches content as prefix (leak e-mail part)
  392. // and returns public key found.
  393. func SearchPublicKeyByContent(content string) (*PublicKey, error) {
  394. key := new(PublicKey)
  395. has, err := x.
  396. Where("content like ?", content+"%").
  397. Get(key)
  398. if err != nil {
  399. return nil, err
  400. } else if !has {
  401. return nil, ErrKeyNotExist{}
  402. }
  403. return key, nil
  404. }
  405. // ListPublicKeys returns a list of public keys belongs to given user.
  406. func ListPublicKeys(uid int64) ([]*PublicKey, error) {
  407. keys := make([]*PublicKey, 0, 5)
  408. return keys, x.
  409. Where("owner_id = ?", uid).
  410. Find(&keys)
  411. }
  412. // UpdatePublicKeyUpdated updates public key use time.
  413. func UpdatePublicKeyUpdated(id int64) error {
  414. // Check if key exists before update as affected rows count is unreliable
  415. // and will return 0 affected rows if two updates are made at the same time
  416. if cnt, err := x.ID(id).Count(&PublicKey{}); err != nil {
  417. return err
  418. } else if cnt != 1 {
  419. return ErrKeyNotExist{id}
  420. }
  421. _, err := x.ID(id).Cols("updated_unix").Update(&PublicKey{
  422. UpdatedUnix: util.TimeStampNow(),
  423. })
  424. if err != nil {
  425. return err
  426. }
  427. return nil
  428. }
  429. // deletePublicKeys does the actual key deletion but does not update authorized_keys file.
  430. func deletePublicKeys(e *xorm.Session, keyIDs ...int64) error {
  431. if len(keyIDs) == 0 {
  432. return nil
  433. }
  434. _, err := e.In("id", keyIDs).Delete(new(PublicKey))
  435. return err
  436. }
  437. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  438. func DeletePublicKey(doer *User, id int64) (err error) {
  439. key, err := GetPublicKeyByID(id)
  440. if err != nil {
  441. return err
  442. }
  443. // Check if user has access to delete this key.
  444. if !doer.IsAdmin && doer.ID != key.OwnerID {
  445. return ErrKeyAccessDenied{doer.ID, key.ID, "public"}
  446. }
  447. sess := x.NewSession()
  448. defer sess.Close()
  449. if err = sess.Begin(); err != nil {
  450. return err
  451. }
  452. if err = deletePublicKeys(sess, id); err != nil {
  453. return err
  454. }
  455. if err = sess.Commit(); err != nil {
  456. return err
  457. }
  458. return RewriteAllPublicKeys()
  459. }
  460. // RewriteAllPublicKeys removes any authorized key and rewrite all keys from database again.
  461. // Note: x.Iterate does not get latest data after insert/delete, so we have to call this function
  462. // outside any session scope independently.
  463. func RewriteAllPublicKeys() error {
  464. //Don't rewrite key if internal server
  465. if setting.SSH.StartBuiltinServer {
  466. return nil
  467. }
  468. sshOpLocker.Lock()
  469. defer sshOpLocker.Unlock()
  470. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  471. tmpPath := fPath + ".tmp"
  472. t, err := os.OpenFile(tmpPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  473. if err != nil {
  474. return err
  475. }
  476. defer func() {
  477. t.Close()
  478. os.Remove(tmpPath)
  479. }()
  480. if setting.SSH.AuthorizedKeysBackup && com.IsExist(fPath) {
  481. bakPath := fmt.Sprintf("%s_%d.gitea_bak", fPath, time.Now().Unix())
  482. if err = com.Copy(fPath, bakPath); err != nil {
  483. return err
  484. }
  485. }
  486. err = x.Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
  487. _, err = t.WriteString((bean.(*PublicKey)).AuthorizedString())
  488. return err
  489. })
  490. if err != nil {
  491. return err
  492. }
  493. if com.IsExist(fPath) {
  494. f, err := os.Open(fPath)
  495. if err != nil {
  496. return err
  497. }
  498. scanner := bufio.NewScanner(f)
  499. for scanner.Scan() {
  500. line := scanner.Text()
  501. if strings.HasPrefix(line, tplCommentPrefix) {
  502. scanner.Scan()
  503. continue
  504. }
  505. _, err = t.WriteString(line + "\n")
  506. if err != nil {
  507. return err
  508. }
  509. }
  510. defer f.Close()
  511. }
  512. return os.Rename(tmpPath, fPath)
  513. }
  514. // ________ .__ ____ __.
  515. // \______ \ ____ ______ | | ____ ___.__.| |/ _|____ ___.__.
  516. // | | \_/ __ \\____ \| | / _ < | || <_/ __ < | |
  517. // | ` \ ___/| |_> > |_( <_> )___ || | \ ___/\___ |
  518. // /_______ /\___ > __/|____/\____// ____||____|__ \___ > ____|
  519. // \/ \/|__| \/ \/ \/\/
  520. // DeployKey represents deploy key information and its relation with repository.
  521. type DeployKey struct {
  522. ID int64 `xorm:"pk autoincr"`
  523. KeyID int64 `xorm:"UNIQUE(s) INDEX"`
  524. RepoID int64 `xorm:"UNIQUE(s) INDEX"`
  525. Name string
  526. Fingerprint string
  527. Content string `xorm:"-"`
  528. Mode AccessMode `xorm:"NOT NULL DEFAULT 1"`
  529. CreatedUnix util.TimeStamp `xorm:"created"`
  530. UpdatedUnix util.TimeStamp `xorm:"updated"`
  531. HasRecentActivity bool `xorm:"-"`
  532. HasUsed bool `xorm:"-"`
  533. }
  534. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  535. func (key *DeployKey) AfterLoad() {
  536. key.HasUsed = key.UpdatedUnix > key.CreatedUnix
  537. key.HasRecentActivity = key.UpdatedUnix.AddDuration(7*24*time.Hour) > util.TimeStampNow()
  538. }
  539. // GetContent gets associated public key content.
  540. func (key *DeployKey) GetContent() error {
  541. pkey, err := GetPublicKeyByID(key.KeyID)
  542. if err != nil {
  543. return err
  544. }
  545. key.Content = pkey.Content
  546. return nil
  547. }
  548. // IsReadOnly checks if the key can only be used for read operations
  549. func (key *DeployKey) IsReadOnly() bool {
  550. return key.Mode == AccessModeRead
  551. }
  552. func checkDeployKey(e Engine, keyID, repoID int64, name string) error {
  553. // Note: We want error detail, not just true or false here.
  554. has, err := e.
  555. Where("key_id = ? AND repo_id = ?", keyID, repoID).
  556. Get(new(DeployKey))
  557. if err != nil {
  558. return err
  559. } else if has {
  560. return ErrDeployKeyAlreadyExist{keyID, repoID}
  561. }
  562. has, err = e.
  563. Where("repo_id = ? AND name = ?", repoID, name).
  564. Get(new(DeployKey))
  565. if err != nil {
  566. return err
  567. } else if has {
  568. return ErrDeployKeyNameAlreadyUsed{repoID, name}
  569. }
  570. return nil
  571. }
  572. // addDeployKey adds new key-repo relation.
  573. func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string, mode AccessMode) (*DeployKey, error) {
  574. if err := checkDeployKey(e, keyID, repoID, name); err != nil {
  575. return nil, err
  576. }
  577. key := &DeployKey{
  578. KeyID: keyID,
  579. RepoID: repoID,
  580. Name: name,
  581. Fingerprint: fingerprint,
  582. Mode: mode,
  583. }
  584. _, err := e.Insert(key)
  585. return key, err
  586. }
  587. // HasDeployKey returns true if public key is a deploy key of given repository.
  588. func HasDeployKey(keyID, repoID int64) bool {
  589. has, _ := x.
  590. Where("key_id = ? AND repo_id = ?", keyID, repoID).
  591. Get(new(DeployKey))
  592. return has
  593. }
  594. // AddDeployKey add new deploy key to database and authorized_keys file.
  595. func AddDeployKey(repoID int64, name, content string, readOnly bool) (*DeployKey, error) {
  596. fingerprint, err := calcFingerprint(content)
  597. if err != nil {
  598. return nil, err
  599. }
  600. accessMode := AccessModeRead
  601. if !readOnly {
  602. accessMode = AccessModeWrite
  603. }
  604. pkey := &PublicKey{
  605. Fingerprint: fingerprint,
  606. Mode: accessMode,
  607. Type: KeyTypeDeploy,
  608. }
  609. has, err := x.Get(pkey)
  610. if err != nil {
  611. return nil, err
  612. }
  613. sess := x.NewSession()
  614. defer sess.Close()
  615. if err = sess.Begin(); err != nil {
  616. return nil, err
  617. }
  618. // First time use this deploy key.
  619. if !has {
  620. pkey.Content = content
  621. pkey.Name = name
  622. if err = addKey(sess, pkey); err != nil {
  623. return nil, fmt.Errorf("addKey: %v", err)
  624. }
  625. }
  626. key, err := addDeployKey(sess, pkey.ID, repoID, name, pkey.Fingerprint, accessMode)
  627. if err != nil {
  628. return nil, fmt.Errorf("addDeployKey: %v", err)
  629. }
  630. return key, sess.Commit()
  631. }
  632. // GetDeployKeyByID returns deploy key by given ID.
  633. func GetDeployKeyByID(id int64) (*DeployKey, error) {
  634. key := new(DeployKey)
  635. has, err := x.ID(id).Get(key)
  636. if err != nil {
  637. return nil, err
  638. } else if !has {
  639. return nil, ErrDeployKeyNotExist{id, 0, 0}
  640. }
  641. return key, nil
  642. }
  643. // GetDeployKeyByRepo returns deploy key by given public key ID and repository ID.
  644. func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) {
  645. key := &DeployKey{
  646. KeyID: keyID,
  647. RepoID: repoID,
  648. }
  649. has, err := x.Get(key)
  650. if err != nil {
  651. return nil, err
  652. } else if !has {
  653. return nil, ErrDeployKeyNotExist{0, keyID, repoID}
  654. }
  655. return key, nil
  656. }
  657. // UpdateDeployKeyCols updates deploy key information in the specified columns.
  658. func UpdateDeployKeyCols(key *DeployKey, cols ...string) error {
  659. _, err := x.ID(key.ID).Cols(cols...).Update(key)
  660. return err
  661. }
  662. // UpdateDeployKey updates deploy key information.
  663. func UpdateDeployKey(key *DeployKey) error {
  664. _, err := x.ID(key.ID).AllCols().Update(key)
  665. return err
  666. }
  667. // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed.
  668. func DeleteDeployKey(doer *User, id int64) error {
  669. key, err := GetDeployKeyByID(id)
  670. if err != nil {
  671. if IsErrDeployKeyNotExist(err) {
  672. return nil
  673. }
  674. return fmt.Errorf("GetDeployKeyByID: %v", err)
  675. }
  676. // Check if user has access to delete this key.
  677. if !doer.IsAdmin {
  678. repo, err := GetRepositoryByID(key.RepoID)
  679. if err != nil {
  680. return fmt.Errorf("GetRepositoryByID: %v", err)
  681. }
  682. yes, err := HasAccess(doer.ID, repo, AccessModeAdmin)
  683. if err != nil {
  684. return fmt.Errorf("HasAccess: %v", err)
  685. } else if !yes {
  686. return ErrKeyAccessDenied{doer.ID, key.ID, "deploy"}
  687. }
  688. }
  689. sess := x.NewSession()
  690. defer sess.Close()
  691. if err = sess.Begin(); err != nil {
  692. return err
  693. }
  694. if _, err = sess.ID(key.ID).Delete(new(DeployKey)); err != nil {
  695. return fmt.Errorf("delete deploy key [%d]: %v", key.ID, err)
  696. }
  697. // Check if this is the last reference to same key content.
  698. has, err := sess.
  699. Where("key_id = ?", key.KeyID).
  700. Get(new(DeployKey))
  701. if err != nil {
  702. return err
  703. } else if !has {
  704. if err = deletePublicKeys(sess, key.KeyID); err != nil {
  705. return err
  706. }
  707. }
  708. return sess.Commit()
  709. }
  710. // ListDeployKeys returns all deploy keys by given repository ID.
  711. func ListDeployKeys(repoID int64) ([]*DeployKey, error) {
  712. keys := make([]*DeployKey, 0, 5)
  713. return keys, x.
  714. Where("repo_id = ?", repoID).
  715. Find(&keys)
  716. }