publickey.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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. "os"
  11. "os/exec"
  12. "path"
  13. "path/filepath"
  14. "strings"
  15. "sync"
  16. "time"
  17. "github.com/Unknwon/com"
  18. )
  19. var (
  20. sshOpLocker = sync.Mutex{}
  21. //publicKeyRootPath string
  22. sshPath string
  23. appPath string
  24. // "### autogenerated by gitgos, DO NOT EDIT\n"
  25. tmplPublicKey = "command=\"%s serv key-%d\",no-port-forwarding," +
  26. "no-X11-forwarding,no-agent-forwarding,no-pty %s\n"
  27. )
  28. func exePath() (string, error) {
  29. file, err := exec.LookPath(os.Args[0])
  30. if err != nil {
  31. return "", err
  32. }
  33. return filepath.Abs(file)
  34. }
  35. func homeDir() string {
  36. home, err := com.HomeDir()
  37. if err != nil {
  38. return "/"
  39. }
  40. return home
  41. }
  42. func init() {
  43. var err error
  44. appPath, err = exePath()
  45. if err != nil {
  46. println(err.Error())
  47. os.Exit(2)
  48. }
  49. sshPath = filepath.Join(homeDir(), ".ssh")
  50. }
  51. type PublicKey struct {
  52. Id int64
  53. OwnerId int64 `xorm:"index"`
  54. Name string `xorm:"unique not null"`
  55. Fingerprint string
  56. Content string `xorm:"text not null"`
  57. Created time.Time `xorm:"created"`
  58. Updated time.Time `xorm:"updated"`
  59. }
  60. func GenAuthorizedKey(keyId int64, key string) string {
  61. return fmt.Sprintf(tmplPublicKey, appPath, keyId, key)
  62. }
  63. func AddPublicKey(key *PublicKey) (err error) {
  64. // Calculate fingerprint.
  65. tmpPath := filepath.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
  66. "id_rsa.pub")
  67. os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
  68. f, err := os.Create(tmpPath)
  69. if err != nil {
  70. return
  71. }
  72. if _, err = f.WriteString(key.Content); err != nil {
  73. return err
  74. }
  75. f.Close()
  76. stdout, _, err := com.ExecCmd("ssh-keygen", "-l", "-f", tmpPath)
  77. if err != nil {
  78. return err
  79. } else if len(stdout) < 2 {
  80. return errors.New("Not enough output for calculating fingerprint")
  81. }
  82. key.Fingerprint = strings.Split(stdout, " ")[1]
  83. // Save SSH key.
  84. if _, err = orm.Insert(key); err != nil {
  85. return err
  86. }
  87. if err = SaveAuthorizedKeyFile(key); err != nil {
  88. if _, err2 := orm.Delete(key); err2 != nil {
  89. return err2
  90. }
  91. return err
  92. }
  93. return nil
  94. }
  95. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  96. func DeletePublicKey(key *PublicKey) (err error) {
  97. has, err := orm.Id(key.Id).Get(key)
  98. if err != nil {
  99. return err
  100. } else if !has {
  101. return errors.New("Public key does not exist")
  102. }
  103. if _, err = orm.Delete(key); err != nil {
  104. return err
  105. }
  106. sshOpLocker.Lock()
  107. defer sshOpLocker.Unlock()
  108. p := filepath.Join(sshPath, "authorized_keys")
  109. tmpP := filepath.Join(sshPath, "authorized_keys.tmp")
  110. fr, err := os.Open(p)
  111. if err != nil {
  112. return err
  113. }
  114. defer fr.Close()
  115. fw, err := os.Create(tmpP)
  116. if err != nil {
  117. return err
  118. }
  119. defer fw.Close()
  120. buf := bufio.NewReader(fr)
  121. for {
  122. line, errRead := buf.ReadString('\n')
  123. line = strings.TrimSpace(line)
  124. if errRead != nil {
  125. if errRead != io.EOF {
  126. return errRead
  127. }
  128. // Reached end of file, if nothing to read then break,
  129. // otherwise handle the last line.
  130. if len(line) == 0 {
  131. break
  132. }
  133. }
  134. // Found the line and copy rest of file.
  135. if strings.Contains(line, fmt.Sprintf("key-%d", key.Id)) && strings.Contains(line, key.Content) {
  136. continue
  137. }
  138. // Still finding the line, copy the line that currently read.
  139. if _, err = fw.WriteString(line + "\n"); err != nil {
  140. return err
  141. }
  142. if errRead == io.EOF {
  143. break
  144. }
  145. }
  146. if err = os.Remove(p); err != nil {
  147. return err
  148. }
  149. return os.Rename(tmpP, p)
  150. }
  151. func ListPublicKey(userId int64) ([]PublicKey, error) {
  152. keys := make([]PublicKey, 0)
  153. err := orm.Find(&keys, &PublicKey{OwnerId: userId})
  154. return keys, err
  155. }
  156. func SaveAuthorizedKeyFile(key *PublicKey) error {
  157. sshOpLocker.Lock()
  158. defer sshOpLocker.Unlock()
  159. p := filepath.Join(sshPath, "authorized_keys")
  160. f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  161. if err != nil {
  162. return err
  163. }
  164. defer f.Close()
  165. //os.Chmod(p, 0600)
  166. _, err = f.WriteString(GenAuthorizedKey(key.Id, key.Content))
  167. return err
  168. }