diff --git a/common/ksba-io-support.c b/common/ksba-io-support.c
index a23608164..352485ffa 100644
--- a/common/ksba-io-support.c
+++ b/common/ksba-io-support.c
@@ -1,848 +1,953 @@
 /* kska-io-support.c - Supporting functions for ksba reader and writer
  * Copyright (C) 2001-2005, 2007, 2010-2011, 2017  Werner Koch
  * Copyright (C) 2006, 2023  g10 Code GmbH
  *
  * This file is part of GnuPG.
  *
  * This file is free software; you can redistribute it and/or modify
  * it under the terms of either
  *
  *   - the GNU Lesser General Public License as published by the Free
  *     Software Foundation; either version 3 of the License, or (at
  *     your option) any later version.
  *
  * or
  *
  *   - the GNU General Public License as published by the Free
  *     Software Foundation; either version 2 of the License, or (at
  *     your option) any later version.
  *
  * or both in parallel, as here.
  *
  * This file is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * 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 <https://www.gnu.org/licenses/>.
  * SPDX-License-Identifier: (LGPL-3.0-or-later OR GPL-2.0-or-later)
  */
 
 #include <config.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <errno.h>
 #include <unistd.h>
 #include <time.h>
 #include <assert.h>
 #include <ksba.h>
 
 #include "util.h"
 #include "i18n.h"
+#include "tlv.h"
 #include "ksba-io-support.h"
 
 
 #ifdef HAVE_DOSISH_SYSTEM
   #define LF "\r\n"
 #else
   #define LF "\n"
 #endif
 
 
 /* Data used by the reader callbacks.  */
 struct reader_cb_parm_s
 {
   estream_t fp;
 
   unsigned char line[1024];
   int linelen;
   int readpos;
   int have_lf;
   unsigned long line_counter;
 
   int allow_multi_pem;  /* Allow processing of multiple PEM objects. */
   int autodetect;       /* Try to detect the input encoding. */
   int assume_pem;       /* Assume input encoding is PEM. */
   int assume_base64;    /* Assume input is base64 encoded. */
+  int strip_zeroes;     /* Expect a SEQUENCE followed by zero padding.  */
+                        /* 1 = check state; 2 = reading; 3 = checking  */
+                        /* for zeroes.                                 */
+  int use_maxread;      /* If true read not more than MAXREAD.  */
+  unsigned int maxread; /* # of bytes left to read. */
+  off_t nzeroes;        /* Number of padding zeroes red.        */
 
   int identified;
   int is_pem;
   int is_base64;
   int stop_seen;
   int might_be_smime;
 
   int eof_seen;
 
   struct {
     int idx;
     unsigned char val;
     int stop_seen;
   } base64;
 };
 
 
 /* Data used by the writer callbacks.  */
 struct writer_cb_parm_s
 {
   estream_t stream;    /* Output stream.  */
 
   char *pem_name;      /* Malloced.  */
 
   struct {
     gnupg_ksba_progress_cb_t cb;
     ctrl_t ctrl;
     u32 last_time;		/* last time reported */
     uint64_t last;		/* last amount reported */
     uint64_t current;	        /* current amount */
     uint64_t total;	        /* total amount */
   } progress;
 
   int wrote_begin;
   int did_finish;
 
   struct {
     int idx;
     int quad_count;
     unsigned char radbuf[4];
   } base64;
 
 };
 
 
 /* Context for this module's functions.  */
 struct gnupg_ksba_io_s {
   int is_writer;  /* True if this context refers a writer object.  */
   union {
     struct reader_cb_parm_s rparm;
     struct writer_cb_parm_s wparm;
   } u;
 
   union {
     ksba_reader_t reader;
     ksba_writer_t writer;
   } u2;
 };
 
 
 /* The base-64 character list */
 static char bintoasc[64] =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz"
        "0123456789+/";
 /* The reverse base-64 list */
 static unsigned char asctobin[256] = {
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3e, 0xff, 0xff, 0xff, 0x3f,
   0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
   0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12,
   0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24,
   0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
   0x31, 0x32, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   0xff, 0xff, 0xff, 0xff
 };
 
 
 static int
 has_only_base64 (const unsigned char *line, int linelen)
 {
   if (linelen < 20)
     return 0;
   for (; linelen; line++, linelen--)
     {
       if (*line == '\n' || (linelen > 1 && *line == '\r' && line[1] == '\n'))
           break;
       if ( !strchr (bintoasc, *line) )
         return 0;
     }
   return 1;  /* yes */
 }
 
 static int
 is_empty_line (const unsigned char *line, int linelen)
 {
   if (linelen >= 2 && *line == '\r' && line[1] == '\n')
     return 1;
   if (linelen >= 1 && *line == '\n')
     return 1;
   return 0;
 }
 
 
 static int
 base64_reader_cb (void *cb_value, char *buffer, size_t count, size_t *nread)
 {
   struct reader_cb_parm_s *parm = cb_value;
   size_t n;
   int c, c2;
 
   *nread = 0;
   if (!buffer)
     return -1; /* not supported */
 
  next:
   if (!parm->linelen)
     {
       /* read an entire line or up to the size of the buffer */
       parm->line_counter++;
       parm->have_lf = 0;
       for (n=0; n < DIM(parm->line);)
         {
           c = es_getc (parm->fp);
           if (c == EOF)
             {
               parm->eof_seen = 1;
               if (es_ferror (parm->fp))
                 return -1;
               break;
             }
           parm->line[n++] = c;
           if (c == '\n')
             {
               parm->have_lf = 1;
               /* Fixme: we need to skip overlong lines while detecting
                  the dashed lines */
               break;
             }
         }
       parm->linelen = n;
       if (!n)
         return -1; /* eof */
       parm->readpos = 0;
     }
 
   if (!parm->identified)
     {
       if (!parm->autodetect)
         {
           if (parm->assume_pem)
             {
               /* wait for the header line */
               parm->linelen = parm->readpos = 0;
               if (!parm->have_lf
                   || strncmp ((char*)parm->line, "-----BEGIN ", 11)
                   || !strncmp ((char*)parm->line+11, "PGP ", 4))
                 goto next;
               parm->is_pem = 1;
             }
           else if (parm->assume_base64)
             parm->is_base64 = 1;
         }
       else if (parm->line_counter == 1 && !parm->have_lf)
         {
           /* first line too long - assume DER encoding */
           parm->is_pem = 0;
         }
       else if (parm->line_counter == 1 && parm->linelen && *parm->line == 0x30)
         {
           /* the very first byte does pretty much look like a SEQUENCE tag*/
           parm->is_pem = 0;
         }
       else if ( parm->have_lf
                 && !strncmp ((char*)parm->line, "-----BEGIN ", 11)
                 && strncmp ((char *)parm->line+11, "PGP ", 4) )
         {
           /* Fixme: we must only compare if the line really starts at
              the beginning */
           parm->is_pem = 1;
           parm->linelen = parm->readpos = 0;
         }
       else if ( parm->have_lf && parm->line_counter == 1
                 && parm->linelen >= 13
                 && !ascii_memcasecmp (parm->line, "Content-Type:", 13))
         { /* might be a S/MIME body */
           parm->might_be_smime = 1;
           parm->linelen = parm->readpos = 0;
           goto next;
         }
       else if (parm->might_be_smime == 1
                && is_empty_line (parm->line, parm->linelen))
         {
           parm->might_be_smime = 2;
           parm->linelen = parm->readpos = 0;
           goto next;
         }
       else if (parm->might_be_smime == 2)
         {
           parm->might_be_smime = 0;
           if ( !has_only_base64 (parm->line, parm->linelen))
             {
               parm->linelen = parm->readpos = 0;
               goto next;
             }
           parm->is_pem = 1;
         }
       else
         {
           parm->linelen = parm->readpos = 0;
           goto next;
         }
       parm->identified = 1;
       parm->base64.stop_seen = 0;
       parm->base64.idx = 0;
     }
 
 
   n = 0;
   if (parm->is_pem || parm->is_base64)
     {
       if (parm->is_pem && parm->have_lf
           && !strncmp ((char*)parm->line, "-----END ", 9))
         {
           parm->identified = 0;
           parm->linelen = parm->readpos = 0;
 
           /* If the caller want to read multiple PEM objects from one
              file, we have to reset our internal state and return a
              EOF immediately. The caller is the expected to use
              ksba_reader_clear to clear the EOF condition and continue
              to read.  If we don't want to do that we just return 0
              bytes which will force the ksba_reader to skip until
              EOF. */
           if (parm->allow_multi_pem)
             {
               parm->identified = 0;
               parm->autodetect = 0;
               parm->assume_pem = 1;
               parm->stop_seen = 0;
               return -1; /* Send EOF now. */
             }
         }
       else if (parm->stop_seen)
         { /* skip the rest of the line */
           parm->linelen = parm->readpos = 0;
         }
       else
         {
           int idx = parm->base64.idx;
           unsigned char val = parm->base64.val;
 
           while (n < count && parm->readpos < parm->linelen )
             {
               c = parm->line[parm->readpos++];
               if (c == '\n' || c == ' ' || c == '\r' || c == '\t')
                 continue;
               if ((c = asctobin[(c2=c)]) == 255)
                 {
                   if (c2 == '=')
                     { /* pad character: stop */
                       if (idx == 1)
                         buffer[n++] = val;
                       parm->stop_seen = 1;
                       break;
                     }
                   else if (c2 == '-'
                            && parm->readpos == 1
                            && parm->readpos-1+9 < parm->linelen
                            && !strncmp ((char*)parm->line + parm->readpos-1,
                                         "-----END ", 9))
                     { /* END line seen (padding was not needed). */
                       parm->stop_seen = 1;
                       break;
                     }
                   log_error (_("invalid radix64 character %02x skipped\n"),
                              c2);
                   continue;
                 }
               switch (idx)
                 {
                 case 0:
                   val = c << 2;
                   break;
                 case 1:
                   val |= (c>>4)&3;
                   buffer[n++] = val;
                   val = (c<<4)&0xf0;
                   break;
                 case 2:
                   val |= (c>>2)&15;
                   buffer[n++] = val;
                   val = (c<<6)&0xc0;
                   break;
                 case 3:
                   val |= c&0x3f;
                   buffer[n++] = val;
                   break;
                 }
               idx = (idx+1) % 4;
             }
           if (parm->readpos == parm->linelen)
             parm->linelen = parm->readpos = 0;
 
           parm->base64.idx = idx;
           parm->base64.val = val;
         }
     }
   else
     { /* DER encoded */
       while (n < count && parm->readpos < parm->linelen)
           buffer[n++] = parm->line[parm->readpos++];
       if (parm->readpos == parm->linelen)
         parm->linelen = parm->readpos = 0;
     }
 
   *nread = n;
   return 0;
 }
 
 
