publickey.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "strings"
  15. "sync"
  16. "time"
  17. "github.com/Unknwon/com"
  18. qlog "github.com/qiniu/log"
  19. "github.com/gogits/gogs/modules/base"
  20. "github.com/gogits/gogs/modules/log"
  21. )
  22. const (
  23. // "### autogenerated by gitgos, DO NOT EDIT\n"
  24. _TPL_PUBLICK_KEY = `command="%s serv key-%d",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
  25. )
  26. var (
  27. ErrKeyAlreadyExist = errors.New("Public key already exist")
  28. ErrKeyNotExist = errors.New("Public key does not exist")
  29. )
  30. var sshOpLocker = sync.Mutex{}
  31. var (
  32. sshPath string // SSH directory.
  33. appPath string // Execution(binary) path.
  34. )
  35. // homeDir returns the home directory of current user.
  36. func homeDir() string {
  37. home, err := com.HomeDir()
  38. if err != nil {
  39. qlog.Fatalln(err)
  40. }
  41. return home
  42. }
  43. func init() {
  44. var err error
  45. if appPath, err = base.ExecDir(); err != nil {
  46. qlog.Fatalf("publickey.init(fail to get app path): %v\n", err)
  47. }
  48. // Determine and create .ssh path.
  49. sshPath = filepath.Join(homeDir(), ".ssh")
  50. if err = os.MkdirAll(sshPath, os.ModePerm); err != nil {
  51. qlog.Fatalf("publickey.init(fail to create sshPath(%s)): %v\n", sshPath, err)
  52. }
  53. }
  54. // PublicKey represents a SSH key.
  55. type PublicKey struct {
  56. Id int64
  57. OwnerId int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  58. Name string `xorm:"UNIQUE(s) NOT NULL"`
  59. Fingerprint string
  60. Content string `xorm:"TEXT NOT NULL"`
  61. Created time.Time `xorm:"CREATED"`
  62. Updated time.Time `xorm:"UPDATED"`
  63. }
  64. // GetAuthorizedString generates and returns formatted public key string for authorized_keys file.
  65. func (key *PublicKey) GetAuthorizedString() string {
  66. return fmt.Sprintf(_TPL_PUBLICK_KEY, appPath, key.Id, key.Content)
  67. }
  68. // saveAuthorizedKeyFile writes SSH key content to authorized_keys file.
  69. func saveAuthorizedKeyFile(key *PublicKey) error {
  70. sshOpLocker.Lock()
  71. defer sshOpLocker.Unlock()
  72. fpath := filepath.Join(sshPath, "authorized_keys")
  73. f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  74. if err != nil {
  75. return err
  76. }
  77. defer f.Close()
  78. _, err = f.WriteString(key.GetAuthorizedString())
  79. return err
  80. }
  81. // AddPublicKey adds new public key to database and authorized_keys file.
  82. func AddPublicKey(key *PublicKey) (err error) {
  83. has, err := orm.Get(key)
  84. if err != nil {
  85. return err
  86. } else if has {
  87. return ErrKeyAlreadyExist
  88. }
  89. // Calculate fingerprint.
  90. tmpPath := strings.Replace(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
  91. "id_rsa.pub"), "\\", "/", -1)
  92. os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
  93. if err = ioutil.WriteFile(tmpPath, []byte(key.Content), os.ModePerm); err != nil {
  94. return err
  95. }
  96. stdout, stderr, err := com.ExecCmd("ssh-keygen", "-l", "-f", tmpPath)
  97. if err != nil {
  98. return errors.New("ssh-keygen -l -f: " + stderr)
  99. } else if len(stdout) < 2 {
  100. return errors.New("Not enough output for calculating fingerprint")
  101. }
  102. key.Fingerprint = strings.Split(stdout, " ")[1]
  103. // Save SSH key.
  104. if _, err = orm.Insert(key); err != nil {
  105. return err
  106. } else if err = saveAuthorizedKeyFile(key); err != nil {
  107. // Roll back.
  108. if _, err2 := orm.Delete(key); err2 != nil {
  109. return err2
  110. }
  111. return err
  112. }
  113. return nil
  114. }
  115. // ListPublicKey returns a list of all public keys that user has.
  116. func ListPublicKey(uid int64) ([]PublicKey, error) {
  117. keys := make([]PublicKey, 0, 5)
  118. err := orm.Find(&keys, &PublicKey{OwnerId: uid})
  119. return keys, err
  120. }
  121. // rewriteAuthorizedKeys finds and deletes corresponding line in authorized_keys file.
  122. func rewriteAuthorizedKeys(key *PublicKey, p, tmpP string) error {
  123. sshOpLocker.Lock()
  124. defer sshOpLocker.Unlock()
  125. fr, err := os.Open(p)
  126. if err != nil {
  127. return err
  128. }
  129. defer fr.Close()
  130. fw, err := os.Create(tmpP)
  131. if err != nil {
  132. return err
  133. }
  134. defer fw.Close()
  135. isFound := false
  136. keyword := fmt.Sprintf("key-%d", key.Id)
  137. buf := bufio.NewReader(fr)
  138. for {
  139. line, errRead := buf.ReadString('\n')
  140. line = strings.TrimSpace(line)
  141. if errRead != nil {
  142. if errRead != io.EOF {
  143. return errRead
  144. }
  145. // Reached end of file, if nothing to read then break,
  146. // otherwise handle the last line.
  147. if len(line) == 0 {
  148. break
  149. }
  150. }
  151. // Found the line and copy rest of file.
  152. if !isFound && strings.Contains(line, keyword) && strings.Contains(line, key.Content) {
  153. isFound = true
  154. continue
  155. }
  156. // Still finding the line, copy the line that currently read.
  157. if _, err = fw.WriteString(line + "\n"); err != nil {
  158. return err
  159. }
  160. if errRead == io.EOF {
  161. break
  162. }
  163. }
  164. return nil
  165. }
  166. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  167. func DeletePublicKey(key *PublicKey) error {
  168. has, err := orm.Get(key)
  169. if err != nil {
  170. return err
  171. } else if !has {
  172. return ErrKeyNotExist
  173. }
  174. if _, err = orm.Delete(key); err != nil {
  175. return err
  176. }
  177. fpath := filepath.Join(sshPath, "authorized_keys")
  178. tmpPath := filepath.Join(sshPath, "authorized_keys.tmp")
  179. log.Trace("publickey.DeletePublicKey(authorized_keys): %s", fpath)
  180. if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil {
  181. return err
  182. } else if err = os.Remove(fpath); err != nil {
  183. return err
  184. }
  185. return os.Rename(tmpPath, fpath)
  186. }