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
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
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  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 `xorm:"created"`
  49. Updated time.Time `xorm:"-"`
  50. UpdatedUnix int64 `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.Created = time.Unix(key.CreatedUnix, 0).Local()
  57. key.Updated = time.Unix(key.UpdatedUnix, 0).Local()
  58. key.HasUsed = key.Updated.After(key.Created)
  59. key.HasRecentActivity = key.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  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, key.ID, setting.CustomConf, 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 = 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 "", errors.New("SSH is disabled")
  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. sshOpLocker.Lock()
  270. defer sshOpLocker.Unlock()
  271. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  272. f, err := os.OpenFile(fPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  273. if err != nil {
  274. return err
  275. }
  276. defer f.Close()
  277. // Note: chmod command does not support in Windows.
  278. if !setting.IsWindows {
  279. fi, err := f.Stat()
  280. if err != nil {
  281. return err
  282. }
  283. // .ssh directory should have mode 700, and authorized_keys file should have mode 600.
  284. if fi.Mode().Perm() > 0600 {
  285. log.Error(4, "authorized_keys file has unusual permission flags: %s - setting to -rw-------", fi.Mode().Perm().String())
  286. if err = f.Chmod(0600); err != nil {
  287. return err
  288. }
  289. }
  290. }
  291. for _, key := range keys {
  292. if _, err = f.WriteString(key.AuthorizedString()); err != nil {
  293. return err
  294. }
  295. }
  296. return nil
  297. }
  298. // checkKeyFingerprint only checks if key fingerprint has been used as public key,
  299. // it is OK to use same key as deploy key for multiple repositories/users.
  300. func checkKeyFingerprint(e Engine, fingerprint string) error {
  301. has, err := e.Get(&PublicKey{
  302. Fingerprint: fingerprint,
  303. Type: KeyTypeUser,
  304. })
  305. if err != nil {
  306. return err
  307. } else if has {
  308. return ErrKeyAlreadyExist{0, fingerprint, ""}
  309. }
  310. return nil
  311. }
  312. func calcFingerprint(publicKeyContent string) (string, error) {
  313. // Calculate fingerprint.
  314. tmpPath, err := writeTmpKeyFile(publicKeyContent)
  315. if err != nil {
  316. return "", err
  317. }
  318. defer os.Remove(tmpPath)
  319. stdout, stderr, err := process.GetManager().Exec("AddPublicKey", "ssh-keygen", "-lf", tmpPath)
  320. if err != nil {
  321. return "", fmt.Errorf("'ssh-keygen -lf %s' failed with error '%s': %s", tmpPath, err, stderr)
  322. } else if len(stdout) < 2 {
  323. return "", errors.New("not enough output for calculating fingerprint: " + stdout)
  324. }
  325. return strings.Split(stdout, " ")[1], nil
  326. }
  327. func addKey(e Engine, key *PublicKey) (err error) {
  328. if len(key.Fingerprint) <= 0 {
  329. key.Fingerprint, err = calcFingerprint(key.Content)
  330. if err != nil {
  331. return err
  332. }
  333. }
  334. // Save SSH key.
  335. if _, err = e.Insert(key); err != nil {
  336. return err
  337. }
  338. // Don't need to rewrite this file if builtin SSH server is enabled.
  339. if setting.SSH.StartBuiltinServer {
  340. return nil
  341. }
  342. return appendAuthorizedKeysToFile(key)
  343. }
  344. // AddPublicKey adds new public key to database and authorized_keys file.
  345. func AddPublicKey(ownerID int64, name, content string) (*PublicKey, error) {
  346. log.Trace(content)
  347. fingerprint, err := calcFingerprint(content)
  348. if err != nil {
  349. return nil, err
  350. }
  351. if err := checkKeyFingerprint(x, fingerprint); err != nil {
  352. return nil, err
  353. }
  354. // Key name of same user cannot be duplicated.
  355. has, err := x.
  356. Where("owner_id = ? AND name = ?", ownerID, name).
  357. Get(new(PublicKey))
  358. if err != nil {
  359. return nil, err
  360. } else if has {
  361. return nil, ErrKeyNameAlreadyUsed{ownerID, name}
  362. }
  363. sess := x.NewSession()
  364. defer sess.Close()
  365. if err = sess.Begin(); err != nil {
  366. return nil, err
  367. }
  368. key := &PublicKey{
  369. OwnerID: ownerID,
  370. Name: name,
  371. Fingerprint: fingerprint,
  372. Content: content,
  373. Mode: AccessModeWrite,
  374. Type: KeyTypeUser,
  375. }
  376. if err = addKey(sess, key); err != nil {
  377. return nil, fmt.Errorf("addKey: %v", err)
  378. }
  379. return key, sess.Commit()
  380. }
  381. // GetPublicKeyByID returns public key by given ID.
  382. func GetPublicKeyByID(keyID int64) (*PublicKey, error) {
  383. key := new(PublicKey)
  384. has, err := x.
  385. Id(keyID).
  386. Get(key)
  387. if err != nil {
  388. return nil, err
  389. } else if !has {
  390. return nil, ErrKeyNotExist{keyID}
  391. }
  392. return key, nil
  393. }
  394. // SearchPublicKeyByContent searches content as prefix (leak e-mail part)
  395. // and returns public key found.
  396. func SearchPublicKeyByContent(content string) (*PublicKey, error) {
  397. key := new(PublicKey)
  398. has, err := x.
  399. Where("content like ?", content+"%").
  400. Get(key)
  401. if err != nil {
  402. return nil, err
  403. } else if !has {
  404. return nil, ErrKeyNotExist{}
  405. }
  406. return key, nil
  407. }
  408. // ListPublicKeys returns a list of public keys belongs to given user.
  409. func ListPublicKeys(uid int64) ([]*PublicKey, error) {
  410. keys := make([]*PublicKey, 0, 5)
  411. return keys, x.
  412. Where("owner_id = ?", uid).
  413. Find(&keys)
  414. }
  415. // UpdatePublicKeyUpdated updates public key use time.
  416. func UpdatePublicKeyUpdated(id int64) error {
  417. // Check if key exists before update as affected rows count is unreliable
  418. // and will return 0 affected rows if two updates are made at the same time
  419. if cnt, err := x.ID(id).Count(&PublicKey{}); err != nil {
  420. return err
  421. } else if cnt != 1 {
  422. return ErrKeyNotExist{id}
  423. }
  424. _, err := x.ID(id).Cols("updated_unix").Update(&PublicKey{
  425. UpdatedUnix: time.Now().Unix(),
  426. })
  427. if err != nil {
  428. return err
  429. }
  430. return nil
  431. }
  432. // deletePublicKeys does the actual key deletion but does not update authorized_keys file.
  433. func deletePublicKeys(e *xorm.Session, keyIDs ...int64) error {
  434. if len(keyIDs) == 0 {
  435. return nil
  436. }
  437. _, err := e.In("id", keyIDs).Delete(new(PublicKey))
  438. return err
  439. }
  440. // DeletePublicKey deletes SSH key information both in database and authorized_keys file.
  441. func DeletePublicKey(doer *User, id int64) (err error) {
  442. key, err := GetPublicKeyByID(id)
  443. if err != nil {
  444. if IsErrKeyNotExist(err) {
  445. return nil
  446. }
  447. return fmt.Errorf("GetPublicKeyByID: %v", err)
  448. }
  449. // Check if user has access to delete this key.
  450. if !doer.IsAdmin && doer.ID != key.OwnerID {
  451. return ErrKeyAccessDenied{doer.ID, key.ID, "public"}
  452. }
  453. sess := x.NewSession()
  454. defer sess.Close()
  455. if err = sess.Begin(); err != nil {
  456. return err
  457. }
  458. if err = deletePublicKeys(sess, id); err != nil {
  459. return err
  460. }
  461. if err = sess.Commit(); err != nil {
  462. return err
  463. }
  464. return RewriteAllPublicKeys()
  465. }
  466. // RewriteAllPublicKeys removes any authorized key and rewrite all keys from database again.
  467. // Note: x.Iterate does not get latest data after insert/delete, so we have to call this function
  468. // outside any session scope independently.
  469. func RewriteAllPublicKeys() error {
  470. sshOpLocker.Lock()
  471. defer sshOpLocker.Unlock()
  472. fPath := filepath.Join(setting.SSH.RootPath, "authorized_keys")
  473. tmpPath := fPath + ".tmp"
  474. t, err := os.OpenFile(tmpPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
  475. if err != nil {
  476. return err
  477. }
  478. defer func() {
  479. t.Close()
  480. os.Remove(tmpPath)
  481. }()
  482. if setting.SSH.AuthorizedKeysBackup && com.IsExist(fPath) {
  483. bakPath := fmt.Sprintf("%s_%d.gitea_bak", fPath, time.Now().Unix())
  484. if err = com.Copy(fPath, bakPath); err != nil {
  485. return err
  486. }
  487. }
  488. err = x.Iterate(new(PublicKey), func(idx int, bean interface{}) (err error) {
  489. _, err = t.WriteString((bean.(*PublicKey)).AuthorizedString())
  490. return err
  491. })
  492. if err != nil {
  493. return err
  494. }
  495. if com.IsExist(fPath) {
  496. f, err := os.Open(fPath)
  497. if err != nil {
  498. return err
  499. }
  500. scanner := bufio.NewScanner(f)
  501. for scanner.Scan() {
  502. line := scanner.Text()
  503. if strings.HasPrefix(line, tplCommentPrefix) {
  504. scanner.Scan()
  505. continue
  506. }
  507. _, err = t.WriteString(line + "\n")
  508. if err != nil {
  509. return err
  510. }
  511. }
  512. defer f.Close()
  513. }
  514. return os.Rename(tmpPath, fPath)
  515. }
  516. // ________ .__ ____ __.
  517. // \______ \ ____ ______ | | ____ ___.__.| |/ _|____ ___.__.
  518. // | | \_/ __ \\____ \| | / _ < | || <_/ __ < | |
  519. // | ` \ ___/| |_> > |_( <_> )___ || | \ ___/\___ |
  520. // /_______ /\___ > __/|____/\____// ____||____|__ \___ > ____|
  521. // \/ \/|__| \/ \/ \/\/
  522. // DeployKey represents deploy key information and its relation with repository.
  523. type DeployKey struct {
  524. ID int64 `xorm:"pk autoincr"`
  525. KeyID int64 `xorm:"UNIQUE(s) INDEX"`
  526. RepoID int64 `xorm:"UNIQUE(s) INDEX"`
  527. Name string
  528. Fingerprint string
  529. Content string `xorm:"-"`
  530. Created time.Time `xorm:"-"`
  531. CreatedUnix int64 `xorm:"created"`
  532. Updated time.Time `xorm:"-"`
  533. UpdatedUnix int64 `xorm:"updated"`
  534. HasRecentActivity bool `xorm:"-"`
  535. HasUsed bool `xorm:"-"`
  536. }
  537. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  538. func (key *DeployKey) AfterLoad() {
  539. key.Created = time.Unix(key.CreatedUnix, 0).Local()
  540. key.Updated = time.Unix(key.UpdatedUnix, 0).Local()
  541. key.HasUsed = key.Updated.After(key.Created)
  542. key.HasRecentActivity = key.Updated.Add(7 * 24 * time.Hour).After(time.Now())
  543. }
  544. // GetContent gets associated public key content.
  545. func (key *DeployKey) GetContent() error {
  546. pkey, err := GetPublicKeyByID(key.KeyID)
  547. if err != nil {
  548. return err
  549. }
  550. key.Content = pkey.Content
  551. return nil
  552. }
  553. func checkDeployKey(e Engine, keyID, repoID int64, name string) error {
  554. // Note: We want error detail, not just true or false here.
  555. has, err := e.
  556. Where("key_id = ? AND repo_id = ?", keyID, repoID).
  557. Get(new(DeployKey))
  558. if err != nil {
  559. return err
  560. } else if has {
  561. return ErrDeployKeyAlreadyExist{keyID, repoID}
  562. }
  563. has, err = e.
  564. Where("repo_id = ? AND name = ?", repoID, name).
  565. Get(new(DeployKey))
  566. if err != nil {
  567. return err
  568. } else if has {
  569. return ErrDeployKeyNameAlreadyUsed{repoID, name}
  570. }
  571. return nil
  572. }
  573. // addDeployKey adds new key-repo relation.
  574. func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string) (*DeployKey, error) {
  575. if err := checkDeployKey(e, keyID, repoID, name); err != nil {
  576. return nil, err
  577. }
  578. key := &DeployKey{
  579. KeyID: keyID,
  580. RepoID: repoID,
  581. Name: name,
  582. Fingerprint: fingerprint,
  583. }
  584. _, err := e.Insert(key)
  585. return key, err
  586. }
  587. // HasDeployKey returns true if public key is a deploy key of given repository.
  588. func HasDeployKey(keyID, repoID int64) bool {
  589. has, _ := x.
  590. Where("key_id = ? AND repo_id = ?", keyID, repoID).
  591. Get(new(DeployKey))
  592. return has
  593. }
  594. // AddDeployKey add new deploy key to database and authorized_keys file.
  595. func AddDeployKey(repoID int64, name, content string) (*DeployKey, error) {
  596. fingerprint, err := calcFingerprint(content)
  597. if err != nil {
  598. return nil, err
  599. }
  600. pkey := &PublicKey{
  601. Fingerprint: fingerprint,
  602. Mode: AccessModeRead,
  603. Type: KeyTypeDeploy,
  604. }
  605. has, err := x.Get(pkey)
  606. if err != nil {
  607. return nil, err
  608. }
  609. sess := x.NewSession()
  610. defer sess.Close()
  611. if err = sess.Begin(); err != nil {
  612. return nil, err
  613. }
  614. // First time use this deploy key.
  615. if !has {
  616. pkey.Content = content
  617. pkey.Name = name
  618. if err = addKey(sess, pkey); err != nil {
  619. return nil, fmt.Errorf("addKey: %v", err)
  620. }
  621. }
  622. key, err := addDeployKey(sess, pkey.ID, repoID, name, pkey.Fingerprint)
  623. if err != nil {
  624. return nil, fmt.Errorf("addDeployKey: %v", err)
  625. }
  626. return key, sess.Commit()
  627. }
  628. // GetDeployKeyByID returns deploy key by given ID.
  629. func GetDeployKeyByID(id int64) (*DeployKey, error) {
  630. key := new(DeployKey)
  631. has, err := x.ID(id).Get(key)
  632. if err != nil {
  633. return nil, err
  634. } else if !has {
  635. return nil, ErrDeployKeyNotExist{id, 0, 0}
  636. }
  637. return key, nil
  638. }
  639. // GetDeployKeyByRepo returns deploy key by given public key ID and repository ID.
  640. func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) {
  641. key := &DeployKey{
  642. KeyID: keyID,
  643. RepoID: repoID,
  644. }
  645. has, err := x.Get(key)
  646. if err != nil {
  647. return nil, err
  648. } else if !has {
  649. return nil, ErrDeployKeyNotExist{0, keyID, repoID}
  650. }
  651. return key, nil
  652. }
  653. // UpdateDeployKey updates deploy key information.
  654. func UpdateDeployKey(key *DeployKey) error {
  655. _, err := x.ID(key.ID).AllCols().Update(key)
  656. return err
  657. }
  658. // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed.
  659. func DeleteDeployKey(doer *User, id int64) error {
  660. key, err := GetDeployKeyByID(id)
  661. if err != nil {
  662. if IsErrDeployKeyNotExist(err) {
  663. return nil
  664. }
  665. return fmt.Errorf("GetDeployKeyByID: %v", err)
  666. }
  667. // Check if user has access to delete this key.
  668. if !doer.IsAdmin {
  669. repo, err := GetRepositoryByID(key.RepoID)
  670. if err != nil {
  671. return fmt.Errorf("GetRepositoryByID: %v", err)
  672. }
  673. yes, err := HasAccess(doer.ID, repo, AccessModeAdmin)
  674. if err != nil {
  675. return fmt.Errorf("HasAccess: %v", err)
  676. } else if !yes {
  677. return ErrKeyAccessDenied{doer.ID, key.ID, "deploy"}
  678. }
  679. }
  680. sess := x.NewSession()
  681. defer sess.Close()
  682. if err = sess.Begin(); err != nil {
  683. return err
  684. }
  685. if _, err = sess.ID(key.ID).Delete(new(DeployKey)); err != nil {
  686. return fmt.Errorf("delete deploy key [%d]: %v", key.ID, err)
  687. }
  688. // Check if this is the last reference to same key content.
  689. has, err := sess.
  690. Where("key_id = ?", key.KeyID).
  691. Get(new(DeployKey))
  692. if err != nil {
  693. return err
  694. } else if !has {
  695. if err = deletePublicKeys(sess, key.KeyID); err != nil {
  696. return err
  697. }
  698. }
  699. return sess.Commit()
  700. }
  701. // ListDeployKeys returns all deploy keys by given repository ID.
  702. func ListDeployKeys(repoID int64) ([]*DeployKey, error) {
  703. keys := make([]*DeployKey, 0, 5)
  704. return keys, x.
  705. Where("repo_id = ?", repoID).
  706. Find(&keys)
  707. }