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.

publickey.go 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. "github.com/gogits/gogs/modules/log"
  20. "github.com/gogits/gogs/modules/process"
  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. // exePath returns the executable path.
  36. func exePath() (string, error) {
  37. file, err := exec.LookPath(os.Args[0])
  38. if err != nil {
  39. return "", err
  40. }
  41. return filepath.Abs(file)
  42. }
  43. // homeDir returns the home directory of current user.
  44. func homeDir() string {
  45. home, err := com.HomeDir()
  46. if err != nil {
  47. log.Fatal(4, "Fail to get home directory: %v", err)
  48. }
  49. return home
  50. }
  51. func init() {
  52. var err error
  53. if appPath, err = exePath(); err != nil {
  54. log.Fatal(4, "fail to get app path: %v\n", err)
  55. }
  56. appPath = strings.Replace(appPath, "\\", "/", -1)
  57. // Determine and create .ssh path.
  58. SshPath = filepath.Join(homeDir(), ".ssh")
  59. if err = os.MkdirAll(SshPath, os.ModePerm); err != nil {
  60. log.Fatal(4, "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
  72. HasRecentActivity bool `xorm:"-"`
  73. HasUsed bool `xorm:"-"`
  74. }
  75. // GetAuthorizedString generates and returns formatted public key string for authorized_keys file.
  76. func (key *PublicKey) GetAuthorizedString() string {
  77. return fmt.Sprintf(_TPL_PUBLICK_KEY, appPath, key.Id, key.Content)
  78. }
  79. var (
  80. MinimumKeySize = map[string]int{
  81. "(ED25519)": 256,
  82. "(ECDSA)": 256,
  83. "(NTRU)": 1087,
  84. "(MCE)": 1702,
  85. "(McE)": 1702,
  86. "(RSA)": 2048,
  87. }
  88. )
  89. // CheckPublicKeyString checks if the given public key string is recognized by SSH.
  90. func CheckPublicKeyString(content string) (bool, error) {
  91. if strings.ContainsAny(content, "\n\r") {
  92. return false, errors.New("Only a single line with a single key please")
  93. }
  94. // write the key to a file…
  95. tmpFile, err := ioutil.TempFile(os.TempDir(), "keytest")
  96. if err != nil {
  97. return false, err
  98. }
  99. tmpPath := tmpFile.Name()
  100. defer os.Remove(tmpPath)
  101. tmpFile.WriteString(content)
  102. tmpFile.Close()
  103. // … see if ssh-keygen recognizes its contents
  104. stdout, stderr, err := process.Exec("CheckPublicKeyString", "ssh-keygen", "-l", "-f", tmpPath)
  105. if err != nil {
  106. return false, errors.New("ssh-keygen -l -f: " + stderr)
  107. } else if len(stdout) < 2 {
  108. return false, errors.New("ssh-keygen returned not enough output to evaluate the key")
  109. }
  110. sshKeygenOutput := strings.Split(stdout, " ")
  111. if len(sshKeygenOutput) < 4 {
  112. return false, errors.New("Not enough fields returned by ssh-keygen -l -f")
  113. }
  114. keySize, err := com.StrTo(sshKeygenOutput[0]).Int()
  115. if err != nil {
  116. return false, errors.New("Cannot get key size of the given key")
  117. }
  118. keyType := strings.TrimSpace(sshKeygenOutput[len(sshKeygenOutput)-1])
  119. if minimumKeySize := MinimumKeySize[keyType]; minimumKeySize == 0 {
  120. return false, errors.New("Sorry, unrecognized public key type")
  121. } else if keySize < minimumKeySize {
  122. return false, fmt.Errorf("The minimum accepted size of a public key %s is %d", keyType, minimumKeySize)
  123. }
  124. return true, nil
  125. }
  126. // saveAuthorizedKeyFile writes SSH key content to authorized_keys file.
  127. func saveAuthorizedKeyFile(key *PublicKey) error {
  128. sshOpLocker.Lock()
  129. defer sshOpLocker.Unlock()
  130. fpath := filepath.Join(SshPath, "authorized_keys")
  131. f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  132. if err != nil {
  133. return err
  134. }
  135. defer f.Close()
  136. _, err = f.WriteString(key.GetAuthorizedString())
  137. return err
  138. }
  139. // AddPublicKey adds new public key to database and authorized_keys file.
  140. func AddPublicKey(key *PublicKey) (err error) {
  141. has, err := x.Get(key)
  142. if err != nil {
  143. return err
  144. } else if has {
  145. return ErrKeyAlreadyExist
  146. }
  147. // Calculate fingerprint.
  148. tmpPath := strings.Replace(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
  149. "id_rsa.pub"), "\\", "/", -1)
  150. os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
  151. if err = ioutil.WriteFile(tmpPath, []byte(key.Content), os.ModePerm); err != nil {
  152. return err
  153. }
  154. stdout, stderr, err := process.Exec("AddPublicKey", "ssh-keygen", "-l", "-f", tmpPath)
  155. if err != nil {
  156. return errors.New("ssh-keygen -l -f: " + stderr)
  157. } else if len(stdout) < 2 {
  158. return errors.New("Not enough output for calculating fingerprint")
  159. }
  160. key.Fingerprint = strings.Split(stdout, " ")[1]
  161. // Save SSH key.
  162. if _, err = x.Insert(key); err != nil {
  163. return err
  164. } else if err = saveAuthorizedKeyFile(key); err != nil {
  165. // Roll back.
  166. if _, err2 := x.Delete(key); err2 != nil {
  167. return err2
  168. }
  169. return err
  170. }
  171. return nil
  172. }
  173. // ListPublicKey returns a list of all public keys that user has.
  174. func ListPublicKey(uid int64) ([]*PublicKey, error) {
  175. keys := make([]*PublicKey, 0, 5)
  176. err := x.Find(&keys, &PublicKey{OwnerId: uid})
  177. if err != nil {
  178. return nil, err
  179. }
  180. for _, key := range keys {
  181. key.HasUsed = key.Updated.After(key.Created)
  182. key.HasRecentActivity = key.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  183. }
  184. return keys, nil
  185. }
  186. // rewriteAuthorizedKeys finds and deletes corresponding line in authorized_keys file.
  187. func rewriteAuthorizedKeys(key *PublicKey, p, tmpP string) error {
  188. sshOpLocker.Lock()
  189. defer sshOpLocker.Unlock()
  190. fr, err := os.Open(p)
  191. if err != nil {
  192. return err
  193. }
  194. defer fr.Close()
  195. fw, err := os.OpenFile(tmpP, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  196. if err != nil {
  197. return err
  198. }
  199. defer fw.Close()
  200. isFound := false
  201. keyword := fmt.Sprintf("key-%d", key.Id)
  202. buf := bufio.NewReader(fr)
  203. for {
  204. line, errRead := buf.ReadString('\n')
  205. line = strings.TrimSpace(line)
  206. if errRead != nil {
  207. if errRead != io.EOF {
  208. return errRead
  209. }
  210. // Reached end of file, if nothing to read then break,
  211. // otherwise handle the last line.
  212. if len(line) == 0 {
  213. break
  214. }
  215. }
  216. // Found the line and copy rest of file.
  217. if !isFound && strings.Contains(line, keyword) && strings.Contains(line, key.Content) {
  218. isFound = true
  219. continue
  220. }
  221. // Still finding the line, copy the line that currently read.
  222. if _, err = fw.WriteString(line + "\n"); err != nil {
  223. return err
  224. }
  225. if errRead == io.EOF {
  226. break
  227. }
  228. }
  229. return nil
  230. }
  231. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  232. func DeletePublicKey(key *PublicKey) error {
  233. has, err := x.Get(key)
  234. if err != nil {
  235. return err
  236. } else if !has {
  237. return ErrKeyNotExist
  238. }
  239. if _, err = x.Delete(key); err != nil {
  240. return err
  241. }
  242. fpath := filepath.Join(SshPath, "authorized_keys")
  243. tmpPath := filepath.Join(SshPath, "authorized_keys.tmp")
  244. if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil {
  245. return err
  246. } else if err = os.Remove(fpath); err != nil {
  247. return err
  248. }
  249. return os.Rename(tmpPath, fpath)
  250. }