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

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