publickey.go 8.2 KB

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