ssh_key.go 22 KB

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