Imported Upstream version 2.3.1
[platform/upstream/gpg2.git] / g10 / mainproc.c
index d56790b..10cc697 100644 (file)
@@ -1,6 +1,7 @@
 /* mainproc.c - handle packets
  * Copyright (C) 1998-2009 Free Software Foundation, Inc.
  * Copyright (C) 2013-2014 Werner Koch
+ * Copyright (C) 2020 g10 Code GmbH
  *
  * This file is part of GnuPG.
  *
@@ -15,7 +16,7 @@
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with this program; if not, see <http://www.gnu.org/licenses/>.
+ * along with this program; if not, see <https://www.gnu.org/licenses/>.
  */
 
 #include <config.h>
 #include <time.h>
 
 #include "gpg.h"
-#include "util.h"
+#include "../common/util.h"
 #include "packet.h"
-#include "iobuf.h"
+#include "../common/iobuf.h"
 #include "options.h"
 #include "keydb.h"
 #include "filter.h"
 #include "main.h"
-#include "status.h"
-#include "i18n.h"
+#include "../common/status.h"
+#include "../common/i18n.h"
 #include "trustdb.h"
 #include "keyserver-internal.h"
 #include "photoid.h"
-#include "mbox-util.h"
+#include "../common/mbox-util.h"
 #include "call-dirmngr.h"
+#include "../common/compliance.h"
 
 /* Put an upper limit on nested packets.  The 32 is an arbitrary
    value, a much lower should actually be sufficient.  */
 #define MAX_NESTING_DEPTH 32
 
 
-/* An object to build a list of keyid related info.  */
-struct kidlist_item
-{
-  struct kidlist_item *next;
-  u32 kid[2];
-  int pubkey_algo;
-  int reason;
-};
-
-
 /*
  * Object to hold the processing context.
  */
@@ -78,7 +70,7 @@ struct mainproc_context
      signature. */
   struct
   {
-    /* A file descriptor of the the signed data.  Only used if not -1. */
+    /* A file descriptor of the signed data.  Only used if not -1. */
     int data_fd;
     /* A list of filenames with the data files or NULL. This is only
        used if DATA_FD is -1. */
@@ -93,8 +85,9 @@ struct mainproc_context
   kbnode_t list;    /* The current list of packets. */
   iobuf_t iobuf;    /* Used to get the filename etc. */
   int trustletter;  /* Temporary usage in list_node. */
-  ulong symkeys;
-  struct kidlist_item *pkenc_list; /* List of encryption packets. */
+  ulong symkeys;    /* Number of symmetrically encrypted session keys.  */
+  struct pubkey_enc_list *pkenc_list; /* List of encryption packets. */
+  int seen_pkt_encrypted_aead; /* PKT_ENCRYPTED_AEAD packet seen. */
   struct {
     unsigned int sig_seen:1;      /* Set to true if a signature packet
                                      has been seen. */
@@ -104,16 +97,22 @@ struct mainproc_context
 };
 
 
+/* Counter with the number of literal data packets seen.  Note that
+ * this is also bumped at the end of an encryption.  This counter is
+ * used for a basic consistency check of a received PGP message.  */
+static int literals_seen;
+
+
 /*** Local prototypes.  ***/
-static int do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a);
+static int do_proc_packets (CTX c, iobuf_t a);
 static void list_node (CTX c, kbnode_t node);
 static void proc_tree (CTX c, kbnode_t node);
-static int literals_seen;
 
 
 /*** Functions.  ***/
 
-
+/* Reset the literal data counter.  This is required to setup a new
+ * decryption or verification context.  */
 void
 reset_literals_seen(void)
 {
@@ -124,13 +123,14 @@ reset_literals_seen(void)
 static void
 release_list( CTX c )
 {
-  if (!c->list)
-    return;
   proc_tree (c, c->list);
   release_kbnode (c->list);
   while (c->pkenc_list)
     {
-      struct kidlist_item *tmp = c->pkenc_list->next;
+      struct pubkey_enc_list *tmp = c->pkenc_list->next;
+
+      mpi_release (c->pkenc_list->data[0]);
+      mpi_release (c->pkenc_list->data[1]);
       xfree (c->pkenc_list);
       c->pkenc_list = tmp;
     }
@@ -139,6 +139,7 @@ release_list( CTX c )
   c->any.data = 0;
   c->any.uncompress_failed = 0;
   c->last_was_session_key = 0;
+  c->seen_pkt_encrypted_aead = 0;
   xfree (c->dek);
   c->dek = NULL;
 }
@@ -246,46 +247,117 @@ add_signature (CTX c, PACKET *pkt)
   return 1;
 }
 
