diff options
author | Tim Culverhouse <tim@timculverhouse.com> | 2022-04-25 08:30:43 -0500 |
---|---|---|
committer | Robin Jarry <robin@jarry.cc> | 2022-04-27 09:46:11 +0200 |
commit | d09636ee0b9957ed60fc01224ddfbb03c4f4b7fa (patch) | |
tree | 5f0ec8c9ad11a0f638c25dbd896a518e983dc779 /lib | |
parent | afe35839eddfaf43be0f791e97a926a15d91fc02 (diff) | |
download | aerc-d09636ee0b9957ed60fc01224ddfbb03c4f4b7fa.tar.gz |
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>
Diffstat (limited to 'lib')
-rw-r--r-- | lib/crypto/crypto.go | 28 | ||||
-rw-r--r-- | lib/crypto/pgp/pgp.go | 240 | ||||
-rw-r--r-- | lib/keystore.go | 105 | ||||
-rw-r--r-- | lib/messageview.go | 16 |
4 files changed, 276 insertions, 113 deletions
diff --git a/lib/crypto/crypto.go b/lib/crypto/crypto.go new file mode 100644 index 00000000..47cb9544 --- /dev/null +++ b/lib/crypto/crypto.go @@ -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{} + } +} diff --git a/lib/crypto/pgp/pgp.go b/lib/crypto/pgp/pgp.go new file mode 100644 index 00000000..70a003a0 --- /dev/null +++ b/lib/crypto/pgp/pgp.go @@ -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 +} diff --git a/lib/keystore.go b/lib/keystore.go deleted file mode 100644 index 0b9d41af..00000000 --- a/lib/keystore.go +++ /dev/null @@ -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 -} diff --git a/lib/messageview.go b/lib/messageview.go index f221fb2c..a1797d53 100644 --- a/lib/messageview.go +++ b/lib/messageview.go @@ -8,8 +8,8 @@ import ( "github.com/ProtonMail/go-crypto/openpgp" "github.com/emersion/go-message" _ "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/worker/lib" "git.sr.ht/~rjarry/aerc/worker/types" @@ -30,7 +30,7 @@ type MessageView interface { // Fetches a specific body part for this message FetchBodyPart(part []int, cb func(io.Reader)) - PGPDetails() *openpgp.MessageDetails + MessageDetails() *models.MessageDetails } func usePGP(info *models.BodyStructure) bool { @@ -56,12 +56,12 @@ type MessageStoreView struct { messageInfo *models.MessageInfo messageStore *MessageStore message []byte - details *openpgp.MessageDetails + details *models.MessageDetails bodyStructure *models.BodyStructure } func NewMessageStoreView(messageInfo *models.MessageInfo, - store *MessageStore, decryptKeys openpgp.PromptFunction, + store *MessageStore, pgp crypto.Provider, decryptKeys openpgp.PromptFunction, cb func(MessageView, error)) { msv := &MessageStoreView{messageInfo, store, @@ -70,12 +70,12 @@ func NewMessageStoreView(messageInfo *models.MessageInfo, if usePGP(messageInfo.BodyStructure) { store.FetchFull([]uint32{messageInfo.Uid}, func(fm *types.FullMessage) { reader := lib.NewCRLFReader(fm.Content.Reader) - pgpReader, err := pgpmail.Read(reader, Keyring, decryptKeys, nil) + md, err := pgp.Decrypt(reader, decryptKeys) if err != nil { cb(nil, err) return } - msv.message, err = ioutil.ReadAll(pgpReader.MessageDetails.UnverifiedBody) + msv.message, err = ioutil.ReadAll(md.Body) if err != nil { cb(nil, err) return @@ -91,7 +91,7 @@ func NewMessageStoreView(messageInfo *models.MessageInfo, return } msv.bodyStructure = bs - msv.details = pgpReader.MessageDetails + msv.details = md cb(msv, nil) }) } else { @@ -112,7 +112,7 @@ func (msv *MessageStoreView) Store() *MessageStore { return msv.messageStore } -func (msv *MessageStoreView) PGPDetails() *openpgp.MessageDetails { +func (msv *MessageStoreView) MessageDetails() *models.MessageDetails { return msv.details } |