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.

gpg_key.go 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package asymkey
  4. import (
  5. "context"
  6. "fmt"
  7. "strings"
  8. "time"
  9. "code.gitea.io/gitea/models/db"
  10. user_model "code.gitea.io/gitea/models/user"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/timeutil"
  13. "github.com/keybase/go-crypto/openpgp"
  14. "github.com/keybase/go-crypto/openpgp/packet"
  15. "xorm.io/xorm"
  16. )
  17. // __________________ ________ ____ __.
  18. // / _____/\______ \/ _____/ | |/ _|____ ___.__.
  19. // / \ ___ | ___/ \ ___ | <_/ __ < | |
  20. // \ \_\ \| | \ \_\ \ | | \ ___/\___ |
  21. // \______ /|____| \______ / |____|__ \___ > ____|
  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:"MEDIUMTEXT NOT NULL"`
  30. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  31. ExpiredUnix timeutil.TimeStamp
  32. AddedUnix timeutil.TimeStamp
  33. SubsKey []*GPGKey `xorm:"-"`
  34. Emails []*user_model.EmailAddress
  35. Verified bool `xorm:"NOT NULL DEFAULT false"`
  36. CanSign bool
  37. CanEncryptComms bool
  38. CanEncryptStorage bool
  39. CanCertify bool
  40. }
  41. func init() {
  42. db.RegisterModel(new(GPGKey))
  43. }
  44. // BeforeInsert will be invoked by XORM before inserting a record
  45. func (key *GPGKey) BeforeInsert() {
  46. key.AddedUnix = timeutil.TimeStampNow()
  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. err := session.Where("primary_key_id=?", key.KeyID).Find(&key.SubsKey)
  51. if err != nil {
  52. log.Error("Find Sub GPGkeys[%s]: %v", key.KeyID, err)
  53. }
  54. }
  55. // PaddedKeyID show KeyID padded to 16 characters
  56. func (key *GPGKey) PaddedKeyID() string {
  57. return PaddedKeyID(key.KeyID)
  58. }
  59. // PaddedKeyID show KeyID padded to 16 characters
  60. func PaddedKeyID(keyID string) string {
  61. if len(keyID) > 15 {
  62. return keyID
  63. }
  64. zeros := "0000000000000000"
  65. return zeros[0:16-len(keyID)] + keyID
  66. }
  67. // ListGPGKeys returns a list of public keys belongs to given user.
  68. func ListGPGKeys(ctx context.Context, uid int64, listOptions db.ListOptions) ([]*GPGKey, error) {
  69. sess := db.GetEngine(ctx).Table(&GPGKey{}).Where("owner_id=? AND primary_key_id=''", uid)
  70. if listOptions.Page != 0 {
  71. sess = db.SetSessionPagination(sess, &listOptions)
  72. }
  73. keys := make([]*GPGKey, 0, 2)
  74. return keys, sess.Find(&keys)
  75. }
  76. // CountUserGPGKeys return number of gpg keys a user own
  77. func CountUserGPGKeys(ctx context.Context, userID int64) (int64, error) {
  78. return db.GetEngine(ctx).Where("owner_id=? AND primary_key_id=''", userID).Count(&GPGKey{})
  79. }
  80. func GetGPGKeyForUserByID(ctx context.Context, ownerID, keyID int64) (*GPGKey, error) {
  81. key := new(GPGKey)
  82. has, err := db.GetEngine(ctx).Where("id=? AND owner_id=?", keyID, ownerID).Get(key)
  83. if err != nil {
  84. return nil, err
  85. } else if !has {
  86. return nil, ErrGPGKeyNotExist{keyID}
  87. }
  88. return key, nil
  89. }
  90. // GetGPGKeysByKeyID returns public key by given ID.
  91. func GetGPGKeysByKeyID(ctx context.Context, keyID string) ([]*GPGKey, error) {
  92. keys := make([]*GPGKey, 0, 1)
  93. return keys, db.GetEngine(ctx).Where("key_id=?", keyID).Find(&keys)
  94. }
  95. // GPGKeyToEntity retrieve the imported key and the traducted entity
  96. func GPGKeyToEntity(k *GPGKey) (*openpgp.Entity, error) {
  97. impKey, err := GetGPGImportByKeyID(k.KeyID)
  98. if err != nil {
  99. return nil, err
  100. }
  101. keys, err := checkArmoredGPGKeyString(impKey.Content)
  102. if err != nil {
  103. return nil, err
  104. }
  105. return keys[0], err
  106. }
  107. // parseSubGPGKey parse a sub Key
  108. func parseSubGPGKey(ownerID int64, primaryID string, pubkey *packet.PublicKey, expiry time.Time) (*GPGKey, error) {
  109. content, err := base64EncPubKey(pubkey)
  110. if err != nil {
  111. return nil, err
  112. }
  113. return &GPGKey{
  114. OwnerID: ownerID,
  115. KeyID: pubkey.KeyIdString(),
  116. PrimaryKeyID: primaryID,
  117. Content: content,
  118. CreatedUnix: timeutil.TimeStamp(pubkey.CreationTime.Unix()),
  119. ExpiredUnix: timeutil.TimeStamp(expiry.Unix()),
  120. CanSign: pubkey.CanSign(),
  121. CanEncryptComms: pubkey.PubKeyAlgo.CanEncrypt(),
  122. CanEncryptStorage: pubkey.PubKeyAlgo.CanEncrypt(),
  123. CanCertify: pubkey.PubKeyAlgo.CanSign(),
  124. }, nil
  125. }
  126. // parseGPGKey parse a PrimaryKey entity (primary key + subs keys + self-signature)
  127. func parseGPGKey(ctx context.Context, ownerID int64, e *openpgp.Entity, verified bool) (*GPGKey, error) {
  128. pubkey := e.PrimaryKey
  129. expiry := getExpiryTime(e)
  130. // Parse Subkeys
  131. subkeys := make([]*GPGKey, len(e.Subkeys))
  132. for i, k := range e.Subkeys {
  133. subs, err := parseSubGPGKey(ownerID, pubkey.KeyIdString(), k.PublicKey, expiry)
  134. if err != nil {
  135. return nil, ErrGPGKeyParsing{ParseError: err}
  136. }
  137. subkeys[i] = subs
  138. }
  139. // Check emails
  140. userEmails, err := user_model.GetEmailAddresses(ctx, ownerID)
  141. if err != nil {
  142. return nil, err
  143. }
  144. emails := make([]*user_model.EmailAddress, 0, len(e.Identities))
  145. for _, ident := range e.Identities {
  146. if ident.Revocation != nil {
  147. continue
  148. }
  149. email := strings.ToLower(strings.TrimSpace(ident.UserId.Email))
  150. for _, e := range userEmails {
  151. if e.IsActivated && e.LowerEmail == email {
  152. emails = append(emails, e)
  153. break
  154. }
  155. }
  156. }
  157. if !verified {
  158. // In the case no email as been found
  159. if len(emails) == 0 {
  160. failedEmails := make([]string, 0, len(e.Identities))
  161. for _, ident := range e.Identities {
  162. failedEmails = append(failedEmails, ident.UserId.Email)
  163. }
  164. return nil, ErrGPGNoEmailFound{failedEmails, e.PrimaryKey.KeyIdString()}
  165. }
  166. }
  167. content, err := base64EncPubKey(pubkey)
  168. if err != nil {
  169. return nil, err
  170. }
  171. return &GPGKey{
  172. OwnerID: ownerID,
  173. KeyID: pubkey.KeyIdString(),
  174. PrimaryKeyID: "",
  175. Content: content,
  176. CreatedUnix: timeutil.TimeStamp(pubkey.CreationTime.Unix()),
  177. ExpiredUnix: timeutil.TimeStamp(expiry.Unix()),
  178. Emails: emails,
  179. SubsKey: subkeys,
  180. Verified: verified,
  181. CanSign: pubkey.CanSign(),
  182. CanEncryptComms: pubkey.PubKeyAlgo.CanEncrypt(),
  183. CanEncryptStorage: pubkey.PubKeyAlgo.CanEncrypt(),
  184. CanCertify: pubkey.PubKeyAlgo.CanSign(),
  185. }, nil
  186. }
  187. // deleteGPGKey does the actual key deletion
  188. func deleteGPGKey(ctx context.Context, keyID string) (int64, error) {
  189. if keyID == "" {
  190. return 0, fmt.Errorf("empty KeyId forbidden") // Should never happen but just to be sure
  191. }
  192. // Delete imported key
  193. n, err := db.GetEngine(ctx).Where("key_id=?", keyID).Delete(new(GPGKeyImport))
  194. if err != nil {
  195. return n, err
  196. }
  197. return db.GetEngine(ctx).Where("key_id=?", keyID).Or("primary_key_id=?", keyID).Delete(new(GPGKey))
  198. }
  199. // DeleteGPGKey deletes GPG key information in database.
  200. func DeleteGPGKey(ctx context.Context, doer *user_model.User, id int64) (err error) {
  201. key, err := GetGPGKeyForUserByID(ctx, doer.ID, id)
  202. if err != nil {
  203. if IsErrGPGKeyNotExist(err) {
  204. return nil
  205. }
  206. return fmt.Errorf("GetPublicKeyByID: %w", err)
  207. }
  208. ctx, committer, err := db.TxContext(ctx)
  209. if err != nil {
  210. return err
  211. }
  212. defer committer.Close()
  213. if _, err = deleteGPGKey(ctx, key.KeyID); err != nil {
  214. return err
  215. }
  216. return committer.Commit()
  217. }
  218. func checkKeyEmails(ctx context.Context, email string, keys ...*GPGKey) (bool, string) {
  219. uid := int64(0)
  220. var userEmails []*user_model.EmailAddress
  221. var user *user_model.User
  222. for _, key := range keys {
  223. for _, e := range key.Emails {
  224. if e.IsActivated && (email == "" || strings.EqualFold(e.Email, email)) {
  225. return true, e.Email
  226. }
  227. }
  228. if key.Verified && key.OwnerID != 0 {
  229. if uid != key.OwnerID {
  230. userEmails, _ = user_model.GetEmailAddresses(ctx, key.OwnerID)
  231. uid = key.OwnerID
  232. user = &user_model.User{ID: uid}
  233. _, _ = user_model.GetUser(ctx, user)
  234. }
  235. for _, e := range userEmails {
  236. if e.IsActivated && (email == "" || strings.EqualFold(e.Email, email)) {
  237. return true, e.Email
  238. }
  239. }
  240. if user.KeepEmailPrivate && strings.EqualFold(email, user.GetEmail()) {
  241. return true, user.GetEmail()
  242. }
  243. }
  244. }
  245. return false, email
  246. }