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.

469 lines
12 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. "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, len(e.Identities))
  189. n := 0
  190. for _, ident := range e.Identities {
  191. email := strings.ToLower(strings.TrimSpace(ident.UserId.Email))
  192. for _, e := range userEmails {
  193. if e.Email == email && e.IsActivated {
  194. emails[n] = e
  195. break
  196. }
  197. }
  198. if emails[n] == nil {
  199. return nil, ErrGPGEmailNotFound{ident.UserId.Email}
  200. }
  201. n++
  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. if err = sess.Commit(); err != nil {
  251. return err
  252. }
  253. return nil
  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)
  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. //Generating hash of commit
  360. hash, err := populateHash(sig.Hash, []byte(c.Signature.Payload))
  361. if err != nil { //Skipping ailed to generate hash
  362. log.Error(3, "PopulateHash: %v", err)
  363. return &CommitVerification{
  364. Verified: false,
  365. Reason: "gpg.error.generate_hash",
  366. }
  367. }
  368. //We get PK
  369. if err := verifySign(sig, hash, k); err == nil {
  370. return &CommitVerification{ //Everything is ok
  371. Verified: true,
  372. Reason: fmt.Sprintf("%s <%s> / %s", c.Committer.Name, c.Committer.Email, k.KeyID),
  373. SigningUser: committer,
  374. SigningKey: k,
  375. }
  376. }
  377. //And test also SubsKey
  378. for _, sk := range k.SubsKey {
  379. //Generating hash of commit
  380. hash, err := populateHash(sig.Hash, []byte(c.Signature.Payload))
  381. if err != nil { //Skipping ailed to generate hash
  382. log.Error(3, "PopulateHash: %v", err)
  383. return &CommitVerification{
  384. Verified: false,
  385. Reason: "gpg.error.generate_hash",
  386. }
  387. }
  388. if err := verifySign(sig, hash, sk); err == nil {
  389. return &CommitVerification{ //Everything is ok
  390. Verified: true,
  391. Reason: fmt.Sprintf("%s <%s> / %s", c.Committer.Name, c.Committer.Email, sk.KeyID),
  392. SigningUser: committer,
  393. SigningKey: sk,
  394. }
  395. }
  396. }
  397. }
  398. return &CommitVerification{ //Default at this stage
  399. Verified: false,
  400. Reason: "gpg.error.no_gpg_keys_found",
  401. }
  402. }
  403. return &CommitVerification{
  404. Verified: false, //Default value
  405. Reason: "gpg.error.not_signed_commit", //Default value
  406. }
  407. }
  408. // ParseCommitsWithSignature checks if signaute of commits are corresponding to users gpg keys.
  409. func ParseCommitsWithSignature(oldCommits *list.List) *list.List {
  410. var (
  411. newCommits = list.New()
  412. e = oldCommits.Front()
  413. )
  414. for e != nil {
  415. c := e.Value.(UserCommit)
  416. newCommits.PushBack(SignCommit{
  417. UserCommit: &c,
  418. Verification: ParseCommitWithSignature(c.Commit),
  419. })
  420. e = e.Next()
  421. }
  422. return newCommits
  423. }