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 22KB

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