-static int
+static gpg_error_t
 symkey_decrypt_seskey (DEK *dek, byte *seskey, size_t slen)
 {
+  gpg_error_t err;
   gcry_cipher_hd_t hd;
+  unsigned int noncelen, keylen;
+  enum gcry_cipher_modes ciphermode;
+
+  if (dek->use_aead)
+    {
+      err = openpgp_aead_algo_info (dek->use_aead, &ciphermode, &noncelen);
+      if (err)
+        return err;
+    }
+  else
+    {
+      ciphermode = GCRY_CIPHER_MODE_CFB;
+      noncelen = 0;
+    }
 
-  if(slen < 17 || slen > 33)
+  /* Check that the session key has a size of 16 to 32 bytes.  */
+  if ((dek->use_aead && (slen < (noncelen + 16 + 16)
+                         || slen > (noncelen + 32 + 16)))
+      || (!dek->use_aead && (slen < 17 || slen > 33)))
     {
       log_error ( _("weird size for an encrypted session key (%d)\n"),
                  (int)slen);
-      return GPG_ERR_BAD_KEY;
+      return gpg_error (GPG_ERR_BAD_KEY);
     }
 
-  if (openpgp_cipher_open (&hd, dek->algo, GCRY_CIPHER_MODE_CFB, 1))
-      BUG ();
-  if (gcry_cipher_setkey ( hd, dek->key, dek->keylen ))
-    BUG ();
-  gcry_cipher_setiv ( hd, NULL, 0 );
-  gcry_cipher_decrypt ( hd, seskey, slen, NULL, 0 );
-  gcry_cipher_close ( hd );
-
-  /* Now we replace the dek components with the real session key to
-     decrypt the contents of the sequencing packet. */
+  err = openpgp_cipher_open (&hd, dek->algo, ciphermode, GCRY_CIPHER_SECURE);
+  if (!err)
+    err = gcry_cipher_setkey (hd, dek->key, dek->keylen);
+  if (!err)
+    err = gcry_cipher_setiv (hd, noncelen? seskey : NULL, noncelen);
+  if (err)
+    goto leave;
 
-  dek->keylen=slen-1;
-  dek->algo=seskey[0];
-
-  if(dek->keylen > DIM(dek->key))
-    BUG ();
+  if (dek->use_aead)
+    {
+      byte ad[4];
+
+      ad[0] = (0xc0 | PKT_SYMKEY_ENC);
+      ad[1] = 5;
+      ad[2] = dek->algo;
+      ad[3] = dek->use_aead;
+      err = gcry_cipher_authenticate (hd, ad, 4);
+      if (err)
+        goto leave;
+      gcry_cipher_final (hd);
+      keylen = slen - noncelen - 16;
+      err = gcry_cipher_decrypt (hd, seskey+noncelen, keylen, NULL, 0);
+      if (err)
+        goto leave;
+      err = gcry_cipher_checktag (hd, seskey+noncelen+keylen, 16);
+      if (err)
+        goto leave;
+      /* Now we replace the dek components with the real session key to
+       * decrypt the contents of the sequencing packet. */
+      if (keylen > DIM(dek->key))
+        {
+          err = gpg_error (GPG_ERR_TOO_LARGE);
+          goto leave;
+        }
+      dek->keylen = keylen;
+      memcpy (dek->key, seskey + noncelen, dek->keylen);
+    }
+  else
+    {
+      gcry_cipher_decrypt (hd, seskey, slen, NULL, 0 );
+      /* Here we can only test whether the algo given in decrypted
+       * session key is a valid OpenPGP algo.  With 11 defined
+       * symmetric algorithms we will miss 4.3% of wrong passphrases
+       * here.  The actual checking is done later during bulk
+       * decryption; we can't bring this check forward easily.  We
+       * need to use the GPG_ERR_CHECKSUM so that we won't run into
+       * the gnupg < 2.2 bug compatible case which would terminate the
+       * process on GPG_ERR_CIPHER_ALGO.  Note that with AEAD (above)
+       * we will have a reliable test here.  */
+      if (openpgp_cipher_test_algo (seskey[0])
+          || openpgp_cipher_get_algo_keylen (seskey[0]) != slen - 1)
+        {
+          err = gpg_error (GPG_ERR_CHECKSUM);
+          goto leave;
+        }
 
-  memcpy(dek->key, seskey + 1, dek->keylen);
+      /* Now we replace the dek components with the real session key to
+       * decrypt the contents of the sequencing packet. */
+      keylen = slen-1;
+      if (keylen > DIM(dek->key))
+        {
+          err = gpg_error (GPG_ERR_TOO_LARGE);
+          goto leave;
+        }
+      dek->algo = seskey[0];
+      dek->keylen = keylen;
+      memcpy (dek->key, seskey + 1, dek->keylen);
+    }
 
   /*log_hexdump( "thekey", dek->key, dek->keylen );*/
 
-  return 0;
+ leave:
+  gcry_cipher_close (hd);
+  return err;
 }
 
 
 static void
 proc_symkey_enc (CTX c, PACKET *pkt)
 {
+  gpg_error_t err;
   PKT_symkey_enc *enc;
 
   enc = pkt->pkt.symkey_enc;
@@ -295,19 +367,24 @@ proc_symkey_enc (CTX c, PACKET *pkt)
     {
       int algo = enc->cipher_algo;
       const char *s = openpgp_cipher_algo_name (algo);
+      const char *a = (enc->aead_algo ? openpgp_aead_algo_name (enc->aead_algo)
+                       /**/           : "CFB");
 
       if (!openpgp_cipher_test_algo (algo))
         {
           if (!opt.quiet)
             {
               if (enc->seskeylen)
-                log_info (_("%s encrypted session key\n"), s );
+                log_info (_("%s.%s encrypted session key\n"), s, a );
               else
-                log_info (_("%s encrypted data\n"), s );
+                log_info (_("%s.%s encrypted data\n"), s, a );
             }
         }
       else
-        log_error (_("encrypted with unknown algorithm %d\n"), algo);
+        {
+          log_error (_("encrypted with unknown algorithm %d.%s\n"), algo, a);
+          s = NULL; /* Force a goto leave.  */
+        }
 
       if (openpgp_md_test_algo (enc->s2k.hash_algo))
         {
@@ -331,10 +408,11 @@ proc_symkey_enc (CTX c, PACKET *pkt)
         }
       else
         {
-          c->dek = passphrase_to_dek (NULL, 0, algo, &enc->s2k, 3, NULL, NULL);
+          c->dek = passphrase_to_dek (algo, &enc->s2k, 0, 0, NULL, NULL);
           if (c->dek)
             {
               c->dek->symmetric = 1;
+              c->dek->use_aead = enc->aead_algo;
 
               /* FIXME: This doesn't work perfectly if a symmetric key
                  comes before a public key in the message - if the
@@ -345,9 +423,24 @@ proc_symkey_enc (CTX c, PACKET *pkt)
                  come later. */
               if (enc->seskeylen)
                 {
-                  if (symkey_decrypt_seskey (c->dek,
-                                             enc->seskey, enc->seskeylen))
+                  err = symkey_decrypt_seskey (c->dek,
+                                               enc->seskey, enc->seskeylen);
+                  if (err)
                     {
+                      log_info ("decryption of the symmetrically encrypted"
+                                 " session key failed: %s\n",
+                                 gpg_strerror (err));
+                      if (gpg_err_code (err) != GPG_ERR_BAD_KEY
+                          && gpg_err_code (err) != GPG_ERR_CHECKSUM)
+                        log_fatal ("process terminated to be bug compatible"
+                                   " with GnuPG <= 2.2\n");
+                      if (c->dek->s2k_cacheid[0])
+                        {
+                          if (opt.debug)
+                            log_debug ("cleared passphrase cached with ID:"
+                                       " %s\n", c->dek->s2k_cacheid);
+                          passphrase_clear_cache (c->dek->s2k_cacheid);
+                        }
                       xfree (c->dek);
                       c->dek = NULL;
                     }
@@ -360,15 +453,14 @@ proc_symkey_enc (CTX c, PACKET *pkt)
 
  leave:
   c->symkeys++;
-  free_packet (pkt);
+  free_packet (pkt, NULL);
 }
 
 
 static void
-proc_pubkey_enc (ctrl_t ctrl, CTX c, PACKET *pkt)
+proc_pubkey_enc (CTX c, PACKET *pkt)
 {
   PKT_pubkey_enc *enc;
-  int result = 0;
 
   /* Check whether the secret key is available and store in this case.  */
   c->last_was_session_key = 1;
@@ -379,86 +471,33 @@ proc_pubkey_enc (ctrl_t ctrl, CTX c, PACKET *pkt)
   if (opt.verbose)
     log_info (_("public key is %s\n"), keystr (enc->keyid));
 
-  if (is_status_enabled())
+  if (is_status_enabled ())
     {
       char buf[50];
-      /* FIXME: For ECC support we need to map the OpenPGP algo number
-         to the Libgcrypt defined one.  This is due a chicken-egg
-         problem: We need to have code in Libgcrypt for a new
-         algorithm so to implement a proposed new algorithm before the
-         IANA will finally assign an OpenPGP identifier.  */
       snprintf (buf, sizeof buf, "%08lX%08lX %d 0",
-               (ulong)enc->keyid[0], (ulong)enc->keyid[1], enc->pubkey_algo);
+                (ulong)enc->keyid[0], (ulong)enc->keyid[1], enc->pubkey_algo);
       write_status_text (STATUS_ENC_TO, buf);
     }
 
-  if (!opt.list_only && opt.override_session_key)
+  if (!opt.list_only && !opt.override_session_key)
     {
-      /* It does not make much sense to store the session key in
-       * secure memory because it has already been passed on the
-       * command line and the GCHQ knows about it.  */
-      c->dek = xmalloc_clear (sizeof *c->dek);
-      result = get_override_session_key (c->dek, opt.override_session_key);
-      if (result)
-        {
-          xfree (c->dek);
-          c->dek = NULL;
-       }
-    }
-  else if (enc->pubkey_algo == PUBKEY_ALGO_ELGAMAL_E
-           || enc->pubkey_algo == PUBKEY_ALGO_ECDH
-           || enc->pubkey_algo == PUBKEY_ALGO_RSA
-           || enc->pubkey_algo == PUBKEY_ALGO_RSA_E
-           || enc->pubkey_algo == PUBKEY_ALGO_ELGAMAL)
-    {
-      /* Note that we also allow type 20 Elgamal keys for decryption.
-         There are still a couple of those keys in active use as a
-         subkey.  */
-
-      /* FIXME: Store this all in a list and process it later so that
-         we can prioritize what key to use.  This gives a better user
-         experience if wildcard keyids are used.  */
-      if  (!c->dek && ((!enc->keyid[0] && !enc->keyid[1])
-                       || opt.try_all_secrets
-                       || have_secret_key_with_kid (enc->keyid)))
-        {
-          if(opt.list_only)
-            result = -1;
-          else
-            {
-              c->dek = xmalloc_secure_clear (sizeof *c->dek);
-              if ((result = get_session_key (ctrl, enc, c->dek)))
-                {
-                  /* Error: Delete the DEK. */
-                  xfree (c->dek);
-                  c->dek = NULL;
-               }
-           }
-       }
-      else
-        result = GPG_ERR_NO_SECKEY;
-    }
-  else
-    result = GPG_ERR_PUBKEY_ALGO;
+      struct pubkey_enc_list *x = xmalloc (sizeof *x);
 
-  if (result == -1)
-    ;
-  else
-    {
-      /* Store it for later display.  */
-      struct kidlist_item *x = xmalloc (sizeof *x);
-      x->kid[0] = enc->keyid[0];
-      x->kid[1] = enc->keyid[1];
+      x->keyid[0] = enc->keyid[0];
+      x->keyid[1] = enc->keyid[1];
       x->pubkey_algo = enc->pubkey_algo;
-      x->reason = result;
+      x->result = -1;
+      x->data[0] = x->data[1] = NULL;
+      if (enc->data[0])
+        {
+          x->data[0] = mpi_copy (enc->data[0]);
+          x->data[1] = mpi_copy (enc->data[1]);
+        }
       x->next = c->pkenc_list;
       c->pkenc_list = x;
-
-      if (!result && opt.verbose > 1)
-        log_info (_("public key encrypted data: good DEK\n"));
     }
 
-  free_packet(pkt);
+  free_packet(pkt, NULL);
 }
 
 
@@ -467,56 +506,34 @@ proc_pubkey_enc (ctrl_t ctrl, CTX c, PACKET *pkt)
  * not decrypt.
  */
 static void
-print_pkenc_list (struct kidlist_item *list, int failed)
+print_pkenc_list (ctrl_t ctrl, struct pubkey_enc_list *list)
 {
   for (; list; list = list->next)
     {
       PKT_public_key *pk;
-      const char *algstr;
-
-      if (failed && !list->reason)
-        continue;
-      if (!failed && list->reason)
-        continue;
+      char pkstrbuf[PUBKEY_STRING_SIZE];
+      char *p;
 
-      algstr = openpgp_pk_algo_name (list->pubkey_algo);
       pk = xmalloc_clear (sizeof *pk);
 
-      if (!algstr)
-        algstr = "[?]";
       pk->pubkey_algo = list->pubkey_algo;
-      if (!get_pubkey (pk, list->kid))
+      if (!get_pubkey (ctrl, pk, list->keyid))
         {
-          char *p;
-          log_info (_("encrypted with %u-bit %s key, ID %s, created %s\n"),
-                    nbits_from_pk (pk), algstr, keystr_from_pk(pk),
+          pubkey_string (pk, pkstrbuf, sizeof pkstrbuf);
+
+          log_info (_("encrypted with %s key, ID %s, created %s\n"),
+                    pkstrbuf, keystr_from_pk (pk),
                     strtimestamp (pk->timestamp));
-          p = get_user_id_native (list->kid);
+          p = get_user_id_native (ctrl, list->keyid);
           log_printf (_("      \"%s\"\n"), p);
           xfree (p);
         }
       else
         log_info (_("encrypted with %s key, ID %s\n"),
-                  algstr, keystr(list->kid));
+                  openpgp_pk_algo_name (list->pubkey_algo),
+                  keystr(list->keyid));
 
       free_public_key (pk);
-
-      if (gpg_err_code (list->reason) == GPG_ERR_NO_SECKEY)
-        {
-          if (is_status_enabled())
-            {
-              char buf[20];
-              snprintf (buf, sizeof buf, "%08lX%08lX",
-                        (ulong)list->kid[0], (ulong)list->kid[1]);
-              write_status_text (STATUS_NO_SECKEY, buf);
-           }
-       }
-      else if (list->reason)
-        {
-          log_info (_("public key decryption failed: %s\n"),
-                    gpg_strerror (list->reason));
-          write_status_error ("pkdecrypt_failed", list->reason);
-        }
     }
 }
 
@@ -525,6 +542,17 @@ static void
 proc_encrypted (CTX c, PACKET *pkt)
 {
   int result = 0;
+  int early_plaintext = literals_seen;
+
+  if (pkt->pkttype == PKT_ENCRYPTED_AEAD)
+    c->seen_pkt_encrypted_aead = 1;
+
+  if (early_plaintext)
+    {
+      log_info (_("WARNING: multiple plaintexts seen\n"));
+      write_status_errcode ("decryption.early_plaintext", GPG_ERR_BAD_DATA);
+      /* We fail only later so that we can print some more info first.  */
+    }
 
   if (!opt.quiet)
     {
@@ -532,11 +560,57 @@ proc_encrypted (CTX c, PACKET *pkt)
         log_info (_("encrypted with %lu passphrases\n"), c->symkeys);
       else if (c->symkeys == 1)
         log_info (_("encrypted with 1 passphrase\n"));
-      print_pkenc_list ( c->pkenc_list, 1 );
-      print_pkenc_list ( c->pkenc_list, 0 );
+      print_pkenc_list (c->ctrl, c->pkenc_list);
+    }
+
+  /* Figure out the session key by looking at all pkenc packets. */
+  if (opt.list_only || c->dek)
+    ;
+  else if (opt.override_session_key)
+    {
+      c->dek = xmalloc_clear (sizeof *c->dek);
+      result = get_override_session_key (c->dek, opt.override_session_key);
+      if (result)
+        {
+          xfree (c->dek);
+          c->dek = NULL;
+          log_info (_("public key decryption failed: %s\n"),
+                    gpg_strerror (result));
+          write_status_error ("pkdecrypt_failed", result);
+        }
+    }
+  else if (c->pkenc_list)
+    {
+      c->dek = xmalloc_secure_clear (sizeof *c->dek);
+      result = get_session_key (c->ctrl, c->pkenc_list, c->dek);
+      if (is_status_enabled ())
+        {
+          struct pubkey_enc_list *list;
+
+          for (list = c->pkenc_list; list; list = list->next)
+            if (list->result && list->result != -1)
+              {
+                char buf[20];
+                snprintf (buf, sizeof buf, "%08lX%08lX",
+                          (ulong)list->keyid[0], (ulong)list->keyid[1]);
+                write_status_text (STATUS_NO_SECKEY, buf);
+              }
+        }
+
+      if (result)
+        {
+          log_info (_("public key decryption failed: %s\n"),
+                    gpg_strerror (result));
+          write_status_error ("pkdecrypt_failed", result);
+
+          /* Error: Delete the DEK. */
+          xfree (c->dek);
+          c->dek = NULL;
+        }
     }
 
-  /* FIXME: Figure out the session key by looking at all pkenc packets. */
+  if (c->dek && opt.verbose > 1)
+    log_info (_("public key encrypted data: good DEK\n"));
 
   write_status (STATUS_BEGIN_DECRYPTION);
 
@@ -589,7 +663,7 @@ proc_encrypted (CTX c, PACKET *pkt)
               log_info (_("assuming %s encrypted data\n"), "IDEA");
             }
 
-          c->dek = passphrase_to_dek ( NULL, 0, algo, s2k, 3, NULL, &canceled);
+          c->dek = passphrase_to_dek (algo, s2k, 0, 0, NULL, &canceled);
           if (c->dek)
             c->dek->algo_info_printed = 1;
           else if (canceled)
@@ -599,41 +673,114 @@ proc_encrypted (CTX c, PACKET *pkt)
         }
     }
   else if (!c->dek)
-    result = GPG_ERR_NO_SECKEY;
+    {
+      if (c->symkeys && !c->pkenc_list)
+        result = gpg_error (GPG_ERR_BAD_KEY);
+
+      if (!result)
+        result = gpg_error (GPG_ERR_NO_SECKEY);
+    }
+
+  /* Compute compliance with CO_DE_VS.  */
+  if (!result && is_status_enabled ()
+      /* Symmetric encryption and asymmetric encryption voids compliance.  */
+      && (c->symkeys != !!c->pkenc_list )
+      /* Overriding session key voids compliance.  */
+      && !opt.override_session_key
+      /* Check symmetric cipher.  */
+      && gnupg_gcrypt_is_compliant (CO_DE_VS)
+      && gnupg_cipher_is_compliant (CO_DE_VS, c->dek->algo,
+                                    GCRY_CIPHER_MODE_CFB))
+    {
+      struct pubkey_enc_list *i;
+      int compliant = 1;
+      PKT_public_key *pk = xmalloc (sizeof *pk);
+
+      if ( !(c->pkenc_list || c->symkeys) )
+        log_debug ("%s: where else did the session key come from?\n", __func__);
+
+      /* Now check that every key used to encrypt the session key is
+       * compliant.  */
+      for (i = c->pkenc_list; i && compliant; i = i->next)
+        {
+          memset (pk, 0, sizeof *pk);
+          pk->pubkey_algo = i->pubkey_algo;
+          if (get_pubkey (c->ctrl, pk, i->keyid) != 0
+              || ! gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, 0,
+                                          pk->pkey, nbits_from_pk (pk), NULL))
+            compliant = 0;
+          release_public_key_parts (pk);
+        }
+
+      xfree (pk);
+
+      if (compliant)
+        write_status_strings (STATUS_DECRYPTION_COMPLIANCE_MODE,
+                              gnupg_status_compliance_flag (CO_DE_VS),
+                              NULL);
+
+    }
 
   if (!result)
     result = decrypt_data (c->ctrl, c, pkt->pkt.encrypted, c->dek );
 
