aboutsummaryrefslogtreecommitdiff
path: root/src/util/crypto_helper_denom.c
blob: c61a46f1d4e26e8f1084673f0db2c2fdc705b22b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
/*
  This file is part of TALER
  Copyright (C) 2020 Taler Systems SA

  TALER 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, or (at your option) any later version.

  TALER 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
  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file util/crypto_helper_denom.c
 * @brief utility functions for running out-of-process private key operations
 * @author Christian Grothoff
 */
#include "platform.h"
#include "taler_util.h"
#include "taler_signatures.h"
#include "taler-helper-crypto-rsa.h"
#include <poll.h>


struct TALER_CRYPTO_DenominationHelper
{
  /**
   * Function to call with updates to available key material.
   */
  TALER_CRYPTO_DenominationKeyStatusCallback dkc;

  /**
   * Closure for @e dkc
   */
  void *dkc_cls;

  /**
   * Socket address of the denomination helper process.
   * Used to reconnect if the connection breaks.
   */
  struct sockaddr_un sa;

  /**
   * Socket address of this process.
   */
  struct sockaddr_un my_sa;

  /**
   * Template for @e my_sa.
   */
  char *template;

  /**
   * The UNIX domain socket, -1 if we are currently not connected.
   */
  int sock;

  /**
   * Have we ever been sync'ed?
   */
  bool synced;
};


/**
 * Disconnect from the helper process.  Updates
 * @e sock field in @a dh.
 *
 * @param[in,out] dh handle to tear down connection of
 */
static void
do_disconnect (struct TALER_CRYPTO_DenominationHelper *dh)
{
  GNUNET_break (0 == close (dh->sock));
  if (0 != unlink (dh->my_sa.sun_path))
    GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
                              "unlink",
                              dh->my_sa.sun_path);
  dh->sock = -1;
}


/**
 * Try to connect to the helper process.  Updates
 * @e sock field in @a dh.
 *
 * @param[in,out] dh handle to establish connection for
 */
static void
try_connect (struct TALER_CRYPTO_DenominationHelper *dh)
{
  if (-1 != dh->sock)
    return;
  dh->sock = socket (AF_UNIX,
                     SOCK_DGRAM,
                     0);
  if (-1 == dh->sock)
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                         "socket");
    return;
  }
  {
    char *tmpdir;

    tmpdir = GNUNET_DISK_mktemp (dh->template);
    if (NULL == tmpdir)
    {
      do_disconnect (dh);
      return;
    }
    /* we use >= here because we want the sun_path to always
       be 0-terminated */
    if (strlen (tmpdir) >= sizeof (dh->sa.sun_path))
    {
      GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
                                 "PATHS",
                                 "TALER_RUNTIME_DIR",
                                 "path too long");
      GNUNET_free (tmpdir);
      do_disconnect (dh);
      return;
    }
    dh->my_sa.sun_family = AF_UNIX;
    strncpy (dh->my_sa.sun_path,
             tmpdir,
             sizeof (dh->sa.sun_path));
    if (0 != unlink (tmpdir))
      GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
                                "unlink",
                                tmpdir);
    GNUNET_free (tmpdir);
  }
  if (0 != bind (dh->sock,
                 (const struct sockaddr *) &dh->my_sa,
                 sizeof (dh->my_sa)))
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                         "bind");
    do_disconnect (dh);
    return;
  }
  {
    struct GNUNET_MessageHeader hdr = {
      .size = htons (sizeof (hdr)),
      .type = htons (TALER_HELPER_RSA_MT_REQ_INIT)
    };
    ssize_t ret;

    ret = sendto (dh->sock,
                  &hdr,
                  sizeof (hdr),
                  0,
                  (const struct sockaddr *) &dh->sa,
                  sizeof (dh->sa));
    if (ret < 0)
    {
      GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
                                "sendto",
                                dh->sa.sun_path);
      do_disconnect (dh);
      return;
    }
    /* We are using SOCK_DGRAM, partial writes should not be possible */
    GNUNET_break (((size_t) ret) == sizeof (hdr));
    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                "Successfully sent REQ_INIT\n");
  }

}