+/* Read up to 10 bytes to test whether the data consist of a sequence;
+ * if that is true, set the limited flag and record the length of the
+ * entire sequence in PARM.  Unget everything then.  Return true if we
+ * have a sequence with a fixed length.  */
+static int
+starts_with_sequence (struct reader_cb_parm_s *parm)
+{
+  gpg_error_t err;
+  unsigned char peekbuf[10];
+  int npeeked, c;
+  int found = 0;
+  const unsigned char *p;
+  size_t n, objlen, hdrlen;
+  int class, tag, constructed, ndef;
+
+  for (npeeked=0; npeeked < sizeof peekbuf; npeeked++)
+    {
+      c = es_getc (parm->fp);
+      if (c == EOF)
+        goto leave;
+      peekbuf[npeeked] = c;
+    }
+  /* Enough to check for a sequence.  */
+
+  p = peekbuf;
+  n = npeeked;
+  err = parse_ber_header (&p, &n, &class, &tag, &constructed,
+                          &ndef, &objlen, &hdrlen);
+  if (err)
+    {
+      log_debug ("%s: error parsing data: %s\n", __func__, gpg_strerror (err));
+      goto leave;
+    }
+
+  if (class == CLASS_UNIVERSAL && constructed && tag == TAG_SEQUENCE && !ndef)
+    {
+      /* We need to add 1 due to the way we implement the limit.  */
+      parm->maxread = objlen + hdrlen + 1;
+      if (!(parm->maxread < objlen + hdrlen) && parm->maxread)
+        parm->use_maxread = 1;
+      found = 1;
+    }
+
+ leave:
+  while (npeeked)
+    es_ungetc (peekbuf[--npeeked], parm->fp);
+  return found;
+}
+
 
 static int
 simple_reader_cb (void *cb_value, char *buffer, size_t count, size_t *nread)
 {
   struct reader_cb_parm_s *parm = cb_value;
   size_t n;
   int c = 0;
 
   *nread = 0;
   if (!buffer)
     return -1; /* not supported */
 
+ restart:
+  if (parm->strip_zeroes)
+    {
+      if (parm->strip_zeroes == 1)
+        {
+          if (starts_with_sequence (parm))
+            parm->strip_zeroes = 2;  /* Found fixed length sequence.  */
+          else
+            parm->strip_zeroes = 0;  /* Disable zero padding check.  */
+        }
+      else if (parm->strip_zeroes == 3)
+        {
+          /* Limit reached - check that only zeroes follow.  */
+          while (!(c = es_getc (parm->fp)))
+            parm->nzeroes++;
+          if (c == EOF)
+            { /* only zeroes found. Reset zero padding engine and
+               * return EOF.  */
+              parm->strip_zeroes = 0;
+              parm->eof_seen = 1;
+              return -1;
+            }
+          /* Not only zeroes. Reset engine and continue.  */
+          parm->strip_zeroes = 0;
+        }
+    }
+
   for (n=0; n < count; n++)
     {
-      c = es_getc (parm->fp);
+      if (parm->use_maxread && !--parm->maxread)
+        {
+          parm->use_maxread = 0;
+          if (parm->strip_zeroes)
+            {
+              parm->strip_zeroes = 3;
+              parm->nzeroes = 0;
+              if (n)
+                goto leave; /* Return what we already got.             */
+              goto restart; /* Immediately check for trailing zeroes.  */
+            }
+        }
+
+      if (parm->nzeroes)
+        {
+          parm->nzeroes--;
+          c = 0;
+        }
+      else
+        c = es_getc (parm->fp);
       if (c == EOF)
         {
           parm->eof_seen = 1;
           if (es_ferror (parm->fp))
             return -1;
           if (n)
             break; /* Return what we have before an EOF.  */
           return -1;
         }
       *(byte *)buffer++ = c;
     }
 
+ leave:
   *nread = n;
   return 0;
 }
 
 
 
 
 /* Call the progress callback if its time.  We do this very 2 seconds
  * or if FORCE is set.  However, we also require that at least 64KiB
  * have been written to avoid unnecessary progress lines for small
  * files.  */
 static gpg_error_t
 update_write_progress (struct writer_cb_parm_s *parm, size_t count, int force)
 {
   gpg_error_t err = 0;
   u32 timestamp;
 
   parm->progress.current += count;
   if (parm->progress.current >= (64*1024))
     {
       timestamp = make_timestamp ();
       if (force || (timestamp - parm->progress.last_time > 1))
         {
           parm->progress.last = parm->progress.current;
           parm->progress.last_time = timestamp;
           err = parm->progress.cb (parm->progress.ctrl,
                                    parm->progress.current,
                                    parm->progress.total);
         }
     }
   return err;
 }
 
 
 static int
 base64_writer_cb (void *cb_value, const void *buffer, size_t count)
 {
   struct writer_cb_parm_s *parm = cb_value;
   unsigned char radbuf[4];
   int i, c, idx, quad_count;
   const unsigned char *p;
   estream_t stream = parm->stream;
   int rc;
   size_t nleft;
 
   if (!count)
     return 0;
 
   if (!parm->wrote_begin)
     {
       if (parm->pem_name)
         {
           es_fputs ("-----BEGIN ", stream);
           es_fputs (parm->pem_name, stream);
           es_fputs ("-----\n", stream);
         }
       parm->wrote_begin = 1;
       parm->base64.idx = 0;
       parm->base64.quad_count = 0;
     }
 
   idx = parm->base64.idx;
   quad_count = parm->base64.quad_count;
   for (i=0; i < idx; i++)
     radbuf[i] = parm->base64.radbuf[i];
 
   for (p=buffer, nleft = count; nleft; p++, nleft--)
     {
       radbuf[idx++] = *p;
       if (idx > 2)
         {
           idx = 0;
           c = bintoasc[(*radbuf >> 2) & 077];
           es_putc (c, stream);
           c = bintoasc[(((*radbuf<<4)&060)|((radbuf[1] >> 4)&017))&077];
           es_putc (c, stream);
           c = bintoasc[(((radbuf[1]<<2)&074)|((radbuf[2]>>6)&03))&077];
           es_putc (c, stream);
           c = bintoasc[radbuf[2]&077];
           es_putc (c, stream);
           if (++quad_count >= (64/4))
             {
               es_fputs (LF, stream);
               quad_count = 0;
             }
         }
     }
   for (i=0; i < idx; i++)
     parm->base64.radbuf[i] = radbuf[i];
   parm->base64.idx = idx;
   parm->base64.quad_count = quad_count;
 
   rc = es_ferror (stream)? gpg_error_from_syserror () : 0;
   /* Note that we use the unencoded count for the progress.  */
   if (!rc && parm->progress.cb)
     rc = update_write_progress (parm, count, 0);
   return rc;
 }
 
 
 /* This callback is only used in stream mode.  However, we don't
    restrict it to this.  */
 static int
 plain_writer_cb (void *cb_value, const void *buffer, size_t count)
 {
   struct writer_cb_parm_s *parm = cb_value;
   estream_t stream = parm->stream;
   int rc;
 
   if (!count)
     return 0;
 
   es_write (stream, buffer, count, NULL);
   rc = es_ferror (stream)? gpg_error_from_syserror () : 0;
   if (!rc && parm->progress.cb)
     rc = update_write_progress (parm, count, 0);
   return rc;
 }
 
 
 static int
 base64_finish_write (struct writer_cb_parm_s *parm)
 {
   unsigned char *radbuf;
   int c, idx, quad_count;
   estream_t stream = parm->stream;
   int rc;
 
   if (!parm->wrote_begin)
     return 0; /* Nothing written or we are not called in base-64 mode. */
 
   /* flush the base64 encoding */
   idx = parm->base64.idx;
   quad_count = parm->base64.quad_count;
   if (idx)
     {
       radbuf = parm->base64.radbuf;
 
       c = bintoasc[(*radbuf>>2)&077];
       es_putc (c, stream);
       if (idx == 1)
         {
           c = bintoasc[((*radbuf << 4) & 060) & 077];
           es_putc (c, stream);
           es_putc ('=', stream);
           es_putc ('=', stream);
         }
       else
         {
           c = bintoasc[(((*radbuf<<4)&060)|((radbuf[1]>>4)&017))&077];
           es_putc (c, stream);
           c = bintoasc[((radbuf[1] << 2) & 074) & 077];
           es_putc (c, stream);
           es_putc ('=', stream);
 
         }
       if (++quad_count >= (64/4))
         {
           es_fputs (LF, stream);
           quad_count = 0;
         }
     }
 
   if (quad_count)
     es_fputs (LF, stream);
 
   if (parm->pem_name)
     {
       es_fputs ("-----END ", stream);
       es_fputs (parm->pem_name, stream);
       es_fputs ("-----\n", stream);
     }
 
   rc = es_ferror (stream)? gpg_error_from_syserror () : 0;
   if (!rc && parm->progress.cb)
     rc = update_write_progress (parm, 0, 1);
   return rc;
 }
 
 
 
 
 /* Create a reader for the stream FP.  FLAGS can be used to specify
  * the expected input encoding.
  *
  * The function returns a gnupg_ksba_io_t object which must be passed to
  * the gpgme_destroy_reader function.  The created ksba_reader_t
  * object is stored at R_READER - the caller must not call the
  * ksba_reader_release function on.
  *
  * The supported flags are:
  *
  * GNUPG_KSBA_IO_PEM        - Assume the input is PEM encoded
  * GNUPG_KSBA_IO_BASE64     - Assume the input is Base64 encoded.
  * GNUPG_KSBA_IO_AUTODETECT - The reader tries to detect the encoding.
  * GNUPG_KSBA_IO_MULTIPEM   - The reader expects that the caller uses
  *                            ksba_reader_clear after EOF until no more
  *                            objects were found.
+ * GNUPG_KSBA_IO_STRIP      - Strip zero padding from some CMS objects.
  *
  * Note that the PEM flag has a higher priority than the BASE64 flag
  * which in turn has a gight priority than the AUTODETECT flag.
  */
 gpg_error_t
 gnupg_ksba_create_reader (gnupg_ksba_io_t *ctx,
                           unsigned int flags, estream_t fp,
                           ksba_reader_t *r_reader)
 {
   int rc;
   ksba_reader_t r;
 
   *r_reader = NULL;
   *ctx = xtrycalloc (1, sizeof **ctx);
   if (!*ctx)
     return out_of_core ();
   (*ctx)->u.rparm.allow_multi_pem = !!(flags & GNUPG_KSBA_IO_MULTIPEM);
+  (*ctx)->u.rparm.strip_zeroes    = !!(flags & GNUPG_KSBA_IO_STRIP);
 
   rc = ksba_reader_new (&r);
   if (rc)
     {
       xfree (*ctx); *ctx = NULL;
       return rc;
     }
 
   (*ctx)->u.rparm.fp = fp;
   if ((flags & GNUPG_KSBA_IO_PEM))
     {
       (*ctx)->u.rparm.assume_pem = 1;
       (*ctx)->u.rparm.assume_base64 = 1;
       rc = ksba_reader_set_cb (r, base64_reader_cb, &(*ctx)->u.rparm);
     }
   else if ((flags & GNUPG_KSBA_IO_BASE64))
     {
       (*ctx)->u.rparm.assume_base64 = 1;
       rc = ksba_reader_set_cb (r, base64_reader_cb, &(*ctx)->u.rparm);
     }
   else if ((flags & GNUPG_KSBA_IO_AUTODETECT))
     {
       (*ctx)->u.rparm.autodetect = 1;
       rc = ksba_reader_set_cb (r, base64_reader_cb, &(*ctx)->u.rparm);
     }
   else
       rc = ksba_reader_set_cb (r, simple_reader_cb, &(*ctx)->u.rparm);
 
   if (rc)
     {
       ksba_reader_release (r);
       xfree (*ctx); *ctx = NULL;
       return rc;
     }
 
   (*ctx)->u2.reader = r;
   *r_reader = r;
   return 0;
 }
 
 
 /* Return True if an EOF as been seen.  */
 int
 gnupg_ksba_reader_eof_seen (gnupg_ksba_io_t ctx)
 {
   return ctx && ctx->u.rparm.eof_seen;
 }
 
 
 /* Destroy a reader object.  */
 void
 gnupg_ksba_destroy_reader (gnupg_ksba_io_t ctx)
 {
   if (!ctx)
     return;
 
   ksba_reader_release (ctx->u2.reader);
   xfree (ctx);
 }
 
 
 
 /* Create a writer for the given STREAM.  Depending on FLAGS an output
  * encoding is chosen.  In PEM mode PEM_NAME is used for the header
  * and footer lines; if PEM_NAME is NULL the string "CMS OBJECT" is
  * used.
  *
  * The function returns a gnupg_ksba_io_t object which must be passed to
  * the gpgme_destroy_writer function.  The created ksba_writer_t
  * object is stored at R_WRITER - the caller must not call the
  * ksba_reader_release function on it.
  *
  * The supported flags are:
  *
  * GNUPG_KSBA_IO_PEM    - Write output as PEM
  * GNUPG_KSBA_IO_BASE64 - Write output as plain Base64; note that the PEM
  *                        flag overrides this flag.
  *
  */
 gpg_error_t
 gnupg_ksba_create_writer (gnupg_ksba_io_t *ctx, unsigned int flags,
                           const char *pem_name, estream_t stream,
                           ksba_writer_t *r_writer)
 {
   int rc;
   ksba_writer_t w;
 
   *r_writer = NULL;
   *ctx = xtrycalloc (1, sizeof **ctx);
   if (!*ctx)
     return gpg_error_from_syserror ();
   (*ctx)->is_writer = 1;
 
   rc = ksba_writer_new (&w);
   if (rc)
     {
       xfree (*ctx); *ctx = NULL;
       return rc;
     }
 
   if ((flags & GNUPG_KSBA_IO_PEM) || (flags & GNUPG_KSBA_IO_BASE64))
     {
       (*ctx)->u.wparm.stream = stream;
       if ((flags & GNUPG_KSBA_IO_PEM))
         {
           (*ctx)->u.wparm.pem_name = xtrystrdup (pem_name
                                                  ? pem_name
                                                  : "CMS OBJECT");
           if (!(*ctx)->u.wparm.pem_name)
             {
               rc = gpg_error_from_syserror ();
               ksba_writer_release (w);
               xfree (*ctx); *ctx = NULL;
               return rc;
             }
         }
       rc = ksba_writer_set_cb (w, base64_writer_cb, &(*ctx)->u.wparm);
     }
   else if (stream)
     {
       (*ctx)->u.wparm.stream = stream;
       rc = ksba_writer_set_cb (w, plain_writer_cb, &(*ctx)->u.wparm);
     }
   else
     rc = gpg_error (GPG_ERR_INV_ARG);
 
   if (rc)
     {
       ksba_writer_release (w);
       xfree (*ctx); *ctx = NULL;
       return rc;
     }
 
   (*ctx)->u2.writer = w;
   *r_writer = w;
   return 0;
 }
 
 
 /* Flush a writer.  This is for example required to write the padding
  * or the PEM footer.  */
 gpg_error_t
 gnupg_ksba_finish_writer (gnupg_ksba_io_t ctx)
 {
   struct writer_cb_parm_s *parm;
 
   if (!ctx)
     return gpg_error (GPG_ERR_INV_VALUE);
   parm = &ctx->u.wparm;
   if (parm->did_finish)
     return 0; /* Already done. */
   parm->did_finish = 1;
   if (!parm->stream)
     return 0; /* Callback was not used.  */
   return base64_finish_write (parm);
 }
 
 
 /* Destroy a writer object.  */
 void
 gnupg_ksba_destroy_writer (gnupg_ksba_io_t ctx)
 {
   if (!ctx)
     return;
 
   ksba_writer_release (ctx->u2.writer);
   xfree (ctx->u.wparm.pem_name);
   xfree (ctx);
 }
 
 
 /* Set a callback to the writer object.  CTRL will be bassed to the
  * callback.  */
 void
 gnupg_ksba_set_progress_cb (gnupg_ksba_io_t ctx,
                             gnupg_ksba_progress_cb_t cb, ctrl_t ctrl)
 {
   struct writer_cb_parm_s *parm;
 
   if (!ctx || !ctx->is_writer)
     return; /* Currently only supported for writer objects.  */
   parm = &ctx->u.wparm;
 
   parm->progress.cb = cb;
   parm->progress.ctrl = ctrl;
   parm->progress.last_time = 0;
   parm->progress.last = 0;
   parm->progress.current = 0;
   parm->progress.total = 0;
 }
 
 
 /* Update the total count for the progress thingy.  */
 void
 gnupg_ksba_set_total (gnupg_ksba_io_t ctx, uint64_t total)
 {
   struct writer_cb_parm_s *parm;
 
   if (!ctx || !ctx->is_writer)
     return; /* Currently only supported for writer objects.  */
   parm = &ctx->u.wparm;
   parm->progress.total = total;
 }
diff --git a/common/ksba-io-support.h b/common/ksba-io-support.h
index f309e6647..1dbc303c8 100644
--- a/common/ksba-io-support.h
+++ b/common/ksba-io-support.h
@@ -1,74 +1,75 @@
 /* ksba-io-support.h - Supporting functions for ksba reader and writer
  * Copyright (C) 2017  Werner Koch
  *
  * This file is part of GnuPG.
  *
  * This file is free software; you can redistribute it and/or modify
  * it under the terms of either
  *
  *   - the GNU Lesser General Public License as published by the Free
  *     Software Foundation; either version 3 of the License, or (at
  *     your option) any later version.
  *
  * or
  *
  *   - the GNU General Public License as published by the Free
  *     Software Foundation; either version 2 of the License, or (at
  *     your option) any later version.
  *
  * or both in parallel, as here.
  *
  * This file is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * 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 <https://www.gnu.org/licenses/>.
  * SPDX-License-Identifier: (LGPL-3.0-or-later OR GPL-2.0-or-later)
  */
 
 #ifndef GNUPG_KSBA_IO_SUPPORT_H
 #define GNUPG_KSBA_IO_SUPPORT_H
 
 /* Flags used with gnupg_ksba_create_reader and
  * gnupg_ksba_create_writer.  */
 #define GNUPG_KSBA_IO_PEM         1  /* X.509 PEM format.  */
 #define GNUPG_KSBA_IO_BASE64      2  /* Plain Base64 format.  */
 #define GNUPG_KSBA_IO_AUTODETECT  4  /* Try to autodetect the format.  */
 #define GNUPG_KSBA_IO_MULTIPEM    8  /* Allow more than one PEM chunk.  */