+  /* Trigger the deferred error.  */
+  if (!result && early_plaintext)
+    result = gpg_error (GPG_ERR_BAD_DATA);
+
   if (result == -1)
     ;
   else if (!result
            && !opt.ignore_mdc_error
            && !pkt->pkt.encrypted->mdc_method
-           && openpgp_cipher_get_algo_blklen (c->dek->algo) != 8
-           && c->dek->algo != CIPHER_ALGO_TWOFISH)
-    {
-      /* The message has been decrypted but has no MDC despite that a
-         modern cipher (blocklength != 64 bit, except for Twofish) is
-         used and the option to ignore MDC errors is not used: To
-         avoid attacks changing an MDC message to a non-MDC message,
-         we fail here.  */
+           && !pkt->pkt.encrypted->aead_algo)
+    {
+      /* The message has been decrypted but does not carry an MDC or
+       * uses AEAD encryption.  --ignore-mdc-error has also not been
+       * used.  To avoid attacks changing an MDC message to a non-MDC
+       * message, we fail here.  */
       log_error (_("WARNING: message was not integrity protected\n"));
-      if (opt.verbose > 1)
-        log_info ("decryption forced to fail\n");
+      if (!pkt->pkt.encrypted->mdc_method
+          && (openpgp_cipher_get_algo_blklen (c->dek->algo) == 8
+              || c->dek->algo == CIPHER_ALGO_TWOFISH))
+        {
+          /* Before 2.2.8 we did not fail hard for a missing MDC if
+           * one of the old ciphers where used.  Although these cases
+           * are rare in practice we print a hint on how to decrypt
+           * such messages.  */
+          log_string
+            (GPGRT_LOGLVL_INFO,
+             _("Hint: If this message was created before the year 2003 it is\n"
+               "likely that this message is legitimate.  This is because back\n"
+               "then integrity protection was not widely used.\n"));
+          log_info (_("Use the option '%s' to decrypt anyway.\n"),
+                     "--ignore-mdc-error");
+          write_status_errcode ("nomdc_with_legacy_cipher",
+                                GPG_ERR_DECRYPT_FAILED);
+        }
+      log_info (_("decryption forced to fail!\n"));
       write_status (STATUS_DECRYPTION_FAILED);
     }
   else if (!result || (gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE
+                       && !pkt->pkt.encrypted->aead_algo
                        && opt.ignore_mdc_error))
     {
+      /* All is fine or for an MDC message the MDC failed but the
+       * --ignore-mdc-error option is active.  For compatibility
+       * reasons we issue GOODMDC also for AEAD messages.  */
       write_status (STATUS_DECRYPTION_OKAY);
       if (opt.verbose > 1)
         log_info(_("decryption okay\n"));
-      if (pkt->pkt.encrypted->mdc_method && !result)
+
+      if (pkt->pkt.encrypted->aead_algo)
         write_status (STATUS_GOODMDC);
-      else if (!opt.no_mdc_warn)
+      else if (pkt->pkt.encrypted->mdc_method && !result)
+        write_status (STATUS_GOODMDC);
+      else
         log_info (_("WARNING: message was not integrity protected\n"));
     }
-  else if (gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE)
+  else if (gpg_err_code (result) == GPG_ERR_BAD_SIGNATURE
+           || gpg_err_code (result) == GPG_ERR_TRUNCATED)
     {
       glo_ctrl.lasterr = result;
       log_error (_("WARNING: encrypted message has been manipulated!\n"));
@@ -642,13 +789,15 @@ proc_encrypted (CTX c, PACKET *pkt)
     }
   else
     {
-      if (gpg_err_code (result) == GPG_ERR_BAD_KEY
-          && *c->dek->s2k_cacheid != '\0')
+      if ((gpg_err_code (result) == GPG_ERR_BAD_KEY
+          || gpg_err_code (result) == GPG_ERR_CHECKSUM
+          || gpg_err_code (result) == GPG_ERR_CIPHER_ALGO)
+          && c->dek && *c->dek->s2k_cacheid != '\0')
         {
           if (opt.debug)
             log_debug ("cleared passphrase cached with ID: %s\n",
                        c->dek->s2k_cacheid);
-          passphrase_clear_cache (NULL, c->dek->s2k_cacheid, 0);
+          passphrase_clear_cache (c->dek->s2k_cacheid);
         }
       glo_ctrl.lasterr = result;
       write_status (STATUS_DECRYPTION_FAILED);
@@ -659,9 +808,30 @@ proc_encrypted (CTX c, PACKET *pkt)
 
   xfree (c->dek);
   c->dek = NULL;
-  free_packet (pkt);
+  free_packet (pkt, NULL);
   c->last_was_session_key = 0;
   write_status (STATUS_END_DECRYPTION);
+
+  /* Bump the counter even if we have not seen a literal data packet
+   * inside an encryption container.  This acts as a sentinel in case
+   * a misplace extra literal data packets follows after this
+   * encrypted packet.  */
+  literals_seen++;
+}
+
+
+static int
+have_seen_pkt_encrypted_aead( CTX c )
+{
+  CTX cc;
+
+  for (cc = c; cc; cc = cc->anchor)
+    {
+      if (cc->seen_pkt_encrypted_aead)
+       return 1;
+    }
+
+  return 0;
 }
 
 
@@ -671,13 +841,23 @@ proc_plaintext( CTX c, PACKET *pkt )
   PKT_plaintext *pt = pkt->pkt.plaintext;
   int any, clearsig, rc;
   kbnode_t n;
+  unsigned char *extrahash;
+  size_t extrahashlen;
 
+  /* This is a literal data packet.  Bump a counter for later checks.  */
   literals_seen++;
 
   if (pt->namelen == 8 && !memcmp( pt->name, "_CONSOLE", 8))
     log_info (_("Note: sender requested \"for-your-eyes-only\"\n"));
   else if (opt.verbose)
-    log_info (_("original file name='%.*s'\n"), pt->namelen, pt->name);
+    {
+      /* We don't use print_utf8_buffer because that would require a
+       * string change which we don't want in 2.2.  It is also not
+       * clear whether the filename is always utf-8 encoded.  */
+      char *tmp = make_printable_string (pt->name, pt->namelen, 0);
+      log_info (_("original file name='%.*s'\n"), (int)strlen (tmp), tmp);
+      xfree (tmp);
+    }
 
   free_md_filter_context (&c->mfx);
   if (gcry_md_open (&c->mfx.md, 0, 0))
@@ -696,7 +876,10 @@ proc_plaintext( CTX c, PACKET *pkt )
           /* The onepass signature case. */
           if (n->pkt->pkt.onepass_sig->digest_algo)
             {
-              gcry_md_enable (c->mfx.md, n->pkt->pkt.onepass_sig->digest_algo);
+              if (!opt.skip_verify)
+                gcry_md_enable (c->mfx.md,
+                                n->pkt->pkt.onepass_sig->digest_algo);
+
               any = 1;
             }
         }
@@ -714,7 +897,8 @@ proc_plaintext( CTX c, PACKET *pkt )
            * documents.  */
           clearsig = (*data == 0x01);
           for (data++, datalen--; datalen; datalen--, data++)
-            gcry_md_enable (c->mfx.md, *data);
+            if (!opt.skip_verify)
+              gcry_md_enable (c->mfx.md, *data);
           any = 1;
           break;  /* Stop here as one-pass signature packets are not
                      expected.  */
@@ -722,12 +906,13 @@ proc_plaintext( CTX c, PACKET *pkt )
       else if (n->pkt->pkttype == PKT_SIGNATURE)
         {
           /* The SIG+LITERAL case that PGP used to use.  */
-          gcry_md_enable ( c->mfx.md, n->pkt->pkt.signature->digest_algo );
+          if (!opt.skip_verify)
+            gcry_md_enable (c->mfx.md, n->pkt->pkt.signature->digest_algo);
           any = 1;
         }
     }
 