struct TALER_CRYPTO_DenominationHelper *
TALER_CRYPTO_helper_denom_connect (
  const struct GNUNET_CONFIGURATION_Handle *cfg,
  TALER_CRYPTO_DenominationKeyStatusCallback dkc,
  void *dkc_cls)
{
  struct TALER_CRYPTO_DenominationHelper *dh;
  char *unixpath;

  if (GNUNET_OK !=
      GNUNET_CONFIGURATION_get_value_filename (cfg,
                                               "taler-helper-crypto-rsa",
                                               "UNIXPATH",
                                               &unixpath))
  {
    GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
                               "taler-helper-crypto-rsa",
                               "UNIXPATH");
    return NULL;
  }
  /* we use >= here because we want the sun_path to always
     be 0-terminated */
  if (strlen (unixpath) >= sizeof (dh->sa.sun_path))
  {
    GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR,
                               "taler-helper-crypto-rsa",
                               "UNIXPATH",
                               "path too long");
    GNUNET_free (unixpath);
    return NULL;
  }
  dh = GNUNET_new (struct TALER_CRYPTO_DenominationHelper);
  dh->dkc = dkc;
  dh->dkc_cls = dkc_cls;
  dh->sa.sun_family = AF_UNIX;
  strncpy (dh->sa.sun_path,
           unixpath,
           sizeof (dh->sa.sun_path));
  dh->sock = -1;
  {
    char *tmpdir;
    char *template;

    if (GNUNET_OK !=
        GNUNET_CONFIGURATION_get_value_filename (cfg,
                                                 "PATHS",
                                                 "TALER_RUNTIME_DIR",
                                                 &tmpdir))
    {
      GNUNET_log_config_missing (GNUNET_ERROR_TYPE_WARNING,
                                 "PATHS",
                                 "TALER_RUNTIME_DIR");
      tmpdir = GNUNET_strdup ("/tmp");
    }
    GNUNET_asprintf (&template,
                     "%s/crypto-rsa-client/XXXXXX",
                     tmpdir);
    GNUNET_free (tmpdir);
    if (GNUNET_OK !=
        GNUNET_DISK_directory_create_for_file (template))
    {
      GNUNET_free (dh);
      GNUNET_free (template);
      return NULL;
    }
    dh->template = template;
  }
  TALER_CRYPTO_helper_denom_poll (dh);
  return dh;
}


/**
 * Handle a #TALER_HELPER_RSA_MT_AVAIL message from the helper.
 *
 * @param dh helper context
 * @param hdr message that we received
 * @return #GNUNET_OK on success
 */
static int
handle_mt_avail (struct TALER_CRYPTO_DenominationHelper *dh,
                 const struct GNUNET_MessageHeader *hdr)
{
  const struct TALER_CRYPTO_RsaKeyAvailableNotification *kan
    = (const struct TALER_CRYPTO_RsaKeyAvailableNotification *) hdr;
  const char *buf = (const char *) &kan[1];
  const char *section_name;

  if (sizeof (*kan) > ntohs (hdr->size))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  if (ntohs (hdr->size) !=
      sizeof (*kan)
      + ntohs (kan->pub_size)
      + ntohs (kan->section_name_len))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  section_name = &buf[ntohs (kan->pub_size)];
  if ('\0' != section_name[ntohs (kan->section_name_len) - 1])
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }

  {
    struct TALER_DenominationPublicKey denom_pub;
    struct GNUNET_HashCode h_denom_pub;

    denom_pub.rsa_public_key
      = GNUNET_CRYPTO_rsa_public_key_decode (buf,
                                             ntohs (kan->pub_size));
    if (NULL == denom_pub.rsa_public_key)
    {
      GNUNET_break_op (0);
      return GNUNET_SYSERR;
    }
    GNUNET_CRYPTO_rsa_public_key_hash (denom_pub.rsa_public_key,
                                       &h_denom_pub);
    if (GNUNET_OK !=
        TALER_exchange_secmod_rsa_verify (
          &h_denom_pub,
          section_name,
          GNUNET_TIME_absolute_ntoh (kan->anchor_time),
          GNUNET_TIME_relative_ntoh (kan->duration_withdraw),
          &kan->secm_pub,
          &kan->secm_sig))
    {
      GNUNET_break_op (0);
      GNUNET_CRYPTO_rsa_public_key_free (denom_pub.rsa_public_key);
      return GNUNET_SYSERR;
    }
    dh->dkc (dh->dkc_cls,
             section_name,
             GNUNET_TIME_absolute_ntoh (kan->anchor_time),
             GNUNET_TIME_relative_ntoh (kan->duration_withdraw),
             &h_denom_pub,
             &denom_pub,
             &kan->secm_pub,
             &kan->secm_sig);
    GNUNET_CRYPTO_rsa_public_key_free (denom_pub.rsa_public_key);
  }
  return GNUNET_OK;
}


/**
 * Handle a #TALER_HELPER_RSA_MT_PURGE message from the helper.
 *
 * @param dh helper context
 * @param hdr message that we received
 * @return #GNUNET_OK on success
 */
