publickey.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. "bytes"
  8. "errors"
  9. "fmt"
  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`
  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 of user.
  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. // GenAuthorizedKey returns formatted public key string.
  65. func GenAuthorizedKey(keyId int64, key string) string {
  66. return fmt.Sprintf(TPL_PUBLICK_KEY+"\n", appPath, keyId, key)
  67. }
  68. // AddPublicKey adds new public key to database and SSH key file.
  69. func AddPublicKey(key *PublicKey) (err error) {
  70. // Check if public key name has been used.
  71. has, err := orm.Get(key)
  72. if err != nil {
  73. return err
  74. } else if has {
  75. return ErrKeyAlreadyExist
  76. }
  77. // Calculate fingerprint.
  78. tmpPath := strings.Replace(filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
  79. "id_rsa.pub"), "\\", "/", -1)
  80. os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
  81. if err = ioutil.WriteFile(tmpPath, []byte(key.Content), os.ModePerm); err != nil {
  82. return err
  83. }
  84. stdout, stderr, err := com.ExecCmd("ssh-keygen", "-l", "-f", tmpPath)
  85. if err != nil {
  86. return errors.New("ssh-keygen -l -f: " + stderr)
  87. } else if len(stdout) < 2 {
  88. return errors.New("Not enough output for calculating fingerprint")
  89. }
  90. key.Fingerprint = strings.Split(stdout, " ")[1]
  91. // Save SSH key.
  92. if _, err = orm.Insert(key); err != nil {
  93. return err
  94. }
  95. if err = SaveAuthorizedKeyFile(key); err != nil {
  96. if _, err2 := orm.Delete(key); err2 != nil {
  97. return err2
  98. }
  99. return err
  100. }
  101. return nil
  102. }
  103. // rewriteAuthorizedKeys finds and deletes corresponding line in authorized_keys file.
  104. func rewriteAuthorizedKeys(key *PublicKey, p, tmpP string) error {
  105. sshOpLocker.Lock()
  106. defer sshOpLocker.Unlock()
  107. fr, err := os.Open(p)
  108. if err != nil {
  109. return err
  110. }
  111. defer fr.Close()
  112. fw, err := os.Create(tmpP)
  113. if err != nil {
  114. return err
  115. }
  116. defer fw.Close()
  117. isFound := false
  118. keyword := []byte(fmt.Sprintf("key-%d", key.Id))
  119. content := []byte(key.Content)
  120. snr := bufio.NewScanner(fr)
  121. for snr.Scan() {
  122. line := append(bytes.TrimSpace(snr.Bytes()), '\n')
  123. if len(line) == 0 {
  124. continue
  125. }
  126. // Found the line and copy rest of file.
  127. if !isFound && bytes.Contains(line, keyword) && bytes.Contains(line, content) {
  128. isFound = true
  129. continue
  130. }
  131. // Still finding the line, copy the line that currently read.
  132. if _, err = fw.Write(line); err != nil {
  133. return err
  134. }
  135. }
  136. return nil
  137. }
  138. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  139. func DeletePublicKey(key *PublicKey) error {
  140. has, err := orm.Get(key)
  141. if err != nil {
  142. return err
  143. } else if !has {
  144. return ErrKeyNotExist
  145. }
  146. if _, err = orm.Delete(key); err != nil {
  147. return err
  148. }
  149. p := filepath.Join(sshPath, "authorized_keys")
  150. tmpP := filepath.Join(sshPath, "authorized_keys.tmp")
  151. log.Trace("publickey.DeletePublicKey(authorized_keys): %s", p)
  152. if err = rewriteAuthorizedKeys(key, p, tmpP); err != nil {
  153. return err
  154. } else if err = os.Remove(p); err != nil {
  155. return err
  156. }
  157. return os.Rename(tmpP, p)
  158. }
  159. // ListPublicKey returns a list of public keys that user has.
  160. func ListPublicKey(userId int64) ([]PublicKey, error) {
  161. keys := make([]PublicKey, 0)
  162. err := orm.Find(&keys, &PublicKey{OwnerId: userId})
  163. return keys, err
  164. }
  165. // SaveAuthorizedKeyFile writes SSH key content to SSH key file.
  166. func SaveAuthorizedKeyFile(key *PublicKey) error {
  167. sshOpLocker.Lock()
  168. defer sshOpLocker.Unlock()
  169. p := filepath.Join(sshPath, "authorized_keys")
  170. f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  171. if err != nil {
  172. return err
  173. }
  174. defer f.Close()
  175. _, err = f.WriteString(GenAuthorizedKey(key.Id, key.Content))
  176. return err
  177. }