-  if (!any && !opt.skip_verify)
+  if (!any && !opt.skip_verify && !have_seen_pkt_encrypted_aead(c))
     {
       /* This is for the old GPG LITERAL+SIG case.  It's not legal
          according to 2440, so hopefully it won't come up that often.
@@ -749,17 +934,19 @@ proc_plaintext( CTX c, PACKET *pkt )
     {
       log_info (_("WARNING: multiple plaintexts seen\n"));
 
-      if (!opt.flags.allow_multiple_messages)
-        {
-          write_status_text (STATUS_ERROR, "proc_pkt.plaintext 89_BAD_DATA");
-          log_inc_errorcount ();
-          rc = gpg_error (GPG_ERR_UNEXPECTED);
-        }
+      write_status_text (STATUS_ERROR, "proc_pkt.plaintext 89_BAD_DATA");
+      log_inc_errorcount ();
+      rc = gpg_error (GPG_ERR_UNEXPECTED);
     }
 
   if (!rc)
     {
-      rc = handle_plaintext (pt, &c->mfx, c->sigs_only, clearsig);
+      /* It we are in --verify mode, we do not want to output the
+       * signed text.  However, if --output is also used we do what
+       * has been requested and write out the signed data.  */
+      rc = handle_plaintext (pt, &c->mfx,
+                             (opt.outfp || opt.outfile)? 0 :  c->sigs_only,
+                             clearsig);
       if (gpg_err_code (rc) == GPG_ERR_EACCES && !c->sigs_only)
         {
           /* Can't write output but we hash it anyway to check the
@@ -771,12 +958,37 @@ proc_plaintext( CTX c, PACKET *pkt )
   if (rc)
     log_error ("handle plaintext failed: %s\n", gpg_strerror (rc));
 
-  free_packet(pkt);
+  /* We add a marker control packet instead of the plaintext packet.
+   * This is so that we can later detect invalid packet sequences.
+   * The packet is further used to convey extra data from the
+   * plaintext packet to the signature verification. */
+  extrahash = xtrymalloc (6 + pt->namelen);
+  if (!extrahash)
+    {
+      /* No way to return an error.  */
+      rc = gpg_error_from_syserror ();
+      log_error ("malloc failed in %s: %s\n", __func__, gpg_strerror (rc));
+      extrahashlen = 0;
+    }
+  else
+    {
+      extrahash[0] = pt->mode;
+      extrahash[1] = pt->namelen;
+      if (pt->namelen)
+        memcpy (extrahash+2, pt->name, pt->namelen);
+      extrahashlen = 2 + pt->namelen;
+      extrahash[extrahashlen++] = pt->timestamp >> 24;
+      extrahash[extrahashlen++] = pt->timestamp >> 16;
+      extrahash[extrahashlen++] = pt->timestamp >>  8;
+      extrahash[extrahashlen++] = pt->timestamp      ;
+    }
+
+  free_packet (pkt, NULL);
   c->last_was_session_key = 0;
 
-  /* We add a marker control packet instead of the plaintext packet.
-   * This is so that we can later detect invalid packet sequences.  */
-  n = new_kbnode (create_gpg_control (CTRLPKT_PLAINTEXT_MARK, NULL, 0));
+  n = new_kbnode (create_gpg_control (CTRLPKT_PLAINTEXT_MARK,
+                                      extrahash, extrahashlen));
+  xfree (extrahash);
   if (c->list)
     add_kbnode (c->list, n);
   else
@@ -834,19 +1046,23 @@ proc_compressed (CTX c, PACKET *pkt)
   else if (rc)
     log_error ("uncompressing failed: %s\n", gpg_strerror (rc));
 
-  free_packet(pkt);
+  free_packet (pkt, NULL);
   c->last_was_session_key = 0;
   return rc;
 }
 
 
 /*
- * check the signature
- * Returns: 0 = valid signature or an error code
+ * Check the signature.  If R_PK is not NULL a copy of the public key
+ * used to verify the signature will be stored there, or NULL if not
+ * found.  If FORCED_PK is not NULL, this public key is used to verify
+ * _data signatures_ and no key lookup is done.  Returns: 0 = valid
+ * signature or an error code
  */
 static int
-do_check_sig (CTX c, kbnode_t node, int *is_selfsig,
-             int *is_expkey, int *is_revkey)
+do_check_sig (CTX c, kbnode_t node, const void *extrahash, size_t extrahashlen,
+              PKT_public_key *forced_pk, int *is_selfsig,
+             int *is_expkey, int *is_revkey, PKT_public_key **r_pk)
 {
   PKT_signature *sig;
   gcry_md_hd_t md = NULL;
@@ -854,6 +1070,9 @@ do_check_sig (CTX c, kbnode_t node, int *is_selfsig,
   gcry_md_hd_t md_good = NULL;
   int algo, rc;
 
+  if (r_pk)
+    *r_pk = NULL;
+
   log_assert (node->pkt->pkttype == PKT_SIGNATURE);
   if (is_selfsig)
     *is_selfsig = 0;
@@ -909,7 +1128,7 @@ do_check_sig (CTX c, kbnode_t node, int *is_selfsig,
       if (c->list->pkt->pkttype == PKT_PUBLIC_KEY
           || c->list->pkt->pkttype == PKT_PUBLIC_SUBKEY)
         {
-          return check_key_signature( c->list, node, is_selfsig );
+          return check_key_signature (c->ctrl, c->list, node, is_selfsig);
        }
       else if (sig->sig_class == 0x20)
         {
@@ -928,19 +1147,33 @@ do_check_sig (CTX c, kbnode_t node, int *is_selfsig,
 
   /* We only get here if we are checking the signature of a binary
      (0x00) or text document (0x01).  */
-  rc = check_signature2 (sig, md, NULL, is_expkey, is_revkey, NULL);
+  rc = check_signature2 (c->ctrl, sig, md, extrahash, extrahashlen,
+                         forced_pk,
+                         NULL, is_expkey, is_revkey, r_pk);
   if (! rc)
     md_good = md;
   else if (gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE && md2)
     {
-      rc = check_signature2 (sig, md2, NULL, is_expkey, is_revkey, NULL);
-      if (! rc)
-       md_good = md2;
+      PKT_public_key *pk2;
+
+      rc = check_signature2 (c->ctrl, sig, md2, extrahash, extrahashlen,
+                             forced_pk,
+                             NULL, is_expkey, is_revkey,
+                             r_pk? &pk2 : NULL);
+      if (!rc)
+        {
+          md_good = md2;
+          if (r_pk)
+            {
+              free_public_key (*r_pk);
+              *r_pk = pk2;
+            }
+        }
     }
 
   if (md_good)
     {
-      unsigned char *buffer = gcry_md_read (md_good, 0);
+      unsigned char *buffer = gcry_md_read (md_good, sig->digest_algo);
       sig->digest_len = gcry_md_get_algo_dlen (map_md_openpgp_to_gcry (algo));
       memcpy (sig->digest, buffer, sig->digest_len);
     }
@@ -985,13 +1218,10 @@ print_userid (PACKET *pkt)
 static void
 list_node (CTX c, kbnode_t node)
 {
-  int mainkey;
-  char pkstrbuf[PUBKEY_STRING_SIZE];
-
   if (!node)
     ;
-  else if ((mainkey = (node->pkt->pkttype == PKT_PUBLIC_KEY))
-           || node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
+  else if (node->pkt->pkttype == PKT_PUBLIC_KEY
+           || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
     {
       PKT_public_key *pk = node->pkt->pkt.public_key;
 
@@ -1000,10 +1230,15 @@ list_node (CTX c, kbnode_t node)
           u32 keyid[2];
 
           keyid_from_pk( pk, keyid );
-          if (mainkey)
-            c->trustletter = (opt.fast_list_mode?
-                              0 : get_validity_info( pk, NULL));
-          es_printf ("%s:", mainkey? "pub":"sub" );
+          if (pk->flags.primary)
+            c->trustletter = (opt.fast_list_mode
+                              ? 0
+                              : get_validity_info
+                                  (c->ctrl,
+                                   node->pkt->pkttype == PKT_PUBLIC_KEY
+                                   ? node : NULL,
+                                   pk, NULL));
+          es_printf ("%s:", pk->flags.primary? "pub":"sub" );
           if (c->trustletter)
             es_putc (c->trustletter, es_stdout);
           es_printf (":%u:%d:%08lX%08lX:%s:%s::",
@@ -1012,44 +1247,25 @@ list_node (CTX c, kbnode_t node)
                      (ulong)keyid[0],(ulong)keyid[1],
                      colon_datestr_from_pk( pk ),
                      colon_strtime (pk->expiredate) );
-          if (mainkey && !opt.fast_list_mode)
-            es_putc (get_ownertrust_info (pk), es_stdout);
+          if (pk->flags.primary && !opt.fast_list_mode)
+            es_putc (get_ownertrust_info (c->ctrl, pk, 1), es_stdout);
           es_putc (':', es_stdout);
+          es_putc ('\n', es_stdout);
         }
       else
-        es_printf ("%s  %s/%s %s",
-                   mainkey? "pub":"sub",
-                   pubkey_string (pk, pkstrbuf, sizeof pkstrbuf),
-                   keystr_from_pk (pk),
-                   datestr_from_pk (pk));
-
-      if (pk->flags.revoked)
         {
-          es_printf (" [");
-          es_printf (_("revoked: %s"), revokestr_from_pk (pk));
-          es_printf ("]\n");
+          print_key_line (c->ctrl, es_stdout, pk, 0);
         }
-      else if( pk->expiredate && !opt.with_colons)
-        {
-          es_printf (" [");
-          es_printf (_("expires: %s"), expirestr_from_pk (pk));
-          es_printf ("]\n");
-        }
-      else
-        es_putc ('\n', es_stdout);
 
-      if ((mainkey && opt.fingerprint) || opt.fingerprint > 1)
-        print_fingerprint (NULL, pk, 0);
+      if (opt.keyid_format == KF_NONE && !opt.with_colons)
+        ; /* Already printed.  */
+      else if ((pk->flags.primary && opt.fingerprint) || opt.fingerprint > 1)
+        print_fingerprint (c->ctrl, NULL, pk, 0);
 
-      if (opt.with_colons)
+      if (pk->flags.primary)
         {
-          if (node->next && node->next->pkt->pkttype == PKT_RING_TRUST)
-            es_printf ("rtv:1:%u:\n",
-                       node->next->pkt->pkt.ring_trust->trustval);
-        }
+          int kl = opt.keyid_format == KF_NONE? 0 : keystrlen ();
 
-      if (mainkey)
-        {
           /* Now list all userids with their signatures. */
           for (node = node->next; node; node = node->next)
             {
@@ -1064,20 +1280,12 @@ list_node (CTX c, kbnode_t node)
                                node->pkt->pkt.user_id->attrib_data?"uat":"uid");
                   else
                     es_printf ("uid%*s",
-                               (int)keystrlen ()+(opt.legacy_list_mode? 9:11),
+                               kl + (opt.legacy_list_mode? 9:11),
                                "" );
                   print_userid (node->pkt);
                   if (opt.with_colons)
                     es_putc (':', es_stdout);
                   es_putc ('\n', es_stdout);
-                  if (opt.with_colons
-                      && node->next
-                      && node->next->pkt->pkttype == PKT_RING_TRUST)
-                    {
-                      es_printf ("rtv:2:%u:\n",
-                                 node->next->pkt->pkt.ring_trust?
-                                 node->next->pkt->pkt.ring_trust->trustval : 0);
-                    }
                }
               else if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
                 {
@@ -1086,7 +1294,7 @@ list_node (CTX c, kbnode_t node)
             }
         }
     }
-  else if ((mainkey = (node->pkt->pkttype == PKT_SECRET_KEY) )
+  else if (node->pkt->pkttype == PKT_SECRET_KEY
            || node->pkt->pkttype == PKT_SECRET_SUBKEY)
     {
 
@@ -1113,7 +1321,8 @@ list_node (CTX c, kbnode_t node)
       if (opt.check_sigs)
         {
           fflush (stdout);
-          rc2 = do_check_sig (c, node, &is_selfsig, NULL, NULL);
+          rc2 = do_check_sig (c, node, NULL, 0, NULL,
+                              &is_selfsig, NULL, NULL, NULL);
           switch (gpg_err_code (rc2))
             {
             case 0:                      sigrc = '!'; break;
@@ -1173,7 +1382,7 @@ list_node (CTX c, kbnode_t node)
        }
       else if (!opt.fast_list_mode)
         {
-          p = get_user_id (sig->keyid, &n);
+          p = get_user_id (c->ctrl, sig->keyid, &n, NULL);
           es_write_sanitized (es_stdout, p, n,
                               opt.with_colons?":":NULL, NULL );
           xfree (p);
@@ -1195,7 +1404,7 @@ proc_packets (ctrl_t ctrl, void *anchor, iobuf_t a )
 
   c->ctrl = ctrl;
   c->anchor = anchor;
-  rc = do_proc_packets (ctrl, c, a);
+  rc = do_proc_packets (c, a);
   xfree (c);
 
   return rc;
@@ -1218,7 +1427,7 @@ proc_signature_packets (ctrl_t ctrl, void *anchor, iobuf_t a,
   c->signed_data.used = !!signedfiles;
 
   c->sigfilename = sigfilename;
-  rc = do_proc_packets (ctrl, c, a);
+  rc = do_proc_packets (c, a);
 
   /* If we have not encountered any signature we print an error
      messages, send a NODATA status back and return an error code.
@@ -1261,7 +1470,7 @@ proc_signature_packets_by_fd (ctrl_t ctrl,
   c->signed_data.data_names = NULL;
   c->signed_data.used = (signed_data_fd != -1);
 
-  rc = do_proc_packets (ctrl, c, a);
+  rc = do_proc_packets (c, a);
 
   /* If we have not encountered any signature we print an error
      messages, send a NODATA status back and return an error code.
@@ -1294,7 +1503,7 @@ proc_encryption_packets (ctrl_t ctrl, void *anchor, iobuf_t a )
   c->ctrl = ctrl;
   c->anchor = anchor;
   c->encrypt_only = 1;
-  rc = do_proc_packets (ctrl, c, a);
+  rc = do_proc_packets (c, a);
   xfree (c);
   return rc;
 }
@@ -1320,9 +1529,10 @@ check_nesting (CTX c)
 
 
 static int
-do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a)
+do_proc_packets (CTX c, iobuf_t a)
 {
   PACKET *pkt;
+  struct parse_packet_ctx_s parsectx;
   int rc = 0;
   int any_data = 0;
   int newpkt;
@@ -1334,16 +1544,17 @@ do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a)
   pkt = xmalloc( sizeof *pkt );
   c->iobuf = a;
   init_packet(pkt);
-  while ((rc=parse_packet(a, pkt)) != -1)
+  init_parse_packet (&parsectx, a);
+  while ((rc=parse_packet (&parsectx, pkt)) != -1)
     {
       any_data = 1;
       if (rc)
         {
-          free_packet (pkt);
+          free_packet (pkt, &parsectx);
           /* Stop processing when an invalid packet has been encountered
            * but don't do so when we are doing a --list-packets.  */
           if (gpg_err_code (rc) == GPG_ERR_INV_PACKET
-              && opt.list_packets != 2 )
+              && opt.list_packets == 0)
             break;
           continue;
        }
@@ -1352,10 +1563,11 @@ do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a)
         {
           switch (pkt->pkttype)
             {
-            case PKT_PUBKEY_ENC:    proc_pubkey_enc (ctrl, c, pkt); break;
+            case PKT_PUBKEY_ENC:    proc_pubkey_enc (c, pkt); break;
             case PKT_SYMKEY_ENC:    proc_symkey_enc (c, pkt); break;
             case PKT_ENCRYPTED:
-            case PKT_ENCRYPTED_MDC: proc_encrypted (c, pkt); break;
+            case PKT_ENCRYPTED_MDC:
+            case PKT_ENCRYPTED_AEAD:proc_encrypted (c, pkt); break;
             case PKT_COMPRESSED:    rc = proc_compressed (c, pkt); break;
             default: newpkt = 0; break;
            }
@@ -1371,6 +1583,7 @@ do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a)
             case PKT_PUBKEY_ENC:
             case PKT_ENCRYPTED:
             case PKT_ENCRYPTED_MDC:
+            case PKT_ENCRYPTED_AEAD:
               write_status_text( STATUS_UNEXPECTED, "0" );
               rc = GPG_ERR_UNEXPECTED;
               goto leave;
@@ -1396,9 +1609,10 @@ do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a)
 
             case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
             case PKT_SYMKEY_ENC:  proc_symkey_enc (c, pkt); break;
-            case PKT_PUBKEY_ENC:  proc_pubkey_enc (ctrl, c, pkt); break;
+            case PKT_PUBKEY_ENC:  proc_pubkey_enc (c, pkt); break;
             case PKT_ENCRYPTED:
-            case PKT_ENCRYPTED_MDC: proc_encrypted (c, pkt); break;
+            case PKT_ENCRYPTED_MDC:
+            case PKT_ENCRYPTED_AEAD: proc_encrypted (c, pkt); break;
             case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
             case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
             case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
@@ -1422,10 +1636,11 @@ do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a)
               break;
             case PKT_USER_ID:     newpkt = add_user_id (c, pkt); break;
             case PKT_SIGNATURE:   newpkt = add_signature (c, pkt); break;
-            case PKT_PUBKEY_ENC:  proc_pubkey_enc (ctrl, c, pkt); break;
+            case PKT_PUBKEY_ENC:  proc_pubkey_enc (c, pkt); break;
             case PKT_SYMKEY_ENC:  proc_symkey_enc (c, pkt); break;
             case PKT_ENCRYPTED:
-            case PKT_ENCRYPTED_MDC: proc_encrypted (c, pkt); break;
+            case PKT_ENCRYPTED_MDC:
+            case PKT_ENCRYPTED_AEAD: proc_encrypted (c, pkt); break;
             case PKT_PLAINTEXT:   proc_plaintext (c, pkt); break;
             case PKT_COMPRESSED:  rc = proc_compressed (c, pkt); break;
             case PKT_ONEPASS_SIG: newpkt = add_onepass_sig (c, pkt); break;
@@ -1457,7 +1672,7 @@ do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a)
           init_packet (pkt);
        }
       else
-        free_packet(pkt);
+        free_packet (pkt, &parsectx);
     }
 
   if (rc == GPG_ERR_INV_PACKET)
@@ -1472,87 +1687,58 @@ do_proc_packets (ctrl_t ctrl, CTX c, iobuf_t a)
  leave:
   release_list (c);
   xfree(c->dek);
-  free_packet (pkt);
+  free_packet (pkt, &parsectx);
+  deinit_parse_packet (&parsectx);
   xfree (pkt);
   free_md_filter_context (&c->mfx);
   return rc;
 }
 
 
-/* Helper for pka_uri_from_sig to parse the to-be-verified address out
-   of the notation data. */
-static pka_info_t *
-get_pka_address (PKT_signature *sig)
+/* Return true if the AKL has the WKD method specified.  */
+static int
+akl_has_wkd_method (void)
 {
-  pka_info_t *pka = NULL;
-  struct notation *nd,*notation;
-
-  notation=sig_to_notation(sig);
-
-  for(nd=notation;nd;nd=nd->next)
-    {
-      if(strcmp(nd->name,"pka-address@gnupg.org")!=0)
-        continue; /* Not the notation we want. */
-
-      /* For now we only use the first valid PKA notation. In future
-        we might want to keep additional PKA notations in a linked
-        list. */
-      if (is_valid_mailbox (nd->value))
-       {
-         pka = xmalloc (sizeof *pka + strlen(nd->value));
-         pka->valid = 0;
-         pka->checked = 0;
-         pka->uri = NULL;
-         strcpy (pka->email, nd->value);
-         break;
-       }
-    }
-
-  free_notation(notation);
+  struct akl *akl;
 
-  return pka;
+  for (akl = opt.auto_key_locate; akl; akl = akl->next)
+    if (akl->type == AKL_WKD)
+      return 1;
+  return 0;
 }
 
 
-/* Return the URI from a DNS PKA record.  If this record has already
-   be retrieved for the signature we merely return it; if not we go
  out and try to get that DNS record. */
-static const char *
-pka_uri_from_sig (CTX c, PKT_signature *sig)
+/* Return the ISSUER fingerprint buffer and its length at R_LEN.
+ * Returns NULL if not available.  The returned buffer is valid as
* long as SIG is not modified.  */
+const byte *
+issuer_fpr_raw (PKT_signature *sig, size_t *r_len)
 {
-  if (!sig->flags.pka_tried)
-    {
-      log_assert (!sig->pka_info);
-      sig->flags.pka_tried = 1;
-      sig->pka_info = get_pka_address (sig);
-      if (sig->pka_info)
-        {
-          char *url;
-          unsigned char *fpr;
-          size_t fprlen;
+  const byte *p;
+  size_t n;
 
-          if (!gpg_dirmngr_get_pka (c->ctrl, sig->pka_info->email,
-                                    &fpr, &fprlen, &url))
-            {
-              if (fpr && fprlen == sizeof sig->pka_info->fpr)
-                {
-                  memcpy (sig->pka_info->fpr, fpr, fprlen);
-                  if (url)
-                    {
-                      sig->pka_info->valid = 1;
-                      if (!*url)
-                        xfree (url);
-                      else
-                        sig->pka_info->uri = url;
-                      url = NULL;
-                    }
-                }
-              xfree (fpr);
-              xfree (url);
-            }
-        }
+  p = parse_sig_subpkt (sig, 1, SIGSUBPKT_ISSUER_FPR, &n);
+  if (p && ((n == 21 && p[0] == 4) || (n == 33 && p[0] == 5)))
+    {
+      *r_len = n - 1;
+      return p+1;
     }
-  return sig->pka_info? sig->pka_info->uri : NULL;
+  *r_len = 0;
+  return NULL;
+}
+
+
+/* Return the ISSUER fingerprint string in human readable format if
+ * available.  Caller must release the string.  */
+/* FIXME: Move to another file.  */
+char *
+issuer_fpr_string (PKT_signature *sig)
+{
+  const byte *p;
+  size_t n;
+
+  p = issuer_fpr_raw (sig, &n);
+  return p? bin2hex (p, n, NULL) : NULL;
 }
 
 
@@ -1589,12 +1775,14 @@ check_sig_and_print (CTX c, kbnode_t node)
 {
   PKT_signature *sig = node->pkt->pkt.signature;
   const char *astr;
-  int rc;
+  gpg_error_t rc;
   int is_expkey = 0;
   int is_revkey = 0;
-  char pkstrbuf[PUBKEY_STRING_SIZE];
-
-  *pkstrbuf = 0;
+  char *issuer_fpr = NULL;
+  PKT_public_key *pk = NULL;  /* The public key for the signature or NULL. */
+  const void *extrahash = NULL;
+  size_t extrahashlen = 0;
+  kbnode_t included_keyblock = NULL;
 
   if (opt.skip_verify)
     {
@@ -1603,31 +1791,31 @@ check_sig_and_print (CTX c, kbnode_t node)
     }
 
   /* Check that the message composition is valid.
-
-     Per RFC-2440bis (-15) allowed:
-
-     S{1,n}           -- detached signature.
-     S{1,n} P         -- old style PGP2 signature
-     O{1,n} P S{1,n}  -- standard OpenPGP signature.
-     C P S{1,n}       -- cleartext signature.
-
-
-          O = One-Pass Signature packet.
-          S = Signature packet.
-          P = OpenPGP Message packet (Encrypted | Compressed | Literal)
-                 (Note that the current rfc2440bis draft also allows
-                  for a signed message but that does not work as it
-                  introduces ambiguities.)
-              We keep track of these packages using the marker packet
-              CTRLPKT_PLAINTEXT_MARK.
-          C = Marker packet for cleartext signatures.
-
-     We reject all other messages.
-
-     Actually we are calling this too often, i.e. for verification of
-     each message but better have some duplicate work than to silently
-     introduce a bug here.
-  */
+   *
+   * Per RFC-2440bis (-15) allowed:
+   *
+   * S{1,n}           -- detached signature.
+   * S{1,n} P         -- old style PGP2 signature
+   * O{1,n} P S{1,n}  -- standard OpenPGP signature.
+   * C P S{1,n}       -- cleartext signature.
+   *
+   *
+   *      O = One-Pass Signature packet.
+   *      S = Signature packet.
+   *      P = OpenPGP Message packet (Encrypted | Compressed | Literal)
+   *             (Note that the current rfc2440bis draft also allows
+   *              for a signed message but that does not work as it
+   *              introduces ambiguities.)
+   *          We keep track of these packages using the marker packet
+   *          CTRLPKT_PLAINTEXT_MARK.
+   *      C = Marker packet for cleartext signatures.
+   *
+   * We reject all other messages.
+   *
+   * Actually we are calling this too often, i.e. for verification of
+   * each message but better have some duplicate work than to silently
+   * introduce a bug here.
+   */
   {
     kbnode_t n;
     int n_onepass, n_sig;
@@ -1652,6 +1840,8 @@ check_sig_and_print (CTX c, kbnode_t node)
           {
             if (n->next)
               goto ambiguous;  /* We only allow one P packet. */
+            extrahash = n->pkt->pkt.gpg_control->data;
+            extrahashlen = n->pkt->pkt.gpg_control->datalen;
           }
         else
           goto ambiguous;
@@ -1666,6 +1856,9 @@ check_sig_and_print (CTX c, kbnode_t node)
                     && (n->pkt->pkt.gpg_control->control
                         == CTRLPKT_PLAINTEXT_MARK)))
           goto ambiguous;
+        extrahash = n->pkt->pkt.gpg_control->data;
+        extrahashlen = n->pkt->pkt.gpg_control->datalen;
+
         for (n_sig=0, n = n->next;
              n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
           n_sig++;
@@ -1673,14 +1866,12 @@ check_sig_and_print (CTX c, kbnode_t node)
           goto ambiguous;
 
        /* If we wanted to disallow multiple sig verification, we'd do
-          something like this:
-
-          if (n && !opt.allow_multisig_verification)
-             goto ambiguous;
-
-          However, now that we have --allow-multiple-messages, this
-          can stay allowable as we can't get here unless multiple
-          messages (i.e. multiple literals) are allowed. */
+        * something like this:
+         *
+        * if (n)
+         *   goto ambiguous;
+         *
+         * However, this can stay allowable as we can't get here.  */
 
         if (n_onepass != n_sig)
           {
@@ -1698,6 +1889,8 @@ check_sig_and_print (CTX c, kbnode_t node)
                     && (n->pkt->pkt.gpg_control->control
                         == CTRLPKT_PLAINTEXT_MARK)))
           goto ambiguous;
+        extrahash = n->pkt->pkt.gpg_control->data;
+        extrahashlen = n->pkt->pkt.gpg_control->datalen;
         for (n_sig=0, n = n->next;
              n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
           n_sig++;
@@ -1710,33 +1903,87 @@ check_sig_and_print (CTX c, kbnode_t node)
         log_error(_("can't handle this ambiguous signature data\n"));
         return 0;
       }
-  }
+  } /* End checking signature packet composition.  */
 
-  write_status_text (STATUS_NEWSIG, NULL);
+  if (sig->signers_uid)
+    write_status_buffer (STATUS_NEWSIG,
+                         sig->signers_uid, strlen (sig->signers_uid), 0);
+  else
+    write_status_text (STATUS_NEWSIG, NULL);
 
   astr = openpgp_pk_algo_name ( sig->pubkey_algo );
-  if (keystrlen () > 8)
+  issuer_fpr = issuer_fpr_string (sig);
+
+  if (issuer_fpr)
     {
       log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp));
       log_info (_("               using %s key %s\n"),
-                astr? astr: "?",keystr(sig->keyid));
+                astr? astr: "?", issuer_fpr);
+
     }
