You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ssh_key.go 22 kB

11 years ago
11 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  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. sshOpLocker.Lock()
  267. defer sshOpLocker.Unlock()
  268. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  269. f, err := os.OpenFile(fPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  270. if err != nil {
  271. return err
  272. }
  273. defer f.Close()
  274. // Note: chmod command does not support in Windows.
  275. if !setting.IsWindows {
  276. fi, err := f.Stat()
  277. if err != nil {
  278. return err
  279. }
  280. // .ssh directory should have mode 700, and authorized_keys file should have mode 600.
  281. if fi.Mode().Perm() > 0600 {
  282. log.Error(4, "authorized_keys file has unusual permission flags: %s - setting to -rw-------", fi.Mode().Perm().String())
  283. if err = f.Chmod(0600); err != nil {
  284. return err
  285. }
  286. }
  287. }
  288. for _, key := range keys {
  289. if _, err = f.WriteString(key.AuthorizedString()); err != nil {
  290. return err
  291. }
  292. }
  293. return nil
  294. }
  295. // checkKeyFingerprint only checks if key fingerprint has been used as public key,
  296. // it is OK to use same key as deploy key for multiple repositories/users.
  297. func checkKeyFingerprint(e Engine, fingerprint string) error {
  298. has, err := e.Get(&PublicKey{
  299. Fingerprint: fingerprint,
  300. Type: KeyTypeUser,
  301. })
  302. if err != nil {
  303. return err
  304. } else if has {
  305. return ErrKeyAlreadyExist{0, fingerprint, ""}
  306. }
  307. return nil
  308. }
  309. func calcFingerprint(publicKeyContent string) (string, error) {
  310. // Calculate fingerprint.
  311. tmpPath, err := writeTmpKeyFile(publicKeyContent)
  312. if err != nil {
  313. return "", err
  314. }
  315. defer os.Remove(tmpPath)
  316. stdout, stderr, err := process.GetManager().Exec("AddPublicKey", "ssh-keygen", "-lf", tmpPath)
  317. if err != nil {
  318. return "", fmt.Errorf("'ssh-keygen -lf %s' failed with error '%s': %s", tmpPath, err, stderr)
  319. } else if len(stdout) < 2 {
  320. return "", errors.New("not enough output for calculating fingerprint: " + stdout)
  321. }
  322. return strings.Split(stdout, " ")[1], nil
  323. }
  324. func addKey(e Engine, key *PublicKey) (err error) {
  325. if len(key.Fingerprint) <= 0 {
  326. key.Fingerprint, err = calcFingerprint(key.Content)
  327. if err != nil {
  328. return err
  329. }
  330. }
  331. // Save SSH key.
  332. if _, err = e.Insert(key); err != nil {
  333. return err
  334. }
  335. // Don't need to rewrite this file if builtin SSH server is enabled.
  336. if setting.SSH.StartBuiltinServer {
  337. return nil
  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. sshOpLocker.Lock()
  465. defer sshOpLocker.Unlock()
  466. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  467. tmpPath := fPath + ".tmp"
  468. t, err := os.OpenFile(tmpPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  469. if err != nil {
  470. return err
  471. }
  472. defer func() {
  473. t.Close()
  474. os.Remove(tmpPath)
  475. }()
  476. if setting.SSH.AuthorizedKeysBackup && com.IsExist(fPath) {
  477. bakPath := fmt.Sprintf("%s_%d.gitea_bak", fPath, time.Now().Unix())
  478. if err = com.Copy(fPath, bakPath); err != nil {
  479. return err
  480. }
  481. }
  482. err = x.Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
  483. _, err = t.WriteString((bean.(*PublicKey)).AuthorizedString())
  484. return err
  485. })
  486. if err != nil {
  487. return err
  488. }
  489. if com.IsExist(fPath) {
  490. f, err := os.Open(fPath)
  491. if err != nil {
  492. return err
  493. }
  494. scanner := bufio.NewScanner(f)
  495. for scanner.Scan() {
  496. line := scanner.Text()
  497. if strings.HasPrefix(line, tplCommentPrefix) {
  498. scanner.Scan()
  499. continue
  500. }
  501. _, err = t.WriteString(line + "\n")
  502. if err != nil {
  503. return err
  504. }
  505. }
  506. defer f.Close()
  507. }
  508. return os.Rename(tmpPath, fPath)
  509. }
  510. // ________ .__ ____ __.
  511. // \______ \ ____ ______ | | ____ ___.__.| |/ _|____ ___.__.
  512. // | | \_/ __ \\____ \| | / _ < | || <_/ __ < | |
  513. // | ` \ ___/| |_> > |_( <_> )___ || | \ ___/\___ |
  514. // /_______ /\___ > __/|____/\____// ____||____|__ \___ > ____|
  515. // \/ \/|__| \/ \/ \/\/
  516. // DeployKey represents deploy key information and its relation with repository.
  517. type DeployKey struct {
  518. ID int64 `xorm:"pk autoincr"`
  519. KeyID int64 `xorm:"UNIQUE(s) INDEX"`
  520. RepoID int64 `xorm:"UNIQUE(s) INDEX"`
  521. Name string
  522. Fingerprint string
  523. Content string `xorm:"-"`
  524. CreatedUnix util.TimeStamp `xorm:"created"`
  525. UpdatedUnix util.TimeStamp `xorm:"updated"`
  526. HasRecentActivity bool `xorm:"-"`
  527. HasUsed bool `xorm:"-"`
  528. }
  529. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  530. func (key *DeployKey) AfterLoad() {
  531. key.HasUsed = key.UpdatedUnix > key.CreatedUnix
  532. key.HasRecentActivity = key.UpdatedUnix.AddDuration(7*24*time.Hour) > util.TimeStampNow()
  533. }
  534. // GetContent gets associated public key content.
  535. func (key *DeployKey) GetContent() error {
  536. pkey, err := GetPublicKeyByID(key.KeyID)
  537. if err != nil {
  538. return err
  539. }
  540. key.Content = pkey.Content
  541. return nil
  542. }
  543. func checkDeployKey(e Engine, keyID, repoID int64, name string) error {
  544. // Note: We want error detail, not just true or false here.
  545. has, err := e.
  546. Where("key_id = ? AND repo_id = ?", keyID, repoID).
  547. Get(new(DeployKey))
  548. if err != nil {
  549. return err
  550. } else if has {
  551. return ErrDeployKeyAlreadyExist{keyID, repoID}
  552. }
  553. has, err = e.
  554. Where("repo_id = ? AND name = ?", repoID, name).
  555. Get(new(DeployKey))
  556. if err != nil {
  557. return err
  558. } else if has {
  559. return ErrDeployKeyNameAlreadyUsed{repoID, name}
  560. }
  561. return nil
  562. }
  563. // addDeployKey adds new key-repo relation.
  564. func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string) (*DeployKey, error) {
  565. if err := checkDeployKey(e, keyID, repoID, name); err != nil {
  566. return nil, err
  567. }
  568. key := &DeployKey{
  569. KeyID: keyID,
  570. RepoID: repoID,
  571. Name: name,
  572. Fingerprint: fingerprint,
  573. }
  574. _, err := e.Insert(key)
  575. return key, err
  576. }
  577. // HasDeployKey returns true if public key is a deploy key of given repository.
  578. func HasDeployKey(keyID, repoID int64) bool {
  579. has, _ := x.
  580. Where("key_id = ? AND repo_id = ?", keyID, repoID).
  581. Get(new(DeployKey))
  582. return has
  583. }
  584. // AddDeployKey add new deploy key to database and authorized_keys file.
  585. func AddDeployKey(repoID int64, name, content string) (*DeployKey, error) {
  586. fingerprint, err := calcFingerprint(content)
  587. if err != nil {
  588. return nil, err
  589. }
  590. pkey := &PublicKey{
  591. Fingerprint: fingerprint,
  592. Mode: AccessModeRead,
  593. Type: KeyTypeDeploy,
  594. }
  595. has, err := x.Get(pkey)
  596. if err != nil {
  597. return nil, err
  598. }
  599. sess := x.NewSession()
  600. defer sess.Close()
  601. if err = sess.Begin(); err != nil {
  602. return nil, err
  603. }
  604. // First time use this deploy key.
  605. if !has {
  606. pkey.Content = content
  607. pkey.Name = name
  608. if err = addKey(sess, pkey); err != nil {
  609. return nil, fmt.Errorf("addKey: %v", err)
  610. }
  611. }
  612. key, err := addDeployKey(sess, pkey.ID, repoID, name, pkey.Fingerprint)
  613. if err != nil {
  614. return nil, fmt.Errorf("addDeployKey: %v", err)
  615. }
  616. return key, sess.Commit()
  617. }
  618. // GetDeployKeyByID returns deploy key by given ID.
  619. func GetDeployKeyByID(id int64) (*DeployKey, error) {
  620. key := new(DeployKey)
  621. has, err := x.ID(id).Get(key)
  622. if err != nil {
  623. return nil, err
  624. } else if !has {
  625. return nil, ErrDeployKeyNotExist{id, 0, 0}
  626. }
  627. return key, nil
  628. }
  629. // GetDeployKeyByRepo returns deploy key by given public key ID and repository ID.
  630. func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) {
  631. key := &DeployKey{
  632. KeyID: keyID,
  633. RepoID: repoID,
  634. }
  635. has, err := x.Get(key)
  636. if err != nil {
  637. return nil, err
  638. } else if !has {
  639. return nil, ErrDeployKeyNotExist{0, keyID, repoID}
  640. }
  641. return key, nil
  642. }
  643. // UpdateDeployKeyCols updates deploy key information in the specified columns.
  644. func UpdateDeployKeyCols(key *DeployKey, cols ...string) error {
  645. _, err := x.ID(key.ID).Cols(cols...).Update(key)
  646. return err
  647. }
  648. // UpdateDeployKey updates deploy key information.
  649. func UpdateDeployKey(key *DeployKey) error {
  650. _, err := x.ID(key.ID).AllCols().Update(key)
  651. return err
  652. }
  653. // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed.
  654. func DeleteDeployKey(doer *User, id int64) error {
  655. key, err := GetDeployKeyByID(id)
  656. if err != nil {
  657. if IsErrDeployKeyNotExist(err) {
  658. return nil
  659. }
  660. return fmt.Errorf("GetDeployKeyByID: %v", err)
  661. }
  662. // Check if user has access to delete this key.
  663. if !doer.IsAdmin {
  664. repo, err := GetRepositoryByID(key.RepoID)
  665. if err != nil {
  666. return fmt.Errorf("GetRepositoryByID: %v", err)
  667. }
  668. yes, err := HasAccess(doer.ID, repo, AccessModeAdmin)
  669. if err != nil {
  670. return fmt.Errorf("HasAccess: %v", err)
  671. } else if !yes {
  672. return ErrKeyAccessDenied{doer.ID, key.ID, "deploy"}
  673. }
  674. }
  675. sess := x.NewSession()
  676. defer sess.Close()
  677. if err = sess.Begin(); err != nil {
  678. return err
  679. }
  680. if _, err = sess.ID(key.ID).Delete(new(DeployKey)); err != nil {
  681. return fmt.Errorf("delete deploy key [%d]: %v", key.ID, err)
  682. }
  683. // Check if this is the last reference to same key content.
  684. has, err := sess.
  685. Where("key_id = ?", key.KeyID).
  686. Get(new(DeployKey))
  687. if err != nil {
  688. return err
  689. } else if !has {
  690. if err = deletePublicKeys(sess, key.KeyID); err != nil {
  691. return err
  692. }
  693. }
  694. return sess.Commit()
  695. }
  696. // ListDeployKeys returns all deploy keys by given repository ID.
  697. func ListDeployKeys(repoID int64) ([]*DeployKey, error) {
  698. keys := make([]*DeployKey, 0, 5)
  699. return keys, x.
  700. Where("repo_id = ?", repoID).
  701. Find(&keys)
  702. }