~ubuntu-branches/ubuntu/natty/gnupg2/natty-security

« back to all changes in this revision

Viewing changes to scd/app-openpgp.c

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Urlichs
  • Date: 2005-12-08 22:13:21 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20051208221321-4rvs2vu835iam5wv
Tags: 1.9.19-2
* Convert debian/changelog to UTF-8.
* Put gnupg-agent and gpgsm lintian overrides in the respectively
  right package.  Closes: #335066
* Added debhelper tokens to maintainer scripts.
* xsession fixes:
  o Added host name to gpg-agent PID file name.  Closes: #312717
  o Fixed xsession script to be able to run under zsh.  Closes: #308516
  o Don't run gpg-agent if one is already running.  Closes: #336480
* debian/control:
  o Fixed package description of gpgsm package.  Closes: #299842
  o Added mention of gpg-agent to description of gnupg-agent package.
    Closes: #304355
* Thanks to Peter Eisentraut <petere@debian.org> for all of the above.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/* app-openpgp.c - The OpenPGP card application.
2
 
 *      Copyright (C) 2003, 2004 Free Software Foundation, Inc.
 
2
 *      Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
3
3
 *
4
4
 * This file is part of GnuPG.
5
5
 *
17
17
 * along with this program; if not, write to the Free Software
18
18
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
19
19
 *
20
 
 * $Id: app-openpgp.c,v 1.9.2.22 2004/10/22 09:41:56 wk Exp $
 
20
 * $Id: app-openpgp.c,v 1.9.2.38 2005/06/16 08:11:59 wk Exp $
21
21
 */
22
22
 
23
23
#include <config.h>
79
79
  { 0x00C4, 0, 0x6E, 1, 0, 1, 1, "CHV Status Bytes" },
80
80
  { 0x00C5, 0, 0x6E, 1, 0, 0, 0, "Fingerprints" },
81
81
  { 0x00C6, 0, 0x6E, 1, 0, 0, 0, "CA Fingerprints" },
 
82
  { 0x00CD, 0, 0x6E, 1, 0, 0, 0, "Generation time" },
82
83
  { 0x007A, 1,    0, 1, 0, 0, 0, "Security Support Template" },
83
84
  { 0x0093, 0, 0x7A, 1, 1, 0, 0, "Digital Signature Counter" },
 
85
  { 0x0101, 0,    0, 0, 0, 0, 0, "Private DO 1"},
 
86
  { 0x0102, 0,    0, 0, 0, 0, 0, "Private DO 2"},
 
87
  { 0x0103, 0,    0, 0, 0, 0, 0, "Private DO 3"},
 
88
  { 0x0104, 0,    0, 0, 0, 0, 0, "Private DO 4"},
84
89
  { 0 }
85
90
};
86
91
 
87
92
 
 
93
/* One cache item for DOs.  */
88
94
struct cache_s {
89
95
  struct cache_s *next;
90
96
  int tag;
92
98
  unsigned char data[1];
93
99
};
94
100
 
 
101
 
 
102
/* Object with application (i.e. OpenPGP card) specific data.  */
95
103
struct app_local_s {
 
104
  /* A linked list with cached DOs.  */
96
105
  struct cache_s *cache;
 
106
  
 
107
  /* Keep track of the public keys.  */
 
108
  struct
 
109
  {
 
110
    int read_done;   /* True if we have at least tried to read them.  */
 
111
    unsigned char *key; /* This is a malloced buffer with a canonical
 
112
                           encoded S-expression encoding a public
 
113
                           key. Might be NULL if key is not
 
114
                           available.  */
 
115
    size_t keylen;      /* The length of the above S-expression.  Thsi
 
116
                           is usullay only required for corss checks
 
117
                           because the length of an S-expression is
 
118
                           implicitly available.  */
 
119
  } pk[3];
 
120
 
 
121
  /* Keep track of card capabilities.  */
97
122
  struct 
98
123
  {
99
124
    unsigned int get_challenge:1;
101
126
    unsigned int change_force_chv:1;
102
127
    unsigned int private_dos:1;
103
128
  } extcap;
 
129
 
 
130
  /* Flags used to control the application.  */
104
131
  struct
105
132
  {
106
133
    unsigned int no_sync:1;   /* Do not sync CHV1 and CHV2 */
109
136
};
110
137
 
111
138
 
 
139
 
 
140
/***** Local prototypes  *****/
112
141
static unsigned long convert_sig_counter_value (const unsigned char *value,
113
142
                                                size_t valuelen);
114
 
static unsigned long get_sig_counter (APP app);
115
 
 
 
143
static unsigned long get_sig_counter (app_t app);
 
144
 
 
145
 
 
146
 
 
147
 
 
148
 
116
149
/* Deconstructor. */
117
150
static void
118
151
do_deinit (app_t app)
120
153
  if (app && app->app_local)
121
154
    {
122
155
      struct cache_s *c, *c2;
 
156
      int i;
123
157
 
124
158
      for (c = app->app_local->cache; c; c = c2)
125
159
        {
126
160
          c2 = c->next;
127
161
          xfree (c);
128
162
        }
 
163
 
 
164
      for (i=0; i < DIM (app->app_local->pk); i++)
 
165
        {
 
166
          xfree (app->app_local->pk[i].key);
 
167
          app->app_local->pk[i].read_done = 0;
 
168
        }
129
169
      xfree (app->app_local);
130
170
      app->app_local = NULL;
131
171
    }
133
173
 
134
174
 
135
175
/* Wrapper around iso7816_get_data which first tries to get the data
136
 
   from the cache. */
 
176
   from the cache.  With GET_IMMEDIATE passed as true, the cache is
 
177
   bypassed. */
137
178
static gpg_error_t
138
179
get_cached_data (app_t app, int tag, 
139
 
                 unsigned char **result, size_t *resultlen)
 
180
                 unsigned char **result, size_t *resultlen,
 
181
                 int get_immediate)
140
182
{
141
183
  gpg_error_t err;
142
184
  int i;
147
189
  *result = NULL;
148
190
  *resultlen = 0;
149
191
 
150
 
  for (c=app->app_local->cache; c; c = c->next)
151
 
    if (c->tag == tag)
152
 
      {
153
 
        if(c->length)
 
192
  if (!get_immediate)
 
193
    {
 
194
      for (c=app->app_local->cache; c; c = c->next)
 
195
        if (c->tag == tag)
154
196
          {
155
 
            p = xtrymalloc (c->length);
156
 
            if (!p)
157
 
              return gpg_error (gpg_err_code_from_errno (errno));
158
 
            memcpy (p, c->data, c->length);
159
 
            *result = p;
 
197
            if(c->length)
 
198
              {
 
199
                p = xtrymalloc (c->length);
 
200
                if (!p)
 
201
                  return gpg_error (gpg_err_code_from_errno (errno));
 
202
                memcpy (p, c->data, c->length);
 
203
                *result = p;
 
204
              }
 
205
            
 
206
            *resultlen = c->length;
 
207
            
 
208
            return 0;
160
209
          }
161
 
 
162
 
        *resultlen = c->length;
163
 
 
164
 
        return 0;
165
 
      }
166
 
 
 
210
    }
167
211
  
168
212
  err = iso7816_get_data (app->slot, tag, &p, &len);
169
213
  if (err)
172
216
  *resultlen = len;
173
217
 
174
218
  /* Check whether we should cache this object. */
 
219
  if (get_immediate)
 
220
    return 0;
 
221
 
175
222
  for (i=0; data_objects[i].tag; i++)
176
223
    if (data_objects[i].tag == tag)
177
224
      {
180
227
        break;
181
228
      }
182
229
 
183
 
  /* No, cache it. */
184
 
 
 
230
  /* Okay, cache it. */
185
231
  for (c=app->app_local->cache; c; c = c->next)
186
232
    assert (c->tag != tag);
187
233
  
267
313
   NULL if not found or a pointer which must be used to release the
268
314
   buffer holding value. */
269
315
static void *
270
 
get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes)
 
316
get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
 
317
            int *r_rc)
271
318
{
272
319
  int rc, i;
273
320
  unsigned char *buffer;
274
321
  size_t buflen;
275
322
  unsigned char *value;
276
323
  size_t valuelen;
 
324
  int dummyrc;
 
325
 
 
326
  if (!r_rc)
 
327
    r_rc = &dummyrc;
277
328
 
278
329
  *result = NULL;
279
330
  *nbytes = 0;
 
331
  *r_rc = 0;
280
332
  for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
281
333
    ;
282
334
 
283
335
  if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
284
336
    {
285
 
      if( iso7816_get_data (app->slot, tag, &buffer, &buflen))
286
 
        return NULL;
 
337
      rc = iso7816_get_data (app->slot, tag, &buffer, &buflen);
 
338
      if (rc)
 
339
        {
 
340
          *r_rc = rc;
 
341
          return NULL;
 
342
        }
287
343
      *result = buffer;
288
344
      *nbytes = buflen;
289
345
      return buffer;
294
350
  if (data_objects[i].tag && data_objects[i].get_from)
295
351
    {
296
352
      rc = get_cached_data (app, data_objects[i].get_from,
297
 
                            &buffer, &buflen);
 
353
                            &buffer, &buflen,
 
354
                            (data_objects[i].dont_cache 
 
355
                             || data_objects[i].get_immediate_in_v11));
298
356
      if (!rc)
299
357
        {
300
358
          const unsigned char *s;
301
359
 
302
 
          s = find_tlv (buffer, buflen, tag, &valuelen);
 
360
          s = find_tlv_unchecked (buffer, buflen, tag, &valuelen);
303
361
          if (!s)
304
362
            value = NULL; /* not found */
305
363
          else if (valuelen > buflen - (s - buffer))
315
373
 
316
374
  if (!value) /* Not in a constructed DO, try simple. */
317
375
    {
318
 
      rc = get_cached_data (app, tag, &buffer, &buflen);
 
376
      rc = get_cached_data (app, tag, &buffer, &buflen,
 
377
                            (data_objects[i].dont_cache 
 
378
                             || data_objects[i].get_immediate_in_v11));
319
379
      if (!rc)
320
380
        {
321
381
          value = buffer;
329
389
      *result = value;
330
390
      return buffer;
331
391
    }
 
392
  *r_rc = rc;
332
393
  return NULL;
333
394
}
334
395
 
372
433
                  
373
434
                  if (j==i || data_objects[i].tag != data_objects[j].get_from)
374
435
                    continue;
375
 
                  value = find_tlv (buffer, buflen,
376
 
                                    data_objects[j].tag, &valuelen);
 
436
                  value = find_tlv_unchecked (buffer, buflen,
 
437
                                              data_objects[j].tag, &valuelen);
377
438
                  if (!value)
378
439
                    ; /* not found */
379
440
                  else if (valuelen > buflen - (value - buffer))
421
482
   at any time and should be called after changing the login-data DO.
422
483
 
423
484
   Everything up to a LF is considered a mailbox or account name.  If
424
 
   the first LF is follewed by DC4 (0x14) control sequence are
 
485
   the first LF is followed by DC4 (0x14) control sequence are
425
486
   expected up to the next LF.  Control sequences are separated by FS
426
487
   (0x28) and consist of key=value pairs.  There is one key defined:
427
488
 
447
508
  app->app_local->flags.def_chv2 = 0;
448
509
 
449
510
  /* Read the DO.  */
450
 
  relptr = get_one_do (app, 0x005E, &buffer, &buflen);
 
511
  relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL);
451
512
  if (!relptr)
452
513
    return; /* Ooops. */
453
514
  for (; buflen; buflen--, buffer++)
486
547
}
487
548
 
488
549
/* Note, that FPR must be at least 20 bytes. */
489
 
static int 
 
550
static gpg_error_t 
490
551
store_fpr (int slot, int keynumber, u32 timestamp,
491
552
           const unsigned char *m, size_t mlen,
492
553
           const unsigned char *e, size_t elen, 
504
565
  n = 6 + 2 + mlen + 2 + elen;
505
566
  p = buffer = xtrymalloc (3 + n);
506
567
  if (!buffer)
507
 
    return gpg_error (gpg_err_code_from_errno (errno));
 
568
    return gpg_error_from_errno (errno);
508
569
  
509
570
  *p++ = 0x99;     /* ctb */
510
571
  *p++ = n >> 8;   /* 2 byte length header */
576
637
}
577
638
 
578
639
static void
 
640
send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
 
641
                          int number, const unsigned char *stamp)
 
