Debian Codegraph @

simulator/ms-tpm-20-ref/TPMCmd/tpm/src/X509/TpmASN1.c

raw
1 /* Microsoft Reference Implementation for TPM 2.0
2 *
3 * The copyright in this software is being made available under the BSD License,
4 * included below. This software may be subject to other third party and
5 * contributor rights, including patent rights, and no such rights are granted
6 * under this license.
7 *
8 * Copyright (c) Microsoft Corporation
9 *
10 * All rights reserved.
11 *
12 * BSD License
13 *
14 * Redistribution and use in source and binary forms, with or without modification,
15 * are permitted provided that the following conditions are met:
16 *
17 * Redistributions of source code must retain the above copyright notice, this list
18 * of conditions and the following disclaimer.
19 *
20 * Redistributions in binary form must reproduce the above copyright notice, this
21 * list of conditions and the following disclaimer in the documentation and/or
22 * other materials provided with the distribution.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS""
25 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
28 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
31 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 */
35 //** Includes
36 #include "Tpm.h"
37
38 #define _OIDS_
39 #include "OIDs.h"
40
41 #include "TpmASN1.h"
42 #include "TpmASN1_fp.h"
43
44 //** Unmarshaling Functions
45
46 //*** ASN1UnmarshalContextInitialize()
47 // Function does standard initialization of a context.
48 // Return Type: BOOL
49 // TRUE(1) success
50 // FALSE(0) failure
51 BOOL
52 ASN1UnmarshalContextInitialize(
53 ASN1UnmarshalContext *ctx,
54 INT16 size,
55 BYTE *buffer
56 )
57 {
58 VERIFY(buffer != NULL);
59 VERIFY(size > 0);
60 ctx->buffer = buffer;
61 ctx->size = size;
62 ctx->offset = 0;
63 ctx->tag = 0xFF;
64 return TRUE;
65 Error:
66 return FALSE;
67 }
68
69 //***ASN1DecodeLength()
70 // This function extracts the length of an element from 'buffer' starting at 'offset'.
71 // Return Type: UINT16
72 // >=0 the extracted length
73 // <0 an error
74 INT16
75 ASN1DecodeLength(
76 ASN1UnmarshalContext *ctx
77 )
78 {
79 BYTE first; // Next octet in buffer
80 INT16 value;
81 //
82 VERIFY(ctx->offset < ctx->size);
83 first = NEXT_OCTET(ctx);
84 // If the number of octets of the entity is larger than 127, then the first octet
85 // is the number of octets in the length specifier.
86 if(first >= 0x80)
87 {
88 // Make sure that this length field is contained with the structure being
89 // parsed
90 CHECK_SIZE(ctx, (first & 0x7F));
91 if(first == 0x82)
92 {
93 // Two octets of size
94 // get the next value
95 value = (INT16)NEXT_OCTET(ctx);
96 // Make sure that the result will fit in an INT16
97 VERIFY(value < 0x0080);
98 // Shift up and add next octet
99 value = (value << 8) + NEXT_OCTET(ctx);
100 }
101 else if(first == 0x81)
102 value = NEXT_OCTET(ctx);
103 // Sizes larger than will fit in a INT16 are an error
104 else
105 goto Error;
106 }
107 else
108 value = first;
109 // Make sure that the size defined something within the current context
110 CHECK_SIZE(ctx, value);
111 return value;
112 Error:
113 ctx->size = -1; // Makes everything fail from now on.
114 return -1;
115 }
116
117 //***ASN1NextTag()
118 // This function extracts the next type from 'buffer' starting at 'offset'.
119 // It advances 'offset' as it parses the type and the length of the type. It returns
120 // the length of the type. On return, the 'length' octets starting at 'offset' are the
121 // octets of the type.
122 // Return Type: UINT
123 // >=0 the number of octets in 'type'
124 // <0 an error
125 INT16
126 ASN1NextTag(
127 ASN1UnmarshalContext *ctx
128 )
129 {
130 // A tag to get?
131 VERIFY(ctx->offset < ctx->size);
132 // Get it
133 ctx->tag = NEXT_OCTET(ctx);
134 // Make sure that it is not an extended tag
135 VERIFY((ctx->tag & 0x1F) != 0x1F);
136 // Get the length field and return that
137 return ASN1DecodeLength(ctx);
138
139 Error:
140 // Attempt to read beyond the end of the context or an illegal tag
141 ctx->size = -1; // Persistent failure
142 ctx->tag = 0xFF;
143 return -1;
144 }
145
146
147 //*** ASN1GetBitStringValue()
148 // Try to parse a bit string of up to 32 bits from a value that is expected to be
149 // a bit string.
150 // If there is a general parsing error, the context->size is set to -1.
151 // Return Type: BOOL
152 // TRUE(1) success
153 // FALSE(0) failure
154 BOOL
155 ASN1GetBitStringValue(
156 ASN1UnmarshalContext *ctx,
157 UINT32 *val
158 )
159 {
160 int shift;
161 INT16 length;
162 UINT32 value = 0;
163 //
164
165 VERIFY((length = ASN1NextTag(ctx)) >= 1);
166 VERIFY(ctx->tag == ASN1_BITSTRING);
167 // Get the shift value for the bit field (how many bits to loop off of the end)
168 shift = NEXT_OCTET(ctx);
169 length--;
170 // the shift count has to make sense
171 VERIFY((shift < 8) && ((length > 0) || (shift == 0)));
172 // if there are any bytes left
173 for(; length > 0; length--)
174 {
175 if(length > 1)
176 {
177 // for all but the last octet, just shift and add the new octet
178 VERIFY((value & 0xFF000000) == 0); // can't loose significant bits
179 value = (value << 8) + NEXT_OCTET(ctx);
180 }
181 else
182 {
183 // for the last octet, just shift the accumulated value enough to
184 // accept the significant bits in the last octet and shift the last
185 // octet down
186 VERIFY(((value & (0xFF000000 << (8 - shift)))) == 0);
187 value = (value << (8 - shift)) + (NEXT_OCTET(ctx) >> shift);
188 }
189 }
190 *val = value;
191 return TRUE;
192 Error:
193 ctx->size = -1;
194 return FALSE;
195 }
196
197 //*******************************************************************
198 //** Marshaling Functions
199 //*******************************************************************
200
201 //*** Introduction
202 // Marshaling of an ASN.1 structure is accomplished from the bottom up. That is,
203 // the things that will be at the end of the structure are added last. To manage the
204 // collecting of the relative sizes, start a context for the outermost container, if
205 // there is one, and then placing items in from the bottom up. If the bottom-most
206 // item is also within a structure, create a nested context by calling
207 // ASN1StartMarshalingContext().
208 //
209 // The context control structure contains a 'buffer' pointer, an 'offset', an 'end'
210 // and a stack. 'offset' is the offset from the start of the buffer of the last added
211 // byte. When 'offset' reaches 0, the buffer is full. 'offset' is a signed value so
212 // that, when it becomes negative, there is an overflow. Only two functions are
213 // allowed to move bytes into the buffer: ASN1PushByte() and ASN1PushBytes(). These
214 // functions make sure that no data is written beyond the end of the buffer.
215 //
216 // When a new context is started, the current value of 'end' is pushed
217 // on the stack and 'end' is set to 'offset. As bytes are added, offset gets smaller.
218 // At any time, the count of bytes in the current context is simply 'end' - 'offset'.
219 //
220 // Since starting a new context involves setting 'end' = 'offset', the number of bytes
221 // in the context starts at 0. The nominal way of ending a context is to use
222 // 'end' - 'offset' to set the length value, and then a tag is added to the buffer.
223 // Then the previous 'end' value is popped meaning that the context just ended
224 // becomes a member of the now current context.
225 //
226 // The nominal strategy for building a completed ASN.1 structure is to push everything
227 // into the buffer and then move everything to the start of the buffer. The move is
228 // simple as the size of the move is the initial 'end' value minus the final 'offset'
229 // value. The destination is 'buffer' and the source is 'buffer' + 'offset'. As Skippy
230 // would say "Easy peasy, Joe."
231 //
232 // It is not necessary to provide a buffer into which the data is placed. If no buffer
233 // is provided, then the marshaling process will return values needed for marshaling.
234 // On strategy for filling the buffer would be to execute the process for building
235 // the structure without using a buffer. This would return the overall size of the
236 // structure. Then that amount of data could be allocated for the buffer and the fill
237 // process executed again with the data going into the buffer. At the end, the data
238 // would be in its final resting place.
239
240 //*** ASN1InitialializeMarshalContext()
241 // This creates a structure for handling marshaling of an ASN.1 formatted data
242 // structure.
243 void
244 ASN1InitialializeMarshalContext(
245 ASN1MarshalContext *ctx,
246 INT16 length,
247 BYTE *buffer
248 )
249 {
250 ctx->buffer = buffer;
251 if(buffer)
252 ctx->offset = length;
253 else
254 ctx->offset = INT16_MAX;
255 ctx->end = ctx->offset;
256 ctx->depth = -1;
257 }
258
259 //*** ASN1StartMarshalContext()
260 // This starts a new constructed element. It is constructed on 'top' of the value
261 // that was previously placed in the structure.
262 void
263 ASN1StartMarshalContext(
264 ASN1MarshalContext *ctx
265 )
266 {
267 pAssert((ctx->depth + 1) < MAX_DEPTH);
268 ctx->depth++;
269 ctx->ends[ctx->depth] = ctx->end;
270 ctx->end = ctx->offset;
271 }
272
273 //*** ASN1EndMarshalContext()
274 // This function restores the end pointer for an encapsulating structure.
275 // Return Type: INT16
276 // > 0 the size of the encapsulated structure that was just ended
277 // <= 0 an error
278 INT16
279 ASN1EndMarshalContext(
280 ASN1MarshalContext *ctx
281 )
282 {
283 INT16 length;
284 pAssert(ctx->depth >= 0);
285 length = ctx->end - ctx->offset;
286 ctx->end = ctx->ends[ctx->depth--];
287 if((ctx->depth == -1) && (ctx->buffer))
288 {
289 MemoryCopy(ctx->buffer, ctx->buffer + ctx->offset, ctx->end - ctx->offset);
290 }
291 return length;
292 }
293
294
295 //***ASN1EndEncapsulation()
296 // This function puts a tag and length in the buffer. In this function, an embedded
297 // BIT_STRING is assumed to be a collection of octets. To indicate that all bits
298 // are used, a byte of zero is prepended. If a raw bit-string is needed, a new
299 // function like ASN1PushInteger() would be needed.
300 // Return Type: INT16
301 // > 0 number of octets in the encapsulation
302 // == 0 failure
303 UINT16
304 ASN1EndEncapsulation(
305 ASN1MarshalContext *ctx,
306 BYTE tag
307 )
308 {
309 // only add a leading zero for an encapsulated BIT STRING
310 if (tag == ASN1_BITSTRING)
311 ASN1PushByte(ctx, 0);
312 ASN1PushTagAndLength(ctx, tag, ctx->end - ctx->offset);
313 return ASN1EndMarshalContext(ctx);
314 }
315
316 //*** ASN1PushByte()
317 BOOL
318 ASN1PushByte(
319 ASN1MarshalContext *ctx,
320 BYTE b
321 )
322 {
323 if(ctx->offset > 0)
324 {
325 ctx->offset -= 1;
326 if(ctx->buffer)
327 ctx->buffer[ctx->offset] = b;
328 return TRUE;
329 }
330 ctx->offset = -1;
331 return FALSE;
332 }
333
334 //*** ASN1PushBytes()
335 // Push some raw bytes onto the buffer. 'count' cannot be zero.
336 // Return Type: IN16
337 // > 0 count bytes
338 // == 0 failure unless count was zero
339 INT16
340 ASN1PushBytes(
341 ASN1MarshalContext *ctx,
342 INT16 count,
343 const BYTE *buffer
344 )
345 {
346 // make sure that count is not negative which would mess up the math; and that
347 // if there is a count, there is a buffer
348 VERIFY((count >= 0) && ((buffer != NULL) || (count == 0)));
349 // back up the offset to determine where the new octets will get pushed
350 ctx->offset -= count;
351 // can't go negative
352 VERIFY(ctx->offset >= 0);
353 // if there are buffers, move the data, otherwise, assume that this is just a
354 // test.
355 if(count && buffer && ctx->buffer)
356 MemoryCopy(&ctx->buffer[ctx->offset], buffer, count);
357 return count;
358 Error:
359 ctx->offset = -1;
360 return 0;
361 }
362
363 //*** ASN1PushNull()
364 // Return Type: IN16
365 // > 0 count bytes
366 // == 0 failure unless count was zero
367 INT16
368 ASN1PushNull(
369 ASN1MarshalContext *ctx
370 )
371 {
372 ASN1PushByte(ctx, 0);
373 ASN1PushByte(ctx, ASN1_NULL);
374 return (ctx->offset >= 0) ? 2 : 0;
375 }
376
377 //*** ASN1PushLength()
378 // Push a length value. This will only handle length values that fit in an INT16.
379 // Return Type: UINT16
380 // > 0 number of bytes added
381 // == 0 failure
382 INT16
383 ASN1PushLength(
384 ASN1MarshalContext *ctx,
385 INT16 len
386 )
387 {
388 UINT16 start = ctx->offset;
389 VERIFY(len >= 0);
390 if(len <= 127)
391 ASN1PushByte(ctx, (BYTE)len);
392 else
393 {
394 ASN1PushByte(ctx, (BYTE)(len & 0xFF));
395 len >>= 8;
396 if(len == 0)
397 ASN1PushByte(ctx, 0x81);
398 else
399 {
400 ASN1PushByte(ctx, (BYTE)(len));
401 ASN1PushByte(ctx, 0x82);
402 }
403 }
404 goto Exit;
405 Error:
406 ctx->offset = -1;
407 Exit:
408 return (ctx->offset > 0) ? start - ctx->offset : 0;
409 }
410
411 //*** ASN1PushTagAndLength()
412 // Return Type: INT16
413 // > 0 number of bytes added
414 // == 0 failure
415 INT16
416 ASN1PushTagAndLength(
417 ASN1MarshalContext *ctx,
418 BYTE tag,
419 INT16 length
420 )
421 {
422 INT16 bytes;
423 bytes = ASN1PushLength(ctx, length);
424 bytes += (INT16)ASN1PushByte(ctx, tag);
425 return (ctx->offset < 0) ? 0 : bytes;
426 }
427
428
429 //*** ASN1PushTaggedOctetString()
430 // This function will push a random octet string.
431 // Return Type: INT16
432 // > 0 number of bytes added
433 // == 0 failure
434 INT16
435 ASN1PushTaggedOctetString(
436 ASN1MarshalContext *ctx,
437 INT16 size,
438 const BYTE *string,
439 BYTE tag
440 )
441 {
442 ASN1PushBytes(ctx, size, string);
443 // PushTagAndLenght just tells how many octets it added so the total size of this
444 // element is the sum of those octets and input size.
445 size += ASN1PushTagAndLength(ctx, tag, size);
446 return size;
447 }
448
449 //*** ASN1PushUINT()
450 // This function pushes an native-endian integer value. This just changes a
451 // native-endian integer into a big-endian byte string and calls ASN1PushInteger().
452 // That function will remove leading zeros and make sure that the number is positive.
453 // Return Type: IN16
454 // > 0 count bytes
455 // == 0 failure unless count was zero
456 INT16
457 ASN1PushUINT(
458 ASN1MarshalContext *ctx,
459 UINT32 integer
460 )
461 {
462 BYTE marshaled[4];
463 UINT32_TO_BYTE_ARRAY(integer, marshaled);
464 return ASN1PushInteger(ctx, 4, marshaled);
465 }
466
467 //*** ASN1PushInteger
468 // Push a big-endian integer on the end of the buffer
469 // Return Type: UINT16
470 // > 0 the number of bytes marshaled for the integer
471 // == 0 failure
472 INT16
473 ASN1PushInteger(
474 ASN1MarshalContext *ctx, // IN/OUT: buffer context
475 INT16 iLen, // IN: octets of the integer
476 BYTE *integer // IN: big-endian integer
477 )
478 {
479 // no leading 0's
480 while((*integer == 0) && (--iLen > 0))
481 integer++;
482 // Move the bytes to the buffer
483 ASN1PushBytes(ctx, iLen, integer);
484 // if needed, add a leading byte of 0 to make the number positive
485 if(*integer & 0x80)
486 iLen += (INT16)ASN1PushByte(ctx, 0);
487 // PushTagAndLenght just tells how many octets it added so the total size of this
488 // element is the sum of those octets and the adjusted input size.
489 iLen += ASN1PushTagAndLength(ctx, ASN1_INTEGER, iLen);
490 return iLen;
491 }
492
493 //*** ASN1PushOID()
494 // This function is used to add an OID. An OID is 0x06 followed by a byte of size
495 // followed by size bytes. This is used to avoid having to do anything special in the
496 // definition of an OID.
497 // Return Type: UINT16
498 // > 0 the number of bytes marshaled for the integer
499 // == 0 failure
500 INT16
501 ASN1PushOID(
502 ASN1MarshalContext *ctx,
503 const BYTE *OID
504 )
505 {
506 if((*OID == ASN1_OBJECT_IDENTIFIER) && ((OID[1] & 0x80) == 0))
507 {
508 return ASN1PushBytes(ctx, OID[1] + 2, OID);
509 }
510 ctx->offset = -1;
511 return 0;
512 }
513
514