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.

332 lines
8.4 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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. "github.com/gogits/gogs/modules/setting"
  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. log.Fatal(4, "Fail to get home directory: %v", err)
  49. }
  50. return home
  51. }
  52. func init() {
  53. var err error
  54. if appPath, err = exePath(); err != nil {
  55. log.Fatal(4, "fail to get app path: %v\n", err)
  56. }
  57. appPath = strings.Replace(appPath, "\\", "/", -1)
  58. // Determine and create .ssh path.
  59. SshPath = filepath.Join(homeDir(), ".ssh")
  60. if err = os.MkdirAll(SshPath, 0700); err != nil {
  61. log.Fatal(4, "fail to create SshPath(%s): %v\n", SshPath, err)
  62. }
  63. }
  64. // PublicKey represents a SSH key.
  65. type PublicKey struct {
  66. Id int64
  67. OwnerId int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  68. Name string `xorm:"UNIQUE(s) NOT NULL"`
  69. Fingerprint string
  70. Content string `xorm:"TEXT NOT NULL"`
  71. Created time.Time `xorm:"CREATED"`
  72. Updated time.Time
  73. HasRecentActivity bool `xorm:"-"`
  74. HasUsed bool `xorm:"-"`
  75. }
  76. // GetAuthorizedString generates and returns formatted public key string for authorized_keys file.
  77. func (key *PublicKey) GetAuthorizedString() string {
  78. return fmt.Sprintf(_TPL_PUBLICK_KEY, appPath, key.Id, key.Content)
  79. }
  80. var (
  81. MinimumKeySize = map[string]int{
  82. "(ED25519)": 256,
  83. "(ECDSA)": 256,
  84. "(NTRU)": 1087,
  85. "(MCE)": 1702,
  86. "(McE)": 1702,
  87. "(RSA)": 2048,
  88. "(DSA)": 1024,
  89. }
  90. )
  91. // CheckPublicKeyString checks if the given public key string is recognized by SSH.
  92. func CheckPublicKeyString(content string) (bool, error) {
  93. if strings.ContainsAny(content, "\n\r") {
  94. return false, errors.New("Only a single line with a single key please")
  95. }
  96. // write the key to a file…
  97. tmpFile, err := ioutil.TempFile(os.TempDir(), "keytest")
  98. if err != nil {
  99. return false, err
  100. }
  101. tmpPath := tmpFile.Name()
  102. defer os.Remove(tmpPath)
  103. tmpFile.WriteString(content)
  104. tmpFile.Close()
  105. // Check if ssh-keygen recognizes its contents.
  106. stdout, stderr, err := process.Exec("CheckPublicKeyString", "ssh-keygen", "-l", "-f", tmpPath)
  107. if err != nil {
  108. return false, errors.New("ssh-keygen -l -f: " + stderr)
  109. } else if len(stdout) < 2 {
  110. return false, errors.New("ssh-keygen returned not enough output to evaluate the key")
  111. }
  112. // The ssh-keygen in Windows does not print key type, so no need go further.
  113. if setting.IsWindows {
  114. return true, nil
  115. }
  116. sshKeygenOutput := strings.Split(stdout, " ")
  117. if len(sshKeygenOutput) < 4 {
  118. return false, errors.New("Not enough fields returned by ssh-keygen -l -f")
  119. }
  120. // Check if key type and key size match.
  121. keySize, err := com.StrTo(sshKeygenOutput[0]).Int()
  122. if err != nil {
  123. return false, errors.New("Cannot get key size of the given key")
  124. }
  125. keyType := strings.TrimSpace(sshKeygenOutput[len(sshKeygenOutput)-1])
  126. if minimumKeySize := MinimumKeySize[keyType]; minimumKeySize == 0 {
  127. return false, errors.New("Sorry, unrecognized public key type")
  128. } else if keySize < minimumKeySize {
  129. return false, fmt.Errorf("The minimum accepted size of a public key %s is %d", keyType, minimumKeySize)
  130. }
  131. return true, nil
  132. }
  133. // saveAuthorizedKeyFile writes SSH key content to authorized_keys file.
  134. func saveAuthorizedKeyFile(key *PublicKey) error {
  135. sshOpLocker.Lock()
  136. defer sshOpLocker.Unlock()
  137. fpath := filepath.Join(SshPath, "authorized_keys")
  138. f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  139. if err != nil {
  140. return err
  141. }
  142. defer f.Close()
  143. finfo, err := f.Stat()
  144. if err != nil {
  145. return err
  146. }
  147. // FIXME: following command does not support in Windows.
  148. if !setting.IsWindows {
  149. if finfo.Mode().Perm() > 0600 {
  150. log.Error(4, "authorized_keys file has unusual permission flags: %s - setting to -rw-------", finfo.Mode().Perm().String())
  151. if err = f.Chmod(0600); err != nil {
  152. return err
  153. }
  154. }
  155. }
  156. _, err = f.WriteString(key.GetAuthorizedString())
  157. return err
  158. }
  159. // AddPublicKey adds new public key to database and authorized_keys file.
  160. func AddPublicKey(key *PublicKey) (err error) {
  161. has, err := x.Get(key)
  162. if err != nil {
  163. return err
  164. } else if has {
  165. return ErrKeyAlreadyExist
  166. }
  167. // Calculate fingerprint.
  168. tmpPath := strings.Replace(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
  169. "id_rsa.pub"), "\\", "/", -1)
  170. os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
  171. if err = ioutil.WriteFile(tmpPath, []byte(key.Content), os.ModePerm); err != nil {
  172. return err
  173. }
  174. stdout, stderr, err := process.Exec("AddPublicKey", "ssh-keygen", "-l", "-f", tmpPath)
  175. if err != nil {
  176. return errors.New("ssh-keygen -l -f: " + stderr)
  177. } else if len(stdout) < 2 {
  178. return errors.New("Not enough output for calculating fingerprint")
  179. }
  180. key.Fingerprint = strings.Split(stdout, " ")[1]
  181. // Save SSH key.
  182. if _, err = x.Insert(key); err != nil {
  183. return err
  184. } else if err = saveAuthorizedKeyFile(key); err != nil {
  185. // Roll back.
  186. if _, err2 := x.Delete(key); err2 != nil {
  187. return err2
  188. }
  189. return err
  190. }
  191. return nil
  192. }
  193. // GetPublicKeyById returns public key by given ID.
  194. func GetPublicKeyById(keyId int64) (*PublicKey, error) {
  195. key := new(PublicKey)
  196. has, err := x.Id(keyId).Get(key)
  197. if err != nil {
  198. return nil, err
  199. } else if !has {
  200. return nil, ErrKeyNotExist
  201. }
  202. return key, nil
  203. }
  204. // ListPublicKey returns a list of all public keys that user has.
  205. func ListPublicKey(uid int64) ([]*PublicKey, error) {
  206. keys := make([]*PublicKey, 0, 5)
  207. err := x.Find(&keys, &PublicKey{OwnerId: uid})
  208. if err != nil {
  209. return nil, err
  210. }
  211. for _, key := range keys {
  212. key.HasUsed = key.Updated.After(key.Created)
  213. key.HasRecentActivity = key.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  214. }
  215. return keys, nil
  216. }
  217. // rewriteAuthorizedKeys finds and deletes corresponding line in authorized_keys file.
  218. func rewriteAuthorizedKeys(key *PublicKey, p, tmpP string) error {
  219. sshOpLocker.Lock()
  220. defer sshOpLocker.Unlock()
  221. fr, err := os.Open(p)
  222. if err != nil {
  223. return err
  224. }
  225. defer fr.Close()
  226. fw, err := os.OpenFile(tmpP, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  227. if err != nil {
  228. return err
  229. }
  230. defer fw.Close()
  231. isFound := false
  232. keyword := fmt.Sprintf("key-%d", key.Id)
  233. buf := bufio.NewReader(fr)
  234. for {
  235. line, errRead := buf.ReadString('\n')
  236. line = strings.TrimSpace(line)
  237. if errRead != nil {
  238. if errRead != io.EOF {
  239. return errRead
  240. }
  241. // Reached end of file, if nothing to read then break,
  242. // otherwise handle the last line.
  243. if len(line) == 0 {
  244. break
  245. }
  246. }
  247. // Found the line and copy rest of file.
  248. if !isFound && strings.Contains(line, keyword) && strings.Contains(line, key.Content) {
  249. isFound = true
  250. continue
  251. }
  252. // Still finding the line, copy the line that currently read.
  253. if _, err = fw.WriteString(line + "\n"); err != nil {
  254. return err
  255. }
  256. if errRead == io.EOF {
  257. break
  258. }
  259. }
  260. return nil
  261. }
  262. // UpdatePublicKey updates given public key.
  263. func UpdatePublicKey(key *PublicKey) error {
  264. _, err := x.Id(key.Id).AllCols().Update(key)
  265. return err
  266. }
  267. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  268. func DeletePublicKey(key *PublicKey) error {
  269. has, err := x.Get(key)
  270. if err != nil {
  271. return err
  272. } else if !has {
  273. return ErrKeyNotExist
  274. }
  275. if _, err = x.Delete(key); err != nil {
  276. return err
  277. }
  278. fpath := filepath.Join(SshPath, "authorized_keys")
  279. tmpPath := filepath.Join(SshPath, "authorized_keys.tmp")
  280. if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil {
  281. return err
  282. } else if err = os.Remove(fpath); err != nil {
  283. return err
  284. }
  285. return os.Rename(tmpPath, fpath)
  286. }