ssh_key.go 21 KB

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