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

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