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

ssh_key.go 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  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"
  12. "io/ioutil"
  13. "math/big"
  14. "os"
  15. "path"
  16. "path/filepath"
  17. "strings"
  18. "sync"
  19. "time"
  20. "github.com/Unknwon/com"
  21. "github.com/go-xorm/xorm"
  22. "golang.org/x/crypto/ssh"
  23. "github.com/gogits/gogs/modules/log"
  24. "github.com/gogits/gogs/modules/process"
  25. "github.com/gogits/gogs/modules/setting"
  26. )
  27. const (
  28. // "### autogenerated by gitgos, DO NOT EDIT\n"
  29. _TPL_PUBLICK_KEY = `command="%s serv key-%d --config='%s'",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
  30. )
  31. var sshOpLocker = sync.Mutex{}
  32. type KeyType int
  33. const (
  34. KEY_TYPE_USER = iota + 1
  35. KEY_TYPE_DEPLOY
  36. )
  37. // PublicKey represents a SSH or deploy key.
  38. type PublicKey struct {
  39. ID int64 `xorm:"pk autoincr"`
  40. OwnerID int64 `xorm:"INDEX NOT NULL"`
  41. Name string `xorm:"NOT NULL"`
  42. Fingerprint string `xorm:"NOT NULL"`
  43. Content string `xorm:"TEXT NOT NULL"`
  44. Mode AccessMode `xorm:"NOT NULL DEFAULT 2"`
  45. Type KeyType `xorm:"NOT NULL DEFAULT 1"`
  46. Created time.Time `xorm:"CREATED"`
  47. Updated time.Time // Note: Updated must below Created for AfterSet.
  48. HasRecentActivity bool `xorm:"-"`
  49. HasUsed bool `xorm:"-"`
  50. }
  51. func (k *PublicKey) AfterSet(colName string, _ xorm.Cell) {
  52. switch colName {
  53. case "created":
  54. k.HasUsed = k.Updated.After(k.Created)
  55. k.HasRecentActivity = k.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  56. }
  57. }
  58. // OmitEmail returns content of public key but without e-mail address.
  59. func (k *PublicKey) OmitEmail() string {
  60. return strings.Join(strings.Split(k.Content, " ")[:2], " ")
  61. }
  62. // GetAuthorizedString generates and returns formatted public key string for authorized_keys file.
  63. func (key *PublicKey) GetAuthorizedString() string {
  64. return fmt.Sprintf(_TPL_PUBLICK_KEY, 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")
  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. s := strings.Replace(strings.Replace(strings.TrimSpace(content), "\r\n", "\n", -1), "\r", "\n", -1)
  81. lines := strings.Split(s, "\n")
  82. var keyType, keyContent, keyComment string
  83. if len(lines) == 1 {
  84. // Parse openssh format
  85. parts := strings.SplitN(lines[0], " ", 3)
  86. switch len(parts) {
  87. case 0:
  88. return "", errors.New("Empty key")
  89. case 1:
  90. keyContent = parts[0]
  91. case 2:
  92. keyType = parts[0]
  93. keyContent = parts[1]
  94. default:
  95. keyType = parts[0]
  96. keyContent = parts[1]
  97. keyComment = parts[2]
  98. }
  99. // If keyType is not given, extract it from content. If given, validate it
  100. if len(keyType) == 0 {
  101. if t, err := extractTypeFromBase64Key(keyContent); err == nil {
  102. keyType = t
  103. } else {
  104. return "", err
  105. }
  106. } else {
  107. if t, err := extractTypeFromBase64Key(keyContent); err != nil || keyType != t {
  108. return "", err
  109. }
  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. if t, err := extractTypeFromBase64Key(keyContent); err == nil {
  126. keyType = t
  127. } else {
  128. return "", err
  129. }
  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, "gogs_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("tmpFile.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.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. // NOTE: ed25519 is not supported.
  173. func SSHNativeParsePublicKey(keyLine string) (string, int, error) {
  174. fields := strings.Fields(keyLine)
  175. if len(fields) < 2 {
  176. return "", 0, fmt.Errorf("not enough fields in public key line: %s", string(keyLine))
  177. }
  178. raw, err := base64.StdEncoding.DecodeString(fields[1])
  179. if err != nil {
  180. return "", 0, err
  181. }
  182. pkey, err := ssh.ParsePublicKey(raw)
  183. if err != nil {
  184. if strings.Contains(err.Error(), "ssh: unknown key algorithm") {
  185. return "", 0, ErrKeyUnableVerify{err.Error()}
  186. }
  187. return "", 0, fmt.Errorf("ssh.ParsePublicKey: %v", err)
  188. }
  189. // The ssh library can parse the key, so next we find out what key exactly we have.
  190. switch pkey.Type() {
  191. case ssh.KeyAlgoDSA:
  192. rawPub := struct {
  193. Name string
  194. P, Q, G, Y *big.Int
  195. }{}
  196. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  197. return "", 0, err
  198. }
  199. // as per https://bugzilla.mindrot.org/show_bug.cgi?id=1647 we should never
  200. // see dsa keys != 1024 bit, but as it seems to work, we will not check here
  201. return "dsa", rawPub.P.BitLen(), nil // use P as per crypto/dsa/dsa.go (is L)
  202. case ssh.KeyAlgoRSA:
  203. rawPub := struct {
  204. Name string
  205. E *big.Int
  206. N *big.Int
  207. }{}
  208. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  209. return "", 0, err
  210. }
  211. return "rsa", rawPub.N.BitLen(), nil // use N as per crypto/rsa/rsa.go (is bits)
  212. case ssh.KeyAlgoECDSA256:
  213. return "ecdsa", 256, nil
  214. case ssh.KeyAlgoECDSA384:
  215. return "ecdsa", 384, nil
  216. case ssh.KeyAlgoECDSA521:
  217. return "ecdsa", 521, nil
  218. case "ssh-ed25519": // TODO replace with ssh constant when available
  219. return "ed25519", 256, nil
  220. }
  221. return "", 0, fmt.Errorf("Unsupported key length detection for type: %s", pkey.Type())
  222. }
  223. // CheckPublicKeyString checks if the given public key string is recognized by SSH.
  224. //
  225. // The function returns the actual public key line on success.
  226. func CheckPublicKeyString(content string) (_ string, err error) {
  227. if setting.SSH.Disabled {
  228. return "", errors.New("SSH is disabled")
  229. }
  230. content, err = parseKeyString(content)
  231. if err != nil {
  232. return "", err
  233. }
  234. content = strings.TrimRight(content, "\n\r")
  235. if strings.ContainsAny(content, "\n\r") {
  236. return "", errors.New("only a single line with a single key please")
  237. }
  238. // remove any unnecessary whitespace now
  239. content = strings.TrimSpace(content)
  240. var (
  241. keyType string
  242. length int
  243. )
  244. if setting.SSH.StartBuiltinServer {
  245. keyType, length, err = SSHNativeParsePublicKey(content)
  246. } else {
  247. keyType, length, err = SSHKeyGenParsePublicKey(content)
  248. }
  249. if err != nil {
  250. return "", fmt.Errorf("ParsePublicKey: %v", err)
  251. }
  252. log.Trace("Key info [native: %v]: %s-%d", setting.SSH.StartBuiltinServer, keyType, length)
  253. if !setting.SSH.MinimumKeySizeCheck {
  254. return content, nil
  255. }
  256. if minLen, found := setting.SSH.MinimumKeySizes[keyType]; found && length >= minLen {
  257. return content, nil
  258. } else if found && length < minLen {
  259. return "", fmt.Errorf("Key length is not enough: got %d, needs %d", length, minLen)
  260. }
  261. return "", fmt.Errorf("Key type is not allowed: %s", keyType)
  262. }
  263. // saveAuthorizedKeyFile writes SSH key content to authorized_keys file.
  264. func saveAuthorizedKeyFile(keys ...*PublicKey) error {
  265. sshOpLocker.Lock()
  266. defer sshOpLocker.Unlock()
  267. fpath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  268. f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  269. if err != nil {
  270. return err
  271. }
  272. defer f.Close()
  273. fi, err := f.Stat()
  274. if err != nil {
  275. return err
  276. }
  277. // FIXME: following command does not support in Windows.
  278. if !setting.IsWindows {
  279. // .ssh directory should have mode 700, and authorized_keys file should have mode 600.
  280. if fi.Mode().Perm() > 0600 {
  281. log.Error(4, "authorized_keys file has unusual permission flags: %s - setting to -rw-------", fi.Mode().Perm().String())
  282. if err = f.Chmod(0600); err != nil {
  283. return err
  284. }
  285. }
  286. }
  287. for _, key := range keys {
  288. if _, err = f.WriteString(key.GetAuthorizedString()); err != nil {
  289. return err
  290. }
  291. }
  292. return nil
  293. }
  294. // checkKeyContent onlys checks if key content has been used as public key,
  295. // it is OK to use same key as deploy key for multiple repositories/users.
  296. func checkKeyContent(content string) error {
  297. has, err := x.Get(&PublicKey{
  298. Content: content,
  299. Type: KEY_TYPE_USER,
  300. })
  301. if err != nil {
  302. return err
  303. } else if has {
  304. return ErrKeyAlreadyExist{0, content}
  305. }
  306. return nil
  307. }
  308. func addKey(e Engine, key *PublicKey) (err error) {
  309. // Calculate fingerprint.
  310. tmpPath := strings.Replace(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
  311. "id_rsa.pub"), "\\", "/", -1)
  312. os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
  313. if err = ioutil.WriteFile(tmpPath, []byte(key.Content), 0644); err != nil {
  314. return err
  315. }
  316. stdout, stderr, err := process.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. key.Fingerprint = strings.Split(stdout, " ")[1]
  323. // Save SSH key.
  324. if _, err = e.Insert(key); err != nil {
  325. return err
  326. }
  327. // Don't need to rewrite this file if builtin SSH server is enabled.
  328. if setting.SSH.StartBuiltinServer {
  329. return nil
  330. }
  331. return saveAuthorizedKeyFile(key)
  332. }
  333. // AddPublicKey adds new public key to database and authorized_keys file.
  334. func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) {
  335. log.Trace(content)
  336. if err := checkKeyContent(content); err != nil {
  337. return nil, err
  338. }
  339. // Key name of same user cannot be duplicated.
  340. has, err := x.Where("owner_id=? AND name=?", ownerID, name).Get(new(PublicKey))
  341. if err != nil {
  342. return nil, err
  343. } else if has {
  344. return nil, ErrKeyNameAlreadyUsed{ownerID, name}
  345. }
  346. sess := x.NewSession()
  347. defer sessionRelease(sess)
  348. if err = sess.Begin(); err != nil {
  349. return nil, err
  350. }
  351. key := &PublicKey{
  352. OwnerID: ownerID,
  353. Name: name,
  354. Content: content,
  355. Mode: ACCESS_MODE_WRITE,
  356. Type: KEY_TYPE_USER,
  357. }
  358. if err = addKey(sess, key); err != nil {
  359. return nil, fmt.Errorf("addKey: %v", err)
  360. }
  361. return key, sess.Commit()
  362. }
  363. // GetPublicKeyByID returns public key by given ID.
  364. func GetPublicKeyByID(keyID int64) (*PublicKey, error) {
  365. key := new(PublicKey)
  366. has, err := x.Id(keyID).Get(key)
  367. if err != nil {
  368. return nil, err
  369. } else if !has {
  370. return nil, ErrKeyNotExist{keyID}
  371. }
  372. return key, nil
  373. }
  374. // SearchPublicKeyByContent searches content as prefix (leak e-mail part)
  375. // and returns public key found.
  376. func SearchPublicKeyByContent(content string) (*PublicKey, error) {
  377. key := new(PublicKey)
  378. has, err := x.Where("content like ?", content+"%").Get(key)
  379. if err != nil {
  380. return nil, err
  381. } else if !has {
  382. return nil, ErrKeyNotExist{}
  383. }
  384. return key, nil
  385. }
  386. // ListPublicKeys returns a list of public keys belongs to given user.
  387. func ListPublicKeys(uid int64) ([]*PublicKey, error) {
  388. keys := make([]*PublicKey, 0, 5)
  389. return keys, x.Where("owner_id=?", uid).Find(&keys)
  390. }
  391. // rewriteAuthorizedKeys finds and deletes corresponding line in authorized_keys file.
  392. func rewriteAuthorizedKeys(key *PublicKey, p, tmpP string) error {
  393. fr, err := os.Open(p)
  394. if err != nil {
  395. return err
  396. }
  397. defer fr.Close()
  398. fw, err := os.OpenFile(tmpP, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  399. if err != nil {
  400. return err
  401. }
  402. defer fw.Close()
  403. isFound := false
  404. keyword := fmt.Sprintf("key-%d", key.ID)
  405. buf := bufio.NewReader(fr)
  406. for {
  407. line, errRead := buf.ReadString('\n')
  408. line = strings.TrimSpace(line)
  409. if errRead != nil {
  410. if errRead != io.EOF {
  411. return errRead
  412. }
  413. // Reached end of file, if nothing to read then break,
  414. // otherwise handle the last line.
  415. if len(line) == 0 {
  416. break
  417. }
  418. }
  419. // Found the line and copy rest of file.
  420. if !isFound && strings.Contains(line, keyword) && strings.Contains(line, key.Content) {
  421. isFound = true
  422. continue
  423. }
  424. // Still finding the line, copy the line that currently read.
  425. if _, err = fw.WriteString(line + "\n"); err != nil {
  426. return err
  427. }
  428. if errRead == io.EOF {
  429. break
  430. }
  431. }
  432. if !isFound {
  433. log.Warn("SSH key %d not found in authorized_keys file for deletion", key.ID)
  434. }
  435. return nil
  436. }
  437. // UpdatePublicKey updates given public key.
  438. func UpdatePublicKey(key *PublicKey) error {
  439. _, err := x.Id(key.ID).AllCols().Update(key)
  440. return err
  441. }
  442. func deletePublicKey(e *xorm.Session, keyID int64) error {
  443. sshOpLocker.Lock()
  444. defer sshOpLocker.Unlock()
  445. key := &PublicKey{ID: keyID}
  446. has, err := e.Get(key)
  447. if err != nil {
  448. return err
  449. } else if !has {
  450. return nil
  451. }
  452. if _, err = e.Id(key.ID).Delete(new(PublicKey)); err != nil {
  453. return err
  454. }
  455. // Don't need to rewrite this file if builtin SSH server is enabled.
  456. if setting.SSH.StartBuiltinServer {
  457. return nil
  458. }
  459. fpath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  460. tmpPath := fpath + ".tmp"
  461. if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil {
  462. return err
  463. } else if err = os.Remove(fpath); err != nil {
  464. return err
  465. }
  466. return os.Rename(tmpPath, fpath)
  467. }
  468. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  469. func DeletePublicKey(doer *User, id int64) (err error) {
  470. key, err := GetPublicKeyByID(id)
  471. if err != nil {
  472. if IsErrKeyNotExist(err) {
  473. return nil
  474. }
  475. return fmt.Errorf("GetPublicKeyByID: %v", err)
  476. }
  477. // Check if user has access to delete this key.
  478. if !doer.IsAdmin && doer.Id != key.OwnerID {
  479. return ErrKeyAccessDenied{doer.Id, key.ID, "public"}
  480. }
  481. sess := x.NewSession()
  482. defer sessionRelease(sess)
  483. if err = sess.Begin(); err != nil {
  484. return err
  485. }
  486. if err = deletePublicKey(sess, id); err != nil {
  487. return err
  488. }
  489. return sess.Commit()
  490. }
  491. // RewriteAllPublicKeys removes any authorized key and rewrite all keys from database again.
  492. func RewriteAllPublicKeys() error {
  493. sshOpLocker.Lock()
  494. defer sshOpLocker.Unlock()
  495. fpath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  496. tmpPath := fpath + ".tmp"
  497. f, err := os.OpenFile(tmpPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  498. if err != nil {
  499. return err
  500. }
  501. defer os.Remove(tmpPath)
  502. err = x.Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
  503. _, err = f.WriteString((bean.(*PublicKey)).GetAuthorizedString())
  504. return err
  505. })
  506. f.Close()
  507. if err != nil {
  508. return err
  509. }
  510. if com.IsExist(fpath) {
  511. if err = os.Remove(fpath); err != nil {
  512. return err
  513. }
  514. }
  515. if err = os.Rename(tmpPath, fpath); err != nil {
  516. return err
  517. }
  518. return nil
  519. }
  520. // ________ .__ ____ __.
  521. // \______ \ ____ ______ | | ____ ___.__.| |/ _|____ ___.__.
  522. // | | \_/ __ \\____ \| | / _ < | || <_/ __ < | |
  523. // | ` \ ___/| |_> > |_( <_> )___ || | \ ___/\___ |
  524. // /_______ /\___ > __/|____/\____// ____||____|__ \___ > ____|
  525. // \/ \/|__| \/ \/ \/\/
  526. // DeployKey represents deploy key information and its relation with repository.
  527. type DeployKey struct {
  528. ID int64 `xorm:"pk autoincr"`
  529. KeyID int64 `xorm:"UNIQUE(s) INDEX"`
  530. RepoID int64 `xorm:"UNIQUE(s) INDEX"`
  531. Name string
  532. Fingerprint string
  533. Content string `xorm:"-"`
  534. Created time.Time `xorm:"CREATED"`
  535. Updated time.Time // Note: Updated must below Created for AfterSet.
  536. HasRecentActivity bool `xorm:"-"`
  537. HasUsed bool `xorm:"-"`
  538. }
  539. func (k *DeployKey) AfterSet(colName string, _ xorm.Cell) {
  540. switch colName {
  541. case "created":
  542. k.HasUsed = k.Updated.After(k.Created)
  543. k.HasRecentActivity = k.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  544. }
  545. }
  546. // GetContent gets associated public key content.
  547. func (k *DeployKey) GetContent() error {
  548. pkey, err := GetPublicKeyByID(k.KeyID)
  549. if err != nil {
  550. return err
  551. }
  552. k.Content = pkey.Content
  553. return nil
  554. }
  555. func checkDeployKey(e Engine, keyID, repoID int64, name string) error {
  556. // Note: We want error detail, not just true or false here.
  557. has, err := e.Where("key_id=? AND repo_id=?", keyID, repoID).Get(new(DeployKey))
  558. if err != nil {
  559. return err
  560. } else if has {
  561. return ErrDeployKeyAlreadyExist{keyID, repoID}
  562. }
  563. has, err = e.Where("repo_id=? AND name=?", repoID, name).Get(new(DeployKey))
  564. if err != nil {
  565. return err
  566. } else if has {
  567. return ErrDeployKeyNameAlreadyUsed{repoID, name}
  568. }
  569. return nil
  570. }
  571. // addDeployKey adds new key-repo relation.
  572. func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string) (*DeployKey, error) {
  573. if err := checkDeployKey(e, keyID, repoID, name); err != nil {
  574. return nil, err
  575. }
  576. key := &DeployKey{
  577. KeyID: keyID,
  578. RepoID: repoID,
  579. Name: name,
  580. Fingerprint: fingerprint,
  581. }
  582. _, err := e.Insert(key)
  583. return key, err
  584. }
  585. // HasDeployKey returns true if public key is a deploy key of given repository.
  586. func HasDeployKey(keyID, repoID int64) bool {
  587. has, _ := x.Where("key_id=? AND repo_id=?", keyID, repoID).Get(new(DeployKey))
  588. return has
  589. }
  590. // AddDeployKey add new deploy key to database and authorized_keys file.
  591. func AddDeployKey(repoID int64, name, content string) (*DeployKey, error) {
  592. if err := checkKeyContent(content); err != nil {
  593. return nil, err
  594. }
  595. pkey := &PublicKey{
  596. Content: content,
  597. Mode: ACCESS_MODE_READ,
  598. Type: KEY_TYPE_DEPLOY,
  599. }
  600. has, err := x.Get(pkey)
  601. if err != nil {
  602. return nil, err
  603. }
  604. sess := x.NewSession()
  605. defer sessionRelease(sess)
  606. if err = sess.Begin(); err != nil {
  607. return nil, err
  608. }
  609. // First time use this deploy key.
  610. if !has {
  611. if err = addKey(sess, pkey); err != nil {
  612. return nil, fmt.Errorf("addKey: %v", err)
  613. }
  614. }
  615. key, err := addDeployKey(sess, pkey.ID, repoID, name, pkey.Fingerprint)
  616. if err != nil {
  617. return nil, fmt.Errorf("addDeployKey: %v", err)
  618. }
  619. return key, sess.Commit()
  620. }
  621. // GetDeployKeyByID returns deploy key by given ID.
  622. func GetDeployKeyByID(id int64) (*DeployKey, error) {
  623. key := new(DeployKey)
  624. has, err := x.Id(id).Get(key)
  625. if err != nil {
  626. return nil, err
  627. } else if !has {
  628. return nil, ErrDeployKeyNotExist{id, 0, 0}
  629. }
  630. return key, nil
  631. }
  632. // GetDeployKeyByRepo returns deploy key by given public key ID and repository ID.
  633. func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) {
  634. key := &DeployKey{
  635. KeyID: keyID,
  636. RepoID: repoID,
  637. }
  638. has, err := x.Get(key)
  639. if err != nil {
  640. return nil, err
  641. } else if !has {
  642. return nil, ErrDeployKeyNotExist{0, keyID, repoID}
  643. }
  644. return key, nil
  645. }
  646. // UpdateDeployKey updates deploy key information.
  647. func UpdateDeployKey(key *DeployKey) error {
  648. _, err := x.Id(key.ID).AllCols().Update(key)
  649. return err
  650. }
  651. // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed.
  652. func DeleteDeployKey(doer *User, id int64) error {
  653. key, err := GetDeployKeyByID(id)
  654. if err != nil {
  655. if IsErrDeployKeyNotExist(err) {
  656. return nil
  657. }
  658. return fmt.Errorf("GetDeployKeyByID: %v", err)
  659. }
  660. // Check if user has access to delete this key.
  661. if !doer.IsAdmin {
  662. repo, err := GetRepositoryByID(key.RepoID)
  663. if err != nil {
  664. return fmt.Errorf("GetRepositoryByID: %v", err)
  665. }
  666. yes, err := HasAccess(doer, repo, ACCESS_MODE_ADMIN)
  667. if err != nil {
  668. return fmt.Errorf("HasAccess: %v", err)
  669. } else if !yes {
  670. return ErrKeyAccessDenied{doer.Id, key.ID, "deploy"}
  671. }
  672. }
  673. sess := x.NewSession()
  674. defer sessionRelease(sess)
  675. if err = sess.Begin(); err != nil {
  676. return err
  677. }
  678. if _, err = sess.Id(key.ID).Delete(new(DeployKey)); err != nil {
  679. return fmt.Errorf("delete deploy key[%d]: %v", key.ID, err)
  680. }
  681. // Check if this is the last reference to same key content.
  682. has, err := sess.Where("key_id=?", key.KeyID).Get(new(DeployKey))
  683. if err != nil {
  684. return err
  685. } else if !has {
  686. if err = deletePublicKey(sess, key.KeyID); err != nil {
  687. return err
  688. }
  689. }
  690. return sess.Commit()
  691. }
  692. // ListDeployKeys returns all deploy keys by given repository ID.
  693. func ListDeployKeys(repoID int64) ([]*DeployKey, error) {
  694. keys := make([]*DeployKey, 0, 5)
  695. return keys, x.Where("repo_id=?", repoID).Find(&keys)
  696. }