本站源代码
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.

772 lines
22KB

  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 == nil {
  623. log.Warn("Unable to get defaultGPGSettings for unattached commit: %s", c.ID.String())
  624. } else if defaultGPGSettings.Sign {
  625. if commitVerification := verifyWithGPGSettings(defaultGPGSettings, sig, c.Signature.Payload, committer, keyID); commitVerification != nil {
  626. if commitVerification.Reason == BadSignature {
  627. defaultReason = BadSignature
  628. } else {
  629. return commitVerification
  630. }
  631. }
  632. }
  633. return &CommitVerification{ //Default at this stage
  634. CommittingUser: committer,
  635. Verified: false,
  636. Warning: defaultReason != NoKeyFound,
  637. Reason: defaultReason,
  638. SigningKey: &GPGKey{
  639. KeyID: keyID,
  640. },
  641. }
  642. }
  643. func verifyWithGPGSettings(gpgSettings *git.GPGSettings, sig *packet.Signature, payload string, committer *User, keyID string) *CommitVerification {
  644. // First try to find the key in the db
  645. if commitVerification := hashAndVerifyForKeyID(sig, payload, committer, gpgSettings.KeyID, gpgSettings.Name, gpgSettings.Email); commitVerification != nil {
  646. return commitVerification
  647. }
  648. // Otherwise we have to parse the key
  649. ekey, err := checkArmoredGPGKeyString(gpgSettings.PublicKeyContent)
  650. if err != nil {
  651. log.Error("Unable to get default signing key: %v", err)
  652. return &CommitVerification{
  653. CommittingUser: committer,
  654. Verified: false,
  655. Reason: "gpg.error.generate_hash",
  656. }
  657. }
  658. pubkey := ekey.PrimaryKey
  659. content, err := base64EncPubKey(pubkey)
  660. if err != nil {
  661. return &CommitVerification{
  662. CommittingUser: committer,
  663. Verified: false,
  664. Reason: "gpg.error.generate_hash",
  665. }
  666. }
  667. k := &GPGKey{
  668. Content: content,
  669. CanSign: pubkey.CanSign(),
  670. KeyID: pubkey.KeyIdString(),
  671. }
  672. if commitVerification := hashAndVerifyWithSubKeys(sig, payload, k, committer, &User{
  673. Name: gpgSettings.Name,
  674. Email: gpgSettings.Email,
  675. }, gpgSettings.Email); commitVerification != nil {
  676. return commitVerification
  677. }
  678. if keyID == k.KeyID {
  679. // This is a bad situation ... We have a key id that matches our default key but the signature doesn't match.
  680. return &CommitVerification{
  681. CommittingUser: committer,
  682. Verified: false,
  683. Warning: true,
  684. Reason: BadSignature,
  685. }
  686. }
  687. return nil
  688. }
  689. // ParseCommitsWithSignature checks if signaute of commits are corresponding to users gpg keys.
  690. func ParseCommitsWithSignature(oldCommits *list.List) *list.List {
  691. var (
  692. newCommits = list.New()
  693. e = oldCommits.Front()
  694. )
  695. for e != nil {
  696. c := e.Value.(UserCommit)
  697. newCommits.PushBack(SignCommit{
  698. UserCommit: &c,
  699. Verification: ParseCommitWithSignature(c.Commit),
  700. })
  701. e = e.Next()
  702. }
  703. return newCommits
  704. }
上海开阖软件有限公司 沪ICP备12045867号-1