-  else
+  else if (!keystrlen () || keystrlen () > 8)
+    {
+      log_info (_("Signature made %s\n"), asctimestamp(sig->timestamp));
+      log_info (_("               using %s key %s\n"),
+                astr? astr: "?", keystr(sig->keyid));
+    }
+  else /* Legacy format.  */
     log_info (_("Signature made %s using %s key ID %s\n"),
               asctimestamp(sig->timestamp), astr? astr: "?",
               keystr(sig->keyid));
 
-  rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey );
+  /* In verbose mode print the signers UID.  */
+  if (sig->signers_uid)
+    log_info (_("               issuer \"%s\"\n"), sig->signers_uid);
+
+  rc = do_check_sig (c, node, extrahash, extrahashlen, NULL,
+                     NULL, &is_expkey, &is_revkey, &pk);
+
+  /* If the key is not found but the signature includes a key block we
+   * use that key block for verification and on success import it.  */
+  if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
+      && sig->flags.key_block
+      && opt.flags.auto_key_import)
+    {
+      PKT_public_key *included_pk;
+      const byte *kblock;
+      size_t kblock_len;
+
+      included_pk = xcalloc (1, sizeof *included_pk);
+      kblock = parse_sig_subpkt (sig, 1, SIGSUBPKT_KEY_BLOCK, &kblock_len);
+      if (kblock && kblock_len > 1
+          && !get_pubkey_from_buffer (c->ctrl, included_pk,
+                                      kblock+1, kblock_len-1,
+                                      sig->keyid, &included_keyblock))
+        {
+          rc = do_check_sig (c, node, extrahash, extrahashlen, included_pk,
+                             NULL, &is_expkey, &is_revkey, &pk);
+          if (opt.verbose)
+            log_debug ("checked signature using included key block: %s\n",
+                       gpg_strerror (rc));
+          if (!rc)
+            {
+              /* The keyblock has been verified, we now import it.  */
+              rc = import_included_key_block (c->ctrl, included_keyblock);
+            }
 
-  /* If the key isn't found, check for a preferred keyserver */
+        }
+      free_public_key (included_pk);
+    }
 