642
{                      
 
643
  char numbuf1[50], numbuf2[50];
 
644
  unsigned long value;
 
645
 
 
646
  value = (stamp[0] << 24) | (stamp[1]<<16) | (stamp[2]<<8) | stamp[3];
 
647
  if (!value)
 
648
    return;
 
649
  sprintf (numbuf1, "%d", number);
 
650
  sprintf (numbuf2, "%lu", value);
 
651
  send_status_info (ctrl, keyword,
 
652
                    numbuf1, (size_t)strlen(numbuf1),
 
653
                    numbuf2, (size_t)strlen(numbuf2), NULL, 0);
 
654
}
 
655
 
 
656
static void
579
657
send_key_data (ctrl_t ctrl, const char *name, 
580
658
               const unsigned char *a, size_t alen)
581
659
{
593
671
 
594
672
/* Implement the GETATTR command.  This is similar to the LEARN
595
673
   command but returns just one value via the status interface. */
596
 
static int 
 
674
static gpg_error_t 
597
675
do_getattr (app_t app, ctrl_t ctrl, const char *name)
598
676
{
599
677
  static struct {
607
685
    { "DISP-SEX",     0x5F35 },
608
686
    { "PUBKEY-URL",   0x5F50 },
609
687
    { "KEY-FPR",      0x00C5, 3 },
 
688
    { "KEY-TIME",     0x00CD, 4 },
610
689
    { "CA-FPR",       0x00C6, 3 },
611
 
    { "CHV-STATUS",   0x00C4, 1 },
 
690
    { "CHV-STATUS",   0x00C4, 1 }, 
612
691
    { "SIG-COUNTER",  0x0093, 2 },
613
692
    { "SERIALNO",     0x004F, -1 },
614
693
    { "AID",          0x004F },
615
694
    { "EXTCAP",       0x0000, -2 },
 
695
    { "PRIVATE-DO-1", 0x0101 },
 
696
    { "PRIVATE-DO-2", 0x0102 },
 
697
    { "PRIVATE-DO-3", 0x0103 },
 
698
    { "PRIVATE-DO-4", 0x0104 },
 
699
    { "$AUTHKEYID",   0x0000, -3 },
 
700
    { "$DISPSERIALNO",0x0000, -4 },
616
701
    { NULL, 0 }
617
702
  };
618
 
  int idx, i;
 
703
  int idx, i, rc;
619
704
  void *relptr;
620
705
  unsigned char *value;
621
706
  size_t valuelen;
659
744
      send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
660
745
      return 0;
661
746
    }
 
747
  if (table[idx].special == -3)
 
748
    {
 
749
      char const tmp[] = "OPENPGP.3";
 
750
      send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
 
751
      return 0;
 
752
    }
 
753
  if (table[idx].special == -4)
 
754
    {
 
755
      char *serial;
 
756
      time_t stamp;
 
757
    
 
758
      if (!app_get_serial_and_stamp (app, &serial, &stamp))
 
759
        {
 
760
          if (strlen (serial) > 16+12)
 
761
            {
 
762
              send_status_info (ctrl, table[idx].name, serial+16, 12, NULL, 0);
 
763
              xfree (serial);
 
764
              return 0;
 
765
            }
 
766
          xfree (serial);
 
767
        }
 
768
      return gpg_error (GPG_ERR_INV_NAME); 
 
769
    }
662
770
 
663
 
  relptr = get_one_do (app, table[idx].tag, &value, &valuelen);
 
771
  relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
664
772
  if (relptr)
665
773
    {
666
774
      if (table[idx].special == 1)
686
794
            for (i=0; i < 3; i++)
687
795
              send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
688
796
        }
 
797
      else if (table[idx].special == 4)
 
798
        {
 
799
          if (valuelen >= 12)
 
800
            for (i=0; i < 3; i++)
 
801
              send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
 
802
        }
689
803
      else
690
804
        send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
691
805
 
692
806
      xfree (relptr);
693
807
    }
 
808
  return rc;
 
809
}
 
810
 
 
811
/* Retrieve the fingerprint from the card inserted in SLOT and write
 
812
   the according hex representation to FPR.  Caller must have provide
 
813
   a buffer at FPR of least 41 bytes.  Returns 0 on success or an
 
814
   error code. */
 
815
#if GNUPG_MAJOR_VERSION > 1
 
816
static gpg_error_t
 
817
retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
 
818
{
 
819
  gpg_error_t err = 0;
 
820
  void *relptr;
 
821
  unsigned char *value;
 
822
  size_t valuelen;
 
823
  int i;
 
824
 
 
825
  assert (keyno >=0 && keyno <= 2);
 
826
 
 
827
  relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
 
828
  if (relptr && valuelen >= 60)
 
829
    {
 
830
      for (i = 0; i < 20; i++)
 
831
        sprintf (fpr + (i * 2), "%02X", value[(keyno*20)+i]);
 
832
    }
 
833
  else
 
834
    err = gpg_error (GPG_ERR_NOT_FOUND);
 
835
  xfree (relptr);
 
836
  return err;
 
837
}
 
838
#endif /*GNUPG_MAJOR_VERSION > 1*/
 
839
 
 
840
 
 
841
/* Retrieve the public key material for the RSA key, whose fingerprint
 
842
   is FPR, from gpg output, which can be read through the stream FP.
 
843
   The RSA modulus will be stored at the address of M and MLEN, the
 
844
   public exponent at E and ELEN.  Returns zero on success, an error
 
845
   code on failure.  Caller must release the allocated buffers at M
 
846
   and E if the function returns success.  */
 
847
#if GNUPG_MAJOR_VERSION > 1
 
848
static gpg_error_t
 
849
retrieve_key_material (FILE *fp, const char *hexkeyid,
 
850
                       const unsigned char **m, size_t *mlen,
 
851
                       const unsigned char **e, size_t *elen)
 
852
{
 
853
  gcry_error_t err = 0;
 
854
  char *line = NULL;    /* read_line() buffer. */
 
855
  size_t line_size = 0; /* Helper for for read_line. */
 
856
  int found_key = 0;    /* Helper to find a matching key. */
 
857
  unsigned char *m_new = NULL;
 
858
  unsigned char *e_new = NULL;
 
859
  size_t m_new_n = 0;
 
860
  size_t e_new_n = 0;
 
861
 
 
862
  /* Loop over all records until we have found the subkey
 
863
     corresponsing to the fingerprint. Inm general the first record
 
864
     should be the pub record, but we don't rely on that.  Given that
 
865
     we only need to look at one key, it is sufficient to compare the
 
866
     keyid so that we don't need to look at "fpr" records. */
 
867
  for (;;)
 
868
    {
 
869
      char *p;
 
870
      char *fields[6];
 
871
      int nfields;
 
872
      size_t max_length;
 
873
      gcry_mpi_t mpi;
 
874
      int i;
 
875
 
 
876
      max_length = 4096;
 
877
      i = read_line (fp, &line, &line_size, &max_length);
 
878
      if (!i)
 
879
        break; /* EOF. */
 
880
      if (i < 0)
 
881
        {
 
882
          err = gpg_error_from_errno (errno);
 
883
          goto leave; /* Error. */
 
884
        }
 
885
      if (!max_length)
 
886
        {
 
887
          err = gpg_error (GPG_ERR_TRUNCATED);
 
888
          goto leave;  /* Line truncated - we better stop processing.  */
 
889
        }
 
890
 
 
891
      /* Parse the line into fields. */
 
892
      for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
 
893
        {
 
894
          fields[nfields] = p;
 
895
          p = strchr (p, ':');
 
896
          if (p)
 
897
            *(p++) = 0;
 
898
        }
 
899
      if (!nfields)
 
900
        continue; /* No fields at all - skip line.  */
 
901
 
 
902
      if (!found_key)
 
903
        {
 
904
          if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
 
905
               && nfields > 4 && !strcmp (fields[4], hexkeyid))
 
906
            found_key = 1;
 
907
          continue;
 
908
        }
 
909
      
 
910
      if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
 
911
        break; /* Next key - stop.  */
 
912
 
 
913
      if ( strcmp (fields[0], "pkd") )
 
914
        continue; /* Not a key data record.  */
 
915
      i = 0; /* Avoid erroneous compiler warning. */
 
916
      if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
 
917
           || (!i && m_new) || (i && e_new))
 
