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_commit_verification.go 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package asymkey
  4. import (
  5. "context"
  6. "fmt"
  7. "hash"
  8. "strings"
  9. "code.gitea.io/gitea/models/db"
  10. repo_model "code.gitea.io/gitea/models/repo"
  11. user_model "code.gitea.io/gitea/models/user"
  12. "code.gitea.io/gitea/modules/git"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/setting"
  15. "github.com/keybase/go-crypto/openpgp/packet"
  16. )
  17. // __________________ ________ ____ __.
  18. // / _____/\______ \/ _____/ | |/ _|____ ___.__.
  19. // / \ ___ | ___/ \ ___ | <_/ __ < | |
  20. // \ \_\ \| | \ \_\ \ | | \ ___/\___ |
  21. // \______ /|____| \______ / |____|__ \___ > ____|
  22. // \/ \/ \/ \/\/
  23. // _________ .__ __
  24. // \_ ___ \ ____ _____ _____ |__|/ |_
  25. // / \ \/ / _ \ / \ / \| \ __\
  26. // \ \___( <_> ) Y Y \ Y Y \ || |
  27. // \______ /\____/|__|_| /__|_| /__||__|
  28. // \/ \/ \/
  29. // ____ ____ .__ _____.__ __ .__
  30. // \ \ / /___________|__|/ ____\__| ____ _____ _/ |_|__| ____ ____
  31. // \ Y // __ \_ __ \ \ __\| |/ ___\\__ \\ __\ |/ _ \ / \
  32. // \ /\ ___/| | \/ || | | \ \___ / __ \| | | ( <_> ) | \
  33. // \___/ \___ >__| |__||__| |__|\___ >____ /__| |__|\____/|___| /
  34. // \/ \/ \/ \/
  35. // This file provides functions relating commit verification
  36. // CommitVerification represents a commit validation of signature
  37. type CommitVerification struct {
  38. Verified bool
  39. Warning bool
  40. Reason string
  41. SigningUser *user_model.User
  42. CommittingUser *user_model.User
  43. SigningEmail string
  44. SigningKey *GPGKey
  45. SigningSSHKey *PublicKey
  46. TrustStatus string
  47. }
  48. // SignCommit represents a commit with validation of signature.
  49. type SignCommit struct {
  50. Verification *CommitVerification
  51. *user_model.UserCommit
  52. }
  53. const (
  54. // BadSignature is used as the reason when the signature has a KeyID that is in the db
  55. // but no key that has that ID verifies the signature. This is a suspicious failure.
  56. BadSignature = "gpg.error.probable_bad_signature"
  57. // BadDefaultSignature is used as the reason when the signature has a KeyID that matches the
  58. // default Key but is not verified by the default key. This is a suspicious failure.
  59. BadDefaultSignature = "gpg.error.probable_bad_default_signature"
  60. // NoKeyFound is used as the reason when no key can be found to verify the signature.
  61. NoKeyFound = "gpg.error.no_gpg_keys_found"
  62. )
  63. // ParseCommitsWithSignature checks if signaute of commits are corresponding to users gpg keys.
  64. func ParseCommitsWithSignature(ctx context.Context, oldCommits []*user_model.UserCommit, repoTrustModel repo_model.TrustModelType, isOwnerMemberCollaborator func(*user_model.User) (bool, error)) []*SignCommit {
  65. newCommits := make([]*SignCommit, 0, len(oldCommits))
  66. keyMap := map[string]bool{}
  67. for _, c := range oldCommits {
  68. signCommit := &SignCommit{
  69. UserCommit: c,
  70. Verification: ParseCommitWithSignature(ctx, c.Commit),
  71. }
  72. _ = CalculateTrustStatus(signCommit.Verification, repoTrustModel, isOwnerMemberCollaborator, &keyMap)
  73. newCommits = append(newCommits, signCommit)
  74. }
  75. return newCommits
  76. }
  77. // ParseCommitWithSignature check if signature is good against keystore.
  78. func ParseCommitWithSignature(ctx context.Context, c *git.Commit) *CommitVerification {
  79. var committer *user_model.User
  80. if c.Committer != nil {
  81. var err error
  82. // Find Committer account
  83. committer, err = user_model.GetUserByEmail(ctx, c.Committer.Email) // This finds the user by primary email or activated email so commit will not be valid if email is not
  84. if err != nil { // Skipping not user for committer
  85. committer = &user_model.User{
  86. Name: c.Committer.Name,
  87. Email: c.Committer.Email,
  88. }
  89. // We can expect this to often be an ErrUserNotExist. in the case
  90. // it is not, however, it is important to log it.
  91. if !user_model.IsErrUserNotExist(err) {
  92. log.Error("GetUserByEmail: %v", err)
  93. return &CommitVerification{
  94. CommittingUser: committer,
  95. Verified: false,
  96. Reason: "gpg.error.no_committer_account",
  97. }
  98. }
  99. }
  100. }
  101. // If no signature just report the committer
  102. if c.Signature == nil {
  103. return &CommitVerification{
  104. CommittingUser: committer,
  105. Verified: false, // Default value
  106. Reason: "gpg.error.not_signed_commit", // Default value
  107. }
  108. }
  109. // If this a SSH signature handle it differently
  110. if strings.HasPrefix(c.Signature.Signature, "-----BEGIN SSH SIGNATURE-----") {
  111. return ParseCommitWithSSHSignature(ctx, c, committer)
  112. }
  113. // Parsing signature
  114. sig, err := extractSignature(c.Signature.Signature)
  115. if err != nil { // Skipping failed to extract sign
  116. log.Error("SignatureRead err: %v", err)
  117. return &CommitVerification{
  118. CommittingUser: committer,
  119. Verified: false,
  120. Reason: "gpg.error.extract_sign",
  121. }
  122. }
  123. keyID := ""
  124. if sig.IssuerKeyId != nil && (*sig.IssuerKeyId) != 0 {
  125. keyID = fmt.Sprintf("%X", *sig.IssuerKeyId)
  126. }
  127. if keyID == "" && sig.IssuerFingerprint != nil && len(sig.IssuerFingerprint) > 0 {
  128. keyID = fmt.Sprintf("%X", sig.IssuerFingerprint[12:20])
  129. }
  130. defaultReason := NoKeyFound
  131. // First check if the sig has a keyID and if so just look at that
  132. if commitVerification := hashAndVerifyForKeyID(
  133. ctx,
  134. sig,
  135. c.Signature.Payload,
  136. committer,
  137. keyID,
  138. setting.AppName,
  139. ""); commitVerification != nil {
  140. if commitVerification.Reason == BadSignature {
  141. defaultReason = BadSignature
  142. } else {
  143. return commitVerification
  144. }
  145. }
  146. // Now try to associate the signature with the committer, if present
  147. if committer.ID != 0 {
  148. keys, err := ListGPGKeys(ctx, committer.ID, db.ListOptions{})
  149. if err != nil { // Skipping failed to get gpg keys of user
  150. log.Error("ListGPGKeys: %v", err)
  151. return &CommitVerification{
  152. CommittingUser: committer,
  153. Verified: false,
  154. Reason: "gpg.error.failed_retrieval_gpg_keys",
  155. }
  156. }
  157. committerEmailAddresses, _ := user_model.GetEmailAddresses(ctx, committer.ID)
  158. activated := false
  159. for _, e := range committerEmailAddresses {
  160. if e.IsActivated && strings.EqualFold(e.Email, c.Committer.Email) {
  161. activated = true
  162. break
  163. }
  164. }
  165. for _, k := range keys {
  166. // Pre-check (& optimization) that emails attached to key can be attached to the committer email and can validate
  167. canValidate := false
  168. email := ""
  169. if k.Verified && activated {
  170. canValidate = true
  171. email = c.Committer.Email
  172. }
  173. if !canValidate {
  174. for _, e := range k.Emails {
  175. if e.IsActivated && strings.EqualFold(e.Email, c.Committer.Email) {
  176. canValidate = true
  177. email = e.Email
  178. break
  179. }
  180. }
  181. }
  182. if !canValidate {
  183. continue // Skip this key
  184. }
  185. commitVerification := hashAndVerifyWithSubKeysCommitVerification(sig, c.Signature.Payload, k, committer, committer, email)
  186. if commitVerification != nil {
  187. return commitVerification
  188. }
  189. }
  190. }
  191. if setting.Repository.Signing.SigningKey != "" && setting.Repository.Signing.SigningKey != "default" && setting.Repository.Signing.SigningKey != "none" {
  192. // OK we should try the default key
  193. gpgSettings := git.GPGSettings{
  194. Sign: true,
  195. KeyID: setting.Repository.Signing.SigningKey,
  196. Name: setting.Repository.Signing.SigningName,
  197. Email: setting.Repository.Signing.SigningEmail,
  198. }
  199. if err := gpgSettings.LoadPublicKeyContent(); err != nil {
  200. log.Error("Error getting default signing key: %s %v", gpgSettings.KeyID, err)
  201. } else if commitVerification := verifyWithGPGSettings(ctx, &gpgSettings, sig, c.Signature.Payload, committer, keyID); commitVerification != nil {
  202. if commitVerification.Reason == BadSignature {
  203. defaultReason = BadSignature
  204. } else {
  205. return commitVerification
  206. }
  207. }
  208. }
  209. defaultGPGSettings, err := c.GetRepositoryDefaultPublicGPGKey(false)
  210. if err != nil {
  211. log.Error("Error getting default public gpg key: %v", err)
  212. } else if defaultGPGSettings == nil {
  213. log.Warn("Unable to get defaultGPGSettings for unattached commit: %s", c.ID.String())
  214. } else if defaultGPGSettings.Sign {
  215. if commitVerification := verifyWithGPGSettings(ctx, defaultGPGSettings, sig, c.Signature.Payload, committer, keyID); commitVerification != nil {
  216. if commitVerification.Reason == BadSignature {
  217. defaultReason = BadSignature
  218. } else {
  219. return commitVerification
  220. }
  221. }
  222. }
  223. return &CommitVerification{ // Default at this stage
  224. CommittingUser: committer,
  225. Verified: false,
  226. Warning: defaultReason != NoKeyFound,
  227. Reason: defaultReason,
  228. SigningKey: &GPGKey{
  229. KeyID: keyID,
  230. },
  231. }
  232. }
  233. func verifyWithGPGSettings(ctx context.Context, gpgSettings *git.GPGSettings, sig *packet.Signature, payload string, committer *user_model.User, keyID string) *CommitVerification {
  234. // First try to find the key in the db
  235. if commitVerification := hashAndVerifyForKeyID(ctx, sig, payload, committer, gpgSettings.KeyID, gpgSettings.Name, gpgSettings.Email); commitVerification != nil {
  236. return commitVerification
  237. }
  238. // Otherwise we have to parse the key
  239. ekeys, err := checkArmoredGPGKeyString(gpgSettings.PublicKeyContent)
  240. if err != nil {
  241. log.Error("Unable to get default signing key: %v", err)
  242. return &CommitVerification{
  243. CommittingUser: committer,
  244. Verified: false,
  245. Reason: "gpg.error.generate_hash",
  246. }
  247. }
  248. for _, ekey := range ekeys {
  249. pubkey := ekey.PrimaryKey
  250. content, err := base64EncPubKey(pubkey)
  251. if err != nil {
  252. return &CommitVerification{
  253. CommittingUser: committer,
  254. Verified: false,
  255. Reason: "gpg.error.generate_hash",
  256. }
  257. }
  258. k := &GPGKey{
  259. Content: content,
  260. CanSign: pubkey.CanSign(),
  261. KeyID: pubkey.KeyIdString(),
  262. }
  263. for _, subKey := range ekey.Subkeys {
  264. content, err := base64EncPubKey(subKey.PublicKey)
  265. if err != nil {
  266. return &CommitVerification{
  267. CommittingUser: committer,
  268. Verified: false,
  269. Reason: "gpg.error.generate_hash",
  270. }
  271. }
  272. k.SubsKey = append(k.SubsKey, &GPGKey{
  273. Content: content,
  274. CanSign: subKey.PublicKey.CanSign(),
  275. KeyID: subKey.PublicKey.KeyIdString(),
  276. })
  277. }
  278. if commitVerification := hashAndVerifyWithSubKeysCommitVerification(sig, payload, k, committer, &user_model.User{
  279. Name: gpgSettings.Name,
  280. Email: gpgSettings.Email,
  281. }, gpgSettings.Email); commitVerification != nil {
  282. return commitVerification
  283. }
  284. if keyID == k.KeyID {
  285. // This is a bad situation ... We have a key id that matches our default key but the signature doesn't match.
  286. return &CommitVerification{
  287. CommittingUser: committer,
  288. Verified: false,
  289. Warning: true,
  290. Reason: BadSignature,
  291. }
  292. }
  293. }
  294. return nil
  295. }
  296. func verifySign(s *packet.Signature, h hash.Hash, k *GPGKey) error {
  297. // Check if key can sign
  298. if !k.CanSign {
  299. return fmt.Errorf("key can not sign")
  300. }
  301. // Decode key
  302. pkey, err := base64DecPubKey(k.Content)
  303. if err != nil {
  304. return err
  305. }
  306. return pkey.VerifySignature(h, s)
  307. }
  308. func hashAndVerify(sig *packet.Signature, payload string, k *GPGKey) (*GPGKey, error) {
  309. // Generating hash of commit
  310. hash, err := populateHash(sig.Hash, []byte(payload))
  311. if err != nil { // Skipping as failed to generate hash
  312. log.Error("PopulateHash: %v", err)
  313. return nil, err
  314. }
  315. // We will ignore errors in verification as they don't need to be propagated up
  316. err = verifySign(sig, hash, k)
  317. if err != nil {
  318. return nil, nil
  319. }
  320. return k, nil
  321. }
  322. func hashAndVerifyWithSubKeys(sig *packet.Signature, payload string, k *GPGKey) (*GPGKey, error) {
  323. verified, err := hashAndVerify(sig, payload, k)
  324. if err != nil || verified != nil {
  325. return verified, err
  326. }
  327. for _, sk := range k.SubsKey {
  328. verified, err := hashAndVerify(sig, payload, sk)
  329. if err != nil || verified != nil {
  330. return verified, err
  331. }
  332. }
  333. return nil, nil
  334. }
  335. func hashAndVerifyWithSubKeysCommitVerification(sig *packet.Signature, payload string, k *GPGKey, committer, signer *user_model.User, email string) *CommitVerification {
  336. key, err := hashAndVerifyWithSubKeys(sig, payload, k)
  337. if err != nil { // Skipping failed to generate hash
  338. return &CommitVerification{
  339. CommittingUser: committer,
  340. Verified: false,
  341. Reason: "gpg.error.generate_hash",
  342. }
  343. }
  344. if key != nil {
  345. return &CommitVerification{ // Everything is ok
  346. CommittingUser: committer,
  347. Verified: true,
  348. Reason: fmt.Sprintf("%s / %s", signer.Name, key.KeyID),
  349. SigningUser: signer,
  350. SigningKey: key,
  351. SigningEmail: email,
  352. }
  353. }
  354. return nil
  355. }
  356. func hashAndVerifyForKeyID(ctx context.Context, sig *packet.Signature, payload string, committer *user_model.User, keyID, name, email string) *CommitVerification {
  357. if keyID == "" {
  358. return nil
  359. }
  360. keys, err := GetGPGKeysByKeyID(ctx, keyID)
  361. if err != nil {
  362. log.Error("GetGPGKeysByKeyID: %v", err)
  363. return &CommitVerification{
  364. CommittingUser: committer,
  365. Verified: false,
  366. Reason: "gpg.error.failed_retrieval_gpg_keys",
  367. }
  368. }
  369. if len(keys) == 0 {
  370. return nil
  371. }
  372. for _, key := range keys {
  373. var primaryKeys []*GPGKey
  374. if key.PrimaryKeyID != "" {
  375. primaryKeys, err = GetGPGKeysByKeyID(ctx, key.PrimaryKeyID)
  376. if err != nil {
  377. log.Error("GetGPGKeysByKeyID: %v", err)
  378. return &CommitVerification{
  379. CommittingUser: committer,
  380. Verified: false,
  381. Reason: "gpg.error.failed_retrieval_gpg_keys",
  382. }
  383. }
  384. }
  385. activated, email := checkKeyEmails(ctx, email, append([]*GPGKey{key}, primaryKeys...)...)
  386. if !activated {
  387. continue
  388. }
  389. signer := &user_model.User{
  390. Name: name,
  391. Email: email,
  392. }
  393. if key.OwnerID != 0 {
  394. owner, err := user_model.GetUserByID(ctx, key.OwnerID)
  395. if err == nil {
  396. signer = owner
  397. } else if !user_model.IsErrUserNotExist(err) {
  398. log.Error("Failed to user_model.GetUserByID: %d for key ID: %d (%s) %v", key.OwnerID, key.ID, key.KeyID, err)
  399. return &CommitVerification{
  400. CommittingUser: committer,
  401. Verified: false,
  402. Reason: "gpg.error.no_committer_account",
  403. }
  404. }
  405. }
  406. commitVerification := hashAndVerifyWithSubKeysCommitVerification(sig, payload, key, committer, signer, email)
  407. if commitVerification != nil {
  408. return commitVerification
  409. }
  410. }
  411. // This is a bad situation ... We have a key id that is in our database but the signature doesn't match.
  412. return &CommitVerification{
  413. CommittingUser: committer,
  414. Verified: false,
  415. Warning: true,
  416. Reason: BadSignature,
  417. }
  418. }
  419. // CalculateTrustStatus will calculate the TrustStatus for a commit verification within a repository
  420. // There are several trust models in Gitea
  421. func CalculateTrustStatus(verification *CommitVerification, repoTrustModel repo_model.TrustModelType, isOwnerMemberCollaborator func(*user_model.User) (bool, error), keyMap *map[string]bool) error {
  422. if !verification.Verified {
  423. return nil
  424. }
  425. // In the Committer trust model a signature is trusted if it matches the committer
  426. // - it doesn't matter if they're a collaborator, the owner, Gitea or Github
  427. // NB: This model is commit verification only
  428. if repoTrustModel == repo_model.CommitterTrustModel {
  429. // default to "unmatched"
  430. verification.TrustStatus = "unmatched"
  431. // We can only verify against users in our database but the default key will match
  432. // against by email if it is not in the db.
  433. if (verification.SigningUser.ID != 0 &&
  434. verification.CommittingUser.ID == verification.SigningUser.ID) ||
  435. (verification.SigningUser.ID == 0 && verification.CommittingUser.ID == 0 &&
  436. verification.SigningUser.Email == verification.CommittingUser.Email) {
  437. verification.TrustStatus = "trusted"
  438. }
  439. return nil
  440. }
  441. // Now we drop to the more nuanced trust models...
  442. verification.TrustStatus = "trusted"
  443. if verification.SigningUser.ID == 0 {
  444. // This commit is signed by the default key - but this key is not assigned to a user in the DB.
  445. // However in the repo_model.CollaboratorCommitterTrustModel we cannot mark this as trusted
  446. // unless the default key matches the email of a non-user.
  447. if repoTrustModel == repo_model.CollaboratorCommitterTrustModel && (verification.CommittingUser.ID != 0 ||
  448. verification.SigningUser.Email != verification.CommittingUser.Email) {
  449. verification.TrustStatus = "untrusted"
  450. }
  451. return nil
  452. }
  453. // Check we actually have a GPG SigningKey
  454. var err error
  455. if verification.SigningKey != nil {
  456. var isMember bool
  457. if keyMap != nil {
  458. var has bool
  459. isMember, has = (*keyMap)[verification.SigningKey.KeyID]
  460. if !has {
  461. isMember, err = isOwnerMemberCollaborator(verification.SigningUser)
  462. (*keyMap)[verification.SigningKey.KeyID] = isMember
  463. }
  464. } else {
  465. isMember, err = isOwnerMemberCollaborator(verification.SigningUser)
  466. }
  467. if !isMember {
  468. verification.TrustStatus = "untrusted"
  469. if verification.CommittingUser.ID != verification.SigningUser.ID {
  470. // The committing user and the signing user are not the same
  471. // This should be marked as questionable unless the signing user is a collaborator/team member etc.
  472. verification.TrustStatus = "unmatched"
  473. }
  474. } else if repoTrustModel == repo_model.CollaboratorCommitterTrustModel && verification.CommittingUser.ID != verification.SigningUser.ID {
  475. // The committing user and the signing user are not the same and our trustmodel states that they must match
  476. verification.TrustStatus = "unmatched"
  477. }
  478. }
  479. return err
  480. }