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.

680 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. fields := strings.Fields(content)
  143. if len(fields) < 2 {
  144. return "", errors.New("too less fields")
  145. }
  146. key, err := base64.StdEncoding.DecodeString(fields[1])
  147. if err != nil {
  148. return "", fmt.Errorf("StdEncoding.DecodeString: %v", err)
  149. }
  150. pkey, err := ssh.ParsePublicKey([]byte(key))
  151. if err != nil {
  152. return "", fmt.Errorf("ParsePublicKey: %v", err)
  153. }
  154. log.Trace("Key type: %s", pkey.Type())
  155. return content, nil
  156. }
  157. // saveAuthorizedKeyFile writes SSH key content to authorized_keys file.
  158. func saveAuthorizedKeyFile(keys ...*PublicKey) error {
  159. sshOpLocker.Lock()
  160. defer sshOpLocker.Unlock()
  161. fpath := filepath.Join(setting.SSHRootPath, "authorized_keys")
  162. f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  163. if err != nil {
  164. return err
  165. }
  166. defer f.Close()
  167. fi, err := f.Stat()
  168. if err != nil {
  169. return err
  170. }
  171. // FIXME: following command does not support in Windows.
  172. if !setting.IsWindows {
  173. // .ssh directory should have mode 700, and authorized_keys file should have mode 600.
  174. if fi.Mode().Perm() > 0600 {
  175. log.Error(4, "authorized_keys file has unusual permission flags: %s - setting to -rw-------", fi.Mode().Perm().String())
  176. if err = f.Chmod(0600); err != nil {
  177. return err
  178. }
  179. }
  180. }
  181. for _, key := range keys {
  182. if _, err = f.WriteString(key.GetAuthorizedString()); err != nil {
  183. return err
  184. }
  185. }
  186. return nil
  187. }
  188. // checkKeyContent onlys checks if key content has been used as public key,
  189. // it is OK to use same key as deploy key for multiple repositories/users.
  190. func checkKeyContent(content string) error {
  191. has, err := x.Get(&PublicKey{
  192. Content: content,
  193. Type: KEY_TYPE_USER,
  194. })
  195. if err != nil {
  196. return err
  197. } else if has {
  198. return ErrKeyAlreadyExist{0, content}
  199. }
  200. return nil
  201. }
  202. func addKey(e Engine, key *PublicKey) (err error) {
  203. // Calculate fingerprint.
  204. tmpPath := strings.Replace(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
  205. "id_rsa.pub"), "\\", "/", -1)
  206. os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
  207. if err = ioutil.WriteFile(tmpPath, []byte(key.Content), 0644); err != nil {
  208. return err
  209. }
  210. stdout, stderr, err := process.Exec("AddPublicKey", "ssh-keygen", "-lf", tmpPath)
  211. if err != nil {
  212. return errors.New("ssh-keygen -lf: " + stderr)
  213. } else if len(stdout) < 2 {
  214. return errors.New("not enough output for calculating fingerprint: " + stdout)
  215. }
  216. key.Fingerprint = strings.Split(stdout, " ")[1]
  217. // Save SSH key.
  218. if _, err = e.Insert(key); err != nil {
  219. return err
  220. }
  221. // Don't need to rewrite this file if builtin SSH server is enabled.
  222. if setting.StartSSHServer {
  223. return nil
  224. }
  225. return saveAuthorizedKeyFile(key)
  226. }
  227. // AddPublicKey adds new public key to database and authorized_keys file.
  228. func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) {
  229. if err := checkKeyContent(content); err != nil {
  230. return nil, err
  231. }
  232. // Key name of same user cannot be duplicated.
  233. has, err := x.Where("owner_id=? AND name=?", ownerID, name).Get(new(PublicKey))
  234. if err != nil {
  235. return nil, err
  236. } else if has {
  237. return nil, ErrKeyNameAlreadyUsed{ownerID, name}
  238. }
  239. sess := x.NewSession()
  240. defer sessionRelease(sess)
  241. if err = sess.Begin(); err != nil {
  242. return nil, err
  243. }
  244. key := &PublicKey{
  245. OwnerID: ownerID,
  246. Name: name,
  247. Content: content,
  248. Mode: ACCESS_MODE_WRITE,
  249. Type: KEY_TYPE_USER,
  250. }
  251. if err = addKey(sess, key); err != nil {
  252. return nil, fmt.Errorf("addKey: %v", err)
  253. }
  254. return key, sess.Commit()
  255. }
  256. // GetPublicKeyByID returns public key by given ID.
  257. func GetPublicKeyByID(keyID int64) (*PublicKey, error) {
  258. key := new(PublicKey)
  259. has, err := x.Id(keyID).Get(key)
  260. if err != nil {
  261. return nil, err
  262. } else if !has {
  263. return nil, ErrKeyNotExist{keyID}
  264. }
  265. return key, nil
  266. }
  267. // SearchPublicKeyByContent searches content as prefix (leak e-mail part)
  268. // and returns public key found.
  269. func SearchPublicKeyByContent(content string) (*PublicKey, error) {
  270. key := new(PublicKey)
  271. has, err := x.Where("content like ?", content+"%").Get(key)
  272. if err != nil {
  273. return nil, err
  274. } else if !has {
  275. return nil, ErrKeyNotExist{}
  276. }
  277. return key, nil
  278. }
  279. // ListPublicKeys returns a list of public keys belongs to given user.
  280. func ListPublicKeys(uid int64) ([]*PublicKey, error) {
  281. keys := make([]*PublicKey, 0, 5)
  282. return keys, x.Where("owner_id=?", uid).Find(&keys)
  283. }
  284. // rewriteAuthorizedKeys finds and deletes corresponding line in authorized_keys file.
  285. func rewriteAuthorizedKeys(key *PublicKey, p, tmpP string) error {
  286. fr, err := os.Open(p)
  287. if err != nil {
  288. return err
  289. }
  290. defer fr.Close()
  291. fw, err := os.OpenFile(tmpP, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  292. if err != nil {
  293. return err
  294. }
  295. defer fw.Close()
  296. isFound := false
  297. keyword := fmt.Sprintf("key-%d", key.ID)
  298. buf := bufio.NewReader(fr)
  299. for {
  300. line, errRead := buf.ReadString('\n')
  301. line = strings.TrimSpace(line)
  302. if errRead != nil {
  303. if errRead != io.EOF {
  304. return errRead
  305. }
  306. // Reached end of file, if nothing to read then break,
  307. // otherwise handle the last line.
  308. if len(line) == 0 {
  309. break
  310. }
  311. }
  312. // Found the line and copy rest of file.
  313. if !isFound && strings.Contains(line, keyword) && strings.Contains(line, key.Content) {
  314. isFound = true
  315. continue
  316. }
  317. // Still finding the line, copy the line that currently read.
  318. if _, err = fw.WriteString(line + "\n"); err != nil {
  319. return err
  320. }
  321. if errRead == io.EOF {
  322. break
  323. }
  324. }
  325. return nil
  326. }
  327. // UpdatePublicKey updates given public key.
  328. func UpdatePublicKey(key *PublicKey) error {
  329. _, err := x.Id(key.ID).AllCols().Update(key)
  330. return err
  331. }
  332. func deletePublicKey(e *xorm.Session, keyID int64) error {
  333. sshOpLocker.Lock()
  334. defer sshOpLocker.Unlock()
  335. key := &PublicKey{ID: keyID}
  336. has, err := e.Get(key)
  337. if err != nil {
  338. return err
  339. } else if !has {
  340. return nil
  341. }
  342. if _, err = e.Id(key.ID).Delete(new(PublicKey)); err != nil {
  343. return err
  344. }
  345. // Don't need to rewrite this file if builtin SSH server is enabled.
  346. if setting.StartSSHServer {
  347. return nil
  348. }
  349. fpath := filepath.Join(setting.SSHRootPath, "authorized_keys")
  350. tmpPath := filepath.Join(setting.SSHRootPath, "authorized_keys.tmp")
  351. if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil {
  352. return err
  353. } else if err = os.Remove(fpath); err != nil {
  354. return err
  355. }
  356. return os.Rename(tmpPath, fpath)
  357. }
  358. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  359. func DeletePublicKey(doer *User, id int64) (err error) {
  360. key, err := GetPublicKeyByID(id)
  361. if err != nil {
  362. if IsErrKeyNotExist(err) {
  363. return nil
  364. }
  365. return fmt.Errorf("GetPublicKeyByID: %v", err)
  366. }
  367. // Check if user has access to delete this key.
  368. if !doer.IsAdmin && doer.Id != key.OwnerID {
  369. return ErrKeyAccessDenied{doer.Id, key.ID, "public"}
  370. }
  371. sess := x.NewSession()
  372. defer sessionRelease(sess)
  373. if err = sess.Begin(); err != nil {
  374. return err
  375. }
  376. if err = deletePublicKey(sess, id); err != nil {
  377. return err
  378. }
  379. return sess.Commit()
  380. }
  381. // RewriteAllPublicKeys removes any authorized key and rewrite all keys from database again.
  382. func RewriteAllPublicKeys() error {
  383. sshOpLocker.Lock()
  384. defer sshOpLocker.Unlock()
  385. tmpPath := filepath.Join(setting.SSHRootPath, "authorized_keys.tmp")
  386. f, err := os.OpenFile(tmpPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  387. if err != nil {
  388. return err
  389. }
  390. defer os.Remove(tmpPath)
  391. err = x.Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
  392. _, err = f.WriteString((bean.(*PublicKey)).GetAuthorizedString())
  393. return err
  394. })
  395. f.Close()
  396. if err != nil {
  397. return err
  398. }
  399. fpath := filepath.Join(setting.SSHRootPath, "authorized_keys")
  400. if com.IsExist(fpath) {
  401. if err = os.Remove(fpath); err != nil {
  402. return err
  403. }
  404. }
  405. if err = os.Rename(tmpPath, fpath); err != nil {
  406. return err
  407. }
  408. return nil
  409. }
  410. // ________ .__ ____ __.
  411. // \______ \ ____ ______ | | ____ ___.__.| |/ _|____ ___.__.
  412. // | | \_/ __ \\____ \| | / _ < | || <_/ __ < | |
  413. // | ` \ ___/| |_> > |_( <_> )___ || | \ ___/\___ |
  414. // /_______ /\___ > __/|____/\____// ____||____|__ \___ > ____|
  415. // \/ \/|__| \/ \/ \/\/
  416. // DeployKey represents deploy key information and its relation with repository.
  417. type DeployKey struct {
  418. ID int64 `xorm:"pk autoincr"`
  419. KeyID int64 `xorm:"UNIQUE(s) INDEX"`
  420. RepoID int64 `xorm:"UNIQUE(s) INDEX"`
  421. Name string
  422. Fingerprint string
  423. Content string `xorm:"-"`
  424. Created time.Time `xorm:"CREATED"`
  425. Updated time.Time // Note: Updated must below Created for AfterSet.
  426. HasRecentActivity bool `xorm:"-"`
  427. HasUsed bool `xorm:"-"`
  428. }
  429. func (k *DeployKey) AfterSet(colName string, _ xorm.Cell) {
  430. switch colName {
  431. case "created":
  432. k.HasUsed = k.Updated.After(k.Created)
  433. k.HasRecentActivity = k.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  434. }
  435. }
  436. // GetContent gets associated public key content.
  437. func (k *DeployKey) GetContent() error {
  438. pkey, err := GetPublicKeyByID(k.KeyID)
  439. if err != nil {
  440. return err
  441. }
  442. k.Content = pkey.Content
  443. return nil
  444. }
  445. func checkDeployKey(e Engine, keyID, repoID int64, name string) error {
  446. // Note: We want error detail, not just true or false here.
  447. has, err := e.Where("key_id=? AND repo_id=?", keyID, repoID).Get(new(DeployKey))
  448. if err != nil {
  449. return err
  450. } else if has {
  451. return ErrDeployKeyAlreadyExist{keyID, repoID}
  452. }
  453. has, err = e.Where("repo_id=? AND name=?", repoID, name).Get(new(DeployKey))
  454. if err != nil {
  455. return err
  456. } else if has {
  457. return ErrDeployKeyNameAlreadyUsed{repoID, name}
  458. }
  459. return nil
  460. }
  461. // addDeployKey adds new key-repo relation.
  462. func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string) (*DeployKey, error) {
  463. if err := checkDeployKey(e, keyID, repoID, name); err != nil {
  464. return nil, err
  465. }
  466. key := &DeployKey{
  467. KeyID: keyID,
  468. RepoID: repoID,
  469. Name: name,
  470. Fingerprint: fingerprint,
  471. }
  472. _, err := e.Insert(key)
  473. return key, err
  474. }
  475. // HasDeployKey returns true if public key is a deploy key of given repository.
  476. func HasDeployKey(keyID, repoID int64) bool {
  477. has, _ := x.Where("key_id=? AND repo_id=?", keyID, repoID).Get(new(DeployKey))
  478. return has
  479. }
  480. // AddDeployKey add new deploy key to database and authorized_keys file.
  481. func AddDeployKey(repoID int64, name, content string) (*DeployKey, error) {
  482. if err := checkKeyContent(content); err != nil {
  483. return nil, err
  484. }
  485. pkey := &PublicKey{
  486. Content: content,
  487. Mode: ACCESS_MODE_READ,
  488. Type: KEY_TYPE_DEPLOY,
  489. }
  490. has, err := x.Get(pkey)
  491. if err != nil {
  492. return nil, err
  493. }
  494. sess := x.NewSession()
  495. defer sessionRelease(sess)
  496. if err = sess.Begin(); err != nil {
  497. return nil, err
  498. }
  499. // First time use this deploy key.
  500. if !has {
  501. if err = addKey(sess, pkey); err != nil {
  502. return nil, fmt.Errorf("addKey: %v", err)
  503. }
  504. }
  505. key, err := addDeployKey(sess, pkey.ID, repoID, name, pkey.Fingerprint)
  506. if err != nil {
  507. return nil, fmt.Errorf("addDeployKey: %v", err)
  508. }
  509. return key, sess.Commit()
  510. }
  511. // GetDeployKeyByID returns deploy key by given ID.
  512. func GetDeployKeyByID(id int64) (*DeployKey, error) {
  513. key := new(DeployKey)
  514. has, err := x.Id(id).Get(key)
  515. if err != nil {
  516. return nil, err
  517. } else if !has {
  518. return nil, ErrDeployKeyNotExist{id, 0, 0}
  519. }
  520. return key, nil
  521. }
  522. // GetDeployKeyByRepo returns deploy key by given public key ID and repository ID.
  523. func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) {
  524. key := &DeployKey{
  525. KeyID: keyID,
  526. RepoID: repoID,
  527. }
  528. has, err := x.Get(key)
  529. if err != nil {
  530. return nil, err
  531. } else if !has {
  532. return nil, ErrDeployKeyNotExist{0, keyID, repoID}
  533. }
  534. return key, nil
  535. }
  536. // UpdateDeployKey updates deploy key information.
  537. func UpdateDeployKey(key *DeployKey) error {
  538. _, err := x.Id(key.ID).AllCols().Update(key)
  539. return err
  540. }
  541. // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed.
  542. func DeleteDeployKey(doer *User, id int64) error {
  543. key, err := GetDeployKeyByID(id)
  544. if err != nil {
  545. if IsErrDeployKeyNotExist(err) {
  546. return nil
  547. }
  548. return fmt.Errorf("GetDeployKeyByID: %v", err)
  549. }
  550. // Check if user has access to delete this key.
  551. if !doer.IsAdmin {
  552. repo, err := GetRepositoryByID(key.RepoID)
  553. if err != nil {
  554. return fmt.Errorf("GetRepositoryByID: %v", err)
  555. }
  556. yes, err := HasAccess(doer, repo, ACCESS_MODE_ADMIN)
  557. if err != nil {
  558. return fmt.Errorf("HasAccess: %v", err)
  559. } else if !yes {
  560. return ErrKeyAccessDenied{doer.Id, key.ID, "deploy"}
  561. }
  562. }
  563. sess := x.NewSession()
  564. defer sessionRelease(sess)
  565. if err = sess.Begin(); err != nil {
  566. return err
  567. }
  568. if _, err = sess.Id(key.ID).Delete(new(DeployKey)); err != nil {
  569. return fmt.Errorf("delete deploy key[%d]: %v", key.ID, err)
  570. }
  571. // Check if this is the last reference to same key content.
  572. has, err := sess.Where("key_id=?", key.KeyID).Get(new(DeployKey))
  573. if err != nil {
  574. return err
  575. } else if !has {
  576. if err = deletePublicKey(sess, key.KeyID); err != nil {
  577. return err
  578. }
  579. }
  580. return sess.Commit()
  581. }
  582. // ListDeployKeys returns all deploy keys by given repository ID.
  583. func ListDeployKeys(repoID int64) ([]*DeployKey, error) {
  584. keys := make([]*DeployKey, 0, 5)
  585. return keys, x.Where("repo_id=?", repoID).Find(&keys)
  586. }