918
        {
 
919
          err = gpg_error (GPG_ERR_GENERAL);
 
920
          goto leave; /* Error: Invalid key data record or not an RSA key.  */
 
921
        }
 
922
      
 
923
      err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
 
924
      if (err)
 
925
        mpi = NULL;
 
926
      else if (!i)
 
927
        err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
 
928
      else
 
929
        err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
 
930
      gcry_mpi_release (mpi);
 
931
      if (err)
 
932
        goto leave;
 
933
    }
 
934
  
 
935
  if (m_new && e_new)
 
936
    {
 
937
      *m = m_new;
 
938
      *mlen = m_new_n;
 
939
      m_new = NULL;
 
940
      *e = e_new;
 
941
      *elen = e_new_n;
 
942
      e_new = NULL;
 
943
    }
 
944
  else
 
945
    err = gpg_error (GPG_ERR_GENERAL);
 
946
 
 
947
 leave:
 
948
  xfree (m_new);
 
949
  xfree (e_new);
 
950
  xfree (line);
 
951
  return err;
 
952
}
 
953
#endif /*GNUPG_MAJOR_VERSION > 1*/
 
954
 
 
955
 
 
956
/* Get the public key for KEYNO and store it as an S-expresion with
 
957
   the APP handle.  On error that field gets cleared.  If we already
 
958
   know about the public key we will just return.  Note that this does
 
959
   not mean a key is available; this is soley indicated by the
 
960
   presence of the app->app_local->pk[KEYNO-1].key field.
 
961
 
 
962
   Note that GnuPG 1.x does not need this and it would be too time
 
963
   consuming to send it just for the fun of it. However, given that we
 
964
   use the same code in gpg 1.4, we can't use the gcry S-expresion
 
965
   here but need to open encode it. */
 
966
#if GNUPG_MAJOR_VERSION > 1
 
967
static gpg_error_t
 
968
get_public_key (app_t app, int keyno)
 
969
{
 
970
  gpg_error_t err = 0;
 
971
  unsigned char *buffer;
 
972
  const unsigned char *keydata, *m, *e;
 
973
  size_t buflen, keydatalen, mlen, elen;
 
974
  unsigned char *mbuf = NULL;
 
975
  unsigned char *ebuf = NULL;
 
976
  char *keybuf = NULL;
 
977
  char *keybuf_p;
 
978
 
 
979
  if (keyno < 1 || keyno > 3)
 
980
    return gpg_error (GPG_ERR_INV_ID);
 
981
  keyno--;
 
982
 
 
983
  /* Already cached? */
 
984
  if (app->app_local->pk[keyno].read_done)
 
985
    return 0;
 
986
 
 
987
  xfree (app->app_local->pk[keyno].key);
 
988
  app->app_local->pk[keyno].key = NULL;
 
989
  app->app_local->pk[keyno].keylen = 0;
 
990
 
 
991
  m = e = NULL; /* (avoid cc warning) */
 
992
 
 
993
  if (app->card_version > 0x0100)
 
994
    {
 
995
      /* We may simply read the public key out of these cards.  */
 
996
      err = iso7816_read_public_key 
 
997
        (app->slot, (const unsigned char*)(keyno == 0? "\xB6" :
 
998
                                           keyno == 1? "\xB8" : "\xA4"),
 
999
         2,  
 
1000
         &buffer, &buflen);
 
1001
      if (err)
 
1002
        {
 
1003
          log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
 
1004
          goto leave;
 
1005
        }
 
1006
 
 
1007
      keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
 
1008
      if (!keydata)
 
1009
        {
 
1010
          err = gpg_error (GPG_ERR_CARD);
 
1011
          log_error (_("response does not contain the public key data\n"));
 
1012
          goto leave;
 
1013
        }
 
1014
 
 
1015
      m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
 
1016
      if (!m)
 
1017
        {
 
1018
          err = gpg_error (GPG_ERR_CARD);
 
1019
          log_error (_("response does not contain the RSA modulus\n"));
 
1020
          goto leave;
 
1021
        }
 
1022
      
 
1023
 
 
1024
      e = find_tlv (keydata, keydatalen, 0x0082, &elen);
 
1025
      if (!e)
 
1026
        {
 
1027
          err = gpg_error (GPG_ERR_CARD);
 
1028
          log_error (_("response does not contain the RSA public exponent\n"));
 
1029
          goto leave;
 
1030
        }
 
1031
 
 
1032
      /* Prepend numbers with a 0 if needed.  */
 
1033
      if (mlen && (*m & 0x80))
 
1034
        {
 
1035
          mbuf = xtrymalloc ( mlen + 1);
 
1036
          if (!mbuf)
 
1037
            {
 
1038
              err = gpg_error_from_errno (errno);
 
1039
              goto leave;
 
1040
            }
 
1041
          *mbuf = 0;
 
1042
          memcpy (mbuf+1, m, mlen);
 
1043
          mlen++;
 
1044
          m = mbuf;
 
1045
        }
 
1046
      if (elen && (*e & 0x80))
 
1047
        {
 
1048
          ebuf = xtrymalloc ( elen + 1);
 
1049
          if (!ebuf)
 
1050
            {
 
1051
              err = gpg_error_from_errno (errno);
 
1052
              goto leave;
 
1053
            }
 
1054
          *ebuf = 0;
 
1055
          memcpy (ebuf+1, e, elen);
 
1056
          elen++;
 
1057
          e = ebuf;
 
1058
        }
 
1059
 
 
1060
    }
 
1061
  else
 
1062
    {
 
1063
      /* Due to a design problem in v1.0 cards we can't get the public
 
1064
         key out of these cards without doing a verify on CHV3.
 
1065
         Clearly that is not an option and thus we try to locate the
 
1066
         key using an external helper.
 
1067
 
 
1068
         The helper we use here is gpg itself, which should know about
 
1069
         the key in any case.  */
 
1070
 
 
1071
      char fpr[41];
 
1072
      char *hexkeyid;
 
1073
      char *command = NULL;
 
1074
      FILE *fp;
 
1075
      int ret;
 
1076
 
 
1077
      buffer = NULL; /* We don't need buffer.  */
 
1078
 
 
1079
      err = retrieve_fpr_from_card (app, keyno, fpr);
 
1080
      if (err)
 
1081
        {
 
1082
          log_error ("error while retrieving fpr from card: %s\n",
 
1083
                     gpg_strerror (err));
 
1084
          goto leave;
 
1085
        }
 
1086
      hexkeyid = fpr + 24;
 
1087
 
 
1088
      ret = asprintf (&command,
 
1089
                      "gpg --list-keys --with-colons --with-key-data '%s'",
 
1090
                      fpr);
 
1091
      if (ret < 0)
 
1092
        {
 
1093
          err = gpg_error_from_errno (errno);
 
1094
          goto leave;
 
1095
        }
 
1096
 
 
1097
      fp = popen (command, "r");
 
1098
      free (command);
 
1099
      if (!fp)
 
1100
        {
 
1101
          err = gpg_error_from_errno (errno);
 
1102
          log_error ("running gpg failed: %s\n", gpg_strerror (err));
 
1103
          goto leave;
 
1104
        }
 
1105
 
 
1106
      err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
 
1107
      fclose (fp);
 
1108
      if (err)
 
1109
        {
 
1110
          log_error ("error while retrieving key material through pipe: %s\n",
 
1111
                     gpg_strerror (err));
 
1112
          goto leave;
 
1113
        }
 
1114
    }
 
1115
 
 
1116
  /* Allocate a buffer to construct the S-expression.  */
 
1117
  /* FIXME: We should provide a generalized S-expression creation
 
1118
     mechanism. */
 
1119
  keybuf = xtrymalloc (50 + 2*35 + mlen + elen + 1);
 
1120
  if (!keybuf)
 
1121
    {
 
1122
      err = gpg_error_from_errno (errno);
 
1123
      goto leave;
 
1124
    }
 
1125
  
 
1126
  sprintf (keybuf, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen);
 
1127
  keybuf_p = keybuf + strlen (keybuf);
 
1128
  memcpy (keybuf_p, m, mlen);
 
1129
  keybuf_p += mlen;
 
1130
  sprintf (keybuf_p, ")(1:e%u:", (unsigned int)elen);
 
1131
  keybuf_p += strlen (keybuf_p);
 
1132
  memcpy (keybuf_p, e, elen);
 
1133
  keybuf_p += elen;
 
1134
  strcpy (keybuf_p, ")))");
 
1135
  keybuf_p += strlen (keybuf_p);
 
1136
  
 
1137
  app->app_local->pk[keyno].key = (unsigned char*)keybuf;
 
1138
  app->app_local->pk[keyno].keylen = (keybuf_p - keybuf);
 
1139
 
 
1140
 leave:
 
1141
  /* Set a flag to indicate that we tried to read the key.  */
 
1142
  app->app_local->pk[keyno].read_done = 1;
 
1143
 
 
1144
  xfree (buffer);
 
1145
  xfree (mbuf);
 
1146
  xfree (ebuf);
694
1147
  return 0;
695
1148
}
696
 
 
697
 
 
698
 
static int
 
1149
#endif /* GNUPG_MAJOR_VERSION > 1 */
 
1150
 
 
1151
 
 
1152
 
 
1153
/* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
 
1154
   This is used by the LEARN command. */
 
1155
static gpg_error_t
 
1156
send_keypair_info (app_t app, ctrl_t ctrl, int keyno)
 
