You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

publickey.go 8.1KB

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