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

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