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.

ssh_key.go 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "bufio"
  8. "encoding/base64"
  9. "encoding/binary"
  10. "errors"
  11. "fmt"
  12. "io/ioutil"
  13. "math/big"
  14. "os"
  15. "path/filepath"
  16. "strings"
  17. "sync"
  18. "time"
  19. "code.gitea.io/gitea/modules/log"
  20. "code.gitea.io/gitea/modules/process"
  21. "code.gitea.io/gitea/modules/setting"
  22. "code.gitea.io/gitea/modules/util"
  23. "github.com/Unknwon/com"
  24. "github.com/go-xorm/xorm"
  25. "golang.org/x/crypto/ssh"
  26. "xorm.io/builder"
  27. )
  28. const (
  29. tplCommentPrefix = `# gitea public key`
  30. tplPublicKey = tplCommentPrefix + "\n" + `command="%s --config='%s' serv key-%d",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty %s` + "\n"
  31. )
  32. var sshOpLocker sync.Mutex
  33. // KeyType specifies the key type
  34. type KeyType int
  35. const (
  36. // KeyTypeUser specifies the user key
  37. KeyTypeUser = iota + 1
  38. // KeyTypeDeploy specifies the deploy key
  39. KeyTypeDeploy
  40. )
  41. // PublicKey represents a user or deploy SSH public key.
  42. type PublicKey struct {
  43. ID int64 `xorm:"pk autoincr"`
  44. OwnerID int64 `xorm:"INDEX NOT NULL"`
  45. Name string `xorm:"NOT NULL"`
  46. Fingerprint string `xorm:"INDEX NOT NULL"`
  47. Content string `xorm:"TEXT NOT NULL"`
  48. Mode AccessMode `xorm:"NOT NULL DEFAULT 2"`
  49. Type KeyType `xorm:"NOT NULL DEFAULT 1"`
  50. LoginSourceID int64 `xorm:"NOT NULL DEFAULT 0"`
  51. CreatedUnix util.TimeStamp `xorm:"created"`
  52. UpdatedUnix util.TimeStamp `xorm:"updated"`
  53. HasRecentActivity bool `xorm:"-"`
  54. HasUsed bool `xorm:"-"`
  55. }
  56. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  57. func (key *PublicKey) AfterLoad() {
  58. key.HasUsed = key.UpdatedUnix > key.CreatedUnix
  59. key.HasRecentActivity = key.UpdatedUnix.AddDuration(7*24*time.Hour) > util.TimeStampNow()
  60. }
  61. // OmitEmail returns content of public key without email address.
  62. func (key *PublicKey) OmitEmail() string {
  63. return strings.Join(strings.Split(key.Content, " ")[:2], " ")
  64. }
  65. // AuthorizedString returns formatted public key string for authorized_keys file.
  66. func (key *PublicKey) AuthorizedString() string {
  67. return fmt.Sprintf(tplPublicKey, setting.AppPath, setting.CustomConf, key.ID, key.Content)
  68. }
  69. func extractTypeFromBase64Key(key string) (string, error) {
  70. b, err := base64.StdEncoding.DecodeString(key)
  71. if err != nil || len(b) < 4 {
  72. return "", fmt.Errorf("invalid key format: %v", err)
  73. }
  74. keyLength := int(binary.BigEndian.Uint32(b))
  75. if len(b) < 4+keyLength {
  76. return "", fmt.Errorf("invalid key format: not enough length %d", keyLength)
  77. }
  78. return string(b[4 : 4+keyLength]), nil
  79. }
  80. // parseKeyString parses any key string in OpenSSH or SSH2 format to clean OpenSSH string (RFC4253).
  81. func parseKeyString(content string) (string, error) {
  82. // Transform all legal line endings to a single "\n".
  83. content = strings.NewReplacer("\r\n", "\n", "\r", "\n").Replace(content)
  84. // remove trailing newline (and beginning spaces too)
  85. content = strings.TrimSpace(content)
  86. lines := strings.Split(content, "\n")
  87. var keyType, keyContent, keyComment string
  88. if len(lines) == 1 {
  89. // Parse OpenSSH format.
  90. parts := strings.SplitN(lines[0], " ", 3)
  91. switch len(parts) {
  92. case 0:
  93. return "", errors.New("empty key")
  94. case 1:
  95. keyContent = parts[0]
  96. case 2:
  97. keyType = parts[0]
  98. keyContent = parts[1]
  99. default:
  100. keyType = parts[0]
  101. keyContent = parts[1]
  102. keyComment = parts[2]
  103. }
  104. // If keyType is not given, extract it from content. If given, validate it.
  105. t, err := extractTypeFromBase64Key(keyContent)
  106. if err != nil {
  107. return "", fmt.Errorf("extractTypeFromBase64Key: %v", err)
  108. }
  109. if len(keyType) == 0 {
  110. keyType = t
  111. } else if keyType != t {
  112. return "", fmt.Errorf("key type and content does not match: %s - %s", keyType, t)
  113. }
  114. } else {
  115. // Parse SSH2 file format.
  116. continuationLine := false
  117. for _, line := range lines {
  118. // Skip lines that:
  119. // 1) are a continuation of the previous line,
  120. // 2) contain ":" as that are comment lines
  121. // 3) contain "-" as that are begin and end tags
  122. if continuationLine || strings.ContainsAny(line, ":-") {
  123. continuationLine = strings.HasSuffix(line, "\\")
  124. } else {
  125. keyContent += line
  126. }
  127. }
  128. t, err := extractTypeFromBase64Key(keyContent)
  129. if err != nil {
  130. return "", fmt.Errorf("extractTypeFromBase64Key: %v", err)
  131. }
  132. keyType = t
  133. }
  134. return keyType + " " + keyContent + " " + keyComment, nil
  135. }
  136. // writeTmpKeyFile writes key content to a temporary file
  137. // and returns the name of that file, along with any possible errors.
  138. func writeTmpKeyFile(content string) (string, error) {
  139. tmpFile, err := ioutil.TempFile(setting.SSH.KeyTestPath, "gitea_keytest")
  140. if err != nil {
  141. return "", fmt.Errorf("TempFile: %v", err)
  142. }
  143. defer tmpFile.Close()
  144. if _, err = tmpFile.WriteString(content); err != nil {
  145. return "", fmt.Errorf("WriteString: %v", err)
  146. }
  147. return tmpFile.Name(), nil
  148. }
  149. // SSHKeyGenParsePublicKey extracts key type and length using ssh-keygen.
  150. func SSHKeyGenParsePublicKey(key string) (string, int, error) {
  151. // The ssh-keygen in Windows does not print key type, so no need go further.
  152. if setting.IsWindows {
  153. return "", 0, nil
  154. }
  155. tmpName, err := writeTmpKeyFile(key)
  156. if err != nil {
  157. return "", 0, fmt.Errorf("writeTmpKeyFile: %v", err)
  158. }
  159. defer os.Remove(tmpName)
  160. stdout, stderr, err := process.GetManager().Exec("SSHKeyGenParsePublicKey", setting.SSH.KeygenPath, "-lf", tmpName)
  161. if err != nil {
  162. return "", 0, fmt.Errorf("fail to parse public key: %s - %s", err, stderr)
  163. }
  164. if strings.Contains(stdout, "is not a public key file") {
  165. return "", 0, ErrKeyUnableVerify{stdout}
  166. }
  167. fields := strings.Split(stdout, " ")
  168. if len(fields) < 4 {
  169. return "", 0, fmt.Errorf("invalid public key line: %s", stdout)
  170. }
  171. keyType := strings.Trim(fields[len(fields)-1], "()\r\n")
  172. return strings.ToLower(keyType), com.StrTo(fields[0]).MustInt(), nil
  173. }
  174. // SSHNativeParsePublicKey extracts the key type and length using the golang SSH library.
  175. func SSHNativeParsePublicKey(keyLine string) (string, int, error) {
  176. fields := strings.Fields(keyLine)
  177. if len(fields) < 2 {
  178. return "", 0, fmt.Errorf("not enough fields in public key line: %s", keyLine)
  179. }
  180. raw, err := base64.StdEncoding.DecodeString(fields[1])
  181. if err != nil {
  182. return "", 0, err
  183. }
  184. pkey, err := ssh.ParsePublicKey(raw)
  185. if err != nil {
  186. if strings.Contains(err.Error(), "ssh: unknown key algorithm") {
  187. return "", 0, ErrKeyUnableVerify{err.Error()}
  188. }
  189. return "", 0, fmt.Errorf("ParsePublicKey: %v", err)
  190. }
  191. // The ssh library can parse the key, so next we find out what key exactly we have.
  192. switch pkey.Type() {
  193. case ssh.KeyAlgoDSA:
  194. rawPub := struct {
  195. Name string
  196. P, Q, G, Y *big.Int
  197. }{}
  198. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  199. return "", 0, err
  200. }
  201. // as per https://bugzilla.mindrot.org/show_bug.cgi?id=1647 we should never
  202. // see dsa keys != 1024 bit, but as it seems to work, we will not check here
  203. return "dsa", rawPub.P.BitLen(), nil // use P as per crypto/dsa/dsa.go (is L)
  204. case ssh.KeyAlgoRSA:
  205. rawPub := struct {
  206. Name string
  207. E *big.Int
  208. N *big.Int
  209. }{}
  210. if err := ssh.Unmarshal(pkey.Marshal(), &rawPub); err != nil {
  211. return "", 0, err
  212. }
  213. return "rsa", rawPub.N.BitLen(), nil // use N as per crypto/rsa/rsa.go (is bits)
  214. case ssh.KeyAlgoECDSA256:
  215. return "ecdsa", 256, nil
  216. case ssh.KeyAlgoECDSA384:
  217. return "ecdsa", 384, nil
  218. case ssh.KeyAlgoECDSA521:
  219. return "ecdsa", 521, nil
  220. case ssh.KeyAlgoED25519:
  221. return "ed25519", 256, nil
  222. }
  223. return "", 0, fmt.Errorf("unsupported key length detection for type: %s", pkey.Type())
  224. }
  225. // CheckPublicKeyString checks if the given public key string is recognized by SSH.
  226. // It returns the actual public key line on success.
  227. func CheckPublicKeyString(content string) (_ string, err error) {
  228. if setting.SSH.Disabled {
  229. return "", ErrSSHDisabled{}
  230. }
  231. content, err = parseKeyString(content)
  232. if err != nil {
  233. return "", err
  234. }
  235. content = strings.TrimRight(content, "\n\r")
  236. if strings.ContainsAny(content, "\n\r") {
  237. return "", errors.New("only a single line with a single key please")
  238. }
  239. // remove any unnecessary whitespace now
  240. content = strings.TrimSpace(content)
  241. if !setting.SSH.MinimumKeySizeCheck {
  242. return content, nil
  243. }
  244. var (
  245. fnName string
  246. keyType string
  247. length int
  248. )
  249. if setting.SSH.StartBuiltinServer {
  250. fnName = "SSHNativeParsePublicKey"
  251. keyType, length, err = SSHNativeParsePublicKey(content)
  252. } else {
  253. fnName = "SSHKeyGenParsePublicKey"
  254. keyType, length, err = SSHKeyGenParsePublicKey(content)
  255. }
  256. if err != nil {
  257. return "", fmt.Errorf("%s: %v", fnName, err)
  258. }
  259. log.Trace("Key info [native: %v]: %s-%d", setting.SSH.StartBuiltinServer, keyType, length)
  260. if minLen, found := setting.SSH.MinimumKeySizes[keyType]; found && length >= minLen {
  261. return content, nil
  262. } else if found && length < minLen {
  263. return "", fmt.Errorf("key length is not enough: got %d, needs %d", length, minLen)
  264. }
  265. return "", fmt.Errorf("key type is not allowed: %s", keyType)
  266. }
  267. // appendAuthorizedKeysToFile appends new SSH keys' content to authorized_keys file.
  268. func appendAuthorizedKeysToFile(keys ...*PublicKey) error {
  269. // Don't need to rewrite this file if builtin SSH server is enabled.
  270. if setting.SSH.StartBuiltinServer {
  271. return nil
  272. }
  273. sshOpLocker.Lock()
  274. defer sshOpLocker.Unlock()
  275. if setting.SSH.RootPath != "" {
  276. // First of ensure that the RootPath is present, and if not make it with 0700 permissions
  277. // This of course doesn't guarantee that this is the right directory for authorized_keys
  278. // but at least if it's supposed to be this directory and it doesn't exist and we're the
  279. // right user it will at least be created properly.
  280. err := os.MkdirAll(setting.SSH.RootPath, 0700)
  281. if err != nil {
  282. log.Error("Unable to MkdirAll(%s): %v", setting.SSH.RootPath, err)
  283. return err
  284. }
  285. }
  286. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  287. f, err := os.OpenFile(fPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  288. if err != nil {
  289. return err
  290. }
  291. defer f.Close()
  292. // Note: chmod command does not support in Windows.
  293. if !setting.IsWindows {
  294. fi, err := f.Stat()
  295. if err != nil {
  296. return err
  297. }
  298. // .ssh directory should have mode 700, and authorized_keys file should have mode 600.
  299. if fi.Mode().Perm() > 0600 {
  300. log.Error("authorized_keys file has unusual permission flags: %s - setting to -rw-------", fi.Mode().Perm().String())
  301. if err = f.Chmod(0600); err != nil {
  302. return err
  303. }
  304. }
  305. }
  306. for _, key := range keys {
  307. if _, err = f.WriteString(key.AuthorizedString()); err != nil {
  308. return err
  309. }
  310. }
  311. return nil
  312. }
  313. // checkKeyFingerprint only checks if key fingerprint has been used as public key,
  314. // it is OK to use same key as deploy key for multiple repositories/users.
  315. func checkKeyFingerprint(e Engine, fingerprint string) error {
  316. has, err := e.Get(&PublicKey{
  317. Fingerprint: fingerprint,
  318. })
  319. if err != nil {
  320. return err
  321. } else if has {
  322. return ErrKeyAlreadyExist{0, fingerprint, ""}
  323. }
  324. return nil
  325. }
  326. func calcFingerprintSSHKeygen(publicKeyContent string) (string, error) {
  327. // Calculate fingerprint.
  328. tmpPath, err := writeTmpKeyFile(publicKeyContent)
  329. if err != nil {
  330. return "", err
  331. }
  332. defer os.Remove(tmpPath)
  333. stdout, stderr, err := process.GetManager().Exec("AddPublicKey", "ssh-keygen", "-lf", tmpPath)
  334. if err != nil {
  335. return "", fmt.Errorf("'ssh-keygen -lf %s' failed with error '%s': %s", tmpPath, err, stderr)
  336. } else if len(stdout) < 2 {
  337. return "", errors.New("not enough output for calculating fingerprint: " + stdout)
  338. }
  339. return strings.Split(stdout, " ")[1], nil
  340. }
  341. func calcFingerprintNative(publicKeyContent string) (string, error) {
  342. // Calculate fingerprint.
  343. pk, _, _, _, err := ssh.ParseAuthorizedKey([]byte(publicKeyContent))
  344. if err != nil {
  345. return "", err
  346. }
  347. return ssh.FingerprintSHA256(pk), nil
  348. }
  349. func calcFingerprint(publicKeyContent string) (string, error) {
  350. //Call the method based on configuration
  351. var (
  352. fnName, fp string
  353. err error
  354. )
  355. if setting.SSH.StartBuiltinServer {
  356. fnName = "calcFingerprintNative"
  357. fp, err = calcFingerprintNative(publicKeyContent)
  358. } else {
  359. fnName = "calcFingerprintSSHKeygen"
  360. fp, err = calcFingerprintSSHKeygen(publicKeyContent)
  361. }
  362. if err != nil {
  363. return "", fmt.Errorf("%s: %v", fnName, err)
  364. }
  365. return fp, nil
  366. }
  367. func addKey(e Engine, key *PublicKey) (err error) {
  368. if len(key.Fingerprint) == 0 {
  369. key.Fingerprint, err = calcFingerprint(key.Content)
  370. if err != nil {
  371. return err
  372. }
  373. }
  374. // Save SSH key.
  375. if _, err = e.Insert(key); err != nil {
  376. return err
  377. }
  378. return appendAuthorizedKeysToFile(key)
  379. }
  380. // AddPublicKey adds new public key to database and authorized_keys file.
  381. func AddPublicKey(ownerID int64, name, content string, loginSourceID int64) (*PublicKey, error) {
  382. log.Trace(content)
  383. fingerprint, err := calcFingerprint(content)
  384. if err != nil {
  385. return nil, err
  386. }
  387. sess := x.NewSession()
  388. defer sess.Close()
  389. if err = sess.Begin(); err != nil {
  390. return nil, err
  391. }
  392. if err := checkKeyFingerprint(sess, fingerprint); err != nil {
  393. return nil, err
  394. }
  395. // Key name of same user cannot be duplicated.
  396. has, err := sess.
  397. Where("owner_id = ? AND name = ?", ownerID, name).
  398. Get(new(PublicKey))
  399. if err != nil {
  400. return nil, err
  401. } else if has {
  402. return nil, ErrKeyNameAlreadyUsed{ownerID, name}
  403. }
  404. key := &PublicKey{
  405. OwnerID: ownerID,
  406. Name: name,
  407. Fingerprint: fingerprint,
  408. Content: content,
  409. Mode: AccessModeWrite,
  410. Type: KeyTypeUser,
  411. LoginSourceID: loginSourceID,
  412. }
  413. if err = addKey(sess, key); err != nil {
  414. return nil, fmt.Errorf("addKey: %v", err)
  415. }
  416. return key, sess.Commit()
  417. }
  418. // GetPublicKeyByID returns public key by given ID.
  419. func GetPublicKeyByID(keyID int64) (*PublicKey, error) {
  420. key := new(PublicKey)
  421. has, err := x.
  422. Id(keyID).
  423. Get(key)
  424. if err != nil {
  425. return nil, err
  426. } else if !has {
  427. return nil, ErrKeyNotExist{keyID}
  428. }
  429. return key, nil
  430. }
  431. func searchPublicKeyByContentWithEngine(e Engine, content string) (*PublicKey, error) {
  432. key := new(PublicKey)
  433. has, err := e.
  434. Where("content like ?", content+"%").
  435. Get(key)
  436. if err != nil {
  437. return nil, err
  438. } else if !has {
  439. return nil, ErrKeyNotExist{}
  440. }
  441. return key, nil
  442. }
  443. // SearchPublicKeyByContent searches content as prefix (leak e-mail part)
  444. // and returns public key found.
  445. func SearchPublicKeyByContent(content string) (*PublicKey, error) {
  446. return searchPublicKeyByContentWithEngine(x, content)
  447. }
  448. // SearchPublicKey returns a list of public keys matching the provided arguments.
  449. func SearchPublicKey(uid int64, fingerprint string) ([]*PublicKey, error) {
  450. keys := make([]*PublicKey, 0, 5)
  451. cond := builder.NewCond()
  452. if uid != 0 {
  453. cond = cond.And(builder.Eq{"owner_id": uid})
  454. }
  455. if fingerprint != "" {
  456. cond = cond.And(builder.Eq{"fingerprint": fingerprint})
  457. }
  458. return keys, x.Where(cond).Find(&keys)
  459. }
  460. // ListPublicKeys returns a list of public keys belongs to given user.
  461. func ListPublicKeys(uid int64) ([]*PublicKey, error) {
  462. keys := make([]*PublicKey, 0, 5)
  463. return keys, x.
  464. Where("owner_id = ?", uid).
  465. Find(&keys)
  466. }
  467. // ListPublicLdapSSHKeys returns a list of synchronized public ldap ssh keys belongs to given user and login source.
  468. func ListPublicLdapSSHKeys(uid int64, loginSourceID int64) ([]*PublicKey, error) {
  469. keys := make([]*PublicKey, 0, 5)
  470. return keys, x.
  471. Where("owner_id = ? AND login_source_id = ?", uid, loginSourceID).
  472. Find(&keys)
  473. }
  474. // UpdatePublicKeyUpdated updates public key use time.
  475. func UpdatePublicKeyUpdated(id int64) error {
  476. // Check if key exists before update as affected rows count is unreliable
  477. // and will return 0 affected rows if two updates are made at the same time
  478. if cnt, err := x.ID(id).Count(&PublicKey{}); err != nil {
  479. return err
  480. } else if cnt != 1 {
  481. return ErrKeyNotExist{id}
  482. }
  483. _, err := x.ID(id).Cols("updated_unix").Update(&PublicKey{
  484. UpdatedUnix: util.TimeStampNow(),
  485. })
  486. if err != nil {
  487. return err
  488. }
  489. return nil
  490. }
  491. // deletePublicKeys does the actual key deletion but does not update authorized_keys file.
  492. func deletePublicKeys(e Engine, keyIDs ...int64) error {
  493. if len(keyIDs) == 0 {
  494. return nil
  495. }
  496. _, err := e.In("id", keyIDs).Delete(new(PublicKey))
  497. return err
  498. }
  499. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  500. func DeletePublicKey(doer *User, id int64) (err error) {
  501. key, err := GetPublicKeyByID(id)
  502. if err != nil {
  503. return err
  504. }
  505. // Check if user has access to delete this key.
  506. if !doer.IsAdmin && doer.ID != key.OwnerID {
  507. return ErrKeyAccessDenied{doer.ID, key.ID, "public"}
  508. }
  509. sess := x.NewSession()
  510. defer sess.Close()
  511. if err = sess.Begin(); err != nil {
  512. return err
  513. }
  514. if err = deletePublicKeys(sess, id); err != nil {
  515. return err
  516. }
  517. if err = sess.Commit(); err != nil {
  518. return err
  519. }
  520. sess.Close()
  521. return RewriteAllPublicKeys()
  522. }
  523. // RewriteAllPublicKeys removes any authorized key and rewrite all keys from database again.
  524. // Note: x.Iterate does not get latest data after insert/delete, so we have to call this function
  525. // outside any session scope independently.
  526. func RewriteAllPublicKeys() error {
  527. return rewriteAllPublicKeys(x)
  528. }
  529. func rewriteAllPublicKeys(e Engine) error {
  530. //Don't rewrite key if internal server
  531. if setting.SSH.StartBuiltinServer || !setting.SSH.CreateAuthorizedKeysFile {
  532. return nil
  533. }
  534. sshOpLocker.Lock()
  535. defer sshOpLocker.Unlock()
  536. if setting.SSH.RootPath != "" {
  537. // First of ensure that the RootPath is present, and if not make it with 0700 permissions
  538. // This of course doesn't guarantee that this is the right directory for authorized_keys
  539. // but at least if it's supposed to be this directory and it doesn't exist and we're the
  540. // right user it will at least be created properly.
  541. err := os.MkdirAll(setting.SSH.RootPath, 0700)
  542. if err != nil {
  543. log.Error("Unable to MkdirAll(%s): %v", setting.SSH.RootPath, err)
  544. return err
  545. }
  546. }
  547. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  548. tmpPath := fPath + ".tmp"
  549. t, err := os.OpenFile(tmpPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  550. if err != nil {
  551. return err
  552. }
  553. defer func() {
  554. t.Close()
  555. os.Remove(tmpPath)
  556. }()
  557. if setting.SSH.AuthorizedKeysBackup && com.IsExist(fPath) {
  558. bakPath := fmt.Sprintf("%s_%d.gitea_bak", fPath, time.Now().Unix())
  559. if err = com.Copy(fPath, bakPath); err != nil {
  560. return err
  561. }
  562. }
  563. err = e.Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
  564. _, err = t.WriteString((bean.(*PublicKey)).AuthorizedString())
  565. return err
  566. })
  567. if err != nil {
  568. return err
  569. }
  570. if com.IsExist(fPath) {
  571. f, err := os.Open(fPath)
  572. if err != nil {
  573. return err
  574. }
  575. scanner := bufio.NewScanner(f)
  576. for scanner.Scan() {
  577. line := scanner.Text()
  578. if strings.HasPrefix(line, tplCommentPrefix) {
  579. scanner.Scan()
  580. continue
  581. }
  582. _, err = t.WriteString(line + "\n")
  583. if err != nil {
  584. f.Close()
  585. return err
  586. }
  587. }
  588. f.Close()
  589. }
  590. t.Close()
  591. return os.Rename(tmpPath, fPath)
  592. }
  593. // ________ .__ ____ __.
  594. // \______ \ ____ ______ | | ____ ___.__.| |/ _|____ ___.__.
  595. // | | \_/ __ \\____ \| | / _ < | || <_/ __ < | |
  596. // | ` \ ___/| |_> > |_( <_> )___ || | \ ___/\___ |
  597. // /_______ /\___ > __/|____/\____// ____||____|__ \___ > ____|
  598. // \/ \/|__| \/ \/ \/\/
  599. // DeployKey represents deploy key information and its relation with repository.
  600. type DeployKey struct {
  601. ID int64 `xorm:"pk autoincr"`
  602. KeyID int64 `xorm:"UNIQUE(s) INDEX"`
  603. RepoID int64 `xorm:"UNIQUE(s) INDEX"`
  604. Name string
  605. Fingerprint string
  606. Content string `xorm:"-"`
  607. Mode AccessMode `xorm:"NOT NULL DEFAULT 1"`
  608. CreatedUnix util.TimeStamp `xorm:"created"`
  609. UpdatedUnix util.TimeStamp `xorm:"updated"`
  610. HasRecentActivity bool `xorm:"-"`
  611. HasUsed bool `xorm:"-"`
  612. }
  613. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  614. func (key *DeployKey) AfterLoad() {
  615. key.HasUsed = key.UpdatedUnix > key.CreatedUnix
  616. key.HasRecentActivity = key.UpdatedUnix.AddDuration(7*24*time.Hour) > util.TimeStampNow()
  617. }
  618. // GetContent gets associated public key content.
  619. func (key *DeployKey) GetContent() error {
  620. pkey, err := GetPublicKeyByID(key.KeyID)
  621. if err != nil {
  622. return err
  623. }
  624. key.Content = pkey.Content
  625. return nil
  626. }
  627. // IsReadOnly checks if the key can only be used for read operations
  628. func (key *DeployKey) IsReadOnly() bool {
  629. return key.Mode == AccessModeRead
  630. }
  631. func checkDeployKey(e Engine, keyID, repoID int64, name string) error {
  632. // Note: We want error detail, not just true or false here.
  633. has, err := e.
  634. Where("key_id = ? AND repo_id = ?", keyID, repoID).
  635. Get(new(DeployKey))
  636. if err != nil {
  637. return err
  638. } else if has {
  639. return ErrDeployKeyAlreadyExist{keyID, repoID}
  640. }
  641. has, err = e.
  642. Where("repo_id = ? AND name = ?", repoID, name).
  643. Get(new(DeployKey))
  644. if err != nil {
  645. return err
  646. } else if has {
  647. return ErrDeployKeyNameAlreadyUsed{repoID, name}
  648. }
  649. return nil
  650. }
  651. // addDeployKey adds new key-repo relation.
  652. func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string, mode AccessMode) (*DeployKey, error) {
  653. if err := checkDeployKey(e, keyID, repoID, name); err != nil {
  654. return nil, err
  655. }
  656. key := &DeployKey{
  657. KeyID: keyID,
  658. RepoID: repoID,
  659. Name: name,
  660. Fingerprint: fingerprint,
  661. Mode: mode,
  662. }
  663. _, err := e.Insert(key)
  664. return key, err
  665. }
  666. // HasDeployKey returns true if public key is a deploy key of given repository.
  667. func HasDeployKey(keyID, repoID int64) bool {
  668. has, _ := x.
  669. Where("key_id = ? AND repo_id = ?", keyID, repoID).
  670. Get(new(DeployKey))
  671. return has
  672. }
  673. // AddDeployKey add new deploy key to database and authorized_keys file.
  674. func AddDeployKey(repoID int64, name, content string, readOnly bool) (*DeployKey, error) {
  675. fingerprint, err := calcFingerprint(content)
  676. if err != nil {
  677. return nil, err
  678. }
  679. accessMode := AccessModeRead
  680. if !readOnly {
  681. accessMode = AccessModeWrite
  682. }
  683. sess := x.NewSession()
  684. defer sess.Close()
  685. if err = sess.Begin(); err != nil {
  686. return nil, err
  687. }
  688. pkey := &PublicKey{
  689. Fingerprint: fingerprint,
  690. }
  691. has, err := sess.Get(pkey)
  692. if err != nil {
  693. return nil, err
  694. }
  695. if has {
  696. if pkey.Type != KeyTypeDeploy {
  697. return nil, ErrKeyAlreadyExist{0, fingerprint, ""}
  698. }
  699. } else {
  700. // First time use this deploy key.
  701. pkey.Mode = accessMode
  702. pkey.Type = KeyTypeDeploy
  703. pkey.Content = content
  704. pkey.Name = name
  705. if err = addKey(sess, pkey); err != nil {
  706. return nil, fmt.Errorf("addKey: %v", err)
  707. }
  708. }
  709. key, err := addDeployKey(sess, pkey.ID, repoID, name, pkey.Fingerprint, accessMode)
  710. if err != nil {
  711. return nil, err
  712. }
  713. return key, sess.Commit()
  714. }
  715. // GetDeployKeyByID returns deploy key by given ID.
  716. func GetDeployKeyByID(id int64) (*DeployKey, error) {
  717. return getDeployKeyByID(x, id)
  718. }
  719. func getDeployKeyByID(e Engine, id int64) (*DeployKey, error) {
  720. key := new(DeployKey)
  721. has, err := e.ID(id).Get(key)
  722. if err != nil {
  723. return nil, err
  724. } else if !has {
  725. return nil, ErrDeployKeyNotExist{id, 0, 0}
  726. }
  727. return key, nil
  728. }
  729. // GetDeployKeyByRepo returns deploy key by given public key ID and repository ID.
  730. func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) {
  731. return getDeployKeyByRepo(x, keyID, repoID)
  732. }
  733. func getDeployKeyByRepo(e Engine, keyID, repoID int64) (*DeployKey, error) {
  734. key := &DeployKey{
  735. KeyID: keyID,
  736. RepoID: repoID,
  737. }
  738. has, err := e.Get(key)
  739. if err != nil {
  740. return nil, err
  741. } else if !has {
  742. return nil, ErrDeployKeyNotExist{0, keyID, repoID}
  743. }
  744. return key, nil
  745. }
  746. // UpdateDeployKeyCols updates deploy key information in the specified columns.
  747. func UpdateDeployKeyCols(key *DeployKey, cols ...string) error {
  748. _, err := x.ID(key.ID).Cols(cols...).Update(key)
  749. return err
  750. }
  751. // UpdateDeployKey updates deploy key information.
  752. func UpdateDeployKey(key *DeployKey) error {
  753. _, err := x.ID(key.ID).AllCols().Update(key)
  754. return err
  755. }
  756. // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed.
  757. func DeleteDeployKey(doer *User, id int64) error {
  758. sess := x.NewSession()
  759. defer sess.Close()
  760. if err := sess.Begin(); err != nil {
  761. return err
  762. }
  763. if err := deleteDeployKey(sess, doer, id); err != nil {
  764. return err
  765. }
  766. return sess.Commit()
  767. }
  768. func deleteDeployKey(sess Engine, doer *User, id int64) error {
  769. key, err := getDeployKeyByID(sess, id)
  770. if err != nil {
  771. if IsErrDeployKeyNotExist(err) {
  772. return nil
  773. }
  774. return fmt.Errorf("GetDeployKeyByID: %v", err)
  775. }
  776. // Check if user has access to delete this key.
  777. if !doer.IsAdmin {
  778. repo, err := getRepositoryByID(sess, key.RepoID)
  779. if err != nil {
  780. return fmt.Errorf("GetRepositoryByID: %v", err)
  781. }
  782. has, err := isUserRepoAdmin(sess, repo, doer)
  783. if err != nil {
  784. return fmt.Errorf("GetUserRepoPermission: %v", err)
  785. } else if !has {
  786. return ErrKeyAccessDenied{doer.ID, key.ID, "deploy"}
  787. }
  788. }
  789. if _, err = sess.ID(key.ID).Delete(new(DeployKey)); err != nil {
  790. return fmt.Errorf("delete deploy key [%d]: %v", key.ID, err)
  791. }
  792. // Check if this is the last reference to same key content.
  793. has, err := sess.
  794. Where("key_id = ?", key.KeyID).
  795. Get(new(DeployKey))
  796. if err != nil {
  797. return err
  798. } else if !has {
  799. if err = deletePublicKeys(sess, key.KeyID); err != nil {
  800. return err
  801. }
  802. // after deleted the public keys, should rewrite the public keys file
  803. if err = rewriteAllPublicKeys(sess); err != nil {
  804. return err
  805. }
  806. }
  807. return nil
  808. }
  809. // ListDeployKeys returns all deploy keys by given repository ID.
  810. func ListDeployKeys(repoID int64) ([]*DeployKey, error) {
  811. return listDeployKeys(x, repoID)
  812. }
  813. func listDeployKeys(e Engine, repoID int64) ([]*DeployKey, error) {
  814. keys := make([]*DeployKey, 0, 5)
  815. return keys, e.
  816. Where("repo_id = ?", repoID).
  817. Find(&keys)
  818. }
  819. // SearchDeployKeys returns a list of deploy keys matching the provided arguments.
  820. func SearchDeployKeys(repoID int64, keyID int64, fingerprint string) ([]*DeployKey, error) {
  821. keys := make([]*DeployKey, 0, 5)
  822. cond := builder.NewCond()
  823. if repoID != 0 {
  824. cond = cond.And(builder.Eq{"repo_id": repoID})
  825. }
  826. if keyID != 0 {
  827. cond = cond.And(builder.Eq{"key_id": keyID})
  828. }
  829. if fingerprint != "" {
  830. cond = cond.And(builder.Eq{"fingerprint": fingerprint})
  831. }
  832. return keys, x.Where(cond).Find(&keys)
  833. }