+#define GNUPG_KSBA_IO_STRIP      16  /* Strip off zero padding.         */
 
 
 /* Context object.  */
 typedef struct gnupg_ksba_io_s *gnupg_ksba_io_t;
 
 /* Progress callback type.  */
 typedef gpg_error_t (*gnupg_ksba_progress_cb_t)(ctrl_t ctrl,
                                                 uint64_t current,
                                                 uint64_t total);
 
 
 gpg_error_t gnupg_ksba_create_reader (gnupg_ksba_io_t *ctx,
                                       unsigned int flags,
                                       estream_t fp,
                                       ksba_reader_t *r_reader);
 
 int gnupg_ksba_reader_eof_seen (gnupg_ksba_io_t ctx);
 void gnupg_ksba_destroy_reader (gnupg_ksba_io_t ctx);
 
 gpg_error_t gnupg_ksba_create_writer (gnupg_ksba_io_t *ctx,
                                       unsigned int flags,
                                       const char *pem_name,
                                       estream_t stream,
                                       ksba_writer_t *r_writer);
 gpg_error_t gnupg_ksba_finish_writer (gnupg_ksba_io_t ctx);
 void gnupg_ksba_destroy_writer (gnupg_ksba_io_t ctx);
 
 void gnupg_ksba_set_progress_cb (gnupg_ksba_io_t ctx,
                                  gnupg_ksba_progress_cb_t cb, ctrl_t ctrl);
 void gnupg_ksba_set_total (gnupg_ksba_io_t ctx, uint64_t total);
 
 
 
 
 #endif /*GNUPG_KSBA_IO_SUPPORT_H*/
