cryptlib  3.4.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros
envelope.h
Go to the documentation of this file.
1 /****************************************************************************
2 * *
3 * Enveloping Routines Header File *
4 * Copyright Peter Gutmann 1996-2009 *
5 * *
6 ****************************************************************************/
7 
8 #ifndef _ENV_DEFINED
9 
10 #define _ENV_DEFINED
11 
12 #ifndef _STREAM_DEFINED
13  #if defined( INC_ALL )
14  #include "stream.h"
15  #else
16  #include "io/stream.h"
17  #endif /* Compiler-specific includes */
18 #endif /* _STREAM_DEFINED */
19 #ifdef USE_COMPRESSION
20  #if defined( INC_ALL )
21  #include "zlib.h"
22  #else
23  #include "zlib/zlib.h"
24  #endif /* Compiler-specific includes */
25 #endif /* USE_COMPRESSION */
26 
27 /****************************************************************************
28 * *
29 * Envelope Actions *
30 * *
31 ****************************************************************************/
32 
33 /* Types of actions that can be performed on a piece of envelope data. The
34  two key exchange actions are handled identically, but are given different
35  tags because we place PKC-based key exchange actions (which may be
36  handled automatically on de-enveloping) before conventional key exchange
37  actions (which usually require manual intervention for passphrases). For
38  this reason the actions are given in their sort order (i.e.
39  ACTION_KEYEXCHANGE_PKC precedes ACTION_KEYEXCHANGE in the action list).
40  The same occurs for the crypto actions ACTION_xxx, ACTION_CRYPT, and
41  ACTION_MAC, which when used for authenticated encryption are applied in
42  that order */
43 
44 typedef enum {
45  ACTION_NONE, /* Non-action */
46 
47  /* Pre-actions */
48  ACTION_KEYEXCHANGE_PKC, /* Generate/read PKC exchange information */
49  ACTION_KEYEXCHANGE, /* Generate/read key exchange information */
50 
51  /* Actions */
52  ACTION_xxx, /* Generic-secret XXX action */
53  ACTION_CRYPT, /* En/decrypt */
54  ACTION_MAC, /* MAC */
55  ACTION_COMPRESS, /* Compress */
56  ACTION_HASH, /* Hash */
57 
58  /* Post-actions */
59  ACTION_SIGN, /* Generate/check signature */
60 
61  ACTION_LAST /* Last valid action type */
62  } ACTION_TYPE;
63 
64 /* An 'action list' that defines what we need to do to the content when
65  enveloping data. There are three action lists, one for actions to perform
66  before enveloping data, one to perform during enveloping (which is
67  actually just a single action rather than a list), and one to perform
68  after enveloping. ACTION_KEYEXCHANGE and ACTION_KEYEXCHANGE_PKC are found
69  in the pre-enveloping list, ACTION_SIGN in the post-enveloping list, and
70  everything else in the during-enveloping list.
71 
72  Some actions are many-to-one, in which a number of controlling actions in
73  one list may act on a single subject action in another list (for example a
74  number of signature actions may sign the output from a single hash
75  action). This is handled by having the controlling actions maintain
76  pointers to the subject action, for example a number of key export actions
77  would point to one encryption action, with the export actions exporting
78  the session key for the encryption action.
79 
80  The ACTION_NEEDSCONTROLLER flag records whether this is a subject action
81  that still requires a controlling action. This allows us to identify
82  unused subject actions more easily than by scanning all controller->
83  subject relationships.
84 
85  The ACTION_ADDEDAUTOMATICALLY flag records whether a subject action was
86  added automatically and invisibly to the caller as a result of adding a
87  controlling action, for example a hash action created when a signing
88  action is added. This is to ensure that we don't return an error the
89  first time the caller adds an action which is identical to an
90  automatically added action */
91 
92 #define ACTION_NEEDSCONTROLLER 0x01 /* Whether action reqs.controller */
93 #define ACTION_ADDEDAUTOMATICALLY 0x02 /* Whether action added automat.*/
94 
95 typedef struct AI {
96  /* Control and status information */
97  ACTION_TYPE action; /* Type of action to perform */
98  int flags; /* Action flags */
99  struct AI *next; /* Next item in the list */
100 
101  /* The controlling/subject action. This points to the subject action
102  associated with a controlling action if this is a controlling
103  action */
104  struct AI *associatedAction; /* Associated action */
105 
106  /* Information related to the action. These fields contain various
107  pieces of information required as part of the action. The crypt
108  handle contains the encryption context needed to perform the action
109  (e.g. encryption, hashing, signing). If we're generating CMS
110  signatures, there may be extra attribute data present which is
111  included in the signature, and we may also have countersignature
112  information present, typically a timestamping session object */
113  CRYPT_CONTEXT iCryptHandle; /* Encryption handle for action */
114  CRYPT_CERTIFICATE iExtraData; /* Extra attribute data for CMS sigs.*/
115  CRYPT_SESSION iTspSession; /* Timestamping session object */
116  int encodedSize; /* The encoded size of the action */
117  } ACTION_LIST;
118 
119 /* Result codes for the checkAction() function when adding an action to
120  an action list. The two 'action present' results are for the case where
121  the action is already present and shouldn't be added again, and where the
122  action is present from being added as an (invisible to the user) side-
123  effect of another action being added, so that this attempt to add it
124  should be reported as CRYPT_OK rather than CRYPT_INITED */
125 
126 typedef enum {
127  ACTION_RESULT_OK, /* Action not present, can be added */
128  ACTION_RESULT_EMPTY, /* Action list is empty */
129  ACTION_RESULT_INITED, /* Action present (CRYPT_ERROR_INITED) */
130  ACTION_RESULT_PRESENT, /* Action present (CRYPT_OK) */
131  ACTION_RESULT_ERROR, /* Arg.error (CRYPT_ARGERROR_NUM1) */
132  ACTION_RESULT_LAST /* Last valid action result type */
133  } ACTION_RESULT;
134 
135 /* Envelope content information types */
136 
137 typedef enum {
138  CONTENT_NONE, /* No content type */
139  CONTENT_CRYPT, /* Encrypted content info */
140  CONTENT_AUTHENC, /* Auth-enc content info */
141  CONTENT_SIGNATURE, /* Signed content info */
142  CONTENT_LAST /* Last valid content type */
143  } CONTENT_TYPE;
144 
145 /* Content information flags. These are:
146 
147  CONTENTLIST_PROCESSED: The signature object has been processed by having
148  the signature verified (or at least attempted to be verified).
149  The verification result is stored/cached with the content info
150  for later use.
151 
152  CONTENTLIST_EXTERNALKEY: The signature-check key was supplied by the user
153  rather than being instantiated internally from certificates
154  associated with the signature */
155 
156 #define CONTENTLIST_PROCESSED 0x01 /* Whether object has been processed */
157 #define CONTENTLIST_EXTERNALKEY 0x02 /* Whether key was added externally */
158 
159 /* A 'content list' which is used to store objects found in the non-data
160  portion of the envelope until we can do something with them when de-
161  enveloping data */
162 
163 #define clEncrInfo contentInfo.contentEncrInfo
164 #define clSigInfo contentInfo.contentSigInfo
165 #define clAuthEncInfo contentInfo.contentAuthEncInfo
166 
167 typedef struct {
168  /* Signature algorithm/key information */
169  CRYPT_ALGO_TYPE hashAlgo; /* Hash algo.for signed data */
170  CRYPT_HANDLE iSigCheckKey; /* Signature check key */
171 
172  /* Authenticated/unauthenticated attribute information */
173  CRYPT_CERTIFICATE iExtraData; /* Authent.attrib.in CMS signatures */
174  BUFFER_OPT_FIXED( extraDataLength ) \
175  const void *extraData; /* Authent.attrib.in PGP signatures */
177  CRYPT_ENVELOPE iTimestamp; /* Unauth.attrib.in CMS signatures */
178  BUFFER_OPT_FIXED( extraData2Length ) \
179  const void *extraData2; /* Unauthenticated attributes */
181 
182  /* We only need to process a signed object once, once we've done this we
183  store the processing result so that any further attempts to process
184  the object will return the previously obtained result (an object can
185  be processed multiple times if the user wanders up and down the
186  content list using the cursor management capabilities) */
187  int processingResult; /* Result of processing */
188 
189  /* To allow positioning of the cursor within this item (== attribute
190  group), we have to keep track of the virtual position within the
191  group. The virtual attribute order is result -> key -> auth.
192  attr -> timestamp */
195 
196 typedef struct {
197  /* Encryption algorithm/key information */
198  CRYPT_ALGO_TYPE cryptAlgo; /* Encryption algo.for this object */
199  CRYPT_MODE_TYPE cryptMode; /* Encrytion mode for this object */
200 
201  /* Encryption key setup information */
202  BUFFER( CRYPT_MAX_HASHSIZE, saltOrIVsize ) \
203  BYTE saltOrIV[ CRYPT_MAX_HASHSIZE + 8 ];/* Salt for password-derived key or */
204  int saltOrIVsize; /* IV for session encr.context */
205  CRYPT_ALGO_TYPE keySetupAlgo; /* Hash algo.for pw-derived key */
206  int keySetupIterations; /* Iterations for pw-derived key */
207  int keySize; /* Key size (if not implicit) */
209 
210 typedef struct {
211  /* Authenticated-encryption algorithm information */
212  CRYPT_ALGO_TYPE authEncAlgo; /* AuthEnc algo.for this object */
213 
214  /* Authenticated encryption algorithm parameter data */
215  BUFFER( 128, authEncParamLength ) \
216  BYTE authEncParamData[ 128 + 8 ];
217  int authEncParamLength; /* AuthEnc parameter data */
218  BUFFER_FIXED( encParamDataLength ) \
219  void *encParamData;
220  int encParamDataLength; /* Encryption algorithm params */
221  BUFFER_FIXED( macParamDataLength ) \
222  void *macParamData;
223  int macParamDataLength; /* MAC algorithm params */
225 
226 typedef struct CL {
227  /* Control and status information */
228  CONTENT_TYPE type; /* Content type enc/authenc/sig */
229  CRYPT_ATTRIBUTE_TYPE envInfo; /* Env.info required to continue */
230  CRYPT_FORMAT_TYPE formatType; /* Data format */
231  int flags; /* Item flags */
232  struct CL *prev, *next; /* Prev, next items in the list */
233 
234  /* The object contained in this list element. All object type-specific
235  pointers in the xxxInfo data point into fields inside this data */
237  const void *object; /* The object data */
238  int objectSize; /* Size of the object */
239 
240  /* Details on the object. Here we store whatever is required to process
241  the object without having to call queryXXXObject() for the details */
243  BYTE keyID[ CRYPT_MAX_HASHSIZE + 8 ];/* cryptlib key ID */
246  const void *issuerAndSerialNumber;/* CMS key ID */
249  const void *payload; /* Payload data (e.g. encr.key) */
251  union {
252  CONTENT_ENCR_INFO contentEncrInfo; /* Encryption obj-specific infor.*/
253  CONTENT_SIG_INFO contentSigInfo; /* Signature obj-specific info.*/
254  CONTENT_AUTHENC_INFO contentAuthEncInfo;/* Auth-enc obj-spec.info */
255  } contentInfo;
256  } CONTENT_LIST;
257 
258 /****************************************************************************
259 * *
260 * De-envelope Actions *
261 * *
262 ****************************************************************************/
263 
264 /* The current state of the (de)enveloping. The states are the predata state
265  (when we're performing final setup steps and handling header information
266  in the envelope), the data state (when we're enveloping data), the
267  postdata state (when we're handling trailer information), and the
268  extradata state (when we're processing out-of-band data such as the data
269  associated with detached signatures) */
270 
271 typedef enum {
272  STATE_PREDATA, /* Emitting header information */
273  STATE_DATA, /* During (de)enveloping of data */
274  STATE_POSTDATA, /* After (de)enveloping of data */
275  STATE_EXTRADATA, /* Additional out-of-band data */
276  STATE_FINISHED, /* Finished processing */
277  STATE_LAST /* Last valid enveloping state */
278  } ENVELOPE_STATE;
279 
280 /* The current state of the processing of CMS headers that contain non-data
281  during the enveloping process. Before the enveloping of data begins, the
282  user pushes in a variety of enveloping information, which in turn might
283  trigger the creation of more internal information objects. Once the
284  enveloping begins, this information is encoded as ASN.1 structures and
285  written into the envelope buffer. The encoding process can be interrupted
286  at any point when the envelope buffer fills up, so we break it down into a
287  series of atomic states between which the enveloping process can be
288  interrupted by the caller removing data from the envelope.
289 
290  There are two sets of states, the first set that covers the encoding of
291  the header information at the start of the envelope (only key exchange
292  information requires this), and the second that covers the information at
293  the end of the envelope (only signatures require this) */
294 
295 typedef enum {
296  ENVSTATE_NONE, /* No header processing/before header */
297 
298  /* Header state information */
299  ENVSTATE_HEADER, /* Emitting header */
300  ENVSTATE_KEYINFO, /* Emitting key exchange information */
301  ENVSTATE_ENCRINFO, /* Emitting EncrContentInfo information */
302 
303  ENVSTATE_DATA, /* Emitting data payload information */
304 
305  /* Trailer state information */
306  ENVSTATE_FLUSHED, /* Data flushed through into buffer */
307  ENVSTATE_SIGNATURE, /* Emitting signatures */
308 
309  ENVSTATE_DONE, /* Finished processing header/trailer */
310 
311  ENVSTATE_LAST /* Last valid enveloping state */
312  } ENV_STATE;
313 
314 /* The current state of the processing of CMS headers that contain non-data
315  in the envelope during the de-enveloping process. This is implemented as
316  a somewhat complex FSM because the enveloping routines give the user the
317  ability to push in arbitrary amounts of data corresponding to various
318  enveloping structures and simultaneously pop out data/information based
319  on decoding them. A typical complex enveloped type might contain a
320  number of headers, a session key encrypted with 18 different public keys,
321  five varieties of signature type, and God knows what else, of which the
322  caller might feed us 500 bytes - a small fraction of the total data - and
323  then ask for information on what they've just fed us. We have to
324  remember how far we got (halfway through an RSA-encrypted DES key fifteen
325  levels of nesting down in an ASN.1 structure), process everything that we
326  can, and then get back to them on what we found. Then they feed us
327  another few hundred bytes and the whole thing starts anew.
328 
329  The state machine works by processing one complete object or part of an
330  object at a time and then moving on to the next state that corresponds to
331  handling another part of the object or another object. If there isn't
332  enough data present to process a part or subpart, we return an underflow
333  error and try again when more data is added */
334 
335 typedef enum {
336  DEENVSTATE_NONE, /* No header processing/before header */
337 
338  /* Header state information */
339  DEENVSTATE_SET_ENCR, /* Processing start of SET OF EncrKeyInfo */
340  DEENVSTATE_ENCR, /* Processing EncrKeyInfo records */
341  DEENVSTATE_ENCRCONTENT, /* Processing EncrContentInfo */
342 
343  DEENVSTATE_SET_HASH, /* Processing start of SET OF DigestAlgoID */
344  DEENVSTATE_HASH, /* Processing DigestAlgoID records */
345  DEENVSTATE_CONTENT, /* Processing ContentInfo */
346 
347  DEENVSTATE_DATA, /* Processing data payload */
348 
349  /* Trailer state information */
350  DEENVSTATE_CERTSET, /* Processing optional cert chain */
351  DEENVSTATE_SET_SIG, /* Processing start of SET OF Signature */
352  DEENVSTATE_SIG, /* Processing Signature records */
353  DEENVSTATE_EOC, /* Processing end-of-contents octets */
354 
355  DEENVSTATE_DONE, /* Finished processing header/trailer */
356 
357  DEENVSTATE_LAST /* Last valid de-enveloping state */
358  } DEENV_STATE;
359 
360 /* The current state of processing of PGP headers that contain non-data in
361  the envelope during the de-enveloping process. These are somewhat
362  different to the ASN.1-encoded objects used by cryptlib in that many of
363  the objects are emitted as discrete packets rather than the nested
364  objects used in ASN.1 objects. This makes some parts of the processing
365  much easier (less length information to track) and some parts much harder
366  (since just about anything could appear next, you need to maintain a
367  lookahead to figure out what to do next, but you may run out of data
368  before you can determine which state is next). The handling of content
369  inside encrypted data is particularly messy since there's a plain-data
370  header that has to be removed in a manner which is transparent to the
371  user.
372 
373  The two de-enveloping encrypted-data states are almost identical except
374  for the fact that one performs PGP's odd IV resync while the other
375  doesn't, a requirement buried in the depths of two otherwise identical
376  text blocks in the RFC */
377 
378 typedef enum {
379  PGP_DEENVSTATE_NONE, /* No message processing/before message */
380 
381  /* Header state information */
382  PGP_DEENVSTATE_ENCR, /* Encrypted data packet */
383  PGP_DEENVSTATE_ENCR_MDC, /* Encrypted data with MDC */
384 
386  PGP_DEENVSTATE_DATA_HEADER, /* Out-of-band data inside compressed data */
387 
388  PGP_DEENVSTATE_DONE, /* Finished processing message */
389 
390  PGP_DEENVSTATE_LAST /* Last valid de-enveloping state */
391  } PGP_DEENV_STATE;
392 
393 /* Envelope information flags. These are:
394 
395  ENVELOPE_ISDEENVELOPE: The envelope is a de-enveloping envelope.
396 
397  ENVELOPE_DETACHED_SIG: The (signed data) envelope should generate a
398  standalone detached signature rather than signed enveloped data.
399 
400  ENVELOPE_NOSIGNINGCERTS: When generating a S/MIME signed data, don't
401  include the signing certificates with the data.
402 
403  ENVELOPE_ATTRONLY: The (signed data) envelope only contains authenticated
404  attributes, but not actual data. This is required by SCEP.
405 
406  ENVELOPE_ZSTREAMINITED: Whether the zlib compression/decompression stream
407  has been initialised.
408 
409  ENVELOPE_AUTHENC: Use authenticated encryption, which adds a MAC tag to
410  the encrypted data */
411 
412 #define ENVELOPE_ISDEENVELOPE 0x0001 /* De-enveloping envelope */
413 #define ENVELOPE_DETACHED_SIG 0x0002 /* Generate detached signature */
414 #define ENVELOPE_NOSIGNINGCERTS 0x0004 /* Don't include signing certs */
415 #define ENVELOPE_ATTRONLY 0x0008 /* Env.contains only auth'd attrs.*/
416 #define ENVELOPE_ZSTREAMINITED 0x0010 /* Whether zlib stream has been inited */
417 #define ENVELOPE_AUTHENC 0x0020 /* Use authenticated encryption */
418 
419 /* Envelope data processing flags. These are:
420 
421  ENVDATA_AUTHENACTIONSACTIVE: The (authenticated-encrypted) envelope is
422  currently hashing payload data. This differs from
423  HASHACTIONSACTIVE in that it hashes ciphertext, not plaintext.
424 
425  ENVDATA_HASINDEFTRAILER: The (signed) envelope trailer has an indefinite
426  length due to the use of signature algorithms that produce
427  variable-length output that can't be determined in advance.
428 
429  ENVDATA_HASHACTIONSACTIVE: The (signed) envelope is currently hashing
430  payload data. This differs from AUTHENCACTIONSACTIVE in that
431  it hashes plaintext, not ciphertext.
432 
433  ENVDATA_NOLENGTHINFO: The payload uses neither a definite- nor
434  indefinite-length encoding but continues until the caller tells
435  us it's finished. This is used to handle PGP 2.x compressed
436  data, which just continues until EOF with no length information
437  provided.
438 
439  ENVDATA_NOSEGMENT: The payload data shouldn't be segmented because a
440  definite-length encoding is being used.
441 
442  ENVDATA_SEGMENTCOMPLETE: An indefinite-length segment has been completed
443  an another one must be begun before more payload data can be
444  emitted.
445 
446  ENVDATA_ENDOFCONTENTS: The EOC octets on indefinite payload data have
447  been reached.
448 
449  ENVDATA_NEEDSPADDING: Before (encrypted) enveloping can been completed
450  the payload data needs PKCS #5 padding added to it.
451 
452  ENVDATA_HASATTACHEDOOB: The envelope has out-of-band additional data
453  attached to the payload data. This is used by OpenPGP to tack
454  an MDC packet onto the end of encrypted data.
455 
456  The handling of several of these flags is quite complex, more details can
457  be found in encode/decode.c */
458 
459 #define ENVDATA_HASINDEFTRAILER 0x0001 /* Whether trailer size is indefinite */
460 #define ENVDATA_HASHACTIONSACTIVE 0x0002 /* Payload hashing is active */
461 #define ENVDATA_AUTHENCACTIONSACTIVE 0x0004 /* Payload ciphertext hashing active */
462 #define ENVDATA_NOLENGTHINFO 0x0008 /* No length info for payload avail.*/
463 #define ENVDATA_NOSEGMENT 0x0010 /* Don't segment payload data */
464 #define ENVDATA_SEGMENTCOMPLETE 0x0020 /* Current segment has been completed */
465 #define ENVDATA_ENDOFCONTENTS 0x0040 /* EOC reached */
466 #define ENVDATA_NEEDSPADDING 0x0080 /* Whether to add PKCS #5 padding */
467 #define ENVDATA_HASATTACHEDOOB 0x0100 /* Whether data has attached OOB extra */
468 
469 /* Envelope data-copy flags. These are:
470 
471  ENVCOPY_FLAG_NONE: Perform no special processing.
472 
473  ENVCOPY_FLAG_OOBDATA: Data is out-of-band data that isn't part of the
474  normal data payload */
475 
476 #define ENVCOPY_FLAG_NONE 0x00 /* No special action */
477 #define ENVCOPY_FLAG_OOBDATA 0x01 /* Data is OOB rather than payload data */
478 
479 /* The size of the buffer used to handle read-ahead into out-of-band data at
480  the start of the payload */
481 
482 #define OOB_BUFFER_SIZE 8
483 
484 /* The structure that stores the information on an envelope */
485 
486 typedef struct EI {
487  /* Control and status information */
488  CRYPT_FORMAT_TYPE type; /* Envelope type */
489  CRYPT_CONTENT_TYPE contentType; /* Inner content type */
490  ACTION_TYPE usage; /* Usage (signing, encryption, etc) */
491  int version; /* Protocol version/subtype */
492  int flags; /* Envelope information flags */
493  int dataFlags; /* Envelope data processing flags */
494 
495  /* The list of actions to perform on the data. There are three sets of
496  actions, the preActions (key exchange), the main actions (encryption
497  or hashing), and the postActions (signing) */
501 
502  /* Several action groups produce information which is prepended or
503  appended to the data. The following variables record the encoded size
504  of this information. In some cases the size of the appended
505  information isn't known when the enveloping is started so we have to
506  use an indefinite-length encoding for the outermost wrapper, if this
507  is the case then we set the ENVDATA_HASINDEFTRAILER flag to indicate
508  that a definite-length encoding shouldn't be used even if the payload
509  size is known */
510  int cryptActionSize; /* Size of key exchange actions */
511  int signActionSize; /* Size of signatures */
512  int extraDataSize; /* Size of any extra data */
513 
514  /* When prepending or appending header or trailer information to an
515  envelope we need to record the current position in the action list so
516  that we can continue later if we run out of room */
518 
519  /* When de-enveloping we may have objects present that can't be used
520  until user-supplied de-enveloping information is added to the
521  envelope. We store these in a linked list in memory until the
522  information needed to work with them is present. We also store a
523  pointer to the current position in the list, which is used when
524  traversing the list */
526 
527  /* The public-key encryption/private-key decryption and signature-check
528  keysets that are used to look up any keys required during the
529  enveloping/de-enveloping process */
533 
534  /* When we're encrypting/decrypting the envelope payload, the one action
535  that we'll be performing constantly is encryption. Similarly, when
536  we're signing/sig.checking, we'll be hashing the payload. In order
537  to make this process more efficientm, we record the encryption and
538  hashing info here to save having to pull it out of the action list
539  whenever it's needed.
540 
541  The encryption context, of which there's only one, is stored here.
542  Note that since there is a second reference held in the action list,
543  there's no need to explicitly delete this when we destroy the
544  envelope object since it's already been destroyed when the action
545  list is destroyed.
546 
547  For hashing, we may have multiple hash contexts active, so we still
548  use the action list for these. However it's convenient to have
549  direct confirmation that we have to hash the payload data to save
550  having to check the action list each time, so we set the
551  ENVDATA_HASHACTIONSACTIVE flag to indicate that hashing is taking
552  place. This is only set while the hashing is taking place, once
553  there's no more data to be hashed it's cleared to prevent out-of-band
554  data from being hashed as well */
556 
557  /* Some types of key management/signature require additional certs.
558  For encryption, there may be originator certs present for use with
559  key agreement algorithms; for signing, there may be a signing-cert
560  meta-object present to contain the union of multiple sets of signing
561  certs if multiple signatures are present. These are held in the
562  following certificate object */
564 
565  /* The encryption/hashing/signature defaults for this envelope. These
566  are recorded here when the envelope is created (so that a later
567  change of the default value won't affect the enveloping process) but
568  can be changed explicitly on a per-envelope basis by setting the
569  options just for the envelope rather than for all of cryptlib */
570  CRYPT_ALGO_TYPE defaultHash; /* Default hash algorithm */
571  CRYPT_ALGO_TYPE defaultAlgo; /* Default encryption algorithm */
572  CRYPT_ALGO_TYPE defaultMAC; /* Default MAC algorithm */
573 
574 #ifdef USE_COMPRESSION
575  /* zlib stream compression data structure used to hold the compression/
576  decompression state */
577  z_stream zStream; /* zlib state variable */
578 #endif /* USE_COMPRESSION */
579 
580  /* Buffer information */
581  BUFFER( bufSize, bufPos ) \
582  BYTE *buffer; /* Data buffer */
583  int bufSize; /* Total buffer size */
584  int bufPos; /* Last data position in buffer */
585 
586  /* Auxiliary buffer used as a staging area for holding signature data
587  that may not currently fit into the main buffer. These are generated
588  into the auxiliary buffer and then copied into the main buffer as
589  required */
591  BYTE *auxBuffer; /* Buffer for sig.data */
592  int auxBufSize, auxBufPos; /* Current pos and total aux.buf.size */
593 
594  /* When the caller knows in advance how large the payload will be, they
595  can advise the enveloping code of this, which allows a more efficient
596  encoding of the data. The following variable records the payload
597  size */
599 
600  /* The current state of header processing. The cryptlib/CMS and PGP
601  processing states are kept separate (although they could actually be
602  merged into the same variable) because they are conceptually separate
603  and shouldn't really be treated as the same thing */
604  ENVELOPE_STATE state; /* Current state of processing */
605  ENV_STATE envState; /* Current state of env.non-data proc.*/
606  DEENV_STATE deenvState; /* Current state of de-env.non-data proc.*/
607 #ifdef USE_PGP
608  PGP_DEENV_STATE pgpDeenvState; /* Current state of PGP de-env.n-d proc.*/
609 #endif /* USE_PGP */
610  long hdrSetLength; /* Remaining bytes in SET OF EKeyInfo */
611 
612  /* Some data formats place out-of-band data at the start of the payload
613  rather than putting it in the header, the data-left variable keeps
614  track of how many bytes of data still need to be removed before we
615  can return actual payload data to the caller. In some cases the
616  amount of data can't be specified as a simple byte count but involves
617  format-specific events (e.g. the presence of a flag or data count in
618  the OOB data that indicates that there's more data present), the
619  event-count variable records how many of these events still need to
620  be handled before we can return data to the caller. Finally, some
621  content types (e.g. compressed data) don't allow lookahead reads,
622  which are necessary in some cases to determine how the payload needs
623  to be handled. To handle this we have to remember the returned OOB
624  data (if it's read via a lookahead read) so that we can reinsert it
625  into the output stream on the next read call */
626  int oobDataLeft; /* Remaining out-of-band data in payload */
627  int oobEventCount; /* No.events left to process */
629  BYTE oobBuffer[ OOB_BUFFER_SIZE + 8 ]; /* Buffered OOB data */
631 
632  /* Information on the current OCTET STRING segment in the buffer during
633  the de-enveloping process. We keep track of the segment start point
634  (the byte after the OCTET STRING tag), the segment data start point
635  (which may move when the segment is terminated if the length encoding
636  shrinks due to a short segment), and whether we've just completed a
637  segment (which we need to do before we can pop any data from the
638  envelope, this is tracked via the ENVDATA_SEGMENTCOMPLETE flag). In
639  addition we track where the last completed segment ends, as the buffer
640  may contain one or more completed segments followed by an incomplete
641  segment, and any attempt to read into the incomplete segment will
642  require it to be completed first */
643  int segmentStart; /* Segment len+data start point */
644  int segmentDataStart; /* Segment data start point */
645  int segmentDataEnd; /* End of completed data */
646 
647  /* The remaining data in the current OCTET STRING segment, explicitly
648  declared as a long since we may be processing data that came from a
649  32-bit machine on a 16-bit machine. During enveloping this is used
650  to track the amount of data left from the user-declared payloadSize
651  that can still be added to the envelope. During de-enveloping, it's
652  used to record how much data is left in the current segment */
653  long segmentSize; /* Remaining data in segment */
654 
655  /* Once the low-level segment-processing code sees the end-of-contents
656  octets for the payload, we need to notify the higher-level code that
657  anything that follows is out-of-band data that needs to be processed
658  at a higher level. We do this by setting the ENVDATA_ENDOFCONTENTS
659  flag to record the fact that we've seen the payload EOC and have
660  moved to trailing out-of-band data. Since the post-payload data
661  isn't directly retrievable by the user, we use the dataLeft variable
662  to keep track of how much of what's left in the envelope is payload
663  that can be copied out */
664  int dataLeft;
665 
666  /* Block cipher buffer for leftover bytes. This contains any bytes
667  remaining to be en/decrypted when the input data size isn't a
668  multiple of the cipher block size */
670  BYTE blockBuffer[ CRYPT_MAX_IVSIZE + 8 ];/* Leftover byte buffer */
671  int blockBufferPos; /* Position in buffer */
672  int blockSize; /* Cipher block size */
673  int blockSizeMask; /* Mask for blockSize-sized blocks */
674 
675  /* The overall envelope status. Some error states (underflow/overflow
676  enveloping information errors, randomness errors, and a few others)
677  are recoverable whereas other states (bad data) aren't recoverable.
678  If we run into a nonrecoverable error, we remember the status here so
679  that any further attempts to work with the envelope will return this
680  status */
682 
683  /* Error information */
685  CRYPT_ERRTYPE_TYPE errorType; /* Error type */
686 
687  /* Low-level error information */
689 
690  /* Pointers to the enveloping/de-enveloping functions */
692  int ( *addInfo )( INOUT struct EI *envelopeInfoPtr,
694  IN_INT_Z const int value );
696  int ( *addInfoString )( INOUT struct EI *envelopeInfoPtr,
700  IN_BUFFER( valueLength ) const void *value,
702  const int valueLength );
704  int ( *checkMissingInfo )( INOUT struct EI *envelopeInfoPtr );
709  int ( *processPreambleFunction )( INOUT struct EI *envelopeInfoPtr );
711  int ( *processPostambleFunction )( INOUT struct EI *envelopeInfoPtr,
714  int ( *copyToEnvelopeFunction )( INOUT struct EI *envelopeInfoPtr,
717  CHECK_RETVAL_FNPTR STDC_NONNULL_ARG( ( 1, 2, 4 ) ) \
718  int ( *copyFromEnvelopeFunction )( INOUT struct EI *envelopeInfoPtr,
719  OUT_BUFFER( maxLength, length ) BYTE *buffer,
720  IN_LENGTH const int maxLength,
721  OUT_LENGTH_Z int *length,
722  IN_FLAGS( ENVCOPY ) const int flags );
723  CHECK_RETVAL_FNPTR STDC_NONNULL_ARG( ( 1, 2 ) ) \
724  int ( *processExtraData )( INOUT struct EI *envelopeInfoPtr,
725  IN_BUFFER( length ) const void *buffer,
726  IN_LENGTH const int length );
727  CHECK_RETVAL_FNPTR STDC_NONNULL_ARG( ( 1, 2 ) ) \
728  int ( *syncDeenvelopeData )( INOUT struct EI *envelopeInfoPtr,
730 
731  /* The object's handle and the handle of the user who owns this object.
732  The former is used when sending messages to the object when only the
733  xxx_INFO is available, the latter is used to avoid having to fetch the
734  same information from the system object table */
737 
738  /* The local memory pool used to allocate small data objects attached to
739  the envelope */
741 
742  /* Variable-length storage for the type-specific data */
744  } ENVELOPE_INFO;
745 
746 /****************************************************************************
747 * *
748 * Enveloping Functions *
749 * *
750 ****************************************************************************/
751 
752 /* Envelope attribute handling functions */
753 
754 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
755 int getEnvelopeAttribute( INOUT ENVELOPE_INFO *envelopeInfoPtr,
758 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
759 int getEnvelopeAttributeS( INOUT ENVELOPE_INFO *envelopeInfoPtr,
762 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
763 int setEnvelopeAttribute( INOUT ENVELOPE_INFO *envelopeInfoPtr,
764  IN_INT_Z const int value,
766 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
767 int setEnvelopeAttributeS( INOUT ENVELOPE_INFO *envelopeInfoPtr,
768  IN_BUFFER( dataLength ) const void *data,
771 
772 
773 /* Prototypes for envelope action management functions */
774 
775 typedef CHECK_RETVAL_FNPTR STDC_NONNULL_ARG( ( 1 ) ) \
776  int ( *CHECKACTIONFUNCTION )( const ACTION_LIST *actionListPtr,
778 
781 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
782 int addAction( OUT_PTR ACTION_LIST **actionListHeadPtrPtr,
783  INOUT MEMPOOL_STATE memPoolState,
784  IN_ENUM( ACTION ) const ACTION_TYPE actionType,
786 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 3 ) ) \
787 int addActionEx( OUT_OPT_PTR_OPT ACTION_LIST **newActionPtrPtr,
788  OUT_PTR ACTION_LIST **actionListHeadPtrPtr,
789  INOUT MEMPOOL_STATE memPoolState,
790  IN_ENUM( ACTION ) const ACTION_TYPE actionType,
791  IN_HANDLE const CRYPT_HANDLE cryptHandle );
792 CHECK_RETVAL_ENUM( ACTION ) \
793 ACTION_RESULT checkAction( IN_OPT const ACTION_LIST *actionListStart,
794  IN_ENUM( ACTION ) const ACTION_TYPE actionType,
795  IN_HANDLE const CRYPT_HANDLE cryptHandle );
796 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
797 int checkActionIndirect( const ACTION_LIST *actionListStart,
798  IN CHECKACTIONFUNCTION checkActionFunction,
799  IN_INT_Z const int intParam );
802  IN_ENUM( ACTION ) const ACTION_TYPE actionType );
803 CHECK_RETVAL_PTR STDC_NONNULL_ARG( ( 1 ) ) \
804 ACTION_LIST *findLastAction( const ACTION_LIST *actionListPtr,
805  IN_ENUM( ACTION ) \
806  const ACTION_TYPE actionType );
807 CHECK_RETVAL_PTR STDC_NONNULL_ARG( ( 1, 2 ) ) \
808 ACTION_LIST *findActionIndirect( const ACTION_LIST *actionListStart,
809  IN CHECKACTIONFUNCTION checkActionFunction,
810  IN_INT_Z const int intParam );
811 STDC_NONNULL_ARG( ( 1, 2 ) ) \
812 void deleteActionList( INOUT MEMPOOL_STATE memPoolState,
813  INOUT ACTION_LIST *actionListPtr );
814 STDC_NONNULL_ARG( ( 1 ) ) \
815 int deleteUnusedActions( INOUT ENVELOPE_INFO *envelopeInfoPtr );
816 CHECK_RETVAL_BOOL STDC_NONNULL_ARG( ( 1 ) ) \
817 BOOLEAN checkActions( INOUT ENVELOPE_INFO *envelopeInfoPtr );
818 
819 /* Prototypes for content list management functions */
820 
823 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
824 int createContentListItem( OUT_PTR CONTENT_LIST **newContentListItemPtrPtr,
825  INOUT MEMPOOL_STATE memPoolState,
826  IN_ENUM( CONTENT ) const CONTENT_TYPE type,
827  IN_ENUM( CRYPT_FORMAT ) \
829  IN_BUFFER_OPT( objectSize ) const void *object,
831 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
832 int appendContentListItem( INOUT ENVELOPE_INFO *envelopeInfoPtr,
834 STDC_NONNULL_ARG( ( 1, 2 ) ) \
835 int deleteContentList( INOUT MEMPOOL_STATE memPoolState,
837 
838 /* Prototypes for misc.management functions */
839 
840 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
841 int addKeysetInfo( INOUT ENVELOPE_INFO *envelopeInfoPtr,
842  IN_RANGE( CRYPT_ENVINFO_KEYSET_ENCRYPT, \
844  const CRYPT_ATTRIBUTE_TYPE keysetFunction,
848  IN_MODE_OPT const CRYPT_MODE_TYPE cryptMode );
851  IN_MODE_OPT const CRYPT_MODE_TYPE cryptMode );
852 
853 /* Prepare the envelope for data en/decryption */
854 
855 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
856 int initEnvelopeEncryption( INOUT ENVELOPE_INFO *envelopeInfoPtr,
863 
864 /* Prototypes for enveloping internal functions */
865 
866 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
867 int cmsPreEnvelopeEncrypt( INOUT ENVELOPE_INFO *envelopeInfoPtr );
868 CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \
869 int cmsPreEnvelopeSign( INOUT ENVELOPE_INFO *envelopeInfoPtr );
870 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2 ) ) \
871 int hashEnvelopeData( const ACTION_LIST *hashActionPtr,
872  IN_BUFFER( dataLength ) const void *data,
873  IN_LENGTH const int dataLength );
874 CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 4 ) ) \
875 int cmsInitSigParams( const ACTION_LIST *actionListPtr,
876  IN_ENUM( CRYPT_FORMAT ) const CRYPT_FORMAT_TYPE formatType,
879 
880 /* Prototypes for envelope mapping functions */
881 
882 #ifdef USE_CMS
883  STDC_NONNULL_ARG( ( 1 ) ) \
884  void initCMSEnveloping( INOUT ENVELOPE_INFO *envelopeInfoPtr );
885  STDC_NONNULL_ARG( ( 1 ) ) \
886  void initCMSDeenveloping( INOUT ENVELOPE_INFO *envelopeInfoPtr );
887 #else
888  #define initCMSEnveloping( envelopeInfoPtr )
889  #define initCMSDeenveloping( envelopeInfoPtr )
890 #endif /* USE_CMS */
891 #ifdef USE_PGP
892  STDC_NONNULL_ARG( ( 1 ) ) \
893  void initPGPEnveloping( INOUT ENVELOPE_INFO *envelopeInfoPtr );
894  STDC_NONNULL_ARG( ( 1 ) ) \
895  void initPGPDeenveloping( INOUT ENVELOPE_INFO *envelopeInfoPtr );
896 #else
897  #define initPGPEnveloping( envelopeInfoPtr )
898  #define initPGPDeenveloping( envelopeInfoPtr )
899 #endif /* USE_PGP */
900 STDC_NONNULL_ARG( ( 1 ) ) \
901 void initEnvelopeStreaming( INOUT ENVELOPE_INFO *envelopeInfoPtr );
902 STDC_NONNULL_ARG( ( 1 ) ) \
903 void initEnvResourceHandling( INOUT ENVELOPE_INFO *envelopeInfoPtr );
904 STDC_NONNULL_ARG( ( 1 ) ) \
905 void initDeenvelopeStreaming( INOUT ENVELOPE_INFO *envelopeInfoPtr );
906 STDC_NONNULL_ARG( ( 1 ) ) \
907 void initDenvResourceHandling( INOUT ENVELOPE_INFO *envelopeInfoPtr );
908 
909 #endif /* _ENV_DEFINED */