refactor: refactor pgp implementation

This commit refactors the internal PGP implementation to make way for
GPG integration.

Signed-off-by: Tim Culverhouse <tim@timculverhouse.com>
Acked-by: Koni Marti <koni.marti@gmail.com>
Acked-by: Robin Jarry <robin@jarry.cc>
This commit is contained in:
Tim Culverhouse 2022-04-25 08:30:43 -05:00 committed by Robin Jarry
parent afe35839ed
commit d09636ee0b
15 changed files with 356 additions and 193 deletions

11
aerc.go
View file

@ -22,6 +22,7 @@ import (
"git.sr.ht/~rjarry/aerc/commands/terminal" "git.sr.ht/~rjarry/aerc/commands/terminal"
"git.sr.ht/~rjarry/aerc/config" "git.sr.ht/~rjarry/aerc/config"
"git.sr.ht/~rjarry/aerc/lib" "git.sr.ht/~rjarry/aerc/lib"
"git.sr.ht/~rjarry/aerc/lib/crypto"
"git.sr.ht/~rjarry/aerc/lib/templates" "git.sr.ht/~rjarry/aerc/lib/templates"
libui "git.sr.ht/~rjarry/aerc/lib/ui" libui "git.sr.ht/~rjarry/aerc/lib/ui"
"git.sr.ht/~rjarry/aerc/logging" "git.sr.ht/~rjarry/aerc/logging"
@ -168,7 +169,11 @@ func main() {
deferLoop := make(chan struct{}) deferLoop := make(chan struct{})
aerc = widgets.NewAerc(conf, logger, func(cmd []string) error { c := crypto.New(conf.General.PgpProvider)
c.Init(logger)
defer c.Close()
aerc = widgets.NewAerc(conf, logger, c, func(cmd []string) error {
return execCommand(aerc, ui, cmd) return execCommand(aerc, ui, cmd)
}, func(cmd string) []string { }, func(cmd string) []string {
return getCompletions(aerc, cmd) return getCompletions(aerc, cmd)
@ -188,10 +193,6 @@ func main() {
ui.EnableMouse() ui.EnableMouse()
} }
logger.Println("Initializing PGP keyring")
lib.InitKeyring()
defer lib.UnlockKeyring()
logger.Println("Starting Unix server") logger.Println("Starting Unix server")
as, err := lib.StartServer(logger) as, err := lib.StartServer(logger)
if err != nil { if err != nil {

View file

@ -45,7 +45,7 @@ func (ViewMessage) Execute(aerc *widgets.Aerc, args []string) error {
aerc.PushError(msg.Error.Error()) aerc.PushError(msg.Error.Error())
return nil return nil
} }
lib.NewMessageStoreView(msg, store, aerc.DecryptKeys, lib.NewMessageStoreView(msg, store, aerc.Crypto, aerc.DecryptKeys,
func(view lib.MessageView, err error) { func(view lib.MessageView, err error) {
if err != nil { if err != nil {
aerc.PushError(err.Error()) aerc.PushError(err.Error())

View file

@ -68,7 +68,7 @@ func (Delete) Execute(aerc *widgets.Aerc, args []string) error {
acct.Messages().Invalidate() acct.Messages().Invalidate()
return nil return nil
} }
lib.NewMessageStoreView(next, store, aerc.DecryptKeys, lib.NewMessageStoreView(next, store, aerc.Crypto, aerc.DecryptKeys,
func(view lib.MessageView, err error) { func(view lib.MessageView, err error) {
if err != nil { if err != nil {
aerc.PushError(err.Error()) aerc.PushError(err.Error())

View file

@ -42,7 +42,7 @@ func (NextPrevMsg) Execute(aerc *widgets.Aerc, args []string) error {
aerc.RemoveTab(mv) aerc.RemoveTab(mv)
return nil return nil
} }
lib.NewMessageStoreView(nextMsg, store, aerc.DecryptKeys, lib.NewMessageStoreView(nextMsg, store, aerc.Crypto, aerc.DecryptKeys,
func(view lib.MessageView, err error) { func(view lib.MessageView, err error) {
if err != nil { if err != nil {
aerc.PushError(err.Error()) aerc.PushError(err.Error())

View file

@ -27,6 +27,7 @@ import (
type GeneralConfig struct { type GeneralConfig struct {
DefaultSavePath string `ini:"default-save-path"` DefaultSavePath string `ini:"default-save-path"`
PgpProvider string `ini:"pgp-provider"`
UnsafeAccountsConf bool `ini:"unsafe-accounts-conf"` UnsafeAccountsConf bool `ini:"unsafe-accounts-conf"`
} }
@ -579,6 +580,21 @@ func validateBorderChars(section *ini.Section, config *UIConfig) error {
return nil return nil
} }
func validatePgpProvider(section *ini.Section) error {
m := map[string]bool{
"internal": true,
}
for key, val := range section.KeysHash() {
switch key {
case "pgp-provider":
if !m[strings.ToLower(val)] {
return fmt.Errorf("%v must be 'internal'", key)
}
}
}
return nil
}
func LoadConfigFromFile(root *string, logger *log.Logger) (*AercConfig, error) { func LoadConfigFromFile(root *string, logger *log.Logger) (*AercConfig, error) {
if root == nil { if root == nil {
_root := path.Join(xdg.ConfigHome(), "aerc") _root := path.Join(xdg.ConfigHome(), "aerc")
@ -618,6 +634,7 @@ func LoadConfigFromFile(root *string, logger *log.Logger) (*AercConfig, error) {
Ini: file, Ini: file,
General: GeneralConfig{ General: GeneralConfig{
PgpProvider: "internal",
UnsafeAccountsConf: false, UnsafeAccountsConf: false,
}, },
@ -704,6 +721,9 @@ func LoadConfigFromFile(root *string, logger *log.Logger) (*AercConfig, error) {
if err := ui.MapTo(&config.General); err != nil { if err := ui.MapTo(&config.General); err != nil {
return nil, err return nil, err
} }
if err := validatePgpProvider(ui); err != nil {
return nil, err
}
} }
filename = path.Join(*root, "accounts.conf") filename = path.Join(*root, "accounts.conf")

28
lib/crypto/crypto.go Normal file
View file

@ -0,0 +1,28 @@
package crypto
import (
"bytes"
"io"
"log"
"git.sr.ht/~rjarry/aerc/lib/crypto/pgp"
"git.sr.ht/~rjarry/aerc/models"
"github.com/ProtonMail/go-crypto/openpgp"
"github.com/emersion/go-message/mail"
)
type Provider interface {
Decrypt(io.Reader, openpgp.PromptFunction) (*models.MessageDetails, error)
Encrypt(*bytes.Buffer, []string, string, openpgp.PromptFunction, *mail.Header) (io.WriteCloser, error)
Sign(*bytes.Buffer, string, openpgp.PromptFunction, *mail.Header) (io.WriteCloser, error)
ImportKeys(io.Reader) error
Init(*log.Logger) error
Close()
}
func New(s string) Provider {
switch s {
default:
return &pgp.Mail{}
}
}

240
lib/crypto/pgp/pgp.go Normal file
View file

@ -0,0 +1,240 @@
package pgp
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path"
"strings"
"time"
"git.sr.ht/~rjarry/aerc/models"
"github.com/ProtonMail/go-crypto/openpgp"
"github.com/ProtonMail/go-crypto/openpgp/packet"
"github.com/emersion/go-message/mail"
"github.com/emersion/go-pgpmail"
"github.com/kyoh86/xdg"
"github.com/pkg/errors"
)
type Mail struct {
logger *log.Logger
}
var (
Keyring openpgp.EntityList
locked bool
)
func (m *Mail) Init(l *log.Logger) error {
m.logger = l
m.logger.Println("Initializing PGP keyring")
os.MkdirAll(path.Join(xdg.DataHome(), "aerc"), 0700)
lockpath := path.Join(xdg.DataHome(), "aerc", "keyring.lock")
lockfile, err := os.OpenFile(lockpath, os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
// TODO: Consider connecting to main process over IPC socket
locked = false
} else {
locked = true
lockfile.Close()
}
keypath := path.Join(xdg.DataHome(), "aerc", "keyring.asc")
keyfile, err := os.Open(keypath)
if os.IsNotExist(err) {
return nil
} else if err != nil {
panic(err)
}
defer keyfile.Close()
Keyring, err = openpgp.ReadKeyRing(keyfile)
if err != nil {
panic(err)
}
return nil
}
func (m *Mail) Close() {
if !locked {
return
}
lockpath := path.Join(xdg.DataHome(), "aerc", "keyring.lock")
os.Remove(lockpath)
}
func (m *Mail) getEntityByEmail(email string) (e *openpgp.Entity, err error) {
for _, entity := range Keyring {
ident := entity.PrimaryIdentity()
if ident != nil && ident.UserId.Email == email {
return entity, nil
}
}
return nil, fmt.Errorf("entity not found in keyring")
}
func (m *Mail) getSignerEntityByEmail(email string) (e *openpgp.Entity, err error) {
for _, key := range Keyring.DecryptionKeys() {
if key.Entity == nil {
continue
}
ident := key.Entity.PrimaryIdentity()
if ident != nil && ident.UserId.Email == email {
return key.Entity, nil
}
}
return nil, fmt.Errorf("entity not found in keyring")
}
func (m *Mail) Decrypt(r io.Reader, decryptKeys openpgp.PromptFunction) (*models.MessageDetails, error) {
md := new(models.MessageDetails)
pgpReader, err := pgpmail.Read(r, Keyring, decryptKeys, nil)
if err != nil {
return nil, err
}
if pgpReader.MessageDetails.IsEncrypted {
md.IsEncrypted = true
md.DecryptedWith = pgpReader.MessageDetails.DecryptedWith.Entity.PrimaryIdentity().Name
md.DecryptedWithKeyId = pgpReader.MessageDetails.DecryptedWith.PublicKey.KeyId
}
if pgpReader.MessageDetails.IsSigned {
// we should consume the UnverifiedBody until EOF in order
// to get the correct signature data
data, err := ioutil.ReadAll(pgpReader.MessageDetails.UnverifiedBody)
if err != nil {
return nil, err
}
pgpReader.MessageDetails.UnverifiedBody = bytes.NewReader(data)
md.IsSigned = true
md.SignedBy = ""
md.SignedByKeyId = pgpReader.MessageDetails.SignedByKeyId
md.SignatureValidity = models.Valid
if pgpReader.MessageDetails.SignatureError != nil {
md.SignatureError = pgpReader.MessageDetails.SignatureError.Error()
md.SignatureValidity = handleSignatureError(md.SignatureError)
}
if pgpReader.MessageDetails.SignedBy != nil {
md.SignedBy = pgpReader.MessageDetails.SignedBy.Entity.PrimaryIdentity().Name
}
}
md.Body = pgpReader.MessageDetails.UnverifiedBody
return md, nil
}
func (m *Mail) ImportKeys(r io.Reader) error {
keys, err := openpgp.ReadKeyRing(r)
if err != nil {
return err
}
Keyring = append(Keyring, keys...)
if locked {
keypath := path.Join(xdg.DataHome(), "aerc", "keyring.asc")
keyfile, err := os.OpenFile(keypath, os.O_CREATE|os.O_APPEND, 0600)
if err != nil {
return err
}
defer keyfile.Close()
for _, key := range keys {
if key.PrivateKey != nil {
err = key.SerializePrivate(keyfile, &packet.Config{})
} else {
err = key.Serialize(keyfile)
}
if err != nil {
return err
}
}
}
return nil
}
func (m *Mail) Encrypt(buf *bytes.Buffer, rcpts []string, signerEmail string, decryptKeys openpgp.PromptFunction, header *mail.Header) (io.WriteCloser, error) {
var err error
var to []*openpgp.Entity
var signer *openpgp.Entity
if signerEmail != "" {
signer, err = m.getSigner(signerEmail, decryptKeys)
if err != nil {
return nil, err
}
}
for _, rcpt := range rcpts {
toEntity, err := m.getEntityByEmail(rcpt)
if err != nil {
return nil, errors.Wrap(err, "no key for "+rcpt)
}
to = append(to, toEntity)
}
cleartext, err := pgpmail.Encrypt(buf, header.Header.Header,
to, signer, nil)
if err != nil {
return nil, err
}
return cleartext, nil
}
func (m *Mail) Sign(buf *bytes.Buffer, signerEmail string, decryptKeys openpgp.PromptFunction, header *mail.Header) (io.WriteCloser, error) {
var err error
var signer *openpgp.Entity
if signerEmail != "" {
signer, err = m.getSigner(signerEmail, decryptKeys)
if err != nil {
return nil, err
}
}
cleartext, err := pgpmail.Sign(buf, header.Header.Header, signer, nil)
if err != nil {
return nil, err
}
return cleartext, nil
}
func (m *Mail) getSigner(signerEmail string, decryptKeys openpgp.PromptFunction) (signer *openpgp.Entity, err error) {
if err != nil {
return nil, err
}
signer, err = m.getSignerEntityByEmail(signerEmail)
if err != nil {
return nil, err
}
key, ok := signer.SigningKey(time.Now())
if !ok {
return nil, fmt.Errorf("no signing key found for %s", signerEmail)
}
if !key.PrivateKey.Encrypted {
return signer, nil
}
_, err = decryptKeys([]openpgp.Key{key}, false)
if err != nil {
return nil, err
}
return signer, nil
}
func handleSignatureError(e string) models.SignatureValidity {
if e == "openpgp: signature made by unknown entity" {
return models.UnknownEntity
}
if strings.HasPrefix(e, "pgpmail: unsupported micalg") {
return models.UnsupportedMicalg
}
if strings.HasPrefix(e, "pgpmail") {
return models.InvalidSignature
}
return models.UnknownValidity
}

View file

@ -1,105 +0,0 @@
package lib
import (
"fmt"
"io"
"os"
"path"
"github.com/ProtonMail/go-crypto/openpgp"
"github.com/ProtonMail/go-crypto/openpgp/packet"
"github.com/kyoh86/xdg"
)
var (
Keyring openpgp.EntityList
locked bool
)
func InitKeyring() {
os.MkdirAll(path.Join(xdg.DataHome(), "aerc"), 0700)
lockpath := path.Join(xdg.DataHome(), "aerc", "keyring.lock")
lockfile, err := os.OpenFile(lockpath, os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
// TODO: Consider connecting to main process over IPC socket
locked = false
} else {
locked = true
lockfile.Close()
}
keypath := path.Join(xdg.DataHome(), "aerc", "keyring.asc")
keyfile, err := os.Open(keypath)
if os.IsNotExist(err) {
return
} else if err != nil {
panic(err)
}
defer keyfile.Close()
Keyring, err = openpgp.ReadKeyRing(keyfile)
if err != nil {
panic(err)
}
}
func UnlockKeyring() {
if !locked {
return
}
lockpath := path.Join(xdg.DataHome(), "aerc", "keyring.lock")
os.Remove(lockpath)
}
func GetEntityByEmail(email string) (e *openpgp.Entity, err error) {
for _, entity := range Keyring {
ident := entity.PrimaryIdentity()
if ident != nil && ident.UserId.Email == email {
return entity, nil
}
}
return nil, fmt.Errorf("entity not found in keyring")
}
func GetSignerEntityByEmail(email string) (e *openpgp.Entity, err error) {
for _, key := range Keyring.DecryptionKeys() {
if key.Entity == nil {
continue
}
ident := key.Entity.PrimaryIdentity()
if ident != nil && ident.UserId.Email == email {
return key.Entity, nil
}
}
return nil, fmt.Errorf("entity not found in keyring")
}
func ImportKeys(r io.Reader) error {
keys, err := openpgp.ReadKeyRing(r)
if err != nil {
return err
}
Keyring = append(Keyring, keys...)
if locked {
keypath := path.Join(xdg.DataHome(), "aerc", "keyring.asc")
keyfile, err := os.OpenFile(keypath, os.O_CREATE|os.O_APPEND, 0600)
if err != nil {
return err
}
defer keyfile.Close()
for _, key := range keys {
if key.PrivateKey != nil {
err = key.SerializePrivate(keyfile, &packet.Config{})
} else {
err = key.Serialize(keyfile)
}
if err != nil {
return err
}
}
}
return nil
}

View file

@ -8,8 +8,8 @@ import (
"github.com/ProtonMail/go-crypto/openpgp" "github.com/ProtonMail/go-crypto/openpgp"
"github.com/emersion/go-message" "github.com/emersion/go-message"
_ "github.com/emersion/go-message/charset" _ "github.com/emersion/go-message/charset"
"github.com/emersion/go-pgpmail"
"git.sr.ht/~rjarry/aerc/lib/crypto"
"git.sr.ht/~rjarry/aerc/models" "git.sr.ht/~rjarry/aerc/models"
"git.sr.ht/~rjarry/aerc/worker/lib" "git.sr.ht/~rjarry/aerc/worker/lib"
"git.sr.ht/~rjarry/aerc/worker/types" "git.sr.ht/~rjarry/aerc/worker/types"
@ -30,7 +30,7 @@ type MessageView interface {
// Fetches a specific body part for this message // Fetches a specific body part for this message
FetchBodyPart(part []int, cb func(io.Reader)) FetchBodyPart(part []int, cb func(io.Reader))
PGPDetails() *openpgp.MessageDetails MessageDetails() *models.MessageDetails
} }
func usePGP(info *models.BodyStructure) bool { func usePGP(info *models.BodyStructure) bool {
@ -56,12 +56,12 @@ type MessageStoreView struct {
messageInfo *models.MessageInfo messageInfo *models.MessageInfo
messageStore *MessageStore messageStore *MessageStore
message []byte message []byte
details *openpgp.MessageDetails details *models.MessageDetails
bodyStructure *models.BodyStructure bodyStructure *models.BodyStructure
} }
func NewMessageStoreView(messageInfo *models.MessageInfo, func NewMessageStoreView(messageInfo *models.MessageInfo,
store *MessageStore, decryptKeys openpgp.PromptFunction, store *MessageStore, pgp crypto.Provider, decryptKeys openpgp.PromptFunction,
cb func(MessageView, error)) { cb func(MessageView, error)) {
msv := &MessageStoreView{messageInfo, store, msv := &MessageStoreView{messageInfo, store,
@ -70,12 +70,12 @@ func NewMessageStoreView(messageInfo *models.MessageInfo,
if usePGP(messageInfo.BodyStructure) { if usePGP(messageInfo.BodyStructure) {
store.FetchFull([]uint32{messageInfo.Uid}, func(fm *types.FullMessage) { store.FetchFull([]uint32{messageInfo.Uid}, func(fm *types.FullMessage) {
reader := lib.NewCRLFReader(fm.Content.Reader) reader := lib.NewCRLFReader(fm.Content.Reader)
pgpReader, err := pgpmail.Read(reader, Keyring, decryptKeys, nil) md, err := pgp.Decrypt(reader, decryptKeys)
if err != nil { if err != nil {
cb(nil, err) cb(nil, err)
return return
} }
msv.message, err = ioutil.ReadAll(pgpReader.MessageDetails.UnverifiedBody) msv.message, err = ioutil.ReadAll(md.Body)
if err != nil { if err != nil {
cb(nil, err) cb(nil, err)
return return
@ -91,7 +91,7 @@ func NewMessageStoreView(messageInfo *models.MessageInfo,
return return
} }
msv.bodyStructure = bs msv.bodyStructure = bs
msv.details = pgpReader.MessageDetails msv.details = md
cb(msv, nil) cb(msv, nil)
}) })
} else { } else {
@ -112,7 +112,7 @@ func (msv *MessageStoreView) Store() *MessageStore {
return msv.messageStore return msv.messageStore
} }
func (msv *MessageStoreView) PGPDetails() *openpgp.MessageDetails { func (msv *MessageStoreView) MessageDetails() *models.MessageDetails {
return msv.details return msv.details
} }

View file

@ -185,3 +185,27 @@ type OriginalMail struct {
MIMEType string MIMEType string
RFC822Headers *mail.Header RFC822Headers *mail.Header
} }
type SignatureValidity int32
const (
UnknownValidity SignatureValidity = iota
Valid
InvalidSignature
UnknownEntity
UnsupportedMicalg
MicalgMismatch
)
type MessageDetails struct {
IsEncrypted bool
IsSigned bool
SignedBy string // Primary identity of signing key
SignedByKeyId uint64
SignatureValidity SignatureValidity
SignatureError string
DecryptedWith string // Primary Identity of decryption key
DecryptedWithKeyId uint64 // Public key id of decryption key
Body io.Reader
Micalg string
}

View file

@ -16,6 +16,7 @@ import (
"git.sr.ht/~rjarry/aerc/config" "git.sr.ht/~rjarry/aerc/config"
"git.sr.ht/~rjarry/aerc/lib" "git.sr.ht/~rjarry/aerc/lib"
"git.sr.ht/~rjarry/aerc/lib/crypto"
"git.sr.ht/~rjarry/aerc/lib/ui" "git.sr.ht/~rjarry/aerc/lib/ui"
"git.sr.ht/~rjarry/aerc/models" "git.sr.ht/~rjarry/aerc/models"
) )
@ -38,6 +39,8 @@ type Aerc struct {
ui *ui.UI ui *ui.UI
beep func() error beep func() error
dialog ui.DrawableInteractive dialog ui.DrawableInteractive
Crypto crypto.Provider
} }
type Choice struct { type Choice struct {
@ -47,9 +50,9 @@ type Choice struct {
} }
func NewAerc(conf *config.AercConfig, logger *log.Logger, func NewAerc(conf *config.AercConfig, logger *log.Logger,
cmd func(cmd []string) error, complete func(cmd string) []string, crypto crypto.Provider, cmd func(cmd []string) error,
cmdHistory lib.History, deferLoop chan struct{}, complete func(cmd string) []string, cmdHistory lib.History,
) *Aerc { deferLoop chan struct{}) *Aerc {
tabs := ui.NewTabs(&conf.Ui) tabs := ui.NewTabs(&conf.Ui)
statusbar := ui.NewStack(conf.Ui) statusbar := ui.NewStack(conf.Ui)
@ -79,6 +82,7 @@ func NewAerc(conf *config.AercConfig, logger *log.Logger,
statusline: statusline, statusline: statusline,
prompts: ui.NewStack(conf.Ui), prompts: ui.NewStack(conf.Ui),
tabs: tabs, tabs: tabs,
Crypto: crypto,
} }
statusline.SetAerc(aerc) statusline.SetAerc(aerc)

View file

@ -15,9 +15,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/ProtonMail/go-crypto/openpgp"
"github.com/emersion/go-message/mail" "github.com/emersion/go-message/mail"
"github.com/emersion/go-pgpmail"
"github.com/gdamore/tcell/v2" "github.com/gdamore/tcell/v2"
"github.com/mattn/go-runewidth" "github.com/mattn/go-runewidth"
"github.com/mitchellh/go-homedir" "github.com/mitchellh/go-homedir"
@ -25,7 +23,6 @@ import (
"git.sr.ht/~rjarry/aerc/completer" "git.sr.ht/~rjarry/aerc/completer"
"git.sr.ht/~rjarry/aerc/config" "git.sr.ht/~rjarry/aerc/config"
"git.sr.ht/~rjarry/aerc/lib"
"git.sr.ht/~rjarry/aerc/lib/format" "git.sr.ht/~rjarry/aerc/lib/format"
"git.sr.ht/~rjarry/aerc/lib/templates" "git.sr.ht/~rjarry/aerc/lib/templates"
"git.sr.ht/~rjarry/aerc/lib/ui" "git.sr.ht/~rjarry/aerc/lib/ui"
@ -455,38 +452,27 @@ func (c *Composer) WriteMessage(header *mail.Header, writer io.Writer) error {
var cleartext io.WriteCloser var cleartext io.WriteCloser
var err error var err error
var signer *openpgp.Entity var signerEmail string
if c.sign { if c.sign {
signer, err = getSigner(c) signerEmail, err = getSenderEmail(c)
if err != nil { if err != nil {
return err return err
} }
} else { } else {
signer = nil signerEmail = ""
} }
if c.encrypt { if c.encrypt {
var to []*openpgp.Entity
rcpts, err := getRecipientsEmail(c) rcpts, err := getRecipientsEmail(c)
if err != nil { if err != nil {
return err return err
} }
for _, rcpt := range rcpts { cleartext, err = c.aerc.Crypto.Encrypt(&buf, rcpts, signerEmail, c.aerc.DecryptKeys, header)
toEntity, err := lib.GetEntityByEmail(rcpt)
if err != nil {
return errors.Wrap(err, "no key for "+rcpt)
}
to = append(to, toEntity)
}
cleartext, err = pgpmail.Encrypt(&buf, header.Header.Header,
to, signer, nil)
if err != nil { if err != nil {
return err return err
} }
} else { } else {
cleartext, err = pgpmail.Sign(&buf, header.Header.Header, cleartext, err = c.aerc.Crypto.Sign(&buf, signerEmail, c.aerc.DecryptKeys, header)
signer, nil)
if err != nil { if err != nil {
return err return err
} }
@ -1031,30 +1017,3 @@ func (rm *reviewMessage) OnInvalidate(fn func(ui.Drawable)) {
func (rm *reviewMessage) Draw(ctx *ui.Context) { func (rm *reviewMessage) Draw(ctx *ui.Context) {
rm.grid.Draw(ctx) rm.grid.Draw(ctx)
} }
func getSigner(c *Composer) (signer *openpgp.Entity, err error) {
signerEmail, err := getSenderEmail(c)
if err != nil {
return nil, err
}
signer, err = lib.GetSignerEntityByEmail(signerEmail)
if err != nil {
return nil, err
}
key, ok := signer.SigningKey(time.Now())
if !ok {
return nil, fmt.Errorf("no signing key found for %s", signerEmail)
}
if !key.PrivateKey.Encrypted {
return signer, nil
}
_, err = c.aerc.DecryptKeys([]openpgp.Key{key}, false)
if err != nil {
return nil, err
}
return signer, nil
}

View file

@ -295,7 +295,8 @@ func (ml *MessageList) MouseEvent(localX int, localY int, event tcell.Event) {
if msg == nil { if msg == nil {
return return
} }
lib.NewMessageStoreView(msg, store, ml.aerc.DecryptKeys, lib.NewMessageStoreView(msg, store, ml.aerc.Crypto,
ml.aerc.DecryptKeys,
func(view lib.MessageView, err error) { func(view lib.MessageView, err error) {
if err != nil { if err != nil {
ml.aerc.PushError(err.Error()) ml.aerc.PushError(err.Error())

View file

@ -75,9 +75,9 @@ func NewMessageViewer(acct *AccountView,
{Strategy: ui.SIZE_EXACT, Size: ui.Const(headerHeight)}, {Strategy: ui.SIZE_EXACT, Size: ui.Const(headerHeight)},
} }
if msg.PGPDetails() != nil { if msg.MessageDetails() != nil {
height := 1 height := 1
if msg.PGPDetails().IsSigned && msg.PGPDetails().IsEncrypted { if msg.MessageDetails().IsSigned && msg.MessageDetails().IsEncrypted {
height = 2 height = 2
} }
rows = append(rows, ui.GridSpec{Strategy: ui.SIZE_EXACT, Size: ui.Const(height)}) rows = append(rows, ui.GridSpec{Strategy: ui.SIZE_EXACT, Size: ui.Const(height)})
@ -107,8 +107,8 @@ func NewMessageViewer(acct *AccountView,
borderChar := acct.UiConfig().BorderCharHorizontal borderChar := acct.UiConfig().BorderCharHorizontal
grid.AddChild(header).At(0, 0) grid.AddChild(header).At(0, 0)
if msg.PGPDetails() != nil { if msg.MessageDetails() != nil {
grid.AddChild(NewPGPInfo(msg.PGPDetails(), acct.UiConfig())).At(1, 0) grid.AddChild(NewPGPInfo(msg.MessageDetails(), acct.UiConfig())).At(1, 0)
grid.AddChild(ui.NewFill(borderChar, borderStyle)).At(2, 0) grid.AddChild(ui.NewFill(borderChar, borderStyle)).At(2, 0)
grid.AddChild(switcher).At(3, 0) grid.AddChild(switcher).At(3, 0)
} else { } else {

View file

@ -1,22 +1,18 @@
package widgets package widgets
import ( import (
"errors"
"git.sr.ht/~rjarry/aerc/config" "git.sr.ht/~rjarry/aerc/config"
"git.sr.ht/~rjarry/aerc/lib/ui" "git.sr.ht/~rjarry/aerc/lib/ui"
"git.sr.ht/~rjarry/aerc/models"
"github.com/ProtonMail/go-crypto/openpgp"
pgperrors "github.com/ProtonMail/go-crypto/openpgp/errors"
) )
type PGPInfo struct { type PGPInfo struct {
ui.Invalidatable ui.Invalidatable
details *openpgp.MessageDetails details *models.MessageDetails
uiConfig config.UIConfig uiConfig config.UIConfig
} }
func NewPGPInfo(details *openpgp.MessageDetails, uiConfig config.UIConfig) *PGPInfo { func NewPGPInfo(details *models.MessageDetails, uiConfig config.UIConfig) *PGPInfo {
return &PGPInfo{details: details, uiConfig: uiConfig} return &PGPInfo{details: details, uiConfig: uiConfig}
} }
@ -27,38 +23,33 @@ func (p *PGPInfo) DrawSignature(ctx *ui.Context) {
defaultStyle := p.uiConfig.GetStyle(config.STYLE_DEFAULT) defaultStyle := p.uiConfig.GetStyle(config.STYLE_DEFAULT)
// TODO: Nicer prompt for TOFU, fetch from keyserver, etc // TODO: Nicer prompt for TOFU, fetch from keyserver, etc
if errors.Is(p.details.SignatureError, pgperrors.ErrUnknownIssuer) || if p.details.SignatureValidity == models.UnknownEntity ||
p.details.SignedBy == nil { p.details.SignedBy == "" {
x := ctx.Printf(0, 0, warningStyle, "*") x := ctx.Printf(0, 0, warningStyle, "*")
x += ctx.Printf(x, 0, defaultStyle, x += ctx.Printf(x, 0, defaultStyle,
" Signed with unknown key (%8X); authenticity unknown", " Signed with unknown key (%8X); authenticity unknown",
p.details.SignedByKeyId) p.details.SignedByKeyId)
} else if p.details.SignatureError != nil { } else if p.details.SignatureValidity != models.Valid {
x := ctx.Printf(0, 0, errorStyle, "Invalid signature!") x := ctx.Printf(0, 0, errorStyle, "Invalid signature!")
x += ctx.Printf(x, 0, errorStyle, x += ctx.Printf(x, 0, errorStyle,
" This message may have been tampered with! (%s)", " This message may have been tampered with! (%s)",
p.details.SignatureError.Error()) p.details.SignatureError)
} else { } else {
entity := p.details.SignedBy.Entity
ident := entity.PrimaryIdentity()
x := ctx.Printf(0, 0, validStyle, "✓ Authentic ") x := ctx.Printf(0, 0, validStyle, "✓ Authentic ")
x += ctx.Printf(x, 0, defaultStyle, x += ctx.Printf(x, 0, defaultStyle,
"Signature from %s (%8X)", "Signature from %s (%8X)",
ident.Name, p.details.SignedByKeyId) p.details.SignedBy, p.details.SignedByKeyId)
} }
} }
func (p *PGPInfo) DrawEncryption(ctx *ui.Context, y int) { func (p *PGPInfo) DrawEncryption(ctx *ui.Context, y int) {
validStyle := p.uiConfig.GetStyle(config.STYLE_SUCCESS) validStyle := p.uiConfig.GetStyle(config.STYLE_SUCCESS)
defaultStyle := p.uiConfig.GetStyle(config.STYLE_DEFAULT) defaultStyle := p.uiConfig.GetStyle(config.STYLE_DEFAULT)
entity := p.details.DecryptedWith.Entity
ident := entity.PrimaryIdentity()
x := ctx.Printf(0, y, validStyle, "✓ Encrypted ") x := ctx.Printf(0, y, validStyle, "✓ Encrypted ")
x += ctx.Printf(x, y, defaultStyle, x += ctx.Printf(x, y, defaultStyle,
"To %s (%8X) ", ident.Name, p.details.DecryptedWith.PublicKey.KeyId) "To %s (%8X) ", p.details.DecryptedWith, p.details.DecryptedWithKeyId)
} }
func (p *PGPInfo) Draw(ctx *ui.Context) { func (p *PGPInfo) Draw(ctx *ui.Context) {