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.

471 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. "golang.org/x/crypto/openpgp"
  19. "golang.org/x/crypto/openpgp/armor"
  20. "golang.org/x/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 sessionRelease(sess)
  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. for _, e := range userEmails {
  192. if e.Email == ident.UserId.Email && e.IsActivated {
  193. emails[n] = e
  194. break
  195. }
  196. }
  197. if emails[n] == nil {
  198. return nil, ErrGPGEmailNotFound{ident.UserId.Email}
  199. }
  200. n++
  201. }
  202. content, err := base64EncPubKey(pubkey)
  203. if err != nil {
  204. return nil, err
  205. }
  206. return &GPGKey{
  207. OwnerID: ownerID,
  208. KeyID: pubkey.KeyIdString(),
  209. PrimaryKeyID: "",
  210. Content: content,
  211. Created: pubkey.CreationTime,
  212. Expired: expiry,
  213. Emails: emails,
  214. SubsKey: subkeys,
  215. CanSign: pubkey.CanSign(),
  216. CanEncryptComms: pubkey.PubKeyAlgo.CanEncrypt(),
  217. CanEncryptStorage: pubkey.PubKeyAlgo.CanEncrypt(),
  218. CanCertify: pubkey.PubKeyAlgo.CanSign(),
  219. }, nil
  220. }
  221. // deleteGPGKey does the actual key deletion
  222. func deleteGPGKey(e *xorm.Session, keyID string) (int64, error) {
  223. if keyID == "" {
  224. return 0, fmt.Errorf("empty KeyId forbidden") //Should never happen but just to be sure
  225. }
  226. return e.Where("key_id=?", keyID).Or("primary_key_id=?", keyID).Delete(new(GPGKey))
  227. }
  228. // DeleteGPGKey deletes GPG key information in database.
  229. func DeleteGPGKey(doer *User, id int64) (err error) {
  230. key, err := GetGPGKeyByID(id)
  231. if err != nil {
  232. if IsErrGPGKeyNotExist(err) {
  233. return nil
  234. }
  235. return fmt.Errorf("GetPublicKeyByID: %v", err)
  236. }
  237. // Check if user has access to delete this key.
  238. if !doer.IsAdmin && doer.ID != key.OwnerID {
  239. return ErrGPGKeyAccessDenied{doer.ID, key.ID}
  240. }
  241. sess := x.NewSession()
  242. defer sessionRelease(sess)
  243. if err = sess.Begin(); err != nil {
  244. return err
  245. }
  246. if _, err = deleteGPGKey(sess, key.KeyID); err != nil {
  247. return err
  248. }
  249. if err = sess.Commit(); err != nil {
  250. return err
  251. }
  252. return nil
  253. }
  254. // CommitVerification represents a commit validation of signature
  255. type CommitVerification struct {
  256. Verified bool
  257. Reason string
  258. SigningUser *User
  259. SigningKey *GPGKey
  260. }
  261. // SignCommit represents a commit with validation of signature.
  262. type SignCommit struct {
  263. Verification *CommitVerification
  264. *UserCommit
  265. }
  266. func readerFromBase64(s string) (io.Reader, error) {
  267. bs, err := base64.StdEncoding.DecodeString(s)
  268. if err != nil {
  269. return nil, err
  270. }
  271. return bytes.NewBuffer(bs), nil
  272. }
  273. func populateHash(hashFunc crypto.Hash, msg []byte) (hash.Hash, error) {
  274. h := hashFunc.New()
  275. if _, err := h.Write(msg); err != nil {
  276. return nil, err
  277. }
  278. return h, nil
  279. }
  280. // 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
  281. func readArmoredSign(r io.Reader) (body io.Reader, err error) {
  282. block, err := armor.Decode(r)
  283. if err != nil {
  284. return
  285. }
  286. if block.Type != openpgp.SignatureType {
  287. return nil, fmt.Errorf("expected '" + openpgp.SignatureType + "', got: " + block.Type)
  288. }
  289. return block.Body, nil
  290. }
  291. func extractSignature(s string) (*packet.Signature, error) {
  292. r, err := readArmoredSign(strings.NewReader(s))
  293. if err != nil {
  294. return nil, fmt.Errorf("Failed to read signature armor")
  295. }
  296. p, err := packet.Read(r)
  297. if err != nil {
  298. return nil, fmt.Errorf("Failed to read signature packet")
  299. }
  300. sig, ok := p.(*packet.Signature)
  301. if !ok {
  302. return nil, fmt.Errorf("Packet is not a signature")
  303. }
  304. return sig, nil
  305. }
  306. func verifySign(s *packet.Signature, h hash.Hash, k *GPGKey) error {
  307. //Check if key can sign
  308. if !k.CanSign {
  309. return fmt.Errorf("key can not sign")
  310. }
  311. //Decode key
  312. b, err := readerFromBase64(k.Content)
  313. if err != nil {
  314. return err
  315. }
  316. //Read key
  317. p, err := packet.Read(b)
  318. if err != nil {
  319. return err
  320. }
  321. //Check type
  322. pkey, ok := p.(*packet.PublicKey)
  323. if !ok {
  324. return fmt.Errorf("key is not a public key")
  325. }
  326. return pkey.VerifySignature(h, s)
  327. }
  328. // ParseCommitWithSignature check if signature is good against keystore.
  329. func ParseCommitWithSignature(c *git.Commit) *CommitVerification {
  330. if c.Signature != nil {
  331. //Parsing signature
  332. sig, err := extractSignature(c.Signature.Signature)
  333. if err != nil { //Skipping failed to extract sign
  334. log.Error(3, "SignatureRead err: %v", err)
  335. return &CommitVerification{
  336. Verified: false,
  337. Reason: "gpg.error.extract_sign",
  338. }
  339. }
  340. //Find Committer account
  341. committer, err := GetUserByEmail(c.Committer.Email)
  342. if err != nil { //Skipping not user for commiter
  343. log.Error(3, "NoCommitterAccount: %v", err)
  344. return &CommitVerification{
  345. Verified: false,
  346. Reason: "gpg.error.no_committer_account",
  347. }
  348. }
  349. keys, err := ListGPGKeys(committer.ID)
  350. if err != nil || len(keys) == 0 { //Skipping failed to get gpg keys of user
  351. log.Error(3, "ListGPGKeys: %v", err)
  352. return &CommitVerification{
  353. Verified: false,
  354. Reason: "gpg.error.failed_retrieval_gpg_keys",
  355. }
  356. }
  357. for _, k := range keys {
  358. //Generating hash of commit
  359. hash, err := populateHash(sig.Hash, []byte(c.Signature.Payload))
  360. if err != nil { //Skipping ailed to generate hash
  361. log.Error(3, "PopulateHash: %v", err)
  362. return &CommitVerification{
  363. Verified: false,
  364. Reason: "gpg.error.generate_hash",
  365. }
  366. }
  367. //We get PK
  368. if err := verifySign(sig, hash, k); err == nil {
  369. return &CommitVerification{ //Everything is ok
  370. Verified: true,
  371. Reason: fmt.Sprintf("%s <%s> / %s", c.Committer.Name, c.Committer.Email, k.KeyID),
  372. SigningUser: committer,
  373. SigningKey: k,
  374. }
  375. }
  376. //And test also SubsKey
  377. for _, sk := range k.SubsKey {
  378. //Generating hash of commit
  379. hash, err := populateHash(sig.Hash, []byte(c.Signature.Payload))
  380. if err != nil { //Skipping ailed to generate hash
  381. log.Error(3, "PopulateHash: %v", err)
  382. return &CommitVerification{
  383. Verified: false,
  384. Reason: "gpg.error.generate_hash",
  385. }
  386. }
  387. if err := verifySign(sig, hash, sk); err == nil {
  388. return &CommitVerification{ //Everything is ok
  389. Verified: true,
  390. Reason: fmt.Sprintf("%s <%s> / %s", c.Committer.Name, c.Committer.Email, sk.KeyID),
  391. SigningUser: committer,
  392. SigningKey: sk,
  393. }
  394. }
  395. }
  396. }
  397. return &CommitVerification{ //Default at this stage
  398. Verified: false,
  399. Reason: "gpg.error.no_gpg_keys_found",
  400. }
  401. }
  402. return &CommitVerification{
  403. Verified: false, //Default value
  404. Reason: "gpg.error.not_signed_commit", //Default value
  405. }
  406. }
  407. // ParseCommitsWithSignature checks if signaute of commits are corresponding to users gpg keys.
  408. func ParseCommitsWithSignature(oldCommits *list.List) *list.List {
  409. var (
  410. newCommits = list.New()
  411. e = oldCommits.Front()
  412. )
  413. for e != nil {
  414. c := e.Value.(UserCommit)
  415. newCommits.PushBack(SignCommit{
  416. UserCommit: &c,
  417. Verification: ParseCommitWithSignature(c.Commit),
  418. })
  419. e = e.Next()
  420. }
  421. return newCommits
  422. }