ssh_key.go 22 KB

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