publickey.go 8.6 KB

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