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 //**Introduction
36 /*
37 The code in this file is used to manage the session context counter.
38 The scheme implemented here is a "truncated counter".
39 This scheme allows the TPM to not need TPM_SU_CLEAR for a
40 very long period of time and still not have the context
41 count for a session repeated.
42
43 The counter (contextCounter)in this implementation is a UINT64 but
44 can be smaller. The "tracking array" (contextArray) only
45 has 16-bits per context. The tracking array is the data
46 that needs to be saved and restored across TPM_SU_STATE so that
47 sessions are not lost when the system enters the sleep state.
48 Also, when the TPM is active, the tracking array is kept in
49 RAM making it important that the number of bytes for each
50 entry be kept as small as possible.
51
52 The TPM prevents "collisions" of these truncated values by
53 not allowing a contextID to be assigned if it would be the
54 same as an existing value. Since the array holds 16 bits,
55 after a context has been saved, an additional 2^16-1 contexts
56 may be saved before the count would again match. The normal
57 expectation is that the context will be flushed before its count
58 value is needed again but it is always possible to have long-lived
59 sessions.
60
61 The contextID is assigned when the context is saved (TPM2_ContextSave()).
62 At that time, the TPM will compare the low-order 16 bits of
63 contextCounter to the existing values in contextArray and if one
64 matches, the TPM will return TPM_RC_CONTEXT_GAP (by construction,
65 the entry that contains the matching value is the oldest
66 context).
67
68 The expected remediation by the TRM is to load the oldest saved
69 session context (the one found by the TPM), and save it. Since loading
70 the oldest session also eliminates its contextID value from
71 contextArray, there TPM will always be able to load and save the oldest
72 existing context.
73
74 In the worst case, software may have to load and save several contexts
75 in order to save an additional one. This should happen very infrequently.
76
77 When the TPM searches contextArray and finds that none of the contextIDs
78 match the low-order 16-bits of contextCount, the TPM can copy the low bits
79 to the contextArray associated with the session, and increment contextCount.
80
81 There is one entry in contextArray for each of the active sessions
82 allowed by the TPM implementation. This array contains either a
83 context count, an index, or a value indicating the slot is available (0).
84
85 The index into the contextArray is the handle for the session with the region
86 selector byte of the session set to zero. If an entry in contextArray contains
87 0, then the corresponding handle may be assigned to a session. If the entry
88 contains a value that is less than or equal to the number of loaded sessions
89 for the TPM, then the array entry is the slot in which the context is loaded.
90
91 EXAMPLE: If the TPM allows 8 loaded sessions, then the slot numbers would
92 be 1-8 and a contextArrary value in that range would represent the loaded
93 session.
94
95 NOTE: When the TPM firmware determines that the array entry is for a loaded
96 session, it will subtract 1 to create the zero-based slot number.
97
98 There is one significant corner case in this scheme. When the contextCount
99 is equal to a value in the contextArray, the oldest session needs to be
100 recycled or flushed. In order to recycle the session, it must be loaded.
101 To be loaded, there must be an available slot. Rather than require that a
102 spare slot be available all the time, the TPM will check to see if the
103 contextCount is equal to some value in the contextArray when a session is
104 created. This prevents the last session slot from being used when it
105 is likely that a session will need to be recycled.
106
107 If a TPM with both 1.2 and 2.0 functionality uses this scheme for both
108 1.2 and 2.0 sessions, and the list of active contexts is read with
109 TPM_GetCapabiltiy(), the TPM will create 32-bit representations of the
110 list that contains 16-bit values (the TPM2_GetCapability() returns a list
111 of handles for active sessions rather than a list of contextID). The full
112 contextID has high-order bits that are either the same as the current
113 contextCount or one less. It is one less if the 16-bits
114 of the contextArray has a value that is larger than the low-order 16 bits
115 of contextCount.
116 */
117
118 //** Includes, Defines, and Local Variables
119 #define SESSION_C
120 #include "Tpm.h"
121
122 //** File Scope Function -- ContextIdSetOldest()
123 /*
124 This function is called when the oldest contextID is being loaded or deleted.
125 Once a saved context becomes the oldest, it stays the oldest until it is
126 deleted.
127
128 Finding the oldest is a bit tricky. It is not just the numeric comparison of
129 values but is dependent on the value of contextCounter.
130
131 Assume we have a small contextArray with 8, 4-bit values with values 1 and 2
132 used to indicate the loaded context slot number. Also assume that the array
133 contains hex values of (0 0 1 0 3 0 9 F) and that the contextCounter is an
134 8-bit counter with a value of 0x37. Since the low nibble is 7, that means
135 that values above 7 are older than values below it and, in this example,
136 9 is the oldest value.
137
138 Note if we subtract the counter value, from each slot that contains a saved
139 contextID we get (- - - - B - 2 - 8) and the oldest entry is now easy to find.
140 */
141 static void
ContextIdSetOldest(void)142 ContextIdSetOldest(
143 void
144 )
145 {
146 CONTEXT_SLOT lowBits;
147 CONTEXT_SLOT entry;
148 CONTEXT_SLOT smallest = ((CONTEXT_SLOT)~0);
149 UINT32 i;
150
151 // Set oldestSaveContext to a value indicating none assigned
152 s_oldestSavedSession = MAX_ACTIVE_SESSIONS + 1;
153
154 lowBits = (CONTEXT_SLOT)gr.contextCounter;
155 for(i = 0; i < MAX_ACTIVE_SESSIONS; i++)
156 {
157 entry = gr.contextArray[i];
158
159 // only look at entries that are saved contexts
160 if(entry > MAX_LOADED_SESSIONS)
161 {
162 // Use a less than or equal in case the oldest
163 // is brand new (= lowBits-1) and equal to our initial
164 // value for smallest.
165 if(((CONTEXT_SLOT)(entry - lowBits)) <= smallest)
166 {
167 smallest = (entry - lowBits);
168 s_oldestSavedSession = i;
169 }
170 }
171 }
172 // When we finish, either the s_oldestSavedSession still has its initial
173 // value, or it has the index of the oldest saved context.
174 }
175
176 //** Startup Function -- SessionStartup()
177 // This function initializes the session subsystem on TPM2_Startup().
178 BOOL
SessionStartup(STARTUP_TYPE type)179 SessionStartup(
180 STARTUP_TYPE type
181 )
182 {
183 UINT32 i;
184
185 // Initialize session slots. At startup, all the in-memory session slots
186 // are cleared and marked as not occupied
187 for(i = 0; i < MAX_LOADED_SESSIONS; i++)
188 s_sessions[i].occupied = FALSE; // session slot is not occupied
189
190 // The free session slots the number of maximum allowed loaded sessions
191 s_freeSessionSlots = MAX_LOADED_SESSIONS;
192
193 // Initialize context ID data. On a ST_SAVE or hibernate sequence, it will
194 // scan the saved array of session context counts, and clear any entry that
195 // references a session that was in memory during the state save since that
196 // memory was not preserved over the ST_SAVE.
197 if(type == SU_RESUME || type == SU_RESTART)
198 {
199 // On ST_SAVE we preserve the contexts that were saved but not the ones
200 // in memory
201 for(i = 0; i < MAX_ACTIVE_SESSIONS; i++)
202 {
203 // If the array value is unused or references a loaded session then
204 // that loaded session context is lost and the array entry is
205 // reclaimed.
206 if(gr.contextArray[i] <= MAX_LOADED_SESSIONS)
207 gr.contextArray[i] = 0;
208 }
209 // Find the oldest session in context ID data and set it in
210 // s_oldestSavedSession
211 ContextIdSetOldest();
212 }
213 else
214 {
215 // For STARTUP_CLEAR, clear out the contextArray
216 for(i = 0; i < MAX_ACTIVE_SESSIONS; i++)
217 gr.contextArray[i] = 0;
218
219 // reset the context counter
220 gr.contextCounter = MAX_LOADED_SESSIONS + 1;
221
222 // Initialize oldest saved session
223 s_oldestSavedSession = MAX_ACTIVE_SESSIONS + 1;
224 }
225 return TRUE;
226 }
227
228 //************************************************
229 //** Access Functions
230 //************************************************
231
232 //*** SessionIsLoaded()
233 // This function test a session handle references a loaded session. The handle
234 // must have previously been checked to make sure that it is a valid handle for
235 // an authorization session.
236 // NOTE: A PWAP authorization does not have a session.
237 //
238 // Return Type: BOOL
239 // TRUE(1) session is loaded
240 // FALSE(0) session is not loaded
241 //
242 BOOL
SessionIsLoaded(TPM_HANDLE handle)243 SessionIsLoaded(
244 TPM_HANDLE handle // IN: session handle
245 )
246 {
247 pAssert(HandleGetType(handle) == TPM_HT_POLICY_SESSION
248 || HandleGetType(handle) == TPM_HT_HMAC_SESSION);
249
250 handle = handle & HR_HANDLE_MASK;
251
252 // if out of range of possible active session, or not assigned to a loaded
253 // session return false
254 if(handle >= MAX_ACTIVE_SESSIONS
255 || gr.contextArray[handle] == 0
256 || gr.contextArray[handle] > MAX_LOADED_SESSIONS)
257 return FALSE;
258
259 return TRUE;
260 }
261
262 //*** SessionIsSaved()
263 // This function test a session handle references a saved session. The handle
264 // must have previously been checked to make sure that it is a valid handle for
265 // an authorization session.
266 // NOTE: An password authorization does not have a session.
267 //
268 // This function requires that the handle be a valid session handle.
269 //
270 // Return Type: BOOL
271 // TRUE(1) session is saved
272 // FALSE(0) session is not saved
273 //
274 BOOL
SessionIsSaved(TPM_HANDLE handle)275 SessionIsSaved(
276 TPM_HANDLE handle // IN: session handle
277 )
278 {
279 pAssert(HandleGetType(handle) == TPM_HT_POLICY_SESSION
280 || HandleGetType(handle) == TPM_HT_HMAC_SESSION);
281
282 handle = handle & HR_HANDLE_MASK;
283 // if out of range of possible active session, or not assigned, or
284 // assigned to a loaded session, return false
285 if(handle >= MAX_ACTIVE_SESSIONS
286 || gr.contextArray[handle] == 0
287 || gr.contextArray[handle] <= MAX_LOADED_SESSIONS
288 )
289 return FALSE;
290
291 return TRUE;
292 }
293
294 //*** SequenceNumberForSavedContextIsValid()
295 // This function validates that the sequence number and handle value within a
296 // saved context are valid.
297 BOOL
SequenceNumberForSavedContextIsValid(TPMS_CONTEXT * context)298 SequenceNumberForSavedContextIsValid(
299 TPMS_CONTEXT *context // IN: pointer to a context structure to be
300 // validated
301 )
302 {
303 #define MAX_CONTEXT_GAP ((UINT64)((CONTEXT_SLOT) ~0) + 1)
304
305 TPM_HANDLE handle = context->savedHandle & HR_HANDLE_MASK;
306
307 if(// Handle must be with the range of active sessions
308 handle >= MAX_ACTIVE_SESSIONS
309 // the array entry must be for a saved context
310 || gr.contextArray[handle] <= MAX_LOADED_SESSIONS
311 // the array entry must agree with the sequence number
312 || gr.contextArray[handle] != (CONTEXT_SLOT)context->sequence
313 // the provided sequence number has to be less than the current counter
314 || context->sequence > gr.contextCounter
315 // but not so much that it could not be a valid sequence number
316 || gr.contextCounter - context->sequence > MAX_CONTEXT_GAP)
317 return FALSE;
318
319 return TRUE;
320 }
321
322 //*** SessionPCRValueIsCurrent()
323 //
324 // This function is used to check if PCR values have been updated since the
325 // last time they were checked in a policy session.
326 //
327 // This function requires the session is loaded.
328 // Return Type: BOOL
329 // TRUE(1) PCR value is current
330 // FALSE(0) PCR value is not current
331 BOOL
SessionPCRValueIsCurrent(SESSION * session)332 SessionPCRValueIsCurrent(
333 SESSION *session // IN: session structure
334 )
335 {
336 if(session->pcrCounter != 0
337 && session->pcrCounter != gr.pcrCounter
338 )
339 return FALSE;
340 else
341 return TRUE;
342 }
343
344 //*** SessionGet()
345 // This function returns a pointer to the session object associated with a
346 // session handle.
347 //
348 // The function requires that the session is loaded.
349 SESSION *
SessionGet(TPM_HANDLE handle)350 SessionGet(
351 TPM_HANDLE handle // IN: session handle
352 )
353 {
354 size_t slotIndex;
355 CONTEXT_SLOT sessionIndex;
356
357 pAssert(HandleGetType(handle) == TPM_HT_POLICY_SESSION
358 || HandleGetType(handle) == TPM_HT_HMAC_SESSION
359 );
360
361 slotIndex = handle & HR_HANDLE_MASK;
362
363 pAssert(slotIndex < MAX_ACTIVE_SESSIONS);
364
365 // get the contents of the session array. Because session is loaded, we
366 // should always get a valid sessionIndex
367 sessionIndex = gr.contextArray[slotIndex] - 1;
368
369 pAssert(sessionIndex < MAX_LOADED_SESSIONS);
370
371 return &s_sessions[sessionIndex].session;
372 }
373
374 //************************************************
375 //** Utility Functions
376 //************************************************
377
378 //*** ContextIdSessionCreate()
379 //
380 // This function is called when a session is created. It will check
381 // to see if the current gap would prevent a context from being saved. If
382 // so it will return TPM_RC_CONTEXT_GAP. Otherwise, it will try to find
383 // an open slot in contextArray, set contextArray to the slot.
384 //
385 // This routine requires that the caller has determined the session array
386 // index for the session.
387 //
388 // Return Type: TPM_RC
389 // TPM_RC_CONTEXT_GAP can't assign a new contextID until the oldest
390 // saved session context is recycled
391 // TPM_RC_SESSION_HANDLE there is no slot available in the context array
392 // for tracking of this session context
393 static TPM_RC
ContextIdSessionCreate(TPM_HANDLE * handle,UINT32 sessionIndex)394 ContextIdSessionCreate(
395 TPM_HANDLE *handle, // OUT: receives the assigned handle. This will
396 // be an index that must be adjusted by the
397 // caller according to the type of the
398 // session created
399 UINT32 sessionIndex // IN: The session context array entry that will
400 // be occupied by the created session
401 )
402 {
403 pAssert(sessionIndex < MAX_LOADED_SESSIONS);
404
405 // check to see if creating the context is safe
406 // Is this going to be an assignment for the last session context
407 // array entry? If so, then there will be no room to recycle the
408 // oldest context if needed. If the gap is not at maximum, then
409 // it will be possible to save a context if it becomes necessary.
410 if(s_oldestSavedSession < MAX_ACTIVE_SESSIONS
411 && s_freeSessionSlots == 1)
412 {
413 // See if the gap is at maximum
414 // The current value of the contextCounter will be assigned to the next
415 // saved context. If the value to be assigned would make the same as an
416 // existing context, then we can't use it because of the ambiguity it would
417 // create.
418 if((CONTEXT_SLOT)gr.contextCounter
419 == gr.contextArray[s_oldestSavedSession])
420 return TPM_RC_CONTEXT_GAP;
421 }
422
423 // Find an unoccupied entry in the contextArray
424 for(*handle = 0; *handle < MAX_ACTIVE_SESSIONS; (*handle)++)
425 {
426 if(gr.contextArray[*handle] == 0)
427 {
428 // indicate that the session associated with this handle
429 // references a loaded session
430 gr.contextArray[*handle] = (CONTEXT_SLOT)(sessionIndex + 1);
431 return TPM_RC_SUCCESS;
432 }
433 }
434 return TPM_RC_SESSION_HANDLES;
435 }
436
437 //*** SessionCreate()
438 //
439 // This function does the detailed work for starting an authorization session.
440 // This is done in a support routine rather than in the action code because
441 // the session management may differ in implementations. This implementation
442 // uses a fixed memory allocation to hold sessions and a fixed allocation
443 // to hold the contextID for the saved contexts.
444 //
445 // Return Type: TPM_RC
446 // TPM_RC_CONTEXT_GAP need to recycle sessions
447 // TPM_RC_SESSION_HANDLE active session space is full
448 // TPM_RC_SESSION_MEMORY loaded session space is full
449 TPM_RC
SessionCreate(TPM_SE sessionType,TPMI_ALG_HASH authHash,TPM2B_NONCE * nonceCaller,TPMT_SYM_DEF * symmetric,TPMI_DH_ENTITY bind,TPM2B_DATA * seed,TPM_HANDLE * sessionHandle,TPM2B_NONCE * nonceTpm)450 SessionCreate(
451 TPM_SE sessionType, // IN: the session type
452 TPMI_ALG_HASH authHash, // IN: the hash algorithm
453 TPM2B_NONCE *nonceCaller, // IN: initial nonceCaller
454 TPMT_SYM_DEF *symmetric, // IN: the symmetric algorithm
455 TPMI_DH_ENTITY bind, // IN: the bind object
456 TPM2B_DATA *seed, // IN: seed data
457 TPM_HANDLE *sessionHandle, // OUT: the session handle
458 TPM2B_NONCE *nonceTpm // OUT: the session nonce
459 )
460 {
461 TPM_RC result = TPM_RC_SUCCESS;
462 CONTEXT_SLOT slotIndex;
463 SESSION *session = NULL;
464
465 pAssert(sessionType == TPM_SE_HMAC
466 || sessionType == TPM_SE_POLICY
467 || sessionType == TPM_SE_TRIAL);
468
469 // If there are no open spots in the session array, then no point in searching
470 if(s_freeSessionSlots == 0)
471 return TPM_RC_SESSION_MEMORY;
472
473 // Find a space for loading a session
474 for(slotIndex = 0; slotIndex < MAX_LOADED_SESSIONS; slotIndex++)
475 {
476 // Is this available?
477 if(s_sessions[slotIndex].occupied == FALSE)
478 {
479 session = &s_sessions[slotIndex].session;
480 break;
481 }
482 }
483 // if no spot found, then this is an internal error
484 if(slotIndex >= MAX_LOADED_SESSIONS)
485 FAIL(FATAL_ERROR_INTERNAL);
486
487 // Call context ID function to get a handle. TPM_RC_SESSION_HANDLE may be
488 // returned from ContextIdHandelAssign()
489 result = ContextIdSessionCreate(sessionHandle, slotIndex);
490 if(result != TPM_RC_SUCCESS)
491 return result;
492
493 //*** Only return from this point on is TPM_RC_SUCCESS
494
495 // Can now indicate that the session array entry is occupied.
496 s_freeSessionSlots--;
497 s_sessions[slotIndex].occupied = TRUE;
498
499 // Initialize the session data
500 MemorySet(session, 0, sizeof(SESSION));
501
502 // Initialize internal session data
503 session->authHashAlg = authHash;
504 // Initialize session type
505 if(sessionType == TPM_SE_HMAC)
506 {
507 *sessionHandle += HMAC_SESSION_FIRST;
508 }
509 else
510 {
511 *sessionHandle += POLICY_SESSION_FIRST;
512
513 // For TPM_SE_POLICY or TPM_SE_TRIAL
514 session->attributes.isPolicy = SET;
515 if(sessionType == TPM_SE_TRIAL)
516 session->attributes.isTrialPolicy = SET;
517
518 SessionSetStartTime(session);
519
520 // Initialize policyDigest. policyDigest is initialized with a string of 0
521 // of session algorithm digest size. Since the session is already clear.
522 // Just need to set the size
523 session->u2.policyDigest.t.size =
524 CryptHashGetDigestSize(session->authHashAlg);
525 }
526 // Create initial session nonce
527 session->nonceTPM.t.size = nonceCaller->t.size;
528 CryptRandomGenerate(session->nonceTPM.t.size, session->nonceTPM.t.buffer);
529 MemoryCopy2B(&nonceTpm->b, &session->nonceTPM.b,
530 sizeof(nonceTpm->t.buffer));
531
532 // Set up session parameter encryption algorithm
533 session->symmetric = *symmetric;
534
535 // If there is a bind object or a session secret, then need to compute
536 // a sessionKey.
537 if(bind != TPM_RH_NULL || seed->t.size != 0)
538 {
539 // sessionKey = KDFa(hash, (authValue || seed), "ATH", nonceTPM,
540 // nonceCaller, bits)
541 // The HMAC key for generating the sessionSecret can be the concatenation
542 // of an authorization value and a seed value
543 TPM2B_TYPE(KEY, (sizeof(TPMT_HA) + sizeof(seed->t.buffer)));
544 TPM2B_KEY key;
545
546 // Get hash size, which is also the length of sessionKey
547 session->sessionKey.t.size = CryptHashGetDigestSize(session->authHashAlg);
548
549 // Get authValue of associated entity
550 EntityGetAuthValue(bind, (TPM2B_AUTH *)&key);
551 pAssert(key.t.size + seed->t.size <= sizeof(key.t.buffer));
552
553 // Concatenate authValue and seed
554 MemoryConcat2B(&key.b, &seed->b, sizeof(key.t.buffer));
555
556 // Compute the session key
557 CryptKDFa(session->authHashAlg, &key.b, SESSION_KEY, &session->nonceTPM.b,
558 &nonceCaller->b,
559 session->sessionKey.t.size * 8, session->sessionKey.t.buffer,
560 NULL, FALSE);
561 }
562
563 // Copy the name of the entity that the HMAC session is bound to
564 // Policy session is not bound to an entity
565 if(bind != TPM_RH_NULL && sessionType == TPM_SE_HMAC)
566 {
567 session->attributes.isBound = SET;
568 SessionComputeBoundEntity(bind, &session->u1.boundEntity);
569 }
570 // If there is a bind object and it is subject to DA, then use of this session
571 // is subject to DA regardless of how it is used.
572 session->attributes.isDaBound = (bind != TPM_RH_NULL)
573 && (IsDAExempted(bind) == FALSE);
574
575 // If the session is bound, then check to see if it is bound to lockoutAuth
576 session->attributes.isLockoutBound = (session->attributes.isDaBound == SET)
577 && (bind == TPM_RH_LOCKOUT);
578 return TPM_RC_SUCCESS;
579 }
580
581 //*** SessionContextSave()
582 // This function is called when a session context is to be saved. The
583 // contextID of the saved session is returned. If no contextID can be
584 // assigned, then the routine returns TPM_RC_CONTEXT_GAP.
585 // If the function completes normally, the session slot will be freed.
586 //
587 // This function requires that 'handle' references a loaded session.
588 // Otherwise, it should not be called at the first place.
589 //
590 // Return Type: TPM_RC
591 // TPM_RC_CONTEXT_GAP a contextID could not be assigned
592 // TPM_RC_TOO_MANY_CONTEXTS the counter maxed out
593 //
594 TPM_RC
SessionContextSave(TPM_HANDLE handle,CONTEXT_COUNTER * contextID)595 SessionContextSave(
596 TPM_HANDLE handle, // IN: session handle
597 CONTEXT_COUNTER *contextID // OUT: assigned contextID
598 )
599 {
600 UINT32 contextIndex;
601 CONTEXT_SLOT slotIndex;
602
603 pAssert(SessionIsLoaded(handle));
604
605 // check to see if the gap is already maxed out
606 // Need to have a saved session
607 if(s_oldestSavedSession < MAX_ACTIVE_SESSIONS
608 // if the oldest saved session has the same value as the low bits
609 // of the contextCounter, then the GAP is maxed out.
610 && gr.contextArray[s_oldestSavedSession] == (CONTEXT_SLOT)gr.contextCounter)
611 return TPM_RC_CONTEXT_GAP;
612
613 // if the caller wants the context counter, set it
614 if(contextID != NULL)
615 *contextID = gr.contextCounter;
616
617 contextIndex = handle & HR_HANDLE_MASK;
618 pAssert(contextIndex < MAX_ACTIVE_SESSIONS);
619
620 // Extract the session slot number referenced by the contextArray
621 // because we are going to overwrite this with the low order
622 // contextID value.
623 slotIndex = gr.contextArray[contextIndex] - 1;
624
625 // Set the contextID for the contextArray
626 gr.contextArray[contextIndex] = (CONTEXT_SLOT)gr.contextCounter;
627
628 // Increment the counter
629 gr.contextCounter++;
630
631 // In the unlikely event that the 64-bit context counter rolls over...
632 if(gr.contextCounter == 0)
633 {
634 // back it up
635 gr.contextCounter--;
636 // return an error
637 return TPM_RC_TOO_MANY_CONTEXTS;
638 }
639 // if the low-order bits wrapped, need to advance the value to skip over
640 // the values used to indicate that a session is loaded
641 if(((CONTEXT_SLOT)gr.contextCounter) == 0)
642 gr.contextCounter += MAX_LOADED_SESSIONS + 1;
643
644 // If no other sessions are saved, this is now the oldest.
645 if(s_oldestSavedSession >= MAX_ACTIVE_SESSIONS)
646 s_oldestSavedSession = contextIndex;
647
648 // Mark the session slot as unoccupied
649 s_sessions[slotIndex].occupied = FALSE;
650
651 // and indicate that there is an additional open slot
652 s_freeSessionSlots++;
653
654 return TPM_RC_SUCCESS;
655 }
656
657 //*** SessionContextLoad()
658 // This function is used to load a session from saved context. The session
659 // handle must be for a saved context.
660 //
661 // If the gap is at a maximum, then the only session that can be loaded is
662 // the oldest session, otherwise TPM_RC_CONTEXT_GAP is returned.
663 ///
664 // This function requires that 'handle' references a valid saved session.
665 //
666 // Return Type: TPM_RC
667 // TPM_RC_SESSION_MEMORY no free session slots
668 // TPM_RC_CONTEXT_GAP the gap count is maximum and this
669 // is not the oldest saved context
670 //
671 TPM_RC
SessionContextLoad(SESSION_BUF * session,TPM_HANDLE * handle)672 SessionContextLoad(
673 SESSION_BUF *session, // IN: session structure from saved context
674 TPM_HANDLE *handle // IN/OUT: session handle
675 )
676 {
677 UINT32 contextIndex;
678 CONTEXT_SLOT slotIndex;
679
680 pAssert(HandleGetType(*handle) == TPM_HT_POLICY_SESSION
681 || HandleGetType(*handle) == TPM_HT_HMAC_SESSION);
682
683 // Don't bother looking if no openings
684 if(s_freeSessionSlots == 0)
685 return TPM_RC_SESSION_MEMORY;
686
687 // Find a free session slot to load the session
688 for(slotIndex = 0; slotIndex < MAX_LOADED_SESSIONS; slotIndex++)
689 if(s_sessions[slotIndex].occupied == FALSE) break;
690
691 // if no spot found, then this is an internal error
692 pAssert(slotIndex < MAX_LOADED_SESSIONS);
693
694 contextIndex = *handle & HR_HANDLE_MASK; // extract the index
695
696 // If there is only one slot left, and the gap is at maximum, the only session
697 // context that we can safely load is the oldest one.
698 if(s_oldestSavedSession < MAX_ACTIVE_SESSIONS
699 && s_freeSessionSlots == 1
700 && (CONTEXT_SLOT)gr.contextCounter == gr.contextArray[s_oldestSavedSession]
701 && contextIndex != s_oldestSavedSession)
702 return TPM_RC_CONTEXT_GAP;
703
704 pAssert(contextIndex < MAX_ACTIVE_SESSIONS);
705
706 // set the contextArray value to point to the session slot where
707 // the context is loaded
708 gr.contextArray[contextIndex] = slotIndex + 1;
709
710 // if this was the oldest context, find the new oldest
711 if(contextIndex == s_oldestSavedSession)
712 ContextIdSetOldest();
713
714 // Copy session data to session slot
715 MemoryCopy(&s_sessions[slotIndex].session, session, sizeof(SESSION));
716
717 // Set session slot as occupied
718 s_sessions[slotIndex].occupied = TRUE;
719
720 // Reduce the number of open spots
721 s_freeSessionSlots--;
722
723 return TPM_RC_SUCCESS;
724 }
725
726 //*** SessionFlush()
727 // This function is used to flush a session referenced by its handle. If the
728 // session associated with 'handle' is loaded, the session array entry is
729 // marked as available.
730 //
731 // This function requires that 'handle' be a valid active session.
732 //
733 void
SessionFlush(TPM_HANDLE handle)734 SessionFlush(
735 TPM_HANDLE handle // IN: loaded or saved session handle
736 )
737 {
738 CONTEXT_SLOT slotIndex;
739 UINT32 contextIndex; // Index into contextArray
740
741 pAssert((HandleGetType(handle) == TPM_HT_POLICY_SESSION
742 || HandleGetType(handle) == TPM_HT_HMAC_SESSION
743 )
744 && (SessionIsLoaded(handle) || SessionIsSaved(handle))
745 );
746
747 // Flush context ID of this session
748 // Convert handle to an index into the contextArray
749 contextIndex = handle & HR_HANDLE_MASK;
750
751 pAssert(contextIndex < sizeof(gr.contextArray) / sizeof(gr.contextArray[0]));
752
753 // Get the current contents of the array
754 slotIndex = gr.contextArray[contextIndex];
755
756 // Mark context array entry as available
757 gr.contextArray[contextIndex] = 0;
758
759 // Is this a saved session being flushed
760 if(slotIndex > MAX_LOADED_SESSIONS)
761 {
762 // Flushing the oldest session?
763 if(contextIndex == s_oldestSavedSession)
764 // If so, find a new value for oldest.
765 ContextIdSetOldest();
766 }
767 else
768 {
769 // Adjust slot index to point to session array index
770 slotIndex -= 1;
771
772 // Free session array index
773 s_sessions[slotIndex].occupied = FALSE;
774 s_freeSessionSlots++;
775 }
776
777 return;
778 }
779
780 //*** SessionComputeBoundEntity()
781 // This function computes the binding value for a session. The binding value
782 // for a reserved handle is the handle itself. For all the other entities,
783 // the authValue at the time of binding is included to prevent squatting.
784 // For those values, the Name and the authValue are concatenated
785 // into the bind buffer. If they will not both fit, the will be overlapped
786 // by XORing bytes. If XOR is required, the bind value will be full.
787 void
SessionComputeBoundEntity(TPMI_DH_ENTITY entityHandle,TPM2B_NAME * bind)788 SessionComputeBoundEntity(
789 TPMI_DH_ENTITY entityHandle, // IN: handle of entity
790 TPM2B_NAME *bind // OUT: binding value
791 )
792 {
793 TPM2B_AUTH auth;
794 BYTE *pAuth = auth.t.buffer;
795 UINT16 i;
796
797 // Get name
798 EntityGetName(entityHandle, bind);
799
800 // // The bound value of a reserved handle is the handle itself
801 // if(bind->t.size == sizeof(TPM_HANDLE)) return;
802
803 // For all the other entities, concatenate the authorization value to the name.
804 // Get a local copy of the authorization value because some overlapping
805 // may be necessary.
806 EntityGetAuthValue(entityHandle, &auth);
807
808 // Make sure that the extra space is zeroed
809 MemorySet(&bind->t.name[bind->t.size], 0, sizeof(bind->t.name) - bind->t.size);
810 // XOR the authValue at the end of the name
811 for(i = sizeof(bind->t.name) - auth.t.size; i < sizeof(bind->t.name); i++)
812 bind->t.name[i] ^= *pAuth++;
813
814 // Set the bind value to the maximum size
815 bind->t.size = sizeof(bind->t.name);
816
817 return;
818 }
819
820
821 //*** SessionSetStartTime()
822 // This function is used to initialize the session timing
823 void
SessionSetStartTime(SESSION * session)824 SessionSetStartTime(
825 SESSION *session // IN: the session to update
826 )
827 {
828 session->startTime = g_time;
829 session->epoch = g_timeEpoch;
830 session->timeout = 0;
831 }
832
833 //*** SessionResetPolicyData()
834 // This function is used to reset the policy data without changing the nonce
835 // or the start time of the session.
836 void
SessionResetPolicyData(SESSION * session)837 SessionResetPolicyData(
838 SESSION *session // IN: the session to reset
839 )
840 {
841 SESSION_ATTRIBUTES oldAttributes;
842 pAssert(session != NULL);
843
844 // Will need later
845 oldAttributes = session->attributes;
846
847 // No command
848 session->commandCode = 0;
849
850 // No locality selected
851 MemorySet(&session->commandLocality, 0, sizeof(session->commandLocality));
852
853 // The cpHash size to zero
854 session->u1.cpHash.b.size = 0;
855
856 // No timeout
857 session->timeout = 0;
858
859 // Reset the pcrCounter
860 session->pcrCounter = 0;
861
862 // Reset the policy hash
863 MemorySet(&session->u2.policyDigest.t.buffer, 0,
864 session->u2.policyDigest.t.size);
865
866 // Reset the session attributes
867 MemorySet(&session->attributes, 0, sizeof(SESSION_ATTRIBUTES));
868
869 // Restore the policy attributes
870 session->attributes.isPolicy = SET;
871 session->attributes.isTrialPolicy = oldAttributes.isTrialPolicy;
872
873 // Restore the bind attributes
874 session->attributes.isDaBound = oldAttributes.isDaBound;
875 session->attributes.isLockoutBound = oldAttributes.isLockoutBound;
876 }
877
878 //*** SessionCapGetLoaded()
879 // This function returns a list of handles of loaded session, started
880 // from input 'handle'
881 //
882 // 'Handle' must be in valid loaded session handle range, but does not
883 // have to point to a loaded session.
884 // Return Type: TPMI_YES_NO
885 // YES if there are more handles available
886 // NO all the available handles has been returned
887 TPMI_YES_NO
SessionCapGetLoaded(TPMI_SH_POLICY handle,UINT32 count,TPML_HANDLE * handleList)888 SessionCapGetLoaded(
889 TPMI_SH_POLICY handle, // IN: start handle
890 UINT32 count, // IN: count of returned handles
891 TPML_HANDLE *handleList // OUT: list of handle
892 )
893 {
894 TPMI_YES_NO more = NO;
895 UINT32 i;
896
897 pAssert(HandleGetType(handle) == TPM_HT_LOADED_SESSION);
898
899 // Initialize output handle list
900 handleList->count = 0;
901
902 // The maximum count of handles we may return is MAX_CAP_HANDLES
903 if(count > MAX_CAP_HANDLES) count = MAX_CAP_HANDLES;
904
905 // Iterate session context ID slots to get loaded session handles
906 for(i = handle & HR_HANDLE_MASK; i < MAX_ACTIVE_SESSIONS; i++)
907 {
908 // If session is active
909 if(gr.contextArray[i] != 0)
910 {
911 // If session is loaded
912 if(gr.contextArray[i] <= MAX_LOADED_SESSIONS)
913 {
914 if(handleList->count < count)
915 {
916 SESSION *session;
917
918 // If we have not filled up the return list, add this
919 // session handle to it
920 // assume that this is going to be an HMAC session
921 handle = i + HMAC_SESSION_FIRST;
922 session = SessionGet(handle);
923 if(session->attributes.isPolicy)
924 handle = i + POLICY_SESSION_FIRST;
925 handleList->handle[handleList->count] = handle;
926 handleList->count++;
927 }
928 else
929 {
930 // If the return list is full but we still have loaded object
931 // available, report this and stop iterating
932 more = YES;
933 break;
934 }
935 }
936 }
937 }
938
939 return more;
940 }
941
942 //*** SessionCapGetSaved()
943 // This function returns a list of handles for saved session, starting at
944 // 'handle'.
945 //
946 // 'Handle' must be in a valid handle range, but does not have to point to a
947 // saved session
948 //
949 // Return Type: TPMI_YES_NO
950 // YES if there are more handles available
951 // NO all the available handles has been returned
952 TPMI_YES_NO
SessionCapGetSaved(TPMI_SH_HMAC handle,UINT32 count,TPML_HANDLE * handleList)953 SessionCapGetSaved(
954 TPMI_SH_HMAC handle, // IN: start handle
955 UINT32 count, // IN: count of returned handles
956 TPML_HANDLE *handleList // OUT: list of handle
957 )
958 {
959 TPMI_YES_NO more = NO;
960 UINT32 i;
961
962 #ifdef TPM_HT_SAVED_SESSION
963 pAssert(HandleGetType(handle) == TPM_HT_SAVED_SESSION);
964 #else
965 pAssert(HandleGetType(handle) == TPM_HT_ACTIVE_SESSION);
966 #endif
967
968 // Initialize output handle list
969 handleList->count = 0;
970
971 // The maximum count of handles we may return is MAX_CAP_HANDLES
972 if(count > MAX_CAP_HANDLES) count = MAX_CAP_HANDLES;
973
974 // Iterate session context ID slots to get loaded session handles
975 for(i = handle & HR_HANDLE_MASK; i < MAX_ACTIVE_SESSIONS; i++)
976 {
977 // If session is active
978 if(gr.contextArray[i] != 0)
979 {
980 // If session is saved
981 if(gr.contextArray[i] > MAX_LOADED_SESSIONS)
982 {
983 if(handleList->count < count)
984 {
985 // If we have not filled up the return list, add this
986 // session handle to it
987 handleList->handle[handleList->count] = i + HMAC_SESSION_FIRST;
988 handleList->count++;
989 }
990 else
991 {
992 // If the return list is full but we still have loaded object
993 // available, report this and stop iterating
994 more = YES;
995 break;
996 }
997 }
998 }
999 }
1000
1001 return more;
1002 }
1003
1004 //*** SessionCapGetLoadedNumber()
1005 // This function return the number of authorization sessions currently
1006 // loaded into TPM RAM.
1007 UINT32
SessionCapGetLoadedNumber(void)1008 SessionCapGetLoadedNumber(
1009 void
1010 )
1011 {
1012 return MAX_LOADED_SESSIONS - s_freeSessionSlots;
1013 }
1014
1015 //*** SessionCapGetLoadedAvail()
1016 // This function returns the number of additional authorization sessions, of
1017 // any type, that could be loaded into TPM RAM.
1018 // NOTE: In other implementations, this number may just be an estimate. The only
1019 // requirement for the estimate is, if it is one or more, then at least one
1020 // session must be loadable.
1021 UINT32
SessionCapGetLoadedAvail(void)1022 SessionCapGetLoadedAvail(
1023 void
1024 )
1025 {
1026 return s_freeSessionSlots;
1027 }
1028
1029 //*** SessionCapGetActiveNumber()
1030 // This function returns the number of active authorization sessions currently
1031 // being tracked by the TPM.
1032 UINT32
SessionCapGetActiveNumber(void)1033 SessionCapGetActiveNumber(
1034 void
1035 )
1036 {
1037 UINT32 i;
1038 UINT32 num = 0;
1039
1040 // Iterate the context array to find the number of non-zero slots
1041 for(i = 0; i < MAX_ACTIVE_SESSIONS; i++)
1042 {
1043 if(gr.contextArray[i] != 0) num++;
1044 }
1045
1046 return num;
1047 }
1048
1049 //*** SessionCapGetActiveAvail()
1050 // This function returns the number of additional authorization sessions, of any
1051 // type, that could be created. This not the number of slots for sessions, but
1052 // the number of additional sessions that the TPM is capable of tracking.
1053 UINT32
SessionCapGetActiveAvail(void)1054 SessionCapGetActiveAvail(
1055 void
1056 )
1057 {
1058 UINT32 i;
1059 UINT32 num = 0;
1060
1061 // Iterate the context array to find the number of zero slots
1062 for(i = 0; i < MAX_ACTIVE_SESSIONS; i++)
1063 {
1064 if(gr.contextArray[i] == 0) num++;
1065 }
1066
1067 return num;
1068 }