You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

gpg_key.go 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. // Copyright 2017 The Gitea 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. "bytes"
  7. "container/list"
  8. "crypto"
  9. "encoding/base64"
  10. "fmt"
  11. "hash"
  12. "io"
  13. "strings"
  14. "time"
  15. "code.gitea.io/gitea/modules/git"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. "code.gitea.io/gitea/modules/timeutil"
  19. "github.com/keybase/go-crypto/openpgp"
  20. "github.com/keybase/go-crypto/openpgp/armor"
  21. "github.com/keybase/go-crypto/openpgp/packet"
  22. "xorm.io/xorm"
  23. )
  24. // GPGKey represents a GPG key.
  25. type GPGKey struct {
  26. ID int64 `xorm:"pk autoincr"`
  27. OwnerID int64 `xorm:"INDEX NOT NULL"`
  28. KeyID string `xorm:"INDEX CHAR(16) NOT NULL"`
  29. PrimaryKeyID string `xorm:"CHAR(16)"`
  30. Content string `xorm:"TEXT NOT NULL"`
  31. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  32. ExpiredUnix timeutil.TimeStamp
  33. AddedUnix timeutil.TimeStamp
  34. SubsKey []*GPGKey `xorm:"-"`
  35. Emails []*EmailAddress
  36. CanSign bool
  37. CanEncryptComms bool
  38. CanEncryptStorage bool
  39. CanCertify bool
  40. }
  41. //GPGKeyImport the original import of key
  42. type GPGKeyImport struct {
  43. KeyID string `xorm:"pk CHAR(16) NOT NULL"`
  44. Content string `xorm:"TEXT NOT NULL"`
  45. }
  46. // BeforeInsert will be invoked by XORM before inserting a record
  47. func (key *GPGKey) BeforeInsert() {
  48. key.AddedUnix = timeutil.TimeStampNow()
  49. }
  50. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  51. func (key *GPGKey) AfterLoad(session *xorm.Session) {
  52. err := session.Where("primary_key_id=?", key.KeyID).Find(&key.SubsKey)
  53. if err != nil {
  54. log.Error("Find Sub GPGkeys[%s]: %v", key.KeyID, err)
  55. }
  56. }
  57. // ListGPGKeys returns a list of public keys belongs to given user.
  58. func ListGPGKeys(uid int64) ([]*GPGKey, error) {
  59. keys := make([]*GPGKey, 0, 5)
  60. return keys, x.Where("owner_id=? AND primary_key_id=''", uid).Find(&keys)
  61. }
  62. // GetGPGKeyByID returns public key by given ID.
  63. func GetGPGKeyByID(keyID int64) (*GPGKey, error) {
  64. key := new(GPGKey)
  65. has, err := x.ID(keyID).Get(key)
  66. if err != nil {
  67. return nil, err
  68. } else if !has {
  69. return nil, ErrGPGKeyNotExist{keyID}
  70. }
  71. return key, nil
  72. }
  73. // GetGPGKeysByKeyID returns public key by given ID.
  74. func GetGPGKeysByKeyID(keyID string) ([]*GPGKey, error) {
  75. keys := make([]*GPGKey, 0, 1)
  76. return keys, x.Where("key_id=?", keyID).Find(&keys)
  77. }
  78. // GetGPGImportByKeyID returns the import public armored key by given KeyID.
  79. func GetGPGImportByKeyID(keyID string) (*GPGKeyImport, error) {
  80. key := new(GPGKeyImport)
  81. has, err := x.ID(keyID).Get(key)
  82. if err != nil {
  83. return nil, err
  84. } else if !has {
  85. return nil, ErrGPGKeyImportNotExist{keyID}
  86. }
  87. return key, nil
  88. }
  89. // checkArmoredGPGKeyString checks if the given key string is a valid GPG armored key.
  90. // The function returns the actual public key on success
  91. func checkArmoredGPGKeyString(content string) (*openpgp.Entity, error) {
  92. list, err := openpgp.ReadArmoredKeyRing(strings.NewReader(content))
  93. if err != nil {
  94. return nil, ErrGPGKeyParsing{err}
  95. }
  96. return list[0], nil
  97. }
  98. //addGPGKey add key, import and subkeys to database
  99. func addGPGKey(e Engine, key *GPGKey, content string) (err error) {
  100. //Add GPGKeyImport
  101. if _, err = e.Insert(GPGKeyImport{
  102. KeyID: key.KeyID,
  103. Content: content,
  104. }); err != nil {
  105. return err
  106. }
  107. // Save GPG primary key.
  108. if _, err = e.Insert(key); err != nil {
  109. return err
  110. }
  111. // Save GPG subs key.
  112. for _, subkey := range key.SubsKey {
  113. if err := addGPGSubKey(e, subkey); err != nil {
  114. return err
  115. }
  116. }
  117. return nil
  118. }
  119. //addGPGSubKey add subkeys to database
  120. func addGPGSubKey(e Engine, key *GPGKey) (err error) {
  121. // Save GPG primary key.
  122. if _, err = e.Insert(key); err != nil {
  123. return err
  124. }
  125. // Save GPG subs key.
  126. for _, subkey := range key.SubsKey {
  127. if err := addGPGSubKey(e, subkey); err != nil {
  128. return err
  129. }
  130. }
  131. return nil
  132. }
  133. // AddGPGKey adds new public key to database.
  134. func AddGPGKey(ownerID int64, content string) (*GPGKey, error) {
  135. ekey, err := checkArmoredGPGKeyString(content)
  136. if err != nil {
  137. return nil, err
  138. }
  139. // Key ID cannot be duplicated.
  140. has, err := x.Where("key_id=?", ekey.PrimaryKey.KeyIdString()).
  141. Get(new(GPGKey))
  142. if err != nil {
  143. return nil, err
  144. } else if has {
  145. return nil, ErrGPGKeyIDAlreadyUsed{ekey.PrimaryKey.KeyIdString()}
  146. }
  147. //Get DB session
  148. sess := x.NewSession()
  149. defer sess.Close()
  150. if err = sess.Begin(); err != nil {
  151. return nil, err
  152. }
  153. key, err := parseGPGKey(ownerID, ekey)
  154. if err != nil {
  155. return nil, err
  156. }
  157. if err = addGPGKey(sess, key, content); err != nil {
  158. return nil, err
  159. }
  160. return key, sess.Commit()
  161. }
  162. //base64EncPubKey encode public key content to base 64
  163. func base64EncPubKey(pubkey *packet.PublicKey) (string, error) {
  164. var w bytes.Buffer
  165. err := pubkey.Serialize(&w)
  166. if err != nil {
  167. return "", err
  168. }
  169. return base64.StdEncoding.EncodeToString(w.Bytes()), nil
  170. }
  171. //base64DecPubKey decode public key content from base 64
  172. func base64DecPubKey(content string) (*packet.PublicKey, error) {
  173. b, err := readerFromBase64(content)
  174. if err != nil {
  175. return nil, err
  176. }
  177. //Read key
  178. p, err := packet.Read(b)
  179. if err != nil {
  180. return nil, err
  181. }
  182. //Check type
  183. pkey, ok := p.(*packet.PublicKey)
  184. if !ok {
  185. return nil, fmt.Errorf("key is not a public key")
  186. }
  187. return pkey, nil
  188. }
  189. //GPGKeyToEntity retrieve the imported key and the traducted entity
  190. func GPGKeyToEntity(k *GPGKey) (*openpgp.Entity, error) {
  191. impKey, err := GetGPGImportByKeyID(k.KeyID)
  192. if err != nil {
  193. return nil, err
  194. }
  195. return checkArmoredGPGKeyString(impKey.Content)
  196. }
  197. //parseSubGPGKey parse a sub Key
  198. func parseSubGPGKey(ownerID int64, primaryID string, pubkey *packet.PublicKey, expiry time.Time) (*GPGKey, error) {
  199. content, err := base64EncPubKey(pubkey)
  200. if err != nil {
  201. return nil, err
  202. }
  203. return &GPGKey{
  204. OwnerID: ownerID,
  205. KeyID: pubkey.KeyIdString(),
  206. PrimaryKeyID: primaryID,
  207. Content: content,
  208. CreatedUnix: timeutil.TimeStamp(pubkey.CreationTime.Unix()),
  209. ExpiredUnix: timeutil.TimeStamp(expiry.Unix()),
  210. CanSign: pubkey.CanSign(),
  211. CanEncryptComms: pubkey.PubKeyAlgo.CanEncrypt(),
  212. CanEncryptStorage: pubkey.PubKeyAlgo.CanEncrypt(),
  213. CanCertify: pubkey.PubKeyAlgo.CanSign(),
  214. }, nil
  215. }
  216. //getExpiryTime extract the expire time of primary key based on sig
  217. func getExpiryTime(e *openpgp.Entity) time.Time {
  218. expiry := time.Time{}
  219. //Extract self-sign for expire date based on : https://github.com/golang/crypto/blob/master/openpgp/keys.go#L165
  220. var selfSig *packet.Signature
  221. for _, ident := range e.Identities {
  222. if selfSig == nil {
  223. selfSig = ident.SelfSignature
  224. } else if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId {
  225. selfSig = ident.SelfSignature
  226. break
  227. }
  228. }
  229. if selfSig.KeyLifetimeSecs != nil {
  230. expiry = e.PrimaryKey.CreationTime.Add(time.Duration(*selfSig.KeyLifetimeSecs) * time.Second)
  231. }
  232. return expiry
  233. }
  234. //parseGPGKey parse a PrimaryKey entity (primary key + subs keys + self-signature)
  235. func parseGPGKey(ownerID int64, e *openpgp.Entity) (*GPGKey, error) {
  236. pubkey := e.PrimaryKey
  237. expiry := getExpiryTime(e)
  238. //Parse Subkeys
  239. subkeys := make([]*GPGKey, len(e.Subkeys))
  240. for i, k := range e.Subkeys {
  241. subs, err := parseSubGPGKey(ownerID, pubkey.KeyIdString(), k.PublicKey, expiry)
  242. if err != nil {
  243. return nil, err
  244. }
  245. subkeys[i] = subs
  246. }
  247. //Check emails
  248. userEmails, err := GetEmailAddresses(ownerID)
  249. if err != nil {
  250. return nil, err
  251. }
  252. emails := make([]*EmailAddress, 0, len(e.Identities))
  253. for _, ident := range e.Identities {
  254. email := strings.ToLower(strings.TrimSpace(ident.UserId.Email))
  255. for _, e := range userEmails {
  256. if e.Email == email {
  257. emails = append(emails, e)
  258. break
  259. }
  260. }
  261. }
  262. //In the case no email as been found
  263. if len(emails) == 0 {
  264. failedEmails := make([]string, 0, len(e.Identities))
  265. for _, ident := range e.Identities {
  266. failedEmails = append(failedEmails, ident.UserId.Email)
  267. }
  268. return nil, ErrGPGNoEmailFound{failedEmails}
  269. }
  270. content, err := base64EncPubKey(pubkey)
  271. if err != nil {
  272. return nil, err
  273. }
  274. return &GPGKey{
  275. OwnerID: ownerID,
  276. KeyID: pubkey.KeyIdString(),
  277. PrimaryKeyID: "",
  278. Content: content,
  279. CreatedUnix: timeutil.TimeStamp(pubkey.CreationTime.Unix()),
  280. ExpiredUnix: timeutil.TimeStamp(expiry.Unix()),
  281. Emails: emails,
  282. SubsKey: subkeys,
  283. CanSign: pubkey.CanSign(),
  284. CanEncryptComms: pubkey.PubKeyAlgo.CanEncrypt(),
  285. CanEncryptStorage: pubkey.PubKeyAlgo.CanEncrypt(),
  286. CanCertify: pubkey.PubKeyAlgo.CanSign(),
  287. }, nil
  288. }
  289. // deleteGPGKey does the actual key deletion
  290. func deleteGPGKey(e *xorm.Session, keyID string) (int64, error) {
  291. if keyID == "" {
  292. return 0, fmt.Errorf("empty KeyId forbidden") //Should never happen but just to be sure
  293. }
  294. //Delete imported key
  295. n, err := e.Where("key_id=?", keyID).Delete(new(GPGKeyImport))
  296. if err != nil {
  297. return n, err
  298. }
  299. return e.Where("key_id=?", keyID).Or("primary_key_id=?", keyID).Delete(new(GPGKey))
  300. }
  301. // DeleteGPGKey deletes GPG key information in database.
  302. func DeleteGPGKey(doer *User, id int64) (err error) {
  303. key, err := GetGPGKeyByID(id)
  304. if err != nil {
  305. if IsErrGPGKeyNotExist(err) {
  306. return nil
  307. }
  308. return fmt.Errorf("GetPublicKeyByID: %v", err)
  309. }
  310. // Check if user has access to delete this key.
  311. if !doer.IsAdmin && doer.ID != key.OwnerID {
  312. return ErrGPGKeyAccessDenied{doer.ID, key.ID}
  313. }
  314. sess := x.NewSession()
  315. defer sess.Close()
  316. if err = sess.Begin(); err != nil {
  317. return err
  318. }
  319. if _, err = deleteGPGKey(sess, key.KeyID); err != nil {
  320. return err
  321. }
  322. return sess.Commit()
  323. }
  324. // CommitVerification represents a commit validation of signature
  325. type CommitVerification struct {
  326. Verified bool
  327. Warning bool
  328. Reason string
  329. SigningUser *User
  330. CommittingUser *User
  331. SigningEmail string
  332. SigningKey *GPGKey
  333. }
  334. // SignCommit represents a commit with validation of signature.
  335. type SignCommit struct {
  336. Verification *CommitVerification
  337. *UserCommit
  338. }
  339. const (
  340. // BadSignature is used as the reason when the signature has a KeyID that is in the db
  341. // but no key that has that ID verifies the signature. This is a suspicious failure.
  342. BadSignature = "gpg.error.probable_bad_signature"
  343. // BadDefaultSignature is used as the reason when the signature has a KeyID that matches the
  344. // default Key but is not verified by the default key. This is a suspicious failure.
  345. BadDefaultSignature = "gpg.error.probable_bad_default_signature"
  346. // NoKeyFound is used as the reason when no key can be found to verify the signature.
  347. NoKeyFound = "gpg.error.no_gpg_keys_found"
  348. )
  349. func readerFromBase64(s string) (io.Reader, error) {
  350. bs, err := base64.StdEncoding.DecodeString(s)
  351. if err != nil {
  352. return nil, err
  353. }
  354. return bytes.NewBuffer(bs), nil
  355. }
  356. func populateHash(hashFunc crypto.Hash, msg []byte) (hash.Hash, error) {
  357. h := hashFunc.New()
  358. if _, err := h.Write(msg); err != nil {
  359. return nil, err
  360. }
  361. return h, nil
  362. }
  363. // readArmoredSign read an armored signature block with the given type. https://sourcegraph.com/github.com/golang/crypto/-/blob/openpgp/read.go#L24:6-24:17
  364. func readArmoredSign(r io.Reader) (body io.Reader, err error) {
  365. block, err := armor.Decode(r)
  366. if err != nil {
  367. return
  368. }
  369. if block.Type != openpgp.SignatureType {
  370. return nil, fmt.Errorf("expected '" + openpgp.SignatureType + "', got: " + block.Type)
  371. }
  372. return block.Body, nil
  373. }
  374. func extractSignature(s string) (*packet.Signature, error) {
  375. r, err := readArmoredSign(strings.NewReader(s))
  376. if err != nil {
  377. return nil, fmt.Errorf("Failed to read signature armor")
  378. }
  379. p, err := packet.Read(r)
  380. if err != nil {
  381. return nil, fmt.Errorf("Failed to read signature packet")
  382. }
  383. sig, ok := p.(*packet.Signature)
  384. if !ok {
  385. return nil, fmt.Errorf("Packet is not a signature")
  386. }
  387. return sig, nil
  388. }
  389. func verifySign(s *packet.Signature, h hash.Hash, k *GPGKey) error {
  390. //Check if key can sign
  391. if !k.CanSign {
  392. return fmt.Errorf("key can not sign")
  393. }
  394. //Decode key
  395. pkey, err := base64DecPubKey(k.Content)
  396. if err != nil {
  397. return err
  398. }
  399. return pkey.VerifySignature(h, s)
  400. }
  401. func hashAndVerify(sig *packet.Signature, payload string, k *GPGKey, committer, signer *User, email string) *CommitVerification {
  402. //Generating hash of commit
  403. hash, err := populateHash(sig.Hash, []byte(payload))
  404. if err != nil { //Skipping failed to generate hash
  405. log.Error("PopulateHash: %v", err)
  406. return &CommitVerification{
  407. CommittingUser: committer,
  408. Verified: false,
  409. Reason: "gpg.error.generate_hash",
  410. }
  411. }
  412. if err := verifySign(sig, hash, k); err == nil {
  413. return &CommitVerification{ //Everything is ok
  414. CommittingUser: committer,
  415. Verified: true,
  416. Reason: fmt.Sprintf("%s <%s> / %s", signer.Name, signer.Email, k.KeyID),
  417. SigningUser: signer,
  418. SigningKey: k,
  419. SigningEmail: email,
  420. }
  421. }
  422. return nil
  423. }
  424. func hashAndVerifyWithSubKeys(sig *packet.Signature, payload string, k *GPGKey, committer, signer *User, email string) *CommitVerification {
  425. commitVerification := hashAndVerify(sig, payload, k, committer, signer, email)
  426. if commitVerification != nil {
  427. return commitVerification
  428. }
  429. //And test also SubsKey
  430. for _, sk := range k.SubsKey {
  431. commitVerification := hashAndVerify(sig, payload, sk, committer, signer, email)
  432. if commitVerification != nil {
  433. return commitVerification
  434. }
  435. }
  436. return nil
  437. }
  438. func hashAndVerifyForKeyID(sig *packet.Signature, payload string, committer *User, keyID, name, email string) *CommitVerification {
  439. if keyID == "" {
  440. return nil
  441. }
  442. keys, err := GetGPGKeysByKeyID(keyID)
  443. if err != nil {
  444. log.Error("GetGPGKeysByKeyID: %v", err)
  445. return &CommitVerification{
  446. CommittingUser: committer,
  447. Verified: false,
  448. Reason: "gpg.error.failed_retrieval_gpg_keys",
  449. }
  450. }
  451. if len(keys) == 0 {
  452. return nil
  453. }
  454. for _, key := range keys {
  455. activated := false
  456. if len(email) != 0 {
  457. for _, e := range key.Emails {
  458. if e.IsActivated && strings.EqualFold(e.Email, email) {
  459. activated = true
  460. email = e.Email
  461. break
  462. }
  463. }
  464. } else {
  465. for _, e := range key.Emails {
  466. if e.IsActivated {
  467. activated = true
  468. email = e.Email
  469. break
  470. }
  471. }
  472. }
  473. if !activated {
  474. continue
  475. }
  476. signer := &User{
  477. Name: name,
  478. Email: email,
  479. }
  480. if key.OwnerID != 0 {
  481. owner, err := GetUserByID(key.OwnerID)
  482. if err == nil {
  483. signer = owner
  484. } else if !IsErrUserNotExist(err) {
  485. log.Error("Failed to GetUserByID: %d for key ID: %d (%s) %v", key.OwnerID, key.ID, key.KeyID, err)
  486. return &CommitVerification{
  487. CommittingUser: committer,
  488. Verified: false,
  489. Reason: "gpg.error.no_committer_account",
  490. }
  491. }
  492. }
  493. commitVerification := hashAndVerifyWithSubKeys(sig, payload, key, committer, signer, email)
  494. if commitVerification != nil {
  495. return commitVerification
  496. }
  497. }
  498. // This is a bad situation ... We have a key id that is in our database but the signature doesn't match.
  499. return &CommitVerification{
  500. CommittingUser: committer,
  501. Verified: false,
  502. Warning: true,
  503. Reason: BadSignature,
  504. }
  505. }
  506. // ParseCommitWithSignature check if signature is good against keystore.
  507. func ParseCommitWithSignature(c *git.Commit) *CommitVerification {
  508. var committer *User
  509. if c.Committer != nil {
  510. var err error
  511. //Find Committer account
  512. committer, err = GetUserByEmail(c.Committer.Email) //This finds the user by primary email or activated email so commit will not be valid if email is not
  513. if err != nil { //Skipping not user for commiter
  514. committer = &User{
  515. Name: c.Committer.Name,
  516. Email: c.Committer.Email,
  517. }
  518. // We can expect this to often be an ErrUserNotExist. in the case
  519. // it is not, however, it is important to log it.
  520. if !IsErrUserNotExist(err) {
  521. log.Error("GetUserByEmail: %v", err)
  522. return &CommitVerification{
  523. CommittingUser: committer,
  524. Verified: false,
  525. Reason: "gpg.error.no_committer_account",
  526. }
  527. }
  528. }
  529. }
  530. // If no signature just report the committer
  531. if c.Signature == nil {
  532. return &CommitVerification{
  533. CommittingUser: committer,
  534. Verified: false, //Default value
  535. Reason: "gpg.error.not_signed_commit", //Default value
  536. }
  537. }
  538. //Parsing signature
  539. sig, err := extractSignature(c.Signature.Signature)
  540. if err != nil { //Skipping failed to extract sign
  541. log.Error("SignatureRead err: %v", err)
  542. return &CommitVerification{
  543. CommittingUser: committer,
  544. Verified: false,
  545. Reason: "gpg.error.extract_sign",
  546. }
  547. }
  548. keyID := ""
  549. if sig.IssuerKeyId != nil && (*sig.IssuerKeyId) != 0 {
  550. keyID = fmt.Sprintf("%X", *sig.IssuerKeyId)
  551. }
  552. if keyID == "" && sig.IssuerFingerprint != nil && len(sig.IssuerFingerprint) > 0 {
  553. keyID = fmt.Sprintf("%X", sig.IssuerFingerprint[12:20])
  554. }
  555. defaultReason := NoKeyFound
  556. // First check if the sig has a keyID and if so just look at that
  557. if commitVerification := hashAndVerifyForKeyID(
  558. sig,
  559. c.Signature.Payload,
  560. committer,
  561. keyID,
  562. setting.AppName,
  563. ""); commitVerification != nil {
  564. if commitVerification.Reason == BadSignature {
  565. defaultReason = BadSignature
  566. } else {
  567. return commitVerification
  568. }
  569. }
  570. // Now try to associate the signature with the committer, if present
  571. if committer.ID != 0 {
  572. keys, err := ListGPGKeys(committer.ID)
  573. if err != nil { //Skipping failed to get gpg keys of user
  574. log.Error("ListGPGKeys: %v", err)
  575. return &CommitVerification{
  576. CommittingUser: committer,
  577. Verified: false,
  578. Reason: "gpg.error.failed_retrieval_gpg_keys",
  579. }
  580. }
  581. for _, k := range keys {
  582. //Pre-check (& optimization) that emails attached to key can be attached to the commiter email and can validate
  583. canValidate := false
  584. email := ""
  585. for _, e := range k.Emails {
  586. if e.IsActivated && strings.EqualFold(e.Email, c.Committer.Email) {
  587. canValidate = true
  588. email = e.Email
  589. break
  590. }
  591. }
  592. if !canValidate {
  593. continue //Skip this key
  594. }
  595. commitVerification := hashAndVerifyWithSubKeys(sig, c.Signature.Payload, k, committer, committer, email)
  596. if commitVerification != nil {
  597. return commitVerification
  598. }
  599. }
  600. }
  601. if setting.Repository.Signing.SigningKey != "" && setting.Repository.Signing.SigningKey != "default" && setting.Repository.Signing.SigningKey != "none" {
  602. // OK we should try the default key
  603. gpgSettings := git.GPGSettings{
  604. Sign: true,
  605. KeyID: setting.Repository.Signing.SigningKey,
  606. Name: setting.Repository.Signing.SigningName,
  607. Email: setting.Repository.Signing.SigningEmail,
  608. }
  609. if err := gpgSettings.LoadPublicKeyContent(); err != nil {
  610. log.Error("Error getting default signing key: %s %v", gpgSettings.KeyID, err)
  611. } else if commitVerification := verifyWithGPGSettings(&gpgSettings, sig, c.Signature.Payload, committer, keyID); commitVerification != nil {
  612. if commitVerification.Reason == BadSignature {
  613. defaultReason = BadSignature
  614. } else {
  615. return commitVerification
  616. }
  617. }
  618. }
  619. defaultGPGSettings, err := c.GetRepositoryDefaultPublicGPGKey(false)
  620. if err != nil {
  621. log.Error("Error getting default public gpg key: %v", err)
  622. } else if defaultGPGSettings.Sign {
  623. if commitVerification := verifyWithGPGSettings(defaultGPGSettings, sig, c.Signature.Payload, committer, keyID); commitVerification != nil {
  624. if commitVerification.Reason == BadSignature {
  625. defaultReason = BadSignature
  626. } else {
  627. return commitVerification
  628. }
  629. }
  630. }
  631. return &CommitVerification{ //Default at this stage
  632. CommittingUser: committer,
  633. Verified: false,
  634. Warning: defaultReason != NoKeyFound,
  635. Reason: defaultReason,
  636. SigningKey: &GPGKey{
  637. KeyID: keyID,
  638. },
  639. }
  640. }
  641. func verifyWithGPGSettings(gpgSettings *git.GPGSettings, sig *packet.Signature, payload string, committer *User, keyID string) *CommitVerification {
  642. // First try to find the key in the db
  643. if commitVerification := hashAndVerifyForKeyID(sig, payload, committer, gpgSettings.KeyID, gpgSettings.Name, gpgSettings.Email); commitVerification != nil {
  644. return commitVerification
  645. }
  646. // Otherwise we have to parse the key
  647. ekey, err := checkArmoredGPGKeyString(gpgSettings.PublicKeyContent)
  648. if err != nil {
  649. log.Error("Unable to get default signing key: %v", err)
  650. return &CommitVerification{
  651. CommittingUser: committer,
  652. Verified: false,
  653. Reason: "gpg.error.generate_hash",
  654. }
  655. }
  656. pubkey := ekey.PrimaryKey
  657. content, err := base64EncPubKey(pubkey)
  658. if err != nil {
  659. return &CommitVerification{
  660. CommittingUser: committer,
  661. Verified: false,
  662. Reason: "gpg.error.generate_hash",
  663. }
  664. }
  665. k := &GPGKey{
  666. Content: content,
  667. CanSign: pubkey.CanSign(),
  668. KeyID: pubkey.KeyIdString(),
  669. }
  670. if commitVerification := hashAndVerifyWithSubKeys(sig, payload, k, committer, &User{
  671. Name: gpgSettings.Name,
  672. Email: gpgSettings.Email,
  673. }, gpgSettings.Email); commitVerification != nil {
  674. return commitVerification
  675. }
  676. if keyID == k.KeyID {
  677. // This is a bad situation ... We have a key id that matches our default key but the signature doesn't match.
  678. return &CommitVerification{
  679. CommittingUser: committer,
  680. Verified: false,
  681. Warning: true,
  682. Reason: BadSignature,
  683. }
  684. }
  685. return nil
  686. }
  687. // ParseCommitsWithSignature checks if signaute of commits are corresponding to users gpg keys.
  688. func ParseCommitsWithSignature(oldCommits *list.List) *list.List {
  689. var (
  690. newCommits = list.New()
  691. e = oldCommits.Front()
  692. )
  693. for e != nil {
  694. c := e.Value.(UserCommit)
  695. newCommits.PushBack(SignCommit{
  696. UserCommit: &c,
  697. Verification: ParseCommitWithSignature(c.Commit),
  698. })
  699. e = e.Next()
  700. }
  701. return newCommits
  702. }