publickey.go 8.8 KB

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