publickey.go 8.4 KB

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