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.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. // GetGPGKeyByID returns public key by given ID.
  81. func GetGPGKeyByID(ctx context.Context, keyID int64) (*GPGKey, error) {
  82. key := new(GPGKey)
  83. has, err := db.GetEngine(ctx).ID(keyID).Get(key)
  84. if err != nil {
  85. return nil, err
  86. } else if !has {
  87. return nil, ErrGPGKeyNotExist{keyID}
  88. }
  89. return key, nil
  90. }
  91. // GetGPGKeysByKeyID returns public key by given ID.
  92. func GetGPGKeysByKeyID(ctx context.Context, keyID string) ([]*GPGKey, error) {
  93. keys := make([]*GPGKey, 0, 1)
  94. return keys, db.GetEngine(ctx).Where("key_id=?", keyID).Find(&keys)
  95. }
  96. // GPGKeyToEntity retrieve the imported key and the traducted entity
  97. func GPGKeyToEntity(k *GPGKey) (*openpgp.Entity, error) {
  98. impKey, err := GetGPGImportByKeyID(k.KeyID)
  99. if err != nil {
  100. return nil, err
  101. }
  102. keys, err := checkArmoredGPGKeyString(impKey.Content)
  103. if err != nil {
  104. return nil, err
  105. }
  106. return keys[0], err
  107. }
  108. // parseSubGPGKey parse a sub Key
  109. func parseSubGPGKey(ownerID int64, primaryID string, pubkey *packet.PublicKey, expiry time.Time) (*GPGKey, error) {
  110. content, err := base64EncPubKey(pubkey)
  111. if err != nil {
  112. return nil, err
  113. }
  114. return &GPGKey{
  115. OwnerID: ownerID,
  116. KeyID: pubkey.KeyIdString(),
  117. PrimaryKeyID: primaryID,
  118. Content: content,
  119. CreatedUnix: timeutil.TimeStamp(pubkey.CreationTime.Unix()),
  120. ExpiredUnix: timeutil.TimeStamp(expiry.Unix()),
  121. CanSign: pubkey.CanSign(),
  122. CanEncryptComms: pubkey.PubKeyAlgo.CanEncrypt(),
  123. CanEncryptStorage: pubkey.PubKeyAlgo.CanEncrypt(),
  124. CanCertify: pubkey.PubKeyAlgo.CanSign(),
  125. }, nil
  126. }
  127. // parseGPGKey parse a PrimaryKey entity (primary key + subs keys + self-signature)
  128. func parseGPGKey(ctx context.Context, ownerID int64, e *openpgp.Entity, verified bool) (*GPGKey, error) {
  129. pubkey := e.PrimaryKey
  130. expiry := getExpiryTime(e)
  131. // Parse Subkeys
  132. subkeys := make([]*GPGKey, len(e.Subkeys))
  133. for i, k := range e.Subkeys {
  134. subs, err := parseSubGPGKey(ownerID, pubkey.KeyIdString(), k.PublicKey, expiry)
  135. if err != nil {
  136. return nil, ErrGPGKeyParsing{ParseError: err}
  137. }
  138. subkeys[i] = subs
  139. }
  140. // Check emails
  141. userEmails, err := user_model.GetEmailAddresses(ctx, ownerID)
  142. if err != nil {
  143. return nil, err
  144. }
  145. emails := make([]*user_model.EmailAddress, 0, len(e.Identities))
  146. for _, ident := range e.Identities {
  147. if ident.Revocation != nil {
  148. continue
  149. }
  150. email := strings.ToLower(strings.TrimSpace(ident.UserId.Email))
  151. for _, e := range userEmails {
  152. if e.IsActivated && e.LowerEmail == email {
  153. emails = append(emails, e)
  154. break
  155. }
  156. }
  157. }
  158. if !verified {
  159. // In the case no email as been found
  160. if len(emails) == 0 {
  161. failedEmails := make([]string, 0, len(e.Identities))
  162. for _, ident := range e.Identities {
  163. failedEmails = append(failedEmails, ident.UserId.Email)
  164. }
  165. return nil, ErrGPGNoEmailFound{failedEmails, e.PrimaryKey.KeyIdString()}
  166. }
  167. }
  168. content, err := base64EncPubKey(pubkey)
  169. if err != nil {
  170. return nil, err
  171. }
  172. return &GPGKey{
  173. OwnerID: ownerID,
  174. KeyID: pubkey.KeyIdString(),
  175. PrimaryKeyID: "",
  176. Content: content,
  177. CreatedUnix: timeutil.TimeStamp(pubkey.CreationTime.Unix()),
  178. ExpiredUnix: timeutil.TimeStamp(expiry.Unix()),
  179. Emails: emails,
  180. SubsKey: subkeys,
  181. Verified: verified,
  182. CanSign: pubkey.CanSign(),
  183. CanEncryptComms: pubkey.PubKeyAlgo.CanEncrypt(),
  184. CanEncryptStorage: pubkey.PubKeyAlgo.CanEncrypt(),
  185. CanCertify: pubkey.PubKeyAlgo.CanSign(),
  186. }, nil
  187. }
  188. // deleteGPGKey does the actual key deletion
  189. func deleteGPGKey(ctx context.Context, keyID string) (int64, error) {
  190. if keyID == "" {
  191. return 0, fmt.Errorf("empty KeyId forbidden") // Should never happen but just to be sure
  192. }
  193. // Delete imported key
  194. n, err := db.GetEngine(ctx).Where("key_id=?", keyID).Delete(new(GPGKeyImport))
  195. if err != nil {
  196. return n, err
  197. }
  198. return db.GetEngine(ctx).Where("key_id=?", keyID).Or("primary_key_id=?", keyID).Delete(new(GPGKey))
  199. }
  200. // DeleteGPGKey deletes GPG key information in database.
  201. func DeleteGPGKey(ctx context.Context, doer *user_model.User, id int64) (err error) {
  202. key, err := GetGPGKeyByID(ctx, id)
  203. if err != nil {
  204. if IsErrGPGKeyNotExist(err) {
  205. return nil
  206. }
  207. return fmt.Errorf("GetPublicKeyByID: %w", err)
  208. }
  209. // Check if user has access to delete this key.
  210. if !doer.IsAdmin && doer.ID != key.OwnerID {
  211. return ErrGPGKeyAccessDenied{doer.ID, key.ID}
  212. }
  213. ctx, committer, err := db.TxContext(ctx)
  214. if err != nil {
  215. return err
  216. }
  217. defer committer.Close()
  218. if _, err = deleteGPGKey(ctx, key.KeyID); err != nil {
  219. return err
  220. }
  221. return committer.Commit()
  222. }
  223. func checkKeyEmails(ctx context.Context, email string, keys ...*GPGKey) (bool, string) {
  224. uid := int64(0)
  225. var userEmails []*user_model.EmailAddress
  226. var user *user_model.User
  227. for _, key := range keys {
  228. for _, e := range key.Emails {
  229. if e.IsActivated && (email == "" || strings.EqualFold(e.Email, email)) {
  230. return true, e.Email
  231. }
  232. }
  233. if key.Verified && key.OwnerID != 0 {
  234. if uid != key.OwnerID {
  235. userEmails, _ = user_model.GetEmailAddresses(ctx, key.OwnerID)
  236. uid = key.OwnerID
  237. user = &user_model.User{ID: uid}
  238. _, _ = user_model.GetUser(ctx, user)
  239. }
  240. for _, e := range userEmails {
  241. if e.IsActivated && (email == "" || strings.EqualFold(e.Email, email)) {
  242. return true, e.Email
  243. }
  244. }
  245. if user.KeepEmailPrivate && strings.EqualFold(email, user.GetEmail()) {
  246. return true, user.GetEmail()
  247. }
  248. }
  249. }
  250. return false, email
  251. }