diff --git a/doc/gpgsm.texi b/doc/gpgsm.texi
index c5cfd254c..03fe1c9e6 100644
--- a/doc/gpgsm.texi
+++ b/doc/gpgsm.texi
@@ -1,1742 +1,1744 @@
 @c Copyright (C) 2002 Free Software Foundation, Inc.
 @c This is part of the GnuPG manual.
 @c For copying conditions, see the file gnupg.texi.
 
 @include defs.inc
 
 @node Invoking GPGSM
 @chapter Invoking GPGSM
 @cindex GPGSM command options
 @cindex command options
 @cindex options, GPGSM command
 
 @manpage gpgsm.1
 @ifset manverb
 .B gpgsm
 \- CMS encryption and signing tool
 @end ifset
 
 @mansect synopsis
 @ifset manverb
 .B  gpgsm
 .RB [ \-\-homedir
 .IR dir ]
 .RB [ \-\-options
 .IR file ]
 .RI [ options ]
 .I command
 .RI [ args ]
 @end ifset
 
 
 @mansect description
 @command{gpgsm} is a tool similar to @command{gpg} to provide digital
 encryption and signing services on X.509 certificates and the CMS
 protocol.  It is mainly used as a backend for S/MIME mail processing.
 @command{gpgsm} includes a full featured certificate management and
 complies with all rules defined for the German Sphinx project.
 
 @manpause
 @xref{Option Index}, for an index to @command{GPGSM}'s commands and options.
 @mancont
 
 @menu
 * GPGSM Commands::        List of all commands.
 * GPGSM Options::         List of all options.
 * GPGSM Configuration::   Configuration files.
 * GPGSM Examples::        Some usage examples.
 
 Developer information:
 * Unattended Usage::      Using @command{gpgsm} from other programs.
 * GPGSM Protocol::        The protocol the server mode uses.
 @end menu
 
 @c *******************************************
 @c ***************            ****************
 @c ***************  COMMANDS  ****************
 @c ***************            ****************
 @c *******************************************
 @mansect commands
 @node GPGSM Commands
 @section Commands
 
 Commands are not distinguished from options except for the fact that
 only one command is allowed.
 
 @menu
 * General GPGSM Commands::        Commands not specific to the functionality.
 * Operational GPGSM Commands::    Commands to select the type of operation.
 * Certificate Management::        How to manage certificates.
 @end menu
 
 
 @c *******************************************
 @c **********  GENERAL COMMANDS  *************
 @c *******************************************
 @node General GPGSM Commands
 @subsection Commands not specific to the function
 
 @table @gnupgtabopt
 @item --version
 @opindex version
 Print the program version and licensing information.  Note that you
 cannot abbreviate this command.
 
 @item --help, -h
 @opindex help
 Print a usage message summarizing the most useful command-line options.
 Note that you cannot abbreviate this command.
 
 @item --warranty
 @opindex warranty
 Print warranty information.  Note that you cannot abbreviate this
 command.
 
 @item --dump-options
 @opindex dump-options
 Print a list of all available options and commands.  Note that you cannot
 abbreviate this command.
 @end table
 
 
 @c *******************************************
 @c ********  OPERATIONAL COMMANDS  ***********
 @c *******************************************
 @node Operational GPGSM Commands
 @subsection Commands to select the type of operation
 
 @table @gnupgtabopt
 @item --encrypt
 @opindex encrypt
 Perform an encryption.  The keys the data is encrypted to must be set
 using the option @option{--recipient}.
 
 @item --decrypt
 @opindex decrypt
 Perform a decryption; the type of input is automatically determined.  It
 may either be in binary form or PEM encoded; automatic determination of
 base-64 encoding is not done.
 
 @item --sign
 @opindex sign
 Create a digital signature.  The key used is either the fist one found
 in the keybox or those set with the @option{--local-user} option.
 
 @item --verify
 @opindex verify
 Check a signature file for validity.  Depending on the arguments a
 detached signature may also be checked.
 
 @item --server
 @opindex server
 Run in server mode and wait for commands on the @code{stdin}.
 
 @item --call-dirmngr @var{command} [@var{args}]
 @opindex call-dirmngr
 Behave as a Dirmngr client issuing the request @var{command} with the
 optional list of @var{args}.  The output of the Dirmngr is printed
 stdout.  Please note that file names given as arguments should have an
 absolute file name (i.e. commencing with @code{/}) because they are
 passed verbatim to the Dirmngr and the working directory of the
 Dirmngr might not be the same as the one of this client.  Currently it
 is not possible to pass data via stdin to the Dirmngr.  @var{command}
 should not contain spaces.
 
 This is command is required for certain maintaining tasks of the dirmngr
 where a dirmngr must be able to call back to @command{gpgsm}.  See the Dirmngr
 manual for details.
 
 @item --call-protect-tool @var{arguments}
 @opindex call-protect-tool
 Certain maintenance operations are done by an external program call
 @command{gpg-protect-tool}; this is usually not installed in a directory
 listed in the PATH variable.  This command provides a simple wrapper to
 access this tool.  @var{arguments} are passed verbatim to this command;
 use @samp{--help} to get a list of supported operations.
 
 
 @end table
 
 
 @c *******************************************
 @c *******  CERTIFICATE MANAGEMENT  **********
 @c *******************************************
 @node Certificate Management
 @subsection How to manage the certificates and keys
 
 @table @gnupgtabopt
 @item --generate-key
 @opindex generate-key
 @itemx --gen-key
 @opindex gen-key
 This command allows the creation of a certificate signing request or a
 self-signed certificate.  It is commonly used along with the
 @option{--output} option to save the created CSR or certificate into a
 file.  If used with the @option{--batch} a parameter file is used to
 create the CSR or certificate and it is further possible to create
 non-self-signed certificates.
 
 @item --list-keys
 @itemx -k
 @opindex list-keys
 List all available certificates stored in the local key database.
 Note that the displayed data might be reformatted for better human
 readability and illegal characters are replaced by safe substitutes.
 
 @item --list-secret-keys
 @itemx -K
 @opindex list-secret-keys
 List all available certificates for which a corresponding a secret key
 is available.
 
 @item --list-external-keys @var{pattern}
 @opindex list-keys
 List certificates matching @var{pattern} using an external server.  This
 utilizes the @code{dirmngr} service.
 
 @item --list-chain
 @opindex list-chain
 Same as @option{--list-keys} but also prints all keys making up the chain.
 
 
 @item --dump-cert
 @itemx --dump-keys
 @opindex dump-cert
 @opindex dump-keys
 List all available certificates stored in the local key database using a
 format useful mainly for debugging.
 
 @item --dump-chain
 @opindex dump-chain
 Same as @option{--dump-keys} but also prints all keys making up the chain.
 
 @item --dump-secret-keys
 @opindex dump-secret-keys
 List all available certificates for which a corresponding a secret key
 is available using a format useful mainly for debugging.
 
 @item --dump-external-keys @var{pattern}
 @opindex dump-external-keys
 List certificates matching @var{pattern} using an external server.
 This utilizes the @code{dirmngr} service.  It uses a format useful
 mainly for debugging.
 
 @item --keydb-clear-some-cert-flags
 @opindex keydb-clear-some-cert-flags
 This is a debugging aid to reset certain flags in the key database
 which are used to cache certain certificate stati.  It is especially
 useful if a bad CRL or a weird running OCSP responder did accidentally
 revoke certificate.  There is no security issue with this command
 because @command{gpgsm} always make sure that the validity of a certificate is
 checked right before it is used.
 
 @item --delete-keys @var{pattern}
 @opindex delete-keys
 Delete the keys matching @var{pattern}.  Note that there is no command
 to delete the secret part of the key directly.  In case you need to do
 this, you should run the command @code{gpgsm --dump-secret-keys KEYID}
 before you delete the key, copy the string of hex-digits in the
 ``keygrip'' line and delete the file consisting of these hex-digits
 and the suffix @code{.key} from the @file{private-keys-v1.d} directory
 below our GnuPG home directory (usually @file{~/.gnupg}).
 
 @item --export [@var{pattern}]
 @opindex export
 Export all certificates stored in the Keybox or those specified by the
 optional @var{pattern}. Those pattern consist of a list of user ids
 (@pxref{how-to-specify-a-user-id}).  When used along with the
 @option{--armor} option a few informational lines are prepended before
 each block.  There is one limitation: As there is no commonly agreed
 upon way to pack more than one certificate into an ASN.1 structure,
 the binary export (i.e. without using @option{armor}) works only for
 the export of one certificate.  Thus it is required to specify a
 @var{pattern} which yields exactly one certificate.  Ephemeral
 certificate are only exported if all @var{pattern} are given as
 fingerprints or keygrips.
 
 @item --export-secret-key-p12 @var{key-id}
 @opindex export-secret-key-p12
 Export the private key and the certificate identified by @var{key-id}
 using the PKCS#12 format.  When used with the @code{--armor} option a few
 informational lines are prepended to the output.  Note, that the PKCS#12
 format is not very secure and proper transport security should be used
 to convey the exported key.  (@xref{option --p12-charset}.)
 
 @item --export-secret-key-p8 @var{key-id}
 @itemx --export-secret-key-raw @var{key-id}
 @opindex export-secret-key-p8
 @opindex export-secret-key-raw
 Export the private key of the certificate identified by @var{key-id}
 with any encryption stripped.  The @code{...-raw} command exports in
 PKCS#1 format; the @code{...-p8} command exports in PKCS#8 format.
 When used with the @code{--armor} option a few informational lines are
 prepended to the output.  These commands are useful to prepare a key
 for use on a TLS server.
 
 @item --import [@var{files}]
 @opindex import
 Import the certificates from the PEM or binary encoded files as well as
 from signed-only messages.  This command may also be used to import a
 secret key from a PKCS#12 file.
 
 @item --learn-card
 @opindex learn-card
 Read information about the private keys from the smartcard and import
 the certificates from there.  This command utilizes the @command{gpg-agent}
 and in turn the @command{scdaemon}.
 
 @item --change-passphrase @var{user_id}
 @opindex change-passphrase
 @itemx --passwd @var{user_id}
 @opindex passwd
 Change the passphrase of the private key belonging to the certificate
 specified as @var{user_id}.  Note, that changing the passphrase/PIN of a
 smartcard is not yet supported.
 
 @end table
 
 
 @c *******************************************
 @c ***************            ****************
 @c ***************  OPTIONS   ****************
 @c ***************            ****************
 @c *******************************************
 @mansect options
 @node GPGSM Options
 @section Option Summary
 
 @command{GPGSM} features a bunch of options to control the exact behaviour
 and to change the default configuration.
 
 @menu
 * Configuration Options::   How to change the configuration.
 * Certificate Options::     Certificate related options.
 * Input and Output::        Input and Output.
 * CMS Options::             How to change how the CMS is created.
 * Esoteric Options::        Doing things one usually do not want to do.
 @end menu
 
 
 @c *******************************************
 @c ********  CONFIGURATION OPTIONS  **********
 @c *******************************************
 @node Configuration Options
 @subsection How to change the configuration
 
 These options are used to change the configuration and are usually found
 in the option file.
 
 @table @gnupgtabopt
 
 @anchor{gpgsm-option --options}
 @item --options @var{file}
 @opindex options
 Reads configuration from @var{file} instead of from the default
 per-user configuration file.  The default configuration file is named
 @file{gpgsm.conf} and expected in the @file{.gnupg} directory directly
 below the home directory of the user.
 
 @include opt-homedir.texi
 
 
 @item -v
 @item --verbose
 @opindex v
 @opindex verbose
 Outputs additional information while running.
 You can increase the verbosity by giving several
 verbose commands to @command{gpgsm}, such as @samp{-vv}.
 
 @item --keyserver @var{string}
 @opindex keyserver
 This is a deprecated option.  It was used to add an LDAP server to use
 for X.509 certificate and CRL lookup.  The alias @option{--ldapserver}
 existed from version 2.2.28 to 2.2.33 but is now entirely ignored.
 
 LDAP servers must be given in the configuration for @command{dirmngr}.
 
 
 @item --policy-file @var{filename}
 @opindex policy-file
 Change the default name of the policy file to @var{filename}.
 
 @item --agent-program @var{file}
 @opindex agent-program
 Specify an agent program to be used for secret key operations.  The
 default value is determined by running the command @command{gpgconf}.
 Note that the pipe symbol (@code{|}) is used for a regression test
 suite hack and may thus not be used in the file name.
 
 @item --dirmngr-program @var{file}
 @opindex dirmngr-program
 Specify a dirmngr program to be used for @acronym{CRL} checks.  The
 default value is @file{@value{BINDIR}/dirmngr}.
 
 @item --prefer-system-dirmngr
 @opindex prefer-system-dirmngr
 This option is obsolete and ignored.
 
 @item --disable-dirmngr
 Entirely disable the use of the Dirmngr.
 
 @item --no-autostart
 @opindex no-autostart
 Do not start the gpg-agent or the dirmngr if it has not yet been
 started and its service is required.  This option is mostly useful on
 machines where the connection to gpg-agent has been redirected to
 another machines.  If dirmngr is required on the remote machine, it
 may be started manually using @command{gpgconf --launch dirmngr}.
 
 @item --no-secmem-warning
 @opindex no-secmem-warning
 Do not print a warning when the so called "secure memory" cannot be used.
 
 @item --log-file @var{file}
 @opindex log-file
 When running in server mode, append all logging output to @var{file}.
 Use @file{socket://} to log to socket.
 
 @end table
 
 
 @c *******************************************
 @c ********  CERTIFICATE OPTIONS  ************
 @c *******************************************
 @node Certificate Options
 @subsection Certificate related options
 
 @table @gnupgtabopt
 
 @item  --enable-policy-checks
 @itemx --disable-policy-checks
 @opindex enable-policy-checks
 @opindex disable-policy-checks
 By default policy checks are enabled.  These options may be used to
 change it.
 
 @item  --enable-crl-checks
 @itemx --disable-crl-checks
 @opindex enable-crl-checks
 @opindex disable-crl-checks
 By default the @acronym{CRL} checks are enabled and the DirMngr is
 used to check for revoked certificates.  The disable option is most
 useful with an off-line network connection to suppress this check and
 also to avoid that new certificates introduce a web bug by including a
 certificate specific CRL DP.  The disable option also disables an
 issuer certificate lookup via the authorityInfoAccess property of the
 certificate; the @option{--enable-issuer-key-retrieve} can be used
 to make use of that property anyway.
 
 @item  --enable-trusted-cert-crl-check
 @itemx --disable-trusted-cert-crl-check
 @opindex enable-trusted-cert-crl-check
 @opindex disable-trusted-cert-crl-check
 By default the @acronym{CRL} for trusted root certificates are checked
 like for any other certificates.  This allows a CA to revoke its own
 certificates voluntary without the need of putting all ever issued
 certificates into a CRL.  The disable option may be used to switch this
 extra check off.  Due to the caching done by the Dirmngr, there will not be
 any noticeable performance gain.  Note, that this also disables possible
 OCSP checks for trusted root certificates.  A more specific way of
 disabling this check is by adding the ``relax'' keyword to the root CA
 line of the @file{trustlist.txt}
 
 
 @item --force-crl-refresh
 @opindex force-crl-refresh
 Tell the dirmngr to reload the CRL for each request.  For better
 performance, the dirmngr will actually optimize this by suppressing
 the loading for short time intervals (e.g. 30 minutes). This option
 is useful to make sure that a fresh CRL is available for certificates
 hold in the keybox.  The suggested way of doing this is by using it
 along with the option @option{--with-validation} for a key listing
 command.  This option should not be used in a configuration file.
 
 @item --enable-issuer-based-crl-check
 @opindex enable-issuer-based-crl-check
 Run a CRL check even for certificates which do not have any CRL
 distribution point.  This requires that a suitable LDAP server has
 been configured in Dirmngr and that the CRL can be found using the
 issuer.  This option reverts to what GnuPG did up to version 2.2.20.
 This option is in general not useful.
 
 @item  --enable-ocsp
 @itemx --disable-ocsp
 @opindex enable-ocsp
 @opindex disable-ocsp
 By default @acronym{OCSP} checks are disabled.  The enable option may
 be used to enable OCSP checks via Dirmngr.  If @acronym{CRL} checks
 are also enabled, CRLs will be used as a fallback if for some reason an
 OCSP request will not succeed.  Note, that you have to allow OCSP
 requests in Dirmngr's configuration too (option
 @option{--allow-ocsp}) and configure Dirmngr properly.  If you do not do
 so you will get the error code @samp{Not supported}.
 
 @item --auto-issuer-key-retrieve
 @opindex auto-issuer-key-retrieve
 If a required certificate is missing while validating the chain of
 certificates, try to load that certificate from an external location.
 This usually means that Dirmngr is employed to search for the
 certificate.  Note that this option makes a "web bug" like behavior
 possible.  LDAP server operators can see which keys you request, so by
 sending you a message signed by a brand new key (which you naturally
-will not have on your local keybox), the operator can tell both your IP
-address and the time when you verified the signature.
+will not have on your local keybox), the operator can tell both your
+IP address and the time when you verified the signature.  Note that if
+CRL checking is not disabled issuer certificates are retrieved in any
+case using the caIssuers authorityInfoAccess method.
 
 
 @anchor{gpgsm-option --validation-model}
 @item --validation-model @var{name}
 @opindex validation-model
 This option changes the default validation model.  The only possible
 values are "shell" (which is the default), "chain" which forces the
 use of the chain model and "steed" for a new simplified model.  The
 chain model is also used if an option in the @file{trustlist.txt} or
 an attribute of the certificate requests it.  However the standard
 model (shell) is in that case always tried first.
 
 @item --ignore-cert-extension @var{oid}
 @opindex ignore-cert-extension
 Add @var{oid} to the list of ignored certificate extensions.  The
 @var{oid} is expected to be in dotted decimal form, like
 @code{2.5.29.3}.  This option may be used more than once.  Critical
 flagged certificate extensions matching one of the OIDs in the list
 are treated as if they are actually handled and thus the certificate
 will not be rejected due to an unknown critical extension.  Use this
 option with care because extensions are usually flagged as critical
 for a reason.
 
 @end table
 
 @c *******************************************
 @c ***********  INPUT AND OUTPUT  ************
 @c *******************************************
 @node Input and Output
 @subsection Input and Output
 
 @table @gnupgtabopt
 @item --armor
 @itemx -a
 @opindex armor
 Create PEM encoded output.  Default is binary output.
 
 @item --base64
 @opindex base64
 Create Base-64 encoded output; i.e. PEM without the header lines.
 
 @item --assume-armor
 @opindex assume-armor
 Assume the input data is PEM encoded.  Default is to autodetect the
 encoding but this is may fail.
 
 @item --assume-base64
 @opindex assume-base64
 Assume the input data is plain base-64 encoded.
 
 @item --assume-binary
 @opindex assume-binary
 Assume the input data is binary encoded.
 
 @item --input-size-hint @var{n}
 @opindex input-size-hint
 This option can be used to tell GPGSM the size of the input data in
 bytes.  @var{n} must be a positive base-10 number.  It is used by the
 @option{--status-fd} line ``PROGRESS'' to provide a value for
 ``total'' if that is not available by other means.
 
 @anchor{option --p12-charset}
 @item --p12-charset @var{name}
 @opindex p12-charset
 @command{gpgsm} uses the UTF-8 encoding when encoding passphrases for
 PKCS#12 files.  This option may be used to force the passphrase to be
 encoded in the specified encoding @var{name}.  This is useful if the
 application used to import the key uses a different encoding and thus
 will not be able to import a file generated by @command{gpgsm}.  Commonly
 used values for @var{name} are @code{Latin1} and @code{CP850}.  Note
 that @command{gpgsm} itself automagically imports any file with a
 passphrase encoded to the most commonly used encodings.
 
 
 @item --default-key @var{user_id}
 @opindex default-key
 Use @var{user_id} as the standard key for signing.  This key is used if
 no other key has been defined as a signing key.  Note, that the first
 @option{--local-users} option also sets this key if it has not yet been
 set; however @option{--default-key} always overrides this.
 
 
 @item --local-user @var{user_id}
 @item -u @var{user_id}
 @opindex local-user
 Set the user(s) to be used for signing.  The default is the first
 secret key found in the database.
 
 
 @item --recipient @var{name}
 @itemx -r
 @opindex recipient
 Encrypt to the user id @var{name}.  There are several ways a user id
 may be given (@pxref{how-to-specify-a-user-id}).
 
 
 @item --output @var{file}
 @itemx -o @var{file}
 @opindex output
 Write output to @var{file}.  The default is to write it to stdout.
 
 
 @anchor{gpgsm-option --with-key-data}
 @item --with-key-data
 @opindex with-key-data
 Displays extra information with the @code{--list-keys} commands.  Especially
 a line tagged @code{grp} is printed which tells you the keygrip of a
 key.  This string is for example used as the file name of the
 secret key.  Implies @code{--with-colons}.
 
 @anchor{gpgsm-option --with-validation}
 @item --with-validation
 @opindex with-validation
 When doing a key listing, do a full validation check for each key and
 print the result.  This is usually a slow operation because it
 requires a CRL lookup and other operations.
 
 When used along with @option{--import}, a validation of the certificate to
 import is done and only imported if it succeeds the test.  Note that
 this does not affect an already available certificate in the DB.
 This option is therefore useful to simply verify a certificate.
 
 
 @item --with-md5-fingerprint
 For standard key listings, also print the MD5 fingerprint of the
 certificate.
 
 @item --with-keygrip
 Include the keygrip in standard key listings.  Note that the keygrip is
 always listed in @option{--with-colons} mode.
 
 @item --with-secret
 @opindex with-secret
 Include info about the presence of a secret key in public key listings
 done with @code{--with-colons}.
 
 @end table
 
 @c *******************************************
 @c *************  CMS OPTIONS  ***************
 @c *******************************************
 @node CMS Options
 @subsection How to change how the CMS is created
 
 @table @gnupgtabopt
 @item --include-certs @var{n}
 @opindex include-certs
 Using @var{n} of -2 includes all certificate except for the root cert,
 -1 includes all certs, 0 does not include any certs, 1 includes only the
 signers cert and all other positive values include up to @var{n}
 certificates starting with the signer cert.  The default is -2.
 
 @item --cipher-algo @var{oid}
 @opindex cipher-algo
 Use the cipher algorithm with the ASN.1 object identifier @var{oid} for
 encryption.  For convenience the strings @code{3DES}, @code{AES} and
 @code{AES256} may be used instead of their OIDs.  The default is
 @code{AES} (2.16.840.1.101.3.4.1.2).
 
 @item --digest-algo @code{name}
 Use @code{name} as the message digest algorithm.  Usually this
 algorithm is deduced from the respective signing certificate.  This
 option forces the use of the given algorithm and may lead to severe
 interoperability problems.
 
 @end table
 
 
 
 @c *******************************************
 @c ********  ESOTERIC OPTIONS  ***************
 @c *******************************************
 @node Esoteric Options
 @subsection Doing things one usually do not want to do
 
 
 @table @gnupgtabopt
 
 @item --extra-digest-algo @var{name}
 @opindex extra-digest-algo
 Sometimes signatures are broken in that they announce a different digest
 algorithm than actually used.  @command{gpgsm} uses a one-pass data
 processing model and thus needs to rely on the announced digest
 algorithms to properly hash the data.  As a workaround this option may
 be used to tell @command{gpgsm} to also hash the data using the algorithm
 @var{name}; this slows processing down a little bit but allows verification of
 such broken signatures.  If @command{gpgsm} prints an error like
 ``digest algo 8 has not been enabled'' you may want to try this option,
 with @samp{SHA256} for @var{name}.
 
 @item --compliance @var{string}
 @opindex compliance
 Set the compliance mode.  Valid values are shown when using "help" for
 @var{string}.
 
 @item --min-rsa-length @var{n}
 @opindex min-rsa-length
 This option adjusts the compliance mode "de-vs" for stricter key size
 requirements.  For example, a value of 3000 turns rsa2048 and dsa2048
 keys into non-VS-NfD compliant keys.
 
 @item --require-compliance
 @opindex require-compliance
 To check that data has been encrypted according to the rules of the
 current compliance mode, a gpgsm user needs to evaluate the status
 lines.  This is allows frontends to handle compliance check in a more
 flexible way.  However, for scripted use the required evaluation of
 the status-line requires quite some effort; this option can be used
 instead to make sure that the gpgsm process exits with a failure if
 the compliance rules are not fulfilled.  Note that this option has
 currently an effect only in "de-vs" mode.
 
 @item --always-trust
 @opindex always-trust
 Force encryption to the specified certificates without any validation
 of the certificate chain.  The only requirement is that the
 certificate is capable of encryption.  Note that this option is
 ineffective if @option{--require-compliance} is used.
 
 @item --ignore-cert-with-oid @var{oid}
 @opindex ignore-cert-with-oid
 Add @var{oid} to the list of OIDs to be checked while reading
 certificates from smartcards. The @var{oid} is expected to be in
 dotted decimal form, like @code{2.5.29.3}.  This option may be used
 more than once.  As of now certificates with an extended key usage
 matching one of those OIDs are ignored during a @option{--learn-card}
 operation and not imported.  This option can help to keep the local
 key database clear of unneeded certificates stored on smartcards.
 
 @item --faked-system-time @var{epoch}
 @opindex faked-system-time
 This option is only useful for testing; it sets the system time back or
 forth to @var{epoch} which is the number of seconds elapsed since the year
 1970.  Alternatively @var{epoch} may be given as a full ISO time string
 (e.g. "20070924T154812").
 
 @item --with-ephemeral-keys
 @opindex with-ephemeral-keys
 Include ephemeral flagged keys in the output of key listings.  Note
 that they are included anyway if the key specification for a listing
 is given as fingerprint or keygrip.
 
 @item --compatibility-flags @var{flags}
 @opindex compatibility-flags
 Set compatibility flags to work around problems due to non-compliant
 certificates or data.  The @var{flags} are given as a comma separated
 list of flag names and are OR-ed together.  The special flag "none"
 clears the list and allows to start over with an empty list.  To get a
 list of available flags the sole word "help" can be used.
 
 @item --debug-level @var{level}
 @opindex debug-level
 Select the debug level for investigating problems. @var{level} may be
 a numeric value or by a keyword:
 
 @table @code
 @item none
 No debugging at all.  A value of less than 1 may be used instead of
 the keyword.
 @item basic
 Some basic debug messages.  A value between 1 and 2 may be used
 instead of the keyword.
 @item advanced
 More verbose debug messages.  A value between 3 and 5 may be used
 instead of the keyword.
 @item expert
 Even more detailed messages.  A value between 6 and 8 may be used
 instead of the keyword.
 @item guru
 All of the debug messages you can get. A value greater than 8 may be
 used instead of the keyword.  The creation of hash tracing files is
 only enabled if the keyword is used.
 @end table
 
 How these messages are mapped to the actual debugging flags is not
 specified and may change with newer releases of this program. They are
 however carefully selected to best aid in debugging.
 
 @item --debug @var{flags}
 @opindex debug
 This option is only useful for debugging and the behaviour may change
 at any time without notice; using @code{--debug-levels} is the
 preferred method to select the debug verbosity.  FLAGS are bit encoded
 and may be given in usual C-Syntax. The currently defined bits are:
 
 @table @code
 @item 0  (1)
 X.509 or OpenPGP protocol related data
 @item 1  (2)
 values of big number integers
 @item 2  (4)
 low level crypto operations
 @item 5  (32)
 memory allocation
 @item 6  (64)
 caching
 @item 7  (128)
 show memory statistics
 @item 9  (512)
 write hashed data to files named @code{dbgmd-000*}
 @item 10 (1024)
 trace Assuan protocol
 @end table
 
 Note, that all flags set using this option may get overridden by
 @code{--debug-level}.
 
 @item --debug-all
 @opindex debug-all
 Same as @code{--debug=0xffffffff}
 
 @item --debug-allow-core-dump
 @opindex debug-allow-core-dump
 Usually @command{gpgsm} tries to avoid dumping core by well written code and by
 disabling core dumps for security reasons.  However, bugs are pretty
 durable beasts and to squash them it is sometimes useful to have a core
 dump.  This option enables core dumps unless the Bad Thing happened
 before the option parsing.
 
 @item --debug-no-chain-validation
 @opindex debug-no-chain-validation
 This is actually not a debugging option but only useful as such.  It
 lets @command{gpgsm} bypass all certificate chain validation checks.
 
 @item --debug-ignore-expiration
 @opindex debug-ignore-expiration
 This is actually not a debugging option but only useful as such.  It
 lets @command{gpgsm} ignore all notAfter dates, this is used by the regression
 tests.
 
 @item --passphrase-fd @code{n}
 @opindex passphrase-fd
 Read the passphrase from file descriptor @code{n}. Only the first line
 will be read from file descriptor @code{n}. If you use 0 for @code{n},
 the passphrase will be read from STDIN. This can only be used if only
 one passphrase is supplied.
 
 Note that this passphrase is only used if the option @option{--batch}
 has also been given.
 
 @item --pinentry-mode @code{mode}
 @opindex pinentry-mode
 Set the pinentry mode to @code{mode}.  Allowed values for @code{mode}
 are:
 @table @asis
   @item default
   Use the default of the agent, which is @code{ask}.
   @item ask
   Force the use of the Pinentry.
   @item cancel
   Emulate use of Pinentry's cancel button.
   @item error
   Return a Pinentry error (``No Pinentry'').
   @item loopback
   Redirect Pinentry queries to the caller.  Note that in contrast to
   Pinentry the user is not prompted again if he enters a bad password.
 @end table
 
 @item --request-origin @var{origin}
 @opindex request-origin
 Tell gpgsm to assume that the operation ultimately originated at
 @var{origin}.  Depending on the origin certain restrictions are applied
 and the Pinentry may include an extra note on the origin.  Supported
 values for @var{origin} are: @code{local} which is the default,
 @code{remote} to indicate a remote origin or @code{browser} for an
 operation requested by a web browser.
 
 @item --no-common-certs-import
 @opindex no-common-certs-import
 Suppress the import of common certificates on keybox creation.
 
 @end table
 
 All the long options may also be given in the configuration file after
 stripping off the two leading dashes.
 
 @c *******************************************
 @c ***************            ****************
 @c ***************  USER ID   ****************
 @c ***************            ****************
 @c *******************************************
 @mansect how to specify a user id
 @ifset isman
 @include specify-user-id.texi
 @end ifset
 
 @c *******************************************
 @c ***************            ****************
 @c ***************   FILES    ****************
 @c ***************            ****************
 @c *******************************************
 @mansect files
 @node GPGSM Configuration
 @section Configuration files
 
 There are a few configuration files to control certain aspects of
 @command{gpgsm}'s operation. Unless noted, they are expected in the
 current home directory (@pxref{option --homedir}).
 
 @table @file
 
 @item gpgsm.conf
 @efindex gpgsm.conf
 This is the standard configuration file read by @command{gpgsm} on
 startup.  It may contain any valid long option; the leading two dashes
 may not be entered and the option may not be abbreviated.  This default
 name may be changed on the command line (@pxref{gpgsm-option --options}).
 You should backup this file.
 
 
 @item policies.txt
 @efindex policies.txt
 This is a list of allowed CA policies.  This file should list the
 object identifiers of the policies line by line.  Empty lines and
 lines starting with a hash mark are ignored.  Policies missing in this
 file and not marked as critical in the certificate will print only a
 warning; certificates with policies marked as critical and not listed
 in this file will fail the signature verification.  You should backup
 this file.
 
 For example, to allow only the policy 2.289.9.9, the file should look
 like this:
 
 @c man:.RS
 @example
 # Allowed policies
 2.289.9.9
 @end example
 @c man:.RE
 
 @item qualified.txt
 @efindex qualified.txt
 This is the list of root certificates used for qualified certificates.
 They are defined as certificates capable of creating legally binding
 signatures in the same way as handwritten signatures are.  Comments
 start with a hash mark and empty lines are ignored.  Lines do have a
 length limit but this is not a serious limitation as the format of the
 entries is fixed and checked by @command{gpgsm}: A non-comment line starts with
 optional whitespace, followed by exactly 40 hex characters, white space
 and a lowercased 2 letter country code.  Additional data delimited with
 by a white space is current ignored but might late be used for other
 purposes.
 
 Note that even if a certificate is listed in this file, this does not
 mean that the certificate is trusted; in general the certificates listed
 in this file need to be listed also in @file{trustlist.txt}.
 
 This is a global file an installed in the data directory
 (e.g. @file{@value{DATADIR}/qualified.txt}).  GnuPG installs a suitable
 file with root certificates as used in Germany.  As new Root-CA
 certificates may be issued over time, these entries may need to be
 updated; new distributions of this software should come with an updated
 list but it is still the responsibility of the Administrator to check
 that this list is correct.
 
 Every time @command{gpgsm} uses a certificate for signing or verification
 this file will be consulted to check whether the certificate under
 question has ultimately been issued by one of these CAs.  If this is the
 case the user will be informed that the verified signature represents a
 legally binding (``qualified'') signature.  When creating a signature
 using such a certificate an extra prompt will be issued to let the user
 confirm that such a legally binding signature shall really be created.
 
 Because this software has not yet been approved for use with such
 certificates, appropriate notices will be shown to indicate this fact.
 
 @item help.txt
 @efindex help.txt
 This is plain text file with a few help entries used with
 @command{pinentry} as well as a large list of help items for
 @command{gpg} and @command{gpgsm}.  The standard file has English help
 texts; to install localized versions use filenames like @file{help.LL.txt}
 with LL denoting the locale.  GnuPG comes with a set of predefined help
 files in the data directory (e.g. @file{@value{DATADIR}/gnupg/help.de.txt})
 and allows overriding of any help item by help files stored in the
 system configuration directory (e.g. @file{@value{SYSCONFDIR}/help.de.txt}).
 For a reference of the help file's syntax, please see the installed
 @file{help.txt} file.
 
 
 @item com-certs.pem
 @efindex com-certs.pem
 This file is a collection of common certificates used to populated a
 newly created @file{pubring.kbx}.  An administrator may replace this
 file with a custom one.  The format is a concatenation of PEM encoded
 X.509 certificates.  This global file is installed in the data directory
 (e.g. @file{@value{DATADIR}/com-certs.pem}).
 
 @end table
 
 @c man:.RE
 Note that on larger installations, it is useful to put predefined files
 into the directory @file{/etc/skel/.gnupg/} so that newly created users
 start up with a working configuration.  For existing users a small
 helper script is provided to create these files (@pxref{addgnupghome}).
 
 For internal purposes @command{gpgsm} creates and maintains a few other files;
 they all live in the current home directory (@pxref{option
 --homedir}).  Only @command{gpgsm} may modify these files.
 
 
 @table @file
 @item pubring.kbx
 @efindex pubring.kbx
 This a database file storing the certificates as well as meta
 information.  For debugging purposes the tool @command{kbxutil} may be
 used to show the internal structure of this file.  You should backup
 this file.
 
 @item random_seed
 @efindex random_seed
 This content of this file is used to maintain the internal state of the
 random number generator across invocations.  The same file is used by
 other programs of this software too.
 
 @item S.gpg-agent
 @efindex S.gpg-agent
 If this file exists
 @command{gpgsm} will first try to connect to this socket for
 accessing @command{gpg-agent} before starting a new @command{gpg-agent}
 instance.  Under Windows this socket (which in reality be a plain file
 describing a regular TCP listening port) is the standard way of
 connecting the @command{gpg-agent}.
 
 @end table
 
 
 @c *******************************************
 @c ***************            ****************
 @c ***************  EXAMPLES  ****************
 @c ***************            ****************
 @c *******************************************
 @mansect examples
 @node GPGSM Examples
 @section Examples
 
 @example
 $ gpgsm -er goo@@bar.net <plaintext >ciphertext
 @end example
 
 
 @c *******************************************
 @c ***************              **************
 @c ***************  UNATTENDED  **************
 @c ***************              **************
 @c *******************************************
 @manpause
 @node Unattended Usage
 @section Unattended Usage
 
 @command{gpgsm} is often used as a backend engine by other software.  To help
 with this a machine interface has been defined to have an unambiguous
 way to do this.  This is most likely used with the @code{--server} command
 but may also be used in the standard operation mode by using the
 @code{--status-fd} option.
 
 @menu
 * Automated signature checking::  Automated signature checking.
 * CSR and certificate creation::  CSR and certificate creation.
 @end menu
 
 @node Automated signature checking
 @subsection Automated signature checking
 
 It is very important to understand the semantics used with signature
 verification.  Checking a signature is not as simple as it may sound and
 so the operation is a bit complicated.  In most cases it is required
 to look at several status lines.  Here is a table of all cases a signed
 message may have:
 
 @table @asis
 @item The signature is valid
 This does mean that the signature has been successfully verified, the
 certificates are all sane.  However there are two subcases with
 important information:  One of the certificates may have expired or a
 signature of a message itself as expired.  It is a sound practise to
 consider such a signature still as valid but additional information
 should be displayed.  Depending on the subcase @command{gpgsm} will issue
 these status codes:
   @table @asis
   @item signature valid and nothing did expire
   @code{GOODSIG}, @code{VALIDSIG}, @code{TRUST_FULLY}
   @item signature valid but at least one certificate has expired
   @code{EXPKEYSIG}, @code{VALIDSIG}, @code{TRUST_FULLY}
   @item signature valid but expired
   @code{EXPSIG}, @code{VALIDSIG}, @code{TRUST_FULLY}
   Note, that this case is currently not implemented.
   @end table
 
 @item The signature is invalid
 This means that the signature verification failed (this is an indication
 of a transfer error, a program error or tampering with the message).
 @command{gpgsm} issues one of these status codes sequences:
   @table @code
   @item  @code{BADSIG}
   @item  @code{GOODSIG}, @code{VALIDSIG} @code{TRUST_NEVER}
   @end table
 
 @item Error verifying a signature
 For some reason the signature could not be verified, i.e. it cannot be
 decided whether the signature is valid or invalid.  A common reason for
 this is a missing certificate.
 
 @end table
 
 @node CSR and certificate creation
 @subsection CSR and certificate creation
 
 The command @option{--generate-key} may be used along with the option
 @option{--batch} to either create a certificate signing request (CSR)
 or an X.509 certificate.  This is controlled by a parameter file; the
 format of this file is as follows:
 
 @itemize @bullet
 @item Text only, line length is limited to about 1000 characters.
 @item UTF-8 encoding must be used to specify non-ASCII characters.
 @item Empty lines are ignored.
 @item Leading and trailing while space is ignored.
 @item A hash sign as the first non white space character indicates
 a comment line.
 @item Control statements are indicated by a leading percent sign, the
 arguments are separated by white space from the keyword.
 @item Parameters are specified by a keyword, followed by a colon.  Arguments
 are separated by white space.
 @item The first parameter must be @samp{Key-Type}, control statements
 may be placed anywhere.
 @item
 The order of the parameters does not matter except for @samp{Key-Type}
 which must be the first parameter.  The parameters are only used for
 the generated CSR/certificate; parameters from previous sets are not
 used.  Some syntactically checks may be performed.
 @item
 Key generation takes place when either the end of the parameter file
 is reached, the next @samp{Key-Type} parameter is encountered or at the
 control statement @samp{%commit} is encountered.
 @end itemize
 
 @noindent
 Control statements:
 
 @table @asis
 
 @item %echo @var{text}
 Print @var{text} as diagnostic.
 
 @item %dry-run
 Suppress actual key generation (useful for syntax checking).
 
 @item %commit
 Perform the key generation.  Note that an implicit commit is done at
 the next @asis{Key-Type} parameter.
 
 @c  %certfile <filename>
 @c      [Not yet implemented!]
 @c	Do not write the certificate to the keyDB but to <filename>.
 @c      This must be given before the first
 @c	commit to take place, duplicate specification of the same filename
 @c	is ignored, the last filename before a commit is used.
 @c	The filename is used until a new filename is used (at commit points)
 @c	and all keys are written to that file.	If a new filename is given,
 @c	this file is created (and overwrites an existing one).
 @c	Both control statements must be given.
 @end table
 
 @noindent
 General Parameters:
 
 @table @asis
 
 @item Key-Type: @var{algo}
 Starts a new parameter block by giving the type of the primary
 key. The algorithm must be capable of signing.  This is a required
 parameter.  The supported values for @var{algo} are @samp{rsa},
 @samp{ecdsa}, and @samp{eddsa}.
 
 @item Key-Length: @var{nbits}
 The requested length of a generated key in bits.  Defaults to
 3072. The value is ignored for ECC algorithms.
 
 @item Key-Grip: @var{hexstring}
 This is optional and used to generate a CSR or certificate for an
 already existing key.  Key-Length will be ignored when given.
 
 @item Key-Usage: @var{usage-list}
 Space or comma delimited list of key usage, allowed values are
 @samp{encrypt}, @samp{sign} and @samp{cert}.  This is used to generate
 the keyUsage extension.  Please make sure that the algorithm is
 capable of this usage.  Default is to allow encrypt and sign.
 
 @item Name-DN: @var{subject-name}
 This is the Distinguished Name (DN) of the subject in RFC-2253 format.
 
 @item Name-Email: @var{string}
 This is an email address for the altSubjectName.  This parameter is
 optional but may occur several times to add several email addresses to
 a certificate.
 
 @item Name-DNS: @var{string}
 The is an DNS name for the altSubjectName.  This parameter is optional
 but may occur several times to add several DNS names to a certificate.
 
 @item Name-URI: @var{string}
 This is an URI for the altSubjectName.  This parameter is optional but
 may occur several times to add several URIs to a certificate.
 @end table
 
 @noindent
 Additional parameters used to create a certificate (in contrast to a
 certificate signing request):
 
 @table @asis
 
 @item Serial: @var{sn}
 If this parameter is given an X.509 certificate will be generated.
 @var{sn} is expected to be a hex string representing an unsigned
 integer of arbitrary length.  The special value @samp{random} can be
 used to create a 64 bit random serial number.
 
 @item Issuer-DN: @var{issuer-name}
 This is the DN name of the issuer in RFC-2253 format.  If it is not set
 it will default to the subject DN and a special GnuPG extension will
 be included in the certificate to mark it as a standalone certificate.
 
 @item Creation-Date: @var{iso-date}
 @itemx Not-Before: @var{iso-date}
 Set the notBefore date of the certificate.  Either a date like
 @samp{1986-04-26} or @samp{1986-04-26 12:00} or a standard ISO
 timestamp like @samp{19860426T042640} may be used.  The time is
 considered to be UTC.  If it is not given the current date is used.
 
 @item Expire-Date: @var{iso-date}
 @itemx Not-After: @var{iso-date}
 Set the notAfter date of the certificate.  Either a date like
 @samp{2063-04-05} or @samp{2063-04-05 17:00} or a standard ISO
 timestamp like @samp{20630405T170000} may be used.  The time is
 considered to be UTC.  If it is not given a default value in the not
 too far future is used.
 
 @item Signing-Key: @var{keygrip}
 This gives the keygrip of the key used to sign the certificate.  If it
 is not given a self-signed certificate will be created.  For
 compatibility with future versions, it is suggested to prefix the
 keygrip with a @samp{&}.
 
 @item Hash-Algo: @var{hash-algo}
 Use @var{hash-algo} for this CSR or certificate.  The supported hash
 algorithms are: @samp{sha1}, @samp{sha256}, @samp{sha384} and
 @samp{sha512}; they may also be specified with uppercase letters.  The
 default is @samp{sha256}.
 
 @item Authority-Key-Id: @var{hexstring}
 Insert the decoded value of @var{hexstring} as authorityKeyIdentifier.
 If this is not given and an ECC algorithm is used the public part of
 the certified public key is used as authorityKeyIdentifier.  To
 inhibit any authorityKeyIdentifier use the special value @code{none}
 for @var{hexstring}.
 
 @item Subject-Key-Id: @var{hexstring}
 Insert the decoded value of @var{hexstring} as subjectKeyIdentifier.
 If this is not given and an ECC algorithm is used the public part of
 the signing key is used as authorityKeyIdentifier.  To inhibit any
 subjectKeyIdentifier use the special value @code{none} for
 @var{hexstring}.
 
 @end table
 
 @c *******************************************
 @c ***************           *****************
 @c ***************  ASSSUAN  *****************
 @c ***************           *****************
 @c *******************************************
 @node GPGSM Protocol
 @section The Protocol the Server Mode Uses
 
 Description of the protocol used to access @command{GPGSM}.
 @command{GPGSM} does implement the Assuan protocol and in addition
 provides a regular command line interface which exhibits a full client
 to this protocol (but uses internal linking).  To start
 @command{gpgsm} as a server the command line the option
 @code{--server} must be used.  Additional options are provided to
 select the communication method (i.e. the name of the socket).
 
 We assume that the connection has already been established; see the
 Assuan manual for details.
 
 @menu
 * GPGSM ENCRYPT::         Encrypting a message.
 * GPGSM DECRYPT::         Decrypting a message.
 * GPGSM SIGN::            Signing a message.
 * GPGSM VERIFY::          Verifying a message.
 * GPGSM GENKEY::          Generating a key.
 * GPGSM LISTKEYS::        List available keys.
 * GPGSM EXPORT::          Export certificates.
 * GPGSM IMPORT::          Import certificates.
 * GPGSM DELETE::          Delete certificates.
 * GPGSM GETAUDITLOG::     Retrieve an audit log.
 * GPGSM GETINFO::         Information about the process
 * GPGSM OPTION::          Session options.
 @end menu
 
 
 @node GPGSM ENCRYPT
 @subsection Encrypting a Message
 
 Before encryption can be done the recipient must be set using the
 command:
 
 @example
   RECIPIENT @var{userID}
 @end example
 
 Set the recipient for the encryption.  @var{userID} should be the
 internal representation of the key; the server may accept any other way
 of specification.  If this is a valid and trusted recipient the server
 does respond with OK, otherwise the return is an ERR with the reason why
 the recipient cannot be used, the encryption will then not be done for
 this recipient.  If the policy is not to encrypt at all if not all
 recipients are valid, the client has to take care of this.  All
 @code{RECIPIENT} commands are cumulative until a @code{RESET} or an
 successful @code{ENCRYPT} command.
 
 @example
   INPUT FD[=@var{n}] [--armor|--base64|--binary]
 @end example
 
 Set the file descriptor for the message to be encrypted to @var{n}.
 Obviously the pipe must be open at that point, the server establishes
 its own end.  If the server returns an error the client should consider
 this session failed.  If @var{n} is not given, this commands uses the
 last file descriptor passed to the application.
 @xref{fun-assuan_sendfd, ,the assuan_sendfd function,assuan,the Libassuan
 manual}, on how to do descriptor passing.
 
 The @code{--armor} option may be used to advise the server that the
 input data is in @acronym{PEM} format, @code{--base64} advises that a
 raw base-64 encoding is used, @code{--binary} advises of raw binary
 input (@acronym{BER}).  If none of these options is used, the server
 tries to figure out the used encoding, but this may not always be
 correct.
 
 @example
   OUTPUT FD[=@var{n}] [--armor|--base64]
 @end example
 
 Set the file descriptor to be used for the output (i.e. the encrypted
 message). Obviously the pipe must be open at that point, the server
 establishes its own end.  If the server returns an error the client
 should consider this session failed.
 
 The option @option{--armor} encodes the output in @acronym{PEM} format, the
 @option{--base64} option applies just a base-64 encoding.  No option
 creates binary output (@acronym{BER}).
 
 The actual encryption is done using the command
 
 @example
   ENCRYPT
 @end example
 
 It takes the plaintext from the @code{INPUT} command, writes to the
 ciphertext to the file descriptor set with the @code{OUTPUT} command,
 take the recipients from all the recipients set so far.  If this command
 fails the clients should try to delete all output currently done or
 otherwise mark it as invalid.  @command{GPGSM} does ensure that there
 will not be any
 security problem with leftover data on the output in this case.
 
 This command should in general not fail, as all necessary checks have
 been done while setting the recipients.  The input and output pipes are
 closed.
 
 
 @node GPGSM DECRYPT
 @subsection Decrypting a message
 
 Input and output FDs are set the same way as in encryption, but
 @code{INPUT} refers to the ciphertext and @code{OUTPUT} to the plaintext. There
 is no need to set recipients.  @command{GPGSM} automatically strips any
 @acronym{S/MIME} headers from the input, so it is valid to pass an
 entire MIME part to the INPUT pipe.
 
 The decryption is done by using the command
 
 @example
   DECRYPT
 @end example
 
 It performs the decrypt operation after doing some check on the internal
 state (e.g. that all needed data has been set).  Because it utilizes
 the GPG-Agent for the session key decryption, there is no need to ask
 the client for a protecting passphrase - GpgAgent takes care of this by
 requesting this from the user.
 
 
 @node GPGSM SIGN
 @subsection Signing a Message
 
 Signing is usually done with these commands:
 
 @example
   INPUT FD[=@var{n}] [--armor|--base64|--binary]
 @end example
 
 This tells @command{GPGSM} to read the data to sign from file descriptor @var{n}.
 
 @example
   OUTPUT FD[=@var{m}] [--armor|--base64]
 @end example
 
 Write the output to file descriptor @var{m}.  If a detached signature is
 requested, only the signature is written.
 
 @example
   SIGN [--detached]
 @end example
 
 Sign the data set with the @code{INPUT} command and write it to the sink set by
 @code{OUTPUT}.  With @code{--detached}, a detached signature is created
 (surprise).
 
 The key used for signing is the default one or the one specified in
 the configuration file.  To get finer control over the keys, it is
 possible to use the command
 
 @example
   SIGNER @var{userID}
 @end example
 
 to set the signer's key.  @var{userID} should be the
 internal representation of the key; the server may accept any other way
 of specification.  If this is a valid and trusted recipient the server
 does respond with OK, otherwise the return is an ERR with the reason why
 the key cannot be used, the signature will then not be created using
 this key.  If the policy is not to sign at all if not all
 keys are valid, the client has to take care of this.  All
 @code{SIGNER} commands are cumulative until a @code{RESET} is done.
 Note that a @code{SIGN} does not reset this list of signers which is in
 contrast to the @code{RECIPIENT} command.
 
 
 @node GPGSM VERIFY
 @subsection Verifying a Message
 
 To verify a message the command:
 
 @example
   VERIFY
 @end example
 
 is used. It does a verify operation on the message send to the input FD.
 The result is written out using status lines.  If an output FD was
 given, the signed text will be written to that.  If the signature is a
 detached one, the server will inquire about the signed material and the
 client must provide it.
 
 @node GPGSM GENKEY
 @subsection Generating a Key
 
 This is used to generate a new keypair, store the secret part in the
 @acronym{PSE} and the public key in the key database.  We will probably
 add optional commands to allow the client to select whether a hardware
 token is used to store the key.  Configuration options to
 @command{GPGSM} can be used to restrict the use of this command.
 
 @example
   GENKEY
 @end example
 
 @command{GPGSM} checks whether this command is allowed and then does an
 INQUIRY to get the key parameters, the client should then send the
 key parameters in the native format:
 
 @example
     S: INQUIRE KEY_PARAM native
     C: D foo:fgfgfg
     C: D bar
     C: END
 @end example
 
 Please note that the server may send Status info lines while reading the
 data lines from the client.  After this the key generation takes place
 and the server eventually does send an ERR or OK response.  Status lines
 may be issued as a progress indicator.
 
 
 @node GPGSM LISTKEYS
 @subsection List available keys
 @anchor{gpgsm-cmd listkeys}
 
 To list the keys in the internal database or using an external key
 provider, the command:
 
 @example
   LISTKEYS  @var{pattern}
 @end example
 
 is used.  To allow multiple patterns (which are ORed during the search)
 quoting is required: Spaces are to be translated into "+" or into "%20";
 in turn this requires that the usual escape quoting rules are done.
 
 @example
   LISTSECRETKEYS @var{pattern}
 @end example
 
 Lists only the keys where a secret key is available.
 
 The list commands are affected by the option
 
 @example
   OPTION list-mode=@var{mode}
 @end example
 
 where mode may be:
 @table @code
 @item 0
 Use default (which is usually the same as 1).
 @item 1
 List only the internal keys.
 @item 2
 List only the external keys.
 @item 3
 List internal and external keys.
 @end table
 
 Note that options are valid for the entire session.
 
 
 @node GPGSM EXPORT
 @subsection Export certificates
 
 To export certificate from the internal key database the command:
 
 @example
   EXPORT [--data [--armor] [--base64]] [--] @var{pattern}
 @end example
 
 is used.  To allow multiple patterns (which are ORed) quoting is
 required: Spaces are to be translated into "+" or into "%20"; in turn
 this requires that the usual escape quoting rules are done.
 
 If the @option{--data} option has not been given, the format of the
 output depends on what was set with the @code{OUTPUT} command.  When using
 @acronym{PEM} encoding a few informational lines are prepended.
 
 If the @option{--data} has been given, a target set via @code{OUTPUT} is
 ignored and the data is returned inline using standard
 @code{D}-lines. This avoids the need for an extra file descriptor.  In
 this case the options @option{--armor} and @option{--base64} may be used
 in the same way as with the @code{OUTPUT} command.
 
 
 @node GPGSM IMPORT
 @subsection Import certificates
 
 To import certificates into the internal key database, the command
 
 @example
   IMPORT [--re-import]
 @end example
 
 is used.  The data is expected on the file descriptor set with the
 @code{INPUT} command.  Certain checks are performed on the
 certificate.  Note that the code will also handle PKCS#12 files and
 import private keys; a helper program is used for that.
 
 With the option @option{--re-import} the input data is expected to a be
 a linefeed separated list of fingerprints.  The command will re-import
 the corresponding certificates; that is they are made permanent by
 removing their ephemeral flag.
 
 
 @node GPGSM DELETE
 @subsection Delete certificates
 
 To delete a certificate the command
 
 @example
   DELKEYS @var{pattern}
 @end example
 
 is used.  To allow multiple patterns (which are ORed) quoting is
 required: Spaces are to be translated into "+" or into "%20"; in turn
 this requires that the usual escape quoting rules are done.
 
 The certificates must be specified unambiguously otherwise an error is
 returned.
 
 @node GPGSM GETAUDITLOG
 @subsection Retrieve an audit log
 @anchor{gpgsm-cmd getauditlog}
 
 This command is used to retrieve an audit log.
 
 @example
 GETAUDITLOG [--data] [--html]
 @end example
 
 If @option{--data} is used, the audit log is send using D-lines
 instead of being sent to the file descriptor given by an @code{OUTPUT}
 command.  If @option{--html} is used, the output is formatted as an
 XHTML block. This is designed to be incorporated into a HTML
 document.
 
 
 @node GPGSM GETINFO
 @subsection  Return information about the process
 
 This is a multipurpose function to return a variety of information.
 
 @example
 GETINFO @var{what}
 @end example
 
 The value of @var{what} specifies the kind of information returned:
 @table @code
 @item version
 Return the version of the program.
 @item pid
 Return the process id of the process.
 @item agent-check
 Return OK if the agent is running.
 @item cmd_has_option @var{cmd} @var{opt}
 Return OK if the command @var{cmd} implements the option @var{opt}.
 The leading two dashes usually used with @var{opt} shall not be given.
 @item offline
 Return OK if the connection is in offline mode.  This may be either
 due to a @code{OPTION offline=1} or due to @command{gpgsm} being
 started with option @option{--disable-dirmngr}.
 @item always-trust
 Returns OK of the connection is in always-trust mode.  That is either
 @option{--always-trust} or @option{GPGSM OPTION always-trust} are
 active.
 @end table
 
 @node GPGSM OPTION
 @subsection  Session options
 
 The standard Assuan option handler supports these options.
 
 @example
 OPTION @var{name}[=@var{value}]
 @end example
 
 These @var{name}s are recognized:
 
 @table @code
 
 @item putenv
 Change the session's environment to be passed via gpg-agent to
 Pinentry.  @var{value} is a string of the form
 @code{<KEY>[=[<STRING>]]}.  If only @code{<KEY>} is given the
 environment variable @code{<KEY>} is removed from the session
 environment, if @code{<KEY>=} is given that environment variable is
 set to the empty string, and if @code{<STRING>} is given it is set to
 that string.
 
 @item display
 @efindex DISPLAY
 Set the session environment variable @code{DISPLAY} is set to @var{value}.
 @item ttyname
 @efindex GPG_TTY
 Set the session environment variable @code{GPG_TTY} is set to @var{value}.
 @item ttytype
 @efindex TERM
 Set the session environment variable @code{TERM} is set to @var{value}.
 @item lc-ctype
 @efindex LC_CTYPE
 Set the session environment variable @code{LC_CTYPE} is set to @var{value}.
 @item lc-messages
 @efindex LC_MESSAGES
 Set the session environment variable @code{LC_MESSAGES} is set to @var{value}.
 @item xauthority
 @efindex XAUTHORITY
 Set the session environment variable @code{XAUTHORITY} is set to @var{value}.
 @item pinentry-user-data
 @efindex PINENTRY_USER_DATA
 Set the session environment variable @code{PINENTRY_USER_DATA} is set
 to @var{value}.
 
 @item include-certs
 This option overrides the command line option
 @option{--include-certs}.  A @var{value} of -2 includes all
 certificates except for the root certificate, -1 includes all
 certificates, 0 does not include any certificates, 1 includes only the
 signers certificate and all other positive values include up to
 @var{value} certificates starting with the signer cert.
 
 @item list-mode
 @xref{gpgsm-cmd listkeys}.
 
 @item list-to-output
 If @var{value} is true the output of the list commands
 (@pxref{gpgsm-cmd listkeys}) is written to the file descriptor set
 with the last @code{OUTPUT} command.  If @var{value} is false the output is
 written via data lines; this is the default.
 
 @item with-validation
 If @var{value} is true for each listed certificate the validation
 status is printed.  This may result in the download of a CRL or the
 user being asked about the trustworthiness of a root certificate.  The
 default is given by a command line option (@pxref{gpgsm-option
 --with-validation}).
 
 
 @item with-secret
 If @var{value} is true certificates with a corresponding private key
 are marked by the list commands.
 
 @item validation-model
 This option overrides the command line option
 @option{validation-model} for the session.
 (@xref{gpgsm-option --validation-model}.)
 
 @item with-key-data
 This option globally enables the command line option
 @option{--with-key-data}.  (@xref{gpgsm-option --with-key-data}.)
 
 @item enable-audit-log
 If @var{value} is true data to write an audit log is gathered.
 (@xref{gpgsm-cmd getauditlog}.)
 
 @item allow-pinentry-notify
 If this option is used notifications about the launch of a Pinentry
 are passed back to the client.
 
 @item with-ephemeral-keys
 If @var{value} is true ephemeral certificates are included in the
 output of the list commands.
 
 @item no-encrypt-to
 If this option is used all keys set by the command line option
 @option{--encrypt-to} are ignored.
 
 @item offline
 If @var{value} is true or @var{value} is not given all network access
 is disabled for this session.  This is the same as the command line
 option @option{--disable-dirmngr}.
 
 @item always-trust
 If @var{value} is true or @var{value} is not given encryption to the
 specified certificates is forced without any validation of the
 certificate chain.  The only requirement is that the certificates are
 capable of encryption.  If set to false the standard behaviour is
 re-established.  This option is cleared by a RESET and after each
 encrypt operation.  Note that this option is ignored if
 @option{--always-trust} or @option{--require-compliance} are used.
 
 @item input-size-hint
 This is the same as the @option{--input-size-hint} command line option.
 
 @end table
 
 @mansect see also
 @ifset isman
 @command{gpg2}(1),
 @command{gpg-agent}(1)
 @end ifset
 @include see-also-note.texi