-  if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY && sig->flags.pref_ks)
+  /* If the key isn't found, check for a preferred keyserver.  Note
+   * that this is only done if honor-keyserver-url has been set.  We
+   * test for this in the loop so that we can show info about the
+   * preferred keyservers.  */
+  if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
+      && sig->flags.pref_ks)
     {
       const byte *p;
       int seq = 0;
       size_t n;
+      int any_pref_ks = 0;
 
-      while ((p=enum_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS,&n,&seq,NULL)))
+      while ((p=enum_sig_subpkt (sig, 1, SIGSUBPKT_PREF_KS, &n, &seq, NULL)))
         {
           /* According to my favorite copy editor, in English grammar,
              you say "at" if the key is located on a web page, but
@@ -1745,9 +1992,10 @@ check_sig_and_print (CTX c, kbnode_t node)
           log_info(_("Key available at: ") );
           print_utf8_buffer (log_get_stream(), p, n);
           log_printf ("\n");
+          any_pref_ks = 1;
 
-          if (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE
-              && opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
+          if ((opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
+              && (opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL))
             {
               struct keyserver_spec *spec;
 
@@ -1756,11 +2004,22 @@ check_sig_and_print (CTX c, kbnode_t node)
                 {
                   int res;
 
+                  if (DBG_LOOKUP)
+                    log_debug ("trying auto-key-retrieve method %s\n",
+                               "Pref-KS");
+
+                  free_public_key (pk);
+                  pk = NULL;
                   glo_ctrl.in_auto_key_retrieve++;
-                  res = keyserver_import_keyid (c->ctrl, sig->keyid,spec);
+                  res = keyserver_import_keyid (c->ctrl, sig->keyid,spec,
+                                                KEYSERVER_IMPORT_FLAG_QUICK);
                   glo_ctrl.in_auto_key_retrieve--;
                   if (!res)
-                    rc = do_check_sig(c, node, NULL, &is_expkey, &is_revkey );
+                    rc = do_check_sig (c, node, extrahash, extrahashlen, NULL,
+                                       NULL, &is_expkey, &is_revkey, &pk);
+                  else if (DBG_LOOKUP)
+                    log_debug ("lookup via %s failed: %s\n", "Pref-KS",
+                               gpg_strerror (res));
                   free_keyserver_spec (spec);
 
                   if (!rc)
@@ -1768,59 +2027,85 @@ check_sig_and_print (CTX c, kbnode_t node)
                 }
             }
         }
+
+      if (any_pref_ks
+          && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
+          && !(opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL))
+        log_info (_("Note: Use '%s' to make use of this info\n"),
+                  "--keyserver-option honor-keyserver-url");
     }
 
-  /* If the preferred keyserver thing above didn't work, our second
-     try is to use the URI from a DNS PKA record. */
+  /* If the above methods didn't work, our next try is to retrieve the
+   * key from the WKD.  This requires that WKD is in the AKL and the
+   * Signer's UID is in the signature.  */
   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
       && (opt.keyserver_options.options & KEYSERVER_AUTO_KEY_RETRIEVE)
-      && (opt.keyserver_options.options & KEYSERVER_HONOR_PKA_RECORD))
+      && !opt.flags.disable_signer_uid
+      && akl_has_wkd_method ()
+      && sig->signers_uid)
     {
-      const char *uri = pka_uri_from_sig (c, sig);
-
-      if (uri)
-        {
-          /* FIXME: We might want to locate the key using the
-             fingerprint instead of the keyid. */
-          int res;
-          struct keyserver_spec *spec;
+      int res;
 
-          spec = parse_keyserver_uri (uri, 1);
-          if (spec)
-            {
-              glo_ctrl.in_auto_key_retrieve++;
-              res = keyserver_import_keyid (c->ctrl, sig->keyid, spec);
-                glo_ctrl.in_auto_key_retrieve--;
-                free_keyserver_spec (spec);
-                if (!res)
-                  rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey );
-            }
-        }
+      if (DBG_LOOKUP)
+        log_debug ("trying auto-key-retrieve method %s\n", "WKD");
+      free_public_key (pk);
+      pk = NULL;
+      glo_ctrl.in_auto_key_retrieve++;
+      res = keyserver_import_wkd (c->ctrl, sig->signers_uid,
+                                  KEYSERVER_IMPORT_FLAG_QUICK, NULL, NULL);
+      glo_ctrl.in_auto_key_retrieve--;
+      /* Fixme: If the fingerprint is embedded in the signature,
+       * compare it to the fingerprint of the returned key.  */
+      if (!res)
+        rc = do_check_sig (c, node, extrahash, extrahashlen, NULL,
+                           NULL, &is_expkey, &is_revkey, &pk);
+      else if (DBG_LOOKUP)
+        log_debug ("lookup via %s failed: %s\n", "WKD", gpg_strerror (res));
     }
 