static int
handle_mt_purge (struct TALER_CRYPTO_DenominationHelper *dh,
                 const struct GNUNET_MessageHeader *hdr)
{
  const struct TALER_CRYPTO_RsaKeyPurgeNotification *pn
    = (const struct TALER_CRYPTO_RsaKeyPurgeNotification *) hdr;

  if (sizeof (*pn) != ntohs (hdr->size))
  {
    GNUNET_break_op (0);
    return GNUNET_SYSERR;
  }
  dh->dkc (dh->dkc_cls,
           NULL,
           GNUNET_TIME_UNIT_ZERO_ABS,
           GNUNET_TIME_UNIT_ZERO,
           &pn->h_denom_pub,
           NULL,
           NULL,
           NULL);
  return GNUNET_OK;
}


/**
 * Wait until the socket is ready to read.
 *
 * @param dh helper to wait for
 * @return false on timeout (after 5s)
 */
static bool
await_read_ready (struct TALER_CRYPTO_DenominationHelper *dh)
{
  /* wait for reply with 5s timeout */
  struct pollfd pfd = {
    .fd = dh->sock,
    .events = POLLIN
  };
  sigset_t sigmask;
  struct timespec ts = {
    .tv_sec = 1
  };
  int ret;

  GNUNET_assert (0 == sigemptyset (&sigmask));
  GNUNET_assert (0 == sigaddset (&sigmask, SIGTERM));
  GNUNET_assert (0 == sigaddset (&sigmask, SIGHUP));
  ret = ppoll (&pfd,
               1,
               &ts,
               &sigmask);
  if ( (-1 == ret) &&
       (EINTR != errno) )
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR,
                         "ppoll");
  return (0 < ret);
}


void
TALER_CRYPTO_helper_denom_poll (struct TALER_CRYPTO_DenominationHelper *dh)
{
  char buf[UINT16_MAX];
  ssize_t ret;
  const struct GNUNET_MessageHeader *hdr
    = (const struct GNUNET_MessageHeader *) buf;

  try_connect (dh);
  if (-1 == dh->sock)
    return; /* give up */
  while (1)
  {
    ret = recv (dh->sock,
                buf,
                sizeof (buf),
                MSG_DONTWAIT);
    if (ret < 0)
    {
      if (EAGAIN == errno)
      {
        if (dh->synced)
          break;
        if (! await_read_ready (dh))
        {
          /* timeout AND not synced => full reconnect */
          GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                      "Restarting connection to helper, did not come up properly\n");
          do_disconnect (dh);
          try_connect (dh);
          if (-1 == dh->sock)
            return; /* give up */
        }
        continue; /* try again */
      }
      GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                           "recv");
      do_disconnect (dh);
      return;
    }

    if ( (ret < sizeof (struct GNUNET_MessageHeader)) ||
         (ret != ntohs (hdr->size)) )
    {
      GNUNET_break_op (0);
      do_disconnect (dh);
      return;
    }
    switch (ntohs (hdr->type))
    {
    case TALER_HELPER_RSA_MT_AVAIL:
      if (GNUNET_OK !=
          handle_mt_avail (dh,
                           hdr))
      {
        GNUNET_break_op (0);
        do_disconnect (dh);
        return;
      }
      break;
    case TALER_HELPER_RSA_MT_PURGE:
      if (GNUNET_OK !=
          handle_mt_purge (dh,
                           hdr))
      {
        GNUNET_break_op (0);
        do_disconnect (dh);
        return;
      }
      break;
    case TALER_HELPER_RSA_SYNCED:
      GNUNET_log (GNUNET_ERROR_TYPE_INFO,
                  "Now synchronized with RSA helper\n");
      dh->synced = true;
      break;
    default:
      GNUNET_break_op (0);
      do_disconnect (dh);
      return;
    }
  }
}


struct TALER_DenominationSignature
TALER_CRYPTO_helper_denom_sign (
  struct TALER_CRYPTO_DenominationHelper *dh,
  const struct GNUNET_HashCode *h_denom_pub,
  const void *msg,
  size_t msg_size,
  enum TALER_ErrorCode *ec)
{
  struct TALER_DenominationSignature ds = { NULL };
  {
    char buf[sizeof (struct TALER_CRYPTO_SignRequest) + msg_size];
    struct TALER_CRYPTO_SignRequest *sr
      = (struct TALER_CRYPTO_SignRequest *) buf;
    ssize_t ret;

