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

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