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