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

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