ssh_key.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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/gogs/gogs/pkg/process"
  23. "github.com/gogs/gogs/pkg/setting"
  24. "github.com/gogs/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 RewriteAuthorizedKeys()
  443. }
  444. // RewriteAuthorizedKeys 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 RewriteAuthorizedKeys() error {
  448. sshOpLocker.Lock()
  449. defer sshOpLocker.Unlock()
  450. log.Trace("Doing: RewriteAuthorizedKeys")
  451. os.MkdirAll(setting.SSH.RootPath, os.ModePerm)
  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
  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.Where("key_id = ? AND repo_id = ?", keyID, repoID).Get(new(DeployKey))
  526. if err != nil {
  527. return err
  528. } else if has {
  529. return ErrDeployKeyAlreadyExist{keyID, repoID}
  530. }
  531. has, err = e.Where("repo_id = ? AND name = ?", repoID, name).Get(new(DeployKey))
  532. if err != nil {
  533. return err
  534. } else if has {
  535. return ErrDeployKeyNameAlreadyUsed{repoID, name}
  536. }
  537. return nil
  538. }
  539. // addDeployKey adds new key-repo relation.
  540. func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string) (*DeployKey, error) {
  541. if err := checkDeployKey(e, keyID, repoID, name); err != nil {
  542. return nil, err
  543. }
  544. key := &DeployKey{
  545. KeyID: keyID,
  546. RepoID: repoID,
  547. Name: name,
  548. Fingerprint: fingerprint,
  549. }
  550. _, err := e.Insert(key)
  551. return key, err
  552. }
  553. // HasDeployKey returns true if public key is a deploy key of given repository.
  554. func HasDeployKey(keyID, repoID int64) bool {
  555. has, _ := x.Where("key_id = ? AND repo_id = ?", keyID, repoID).Get(new(DeployKey))
  556. return has
  557. }
  558. // AddDeployKey add new deploy key to database and authorized_keys file.
  559. func AddDeployKey(repoID int64, name, content string) (*DeployKey, error) {
  560. if err := checkKeyContent(content); err != nil {
  561. return nil, err
  562. }
  563. pkey := &PublicKey{
  564. Content: content,
  565. Mode: ACCESS_MODE_READ,
  566. Type: KEY_TYPE_DEPLOY,
  567. }
  568. has, err := x.Get(pkey)
  569. if err != nil {
  570. return nil, err
  571. }
  572. sess := x.NewSession()
  573. defer sess.Close()
  574. if err = sess.Begin(); err != nil {
  575. return nil, err
  576. }
  577. // First time use this deploy key.
  578. if !has {
  579. if err = addKey(sess, pkey); err != nil {
  580. return nil, fmt.Errorf("addKey: %v", err)
  581. }
  582. }
  583. key, err := addDeployKey(sess, pkey.ID, repoID, name, pkey.Fingerprint)
  584. if err != nil {
  585. return nil, fmt.Errorf("addDeployKey: %v", err)
  586. }
  587. return key, sess.Commit()
  588. }
  589. // GetDeployKeyByID returns deploy key by given ID.
  590. func GetDeployKeyByID(id int64) (*DeployKey, error) {
  591. key := new(DeployKey)
  592. has, err := x.Id(id).Get(key)
  593. if err != nil {
  594. return nil, err
  595. } else if !has {
  596. return nil, ErrDeployKeyNotExist{id, 0, 0}
  597. }
  598. return key, nil
  599. }
  600. // GetDeployKeyByRepo returns deploy key by given public key ID and repository ID.
  601. func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) {
  602. key := &DeployKey{
  603. KeyID: keyID,
  604. RepoID: repoID,
  605. }
  606. has, err := x.Get(key)
  607. if err != nil {
  608. return nil, err
  609. } else if !has {
  610. return nil, ErrDeployKeyNotExist{0, keyID, repoID}
  611. }
  612. return key, nil
  613. }
  614. // UpdateDeployKey updates deploy key information.
  615. func UpdateDeployKey(key *DeployKey) error {
  616. _, err := x.Id(key.ID).AllCols().Update(key)
  617. return err
  618. }
  619. // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed.
  620. func DeleteDeployKey(doer *User, id int64) error {
  621. key, err := GetDeployKeyByID(id)
  622. if err != nil {
  623. if IsErrDeployKeyNotExist(err) {
  624. return nil
  625. }
  626. return fmt.Errorf("GetDeployKeyByID: %v", err)
  627. }
  628. // Check if user has access to delete this key.
  629. if !doer.IsAdmin {
  630. repo, err := GetRepositoryByID(key.RepoID)
  631. if err != nil {
  632. return fmt.Errorf("GetRepositoryByID: %v", err)
  633. }
  634. yes, err := HasAccess(doer.ID, repo, ACCESS_MODE_ADMIN)
  635. if err != nil {
  636. return fmt.Errorf("HasAccess: %v", err)
  637. } else if !yes {
  638. return ErrKeyAccessDenied{doer.ID, key.ID, "deploy"}
  639. }
  640. }
  641. sess := x.NewSession()
  642. defer sess.Close()
  643. if err = sess.Begin(); err != nil {
  644. return err
  645. }
  646. if _, err = sess.Id(key.ID).Delete(new(DeployKey)); err != nil {
  647. return fmt.Errorf("delete deploy key [%d]: %v", key.ID, err)
  648. }
  649. // Check if this is the last reference to same key content.
  650. has, err := sess.Where("key_id = ?", key.KeyID).Get(new(DeployKey))
  651. if err != nil {
  652. return err
  653. } else if !has {
  654. if err = deletePublicKeys(sess, key.KeyID); err != nil {
  655. return err
  656. }
  657. }
  658. return sess.Commit()
  659. }
  660. // ListDeployKeys returns all deploy keys by given repository ID.
  661. func ListDeployKeys(repoID int64) ([]*DeployKey, error) {
  662. keys := make([]*DeployKey, 0, 5)
  663. return keys, x.Where("repo_id = ?", repoID).Find(&keys)
  664. }