ssh_key.go 21 KB

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