Fix libzypp build error
[platform/upstream/gpgme.git] / src / decrypt.c
1 /* decrypt.c - Decrypt function.
2  * Copyright (C) 2000 Werner Koch (dd9jn)
3  * Copyright (C) 2001, 2002, 2003, 2004, 2017 g10 Code GmbH
4  *
5  * This file is part of GPGME.
6  *
7  * GPGME is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU Lesser General Public License as
9  * published by the Free Software Foundation; either version 2.1 of
10  * the License, or (at your option) any later version.
11  *
12  * GPGME is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this program; if not, see <https://gnu.org/licenses/>.
19  * SPDX-License-Identifier: LGPL-2.1-or-later
20  */
21
22 #if HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25 #include <stdlib.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <assert.h>
29
30 #include "debug.h"
31 #include "gpgme.h"
32 #include "util.h"
33 #include "context.h"
34 #include "ops.h"
35 #include "data.h"
36
37 \f
38 typedef struct
39 {
40   struct _gpgme_op_decrypt_result result;
41
42   /* The error code from a FAILURE status line or 0.  */
43   gpg_error_t failure_code;
44
45   int okay;
46
47   /* A flag telling that the a decryption failed and two optional error
48    * codes to further specify the failure for public key decryption and
49    * symmetric decryption.  */
50   int failed;
51   gpg_error_t pkdecrypt_failed;
52   gpg_error_t symdecrypt_failed;
53
54   /* At least one secret key is not available.  gpg issues NO_SECKEY
55    * status lines for each key the message has been encrypted to but
56    * that secret key is not available.  This can't be done for hidden
57    * recipients, though.  We track it here to allow for a better error
58    * message than the general DECRYPTION_FAILED. */
59   int any_no_seckey;
60
61   /* If the engine emits a DECRYPTION_INFO status and that does not
62    * indicate that an integrity protection mode is active, this flag
63    * is set.  */
64   int not_integrity_protected;
65
66   /* The error code from the first ERROR line.  This is in some cases
67    * used to return a better matching error code to the caller.  */
68   gpg_error_t first_status_error;
69
70   /* A pointer to the next pointer of the last recipient in the list.
71      This makes appending new invalid signers painless while
72      preserving the order.  */
73   gpgme_recipient_t *last_recipient_p;
74
75   /* The data object serial number of the plaintext.  */
76   uint64_t plaintext_dserial;
77 } *op_data_t;
78
79
80 static void
81 release_op_data (void *hook)
82 {
83   op_data_t opd = (op_data_t) hook;
84   gpgme_recipient_t recipient = opd->result.recipients;
85
86   free (opd->result.unsupported_algorithm);
87   free (opd->result.file_name);
88   free (opd->result.session_key);
89   free (opd->result.symkey_algo);
90
91   while (recipient)
92     {
93       gpgme_recipient_t next = recipient->next;
94       free (recipient);
95       recipient = next;
96     }
97 }
98
99
100 gpgme_decrypt_result_t
101 gpgme_op_decrypt_result (gpgme_ctx_t ctx)
102 {
103   void *hook;
104   op_data_t opd;
105   gpgme_error_t err;
106
107   TRACE_BEG (DEBUG_CTX, "gpgme_op_decrypt_result", ctx, "");
108
109   ctx->ignore_mdc_error = 0;  /* Always reset this flag.  */
110
111   err = _gpgme_op_data_lookup (ctx, OPDATA_DECRYPT, &hook, -1, NULL);
112   opd = hook;
113   if (err || !opd)
114     {
115       TRACE_SUC ("result=(null)");
116       return NULL;
117     }
118
119   /* Make sure that SYMKEY_ALGO has a value.  */
120   if (!opd->result.symkey_algo)
121     {
122       opd->result.symkey_algo = strdup ("?.?");
123       if (!opd->result.symkey_algo)
124         {
125           TRACE_SUC ("result=(null)");
126           return NULL;
127         }
128     }
129
130   if (_gpgme_debug_trace ())
131     {
132       gpgme_recipient_t rcp;
133
134       if (opd->result.unsupported_algorithm)
135         {
136           TRACE_LOG  ("result: unsupported_algorithm: %s",
137                       opd->result.unsupported_algorithm);
138         }
139       if (opd->result.wrong_key_usage)
140         {
141           TRACE_LOG ("result: wrong key usage");
142         }
143       rcp = opd->result.recipients;
144       while (rcp)
145         {
146           TRACE_LOG  ("result: recipient: keyid=%s, pubkey_algo=%i, "
147                       "status=%s", rcp->keyid, rcp->pubkey_algo,
148                       gpg_strerror (rcp->status));
149           rcp = rcp->next;
150         }
151       if (opd->result.file_name)
152         {
153           TRACE_LOG  ("result: original file name: %s", opd->result.file_name);
154         }
155     }
156
157   TRACE_SUC ("result=%p", &opd->result);
158   return &opd->result;
159 }
160
161
162 \f
163 /* Parse the ARGS of an error status line and record some error
164  * conditions at OPD.  Returns 0 on success.  */
165 static gpgme_error_t
166 parse_status_error (char *args, op_data_t opd)
167 {
168   gpgme_error_t err;
169   char *field[3];
170   int nfields;
171   char *args2;
172
173   if (!args)
174     return trace_gpg_error (GPG_ERR_INV_ENGINE);
175
176   args2 = strdup (args); /* Split modifies the input string. */
177   nfields = _gpgme_split_fields (args2, field, DIM (field));
178   if (nfields < 1)
179     {
180       free (args2);
181       return trace_gpg_error (GPG_ERR_INV_ENGINE); /* Required arg missing.  */
182     }
183   err = nfields < 2 ? 0 : atoi (field[1]);
184
185   if (!strcmp (field[0], "decrypt.algorithm"))
186     {
187       if (gpg_err_code (err) == GPG_ERR_UNSUPPORTED_ALGORITHM
188           && nfields > 2
189           && strcmp (field[2], "?"))
190         {
191           opd->result.unsupported_algorithm = strdup (field[2]);
192           if (!opd->result.unsupported_algorithm)
193             {
194               free (args2);
195               return gpg_error_from_syserror ();
196             }
197         }
198     }
199   else if (!strcmp (field[0], "decrypt.keyusage"))
200     {
201       if (gpg_err_code (err) == GPG_ERR_WRONG_KEY_USAGE)
202         opd->result.wrong_key_usage = 1;
203     }
204   else if (!strcmp (field[0], "pkdecrypt_failed"))
205     {
206       switch (gpg_err_code (err))
207         {
208         case GPG_ERR_CANCELED:
209         case GPG_ERR_FULLY_CANCELED:
210           /* It is better to return with a cancel error code than the
211            * general decryption failed error code.  */
212           opd->pkdecrypt_failed = gpg_err_make (gpg_err_source (err),
213                                                 GPG_ERR_CANCELED);
214           break;
215
216         case GPG_ERR_BAD_PASSPHRASE:
217           /* A bad passphrase is severe enough that we return this
218            * error code.  */
219           opd->pkdecrypt_failed = err;
220           break;
221
222         default:
223           /* For now all other error codes are ignored and the
224            * standard DECRYPT_FAILED is returned.  */
225           break;
226         }
227     }
228   else if (!strcmp (field[0], "nomdc_with_legacy_cipher"))
229     {
230       opd->result.legacy_cipher_nomdc = 1;
231       opd->not_integrity_protected = 1;
232     }
233   else if (!strcmp (field[0], "symkey_decrypt.maybe_error"))
234     {
235       switch (gpg_err_code (err))
236         {
237         case GPG_ERR_BAD_PASSPHRASE:
238           /* A bad passphrase is severe enough that we return this
239            * error code.  */
240           opd->symdecrypt_failed = err;
241           break;
242
243         default:
244           /* For now all other error codes are ignored and the
245            * standard DECRYPT_FAILED is returned.  */
246           break;
247         }
248     }
249   /* Record the first error code.  */
250   if (err && !opd->first_status_error)
251     opd->first_status_error = err;
252
253
254   free (args2);
255   return 0;
256 }
257
258
259 static gpgme_error_t
260 parse_enc_to (char *args, gpgme_recipient_t *recp, gpgme_protocol_t protocol)
261 {
262   gpgme_recipient_t rec;
263   char *tail;
264   int i;
265
266   rec = malloc (sizeof (*rec));
267   if (!rec)
268     return gpg_error_from_syserror ();
269
270   rec->next = NULL;
271   rec->keyid = rec->_keyid;
272   rec->status = 0;
273
274   for (i = 0; i < sizeof (rec->_keyid) - 1; i++)
275     {
276       if (args[i] == '\0' || args[i] == ' ')
277         break;
278
279       rec->_keyid[i] = args[i];
280     }
281   rec->_keyid[i] = '\0';
282
283   args = &args[i];
284   if (*args != '\0' && *args != ' ')
285     {
286       free (rec);
287       return trace_gpg_error (GPG_ERR_INV_ENGINE);
288     }
289
290   while (*args == ' ')
291     args++;
292
293   if (*args)
294     {
295       gpg_err_set_errno (0);
296       rec->pubkey_algo = _gpgme_map_pk_algo (strtol (args, &tail, 0), protocol);
297       if (errno || args == tail || *tail != ' ')
298         {
299           /* The crypto backend does not behave.  */
300           free (rec);
301           return trace_gpg_error (GPG_ERR_INV_ENGINE);
302         }
303     }
304
305   /* FIXME: The key length is always 0 right now, so no need to parse
306      it.  */
307
308   *recp = rec;
309   return 0;
310 }
311
312
313 /* Parse the ARGS of a
314  *   DECRYPTION_INFO <mdc_method> <sym_algo> [<aead_algo>]
315  * status.  Returns 0 on success and updates the OPD.
316  */
317 static gpgme_error_t
318 parse_decryption_info (char *args, op_data_t opd, gpgme_protocol_t protocol)
319 {
320   char *field[3];
321   int nfields;
322   char *args2;
323   int mdc, aead_algo;
324   const char *algostr, *modestr;
325
326   if (!args)
327     return trace_gpg_error (GPG_ERR_INV_ENGINE);
328
329   args2 = strdup (args); /* Split modifies the input string. */
330   nfields = _gpgme_split_fields (args2, field, DIM (field));
331   if (nfields < 2)
332     {
333       free (args2);
334       return trace_gpg_error (GPG_ERR_INV_ENGINE); /* Required arg missing.  */
335     }
336
337   mdc     = atoi (field[0]);
338   algostr = _gpgme_cipher_algo_name (atoi (field[1]), protocol);
339   aead_algo    = nfields < 3? 0 : atoi (field[2]);
340   modestr = _gpgme_cipher_mode_name (aead_algo, protocol);
341
342   free (args2);
343
344   free (opd->result.symkey_algo);
345   if (!aead_algo && mdc != 2)
346     opd->result.symkey_algo = _gpgme_strconcat (algostr, ".PGPCFB", NULL);
347   else
348     opd->result.symkey_algo = _gpgme_strconcat (algostr, ".", modestr, NULL);
349   if (!opd->result.symkey_algo)
350     return gpg_error_from_syserror ();
351
352   if (!mdc && !aead_algo)
353     opd->not_integrity_protected = 1;
354
355   return 0;
356 }
357
358
359 gpgme_error_t
360 _gpgme_decrypt_status_handler (void *priv, gpgme_status_code_t code,
361                                char *args)
362 {
363   gpgme_ctx_t ctx = (gpgme_ctx_t) priv;
364   gpgme_error_t err;
365   void *hook;
366   op_data_t opd;
367
368   err = _gpgme_passphrase_status_handler (priv, code, args);
369   if (err)
370     return err;
371
372   err = _gpgme_op_data_lookup (ctx, OPDATA_DECRYPT, &hook, -1, NULL);
373   opd = hook;
374   if (err)
375     return err;
376
377   switch (code)
378     {
379     case GPGME_STATUS_FAILURE:
380       opd->failure_code = _gpgme_parse_failure (args);
381       break;
382
383     case GPGME_STATUS_EOF:
384       /* We force an encryption failure if we know that integrity
385        * protection is missing.  For modern version of gpg using
386        * modern cipher algorithms this is not required because gpg
387        * will issue a failure anyway.  However older gpg versions emit
388        * only a warning.
389        * Fixme: These error values should probably be attributed to
390        * the underlying crypto engine (as error source).  */
391       if (opd->failed)
392         {
393           /* This comes from a specialized ERROR status line.  */
394           if (opd->pkdecrypt_failed)
395             return opd->pkdecrypt_failed;
396           if (opd->symdecrypt_failed)
397             return opd->symdecrypt_failed;
398
399           /* For an integrity failure return just DECRYPTION_FAILED;
400            * the actual cause can be taken from an already set
401            * decryption result flag.  */
402           if ((opd->not_integrity_protected && !ctx->ignore_mdc_error))
403             return gpg_error (GPG_ERR_DECRYPT_FAILED);
404
405           /* If we have any other ERROR code we prefer that over
406            * NO_SECKEY because it is probably the better matching
407            * code.  For example a garbled message with multiple
408            * plaintext will return BAD_DATA here but may also have
409            * indicated a NO_SECKEY.  */
410           if (opd->first_status_error)
411             return opd->first_status_error;
412
413           /* No secret key is pretty common reason.  */
414           if (opd->any_no_seckey)
415             return gpg_error (GPG_ERR_NO_SECKEY);
416
417           /* Generic decryption failed error code.  */
418           return gpg_error (GPG_ERR_DECRYPT_FAILED);
419         }
420       else if (!opd->okay)
421         {
422           /* No data was found.  */
423           return gpg_error (GPG_ERR_NO_DATA);
424         }
425       else if (opd->failure_code)
426         {
427           /* The engine returned failure code at program exit.  */
428           return opd->failure_code;
429         }
430       break;
431
432     case GPGME_STATUS_DECRYPTION_INFO:
433       err = parse_decryption_info (args, opd, ctx->protocol);
434       if (err)
435         return err;
436       break;
437
438     case GPGME_STATUS_DECRYPTION_OKAY:
439       opd->okay = 1;
440       break;
441
442     case GPGME_STATUS_DECRYPTION_FAILED:
443       opd->failed = 1;
444       /* Tell the data object that it shall not return any data.  We
445        * use the serial number because the data object may be owned by
446        * another thread.  We also don't check for an error because it
447        * is possible that the data object has already been destroyed
448        * and we are then not interested in returning an error.  */
449       if (!ctx->ignore_mdc_error)
450         _gpgme_data_set_prop (NULL, opd->plaintext_dserial,
451                               DATA_PROP_BLANKOUT, 1);
452       break;
453
454     case GPGME_STATUS_ERROR:
455       /* Note that this is an informational status code which should
456        * not lead to an error return unless it is something not
457        * related to the backend.  However, it is used to return a
458        * better matching final error code.  */
459       err = parse_status_error (args, opd);
460       if (err)
461         return err;
462       break;
463
464     case GPGME_STATUS_ENC_TO:
465       err = parse_enc_to (args, opd->last_recipient_p, ctx->protocol);
466       if (err)
467         return err;
468
469       opd->last_recipient_p = &(*opd->last_recipient_p)->next;
470       break;
471
472     case GPGME_STATUS_SESSION_KEY:
473       if (opd->result.session_key)
474         free (opd->result.session_key);
475       opd->result.session_key = strdup(args);
476       break;
477
478     case GPGME_STATUS_NO_SECKEY:
479       {
480         gpgme_recipient_t rec = opd->result.recipients;
481         while (rec)
482           {
483             if (!strcmp (rec->keyid, args))
484               {
485                 rec->status = gpg_error (GPG_ERR_NO_SECKEY);
486                 break;
487               }
488             rec = rec->next;
489           }
490         /* FIXME: Is this ok?  */
491         if (!rec)
492           return trace_gpg_error (GPG_ERR_INV_ENGINE);
493         opd->any_no_seckey = 1;
494       }
495       break;
496
497     case GPGME_STATUS_PLAINTEXT:
498       {
499         int mime = 0;
500         err = _gpgme_parse_plaintext (args, &opd->result.file_name, &mime);
501         if (err)
502           return err;
503         opd->result.is_mime = !!mime;
504       }
505       break;
506
507     case GPGME_STATUS_INQUIRE_MAXLEN:
508       if (ctx->status_cb && !ctx->full_status)
509         {
510           err = ctx->status_cb (ctx->status_cb_value, "INQUIRE_MAXLEN", args);
511           if (err)
512             return err;
513         }
514       break;
515
516     case GPGME_STATUS_DECRYPTION_COMPLIANCE_MODE:
517       PARSE_COMPLIANCE_FLAGS (args, &opd->result);
518       break;
519
520     default:
521       break;
522     }
523
524   return 0;
525 }
526
527
528 static gpgme_error_t
529 decrypt_status_handler (void *priv, gpgme_status_code_t code, char *args)
530 {
531   gpgme_error_t err;
532
533   err = _gpgme_progress_status_handler (priv, code, args);
534   if (!err)
535     err = _gpgme_decrypt_status_handler (priv, code, args);
536   return err;
537 }
538
539
540 gpgme_error_t
541 _gpgme_op_decrypt_init_result (gpgme_ctx_t ctx, gpgme_data_t plaintext)
542 {
543   gpgme_error_t err;
544   void *hook;
545   op_data_t opd;
546
547   err = _gpgme_op_data_lookup (ctx, OPDATA_DECRYPT, &hook,
548                                sizeof (*opd), release_op_data);
549   opd = hook;
550   if (err)
551     return err;
552
553   opd->last_recipient_p = &opd->result.recipients;
554   opd->plaintext_dserial = _gpgme_data_get_dserial (plaintext);
555   return 0;
556 }
557
558
559 gpgme_error_t
560 _gpgme_decrypt_start (gpgme_ctx_t ctx, int synchronous,
561                       gpgme_decrypt_flags_t flags,
562                       gpgme_data_t cipher, gpgme_data_t plain)
563 {
564   gpgme_error_t err;
565
566   assert (!(flags & GPGME_DECRYPT_VERIFY));
567
568   err = _gpgme_op_reset (ctx, synchronous);
569   if (err)
570     return err;
571
572   err = _gpgme_op_decrypt_init_result (ctx, plain);
573   if (err)
574     return err;
575
576   if (!cipher)
577     return gpg_error (GPG_ERR_NO_DATA);
578   if (!plain)
579     return gpg_error (GPG_ERR_INV_VALUE);
580
581   if (err)
582     return err;
583
584   if (ctx->passphrase_cb)
585     {
586       err = _gpgme_engine_set_command_handler
587         (ctx->engine, _gpgme_passphrase_command_handler, ctx);
588       if (err)
589         return err;
590     }
591
592   _gpgme_engine_set_status_handler (ctx->engine, decrypt_status_handler, ctx);
593
594   return _gpgme_engine_op_decrypt (ctx->engine,
595                                    flags,
596                                    cipher, plain,
597                                    ctx->export_session_keys,
598                                    ctx->override_session_key,
599                                    ctx->auto_key_retrieve);
600 }
601
602
603 gpgme_error_t
604 gpgme_op_decrypt_start (gpgme_ctx_t ctx, gpgme_data_t cipher,
605                         gpgme_data_t plain)
606 {
607   gpgme_error_t err;
608
609   TRACE_BEG  (DEBUG_CTX, "gpgme_op_decrypt_start", ctx,
610               "cipher=%p, plain=%p", cipher, plain);
611
612   if (!ctx)
613     return TRACE_ERR (gpg_error (GPG_ERR_INV_VALUE));
614
615   err = _gpgme_decrypt_start (ctx, 0, 0, cipher, plain);
616   return TRACE_ERR (err);
617 }
618
619
620 /* Decrypt ciphertext CIPHER within CTX and store the resulting
621    plaintext in PLAIN.  */
622 gpgme_error_t
623 gpgme_op_decrypt (gpgme_ctx_t ctx, gpgme_data_t cipher, gpgme_data_t plain)
624 {
625   gpgme_error_t err;
626
627   TRACE_BEG  (DEBUG_CTX, "gpgme_op_decrypt", ctx,
628               "cipher=%p, plain=%p", cipher, plain);
629
630   if (!ctx)
631     return TRACE_ERR (gpg_error (GPG_ERR_INV_VALUE));
632
633   err = _gpgme_decrypt_start (ctx, 1, 0, cipher, plain);
634   if (!err)
635     err = _gpgme_wait_one (ctx);
636   ctx->ignore_mdc_error = 0;  /* Always reset.  */
637   return TRACE_ERR (err);
638 }