ssh_key.go 21 KB

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