You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

688 lines
18 KiB

10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  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. "bufio"
  7. "encoding/base64"
  8. "encoding/binary"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "io/ioutil"
  13. "os"
  14. "path"
  15. "path/filepath"
  16. "strings"
  17. "sync"
  18. "time"
  19. "github.com/Unknwon/com"
  20. "github.com/go-xorm/xorm"
  21. "golang.org/x/crypto/ssh"
  22. "github.com/gogits/gogs/modules/log"
  23. "github.com/gogits/gogs/modules/process"
  24. "github.com/gogits/gogs/modules/setting"
  25. )
  26. const (
  27. // "### autogenerated by gitgos, DO NOT EDIT\n"
  28. _TPL_PUBLICK_KEY = `command="%s serv key-%d --config='%s'",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
  29. )
  30. var sshOpLocker = sync.Mutex{}
  31. type KeyType int
  32. const (
  33. KEY_TYPE_USER = iota + 1
  34. KEY_TYPE_DEPLOY
  35. )
  36. // PublicKey represents a SSH or deploy key.
  37. type PublicKey struct {
  38. ID int64 `xorm:"pk autoincr"`
  39. OwnerID int64 `xorm:"INDEX NOT NULL"`
  40. Name string `xorm:"NOT NULL"`
  41. Fingerprint string `xorm:"NOT NULL"`
  42. Content string `xorm:"TEXT NOT NULL"`
  43. Mode AccessMode `xorm:"NOT NULL DEFAULT 2"`
  44. Type KeyType `xorm:"NOT NULL DEFAULT 1"`
  45. Created time.Time `xorm:"CREATED"`
  46. Updated time.Time // Note: Updated must below Created for AfterSet.
  47. HasRecentActivity bool `xorm:"-"`
  48. HasUsed bool `xorm:"-"`
  49. }
  50. func (k *PublicKey) AfterSet(colName string, _ xorm.Cell) {
  51. switch colName {
  52. case "created":
  53. k.HasUsed = k.Updated.After(k.Created)
  54. k.HasRecentActivity = k.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  55. }
  56. }
  57. // OmitEmail returns content of public key but without e-mail address.
  58. func (k *PublicKey) OmitEmail() string {
  59. return strings.Join(strings.Split(k.Content, " ")[:2], " ")
  60. }
  61. // GetAuthorizedString generates and returns formatted public key string for authorized_keys file.
  62. func (key *PublicKey) GetAuthorizedString() string {
  63. return fmt.Sprintf(_TPL_PUBLICK_KEY, setting.AppPath, key.ID, setting.CustomConf, key.Content)
  64. }
  65. func extractTypeFromBase64Key(key string) (string, error) {
  66. b, err := base64.StdEncoding.DecodeString(key)
  67. if err != nil || len(b) < 4 {
  68. return "", errors.New("Invalid key format")
  69. }
  70. keyLength := int(binary.BigEndian.Uint32(b))
  71. if len(b) < 4+keyLength {
  72. return "", errors.New("Invalid key format")
  73. }
  74. return string(b[4 : 4+keyLength]), nil
  75. }
  76. // parseKeyString parses any key string in openssh or ssh2 format to clean openssh string (rfc4253)
  77. func parseKeyString(content string) (string, error) {
  78. // Transform all legal line endings to a single "\n"
  79. s := strings.Replace(strings.Replace(strings.TrimSpace(content), "\r\n", "\n", -1), "\r", "\n", -1)
  80. lines := strings.Split(s, "\n")
  81. var keyType, keyContent, keyComment string
  82. if len(lines) == 1 {
  83. // Parse openssh format
  84. parts := strings.SplitN(lines[0], " ", 3)
  85. switch len(parts) {
  86. case 0:
  87. return "", errors.New("Empty key")
  88. case 1:
  89. keyContent = parts[0]
  90. case 2:
  91. keyType = parts[0]
  92. keyContent = parts[1]
  93. default:
  94. keyType = parts[0]
  95. keyContent = parts[1]
  96. keyComment = parts[2]
  97. }
  98. // If keyType is not given, extract it from content. If given, validate it
  99. if len(keyType) == 0 {
  100. if t, err := extractTypeFromBase64Key(keyContent); err == nil {
  101. keyType = t
  102. } else {
  103. return "", err
  104. }
  105. } else {
  106. if t, err := extractTypeFromBase64Key(keyContent); err != nil || keyType != t {
  107. return "", err
  108. }
  109. }
  110. } else {
  111. // Parse SSH2 file format.
  112. continuationLine := false
  113. for _, line := range lines {
  114. // Skip lines that:
  115. // 1) are a continuation of the previous line,
  116. // 2) contain ":" as that are comment lines
  117. // 3) contain "-" as that are begin and end tags
  118. if continuationLine || strings.ContainsAny(line, ":-") {
  119. continuationLine = strings.HasSuffix(line, "\\")
  120. } else {
  121. keyContent = keyContent + line
  122. }
  123. }
  124. if t, err := extractTypeFromBase64Key(keyContent); err == nil {
  125. keyType = t
  126. } else {
  127. return "", err
  128. }
  129. }
  130. return keyType + " " + keyContent + " " + keyComment, nil
  131. }
  132. // CheckPublicKeyString checks if the given public key string is recognized by SSH.
  133. func CheckPublicKeyString(content string) (_ string, err error) {
  134. content, err = parseKeyString(content)
  135. if err != nil {
  136. return "", err
  137. }
  138. content = strings.TrimRight(content, "\n\r")
  139. if strings.ContainsAny(content, "\n\r") {
  140. return "", errors.New("only a single line with a single key please")
  141. }
  142. // remove any unnecessary whitespace now
  143. content = strings.TrimSpace(content)
  144. fields := strings.Fields(content)
  145. if len(fields) < 2 {
  146. return "", errors.New("too less fields")
  147. }
  148. key, err := base64.StdEncoding.DecodeString(fields[1])
  149. if err != nil {
  150. return "", fmt.Errorf("StdEncoding.DecodeString: %v", err)
  151. }
  152. pkey, err := ssh.ParsePublicKey([]byte(key))
  153. if err != nil {
  154. return "", fmt.Errorf("ParsePublicKey: %v", err)
  155. }
  156. log.Trace("Key type: %s", pkey.Type())
  157. return content, nil
  158. }
  159. // saveAuthorizedKeyFile writes SSH key content to authorized_keys file.
  160. func saveAuthorizedKeyFile(keys ...*PublicKey) error {
  161. sshOpLocker.Lock()
  162. defer sshOpLocker.Unlock()
  163. fpath := filepath.Join(setting.SSHRootPath, "authorized_keys")
  164. f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  165. if err != nil {
  166. return err
  167. }
  168. defer f.Close()
  169. fi, err := f.Stat()
  170. if err != nil {
  171. return err
  172. }
  173. // FIXME: following command does not support in Windows.
  174. if !setting.IsWindows {
  175. // .ssh directory should have mode 700, and authorized_keys file should have mode 600.
  176. if fi.Mode().Perm() > 0600 {
  177. log.Error(4, "authorized_keys file has unusual permission flags: %s - setting to -rw-------", fi.Mode().Perm().String())
  178. if err = f.Chmod(0600); err != nil {
  179. return err
  180. }
  181. }
  182. }
  183. for _, key := range keys {
  184. if _, err = f.WriteString(key.GetAuthorizedString()); err != nil {
  185. return err
  186. }
  187. }
  188. return nil
  189. }
  190. // checkKeyContent onlys checks if key content has been used as public key,
  191. // it is OK to use same key as deploy key for multiple repositories/users.
  192. func checkKeyContent(content string) error {
  193. has, err := x.Get(&PublicKey{
  194. Content: content,
  195. Type: KEY_TYPE_USER,
  196. })
  197. if err != nil {
  198. return err
  199. } else if has {
  200. return ErrKeyAlreadyExist{0, content}
  201. }
  202. return nil
  203. }
  204. func addKey(e Engine, key *PublicKey) (err error) {
  205. // Calculate fingerprint.
  206. tmpPath := strings.Replace(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
  207. "id_rsa.pub"), "\\", "/", -1)
  208. os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
  209. if err = ioutil.WriteFile(tmpPath, []byte(key.Content), 0644); err != nil {
  210. return err
  211. }
  212. stdout, stderr, err := process.Exec("AddPublicKey", "ssh-keygen", "-lf", tmpPath)
  213. if err != nil {
  214. return errors.New("ssh-keygen -lf: " + stderr)
  215. } else if len(stdout) < 2 {
  216. return errors.New("not enough output for calculating fingerprint: " + stdout)
  217. }
  218. key.Fingerprint = strings.Split(stdout, " ")[1]
  219. // Save SSH key.
  220. if _, err = e.Insert(key); err != nil {
  221. return err
  222. }
  223. // Don't need to rewrite this file if builtin SSH server is enabled.
  224. if setting.StartSSHServer {
  225. return nil
  226. }
  227. return saveAuthorizedKeyFile(key)
  228. }
  229. // AddPublicKey adds new public key to database and authorized_keys file.
  230. func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) {
  231. if err := checkKeyContent(content); err != nil {
  232. return nil, err
  233. }
  234. // Key name of same user cannot be duplicated.
  235. has, err := x.Where("owner_id=? AND name=?", ownerID, name).Get(new(PublicKey))
  236. if err != nil {
  237. return nil, err
  238. } else if has {
  239. return nil, ErrKeyNameAlreadyUsed{ownerID, name}
  240. }
  241. sess := x.NewSession()
  242. defer sessionRelease(sess)
  243. if err = sess.Begin(); err != nil {
  244. return nil, err
  245. }
  246. key := &PublicKey{
  247. OwnerID: ownerID,
  248. Name: name,
  249. Content: content,
  250. Mode: ACCESS_MODE_WRITE,
  251. Type: KEY_TYPE_USER,
  252. }
  253. if err = addKey(sess, key); err != nil {
  254. return nil, fmt.Errorf("addKey: %v", err)
  255. }
  256. return key, sess.Commit()
  257. }
  258. // GetPublicKeyByID returns public key by given ID.
  259. func GetPublicKeyByID(keyID int64) (*PublicKey, error) {
  260. key := new(PublicKey)
  261. has, err := x.Id(keyID).Get(key)
  262. if err != nil {
  263. return nil, err
  264. } else if !has {
  265. return nil, ErrKeyNotExist{keyID}
  266. }
  267. return key, nil
  268. }
  269. // SearchPublicKeyByContent searches content as prefix (leak e-mail part)
  270. // and returns public key found.
  271. func SearchPublicKeyByContent(content string) (*PublicKey, error) {
  272. key := new(PublicKey)
  273. has, err := x.Where("content like ?", content+"%").Get(key)
  274. if err != nil {
  275. return nil, err
  276. } else if !has {
  277. return nil, ErrKeyNotExist{}
  278. }
  279. return key, nil
  280. }
  281. // ListPublicKeys returns a list of public keys belongs to given user.
  282. func ListPublicKeys(uid int64) ([]*PublicKey, error) {
  283. keys := make([]*PublicKey, 0, 5)
  284. return keys, x.Where("owner_id=?", uid).Find(&keys)
  285. }
  286. // rewriteAuthorizedKeys finds and deletes corresponding line in authorized_keys file.
  287. func rewriteAuthorizedKeys(key *PublicKey, p, tmpP string) error {
  288. fr, err := os.Open(p)
  289. if err != nil {
  290. return err
  291. }
  292. defer fr.Close()
  293. fw, err := os.OpenFile(tmpP, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  294. if err != nil {
  295. return err
  296. }
  297. defer fw.Close()
  298. isFound := false
  299. keyword := fmt.Sprintf("key-%d", key.ID)
  300. buf := bufio.NewReader(fr)
  301. for {
  302. line, errRead := buf.ReadString('\n')
  303. line = strings.TrimSpace(line)
  304. if errRead != nil {
  305. if errRead != io.EOF {
  306. return errRead
  307. }
  308. // Reached end of file, if nothing to read then break,
  309. // otherwise handle the last line.
  310. if len(line) == 0 {
  311. break
  312. }
  313. }
  314. // Found the line and copy rest of file.
  315. if !isFound && strings.Contains(line, keyword) && strings.Contains(line, key.Content) {
  316. isFound = true
  317. continue
  318. }
  319. // Still finding the line, copy the line that currently read.
  320. if _, err = fw.WriteString(line + "\n"); err != nil {
  321. return err
  322. }
  323. if errRead == io.EOF {
  324. break
  325. }
  326. }
  327. if !isFound {
  328. log.Warn("SSH key %d not found in authorized_keys file for deletion", key.ID)
  329. }
  330. return nil
  331. }
  332. // UpdatePublicKey updates given public key.
  333. func UpdatePublicKey(key *PublicKey) error {
  334. _, err := x.Id(key.ID).AllCols().Update(key)
  335. return err
  336. }
  337. func deletePublicKey(e *xorm.Session, keyID int64) error {
  338. sshOpLocker.Lock()
  339. defer sshOpLocker.Unlock()
  340. key := &PublicKey{ID: keyID}
  341. has, err := e.Get(key)
  342. if err != nil {
  343. return err
  344. } else if !has {
  345. return nil
  346. }
  347. if _, err = e.Id(key.ID).Delete(new(PublicKey)); err != nil {
  348. return err
  349. }
  350. // Don't need to rewrite this file if builtin SSH server is enabled.
  351. if setting.StartSSHServer {
  352. return nil
  353. }
  354. fpath := filepath.Join(setting.SSHRootPath, "authorized_keys")
  355. tmpPath := filepath.Join(setting.SSHRootPath, "authorized_keys.tmp")
  356. if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil {
  357. return err
  358. } else if err = os.Remove(fpath); err != nil {
  359. return err
  360. }
  361. return os.Rename(tmpPath, fpath)
  362. }
  363. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  364. func DeletePublicKey(doer *User, id int64) (err error) {
  365. key, err := GetPublicKeyByID(id)
  366. if err != nil {
  367. if IsErrKeyNotExist(err) {
  368. return nil
  369. }
  370. return fmt.Errorf("GetPublicKeyByID: %v", err)
  371. }
  372. // Check if user has access to delete this key.
  373. if !doer.IsAdmin && doer.Id != key.OwnerID {
  374. return ErrKeyAccessDenied{doer.Id, key.ID, "public"}
  375. }
  376. sess := x.NewSession()
  377. defer sessionRelease(sess)
  378. if err = sess.Begin(); err != nil {
  379. return err
  380. }
  381. if err = deletePublicKey(sess, id); err != nil {
  382. return err
  383. }
  384. return sess.Commit()
  385. }
  386. // RewriteAllPublicKeys removes any authorized key and rewrite all keys from database again.
  387. func RewriteAllPublicKeys() error {
  388. sshOpLocker.Lock()
  389. defer sshOpLocker.Unlock()
  390. tmpPath := filepath.Join(setting.SSHRootPath, "authorized_keys.tmp")
  391. f, err := os.OpenFile(tmpPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  392. if err != nil {
  393. return err
  394. }
  395. defer os.Remove(tmpPath)
  396. err = x.Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
  397. _, err = f.WriteString((bean.(*PublicKey)).GetAuthorizedString())
  398. return err
  399. })
  400. f.Close()
  401. if err != nil {
  402. return err
  403. }
  404. fpath := filepath.Join(setting.SSHRootPath, "authorized_keys")
  405. if com.IsExist(fpath) {
  406. if err = os.Remove(fpath); err != nil {
  407. return err
  408. }
  409. }
  410. if err = os.Rename(tmpPath, fpath); err != nil {
  411. return err
  412. }
  413. return nil
  414. }
  415. // ________ .__ ____ __.
  416. // \______ \ ____ ______ | | ____ ___.__.| |/ _|____ ___.__.
  417. // | | \_/ __ \\____ \| | / _ < | || <_/ __ < | |
  418. // | ` \ ___/| |_> > |_( <_> )___ || | \ ___/\___ |
  419. // /_______ /\___ > __/|____/\____// ____||____|__ \___ > ____|
  420. // \/ \/|__| \/ \/ \/\/
  421. // DeployKey represents deploy key information and its relation with repository.
  422. type DeployKey struct {
  423. ID int64 `xorm:"pk autoincr"`
  424. KeyID int64 `xorm:"UNIQUE(s) INDEX"`
  425. RepoID int64 `xorm:"UNIQUE(s) INDEX"`
  426. Name string
  427. Fingerprint string
  428. Content string `xorm:"-"`
  429. Created time.Time `xorm:"CREATED"`
  430. Updated time.Time // Note: Updated must below Created for AfterSet.
  431. HasRecentActivity bool `xorm:"-"`
  432. HasUsed bool `xorm:"-"`
  433. }
  434. func (k *DeployKey) AfterSet(colName string, _ xorm.Cell) {
  435. switch colName {
  436. case "created":
  437. k.HasUsed = k.Updated.After(k.Created)
  438. k.HasRecentActivity = k.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  439. }
  440. }
  441. // GetContent gets associated public key content.
  442. func (k *DeployKey) GetContent() error {
  443. pkey, err := GetPublicKeyByID(k.KeyID)
  444. if err != nil {
  445. return err
  446. }
  447. k.Content = pkey.Content
  448. return nil
  449. }
  450. func checkDeployKey(e Engine, keyID, repoID int64, name string) error {
  451. // Note: We want error detail, not just true or false here.
  452. has, err := e.Where("key_id=? AND repo_id=?", keyID, repoID).Get(new(DeployKey))
  453. if err != nil {
  454. return err
  455. } else if has {
  456. return ErrDeployKeyAlreadyExist{keyID, repoID}
  457. }
  458. has, err = e.Where("repo_id=? AND name=?", repoID, name).Get(new(DeployKey))
  459. if err != nil {
  460. return err
  461. } else if has {
  462. return ErrDeployKeyNameAlreadyUsed{repoID, name}
  463. }
  464. return nil
  465. }
  466. // addDeployKey adds new key-repo relation.
  467. func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string) (*DeployKey, error) {
  468. if err := checkDeployKey(e, keyID, repoID, name); err != nil {
  469. return nil, err
  470. }
  471. key := &DeployKey{
  472. KeyID: keyID,
  473. RepoID: repoID,
  474. Name: name,
  475. Fingerprint: fingerprint,
  476. }
  477. _, err := e.Insert(key)
  478. return key, err
  479. }
  480. // HasDeployKey returns true if public key is a deploy key of given repository.
  481. func HasDeployKey(keyID, repoID int64) bool {
  482. has, _ := x.Where("key_id=? AND repo_id=?", keyID, repoID).Get(new(DeployKey))
  483. return has
  484. }
  485. // AddDeployKey add new deploy key to database and authorized_keys file.
  486. func AddDeployKey(repoID int64, name, content string) (*DeployKey, error) {
  487. if err := checkKeyContent(content); err != nil {
  488. return nil, err
  489. }
  490. pkey := &PublicKey{
  491. Content: content,
  492. Mode: ACCESS_MODE_READ,
  493. Type: KEY_TYPE_DEPLOY,
  494. }
  495. has, err := x.Get(pkey)
  496. if err != nil {
  497. return nil, err
  498. }
  499. sess := x.NewSession()
  500. defer sessionRelease(sess)
  501. if err = sess.Begin(); err != nil {
  502. return nil, err
  503. }
  504. // First time use this deploy key.
  505. if !has {
  506. if err = addKey(sess, pkey); err != nil {
  507. return nil, fmt.Errorf("addKey: %v", err)
  508. }
  509. }
  510. key, err := addDeployKey(sess, pkey.ID, repoID, name, pkey.Fingerprint)
  511. if err != nil {
  512. return nil, fmt.Errorf("addDeployKey: %v", err)
  513. }
  514. return key, sess.Commit()
  515. }
  516. // GetDeployKeyByID returns deploy key by given ID.
  517. func GetDeployKeyByID(id int64) (*DeployKey, error) {
  518. key := new(DeployKey)
  519. has, err := x.Id(id).Get(key)
  520. if err != nil {
  521. return nil, err
  522. } else if !has {
  523. return nil, ErrDeployKeyNotExist{id, 0, 0}
  524. }
  525. return key, nil
  526. }
  527. // GetDeployKeyByRepo returns deploy key by given public key ID and repository ID.
  528. func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) {
  529. key := &DeployKey{
  530. KeyID: keyID,
  531. RepoID: repoID,
  532. }
  533. has, err := x.Get(key)
  534. if err != nil {
  535. return nil, err
  536. } else if !has {
  537. return nil, ErrDeployKeyNotExist{0, keyID, repoID}
  538. }
  539. return key, nil
  540. }
  541. // UpdateDeployKey updates deploy key information.
  542. func UpdateDeployKey(key *DeployKey) error {
  543. _, err := x.Id(key.ID).AllCols().Update(key)
  544. return err
  545. }
  546. // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed.
  547. func DeleteDeployKey(doer *User, id int64) error {
  548. key, err := GetDeployKeyByID(id)
  549. if err != nil {
  550. if IsErrDeployKeyNotExist(err) {
  551. return nil
  552. }
  553. return fmt.Errorf("GetDeployKeyByID: %v", err)
  554. }
  555. // Check if user has access to delete this key.
  556. if !doer.IsAdmin {
  557. repo, err := GetRepositoryByID(key.RepoID)
  558. if err != nil {
  559. return fmt.Errorf("GetRepositoryByID: %v", err)
  560. }
  561. yes, err := HasAccess(doer, repo, ACCESS_MODE_ADMIN)
  562. if err != nil {
  563. return fmt.Errorf("HasAccess: %v", err)
  564. } else if !yes {
  565. return ErrKeyAccessDenied{doer.Id, key.ID, "deploy"}
  566. }
  567. }
  568. sess := x.NewSession()
  569. defer sessionRelease(sess)
  570. if err = sess.Begin(); err != nil {
  571. return err
  572. }
  573. if _, err = sess.Id(key.ID).Delete(new(DeployKey)); err != nil {
  574. return fmt.Errorf("delete deploy key[%d]: %v", key.ID, err)
  575. }
  576. // Check if this is the last reference to same key content.
  577. has, err := sess.Where("key_id=?", key.KeyID).Get(new(DeployKey))
  578. if err != nil {
  579. return err
  580. } else if !has {
  581. if err = deletePublicKey(sess, key.KeyID); err != nil {
  582. return err
  583. }
  584. }
  585. return sess.Commit()
  586. }
  587. // ListDeployKeys returns all deploy keys by given repository ID.
  588. func ListDeployKeys(repoID int64) ([]*DeployKey, error) {
  589. keys := make([]*DeployKey, 0, 5)
  590. return keys, x.Where("repo_id=?", repoID).Find(&keys)
  591. }