1157
{
 
1158
  gpg_error_t err = 0;
 
1159
  /* Note that GnuPG 1.x does not need this and it would be too time
 
1160
     consuming to send it just for the fun of it. */
 
1161
#if GNUPG_MAJOR_VERSION > 1
 
1162
  unsigned char grip[20];
 
1163
  char gripstr[41];
 
1164
  char idbuf[50];
 
1165
  int i;
 
1166
 
 
1167
  err = get_public_key (app, keyno);
 
1168
  if (err)
 
1169
    goto leave;
 
1170
  
 
1171
  assert (keyno >= 1 && keyno <= 3);
 
1172
  if (!app->app_local->pk[keyno-1].key)
 
1173
    goto leave; /* No such key - ignore. */
 
1174
 
 
1175
  err = keygrip_from_canon_sexp (app->app_local->pk[keyno-1].key,
 
1176
                                 app->app_local->pk[keyno-1].keylen,
 
1177
                                 grip);
 
1178
  if (err)
 
1179
    goto leave;
 
1180
  
 
1181
  for (i=0; i < 20; i++)
 
1182
    sprintf (gripstr+i*2, "%02X", grip[i]);
 
1183
 
 
1184
  sprintf (idbuf, "OPENPGP.%d", keyno);
 
1185
  send_status_info (ctrl, "KEYPAIRINFO", 
 
1186
                    gripstr, 40, 
 
1187
                    idbuf, strlen (idbuf), 
 
1188
                    NULL, (size_t)0);
 
1189
 
 
1190
 leave:
 
1191
#endif /* GNUPG_MAJOR_VERSION > 1 */
 
1192
 
 
1193
  return err; 
 
1194
}
 
1195
 
 
1196
 
 
1197
/* Handle the LEARN command for OpenPGP.  */
 
1198
static gpg_error_t
699
1199
do_learn_status (app_t app, ctrl_t ctrl)
700
1200
{
701
1201
  do_getattr (app, ctrl, "EXTCAP");
705
1205
  do_getattr (app, ctrl, "PUBKEY-URL");
706
1206
  do_getattr (app, ctrl, "LOGIN-DATA");
707
1207
  do_getattr (app, ctrl, "KEY-FPR");
 
1208
  if (app->card_version > 0x0100)
 
1209
    do_getattr (app, ctrl, "KEY-TIME");
708
1210
  do_getattr (app, ctrl, "CA-FPR");
709
1211
  do_getattr (app, ctrl, "CHV-STATUS");
710
1212
  do_getattr (app, ctrl, "SIG-COUNTER");
711
 
 
712
 
  return 0;
713
 
}
 
1213
  if (app->app_local->extcap.private_dos)
 
1214
    {
 
1215
      do_getattr (app, ctrl, "PRIVATE-DO-1");
 
1216
      do_getattr (app, ctrl, "PRIVATE-DO-2");
 
1217
      if (app->did_chv2)
 
1218
        do_getattr (app, ctrl, "PRIVATE-DO-3");
 
1219
      if (app->did_chv3)
 
1220
        do_getattr (app, ctrl, "PRIVATE-DO-4");
 
1221
    }
 
1222
  send_keypair_info (app, ctrl, 1);
 
1223
  send_keypair_info (app, ctrl, 2);
 
1224
  send_keypair_info (app, ctrl, 3);
 
1225
  return 0;
 
1226
}
 
1227
 
 
1228
 
 
1229
/* Handle the READKEY command for OpenPGP.  On success a canonical
 
1230
   encoded S-expression with the public key will get stored at PK and
 
1231
   its length (for assertions) at PKLEN; the caller must release that
 
1232
   buffer. On error PK and PKLEN are not changed and an error code is
 
1233
   returned.  */
 
1234
static gpg_error_t
 
1235
do_readkey (app_t app, const char *keyid, unsigned char **pk, size_t *pklen)
 
1236
{
 
1237
#if GNUPG_MAJOR_VERSION > 1
 
1238
  gpg_error_t err;
 
1239
  int keyno;
 
1240
  unsigned char *buf;
 
1241
 
 
1242
  if (!strcmp (keyid, "OPENPGP.1"))
 
1243
    keyno = 1;
 
1244
  else if (!strcmp (keyid, "OPENPGP.2"))
 
1245
    keyno = 2;
 
1246
  else if (!strcmp (keyid, "OPENPGP.3"))
 
1247
    keyno = 3;
 
1248
  else
 
1249
    return gpg_error (GPG_ERR_INV_ID);
 
1250
 
 
1251
  err = get_public_key (app, keyno);
 
1252
  if (err)
 
1253
    return err;
 
1254
 
 
1255
  buf = app->app_local->pk[keyno-1].key;
 
1256
  if (!buf)
 
1257
    return gpg_error (GPG_ERR_NO_PUBKEY);
 
1258
  *pklen = app->app_local->pk[keyno-1].keylen;;
 
1259
  *pk = xtrymalloc (*pklen);
 
1260
  if (!*pk)
 
1261
    {
 
1262
      err = gpg_error_from_errno (errno);
 
1263
      *pklen = 0;
 
1264
      return err;
 
1265
    }
 
1266
  memcpy (*pk, buf, *pklen);
 
1267
  return 0;
 
1268
#else
 
1269
  return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
 
1270
#endif
 
1271
}
 
1272
 
714
1273
 
715
1274
 
716
1275
/* Verify CHV2 if required.  Depending on the configuration of the
717
1276
   card CHV1 will also be verified. */
718
 
static int
 
1277
static gpg_error_t
719
1278
verify_chv2 (app_t app,
720
 
             int (*pincb)(void*, const char *, char **),
 
1279
             gpg_error_t (*pincb)(void*, const char *, char **),
721
1280
             void *pincb_arg)
722
1281
{
723
1282
  int rc = 0;
771
1330
}
772
1331
 
773
1332
/* Verify CHV3 if required. */
774
 
static int
 
1333
static gpg_error_t
775
1334
verify_chv3 (app_t app,
776
 
             int (*pincb)(void*, const char *, char **),
 
1335
             gpg_error_t (*pincb)(void*, const char *, char **),
777
1336
             void *pincb_arg)
778
1337
{
779
1338
  int rc = 0;
792
1351
      void *relptr;
793
1352
      unsigned char *value;
794
1353
      size_t valuelen;
795
 
      int reread_chv_status;
796
 
      
797
1354
 
798
 
      relptr = get_one_do (app, 0x00C4, &value, &valuelen);
 
1355
      relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
799
1356
      if (!relptr || valuelen < 7)
800
1357
        {
801
1358
          log_error (_("error retrieving CHV status from card\n"));
809
1366
          return gpg_error (GPG_ERR_BAD_PIN);
810
1367
        }
811
1368
 
812
 
      reread_chv_status = (value[6] < 3);
813
 
 
814
1369
      log_info(_("%d Admin PIN attempts remaining before card"
815
1370
                 " is permanently locked\n"), value[6]);
816
1371
      xfree (relptr);
817
1372
 
818
 
      rc = pincb (pincb_arg, _("Admin PIN"), &pinvalue); 
 
1373
      /* TRANSLATORS: Do not translate the "|A|" prefix but
 
1374
         keep it at the start of the string.  We need this elsewhere
 
1375
         to get some infos on the string. */
 
1376
      rc = pincb (pincb_arg, _("|A|Admin PIN"), &pinvalue); 
819
1377
      if (rc)
820
1378
        {
821
1379
          log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
839
1397
          return rc;
840
1398
        }
841
1399
      app->did_chv3 = 1;
842
 
      /* If the PIN has been entered wrongly before, we need to flush
843
 
         the cached value so that the next read correctly reflects the
844
 
         resetted retry counter.  Note that version 1.1 of the specs
845
 
         allow direct reading of that DO, so that we could actually
846
 
         flush it in all cases. */
847
 
      if (reread_chv_status)
848
 
        flush_cache_item (app, 0x00C4);
849
1400
    }
850
1401
  return rc;
851
1402
}
853
1404
 
854
1405
/* Handle the SETATTR operation. All arguments are already basically
855
1406
   checked. */
856
 
static int 
 
1407
static gpg_error_t 
857
1408
do_setattr (app_t app, const char *name,
858
 
            int (*pincb)(void*, const char *, char **),
 
1409
            gpg_error_t (*pincb)(void*, const char *, char **),
859
1410
            void *pincb_arg,
860
1411
            const unsigned char *value, size_t valuelen)