    try_connect (dh);
    if (-1 == dh->sock)
    {
      *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE;
      return ds;
    }
    sr->header.size = htons (sizeof (buf));
    sr->header.type = htons (TALER_HELPER_RSA_MT_REQ_SIGN);
    sr->reserved = htonl (0);
    sr->h_denom_pub = *h_denom_pub;
    memcpy (&sr[1],
            msg,
            msg_size);
    ret = sendto (dh->sock,
                  buf,
                  sizeof (buf),
                  0,
                  &dh->sa,
                  sizeof (dh->sa));
    if (ret < 0)
    {
      GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                           "sendto");
      do_disconnect (dh);
      *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE;
      return ds;
    }
    /* We are using SOCK_DGRAM, partial writes should not be possible */
    GNUNET_break (((size_t) ret) == sizeof (buf));
  }

  while (1)
  {
    char buf[UINT16_MAX];
    ssize_t ret;
    const struct GNUNET_MessageHeader *hdr
      = (const struct GNUNET_MessageHeader *) buf;

    if (! await_read_ready (dh))
    {
      do_disconnect (dh);
      *ec = TALER_EC_GENERIC_TIMEOUT;
      return ds;
    }
    ret = recv (dh->sock,
                buf,
                sizeof (buf),
                0);
    if (ret < 0)
    {
      GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                           "recv");
      do_disconnect (dh);
      *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_UNAVAILABLE;
      return ds;
    }
    if ( (ret < sizeof (struct GNUNET_MessageHeader)) ||
         (ret != ntohs (hdr->size)) )
    {
      GNUNET_break_op (0);
      do_disconnect (dh);
      *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG;
      return ds;
    }
    switch (ntohs (hdr->type))
    {
    case TALER_HELPER_RSA_MT_RES_SIGNATURE:
      if (ret < sizeof (struct TALER_CRYPTO_SignResponse))
      {
        GNUNET_break_op (0);
        do_disconnect (dh);
        *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG;
        return ds;
      }
      {
        const struct TALER_CRYPTO_SignResponse *sr =
          (const struct TALER_CRYPTO_SignResponse *) buf;
        struct GNUNET_CRYPTO_RsaSignature *rsa_signature;

        rsa_signature = GNUNET_CRYPTO_rsa_signature_decode (&sr[1],
                                                            ret - sizeof (*sr));
        if (NULL == rsa_signature)
        {
          GNUNET_break_op (0);
          do_disconnect (dh);
          *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG;
          return ds;
        }
        *ec = TALER_EC_NONE;
        ds.rsa_signature = rsa_signature;
        return ds;
      }
    case TALER_HELPER_RSA_MT_RES_SIGN_FAILURE:
      if (ret != sizeof (struct TALER_CRYPTO_SignFailure))
      {
        GNUNET_break_op (0);
        do_disconnect (dh);
        *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG;
        return ds;
      }
      {
        const struct TALER_CRYPTO_SignFailure *sf =
          (const struct TALER_CRYPTO_SignFailure *) buf;

        *ec = (enum TALER_ErrorCode) ntohl (sf->ec);
        return ds;
      }
    case TALER_HELPER_RSA_MT_AVAIL:
      if (GNUNET_OK !=
          handle_mt_avail (dh,
                           hdr))
      {
        GNUNET_break_op (0);
        do_disconnect (dh);
        *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG;
        return ds;
      }
      break; /* while(1) loop ensures we recvfrom() again */
    case TALER_HELPER_RSA_MT_PURGE:
      if (GNUNET_OK !=
          handle_mt_purge (dh,
                           hdr))
      {
        GNUNET_break_op (0);
        do_disconnect (dh);
        *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG;
        return ds;
      }
      break; /* while(1) loop ensures we recvfrom() again */
    default:
      GNUNET_break_op (0);
      do_disconnect (dh);
      *ec = TALER_EC_EXCHANGE_DENOMINATION_HELPER_BUG;
      return ds;
    }
  }
}


void
TALER_CRYPTO_helper_denom_revoke (
  struct TALER_CRYPTO_DenominationHelper *dh,
  const struct GNUNET_HashCode *h_denom_pub)
{
  struct TALER_CRYPTO_RevokeRequest rr = {
    .header.size = htons (sizeof (rr)),
    .header.type = htons (TALER_HELPER_RSA_MT_REQ_REVOKE),
    .h_denom_pub = *h_denom_pub
  };
  ssize_t ret;

  try_connect (dh);
  if (-1 == dh->sock)
    return; /* give up */
  ret = sendto (dh->sock,
                &rr,
                sizeof (rr),
                0,
                (const struct sockaddr *) &dh->sa,
                sizeof (dh->sa));
  if (ret < 0)
  {
    GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
                         "sendto");
    do_disconnect (dh);
    return;
  }
  /* We are using SOCK_DGRAM, partial writes should not be possible */
  GNUNET_break (((size_t) ret) == sizeof (rr));
}


void
TALER_CRYPTO_helper_denom_disconnect (
  struct TALER_CRYPTO_DenominationHelper *dh)
{
  do_disconnect (dh);
  GNUNET_free (dh->template);
  GNUNET_free (dh);
}


/* end of crypto_helper_denom.c */