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 23 kB

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