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.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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, 0700); 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. finfo, err := f.Stat()
  137. if err != nil {
  138. return err
  139. }
  140. if finfo.Mode().Perm() > 0600 {
  141. log.Error(3, "authorized_keys file has unusual permission flags: %s - setting to -rw-------", finfo.Mode().Perm().String())
  142. err = f.Chmod(0600)
  143. if err != nil {
  144. return err
  145. }
  146. }
  147. _, err = f.WriteString(key.GetAuthorizedString())
  148. return err
  149. }
  150. // AddPublicKey adds new public key to database and authorized_keys file.
  151. func AddPublicKey(key *PublicKey) (err error) {
  152. has, err := x.Get(key)
  153. if err != nil {
  154. return err
  155. } else if has {
  156. return ErrKeyAlreadyExist
  157. }
  158. // Calculate fingerprint.
  159. tmpPath := strings.Replace(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
  160. "id_rsa.pub"), "\\", "/", -1)
  161. os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
  162. if err = ioutil.WriteFile(tmpPath, []byte(key.Content), os.ModePerm); err != nil {
  163. return err
  164. }
  165. stdout, stderr, err := process.Exec("AddPublicKey", "ssh-keygen", "-l", "-f", tmpPath)
  166. if err != nil {
  167. return errors.New("ssh-keygen -l -f: " + stderr)
  168. } else if len(stdout) < 2 {
  169. return errors.New("Not enough output for calculating fingerprint")
  170. }
  171. key.Fingerprint = strings.Split(stdout, " ")[1]
  172. // Save SSH key.
  173. if _, err = x.Insert(key); err != nil {
  174. return err
  175. } else if err = saveAuthorizedKeyFile(key); err != nil {
  176. // Roll back.
  177. if _, err2 := x.Delete(key); err2 != nil {
  178. return err2
  179. }
  180. return err
  181. }
  182. return nil
  183. }
  184. // ListPublicKey returns a list of all public keys that user has.
  185. func ListPublicKey(uid int64) ([]*PublicKey, error) {
  186. keys := make([]*PublicKey, 0, 5)
  187. err := x.Find(&keys, &PublicKey{OwnerId: uid})
  188. if err != nil {
  189. return nil, err
  190. }
  191. for _, key := range keys {
  192. key.HasUsed = key.Updated.After(key.Created)
  193. key.HasRecentActivity = key.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  194. }
  195. return keys, nil
  196. }
  197. // rewriteAuthorizedKeys finds and deletes corresponding line in authorized_keys file.
  198. func rewriteAuthorizedKeys(key *PublicKey, p, tmpP string) error {
  199. sshOpLocker.Lock()
  200. defer sshOpLocker.Unlock()
  201. fr, err := os.Open(p)
  202. if err != nil {
  203. return err
  204. }
  205. defer fr.Close()
  206. fw, err := os.OpenFile(tmpP, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  207. if err != nil {
  208. return err
  209. }
  210. defer fw.Close()
  211. isFound := false
  212. keyword := fmt.Sprintf("key-%d", key.Id)
  213. buf := bufio.NewReader(fr)
  214. for {
  215. line, errRead := buf.ReadString('\n')
  216. line = strings.TrimSpace(line)
  217. if errRead != nil {
  218. if errRead != io.EOF {
  219. return errRead
  220. }
  221. // Reached end of file, if nothing to read then break,
  222. // otherwise handle the last line.
  223. if len(line) == 0 {
  224. break
  225. }
  226. }
  227. // Found the line and copy rest of file.
  228. if !isFound && strings.Contains(line, keyword) && strings.Contains(line, key.Content) {
  229. isFound = true
  230. continue
  231. }
  232. // Still finding the line, copy the line that currently read.
  233. if _, err = fw.WriteString(line + "\n"); err != nil {
  234. return err
  235. }
  236. if errRead == io.EOF {
  237. break
  238. }
  239. }
  240. return nil
  241. }
  242. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  243. func DeletePublicKey(key *PublicKey) error {
  244. has, err := x.Get(key)
  245. if err != nil {
  246. return err
  247. } else if !has {
  248. return ErrKeyNotExist
  249. }
  250. if _, err = x.Delete(key); err != nil {
  251. return err
  252. }
  253. fpath := filepath.Join(SshPath, "authorized_keys")
  254. tmpPath := filepath.Join(SshPath, "authorized_keys.tmp")
  255. if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil {
  256. return err
  257. } else if err = os.Remove(fpath); err != nil {
  258. return err
  259. }
  260. return os.Rename(tmpPath, fpath)
  261. }