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 7.9KB

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