publickey.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. "encoding/base64"
  8. "encoding/binary"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "io/ioutil"
  13. "os"
  14. "os/exec"
  15. "path"
  16. "path/filepath"
  17. "strings"
  18. "sync"
  19. "time"
  20. "github.com/Unknwon/com"
  21. "github.com/gogits/gogs/modules/log"
  22. "github.com/gogits/gogs/modules/process"
  23. "github.com/gogits/gogs/modules/setting"
  24. )
  25. const (
  26. // "### autogenerated by gitgos, DO NOT EDIT\n"
  27. _TPL_PUBLICK_KEY = `command="%s serv key-%d --config='%s'",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
  28. )
  29. var (
  30. ErrKeyAlreadyExist = errors.New("Public key already exists")
  31. ErrKeyNotExist = errors.New("Public key does not exist")
  32. ErrKeyUnableVerify = errors.New("Unable to verify public key")
  33. )
  34. var sshOpLocker = sync.Mutex{}
  35. var (
  36. SSHPath string // SSH directory.
  37. appPath string // Execution(binary) path.
  38. )
  39. // exePath returns the executable path.
  40. func exePath() (string, error) {
  41. file, err := exec.LookPath(os.Args[0])
  42. if err != nil {
  43. return "", err
  44. }
  45. return filepath.Abs(file)
  46. }
  47. // homeDir returns the home directory of current user.
  48. func homeDir() string {
  49. home, err := com.HomeDir()
  50. if err != nil {
  51. log.Fatal(4, "Fail to get home directory: %v", err)
  52. }
  53. return home
  54. }
  55. func init() {
  56. var err error
  57. if appPath, err = exePath(); err != nil {
  58. log.Fatal(4, "fail to get app path: %v\n", err)
  59. }
  60. appPath = strings.Replace(appPath, "\\", "/", -1)
  61. // Determine and create .ssh path.
  62. SSHPath = filepath.Join(homeDir(), ".ssh")
  63. if err = os.MkdirAll(SSHPath, 0700); err != nil {
  64. log.Fatal(4, "fail to create '%s': %v", SSHPath, err)
  65. }
  66. }
  67. // PublicKey represents a SSH key.
  68. type PublicKey struct {
  69. Id int64
  70. OwnerId int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  71. Name string `xorm:"UNIQUE(s) NOT NULL"`
  72. Fingerprint string `xorm:"INDEX NOT NULL"`
  73. Content string `xorm:"TEXT NOT NULL"`
  74. Created time.Time `xorm:"CREATED"`
  75. Updated time.Time
  76. HasRecentActivity bool `xorm:"-"`
  77. HasUsed bool `xorm:"-"`
  78. }
  79. // OmitEmail returns content of public key but without e-mail address.
  80. func (k *PublicKey) OmitEmail() string {
  81. return strings.Join(strings.Split(k.Content, " ")[:2], " ")
  82. }
  83. // GetAuthorizedString generates and returns formatted public key string for authorized_keys file.
  84. func (key *PublicKey) GetAuthorizedString() string {
  85. return fmt.Sprintf(_TPL_PUBLICK_KEY, appPath, key.Id, setting.CustomConf, key.Content)
  86. }
  87. var (
  88. MinimumKeySize = map[string]int{
  89. "(ED25519)": 256,
  90. "(ECDSA)": 256,
  91. "(NTRU)": 1087,
  92. "(MCE)": 1702,
  93. "(McE)": 1702,
  94. "(RSA)": 2048,
  95. "(DSA)": 1024,
  96. }
  97. )
  98. func extractTypeFromBase64Key(key string) (string, error) {
  99. b, err := base64.StdEncoding.DecodeString(key)
  100. if err != nil || len(b) < 4 {
  101. return "", errors.New("Invalid key format")
  102. }
  103. keyLength := int(binary.BigEndian.Uint32(b))
  104. if len(b) < 4+keyLength {
  105. return "", errors.New("Invalid key format")
  106. }
  107. return string(b[4 : 4+keyLength]), nil
  108. }
  109. // Parse any key string in openssh or ssh2 format to clean openssh string (rfc4253)
  110. func ParseKeyString(content string) (string, error) {
  111. // Transform all legal line endings to a single "\n"
  112. s := strings.Replace(strings.Replace(strings.TrimSpace(content), "\r\n", "\n", -1), "\r", "\n", -1)
  113. lines := strings.Split(s, "\n")
  114. var keyType, keyContent, keyComment string
  115. if len(lines) == 1 {
  116. // Parse openssh format
  117. parts := strings.Fields(lines[0])
  118. switch len(parts) {
  119. case 0:
  120. return "", errors.New("Empty key")
  121. case 1:
  122. keyContent = parts[0]
  123. case 2:
  124. keyType = parts[0]
  125. keyContent = parts[1]
  126. default:
  127. keyType = parts[0]
  128. keyContent = parts[1]
  129. keyComment = parts[2]
  130. }
  131. // If keyType is not given, extract it from content. If given, validate it
  132. if len(keyType) == 0 {
  133. if t, err := extractTypeFromBase64Key(keyContent); err == nil {
  134. keyType = t
  135. } else {
  136. return "", err
  137. }
  138. } else {
  139. if t, err := extractTypeFromBase64Key(keyContent); err != nil || keyType != t {
  140. return "", err
  141. }
  142. }
  143. } else {
  144. // Parse SSH2 file format.
  145. continuationLine := false
  146. for _, line := range lines {
  147. // Skip lines that:
  148. // 1) are a continuation of the previous line,
  149. // 2) contain ":" as that are comment lines
  150. // 3) contain "-" as that are begin and end tags
  151. if continuationLine || strings.ContainsAny(line, ":-") {
  152. continuationLine = strings.HasSuffix(line, "\\")
  153. } else {
  154. keyContent = keyContent + line
  155. }
  156. }
  157. if t, err := extractTypeFromBase64Key(keyContent); err == nil {
  158. keyType = t
  159. } else {
  160. return "", err
  161. }
  162. }
  163. return keyType + " " + keyContent + " " + keyComment, nil
  164. }
  165. // CheckPublicKeyString checks if the given public key string is recognized by SSH.
  166. func CheckPublicKeyString(content string) (bool, error) {
  167. content = strings.TrimRight(content, "\n\r")
  168. if strings.ContainsAny(content, "\n\r") {
  169. return false, errors.New("only a single line with a single key please")
  170. }
  171. // write the key to a file…
  172. tmpFile, err := ioutil.TempFile(os.TempDir(), "keytest")
  173. if err != nil {
  174. return false, err
  175. }
  176. tmpPath := tmpFile.Name()
  177. defer os.Remove(tmpPath)
  178. tmpFile.WriteString(content)
  179. tmpFile.Close()
  180. // Check if ssh-keygen recognizes its contents.
  181. stdout, stderr, err := process.Exec("CheckPublicKeyString", "ssh-keygen", "-l", "-f", tmpPath)
  182. if err != nil {
  183. return false, errors.New("ssh-keygen -l -f: " + stderr)
  184. } else if len(stdout) < 2 {
  185. return false, errors.New("ssh-keygen returned not enough output to evaluate the key: " + stdout)
  186. }
  187. // The ssh-keygen in Windows does not print key type, so no need go further.
  188. if setting.IsWindows {
  189. return true, nil
  190. }
  191. fmt.Println(stdout)
  192. sshKeygenOutput := strings.Split(stdout, " ")
  193. if len(sshKeygenOutput) < 4 {
  194. return false, ErrKeyUnableVerify
  195. }
  196. // Check if key type and key size match.
  197. keySize := com.StrTo(sshKeygenOutput[0]).MustInt()
  198. if keySize == 0 {
  199. return false, errors.New("cannot get key size of the given key")
  200. }
  201. keyType := strings.TrimSpace(sshKeygenOutput[len(sshKeygenOutput)-1])
  202. if minimumKeySize := MinimumKeySize[keyType]; minimumKeySize == 0 {
  203. return false, errors.New("sorry, unrecognized public key type")
  204. } else if keySize < minimumKeySize {
  205. return false, fmt.Errorf("the minimum accepted size of a public key %s is %d", keyType, minimumKeySize)
  206. }
  207. return true, nil
  208. }
  209. // saveAuthorizedKeyFile writes SSH key content to authorized_keys file.
  210. func saveAuthorizedKeyFile(keys ...*PublicKey) error {
  211. sshOpLocker.Lock()
  212. defer sshOpLocker.Unlock()
  213. fpath := filepath.Join(SSHPath, "authorized_keys")
  214. f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  215. if err != nil {
  216. return err
  217. }
  218. defer f.Close()
  219. finfo, err := f.Stat()
  220. if err != nil {
  221. return err
  222. }
  223. // FIXME: following command does not support in Windows.
  224. if !setting.IsWindows {
  225. if finfo.Mode().Perm() > 0600 {
  226. log.Error(4, "authorized_keys file has unusual permission flags: %s - setting to -rw-------", finfo.Mode().Perm().String())
  227. if err = f.Chmod(0600); err != nil {
  228. return err
  229. }
  230. }
  231. }
  232. for _, key := range keys {
  233. if _, err = f.WriteString(key.GetAuthorizedString()); err != nil {
  234. return err
  235. }
  236. }
  237. return nil
  238. }
  239. // AddPublicKey adds new public key to database and authorized_keys file.
  240. func AddPublicKey(key *PublicKey) (err error) {
  241. has, err := x.Get(key)
  242. if err != nil {
  243. return err
  244. } else if has {
  245. return ErrKeyAlreadyExist
  246. }
  247. // Calculate fingerprint.
  248. tmpPath := strings.Replace(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
  249. "id_rsa.pub"), "\\", "/", -1)
  250. os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
  251. if err = ioutil.WriteFile(tmpPath, []byte(key.Content), os.ModePerm); err != nil {
  252. return err
  253. }
  254. stdout, stderr, err := process.Exec("AddPublicKey", "ssh-keygen", "-l", "-f", tmpPath)
  255. if err != nil {
  256. return errors.New("ssh-keygen -l -f: " + stderr)
  257. } else if len(stdout) < 2 {
  258. return errors.New("not enough output for calculating fingerprint: " + stdout)
  259. }
  260. key.Fingerprint = strings.Split(stdout, " ")[1]
  261. if has, err := x.Get(&PublicKey{Fingerprint: key.Fingerprint}); err == nil && has {
  262. return ErrKeyAlreadyExist
  263. }
  264. // Save SSH key.
  265. if _, err = x.Insert(key); err != nil {
  266. return err
  267. } else if err = saveAuthorizedKeyFile(key); err != nil {
  268. // Roll back.
  269. if _, err2 := x.Delete(key); err2 != nil {
  270. return err2
  271. }
  272. return err
  273. }
  274. return nil
  275. }
  276. // GetPublicKeyById returns public key by given ID.
  277. func GetPublicKeyById(keyId int64) (*PublicKey, error) {
  278. key := new(PublicKey)
  279. has, err := x.Id(keyId).Get(key)
  280. if err != nil {
  281. return nil, err
  282. } else if !has {
  283. return nil, ErrKeyNotExist
  284. }
  285. return key, nil
  286. }
  287. // ListPublicKeys returns a list of public keys belongs to given user.
  288. func ListPublicKeys(uid int64) ([]*PublicKey, error) {
  289. keys := make([]*PublicKey, 0, 5)
  290. err := x.Where("owner_id=?", uid).Find(&keys)
  291. if err != nil {
  292. return nil, err
  293. }
  294. for _, key := range keys {
  295. key.HasUsed = key.Updated.After(key.Created)
  296. key.HasRecentActivity = key.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  297. }
  298. return keys, nil
  299. }
  300. // rewriteAuthorizedKeys finds and deletes corresponding line in authorized_keys file.
  301. func rewriteAuthorizedKeys(key *PublicKey, p, tmpP string) error {
  302. sshOpLocker.Lock()
  303. defer sshOpLocker.Unlock()
  304. fr, err := os.Open(p)
  305. if err != nil {
  306. return err
  307. }
  308. defer fr.Close()
  309. fw, err := os.OpenFile(tmpP, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  310. if err != nil {
  311. return err
  312. }
  313. defer fw.Close()
  314. isFound := false
  315. keyword := fmt.Sprintf("key-%d", key.Id)
  316. buf := bufio.NewReader(fr)
  317. for {
  318. line, errRead := buf.ReadString('\n')
  319. line = strings.TrimSpace(line)
  320. if errRead != nil {
  321. if errRead != io.EOF {
  322. return errRead
  323. }
  324. // Reached end of file, if nothing to read then break,
  325. // otherwise handle the last line.
  326. if len(line) == 0 {
  327. break
  328. }
  329. }
  330. // Found the line and copy rest of file.
  331. if !isFound && strings.Contains(line, keyword) && strings.Contains(line, key.Content) {
  332. isFound = true
  333. continue
  334. }
  335. // Still finding the line, copy the line that currently read.
  336. if _, err = fw.WriteString(line + "\n"); err != nil {
  337. return err
  338. }
  339. if errRead == io.EOF {
  340. break
  341. }
  342. }
  343. return nil
  344. }
  345. // UpdatePublicKey updates given public key.
  346. func UpdatePublicKey(key *PublicKey) error {
  347. _, err := x.Id(key.Id).AllCols().Update(key)
  348. return err
  349. }
  350. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  351. func DeletePublicKey(key *PublicKey) error {
  352. has, err := x.Get(key)
  353. if err != nil {
  354. return err
  355. } else if !has {
  356. return ErrKeyNotExist
  357. }
  358. if _, err = x.Delete(key); err != nil {
  359. return err
  360. }
  361. fpath := filepath.Join(SSHPath, "authorized_keys")
  362. tmpPath := filepath.Join(SSHPath, "authorized_keys.tmp")
  363. if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil {
  364. return err
  365. } else if err = os.Remove(fpath); err != nil {
  366. return err
  367. }
  368. return os.Rename(tmpPath, fpath)
  369. }
  370. // RewriteAllPublicKeys removes any authorized key and rewrite all keys from database again.
  371. func RewriteAllPublicKeys() error {
  372. sshOpLocker.Lock()
  373. defer sshOpLocker.Unlock()
  374. tmpPath := filepath.Join(SSHPath, "authorized_keys.tmp")
  375. f, err := os.Create(tmpPath)
  376. if err != nil {
  377. return err
  378. }
  379. defer os.Remove(tmpPath)
  380. err = x.Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
  381. _, err = f.WriteString((bean.(*PublicKey)).GetAuthorizedString())
  382. return err
  383. })
  384. f.Close()
  385. if err != nil {
  386. return err
  387. }
  388. fpath := filepath.Join(SSHPath, "authorized_keys")
  389. if com.IsExist(fpath) {
  390. if err = os.Remove(fpath); err != nil {
  391. return err
  392. }
  393. }
  394. if err = os.Rename(tmpPath, fpath); err != nil {
  395. return err
  396. }
  397. return nil
  398. }