-  /* If the preferred keyserver thing above didn't work and we got
-       no information from the DNS PKA, this is a third try. */
-
+  /* If the above methods didn't work, our next try is to locate
+   * the key via its fingerprint from a keyserver.  This requires
+   * that the signers fingerprint is encoded in the signature.  */
   if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
       && (opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
       && keyserver_any_configured (c->ctrl))
     {
       int res;
+      const byte *p;
+      size_t n;
 
-      glo_ctrl.in_auto_key_retrieve++;
-      res=keyserver_import_keyid (c->ctrl, sig->keyid, opt.keyserver );
-      glo_ctrl.in_auto_key_retrieve--;
-      if (!res)
-        rc = do_check_sig (c, node, NULL, &is_expkey, &is_revkey );
+      p = issuer_fpr_raw (sig, &n);
+      if (p)
+        {
+          if (DBG_LOOKUP)
+            log_debug ("trying auto-key-retrieve method %s\n", "KS");
+
+          /* v4 or v5 packet with a SHA-1/256 fingerprint.  */
+          free_public_key (pk);
+          pk = NULL;
+          glo_ctrl.in_auto_key_retrieve++;
+          res = keyserver_import_fprint (c->ctrl, p, n, opt.keyserver,
+                                         KEYSERVER_IMPORT_FLAG_QUICK);
+          glo_ctrl.in_auto_key_retrieve--;
+          if (!res)
+            rc = do_check_sig (c, node, extrahash, extrahashlen, NULL,
+                               NULL, &is_expkey, &is_revkey, &pk);
+          else if (DBG_LOOKUP)
+            log_debug ("lookup via %s failed: %s\n", "KS", gpg_strerror (res));
+        }
     }
 
+  /* Do do something with the result of the signature checking.  */
   if (!rc || gpg_err_code (rc) == GPG_ERR_BAD_SIGNATURE)
     {
+      /* We have checked the signature and the result is either a good
+       * signature or a bad signature.  Further examination follows.  */
       kbnode_t un, keyblock;
       int count = 0;
+      int keyblock_has_pk = 0;  /* For failsafe check.  */
       int statno;
       char keyid_str[50];
-      PKT_public_key *pk = NULL;
+      PKT_public_key *mainpk = NULL;
 
       if (rc)
         statno = STATUS_BADSIG;
@@ -1833,7 +2118,17 @@ check_sig_and_print (CTX c, kbnode_t node)
       else
         statno = STATUS_GOODSIG;
 
-      keyblock = get_pubkeyblock (sig->keyid);
+      /* FIXME: We should have the public key in PK and thus the
+       * keyblock has already been fetched.  Thus we could use the
+       * fingerprint or PK itself to lookup the entire keyblock.  That
+       * would best be done with a cache.  */
+      if (included_keyblock)
+        {
+          keyblock = included_keyblock;
+          included_keyblock = NULL;
+        }
+      else
+        keyblock = get_pubkeyblock_for_sig (c->ctrl, sig);
 
       snprintf (keyid_str, sizeof keyid_str, "%08lX%08lX [uncertain] ",
                 (ulong)sig->keyid[0], (ulong)sig->keyid[1]);
@@ -1844,26 +2139,33 @@ check_sig_and_print (CTX c, kbnode_t node)
         {
           int valid;
 
-          if (un->pkt->pkttype==PKT_PUBLIC_KEY)
+          if (!keyblock_has_pk
+              && (un->pkt->pkttype == PKT_PUBLIC_KEY
+                  || un->pkt->pkttype == PKT_PUBLIC_SUBKEY)
+              && !cmp_public_keys (un->pkt->pkt.public_key, pk))
             {
-              pk=un->pkt->pkt.public_key;
+              keyblock_has_pk = 1;
+            }
+          if (un->pkt->pkttype == PKT_PUBLIC_KEY)
+            {
+              mainpk = un->pkt->pkt.public_key;
               continue;
             }
           if (un->pkt->pkttype != PKT_USER_ID)
             continue;
           if (!un->pkt->pkt.user_id->created)
             continue;
-          if (un->pkt->pkt.user_id->is_revoked)
+          if (un->pkt->pkt.user_id->flags.revoked)
             continue;
-          if (un->pkt->pkt.user_id->is_expired)
+          if (un->pkt->pkt.user_id->flags.expired)
             continue;
-          if (!un->pkt->pkt.user_id->is_primary)
+          if (!un->pkt->pkt.user_id->flags.primary)
             continue;
           /* We want the textual primary user ID here */
           if (un->pkt->pkt.user_id->attrib_data)
             continue;
 
-          log_assert (pk);
+          log_assert (mainpk);
 
          /* Since this is just informational, don't actually ask the
             user to update any trust information.  (Note: we register
@@ -1871,7 +2173,8 @@ check_sig_and_print (CTX c, kbnode_t node)
             does not print a LF we need to compute the validity
             before calling that function.  */
           if ((opt.verify_options & VERIFY_SHOW_UID_VALIDITY))
-            valid = get_validity (pk, un->pkt->pkt.user_id, NULL, 0);
+            valid = get_validity (c->ctrl, keyblock, mainpk,
+                                  un->pkt->pkt.user_id, NULL, 0);
           else
             valid = 0; /* Not used.  */
 
@@ -1884,14 +2187,22 @@ check_sig_and_print (CTX c, kbnode_t node)
           else
             log_printf ("\n");
 
-          /* Get a string description of the algo for informational
-             output we want to print later.  It is convenient to do it
-             here because we already have the right public key. */
-          pubkey_string (pk, pkstrbuf, sizeof pkstrbuf);
           count++;
+          /* At this point we could in theory stop because the primary
+           * UID flag is never set for more than one User ID per
+           * keyblock.  However, we use this loop also for a failsafe
+           * check that the public key used to create the signature is
+           * contained in the keyring.*/
        }
 
-      /* In case we did not found a valid valid textual userid above
+      log_assert (mainpk);
+      if (!keyblock_has_pk)
+        {
+          log_error ("signature key lost from keyblock\n");
+          rc = gpg_error (GPG_ERR_INTERNAL);
+        }
+
+      /* In case we did not found a valid textual userid above
          we print the first user id packet or a "[?]" instead along
          with the "Good|Expired|Bad signature" line.  */
       if (!count)
@@ -1935,24 +2246,25 @@ check_sig_and_print (CTX c, kbnode_t node)
             {
               if (un->pkt->pkttype != PKT_USER_ID)
                 continue;
-              if ((un->pkt->pkt.user_id->is_revoked
-                   || un->pkt->pkt.user_id->is_expired)
+              if ((un->pkt->pkt.user_id->flags.revoked
+                   || un->pkt->pkt.user_id->flags.expired)
                   && !(opt.verify_options & VERIFY_SHOW_UNUSABLE_UIDS))
                 continue;
               /* Skip textual primary user ids which we printed above. */
-              if (un->pkt->pkt.user_id->is_primary
+              if (un->pkt->pkt.user_id->flags.primary
                   && !un->pkt->pkt.user_id->attrib_data )
                 continue;
 
               /* If this user id has attribute data, print that.  */
               if (un->pkt->pkt.user_id->attrib_data)
                 {
-                  dump_attribs (un->pkt->pkt.user_id, pk);
+                  dump_attribs (un->pkt->pkt.user_id, mainpk);
 
                   if (opt.verify_options&VERIFY_SHOW_PHOTOS)
-                    show_photos (un->pkt->pkt.user_id->attribs,
+                    show_photos (c->ctrl,
+                                 un->pkt->pkt.user_id->attribs,
                                  un->pkt->pkt.user_id->numattribs,
-                                 pk ,un->pkt->pkt.user_id);
+                                 mainpk ,un->pkt->pkt.user_id);
                 }
 
               p = utf8_to_native (un->pkt->pkt.user_id->name,
@@ -1964,23 +2276,23 @@ check_sig_and_print (CTX c, kbnode_t node)
                 {
                   const char *valid;
 
-                  if (un->pkt->pkt.user_id->is_revoked)
+                  if (un->pkt->pkt.user_id->flags.revoked)
                     valid = _("revoked");
-                  else if (un->pkt->pkt.user_id->is_expired)
+                  else if (un->pkt->pkt.user_id->flags.expired)
                     valid = _("expired");
                   else
                    /* Since this is just informational, don't
                       actually ask the user to update any trust
                       information.  */
                     valid = (trust_value_to_string
-                             (get_validity (pk, un->pkt->pkt.user_id, sig, 0)));
+                             (get_validity (c->ctrl, keyblock, mainpk,
+                                            un->pkt->pkt.user_id, NULL, 0)));
                   log_printf (" [%s]\n",valid);
                 }
               else
                 log_printf ("\n");
             }
        }
-      release_kbnode( keyblock );
 
       /* For good signatures print notation data.  */
       if (!rc)
@@ -2005,81 +2317,71 @@ check_sig_and_print (CTX c, kbnode_t node)
         }
 
       /* For good signatures print the VALIDSIG status line.  */
-      if (!rc && is_status_enabled ())
+      if (!rc && is_status_enabled () && pk)
         {
-          PKT_public_key *vpk = xmalloc_clear (sizeof *vpk);
-
-          if (!get_pubkey (vpk, sig->keyid))
-            {
-              byte array[MAX_FINGERPRINT_LEN], *p;
-              char buf[MAX_FINGERPRINT_LEN*4+90], *bufp;
-              size_t i, n;
-
-              bufp = buf;
-              fingerprint_from_pk (vpk, array, &n);
-              p = array;
-              for(i=0; i < n ; i++, p++, bufp += 2)
-                sprintf (bufp, "%02X", *p );
-              /* TODO: Replace the reserved '0' in the field below
-                 with bits for status flags (policy url, notation,
-                 etc.).  Remember to make the buffer larger to match! */
-              sprintf (bufp, " %s %lu %lu %d 0 %d %d %02X ",
-                       strtimestamp( sig->timestamp ),
-                       (ulong)sig->timestamp,(ulong)sig->expiredate,
-                       sig->version,sig->pubkey_algo,sig->digest_algo,
-                       sig->sig_class);
-              bufp = bufp + strlen (bufp);
-              if (!vpk->flags.primary)
-                {
-                  u32 akid[2];
-
-                  akid[0] = vpk->main_keyid[0];
-                  akid[1] = vpk->main_keyid[1];
-                  free_public_key (vpk);
-                  vpk = xmalloc_clear (sizeof *vpk);
-                  if (get_pubkey (vpk, akid))
-                    {
-                      /* Impossible error, we simply return a zeroed out fpr */
-                      n = MAX_FINGERPRINT_LEN < 20? MAX_FINGERPRINT_LEN : 20;
-                      memset (array, 0, n);
-                    }
-                  else
-                    fingerprint_from_pk( vpk, array, &n );
-                }
-              p = array;
-              for (i=0; i < n ; i++, p++, bufp += 2)
-                sprintf(bufp, "%02X", *p );
-              write_status_text (STATUS_VALIDSIG, buf);
-           }
-          free_public_key (vpk);
+          char pkhex[MAX_FINGERPRINT_LEN*2+1];
+          char mainpkhex[MAX_FINGERPRINT_LEN*2+1];
+
+          hexfingerprint (pk, pkhex, sizeof pkhex);
+          hexfingerprint (mainpk, mainpkhex, sizeof mainpkhex);
+
+          /* TODO: Replace the reserved '0' in the field below with
+             bits for status flags (policy url, notation, etc.).  */
+          write_status_printf (STATUS_VALIDSIG,
+                               "%s %s %lu %lu %d 0 %d %d %02X %s",
+                               pkhex,
+                               strtimestamp (sig->timestamp),
+                               (ulong)sig->timestamp,
+                               (ulong)sig->expiredate,
+                               sig->version, sig->pubkey_algo,
+                               sig->digest_algo,
+                               sig->sig_class,
+                               mainpkhex);
        }
 
+      /* Print compliance warning for Good signatures.  */
+      if (!rc && pk && !opt.quiet
+          && !gnupg_pk_is_compliant (opt.compliance, pk->pubkey_algo, 0,
+                                     pk->pkey, nbits_from_pk (pk), NULL))
+        {
+          log_info (_("WARNING: This key is not suitable for signing"
+                      " in %s mode\n"),
+                    gnupg_compliance_option_string (opt.compliance));
+        }
+
       /* For good signatures compute and print the trust information.
          Note that in the Tofu trust model this may ask the user on
          how to resolve a conflict.  */
       if (!rc)
         {
-          if ((opt.verify_options & VERIFY_PKA_LOOKUPS))
-            pka_uri_from_sig (c, sig); /* Make sure PKA info is available. */
-          rc = check_signatures_trust (sig);
+          rc = check_signatures_trust (c->ctrl, keyblock, pk, sig);
         }
 
       /* Print extra information about the signature.  */
       if (sig->flags.expired)
         {
           log_info (_("Signature expired %s\n"), asctimestamp(sig->expiredate));
-          rc = GPG_ERR_GENERAL; /* Need a better error here?  */
+          if (!rc)
+            rc = gpg_error (GPG_ERR_GENERAL); /* Need a better error here?  */
         }
       else if (sig->expiredate)
         log_info (_("Signature expires %s\n"), asctimestamp(sig->expiredate));
 
       if (opt.verbose)
-        log_info (_("%s signature, digest algorithm %s%s%s\n"),
-                  sig->sig_class==0x00?_("binary"):
-                  sig->sig_class==0x01?_("textmode"):_("unknown"),
-                  gcry_md_algo_name (sig->digest_algo),
-                  *pkstrbuf?_(", key algorithm "):"",
-                  pkstrbuf);
+        {
+          char pkstrbuf[PUBKEY_STRING_SIZE];
+
+          if (pk)
+            pubkey_string (pk, pkstrbuf, sizeof pkstrbuf);
+          else
+            *pkstrbuf = 0;
+
+          log_info (_("%s signature, digest algorithm %s%s%s\n"),
+                    sig->sig_class==0x00?_("binary"):
+                    sig->sig_class==0x01?_("textmode"):_("unknown"),
+                    gcry_md_algo_name (sig->digest_algo),
+                    *pkstrbuf?_(", key algorithm "):"", pkstrbuf);
+        }
 
       /* Print final warnings.  */
       if (!rc && !c->signed_data.used)
@@ -2120,29 +2422,44 @@ check_sig_and_print (CTX c, kbnode_t node)
             }
         }
 
