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

ssh_key.go 22 kB

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