Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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