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.

478 lines
13 KiB

  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/git"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/util"
  18. "github.com/go-xorm/xorm"
  19. "github.com/keybase/go-crypto/openpgp"
  20. "github.com/keybase/go-crypto/openpgp/armor"
  21. "github.com/keybase/go-crypto/openpgp/packet"
  22. )
  23. // GPGKey represents a GPG key.
  24. type GPGKey struct {
  25. ID int64 `xorm:"pk autoincr"`
  26. OwnerID int64 `xorm:"INDEX NOT NULL"`
  27. KeyID string `xorm:"INDEX CHAR(16) NOT NULL"`
  28. PrimaryKeyID string `xorm:"CHAR(16)"`
  29. Content string `xorm:"TEXT NOT NULL"`
  30. CreatedUnix util.TimeStamp `xorm:"created"`
  31. ExpiredUnix util.TimeStamp
  32. AddedUnix util.TimeStamp
  33. SubsKey []*GPGKey `xorm:"-"`
  34. Emails []*EmailAddress
  35. CanSign bool
  36. CanEncryptComms bool
  37. CanEncryptStorage bool
  38. CanCertify bool
  39. }
  40. // BeforeInsert will be invoked by XORM before inserting a record
  41. func (key *GPGKey) BeforeInsert() {
  42. key.AddedUnix = util.TimeStampNow()
  43. }
  44. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  45. func (key *GPGKey) AfterLoad(session *xorm.Session) {
  46. err := session.Where("primary_key_id=?", key.KeyID).Find(&key.SubsKey)
  47. if err != nil {
  48. log.Error(3, "Find Sub GPGkeys[%d]: %v", key.KeyID, err)
  49. }
  50. }
  51. // ListGPGKeys returns a list of public keys belongs to given user.
  52. func ListGPGKeys(uid int64) ([]*GPGKey, error) {
  53. keys := make([]*GPGKey, 0, 5)
  54. return keys, x.Where("owner_id=? AND primary_key_id=''", uid).Find(&keys)
  55. }
  56. // GetGPGKeyByID returns public key by given ID.
  57. func GetGPGKeyByID(keyID int64) (*GPGKey, error) {
  58. key := new(GPGKey)
  59. has, err := x.ID(keyID).Get(key)
  60. if err != nil {
  61. return nil, err
  62. } else if !has {
  63. return nil, ErrGPGKeyNotExist{keyID}
  64. }
  65. return key, nil
  66. }
  67. // checkArmoredGPGKeyString checks if the given key string is a valid GPG armored key.
  68. // The function returns the actual public key on success
  69. func checkArmoredGPGKeyString(content string) (*openpgp.Entity, error) {
  70. list, err := openpgp.ReadArmoredKeyRing(strings.NewReader(content))
  71. if err != nil {
  72. return nil, ErrGPGKeyParsing{err}
  73. }
  74. return list[0], nil
  75. }
  76. //addGPGKey add key and subkeys to database
  77. func addGPGKey(e Engine, key *GPGKey) (err error) {
  78. // Save GPG primary key.
  79. if _, err = e.Insert(key); err != nil {
  80. return err
  81. }
  82. // Save GPG subs key.
  83. for _, subkey := range key.SubsKey {
  84. if err := addGPGKey(e, subkey); err != nil {
  85. return err
  86. }
  87. }
  88. return nil
  89. }
  90. // AddGPGKey adds new public key to database.
  91. func AddGPGKey(ownerID int64, content string) (*GPGKey, error) {
  92. ekey, err := checkArmoredGPGKeyString(content)
  93. if err != nil {
  94. return nil, err
  95. }
  96. // Key ID cannot be duplicated.
  97. has, err := x.Where("key_id=?", ekey.PrimaryKey.KeyIdString()).
  98. Get(new(GPGKey))
  99. if err != nil {
  100. return nil, err
  101. } else if has {
  102. return nil, ErrGPGKeyIDAlreadyUsed{ekey.PrimaryKey.KeyIdString()}
  103. }
  104. //Get DB session
  105. sess := x.NewSession()
  106. defer sess.Close()
  107. if err = sess.Begin(); err != nil {
  108. return nil, err
  109. }
  110. key, err := parseGPGKey(ownerID, ekey)
  111. if err != nil {
  112. return nil, err
  113. }
  114. if err = addGPGKey(sess, key); err != nil {
  115. return nil, err
  116. }
  117. return key, sess.Commit()
  118. }
  119. //base64EncPubKey encode public kay content to base 64
  120. func base64EncPubKey(pubkey *packet.PublicKey) (string, error) {
  121. var w bytes.Buffer
  122. err := pubkey.Serialize(&w)
  123. if err != nil {
  124. return "", err
  125. }
  126. return base64.StdEncoding.EncodeToString(w.Bytes()), nil
  127. }
  128. //parseSubGPGKey parse a sub Key
  129. func parseSubGPGKey(ownerID int64, primaryID string, pubkey *packet.PublicKey, expiry time.Time) (*GPGKey, error) {
  130. content, err := base64EncPubKey(pubkey)
  131. if err != nil {
  132. return nil, err
  133. }
  134. return &GPGKey{
  135. OwnerID: ownerID,
  136. KeyID: pubkey.KeyIdString(),
  137. PrimaryKeyID: primaryID,
  138. Content: content,
  139. CreatedUnix: util.TimeStamp(pubkey.CreationTime.Unix()),
  140. ExpiredUnix: util.TimeStamp(expiry.Unix()),
  141. CanSign: pubkey.CanSign(),
  142. CanEncryptComms: pubkey.PubKeyAlgo.CanEncrypt(),
  143. CanEncryptStorage: pubkey.PubKeyAlgo.CanEncrypt(),
  144. CanCertify: pubkey.PubKeyAlgo.CanSign(),
  145. }, nil
  146. }
  147. //parseGPGKey parse a PrimaryKey entity (primary key + subs keys + self-signature)
  148. func parseGPGKey(ownerID int64, e *openpgp.Entity) (*GPGKey, error) {
  149. pubkey := e.PrimaryKey
  150. //Extract self-sign for expire date based on : https://github.com/golang/crypto/blob/master/openpgp/keys.go#L165
  151. var selfSig *packet.Signature
  152. for _, ident := range e.Identities {
  153. if selfSig == nil {
  154. selfSig = ident.SelfSignature
  155. } else if ident.SelfSignature.IsPrimaryId != nil && *ident.SelfSignature.IsPrimaryId {
  156. selfSig = ident.SelfSignature
  157. break
  158. }
  159. }
  160. expiry := time.Time{}
  161. if selfSig.KeyLifetimeSecs != nil {
  162. expiry = selfSig.CreationTime.Add(time.Duration(*selfSig.KeyLifetimeSecs) * time.Second)
  163. }
  164. //Parse Subkeys
  165. subkeys := make([]*GPGKey, len(e.Subkeys))
  166. for i, k := range e.Subkeys {
  167. subs, err := parseSubGPGKey(ownerID, pubkey.KeyIdString(), k.PublicKey, expiry)
  168. if err != nil {
  169. return nil, err
  170. }
  171. subkeys[i] = subs
  172. }
  173. //Check emails
  174. userEmails, err := GetEmailAddresses(ownerID)
  175. if err != nil {
  176. return nil, err
  177. }
  178. emails := make([]*EmailAddress, 0, len(e.Identities))
  179. for _, ident := range e.Identities {
  180. email := strings.ToLower(strings.TrimSpace(ident.UserId.Email))
  181. for _, e := range userEmails {
  182. if e.Email == email {
  183. emails = append(emails, e)
  184. break
  185. }
  186. }
  187. }
  188. //In the case no email as been found
  189. if len(emails) == 0 {
  190. failedEmails := make([]string, 0, len(e.Identities))
  191. for _, ident := range e.Identities {
  192. failedEmails = append(failedEmails, ident.UserId.Email)
  193. }
  194. return nil, ErrGPGNoEmailFound{failedEmails}
  195. }
  196. content, err := base64EncPubKey(pubkey)
  197. if err != nil {
  198. return nil, err
  199. }
  200. return &GPGKey{
  201. OwnerID: ownerID,
  202. KeyID: pubkey.KeyIdString(),
  203. PrimaryKeyID: "",
  204. Content: content,
  205. CreatedUnix: util.TimeStamp(pubkey.CreationTime.Unix()),
  206. ExpiredUnix: util.TimeStamp(expiry.Unix()),
  207. Emails: emails,
  208. SubsKey: subkeys,
  209. CanSign: pubkey.CanSign(),
  210. CanEncryptComms: pubkey.PubKeyAlgo.CanEncrypt(),
  211. CanEncryptStorage: pubkey.PubKeyAlgo.CanEncrypt(),
  212. CanCertify: pubkey.PubKeyAlgo.CanSign(),
  213. }, nil
  214. }
  215. // deleteGPGKey does the actual key deletion
  216. func deleteGPGKey(e *xorm.Session, keyID string) (int64, error) {
  217. if keyID == "" {
  218. return 0, fmt.Errorf("empty KeyId forbidden") //Should never happen but just to be sure
  219. }
  220. return e.Where("key_id=?", keyID).Or("primary_key_id=?", keyID).Delete(new(GPGKey))
  221. }
  222. // DeleteGPGKey deletes GPG key information in database.
  223. func DeleteGPGKey(doer *User, id int64) (err error) {
  224. key, err := GetGPGKeyByID(id)
  225. if err != nil {
  226. if IsErrGPGKeyNotExist(err) {
  227. return nil
  228. }
  229. return fmt.Errorf("GetPublicKeyByID: %v", err)
  230. }
  231. // Check if user has access to delete this key.
  232. if !doer.IsAdmin && doer.ID != key.OwnerID {
  233. return ErrGPGKeyAccessDenied{doer.ID, key.ID}
  234. }
  235. sess := x.NewSession()
  236. defer sess.Close()
  237. if err = sess.Begin(); err != nil {
  238. return err
  239. }
  240. if _, err = deleteGPGKey(sess, key.KeyID); err != nil {
  241. return err
  242. }
  243. return sess.Commit()
  244. }
  245. // CommitVerification represents a commit validation of signature
  246. type CommitVerification struct {
  247. Verified bool
  248. Reason string
  249. SigningUser *User
  250. SigningKey *GPGKey
  251. }
  252. // SignCommit represents a commit with validation of signature.
  253. type SignCommit struct {
  254. Verification *CommitVerification
  255. *UserCommit
  256. }
  257. func readerFromBase64(s string) (io.Reader, error) {
  258. bs, err := base64.StdEncoding.DecodeString(s)
  259. if err != nil {
  260. return nil, err
  261. }
  262. return bytes.NewBuffer(bs), nil
  263. }
  264. func populateHash(hashFunc crypto.Hash, msg []byte) (hash.Hash, error) {
  265. h := hashFunc.New()
  266. if _, err := h.Write(msg); err != nil {
  267. return nil, err
  268. }
  269. return h, nil
  270. }
  271. // 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
  272. func readArmoredSign(r io.Reader) (body io.Reader, err error) {
  273. block, err := armor.Decode(r)
  274. if err != nil {
  275. return
  276. }
  277. if block.Type != openpgp.SignatureType {
  278. return nil, fmt.Errorf("expected '" + openpgp.SignatureType + "', got: " + block.Type)
  279. }
  280. return block.Body, nil
  281. }
  282. func extractSignature(s string) (*packet.Signature, error) {
  283. r, err := readArmoredSign(strings.NewReader(s))
  284. if err != nil {
  285. return nil, fmt.Errorf("Failed to read signature armor")
  286. }
  287. p, err := packet.Read(r)
  288. if err != nil {
  289. return nil, fmt.Errorf("Failed to read signature packet")
  290. }
  291. sig, ok := p.(*packet.Signature)
  292. if !ok {
  293. return nil, fmt.Errorf("Packet is not a signature")
  294. }
  295. return sig, nil
  296. }
  297. func verifySign(s *packet.Signature, h hash.Hash, k *GPGKey) error {
  298. //Check if key can sign
  299. if !k.CanSign {
  300. return fmt.Errorf("key can not sign")
  301. }
  302. //Decode key
  303. b, err := readerFromBase64(k.Content)
  304. if err != nil {
  305. return err
  306. }
  307. //Read key
  308. p, err := packet.Read(b)
  309. if err != nil {
  310. return err
  311. }
  312. //Check type
  313. pkey, ok := p.(*packet.PublicKey)
  314. if !ok {
  315. return fmt.Errorf("key is not a public key")
  316. }
  317. return pkey.VerifySignature(h, s)
  318. }
  319. // ParseCommitWithSignature check if signature is good against keystore.
  320. func ParseCommitWithSignature(c *git.Commit) *CommitVerification {
  321. if c.Signature != nil && c.Committer != nil {
  322. //Parsing signature
  323. sig, err := extractSignature(c.Signature.Signature)
  324. if err != nil { //Skipping failed to extract sign
  325. log.Error(3, "SignatureRead err: %v", err)
  326. return &CommitVerification{
  327. Verified: false,
  328. Reason: "gpg.error.extract_sign",
  329. }
  330. }
  331. //Find Committer account
  332. committer, err := GetUserByEmail(c.Committer.Email) //This find the user by primary email or activated email so commit will not be valid if email is not
  333. if err != nil { //Skipping not user for commiter
  334. // We can expect this to often be an ErrUserNotExist. in the case
  335. // it is not, however, it is important to log it.
  336. if !IsErrUserNotExist(err) {
  337. log.Error(3, "GetUserByEmail: %v", err)
  338. }
  339. return &CommitVerification{
  340. Verified: false,
  341. Reason: "gpg.error.no_committer_account",
  342. }
  343. }
  344. keys, err := ListGPGKeys(committer.ID)
  345. if err != nil { //Skipping failed to get gpg keys of user
  346. log.Error(3, "ListGPGKeys: %v", err)
  347. return &CommitVerification{
  348. Verified: false,
  349. Reason: "gpg.error.failed_retrieval_gpg_keys",
  350. }
  351. }
  352. for _, k := range keys {
  353. //Pre-check (& optimization) that emails attached to key can be attached to the commiter email and can validate
  354. canValidate := false
  355. lowerCommiterEmail := strings.ToLower(c.Committer.Email)
  356. for _, e := range k.Emails {
  357. if e.IsActivated && strings.ToLower(e.Email) == lowerCommiterEmail {
  358. canValidate = true
  359. break
  360. }
  361. }
  362. if !canValidate {
  363. continue //Skip this key
  364. }
  365. //Generating hash of commit
  366. hash, err := populateHash(sig.Hash, []byte(c.Signature.Payload))
  367. if err != nil { //Skipping ailed to generate hash
  368. log.Error(3, "PopulateHash: %v", err)
  369. return &CommitVerification{
  370. Verified: false,
  371. Reason: "gpg.error.generate_hash",
  372. }
  373. }
  374. //We get PK
  375. if err := verifySign(sig, hash, k); err == nil {
  376. return &CommitVerification{ //Everything is ok
  377. Verified: true,
  378. Reason: fmt.Sprintf("%s <%s> / %s", c.Committer.Name, c.Committer.Email, k.KeyID),
  379. SigningUser: committer,
  380. SigningKey: k,
  381. }
  382. }
  383. //And test also SubsKey
  384. for _, sk := range k.SubsKey {
  385. //Generating hash of commit
  386. hash, err := populateHash(sig.Hash, []byte(c.Signature.Payload))
  387. if err != nil { //Skipping ailed to generate hash
  388. log.Error(3, "PopulateHash: %v", err)
  389. return &CommitVerification{
  390. Verified: false,
  391. Reason: "gpg.error.generate_hash",
  392. }
  393. }
  394. if err := verifySign(sig, hash, sk); err == nil {
  395. return &CommitVerification{ //Everything is ok
  396. Verified: true,
  397. Reason: fmt.Sprintf("%s <%s> / %s", c.Committer.Name, c.Committer.Email, sk.KeyID),
  398. SigningUser: committer,
  399. SigningKey: sk,
  400. }
  401. }
  402. }
  403. }
  404. return &CommitVerification{ //Default at this stage
  405. Verified: false,
  406. Reason: "gpg.error.no_gpg_keys_found",
  407. }
  408. }
  409. return &CommitVerification{
  410. Verified: false, //Default value
  411. Reason: "gpg.error.not_signed_commit", //Default value
  412. }
  413. }
  414. // ParseCommitsWithSignature checks if signaute of commits are corresponding to users gpg keys.
  415. func ParseCommitsWithSignature(oldCommits *list.List) *list.List {
  416. var (
  417. newCommits = list.New()
  418. e = oldCommits.Front()
  419. )
  420. for e != nil {
  421. c := e.Value.(UserCommit)
  422. newCommits.PushBack(SignCommit{
  423. UserCommit: &c,
  424. Verification: ParseCommitWithSignature(c.Commit),
  425. })
  426. e = e.Next()
  427. }
  428. return newCommits
  429. }