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 db
  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. "golang.org/x/crypto/ssh"
  20. log "gopkg.in/clog.v1"
  21. "xorm.io/xorm"
  22. "gogs.io/gogs/internal/process"
  23. "gogs.io/gogs/internal/setting"
  24. )
  25. const (
  26. _TPL_PUBLICK_KEY = `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. KEY_TYPE_USER = iota + 1
  32. KEY_TYPE_DEPLOY
  33. )
  34. // PublicKey represents a user or deploy SSH public key.
  35. type PublicKey struct {
  36. ID int64
  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:"-" json:"-"`
  44. CreatedUnix int64
  45. Updated time.Time `xorm:"-" json:"-"` // Note: Updated must below Created for AfterSet.
  46. UpdatedUnix int64
  47. HasRecentActivity bool `xorm:"-" json:"-"`
  48. HasUsed bool `xorm:"-" json:"-"`
  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 (k *PublicKey) AuthorizedString() string {
  72. return fmt.Sprintf(_TPL_PUBLICK_KEY, setting.AppPath, k.ID, setting.CustomConf, k.Content)
  73. }
  74. // IsDeployKey returns true if the public key is used as deploy key.
  75. func (k *PublicKey) IsDeployKey() bool {
  76. return k.Type == KEY_TYPE_DEPLOY
  77. }
  78. func extractTypeFromBase64Key(key string) (string, error) {
  79. b, err := base64.StdEncoding.DecodeString(key)
  80. if err != nil || len(b) < 4 {
  81. return "", fmt.Errorf("invalid key format: %v", err)
  82. }
  83. keyLength := int(binary.BigEndian.Uint32(b))
  84. if len(b) < 4+keyLength {
  85. return "", fmt.Errorf("invalid key format: not enough length %d", keyLength)
  86. }
  87. return string(b[4 : 4+keyLength]), nil
  88. }
  89. // parseKeyString parses any key string in OpenSSH or SSH2 format to clean OpenSSH string (RFC4253).
  90. func parseKeyString(content string) (string, error) {
  91. // Transform all legal line endings to a single "\n"
  92. // Replace all windows full new lines ("\r\n")
  93. content = strings.Replace(content, "\r\n", "\n", -1)
  94. // Replace all windows half new lines ("\r"), if it happen not to match replace above
  95. content = strings.Replace(content, "\r", "\n", -1)
  96. // Replace ending new line as its may cause unwanted behaviour (extra line means not a single line key | OpenSSH key)
  97. content = strings.TrimRight(content, "\n")
  98. // split lines
  99. lines := strings.Split(content, "\n")
  100. var keyType, keyContent, keyComment string
  101. if len(lines) == 1 {
  102. // Parse OpenSSH format.
  103. parts := strings.SplitN(lines[0], " ", 3)
  104. switch len(parts) {
  105. case 0:
  106. return "", errors.New("empty key")
  107. case 1:
  108. keyContent = parts[0]
  109. case 2:
  110. keyType = parts[0]
  111. keyContent = parts[1]
  112. default:
  113. keyType = parts[0]
  114. keyContent = parts[1]
  115. keyComment = parts[2]
  116. }
  117. // If keyType is not given, extract it from content. If given, validate it.
  118. t, err := extractTypeFromBase64Key(keyContent)
  119. if err != nil {
  120. return "", fmt.Errorf("extractTypeFromBase64Key: %v", err)
  121. }
  122. if len(keyType) == 0 {
  123. keyType = t
  124. } else if keyType != t {
  125. return "", fmt.Errorf("key type and content does not match: %s - %s", keyType, t)
  126. }
  127. } else {
  128. // Parse SSH2 file format.
  129. continuationLine := false
  130. for _, line := range lines {
  131. // Skip lines that:
  132. // 1) are a continuation of the previous line,
  133. // 2) contain ":" as that are comment lines
  134. // 3) contain "-" as that are begin and end tags
  135. if continuationLine || strings.ContainsAny(line, ":-") {
  136. continuationLine = strings.HasSuffix(line, "\\")
  137. } else {
  138. keyContent = keyContent + line
  139. }
  140. }
  141. t, err := extractTypeFromBase64Key(keyContent)
  142. if err != nil {
  143. return "", fmt.Errorf("extractTypeFromBase64Key: %v", err)
  144. }
  145. keyType = t
  146. }
  147. return keyType + " " + keyContent + " " + keyComment, nil
  148. }
  149. // writeTmpKeyFile writes key content to a temporary file
  150. // and returns the name of that file, along with any possible errors.
  151. func writeTmpKeyFile(content string) (string, error) {
  152. tmpFile, err := ioutil.TempFile(setting.SSH.KeyTestPath, "gogs_keytest")
  153. if err != nil {
  154. return "", fmt.Errorf("TempFile: %v", err)
  155. }
  156. defer tmpFile.Close()
  157. if _, err = tmpFile.WriteString(content); err != nil {
  158. return "", fmt.Errorf("WriteString: %v", err)
  159. }
  160. return tmpFile.Name(), nil
  161. }
  162. // SSHKeyGenParsePublicKey extracts key type and length using ssh-keygen.
  163. func SSHKeyGenParsePublicKey(key string) (string, int, error) {
  164. tmpName, err := writeTmpKeyFile(key)
  165. if err != nil {
  166. return "", 0, fmt.Errorf("writeTmpKeyFile: %v", err)
  167. }
  168. defer os.Remove(tmpName)
  169. stdout, stderr, err := process.Exec("SSHKeyGenParsePublicKey", setting.SSH.KeygenPath, "-lf", tmpName)
  170. if err != nil {
  171. return "", 0, fmt.Errorf("fail to parse public key: %s - %s", err, stderr)
  172. }
  173. if strings.Contains(stdout, "is not a public key file") {
  174. return "", 0, ErrKeyUnableVerify{stdout}
  175. }
  176. fields := strings.Split(stdout, " ")
  177. if len(fields) < 4 {
  178. return "", 0, fmt.Errorf("invalid public key line: %s", stdout)
  179. }
  180. keyType := strings.Trim(fields[len(fields)-1], "()\r\n")
  181. return strings.ToLower(keyType), com.StrTo(fields[0]).MustInt(), nil
  182. }
  183. // SSHNativeParsePublicKey extracts the key type and length using the golang SSH library.
  184. func SSHNativeParsePublicKey(keyLine string) (string, int, error) {
  185. fields := strings.Fields(keyLine)
  186. if len(fields) < 2 {
  187. return "", 0, fmt.Errorf("not enough fields in public key line: %s", string(keyLine))
  188. }
  189. raw, err := base64.StdEncoding.DecodeString(fields[1])
  190. if err != nil {
  191. return "", 0, err
  192. }
  193. pkey, err := ssh.ParsePublicKey(raw)
  194. if err != nil {
  195. if strings.Contains(err.Error(), "ssh: unknown key algorithm") {
  196. return "", 0, ErrKeyUnableVerify{err.Error()}
  197. }
  198. return "", 0, fmt.Errorf("ParsePublicKey: %v", err)
  199. }
  200. // The ssh library can parse the key, so next we find out what key exactly we have.
  201. switch pkey.Type() {
  202. case ssh.KeyAlgoDSA:
  203. rawPub := struct {
  204. Name string
  205. P, Q, G, Y *big.Int
  206. }{}
  207. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  208. return "", 0, err
  209. }
  210. // as per https://bugzilla.mindrot.org/show_bug.cgi?id=1647 we should never
  211. // see dsa keys != 1024 bit, but as it seems to work, we will not check here
  212. return "dsa", rawPub.P.BitLen(), nil // use P as per crypto/dsa/dsa.go (is L)
  213. case ssh.KeyAlgoRSA:
  214. rawPub := struct {
  215. Name string
  216. E *big.Int
  217. N *big.Int
  218. }{}
  219. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  220. return "", 0, err
  221. }
  222. return "rsa", rawPub.N.BitLen(), nil // use N as per crypto/rsa/rsa.go (is bits)
  223. case ssh.KeyAlgoECDSA256:
  224. return "ecdsa", 256, nil
  225. case ssh.KeyAlgoECDSA384:
  226. return "ecdsa", 384, nil
  227. case ssh.KeyAlgoECDSA521:
  228. return "ecdsa", 521, nil
  229. case ssh.KeyAlgoED25519:
  230. return "ed25519", 256, nil
  231. }
  232. return "", 0, fmt.Errorf("unsupported key length detection for type: %s", pkey.Type())
  233. }
  234. // CheckPublicKeyString checks if the given public key string is recognized by SSH.
  235. // It returns the actual public key line on success.
  236. func CheckPublicKeyString(content string) (_ string, err error) {
  237. if setting.SSH.Disabled {
  238. return "", errors.New("SSH is disabled")
  239. }
  240. content, err = parseKeyString(content)
  241. if err != nil {
  242. return "", err
  243. }
  244. content = strings.TrimRight(content, "\n\r")
  245. if strings.ContainsAny(content, "\n\r") {
  246. return "", errors.New("only a single line with a single key please")
  247. }
  248. // Remove any unnecessary whitespace
  249. content = strings.TrimSpace(content)
  250. if !setting.SSH.MinimumKeySizeCheck {
  251. return content, nil
  252. }
  253. var (
  254. fnName string
  255. keyType string
  256. length int
  257. )
  258. if setting.SSH.StartBuiltinServer {
  259. fnName = "SSHNativeParsePublicKey"
  260. keyType, length, err = SSHNativeParsePublicKey(content)
  261. } else {
  262. fnName = "SSHKeyGenParsePublicKey"
  263. keyType, length, err = SSHKeyGenParsePublicKey(content)
  264. }
  265. if err != nil {
  266. return "", fmt.Errorf("%s: %v", fnName, err)
  267. }
  268. log.Trace("Key info [native: %v]: %s-%d", setting.SSH.StartBuiltinServer, keyType, length)
  269. if minLen, found := setting.SSH.MinimumKeySizes[keyType]; found && length >= minLen {
  270. return content, nil
  271. } else if found && length < minLen {
  272. return "", fmt.Errorf("key length is not enough: got %d, needs %d", length, minLen)
  273. }
  274. return "", fmt.Errorf("key type is not allowed: %s", keyType)
  275. }
  276. // appendAuthorizedKeysToFile appends new SSH keys' content to authorized_keys file.
  277. func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
  278. sshOpLocker.Lock()
  279. defer sshOpLocker.Unlock()
  280. fpath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  281. f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  282. if err != nil {
  283. return err
  284. }
  285. defer f.Close()
  286. // Note: chmod command does not support in Windows.
  287. if !setting.IsWindows {
  288. fi, err := f.Stat()
  289. if err != nil {
  290. return err
  291. }
  292. // .ssh directory should have mode 700, and authorized_keys file should have mode 600.
  293. if fi.Mode().Perm() > 0600 {
  294. log.Error(4, "authorized_keys file has unusual permission flags: %s - setting to -rw-------", fi.Mode().Perm().String())
  295. if err = f.Chmod(0600); err != nil {
  296. return err
  297. }
  298. }
  299. }
  300. for _, key := range keys {
  301. if _, err = f.WriteString(key.AuthorizedString()); err != nil {
  302. return err
  303. }
  304. }
  305. return nil
  306. }
  307. // checkKeyContent onlys checks if key content has been used as public key,
  308. // it is OK to use same key as deploy key for multiple repositories/users.
  309. func checkKeyContent(content string) error {
  310. has, err := x.Get(&PublicKey{
  311. Content: content,
  312. Type: KEY_TYPE_USER,
  313. })
  314. if err != nil {
  315. return err
  316. } else if has {
  317. return ErrKeyAlreadyExist{0, content}
  318. }
  319. return nil
  320. }
  321. func addKey(e Engine, key *PublicKey) (err error) {
  322. // Calculate fingerprint.
  323. tmpPath := strings.Replace(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
  324. "id_rsa.pub"), "\\", "/", -1)
  325. os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
  326. if err = ioutil.WriteFile(tmpPath, []byte(key.Content), 0644); err != nil {
  327. return err
  328. }
  329. stdout, stderr, err := process.Exec("AddPublicKey", setting.SSH.KeygenPath, "-lf", tmpPath)
  330. if err != nil {
  331. return fmt.Errorf("fail to parse public key: %s - %s", err, stderr)
  332. } else if len(stdout) < 2 {
  333. return errors.New("not enough output for calculating fingerprint: " + stdout)
  334. }
  335. key.Fingerprint = strings.Split(stdout, " ")[1]
  336. // Save SSH key.
  337. if _, err = e.Insert(key); err != nil {
  338. return err
  339. }
  340. // Don't need to rewrite this file if builtin SSH server is enabled.
  341. if setting.SSH.StartBuiltinServer {
  342. return nil
  343. }
  344. return appendAuthorizedKeysToFile(key)
  345. }
  346. // AddPublicKey adds new public key to database and authorized_keys file.
  347. func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) {
  348. log.Trace(content)
  349. if err := checkKeyContent(content); err != nil {
  350. return nil, err
  351. }
  352. // Key name of same user cannot be duplicated.
  353. has, err := x.Where("owner_id = ? AND name = ?", ownerID, name).Get(new(PublicKey))
  354. if err != nil {
  355. return nil, err
  356. } else if has {
  357. return nil, ErrKeyNameAlreadyUsed{ownerID, name}
  358. }
  359. sess := x.NewSession()
  360. defer sess.Close()
  361. if err = sess.Begin(); err != nil {
  362. return nil, err
  363. }
  364. key := &PublicKey{
  365. OwnerID: ownerID,
  366. Name: name,
  367. Content: content,
  368. Mode: ACCESS_MODE_WRITE,
  369. Type: KEY_TYPE_USER,
  370. }
  371. if err = addKey(sess, key); err != nil {
  372. return nil, fmt.Errorf("addKey: %v", err)
  373. }
  374. return key, sess.Commit()
  375. }
  376. // GetPublicKeyByID returns public key by given ID.
  377. func GetPublicKeyByID(keyID int64) (*PublicKey, error) {
  378. key := new(PublicKey)
  379. has, err := x.Id(keyID).Get(key)
  380. if err != nil {
  381. return nil, err
  382. } else if !has {
  383. return nil, ErrKeyNotExist{keyID}
  384. }
  385. return key, nil
  386. }
  387. // SearchPublicKeyByContent searches content as prefix (leak e-mail part)
  388. // and returns public key found.
  389. func SearchPublicKeyByContent(content string) (*PublicKey, error) {
  390. key := new(PublicKey)
  391. has, err := x.Where("content like ?", content+"%").Get(key)
  392. if err != nil {
  393. return nil, err
  394. } else if !has {
  395. return nil, ErrKeyNotExist{}
  396. }
  397. return key, nil
  398. }
  399. // ListPublicKeys returns a list of public keys belongs to given user.
  400. func ListPublicKeys(uid int64) ([]*PublicKey, error) {
  401. keys := make([]*PublicKey, 0, 5)
  402. return keys, x.Where("owner_id = ?", uid).Find(&keys)
  403. }
  404. // UpdatePublicKey updates given public key.
  405. func UpdatePublicKey(key *PublicKey) error {
  406. _, err := x.Id(key.ID).AllCols().Update(key)
  407. return err
  408. }
  409. // deletePublicKeys does the actual key deletion but does not update authorized_keys file.
  410. func deletePublicKeys(e *xorm.Session, keyIDs ...int64) error {
  411. if len(keyIDs) == 0 {
  412. return nil
  413. }
  414. _, err := e.In("id", keyIDs).Delete(new(PublicKey))
  415. return err
  416. }
  417. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  418. func DeletePublicKey(doer *User, id int64) (err error) {
  419. key, err := GetPublicKeyByID(id)
  420. if err != nil {
  421. if IsErrKeyNotExist(err) {
  422. return nil
  423. }
  424. return fmt.Errorf("GetPublicKeyByID: %v", err)
  425. }
  426. // Check if user has access to delete this key.
  427. if !doer.IsAdmin && doer.ID != key.OwnerID {
  428. return ErrKeyAccessDenied{doer.ID, key.ID, "public"}
  429. }
  430. sess := x.NewSession()
  431. defer sess.Close()
  432. if err = sess.Begin(); err != nil {
  433. return err
  434. }
  435. if err = deletePublicKeys(sess, id); err != nil {
  436. return err
  437. }
  438. if err = sess.Commit(); err != nil {
  439. return err
  440. }
  441. return RewriteAuthorizedKeys()
  442. }
  443. // RewriteAuthorizedKeys removes any authorized key and rewrite all keys from database again.
  444. // Note: x.Iterate does not get latest data after insert/delete, so we have to call this function
  445. // outsite any session scope independently.
  446. func RewriteAuthorizedKeys() error {
  447. sshOpLocker.Lock()
  448. defer sshOpLocker.Unlock()
  449. log.Trace("Doing: RewriteAuthorizedKeys")
  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:"-" json:"-"`
  490. Created time.Time `xorm:"-" json:"-"`
  491. CreatedUnix int64
  492. Updated time.Time `xorm:"-" json:"-"` // Note: Updated must below Created for AfterSet.
  493. UpdatedUnix int64
  494. HasRecentActivity bool `xorm:"-" json:"-"`
  495. HasUsed bool `xorm:"-" json:"-"`
  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. }