861
1412
{
864
1415
  static struct {
865
1416
    const char *name;
866
1417
    int tag;
 
1418
    int need_chv;
867
1419
    int special;
868
1420
  } table[] = {
869
 
    { "DISP-NAME",    0x005B },
870
 
    { "LOGIN-DATA",   0x005E, 2 },
871
 
    { "DISP-LANG",    0x5F2D },
872
 
    { "DISP-SEX",     0x5F35 },
873
 
    { "PUBKEY-URL",   0x5F50 },
874
 
    { "CHV-STATUS-1", 0x00C4, 1 },
875
 
    { "CA-FPR-1",     0x00CA },
876
 
    { "CA-FPR-2",     0x00CB },
877
 
    { "CA-FPR-3",     0x00CC },
 
1421
    { "DISP-NAME",    0x005B, 3 },
 
1422
    { "LOGIN-DATA",   0x005E, 3, 2 },
 
1423
    { "DISP-LANG",    0x5F2D, 3 },
 
1424
    { "DISP-SEX",     0x5F35, 3 },
 
1425
    { "PUBKEY-URL",   0x5F50, 3 },
 
1426
    { "CHV-STATUS-1", 0x00C4, 3, 1 },
 
1427
    { "CA-FPR-1",     0x00CA, 3 },
 
1428
    { "CA-FPR-2",     0x00CB, 3 },
 
1429
    { "CA-FPR-3",     0x00CC, 3 },
 
1430
    { "PRIVATE-DO-1", 0x0101, 2 },
 
1431
    { "PRIVATE-DO-2", 0x0102, 3 },
 
1432
    { "PRIVATE-DO-3", 0x0103, 2 },
 
1433
    { "PRIVATE-DO-4", 0x0104, 3 },
878
1434
    { NULL, 0 }
879
1435
  };
880
1436
 
884
1440
  if (!table[idx].name)
885
1441
    return gpg_error (GPG_ERR_INV_NAME); 
886
1442
 
887
 
  rc = verify_chv3 (app, pincb, pincb_arg);
 
1443
  switch (table[idx].need_chv)
 
1444
    {
 
1445
    case 2:
 
1446
      rc = verify_chv2 (app, pincb, pincb_arg);
 
1447
      break;
 
1448
    case 3:
 
1449
      rc = verify_chv3 (app, pincb, pincb_arg);
 
1450
      break;
 
1451
    default:
 
1452
      rc = 0;
 
1453
    }
888
1454
  if (rc)
889
1455
    return rc;
890
1456
 
906
1472
 
907
1473
 
908
1474
/* Handle the PASSWD command. */
909
 
static int 
 
1475
static gpg_error_t 
910
1476
do_change_pin (app_t app, ctrl_t ctrl,  const char *chvnostr, int reset_mode,
911
 
               int (*pincb)(void*, const char *, char **),
 
1477
               gpg_error_t (*pincb)(void*, const char *, char **),
912
1478
               void *pincb_arg)
913
1479
{
914
1480
  int rc = 0;
953
1519
  else
954
1520
    app->did_chv1 = app->did_chv2 = 0;
955
1521
 
956
 
  rc = pincb (pincb_arg, chvno == 3? "New Admin PIN" : "New PIN", &pinvalue); 
 
1522
  /* TRANSLATORS: Do not translate the "|*|" prefixes but
 
1523
     keep it at the start of the string.  We need this elsewhere
 
1524
     to get some infos on the string. */
 
1525
  rc = pincb (pincb_arg, chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"), 
 
1526
              &pinvalue); 
957
1527
  if (rc)
958
1528
    {
959
 
      log_error ("error getting new PIN: %s\n", gpg_strerror (rc));
 
1529
      log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
960
1530
      goto leave;
961
1531
    }
962
1532
 
991
1561
}
992
1562
 
993
1563
 
 
1564
/* Check whether a key already exists.  KEYIDX is the index of the key
 
1565
   (0..2).  If FORCE is TRUE a diagnositic will be printed but no
 
1566
   error returned if the key already exists. */
 
1567
static gpg_error_t
 
1568
does_key_exist (app_t app, int keyidx, int force)
 
1569
{
 
1570
  const unsigned char *fpr;
 
1571
  unsigned char *buffer;
 
1572
  size_t buflen, n;
 
1573
  int i;
 
1574
 
 
1575
  assert (keyidx >=0 && keyidx <= 2);
 
1576
 
 
1577
  if (iso7816_get_data (app->slot, 0x006E, &buffer, &buflen))
 
1578
    {
 
1579
      log_error (_("error reading application data\n"));
 
1580
      return gpg_error (GPG_ERR_GENERAL);
 
1581
    }
 
1582
  fpr = find_tlv (buffer, buflen, 0x00C5, &n);
 
1583
  if (!fpr || n < 60)
 
1584
    {
 
1585
      log_error (_("error reading fingerprint DO\n"));
 
1586
      xfree (buffer);
 
1587
      return gpg_error (GPG_ERR_GENERAL);
 
1588
    }
 
1589
  fpr += 20*keyidx;
 
1590
  for (i=0; i < 20 && !fpr[i]; i++)
 
1591
    ;
 
1592
  xfree (buffer);
 
1593
  if (i!=20 && !force)
 
1594
    {
 
1595
      log_error (_("key already exists\n"));
 
1596
      return gpg_error (GPG_ERR_EEXIST);
 
1597
    }
 
1598
  else if (i!=20)
 
1599
    log_info (_("existing key will be replaced\n"));
 
1600
  else
 
1601
    log_info (_("generating new key\n"));
 
1602
  return 0;
 
1603
}
 
1604
 
 
1605
 
 
1606
 
 
1607
/* Handle the WRITEKEY command for OpenPGP.  This function expects a
 
1608
   canonical encoded S-expression with the secret key in KEYDATA and
 
1609
   its length (for assertions) in KEYDATALEN.  KEYID needs to be the
 
1610
   usual keyid which for OpenPGP is the string "OPENPGP.n" with
 
1611
   n=1,2,3.  Bit 0 of FLAGS indicates whether an existing key shall
 
1612
   get overwritten.  PINCB and PINCB_ARG are the usual arguments for
 
1613
   the pinentry callback.  */
 
1614
static gpg_error_t
 
1615
do_writekey (app_t app, ctrl_t ctrl,
 
1616
             const char *keyid, unsigned int flags,
 
1617
             gpg_error_t (*pincb)(void*, const char *, char **),
 
1618
             void *pincb_arg,
 
1619
             const unsigned char *keydata, size_t keydatalen)
 
1620
{
 
1621
  gpg_error_t err;
 
1622
  int force = (flags & 1);
 
1623
  int keyno;
 
1624
  const unsigned char *buf, *tok;
 
1625
  size_t buflen, toklen;
 
1626
  int depth, last_depth1, last_depth2;
 
1627
  const unsigned char *rsa_n = NULL;
 
1628
  const unsigned char *rsa_e = NULL;
 
1629
  const unsigned char *rsa_p = NULL;
 
1630
  const unsigned char *rsa_q = NULL;
 
1631
  size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
 
1632
  unsigned int nbits;
 
1633
  unsigned char *template = NULL;
 
1634
  unsigned char *tp;
 
1635
  size_t template_len;
 
1636
  unsigned char fprbuf[20];
 
1637
  u32 created_at = 0;
 
1638
 
 
1639
  if (!strcmp (keyid, "OPENPGP.1"))
 
1640
    keyno = 0;
 
1641
  else if (!strcmp (keyid, "OPENPGP.2"))
 
1642
    keyno = 1;
 
1643
  else if (!strcmp (keyid, "OPENPGP.3"))
 
1644
    keyno = 2;
 
1645
  else
 
1646
    return gpg_error (GPG_ERR_INV_ID);
 
1647
  
 
1648
  err = does_key_exist (app, keyno, force);
 
1649
  if (err)
 
1650
    return err;
 
1651
 
 
1652
 
 
1653
  /* 
 
1654
     Parse the S-expression
 
1655
   */
 
1656
  buf = keydata;
 
1657
  buflen = keydatalen;
 
1658
  depth = 0;
 
1659
  if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
 
1660
    goto leave;
 
1661
  if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
 
1662
    goto leave;
 
1663
  if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
 
1664
    {
 
1665
      if (!tok)
 
1666
        ;
 
1667
      else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
 
1668
        log_info ("protected-private-key passed to writekey\n");
 
1669
      else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
 
1670
        log_info ("shadowed-private-key passed to writekey\n");
 
1671
      err = gpg_error (GPG_ERR_BAD_SECKEY);
 
1672
      goto leave;
 
1673
    }
 
1674
  if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
 
1675
    goto leave;
 
1676
  if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
 
1677
    goto leave;
 
1678
  if (!tok || toklen != 3 || memcmp ("rsa", tok, toklen))
 
1679
    {
 
1680
      err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
 
1681
      goto leave;
 
1682
    }
 
1683
  last_depth1 = depth;
 
1684
  while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
 
1685
         && depth && depth >= last_depth1)
 
1686
    {
 
1687
      if (tok)
 
1688
        {
 
1689
          err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
 
1690
          goto leave;
 
1691
        }
 
1692
      if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
 
1693
        goto leave;
 
1694
      if (tok && toklen == 1)
 
1695
        {
 
1696
          const unsigned char **mpi;
 
1697
          size_t *mpi_len;
 
1698
 
 
1699
          switch (*tok)
 
1700
            {
 
1701
            case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break; 
 
1702
            case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break; 
 
1703
            case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break; 
 
1704
            case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break; 
 
1705
            default: mpi = NULL;  mpi_len = NULL; break;
 
1706
            }
 
1707
          if (mpi && *mpi)
 
1708
            {
 
1709
              err = gpg_error (GPG_ERR_DUP_VALUE);
 
1710
              goto leave;
 
1711
            }
 
1712
          if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
 
1713
            goto leave;
 
1714
          if (tok && mpi)
 
1715
            {
 
1716
              /* Strip off leading zero bytes and save. */
 
1717
              for (;toklen && !*tok; toklen--, tok++)
 
1718
                ;
 
1719
              *mpi = tok;
 
1720
              *mpi_len = toklen;
 
1721
            }
 
1722
        }
 
1723
      /* Skip until end of list. */
 
1724
      last_depth2 = depth;
 
1725
      while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
 
1726
             && depth && depth >= last_depth2)
 
1727
        ;
 
1728
      if (err)
 
1729
        goto leave;
 
1730
    }
 
1731
  /* Parse other attributes. */
 
1732
  last_depth1 = depth;
 
1733
  while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
 
1734
         && depth && depth >= last_depth1)
 
1735
    {
 
1736
      if (tok)
 
1737
        {
 
1738
          err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
 
1739
          goto leave;
 
1740
        }
 
1741
      if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
 
1742
        goto leave;
 
1743
      if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
 
1744
        {
 
1745
          if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
 
1746
            goto leave;
 
1747
          if (tok)
 
1748
            {
 
1749
              for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
 
1750
                   tok++, toklen--)
 
1751
                created_at = created_at*10 + (*tok - '0');
 
1752
            }
 
1753
        }
 
1754
      /* Skip until end of list. */
 
1755
      last_depth2 = depth;
 
1756
      while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
 
1757
             && depth && depth >= last_depth2)
 
1758
        ;
 
1759
      if (err)
 
1760
        goto leave;
 
1761
    }
 
1762
 
 
1763
 
 
1764
  /* Check that we have all parameters and that they match the card
 
1765
     description. */
 
1766
  if (!created_at)
 
1767
    {
 
1768
      log_error (_("creation timestamp missing\n"));
 
1769
      err = gpg_error (GPG_ERR_INV_VALUE);
 
1770
      goto leave;
 
1771
    }
 
1772
  nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
 
1773
  if (nbits != 1024)
 
1774
    {
 
1775
      log_error (_("RSA modulus missing or not of size %d bits\n"), 1024);
 
1776
      err = gpg_error (GPG_ERR_BAD_SECKEY);
 
1777
      goto leave;
 
1778
    }
 
1779
  nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
 
1780
  if (nbits < 2 || nbits > 32)
 
1781
    {
 
1782
      log_error (_("RSA public exponent missing or larger than %d bits\n"),
 
1783
                 32);
 
1784
      err = gpg_error (GPG_ERR_BAD_SECKEY);
 
1785
      goto leave;
 
1786
    }
 
1787
  nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
 
1788
  if (nbits != 512)
 
1789
    {
 
1790
      log_error (_("RSA prime %s missing or not of size %d bits\n"), "P", 512);
 
1791
      err = gpg_error (GPG_ERR_BAD_SECKEY);
 
1792
      goto leave;
 
1793
    }
 
1794
  nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
 
1795
  if (nbits != 512)
 
1796
    {
 
1797
      log_error (_("RSA prime %s missing or not of size %d bits\n"), "Q", 512);
 
1798
      err = gpg_error (GPG_ERR_BAD_SECKEY);
 
1799
      goto leave;
 
1800
    }
 