diff --git a/sm/verify.c b/sm/verify.c
index 6840ed16b..b092b90da 100644
--- a/sm/verify.c
+++ b/sm/verify.c
@@ -1,750 +1,756 @@
 /* verify.c - Verify a messages signature
  * Copyright (C) 2001, 2002, 2003, 2007,
  *               2010 Free Software Foundation, Inc.
  * Copyright (C) 2001-2019 Werner Koch
  * Copyright (C) 2015-2020 g10 Code GmbH
  *
  * This file is part of GnuPG.
  *
  * GnuPG is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 3 of the License, or
  * (at your option) any later version.
  *
  * GnuPG is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * 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 <https://www.gnu.org/licenses/>.
  * SPDX-License-Identifier: GPL-3.0-or-later
  */
 
 #include <config.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <errno.h>
 #include <unistd.h>
 #include <time.h>
 #include <assert.h>
 
 #include "gpgsm.h"
 #include <gcrypt.h>
 #include <ksba.h>
 
 #include "keydb.h"
 #include "../common/i18n.h"
 #include "../common/compliance.h"
 
 static char *
 strtimestamp_r (ksba_isotime_t atime)
 {
   char *buffer = xmalloc (15);
 
   if (!atime || !*atime)
     strcpy (buffer, "none");
   else
     sprintf (buffer, "%.4s-%.2s-%.2s", atime, atime+4, atime+6);
   return buffer;
 }
 
 
 
 /* Hash the data for a detached signature.  Returns 0 on success.  */
 static gpg_error_t
 hash_data (int fd, gcry_md_hd_t md)
 {
   gpg_error_t err = 0;
   estream_t fp;
   char buffer[4096];
   int nread;
 
   fp = es_fdopen_nc (fd, "rb");
   if (!fp)
     {
       err = gpg_error_from_syserror ();
       log_error ("fdopen(%d) failed: %s\n", fd, gpg_strerror (err));
       return err;
     }
 
   do
     {
       nread = es_fread (buffer, 1, DIM(buffer), fp);
       gcry_md_write (md, buffer, nread);
     }
   while (nread);
   if (es_ferror (fp))
     {
       err = gpg_error_from_syserror ();
       log_error ("read error on fd %d: %s\n", fd, gpg_strerror (err));
     }
   es_fclose (fp);
   return err;
 }
 
 
 
 
 /* Perform a verify operation.  To verify detached signatures, DATA_FD
    must be different than -1.  With OUT_FP given and a non-detached
    signature, the signed material is written to that stream.  */
 int
 gpgsm_verify (ctrl_t ctrl, int in_fd, int data_fd, estream_t out_fp)
 {
   int i, rc;
   gnupg_ksba_io_t b64reader = NULL;
   gnupg_ksba_io_t b64writer = NULL;
   ksba_reader_t reader;
   ksba_writer_t writer = NULL;
   ksba_cms_t cms = NULL;
   ksba_stop_reason_t stopreason;
   ksba_cert_t cert;
   KEYDB_HANDLE kh;
   gcry_md_hd_t data_md = NULL;
   int signer;
   const char *algoid;
   int algo;
-  int is_detached;
+  int is_detached, maybe_detached;
   estream_t in_fp = NULL;
   char *p;
 
   audit_set_type (ctrl->audit, AUDIT_TYPE_VERIFY);
 
+  /* Although we detect detached signatures during the parsing phase,
+   * we need to know it earlier and thus accept the caller's idea of
+   * what to verify.  */
+  maybe_detached = (data_fd != -1);
+
   kh = keydb_new ();
   if (!kh)
     {
       log_error (_("failed to allocate keyDB handle\n"));
       rc = gpg_error (GPG_ERR_GENERAL);
       goto leave;
     }
 
 
   in_fp = es_fdopen_nc (in_fd, "rb");
   if (!in_fp)
     {
       rc = gpg_error_from_syserror ();
       log_error ("fdopen() failed: %s\n", strerror (errno));
       goto leave;
     }
 
   rc = gnupg_ksba_create_reader
     (&b64reader, ((ctrl->is_pem? GNUPG_KSBA_IO_PEM : 0)
                   | (ctrl->is_base64? GNUPG_KSBA_IO_BASE64 : 0)
-                  | (ctrl->autodetect_encoding? GNUPG_KSBA_IO_AUTODETECT : 0)),
+                  | (ctrl->autodetect_encoding? GNUPG_KSBA_IO_AUTODETECT : 0)
+                  | (maybe_detached? GNUPG_KSBA_IO_STRIP : 0)),
      in_fp, &reader);
   if (rc)
     {
       log_error ("can't create reader: %s\n", gpg_strerror (rc));
       goto leave;
     }
 
   if (out_fp)
     {
       rc = gnupg_ksba_create_writer
         (&b64writer, ((ctrl->create_pem? GNUPG_KSBA_IO_PEM : 0)
                       | (ctrl->create_base64? GNUPG_KSBA_IO_BASE64 : 0)),
          ctrl->pem_name, out_fp, &writer);
       if (rc)
         {
           log_error ("can't create writer: %s\n", gpg_strerror (rc));
           goto leave;
         }
     }
 
   gnupg_ksba_set_progress_cb (b64writer, gpgsm_progress_cb, ctrl);
   if (ctrl->input_size_hint)
     gnupg_ksba_set_total (b64writer, ctrl->input_size_hint);
 
   rc = ksba_cms_new (&cms);
   if (rc)
     goto leave;
 
   rc = ksba_cms_set_reader_writer (cms, reader, writer);
   if (rc)
     {
       log_error ("ksba_cms_set_reader_writer failed: %s\n",
                  gpg_strerror (rc));
       goto leave;
     }
 
   rc = gcry_md_open (&data_md, 0, 0);
   if (rc)
     {
       log_error ("md_open failed: %s\n", gpg_strerror (rc));
       goto leave;
     }
   if (DBG_HASHING)
     gcry_md_debug (data_md, "vrfy.data");
 
   audit_log (ctrl->audit, AUDIT_SETUP_READY);
 
   is_detached = 0;
   do
     {
       rc = ksba_cms_parse (cms, &stopreason);
       if (rc)
         {
           log_error ("ksba_cms_parse failed: %s\n", gpg_strerror (rc));
           goto leave;
         }
 
       if (stopreason == KSBA_SR_NEED_HASH)
         {
           is_detached = 1;
           audit_log (ctrl->audit, AUDIT_DETACHED_SIGNATURE);
           if (opt.verbose)
             log_info ("detached signature\n");
         }
 
       if (stopreason == KSBA_SR_NEED_HASH
           || stopreason == KSBA_SR_BEGIN_DATA)
         {
           audit_log (ctrl->audit, AUDIT_GOT_DATA);
 
           /* We are now able to enable the hash algorithms */
           for (i=0; (algoid=ksba_cms_get_digest_algo_list (cms, i)); i++)
             {
               algo = gcry_md_map_name (algoid);
               if (!algo)
                 {
                   log_error ("unknown hash algorithm '%s'\n",
                              algoid? algoid:"?");
                   if (algoid
                       && (  !strcmp (algoid, "1.2.840.113549.1.1.2")
                           ||!strcmp (algoid, "1.2.840.113549.2.2")))
                     log_info (_("(this is the MD2 algorithm)\n"));
                   audit_log_s (ctrl->audit, AUDIT_BAD_DATA_HASH_ALGO, algoid);
                 }
               else
                 {
                   if (DBG_X509)
                     log_debug ("enabling hash algorithm %d (%s)\n",
                                algo, algoid? algoid:"");
                   gcry_md_enable (data_md, algo);
                   audit_log_i (ctrl->audit, AUDIT_DATA_HASH_ALGO, algo);
                 }
             }
           if (opt.extra_digest_algo)
             {
               if (DBG_X509)
                 log_debug ("enabling extra hash algorithm %d\n",
                            opt.extra_digest_algo);
               gcry_md_enable (data_md, opt.extra_digest_algo);
               audit_log_i (ctrl->audit, AUDIT_DATA_HASH_ALGO,
                            opt.extra_digest_algo);
             }
           if (is_detached)
             {
               if (data_fd == -1)
                 {
                   log_info ("detached signature w/o data "
                             "- assuming certs-only\n");
                   audit_log (ctrl->audit, AUDIT_CERT_ONLY_SIG);
                 }
               else
                 audit_log_ok (ctrl->audit, AUDIT_DATA_HASHING,
                               hash_data (data_fd, data_md));
             }
           else
             {
               ksba_cms_set_hash_function (cms, HASH_FNC, data_md);
             }
         }
       else if (stopreason == KSBA_SR_END_DATA)
         { /* The data bas been hashed */
           audit_log_ok (ctrl->audit, AUDIT_DATA_HASHING, 0);
         }
     }
   while (stopreason != KSBA_SR_READY);
 
   if (b64writer)
     {
       rc = gnupg_ksba_finish_writer (b64writer);
       if (rc)
         {
           log_error ("write failed: %s\n", gpg_strerror (rc));
           audit_log_ok (ctrl->audit, AUDIT_WRITE_ERROR, rc);
           goto leave;
         }
     }
 
   if (data_fd != -1 && !is_detached)
     {
       log_error ("data given for a non-detached signature\n");
       rc = gpg_error (GPG_ERR_CONFLICT);
       audit_log (ctrl->audit, AUDIT_USAGE_ERROR);
       goto leave;
     }
 
   for (i=0; (cert=ksba_cms_get_cert (cms, i)); i++)
     {
       /* Fixme: it might be better to check the validity of the
          certificate first before entering it into the DB.  This way
          we would avoid cluttering the DB with invalid
          certificates. */
       audit_log_cert (ctrl->audit, AUDIT_SAVE_CERT, cert,
                       keydb_store_cert (ctrl, cert, 0, NULL));
       ksba_cert_release (cert);
     }
 
   cert = NULL;
   for (signer=0; ; signer++)
     {
       char *issuer = NULL;
       gcry_sexp_t sigval = NULL;
       ksba_isotime_t sigtime, keyexptime;
       ksba_sexp_t serial;
       char *msgdigest = NULL;
       size_t msgdigestlen;
       char *ctattr;
       int sigval_hash_algo;
       int info_pkalgo;
       unsigned int nbits;
       int pkalgo;
       char *pkalgostr = NULL;
       char *pkcurve = NULL;
       char *pkfpr = NULL;
       unsigned int pkalgoflags, verifyflags;
 
       rc = ksba_cms_get_issuer_serial (cms, signer, &issuer, &serial);
       if (!signer && gpg_err_code (rc) == GPG_ERR_NO_DATA
           && data_fd == -1 && is_detached)
         {
           log_info ("certs-only message accepted\n");
           rc = 0;
           break;
         }
       if (rc)
         {
           if (signer && rc == -1)
             rc = 0;
           break;
         }
 
       gpgsm_status (ctrl, STATUS_NEWSIG, NULL);
       audit_log_i (ctrl->audit, AUDIT_NEW_SIG, signer);
 
       if (DBG_X509)
         {
           log_debug ("signer %d - issuer: '%s'\n",
                      signer, issuer? issuer:"[NONE]");
           log_debug ("signer %d - serial: ", signer);
           gpgsm_dump_serial (serial);
           log_printf ("\n");
         }
       if (ctrl->audit)
         {
           char *tmpstr = gpgsm_format_sn_issuer (serial, issuer);
           audit_log_s (ctrl->audit, AUDIT_SIG_NAME, tmpstr);
           xfree (tmpstr);
         }
 
       rc = ksba_cms_get_signing_time (cms, signer, sigtime);
       if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
         *sigtime = 0;
       else if (rc)
         {
           log_error ("error getting signing time: %s\n", gpg_strerror (rc));
           *sigtime = 0; /* (we can't encode an error in the time string.) */
         }
 
       rc = ksba_cms_get_message_digest (cms, signer,
                                         &msgdigest, &msgdigestlen);
       if (!rc)
         {
           algoid = ksba_cms_get_digest_algo (cms, signer);
           algo = gcry_md_map_name (algoid);
           if (DBG_X509)
             log_debug ("signer %d - digest algo: %d\n", signer, algo);
           if (! gcry_md_is_enabled (data_md, algo))
             {
               log_error ("digest algo %d (%s) has not been enabled\n",
                          algo, algoid?algoid:"");
               audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "unsupported");
               goto next_signer;
             }
         }
       else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
         {
           assert (!msgdigest);
           rc = 0;
           algoid = NULL;
           algo = 0;
         }
       else /* real error */
         {
           audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "error");
           break;
         }
 
       rc = ksba_cms_get_sigattr_oids (cms, signer,
                                       "1.2.840.113549.1.9.3", &ctattr);
       if (!rc)
         {
           const char *s;
 
           if (DBG_X509)
             log_debug ("signer %d - content-type attribute: %s",
                        signer, ctattr);
 
           s = ksba_cms_get_content_oid (cms, 1);
           if (!s || strcmp (ctattr, s))
             {
               log_error ("content-type attribute does not match "
                          "actual content-type\n");
               ksba_free (ctattr);
               ctattr = NULL;
               audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "bad");
               goto next_signer;
             }
           ksba_free (ctattr);
           ctattr = NULL;
         }
       else if (rc != -1)
         {
           log_error ("error getting content-type attribute: %s\n",
                      gpg_strerror (rc));
           audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "bad");
           goto next_signer;
         }
       rc = 0;
 
 
       sigval = gpgsm_ksba_cms_get_sig_val (cms, signer);
       if (!sigval)
         {
           log_error ("no signature value available\n");
           audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "bad");
           goto next_signer;
         }
 
       sigval_hash_algo = gpgsm_get_hash_algo_from_sigval (sigval, &pkalgoflags);
       if (DBG_X509)
         {
           log_debug ("signer %d - signature available (sigval hash=%d pkaf=%u)",
                      signer, sigval_hash_algo, pkalgoflags);
         }
       if (!sigval_hash_algo)
         sigval_hash_algo = algo; /* Fallback used e.g. with old libksba. */
 
       /* Find the certificate of the signer */
       keydb_search_reset (kh);
       rc = keydb_search_issuer_sn (ctrl, kh, issuer, serial);
       if (rc)
         {
           if (rc == -1)
             {
               log_error ("certificate not found\n");
               rc = gpg_error (GPG_ERR_NO_PUBKEY);
             }
           else
             log_error ("failed to find the certificate: %s\n",
                        gpg_strerror(rc));
           {
             char numbuf[50];
             sprintf (numbuf, "%d", rc);
 
             gpgsm_status2 (ctrl, STATUS_ERROR, "verify.findkey",
                            numbuf, NULL);
           }
           audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "no-cert");
           goto next_signer;
         }
 
       rc = keydb_get_cert (kh, &cert);
       if (rc)
         {
           log_error ("failed to get cert: %s\n", gpg_strerror (rc));
           audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "error");
           goto next_signer;
         }
 
       pkfpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1);
       pkalgostr = gpgsm_pubkey_algo_string (cert, NULL);
       pkalgo = gpgsm_get_key_algo_info2 (cert, &nbits, &pkcurve);
       /* Remap the ECC algo to the algo we use.  Note that EdDSA has
        * already been mapped.  */
       if (pkalgo == GCRY_PK_ECC)
         pkalgo = GCRY_PK_ECDSA;
 
       log_info (_("Signature made "));
       if (*sigtime)
         {
           /* We take the freedom as noted in RFC3339 to use a space
            * instead of the "T" delimiter between date and time.  We
            * also append a separate UTC instead of a "Z" or "+00:00"
            * suffix because that makes it clear to everyone what kind
            * of time this is.  */
           dump_isotime (sigtime);
           log_printf (" UTC");
         }
       else
         log_printf (_("[date not given]"));
       log_info (_("               using %s key %s\n"), pkalgostr, pkfpr);
       if (opt.verbose)
         {
           log_info (_("algorithm:"));
           log_printf (" %s + %s",
                       pubkey_algo_to_string (pkalgo),
                       gcry_md_algo_name (sigval_hash_algo));
           if (algo != sigval_hash_algo)
             log_printf (" (%s)", gcry_md_algo_name (algo));
           log_printf ("\n");
         }
 
       audit_log_i (ctrl->audit, AUDIT_DATA_HASH_ALGO, algo);
 
       /* Check compliance.  */
       if (! gnupg_pk_is_allowed (opt.compliance, PK_USE_VERIFICATION,
                                  pkalgo, pkalgoflags, NULL, nbits, NULL))
         {
           char  kidstr[10+1];
 
           snprintf (kidstr, sizeof kidstr, "0x%08lX",
                     gpgsm_get_short_fingerprint (cert, NULL));
           log_error (_("key %s may not be used for signing in %s mode\n"),
                      kidstr,
                      gnupg_compliance_option_string (opt.compliance));
           goto next_signer;
         }
 
       if (!gnupg_digest_is_allowed (opt.compliance, 0, sigval_hash_algo))
         {
           log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
                      gcry_md_algo_name (sigval_hash_algo),
                      gnupg_compliance_option_string (opt.compliance));
           goto next_signer;
         }
 
       /* Print compliance warning for the key.  */
       if (!opt.quiet
           && !gnupg_pk_is_compliant (opt.compliance, pkalgo, pkalgoflags,
                                      NULL, nbits, pkcurve))
           {
             log_info (_("WARNING: This key is not suitable for signing"
                         " in %s mode\n"),
                       gnupg_compliance_option_string (opt.compliance));
           }
 
       /* Check compliance with CO_DE_VS.  */
       if (gnupg_pk_is_compliant (CO_DE_VS, pkalgo, pkalgoflags,
                                  NULL, nbits, pkcurve)
           && gnupg_gcrypt_is_compliant (CO_DE_VS)
           && gnupg_digest_is_compliant (CO_DE_VS, sigval_hash_algo))
         gpgsm_status (ctrl, STATUS_VERIFICATION_COMPLIANCE_MODE,
                       gnupg_status_compliance_flag (CO_DE_VS));
       else if (opt.require_compliance
                && opt.compliance == CO_DE_VS)
         {
           log_error (_("operation forced to fail due to"
                        " unfulfilled compliance rules\n"));
           gpgsm_errors_seen = 1;
         }
 
       /* Now we can check the signature.  */
       if (msgdigest)
         { /* Signed attributes are available. */
           gcry_md_hd_t md;
           unsigned char *s;
 
           /* Check that the message digest in the signed attributes
              matches the one we calculated on the data.  */
           s = gcry_md_read (data_md, algo);
           if ( !s || !msgdigestlen
                || gcry_md_get_algo_dlen (algo) != msgdigestlen
                || memcmp (s, msgdigest, msgdigestlen) )
             {
               char *fpr;
 
               log_error (_("invalid signature: message digest attribute "
                            "does not match computed one\n"));
               if (DBG_X509)
                 {
                   if (msgdigest)
                     log_printhex (msgdigest, msgdigestlen, "message:  ");
                   if (s)
                     log_printhex (s, gcry_md_get_algo_dlen (algo),
                                   "computed: ");
                 }
               fpr = gpgsm_fpr_and_name_for_status (cert);
               gpgsm_status (ctrl, STATUS_BADSIG, fpr);
               xfree (fpr);
               audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "bad");
               goto next_signer;
             }
 
           audit_log_i (ctrl->audit, AUDIT_ATTR_HASH_ALGO, sigval_hash_algo);
           rc = gcry_md_open (&md, sigval_hash_algo, 0);
           if (rc)
             {
               log_error ("md_open failed: %s\n", gpg_strerror (rc));
               audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "error");
               goto next_signer;
             }
           if (DBG_HASHING)
             gcry_md_debug (md, "vrfy.attr");
 
           ksba_cms_set_hash_function (cms, HASH_FNC, md);
           rc = ksba_cms_hash_signed_attrs (cms, signer);
           if (rc)
             {
               log_error ("hashing signed attrs failed: %s\n",
                          gpg_strerror (rc));
               gcry_md_close (md);
               audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "error");
               goto next_signer;
             }
           rc = gpgsm_check_cms_signature (cert, sigval, md, sigval_hash_algo,
                                           pkalgoflags, &info_pkalgo);
           gcry_md_close (md);
         }
       else
         {
           rc = gpgsm_check_cms_signature (cert, sigval, data_md,
                                           algo, pkalgoflags, &info_pkalgo);
         }
 
       if (rc)
         {
           char *fpr;
 
           log_error ("invalid signature: %s\n", gpg_strerror (rc));
           fpr = gpgsm_fpr_and_name_for_status (cert);
           gpgsm_status (ctrl, STATUS_BADSIG, fpr);
           xfree (fpr);
           audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "bad");
           goto next_signer;
         }
       rc = gpgsm_cert_use_verify_p (cert); /*(this displays an info message)*/
       if (rc)
         {
           gpgsm_status_with_err_code (ctrl, STATUS_ERROR, "verify.keyusage",
                                       gpg_err_code (rc));
           rc = 0;
         }
 
       if (DBG_X509)
         log_debug ("signature okay - checking certs\n");
       audit_log (ctrl->audit, AUDIT_VALIDATE_CHAIN);
       rc = gpgsm_validate_chain (ctrl, cert,
                                  *sigtime? sigtime : "19700101T000000",
                                  keyexptime, 0,
                                  NULL, 0, &verifyflags);
       {
         char *fpr, *buf, *tstr;
 
         fpr = gpgsm_fpr_and_name_for_status (cert);
         if (gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED)
           {
             gpgsm_status (ctrl, STATUS_EXPKEYSIG, fpr);
             rc = 0;
           }
         else
           gpgsm_status (ctrl, STATUS_GOODSIG, fpr);
 
         xfree (fpr);
 
         fpr = gpgsm_get_fingerprint_hexstring (cert, GCRY_MD_SHA1);
         tstr = strtimestamp_r (sigtime);
         buf = xasprintf ("%s %s %s %s 0 0 %d %d 00", fpr, tstr,
                          *sigtime? sigtime : "0",
                          *keyexptime? keyexptime : "0",
                          info_pkalgo, algo);
         xfree (tstr);
         xfree (fpr);
         gpgsm_status (ctrl, STATUS_VALIDSIG, buf);
         xfree (buf);
       }
 
       audit_log_ok (ctrl->audit, AUDIT_CHAIN_STATUS, rc);
       if (rc) /* of validate_chain */
         {
           log_error ("invalid certification chain: %s\n", gpg_strerror (rc));
           if (gpg_err_code (rc) == GPG_ERR_BAD_CERT_CHAIN
               || gpg_err_code (rc) == GPG_ERR_BAD_CERT
               || gpg_err_code (rc) == GPG_ERR_BAD_CA_CERT
               || gpg_err_code (rc) == GPG_ERR_CERT_REVOKED)
             gpgsm_status_with_err_code (ctrl, STATUS_TRUST_NEVER, NULL,
                                         gpg_err_code (rc));
           else
             gpgsm_status_with_err_code (ctrl, STATUS_TRUST_UNDEFINED, NULL,
                                         gpg_err_code (rc));
           audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "bad");
           goto next_signer;
         }
 
       audit_log_s (ctrl->audit, AUDIT_SIG_STATUS, "good");
 
       for (i=0; (p = ksba_cert_get_subject (cert, i)); i++)
         {
           log_info (!i? _("Good signature from")
                       : _("                aka"));
           log_printf (" \"");
           gpgsm_es_print_name (log_get_stream (), p);
           log_printf ("\"\n");
           ksba_free (p);
         }
 
       /* Print a note if this is a qualified signature.  */
       {
         size_t qualbuflen;
         char qualbuffer[1];
 
         rc = ksba_cert_get_user_data (cert, "is_qualified", &qualbuffer,
                                       sizeof (qualbuffer), &qualbuflen);
         if (!rc && qualbuflen)
           {
             if (*qualbuffer)
               {
                 log_info (_("This is a qualified signature\n"));
                 if (!opt.qualsig_approval)
                   log_info
                     (_("Note, that this software is not officially approved "
                        "to create or verify such signatures.\n"));
               }
           }
         else if (gpg_err_code (rc) != GPG_ERR_NOT_FOUND)
           log_error ("get_user_data(is_qualified) failed: %s\n",
                      gpg_strerror (rc));
       }
 
       gpgsm_status (ctrl, STATUS_TRUST_FULLY,
                     (verifyflags & VALIDATE_FLAG_STEED)?
                     "0 steed":
                     (verifyflags & VALIDATE_FLAG_CHAIN_MODEL)?
                     "0 chain": "0 shell");
 
     next_signer:
       rc = 0;
       xfree (issuer);
       xfree (serial);
       gcry_sexp_release (sigval);
       xfree (msgdigest);
       xfree (pkalgostr);
       xfree (pkcurve);
       xfree (pkfpr);
       ksba_cert_release (cert);
       cert = NULL;
     }
   rc = 0;
 
  leave:
   ksba_cms_release (cms);
   gnupg_ksba_destroy_reader (b64reader);
   gnupg_ksba_destroy_writer (b64writer);
   keydb_release (kh);
   gcry_md_close (data_md);
   es_fclose (in_fp);
 
   if (rc)
     {
       char numbuf[50];
       sprintf (numbuf, "%d", rc );
       gpgsm_status2 (ctrl, STATUS_ERROR, "verify.leave",
                      numbuf, NULL);
     }
 
   return rc;
 }