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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  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.EntityList, error) {
  96. list, err := openpgp.ReadArmoredKeyRing(strings.NewReader(content))
  97. if err != nil {
  98. return nil, ErrGPGKeyParsing{err}
  99. }
  100. return list, 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. ekeys, err := checkArmoredGPGKeyString(content)
  140. if err != nil {
  141. return nil, err
  142. }
  143. sess := x.NewSession()
  144. defer sess.Close()
  145. if err = sess.Begin(); err != nil {
  146. return nil, err
  147. }
  148. keys := make([]*GPGKey, 0, len(ekeys))
  149. for _, ekey := range ekeys {
  150. // Key ID cannot be duplicated.
  151. has, err := sess.Where("key_id=?", ekey.PrimaryKey.KeyIdString()).
  152. Get(new(GPGKey))
  153. if err != nil {
  154. return nil, err
  155. } else if has {
  156. return nil, ErrGPGKeyIDAlreadyUsed{ekey.PrimaryKey.KeyIdString()}
  157. }
  158. //Get DB session
  159. key, err := parseGPGKey(ownerID, ekey)
  160. if err != nil {
  161. return nil, err
  162. }
  163. if err = addGPGKey(sess, key, content); err != nil {
  164. return nil, err
  165. }
  166. keys = append(keys, key)
  167. }
  168. return keys, sess.Commit()
  169. }
  170. //base64EncPubKey encode public key content to base 64
  171. func base64EncPubKey(pubkey *packet.PublicKey) (string, error) {
  172. var w bytes.Buffer
  173. err := pubkey.Serialize(&w)
  174. if err != nil {
  175. return "", err
  176. }
  177. return base64.StdEncoding.EncodeToString(w.Bytes()), nil
  178. }
  179. //base64DecPubKey decode public key content from base 64
  180. func base64DecPubKey(content string) (*packet.PublicKey, error) {
  181. b, err := readerFromBase64(content)
  182. if err != nil {
  183. return nil, err
  184. }
  185. //Read key
  186. p, err := packet.Read(b)
  187. if err != nil {
  188. return nil, err
  189. }
  190. //Check type
  191. pkey, ok := p.(*packet.PublicKey)
  192. if !ok {
  193. return nil, fmt.Errorf("key is not a public key")
  194. }
  195. return pkey, nil
  196. }
  197. //GPGKeyToEntity retrieve the imported key and the traducted entity
  198. func GPGKeyToEntity(k *GPGKey) (*openpgp.Entity, error) {
  199. impKey, err := GetGPGImportByKeyID(k.KeyID)
  200. if err != nil {
  201. return nil, err
  202. }
  203. keys, err := checkArmoredGPGKeyString(impKey.Content)
  204. if err != nil {
  205. return nil, err
  206. }
  207. return keys[0], err
  208. }
  209. //parseSubGPGKey parse a sub Key
  210. func parseSubGPGKey(ownerID int64, primaryID string, pubkey *packet.PublicKey, expiry time.Time) (*GPGKey, error) {
  211. content, err := base64EncPubKey(pubkey)
  212. if err != nil {
  213. return nil, err
  214. }
  215. return &GPGKey{
  216. OwnerID: ownerID,
  217. KeyID: pubkey.KeyIdString(),
  218. PrimaryKeyID: primaryID,
  219. Content: content,
  220. CreatedUnix: timeutil.TimeStamp(pubkey.CreationTime.Unix()),
  221. ExpiredUnix: timeutil.TimeStamp(expiry.Unix()),
  222. CanSign: pubkey.CanSign(),
  223. CanEncryptComms: pubkey.PubKeyAlgo.CanEncrypt(),
  224. CanEncryptStorage: pubkey.PubKeyAlgo.CanEncrypt(),
  225. CanCertify: pubkey.PubKeyAlgo.CanSign(),
  226. }, nil
  227. }
  228. //getExpiryTime extract the expire time of primary key based on sig
  229. func getExpiryTime(e *openpgp.Entity) time.Time {
  230. expiry := time.Time{}
  231. //Extract self-sign for expire date based on : https://github.com/golang/crypto/blob/master/openpgp/keys.go#L165
  232. var selfSig *packet.Signature
  233. for _, ident := range e.Identities {
  234. if selfSig == nil {
  235. selfSig = ident.SelfSignature
  236. } else if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId {
  237. selfSig = ident.SelfSignature
  238. break
  239. }
  240. }
  241. if selfSig.KeyLifetimeSecs != nil {
  242. expiry = e.PrimaryKey.CreationTime.Add(time.Duration(*selfSig.KeyLifetimeSecs) * time.Second)
  243. }
  244. return expiry
  245. }
  246. //parseGPGKey parse a PrimaryKey entity (primary key + subs keys + self-signature)
  247. func parseGPGKey(ownerID int64, e *openpgp.Entity) (*GPGKey, error) {
  248. pubkey := e.PrimaryKey
  249. expiry := getExpiryTime(e)
  250. //Parse Subkeys
  251. subkeys := make([]*GPGKey, len(e.Subkeys))
  252. for i, k := range e.Subkeys {
  253. subs, err := parseSubGPGKey(ownerID, pubkey.KeyIdString(), k.PublicKey, expiry)
  254. if err != nil {
  255. return nil, ErrGPGKeyParsing{ParseError: err}
  256. }
  257. subkeys[i] = subs
  258. }
  259. //Check emails
  260. userEmails, err := GetEmailAddresses(ownerID)
  261. if err != nil {
  262. return nil, err
  263. }
  264. emails := make([]*EmailAddress, 0, len(e.Identities))
  265. for _, ident := range e.Identities {
  266. if ident.Revocation != nil {
  267. continue
  268. }
  269. email := strings.ToLower(strings.TrimSpace(ident.UserId.Email))
  270. for _, e := range userEmails {
  271. if e.Email == email {
  272. emails = append(emails, e)
  273. break
  274. }
  275. }
  276. }
  277. //In the case no email as been found
  278. if len(emails) == 0 {
  279. failedEmails := make([]string, 0, len(e.Identities))
  280. for _, ident := range e.Identities {
  281. failedEmails = append(failedEmails, ident.UserId.Email)
  282. }
  283. return nil, ErrGPGNoEmailFound{failedEmails}
  284. }
  285. content, err := base64EncPubKey(pubkey)
  286. if err != nil {
  287. return nil, err
  288. }
  289. return &GPGKey{
  290. OwnerID: ownerID,
  291. KeyID: pubkey.KeyIdString(),
  292. PrimaryKeyID: "",
  293. Content: content,
  294. CreatedUnix: timeutil.TimeStamp(pubkey.CreationTime.Unix()),
  295. ExpiredUnix: timeutil.TimeStamp(expiry.Unix()),
  296. Emails: emails,
  297. SubsKey: subkeys,
  298. CanSign: pubkey.CanSign(),
  299. CanEncryptComms: pubkey.PubKeyAlgo.CanEncrypt(),
  300. CanEncryptStorage: pubkey.PubKeyAlgo.CanEncrypt(),
  301. CanCertify: pubkey.PubKeyAlgo.CanSign(),
  302. }, nil
  303. }
  304. // deleteGPGKey does the actual key deletion
  305. func deleteGPGKey(e *xorm.Session, keyID string) (int64, error) {
  306. if keyID == "" {
  307. return 0, fmt.Errorf("empty KeyId forbidden") //Should never happen but just to be sure
  308. }
  309. //Delete imported key
  310. n, err := e.Where("key_id=?", keyID).Delete(new(GPGKeyImport))
  311. if err != nil {
  312. return n, err
  313. }
  314. return e.Where("key_id=?", keyID).Or("primary_key_id=?", keyID).Delete(new(GPGKey))
  315. }
  316. // DeleteGPGKey deletes GPG key information in database.
  317. func DeleteGPGKey(doer *User, id int64) (err error) {
  318. key, err := GetGPGKeyByID(id)
  319. if err != nil {
  320. if IsErrGPGKeyNotExist(err) {
  321. return nil
  322. }
  323. return fmt.Errorf("GetPublicKeyByID: %v", err)
  324. }
  325. // Check if user has access to delete this key.
  326. if !doer.IsAdmin && doer.ID != key.OwnerID {
  327. return ErrGPGKeyAccessDenied{doer.ID, key.ID}
  328. }
  329. sess := x.NewSession()
  330. defer sess.Close()
  331. if err = sess.Begin(); err != nil {
  332. return err
  333. }
  334. if _, err = deleteGPGKey(sess, key.KeyID); err != nil {
  335. return err
  336. }
  337. return sess.Commit()
  338. }
  339. // CommitVerification represents a commit validation of signature
  340. type CommitVerification struct {
  341. Verified bool
  342. Warning bool
  343. Reason string
  344. SigningUser *User
  345. CommittingUser *User
  346. SigningEmail string
  347. SigningKey *GPGKey
  348. TrustStatus string
  349. }
  350. // SignCommit represents a commit with validation of signature.
  351. type SignCommit struct {
  352. Verification *CommitVerification
  353. *UserCommit
  354. }
  355. const (
  356. // BadSignature is used as the reason when the signature has a KeyID that is in the db
  357. // but no key that has that ID verifies the signature. This is a suspicious failure.
  358. BadSignature = "gpg.error.probable_bad_signature"
  359. // BadDefaultSignature is used as the reason when the signature has a KeyID that matches the
  360. // default Key but is not verified by the default key. This is a suspicious failure.
  361. BadDefaultSignature = "gpg.error.probable_bad_default_signature"
  362. // NoKeyFound is used as the reason when no key can be found to verify the signature.
  363. NoKeyFound = "gpg.error.no_gpg_keys_found"
  364. )
  365. func readerFromBase64(s string) (io.Reader, error) {
  366. bs, err := base64.StdEncoding.DecodeString(s)
  367. if err != nil {
  368. return nil, err
  369. }
  370. return bytes.NewBuffer(bs), nil
  371. }
  372. func populateHash(hashFunc crypto.Hash, msg []byte) (hash.Hash, error) {
  373. h := hashFunc.New()
  374. if _, err := h.Write(msg); err != nil {
  375. return nil, err
  376. }
  377. return h, nil
  378. }
  379. // 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
  380. func readArmoredSign(r io.Reader) (body io.Reader, err error) {
  381. block, err := armor.Decode(r)
  382. if err != nil {
  383. return
  384. }
  385. if block.Type != openpgp.SignatureType {
  386. return nil, fmt.Errorf("expected '" + openpgp.SignatureType + "', got: " + block.Type)
  387. }
  388. return block.Body, nil
  389. }
  390. func extractSignature(s string) (*packet.Signature, error) {
  391. r, err := readArmoredSign(strings.NewReader(s))
  392. if err != nil {
  393. return nil, fmt.Errorf("Failed to read signature armor")
  394. }
  395. p, err := packet.Read(r)
  396. if err != nil {
  397. return nil, fmt.Errorf("Failed to read signature packet")
  398. }
  399. sig, ok := p.(*packet.Signature)
  400. if !ok {
  401. return nil, fmt.Errorf("Packet is not a signature")
  402. }
  403. return sig, nil
  404. }
  405. func verifySign(s *packet.Signature, h hash.Hash, k *GPGKey) error {
  406. //Check if key can sign
  407. if !k.CanSign {
  408. return fmt.Errorf("key can not sign")
  409. }
  410. //Decode key
  411. pkey, err := base64DecPubKey(k.Content)
  412. if err != nil {
  413. return err
  414. }
  415. return pkey.VerifySignature(h, s)
  416. }
  417. func hashAndVerify(sig *packet.Signature, payload string, k *GPGKey, committer, signer *User, email string) *CommitVerification {
  418. //Generating hash of commit
  419. hash, err := populateHash(sig.Hash, []byte(payload))
  420. if err != nil { //Skipping failed to generate hash
  421. log.Error("PopulateHash: %v", err)
  422. return &CommitVerification{
  423. CommittingUser: committer,
  424. Verified: false,
  425. Reason: "gpg.error.generate_hash",
  426. }
  427. }
  428. if err := verifySign(sig, hash, k); err == nil {
  429. return &CommitVerification{ //Everything is ok
  430. CommittingUser: committer,
  431. Verified: true,
  432. Reason: fmt.Sprintf("%s / %s", signer.Name, k.KeyID),
  433. SigningUser: signer,
  434. SigningKey: k,
  435. SigningEmail: email,
  436. }
  437. }
  438. return nil
  439. }
  440. func hashAndVerifyWithSubKeys(sig *packet.Signature, payload string, k *GPGKey, committer, signer *User, email string) *CommitVerification {
  441. commitVerification := hashAndVerify(sig, payload, k, committer, signer, email)
  442. if commitVerification != nil {
  443. return commitVerification
  444. }
  445. //And test also SubsKey
  446. for _, sk := range k.SubsKey {
  447. commitVerification := hashAndVerify(sig, payload, sk, committer, signer, email)
  448. if commitVerification != nil {
  449. return commitVerification
  450. }
  451. }
  452. return nil
  453. }
  454. func hashAndVerifyForKeyID(sig *packet.Signature, payload string, committer *User, keyID, name, email string) *CommitVerification {
  455. if keyID == "" {
  456. return nil
  457. }
  458. keys, err := GetGPGKeysByKeyID(keyID)
  459. if err != nil {
  460. log.Error("GetGPGKeysByKeyID: %v", err)
  461. return &CommitVerification{
  462. CommittingUser: committer,
  463. Verified: false,
  464. Reason: "gpg.error.failed_retrieval_gpg_keys",
  465. }
  466. }
  467. if len(keys) == 0 {
  468. return nil
  469. }
  470. for _, key := range keys {
  471. var primaryKeys []*GPGKey
  472. if key.PrimaryKeyID != "" {
  473. primaryKeys, err = GetGPGKeysByKeyID(key.PrimaryKeyID)
  474. if err != nil {
  475. log.Error("GetGPGKeysByKeyID: %v", err)
  476. return &CommitVerification{
  477. CommittingUser: committer,
  478. Verified: false,
  479. Reason: "gpg.error.failed_retrieval_gpg_keys",
  480. }
  481. }
  482. }
  483. activated := false
  484. if len(email) != 0 {
  485. for _, e := range key.Emails {
  486. if e.IsActivated && strings.EqualFold(e.Email, email) {
  487. activated = true
  488. email = e.Email
  489. break
  490. }
  491. }
  492. if !activated {
  493. for _, pkey := range primaryKeys {
  494. for _, e := range pkey.Emails {
  495. if e.IsActivated && strings.EqualFold(e.Email, email) {
  496. activated = true
  497. email = e.Email
  498. break
  499. }
  500. }
  501. if activated {
  502. break
  503. }
  504. }
  505. }
  506. } else {
  507. for _, e := range key.Emails {
  508. if e.IsActivated {
  509. activated = true
  510. email = e.Email
  511. break
  512. }
  513. }
  514. if !activated {
  515. for _, pkey := range primaryKeys {
  516. for _, e := range pkey.Emails {
  517. if e.IsActivated {
  518. activated = true
  519. email = e.Email
  520. break
  521. }
  522. }
  523. if activated {
  524. break
  525. }
  526. }
  527. }
  528. }
  529. if !activated {
  530. continue
  531. }
  532. signer := &User{
  533. Name: name,
  534. Email: email,
  535. }
  536. if key.OwnerID != 0 {
  537. owner, err := GetUserByID(key.OwnerID)
  538. if err == nil {
  539. signer = owner
  540. } else if !IsErrUserNotExist(err) {
  541. log.Error("Failed to GetUserByID: %d for key ID: %d (%s) %v", key.OwnerID, key.ID, key.KeyID, err)
  542. return &CommitVerification{
  543. CommittingUser: committer,
  544. Verified: false,
  545. Reason: "gpg.error.no_committer_account",
  546. }
  547. }
  548. }
  549. commitVerification := hashAndVerifyWithSubKeys(sig, payload, key, committer, signer, email)
  550. if commitVerification != nil {
  551. return commitVerification
  552. }
  553. }
  554. // This is a bad situation ... We have a key id that is in our database but the signature doesn't match.
  555. return &CommitVerification{
  556. CommittingUser: committer,
  557. Verified: false,
  558. Warning: true,
  559. Reason: BadSignature,
  560. }
  561. }
  562. // ParseCommitWithSignature check if signature is good against keystore.
  563. func ParseCommitWithSignature(c *git.Commit) *CommitVerification {
  564. var committer *User
  565. if c.Committer != nil {
  566. var err error
  567. //Find Committer account
  568. 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
  569. if err != nil { //Skipping not user for commiter
  570. committer = &User{
  571. Name: c.Committer.Name,
  572. Email: c.Committer.Email,
  573. }
  574. // We can expect this to often be an ErrUserNotExist. in the case
  575. // it is not, however, it is important to log it.
  576. if !IsErrUserNotExist(err) {
  577. log.Error("GetUserByEmail: %v", err)
  578. return &CommitVerification{
  579. CommittingUser: committer,
  580. Verified: false,
  581. Reason: "gpg.error.no_committer_account",
  582. }
  583. }
  584. }
  585. }
  586. // If no signature just report the committer
  587. if c.Signature == nil {
  588. return &CommitVerification{
  589. CommittingUser: committer,
  590. Verified: false, //Default value
  591. Reason: "gpg.error.not_signed_commit", //Default value
  592. }
  593. }
  594. //Parsing signature
  595. sig, err := extractSignature(c.Signature.Signature)
  596. if err != nil { //Skipping failed to extract sign
  597. log.Error("SignatureRead err: %v", err)
  598. return &CommitVerification{
  599. CommittingUser: committer,
  600. Verified: false,
  601. Reason: "gpg.error.extract_sign",
  602. }
  603. }
  604. keyID := ""
  605. if sig.IssuerKeyId != nil && (*sig.IssuerKeyId) != 0 {
  606. keyID = fmt.Sprintf("%X", *sig.IssuerKeyId)
  607. }
  608. if keyID == "" && sig.IssuerFingerprint != nil && len(sig.IssuerFingerprint) > 0 {
  609. keyID = fmt.Sprintf("%X", sig.IssuerFingerprint[12:20])
  610. }
  611. defaultReason := NoKeyFound
  612. // First check if the sig has a keyID and if so just look at that
  613. if commitVerification := hashAndVerifyForKeyID(
  614. sig,
  615. c.Signature.Payload,
  616. committer,
  617. keyID,
  618. setting.AppName,
  619. ""); commitVerification != nil {
  620. if commitVerification.Reason == BadSignature {
  621. defaultReason = BadSignature
  622. } else {
  623. return commitVerification
  624. }
  625. }
  626. // Now try to associate the signature with the committer, if present
  627. if committer.ID != 0 {
  628. keys, err := ListGPGKeys(committer.ID, ListOptions{})
  629. if err != nil { //Skipping failed to get gpg keys of user
  630. log.Error("ListGPGKeys: %v", err)
  631. return &CommitVerification{
  632. CommittingUser: committer,
  633. Verified: false,
  634. Reason: "gpg.error.failed_retrieval_gpg_keys",
  635. }
  636. }
  637. for _, k := range keys {
  638. //Pre-check (& optimization) that emails attached to key can be attached to the commiter email and can validate
  639. canValidate := false
  640. email := ""
  641. for _, e := range k.Emails {
  642. if e.IsActivated && strings.EqualFold(e.Email, c.Committer.Email) {
  643. canValidate = true
  644. email = e.Email
  645. break
  646. }
  647. }
  648. if !canValidate {
  649. continue //Skip this key
  650. }
  651. commitVerification := hashAndVerifyWithSubKeys(sig, c.Signature.Payload, k, committer, committer, email)
  652. if commitVerification != nil {
  653. return commitVerification
  654. }
  655. }
  656. }
  657. if setting.Repository.Signing.SigningKey != "" && setting.Repository.Signing.SigningKey != "default" && setting.Repository.Signing.SigningKey != "none" {
  658. // OK we should try the default key
  659. gpgSettings := git.GPGSettings{
  660. Sign: true,
  661. KeyID: setting.Repository.Signing.SigningKey,
  662. Name: setting.Repository.Signing.SigningName,
  663. Email: setting.Repository.Signing.SigningEmail,
  664. }
  665. if err := gpgSettings.LoadPublicKeyContent(); err != nil {
  666. log.Error("Error getting default signing key: %s %v", gpgSettings.KeyID, err)
  667. } else if commitVerification := verifyWithGPGSettings(&gpgSettings, sig, c.Signature.Payload, committer, keyID); commitVerification != nil {
  668. if commitVerification.Reason == BadSignature {
  669. defaultReason = BadSignature
  670. } else {
  671. return commitVerification
  672. }
  673. }
  674. }
  675. defaultGPGSettings, err := c.GetRepositoryDefaultPublicGPGKey(false)
  676. if err != nil {
  677. log.Error("Error getting default public gpg key: %v", err)
  678. } else if defaultGPGSettings == nil {
  679. log.Warn("Unable to get defaultGPGSettings for unattached commit: %s", c.ID.String())
  680. } else if defaultGPGSettings.Sign {
  681. if commitVerification := verifyWithGPGSettings(defaultGPGSettings, sig, c.Signature.Payload, committer, keyID); commitVerification != nil {
  682. if commitVerification.Reason == BadSignature {
  683. defaultReason = BadSignature
  684. } else {
  685. return commitVerification
  686. }
  687. }
  688. }
  689. return &CommitVerification{ //Default at this stage
  690. CommittingUser: committer,
  691. Verified: false,
  692. Warning: defaultReason != NoKeyFound,
  693. Reason: defaultReason,
  694. SigningKey: &GPGKey{
  695. KeyID: keyID,
  696. },
  697. }
  698. }
  699. func verifyWithGPGSettings(gpgSettings *git.GPGSettings, sig *packet.Signature, payload string, committer *User, keyID string) *CommitVerification {
  700. // First try to find the key in the db
  701. if commitVerification := hashAndVerifyForKeyID(sig, payload, committer, gpgSettings.KeyID, gpgSettings.Name, gpgSettings.Email); commitVerification != nil {
  702. return commitVerification
  703. }
  704. // Otherwise we have to parse the key
  705. ekeys, err := checkArmoredGPGKeyString(gpgSettings.PublicKeyContent)
  706. if err != nil {
  707. log.Error("Unable to get default signing key: %v", err)
  708. return &CommitVerification{
  709. CommittingUser: committer,
  710. Verified: false,
  711. Reason: "gpg.error.generate_hash",
  712. }
  713. }
  714. for _, ekey := range ekeys {
  715. pubkey := ekey.PrimaryKey
  716. content, err := base64EncPubKey(pubkey)
  717. if err != nil {
  718. return &CommitVerification{
  719. CommittingUser: committer,
  720. Verified: false,
  721. Reason: "gpg.error.generate_hash",
  722. }
  723. }
  724. k := &GPGKey{
  725. Content: content,
  726. CanSign: pubkey.CanSign(),
  727. KeyID: pubkey.KeyIdString(),
  728. }
  729. for _, subKey := range ekey.Subkeys {
  730. content, err := base64EncPubKey(subKey.PublicKey)
  731. if err != nil {
  732. return &CommitVerification{
  733. CommittingUser: committer,
  734. Verified: false,
  735. Reason: "gpg.error.generate_hash",
  736. }
  737. }
  738. k.SubsKey = append(k.SubsKey, &GPGKey{
  739. Content: content,
  740. CanSign: subKey.PublicKey.CanSign(),
  741. KeyID: subKey.PublicKey.KeyIdString(),
  742. })
  743. }
  744. if commitVerification := hashAndVerifyWithSubKeys(sig, payload, k, committer, &User{
  745. Name: gpgSettings.Name,
  746. Email: gpgSettings.Email,
  747. }, gpgSettings.Email); commitVerification != nil {
  748. return commitVerification
  749. }
  750. if keyID == k.KeyID {
  751. // This is a bad situation ... We have a key id that matches our default key but the signature doesn't match.
  752. return &CommitVerification{
  753. CommittingUser: committer,
  754. Verified: false,
  755. Warning: true,
  756. Reason: BadSignature,
  757. }
  758. }
  759. }
  760. return nil
  761. }
  762. // ParseCommitsWithSignature checks if signaute of commits are corresponding to users gpg keys.
  763. func ParseCommitsWithSignature(oldCommits *list.List, repository *Repository) *list.List {
  764. var (
  765. newCommits = list.New()
  766. e = oldCommits.Front()
  767. )
  768. keyMap := map[string]bool{}
  769. for e != nil {
  770. c := e.Value.(UserCommit)
  771. signCommit := SignCommit{
  772. UserCommit: &c,
  773. Verification: ParseCommitWithSignature(c.Commit),
  774. }
  775. _ = CalculateTrustStatus(signCommit.Verification, repository, &keyMap)
  776. newCommits.PushBack(signCommit)
  777. e = e.Next()
  778. }
  779. return newCommits
  780. }
  781. // CalculateTrustStatus will calculate the TrustStatus for a commit verification within a repository
  782. func CalculateTrustStatus(verification *CommitVerification, repository *Repository, keyMap *map[string]bool) (err error) {
  783. if !verification.Verified {
  784. return
  785. }
  786. // There are several trust models in Gitea
  787. trustModel := repository.GetTrustModel()
  788. // In the Committer trust model a signature is trusted if it matches the committer
  789. // - it doesn't matter if they're a collaborator, the owner, Gitea or Github
  790. // NB: This model is commit verification only
  791. if trustModel == CommitterTrustModel {
  792. // default to "unmatched"
  793. verification.TrustStatus = "unmatched"
  794. // We can only verify against users in our database but the default key will match
  795. // against by email if it is not in the db.
  796. if (verification.SigningUser.ID != 0 &&
  797. verification.CommittingUser.ID == verification.SigningUser.ID) ||
  798. (verification.SigningUser.ID == 0 && verification.CommittingUser.ID == 0 &&
  799. verification.SigningUser.Email == verification.CommittingUser.Email) {
  800. verification.TrustStatus = "trusted"
  801. }
  802. return
  803. }
  804. // Now we drop to the more nuanced trust models...
  805. verification.TrustStatus = "trusted"
  806. if verification.SigningUser.ID == 0 {
  807. // This commit is signed by the default key - but this key is not assigned to a user in the DB.
  808. // However in the CollaboratorCommitterTrustModel we cannot mark this as trusted
  809. // unless the default key matches the email of a non-user.
  810. if trustModel == CollaboratorCommitterTrustModel && (verification.CommittingUser.ID != 0 ||
  811. verification.SigningUser.Email != verification.CommittingUser.Email) {
  812. verification.TrustStatus = "untrusted"
  813. }
  814. return
  815. }
  816. var isMember bool
  817. if keyMap != nil {
  818. var has bool
  819. isMember, has = (*keyMap)[verification.SigningKey.KeyID]
  820. if !has {
  821. isMember, err = repository.IsOwnerMemberCollaborator(verification.SigningUser.ID)
  822. (*keyMap)[verification.SigningKey.KeyID] = isMember
  823. }
  824. } else {
  825. isMember, err = repository.IsOwnerMemberCollaborator(verification.SigningUser.ID)
  826. }
  827. if !isMember {
  828. verification.TrustStatus = "untrusted"
  829. if verification.CommittingUser.ID != verification.SigningUser.ID {
  830. // The committing user and the signing user are not the same
  831. // This should be marked as questionable unless the signing user is a collaborator/team member etc.
  832. verification.TrustStatus = "unmatched"
  833. }
  834. } else if trustModel == CollaboratorCommitterTrustModel && verification.CommittingUser.ID != verification.SigningUser.ID {
  835. // The committing user and the signing user are not the same and our trustmodel states that they must match
  836. verification.TrustStatus = "unmatched"
  837. }
  838. return
  839. }