Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

publickey.go 5.5KB

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