1801
  
 
1802
 
 
1803
  /* Build the private key template as described in section 4.3.3.6 of
 
1804
     the OpenPGP card specs:
 
1805
         0xC0   <length> public exponent
 
1806
         0xC1   <length> prime p 
 
1807
         0xC2   <length> prime q 
 
1808
  */
 
1809
  assert (rsa_e_len <= 4);
 
1810
  template_len = (1 + 1 + 4
 
1811
                  + 1 + 1 + rsa_p_len
 
1812
                  + 1 + 1 + rsa_q_len);
 
1813
  template = tp = xtrymalloc_secure (template_len);
 
1814
  if (!template)
 
1815
    {
 
1816
      err = gpg_error_from_errno (errno);
 
1817
      goto leave;
 
1818
    }
 
1819
  *tp++ = 0xC0;
 
1820
  *tp++ = 4;
 
1821
  memcpy (tp, rsa_e, rsa_e_len);
 
1822
  if (rsa_e_len < 4)
 
1823
    {
 
1824
      /* Right justify E. */
 
1825
      memmove (tp+4-rsa_e_len, tp, 4-rsa_e_len);
 
1826
      memset (tp, 0, 4-rsa_e_len);
 
1827
    }                 
 
1828
  tp += 4;
 
1829
 
 
1830
  *tp++ = 0xC1;
 
1831
  *tp++ = rsa_p_len;
 
1832
  memcpy (tp, rsa_p, rsa_p_len);
 
1833
  tp += rsa_p_len;
 
1834
 
 
1835
  *tp++ = 0xC2;
 
1836
  *tp++ = rsa_q_len;
 
1837
  memcpy (tp, rsa_q, rsa_q_len);
 
1838
  tp += rsa_q_len;
 
1839
 
 
1840
  assert (tp - template == template_len);
 
1841
 
 
1842
 
 
1843
  /* Obviously we need to remove the cached public key.  */
 
1844
  xfree (app->app_local->pk[keyno].key);
 
1845
  app->app_local->pk[keyno].key = NULL;
 
1846
  app->app_local->pk[keyno].keylen = 0;
 
1847
  app->app_local->pk[keyno].read_done = 0;
 
1848
 
 
1849
  /* Prepare for storing the key.  */
 
1850
  err = verify_chv3 (app, pincb, pincb_arg);
 
1851
  if (err)
 
1852
    goto leave;
 
1853
 
 
1854
  /* Store the key. */
 
1855
  err = iso7816_put_data (app->slot,
 
1856
                         (app->card_version > 0x0007? 0xE0 : 0xE9) + keyno,
 
1857
                         template, template_len);
 
1858
  if (err)
 
1859
    {
 
1860
      log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
 
1861
      goto leave;
 
1862
    }
 
1863
 
 
1864
  err = store_fpr (app->slot, keyno, created_at,
 
1865
                  rsa_n, rsa_n_len, rsa_e, rsa_e_len,
 
1866
                  fprbuf, app->card_version);
 
1867
  if (err)
 
1868
    goto leave;
 
1869
 
 
1870
 
 
1871
 leave:
 
1872
  xfree (template);
 
1873
  return err;
 
1874
}
 
1875
 
994
1876
 
995
1877
/* Handle the GENKEY command. */
996
 
static int 
 
1878
static gpg_error_t 
997
1879
do_genkey (app_t app, ctrl_t ctrl,  const char *keynostr, unsigned int flags,
998
 
          int (*pincb)(void*, const char *, char **),
 
1880
          gpg_error_t (*pincb)(void*, const char *, char **),
999
1881
          void *pincb_arg)
