ssh_key.go 21 KB

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