ssh_key.go 21 KB

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