publickey.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
  28. )
  29. var (
  30. ErrKeyAlreadyExist = errors.New("Public key already exist")
  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 SshPath(%s): %v\n", 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, 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(key *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. _, err = f.WriteString(key.GetAuthorizedString())
  233. return err
  234. }
  235. // AddPublicKey adds new public key to database and authorized_keys file.
  236. func AddPublicKey(key *PublicKey) (err error) {
  237. has, err := x.Get(key)
  238. if err != nil {
  239. return err
  240. } else if has {
  241. return ErrKeyAlreadyExist
  242. }
  243. // Calculate fingerprint.
  244. tmpPath := strings.Replace(path.Join(os.TempDir(), fmt.Sprintf("%d", time.Now().Nanosecond()),
  245. "id_rsa.pub"), "\\", "/", -1)
  246. os.MkdirAll(path.Dir(tmpPath), os.ModePerm)
  247. if err = ioutil.WriteFile(tmpPath, []byte(key.Content), os.ModePerm); err != nil {
  248. return err
  249. }
  250. stdout, stderr, err := process.Exec("AddPublicKey", "ssh-keygen", "-l", "-f", tmpPath)
  251. if err != nil {
  252. return errors.New("ssh-keygen -l -f: " + stderr)
  253. } else if len(stdout) < 2 {
  254. return errors.New("not enough output for calculating fingerprint: " + stdout)
  255. }
  256. key.Fingerprint = strings.Split(stdout, " ")[1]
  257. if has, err := x.Get(&PublicKey{Fingerprint: key.Fingerprint}); err == nil && has {
  258. return ErrKeyAlreadyExist
  259. }
  260. // Save SSH key.
  261. if _, err = x.Insert(key); err != nil {
  262. return err
  263. } else if err = saveAuthorizedKeyFile(key); err != nil {
  264. // Roll back.
  265. if _, err2 := x.Delete(key); err2 != nil {
  266. return err2
  267. }
  268. return err
  269. }
  270. return nil
  271. }
  272. // GetPublicKeyById returns public key by given ID.
  273. func GetPublicKeyById(keyId int64) (*PublicKey, error) {
  274. key := new(PublicKey)
  275. has, err := x.Id(keyId).Get(key)
  276. if err != nil {
  277. return nil, err
  278. } else if !has {
  279. return nil, ErrKeyNotExist
  280. }
  281. return key, nil
  282. }
  283. // ListPublicKeys returns a list of public keys belongs to given user.
  284. func ListPublicKeys(uid int64) ([]*PublicKey, error) {
  285. keys := make([]*PublicKey, 0, 5)
  286. err := x.Where("owner_id=?", uid).Find(&keys)
  287. if err != nil {
  288. return nil, err
  289. }
  290. for _, key := range keys {
  291. key.HasUsed = key.Updated.After(key.Created)
  292. key.HasRecentActivity = key.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  293. }
  294. return keys, nil
  295. }
  296. // rewriteAuthorizedKeys finds and deletes corresponding line in authorized_keys file.
  297. func rewriteAuthorizedKeys(key *PublicKey, p, tmpP string) error {
  298. sshOpLocker.Lock()
  299. defer sshOpLocker.Unlock()
  300. fr, err := os.Open(p)
  301. if err != nil {
  302. return err
  303. }
  304. defer fr.Close()
  305. fw, err := os.OpenFile(tmpP, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  306. if err != nil {
  307. return err
  308. }
  309. defer fw.Close()
  310. isFound := false
  311. keyword := fmt.Sprintf("key-%d", key.Id)
  312. buf := bufio.NewReader(fr)
  313. for {
  314. line, errRead := buf.ReadString('\n')
  315. line = strings.TrimSpace(line)
  316. if errRead != nil {
  317. if errRead != io.EOF {
  318. return errRead
  319. }
  320. // Reached end of file, if nothing to read then break,
  321. // otherwise handle the last line.
  322. if len(line) == 0 {
  323. break
  324. }
  325. }
  326. // Found the line and copy rest of file.
  327. if !isFound && strings.Contains(line, keyword) && strings.Contains(line, key.Content) {
  328. isFound = true
  329. continue
  330. }
  331. // Still finding the line, copy the line that currently read.
  332. if _, err = fw.WriteString(line + "\n"); err != nil {
  333. return err
  334. }
  335. if errRead == io.EOF {
  336. break
  337. }
  338. }
  339. return nil
  340. }
  341. // UpdatePublicKey updates given public key.
  342. func UpdatePublicKey(key *PublicKey) error {
  343. _, err := x.Id(key.Id).AllCols().Update(key)
  344. return err
  345. }
  346. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  347. func DeletePublicKey(key *PublicKey) error {
  348. has, err := x.Get(key)
  349. if err != nil {
  350. return err
  351. } else if !has {
  352. return ErrKeyNotExist
  353. }
  354. if _, err = x.Delete(key); err != nil {
  355. return err
  356. }
  357. fpath := filepath.Join(SshPath, "authorized_keys")
  358. tmpPath := filepath.Join(SshPath, "authorized_keys.tmp")
  359. if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil {
  360. return err
  361. } else if err = os.Remove(fpath); err != nil {
  362. return err
  363. }
  364. return os.Rename(tmpPath, fpath)
  365. }