+      /* Compute compliance with CO_DE_VS.  */
+      if (pk && is_status_enabled ()
+          && gnupg_gcrypt_is_compliant (CO_DE_VS)
+          && gnupg_pk_is_compliant (CO_DE_VS, pk->pubkey_algo, 0, pk->pkey,
+                                    nbits_from_pk (pk), NULL)
+          && gnupg_digest_is_compliant (CO_DE_VS, sig->digest_algo))
+        write_status_strings (STATUS_VERIFICATION_COMPLIANCE_MODE,
+                              gnupg_status_compliance_flag (CO_DE_VS),
+                              NULL);
+
+      free_public_key (pk);
+      pk = NULL;
+      release_kbnode( keyblock );
       if (rc)
         g10_errors_seen = 1;
       if (opt.batch && rc)
         g10_exit (1);
     }
-  else
+  else  /* Error checking the signature. (neither Good nor Bad).  */
     {
-      char buf[50];
-
-      snprintf (buf, sizeof buf, "%08lX%08lX %d %d %02x %lu %d",
-                (ulong)sig->keyid[0], (ulong)sig->keyid[1],
-                sig->pubkey_algo, sig->digest_algo,
-                sig->sig_class, (ulong)sig->timestamp, rc);
-      write_status_text (STATUS_ERRSIG, buf);
+      write_status_printf (STATUS_ERRSIG, "%08lX%08lX %d %d %02x %lu %d %s",
+                           (ulong)sig->keyid[0], (ulong)sig->keyid[1],
+                           sig->pubkey_algo, sig->digest_algo,
+                           sig->sig_class, (ulong)sig->timestamp,
+                           gpg_err_code (rc),
+                           issuer_fpr? issuer_fpr:"-");
       if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY)
         {
-          buf[16] = 0;
-          write_status_text (STATUS_NO_PUBKEY, buf);
+          write_status_printf (STATUS_NO_PUBKEY, "%08lX%08lX",
+                               (ulong)sig->keyid[0], (ulong)sig->keyid[1]);
        }
       if (gpg_err_code (rc) != GPG_ERR_NOT_PROCESSED)
         log_error (_("Can't check signature: %s\n"), gpg_strerror (rc));
     }
 
+  free_public_key (pk);
+  release_kbnode (included_keyblock);
+  xfree (issuer_fpr);
   return rc;
 }
 
@@ -2161,7 +2478,7 @@ proc_tree (CTX c, kbnode_t node)
 
   /* We must skip our special plaintext marker packets here because
      they may be the root packet.  These packets are only used in
-     addional checks and skipping them here doesn't matter.  */
+     additional checks and skipping them here doesn't matter.  */
   while (node
          && node->pkt->pkttype == PKT_GPG_CONTROL
           && node->pkt->pkt.gpg_control->control == CTRLPKT_PLAINTEXT_MARK)
@@ -2175,12 +2492,12 @@ proc_tree (CTX c, kbnode_t node)
   if (node->pkt->pkttype == PKT_PUBLIC_KEY
       || node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
     {
-      merge_keys_and_selfsig (node);
+      merge_keys_and_selfsig (c->ctrl, node);
       list_node (c, node);
     }
   else if (node->pkt->pkttype == PKT_SECRET_KEY)
     {
-      merge_keys_and_selfsig (node);
+      merge_keys_and_selfsig (c->ctrl, node);
       list_node (c, node);
     }
   else if (node->pkt->pkttype == PKT_ONEPASS_SIG)
@@ -2274,11 +2591,16 @@ proc_tree (CTX c, kbnode_t node)
           for (; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE)))
             {
               /* We can't currently handle multiple signatures of
-                 different classes or digests (we'd pretty much have
-                 to run a different hash context for each), but if
-                 they are all the same, make an exception. */
+               * different classes (we'd pretty much have to run a
+               * different hash context for each), but if they are all
+               * the same and it is detached signature, we make an
+               * exception.  Note that the old code also disallowed
+               * multiple signatures if the digest algorithms are
+               * different.  We softened this restriction only for
+               * detached signatures, to be on the safe side. */
               if (n1->pkt->pkt.signature->sig_class != class
-                  || n1->pkt->pkt.signature->digest_algo != hash)
+                  || (c->any.data
+                      && n1->pkt->pkt.signature->digest_algo != hash))
                 {
                   multiple_ok = 0;
                   log_info (_("WARNING: multiple signatures detected.  "
@@ -2300,6 +2622,17 @@ proc_tree (CTX c, kbnode_t node)
           if (rc)
             goto detached_hash_err;
 
+          if (multiple_ok)
+            {
+              /* If we have and want to handle multiple signatures we
+               * need to enable all hash algorithms for the context.  */
+              for (n1 = node; (n1 = find_next_kbnode (n1, PKT_SIGNATURE)); )
+                if (!openpgp_md_test_algo (n1->pkt->pkt.signature->digest_algo))
+                  gcry_md_enable (c->mfx.md,
+                                  map_md_openpgp_to_gcry
+                                  (n1->pkt->pkt.signature->digest_algo));
+            }
+
           if (RFC2440 || RFC4880)
             ; /* Strict RFC mode.  */
           else if (sig->digest_algo == DIGEST_ALGO_SHA1
@@ -2307,7 +2640,9 @@ proc_tree (CTX c, kbnode_t node)
                    && sig->sig_class == 0x01)
             {
               /* Enable a workaround for a pgp5 bug when the detached
-               * signature has been created in textmode.  */
+               * signature has been created in textmode.  Note that we
+               * do not implement this for multiple signatures with
+               * different hash algorithms. */
               rc = gcry_md_open (&c->mfx.md2, sig->digest_algo, 0);
               if (rc)
                 goto detached_hash_err;