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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  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. TrustStatus string
  334. }
  335. // SignCommit represents a commit with validation of signature.
  336. type SignCommit struct {
  337. Verification *CommitVerification
  338. *UserCommit
  339. }
  340. const (
  341. // BadSignature is used as the reason when the signature has a KeyID that is in the db
  342. // but no key that has that ID verifies the signature. This is a suspicious failure.
  343. BadSignature = "gpg.error.probable_bad_signature"
  344. // BadDefaultSignature is used as the reason when the signature has a KeyID that matches the
  345. // default Key but is not verified by the default key. This is a suspicious failure.
  346. BadDefaultSignature = "gpg.error.probable_bad_default_signature"
  347. // NoKeyFound is used as the reason when no key can be found to verify the signature.
  348. NoKeyFound = "gpg.error.no_gpg_keys_found"
  349. )
  350. func readerFromBase64(s string) (io.Reader, error) {
  351. bs, err := base64.StdEncoding.DecodeString(s)
  352. if err != nil {
  353. return nil, err
  354. }
  355. return bytes.NewBuffer(bs), nil
  356. }
  357. func populateHash(hashFunc crypto.Hash, msg []byte) (hash.Hash, error) {
  358. h := hashFunc.New()
  359. if _, err := h.Write(msg); err != nil {
  360. return nil, err
  361. }
  362. return h, nil
  363. }
  364. // 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
  365. func readArmoredSign(r io.Reader) (body io.Reader, err error) {
  366. block, err := armor.Decode(r)
  367. if err != nil {
  368. return
  369. }
  370. if block.Type != openpgp.SignatureType {
  371. return nil, fmt.Errorf("expected '" + openpgp.SignatureType + "', got: " + block.Type)
  372. }
  373. return block.Body, nil
  374. }
  375. func extractSignature(s string) (*packet.Signature, error) {
  376. r, err := readArmoredSign(strings.NewReader(s))
  377. if err != nil {
  378. return nil, fmt.Errorf("Failed to read signature armor")
  379. }
  380. p, err := packet.Read(r)
  381. if err != nil {
  382. return nil, fmt.Errorf("Failed to read signature packet")
  383. }
  384. sig, ok := p.(*packet.Signature)
  385. if !ok {
  386. return nil, fmt.Errorf("Packet is not a signature")
  387. }
  388. return sig, nil
  389. }
  390. func verifySign(s *packet.Signature, h hash.Hash, k *GPGKey) error {
  391. //Check if key can sign
  392. if !k.CanSign {
  393. return fmt.Errorf("key can not sign")
  394. }
  395. //Decode key
  396. pkey, err := base64DecPubKey(k.Content)
  397. if err != nil {
  398. return err
  399. }
  400. return pkey.VerifySignature(h, s)
  401. }
  402. func hashAndVerify(sig *packet.Signature, payload string, k *GPGKey, committer, signer *User, email string) *CommitVerification {
  403. //Generating hash of commit
  404. hash, err := populateHash(sig.Hash, []byte(payload))
  405. if err != nil { //Skipping failed to generate hash
  406. log.Error("PopulateHash: %v", err)
  407. return &CommitVerification{
  408. CommittingUser: committer,
  409. Verified: false,
  410. Reason: "gpg.error.generate_hash",
  411. }
  412. }
  413. if err := verifySign(sig, hash, k); err == nil {
  414. return &CommitVerification{ //Everything is ok
  415. CommittingUser: committer,
  416. Verified: true,
  417. Reason: fmt.Sprintf("%s <%s> / %s", signer.Name, signer.Email, k.KeyID),
  418. SigningUser: signer,
  419. SigningKey: k,
  420. SigningEmail: email,
  421. }
  422. }
  423. return nil
  424. }
  425. func hashAndVerifyWithSubKeys(sig *packet.Signature, payload string, k *GPGKey, committer, signer *User, email string) *CommitVerification {
  426. commitVerification := hashAndVerify(sig, payload, k, committer, signer, email)
  427. if commitVerification != nil {
  428. return commitVerification
  429. }
  430. //And test also SubsKey
  431. for _, sk := range k.SubsKey {
  432. commitVerification := hashAndVerify(sig, payload, sk, committer, signer, email)
  433. if commitVerification != nil {
  434. return commitVerification
  435. }
  436. }
  437. return nil
  438. }
  439. func hashAndVerifyForKeyID(sig *packet.Signature, payload string, committer *User, keyID, name, email string) *CommitVerification {
  440. if keyID == "" {
  441. return nil
  442. }
  443. keys, err := GetGPGKeysByKeyID(keyID)
  444. if err != nil {
  445. log.Error("GetGPGKeysByKeyID: %v", err)
  446. return &CommitVerification{
  447. CommittingUser: committer,
  448. Verified: false,
  449. Reason: "gpg.error.failed_retrieval_gpg_keys",
  450. }
  451. }
  452. if len(keys) == 0 {
  453. return nil
  454. }
  455. for _, key := range keys {
  456. activated := false
  457. if len(email) != 0 {
  458. for _, e := range key.Emails {
  459. if e.IsActivated && strings.EqualFold(e.Email, email) {
  460. activated = true
  461. email = e.Email
  462. break
  463. }
  464. }
  465. } else {
  466. for _, e := range key.Emails {
  467. if e.IsActivated {
  468. activated = true
  469. email = e.Email
  470. break
  471. }
  472. }
  473. }
  474. if !activated {
  475. continue
  476. }
  477. signer := &User{
  478. Name: name,
  479. Email: email,
  480. }
  481. if key.OwnerID != 0 {
  482. owner, err := GetUserByID(key.OwnerID)
  483. if err == nil {
  484. signer = owner
  485. } else if !IsErrUserNotExist(err) {
  486. log.Error("Failed to GetUserByID: %d for key ID: %d (%s) %v", key.OwnerID, key.ID, key.KeyID, err)
  487. return &CommitVerification{
  488. CommittingUser: committer,
  489. Verified: false,
  490. Reason: "gpg.error.no_committer_account",
  491. }
  492. }
  493. }
  494. commitVerification := hashAndVerifyWithSubKeys(sig, payload, key, committer, signer, email)
  495. if commitVerification != nil {
  496. return commitVerification
  497. }
  498. }
  499. // This is a bad situation ... We have a key id that is in our database but the signature doesn't match.
  500. return &CommitVerification{
  501. CommittingUser: committer,
  502. Verified: false,
  503. Warning: true,
  504. Reason: BadSignature,
  505. }
  506. }
  507. // ParseCommitWithSignature check if signature is good against keystore.
  508. func ParseCommitWithSignature(c *git.Commit) *CommitVerification {
  509. var committer *User
  510. if c.Committer != nil {
  511. var err error
  512. //Find Committer account
  513. 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
  514. if err != nil { //Skipping not user for commiter
  515. committer = &User{
  516. Name: c.Committer.Name,
  517. Email: c.Committer.Email,
  518. }
  519. // We can expect this to often be an ErrUserNotExist. in the case
  520. // it is not, however, it is important to log it.
  521. if !IsErrUserNotExist(err) {
  522. log.Error("GetUserByEmail: %v", err)
  523. return &CommitVerification{
  524. CommittingUser: committer,
  525. Verified: false,
  526. Reason: "gpg.error.no_committer_account",
  527. }
  528. }
  529. }
  530. }
  531. // If no signature just report the committer
  532. if c.Signature == nil {
  533. return &CommitVerification{
  534. CommittingUser: committer,
  535. Verified: false, //Default value
  536. Reason: "gpg.error.not_signed_commit", //Default value
  537. }
  538. }
  539. //Parsing signature
  540. sig, err := extractSignature(c.Signature.Signature)
  541. if err != nil { //Skipping failed to extract sign
  542. log.Error("SignatureRead err: %v", err)
  543. return &CommitVerification{
  544. CommittingUser: committer,
  545. Verified: false,
  546. Reason: "gpg.error.extract_sign",
  547. }
  548. }
  549. keyID := ""
  550. if sig.IssuerKeyId != nil && (*sig.IssuerKeyId) != 0 {
  551. keyID = fmt.Sprintf("%X", *sig.IssuerKeyId)
  552. }
  553. if keyID == "" && sig.IssuerFingerprint != nil && len(sig.IssuerFingerprint) > 0 {
  554. keyID = fmt.Sprintf("%X", sig.IssuerFingerprint[12:20])
  555. }
  556. defaultReason := NoKeyFound
  557. // First check if the sig has a keyID and if so just look at that
  558. if commitVerification := hashAndVerifyForKeyID(
  559. sig,
  560. c.Signature.Payload,
  561. committer,
  562. keyID,
  563. setting.AppName,
  564. ""); commitVerification != nil {
  565. if commitVerification.Reason == BadSignature {
  566. defaultReason = BadSignature
  567. } else {
  568. return commitVerification
  569. }
  570. }
  571. // Now try to associate the signature with the committer, if present
  572. if committer.ID != 0 {
  573. keys, err := ListGPGKeys(committer.ID)
  574. if err != nil { //Skipping failed to get gpg keys of user
  575. log.Error("ListGPGKeys: %v", err)
  576. return &CommitVerification{
  577. CommittingUser: committer,
  578. Verified: false,
  579. Reason: "gpg.error.failed_retrieval_gpg_keys",
  580. }
  581. }
  582. for _, k := range keys {
  583. //Pre-check (& optimization) that emails attached to key can be attached to the commiter email and can validate
  584. canValidate := false
  585. email := ""
  586. for _, e := range k.Emails {
  587. if e.IsActivated && strings.EqualFold(e.Email, c.Committer.Email) {
  588. canValidate = true
  589. email = e.Email
  590. break
  591. }
  592. }
  593. if !canValidate {
  594. continue //Skip this key
  595. }
  596. commitVerification := hashAndVerifyWithSubKeys(sig, c.Signature.Payload, k, committer, committer, email)
  597. if commitVerification != nil {
  598. return commitVerification
  599. }
  600. }
  601. }
  602. if setting.Repository.Signing.SigningKey != "" && setting.Repository.Signing.SigningKey != "default" && setting.Repository.Signing.SigningKey != "none" {
  603. // OK we should try the default key
  604. gpgSettings := git.GPGSettings{
  605. Sign: true,
  606. KeyID: setting.Repository.Signing.SigningKey,
  607. Name: setting.Repository.Signing.SigningName,
  608. Email: setting.Repository.Signing.SigningEmail,
  609. }
  610. if err := gpgSettings.LoadPublicKeyContent(); err != nil {
  611. log.Error("Error getting default signing key: %s %v", gpgSettings.KeyID, err)
  612. } else if commitVerification := verifyWithGPGSettings(&gpgSettings, sig, c.Signature.Payload, committer, keyID); commitVerification != nil {
  613. if commitVerification.Reason == BadSignature {
  614. defaultReason = BadSignature
  615. } else {
  616. return commitVerification
  617. }
  618. }
  619. }
  620. defaultGPGSettings, err := c.GetRepositoryDefaultPublicGPGKey(false)
  621. if err != nil {
  622. log.Error("Error getting default public gpg key: %v", err)
  623. } else if defaultGPGSettings == nil {
  624. log.Warn("Unable to get defaultGPGSettings for unattached commit: %s", c.ID.String())
  625. } else if defaultGPGSettings.Sign {
  626. if commitVerification := verifyWithGPGSettings(defaultGPGSettings, sig, c.Signature.Payload, committer, keyID); commitVerification != nil {
  627. if commitVerification.Reason == BadSignature {
  628. defaultReason = BadSignature
  629. } else {
  630. return commitVerification
  631. }
  632. }
  633. }
  634. return &CommitVerification{ //Default at this stage
  635. CommittingUser: committer,
  636. Verified: false,
  637. Warning: defaultReason != NoKeyFound,
  638. Reason: defaultReason,
  639. SigningKey: &GPGKey{
  640. KeyID: keyID,
  641. },
  642. }
  643. }
  644. func verifyWithGPGSettings(gpgSettings *git.GPGSettings, sig *packet.Signature, payload string, committer *User, keyID string) *CommitVerification {
  645. // First try to find the key in the db
  646. if commitVerification := hashAndVerifyForKeyID(sig, payload, committer, gpgSettings.KeyID, gpgSettings.Name, gpgSettings.Email); commitVerification != nil {
  647. return commitVerification
  648. }
  649. // Otherwise we have to parse the key
  650. ekey, err := checkArmoredGPGKeyString(gpgSettings.PublicKeyContent)
  651. if err != nil {
  652. log.Error("Unable to get default signing key: %v", err)
  653. return &CommitVerification{
  654. CommittingUser: committer,
  655. Verified: false,
  656. Reason: "gpg.error.generate_hash",
  657. }
  658. }
  659. pubkey := ekey.PrimaryKey
  660. content, err := base64EncPubKey(pubkey)
  661. if err != nil {
  662. return &CommitVerification{
  663. CommittingUser: committer,
  664. Verified: false,
  665. Reason: "gpg.error.generate_hash",
  666. }
  667. }
  668. k := &GPGKey{
  669. Content: content,
  670. CanSign: pubkey.CanSign(),
  671. KeyID: pubkey.KeyIdString(),
  672. }
  673. for _, subKey := range ekey.Subkeys {
  674. content, err := base64EncPubKey(subKey.PublicKey)
  675. if err != nil {
  676. return &CommitVerification{
  677. CommittingUser: committer,
  678. Verified: false,
  679. Reason: "gpg.error.generate_hash",
  680. }
  681. }
  682. k.SubsKey = append(k.SubsKey, &GPGKey{
  683. Content: content,
  684. CanSign: subKey.PublicKey.CanSign(),
  685. KeyID: subKey.PublicKey.KeyIdString(),
  686. })
  687. }
  688. if commitVerification := hashAndVerifyWithSubKeys(sig, payload, k, committer, &User{
  689. Name: gpgSettings.Name,
  690. Email: gpgSettings.Email,
  691. }, gpgSettings.Email); commitVerification != nil {
  692. return commitVerification
  693. }
  694. if keyID == k.KeyID {
  695. // This is a bad situation ... We have a key id that matches our default key but the signature doesn't match.
  696. return &CommitVerification{
  697. CommittingUser: committer,
  698. Verified: false,
  699. Warning: true,
  700. Reason: BadSignature,
  701. }
  702. }
  703. return nil
  704. }
  705. // ParseCommitsWithSignature checks if signaute of commits are corresponding to users gpg keys.
  706. func ParseCommitsWithSignature(oldCommits *list.List, repository *Repository) *list.List {
  707. var (
  708. newCommits = list.New()
  709. e = oldCommits.Front()
  710. )
  711. memberMap := map[int64]bool{}
  712. for e != nil {
  713. c := e.Value.(UserCommit)
  714. signCommit := SignCommit{
  715. UserCommit: &c,
  716. Verification: ParseCommitWithSignature(c.Commit),
  717. }
  718. _ = CalculateTrustStatus(signCommit.Verification, repository, &memberMap)
  719. newCommits.PushBack(signCommit)
  720. e = e.Next()
  721. }
  722. return newCommits
  723. }
  724. // CalculateTrustStatus will calculate the TrustStatus for a commit verification within a repository
  725. func CalculateTrustStatus(verification *CommitVerification, repository *Repository, memberMap *map[int64]bool) (err error) {
  726. if verification.Verified {
  727. verification.TrustStatus = "trusted"
  728. if verification.SigningUser.ID != 0 {
  729. var isMember bool
  730. if memberMap != nil {
  731. var has bool
  732. isMember, has = (*memberMap)[verification.SigningUser.ID]
  733. if !has {
  734. isMember, err = repository.IsOwnerMemberCollaborator(verification.SigningUser.ID)
  735. (*memberMap)[verification.SigningUser.ID] = isMember
  736. }
  737. } else {
  738. isMember, err = repository.IsOwnerMemberCollaborator(verification.SigningUser.ID)
  739. }
  740. if !isMember {
  741. verification.TrustStatus = "untrusted"
  742. if verification.CommittingUser.ID != verification.SigningUser.ID {
  743. // The committing user and the signing user are not the same and are not the default key
  744. // This should be marked as questionable unless the signing user is a collaborator/team member etc.
  745. verification.TrustStatus = "unmatched"
  746. }
  747. }
  748. }
  749. }
  750. return
  751. }