publickey.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. 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. if has, err := x.Get(&PublicKey{Fingerprint: key.Fingerprint}); err == nil && has {
  184. return ErrKeyAlreadyExist
  185. }
  186. // Save SSH key.
  187. if _, err = x.Insert(key); err != nil {
  188. return err
  189. } else if err = saveAuthorizedKeyFile(key); err != nil {
  190. // Roll back.
  191. if _, err2 := x.Delete(key); err2 != nil {
  192. return err2
  193. }
  194. return err
  195. }
  196. return nil
  197. }
  198. // GetPublicKeyById returns public key by given ID.
  199. func GetPublicKeyById(keyId int64) (*PublicKey, error) {
  200. key := new(PublicKey)
  201. has, err := x.Id(keyId).Get(key)
  202. if err != nil {
  203. return nil, err
  204. } else if !has {
  205. return nil, ErrKeyNotExist
  206. }
  207. return key, nil
  208. }
  209. // ListPublicKeys returns a list of public keys belongs to given user.
  210. func ListPublicKeys(uid int64) ([]*PublicKey, error) {
  211. keys := make([]*PublicKey, 0, 5)
  212. err := x.Where("owner_id=?", uid).Find(&keys)
  213. if err != nil {
  214. return nil, err
  215. }
  216. for _, key := range keys {
  217. key.HasUsed = key.Updated.After(key.Created)
  218. key.HasRecentActivity = key.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  219. }
  220. return keys, nil
  221. }
  222. // rewriteAuthorizedKeys finds and deletes corresponding line in authorized_keys file.
  223. func rewriteAuthorizedKeys(key *PublicKey, p, tmpP string) error {
  224. sshOpLocker.Lock()
  225. defer sshOpLocker.Unlock()
  226. fr, err := os.Open(p)
  227. if err != nil {
  228. return err
  229. }
  230. defer fr.Close()
  231. fw, err := os.OpenFile(tmpP, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  232. if err != nil {
  233. return err
  234. }
  235. defer fw.Close()
  236. isFound := false
  237. keyword := fmt.Sprintf("key-%d", key.Id)
  238. buf := bufio.NewReader(fr)
  239. for {
  240. line, errRead := buf.ReadString('\n')
  241. line = strings.TrimSpace(line)
  242. if errRead != nil {
  243. if errRead != io.EOF {
  244. return errRead
  245. }
  246. // Reached end of file, if nothing to read then break,
  247. // otherwise handle the last line.
  248. if len(line) == 0 {
  249. break
  250. }
  251. }
  252. // Found the line and copy rest of file.
  253. if !isFound && strings.Contains(line, keyword) && strings.Contains(line, key.Content) {
  254. isFound = true
  255. continue
  256. }
  257. // Still finding the line, copy the line that currently read.
  258. if _, err = fw.WriteString(line + "\n"); err != nil {
  259. return err
  260. }
  261. if errRead == io.EOF {
  262. break
  263. }
  264. }
  265. return nil
  266. }
  267. // UpdatePublicKey updates given public key.
  268. func UpdatePublicKey(key *PublicKey) error {
  269. _, err := x.Id(key.Id).AllCols().Update(key)
  270. return err
  271. }
  272. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  273. func DeletePublicKey(key *PublicKey) error {
  274. has, err := x.Get(key)
  275. if err != nil {
  276. return err
  277. } else if !has {
  278. return ErrKeyNotExist
  279. }
  280. if _, err = x.Delete(key); err != nil {
  281. return err
  282. }
  283. fpath := filepath.Join(SshPath, "authorized_keys")
  284. tmpPath := filepath.Join(SshPath, "authorized_keys.tmp")
  285. if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil {
  286. return err
  287. } else if err = os.Remove(fpath); err != nil {
  288. return err
  289. }
  290. return os.Rename(tmpPath, fpath)
  291. }