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