1000
1882
{
1001
1883
  int rc;
1002
 
  int i;
1003
1884
  char numbuf[30];
1004
1885
  unsigned char fprbuf[20];
1005
 
  const unsigned char *fpr;
1006
1886
  const unsigned char *keydata, *m, *e;
1007
 
  unsigned char *buffer;
1008
 
  size_t buflen, keydatalen, n, mlen, elen;
 
1887
  unsigned char *buffer = NULL;
 
1888
  size_t buflen, keydatalen, mlen, elen;
1009
1889
  time_t created_at;
1010
1890
  int keyno = atoi (keynostr);
1011
1891
  int force = (flags & 1);
1019
1899
     generation.  This _might_ help a card to gather more entropy. */
1020
1900
  flush_cache (app);
1021
1901
 
1022
 
  rc = iso7816_get_data (app->slot, 0x006E, &buffer, &buflen);
 
1902
  /* Obviously we need to remove the cached public key.  */
 
1903
  xfree (app->app_local->pk[keyno].key);
 
1904
  app->app_local->pk[keyno].key = NULL;
 
1905
  app->app_local->pk[keyno].keylen = 0;
 
1906
  app->app_local->pk[keyno].read_done = 0;
 
1907
 
 
1908
  /* Check whether a key already exists.  */
 
1909
  rc = does_key_exist (app, keyno, force);
1023
1910
  if (rc)
1024
 
    {
1025
 
      log_error ("error reading application data\n");
1026
 
      return gpg_error (GPG_ERR_GENERAL);
1027
 
    }
1028
 
  fpr = find_tlv (buffer, buflen, 0x00C5, &n);
1029
 
  if (!fpr || n != 60)
1030
 
    {
1031
 
      rc = gpg_error (GPG_ERR_GENERAL);
1032
 
      log_error ("error reading fingerprint DO\n");
1033
 
      goto leave;
1034
 
    }
1035
 
  fpr += 20*keyno;
1036
 
  for (i=0; i < 20 && !fpr[i]; i++)
1037
 
    ;
1038
 
  if (i!=20 && !force)
1039
 
    {
1040
 
      rc = gpg_error (GPG_ERR_EEXIST);
1041
 
      log_error ("key already exists\n");
1042
 
      goto leave;
1043
 
    }
1044
 
  else if (i!=20)
1045
 
    log_info ("existing key will be replaced\n");
1046
 
  else
1047
 
    log_info ("generating new key\n");
1048
 
 
1049
 
 
 
1911
    return rc;
 
1912
 
 
1913
  /* Prepare for key generation by verifying the ADmin PIN.  */
1050
1914
  rc = verify_chv3 (app, pincb, pincb_arg);
1051
1915
  if (rc)
1052
1916
    goto leave;
1053
 
 
1054
 
  xfree (buffer); buffer = NULL;
1055
 
 
 
1917
   
1056
1918
#if 1
1057
 
  log_info ("please wait while key is being generated ...\n");
 
1919
  log_info (_("please wait while key is being generated ...\n"));
1058
1920
  start_at = time (NULL);
1059
1921
  rc = iso7816_generate_keypair 
1060
1922
#else
1061
1923
#warning key generation temporary replaced by reading an existing key.
1062
1924
  rc = iso7816_read_public_key
1063
1925
#endif
1064
 
                              (app->slot, 
1065
 
                                 keyno == 0? "\xB6" :
1066
 
                                 keyno == 1? "\xB8" : "\xA4",
1067
 
                                 2,
1068
 
                                 &buffer, &buflen);
 
1926
    (app->slot, (const unsigned char*)(keyno == 0? "\xB6" :
 
1927
                                       keyno == 1? "\xB8" : "\xA4"),
 
1928
     2,
 
1929
     &buffer, &buflen);
1069
1930
  if (rc)
1070
1931
    {
1071
1932
      rc = gpg_error (GPG_ERR_CARD);
1072
 
      log_error ("generating key failed\n");
 
1933
      log_error (_("generating key failed\n"));
1073
1934
      goto leave;
1074
1935
    }
1075
 
  log_info ("key generation completed (%d seconds)\n",
 
1936
  log_info (_("key generation completed (%d seconds)\n"),
1076
1937
            (int)(time (NULL) - start_at));
1077
1938
  keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1078
1939
  if (!keydata)
1079
1940
    {
1080
1941
      rc = gpg_error (GPG_ERR_CARD);
1081
 
      log_error ("response does not contain the public key data\n");
 
1942
      log_error (_("response does not contain the public key data\n"));
1082
1943
      goto leave;
1083
1944
    }
1084
1945
 
1086
1947
  if (!m)
1087
1948
    {
1088
1949
      rc = gpg_error (GPG_ERR_CARD);
1089
 
      log_error ("response does not contain the RSA modulus\n");
 
1950
      log_error (_("response does not contain the RSA modulus\n"));
1090
1951
      goto leave;
1091
1952
    }
1092
1953
/*    log_printhex ("RSA n:", m, mlen); */
1096
1957
  if (!e)
1097
1958
    {
1098
1959
      rc = gpg_error (GPG_ERR_CARD);
1099
 
      log_error ("response does not contain the RSA public exponent\n");
 
1960
      log_error (_("response does not contain the RSA public exponent\n"));
1100
1961
      goto leave;
1101
1962
    }
1102
1963
/*    log_printhex ("RSA e:", e, elen); */
1129
1990
    ul = (value[0] << 16) | (value[1] << 8) | value[2];
1130
1991
  else
1131
1992
    {
1132
 
      log_error ("invalid structure of OpenPGP card (DO 0x93)\n");
 
1993
      log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
1133
1994
      ul = 0;
1134
1995
    }
1135
1996
  return ul;
1143
2004
  size_t valuelen;
1144
2005
  unsigned long ul;
1145
2006
 
1146
 
  relptr = get_one_do (app, 0x0093, &value, &valuelen);
 
2007
  relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
1147
2008
  if (!relptr)
1148
2009
    return 0;
1149
2010
  ul = convert_sig_counter_value (value, valuelen);
1151
2012
  return ul;
1152
2013
}
1153
2014
 
1154
 
static int
 
2015
static gpg_error_t
1155
2016
compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
1156
2017
{
1157
2018
  const unsigned char *fpr;
1161
2022
  
1162
2023
  assert (keyno >= 1 && keyno <= 3);
1163
2024
 
1164
 
  rc = get_cached_data (app, 0x006E, &buffer, &buflen);
 
2025
  rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0);
1165
2026
  if (rc)
1166
2027
    {
1167
 
      log_error ("error reading application data\n");
 
2028
      log_error (_("error reading application data\n"));
1168
2029
      return gpg_error (GPG_ERR_GENERAL);
1169
2030
    }
1170
2031
  fpr = find_tlv (buffer, buflen, 0x00C5, &n);
1171
2032
  if (!fpr || n != 60)
1172
2033
    {
1173
2034
      xfree (buffer);
1174
 
      log_error ("error reading fingerprint DO\n");
 
2035
      log_error (_("error reading fingerprint DO\n"));
1175
2036
      return gpg_error (GPG_ERR_GENERAL);
1176
2037
    }
1177
2038
  fpr += (keyno-1)*20;
1191
2052
     the key on the card has been replaced but the shadow information
1192
2053
     known to gpg was not updated.  If there is no fingerprint we
1193
2054
     assume that this is okay. */
1194
 
static int
 
2055
static gpg_error_t
1195
2056
check_against_given_fingerprint (app_t app, const char *fpr, int keyno)
1196
2057
{
1197
2058
  unsigned char tmp[20];
1222
2083
   GPG_ERR_WRONG_CARD to indicate that the card currently present does
1223
2084
   not match the one required for the requested action (e.g. the
1224
2085
   serial number does not match). */
1225
 
static int 
 
2086
static gpg_error_t 
1226
2087
do_sign (app_t app, const char *keyidstr, int hashalgo,
1227
 
         int (*pincb)(void*, const char *, char **),
 
2088
         gpg_error_t (*pincb)(void*, const char *, char **),
1228
2089
         void *pincb_arg,
1229
2090
         const void *indata, size_t indatalen,
1230
2091
         unsigned char **outdata, size_t *outdatalen )
1245
2106
 
1246
2107
  if (!keyidstr || !*keyidstr)
1247
2108
    return gpg_error (GPG_ERR_INV_VALUE);
1248
 
  if (indatalen != 20)
 
2109
  if (indatalen == 20)
 
2110
    ;
 
2111
  else if (indatalen == (15 + 20) && hashalgo == GCRY_MD_SHA1
 
2112
           && !memcmp (indata, sha1_prefix, 15))
 
2113
    ;
 
2114
  else if (indatalen == (15 + 20) && hashalgo == GCRY_MD_RMD160
 
2115
           && !memcmp (indata, rmd160_prefix, 15))
 
2116
    ;
 
2117
  else
1249
2118
    return gpg_error (GPG_ERR_INV_VALUE);
1250
2119
 
1251
2120
  /* Check whether an OpenPGP card of any version has been requested. */
1290
2159
  memcpy (data+15, indata, indatalen);
1291
2160
 
1292
2161
  sigcount = get_sig_counter (app);
1293
 
  log_info ("signatures created so far: %lu\n", sigcount);
 
2162
  log_info (_("signatures created so far: %lu\n"), sigcount);
1294
2163
 
1295
2164
  if (!app->did_chv1 || app->force_chv1 ) 
1296
2165
    {
1298
2167
 
1299
2168
      {
1300
2169
        char *prompt;
1301
 
#define PROMPTSTRING  _("PIN [sigs done: %lu]")
 
2170
#define PROMPTSTRING  _("||Please enter the PIN%%0A[sigs done: %lu]")
1302
2171
 
1303
2172
        prompt = malloc (strlen (PROMPTSTRING) + 50);
1304
2173
        if (!prompt)
1356
2225
/* Compute a digital signature using the INTERNAL AUTHENTICATE command
1357
2226
   on INDATA which is expected to be the raw message digest. For this
1358
2227
   application the KEYIDSTR consists of the serialnumber and the
1359
 
   fingerprint delimited by a slash.
 
2228
   fingerprint delimited by a slash.  Optionally the id OPENPGP.3 may
 
2229
   be given.
1360
2230
 
1361
 
   Note that this fucntion may return the error code
 
2231
   Note that this function may return the error code
1362
2232
   GPG_ERR_WRONG_CARD to indicate that the card currently present does
1363
2233
   not match the one required for the requested action (e.g. the
1364
2234
   serial number does not match). */
1365
 
static int 
 
2235
static gpg_error_t 
1366
2236
do_auth (app_t app, const char *keyidstr,
1367
 
         int (*pincb)(void*, const char *, char **),
 
2237
         gpg_error_t (*pincb)(void*, const char *, char **),
1368
2238
         void *pincb_arg,
1369
2239
         const void *indata, size_t indatalen,
1370
2240
         unsigned char **outdata, size_t *outdatalen )
1381
2251
    return gpg_error (GPG_ERR_INV_VALUE);
1382
2252
 
1383
2253
  /* Check whether an OpenPGP card of any version has been requested. */
1384
 
  if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
1385
 
    return gpg_error (GPG_ERR_INV_ID);
1386
 
  
1387
 
  for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
 
2254
  if (!strcmp (keyidstr, "OPENPGP.3"))
1388
2255
    ;
1389
 
  if (n != 32)
 
2256
  else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
1390
2257
    return gpg_error (GPG_ERR_INV_ID);
1391
 
  else if (!*s)
1392
 
    ; /* no fingerprint given: we allow this for now. */
1393
 
  else if (*s == '/')
1394
 
    fpr = s + 1; 
1395
2258
  else
1396
 
    return gpg_error (GPG_ERR_INV_ID);
1397
 
 
1398
 
  for (s=keyidstr, n=0; n < 16; s += 2, n++)
1399
 
    tmp_sn[n] = xtoi_2 (s);
1400
 
 
1401
 
  if (app->serialnolen != 16)
1402
 
    return gpg_error (GPG_ERR_INV_CARD);
1403
 
  if (memcmp (app->serialno, tmp_sn, 16))
1404
 
    return gpg_error (GPG_ERR_WRONG_CARD);
 
2259
    {
 
2260
      for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
 
2261
        ;
 
2262
      if (n != 32)
 
2263
        return gpg_error (GPG_ERR_INV_ID);
 
2264
      else if (!*s)
 
2265
        ; /* no fingerprint given: we allow this for now. */
 
2266
      else if (*s == '/')
 
2267
        fpr = s + 1; 
 
2268
      else
 
2269
        return gpg_error (GPG_ERR_INV_ID);
 
2270
 
 
2271
      for (s=keyidstr, n=0; n < 16; s += 2, n++)
 
2272
        tmp_sn[n] = xtoi_2 (s);
 
2273
      
 
2274
      if (app->serialnolen != 16)
 
2275
        return gpg_error (GPG_ERR_INV_CARD);
 
2276
      if (memcmp (app->serialno, tmp_sn, 16))
 
2277
        return gpg_error (GPG_ERR_WRONG_CARD);
 
2278
    }
1405
2279
 
1406
2280
  /* If a fingerprint has been specified check it against the one on
1407
2281
     the card.  This is allows for a meaningful error message in case
1421
2295
}
1422
2296
 
1423
2297
 
1424
 
static int 
 
2298
static gpg_error_t 
1425
2299
do_decipher (app_t app, const char *keyidstr,
1426
 
             int (pincb)(void*, const char *, char **),
 
2300
             gpg_error_t (*pincb)(void*, const char *, char **),
1427
2301
             void *pincb_arg,
1428
2302
             const void *indata, size_t indatalen,
1429
2303
             unsigned char **outdata, size_t *outdatalen )
1482
2356
   cheap check on the PIN: If there is something wrong with the PIN
1483
2357
   entry system, only the regular CHV will get blocked and not the
1484
2358
   dangerous CHV3.  KEYIDSTR is the usual card's serial number; an
1485
 
   optional fingerprint part will be ignored. */
1486
 
static int 
 
2359
   optional fingerprint part will be ignored.
 
2360
 
 
2361
   There is a special mode if the keyidstr is "<serialno>[CHV3]" with
 
2362
   the "[CHV3]" being a literal string:  The Admin Pin is checked if
 
2363
   and only if the retry counter is still at 3. */
 
2364
static gpg_error_t 
1487
2365
do_check_pin (app_t app, const char *keyidstr,
1488
 
              int (pincb)(void*, const char *, char **),
 
2366
              gpg_error_t (*pincb)(void*, const char *, char **),
1489
2367
              void *pincb_arg)
1490
2368
{
1491
2369
  unsigned char tmp_sn[20]; 
1492
2370
  const char *s;
1493
2371
  int n;
 
2372
  int admin_pin = 0;
1494
2373
 
1495
2374
  if (!keyidstr || !*keyidstr)
1496
2375
    return gpg_error (GPG_ERR_INV_VALUE);
1507
2386
    ; /* No fingerprint given: we allow this for now. */
1508
2387
  else if (*s == '/')
1509
2388
    ; /* We ignore a fingerprint. */
 
2389
  else if (!strcmp (s, "[CHV3]") )
 
2390
    admin_pin = 1;
1510
2391
  else
1511
2392
    return gpg_error (GPG_ERR_INV_ID);
1512
2393
 
1517
2398
    return gpg_error (GPG_ERR_INV_CARD);
1518
2399
  if (memcmp (app->serialno, tmp_sn, 16))
1519
2400
    return gpg_error (GPG_ERR_WRONG_CARD);
 
2401
 
1520
2402
  /* Yes, there is a race conditions: The user might pull the card
1521
2403
     right here and we won't notice that.  However this is not a
1522
2404
     problem and the check above is merely for a graceful failure
1523
2405
     between operations. */
1524
2406
 
1525
 
  return verify_chv2 (app, pincb, pincb_arg);
 
2407
  if (admin_pin)
 
2408
    {
 
2409
      void *relptr;
 
2410
      unsigned char *value;
 
2411
      size_t valuelen;
 
2412
      int count;
 
2413
      
 
2414
      relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
 
2415
      if (!relptr || valuelen < 7)
 
2416
        {
 
2417
          log_error (_("error retrieving CHV status from card\n"));
 
2418
          xfree (relptr);
 
2419
          return gpg_error (GPG_ERR_CARD);
 
2420
        }
 
2421
      count = value[6];
 
2422
      xfree (relptr);
 
2423
 
 
2424
      if (!count)
 
2425
        {
 
2426
          log_info (_("card is permanently locked!\n"));
 
2427
          return gpg_error (GPG_ERR_BAD_PIN);
 
2428
        }
 
2429
      else if (value[6] < 3)
 
2430
        {
 
2431
          log_info (_("verification of Admin PIN is currently prohibited "
 
2432
                      "through this command\n"));
 
2433
          return gpg_error (GPG_ERR_GENERAL);
 
2434
        }
 
2435
 
 
2436
      app->did_chv3 = 0; /* Force verification.  */
 
2437
      return verify_chv3 (app, pincb, pincb_arg);
 
2438
    }
 
2439
  else
 
2440
    return verify_chv2 (app, pincb, pincb_arg);
1526
2441
}
1527
2442
 
1528
2443
 
1530
2445
 
1531
2446
/* Select the OpenPGP application on the card in SLOT.  This function
1532
2447
   must be used before any other OpenPGP application functions. */
1533
 
int
 
2448
gpg_error_t
1534
2449
app_select_openpgp (app_t app)
1535
2450
{
1536
2451
  static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
1581
2496
          goto leave;
1582
2497
        }
1583
2498
 
1584
 
      relptr = get_one_do (app, 0x00C4, &buffer, &buflen);
 
2499
      relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
1585
2500
      if (!relptr)
1586
2501
        {
1587
2502
          log_error (_("can't access %s - invalid OpenPGP card?\n"),
1591
2506
      app->force_chv1 = (buflen && *buffer == 0);
1592
2507
      xfree (relptr);
1593
2508
 
1594
 
      relptr = get_one_do (app, 0x00C0, &buffer, &buflen);
 
2509
      relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
1595
2510
      if (!relptr)
1596
2511
        {
1597
2512
          log_error (_("can't access %s - invalid OpenPGP card?\n"),
1619
2534
 
1620
2535
      app->fnc.deinit = do_deinit;
1621
2536
      app->fnc.learn_status = do_learn_status;
1622
 
      app->fnc.readcert = NULL;
 
2537
      app->fnc.readkey = do_readkey;
1623
2538
      app->fnc.getattr = do_getattr;
1624
2539
      app->fnc.setattr = do_setattr;
 
2540
      app->fnc.writekey = do_writekey;
1625
2541
      app->fnc.genkey = do_genkey;
1626
2542
      app->fnc.sign = do_sign;
1627
2543
      app->fnc.auth = do_auth;
1638
2554
 
1639
2555
 
1640
2556
 
1641
 
/* This function is a hack to retrieve essential information about the
1642
 
   card to be displayed by simple tools.  It mostly resembles what the
1643
 
   LEARN command returns. All parameters return allocated strings or
1644
 
   buffers or NULL if the data object is not available.  All returned
1645
 
   values are sanitized. */
1646
 
int
1647
 
app_openpgp_cardinfo (app_t app,
1648
 
                      char **serialno,
1649
 
                      char **disp_name,
1650
 
                      char **pubkey_url,
1651
 
                      unsigned char **fpr1,
1652
 
                      unsigned char **fpr2,
1653
 
                      unsigned char **fpr3)
1654
 
{
1655
 
  int rc;
1656
 
  void *relptr;
1657
 
  unsigned char *value;
1658
 
  size_t valuelen;
1659
 
 
1660
 
  if (serialno)
1661
 
    {
1662
 
      time_t dummy;
1663
 
 
1664
 
      *serialno = NULL;
1665
 
      rc = app_get_serial_and_stamp (app, serialno, &dummy);
1666
 
      if (rc)
1667
 
        {
1668
 
          log_error (_("error getting serial number: %s\n"),
1669
 
                     gpg_strerror (rc));
1670
 
          return rc;
1671
 
        }
1672
 
    }
1673
 
      
1674
 
  if (disp_name)
1675
 
    {
1676
 
      *disp_name = NULL;
1677
 
      relptr = get_one_do (app, 0x005B, &value, &valuelen);
1678
 
      if (relptr)
1679
 
        {
1680
 
          *disp_name = make_printable_string (value, valuelen, 0);
1681
 
          xfree (relptr);
1682
 
        }
1683
 
    }
1684
 
 
1685
 
  if (pubkey_url)
1686
 
    {
1687
 
      *pubkey_url = NULL;
1688
 
      relptr = get_one_do (app, 0x5F50, &value, &valuelen);
1689
 
      if (relptr)
1690
 
        {
1691
 
          *pubkey_url = make_printable_string (value, valuelen, 0);
1692
 
          xfree (relptr);
1693
 
        }
1694
 
    }
1695
 
 
1696
 
  if (fpr1)
1697
 
    *fpr1 = NULL;
1698
 
  if (fpr2)
1699
 
    *fpr2 = NULL;
1700
 
  if (fpr3)
1701
 
    *fpr3 = NULL;
1702
 
  relptr = get_one_do (app, 0x00C5, &value, &valuelen);
1703
 
  if (relptr && valuelen >= 60)
1704
 
    {
1705
 
      if (fpr1)
1706
 
        {
1707
 
          *fpr1 = xmalloc (20);
1708
 
          memcpy (*fpr1, value +  0, 20);
1709
 
        }
1710
 
      if (fpr2)
1711
 
        {
1712
 
          *fpr2 = xmalloc (20);
1713
 
          memcpy (*fpr2, value + 20, 20);
1714
 
        }
1715
 
      if (fpr3)
1716
 
        {
1717
 
          *fpr3 = xmalloc (20);
1718
 
          memcpy (*fpr3, value + 40, 20);
1719
 
        }
1720
 
    }
1721
 
  xfree (relptr);
1722
 
 
1723
 
  return 0;
1724
 
}
1725
 
 
1726
 
 
1727
 
 
1728
 
/* This function is currently only used by the sc-copykeys program to
1729
 
   store a key on the smartcard.  app_t ist the application handle,
1730
 
   KEYNO is the number of the key and PINCB, PINCB_ARG are used to ask
1731
 
   for the SO PIN.  TEMPLATE and TEMPLATE_LEN describe a buffer with
1732
 
   the key template to store. CREATED_AT is the timestamp used to
1733
 
   create the fingerprint. M, MLEN is the RSA modulus and E, ELEN the
1734
 
   RSA public exponent. This function silently overwrites an existing
1735
 
   key.*/
1736
 
int 
1737
 
app_openpgp_storekey (app_t app, int keyno,
1738
 
                      unsigned char *template, size_t template_len,
1739
 
                      time_t created_at,
1740
 
                      const unsigned char *m, size_t mlen,
1741
 
                      const unsigned char *e, size_t elen,
1742
 
                      int (*pincb)(void*, const char *, char **),
1743
 
                      void *pincb_arg)
1744
 
{
1745
 
  int rc;
1746
 
  unsigned char fprbuf[20];
1747
 
 
1748
 
  if (keyno < 1 || keyno > 3)
1749
 
    return gpg_error (GPG_ERR_INV_ID);
1750
 
  keyno--;
1751
 
 
1752
 
  rc = verify_chv3 (app, pincb, pincb_arg);
1753
 
  if (rc)
1754
 
    goto leave;
1755
 
 
1756
 
  flush_cache (app);
1757
 
 
1758
 
  rc = iso7816_put_data (app->slot,
1759
 
                         (app->card_version > 0x0007? 0xE0 : 0xE9) + keyno,
1760
 
                         template, template_len);
1761
 
  if (rc)
1762
 
    {
1763
 
      log_error (_("failed to store the key: %s\n"), gpg_strerror (rc));
1764
 
      rc = gpg_error (GPG_ERR_CARD);
1765
 
      goto leave;
1766
 
    }
1767
 
 
1768
 
/*    log_printhex ("RSA n:", m, mlen);  */
1769
 
/*    log_printhex ("RSA e:", e, elen);  */
1770
 
 
1771
 
  rc = store_fpr (app->slot, keyno, (u32)created_at,
1772
 
                  m, mlen, e, elen, fprbuf, app->card_version);
1773
 
 
1774
 
 leave:
1775
 
  return rc;
1776
 
}
1777
 
 
1778
 
 
1779
 
/* Utility function for external tools: Read the public RSA key at
1780
 
   KEYNO and return modulus and exponent in (M,MLEN) and (E,ELEN). */
1781
 
int 
1782
 
app_openpgp_readkey (app_t app, int keyno, unsigned char **m, size_t *mlen,
1783
 
                     unsigned char **e, size_t *elen)
1784
 
{
1785
 
  int rc;
1786
 
  const unsigned char *keydata, *a;
1787
 
  unsigned char *buffer;
1788
 
  size_t buflen, keydatalen, alen;
1789
 
 
1790
 
  *m = NULL;
1791
 
  *e = NULL;
1792
 
 
1793
 
  if (keyno < 1 || keyno > 3)
1794
 
    return gpg_error (GPG_ERR_INV_ID);
1795
 
  keyno--;
1796
 
 
1797
 
  rc = iso7816_read_public_key(app->slot, 
1798
 
                               keyno == 0? "\xB6" :
1799
 
                               keyno == 1? "\xB8" : "\xA4",
1800
 
                               2,
1801
 
                               &buffer, &buflen);
1802
 
  if (rc)
1803
 
    {
1804
 
      rc = gpg_error (GPG_ERR_CARD);
1805
 
      log_error (_("reading the key failed\n"));
1806
 
      goto leave;
1807
 
    }
1808
 
 
1809
 
  keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
1810
 
  if (!keydata)
1811
 
    {
1812
 
      log_error (_("response does not contain the public key data\n"));
1813
 
      rc = gpg_error (GPG_ERR_CARD);
1814
 
      goto leave;
1815
 
    }
1816
 
 
1817
 
  a = find_tlv (keydata, keydatalen, 0x0081, &alen);
1818
 
  if (!a)
1819
 
    {
1820
 
      log_error (_("response does not contain the RSA modulus\n"));
1821
 
      rc = gpg_error (GPG_ERR_CARD);
1822
 
      goto leave;
1823
 
    }
1824
 
  *mlen = alen;
1825
 
  *m = xmalloc (alen);
1826
 
  memcpy (*m, a, alen);
1827
 
  
1828
 
  a = find_tlv (keydata, keydatalen, 0x0082, &alen);
1829
 
  if (!a)
1830
 
    {
1831
 
      log_error (_("response does not contain the RSA public exponent\n"));
1832
 
      rc = gpg_error (GPG_ERR_CARD);
1833
 
      goto leave;
1834
 
    }
1835
 
  *elen = alen;
1836
 
  *e = xmalloc (alen);
1837
 
  memcpy (*e, a, alen);
1838
 
 
1839
 
 leave:
1840
 
  xfree (buffer);
1841
 
  if (rc)
1842
 
    { 
1843
 
      xfree (*m); *m = NULL;
1844
 
      xfree (*e); *e = NULL;
1845
 
    }
1846
 
  return rc;
1847
 
}