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

gpg_key.go 13KB

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