Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

gpg_key.go 13KB

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