publickey.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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(keys ...*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. for _, key := range keys {
  164. _, err = f.WriteString(key.GetAuthorizedString())
  165. if err != nil {
  166. return err
  167. }
  168. }
  169. return nil
  170. }
  171. // AddPublicKey adds new public key to database and authorized_keys file.
  172. func AddPublicKey(key *PublicKey) (err error) {
  173. has, err := x.Get(key)
  174. if err != nil {
  175. return err
  176. } else if has {
  177. return ErrKeyAlreadyExist
  178. }
  179. // Calculate fingerprint.
  180. tmpPath := strings.Replace(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
  181. "id_rsa.pub"), "\\", "/", -1)
  182. os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
  183. if err = ioutil.WriteFile(tmpPath, []byte(key.Content), os.ModePerm); err != nil {
  184. return err
  185. }
  186. stdout, stderr, err := process.Exec("AddPublicKey", "ssh-keygen", "-l", "-f", tmpPath)
  187. if err != nil {
  188. return errors.New("ssh-keygen -l -f: " + stderr)
  189. } else if len(stdout) < 2 {
  190. return errors.New("not enough output for calculating fingerprint: " + stdout)
  191. }
  192. key.Fingerprint = strings.Split(stdout, " ")[1]
  193. if has, err := x.Get(&PublicKey{Fingerprint: key.Fingerprint}); err == nil && has {
  194. return ErrKeyAlreadyExist
  195. }
  196. // Save SSH key.
  197. if _, err = x.Insert(key); err != nil {
  198. return err
  199. } else if err = saveAuthorizedKeyFile(key); err != nil {
  200. // Roll back.
  201. if _, err2 := x.Delete(key); err2 != nil {
  202. return err2
  203. }
  204. return err
  205. }
  206. return nil
  207. }
  208. // GetPublicKeyById returns public key by given ID.
  209. func GetPublicKeyById(keyId int64) (*PublicKey, error) {
  210. key := new(PublicKey)
  211. has, err := x.Id(keyId).Get(key)
  212. if err != nil {
  213. return nil, err
  214. } else if !has {
  215. return nil, ErrKeyNotExist
  216. }
  217. return key, nil
  218. }
  219. // ListPublicKeys returns a list of public keys belongs to given user.
  220. func ListPublicKeys(uid int64) ([]*PublicKey, error) {
  221. keys := make([]*PublicKey, 0, 5)
  222. err := x.Where("owner_id=?", uid).Find(&keys)
  223. if err != nil {
  224. return nil, err
  225. }
  226. for _, key := range keys {
  227. key.HasUsed = key.Updated.After(key.Created)
  228. key.HasRecentActivity = key.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  229. }
  230. return keys, nil
  231. }
  232. // rewriteAuthorizedKeys finds and deletes corresponding line in authorized_keys file.
  233. func rewriteAuthorizedKeys(key *PublicKey, p, tmpP string) error {
  234. sshOpLocker.Lock()
  235. defer sshOpLocker.Unlock()
  236. fr, err := os.Open(p)
  237. if err != nil {
  238. return err
  239. }
  240. defer fr.Close()
  241. fw, err := os.OpenFile(tmpP, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  242. if err != nil {
  243. return err
  244. }
  245. defer fw.Close()
  246. isFound := false
  247. keyword := fmt.Sprintf("key-%d", key.Id)
  248. buf := bufio.NewReader(fr)
  249. for {
  250. line, errRead := buf.ReadString('\n')
  251. line = strings.TrimSpace(line)
  252. if errRead != nil {
  253. if errRead != io.EOF {
  254. return errRead
  255. }
  256. // Reached end of file, if nothing to read then break,
  257. // otherwise handle the last line.
  258. if len(line) == 0 {
  259. break
  260. }
  261. }
  262. // Found the line and copy rest of file.
  263. if !isFound && strings.Contains(line, keyword) && strings.Contains(line, key.Content) {
  264. isFound = true
  265. continue
  266. }
  267. // Still finding the line, copy the line that currently read.
  268. if _, err = fw.WriteString(line + "\n"); err != nil {
  269. return err
  270. }
  271. if errRead == io.EOF {
  272. break
  273. }
  274. }
  275. return nil
  276. }
  277. // UpdatePublicKey updates given public key.
  278. func UpdatePublicKey(key *PublicKey) error {
  279. _, err := x.Id(key.Id).AllCols().Update(key)
  280. return err
  281. }
  282. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  283. func DeletePublicKey(key *PublicKey) error {
  284. has, err := x.Get(key)
  285. if err != nil {
  286. return err
  287. } else if !has {
  288. return ErrKeyNotExist
  289. }
  290. if _, err = x.Delete(key); err != nil {
  291. return err
  292. }
  293. fpath := filepath.Join(SshPath, "authorized_keys")
  294. tmpPath := filepath.Join(SshPath, "authorized_keys.tmp")
  295. if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil {
  296. return err
  297. } else if err = os.Remove(fpath); err != nil {
  298. return err
  299. }
  300. return os.Rename(tmpPath, fpath)
  301. }
  302. // RewriteAllPublicKeys remove any authorized key and re-write all key from database again
  303. func RewriteAllPublicKeys() error {
  304. keys := make([]*PublicKey, 0, 5)
  305. err := x.Find(&keys)
  306. if err != nil {
  307. return err
  308. }
  309. fpath := filepath.Join(SshPath, "authorized_keys")
  310. if _, err := os.Stat(fpath); os.IsNotExist(err) {
  311. return saveAuthorizedKeyFile(keys...)
  312. }
  313. if err := os.Remove(fpath); err != nil {
  314. return err
  315. }
  316. return saveAuthorizedKeyFile(keys...)
  317. }