ia64/xen-unstable

changeset 6573:9ba52ccadc06

vTPM manager - Intel/IBM joint TPM Virtualization implementation for Xen.
This is a software implementation for people without h/w vTPM support.

Signed-off-by: Vinnie Scarlata <vincent.r.scarlata@intel.com>
Signed-off-by: Joseph Cihula <joseph.cihula@intel.com>
Signed-off-by: Steven Hand <steven@xensource.com>
author shand@ubuntu.eng.hq.xensource.com
date Tue Aug 30 11:39:25 2005 -0800 (2005-08-30)
parents edbdd7123d24
children ff536c11c178
files tools/vtpm_manager/COPYING tools/vtpm_manager/Makefile tools/vtpm_manager/README tools/vtpm_manager/Rules.mk tools/vtpm_manager/crypto/Makefile tools/vtpm_manager/crypto/crypto.c tools/vtpm_manager/crypto/crypto.h tools/vtpm_manager/crypto/hash.c tools/vtpm_manager/crypto/rsa.c tools/vtpm_manager/crypto/sym_crypto.c tools/vtpm_manager/crypto/sym_crypto.h tools/vtpm_manager/manager/Makefile tools/vtpm_manager/manager/dmictl.c tools/vtpm_manager/manager/securestorage.c tools/vtpm_manager/manager/tpmpassthrough.c tools/vtpm_manager/manager/vtpm_manager.c tools/vtpm_manager/manager/vtpm_manager.h tools/vtpm_manager/manager/vtpmd.c tools/vtpm_manager/manager/vtpmpriv.h tools/vtpm_manager/manager/vtsp.c tools/vtpm_manager/manager/vtsp.h tools/vtpm_manager/tcs/Makefile tools/vtpm_manager/tcs/contextmgr.c tools/vtpm_manager/tcs/contextmgr.h tools/vtpm_manager/tcs/tcs.c tools/vtpm_manager/tcs/tcs.h tools/vtpm_manager/tcs/tpmddl.h tools/vtpm_manager/tcs/transmit.c tools/vtpm_manager/util/Makefile tools/vtpm_manager/util/bsg.c tools/vtpm_manager/util/bsg.h tools/vtpm_manager/util/buffer.c tools/vtpm_manager/util/buffer.h tools/vtpm_manager/util/depend tools/vtpm_manager/util/hashtable.c tools/vtpm_manager/util/hashtable.h tools/vtpm_manager/util/hashtable_itr.c tools/vtpm_manager/util/hashtable_itr.h tools/vtpm_manager/util/hashtable_private.h tools/vtpm_manager/util/log.c tools/vtpm_manager/util/log.h tools/vtpm_manager/util/tcg.h
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/tools/vtpm_manager/COPYING	Tue Aug 30 11:39:25 2005 -0800
     1.3 @@ -0,0 +1,32 @@
     1.4 +// ===================================================================
     1.5 +// 
     1.6 +// Copyright (c) 2005, Intel Corp.
     1.7 +// All rights reserved.
     1.8 +//
     1.9 +// Redistribution and use in source and binary forms, with or without 
    1.10 +// modification, are permitted provided that the following conditions 
    1.11 +// are met:
    1.12 +//
    1.13 +//   * Redistributions of source code must retain the above copyright 
    1.14 +//     notice, this list of conditions and the following disclaimer.
    1.15 +//   * Redistributions in binary form must reproduce the above 
    1.16 +//     copyright notice, this list of conditions and the following 
    1.17 +//     disclaimer in the documentation and/or other materials provided 
    1.18 +//     with the distribution.
    1.19 +//   * Neither the name of Intel Corporation nor the names of its 
    1.20 +//     contributors may be used to endorse or promote products derived
    1.21 +//     from this software without specific prior written permission.
    1.22 +//
    1.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
    1.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
    1.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
    1.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
    1.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    1.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    1.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
    1.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    1.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
    1.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
    1.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
    1.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
    1.35 +// ===================================================================
     2.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     2.2 +++ b/tools/vtpm_manager/Makefile	Tue Aug 30 11:39:25 2005 -0800
     2.3 @@ -0,0 +1,31 @@
     2.4 +XEN_ROOT = ../..
     2.5 +
     2.6 +# Base definitions and rules
     2.7 +include $(XEN_ROOT)/tools/vtpm_manager/Rules.mk
     2.8 +
     2.9 +SUBDIRS		= crypto tcs util manager
    2.10 +
    2.11 +all: build
    2.12 +
    2.13 +build:
    2.14 +	@set -e; for subdir in $(SUBDIRS); do \
    2.15 +		$(MAKE) -C $$subdir $@; \
    2.16 +	done
    2.17 +
    2.18 +install: build
    2.19 +	@set -e; for subdir in $(SUBDIRS); do \
    2.20 +		$(MAKE) -C $$subdir $@; \
    2.21 +	done
    2.22 +
    2.23 +clean:
    2.24 +	@set -e; for subdir in $(SUBDIRS); do \
    2.25 +		$(MAKE) -C $$subdir $@; \
    2.26 +	done
    2.27 +
    2.28 +
    2.29 +mrproper:
    2.30 +	@set -e; for subdir in $(SUBDIRS); do \
    2.31 +		$(MAKE) -C $$subdir $@; \
    2.32 +	done
    2.33 +
    2.34 +
     3.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.2 +++ b/tools/vtpm_manager/README	Tue Aug 30 11:39:25 2005 -0800
     3.3 @@ -0,0 +1,89 @@
     3.4 +// ===================================================================
     3.5 +//
     3.6 +// Copyright (c) 2005, Intel Corp.
     3.7 +// All rights reserved.
     3.8 +//
     3.9 +// Redistribution and use in source and binary forms, with or without
    3.10 +// modification, are permitted provided that the following conditions
    3.11 +// are met:
    3.12 +//
    3.13 +//   * Redistributions of source code must retain the above copyright
    3.14 +//     notice, this list of conditions and the following disclaimer.
    3.15 +//   * Redistributions in binary form must reproduce the above
    3.16 +//     copyright notice, this list of conditions and the following
    3.17 +//     disclaimer in the documentation and/or other materials provided
    3.18 +//     with the distribution.
    3.19 +//   * Neither the name of Intel Corporation nor the names of its
    3.20 +//     contributors may be used to endorse or promote products derived
    3.21 +//     from this software without specific prior written permission.
    3.22 +//
    3.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    3.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    3.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
    3.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    3.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    3.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    3.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    3.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    3.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
    3.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    3.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
    3.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
    3.35 +// ===================================================================
    3.36 +
    3.37 +Directory Structure
    3.38 +===================
    3.39 +tools/vtpm_manager/crypto    -> crypto files
    3.40 +tools/vtpm_manager/TCS       -> TCS implementation
    3.41 +tools/vtpm_manager/util      -> Utility Library. Include disk-io and buffers.
    3.42 +tools/vtpm_manager/manager   -> VTPM Manager
    3.43 +
    3.44 +Compile Flags
    3.45 +===================
    3.46 +LOGGING_MODULES              -> How extensive logging happens
    3.47 +                                see util/log.h for more info
    3.48 +
    3.49 +VTPM_MULTI_VM                -> Defined: VTPMs run in their own VMs
    3.50 +                                Not Defined (default): VTPMs are processes
    3.51 +
    3.52 +# Debugging flags that may disappear without notice in the future
    3.53 +
    3.54 +DUMMY_BACKEND                -> vtpm_manager listens on /tmp/in.fifo and 
    3.55 +                                /tmp/out.fifo rather than backend
    3.56 +
    3.57 +MANUAL_DM_LAUNCH             -> User must manually launch & kill VTPMs
    3.58 +
    3.59 +USE_FIXED_SRK_AUTH           -> Do not randomly generate a random SRK & Owner auth
    3.60 +
    3.61 +Requirements
    3.62 +============
    3.63 +- xen-unstable 
    3.64 +- IBM frontend/backend vtpm driver patch
    3.65 +
    3.66 +Single-VM Flow
    3.67 +============================
    3.68 +- Launch the VTPM manager (vtpm_managerd) which which begins listening to the BE with one thread
    3.69 +  and listens to a named fifo that is shared by the vtpms to commuincate with the manager.
    3.70 +- VTPM Manager listens to TPM BE.
    3.71 +- When xend launches a tpm frontend equipped VM it contacts the manager over the vtpm backend. 
    3.72 +- When the manager receives the open message from the BE, it launches a vtpm
    3.73 +- Xend allows the VM to continue booting. 
    3.74 +- When a TPM request is issued to the front end, the front end transmits the TPM request to the backend.
    3.75 +- The manager receives the TPM requests and uses a named fifo to forward the request to the vtpm.
    3.76 +- The fifo listener begins listening for the reply from vtpm for the request.
    3.77 +- Vtpm processes request and replies to manager over shared named fifo.
    3.78 +- If needed, the vtpm may send a request to the vtpm_manager at any time to save it's secrets to disk.
    3.79 +- Manager receives response from vtpm and passes it back to backend for forwarding to guest.
    3.80 +
    3.81 +NOTES:
    3.82 +* SaveService SHOULD seal it's table before saving it to disk. However,
    3.83 +  the current Xen infrastructure does not provide a mechanism for this to be
    3.84 +  unsealed later. Specifically, the auth and wrapped key must be available ONLY
    3.85 +  to the service, or it's not even worth encrypting
    3.86 +
    3.87 +  In the future the vtpm manager will be protected by an early boot mechanism
    3.88 +  that will allow for better protection of it's data.
    3.89 +
    3.90 +TODO:
    3.91 +- Timeout on crashed vtpms
    3.92 +- create lock for shared fifo for talking to vtpms.
     4.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.2 +++ b/tools/vtpm_manager/Rules.mk	Tue Aug 30 11:39:25 2005 -0800
     4.3 @@ -0,0 +1,68 @@
     4.4 +# Base definitions and rules (XEN_ROOT must be defined in including Makefile)
     4.5 +include $(XEN_ROOT)/tools/Rules.mk
     4.6 +
     4.7 +#
     4.8 +# Tool definitions
     4.9 +#
    4.10 +
    4.11 +# Installation program and options
    4.12 +INSTALL         = install
    4.13 +INSTALL_PROG    = $(INSTALL) -m0755
    4.14 +INSTALL_DIR     = $(INSTALL) -d -m0755
    4.15 +
    4.16 +# Xen tools installation directory
    4.17 +TOOLS_INSTALL_DIR = $(DESTDIR)/usr/bin
    4.18 +
    4.19 +# General compiler flags
    4.20 +CFLAGS	= -Wall -Werror -g3 -I.
    4.21 +
    4.22 +# For generating dependencies
    4.23 +CFLAGS	+= -Wp,-MD,.$(@F).d
    4.24 +
    4.25 +DEP_FILES	= .*.d
    4.26 +
    4.27 +# Generic project files
    4.28 +HDRS	= $(wildcard *.h)
    4.29 +SRCS	= $(wildcard *.c)
    4.30 +OBJS	= $(patsubst %.c,%.o,$(SRCS))
    4.31 +
    4.32 +# Generic (non-header) dependencies
    4.33 +$(SRCS): Makefile $(XEN_ROOT)/tools/Rules.mk $(XEN_ROOT)/tools/vtpm_manager/Rules.mk
    4.34 +
    4.35 +$(OBJS): $(SRCS)
    4.36 +
    4.37 +-include $(DEP_FILES)
    4.38 +
    4.39 +# Make sure these are just rules
    4.40 +.PHONY : all build install clean
    4.41 +
    4.42 +#
    4.43 +# Project-specific definitions
    4.44 +#
    4.45 +
    4.46 +# Logging Level. See utils/tools.h for usage
    4.47 +CFLAGS += -DLOGGING_MODULES="(BITMASK(VTPM_LOG_TCS)|BITMASK(VTPM_LOG_VTSP)|BITMASK(VTPM_LOG_VTPM)|BITMASK(VTPM_LOG_VTPM_DEEP))"
    4.48 +
    4.49 +# Silent Mode
    4.50 +#CFLAGS += -DLOGGING_MODULES=0x0
    4.51 +#CFLAGS += -DLOGGING_MODULES=0xff
    4.52 +
    4.53 +# Use frontend/backend pairs between manager & DMs?
    4.54 +#CFLAGS += -DVTPM_MULTI_VM
    4.55 +
    4.56 +# vtpm_manager listens on /tmp/in.fifo and /tmp/out.fifo rather than backend
    4.57 +#CFLAGS += -DDUMMY_BACKEND
    4.58 +
    4.59 +# Do not have manager launch DMs.
    4.60 +#CFLAGS += -DMANUAL_DM_LAUNCH
    4.61 +
    4.62 +# Fixed SRK
    4.63 +CFLAGS += -DUSE_FIXED_SRK_AUTH
    4.64 +
    4.65 +# TPM Hardware Device or TPM Simulator
    4.66 +#CFLAGS += -DTPM_HWDEV
    4.67 +
    4.68 +# Include
    4.69 +CFLAGS += -I$(XEN_ROOT)/tools/vtpm_manager/crypto
    4.70 +CFLAGS += -I$(XEN_ROOT)/tools/vtpm_manager/util
    4.71 +CFLAGS += -I$(XEN_ROOT)/tools/vtpm_manager/tcs
     5.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     5.2 +++ b/tools/vtpm_manager/crypto/Makefile	Tue Aug 30 11:39:25 2005 -0800
     5.3 @@ -0,0 +1,18 @@
     5.4 +XEN_ROOT = ../../..
     5.5 +include $(XEN_ROOT)/tools/vtpm_manager/Rules.mk
     5.6 +
     5.7 +BIN		= libtcpaCrypto.a
     5.8 +
     5.9 +all: build
    5.10 +
    5.11 +build: $(BIN)
    5.12 +
    5.13 +install: build
    5.14 +
    5.15 +clean:
    5.16 +	rm -f *.a *.so *.o *.rpm $(DEP_FILES)
    5.17 +
    5.18 +mrproper: clean
    5.19 +
    5.20 +$(BIN): $(OBJS)
    5.21 +	$(AR) rcs $(BIN) $(OBJS)
     6.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     6.2 +++ b/tools/vtpm_manager/crypto/crypto.c	Tue Aug 30 11:39:25 2005 -0800
     6.3 @@ -0,0 +1,88 @@
     6.4 +// ===================================================================
     6.5 +// 
     6.6 +// Copyright (c) 2005, Intel Corp.
     6.7 +// All rights reserved.
     6.8 +//
     6.9 +// Redistribution and use in source and binary forms, with or without 
    6.10 +// modification, are permitted provided that the following conditions 
    6.11 +// are met:
    6.12 +//
    6.13 +//   * Redistributions of source code must retain the above copyright 
    6.14 +//     notice, this list of conditions and the following disclaimer.
    6.15 +//   * Redistributions in binary form must reproduce the above 
    6.16 +//     copyright notice, this list of conditions and the following 
    6.17 +//     disclaimer in the documentation and/or other materials provided 
    6.18 +//     with the distribution.
    6.19 +//   * Neither the name of Intel Corporation nor the names of its 
    6.20 +//     contributors may be used to endorse or promote products derived
    6.21 +//     from this software without specific prior written permission.
    6.22 +//
    6.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
    6.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
    6.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
    6.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
    6.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    6.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    6.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
    6.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    6.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
    6.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
    6.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
    6.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
    6.35 +// ===================================================================
    6.36 +// 
    6.37 +// crypto.c
    6.38 +// 
    6.39 +//  This file will handle all the TPM Crypto functionality
    6.40 +// 
    6.41 +// ==================================================================
    6.42 +
    6.43 +#include <string.h>
    6.44 +#include <openssl/crypto.h>
    6.45 +#include <openssl/err.h>
    6.46 +#include <openssl/evp.h>
    6.47 +#include <openssl/rand.h>
    6.48 +#include "crypto.h"
    6.49 +#include "log.h"
    6.50 +
    6.51 +/**
    6.52 + * Initialize cryptography library
    6.53 + * @rand: random seed
    6.54 + * @size: size of @rand
    6.55 + */
    6.56 +void Crypto_Init(const BYTE* rand, int size) {
    6.57 +	ERR_load_crypto_strings();
    6.58 +  CRYPTO_malloc_init();
    6.59 +  OpenSSL_add_all_algorithms();
    6.60 +  SYM_CIPHER = EVP_aes_128_cbc();
    6.61 +  RAND_poll();
    6.62 +  if (rand == NULL)
    6.63 +    return;
    6.64 +
    6.65 +  RAND_add(rand, size, size);
    6.66 +}
    6.67 +
    6.68 +/**
    6.69 + * Shutdown cryptography library
    6.70 + */
    6.71 +void Crypto_Exit() {
    6.72 +  ERR_free_strings();
    6.73 +  ERR_remove_state(0);
    6.74 +  EVP_cleanup();
    6.75 +}
    6.76 +
    6.77 +
    6.78 +/**
    6.79 + * Get random data
    6.80 + * @data: (OUT) Random data
    6.81 + * @size: Size of @data
    6.82 + */
    6.83 +void Crypto_GetRandom(void* data, int size) {
    6.84 +  int result;
    6.85 +  
    6.86 +  result = RAND_pseudo_bytes((BYTE*) data, size);
    6.87 +  
    6.88 +  if (result <= 0) 
    6.89 +    vtpmlogerror (VTPM_LOG_CRYPTO, "RAND_pseudo_bytes failed: %s\n",
    6.90 +	     ERR_error_string (ERR_get_error(), NULL));
    6.91 +}
     7.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     7.2 +++ b/tools/vtpm_manager/crypto/crypto.h	Tue Aug 30 11:39:25 2005 -0800
     7.3 @@ -0,0 +1,175 @@
     7.4 +// ===================================================================
     7.5 +// 
     7.6 +// Copyright (c) 2005, Intel Corp.
     7.7 +// All rights reserved.
     7.8 +//
     7.9 +// Redistribution and use in source and binary forms, with or without 
    7.10 +// modification, are permitted provided that the following conditions 
    7.11 +// are met:
    7.12 +//
    7.13 +//   * Redistributions of source code must retain the above copyright 
    7.14 +//     notice, this list of conditions and the following disclaimer.
    7.15 +//   * Redistributions in binary form must reproduce the above 
    7.16 +//     copyright notice, this list of conditions and the following 
    7.17 +//     disclaimer in the documentation and/or other materials provided 
    7.18 +//     with the distribution.
    7.19 +//   * Neither the name of Intel Corporation nor the names of its 
    7.20 +//     contributors may be used to endorse or promote products derived
    7.21 +//     from this software without specific prior written permission.
    7.22 +//
    7.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
    7.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
    7.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
    7.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
    7.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    7.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    7.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
    7.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    7.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
    7.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
    7.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
    7.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
    7.35 +// ===================================================================
    7.36 +// 
    7.37 +// crypto.h
    7.38 +// 
    7.39 +//  This file defines the TPM Crypto API
    7.40 +//
    7.41 +// ==================================================================
    7.42 +
    7.43 +#ifndef __CRYPTO_H__
    7.44 +#define __CRYPTO_H__
    7.45 +
    7.46 +#include <stddef.h>
    7.47 +#include <stdint.h>
    7.48 +#include <stdbool.h>
    7.49 +
    7.50 +#include "tcg.h"
    7.51 +#include "sym_crypto.h"
    7.52 +
    7.53 +#define CRYPTO_MAX_SIG_SIZE (2048 / 8)
    7.54 +#define CRYPTO_MAX_RSA_KEY_SIZE (4096 / 8) //in bytes
    7.55 +
    7.56 +#define OAEP_P "TCPA"
    7.57 +#define OAEP_P_SIZE 4
    7.58 +
    7.59 +// Algorithms supported by crypto. Stored in CRYPTO_INFO.algorithmID
    7.60 +#define CRYPTO_ALGORITH_RSA 0x01
    7.61 +
    7.62 +// Supported Encryption Schemes CRYPTO_INFO.encScheme
    7.63 +#define CRYPTO_ES_NONE 0x0001
    7.64 +#define CRYPTO_ES_RSAESPKCSv15 0x0002
    7.65 +#define CRYPTO_ES_RSAESOAEP_SHA1_MGF1 0x0003
    7.66 +
    7.67 +// Supported Signature schemes CRYPTO_INFO.sigScheme
    7.68 +#define CRYPTO_SS_NONE 0x0001
    7.69 +#define CRYPTO_SS_RSASSAPKCS1v15_SHA1 0x0002
    7.70 +#define CRYPTO_SS_RSASSAPKCS1v15_DER 0x0003
    7.71 +
    7.72 +typedef struct CRYPTO_INFO {
    7.73 +  void *keyInfo;
    7.74 +  UINT32 algorithmID;
    7.75 +  UINT32 encScheme;
    7.76 +  UINT32 sigScheme;
    7.77 +} CRYPTO_INFO;
    7.78 +
    7.79 +
    7.80 +void Crypto_Init(const BYTE* rand, int size);
    7.81 +
    7.82 +void Crypto_Exit();
    7.83 +
    7.84 +void Crypto_GetRandom(void* data, int size);
    7.85 +
    7.86 +void Crypto_HMAC(   const BYTE* text, 
    7.87 +                    int text_len, 
    7.88 +                    const BYTE* key, 
    7.89 +                    int key_len,
    7.90 +                    BYTE* digest);
    7.91 +
    7.92 +TPM_RESULT Crypto_HMAC_buf (const buffer_t * text,
    7.93 +                            const buffer_t * key,
    7.94 +                            BYTE * o_digest); /* presumably of 20 bytes */
    7.95 +    
    7.96 +void Crypto_SHA1Full(   const BYTE* text, 
    7.97 +                        UINT32 size,
    7.98 +                        BYTE* hash); //Complete 3part SHA1
    7.99 +
   7.100 +// o_hash needs to be large enough to hold the digest, ie 20 bytes
   7.101 +TPM_RESULT Crypto_SHA1Full_buf (const buffer_t * buf,
   7.102 +                                BYTE * o_hash);
   7.103 +    
   7.104 +void Crypto_SHA1Start(UINT32* maxNumBytes);
   7.105 +void Crypto_SHA1Update(int numBytes, const BYTE* hashData);
   7.106 +void Crypto_SHA1Complete(   int hashDataSize, 
   7.107 +                            const BYTE* hashData, 
   7.108 +                            BYTE* hashValue);
   7.109 +
   7.110 +void Crypto_RSACreateKey(   /*in*/ UINT32 keySize,
   7.111 +                            /*in*/ UINT32 pubExpSize, 
   7.112 +                            /*in*/ BYTE *pubExp,
   7.113 +                            /*out*/ UINT32 *privExpSize, 
   7.114 +                            /*out*/ BYTE *privExp,
   7.115 +                            /*out*/ UINT32 *modulusSize,
   7.116 +                            /*out*/ BYTE *modulus,
   7.117 +                            /*out*/ CRYPTO_INFO *keys);
   7.118 +                            
   7.119 +void Crypto_RSABuildCryptoInfo( /*[IN]*/ UINT32 pubExpSize, 
   7.120 +                                /*[IN]*/ BYTE *pubExp,
   7.121 +                                /*[IN]*/ UINT32 privExpSize, 
   7.122 +                                /*[IN]*/ BYTE *privExp,
   7.123 +                                /*[IN]*/ UINT32 modulusSize, 
   7.124 +                                /*[IN]*/ BYTE *modulus, 
   7.125 +                                /*[OUT]*/ CRYPTO_INFO* cryptoInfo);
   7.126 +                                
   7.127 +void Crypto_RSABuildCryptoInfoPublic(   /*[IN]*/ UINT32 pubExpSize, 
   7.128 +                                        /*[IN]*/ BYTE *pubExp,
   7.129 +                                        /*[IN]*/ UINT32 modulusSize, 
   7.130 +                                        /*[IN]*/ BYTE *modulus, 
   7.131 +                                        CRYPTO_INFO* cryptoInfo);
   7.132 +
   7.133 +//
   7.134 +// symmetric pack and unpack operations
   7.135 +//
   7.136 +TPM_RESULT Crypto_RSAPackCryptoInfo (const CRYPTO_INFO* cryptoInfo,
   7.137 +                                     BYTE ** io_buf, UINT32 * io_buflen);
   7.138 +
   7.139 +TPM_RESULT Crypto_RSAUnpackCryptoInfo (CRYPTO_INFO * ci,
   7.140 +                                       BYTE * in, UINT32 len,
   7.141 +                                       UINT32 * o_lenread);
   7.142 +
   7.143 +                             
   7.144 +// return 0 on success, -1 on error
   7.145 +int Crypto_RSAEnc(  CRYPTO_INFO *keys,
   7.146 +                    UINT32 inDataSize,
   7.147 +                    BYTE *inData,
   7.148 +                    /*out*/ UINT32 *outDataSize,
   7.149 +                    /*out*/ BYTE *outData);
   7.150 +
   7.151 +// return 0 on success, -1 on error
   7.152 +int Crypto_RSADec(  CRYPTO_INFO *keys,
   7.153 +                    UINT32 inDataSize,
   7.154 +                    BYTE *inData,
   7.155 +                    /*out*/ UINT32 *outDataSize,
   7.156 +                    /*out*/ BYTE *outData);
   7.157 +
   7.158 +// return 0 on success, -1 on error
   7.159 +int Crypto_RSASign( CRYPTO_INFO *keys,
   7.160 +                    UINT32 inDataSize,
   7.161 +                    BYTE *inData,
   7.162 +                    /*out*/ UINT32 *sigSize,
   7.163 +                    /*out*/ BYTE *sig);
   7.164 +
   7.165 +bool Crypto_RSAVerify(  CRYPTO_INFO *keys,
   7.166 +                        UINT32 inDataSize,
   7.167 +                        BYTE *inData,
   7.168 +                        UINT32 sigSize,
   7.169 +                        BYTE *sig);
   7.170 +
   7.171 +//private:
   7.172 +int RSA_verify_DER(int dtype, unsigned char *m, unsigned int m_len,
   7.173 +                   unsigned char *sigbuf, unsigned int siglen, CRYPTO_INFO *key);
   7.174 +
   7.175 +int RSA_sign_DER(int type, unsigned char *m, unsigned int m_len,
   7.176 +              unsigned char *sigret, unsigned int *siglen, CRYPTO_INFO *key);
   7.177 +
   7.178 +#endif // __CRYPTO_H__
     8.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     8.2 +++ b/tools/vtpm_manager/crypto/hash.c	Tue Aug 30 11:39:25 2005 -0800
     8.3 @@ -0,0 +1,153 @@
     8.4 +// ===================================================================
     8.5 +// 
     8.6 +// Copyright (c) 2005, Intel Corp.
     8.7 +// All rights reserved.
     8.8 +//
     8.9 +// Redistribution and use in source and binary forms, with or without 
    8.10 +// modification, are permitted provided that the following conditions 
    8.11 +// are met:
    8.12 +//
    8.13 +//   * Redistributions of source code must retain the above copyright 
    8.14 +//     notice, this list of conditions and the following disclaimer.
    8.15 +//   * Redistributions in binary form must reproduce the above 
    8.16 +//     copyright notice, this list of conditions and the following 
    8.17 +//     disclaimer in the documentation and/or other materials provided 
    8.18 +//     with the distribution.
    8.19 +//   * Neither the name of Intel Corporation nor the names of its 
    8.20 +//     contributors may be used to endorse or promote products derived
    8.21 +//     from this software without specific prior written permission.
    8.22 +//
    8.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
    8.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
    8.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
    8.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
    8.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    8.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    8.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
    8.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    8.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
    8.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
    8.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
    8.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
    8.35 +// ===================================================================
    8.36 +// 
    8.37 +// hash.c
    8.38 +// 
    8.39 +//  This file will handle all the TPM Hash functionality
    8.40 +//
    8.41 +// ==================================================================
    8.42 +
    8.43 +#include <string.h>
    8.44 +#include <openssl/crypto.h>
    8.45 +#include <openssl/err.h>
    8.46 +#include <openssl/evp.h>
    8.47 +#include <openssl/rand.h>
    8.48 +#include <openssl/hmac.h>
    8.49 +#include <openssl/sha.h>
    8.50 +#include <openssl/bn.h>
    8.51 +#include <openssl/rsa.h>
    8.52 +
    8.53 +#include "tcg.h"         // for TPM_SUCCESS
    8.54 +#include "crypto.h"
    8.55 +
    8.56 +static SHA_CTX g_shaContext;
    8.57 +
    8.58 +void Crypto_HMAC(   const BYTE* text, 
    8.59 +                    int text_len, 
    8.60 +                    const BYTE* key, 
    8.61 +                    int key_len, 
    8.62 +                    BYTE* digest) {
    8.63 +  if (text == NULL || key == NULL || text_len == 0 || key_len == 0) 
    8.64 +    return;
    8.65 +  
    8.66 +  HMAC(EVP_sha1(), key, key_len, text, text_len, digest, NULL);
    8.67 +}
    8.68 +
    8.69 +TPM_RESULT Crypto_HMAC_buf (const buffer_t * text,
    8.70 +			    const buffer_t * key,
    8.71 +			    BYTE * o_digest) { /* presumably of 20 bytes */
    8.72 +  
    8.73 +  Crypto_HMAC (text->bytes, text->size, 
    8.74 +	       key->bytes, key->size,
    8.75 +	       o_digest);
    8.76 +  
    8.77 +  return TPM_SUCCESS;
    8.78 +}
    8.79 +
    8.80 +
    8.81 +/*
    8.82 + * SHA1
    8.83 + * (OUT) Create a SHA1 hash of text. Calls all three SHA1 steps internally
    8.84 + */
    8.85 +void Crypto_SHA1Full( const BYTE* text, 
    8.86 +      uint32_t size, 
    8.87 +      BYTE* hash) {
    8.88 +
    8.89 +  if (text == NULL || size == 0) 
    8.90 +    return;
    8.91 +  
    8.92 +  // Run SHA1Start + SHAUpdate (if necessary) + SHAComplete
    8.93 +  uint32_t maxBytes; // Not used for anything
    8.94 +  Crypto_SHA1Start(&maxBytes);
    8.95 +  
    8.96 +  while (size > 64){
    8.97 +    Crypto_SHA1Update(64, text); 
    8.98 +    size -= 64;
    8.99 +    text += 64;
   8.100 +  }
   8.101 +  
   8.102 +  Crypto_SHA1Complete(size, text, hash);
   8.103 +}
   8.104 +
   8.105 +// same thing using buffer_t
   8.106 +TPM_RESULT Crypto_SHA1Full_buf (const buffer_t * buf,
   8.107 +                                 BYTE * o_digest) {
   8.108 +
   8.109 +  if (buf->bytes == NULL || buf->size == 0) 
   8.110 +    return TPM_BAD_PARAMETER;
   8.111 +  
   8.112 +  Crypto_SHA1Full (buf->bytes, buf->size, o_digest);
   8.113 +  
   8.114 +  return TPM_SUCCESS;
   8.115 +}
   8.116 +
   8.117 +
   8.118 +/*
   8.119 + * Initialize SHA1
   8.120 + * (OUT) Maximum number of bytes that can be sent to SHA1Update. 
   8.121 + *   Must be a multiple of 64 bytes.
   8.122 + */
   8.123 +void Crypto_SHA1Start(uint32_t* maxNumBytes) {
   8.124 +  int max = SHA_CBLOCK;
   8.125 +  // Initialize the crypto library
   8.126 +  SHA1_Init(&g_shaContext);
   8.127 +  *maxNumBytes = max;
   8.128 +}
   8.129 +
   8.130 +/*
   8.131 + * Process SHA1
   8.132 + * @numBytes: (IN) The number of bytes in hashData. 
   8.133 + *       Must be a multiple of 64 bytes.
   8.134 + * @hashData: (IN) Bytes to be hashed.
   8.135 + */
   8.136 +void Crypto_SHA1Update(int numBytes, const BYTE* hashData) {
   8.137 +
   8.138 +  if (hashData == NULL || numBytes == 0 || numBytes%64 != 0) 
   8.139 +    return;
   8.140 +  
   8.141 +  SHA1_Update(&g_shaContext, hashData, numBytes); 
   8.142 +}
   8.143 +
   8.144 +/*
   8.145 + * Complete the SHA1 process
   8.146 + * @hashDataSize: (IN) Number of bytes in hashData.
   8.147 + *       Must be a multiple of 64 bytes.
   8.148 + * @hashData: (IN) Final bytes to be hashed.
   8.149 + * @hashValue: (OUT) The output of the SHA-1 hash.
   8.150 + */
   8.151 +void Crypto_SHA1Complete(int hashDataSize, 
   8.152 +			 const BYTE* hashData, 
   8.153 +			 BYTE* hashValue) {
   8.154 +  SHA1_Update(&g_shaContext, hashData, hashDataSize);
   8.155 +  SHA1_Final(hashValue, &g_shaContext);
   8.156 +}
     9.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     9.2 +++ b/tools/vtpm_manager/crypto/rsa.c	Tue Aug 30 11:39:25 2005 -0800
     9.3 @@ -0,0 +1,434 @@
     9.4 +// ===================================================================
     9.5 +// 
     9.6 +// Copyright (c) 2005, Intel Corp.
     9.7 +// All rights reserved.
     9.8 +//
     9.9 +// Redistribution and use in source and binary forms, with or without 
    9.10 +// modification, are permitted provided that the following conditions 
    9.11 +// are met:
    9.12 +//
    9.13 +//   * Redistributions of source code must retain the above copyright 
    9.14 +//     notice, this list of conditions and the following disclaimer.
    9.15 +//   * Redistributions in binary form must reproduce the above 
    9.16 +//     copyright notice, this list of conditions and the following 
    9.17 +//     disclaimer in the documentation and/or other materials provided 
    9.18 +//     with the distribution.
    9.19 +//   * Neither the name of Intel Corporation nor the names of its 
    9.20 +//     contributors may be used to endorse or promote products derived
    9.21 +//     from this software without specific prior written permission.
    9.22 +//
    9.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
    9.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
    9.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
    9.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
    9.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    9.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    9.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
    9.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    9.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
    9.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
    9.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
    9.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
    9.35 +// ===================================================================
    9.36 +// 
    9.37 +// rsa.c
    9.38 +// 
    9.39 +//  This file will handle all the TPM RSA crypto functionality
    9.40 +// 
    9.41 +// ==================================================================
    9.42 +
    9.43 +#include <string.h>
    9.44 +#include <openssl/crypto.h>
    9.45 +#include <openssl/evp.h>
    9.46 +#include <openssl/bn.h>
    9.47 +#include <openssl/rsa.h>
    9.48 +#include <openssl/rand.h>
    9.49 +#include <openssl/x509.h>
    9.50 +
    9.51 +#include <openssl/err.h>
    9.52 +#include <stdio.h>
    9.53 +
    9.54 +#include "tcg.h"
    9.55 +#include "buffer.h"
    9.56 +#include "crypto.h"
    9.57 +#include "log.h"
    9.58 +
    9.59 +void Crypto_RSACreateKey(   /*in*/ UINT32 keySize,
    9.60 +                            /*in*/ UINT32 pubExpSize, 
    9.61 +                            /*in*/ BYTE *pubExp,
    9.62 +                            /*out*/ UINT32 *privExpSize, 
    9.63 +                            /*out*/ BYTE *privExp,
    9.64 +                            /*out*/ UINT32 *modulusSize,        
    9.65 +                            /*out*/ BYTE *modulus,
    9.66 +                            /*out*/ CRYPTO_INFO *keys) {
    9.67 +  unsigned long e_value;
    9.68 +  
    9.69 +  if (pubExpSize == 0) // Default e = 2^16+1
    9.70 +    e_value = (0x01 << 16) + 1;
    9.71 +  else {
    9.72 +    // This is not supported, but the following line MIGHT work
    9.73 +    // under then assumption that the format is BigNum compatable
    9.74 +    // Though it's not in the spec, so who knows what it is.
    9.75 +    // Forcing the default.
    9.76 +    //BN_bin2bn(pubExp, pubExpSize, NULL);
    9.77 +    e_value = (0x01 << 16) + 1;
    9.78 +  }
    9.79 +
    9.80 +  RSA *rsa = RSA_generate_key(keySize, e_value, NULL, NULL);
    9.81 +  
    9.82 +  if (keys) {
    9.83 +    keys->keyInfo = rsa;
    9.84 +    keys->algorithmID = CRYPTO_ALGORITH_RSA;
    9.85 +  }
    9.86 +  
    9.87 +  if (modulus)   *modulusSize   = BN_bn2bin(rsa->n, modulus);
    9.88 +  if (privExp)   *privExpSize   = BN_bn2bin(rsa->d, privExp);
    9.89 +}
    9.90 +
    9.91 +// Create a CRYPTO_INFO struct from the BYTE * key parts. 
    9.92 +// If pubExp info is NULL, use TCG default.
    9.93 +// If there is a remainder while calculating the privExp, return FALSE.
    9.94 +
    9.95 +void Crypto_RSABuildCryptoInfo( /*[IN]*/ UINT32 pubExpSize, 
    9.96 +                                /*[IN]*/ BYTE *pubExp,
    9.97 +                                /*[IN]*/ UINT32 privExpSize, 
    9.98 +                                /*[IN]*/ BYTE *privExp,
    9.99 +                                /*[IN]*/ UINT32 modulusSize, 
   9.100 +                                /*[IN]*/ BYTE *modulus, 
   9.101 +                                CRYPTO_INFO* cryptoInfo) {
   9.102 +  cryptoInfo->keyInfo = RSA_new();
   9.103 +  RSA *rsa = (RSA *) cryptoInfo->keyInfo;
   9.104 +  
   9.105 +  rsa->e = BN_new();
   9.106 +  
   9.107 +  if (pubExpSize == 0) { // Default e = 2^16+1
   9.108 +    BN_set_bit(rsa->e, 16);
   9.109 +    BN_set_bit(rsa->e, 0);
   9.110 +  } else {
   9.111 +    // This is not supported, but the following line MIGHT work
   9.112 +    // under then assumption that the format is BigNum compatable
   9.113 +    // Though it's not in the spec, so who knows what it is.
   9.114 +    // Forcing the default.
   9.115 +    //BN_bin2bn(pubExp, pubExpSize, NULL);
   9.116 +    BN_set_bit(rsa->e, 16);
   9.117 +    BN_set_bit(rsa->e, 0);
   9.118 +  }
   9.119 +  
   9.120 +  rsa->n = BN_bin2bn(modulus, modulusSize, NULL);
   9.121 +  rsa->d = BN_bin2bn(privExp, privExpSize, NULL);
   9.122 +}
   9.123 +
   9.124 +// Create a CRYPTO_INFO struct from the BYTE * key parts. 
   9.125 +// If pubExp info is NULL, use TCG default.
   9.126 +// If there is a remainder while calculating the privExp, return FALSE.
   9.127 +
   9.128 +void Crypto_RSABuildCryptoInfoPublic(   /*[IN]*/ UINT32 pubExpSize, 
   9.129 +                                        /*[IN]*/ BYTE *pubExp,
   9.130 +                                        /*[IN]*/ UINT32 modulusSize, 
   9.131 +                                        /*[IN]*/ BYTE *modulus, 
   9.132 +                                        CRYPTO_INFO* cryptoInfo) {
   9.133 +  cryptoInfo->keyInfo = RSA_new();
   9.134 +  RSA *rsa = (RSA *) cryptoInfo->keyInfo;
   9.135 +  
   9.136 +  rsa->e = BN_new();
   9.137 +  
   9.138 +  if (pubExpSize == 0) { // Default e = 2^16+1
   9.139 +    BN_set_bit(rsa->e, 16);
   9.140 +    BN_set_bit(rsa->e, 0);
   9.141 +  } else {
   9.142 +    // This is not supported, but the following line MIGHT work
   9.143 +    // under then assumption that the format is BigNum compatable
   9.144 +    // Though it's not in the spec, so who knows what it is.
   9.145 +    // Forcing the default.
   9.146 +    //BN_bin2bn(pubExp, pubExpSize, NULL);
   9.147 +    BN_set_bit(rsa->e, 16);
   9.148 +    BN_set_bit(rsa->e, 0);
   9.149 +  }
   9.150 +  
   9.151 +  rsa->n = BN_bin2bn(modulus, modulusSize, NULL);
   9.152 +  
   9.153 +}
   9.154 +
   9.155 +int Crypto_RSAEnc(  CRYPTO_INFO *key,
   9.156 +		    UINT32 inDataSize,
   9.157 +		    BYTE *inData,
   9.158 +		    /*out*/ UINT32 *outDataSize,
   9.159 +		    /*out*/ BYTE *outData) {
   9.160 +  RSA *rsa = (RSA *) key->keyInfo;
   9.161 +  UINT32 paddedDataSize = RSA_size (rsa);
   9.162 +  BYTE *paddedData = (BYTE *)malloc(sizeof(BYTE) * paddedDataSize);
   9.163 +  int rc;
   9.164 +    
   9.165 +  if (paddedData == NULL) 
   9.166 +    return -1;
   9.167 +
   9.168 +  *outDataSize = 0;
   9.169 +  
   9.170 +  switch (key->encScheme) {
   9.171 +  case CRYPTO_ES_RSAESPKCSv15:
   9.172 +    if (RSA_padding_add_PKCS1_type_2(paddedData, paddedDataSize, inData, inDataSize) <= 0) {
   9.173 +      rc = -1; 
   9.174 +      goto abort_egress;
   9.175 +    }
   9.176 +    break;
   9.177 +  case CRYPTO_ES_RSAESOAEP_SHA1_MGF1:
   9.178 +    if (RSA_padding_add_PKCS1_OAEP(paddedData,paddedDataSize,inData,inDataSize, (BYTE *) OAEP_P,OAEP_P_SIZE) <= 0 ) {
   9.179 +      rc = -1; 
   9.180 +      goto abort_egress;
   9.181 +    }
   9.182 +    break;
   9.183 +  default:
   9.184 +    rc = -1; 
   9.185 +    goto abort_egress;
   9.186 +  }
   9.187 +  
   9.188 +  rc = RSA_public_encrypt(paddedDataSize, paddedData, outData, rsa, RSA_NO_PADDING);
   9.189 +  if (rc == -1)
   9.190 +    goto abort_egress; 
   9.191 +   
   9.192 +  *outDataSize = rc;
   9.193 +  
   9.194 +  if (rc > 0) rc = 0;
   9.195 +  
   9.196 +  goto egress;
   9.197 +  
   9.198 + abort_egress:
   9.199 + egress:
   9.200 +  
   9.201 +  if (paddedData) 
   9.202 +    free (paddedData);
   9.203 +  return rc;
   9.204 +  
   9.205 +}
   9.206 +
   9.207 +int Crypto_RSADec(  CRYPTO_INFO *key,
   9.208 +                    UINT32 inDataSize,
   9.209 +                    BYTE *inData,
   9.210 +                    /*out*/ UINT32 *outDataSize,
   9.211 +                    /*out*/ BYTE *outData) {
   9.212 +  
   9.213 +  RSA *rsa = (RSA *) key->keyInfo;
   9.214 +  UINT32 paddedDataSize = RSA_size (rsa);
   9.215 +  BYTE *paddedData = (BYTE *)malloc(sizeof(BYTE) * paddedDataSize);
   9.216 +  int rc;
   9.217 +  
   9.218 +  if (paddedData == NULL)
   9.219 +    goto abort_egress;
   9.220 +  
   9.221 +  rc = RSA_private_decrypt(inDataSize, inData, paddedData, rsa, RSA_NO_PADDING);
   9.222 +  if (rc == -1) {
   9.223 +    vtpmlogerror(VTPM_LOG_CRYPTO, "RSA_private_decrypt: %s\n", ERR_error_string(ERR_get_error(), NULL));
   9.224 +    goto abort_egress;
   9.225 +  }
   9.226 +  
   9.227 +  paddedDataSize = rc;
   9.228 +  
   9.229 +  switch (key->encScheme) {
   9.230 +  case CRYPTO_ES_RSAESPKCSv15:
   9.231 +    rc = RSA_padding_check_PKCS1_type_2 (outData, paddedDataSize,
   9.232 +					 paddedData + 1, paddedDataSize - 1,
   9.233 +					 RSA_size(rsa));
   9.234 +    if (rc == -1) {
   9.235 +      vtpmlogerror(VTPM_LOG_CRYPTO, "RSA_padding_check_PKCS1_type_2: %s\n", 
   9.236 +	      ERR_error_string(ERR_get_error(), NULL));
   9.237 +      goto abort_egress;
   9.238 +    }
   9.239 +    *outDataSize = rc;
   9.240 +    break;
   9.241 +  case CRYPTO_ES_RSAESOAEP_SHA1_MGF1:
   9.242 +    rc = RSA_padding_check_PKCS1_OAEP(outData, paddedDataSize,
   9.243 +				      paddedData + 1, paddedDataSize - 1,
   9.244 +				      RSA_size(rsa),
   9.245 +				      (BYTE *) OAEP_P, OAEP_P_SIZE);
   9.246 +    if (rc == -1) {
   9.247 +      vtpmlogerror(VTPM_LOG_CRYPTO, "RSA_padding_check_PKCS1_OAEP: %s\n",
   9.248 +	      ERR_error_string(ERR_get_error(), NULL));
   9.249 +      goto abort_egress;
   9.250 +    }
   9.251 +    *outDataSize = rc;
   9.252 +    break;
   9.253 +  default:
   9.254 +    *outDataSize = 0;
   9.255 +  }
   9.256 +  
   9.257 +  free(paddedData); paddedData = NULL;
   9.258 +  goto egress;
   9.259 +  
   9.260 + abort_egress:
   9.261 +  
   9.262 +  if (paddedData) 
   9.263 +    free (paddedData);
   9.264 +  return -1;
   9.265 +  
   9.266 + egress:
   9.267 +  return 0;
   9.268 +}
   9.269 +
   9.270 +// Signs either a SHA1 digest of a message or a DER encoding of a message
   9.271 +// Textual messages MUST be encoded or Hashed before sending into this function
   9.272 +// It will NOT SHA the message.
   9.273 +int Crypto_RSASign( CRYPTO_INFO *key,
   9.274 +                    UINT32 inDataSize,
   9.275 +                    BYTE *inData,
   9.276 +                    /*out*/ UINT32 *sigSize,
   9.277 +                    /*out*/ BYTE *sig) {
   9.278 +  int status;
   9.279 +  unsigned int intSigSize;
   9.280 +  
   9.281 +  switch(key->sigScheme) {
   9.282 +  case CRYPTO_SS_RSASSAPKCS1v15_SHA1: 
   9.283 +    status = RSA_sign(NID_sha1, inData, inDataSize, sig, &intSigSize, (RSA *) key->keyInfo);
   9.284 +    break;
   9.285 +  case CRYPTO_SS_RSASSAPKCS1v15_DER:
   9.286 +    //        status = Crypto_RSA_sign_DER(NID_md5_sha1, inData, inDataSize, sig, &intSigSize, key);
   9.287 +    vtpmlogerror(VTPM_LOG_CRYPTO, "Crypto: Unimplemented sign type (%d)\n", key->sigScheme);
   9.288 +    status = 0;
   9.289 +    break;
   9.290 +  default:
   9.291 +    status = 0;
   9.292 +  }
   9.293 +  
   9.294 +  if (status == 0) {
   9.295 +    *sigSize = 0;
   9.296 +    vtpmlogerror(VTPM_LOG_CRYPTO, "%s\n", ERR_error_string(ERR_get_error(), NULL));
   9.297 +    return -1;
   9.298 +  }
   9.299 +  
   9.300 +  *sigSize = (UINT32) intSigSize;
   9.301 +  return 0;
   9.302 +}
   9.303 +
   9.304 +bool Crypto_RSAVerify(  CRYPTO_INFO *key,
   9.305 +                        UINT32 inDataSize,
   9.306 +                        BYTE *inData,
   9.307 +                        UINT32 sigSize,
   9.308 +                        BYTE *sig) {
   9.309 +  int status;
   9.310 +  
   9.311 +  switch(key->sigScheme){
   9.312 +  case CRYPTO_SS_RSASSAPKCS1v15_SHA1: 
   9.313 +    status = RSA_verify(NID_sha1, inData, inDataSize, sig, sigSize, (RSA *) key->keyInfo);
   9.314 +    break;
   9.315 +  case CRYPTO_SS_RSASSAPKCS1v15_DER:
   9.316 +    //status = Crypto_RSA_verify_DER(NID_md5_sha1, inData, inDataSize, sig, sigSize, key);
   9.317 +    vtpmlogerror(VTPM_LOG_CRYPTO, "Crypto: Unimplemented sign type (%d)\n", key->sigScheme);
   9.318 +    status = 0;
   9.319 +    break;
   9.320 +  default:
   9.321 +    status = 0;
   9.322 +  }
   9.323 +  
   9.324 +  if (status) 
   9.325 +    return(1);
   9.326 +  else {
   9.327 +    vtpmlogerror(VTPM_LOG_CRYPTO, "RSA verify: %s\n", ERR_error_string(ERR_get_error(), NULL));
   9.328 +    return(0);
   9.329 +  }
   9.330 +  
   9.331 +}
   9.332 +
   9.333 +// helper which packs everything into a BIO!
   9.334 +
   9.335 +// packs the parameters first, then the private key, then the public key
   9.336 +// if *io_buf is NULL, allocate it here as needed. otherwise its size is in
   9.337 +// *io_buflen
   9.338 +TPM_RESULT Crypto_RSAPackCryptoInfo (const CRYPTO_INFO* cryptoInfo,
   9.339 +                                      BYTE ** io_buf, UINT32 * io_buflen) {
   9.340 +  TPM_RESULT status = TPM_SUCCESS;
   9.341 +  BYTE * buf;
   9.342 +  long len, outlen = *io_buflen;
   9.343 +  
   9.344 +  const long PARAMSLEN = 3*sizeof(UINT32);
   9.345 +  
   9.346 +  RSA *rsa = (RSA *) cryptoInfo->keyInfo;
   9.347 +  
   9.348 +  BIO *mem = BIO_new(BIO_s_mem());
   9.349 +  
   9.350 +  
   9.351 +  // write the openssl keys to the BIO
   9.352 +  if ( i2d_RSAPrivateKey_bio (mem, rsa) == 0 ) {
   9.353 +    ERR_print_errors_fp (stderr);
   9.354 +    ERRORDIE (TPM_SIZE);
   9.355 +  }
   9.356 +  if ( i2d_RSAPublicKey_bio (mem, rsa) == 0 ) {
   9.357 +    ERR_print_errors_fp (stderr);
   9.358 +    ERRORDIE (TPM_SIZE);
   9.359 +  }
   9.360 +  
   9.361 +  // get the buffer out
   9.362 +  len = BIO_get_mem_data (mem, &buf);
   9.363 +  
   9.364 +  // see if we need to allocate a return buffer
   9.365 +  if (*io_buf == NULL) {
   9.366 +    *io_buf = (BYTE*) malloc (PARAMSLEN + len);
   9.367 +    if (*io_buf == NULL) 
   9.368 +      ERRORDIE (TPM_SIZE);
   9.369 +  } else {                      // *io_buf is already allocated
   9.370 +    if (outlen < len + PARAMSLEN) 
   9.371 +      ERRORDIE (TPM_SIZE); // but not large enough!  
   9.372 +  }
   9.373 +  
   9.374 +  // copy over the parameters (three UINT32's starting at algorithmID)
   9.375 +  memcpy (*io_buf, &cryptoInfo->algorithmID, PARAMSLEN);
   9.376 +  
   9.377 +  // copy over the DER keys
   9.378 +  memcpy (*io_buf + PARAMSLEN, buf, len);
   9.379 +  
   9.380 +  *io_buflen = len + PARAMSLEN;
   9.381 +  
   9.382 +  goto egress;
   9.383 +  
   9.384 +  
   9.385 + abort_egress:
   9.386 + egress:
   9.387 +  
   9.388 +  BIO_free (mem);
   9.389 +  
   9.390 +  return status;
   9.391 +}
   9.392 +
   9.393 +
   9.394 +
   9.395 +// sets up ci, and returns the number of bytes read in o_lenread
   9.396 +TPM_RESULT Crypto_RSAUnpackCryptoInfo (CRYPTO_INFO * ci,
   9.397 +                                        BYTE * in, UINT32 len,
   9.398 +                                        UINT32 * o_lenread) {
   9.399 +  
   9.400 +  TPM_RESULT status = TPM_SUCCESS;
   9.401 +  long l;
   9.402 +  BIO *mem;
   9.403 +  RSA *rsa;
   9.404 +  
   9.405 +  // first load up the params
   9.406 +  l = 3 * sizeof(UINT32);
   9.407 +  memcpy (&ci->algorithmID, in, l);
   9.408 +  len -= l;
   9.409 +  in += l;
   9.410 +  
   9.411 +  // and now the openssl keys, private first
   9.412 +  mem = BIO_new_mem_buf (in, len);
   9.413 +  
   9.414 +  if ( (rsa = d2i_RSAPrivateKey_bio (mem, NULL)) == NULL ) {
   9.415 +    ERR_print_errors_fp (stderr);
   9.416 +    ERRORDIE (TPM_BAD_PARAMETER);
   9.417 +  }
   9.418 +  // now use the same RSA object and fill in the private key
   9.419 +  if ( d2i_RSAPublicKey_bio (mem, &rsa) == NULL ) {
   9.420 +    ERR_print_errors_fp (stderr);
   9.421 +    ERRORDIE (TPM_BAD_PARAMETER);
   9.422 +  }
   9.423 +  
   9.424 +  ci->keyInfo = rsa;          // needs to be freed somehow later
   9.425 +  
   9.426 +  // FIXME: havent figured out yet how to tell how many bytes were read in the
   9.427 +  // above oprations! so o_lenread is not set
   9.428 +  
   9.429 +  goto egress;
   9.430 +  
   9.431 + abort_egress:
   9.432 + egress:
   9.433 +  
   9.434 +  BIO_free (mem);
   9.435 + 
   9.436 +  return status;  
   9.437 +}
    10.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    10.2 +++ b/tools/vtpm_manager/crypto/sym_crypto.c	Tue Aug 30 11:39:25 2005 -0800
    10.3 @@ -0,0 +1,242 @@
    10.4 +// ===================================================================
    10.5 +// 
    10.6 +// Copyright (c) 2005, Intel Corp.
    10.7 +// All rights reserved.
    10.8 +//
    10.9 +// Redistribution and use in source and binary forms, with or without 
   10.10 +// modification, are permitted provided that the following conditions 
   10.11 +// are met:
   10.12 +//
   10.13 +//   * Redistributions of source code must retain the above copyright 
   10.14 +//     notice, this list of conditions and the following disclaimer.
   10.15 +//   * Redistributions in binary form must reproduce the above 
   10.16 +//     copyright notice, this list of conditions and the following 
   10.17 +//     disclaimer in the documentation and/or other materials provided 
   10.18 +//     with the distribution.
   10.19 +//   * Neither the name of Intel Corporation nor the names of its 
   10.20 +//     contributors may be used to endorse or promote products derived
   10.21 +//     from this software without specific prior written permission.
   10.22 +//
   10.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   10.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   10.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   10.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   10.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   10.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   10.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   10.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   10.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   10.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   10.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   10.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   10.35 +// ===================================================================
   10.36 +// 
   10.37 +// sym_crypto.c
   10.38 +// 
   10.39 +//     Symmetric crypto portion of crypto 
   10.40 +// 
   10.41 +// ==================================================================
   10.42 +
   10.43 +#include <openssl/evp.h>
   10.44 +#include <openssl/rand.h>
   10.45 +
   10.46 +#include "tcg.h"
   10.47 +#include "sym_crypto.h"
   10.48 +
   10.49 +typedef enum crypt_op_type_t {
   10.50 +  CRYPT_ENCRYPT,
   10.51 +  CRYPT_DECRYPT
   10.52 +} crypt_op_type_t;
   10.53 +
   10.54 +TPM_RESULT ossl_symcrypto_op (symkey_t* key,
   10.55 +                              const buffer_t* in,
   10.56 +                              const buffer_t* iv,
   10.57 +                              buffer_t * out,
   10.58 +                              crypt_op_type_t optype);
   10.59 +
   10.60 +
   10.61 +// this is initialized in Crypto_Init()
   10.62 +const EVP_CIPHER * SYM_CIPHER = NULL;
   10.63 +
   10.64 +const BYTE ZERO_IV[EVP_MAX_IV_LENGTH] = {0};
   10.65 +
   10.66 +
   10.67 +TPM_RESULT Crypto_symcrypto_initkey (symkey_t * key, const buffer_t* keybits) {
   10.68 +  TPM_RESULT status = TPM_SUCCESS;
   10.69 +  
   10.70 +  EVP_CIPHER_CTX_init (&key->context);
   10.71 +  
   10.72 +  key->cipher = SYM_CIPHER;
   10.73 +  
   10.74 +  status = buffer_init_copy (&key->key, keybits);
   10.75 +  STATUSCHECK(status);
   10.76 +    
   10.77 +  goto egress;
   10.78 +  
   10.79 + abort_egress:
   10.80 +  EVP_CIPHER_CTX_cleanup (&key->context);
   10.81 +  
   10.82 + egress:
   10.83 +  
   10.84 +  return status;
   10.85 +}
   10.86 +
   10.87 +
   10.88 +
   10.89 +TPM_RESULT Crypto_symcrypto_genkey (symkey_t * key) {
   10.90 +  int res;
   10.91 +  TPM_RESULT status = TPM_SUCCESS;
   10.92 +  
   10.93 +  // hmm, EVP_CIPHER_CTX_init does not return a value
   10.94 +  EVP_CIPHER_CTX_init (&key->context);
   10.95 +  
   10.96 +  key->cipher = SYM_CIPHER;
   10.97 +  
   10.98 +  status = buffer_init (&key->key, EVP_CIPHER_key_length(key->cipher), NULL);
   10.99 +  STATUSCHECK (status);
  10.100 +  
  10.101 +  // and generate the key material
  10.102 +  res = RAND_pseudo_bytes (key->key.bytes, key->key.size);
  10.103 +  if (res < 0) 
  10.104 +    ERRORDIE (TPM_SHORTRANDOM);
  10.105 +  
  10.106 +  
  10.107 +  goto egress;
  10.108 +  
  10.109 + abort_egress:
  10.110 +  EVP_CIPHER_CTX_cleanup (&key->context);
  10.111 +  buffer_free (&key->key);
  10.112 +  
  10.113 + egress:
  10.114 +  return status;  
  10.115 +}
  10.116 +
  10.117 +
  10.118 +TPM_RESULT Crypto_symcrypto_encrypt (symkey_t* key,
  10.119 +                              const buffer_t* clear,
  10.120 +                              buffer_t* o_cipher) {
  10.121 +  TPM_RESULT status = TPM_SUCCESS;
  10.122 +  
  10.123 +  buffer_t iv, cipher_alias;
  10.124 +  
  10.125 +  buffer_init_const (&iv, EVP_MAX_IV_LENGTH, ZERO_IV);
  10.126 +  
  10.127 +  buffer_init (o_cipher,
  10.128 +	       clear->size +
  10.129 +	       EVP_CIPHER_iv_length(key->cipher) +
  10.130 +	       EVP_CIPHER_block_size (key->cipher),
  10.131 +				 0);
  10.132 +  
  10.133 +  // copy the IV into the front
  10.134 +  buffer_copy (o_cipher, &iv);
  10.135 +  
  10.136 +  // make an alias into which we'll put the ciphertext
  10.137 +  buffer_init_alias (&cipher_alias, o_cipher, EVP_CIPHER_iv_length(key->cipher), 0);
  10.138 +  
  10.139 +  status = ossl_symcrypto_op (key, clear, &iv, &cipher_alias, CRYPT_ENCRYPT);
  10.140 +  STATUSCHECK (status);
  10.141 +
  10.142 +  // set the output size correctly
  10.143 +  o_cipher->size += cipher_alias.size;
  10.144 +  
  10.145 +  goto egress;
  10.146 +  
  10.147 + abort_egress:
  10.148 +  
  10.149 + egress:
  10.150 +  
  10.151 +  return status;
  10.152 +  
  10.153 +}
  10.154 +
  10.155 +
  10.156 +
  10.157 +TPM_RESULT Crypto_symcrypto_decrypt (symkey_t* key,
  10.158 +                              const buffer_t* cipher,
  10.159 +                              buffer_t* o_clear) {
  10.160 +  TPM_RESULT status = TPM_SUCCESS;
  10.161 +  
  10.162 +  buffer_t iv, cipher_alias;
  10.163 +  
  10.164 +  // alias for the IV
  10.165 +  buffer_init_alias (&iv, cipher, 0, EVP_CIPHER_iv_length(key->cipher));
  10.166 +  
  10.167 +  // make an alias to where the ciphertext is, after the IV
  10.168 +  buffer_init_alias (&cipher_alias, cipher, EVP_CIPHER_iv_length(key->cipher), 0);
  10.169 +  
  10.170 +  // prepare the output buffer
  10.171 +  status = buffer_init (o_clear,
  10.172 +			cipher->size
  10.173 +			- EVP_CIPHER_iv_length(key->cipher)
  10.174 +			+ EVP_CIPHER_block_size(key->cipher), 
  10.175 +			0);
  10.176 +  STATUSCHECK(status);
  10.177 +  
  10.178 +  // and decrypt
  10.179 +  status = ossl_symcrypto_op (key, &cipher_alias, &iv, o_clear, CRYPT_DECRYPT);
  10.180 +  STATUSCHECK (status);
  10.181 +  
  10.182 +  goto egress;
  10.183 +  
  10.184 + abort_egress:
  10.185 +  buffer_free (o_clear);
  10.186 +  
  10.187 + egress:
  10.188 +  
  10.189 +  return status;
  10.190 +}
  10.191 +
  10.192 +
  10.193 +
  10.194 +TPM_RESULT Crypto_symcrypto_freekey (symkey_t * key) {
  10.195 +  buffer_memset (&key->key, 0);
  10.196 +  buffer_free (&key->key);
  10.197 +  
  10.198 +  EVP_CIPHER_CTX_cleanup (&key->context);
  10.199 +  
  10.200 +  return TPM_SUCCESS;
  10.201 +}
  10.202 +
  10.203 +
  10.204 +TPM_RESULT ossl_symcrypto_op (symkey_t* key,
  10.205 +                              const buffer_t* in,
  10.206 +                              const buffer_t* iv,
  10.207 +                              buffer_t * out,
  10.208 +                              crypt_op_type_t optype) {
  10.209 +  TPM_RESULT status = TPM_SUCCESS;
  10.210 +  
  10.211 +  int inlen, outlen;
  10.212 +  tpm_size_t running;
  10.213 +  
  10.214 +  if ( ! EVP_CipherInit_ex (&key->context,
  10.215 +			    key->cipher, NULL, key->key.bytes, iv->bytes,
  10.216 +			    optype == CRYPT_ENCRYPT ? 1 : 0) ) 
  10.217 +    ERRORDIE (TPM_FAIL);
  10.218 +  
  10.219 +  
  10.220 +  
  10.221 +  inlen = in->size;
  10.222 +  
  10.223 +  outlen  = 0;
  10.224 +  running = 0;
  10.225 +  
  10.226 +  
  10.227 +  if ( ! EVP_CipherUpdate (&key->context, out->bytes, &outlen, in->bytes, inlen) )
  10.228 +    ERRORDIE (TPM_FAIL);
  10.229 +
  10.230 +  running += outlen;
  10.231 +  
  10.232 +  if ( ! EVP_CipherFinal_ex (&key->context, out->bytes + running, &outlen) )
  10.233 +    ERRORDIE (TPM_FAIL);
  10.234 +  
  10.235 +  running += outlen;
  10.236 +  
  10.237 +  out->size = running;
  10.238 +  
  10.239 +  goto egress;
  10.240 +  
  10.241 + abort_egress:
  10.242 + egress:
  10.243 +  
  10.244 +  return status;
  10.245 +}
    11.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    11.2 +++ b/tools/vtpm_manager/crypto/sym_crypto.h	Tue Aug 30 11:39:25 2005 -0800
    11.3 @@ -0,0 +1,72 @@
    11.4 +// ===================================================================
    11.5 +// 
    11.6 +// Copyright (c) 2005, Intel Corp.
    11.7 +// All rights reserved.
    11.8 +//
    11.9 +// Redistribution and use in source and binary forms, with or without 
   11.10 +// modification, are permitted provided that the following conditions 
   11.11 +// are met:
   11.12 +//
   11.13 +//   * Redistributions of source code must retain the above copyright 
   11.14 +//     notice, this list of conditions and the following disclaimer.
   11.15 +//   * Redistributions in binary form must reproduce the above 
   11.16 +//     copyright notice, this list of conditions and the following 
   11.17 +//     disclaimer in the documentation and/or other materials provided 
   11.18 +//     with the distribution.
   11.19 +//   * Neither the name of Intel Corporation nor the names of its 
   11.20 +//     contributors may be used to endorse or promote products derived
   11.21 +//     from this software without specific prior written permission.
   11.22 +//
   11.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   11.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   11.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   11.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   11.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   11.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   11.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   11.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   11.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   11.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   11.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   11.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   11.35 +// ===================================================================
   11.36 +// 
   11.37 +// sym_crypto.h
   11.38 +// 
   11.39 +//     Symmetric Crypto 
   11.40 +// 
   11.41 +// ==================================================================
   11.42 +
   11.43 +#ifndef _SYM_CRYPTO_H
   11.44 +#define _SYM_CRYPTO_H
   11.45 +
   11.46 +#include <openssl/evp.h>
   11.47 +#include "buffer.h"
   11.48 +
   11.49 +typedef struct symkey_t {
   11.50 +  buffer_t key;
   11.51 +  
   11.52 +  EVP_CIPHER_CTX context;
   11.53 +  const EVP_CIPHER * cipher;
   11.54 +} symkey_t;
   11.55 +
   11.56 +extern const EVP_CIPHER * SYM_CIPHER;
   11.57 +
   11.58 +TPM_RESULT Crypto_symcrypto_genkey (symkey_t * key);
   11.59 +
   11.60 +TPM_RESULT Crypto_symcrypto_initkey (symkey_t * key, const buffer_t* keybits);
   11.61 +
   11.62 +
   11.63 +// these functions will allocate their output buffers
   11.64 +TPM_RESULT Crypto_symcrypto_encrypt (symkey_t* key,
   11.65 +                              const buffer_t* clear,
   11.66 +                              buffer_t* o_cipher);
   11.67 +
   11.68 +TPM_RESULT Crypto_symcrypto_decrypt (symkey_t* key,
   11.69 +                              const buffer_t* cipher,
   11.70 +                              buffer_t* o_clear);
   11.71 +
   11.72 +// only free the internal parts, not the 'key' ptr
   11.73 +TPM_RESULT Crypto_symcrypto_freekey (symkey_t * key);
   11.74 +
   11.75 +#endif /* _SYM_CRYPTO_H */
    12.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    12.2 +++ b/tools/vtpm_manager/manager/Makefile	Tue Aug 30 11:39:25 2005 -0800
    12.3 @@ -0,0 +1,27 @@
    12.4 +XEN_ROOT = ../../..
    12.5 +include $(XEN_ROOT)/tools/vtpm_manager/Rules.mk
    12.6 +
    12.7 +BIN		= vtpm_managerd
    12.8 +
    12.9 +all: build
   12.10 +
   12.11 +build: $(BIN)
   12.12 +
   12.13 +install: build
   12.14 +	if [ ! -d "$(DESTDIR)/var/vtpm/fifos" ]; \
   12.15 +		then mkdir -p $(DESTDIR)/var/vtpm/fifos; \
   12.16 +	fi
   12.17 +	$(INSTALL_PROG) $(BIN) $(TOOLS_INSTALL_DIR)
   12.18 +
   12.19 +clean:
   12.20 +	rm -f *.a *.so *.o *.rpm $(DEP_FILES)
   12.21 +
   12.22 +mrproper: clean
   12.23 +	rm -f $(BIN)
   12.24 +
   12.25 +$(BIN): $(OBJS)
   12.26 +	$(CC) $(LDFLAGS) $^ $(LIBS) -o $@
   12.27 +
   12.28 +# libraries
   12.29 +LIBS += ../tcs/libTCS.a ../util/libTCGUtils.a ../crypto/libtcpaCrypto.a
   12.30 +LIBS += -lcrypto -lpthread -lrt -lm
    13.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    13.2 +++ b/tools/vtpm_manager/manager/dmictl.c	Tue Aug 30 11:39:25 2005 -0800
    13.3 @@ -0,0 +1,339 @@
    13.4 +// ===================================================================
    13.5 +// 
    13.6 +// Copyright (c) 2005, Intel Corp.
    13.7 +// All rights reserved.
    13.8 +//
    13.9 +// Redistribution and use in source and binary forms, with or without 
   13.10 +// modification, are permitted provided that the following conditions 
   13.11 +// are met:
   13.12 +//
   13.13 +//   * Redistributions of source code must retain the above copyright 
   13.14 +//     notice, this list of conditions and the following disclaimer.
   13.15 +//   * Redistributions in binary form must reproduce the above 
   13.16 +//     copyright notice, this list of conditions and the following 
   13.17 +//     disclaimer in the documentation and/or other materials provided 
   13.18 +//     with the distribution.
   13.19 +//   * Neither the name of Intel Corporation nor the names of its 
   13.20 +//     contributors may be used to endorse or promote products derived
   13.21 +//     from this software without specific prior written permission.
   13.22 +//
   13.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   13.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   13.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   13.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   13.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   13.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   13.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   13.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   13.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   13.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   13.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   13.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   13.35 +// ===================================================================
   13.36 +// 
   13.37 +//   dmictl.c
   13.38 +// 
   13.39 +//     Functions for creating and destroying DMIs
   13.40 +//
   13.41 +// ==================================================================
   13.42 +
   13.43 +#include <stdio.h>
   13.44 +#include <unistd.h>
   13.45 +#include <string.h>
   13.46 +
   13.47 +#ifndef VTPM_MUTLI_VM
   13.48 + #include <sys/types.h>
   13.49 + #include <sys/stat.h>
   13.50 + #include <fcntl.h>
   13.51 + #include <signal.h>
   13.52 + #include <wait.h>
   13.53 +#endif
   13.54 +
   13.55 +#include "vtpmpriv.h"
   13.56 +#include "bsg.h"
   13.57 +#include "buffer.h"
   13.58 +#include "log.h"
   13.59 +#include "hashtable.h"
   13.60 +#include "hashtable_itr.h"
   13.61 +
   13.62 +#define TPM_EMULATOR_PATH "/usr/bin/vtpmd"
   13.63 +
   13.64 +TPM_RESULT close_dmi( VTPM_DMI_RESOURCE *dmi_res) {
   13.65 +	TPM_RESULT status = TPM_FAIL;
   13.66 +	
   13.67 +	if (dmi_res == NULL) 
   13.68 +		return TPM_SUCCESS;
   13.69 +	
   13.70 +	status = TCS_CloseContext(dmi_res->TCSContext);
   13.71 +	free ( dmi_res->NVMLocation );
   13.72 +	dmi_res->connected = FALSE;
   13.73 +
   13.74 +#ifndef VTPM_MULTI_VM	
   13.75 +	free(dmi_res->guest_tx_fname);
   13.76 +	free(dmi_res->vtpm_tx_fname);
   13.77 +		
   13.78 +	close(dmi_res->guest_tx_fh); dmi_res->guest_tx_fh = -1;
   13.79 +	close(dmi_res->vtpm_tx_fh);  dmi_res->vtpm_tx_fh = -1; 
   13.80 +	
   13.81 +		
   13.82 + #ifndef MANUAL_DM_LAUNCH
   13.83 +  if (dmi_res->dmi_id != VTPM_CTL_DM) {
   13.84 +    if (dmi_res->dmi_pid != 0) {
   13.85 +      vtpmloginfo(VTPM_LOG_VTPM, "Killing dmi on pid %d.\n", dmi_res->dmi_pid);
   13.86 +      if ((kill(dmi_res->dmi_pid, SIGKILL) !=0) ||
   13.87 +         (waitpid(dmi_res->dmi_pid, NULL, 0) != dmi_res->dmi_pid)){
   13.88 +        vtpmlogerror(VTPM_LOG_VTPM, "Could not kill dmi on pid %d.\n", dmi_res->dmi_pid);
   13.89 +        status = TPM_FAIL;
   13.90 +      }
   13.91 +    } else 
   13.92 +      vtpmlogerror(VTPM_LOG_VTPM, "Could not kill dmi because it's pid was 0.\n");
   13.93 +  }
   13.94 + #endif
   13.95 +#endif
   13.96 +
   13.97 +	return status;
   13.98 +}
   13.99 +	
  13.100 +TPM_RESULT VTPM_Handle_New_DMI( const buffer_t *param_buf) {
  13.101 +  
  13.102 +  VTPM_DMI_RESOURCE *new_dmi=NULL;
  13.103 +  TPM_RESULT status=TPM_FAIL;
  13.104 +  BYTE type;
  13.105 +  UINT32 dmi_id, domain_id, *dmi_id_key; 
  13.106 +  int fh;
  13.107 +
  13.108 +#ifndef VTPM_MUTLI_VM
  13.109 +  char dmi_id_str[11]; // UINT32s are up to 10 digits + NULL
  13.110 +  struct stat file_info;
  13.111 +#endif
  13.112 +  
  13.113 +  if (param_buf == NULL) { // Assume creation of Dom 0 control
  13.114 +    type = 0;
  13.115 +    domain_id = VTPM_CTL_DM;
  13.116 +    dmi_id = VTPM_CTL_DM;
  13.117 +  } else if (buffer_len(param_buf) != sizeof(BYTE) + sizeof(UINT32) *2) {
  13.118 +    vtpmloginfo(VTPM_LOG_VTPM, "New DMI command wrong length: %d.\n", buffer_len(param_buf));
  13.119 +    status = TPM_BAD_PARAMETER;
  13.120 +    goto abort_egress;
  13.121 +  } else {
  13.122 +    BSG_UnpackList( param_buf->bytes, 3,
  13.123 +		    BSG_TYPE_BYTE, &type,
  13.124 +		    BSG_TYPE_UINT32, &domain_id,
  13.125 +		    BSG_TYPE_UINT32,  &dmi_id);
  13.126 +  }
  13.127 +  
  13.128 +  new_dmi = (VTPM_DMI_RESOURCE *) hashtable_search(vtpm_globals->dmi_map, &dmi_id);
  13.129 +  if (new_dmi == NULL) { 
  13.130 +    vtpmloginfo(VTPM_LOG_VTPM, "Creating new DMI instance %d attached on domain %d.\n", dmi_id, domain_id);
  13.131 +    // Brand New DMI. Initialize the persistent pieces
  13.132 +    if ((new_dmi = (VTPM_DMI_RESOURCE *) malloc (sizeof(VTPM_DMI_RESOURCE))) == NULL) {
  13.133 +      status = TPM_RESOURCES;
  13.134 +      goto abort_egress;
  13.135 +    }
  13.136 +    memset(new_dmi, 0, sizeof(VTPM_DMI_RESOURCE));
  13.137 +    new_dmi->dmi_id = dmi_id;
  13.138 +    new_dmi->connected = FALSE;
  13.139 +    
  13.140 +    if ((dmi_id_key = (UINT32 *) malloc (sizeof(UINT32))) == NULL) {
  13.141 +      status = TPM_RESOURCES;
  13.142 +      goto abort_egress;
  13.143 +    }      
  13.144 +    *dmi_id_key = new_dmi->dmi_id;
  13.145 +    
  13.146 +    // install into map
  13.147 +    if (!hashtable_insert(vtpm_globals->dmi_map, dmi_id_key, new_dmi)){
  13.148 +      free(new_dmi);
  13.149 +      free(dmi_id_key);
  13.150 +      status = TPM_FAIL;
  13.151 +      goto egress;
  13.152 +    }
  13.153 +    
  13.154 +  } else 
  13.155 +    vtpmloginfo(VTPM_LOG_VTPM, "Re-attaching DMI instance %d on domain %d .\n", dmi_id, domain_id);
  13.156 +  
  13.157 +  if (new_dmi->connected) {
  13.158 +    vtpmlogerror(VTPM_LOG_VTPM, "Attempt to re-attach, currently attached instance %d. Ignoring\n", dmi_id);
  13.159 +    status = TPM_BAD_PARAMETER;
  13.160 +    goto egress;
  13.161 +  }
  13.162 +  
  13.163 +  // Initialize the Non-persistent pieces
  13.164 +  new_dmi->dmi_domain_id = domain_id;
  13.165 +  new_dmi->NVMLocation = NULL;
  13.166 +  
  13.167 +  new_dmi->TCSContext = 0;
  13.168 +  TPMTRYRETURN( TCS_OpenContext(&new_dmi->TCSContext) );
  13.169 +  
  13.170 +  new_dmi->NVMLocation = (char *) malloc(11 + strlen(DMI_NVM_FILE));
  13.171 +  sprintf(new_dmi->NVMLocation, DMI_NVM_FILE, (uint32_t) new_dmi->dmi_id);
  13.172 +  
  13.173 +  // Measure DMI
  13.174 +  // FIXME: This will measure DMI. Until then use a fixed DMI_Measurement value
  13.175 +  /*
  13.176 +  fh = open(TPM_EMULATOR_PATH, O_RDONLY);
  13.177 +  stat_ret = fstat(fh, &file_stat);
  13.178 +  if (stat_ret == 0) 
  13.179 +    dmi_size = file_stat.st_size;
  13.180 +  else {
  13.181 +	vtpmlogerror(VTPM_LOG_VTPM, "Could not open tpm_emulator!!\n");
  13.182 +    status = TPM_IOERROR;
  13.183 +    goto abort_egress;
  13.184 +  }
  13.185 +  dmi_buffer
  13.186 +  */
  13.187 +  memset(&new_dmi->DMI_measurement, 0xcc, sizeof(TPM_DIGEST));
  13.188 +  
  13.189 +#ifndef VTPM_MULTI_VM
  13.190 +  if (dmi_id != VTPM_CTL_DM) {
  13.191 +    // Create a pair of fifo pipes
  13.192 +		if( (new_dmi->guest_tx_fname = (char *) malloc(11 + strlen(GUEST_TX_FIFO))) == NULL){ 
  13.193 +			status = TPM_RESOURCES;
  13.194 +			goto abort_egress;
  13.195 +		}
  13.196 +		sprintf(new_dmi->guest_tx_fname, GUEST_TX_FIFO, (uint32_t) dmi_id);
  13.197 +    
  13.198 +		if ((new_dmi->vtpm_tx_fname = (char *) malloc(11 + strlen(VTPM_TX_FIFO))) == NULL) {
  13.199 +			status = TPM_RESOURCES;
  13.200 +			goto abort_egress;
  13.201 +		}
  13.202 +		sprintf(new_dmi->vtpm_tx_fname, VTPM_TX_FIFO, (uint32_t) dmi_id);
  13.203 +    
  13.204 +    new_dmi->guest_tx_fh = -1;
  13.205 +    new_dmi->vtpm_tx_fh= -1;
  13.206 +    
  13.207 +    if ( stat(new_dmi->guest_tx_fname, &file_info) == -1) {
  13.208 +      if ( mkfifo(new_dmi->guest_tx_fname, S_IWUSR | S_IRUSR ) ){
  13.209 +				status = TPM_FAIL;
  13.210 +				goto abort_egress;
  13.211 +      }
  13.212 +    }
  13.213 +            
  13.214 +    if ( (fh = open(new_dmi->vtpm_tx_fname, O_RDWR)) == -1) {
  13.215 +      if ( mkfifo(new_dmi->vtpm_tx_fname, S_IWUSR | S_IRUSR ) ) {
  13.216 +	status = TPM_FAIL;
  13.217 +	goto abort_egress;
  13.218 +      }
  13.219 +    }
  13.220 +                
  13.221 +    // Launch DMI
  13.222 +    sprintf(dmi_id_str, "%d", (int) dmi_id);
  13.223 +#ifdef MANUAL_DM_LAUNCH
  13.224 +    vtpmlogerror(VTPM_LOG_VTPM, "FAKING starting vtpm with dmi=%s\n", dmi_id_str);
  13.225 +    new_dmi->dmi_pid = 0;
  13.226 +#else
  13.227 +    pid_t pid = fork();
  13.228 +    
  13.229 +    if (pid == -1) {
  13.230 +			vtpmlogerror(VTPM_LOG_VTPM, "Could not fork to launch vtpm\n");
  13.231 +		  status = TPM_RESOURCES;
  13.232 +      goto abort_egress;
  13.233 +		} else if (pid == 0) {
  13.234 +		  if ( stat(new_dmi->NVMLocation, &file_info) == -1)
  13.235 +				execl (TPM_EMULATOR_PATH, "vtmpd", "clear", dmi_id_str, NULL);
  13.236 +			else 
  13.237 +				execl (TPM_EMULATOR_PATH, "vtpmd", "save", dmi_id_str, NULL);
  13.238 +			
  13.239 +			// Returning from these at all is an error.
  13.240 +			vtpmlogerror(VTPM_LOG_VTPM, "Could not exec to launch vtpm\n");
  13.241 +    } else {
  13.242 +      new_dmi->dmi_pid = pid;
  13.243 +      vtpmloginfo(VTPM_LOG_VTPM, "Launching DMI on PID = %d\n", pid);
  13.244 +    }
  13.245 +#endif // MANUAL_DM_LAUNCH
  13.246 +  }
  13.247 +#else // VTPM_MUTLI_VM
  13.248 +  // FIXME: Measure DMI through call to Measurement agent in platform.
  13.249 +#endif 
  13.250 +	
  13.251 +  vtpm_globals->DMI_table_dirty = TRUE;
  13.252 +  new_dmi->connected = TRUE;  
  13.253 +  status=TPM_SUCCESS;
  13.254 +  goto egress;
  13.255 +  
  13.256 + abort_egress:
  13.257 +	close_dmi( new_dmi );
  13.258 +	
  13.259 + egress:
  13.260 +  return status;
  13.261 +}
  13.262 +
  13.263 +TPM_RESULT VTPM_Handle_Close_DMI( const buffer_t *param_buf) {
  13.264 +  
  13.265 +  TPM_RESULT status=TPM_FAIL;
  13.266 +  VTPM_DMI_RESOURCE *dmi_res=NULL;
  13.267 +  UINT32 dmi_id;
  13.268 +  
  13.269 +  if ((param_buf == NULL) || (buffer_len(param_buf) != sizeof(UINT32)) ) {
  13.270 +    vtpmlogerror(VTPM_LOG_VTPM, "Closing DMI has bad size.");
  13.271 +    status = TPM_BAD_PARAMETER;
  13.272 +    goto abort_egress;
  13.273 +  }
  13.274 +  
  13.275 +  BSG_UnpackList( param_buf->bytes, 1,
  13.276 +		  BSG_TYPE_UINT32, &dmi_id);
  13.277 +  
  13.278 +  vtpmloginfo(VTPM_LOG_VTPM, "Closing DMI %d.\n", dmi_id);
  13.279 +  
  13.280 +  dmi_res = (VTPM_DMI_RESOURCE *) hashtable_search(vtpm_globals->dmi_map, &dmi_id);
  13.281 +  if (dmi_res == NULL ) {
  13.282 +    vtpmlogerror(VTPM_LOG_VTPM, "Trying to close nonexistent DMI.\n");
  13.283 +    status = TPM_BAD_PARAMETER;
  13.284 +    goto abort_egress;
  13.285 +  }
  13.286 +	
  13.287 +	if (!dmi_res->connected) {
  13.288 +    vtpmlogerror(VTPM_LOG_VTPM, "Closing non-connected DMI.\n");
  13.289 +    status = TPM_BAD_PARAMETER;
  13.290 +    goto abort_egress;
  13.291 +  }
  13.292 +  
  13.293 +  // Close Dmi
  13.294 +	TPMTRYRETURN(close_dmi( dmi_res ));
  13.295 +  
  13.296 +  status=TPM_SUCCESS;    
  13.297 +  goto egress;
  13.298 +  
  13.299 + abort_egress:
  13.300 + egress:
  13.301 +  
  13.302 +  return status;
  13.303 +}
  13.304 +
  13.305 +TPM_RESULT VTPM_Handle_Delete_DMI( const buffer_t *param_buf) {
  13.306 +  
  13.307 +  TPM_RESULT status=TPM_FAIL;
  13.308 +  VTPM_DMI_RESOURCE *dmi_res=NULL;
  13.309 +  UINT32 dmi_id;
  13.310 +    
  13.311 +  if ((param_buf == NULL) || (buffer_len(param_buf) != sizeof(UINT32)) ) {
  13.312 +    vtpmlogerror(VTPM_LOG_VTPM, "Closing DMI has bad size.\n");
  13.313 +    status = TPM_BAD_PARAMETER;
  13.314 +    goto abort_egress;
  13.315 +  }
  13.316 +  
  13.317 +  BSG_UnpackList( param_buf->bytes, 1,
  13.318 +		  BSG_TYPE_UINT32, &dmi_id);
  13.319 +  
  13.320 +  vtpmloginfo(VTPM_LOG_VTPM, "Deleting DMI %d.\n", dmi_id);    
  13.321 +  
  13.322 +  dmi_res = (VTPM_DMI_RESOURCE *) hashtable_remove(vtpm_globals->dmi_map, &dmi_id);
  13.323 +  if (dmi_res == NULL) {
  13.324 +    vtpmlogerror(VTPM_LOG_VTPM, "Closing non-existent DMI.\n");
  13.325 +    status = TPM_BAD_PARAMETER;
  13.326 +    goto abort_egress;
  13.327 +  }
  13.328 +  
  13.329 +	//TODO: Automatically delete file dmi_res->NVMLocation
  13.330 +  
  13.331 +  // Close DMI first
  13.332 +  TPMTRYRETURN(close_dmi( dmi_res ));
  13.333 +	free ( dmi_res );
  13.334 +	
  13.335 +  status=TPM_SUCCESS;    
  13.336 +  goto egress;
  13.337 +  
  13.338 + abort_egress:
  13.339 + egress:
  13.340 +  
  13.341 +  return status;
  13.342 +}
    14.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    14.2 +++ b/tools/vtpm_manager/manager/securestorage.c	Tue Aug 30 11:39:25 2005 -0800
    14.3 @@ -0,0 +1,401 @@
    14.4 +// ===================================================================
    14.5 +// 
    14.6 +// Copyright (c) 2005, Intel Corp.
    14.7 +// All rights reserved.
    14.8 +//
    14.9 +// Redistribution and use in source and binary forms, with or without 
   14.10 +// modification, are permitted provided that the following conditions 
   14.11 +// are met:
   14.12 +//
   14.13 +//   * Redistributions of source code must retain the above copyright 
   14.14 +//     notice, this list of conditions and the following disclaimer.
   14.15 +//   * Redistributions in binary form must reproduce the above 
   14.16 +//     copyright notice, this list of conditions and the following 
   14.17 +//     disclaimer in the documentation and/or other materials provided 
   14.18 +//     with the distribution.
   14.19 +//   * Neither the name of Intel Corporation nor the names of its 
   14.20 +//     contributors may be used to endorse or promote products derived
   14.21 +//     from this software without specific prior written permission.
   14.22 +//
   14.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   14.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   14.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   14.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   14.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   14.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   14.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   14.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   14.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   14.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   14.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   14.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   14.35 +// ===================================================================
   14.36 +// 
   14.37 +// securestorage.c
   14.38 +// 
   14.39 +//  Functions regarding securely storing DMI secrets.
   14.40 +//
   14.41 +// ==================================================================
   14.42 +
   14.43 +#include <sys/types.h>
   14.44 +#include <sys/stat.h>
   14.45 +#include <fcntl.h>
   14.46 +#include <unistd.h>
   14.47 +#include <string.h>
   14.48 +
   14.49 +#include "tcg.h"
   14.50 +#include "vtpm_manager.h"
   14.51 +#include "vtpmpriv.h"
   14.52 +#include "vtsp.h"
   14.53 +#include "bsg.h"
   14.54 +#include "crypto.h"
   14.55 +#include "hashtable.h"
   14.56 +#include "hashtable_itr.h"
   14.57 +#include "buffer.h"
   14.58 +#include "log.h"
   14.59 +
   14.60 +TPM_RESULT VTPM_Handle_Save_NVM(VTPM_DMI_RESOURCE *myDMI, 
   14.61 +				const buffer_t *inbuf, 
   14.62 +				buffer_t *outbuf) {
   14.63 +  
   14.64 +  TPM_RESULT status = TPM_SUCCESS;
   14.65 +  symkey_t    symkey;
   14.66 +  buffer_t    state_cipher = NULL_BUF,
   14.67 +              symkey_cipher = NULL_BUF;
   14.68 +  int fh;
   14.69 +  long bytes_written;
   14.70 +  BYTE *sealed_NVM=NULL;
   14.71 +  UINT32 sealed_NVM_size, i;
   14.72 +  struct pack_constbuf_t symkey_cipher32, state_cipher32;
   14.73 +  
   14.74 +  vtpmloginfo(VTPM_LOG_VTPM_DEEP, "Save_NVMing[%d]: 0x", buffer_len(inbuf));
   14.75 +  for (i=0; i< buffer_len(inbuf); i++)
   14.76 +    vtpmloginfomore(VTPM_LOG_VTPM_DEEP, "%x ", inbuf->bytes[i]);
   14.77 +  vtpmloginfomore(VTPM_LOG_VTPM_DEEP, "\n");
   14.78 +  
   14.79 +  // Generate a sym key and encrypt state with it
   14.80 +  TPMTRY(TPM_ENCRYPT_ERROR, Crypto_symcrypto_genkey (&symkey) );
   14.81 +  TPMTRY(TPM_ENCRYPT_ERROR, Crypto_symcrypto_encrypt (&symkey, inbuf, &state_cipher) );
   14.82 +  
   14.83 +  // Encrypt symmetric key
   14.84 +  TPMTRYRETURN( VTSP_Bind(    &vtpm_globals->storageKey, 
   14.85 +			      &symkey.key, 
   14.86 +			      &symkey_cipher) );
   14.87 +  
   14.88 +  // Create output blob: symkey_size + symkey_cipher + state_cipher_size + state_cipher
   14.89 +  
   14.90 +  symkey_cipher32.size = buffer_len(&symkey_cipher);
   14.91 +  symkey_cipher32.data = symkey_cipher.bytes;
   14.92 +  
   14.93 +  state_cipher32.size = buffer_len(&state_cipher);
   14.94 +  state_cipher32.data = state_cipher.bytes;
   14.95 +  
   14.96 +  sealed_NVM = (BYTE *) malloc( 2 * sizeof(UINT32) + symkey_cipher32.size + state_cipher32.size);
   14.97 +  
   14.98 +  sealed_NVM_size = BSG_PackList(sealed_NVM, 2,
   14.99 +				 BSG_TPM_SIZE32_DATA, &symkey_cipher32,
  14.100 +				 BSG_TPM_SIZE32_DATA, &state_cipher32);
  14.101 +  
  14.102 +  // Mark DMI Table so new save state info will get pushed to disk on return.
  14.103 +  vtpm_globals->DMI_table_dirty = TRUE;
  14.104 +  
  14.105 +  // Write sealed blob off disk from NVMLocation
  14.106 +  // TODO: How to properly return from these. Do we care if we return failure
  14.107 +  //       after writing the file? We can't get the old one back.
  14.108 +  // TODO: Backup old file and try and recover that way.
  14.109 +  fh = open(myDMI->NVMLocation, O_WRONLY | O_CREAT, S_IREAD | S_IWRITE);
  14.110 +  if ( (bytes_written = write(fh, sealed_NVM, sealed_NVM_size) ) != (long) sealed_NVM_size) {
  14.111 +    vtpmlogerror(VTPM_LOG_VTPM, "We just overwrote a DMI_NVM and failed to finish. %ld/%ld bytes.\n", bytes_written, (long)sealed_NVM_size);
  14.112 +    status = TPM_IOERROR;
  14.113 +    goto abort_egress;
  14.114 +  }
  14.115 +  close(fh);
  14.116 +  
  14.117 +  Crypto_SHA1Full (sealed_NVM, sealed_NVM_size, (BYTE *) &myDMI->NVM_measurement);   
  14.118 +  
  14.119 +  vtpmloginfo(VTPM_LOG_VTPM, "Saved %d bytes of E(symkey) + %d bytes of E(NVM)\n", buffer_len(&symkey_cipher), buffer_len(&state_cipher));
  14.120 +  goto egress;
  14.121 +  
  14.122 + abort_egress:
  14.123 +  vtpmlogerror(VTPM_LOG_VTPM, "Failed to load NVM\n.");
  14.124 +  
  14.125 + egress:
  14.126 +  
  14.127 +  buffer_free ( &state_cipher);
  14.128 +  buffer_free ( &symkey_cipher);
  14.129 +  free(sealed_NVM);
  14.130 +  Crypto_symcrypto_freekey (&symkey);
  14.131 +  
  14.132 +  return status;
  14.133 +}
  14.134 +
  14.135 +
  14.136 +/* inbuf = null outbuf = sealed blob size, sealed blob.*/
  14.137 +TPM_RESULT VTPM_Handle_Load_NVM(VTPM_DMI_RESOURCE *myDMI, 
  14.138 +				const buffer_t *inbuf, 
  14.139 +				buffer_t *outbuf) {
  14.140 +  
  14.141 +  TPM_RESULT status = TPM_SUCCESS;
  14.142 +  symkey_t    symkey;
  14.143 +  buffer_t    state_cipher = NULL_BUF, 
  14.144 +              symkey_clear = NULL_BUF, 
  14.145 +              symkey_cipher = NULL_BUF;
  14.146 +  struct pack_buf_t symkey_cipher32, state_cipher32;
  14.147 +  
  14.148 +  UINT32 sealed_NVM_size;
  14.149 +  BYTE *sealed_NVM = NULL;
  14.150 +  long fh_size;
  14.151 +  int fh, stat_ret, i;
  14.152 +  struct stat file_stat;
  14.153 +  TPM_DIGEST sealedNVMHash;
  14.154 +  
  14.155 +  memset(&symkey, 0, sizeof(symkey_t));
  14.156 +  
  14.157 +  if (myDMI->NVMLocation == NULL) {
  14.158 +    vtpmlogerror(VTPM_LOG_VTPM, "Unable to load NVM because the file name NULL.\n");
  14.159 +    status = TPM_AUTHFAIL;
  14.160 +    goto abort_egress;
  14.161 +  }
  14.162 +  
  14.163 +  //Read sealed blob off disk from NVMLocation
  14.164 +  fh = open(myDMI->NVMLocation, O_RDONLY);
  14.165 +  stat_ret = fstat(fh, &file_stat);
  14.166 +  if (stat_ret == 0) 
  14.167 +    fh_size = file_stat.st_size;
  14.168 +  else {
  14.169 +    status = TPM_IOERROR;
  14.170 +    goto abort_egress;
  14.171 +  }
  14.172 +  
  14.173 +  sealed_NVM = (BYTE *) malloc(fh_size);
  14.174 +  if (read(fh, sealed_NVM, fh_size) != fh_size) {
  14.175 +    status = TPM_IOERROR;
  14.176 +    goto abort_egress;
  14.177 +  }
  14.178 +  close(fh);
  14.179 +  
  14.180 +  vtpmloginfo(VTPM_LOG_VTPM_DEEP, "Load_NVMing[%ld]: 0x", fh_size);
  14.181 +  for (i=0; i< fh_size; i++)
  14.182 +    vtpmloginfomore(VTPM_LOG_VTPM_DEEP, "%x ", sealed_NVM[i]);
  14.183 +  vtpmloginfomore(VTPM_LOG_VTPM_DEEP, "\n");
  14.184 +  
  14.185 +  sealed_NVM_size = BSG_UnpackList(sealed_NVM, 2,
  14.186 +				   BSG_TPM_SIZE32_DATA, &symkey_cipher32,
  14.187 +				   BSG_TPM_SIZE32_DATA, &state_cipher32);
  14.188 +  
  14.189 +  TPMTRYRETURN( buffer_init_convert (&symkey_cipher, 
  14.190 +				     symkey_cipher32.size, 
  14.191 +				     symkey_cipher32.data) );
  14.192 +  
  14.193 +  TPMTRYRETURN( buffer_init_convert (&state_cipher, 
  14.194 +				     state_cipher32.size, 
  14.195 +				     state_cipher32.data) );
  14.196 +  
  14.197 +  Crypto_SHA1Full(sealed_NVM, sealed_NVM_size, (BYTE *) &sealedNVMHash);    
  14.198 +  
  14.199 +  // Verify measurement of sealed blob.
  14.200 +  if (memcmp(&sealedNVMHash, &myDMI->NVM_measurement, sizeof(TPM_DIGEST)) ) {
  14.201 +    vtpmlogerror(VTPM_LOG_VTPM, "VTPM LoadNVM NVM measurement check failed.\n");
  14.202 +    vtpmloginfo(VTPM_LOG_VTPM_DEEP, "Correct hash: ");
  14.203 +    for (i=0; i< sizeof(TPM_DIGEST); i++)
  14.204 +      vtpmloginfomore(VTPM_LOG_VTPM_DEEP, "%x ", ((BYTE*)&myDMI->NVM_measurement)[i]);
  14.205 +    vtpmloginfomore(VTPM_LOG_VTPM_DEEP, "\n");
  14.206 +
  14.207 +    vtpmloginfo(VTPM_LOG_VTPM_DEEP, "Measured hash: ");
  14.208 +    for (i=0; i< sizeof(TPM_DIGEST); i++)
  14.209 +      vtpmloginfomore(VTPM_LOG_VTPM_DEEP, "%x ", ((BYTE*)&sealedNVMHash)[i]);
  14.210 +    vtpmloginfomore(VTPM_LOG_VTPM_DEEP, "\n");
  14.211 +    
  14.212 +    status = TPM_AUTHFAIL;
  14.213 +    goto abort_egress;
  14.214 +  }
  14.215 +  
  14.216 +  // Decrypt Symmetric Key
  14.217 +  TPMTRYRETURN( VTSP_Unbind(  myDMI->TCSContext,
  14.218 +			      vtpm_globals->storageKeyHandle,
  14.219 +			      &symkey_cipher,
  14.220 +			      (const TPM_AUTHDATA*)&vtpm_globals->storage_key_usage_auth,
  14.221 +			      &symkey_clear,
  14.222 +			      &(vtpm_globals->keyAuth) ) );
  14.223 +  
  14.224 +  // create symmetric key using saved bits
  14.225 +  Crypto_symcrypto_initkey (&symkey, &symkey_clear);
  14.226 +  
  14.227 +  // Decrypt State
  14.228 +  TPMTRY(TPM_DECRYPT_ERROR, Crypto_symcrypto_decrypt (&symkey, &state_cipher, outbuf) );
  14.229 +  
  14.230 +  goto egress;
  14.231 +  
  14.232 + abort_egress:
  14.233 +  vtpmlogerror(VTPM_LOG_VTPM, "Failed to load NVM\n.");
  14.234 +  
  14.235 + egress:
  14.236 +  
  14.237 +  buffer_free ( &state_cipher);
  14.238 +  buffer_free ( &symkey_clear);
  14.239 +  buffer_free ( &symkey_cipher);
  14.240 +  free( sealed_NVM );
  14.241 +  Crypto_symcrypto_freekey (&symkey);
  14.242 +  
  14.243 +  return status;
  14.244 +}
  14.245 +
  14.246 +TPM_RESULT VTPM_SaveService(void) {
  14.247 +  TPM_RESULT status=TPM_SUCCESS;
  14.248 +  int fh, dmis=-1;
  14.249 +  
  14.250 +  BYTE *flat_global;
  14.251 +  int flat_global_size, bytes_written;
  14.252 +  UINT32 storageKeySize = buffer_len(&vtpm_globals->storageKeyWrap);
  14.253 +  struct pack_buf_t storage_key_pack = {storageKeySize, vtpm_globals->storageKeyWrap.bytes};
  14.254 +  
  14.255 +  struct hashtable_itr *dmi_itr;
  14.256 +  VTPM_DMI_RESOURCE *dmi_res;
  14.257 +  
  14.258 +  UINT32 flat_global_full_size;
  14.259 +  
  14.260 +  // Global Values needing to be saved
  14.261 +  flat_global_full_size = 3*sizeof(TPM_DIGEST) + // Auths
  14.262 +    sizeof(UINT32) +       // storagekeysize
  14.263 +    storageKeySize +       // storage key
  14.264 +    hashtable_count(vtpm_globals->dmi_map) * // num DMIS
  14.265 +    (sizeof(UINT32) + 2*sizeof(TPM_DIGEST)); // Per DMI info
  14.266 +  
  14.267 +  
  14.268 +  flat_global = (BYTE *) malloc( flat_global_full_size);
  14.269 +  
  14.270 +  flat_global_size = BSG_PackList(flat_global, 4,
  14.271 +				  BSG_TPM_AUTHDATA, &vtpm_globals->owner_usage_auth,
  14.272 +				  BSG_TPM_AUTHDATA, &vtpm_globals->srk_usage_auth,
  14.273 +				  BSG_TPM_SECRET,   &vtpm_globals->storage_key_usage_auth,
  14.274 +				  BSG_TPM_SIZE32_DATA, &storage_key_pack);
  14.275 +  
  14.276 +  // Per DMI values to be saved
  14.277 +  if (hashtable_count(vtpm_globals->dmi_map) > 0) {
  14.278 +    
  14.279 +    dmi_itr = hashtable_iterator(vtpm_globals->dmi_map);
  14.280 +    do {
  14.281 +      dmi_res = (VTPM_DMI_RESOURCE *) hashtable_iterator_value(dmi_itr);
  14.282 +      dmis++;
  14.283 +
  14.284 +      // No need to save dmi0.
  14.285 +      if (dmi_res->dmi_id == 0) 	
  14.286 +	continue;
  14.287 +      
  14.288 +      
  14.289 +      flat_global_size += BSG_PackList( flat_global + flat_global_size, 3,
  14.290 +					BSG_TYPE_UINT32, &dmi_res->dmi_id,
  14.291 +					BSG_TPM_DIGEST, &dmi_res->NVM_measurement,
  14.292 +					BSG_TPM_DIGEST, &dmi_res->DMI_measurement);
  14.293 +      
  14.294 +    } while (hashtable_iterator_advance(dmi_itr));
  14.295 +  }
  14.296 +  
  14.297 +  //FIXME: Once we have a way to protect a TPM key, we should use it to 
  14.298 +  //       encrypt this blob. BUT, unless there is a way to ensure the key is
  14.299 +  //       not used by other apps, this encryption is useless.
  14.300 +  fh = open(STATE_FILE, O_WRONLY | O_CREAT, S_IREAD | S_IWRITE);
  14.301 +  if (fh == -1) {
  14.302 +    vtpmlogerror(VTPM_LOG_VTPM, "Unable to open %s file for write.\n", STATE_FILE);
  14.303 +    status = TPM_IOERROR;
  14.304 +    goto abort_egress;
  14.305 +  }
  14.306 +  
  14.307 +  if ( (bytes_written = write(fh, flat_global, flat_global_size)) != flat_global_size ) {
  14.308 +    vtpmlogerror(VTPM_LOG_VTPM, "Failed to save service data. %d/%d bytes written.\n", bytes_written, flat_global_size);
  14.309 +    status = TPM_IOERROR;
  14.310 +    goto abort_egress;
  14.311 +  }
  14.312 +  vtpm_globals->DMI_table_dirty = FALSE; 
  14.313 +  
  14.314 +  goto egress;
  14.315 +  
  14.316 + abort_egress:
  14.317 + egress:
  14.318 +  
  14.319 +  free(flat_global);
  14.320 +  close(fh);
  14.321 +  
  14.322 +  vtpmloginfo(VTPM_LOG_VTPM, "Saved VTPM Service state (status = %d, dmis = %d)\n", (int) status, dmis);
  14.323 +  return status;
  14.324 +}
  14.325 +
  14.326 +TPM_RESULT VTPM_LoadService(void) {
  14.327 +  
  14.328 +  TPM_RESULT status=TPM_SUCCESS;
  14.329 +  int fh, stat_ret, dmis=0;
  14.330 +  long fh_size = 0, step_size;
  14.331 +  BYTE *flat_global=NULL;
  14.332 +  struct pack_buf_t storage_key_pack;
  14.333 +  UINT32 *dmi_id_key;
  14.334 +  
  14.335 +  VTPM_DMI_RESOURCE *dmi_res;
  14.336 +  struct stat file_stat;
  14.337 +  
  14.338 +  fh = open(STATE_FILE, O_RDONLY );
  14.339 +  stat_ret = fstat(fh, &file_stat);
  14.340 +  if (stat_ret == 0) 
  14.341 +    fh_size = file_stat.st_size;
  14.342 +  else {
  14.343 +    status = TPM_IOERROR;
  14.344 +    goto abort_egress;
  14.345 +  }
  14.346 +  
  14.347 +  flat_global = (BYTE *) malloc(fh_size);
  14.348 +  
  14.349 +  if ((long) read(fh, flat_global, fh_size) != fh_size ) {
  14.350 +    status = TPM_IOERROR;
  14.351 +    goto abort_egress;
  14.352 +  }
  14.353 +  
  14.354 +  // Global Values needing to be saved
  14.355 +  step_size = BSG_UnpackList( flat_global, 4,
  14.356 +			      BSG_TPM_AUTHDATA, &vtpm_globals->owner_usage_auth,
  14.357 +			      BSG_TPM_AUTHDATA, &vtpm_globals->srk_usage_auth,
  14.358 +			      BSG_TPM_SECRET,   &vtpm_globals->storage_key_usage_auth,
  14.359 +			      BSG_TPM_SIZE32_DATA, &storage_key_pack);
  14.360 +  
  14.361 +  TPMTRYRETURN(buffer_init(&vtpm_globals->storageKeyWrap, 0, 0) );
  14.362 +  TPMTRYRETURN(buffer_append_raw(&vtpm_globals->storageKeyWrap, storage_key_pack.size, storage_key_pack.data) );
  14.363 +  
  14.364 +  // Per DMI values to be saved
  14.365 +  while ( step_size < fh_size ){
  14.366 +    if (fh_size - step_size < (long) (sizeof(UINT32) + 2*sizeof(TPM_DIGEST))) {
  14.367 +      vtpmlogerror(VTPM_LOG_VTPM, "Encountered %ld extra bytes at end of manager state.\n", fh_size-step_size);
  14.368 +      step_size = fh_size;
  14.369 +    } else {
  14.370 +      dmi_res = (VTPM_DMI_RESOURCE *) malloc(sizeof(VTPM_DMI_RESOURCE));
  14.371 +      dmis++;
  14.372 +      
  14.373 +      dmi_res->connected = FALSE;
  14.374 +      
  14.375 +      step_size += BSG_UnpackList(flat_global + step_size, 3,
  14.376 +				  BSG_TYPE_UINT32, &dmi_res->dmi_id, 
  14.377 +				  BSG_TPM_DIGEST, &dmi_res->NVM_measurement,
  14.378 +				  BSG_TPM_DIGEST, &dmi_res->DMI_measurement);
  14.379 +      
  14.380 +      // install into map
  14.381 +      dmi_id_key = (UINT32 *) malloc (sizeof(UINT32));
  14.382 +      *dmi_id_key = dmi_res->dmi_id;
  14.383 +      if (!hashtable_insert(vtpm_globals->dmi_map, dmi_id_key, dmi_res)) {
  14.384 +	status = TPM_FAIL;
  14.385 +	goto abort_egress;
  14.386 +      }
  14.387 +      
  14.388 +    }
  14.389 +    
  14.390 +  }
  14.391 +  
  14.392 +  goto egress;
  14.393 +  
  14.394 + abort_egress:
  14.395 +  vtpmlogerror(VTPM_LOG_VTPM, "Failed to save service data\n");
  14.396 + egress:
  14.397 +  
  14.398 +  if (flat_global)
  14.399 +    free(flat_global);
  14.400 +  close(fh);
  14.401 +  
  14.402 +  vtpmloginfo(VTPM_LOG_VTPM, "Previously saved state reloaded (status = %d, dmis = %d).\n", (int) status, dmis);
  14.403 +  return status;
  14.404 +}
    15.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    15.2 +++ b/tools/vtpm_manager/manager/tpmpassthrough.c	Tue Aug 30 11:39:25 2005 -0800
    15.3 @@ -0,0 +1,110 @@
    15.4 +// ===================================================================
    15.5 +// 
    15.6 +// Copyright (c) 2005, Intel Corp.
    15.7 +// All rights reserved.
    15.8 +//
    15.9 +// Redistribution and use in source and binary forms, with or without 
   15.10 +// modification, are permitted provided that the following conditions 
   15.11 +// are met:
   15.12 +//
   15.13 +//   * Redistributions of source code must retain the above copyright 
   15.14 +//     notice, this list of conditions and the following disclaimer.
   15.15 +//   * Redistributions in binary form must reproduce the above 
   15.16 +//     copyright notice, this list of conditions and the following 
   15.17 +//     disclaimer in the documentation and/or other materials provided 
   15.18 +//     with the distribution.
   15.19 +//   * Neither the name of Intel Corporation nor the names of its 
   15.20 +//     contributors may be used to endorse or promote products derived
   15.21 +//     from this software without specific prior written permission.
   15.22 +//
   15.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   15.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   15.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   15.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   15.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   15.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   15.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   15.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   15.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   15.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   15.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   15.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   15.35 +// ===================================================================
   15.36 +// 
   15.37 +// tpmpassthrough.c
   15.38 +// 
   15.39 +//  Functions regarding passing DMI requests to HWTPM
   15.40 +//
   15.41 +// ==================================================================
   15.42 +
   15.43 +#include "tcg.h"
   15.44 +#include "vtpm_manager.h"
   15.45 +#include "vtpmpriv.h"
   15.46 +#include "vtsp.h"
   15.47 +#include "log.h"
   15.48 +
   15.49 +TPM_RESULT VTPM_Handle_TPM_Command( VTPM_DMI_RESOURCE *dmi,
   15.50 +				    buffer_t *inbuf,  
   15.51 +				    buffer_t *outbuf) {
   15.52 +  
   15.53 +  TPM_RESULT status = TPM_SUCCESS;
   15.54 +  TPM_COMMAND_CODE *ord;               
   15.55 +  
   15.56 +  ord = (TPM_COMMAND_CODE *) (inbuf->bytes + sizeof(TPM_TAG) + sizeof(UINT32));
   15.57 +  
   15.58 +  switch (*ord) {
   15.59 +    
   15.60 +    // Forbidden for DMI use
   15.61 +  case TPM_ORD_TakeOwnership:
   15.62 +  case TPM_ORD_ChangeAuthOwner:
   15.63 +  case TPM_ORD_DirWriteAuth:
   15.64 +  case TPM_ORD_DirRead:
   15.65 +  case TPM_ORD_AuthorizeMigrationKey:
   15.66 +  case TPM_ORD_CreateMaintenanceArchive:
   15.67 +  case TPM_ORD_LoadMaintenanceArchive:
   15.68 +  case TPM_ORD_KillMaintenanceFeature:
   15.69 +  case TPM_ORD_LoadManuMaintPub:
   15.70 +  case TPM_ORD_ReadManuMaintPub:
   15.71 +  case TPM_ORD_SelfTestFull:
   15.72 +  case TPM_ORD_SelfTestStartup:
   15.73 +  case TPM_ORD_CertifySelfTest:
   15.74 +  case TPM_ORD_ContinueSelfTest:
   15.75 +  case TPM_ORD_GetTestResult:
   15.76 +  case TPM_ORD_Reset:
   15.77 +  case TPM_ORD_OwnerClear:
   15.78 +  case TPM_ORD_DisableOwnerClear:
   15.79 +  case TPM_ORD_ForceClear:
   15.80 +  case TPM_ORD_DisableForceClear:
   15.81 +  case TPM_ORD_GetCapabilityOwner:
   15.82 +  case TPM_ORD_OwnerSetDisable:
   15.83 +  case TPM_ORD_PhysicalEnable:
   15.84 +  case TPM_ORD_PhysicalDisable:
   15.85 +  case TPM_ORD_SetOwnerInstall:
   15.86 +  case TPM_ORD_PhysicalSetDeactivated:
   15.87 +  case TPM_ORD_SetTempDeactivated:
   15.88 +  case TPM_ORD_CreateEndorsementKeyPair:
   15.89 +  case TPM_ORD_GetAuditEvent:
   15.90 +  case TPM_ORD_GetAuditEventSigned:
   15.91 +  case TPM_ORD_GetOrdinalAuditStatus:
   15.92 +  case TPM_ORD_SetOrdinalAuditStatus:
   15.93 +  case TPM_ORD_SetRedirection:
   15.94 +  case TPM_ORD_FieldUpgrade:
   15.95 +  case TSC_ORD_PhysicalPresence:
   15.96 +    status = TPM_DISABLED_CMD;
   15.97 +    goto abort_egress;
   15.98 +    break;
   15.99 +    
  15.100 +  } // End ORD Switch
  15.101 +  
  15.102 +  // Call TCS with command
  15.103 +  
  15.104 +  TPMTRY(TPM_IOERROR, VTSP_RawTransmit( dmi->TCSContext,inbuf, outbuf) );
  15.105 +  
  15.106 +  goto egress;
  15.107 +  
  15.108 + abort_egress:
  15.109 +  vtpmloginfo(VTPM_LOG_VTPM, "TPM Command Failed in tpmpassthrough.\n");
  15.110 + egress:
  15.111 +  
  15.112 +  return status;
  15.113 +}
    16.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    16.2 +++ b/tools/vtpm_manager/manager/vtpm_manager.c	Tue Aug 30 11:39:25 2005 -0800
    16.3 @@ -0,0 +1,735 @@
    16.4 +// ===================================================================
    16.5 +// 
    16.6 +// Copyright (c) 2005, Intel Corp.
    16.7 +// All rights reserved.
    16.8 +//
    16.9 +// Redistribution and use in source and binary forms, with or without 
   16.10 +// modification, are permitted provided that the following conditions 
   16.11 +// are met:
   16.12 +//
   16.13 +//   * Redistributions of source code must retain the above copyright 
   16.14 +//     notice, this list of conditions and the following disclaimer.
   16.15 +//   * Redistributions in binary form must reproduce the above 
   16.16 +//     copyright notice, this list of conditions and the following 
   16.17 +//     disclaimer in the documentation and/or other materials provided 
   16.18 +//     with the distribution.
   16.19 +//   * Neither the name of Intel Corporation nor the names of its 
   16.20 +//     contributors may be used to endorse or promote products derived
   16.21 +//     from this software without specific prior written permission.
   16.22 +//
   16.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   16.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   16.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   16.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   16.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   16.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   16.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   16.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   16.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   16.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   16.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   16.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   16.35 +// ===================================================================
   16.36 +// 
   16.37 +// vtpm_manager.c
   16.38 +// 
   16.39 +//  This file will house the main logic of the VTPM Manager
   16.40 +//
   16.41 +// ==================================================================
   16.42 +
   16.43 +#include <stdio.h>
   16.44 +#include <unistd.h>
   16.45 +#include <sys/types.h>
   16.46 +#include <sys/stat.h>
   16.47 +#include <fcntl.h>
   16.48 +#include <string.h>
   16.49 +
   16.50 +#ifndef VTPM_MULTI_VM
   16.51 +#include <pthread.h>
   16.52 +#include <errno.h>
   16.53 +#include <aio.h>
   16.54 +#include <time.h>
   16.55 +#endif
   16.56 +
   16.57 +#include "vtpm_manager.h"
   16.58 +#include "vtpmpriv.h"
   16.59 +#include "vtsp.h"
   16.60 +#include "bsg.h"
   16.61 +#include "hashtable.h"
   16.62 +#include "hashtable_itr.h"
   16.63 +
   16.64 +#include "log.h"
   16.65 +#include "buffer.h"
   16.66 +
   16.67 +VTPM_GLOBALS *vtpm_globals=NULL;
   16.68 +
   16.69 +#ifdef VTPM_MULTI_VM
   16.70 + #define vtpmhandlerloginfo(module,fmt,args...) vtpmloginfo (module, fmt, ##args );
   16.71 + #define vtpmhandlerloginfomore(module,fmt,args...) vtpmloginfomore (module, fmt, ##args );
   16.72 + #define vtpmhandlerlogerror(module,fmt,args...) vtpmlogerror (module, fmt, ##args );
   16.73 +#else 
   16.74 + #define vtpmhandlerloginfo(module,fmt,args...) vtpmloginfo (module, "[%d]: " fmt, threadType, ##args );
   16.75 + #define vtpmhandlerloginfomore(module,fmt,args...) vtpmloginfomore (module, fmt, ##args );
   16.76 + #define vtpmhandlerlogerror(module,fmt,args...) vtpmlogerror (module, "[%d]: " fmt, threadType, ##args );
   16.77 +#endif
   16.78 +
   16.79 +// --------------------------- Static Auths --------------------------
   16.80 +#ifdef USE_FIXED_SRK_AUTH
   16.81 +
   16.82 +static BYTE FIXED_SRK_AUTH[20] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   16.83 +                                  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
   16.84 +
   16.85 +static BYTE FIXED_EK_AUTH[20] =  {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
   16.86 +                                  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
   16.87 +
   16.88 +#endif
   16.89 +                                  
   16.90 +// -------------------------- Hash table functions --------------------
   16.91 +
   16.92 +static unsigned int hashfunc32(void *ky) {
   16.93 +  return (* (UINT32 *) ky);
   16.94 +}
   16.95 +
   16.96 +static int equals32(void *k1, void *k2) {
   16.97 +  return (*(UINT32 *) k1 == *(UINT32 *) k2);
   16.98 +}
   16.99 +
  16.100 +// --------------------------- Functions ------------------------------
  16.101 +
  16.102 +TPM_RESULT VTPM_Create_Service(){
  16.103 +  
  16.104 +  TPM_RESULT status = TPM_SUCCESS;
  16.105 +  
  16.106 +  // Generate Auth's for SRK & Owner
  16.107 +#ifdef USE_FIXED_SRK_AUTH
  16.108 +  memcpy(vtpm_globals->owner_usage_auth, FIXED_SRK_AUTH, sizeof(TPM_AUTHDATA));
  16.109 +  memcpy(vtpm_globals->srk_usage_auth, FIXED_EK_AUTH, sizeof(TPM_AUTHDATA));
  16.110 +#else    
  16.111 +  Crypto_GetRandom(vtpm_globals->owner_usage_auth, sizeof(TPM_AUTHDATA) );
  16.112 +  Crypto_GetRandom(vtpm_globals->srk_usage_auth, sizeof(TPM_AUTHDATA) );  
  16.113 +#endif
  16.114 +  
  16.115 +  // Take Owership of TPM
  16.116 +  CRYPTO_INFO ek_cryptoInfo;
  16.117 +  
  16.118 +  vtpmloginfo(VTPM_LOG_VTPM, "Attempting Pubek Read. NOTE: Failure is ok.\n");
  16.119 +  status = VTSP_ReadPubek(vtpm_globals->manager_tcs_handle, &ek_cryptoInfo);
  16.120 +  
  16.121 +  // If we can read PubEK then there is no owner and we should take it.
  16.122 +  if (status == TPM_SUCCESS) { 
  16.123 +    TPMTRYRETURN(VTSP_TakeOwnership(vtpm_globals->manager_tcs_handle,
  16.124 +				    (const TPM_AUTHDATA*)&vtpm_globals->owner_usage_auth, 
  16.125 +				    (const TPM_AUTHDATA*)&vtpm_globals->srk_usage_auth,
  16.126 +				    &ek_cryptoInfo,
  16.127 +				    &vtpm_globals->keyAuth)); 
  16.128 +  
  16.129 +    TPMTRYRETURN(VTSP_DisablePubekRead(vtpm_globals->manager_tcs_handle,
  16.130 +                                       (const TPM_AUTHDATA*)&vtpm_globals->owner_usage_auth,  
  16.131 +                                       &vtpm_globals->keyAuth));     
  16.132 +  }
  16.133 +  
  16.134 +  // Generate storage key's auth
  16.135 +  Crypto_GetRandom(  &vtpm_globals->storage_key_usage_auth, 
  16.136 +		     sizeof(TPM_AUTHDATA) );
  16.137 +  
  16.138 +  TCS_AUTH osap;
  16.139 +  TPM_AUTHDATA sharedsecret;
  16.140 +  
  16.141 +  TPMTRYRETURN( VTSP_OSAP(vtpm_globals->manager_tcs_handle,
  16.142 +			  TPM_ET_SRK,
  16.143 +			  0, 
  16.144 +			  (const TPM_AUTHDATA*)&vtpm_globals->srk_usage_auth,
  16.145 +			  &sharedsecret, 
  16.146 +			  &osap) ); 
  16.147 +  
  16.148 +  TPMTRYRETURN( VTSP_CreateWrapKey( vtpm_globals->manager_tcs_handle,
  16.149 +				    TPM_KEY_BIND,
  16.150 +				    (const TPM_AUTHDATA*)&vtpm_globals->storage_key_usage_auth,
  16.151 +				    TPM_SRK_KEYHANDLE, 
  16.152 +				    (const TPM_AUTHDATA*)&sharedsecret,
  16.153 +				    &vtpm_globals->storageKeyWrap,
  16.154 +				    &osap) );
  16.155 +  
  16.156 +  vtpm_globals->keyAuth.fContinueAuthSession = TRUE;
  16.157 +  
  16.158 +  goto egress;
  16.159 +  
  16.160 + abort_egress:
  16.161 +  exit(1);
  16.162 +  
  16.163 + egress:
  16.164 +  vtpmloginfo(VTPM_LOG_VTPM, "New VTPM Service initialized (Status = %d).\n", status);
  16.165 +  return status;
  16.166 +  
  16.167 +}
  16.168 +
  16.169 +
  16.170 +//////////////////////////////////////////////////////////////////////////////
  16.171 +#ifdef VTPM_MULTI_VM
  16.172 +int VTPM_Service_Handler(){
  16.173 +#else
  16.174 +void *VTPM_Service_Handler(void *threadTypePtr){
  16.175 +#endif
  16.176 +  TPM_RESULT      status =  TPM_FAIL; // Should never return
  16.177 +  UINT32          dmi, in_param_size, cmd_size, out_param_size, out_message_size, out_message_size_full, dmi_cmd_size;
  16.178 +  BYTE            *cmd_header, *in_param, *out_message, *dmi_cmd;
  16.179 +  buffer_t        *command_buf=NULL, *result_buf=NULL;
  16.180 +  TPM_TAG         tag;
  16.181 +  TPM_COMMAND_CODE ord;
  16.182 +  VTPM_DMI_RESOURCE *dmi_res;
  16.183 +  int  size_read, size_write, i;
  16.184 +  
  16.185 +#ifndef VTPM_MULTI_VM
  16.186 +  int threadType = *(int *) threadTypePtr;
  16.187 +  
  16.188 +  // async io structures
  16.189 +  struct aiocb dmi_aio;
  16.190 +  struct aiocb *dmi_aio_a[1];
  16.191 +  dmi_aio_a[0] = &dmi_aio;
  16.192 +#endif
  16.193 +  
  16.194 +#ifdef DUMMY_BACKEND
  16.195 +  int dummy_rx;  
  16.196 +#endif
  16.197 +  
  16.198 +  // TODO: Reinsert ifdefs to enable support for MULTI-VM 
  16.199 +  
  16.200 +  cmd_header = (BYTE *) malloc(VTPM_COMMAND_HEADER_SIZE_SRV);
  16.201 +  command_buf = (buffer_t *) malloc(sizeof(buffer_t));
  16.202 +  result_buf = (buffer_t *) malloc(sizeof(buffer_t));
  16.203 +  
  16.204 +#ifndef VTPM_MULTI_VM
  16.205 +  TPM_RESULT *ret_value = (TPM_RESULT *) malloc(sizeof(TPM_RESULT));
  16.206 +#endif
  16.207 +  
  16.208 +  int *tx_fh, *rx_fh;
  16.209 +  
  16.210 +#ifdef VTPM_MULTI_VM
  16.211 +  rx_fh = &vtpm_globals->be_fh;
  16.212 +#else
  16.213 +  if (threadType == BE_LISTENER_THREAD) {
  16.214 +#ifdef DUMMY_BACKEND    
  16.215 +    dummy_rx = -1;
  16.216 +    rx_fh = &dummy_rx;
  16.217 +#else
  16.218 +    rx_fh = &vtpm_globals->be_fh;
  16.219 +#endif
  16.220 +  } else { // DMI_LISTENER_THREAD
  16.221 +    rx_fh = &vtpm_globals->vtpm_rx_fh;
  16.222 +  }
  16.223 +#endif
  16.224 +  
  16.225 +#ifndef VTPM_MULTI_VM
  16.226 +  int fh;
  16.227 +  if (threadType == BE_LISTENER_THREAD) {
  16.228 +    tx_fh = &vtpm_globals->be_fh;
  16.229 +    if ( (fh = open(GUEST_RX_FIFO, O_RDWR)) == -1) {
  16.230 +      if ( mkfifo(GUEST_RX_FIFO, S_IWUSR | S_IRUSR ) ){
  16.231 +				*ret_value = TPM_FAIL;
  16.232 +				pthread_exit(ret_value);
  16.233 +      }
  16.234 +    } else 
  16.235 +      close(fh);
  16.236 +    
  16.237 +  } else { // else DMI_LISTENER_THREAD
  16.238 +    // tx_fh will be set once the DMI is identified
  16.239 +    // But we need to make sure the read pip is created.
  16.240 +    if ( (fh = open(VTPM_RX_FIFO, O_RDWR)) == -1) {
  16.241 +      if ( mkfifo(VTPM_RX_FIFO, S_IWUSR | S_IRUSR ) ){
  16.242 +	*ret_value = TPM_FAIL;
  16.243 +	pthread_exit(ret_value);
  16.244 +      }
  16.245 +    } else 
  16.246 +      close(fh);
  16.247 +    
  16.248 +  }
  16.249 +#endif
  16.250 +  
  16.251 +  while(1) {
  16.252 +    
  16.253 +    if (threadType == BE_LISTENER_THREAD) {
  16.254 +      vtpmhandlerloginfo(VTPM_LOG_VTPM, "Waiting for Guest requests & ctrl messages.\n");
  16.255 +    } else 
  16.256 +      vtpmhandlerloginfo(VTPM_LOG_VTPM, "Waiting for DMI messages.\n");
  16.257 +    
  16.258 +    
  16.259 +    if (*rx_fh < 0) {
  16.260 +      if (threadType == BE_LISTENER_THREAD) 
  16.261 +#ifdef DUMMY_BACKEND
  16.262 +	*rx_fh = open("/tmp/in.fifo", O_RDWR);
  16.263 +#else
  16.264 +        *rx_fh = open(VTPM_BE_DEV, O_RDWR);
  16.265 +#endif
  16.266 +      else  // DMI Listener   
  16.267 +	*rx_fh = open(VTPM_RX_FIFO, O_RDWR);
  16.268 +      
  16.269 +    }
  16.270 +    
  16.271 +    if (*rx_fh < 0) {
  16.272 +      vtpmhandlerlogerror(VTPM_LOG_VTPM, "Can't open inbound fh.\n");
  16.273 +#ifdef VTPM_MULTI_VM
  16.274 +      return TPM_IOERROR; 
  16.275 +#else
  16.276 +      *ret_value = TPM_IOERROR;
  16.277 +      pthread_exit(ret_value);
  16.278 +#endif
  16.279 +    }
  16.280 +    
  16.281 +    size_read = read(*rx_fh, cmd_header, VTPM_COMMAND_HEADER_SIZE_SRV);
  16.282 +    if (size_read > 0) {
  16.283 +      vtpmhandlerloginfo(VTPM_LOG_VTPM_DEEP, "RECV[%d}: 0x", size_read);
  16.284 +      for (i=0; i<size_read; i++) 
  16.285 +		vtpmhandlerloginfomore(VTPM_LOG_VTPM_DEEP, "%x ", cmd_header[i]);
  16.286 +    } else {
  16.287 +      vtpmhandlerlogerror(VTPM_LOG_VTPM, "Can't read from BE. Aborting... \n");
  16.288 +      close(*rx_fh);
  16.289 +      *rx_fh = -1;
  16.290 +      goto abort_command;
  16.291 +    }
  16.292 +
  16.293 +    if (size_read < (int) VTPM_COMMAND_HEADER_SIZE_SRV) {
  16.294 +      vtpmhandlerloginfo(VTPM_LOG_VTPM_DEEP, "\n");
  16.295 +      vtpmhandlerlogerror(VTPM_LOG_VTPM, "Command shorter than normal header (%d bytes). Aborting...\n", size_read);
  16.296 +      goto abort_command;
  16.297 +    }
  16.298 +    
  16.299 +    BSG_UnpackList(cmd_header, 4,
  16.300 +		   BSG_TYPE_UINT32, &dmi,
  16.301 +		   BSG_TPM_TAG, &tag,
  16.302 +		   BSG_TYPE_UINT32, &in_param_size,
  16.303 +		   BSG_TPM_COMMAND_CODE, &ord );
  16.304 +    
  16.305 +    // Note that in_param_size is in the client's context
  16.306 +    cmd_size = in_param_size - VTPM_COMMAND_HEADER_SIZE_CLT;
  16.307 +    if (cmd_size > 0) {
  16.308 +      in_param = (BYTE *) malloc(cmd_size);
  16.309 +      size_read = read( *rx_fh, in_param, cmd_size);
  16.310 +      if (size_read > 0) {
  16.311 +	for (i=0; i<size_read; i++) 
  16.312 +	  vtpmhandlerloginfomore(VTPM_LOG_VTPM_DEEP, "%x ", in_param[i]);
  16.313 +	
  16.314 +      } else {
  16.315 +        vtpmhandlerlogerror(VTPM_LOG_VTPM, "Error reading from BE. Aborting... \n");
  16.316 +	close(*rx_fh);
  16.317 +	*rx_fh = -1;
  16.318 +	goto abort_command;
  16.319 +      }
  16.320 +      vtpmhandlerloginfomore(VTPM_LOG_VTPM_DEEP, "\n");
  16.321 +      
  16.322 +      if (size_read < (int) cmd_size) {
  16.323 +	vtpmhandlerloginfomore(VTPM_LOG_VTPM_DEEP, "\n");
  16.324 +	vtpmhandlerlogerror(VTPM_LOG_VTPM, "Command read(%d) is shorter than header indicates(%d). Aborting...\n", size_read, cmd_size);
  16.325 +	goto abort_command;
  16.326 +      }
  16.327 +    } else {
  16.328 +      in_param = NULL;
  16.329 +      vtpmhandlerloginfomore(VTPM_LOG_VTPM_DEEP, "\n");
  16.330 +    }            
  16.331 +    
  16.332 +    if ((threadType != BE_LISTENER_THREAD) && (dmi == 0)) {
  16.333 +      vtpmhandlerlogerror(VTPM_LOG_VTPM, "Attempt to access dom0 commands from DMI interface. Aborting...\n");
  16.334 +      goto abort_command;
  16.335 +    }
  16.336 +    
  16.337 +    dmi_res = (VTPM_DMI_RESOURCE *) hashtable_search(vtpm_globals->dmi_map, &dmi);
  16.338 +    if (dmi_res == NULL) {
  16.339 +      vtpmhandlerlogerror(VTPM_LOG_VTPM, "Attempted access to non-existent DMI in domain: %d. Aborting...\n", dmi);
  16.340 +      goto abort_command;
  16.341 +    }
  16.342 +    if (!dmi_res->connected) {
  16.343 +      vtpmhandlerlogerror(VTPM_LOG_VTPM, "Attempted access to disconnected DMI in domain: %d. Aborting...\n", dmi);
  16.344 +      goto abort_command;
  16.345 +    }
  16.346 +    
  16.347 +    if (threadType != BE_LISTENER_THREAD) 
  16.348 +      tx_fh = &dmi_res->vtpm_tx_fh;
  16.349 +    // else we set this before the while loop since it doesn't change.
  16.350 +    
  16.351 +    if ( (buffer_init_convert(command_buf, cmd_size, in_param) != TPM_SUCCESS) || 
  16.352 +	 (buffer_init(result_buf, 0, 0) != TPM_SUCCESS) ) {
  16.353 +      vtpmhandlerlogerror(VTPM_LOG_VTPM, "Failed to setup buffers. Aborting...\n");
  16.354 +      goto abort_command;
  16.355 +    }
  16.356 +    
  16.357 +    // Dispatch it as either control or user request.
  16.358 +    if (tag == VTPM_TAG_REQ) { 
  16.359 +      if (dmi_res->dmi_id == VTPM_CTL_DM){ 
  16.360 +	switch (ord) {
  16.361 +	case VTPM_ORD_OPEN:
  16.362 +	  status = VTPM_Handle_New_DMI(command_buf);
  16.363 +	  break;
  16.364 +          
  16.365 +	case VTPM_ORD_CLOSE:
  16.366 +	  status = VTPM_Handle_Close_DMI(command_buf);
  16.367 +	  break;
  16.368 +          
  16.369 +	case VTPM_ORD_DELETE:
  16.370 +	  status = VTPM_Handle_Delete_DMI(command_buf);
  16.371 +	  break;
  16.372 +	default:
  16.373 +	  status = TPM_BAD_ORDINAL; 
  16.374 +	} // switch
  16.375 +      } else {
  16.376 +	
  16.377 +	switch (ord) {                
  16.378 +	case VTPM_ORD_SAVENVM:
  16.379 +	  status= VTPM_Handle_Save_NVM(dmi_res,
  16.380 +				       command_buf, 
  16.381 +				       result_buf);
  16.382 +	  break;
  16.383 +	case VTPM_ORD_LOADNVM:
  16.384 +	  status= VTPM_Handle_Load_NVM(dmi_res, 
  16.385 +				       command_buf, 
  16.386 +				       result_buf);
  16.387 +	  break;
  16.388 +	  
  16.389 +	case VTPM_ORD_TPMCOMMAND:
  16.390 +	  status= VTPM_Handle_TPM_Command(dmi_res, 
  16.391 +					  command_buf, 
  16.392 +					  result_buf);
  16.393 +	  break;
  16.394 +	  
  16.395 +	default:
  16.396 +	  status = TPM_BAD_ORDINAL; 
  16.397 +	} // switch
  16.398 +      }
  16.399 +    } else { // This is not a VTPM Command at all
  16.400 +      
  16.401 +      if (threadType == BE_LISTENER_THREAD) {
  16.402 +	if (dmi == 0) {
  16.403 +	  // This usually indicates a FE/BE driver.
  16.404 +	  vtpmhandlerlogerror(VTPM_LOG_VTPM, "Illegal use of TPM command from dom0\n");
  16.405 +	  status = TPM_FAIL;
  16.406 +	} else {
  16.407 +	  vtpmhandlerloginfo(VTPM_LOG_VTPM, "Forwarding command to DMI.\n");
  16.408 +	  
  16.409 +	  if (dmi_res->guest_tx_fh < 0)
  16.410 +	    dmi_res->guest_tx_fh = open(dmi_res->guest_tx_fname, O_WRONLY | O_NONBLOCK);
  16.411 +          
  16.412 +	  if (dmi_res->guest_tx_fh < 0){
  16.413 +	    vtpmhandlerlogerror(VTPM_LOG_VTPM, "VTPM ERROR: Can't open outbound fh to dmi.\n");
  16.414 +	    status = TPM_IOERROR;
  16.415 +	    goto abort_with_error;
  16.416 +	  }        
  16.417 +          
  16.418 +	  //Note: Send message + dmi_id
  16.419 +	  if (cmd_size) {
  16.420 +	    dmi_cmd = (BYTE *) malloc(VTPM_COMMAND_HEADER_SIZE_SRV + cmd_size);
  16.421 +	    dmi_cmd_size = VTPM_COMMAND_HEADER_SIZE_SRV + cmd_size;
  16.422 +	    memcpy(dmi_cmd, cmd_header, VTPM_COMMAND_HEADER_SIZE_SRV);
  16.423 +	    memcpy(dmi_cmd + VTPM_COMMAND_HEADER_SIZE_SRV, in_param, cmd_size);
  16.424 +	    size_write = write(dmi_res->guest_tx_fh, dmi_cmd, dmi_cmd_size);
  16.425 +	    
  16.426 +	    if (size_write > 0) {
  16.427 +	      vtpmhandlerloginfo(VTPM_LOG_VTPM_DEEP, "SENT (DMI): 0x");
  16.428 +	      for (i=0; i<VTPM_COMMAND_HEADER_SIZE_SRV + cmd_size; i++) {
  16.429 +		vtpmhandlerloginfomore(VTPM_LOG_VTPM_DEEP, "%x ", dmi_cmd[i]);
  16.430 +	      }
  16.431 +	      vtpmhandlerloginfomore(VTPM_LOG_VTPM_DEEP, "\n");
  16.432 +	    } else {
  16.433 +              vtpmhandlerlogerror(VTPM_LOG_VTPM, "Error writing to DMI. Aborting... \n");
  16.434 +	      close(dmi_res->guest_tx_fh);
  16.435 +	      dmi_res->guest_tx_fh = -1;
  16.436 +              status = TPM_IOERROR;
  16.437 +	      goto abort_with_error;
  16.438 +	    }
  16.439 +	    free(dmi_cmd);
  16.440 +	  } else {
  16.441 +	    dmi_cmd_size = VTPM_COMMAND_HEADER_SIZE_SRV;
  16.442 +	    size_write = write(dmi_res->guest_tx_fh, cmd_header, VTPM_COMMAND_HEADER_SIZE_SRV );
  16.443 +	    if (size_write > 0) {
  16.444 +	      for (i=0; i<VTPM_COMMAND_HEADER_SIZE_SRV; i++) 
  16.445 +		vtpmhandlerloginfomore(VTPM_LOG_VTPM_DEEP, "%x ", cmd_header[i]);
  16.446 +	      
  16.447 +	      vtpmhandlerloginfomore(VTPM_LOG_VTPM_DEEP, "\n");
  16.448 +	    } else {
  16.449 +              vtpmhandlerlogerror(VTPM_LOG_VTPM, "Error writing to DMI. Aborting... \n");
  16.450 +	      close(dmi_res->guest_tx_fh);
  16.451 +	      dmi_res->guest_tx_fh = -1;
  16.452 +              status = TPM_IOERROR;
  16.453 +	      goto abort_with_error;
  16.454 +	    }
  16.455 +	  }
  16.456 +          
  16.457 +	  if (size_write != (int) dmi_cmd_size) 
  16.458 +	    vtpmhandlerlogerror(VTPM_LOG_VTPM, "Could not write entire command to DMI (%d/%d)\n", size_write, dmi_cmd_size);
  16.459 +	  buffer_free(command_buf);
  16.460 +	  
  16.461 +	  if (vtpm_globals->guest_rx_fh < 0) 
  16.462 +	    vtpm_globals->guest_rx_fh = open(GUEST_RX_FIFO, O_RDONLY);
  16.463 +          
  16.464 +	  if (vtpm_globals->guest_rx_fh < 0){
  16.465 +	    vtpmhandlerlogerror(VTPM_LOG_VTPM, "Can't open inbound fh to dmi.\n");
  16.466 +            status = TPM_IOERROR;
  16.467 +	    goto abort_with_error;
  16.468 +	  }                  
  16.469 +	  
  16.470 +          size_read = read( vtpm_globals->guest_rx_fh, cmd_header, VTPM_COMMAND_HEADER_SIZE_SRV);
  16.471 +	  if (size_read > 0) {
  16.472 +	    vtpmhandlerloginfo(VTPM_LOG_VTPM_DEEP, "RECV (DMI): 0x");
  16.473 +	    for (i=0; i<size_read; i++) 
  16.474 +	      vtpmhandlerloginfomore(VTPM_LOG_VTPM_DEEP, "%x ", cmd_header[i]);
  16.475 +	    
  16.476 +	  } else {
  16.477 +            vtpmhandlerlogerror(VTPM_LOG_VTPM, "Error reading from DMI. Aborting... \n");
  16.478 +	    close(vtpm_globals->guest_rx_fh);
  16.479 +	    vtpm_globals->guest_rx_fh = -1;
  16.480 +            status = TPM_IOERROR;
  16.481 +	    goto abort_with_error;
  16.482 +	  }
  16.483 +          
  16.484 +	  if (size_read < (int) VTPM_COMMAND_HEADER_SIZE_SRV) {
  16.485 +	    //vtpmdeepsublog("\n");
  16.486 +	    vtpmhandlerlogerror(VTPM_LOG_VTPM, "Command from DMI shorter than normal header. Aborting...\n");
  16.487 +            status = TPM_IOERROR;
  16.488 +	    goto abort_with_error;
  16.489 +	  }
  16.490 +          
  16.491 +	  BSG_UnpackList(cmd_header, 4,
  16.492 +			 BSG_TYPE_UINT32, &dmi,
  16.493 +			 BSG_TPM_TAG, &tag,
  16.494 +			 BSG_TYPE_UINT32, &in_param_size,
  16.495 +			 BSG_TPM_COMMAND_CODE, &status );
  16.496 +        
  16.497 +	  // Note that in_param_size is in the client's context
  16.498 +	  cmd_size = in_param_size - VTPM_COMMAND_HEADER_SIZE_CLT;
  16.499 +	  if (cmd_size > 0) {
  16.500 +	    in_param = (BYTE *) malloc(cmd_size);
  16.501 +	    size_read = read( vtpm_globals->guest_rx_fh, in_param, cmd_size);
  16.502 +	    if (size_read > 0) {
  16.503 +	      for (i=0; i<size_read; i++) 
  16.504 +		vtpmhandlerloginfomore(VTPM_LOG_VTPM_DEEP, "%x ", in_param[i]);
  16.505 +	      
  16.506 +	    } else {
  16.507 +              vtpmhandlerlogerror(VTPM_LOG_VTPM, "Error reading from BE. Aborting... \n");
  16.508 +	      close(vtpm_globals->guest_rx_fh);
  16.509 +	      vtpm_globals->guest_rx_fh = -1;
  16.510 +              status = TPM_IOERROR;
  16.511 +	      goto abort_with_error;
  16.512 +	    }
  16.513 +	    vtpmhandlerloginfomore(VTPM_LOG_VTPM, "\n");
  16.514 +            
  16.515 +	    if (size_read < (int)cmd_size) {
  16.516 +	      vtpmhandlerloginfomore(VTPM_LOG_VTPM, "\n");
  16.517 +	      vtpmhandlerlogerror(VTPM_LOG_VTPM, "Command read(%d) from DMI is shorter than header indicates(%d). Aborting...\n", size_read, cmd_size);
  16.518 +              status = TPM_IOERROR;
  16.519 +	      goto abort_with_error;
  16.520 +	    }
  16.521 +	  } else {
  16.522 +	    in_param = NULL;
  16.523 +	    vtpmhandlerloginfomore(VTPM_LOG_VTPM, "\n");
  16.524 +	  }
  16.525 +                           
  16.526 +	  if (buffer_init_convert(result_buf, cmd_size, in_param) != TPM_SUCCESS) {
  16.527 +	    vtpmhandlerlogerror(VTPM_LOG_VTPM, "Failed to setup buffers. Aborting...\n");
  16.528 +            status = TPM_FAIL;
  16.529 +	    goto abort_with_error;
  16.530 +	  }
  16.531 +	  
  16.532 +	  vtpmhandlerloginfo(VTPM_LOG_VTPM, "Sending DMI's response to guest.\n");
  16.533 +	} // end else for if (dmi==0)
  16.534 +        
  16.535 +      } else { // This is a DMI lister thread. Thus this is from a DMI
  16.536 +#ifdef VTPM_MULTI_VM
  16.537 +	vtpmhandlerlogerror(VTPM_LOG_VTPM, "Attempt to use unsupported direct access to TPM.\n");
  16.538 +	vtpmhandlerloginfo(VTPM_LOG_VTPM_DEEP, "Bad Command. dmi:%d, tag:%d, size:%d, ord:%d, Params: ", dmi, tag, in_param_size, ord);
  16.539 +	for (UINT32 q=0; q<cmd_size; q++) 
  16.540 +	  vtpmhandlerloginfomore(VTPM_LOG_VTPM_DEEP, "%x ", in_param[q]);
  16.541 +	
  16.542 +	vtpmhandlerloginfomore(VTPM_LOG_VTPM_DEEP, "\n");
  16.543 +        
  16.544 +	status = TPM_FAIL;
  16.545 +#else
  16.546 +	
  16.547 +#endif
  16.548 +      } // end else for if BE Listener
  16.549 +    } // end else for is VTPM Command
  16.550 +    
  16.551 +    // Send response to Backend
  16.552 +    if (*tx_fh < 0) {
  16.553 +      if (threadType == BE_LISTENER_THREAD) 
  16.554 +#ifdef DUMMY_BACKEND
  16.555 +	*tx_fh = open("/tmp/out.fifo", O_RDWR);
  16.556 +#else
  16.557 +        *tx_fh = open(VTPM_BE_DEV, O_RDWR);
  16.558 +#endif
  16.559 +      else  // DMI Listener
  16.560 +	*tx_fh = open(dmi_res->vtpm_tx_fname, O_WRONLY);
  16.561 +    }
  16.562 +    
  16.563 +    if (*tx_fh < 0) {
  16.564 +      vtpmhandlerlogerror(VTPM_LOG_VTPM, "VTPM ERROR: Can't open outbound fh.\n");
  16.565 +#ifdef VTPM_MULTI_VM
  16.566 +      return TPM_IOERROR; 
  16.567 +#else
  16.568 +      *ret_value = TPM_IOERROR;
  16.569 +      pthread_exit(ret_value);
  16.570 +#endif
  16.571 +    }        
  16.572 +    
  16.573 + abort_with_error:
  16.574 +    // Prepend VTPM header with destination DM stamped
  16.575 +    out_param_size = buffer_len(result_buf);
  16.576 +    out_message_size = VTPM_COMMAND_HEADER_SIZE_CLT + out_param_size;
  16.577 +    out_message_size_full = VTPM_COMMAND_HEADER_SIZE_SRV + out_param_size;
  16.578 +    out_message = (BYTE *) malloc (out_message_size_full);
  16.579 +    
  16.580 +    BSG_PackList(out_message, 4,
  16.581 +		 BSG_TYPE_UINT32, (BYTE *) &dmi,
  16.582 +		 BSG_TPM_TAG, (BYTE *) &tag,
  16.583 +		 BSG_TYPE_UINT32, (BYTE *) &out_message_size,
  16.584 +		 BSG_TPM_RESULT, (BYTE *) &status);
  16.585 +    
  16.586 +    if (buffer_len(result_buf) > 0) 
  16.587 +      memcpy(out_message + VTPM_COMMAND_HEADER_SIZE_SRV, result_buf->bytes, out_param_size);
  16.588 +    
  16.589 +    
  16.590 +    //Note: Send message + dmi_id
  16.591 +    size_write = write(*tx_fh, out_message, out_message_size_full );
  16.592 +    if (size_write > 0) {
  16.593 +      vtpmhandlerloginfo(VTPM_LOG_VTPM_DEEP, "SENT: 0x");
  16.594 +      for (i=0; i < out_message_size_full; i++) 
  16.595 +	vtpmhandlerloginfomore(VTPM_LOG_VTPM_DEEP, "%x ", out_message[i]);
  16.596 +      
  16.597 +      vtpmhandlerloginfomore(VTPM_LOG_VTPM_DEEP, "\n");            
  16.598 +    } else {
  16.599 +      vtpmhandlerlogerror(VTPM_LOG_VTPM, "Error writing to BE. Aborting... \n");
  16.600 +      close(*tx_fh);
  16.601 +      *tx_fh = -1;
  16.602 +      goto abort_command;
  16.603 +    }
  16.604 +    free(out_message);
  16.605 +    
  16.606 +    if (size_write < (int)out_message_size_full) {
  16.607 +      vtpmhandlerlogerror(VTPM_LOG_VTPM, "Unable to write full command to BE (%d/%d)\n", size_write, out_message_size_full);
  16.608 +      goto abort_command;
  16.609 +    }
  16.610 +    
  16.611 +  abort_command:
  16.612 +    //free buffers
  16.613 +    bzero(cmd_header, VTPM_COMMAND_HEADER_SIZE_SRV);
  16.614 +    //free(in_param); // This was converted to command_buf. No need to free 
  16.615 +    if (command_buf != result_buf) 
  16.616 +      buffer_free(result_buf);
  16.617 +    
  16.618 +    buffer_free(command_buf);
  16.619 +    
  16.620 +#ifndef VTPM_MULTI_VM
  16.621 +    if (threadType != BE_LISTENER_THREAD) {
  16.622 +#endif
  16.623 +      if ( (vtpm_globals->DMI_table_dirty) &&
  16.624 +	   (VTPM_SaveService() != TPM_SUCCESS) ) {
  16.625 +	vtpmhandlerlogerror(VTPM_LOG_VTPM, "ERROR: Unable to save manager data.\n");
  16.626 +      }
  16.627 +#ifndef VTPM_MULTI_VM
  16.628 +    }
  16.629 +#endif
  16.630 +    
  16.631 +  } // End while(1)
  16.632 +  
  16.633 +}
  16.634 +
  16.635 +
  16.636 +///////////////////////////////////////////////////////////////////////////////
  16.637 +TPM_RESULT VTPM_Init_Service() {
  16.638 +  TPM_RESULT status = TPM_FAIL;   
  16.639 +  BYTE *randomsead;
  16.640 +	UINT32 randomsize;
  16.641 +	
  16.642 +  if ((vtpm_globals = (VTPM_GLOBALS *) malloc(sizeof(VTPM_GLOBALS))) == NULL){
  16.643 +		status = TPM_FAIL;
  16.644 +		goto abort_egress;
  16.645 +	}
  16.646 +	memset(vtpm_globals, 0, sizeof(VTPM_GLOBALS));
  16.647 +  vtpm_globals->be_fh = -1;
  16.648 +
  16.649 +#ifndef VTPM_MULTI_VM
  16.650 +  vtpm_globals->vtpm_rx_fh = -1;
  16.651 +  vtpm_globals->guest_rx_fh = -1;
  16.652 +#endif
  16.653 +  if ((vtpm_globals->dmi_map = create_hashtable(10, hashfunc32, equals32)) == NULL){
  16.654 +		status = TPM_FAIL;
  16.655 +		goto abort_egress;
  16.656 +	}
  16.657 +  
  16.658 +  vtpm_globals->DMI_table_dirty = FALSE;
  16.659 +  
  16.660 +  // Create new TCS Object
  16.661 +  vtpm_globals->manager_tcs_handle = 0;
  16.662 +  
  16.663 +  TPMTRYRETURN(TCS_create());
  16.664 +  
  16.665 +  // Create TCS Context for service
  16.666 +  TPMTRYRETURN( TCS_OpenContext(&vtpm_globals->manager_tcs_handle ) );
  16.667 +
  16.668 +	TPMTRYRETURN( TCSP_GetRandom(vtpm_globals->manager_tcs_handle, 
  16.669 +															 &randomsize, 
  16.670 +															 &randomsead));
  16.671 +
  16.672 +	Crypto_Init(randomsead, randomsize);
  16.673 +	TPMTRYRETURN( TCS_FreeMemory (vtpm_globals->manager_tcs_handle, randomsead)); 
  16.674 +	
  16.675 +  // Create OIAP session for service's authorized commands
  16.676 +  TPMTRYRETURN( VTSP_OIAP( vtpm_globals->manager_tcs_handle, 
  16.677 +			   &vtpm_globals->keyAuth) );
  16.678 +  vtpm_globals->keyAuth.fContinueAuthSession = TRUE;
  16.679 +
  16.680 +	// If failed, create new Service.
  16.681 +  if (VTPM_LoadService() != TPM_SUCCESS)
  16.682 +    TPMTRYRETURN( VTPM_Create_Service() );    
  16.683 +
  16.684 +  
  16.685 +  //Load Storage Key 
  16.686 +  TPMTRYRETURN( VTSP_LoadKey( vtpm_globals->manager_tcs_handle,
  16.687 +			      TPM_SRK_KEYHANDLE,
  16.688 +			      &vtpm_globals->storageKeyWrap,
  16.689 +			      (const TPM_AUTHDATA*)&vtpm_globals->srk_usage_auth,
  16.690 +			      &vtpm_globals->storageKeyHandle,
  16.691 +			      &vtpm_globals->keyAuth,
  16.692 +			      &vtpm_globals->storageKey) );
  16.693 +  
  16.694 +  // Create entry for Dom0 for control messages
  16.695 +  TPMTRYRETURN( VTPM_Handle_New_DMI(NULL) );
  16.696 +  
  16.697 +  // --------------------- Command handlers ---------------------------
  16.698 +  
  16.699 +  goto egress;
  16.700 +  
  16.701 + abort_egress:
  16.702 + egress:
  16.703 +  
  16.704 +  return(status);
  16.705 +}
  16.706 + 
  16.707 +void VTPM_Stop_Service() {
  16.708 +  VTPM_DMI_RESOURCE *dmi_res;
  16.709 +  struct hashtable_itr *dmi_itr;
  16.710 +  
  16.711 +  // Close all the TCS contexts. TCS should evict keys based on this
  16.712 +  if (hashtable_count(vtpm_globals->dmi_map) > 0) {
  16.713 +    dmi_itr = hashtable_iterator(vtpm_globals->dmi_map);
  16.714 +    do {
  16.715 +      dmi_res = (VTPM_DMI_RESOURCE *) hashtable_iterator_value(dmi_itr);
  16.716 +      if (dmi_res->connected) 
  16.717 +				if (close_dmi( dmi_res ) != TPM_SUCCESS) 
  16.718 +					vtpmlogerror(VTPM_LOG_VTPM, "Failed to close dmi %d properly.\n", dmi_res->dmi_id);
  16.719 +      
  16.720 +    } while (hashtable_iterator_advance(dmi_itr));
  16.721 +		free (dmi_itr);
  16.722 +  }
  16.723 +  
  16.724 +	
  16.725 +  TCS_CloseContext(vtpm_globals->manager_tcs_handle);
  16.726 +  
  16.727 +  if ( (vtpm_globals->DMI_table_dirty) &&
  16.728 +       (VTPM_SaveService() != TPM_SUCCESS) )
  16.729 +    vtpmlogerror(VTPM_LOG_VTPM, "Unable to save manager data.\n");
  16.730 +  
  16.731 +  hashtable_destroy(vtpm_globals->dmi_map, 1);
  16.732 +  free(vtpm_globals);
  16.733 +  
  16.734 +  close(vtpm_globals->be_fh);
  16.735 +  Crypto_Exit();
  16.736 +	
  16.737 +  vtpmloginfo(VTPM_LOG_VTPM, "VTPM Manager stopped.\n");
  16.738 +}
    17.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    17.2 +++ b/tools/vtpm_manager/manager/vtpm_manager.h	Tue Aug 30 11:39:25 2005 -0800
    17.3 @@ -0,0 +1,137 @@
    17.4 +// ===================================================================
    17.5 +// 
    17.6 +// Copyright (c) 2005, Intel Corp.
    17.7 +// All rights reserved.
    17.8 +//
    17.9 +// Redistribution and use in source and binary forms, with or without 
   17.10 +// modification, are permitted provided that the following conditions 
   17.11 +// are met:
   17.12 +//
   17.13 +//   * Redistributions of source code must retain the above copyright 
   17.14 +//     notice, this list of conditions and the following disclaimer.
   17.15 +//   * Redistributions in binary form must reproduce the above 
   17.16 +//     copyright notice, this list of conditions and the following 
   17.17 +//     disclaimer in the documentation and/or other materials provided 
   17.18 +//     with the distribution.
   17.19 +//   * Neither the name of Intel Corporation nor the names of its 
   17.20 +//     contributors may be used to endorse or promote products derived
   17.21 +//     from this software without specific prior written permission.
   17.22 +//
   17.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   17.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   17.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   17.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   17.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   17.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   17.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   17.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   17.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   17.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   17.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   17.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   17.35 +// ===================================================================
   17.36 +// 
   17.37 +// vtpm_manager.h
   17.38 +// 
   17.39 +//  Public Interface header for VTPM Manager
   17.40 +//
   17.41 +// ==================================================================
   17.42 +
   17.43 +#ifndef __VTPM_MANAGER_H__
   17.44 +#define __VTPM_MANAGER_H__
   17.45 +
   17.46 +#include "tcg.h"
   17.47 +
   17.48 +#define VTPM_TAG_REQ 0x01c1
   17.49 +#define VTPM_TAG_RSP 0x01c4
   17.50 +#define COMMAND_BUFFER_SIZE 4096
   17.51 +
   17.52 +// Header sizes. Note Header MAY include the DMI
   17.53 +#define VTPM_COMMAND_HEADER_SIZE_SRV ( sizeof(UINT32) + sizeof(TPM_TAG) + sizeof(UINT32) + sizeof(TPM_COMMAND_CODE))
   17.54 +#define VTPM_COMMAND_HEADER_SIZE_CLT (                  sizeof(TPM_TAG) + sizeof(UINT32) + sizeof(TPM_COMMAND_CODE))
   17.55 +
   17.56 +// ********************** Public Functions *************************
   17.57 +TPM_RESULT VTPM_Init_Service(); // Start VTPM Service
   17.58 +void VTPM_Stop_Service();  // Stop VTPM Service
   17.59 +#ifdef VTPM_MULTI_VM
   17.60 +int VTPM_Service_Handler();
   17.61 +#else
   17.62 +void *VTPM_Service_Handler(void *threadTypePtr);
   17.63 +#endif
   17.64 +
   17.65 +//************************ Command Codes ****************************
   17.66 +#define VTPM_ORD_OPEN              1   // ULM Creates New DMI
   17.67 +#define VTPM_ORD_CLOSE             2   // ULM Closes a DMI
   17.68 +#define VTPM_ORD_DELETE            3   // ULM Permemently Deletes DMI
   17.69 +#define VTPM_ORD_SAVENVM          4   // DMI requests Secrets Unseal
   17.70 +#define VTPM_ORD_LOADNVM          5   // DMI requests Secrets Saved
   17.71 +#define VTPM_ORD_TPMCOMMAND       6   // DMI issues HW TPM Command
   17.72 +
   17.73 +//************************ Return Codes ****************************
   17.74 +#define VTPM_SUCCESS               0
   17.75 +#define VTPM_FAIL                  1
   17.76 +#define VTPM_UNSUPPORTED           2
   17.77 +#define VTPM_FORBIDDEN             3
   17.78 +#define VTPM_RESTORE_CONTEXT_FAILED    4
   17.79 +#define VTPM_INVALID_REQUEST       5
   17.80 +
   17.81 +/******************* Command Parameter API *************************
   17.82 +
   17.83 +VTPM Command Format
   17.84 +  dmi: 4 bytes                  // Source of message. 
   17.85 +                                // WARNING: This is prepended by the channel. 
   17.86 +                                // Thus it is received by VTPM Manager, 
   17.87 +                                // but not sent by DMI
   17.88 +  tpm tag: 2 bytes
   17.89 +  command size: 4 bytes         // Size of command including header but not DMI
   17.90 +  ord: 4 bytes                  // Command ordinal above
   17.91 +  parameters: size - 10 bytes   // Command Parameter
   17.92 +
   17.93 +VTPM Response Format
   17.94 +  tpm tag: 2 bytes
   17.95 +  response_size: 4 bytes
   17.96 +  status: 4 bytes         
   17.97 +  parameters: size - 10 bytes
   17.98 +
   17.99 +
  17.100 +VTPM_Open:
  17.101 +  Input Parameters:
  17.102 +    Domain_type: 1 byte
  17.103 +    domain_id: 4 bytes
  17.104 +    instance_id: 4 bytes
  17.105 +  Output Parameters:
  17.106 +    None
  17.107 +    
  17.108 +VTPM_Close
  17.109 +  Input Parameters:
  17.110 +    instance_id: 4 bytes
  17.111 +  Output Parameters:
  17.112 +    None
  17.113 +
  17.114 +VTPM_Delete
  17.115 +  Input Parameters:
  17.116 +    instance_id: 4 bytes
  17.117 +  Output Parameters:
  17.118 +    None
  17.119 +
  17.120 +VTPM_SaveNVM
  17.121 +  Input Parameters:
  17.122 +    data: n bytes (Header indicates size of data)
  17.123 +  Output Parameters:
  17.124 +    None
  17.125 +
  17.126 +VTPM_LoadNVM
  17.127 +  Input Parameters:
  17.128 +    None
  17.129 +  Output Parameters:
  17.130 +    data: n bytes (Header indicates size of data)
  17.131 +
  17.132 +VTPM_TPMCommand
  17.133 +  Input Parameters:
  17.134 +    TPM Command Byte Stream: n bytes 
  17.135 +  Output Parameters:
  17.136 +    TPM Reponse Byte Stream: n bytes 
  17.137 +
  17.138 +*********************************************************************/
  17.139 +
  17.140 +#endif //_VTPM_MANAGER_H_
    18.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    18.2 +++ b/tools/vtpm_manager/manager/vtpmd.c	Tue Aug 30 11:39:25 2005 -0800
    18.3 @@ -0,0 +1,134 @@
    18.4 +// ===================================================================
    18.5 +// 
    18.6 +// Copyright (c) 2005, Intel Corp.
    18.7 +// All rights reserved.
    18.8 +//
    18.9 +// Redistribution and use in source and binary forms, with or without 
   18.10 +// modification, are permitted provided that the following conditions 
   18.11 +// are met:
   18.12 +//
   18.13 +//   * Redistributions of source code must retain the above copyright 
   18.14 +//     notice, this list of conditions and the following disclaimer.
   18.15 +//   * Redistributions in binary form must reproduce the above 
   18.16 +//     copyright notice, this list of conditions and the following 
   18.17 +//     disclaimer in the documentation and/or other materials provided 
   18.18 +//     with the distribution.
   18.19 +//   * Neither the name of Intel Corporation nor the names of its 
   18.20 +//     contributors may be used to endorse or promote products derived
   18.21 +//     from this software without specific prior written permission.
   18.22 +//
   18.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   18.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   18.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   18.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   18.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   18.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   18.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   18.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   18.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   18.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   18.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   18.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   18.35 +// ===================================================================
   18.36 +// 
   18.37 +// vtpmd.c
   18.38 +// 
   18.39 +//  Application
   18.40 +//
   18.41 +// ===================================================================
   18.42 +
   18.43 +#include <stdio.h>
   18.44 +#include <signal.h>
   18.45 +#include <sys/types.h>
   18.46 +#include <unistd.h>
   18.47 +#include "vtpm_manager.h"
   18.48 +#include "vtpmpriv.h"
   18.49 +#include "tcg.h"
   18.50 +#include "log.h"
   18.51 +
   18.52 +#ifndef VTPM_MULTI_VM
   18.53 + #include <pthread.h>
   18.54 +#endif
   18.55 +
   18.56 +void signal_handler(int reason) {
   18.57 +#ifndef VTPM_MULTI_VM
   18.58 +
   18.59 +  if (pthread_equal(pthread_self(), vtpm_globals->master_pid)) {
   18.60 +    if (reason >= 0) { // Reason is a signal
   18.61 +      vtpmloginfo(VTPM_LOG_VTPM, "VTPM Manager shutting down for signal %d.\n", reason);
   18.62 +    } else  {// Reason is a TPM_RESULT * -1
   18.63 +      vtpmloginfo(VTPM_LOG_VTPM,"VTPM Manager shuting down for: %s\n", tpm_get_error_name(-1 * reason) );
   18.64 +    }
   18.65 +    
   18.66 +    return;
   18.67 +  } else {
   18.68 +    vtpmloginfo(VTPM_LOG_VTPM, "Child shutting down\n");
   18.69 +    pthread_exit(NULL);
   18.70 +  }
   18.71 +#else
   18.72 +  VTPM_Stop_Service();
   18.73 +  exit(-1);
   18.74 +#endif
   18.75 +}
   18.76 +
   18.77 +struct sigaction ctl_c_handler;
   18.78 +
   18.79 +int main(int argc, char **argv) {
   18.80 +
   18.81 +  vtpmloginfo(VTPM_LOG_VTPM, "Starting VTPM.\n");
   18.82 +  
   18.83 +  if (VTPM_Init_Service() != TPM_SUCCESS) {
   18.84 +    vtpmlogerror(VTPM_LOG_VTPM, "Closing vtpmd due to error during startup.\n");
   18.85 +    return -1;
   18.86 +  }
   18.87 +  
   18.88 +  ctl_c_handler.sa_handler = signal_handler;
   18.89 +  sigemptyset(&ctl_c_handler.sa_mask);
   18.90 +  ctl_c_handler.sa_flags = 0;    
   18.91 +  
   18.92 +  if (sigaction(SIGINT, &ctl_c_handler, NULL) == -1) 
   18.93 +    vtpmlogerror(VTPM_LOG_VTPM, "Could not install SIGINT handler. Ctl+break will not stop service gently.\n");
   18.94 +  
   18.95 +  // For easier debuggin with gdb
   18.96 +  if (sigaction(SIGHUP, &ctl_c_handler, NULL) == -1) 
   18.97 +    vtpmlogerror(VTPM_LOG_VTPM, "Could not install SIGHUP handler. Ctl+break will not stop service gently.\n");    
   18.98 +  
   18.99 +#ifdef VTPM_MULTI_VM
  18.100 +  TPM_RESULT status = VTPM_Service_Handler();
  18.101 +    
  18.102 +  if (status != TPM_SUCCESS) 
  18.103 +    vtpmlogerror(VTPM_LOG_VTPM, "VTPM Manager exited with status %s. It never should exit.\n", tpm_get_error_name(status));
  18.104 +  
  18.105 +  return -1;
  18.106 +#else
  18.107 +  sigset_t sig_mask;
  18.108 +      
  18.109 +  sigemptyset(&sig_mask);
  18.110 +  sigaddset(&sig_mask, SIGPIPE);
  18.111 +  sigprocmask(SIG_BLOCK, &sig_mask, NULL);
  18.112 +  //pthread_mutex_init(&vtpm_globals->dmi_mutex, NULL);
  18.113 +  pthread_t be_thread, dmi_thread;
  18.114 +  int betype_be, dmitype_dmi;
  18.115 +  
  18.116 +  vtpm_globals->master_pid = pthread_self();
  18.117 +  
  18.118 +  betype_be = BE_LISTENER_THREAD;
  18.119 +  if (pthread_create(&be_thread, NULL, VTPM_Service_Handler, &betype_be) != 0) {
  18.120 +    vtpmlogerror(VTPM_LOG_VTPM, "Failed to launch BE Thread.\n");
  18.121 +    exit(-1);
  18.122 +  }
  18.123 +  
  18.124 +  dmitype_dmi = DMI_LISTENER_THREAD;
  18.125 +  if (pthread_create(&dmi_thread, NULL, VTPM_Service_Handler, &dmitype_dmi) != 0) {
  18.126 +    vtpmlogerror(VTPM_LOG_VTPM, "Failed to launch DMI Thread.\n");
  18.127 +    exit(-1);
  18.128 +  }
  18.129 +  
  18.130 +  //Join the other threads until exit time.
  18.131 +  pthread_join(be_thread, NULL);
  18.132 +  pthread_join(dmi_thread, NULL);
  18.133 +  
  18.134 +  VTPM_Stop_Service();
  18.135 +  return 0;
  18.136 +#endif
  18.137 +}
    19.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    19.2 +++ b/tools/vtpm_manager/manager/vtpmpriv.h	Tue Aug 30 11:39:25 2005 -0800
    19.3 @@ -0,0 +1,151 @@
    19.4 +// ===================================================================
    19.5 +// 
    19.6 +// Copyright (c) 2005, Intel Corp.
    19.7 +// All rights reserved.
    19.8 +//
    19.9 +// Redistribution and use in source and binary forms, with or without 
   19.10 +// modification, are permitted provided that the following conditions 
   19.11 +// are met:
   19.12 +//
   19.13 +//   * Redistributions of source code must retain the above copyright 
   19.14 +//     notice, this list of conditions and the following disclaimer.
   19.15 +//   * Redistributions in binary form must reproduce the above 
   19.16 +//     copyright notice, this list of conditions and the following 
   19.17 +//     disclaimer in the documentation and/or other materials provided 
   19.18 +//     with the distribution.
   19.19 +//   * Neither the name of Intel Corporation nor the names of its 
   19.20 +//     contributors may be used to endorse or promote products derived
   19.21 +//     from this software without specific prior written permission.
   19.22 +//
   19.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   19.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   19.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   19.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   19.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   19.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   19.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   19.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   19.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   19.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   19.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   19.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   19.35 +// ===================================================================
   19.36 +// 
   19.37 +// vtpmpriv.h
   19.38 +// 
   19.39 +//  Structures and functions private to the manager
   19.40 +//
   19.41 +// ==================================================================
   19.42 +
   19.43 +#ifndef __VTPMPRIV_H__
   19.44 +#define __VTPMPRIV_H__
   19.45 +
   19.46 +#include "tcg.h"
   19.47 +#include "tcs.h"
   19.48 +#include "buffer.h"
   19.49 +#include "crypto.h"
   19.50 +
   19.51 +#define STATE_FILE    "/var/vtpm/VTPM"
   19.52 +#define DMI_NVM_FILE  "/var/vtpm/vtpm_dm_%d.data"
   19.53 +#define VTPM_BE_DEV   "/dev/vtpm"
   19.54 +#define VTPM_CTL_DM         0
   19.55 +
   19.56 +#ifndef VTPM_MUTLI_VM
   19.57 + #include <sys/types.h>
   19.58 + #define GUEST_TX_FIFO "/var/vtpm/fifos/guest-to-%d.fifo"
   19.59 + #define GUEST_RX_FIFO "/var/vtpm/fifos/guest-from-all.fifo"
   19.60 +
   19.61 + #define VTPM_TX_FIFO  "/var/vtpm/fifos/vtpm-to-%d.fifo"
   19.62 + #define VTPM_RX_FIFO  "/var/vtpm/fifos/vtpm-from-all.fifo"
   19.63 +
   19.64 + #define BE_LISTENER_THREAD 1
   19.65 + #define DMI_LISTENER_THREAD 2
   19.66 +
   19.67 + // Seconds until DMI timeout. Timeouts result in DMI being out
   19.68 + // of sync, which may require a reboot of DMI and guest to recover
   19.69 + // from. Don't set this to low. Also note that DMI may issue a TPM
   19.70 + // call so we should expect time to process at DMI + TPM processing.
   19.71 + #define DMI_TIMEOUT 90 
   19.72 +#endif
   19.73 +
   19.74 +
   19.75 +// ------------------------ Private Structures -----------------------
   19.76 +typedef struct VTPM_DMI_RESOURCE_T {
   19.77 +  // I/O info for Manager to talk to DMI's over FIFOs
   19.78 +#ifndef VTPM_MUTLI_VM
   19.79 +  int                   guest_tx_fh;          // open GUEST_TX_FIFO
   19.80 +  int                   vtpm_tx_fh;           // open VTPM_TX_FIFO
   19.81 +  char                  *guest_tx_fname;      // open GUEST_TX_FIFO
   19.82 +  char                  *vtpm_tx_fname;       // open VTPM_TX_FIFO
   19.83 +  
   19.84 +  pid_t                 dmi_pid;
   19.85 +#endif
   19.86 +  // Non-persistent Information
   19.87 +  bool                  connected;
   19.88 +  UINT32                dmi_domain_id;
   19.89 +  TCS_CONTEXT_HANDLE    TCSContext;     // TCS Handle
   19.90 +  char                  *NVMLocation;   // NULL term string indicating location
   19.91 +                                        // of NVM.
   19.92 +  // Persistent Information about DMI
   19.93 +  UINT32                dmi_id;
   19.94 +  TPM_DIGEST            NVM_measurement;  // Equal to the SHA1 of the blob
   19.95 +  TPM_DIGEST            DMI_measurement;  // Correct measurement of the owning DMI
   19.96 +} VTPM_DMI_RESOURCE;
   19.97 +
   19.98 +typedef struct tdVTPM_GLOBALS {
   19.99 +  // Non-persistent data
  19.100 +  int                 be_fh;                  // File handle to ipc used to communicate with backend
  19.101 +#ifndef VTPM_MULTI_VM
  19.102 +  int                 vtpm_rx_fh;
  19.103 +  int                 guest_rx_fh;
  19.104 +  
  19.105 +  pid_t               master_pid;
  19.106 +#endif
  19.107 +  struct hashtable    *dmi_map;               // Table of all DMI's known indexed by persistent instance #
  19.108 +#ifndef VTPM_MULTI_VM
  19.109 +  pthread_mutex_t     dmi_map_mutex;          // 
  19.110 +#endif
  19.111 +  TCS_CONTEXT_HANDLE  manager_tcs_handle;     // TCS Handle used by manager
  19.112 +  TPM_HANDLE          storageKeyHandle;       // Key used by persistent store
  19.113 +  CRYPTO_INFO         storageKey;             // For software encryption
  19.114 +  TCS_AUTH            keyAuth;                // OIAP session for storageKey 
  19.115 +  BOOL                DMI_table_dirty;        // Indicates that a command
  19.116 +                                              // has updated the DMI table
  19.117 +
  19.118 +    
  19.119 +  // Persistent Data
  19.120 +  TPM_AUTHDATA        owner_usage_auth;       // OwnerAuth of real TPM
  19.121 +  TPM_AUTHDATA        srk_usage_auth;         // SRK Auth of real TPM    
  19.122 +  buffer_t            storageKeyWrap;         // Wrapped copy of storageKey
  19.123 +
  19.124 +  TPM_AUTHDATA        storage_key_usage_auth; 
  19.125 +    
  19.126 +}VTPM_GLOBALS;
  19.127 +
  19.128 +//Global dmi map
  19.129 +extern VTPM_GLOBALS *vtpm_globals;
  19.130 +
  19.131 +// ********************** Command Handler Prototypes ***********************
  19.132 +TPM_RESULT VTPM_Handle_Load_NVM(       VTPM_DMI_RESOURCE *myDMI, 
  19.133 +                                        const buffer_t *inbuf, 
  19.134 +                                        buffer_t *outbuf);
  19.135 +
  19.136 +TPM_RESULT VTPM_Handle_Save_NVM(       VTPM_DMI_RESOURCE *myDMI, 
  19.137 +                                        const buffer_t *inbuf, 
  19.138 +                                        buffer_t *outbuf);
  19.139 +
  19.140 +TPM_RESULT VTPM_Handle_TPM_Command(    VTPM_DMI_RESOURCE *dmi, 
  19.141 +                                        buffer_t *inbuf, 
  19.142 +                                        buffer_t *outbuf);
  19.143 +
  19.144 +TPM_RESULT VTPM_Handle_New_DMI(const buffer_t *param_buf);
  19.145 +                                
  19.146 +TPM_RESULT VTPM_Handle_Close_DMI(const buffer_t *param_buf);
  19.147 +                                   
  19.148 +TPM_RESULT VTPM_Handle_Delete_DMI(const buffer_t *param_buf);
  19.149 +
  19.150 +TPM_RESULT VTPM_SaveService(void);
  19.151 +TPM_RESULT VTPM_LoadService(void);
  19.152 +
  19.153 +TPM_RESULT close_dmi( VTPM_DMI_RESOURCE *dmi_res);
  19.154 +#endif // __VTPMPRIV_H__
    20.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    20.2 +++ b/tools/vtpm_manager/manager/vtsp.c	Tue Aug 30 11:39:25 2005 -0800
    20.3 @@ -0,0 +1,810 @@
    20.4 +// ===================================================================
    20.5 +// 
    20.6 +// Copyright (c) 2005, Intel Corp.
    20.7 +// All rights reserved.
    20.8 +//
    20.9 +// Redistribution and use in source and binary forms, with or without 
   20.10 +// modification, are permitted provided that the following conditions 
   20.11 +// are met:
   20.12 +//
   20.13 +//   * Redistributions of source code must retain the above copyright 
   20.14 +//     notice, this list of conditions and the following disclaimer.
   20.15 +//   * Redistributions in binary form must reproduce the above 
   20.16 +//     copyright notice, this list of conditions and the following 
   20.17 +//     disclaimer in the documentation and/or other materials provided 
   20.18 +//     with the distribution.
   20.19 +//   * Neither the name of Intel Corporation nor the names of its 
   20.20 +//     contributors may be used to endorse or promote products derived
   20.21 +//     from this software without specific prior written permission.
   20.22 +//
   20.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   20.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   20.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   20.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   20.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   20.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   20.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   20.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   20.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   20.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   20.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   20.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   20.35 +// ===================================================================
   20.36 +// 
   20.37 +// vtsp.c
   20.38 +// 
   20.39 +//  Higher level interface to TCS for use in service.
   20.40 +//
   20.41 +// ==================================================================
   20.42 +
   20.43 +#include <string.h>
   20.44 +#include "tcg.h"
   20.45 +#include "tcs.h"
   20.46 +#include "bsg.h"
   20.47 +#include "log.h"
   20.48 +#include "crypto.h"
   20.49 +#include "vtsp.h"
   20.50 +#include "buffer.h"
   20.51 +
   20.52 +#define  RSA_KEY_SIZE 0x0800
   20.53 +
   20.54 +/***********************************************************************************
   20.55 + * GenerateAuth: Generate authorization info to be sent back to application
   20.56 + *
   20.57 + * Parameters: outParamDigestText  The concatenation of output parameters to be SHA1ed
   20.58 + *    outParamDigestTextSize Size of inParamDigestText
   20.59 + *    HMACkey     Key to be used for HMACing
   20.60 + *          For OIAP use key.authUsage or PersistStore.ownerAuth
   20.61 + *          For OSAP use shared secret
   20.62 + *    pAuth     Authorization information from the application
   20.63 + *
   20.64 + * Return:  TPM_SUCCESS   Authorization data created
   20.65 + *    TPM_AUTHFAIL   Invalid (NULL) HMACkey presented for OSAP
   20.66 + *************************************************************************************/
   20.67 +TPM_RESULT GenerateAuth( /*[IN]*/ const BYTE *inParamDigestText,
   20.68 +			 /*[IN]*/ UINT32 inParamDigestTextSize,
   20.69 +			 /*[IN]*/ const TPM_SECRET *HMACkey,  
   20.70 +			 /*[IN,OUT]*/ TCS_AUTH *auth) {
   20.71 +    
   20.72 +  if (inParamDigestText == NULL || auth == NULL) 
   20.73 +    return (TPM_AUTHFAIL);
   20.74 +  else {
   20.75 +    
   20.76 +    //Generate new OddNonce
   20.77 +    Crypto_GetRandom(auth->NonceOdd.nonce, sizeof(TPM_NONCE));
   20.78 +    
   20.79 +    // Create SHA1 inParamDigest
   20.80 +    TPM_DIGEST inParamDigest;
   20.81 +    Crypto_SHA1Full(inParamDigestText, inParamDigestTextSize, (BYTE *) &inParamDigest);
   20.82 +    
   20.83 +    // Create HMAC text. (Concat inParamsDigest with inAuthSetupParams).
   20.84 +    BYTE hmacText[sizeof(TPM_DIGEST) + (2 * sizeof(TPM_NONCE)) + sizeof(BOOL)];
   20.85 +    
   20.86 +    BSG_PackList(   hmacText, 4, 
   20.87 +		    BSG_TPM_DIGEST, &inParamDigest,
   20.88 +		    BSG_TPM_NONCE, &(auth->NonceEven),
   20.89 +		    BSG_TPM_NONCE, &(auth->NonceOdd), 
   20.90 +		    BSG_TYPE_BOOL, &(auth->fContinueAuthSession) );
   20.91 +    
   20.92 +    Crypto_HMAC((BYTE *) hmacText, sizeof(hmacText), (BYTE *) HMACkey, sizeof(TPM_DIGEST), (BYTE *) &(auth->HMAC));
   20.93 +    
   20.94 +    return(TPM_SUCCESS);
   20.95 +    
   20.96 +  }
   20.97 +}
   20.98 +
   20.99 +/***********************************************************************************
  20.100 + * VerifyAuth: Verify the authdata for a command requiring authorization
  20.101 + *
  20.102 + * Parameters: inParamDigestText  The concatenation of parameters to be SHA1ed
  20.103 + *    inParamDigestTextSize Size of inParamDigestText
  20.104 + *    authDataUsage   AuthDataUsage for the Entity being used
  20.105 + *          Key->authDataUsage or TPM_AUTH_OWNER
  20.106 + *    HMACkey     Key to be used for HMACing
  20.107 + *          For OIAP use key.authUsage or PersistStore.ownerAuth
  20.108 + *          For OSAP use NULL (It will be aquired from the Auth Session)
  20.109 + *          If unknown (default), assume OIAP
  20.110 + *    sessionAuth    A TCS_AUTH info for the session
  20.111 + *    pAuth     Authorization information from the application
  20.112 + *              hContext        If specified, on failed Auth, VerifyAuth will
  20.113 + *                                      generate a new OIAP session in place of themselves
  20.114 + *                                      destroyed session.
  20.115 + *
  20.116 + * Return:  TPM_SUCCESS   Authorization Verified
  20.117 + *    TPM_AUTHFAIL   Authorization Failed
  20.118 + *    TPM_FAIL    Failure during SHA1 routines
  20.119 + *************************************************************************************/
  20.120 +TPM_RESULT VerifyAuth( /*[IN]*/ const BYTE *outParamDigestText,
  20.121 +		       /*[IN]*/ UINT32 outParamDigestTextSize,
  20.122 +		       /*[IN]*/ const TPM_SECRET *HMACkey,  
  20.123 +		       /*[IN,OUT]*/ TCS_AUTH *auth,
  20.124 +		       /*[IN]*/  TCS_CONTEXT_HANDLE hContext) {
  20.125 +  if (outParamDigestText == NULL || auth == NULL) 
  20.126 +    return (TPM_AUTHFAIL);
  20.127 +  
  20.128 +  
  20.129 +  // Create SHA1 inParamDigest
  20.130 +  TPM_DIGEST outParamDigest;
  20.131 +  Crypto_SHA1Full(outParamDigestText, outParamDigestTextSize, (BYTE *) &outParamDigest);
  20.132 +  
  20.133 +  // Create HMAC text. (Concat inParamsDigest with inAuthSetupParams).
  20.134 +  TPM_DIGEST hm;
  20.135 +  BYTE hmacText[sizeof(TPM_DIGEST) + (2 * sizeof(TPM_NONCE)) + sizeof(BOOL)];
  20.136 +  
  20.137 +  BSG_PackList(   hmacText, 4, 
  20.138 +		  BSG_TPM_DIGEST, &outParamDigest,
  20.139 +		  BSG_TPM_NONCE, &(auth->NonceEven),
  20.140 +		  BSG_TPM_NONCE, &(auth->NonceOdd), 
  20.141 +		  BSG_TYPE_BOOL, &(auth->fContinueAuthSession) );
  20.142 +  
  20.143 +  Crypto_HMAC((BYTE *) hmacText, sizeof(hmacText),
  20.144 +	      (BYTE *) HMACkey, sizeof(TPM_DIGEST), (BYTE *) &hm);
  20.145 +    
  20.146 +  // Compare correct HMAC with provided one.
  20.147 +  if (memcmp (&hm, &(auth->HMAC), sizeof(TPM_DIGEST)) == 0)  // 0 indicates equality
  20.148 +    return (TPM_SUCCESS);
  20.149 +  else {
  20.150 +    VTSP_OIAP( hContext, auth);
  20.151 +    return (TPM_AUTHFAIL);
  20.152 +  }
  20.153 +}
  20.154 +
  20.155 +TPM_RESULT VTSP_OIAP(const TCS_CONTEXT_HANDLE hContext,
  20.156 +		     TCS_AUTH *auth) {
  20.157 +  
  20.158 +  vtpmloginfo(VTPM_LOG_VTSP, "OIAP.\n");
  20.159 +  TPM_RESULT status = TPM_SUCCESS;                           
  20.160 +  TPMTRYRETURN( TCSP_OIAP(hContext,
  20.161 +			  &auth->AuthHandle,
  20.162 +			  &auth->NonceEven) );
  20.163 +  goto egress;
  20.164 +  
  20.165 + abort_egress:
  20.166 +  
  20.167 + egress:
  20.168 +  
  20.169 +  return status;
  20.170 +}
  20.171 +
  20.172 +TPM_RESULT VTSP_OSAP(const TCS_CONTEXT_HANDLE hContext,
  20.173 +		     const TPM_ENTITY_TYPE entityType,
  20.174 +		     const UINT32 entityValue,
  20.175 +		     const TPM_AUTHDATA *usageAuth,
  20.176 +		     TPM_SECRET *sharedSecret, 
  20.177 +		     TCS_AUTH *auth) {
  20.178 +  
  20.179 +  vtpmloginfo(VTPM_LOG_VTSP, "OSAP.\n");
  20.180 +  TPM_RESULT status = TPM_SUCCESS;
  20.181 +  TPM_NONCE nonceEvenOSAP, nonceOddOSAP;
  20.182 +  
  20.183 +  Crypto_GetRandom((BYTE *) &nonceOddOSAP, sizeof(TPM_NONCE) ); 
  20.184 +  
  20.185 +  TPMTRYRETURN( TCSP_OSAP(    hContext,
  20.186 +			      TPM_ET_SRK,
  20.187 +			      0, 
  20.188 +			      nonceOddOSAP,
  20.189 +			      &auth->AuthHandle, 
  20.190 +			      &auth->NonceEven, 
  20.191 +			      &nonceEvenOSAP) );
  20.192 +  
  20.193 +  // Calculating Session Secret
  20.194 +  BYTE sharedSecretText[TPM_DIGEST_SIZE * 2];
  20.195 +  
  20.196 +  BSG_PackList(  sharedSecretText, 2,
  20.197 +		 BSG_TPM_NONCE, &nonceEvenOSAP,
  20.198 +		 BSG_TPM_NONCE, &nonceOddOSAP);
  20.199 +  
  20.200 +  Crypto_HMAC(sharedSecretText, sizeof(sharedSecretText), (BYTE *) usageAuth, TPM_DIGEST_SIZE, (BYTE *) sharedSecret);       
  20.201 +    
  20.202 +  goto egress;
  20.203 +  
  20.204 + abort_egress:
  20.205 +  
  20.206 + egress:
  20.207 +  
  20.208 +  return status;
  20.209 +}
  20.210 +
  20.211 +
  20.212 +
  20.213 +TPM_RESULT VTSP_ReadPubek(   const TCS_CONTEXT_HANDLE hContext,
  20.214 +                             CRYPTO_INFO *crypto_info) {
  20.215 +  
  20.216 +  TPM_RESULT status;
  20.217 +  TPM_NONCE antiReplay;
  20.218 +  TPM_DIGEST   checksum;
  20.219 +  BYTE *pubEKtext;
  20.220 +  UINT32 pubEKtextsize;
  20.221 +  
  20.222 +  vtpmloginfo(VTPM_LOG_VTSP, "Reading Public EK.\n");
  20.223 +  
  20.224 +  // GenerateAuth new nonceOdd    
  20.225 +  Crypto_GetRandom(&antiReplay, sizeof(TPM_NONCE) );
  20.226 +  
  20.227 +  
  20.228 +  TPMTRYRETURN( TCSP_ReadPubek(  hContext,
  20.229 +				 antiReplay,
  20.230 +				 &pubEKtextsize,
  20.231 +				 &pubEKtext,
  20.232 +				 &checksum) );
  20.233 +  
  20.234 +  
  20.235 +  // Extract the remaining output parameters
  20.236 +  TPM_PUBKEY pubEK;
  20.237 +  
  20.238 +  BSG_Unpack(BSG_TPM_PUBKEY, pubEKtext, (BYTE *) &pubEK);
  20.239 +  
  20.240 +  // Build CryptoInfo for the bindingKey
  20.241 +  TPM_RSA_KEY_PARMS rsaKeyParms;
  20.242 +  
  20.243 +  BSG_Unpack(BSG_TPM_RSA_KEY_PARMS, 
  20.244 +	     pubEK.algorithmParms.parms, 
  20.245 +	     &rsaKeyParms);
  20.246 +  
  20.247 +  Crypto_RSABuildCryptoInfoPublic(rsaKeyParms.exponentSize, 
  20.248 +				  rsaKeyParms.exponent, 
  20.249 +				  pubEK.pubKey.keyLength, 
  20.250 +				  pubEK.pubKey.key, 
  20.251 +				  crypto_info);
  20.252 +    
  20.253 +  // Destroy rsaKeyParms
  20.254 +  BSG_Destroy(BSG_TPM_RSA_KEY_PARMS, &rsaKeyParms);
  20.255 +
  20.256 +  // Set encryption scheme
  20.257 +  crypto_info->encScheme = CRYPTO_ES_RSAESOAEP_SHA1_MGF1;
  20.258 +  //crypto_info->encScheme = pubEK.algorithmParms.encScheme;
  20.259 +  crypto_info->algorithmID = pubEK.algorithmParms.algorithmID;
  20.260 +  
  20.261 +  goto egress;
  20.262 +  
  20.263 + abort_egress:
  20.264 +  
  20.265 + egress:
  20.266 +  
  20.267 +  return status;
  20.268 +}
  20.269 +
  20.270 +TPM_RESULT VTSP_TakeOwnership(   const TCS_CONTEXT_HANDLE hContext,
  20.271 +                                 const TPM_AUTHDATA *ownerAuth, 
  20.272 +                                 const TPM_AUTHDATA *srkAuth,
  20.273 +                                 CRYPTO_INFO *ek_cryptoInfo,
  20.274 +                                 TCS_AUTH *auth) {
  20.275 +  
  20.276 +  vtpmloginfo(VTPM_LOG_VTSP, "Taking Ownership of TPM.\n");
  20.277 +  
  20.278 +  TPM_RESULT status = TPM_SUCCESS;
  20.279 +  TPM_COMMAND_CODE command = TPM_ORD_TakeOwnership;
  20.280 +  TPM_PROTOCOL_ID proto_id = TPM_PID_OWNER;
  20.281 +  BYTE *new_srk;
  20.282 +  
  20.283 +  BYTE *paramText;        // Digest to make Auth.
  20.284 +  UINT32 paramTextSize;
  20.285 +  
  20.286 +  // vars for srkpubkey parameter
  20.287 +  TPM_KEY srkPub;
  20.288 +  TPM_KEY_PARMS srkKeyInfo = {TPM_ALG_RSA, TPM_ES_RSAESOAEP_SHA1_MGF1, TPM_SS_NONE, 12, 0};
  20.289 +  BYTE srkRSAkeyInfo[12] = { 0x00, 0x00, (RSA_KEY_SIZE >> 8), 0x00,   0x00, 0x00, 0x00, 0x02,   0x00, 0x00, 0x00, 0x00};
  20.290 +  srkKeyInfo.parms = (BYTE *) &srkRSAkeyInfo;
  20.291 +  
  20.292 +  struct pack_buf_t srkText;
  20.293 +  
  20.294 +  // GenerateAuth new nonceOdd    
  20.295 +  Crypto_GetRandom(&auth->NonceOdd, sizeof(TPM_NONCE) );
  20.296 +  
  20.297 +  //These values are accurate for an enc(AuthData).
  20.298 +  struct pack_buf_t encOwnerAuth, encSrkAuth;
  20.299 +  
  20.300 +  encOwnerAuth.data = (BYTE *)malloc(sizeof(BYTE) * 256);
  20.301 +  encSrkAuth.data = (BYTE *)malloc(sizeof(BYTE) * 256);
  20.302 +  
  20.303 +  if (encOwnerAuth.data == NULL || encSrkAuth.data == NULL) {
  20.304 +    vtpmloginfo(VTPM_LOG_VTSP, "Could not malloc encrypted auths.\n");
  20.305 +    status = TPM_RESOURCES;
  20.306 +    goto abort_egress;
  20.307 +  }
  20.308 +  
  20.309 +  Crypto_RSAEnc(ek_cryptoInfo, sizeof(TPM_SECRET), (BYTE *) ownerAuth, &encOwnerAuth.size, encOwnerAuth.data);
  20.310 +  Crypto_RSAEnc(ek_cryptoInfo, sizeof(TPM_SECRET), (BYTE *) srkAuth, &encSrkAuth.size, encSrkAuth.data);
  20.311 +  
  20.312 +  
  20.313 +  // Build srk public key struct
  20.314 +  srkPub.ver = TPM_STRUCT_VER_1_1;
  20.315 +  srkPub.keyUsage = TPM_KEY_STORAGE;
  20.316 +  srkPub.keyFlags = 0x00;
  20.317 +  srkPub.authDataUsage = TPM_AUTH_ALWAYS;
  20.318 +  memcpy(&srkPub.algorithmParms, &srkKeyInfo, sizeof(TPM_KEY_PARMS));
  20.319 +  srkPub.PCRInfoSize = 0;
  20.320 +  srkPub.PCRInfo = 0;
  20.321 +  srkPub.pubKey.keyLength= 0;
  20.322 +  srkPub.encDataSize = 0;
  20.323 +  
  20.324 +  srkText.data = (BYTE *) malloc(sizeof(BYTE) * TCPA_MAX_BUFFER_LENGTH);
  20.325 +  srkText.size = BSG_Pack(BSG_TPM_KEY, (BYTE *) &srkPub, srkText.data);
  20.326 +  
  20.327 +  paramText = (BYTE *) malloc(sizeof(BYTE) *  TCPA_MAX_BUFFER_LENGTH);
  20.328 +  
  20.329 +  paramTextSize = BSG_PackList(paramText, 5,
  20.330 +			       BSG_TPM_COMMAND_CODE,&command,
  20.331 +			       BSG_TPM_PROTOCOL_ID, &proto_id,
  20.332 +			       BSG_TPM_SIZE32_DATA, &encOwnerAuth,
  20.333 +			       BSG_TPM_SIZE32_DATA, &encSrkAuth,
  20.334 +			       BSG_TPM_KEY, &srkPub);
  20.335 +  
  20.336 +  TPMTRYRETURN( GenerateAuth( paramText, paramTextSize, ownerAuth, auth) );
  20.337 +  
  20.338 +  new_srk = srkText.data;
  20.339 +  TPMTRYRETURN( TCSP_TakeOwnership ( hContext,
  20.340 +				     proto_id,
  20.341 +				     encOwnerAuth.size, 
  20.342 +				     encOwnerAuth.data,
  20.343 +				     encSrkAuth.size,
  20.344 +				     encSrkAuth.data,
  20.345 +				     &srkText.size,
  20.346 +				     &new_srk, 
  20.347 +				     auth ) );
  20.348 +  
  20.349 +  
  20.350 +  paramTextSize = BSG_PackList(paramText, 2, 
  20.351 +			       BSG_TPM_RESULT, &status,
  20.352 +			       BSG_TPM_COMMAND_CODE, &command);
  20.353 +  memcpy(paramText + paramTextSize, new_srk, srkText.size);
  20.354 +  paramTextSize += srkText.size;
  20.355 +  
  20.356 +  
  20.357 +  TPMTRYRETURN( VerifyAuth(  paramText, paramTextSize,
  20.358 +			     ownerAuth, auth, 
  20.359 +			     hContext) );
  20.360 +  
  20.361 +  goto egress;
  20.362 +  
  20.363 + abort_egress:
  20.364 +  
  20.365 + egress:
  20.366 +  
  20.367 +  free(srkText.data);
  20.368 +  free(encSrkAuth.data);
  20.369 +  free(encOwnerAuth.data);
  20.370 +  free(paramText);
  20.371 +  
  20.372 +  TCS_FreeMemory(hContext, new_srk);
  20.373 +  
  20.374 +  return status;
  20.375 +}
  20.376 +
  20.377 +TPM_RESULT VTSP_DisablePubekRead( const TCS_CONTEXT_HANDLE    hContext,
  20.378 +                                  const TPM_AUTHDATA          *ownerAuth, 
  20.379 +                                  TCS_AUTH                    *auth) {
  20.380 +  
  20.381 +  vtpmloginfo(VTPM_LOG_VTSP, "Disabling Pubek Read.\n");
  20.382 +  
  20.383 +  TPM_RESULT status = TPM_SUCCESS;
  20.384 +  TPM_COMMAND_CODE command = TPM_ORD_DisablePubekRead;
  20.385 +  
  20.386 +  BYTE *paramText;        // Digest to make Auth.
  20.387 +  UINT32 paramTextSize;
  20.388 +    
  20.389 +  // Generate HMAC   
  20.390 +  Crypto_GetRandom(&auth->NonceOdd, sizeof(TPM_NONCE) );
  20.391 +  
  20.392 +  paramText = (BYTE *) malloc(sizeof(BYTE) * TCPA_MAX_BUFFER_LENGTH);
  20.393 +  
  20.394 +  paramTextSize = BSG_PackList(paramText, 1,
  20.395 +			       BSG_TPM_COMMAND_CODE, &command);
  20.396 +  
  20.397 +  TPMTRYRETURN( GenerateAuth( paramText, paramTextSize,
  20.398 +			      ownerAuth, auth) );
  20.399 +  
  20.400 +  // Call TCS
  20.401 +  TPMTRYRETURN( TCSP_DisablePubekRead ( hContext, // in
  20.402 +                                        auth) );
  20.403 +  
  20.404 +  // Verify Auth
  20.405 +  paramTextSize = BSG_PackList(paramText, 2,
  20.406 +			       BSG_TPM_RESULT, &status,
  20.407 +			       BSG_TPM_COMMAND_CODE, &command);
  20.408 +  
  20.409 +  TPMTRYRETURN( VerifyAuth( paramText, paramTextSize,
  20.410 +			    ownerAuth, auth, 
  20.411 +			    hContext) );
  20.412 +  goto egress;
  20.413 +  
  20.414 + abort_egress:
  20.415 + egress:
  20.416 +  free(paramText);
  20.417 +  return status;
  20.418 +}
  20.419 +
  20.420 +TPM_RESULT VTSP_CreateWrapKey(  const TCS_CONTEXT_HANDLE hContext,
  20.421 +                                const TPM_KEY_USAGE      usage,
  20.422 +                                const TPM_AUTHDATA       *newKeyAuth,
  20.423 +                                const TCS_KEY_HANDLE     parentHandle, 
  20.424 +                                const TPM_AUTHDATA       *osapSharedSecret,
  20.425 +                                buffer_t                 *pubKeyBuf,
  20.426 +                                TCS_AUTH                 *auth) {
  20.427 +  
  20.428 +  int i;
  20.429 +  TPM_RESULT status = TPM_SUCCESS;
  20.430 +  TPM_COMMAND_CODE command = TPM_ORD_CreateWrapKey;
  20.431 +  
  20.432 +  vtpmloginfo(VTPM_LOG_VTSP, "Creating new key of type %d.\n", usage);
  20.433 +  
  20.434 +  // vars for Calculate encUsageAuth
  20.435 +  BYTE *paramText;      
  20.436 +  UINT32 paramTextSize;
  20.437 +  
  20.438 +  // vars for Calculate encUsageAuth
  20.439 +  BYTE XORbuffer[sizeof(TPM_SECRET) + sizeof(TPM_NONCE)];
  20.440 +  TPM_DIGEST XORKey1;
  20.441 +  UINT32 XORbufferSize;
  20.442 +  TPM_SECRET encUsageAuth, encMigrationAuth;
  20.443 +  
  20.444 +  // vars for Flatten newKey prototype
  20.445 +  BYTE *flatKey = (BYTE *) malloc(sizeof(BYTE) *  TCPA_MAX_BUFFER_LENGTH);
  20.446 +  UINT32 flatKeySize = TCPA_MAX_BUFFER_LENGTH;                                    
  20.447 +  struct pack_buf_t newKeyText;
  20.448 +  
  20.449 +  // Fill in newKey
  20.450 +  TPM_KEY newKey;
  20.451 +  
  20.452 +  BYTE RSAkeyInfo[12] = { 0x00, 0x00, (RSA_KEY_SIZE >> 8), 0x00,   0x00, 0x00, 0x00, 0x02,   0x00, 0x00, 0x00, 0x00};
  20.453 +  newKey.algorithmParms.algorithmID = TPM_ALG_RSA;
  20.454 +  newKey.algorithmParms.parms = (BYTE *) &RSAkeyInfo;
  20.455 +  newKey.algorithmParms.parmSize = 12;
  20.456 +  
  20.457 +  switch (usage) {
  20.458 +  case TPM_KEY_SIGNING:
  20.459 +    vtpmloginfo(VTPM_LOG_VTSP, "Creating Signing Key...\n");
  20.460 +    newKey.keyUsage = TPM_KEY_SIGNING;
  20.461 +    newKey.algorithmParms.encScheme = TPM_ES_NONE;
  20.462 +    newKey.algorithmParms.sigScheme = TPM_SS_RSASSAPKCS1v15_SHA1;
  20.463 +    break;
  20.464 +  case TPM_KEY_STORAGE:
  20.465 +    vtpmloginfo(VTPM_LOG_VTSP, "Creating Storage Key...\n");
  20.466 +    newKey.keyUsage = TPM_KEY_STORAGE;
  20.467 +    newKey.algorithmParms.encScheme = TPM_ES_RSAESOAEP_SHA1_MGF1;
  20.468 +    newKey.algorithmParms.sigScheme = TPM_SS_NONE;
  20.469 +    break;
  20.470 +  case TPM_KEY_BIND:
  20.471 +    vtpmloginfo(VTPM_LOG_VTSP, "Creating Binding Key...\n");
  20.472 +    newKey.keyUsage = TPM_KEY_BIND;
  20.473 +    newKey.algorithmParms.encScheme = TPM_ES_RSAESOAEP_SHA1_MGF1;
  20.474 +    newKey.algorithmParms.sigScheme = TPM_SS_NONE;
  20.475 +    break;
  20.476 +  default:
  20.477 +    vtpmloginfo(VTPM_LOG_VTSP, "Cannot create key. Invalid Key Type.\n");
  20.478 +    status = TPM_BAD_PARAMETER;
  20.479 +    goto abort_egress;
  20.480 +  }
  20.481 +  
  20.482 +  
  20.483 +  newKey.ver = TPM_STRUCT_VER_1_1;
  20.484 +  
  20.485 +  newKey.keyFlags = 0;
  20.486 +  newKey.authDataUsage = TPM_AUTH_ALWAYS;
  20.487 +  newKey.pubKey.keyLength= 0;
  20.488 +  newKey.encDataSize = 0;
  20.489 +  newKey.encData = NULL;
  20.490 +  
  20.491 +  // FIXME: Support PCR bindings
  20.492 +  newKey.PCRInfoSize = 0;
  20.493 +  newKey.PCRInfo = NULL;
  20.494 +  
  20.495 +  // Calculate encUsageAuth                                    
  20.496 +  XORbufferSize = BSG_PackList(  XORbuffer, 2, 
  20.497 +				 BSG_TPM_SECRET, osapSharedSecret,
  20.498 +				 BSG_TPM_NONCE, &auth->NonceEven);
  20.499 +  Crypto_SHA1Full(XORbuffer, XORbufferSize, (BYTE *) &XORKey1);
  20.500 +  
  20.501 +  // FIXME: No support for migratable keys.
  20.502 +  for (i=0; i < TPM_DIGEST_SIZE; i++) 
  20.503 +    ((BYTE *) &encUsageAuth)[i] = ((BYTE *) &XORKey1)[i] ^ ((BYTE *) newKeyAuth)[i];
  20.504 +  
  20.505 +  // Flatten newKey prototype
  20.506 +  flatKeySize = BSG_Pack(BSG_TPM_KEY, (BYTE *) &newKey, flatKey);
  20.507 +  newKeyText.data = flatKey;
  20.508 +  newKeyText.size = flatKeySize;
  20.509 +  
  20.510 +  // GenerateAuth new nonceOdd    
  20.511 +  Crypto_GetRandom(&auth->NonceOdd, sizeof(TPM_NONCE) );
  20.512 +  
  20.513 +  // Generate HMAC
  20.514 +  paramText = (BYTE *) malloc(sizeof(BYTE) * TCPA_MAX_BUFFER_LENGTH);
  20.515 +  
  20.516 +  paramTextSize = BSG_PackList(paramText, 3,
  20.517 +			       BSG_TPM_COMMAND_CODE, &command,
  20.518 +			       BSG_TPM_AUTHDATA, &encUsageAuth,
  20.519 +			       BSG_TPM_AUTHDATA, &encMigrationAuth);
  20.520 +  memcpy(paramText + paramTextSize, newKeyText.data, newKeyText.size);
  20.521 +  paramTextSize += newKeyText.size;
  20.522 +  
  20.523 +  
  20.524 +  TPMTRYRETURN( GenerateAuth( paramText, paramTextSize,
  20.525 +			      osapSharedSecret, auth) );
  20.526 +  
  20.527 +  // Call TCS
  20.528 +  TPMTRYRETURN( TCSP_CreateWrapKey(  hContext, 
  20.529 +				     parentHandle,
  20.530 +				     encUsageAuth,
  20.531 +				     encMigrationAuth,
  20.532 +				     &newKeyText.size,
  20.533 +				     &newKeyText.data,
  20.534 +				     auth) );
  20.535 +  
  20.536 +  // Verify Auth
  20.537 +  paramTextSize = BSG_PackList(paramText, 2,
  20.538 +			       BSG_TPM_RESULT, &status,
  20.539 +			       BSG_TPM_COMMAND_CODE, &command);
  20.540 +  memcpy(paramText + paramTextSize, newKeyText.data, newKeyText.size);
  20.541 +  paramTextSize += newKeyText.size;
  20.542 +  
  20.543 +  TPMTRYRETURN( VerifyAuth( paramText, paramTextSize,
  20.544 +			    osapSharedSecret, auth, 0) );
  20.545 +  
  20.546 +  // Unpack/return key structure
  20.547 +  TPMTRYRETURN(buffer_init(pubKeyBuf, 0, 0) );
  20.548 +  TPMTRYRETURN(buffer_append_raw(pubKeyBuf, newKeyText.size, newKeyText.data) );
  20.549 +  
  20.550 +  goto egress;
  20.551 +  
  20.552 + abort_egress:
  20.553 +  
  20.554 + egress:
  20.555 +  
  20.556 +  free(flatKey);
  20.557 +  free(paramText);
  20.558 +  TCS_FreeMemory(hContext, newKeyText.data);
  20.559 +  
  20.560 +  return status;
  20.561 +}
  20.562 +
  20.563 +TPM_RESULT VTSP_LoadKey(const TCS_CONTEXT_HANDLE    hContext,
  20.564 +                        const TCS_KEY_HANDLE        hUnwrappingKey,
  20.565 +                        const buffer_t              *rgbWrappedKeyBlob,
  20.566 +                        const TPM_AUTHDATA          *parentAuth,
  20.567 +                        TPM_HANDLE                  *newKeyHandle,
  20.568 +                        TCS_AUTH                    *auth,
  20.569 +                        CRYPTO_INFO                 *cryptoinfo /*= NULL*/) {
  20.570 +  
  20.571 +  
  20.572 +  vtpmloginfo(VTPM_LOG_VTSP, "Loading Key.\n%s","");
  20.573 +  
  20.574 +  TPM_RESULT status = TPM_SUCCESS;
  20.575 +  TPM_COMMAND_CODE command = TPM_ORD_LoadKey;
  20.576 +  
  20.577 +  BYTE *paramText;        // Digest to make Auth.
  20.578 +  UINT32 paramTextSize;
  20.579 +  
  20.580 +  if ((rgbWrappedKeyBlob == NULL) || (parentAuth == NULL) || 
  20.581 +      (newKeyHandle==NULL) || (auth==NULL)) {
  20.582 +    status = TPM_BAD_PARAMETER;
  20.583 +    goto abort_egress;
  20.584 +  }
  20.585 +  
  20.586 +  // Generate Extra TCS Parameters
  20.587 +  TPM_HANDLE phKeyHMAC;
  20.588 +  
  20.589 +  // Generate HMAC
  20.590 +  Crypto_GetRandom(&auth->NonceOdd, sizeof(TPM_NONCE) );
  20.591 +  
  20.592 +  paramText = (BYTE *) malloc(sizeof(BYTE) *  TCPA_MAX_BUFFER_LENGTH);
  20.593 +  
  20.594 +  paramTextSize = BSG_PackList(paramText, 1,
  20.595 +			       BSG_TPM_COMMAND_CODE, &command);
  20.596 +  
  20.597 +  memcpy(paramText + paramTextSize, rgbWrappedKeyBlob->bytes, buffer_len(rgbWrappedKeyBlob));
  20.598 +  paramTextSize += buffer_len(rgbWrappedKeyBlob);
  20.599 +  
  20.600 +  TPMTRYRETURN( GenerateAuth( paramText, paramTextSize,
  20.601 +			      parentAuth, auth) );
  20.602 +  
  20.603 +  // Call TCS
  20.604 +  TPMTRYRETURN( TCSP_LoadKeyByBlob(  hContext,
  20.605 +				     hUnwrappingKey,
  20.606 +				     buffer_len(rgbWrappedKeyBlob),
  20.607 +				     rgbWrappedKeyBlob->bytes,
  20.608 +				     auth,
  20.609 +				     newKeyHandle,
  20.610 +				     &phKeyHMAC) );
  20.611 +  
  20.612 +  // Verify Auth
  20.613 +  paramTextSize = BSG_PackList(paramText, 3,
  20.614 +			       BSG_TPM_RESULT, &status,
  20.615 +			       BSG_TPM_COMMAND_CODE, &command,
  20.616 +			       BSG_TPM_HANDLE, newKeyHandle);
  20.617 +  
  20.618 +  TPMTRYRETURN( VerifyAuth( paramText, paramTextSize,
  20.619 +			    parentAuth, auth, 
  20.620 +			    hContext) );
  20.621 +  
  20.622 +  // Unpack/return key structure
  20.623 +  if (cryptoinfo != NULL) {
  20.624 +    TPM_KEY newKey;
  20.625 +    
  20.626 +    BSG_Unpack(BSG_TPM_KEY, rgbWrappedKeyBlob->bytes , &newKey);
  20.627 +    TPM_RSA_KEY_PARMS rsaKeyParms;
  20.628 +    
  20.629 +    BSG_Unpack(BSG_TPM_RSA_KEY_PARMS, 
  20.630 +	       newKey.algorithmParms.parms, 
  20.631 +	       &rsaKeyParms);
  20.632 +    
  20.633 +    Crypto_RSABuildCryptoInfoPublic(rsaKeyParms.exponentSize, 
  20.634 +				    rsaKeyParms.exponent, 
  20.635 +				    newKey.pubKey.keyLength, 
  20.636 +				    newKey.pubKey.key, 
  20.637 +				    cryptoinfo);
  20.638 +    
  20.639 +    // Destroy rsaKeyParms
  20.640 +    BSG_Destroy(BSG_TPM_RSA_KEY_PARMS, &rsaKeyParms);
  20.641 +    
  20.642 +    // Set encryption scheme
  20.643 +    cryptoinfo->encScheme = CRYPTO_ES_RSAESOAEP_SHA1_MGF1;
  20.644 +  }
  20.645 +  
  20.646 +  goto egress;
  20.647 +  
  20.648 + abort_egress:
  20.649 +  
  20.650 + egress:
  20.651 +  
  20.652 +  free(paramText);
  20.653 +  return status;
  20.654 +}
  20.655 +
  20.656 +TPM_RESULT VTSP_Unbind( const TCS_CONTEXT_HANDLE    hContext,
  20.657 +                        const TPM_KEY_HANDLE        key_handle,
  20.658 +                        const buffer_t              *bound_data,
  20.659 +                        const TPM_AUTHDATA          *usage_auth,
  20.660 +                        buffer_t                    *clear_data,
  20.661 +                        TCS_AUTH                    *auth) {
  20.662 +  
  20.663 +  vtpmloginfo(VTPM_LOG_VTSP, "Unbinding %d bytes of data.\n", buffer_len(bound_data));
  20.664 +  
  20.665 +  TPM_RESULT status = TPM_SUCCESS;
  20.666 +  TPM_COMMAND_CODE command = TPM_ORD_UnBind;
  20.667 +  
  20.668 +  BYTE *paramText;        // Digest to make Auth.
  20.669 +  UINT32 paramTextSize;
  20.670 +  
  20.671 +  // Generate Extra TCS Parameters
  20.672 +  struct pack_buf_t clear_data32;
  20.673 +  BYTE *clear_data_text;
  20.674 +  UINT32 clear_data_size;
  20.675 +  
  20.676 +  // Generate HMAC   
  20.677 +  Crypto_GetRandom(&auth->NonceOdd, sizeof(TPM_NONCE) );
  20.678 +  
  20.679 +  struct pack_buf_t bound_data32 = {bound_data->size, bound_data->bytes};
  20.680 +  
  20.681 +  paramText = (BYTE *) malloc(sizeof(BYTE) * TCPA_MAX_BUFFER_LENGTH);
  20.682 +  
  20.683 +  paramTextSize = BSG_PackList(paramText, 2,
  20.684 +			       BSG_TPM_COMMAND_CODE, &command,
  20.685 +			       BSG_TPM_SIZE32_DATA, &bound_data32);
  20.686 +  
  20.687 +  TPMTRYRETURN( GenerateAuth( paramText, paramTextSize,
  20.688 +			      usage_auth, auth) );
  20.689 +  
  20.690 +  // Call TCS
  20.691 +  TPMTRYRETURN( TCSP_UnBind( hContext,
  20.692 +			     key_handle,
  20.693 +			     buffer_len(bound_data),
  20.694 +			     bound_data->bytes,
  20.695 +			     auth,
  20.696 +			     &clear_data_size,
  20.697 +			     &clear_data_text) );
  20.698 +  
  20.699 +  
  20.700 +  // Verify Auth
  20.701 +  clear_data32.size = clear_data_size;
  20.702 +  clear_data32.data = clear_data_text;
  20.703 +  paramTextSize = BSG_PackList(paramText, 3,
  20.704 +			       BSG_TPM_RESULT, &status,
  20.705 +			       BSG_TPM_COMMAND_CODE, &command,
  20.706 +			       BSG_TPM_SIZE32_DATA, &clear_data32);
  20.707 +  
  20.708 +  TPMTRYRETURN( VerifyAuth( paramText, paramTextSize,
  20.709 +			    usage_auth, auth, 
  20.710 +			    hContext) );
  20.711 +  
  20.712 +  // Unpack/return key structure
  20.713 +  TPMTRYRETURN(buffer_init(clear_data, 0, 0));
  20.714 +  TPMTRYRETURN(buffer_append_raw (clear_data, clear_data_size, clear_data_text) );
  20.715 +  
  20.716 +  goto egress;
  20.717 +  
  20.718 + abort_egress:
  20.719 +  
  20.720 + egress:
  20.721 +  
  20.722 +  free(paramText);
  20.723 +  TCS_FreeMemory(hContext, clear_data_text);
  20.724 +  
  20.725 +  return status;
  20.726 +}
  20.727 +
  20.728 +TPM_RESULT VTSP_Bind(   CRYPTO_INFO *cryptoInfo, 
  20.729 +			const buffer_t *inData, 
  20.730 +			buffer_t *outData)               
  20.731 +{
  20.732 +  vtpmloginfo(VTPM_LOG_VTSP, "Binding %d bytes of data.\n", buffer_len(inData));
  20.733 +  TPM_BOUND_DATA boundData;
  20.734 +  UINT32 i;
  20.735 +  
  20.736 +  // Fill boundData's accessory information
  20.737 +  boundData.ver = TPM_STRUCT_VER_1_1;
  20.738 +  boundData.payload = TPM_PT_BIND;
  20.739 +  boundData.payloadData = inData->bytes;
  20.740 +  
  20.741 +  // Pack boundData before encryption
  20.742 +  BYTE* flatBoundData = (BYTE *)malloc(sizeof(BYTE) * 
  20.743 +				       (sizeof(TPM_VERSION) +
  20.744 +					sizeof(TPM_PAYLOAD_TYPE) +
  20.745 +					buffer_len(inData)));
  20.746 +  if (flatBoundData == NULL) {
  20.747 +    return TPM_NOSPACE;
  20.748 +  }
  20.749 +  UINT32 flatBoundDataSize = 0;
  20.750 +  flatBoundDataSize = BSG_PackList(  flatBoundData, 2, 
  20.751 +				     BSG_TPM_VERSION, &boundData.ver, 
  20.752 +				     BSG_TYPE_BYTE, &boundData.payload);
  20.753 +  
  20.754 +  memcpy(flatBoundData+flatBoundDataSize, inData->bytes, buffer_len(inData));
  20.755 +  flatBoundDataSize += buffer_len(inData);
  20.756 +  
  20.757 +  BYTE out_tmp[RSA_KEY_SIZE/8]; // RSAEnc does not do blocking, So this is what will come out.
  20.758 +  UINT32 out_tmp_size;
  20.759 +  
  20.760 +  // Encrypt flatBoundData
  20.761 +  Crypto_RSAEnc( cryptoInfo, 
  20.762 +		 flatBoundDataSize, 
  20.763 +		 flatBoundData, 
  20.764 +		 &out_tmp_size, 
  20.765 +		 out_tmp);
  20.766 +  
  20.767 +  if (out_tmp_size > RSA_KEY_SIZE/8) {
  20.768 +    // The result of RSAEnc should be a fixed size based on key size.
  20.769 +    vtpmlogerror(VTPM_LOG_VTSP, "Enc buffer just overflowed.\n");
  20.770 +  }
  20.771 +  
  20.772 +  buffer_init(outData, 0, NULL);
  20.773 +  buffer_append_raw(outData, out_tmp_size, out_tmp);
  20.774 +  
  20.775 +  vtpmloginfo(VTPM_LOG_TXDATA, "Bind Generated[%d] = 0x", out_tmp_size);
  20.776 +  for(i = 0 ; i < out_tmp_size ; i++) {
  20.777 +    vtpmloginfomore(VTPM_LOG_TXDATA, "%2.2x ", out_tmp[i]);
  20.778 +  }
  20.779 +  vtpmloginfomore(VTPM_LOG_TXDATA, "\n");
  20.780 +  
  20.781 +  // Free flatBoundData
  20.782 +  free(flatBoundData);
  20.783 +  
  20.784 +  return TPM_SUCCESS;
  20.785 +}
  20.786 +
  20.787 +// Function Reaches into unsupported TCS command, beware.
  20.788 +TPM_RESULT VTSP_RawTransmit(const TCS_CONTEXT_HANDLE    hContext,
  20.789 +                            const buffer_t *inbuf,
  20.790 +                            buffer_t *outbuf ) {
  20.791 +  
  20.792 +  vtpmloginfo(VTPM_LOG_VTSP, "Passthrough in use.\n");
  20.793 +  TPM_RESULT status = TPM_SUCCESS;
  20.794 +  
  20.795 +  // Generate Extra TCS Parameters
  20.796 +  BYTE *resultText = (BYTE *) malloc(sizeof(BYTE) * TCPA_MAX_BUFFER_LENGTH);
  20.797 +  UINT32 resultTextSize =  TCPA_MAX_BUFFER_LENGTH;
  20.798 +  
  20.799 +  // Call TCS                          
  20.800 +  TPMTRYRETURN( TCSP_RawTransmitData(buffer_len(inbuf), inbuf->bytes, 
  20.801 +				     &resultTextSize, resultText) );
  20.802 +  
  20.803 +  // Unpack/return key structure
  20.804 +  TPMTRYRETURN(buffer_init (outbuf, resultTextSize, resultText) );                                
  20.805 +  goto egress;
  20.806 +  
  20.807 + abort_egress:
  20.808 +  
  20.809 + egress:
  20.810 +  TCS_FreeMemory(hContext, resultText);
  20.811 +  free(resultText);
  20.812 +  return status;
  20.813 +}
    21.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    21.2 +++ b/tools/vtpm_manager/manager/vtsp.h	Tue Aug 30 11:39:25 2005 -0800
    21.3 @@ -0,0 +1,102 @@
    21.4 +// ===================================================================
    21.5 +// 
    21.6 +// Copyright (c) 2005, Intel Corp.
    21.7 +// All rights reserved.
    21.8 +//
    21.9 +// Redistribution and use in source and binary forms, with or without 
   21.10 +// modification, are permitted provided that the following conditions 
   21.11 +// are met:
   21.12 +//
   21.13 +//   * Redistributions of source code must retain the above copyright 
   21.14 +//     notice, this list of conditions and the following disclaimer.
   21.15 +//   * Redistributions in binary form must reproduce the above 
   21.16 +//     copyright notice, this list of conditions and the following 
   21.17 +//     disclaimer in the documentation and/or other materials provided 
   21.18 +//     with the distribution.
   21.19 +//   * Neither the name of Intel Corporation nor the names of its 
   21.20 +//     contributors may be used to endorse or promote products derived
   21.21 +//     from this software without specific prior written permission.
   21.22 +//
   21.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   21.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   21.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   21.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   21.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   21.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   21.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   21.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   21.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   21.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   21.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   21.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   21.35 +// ===================================================================
   21.36 +// 
   21.37 +// vtsp.h
   21.38 +// 
   21.39 +//  Higher level interface to TCS.
   21.40 +//
   21.41 +// ==================================================================
   21.42 +
   21.43 +#ifndef __VTSP_H__
   21.44 +#define __VTSP_H__
   21.45 +
   21.46 +#include "tcg.h"
   21.47 +#include "tcs.h"
   21.48 +
   21.49 +#define KEY_BUFFER_SIZE 2048
   21.50 +
   21.51 +TPM_RESULT VTSP_RawTransmit(const TCS_CONTEXT_HANDLE    hContext,
   21.52 +                            const buffer_t *inbuf,
   21.53 +                            buffer_t *outbuf );
   21.54 +
   21.55 +TPM_RESULT VTSP_OIAP(  const TCS_CONTEXT_HANDLE hContext,
   21.56 +                       TCS_AUTH *auth);
   21.57 +                       
   21.58 +TPM_RESULT VTSP_OSAP(  const TCS_CONTEXT_HANDLE hContext,
   21.59 +                       const TPM_ENTITY_TYPE entityType,
   21.60 +                       const UINT32 entityValue,
   21.61 +                       const TPM_AUTHDATA *usageAuth,
   21.62 +                       TPM_SECRET *sharedsecret, 
   21.63 +                       TCS_AUTH *auth);
   21.64 +
   21.65 +TPM_RESULT VTSP_ReadPubek(   const TCS_CONTEXT_HANDLE hContext,
   21.66 +                             CRYPTO_INFO *cypto_info);
   21.67 +
   21.68 +TPM_RESULT VTSP_TakeOwnership(   const TCS_CONTEXT_HANDLE hContext,
   21.69 +                                 const TPM_AUTHDATA *ownerAuth, 
   21.70 +                                 const TPM_AUTHDATA *srkAuth,
   21.71 +                                 CRYPTO_INFO *ek_cryptoInfo,
   21.72 +                                 TCS_AUTH *auth);
   21.73 +                               
   21.74 +TPM_RESULT VTSP_DisablePubekRead( const TCS_CONTEXT_HANDLE    hContext,
   21.75 +                                  const TPM_AUTHDATA *ownerAuth, 
   21.76 +                                  TCS_AUTH                    *auth);
   21.77 +                               
   21.78 +TPM_RESULT VTSP_CreateWrapKey(  const TCS_CONTEXT_HANDLE hContext,
   21.79 +                                const TPM_KEY_USAGE      usage,
   21.80 +                                const TPM_AUTHDATA       *newKeyAuth,
   21.81 +                                const TCS_KEY_HANDLE     parentHandle, 
   21.82 +                                const TPM_AUTHDATA       *osapSharedSecret,
   21.83 +                                buffer_t                 *pubKeyBuf,
   21.84 +                                TCS_AUTH                 *auth);
   21.85 +
   21.86 +TPM_RESULT VTSP_LoadKey(const TCS_CONTEXT_HANDLE    hContext,
   21.87 +                        const TCS_KEY_HANDLE        hUnwrappingKey,
   21.88 +                        const buffer_t              *rgbWrappedKeyBlob,
   21.89 +                        const TPM_AUTHDATA          *parentAuth,
   21.90 +                        TPM_HANDLE                  *newKeyHandle,
   21.91 +                        TCS_AUTH                    *pAuth,
   21.92 +                        CRYPTO_INFO                 *cryptoinfo);
   21.93 +
   21.94 +TPM_RESULT VTSP_Unbind( const TCS_CONTEXT_HANDLE    hContext,
   21.95 +                        const TPM_KEY_HANDLE        key_handle,
   21.96 +                        const buffer_t              *bound_data,
   21.97 +                        const TPM_AUTHDATA          *usage_auth,
   21.98 +                        buffer_t                    *clear_data,
   21.99 +                        TCS_AUTH                    *auth);
  21.100 +                        
  21.101 +TPM_RESULT VTSP_Bind(   CRYPTO_INFO *cryptoInfo,
  21.102 +            const buffer_t *inData, 
  21.103 +            buffer_t *outData);
  21.104 +                        
  21.105 +#endif //_VTSP_H_
    22.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    22.2 +++ b/tools/vtpm_manager/tcs/Makefile	Tue Aug 30 11:39:25 2005 -0800
    22.3 @@ -0,0 +1,18 @@
    22.4 +XEN_ROOT = ../../..
    22.5 +include $(XEN_ROOT)/tools/vtpm_manager/Rules.mk
    22.6 +
    22.7 +BIN		= libTCS.a
    22.8 +
    22.9 +all: build
   22.10 +
   22.11 +build: $(BIN)
   22.12 +
   22.13 +install: build
   22.14 +
   22.15 +clean:
   22.16 +	rm -f *.a *.so *.o *.rpm $(DEP_FILES)
   22.17 +
   22.18 +mrproper: clean
   22.19 +
   22.20 +$(BIN): $(OBJS)
   22.21 +	$(AR) rcs $(BIN) $(OBJS)
    23.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    23.2 +++ b/tools/vtpm_manager/tcs/contextmgr.c	Tue Aug 30 11:39:25 2005 -0800
    23.3 @@ -0,0 +1,219 @@
    23.4 +// ===================================================================
    23.5 +// 
    23.6 +// Copyright (c) 2005, Intel Corp.
    23.7 +// All rights reserved.
    23.8 +//
    23.9 +// Redistribution and use in source and binary forms, with or without 
   23.10 +// modification, are permitted provided that the following conditions 
   23.11 +// are met:
   23.12 +//
   23.13 +//   * Redistributions of source code must retain the above copyright 
   23.14 +//     notice, this list of conditions and the following disclaimer.
   23.15 +//   * Redistributions in binary form must reproduce the above 
   23.16 +//     copyright notice, this list of conditions and the following 
   23.17 +//     disclaimer in the documentation and/or other materials provided 
   23.18 +//     with the distribution.
   23.19 +//   * Neither the name of Intel Corporation nor the names of its 
   23.20 +//     contributors may be used to endorse or promote products derived
   23.21 +//     from this software without specific prior written permission.
   23.22 +//
   23.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   23.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   23.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   23.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   23.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   23.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   23.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   23.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   23.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   23.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   23.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   23.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   23.35 +// ===================================================================
   23.36 +// 
   23.37 +// contextmgr.c
   23.38 +// 
   23.39 +//  This file contains the context management functions for TCS.
   23.40 +// 
   23.41 +// ==================================================================
   23.42 +
   23.43 +#include <stdio.h>
   23.44 +#include <string.h>
   23.45 +#include <malloc.h>
   23.46 +#include "tcs.h"
   23.47 +#include "contextmgr.h"
   23.48 +#include "log.h"
   23.49 +
   23.50 +BYTE* AddMemBlock(CONTEXT_HANDLE* pContextHandle, // in
   23.51 +		  int    BlockSize)  { // in
   23.52 +  
   23.53 +  BLOCK* pCurrentBlock = NULL;
   23.54 +  BLOCK* pBlock = NULL;
   23.55 +                    
   23.56 +  // check incoming params
   23.57 +  if (pContextHandle == NULL || BlockSize == 0)
   23.58 +    return NULL;
   23.59 +
   23.60 +  // Create New Block
   23.61 +  pBlock = (BLOCK *)malloc(sizeof(BLOCK));
   23.62 +  if (pBlock == NULL)
   23.63 +    return (0);
   23.64 +
   23.65 +  pBlock->aMemory = (BYTE *)malloc(sizeof(BYTE) * BlockSize);
   23.66 +  if (pBlock->aMemory == NULL)
   23.67 +    return (0);
   23.68 +
   23.69 +  memset(pBlock->aMemory, 0, BlockSize);
   23.70 +  pBlock->nBlockSize = BlockSize;
   23.71 +  pBlock->pNextBlock = NULL;
   23.72 +  
   23.73 +  // search for the last block created where to add the 
   23.74 +  // newly created block
   23.75 +  if(pContextHandle->pTopBlock != NULL) {
   23.76 +    pCurrentBlock = pContextHandle->pTopBlock;
   23.77 +    while(pCurrentBlock->pNextBlock != NULL)
   23.78 +      pCurrentBlock = pCurrentBlock->pNextBlock;
   23.79 +    
   23.80 +    
   23.81 +    pCurrentBlock->pNextBlock= pBlock;
   23.82 +  } else
   23.83 +    pContextHandle->pTopBlock = pBlock;
   23.84 +  
   23.85 +  
   23.86 +  pContextHandle->nBlockCount++;
   23.87 +  
   23.88 +  return pBlock->aMemory;
   23.89 +}
   23.90 +
   23.91 +
   23.92 +BOOL DeleteMemBlock(CONTEXT_HANDLE* pContextHandle, // in
   23.93 +                    BYTE*   pTCPA_BYTEs) { // in
   23.94 +  BLOCK* pCurrentBlock = NULL;
   23.95 +  BLOCK* pParentBlock = NULL;
   23.96 +  BOOL bFound = FALSE;
   23.97 +  
   23.98 +  if (pContextHandle == NULL) 
   23.99 +    return FALSE;
  23.100 +
  23.101 +  
  23.102 +  // Search for the Block in the context by aMemory pointer
  23.103 +  pParentBlock = NULL;
  23.104 +  pCurrentBlock = pContextHandle->pTopBlock;
  23.105 +  
  23.106 +  while(pCurrentBlock != NULL) {
  23.107 +    // If aMemory block is found, delete it 
  23.108 +    if(pCurrentBlock->aMemory == pTCPA_BYTEs || pTCPA_BYTEs == NULL) {
  23.109 +      // if it is the top Block, remove it from the top, 
  23.110 +      // otherwise remove it from the ParentBlock and stitch 
  23.111 +      // the NextBlock to the ParentBlock
  23.112 +      if(pParentBlock == NULL)
  23.113 +	pContextHandle->pTopBlock = pContextHandle->pTopBlock->pNextBlock;
  23.114 +      else
  23.115 +	pParentBlock->pNextBlock = pCurrentBlock->pNextBlock;
  23.116 +      
  23.117 +      // delete memory Block associated with pointer pTCPA_BYTEs
  23.118 +      free(pCurrentBlock->aMemory);
  23.119 +      pCurrentBlock->aMemory = NULL;
  23.120 +      
  23.121 +      free(pCurrentBlock);
  23.122 +      pCurrentBlock = pParentBlock;
  23.123 +      
  23.124 +      pContextHandle->nBlockCount--;
  23.125 +      bFound = TRUE;
  23.126 +    }
  23.127 +  
  23.128 +    if(pCurrentBlock != NULL) {
  23.129 +      pParentBlock = pCurrentBlock;
  23.130 +      pCurrentBlock = pCurrentBlock->pNextBlock;
  23.131 +    }
  23.132 +  }
  23.133 +  
  23.134 +  return bFound;
  23.135 +}
  23.136 +
  23.137 +BOOL AddHandleToList(CONTEXT_HANDLE* pContextHandle, // in
  23.138 +		     TPM_RESOURCE_TYPE type, // in
  23.139 +		     TPM_HANDLE    handle)  { // in
  23.140 +  HANDLE_LIST* pNewHandle = NULL;
  23.141 +  
  23.142 +  vtpmloginfo(VTPM_LOG_TCS_DEEP, "Adding Handle to list\n");
  23.143 +  if (pContextHandle == NULL)
  23.144 +    return 0;
  23.145 +  
  23.146 +  pNewHandle = (HANDLE_LIST *)malloc(sizeof(HANDLE_LIST));
  23.147 +  
  23.148 +  if (pNewHandle == NULL) 
  23.149 +    return (0);
  23.150 +  
  23.151 +  pNewHandle->handle = handle;
  23.152 +  pNewHandle->type = type;
  23.153 +  pNewHandle->pNextHandle = pContextHandle->pHandleList;
  23.154 +  
  23.155 +  pContextHandle->pHandleList = pNewHandle;
  23.156 +  
  23.157 +  return 1;
  23.158 +}
  23.159 +
  23.160 +BOOL DeleteHandleFromList(   CONTEXT_HANDLE*     pContextHandle, // in
  23.161 +                             TPM_HANDLE          handle) { // in
  23.162 +    
  23.163 +  HANDLE_LIST *pCurrentHandle = pContextHandle->pHandleList, 
  23.164 +    *pLastHandle = pCurrentHandle;
  23.165 +  
  23.166 +  vtpmloginfo(VTPM_LOG_TCS_DEEP, "Deleting Handle from list\n");
  23.167 +  
  23.168 +  if (pContextHandle == NULL)
  23.169 +    return 0;
  23.170 +  
  23.171 +  while (1) {
  23.172 +    
  23.173 +    if (pCurrentHandle->handle == handle) { // Found element
  23.174 +      if (pCurrentHandle == pLastHandle) { // First element in list 
  23.175 +	pContextHandle->pHandleList = pCurrentHandle->pNextHandle;
  23.176 +	free(pCurrentHandle);
  23.177 +      } else { // Ordinary element
  23.178 +	pLastHandle->pNextHandle = pCurrentHandle->pNextHandle;
  23.179 +	free(pCurrentHandle);
  23.180 +      }
  23.181 +      
  23.182 +      return 1;
  23.183 +      
  23.184 +    } else { // Not found yet;
  23.185 +      pLastHandle = pCurrentHandle;
  23.186 +      pCurrentHandle = pCurrentHandle->pNextHandle;
  23.187 +      if (pCurrentHandle == NULL) // Found end of list
  23.188 +	return 0;
  23.189 +    }
  23.190 +    
  23.191 +  }
  23.192 +}
  23.193 +
  23.194 +BOOL FreeHandleList(    CONTEXT_HANDLE*     pContextHandle) { // in
  23.195 +  HANDLE_LIST* pCurrentHandle;
  23.196 +  BOOL returncode = TRUE;
  23.197 +  
  23.198 +  vtpmloginfo(VTPM_LOG_TCS_DEEP, "Freeing all handles for context\n");
  23.199 +  
  23.200 +  if (pContextHandle == NULL)
  23.201 +    return 1;
  23.202 +  
  23.203 +  pCurrentHandle = pContextHandle->pHandleList;
  23.204 +  while (pCurrentHandle != NULL) {
  23.205 +    
  23.206 +    switch (pCurrentHandle->type) {
  23.207 +    case TPM_RT_KEY:
  23.208 +      returncode = returncode && !TCSP_EvictKey((TCS_CONTEXT_HANDLE) pContextHandle, pCurrentHandle->handle);
  23.209 +      break;
  23.210 +    case TPM_RT_AUTH:
  23.211 +      returncode = returncode && !TCSP_TerminateHandle((TCS_CONTEXT_HANDLE) pContextHandle, pCurrentHandle->handle);
  23.212 +      break;
  23.213 +    default:
  23.214 +      returncode = FALSE;
  23.215 +    }
  23.216 +    
  23.217 +    pCurrentHandle = pCurrentHandle->pNextHandle;
  23.218 +    
  23.219 +  }
  23.220 +  
  23.221 +  return 1;
  23.222 +}
    24.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    24.2 +++ b/tools/vtpm_manager/tcs/contextmgr.h	Tue Aug 30 11:39:25 2005 -0800
    24.3 @@ -0,0 +1,81 @@
    24.4 +// ===================================================================
    24.5 +// 
    24.6 +// Copyright (c) 2005, Intel Corp.
    24.7 +// All rights reserved.
    24.8 +//
    24.9 +// Redistribution and use in source and binary forms, with or without 
   24.10 +// modification, are permitted provided that the following conditions 
   24.11 +// are met:
   24.12 +//
   24.13 +//   * Redistributions of source code must retain the above copyright 
   24.14 +//     notice, this list of conditions and the following disclaimer.
   24.15 +//   * Redistributions in binary form must reproduce the above 
   24.16 +//     copyright notice, this list of conditions and the following 
   24.17 +//     disclaimer in the documentation and/or other materials provided 
   24.18 +//     with the distribution.
   24.19 +//   * Neither the name of Intel Corporation nor the names of its 
   24.20 +//     contributors may be used to endorse or promote products derived
   24.21 +//     from this software without specific prior written permission.
   24.22 +//
   24.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   24.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   24.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   24.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   24.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   24.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   24.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   24.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   24.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   24.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   24.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   24.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   24.35 +// ===================================================================
   24.36 +// 
   24.37 +// contextmgr.c
   24.38 +// 
   24.39 +//  This file contains the context management functions for TCS.
   24.40 +// 
   24.41 +// ==================================================================
   24.42 +
   24.43 +#ifndef __CONTEXTMGR_H__
   24.44 +#define __CONTEXTMGR_H__
   24.45 +
   24.46 +#include "tcg.h"
   24.47 +
   24.48 +#define BLOCK_SIZE 300
   24.49 +
   24.50 +typedef struct block {
   24.51 +  int nBlockSize;
   24.52 +  BYTE* aMemory;
   24.53 +  struct block* pNextBlock;
   24.54 +} BLOCK;
   24.55 +
   24.56 +typedef struct handle_List {
   24.57 +  TPM_HANDLE handle;
   24.58 +  TPM_RESOURCE_TYPE type;
   24.59 +  struct handle_List* pNextHandle;
   24.60 +} HANDLE_LIST;
   24.61 +
   24.62 +typedef struct context_handle {
   24.63 +  int nBlockCount;
   24.64 +  BLOCK* pTopBlock;
   24.65 +  HANDLE_LIST* pHandleList;
   24.66 +} CONTEXT_HANDLE;
   24.67 +
   24.68 +BYTE* AddMemBlock(  CONTEXT_HANDLE*     pContextHandle, // in
   24.69 +                    int                 BlockSize);  // in
   24.70 +
   24.71 +BOOL DeleteMemBlock(CONTEXT_HANDLE* pContextHandle, // in
   24.72 +                    BYTE*           pTCPA_BYTEs); // in
   24.73 +
   24.74 +
   24.75 +BOOL AddHandleToList(   CONTEXT_HANDLE*     pContextHandle, // in
   24.76 +                        TPM_RESOURCE_TYPE   type, // in
   24.77 +                        TPM_HANDLE          handle); // in
   24.78 +
   24.79 +BOOL DeleteHandleFromList(   CONTEXT_HANDLE*     pContextHandle, // in
   24.80 +                             TPM_HANDLE          handle); // in
   24.81 +
   24.82 +BOOL FreeHandleList(    CONTEXT_HANDLE*     pContextHandle); // in
   24.83 +
   24.84 +#endif //_CONTEXTMGR_H_
    25.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    25.2 +++ b/tools/vtpm_manager/tcs/tcs.c	Tue Aug 30 11:39:25 2005 -0800
    25.3 @@ -0,0 +1,1102 @@
    25.4 +// ===================================================================
    25.5 +// 
    25.6 +// Copyright (c) 2005, Intel Corp.
    25.7 +// All rights reserved.
    25.8 +//
    25.9 +// Redistribution and use in source and binary forms, with or without 
   25.10 +// modification, are permitted provided that the following conditions 
   25.11 +// are met:
   25.12 +//
   25.13 +//   * Redistributions of source code must retain the above copyright 
   25.14 +//     notice, this list of conditions and the following disclaimer.
   25.15 +//   * Redistributions in binary form must reproduce the above 
   25.16 +//     copyright notice, this list of conditions and the following 
   25.17 +//     disclaimer in the documentation and/or other materials provided 
   25.18 +//     with the distribution.
   25.19 +//   * Neither the name of Intel Corporation nor the names of its 
   25.20 +//     contributors may be used to endorse or promote products derived
   25.21 +//     from this software without specific prior written permission.
   25.22 +//
   25.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   25.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   25.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   25.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   25.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   25.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   25.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   25.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   25.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   25.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   25.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   25.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   25.35 +// ===================================================================
   25.36 +// 
   25.37 +// tcs.c
   25.38 +// 
   25.39 +//  This file contains the functions that implement a TCS.
   25.40 +// 
   25.41 +// ==================================================================
   25.42 +
   25.43 +#include <stdio.h>
   25.44 +#include <string.h>
   25.45 +#include <malloc.h>
   25.46 +
   25.47 +#include "tcg.h"
   25.48 +#include "bsg.h"
   25.49 +#include "tcs.h"
   25.50 +#include "contextmgr.h"
   25.51 +#include "tpmddl.h"
   25.52 +#include "log.h"
   25.53 +
   25.54 +// Static Global Vars for the TCS
   25.55 +static BOOL TCS_m_bConnected;
   25.56 +static int TCS_m_nCount = 0;
   25.57 +
   25.58 +#define TCPA_MAX_BUFFER_LENGTH 0x2000
   25.59 +
   25.60 +static BYTE InBuf [TCPA_MAX_BUFFER_LENGTH];
   25.61 +static BYTE OutBuf[TCPA_MAX_BUFFER_LENGTH];
   25.62 +
   25.63 +
   25.64 +// ---------------------------------------------------------------------------------
   25.65 +// Initialization/Uninitialization SubComponent API
   25.66 +// ---------------------------------------------------------------------------------
   25.67 +TPM_RESULT TCS_create() {
   25.68 +  TDDL_RESULT hRes = TDDL_E_FAIL;
   25.69 +  TPM_RESULT result = TPM_FAIL;
   25.70 +  TCS_m_bConnected = FALSE;
   25.71 +  
   25.72 +  if (TCS_m_nCount == 0) {
   25.73 +    vtpmloginfo(VTPM_LOG_TCS, "Constructing new TCS:\n");
   25.74 +    hRes = TDDL_Open();
   25.75 +    
   25.76 +    if (hRes == TDDL_SUCCESS) {
   25.77 +      TCS_m_bConnected = TRUE;
   25.78 +      result = TPM_SUCCESS;
   25.79 +    }
   25.80 +  } else
   25.81 +    TCS_m_bConnected = TRUE;
   25.82 +  
   25.83 +  TCS_m_nCount++;
   25.84 +  
   25.85 +  return(result);
   25.86 +}
   25.87 +
   25.88 +
   25.89 +void TCS_destroy()
   25.90 +{
   25.91 +  // FIXME: Should iterate through all open contexts and close them.
   25.92 +  TCS_m_nCount--;
   25.93 +  
   25.94 +  if (TCS_m_bConnected == TRUE && TCS_m_nCount == 0) {
   25.95 +    vtpmloginfo(VTPM_LOG_TCS, "Destructing TCS:\n");
   25.96 +    TDDL_Close();
   25.97 +    TCS_m_bConnected = FALSE;
   25.98 +  }
   25.99 +  
  25.100 +}
  25.101 +
  25.102 +TPM_RESULT TCS_Malloc(  TCS_CONTEXT_HANDLE  hContext, // in
  25.103 +                        UINT32              MemSize, // in
  25.104 +                        BYTE**              ppMemPtr) {// out
  25.105 +
  25.106 +  TPM_RESULT returnCode = TPM_FAIL;
  25.107 +  CONTEXT_HANDLE* pContextHandle = (CONTEXT_HANDLE*)hContext;
  25.108 +  
  25.109 +  if (pContextHandle != NULL && ppMemPtr != NULL) {
  25.110 +    *ppMemPtr = (BYTE *)AddMemBlock(pContextHandle, MemSize);
  25.111 +    returnCode = TPM_SUCCESS;
  25.112 +  }
  25.113 +  
  25.114 +  return returnCode;
  25.115 +}
  25.116 +
  25.117 +TPM_RESULT TCS_FreeMemory(  TCS_CONTEXT_HANDLE  hContext, // in
  25.118 +                            BYTE*               pMemory) { // in
  25.119 +  TPM_RESULT returnCode = TPM_FAIL;
  25.120 +  CONTEXT_HANDLE* pContextHandle = (CONTEXT_HANDLE*)hContext;
  25.121 +  
  25.122 +  if ( (pContextHandle != NULL && pMemory != NULL) &&
  25.123 +       (DeleteMemBlock(pContextHandle, pMemory) == TRUE) )
  25.124 +    returnCode = TPM_SUCCESS;
  25.125 + 
  25.126 +  
  25.127 +  return returnCode;
  25.128 +}
  25.129 +
  25.130 +TPM_RESULT TCS_OpenContext(TCS_CONTEXT_HANDLE* hContext) { // out
  25.131 +  TPM_RESULT returnCode = TPM_FAIL;
  25.132 +  
  25.133 +  vtpmloginfo(VTPM_LOG_TCS, "Calling TCS_OpenContext:\n");
  25.134 +  
  25.135 +  // hContext must point to a null memory context handle
  25.136 +  if(*hContext == HANDLE_NULL) {
  25.137 +    CONTEXT_HANDLE* pContextHandle = (CONTEXT_HANDLE *)malloc(sizeof(CONTEXT_HANDLE));
  25.138 +    if (pContextHandle == NULL) 
  25.139 +      return TPM_SIZE;
  25.140 +    
  25.141 +    
  25.142 +    // initialize to 0
  25.143 +    pContextHandle->nBlockCount = 0;
  25.144 +    pContextHandle->pTopBlock = NULL;
  25.145 +    pContextHandle->pHandleList = NULL;
  25.146 +    
  25.147 +    // Create New Block
  25.148 +    AddMemBlock(pContextHandle, BLOCK_SIZE);
  25.149 +    
  25.150 +    *hContext = (TCS_CONTEXT_HANDLE)pContextHandle;
  25.151 +    returnCode = TPM_SUCCESS;
  25.152 +  }
  25.153 +  
  25.154 +  return(returnCode);
  25.155 +}
  25.156 +
  25.157 +TPM_RESULT TCS_CloseContext(TCS_CONTEXT_HANDLE hContext) {// in
  25.158 +  //FIXME: TCS SHOULD Track track failed auths and make sure
  25.159 +  //we don't try and re-free them here.
  25.160 +  TPM_RESULT returnCode = TPM_FAIL;
  25.161 +  
  25.162 +  CONTEXT_HANDLE* pContextHandle = (CONTEXT_HANDLE*)hContext;
  25.163 +  
  25.164 +  if(pContextHandle != NULL) {
  25.165 +    // Print test info
  25.166 +    vtpmloginfo(VTPM_LOG_TCS, "Calling TCS_CloseContext.\n");
  25.167 +      
  25.168 +    // free memory for all the blocks
  25.169 +    DeleteMemBlock(pContextHandle, NULL );      
  25.170 +    pContextHandle->pTopBlock = NULL;
  25.171 +    
  25.172 +    FreeHandleList(pContextHandle);
  25.173 +    if (pContextHandle->pHandleList != NULL) 
  25.174 +      vtpmlogerror(VTPM_LOG_TCS, "Not all handles evicted from TPM.\n");
  25.175 +    
  25.176 +    // Release the TPM's resources
  25.177 +    free(pContextHandle);
  25.178 +    returnCode = TPM_SUCCESS;
  25.179 +  }
  25.180 +  
  25.181 +  vtpmloginfo(VTPM_LOG_TCS_DEEP, "Finished closing context\n");
  25.182 +  return(returnCode);
  25.183 +}
  25.184 +
  25.185 +// ------------------------------------------------------------------
  25.186 +// Internal Functions
  25.187 +// ------------------------------------------------------------------
  25.188 +int packAuth(BYTE* dst, TCS_AUTH* auth) {
  25.189 +  // CHECK: according to the command specs, the outgoing auth params are:
  25.190 +  // nonceEven
  25.191 +  // nonceOdd
  25.192 +  // continueAuthSession
  25.193 +  // auth digest for return params
  25.194 +  //
  25.195 +  // this is a bit different than this code...
  25.196 +  
  25.197 +  return BSG_PackList(dst, 4, 
  25.198 +		      BSG_TYPE_UINT32, &(auth->AuthHandle), 
  25.199 +		      BSG_TPM_NONCE, &(auth->NonceOdd), 
  25.200 +		      BSG_TYPE_BOOL, &(auth->fContinueAuthSession), 
  25.201 +		      BSG_TPM_AUTHDATA, &(auth->HMAC));
  25.202 +}
  25.203 +
  25.204 +int unpackAuth(TCS_AUTH* auth, BYTE* src) {
  25.205 +  return BSG_UnpackList(src, 3, 
  25.206 +			BSG_TPM_NONCE, &(auth->NonceEven), 
  25.207 +			BSG_TYPE_BOOL, &(auth->fContinueAuthSession), 
  25.208 +			BSG_TPM_AUTHDATA, &(auth->HMAC));
  25.209 +}
  25.210 +
  25.211 +// ------------------------------------------------------------------
  25.212 +// Authorization Commands
  25.213 +// ------------------------------------------------------------------
  25.214 +
  25.215 +TPM_RESULT TCSP_OIAP(TCS_CONTEXT_HANDLE hContext, // in
  25.216 +		     TCS_AUTHHANDLE*  authHandle, // out 
  25.217 +		     TPM_NONCE*   nonce0)  // out
  25.218 +{
  25.219 +  // setup input/output parameters block
  25.220 +  TPM_TAG tag = TPM_TAG_RQU_COMMAND;
  25.221 +  TPM_COMMAND_CODE ordinal = TPM_ORD_OIAP;
  25.222 +  UINT32 paramSize = 0;
  25.223 +  TPM_RESULT returnCode = TPM_SUCCESS;
  25.224 +  
  25.225 +  // setup the TPM driver input and output buffers
  25.226 +  TDDL_RESULT hRes = TDDL_E_FAIL;
  25.227 +  TDDL_UINT32  InLength = TCPA_MAX_BUFFER_LENGTH;
  25.228 +  TDDL_UINT32  OutLength = TCPA_MAX_BUFFER_LENGTH;
  25.229 +  
  25.230 +  // check input params
  25.231 +  if (authHandle == NULL || nonce0 == NULL) 
  25.232 +    return TPM_BAD_PARAMETER;
  25.233 +  
  25.234 +  // Convert Byte Input parameter in the input byte stream InBuf
  25.235 +  InLength = BSG_PackList(InBuf, 3, 
  25.236 +			  BSG_TPM_TAG, &tag, 
  25.237 +			  BSG_TYPE_UINT32, &paramSize, 
  25.238 +			  BSG_TPM_COMMAND_CODE, &ordinal);
  25.239 +    
  25.240 +  // fill paramSize again as we now have the correct size
  25.241 +  BSG_Pack(BSG_TYPE_UINT32, &InLength, InBuf+2);
  25.242 +  
  25.243 +  vtpmloginfo(VTPM_LOG_TCS_DEEP, "Sending paramSize = %d\n", InLength);
  25.244 +  
  25.245 +  // call the TPM driver
  25.246 +  if ((hRes = TDDL_TransmitData(InBuf, InLength, OutBuf, &OutLength)) 
  25.247 +      == TDDL_SUCCESS) {
  25.248 +    
  25.249 +    // unpack to get the tag, paramSize, & returnCode
  25.250 +    int i = BSG_UnpackList( OutBuf, 3, 
  25.251 +			    BSG_TPM_TAG, &tag, 
  25.252 +			    BSG_TYPE_UINT32, &paramSize, 
  25.253 +			    BSG_TPM_COMMAND_CODE, &returnCode);
  25.254 +    
  25.255 +    if (returnCode == TPM_SUCCESS && tag == TPM_TAG_RSP_COMMAND) {
  25.256 +      // Extract the remaining output parameters
  25.257 +      BSG_UnpackList(OutBuf+i, 2, 
  25.258 +		     BSG_TYPE_UINT32, authHandle, 
  25.259 +		     BSG_TPM_NONCE, nonce0);
  25.260 +      
  25.261 +      if (!AddHandleToList((CONTEXT_HANDLE *)hContext, TPM_RT_AUTH, *authHandle)) 
  25.262 +        vtpmlogerror(VTPM_LOG_TCS, "New AuthHandle not recorded\n");
  25.263 +      
  25.264 +      vtpmloginfo(VTPM_LOG_TCS_DEEP, "Received paramSize : %d\n", paramSize);
  25.265 +    } else 
  25.266 +      vtpmlogerror(VTPM_LOG_TCS, "Failed with return code %s\n", tpm_get_error_name(returnCode));
  25.267 +    
  25.268 +  }
  25.269 +  
  25.270 +  return(returnCode);
  25.271 +}
  25.272 +
  25.273 +TPM_RESULT TCSP_OSAP(TCS_CONTEXT_HANDLE hContext,  // in
  25.274 +		     TPM_ENTITY_TYPE  entityType,  // in
  25.275 +		     UINT32    entityValue, // in
  25.276 +		     TPM_NONCE   nonceOddOSAP, // in
  25.277 +		     TCS_AUTHHANDLE*  authHandle,  // out 
  25.278 +		     TPM_NONCE*   nonceEven,  // out
  25.279 +		     TPM_NONCE*   nonceEvenOSAP) // out
  25.280 +{
  25.281 +  // setup input/output parameters block
  25.282 +  TPM_TAG tag = TPM_TAG_RQU_COMMAND;
  25.283 +  UINT32 paramSize = 0;
  25.284 +  TPM_COMMAND_CODE ordinal = TPM_ORD_OSAP;
  25.285 +  TPM_RESULT returnCode = TPM_SUCCESS;
  25.286 +  
  25.287 +  // setup the TPM driver input and output buffers
  25.288 +  TDDL_RESULT hRes = TDDL_E_FAIL;
  25.289 +  TDDL_UINT32  InLength = TCPA_MAX_BUFFER_LENGTH;
  25.290 +  TDDL_UINT32  OutLength = TCPA_MAX_BUFFER_LENGTH;
  25.291 +  
  25.292 +  // check input params
  25.293 +  if (authHandle == NULL || nonceEven == NULL || nonceEvenOSAP == NULL)
  25.294 +    return TPM_BAD_PARAMETER;
  25.295 +  
  25.296 +  // Convert Byte Input parameter in the input byte stream InBuf
  25.297 +  InLength = BSG_PackList(InBuf, 6, 
  25.298 +			  BSG_TPM_TAG, &tag, 
  25.299 +			  BSG_TYPE_UINT32, &paramSize, 
  25.300 +			  BSG_TPM_COMMAND_CODE, &ordinal, 
  25.301 +			  BSG_TYPE_UINT16, &entityType, 
  25.302 +			  BSG_TYPE_UINT32, &entityValue, 
  25.303 +			  BSG_TPM_NONCE, &nonceOddOSAP);
  25.304 +  
  25.305 +  // fill paramSize again as we now have the correct size
  25.306 +  BSG_Pack(BSG_TYPE_UINT32, &InLength, InBuf+2);
  25.307 +  
  25.308 +  vtpmloginfo(VTPM_LOG_TCS_DEEP, "Sending paramSize = %d\n", InLength);
  25.309 +  
  25.310 +  // call the TPM driver
  25.311 +  if ((hRes = TDDL_TransmitData(InBuf, InLength, OutBuf, &OutLength)) 
  25.312 +            == TDDL_SUCCESS) {
  25.313 +
  25.314 +    // unpack to get the tag, paramSize, & returnCode
  25.315 +    int i = BSG_UnpackList(OutBuf, 3, 
  25.316 +			   BSG_TPM_TAG, &tag, 
  25.317 +			   BSG_TYPE_UINT32, &paramSize, 
  25.318 +			   BSG_TPM_COMMAND_CODE, &returnCode);
  25.319 +    
  25.320 +    if (returnCode == TPM_SUCCESS && tag == TPM_TAG_RSP_COMMAND) {
  25.321 +      // Extract the remaining output parameters
  25.322 +      BSG_UnpackList(OutBuf+i, 3, 
  25.323 +		     BSG_TYPE_UINT32, authHandle, 
  25.324 +		     BSG_TPM_NONCE, nonceEven, 
  25.325 +		     BSG_TPM_NONCE, nonceEvenOSAP);
  25.326 +      
  25.327 +      if (!AddHandleToList((CONTEXT_HANDLE *)hContext, TPM_RT_AUTH, *authHandle)) {
  25.328 +	    vtpmlogerror(VTPM_LOG_TCS, "New AuthHandle not recorded\n");
  25.329 +      }
  25.330 +      
  25.331 +      vtpmloginfo(VTPM_LOG_TCS_DEEP, "Received paramSize : %d\n", paramSize);
  25.332 +    } else 
  25.333 +      vtpmlogerror(VTPM_LOG_TCS, "Failed with return code %s\n", tpm_get_error_name(returnCode));
  25.334 +    
  25.335 +  }
  25.336 +  
  25.337 +  return(returnCode);
  25.338 +}
  25.339 +
  25.340 +TPM_RESULT TCSP_TakeOwnership(TCS_CONTEXT_HANDLE hContext,   // in
  25.341 +			      UINT16    protocolID,   // in
  25.342 +			      UINT32    encOwnerAuthSize, // in 
  25.343 +			      BYTE*    encOwnerAuth,  // in
  25.344 +			      UINT32    encSrkAuthSize,  // in
  25.345 +			      BYTE*    encSrkAuth,   // in
  25.346 +			      UINT32*    SrkSize,   // in, out
  25.347 +			      BYTE**    Srk,    // in, out
  25.348 +			      TCS_AUTH*   ownerAuth)   // in, out
  25.349 +{
  25.350 +  // setup input/output parameters block
  25.351 +  TPM_TAG tag = TPM_TAG_RQU_AUTH1_COMMAND;
  25.352 +  UINT32 paramSize = 0;
  25.353 +  TPM_COMMAND_CODE ordinal = TPM_ORD_TakeOwnership;
  25.354 +  TPM_RESULT returnCode = TPM_SUCCESS;
  25.355 +  
  25.356 +  // setup the TPM driver input and output buffers
  25.357 +  TDDL_RESULT hRes = TDDL_E_FAIL;
  25.358 +  TDDL_UINT32 InLength = TCPA_MAX_BUFFER_LENGTH;
  25.359 +  TDDL_UINT32 OutLength = TCPA_MAX_BUFFER_LENGTH;
  25.360 +  
  25.361 +  // check input params
  25.362 +  if (encOwnerAuth == NULL || encSrkAuth == NULL || SrkSize == NULL || *Srk == NULL) 
  25.363 +    return TPM_BAD_PARAMETER;
  25.364 +  
  25.365 +  // Convert Byte Input parameter in the input byte stream InBuf
  25.366 +  InLength = BSG_PackList(InBuf, 5, 
  25.367 +			  BSG_TPM_TAG, &tag, 
  25.368 +			  BSG_TYPE_UINT32, &paramSize, 
  25.369 +			  BSG_TPM_COMMAND_CODE, &ordinal, 
  25.370 +			  BSG_TYPE_UINT16, &protocolID, 
  25.371 +			  BSG_TYPE_UINT32, &encOwnerAuthSize);
  25.372 +  
  25.373 +  memcpy(InBuf+InLength, encOwnerAuth, encOwnerAuthSize);
  25.374 +  InLength += encOwnerAuthSize;
  25.375 +  InLength += BSG_Pack(   BSG_TYPE_UINT32, 
  25.376 +			  &encSrkAuthSize, 
  25.377 +			  InBuf+InLength);
  25.378 +  memcpy(InBuf+InLength, encSrkAuth, encSrkAuthSize);
  25.379 +  InLength += encSrkAuthSize;
  25.380 +  memcpy(InBuf+InLength, *Srk, *SrkSize);
  25.381 +  InLength += *SrkSize;
  25.382 +  InLength += packAuth(InBuf+InLength, ownerAuth);
  25.383 +  // fill paramSize again as we now have the correct size
  25.384 +  BSG_Pack(BSG_TYPE_UINT32, 
  25.385 +	   &InLength, 
  25.386 +	   InBuf+2);
  25.387 +  
  25.388 +  vtpmloginfo(VTPM_LOG_TCS_DEEP, "Sending paramSize = %d\n", InLength);
  25.389 +  
  25.390 +  // call the TPM driver
  25.391 +  if ((hRes = TDDL_TransmitData(InBuf, InLength, OutBuf, &OutLength)) 
  25.392 +              == TDDL_SUCCESS){
  25.393 +    
  25.394 +    // unpack to get the tag, paramSize, & returnCode
  25.395 +    int i = BSG_UnpackList( OutBuf, 3, 
  25.396 +			    BSG_TPM_TAG, &tag, 
  25.397 +			    BSG_TYPE_UINT32, &paramSize, 
  25.398 +			    BSG_TPM_COMMAND_CODE, &returnCode);
  25.399 +    
  25.400 +    if (returnCode == TPM_SUCCESS && tag == TPM_TAG_RSP_AUTH1_COMMAND) {
  25.401 +      // Extract the remaining output parameters
  25.402 +      TPM_KEY srkPub;
  25.403 +      i += BSG_Unpack(BSG_TPM_KEY,  OutBuf+i,  &srkPub); 
  25.404 +      unpackAuth(ownerAuth, OutBuf+i);
  25.405 +      
  25.406 +      // fill output params
  25.407 +      BYTE tempBuf[1024];
  25.408 +      *SrkSize = BSG_Pack(BSG_TPM_KEY,  &srkPub, tempBuf);
  25.409 +      if (TCS_Malloc(hContext, *SrkSize, Srk) == TPM_FAIL) {
  25.410 +	return(TPM_SIZE);
  25.411 +      }
  25.412 +      memcpy(*Srk, tempBuf, *SrkSize);
  25.413 +      
  25.414 +      vtpmloginfo(VTPM_LOG_TCS_DEEP, "Received paramSize : %d", paramSize);
  25.415 +    } else 
  25.416 +      vtpmlogerror(VTPM_LOG_TCS, "TCSP_TakeOwnership Failed with return code %s\n", tpm_get_error_name(returnCode));
  25.417 +  }
  25.418 +  
  25.419 +  return(returnCode);
  25.420 +}
  25.421 +
  25.422 +
  25.423 +TPM_RESULT TCSP_DisablePubekRead (  TCS_CONTEXT_HANDLE hContext, // in
  25.424 +                                    TCS_AUTH*   ownerAuth) { // in, out
  25.425 + 
  25.426 +  // setup input/output parameters block
  25.427 +  TPM_TAG tag = TPM_TAG_RQU_AUTH1_COMMAND;
  25.428 +  UINT32 paramSize = 0;
  25.429 +  TPM_COMMAND_CODE ordinal = TPM_ORD_DisablePubekRead;
  25.430 +  TPM_RESULT returnCode = TPM_SUCCESS;
  25.431 +  
  25.432 +  // setup the TPM driver input and output buffers
  25.433 +  TDDL_RESULT hRes = TDDL_E_FAIL;
  25.434 +  TDDL_UINT32 InLength = TCPA_MAX_BUFFER_LENGTH;
  25.435 +  TDDL_UINT32 OutLength = TCPA_MAX_BUFFER_LENGTH;
  25.436 +    
  25.437 +  // Convert Byte Input parameter in the input byte stream InBuf
  25.438 +  InLength = BSG_PackList(InBuf, 3, 
  25.439 +			  BSG_TPM_TAG, &tag, 
  25.440 +			  BSG_TYPE_UINT32, &paramSize, 
  25.441 +			  BSG_TPM_COMMAND_CODE, &ordinal);
  25.442 +  
  25.443 +  InLength += packAuth(InBuf+InLength, ownerAuth);
  25.444 + 
  25.445 +  // fill paramSize again as we now have the correct size
  25.446 +  BSG_Pack(BSG_TYPE_UINT32, &InLength, InBuf+2);
  25.447 +  
  25.448 +  vtpmloginfo(VTPM_LOG_TCS_DEEP, "Sending paramSize = %d\n", InLength);
  25.449 +  
  25.450 +  // call the TPM driver
  25.451 +  if ((hRes = TDDL_TransmitData(InBuf, InLength, OutBuf, &OutLength)) 
  25.452 +              == TDDL_SUCCESS){
  25.453 +    
  25.454 +    // unpack to get the tag, paramSize, & returnCode
  25.455 +    int i = BSG_UnpackList( OutBuf, 3, 
  25.456 +			    BSG_TPM_TAG, &tag, 
  25.457 +			    BSG_TYPE_UINT32, &paramSize, 
  25.458 +			    BSG_TPM_COMMAND_CODE, &returnCode);
  25.459 +    
  25.460 +    if (returnCode == TPM_SUCCESS && tag == TPM_TAG_RSP_AUTH1_COMMAND) {
  25.461 +      // Extract the remaining output parameters
  25.462 +      unpackAuth(ownerAuth, OutBuf+i);
  25.463 +    } else 
  25.464 +      vtpmlogerror(VTPM_LOG_TCS, "TCSP_DisablePubekRead Failed with return code %s\n", tpm_get_error_name(returnCode));
  25.465 +  }
  25.466 +  
  25.467 +  return(returnCode);
  25.468 +}
  25.469 +
  25.470 +
  25.471 +TPM_RESULT TCSP_TerminateHandle(TCS_CONTEXT_HANDLE hContext, // in
  25.472 +                                TCS_AUTHHANDLE  handle)  // in
  25.473 +{
  25.474 +  // setup input/output parameters block
  25.475 +  TPM_TAG tag = TPM_TAG_RQU_COMMAND;
  25.476 +  UINT32 paramSize = 0;
  25.477 +  TPM_COMMAND_CODE ordinal = TPM_ORD_Terminate_Handle;
  25.478 +  TPM_RESULT returnCode = TPM_SUCCESS;
  25.479 +  
  25.480 +  // setup the TPM driver input and output buffers
  25.481 +  TDDL_RESULT hRes = TDDL_E_FAIL;
  25.482 +  TDDL_UINT32  InLength = TCPA_MAX_BUFFER_LENGTH;
  25.483 +  TDDL_UINT32  OutLength = TCPA_MAX_BUFFER_LENGTH;
  25.484 +  
  25.485 +  // Convert Byte Input parameter in the input byte stream InBuf
  25.486 +  InLength = BSG_PackList(InBuf, 4, 
  25.487 +			  BSG_TPM_TAG, &tag, 
  25.488 +			  BSG_TYPE_UINT32, &paramSize, 
  25.489 +			  BSG_TPM_COMMAND_CODE, &ordinal, 
  25.490 +			  BSG_TYPE_UINT32, &handle);
  25.491 +  // fill paramSize again as we now have the correct size
  25.492 +  BSG_Pack(BSG_TYPE_UINT32, &InLength, InBuf+2);
  25.493 +  
  25.494 +  // call the TPM driver
  25.495 +  if ((hRes = TDDL_TransmitData(InBuf, InLength, OutBuf, &OutLength)) 
  25.496 +              == TDDL_SUCCESS) {
  25.497 +    
  25.498 +    // unpack to get the tag, paramSize, & returnCode
  25.499 +    BSG_UnpackList(OutBuf, 3, 
  25.500 +			   BSG_TPM_TAG, &tag, 
  25.501 +			   BSG_TYPE_UINT32, &paramSize, 
  25.502 +			   BSG_TPM_COMMAND_CODE, &returnCode);
  25.503 +    
  25.504 +    if (!DeleteHandleFromList((CONTEXT_HANDLE *)hContext, handle)) 
  25.505 +      vtpmlogerror(VTPM_LOG_TCS, "KeyHandle not removed from list\n");
  25.506 +       
  25.507 +    
  25.508 +    if (returnCode == TPM_SUCCESS && tag == TPM_TAG_RSP_COMMAND) {
  25.509 +      // Print debug info
  25.510 +      
  25.511 +      vtpmloginfo(VTPM_LOG_TCS_DEEP, "Received paramSize : %d", paramSize);
  25.512 +    } else 
  25.513 +      vtpmlogerror(VTPM_LOG_TCS, "TCSP_TerminateHandle Failed with return code %s\n", tpm_get_error_name(returnCode));
  25.514 +    
  25.515 +  }
  25.516 +  
  25.517 +  return(returnCode);
  25.518 +}
  25.519 +
  25.520 +// TPM Mandatory
  25.521 +TPM_RESULT TCSP_Extend( TCS_CONTEXT_HANDLE hContext, // in
  25.522 +                        TPM_PCRINDEX  pcrNum,  // in
  25.523 +                        TPM_DIGEST  inDigest, // in
  25.524 +                        TPM_PCRVALUE*  outDigest) // out
  25.525 +{
  25.526 +  // setup input/output parameters block
  25.527 +  TPM_TAG tag = TPM_TAG_RQU_COMMAND;
  25.528 +  UINT32 paramSize = 0;
  25.529 +  TPM_COMMAND_CODE ordinal = TPM_ORD_Extend;
  25.530 +  TPM_RESULT returnCode = TPM_SUCCESS;
  25.531 +  
  25.532 +  // setup the TPM driver input and output buffers
  25.533 +  TDDL_RESULT hRes = TDDL_E_FAIL;
  25.534 +  TDDL_UINT32  InLength = TCPA_MAX_BUFFER_LENGTH;
  25.535 +  TDDL_UINT32  OutLength = TCPA_MAX_BUFFER_LENGTH;
  25.536 +  
  25.537 +  // Convert Byte Input parameter in the input byte stream InBuf
  25.538 +  InLength = BSG_PackList(InBuf, 5, 
  25.539 +			  BSG_TPM_TAG, &tag, 
  25.540 +			  BSG_TYPE_UINT32, &paramSize, 
  25.541 +			  BSG_TPM_COMMAND_CODE, &ordinal, 
  25.542 +			  BSG_TYPE_UINT32, &pcrNum, 
  25.543 +			  BSG_TPM_DIGEST, &inDigest);
  25.544 +  // fill paramSize again as we now have the correct size
  25.545 +  BSG_Pack(BSG_TYPE_UINT32, &InLength, InBuf+2);
  25.546 +  
  25.547 +  vtpmloginfo(VTPM_LOG_TCS_DEEP, "Sending paramSize = %d\n", InLength);
  25.548 +  
  25.549 +  // call the TPM driver
  25.550 +  if ((hRes = TDDL_TransmitData(InBuf, InLength, OutBuf, &OutLength)) 
  25.551 +              == TDDL_SUCCESS) {
  25.552 +    
  25.553 +    // unpack to get the tag, paramSize, & returnCode
  25.554 +    int i = BSG_UnpackList(OutBuf, 3, 
  25.555 +			   BSG_TPM_TAG, &tag, 
  25.556 +			   BSG_TYPE_UINT32, &paramSize, 
  25.557 +			   BSG_TPM_COMMAND_CODE, &returnCode);
  25.558 +    
  25.559 +    if (returnCode == TPM_SUCCESS && tag == TPM_TAG_RSP_COMMAND){
  25.560 +      // Extract the remaining output parameters
  25.561 +      BSG_Unpack(BSG_TPM_PCRVALUE, OutBuf+i, outDigest);
  25.562 +      
  25.563 +      vtpmloginfo(VTPM_LOG_TCS_DEEP, "Received paramSize : %d\n", paramSize);
  25.564 +    } else 
  25.565 +      vtpmlogerror(VTPM_LOG_TCS, "TCSP_Extend Failed with return code %s\n", tpm_get_error_name(returnCode));
  25.566 +  }
  25.567 +  
  25.568 +  return(returnCode);
  25.569 +}
  25.570 +
  25.571 +TPM_RESULT TCSP_Seal(   TCS_CONTEXT_HANDLE hContext,  // in
  25.572 +                        TCS_KEY_HANDLE  keyHandle,  // in
  25.573 +                        TPM_ENCAUTH   encAuth,  // in
  25.574 +                        UINT32    pcrInfoSize, // in
  25.575 +                        BYTE*    PcrInfo,  // in
  25.576 +                        UINT32    inDataSize,  // in
  25.577 +                        BYTE*    inData,   // in
  25.578 +                        TCS_AUTH*   pubAuth,  // in, out
  25.579 +                        UINT32*    SealedDataSize, // out
  25.580 +                        BYTE**    SealedData)  // out
  25.581 +{
  25.582 +  // setup input/output parameters block
  25.583 +  TPM_TAG tag = TPM_TAG_RQU_AUTH1_COMMAND;
  25.584 +  UINT32 paramSize = 0;
  25.585 +  TPM_COMMAND_CODE ordinal = TPM_ORD_Seal;
  25.586 +  TPM_RESULT returnCode = TPM_SUCCESS;
  25.587 +  
  25.588 +  // setup the TPM driver input and output buffers
  25.589 +  TDDL_RESULT hRes = TDDL_E_FAIL;
  25.590 +  TDDL_UINT32  InLength = TCPA_MAX_BUFFER_LENGTH;
  25.591 +  TDDL_UINT32  OutLength = TCPA_MAX_BUFFER_LENGTH;
  25.592 +  
  25.593 +  // check input params
  25.594 +  if (inData == NULL || pubAuth == NULL || SealedDataSize == NULL || *SealedData == NULL)
  25.595 +    return TPM_BAD_PARAMETER;
  25.596 +  
  25.597 +  // Convert Byte Input parameter in the input byte stream InBuf
  25.598 +  InLength = BSG_PackList(InBuf, 6, 
  25.599 +			  BSG_TPM_TAG, &tag, 
  25.600 +			  BSG_TYPE_UINT32, &paramSize, 
  25.601 +			  BSG_TPM_COMMAND_CODE, &ordinal, 
  25.602 +			  BSG_TYPE_UINT32, &keyHandle, 
  25.603 +			  BSG_TPM_ENCAUTH, encAuth, 
  25.604 +			  BSG_TYPE_UINT32, &pcrInfoSize);
  25.605 +  memcpy(InBuf+InLength, PcrInfo, pcrInfoSize);
  25.606 +  InLength += pcrInfoSize;
  25.607 +  InLength += BSG_Pack(BSG_TYPE_UINT32, &inDataSize, InBuf+InLength);
  25.608 +  memcpy(InBuf+InLength, inData, inDataSize);
  25.609 +  InLength += inDataSize;
  25.610 +  InLength += packAuth(InBuf+InLength, pubAuth);
  25.611 +  // fill paramSize again as we now have the correct size
  25.612 +  BSG_Pack(BSG_TYPE_UINT32, &InLength, InBuf+2);
  25.613 +    
  25.614 +  // call the TPM driver
  25.615 +  if ((hRes = TDDL_TransmitData(InBuf, InLength, OutBuf, &OutLength)) 
  25.616 +              == TDDL_SUCCESS) {
  25.617 +    // unpack OutBuf to get the tag, paramSize, & returnCode
  25.618 +    int i = BSG_UnpackList(OutBuf, 3, 
  25.619 +			   BSG_TPM_TAG, &tag, 
  25.620 +			   BSG_TYPE_UINT32, &paramSize, 
  25.621 +			   BSG_TPM_COMMAND_CODE, &returnCode);
  25.622 +    
  25.623 +    if (returnCode == TPM_SUCCESS && tag == TPM_TAG_RSP_AUTH1_COMMAND) {
  25.624 +      // Extract the remaining output parameters
  25.625 +      TPM_STORED_DATA sealedData;
  25.626 +      
  25.627 +      i += BSG_Unpack(BSG_TPM_STORED_DATA, OutBuf+i, &sealedData); 
  25.628 +      unpackAuth(pubAuth, OutBuf+i);
  25.629 +      
  25.630 +      // fill SealedData
  25.631 +      BYTE tempBuf[1024];
  25.632 +      *SealedDataSize = BSG_Pack(BSG_TPM_STORED_DATA, &sealedData, tempBuf);
  25.633 +      if (TCS_Malloc(hContext, *SealedDataSize, SealedData) == TPM_FAIL) {
  25.634 +	return TPM_SIZE;
  25.635 +      }
  25.636 +      memcpy(*SealedData, tempBuf, *SealedDataSize);
  25.637 +      
  25.638 +      vtpmloginfo(VTPM_LOG_TCS_DEEP, "Received paramSize : %d\n", paramSize);
  25.639 +    } else 
  25.640 +      vtpmlogerror(VTPM_LOG_TCS, "TCSP_Seal Failed with return code %s\n", tpm_get_error_name(returnCode));
  25.641 +  }
  25.642 +  
  25.643 +  return(returnCode);
  25.644 +}
  25.645 +
  25.646 +TPM_RESULT TCSP_Unseal(TCS_CONTEXT_HANDLE hContext,  // in
  25.647 +		       TCS_KEY_HANDLE  parentHandle, // in
  25.648 +		       UINT32    SealedDataSize, // in
  25.649 +		       BYTE*    SealedData,  // in
  25.650 +		       TCS_AUTH*   parentAuth,  // in, out
  25.651 +		       TCS_AUTH*   dataAuth,  // in, out
  25.652 +		       UINT32*   DataSize,  // out
  25.653 +		       BYTE**    Data)   // out
  25.654 +{
  25.655 +  // setup input/output parameters block
  25.656 +  TPM_TAG tag = TPM_TAG_RQU_AUTH2_COMMAND;
  25.657 +  UINT32 paramSize = 0;
  25.658 +  TPM_COMMAND_CODE ordinal = TPM_ORD_Unseal;
  25.659 +  TPM_RESULT returnCode = TPM_SUCCESS;
  25.660 +  
  25.661 +  // setup the TPM driver input and output buffers
  25.662 +  TDDL_RESULT hRes = TDDL_E_FAIL;
  25.663 +  TDDL_UINT32 InLength = TCPA_MAX_BUFFER_LENGTH;
  25.664 +  TDDL_UINT32 OutLength = TCPA_MAX_BUFFER_LENGTH;
  25.665 +  
  25.666 +  // check input params
  25.667 +  if (SealedData == NULL || parentAuth == NULL || dataAuth == NULL || 
  25.668 +      DataSize == NULL || Data == NULL) 
  25.669 +    return TPM_BAD_PARAMETER;
  25.670 +  
  25.671 +  
  25.672 +  // Convert Byte Input parameter in the input byte stream InBuf
  25.673 +  InLength = BSG_PackList(InBuf, 4, 
  25.674 +			              BSG_TPM_TAG, &tag, 
  25.675 +                          BSG_TYPE_UINT32, &paramSize, 
  25.676 +                          BSG_TPM_COMMAND_CODE, &ordinal, 
  25.677 +                          BSG_TYPE_UINT32, &parentHandle);
  25.678 +  memcpy(InBuf+InLength, SealedData, SealedDataSize);
  25.679 +  InLength += SealedDataSize;
  25.680 +  InLength += packAuth(InBuf+InLength, parentAuth);
  25.681 +  InLength += packAuth(InBuf+InLength, dataAuth);
  25.682 +  // fill paramSize again as we now have the correct size
  25.683 +  BSG_Pack(BSG_TYPE_UINT32, &InLength, InBuf+2);
  25.684 +  
  25.685 +  vtpmloginfo(VTPM_LOG_TCS_DEEP, "Sending paramSize = %d\n", InLength);
  25.686 +    
  25.687 +  // call the TPM driver
  25.688 +  if ((hRes = TDDL_TransmitData(InBuf, InLength, OutBuf, &OutLength)) == TDDL_SUCCESS) {
  25.689 +    // unpack OutBuf to get the tag, paramSize, & returnCode
  25.690 +    int i = BSG_UnpackList( OutBuf, 3, 
  25.691 +                            BSG_TPM_TAG, &tag, 
  25.692 +                            BSG_TYPE_UINT32, &paramSize, 
  25.693 +                            BSG_TPM_COMMAND_CODE, &returnCode);
  25.694 +    
  25.695 +    if (returnCode == TPM_SUCCESS && tag == TPM_TAG_RSP_AUTH2_COMMAND) {
  25.696 +      // Extract the remaining output parameters
  25.697 +      i += BSG_Unpack(BSG_TYPE_UINT32, OutBuf+i, DataSize);
  25.698 +      if (TCS_Malloc(hContext, *DataSize, Data) == TPM_FAIL) {
  25.699 +        return TPM_SIZE;
  25.700 +      }
  25.701 +      memcpy(*Data, OutBuf+i, *DataSize);
  25.702 +      i += *DataSize;
  25.703 +      i += unpackAuth(parentAuth, OutBuf+i);
  25.704 +      unpackAuth(dataAuth, OutBuf+i);
  25.705 +      
  25.706 +      vtpmloginfo(VTPM_LOG_TCS_DEEP, "Received paramSize : %d\n", paramSize);
  25.707 +    } else 
  25.708 +      vtpmlogerror(VTPM_LOG_TCS, "TCSP_Unseal Failed with return code %s\n", tpm_get_error_name(returnCode));
  25.709 +  }
  25.710 +  
  25.711 +  return(returnCode);
  25.712 +}
  25.713 +
  25.714 +TPM_RESULT TCSP_UnBind(TCS_CONTEXT_HANDLE hContext,  // in
  25.715 +		       TCS_KEY_HANDLE  keyHandle,  // in
  25.716 +		       UINT32    inDataSize,  // in
  25.717 +		       BYTE*    inData,   // in
  25.718 +		       TCS_AUTH*   privAuth,  // in, out
  25.719 +		       UINT32*   outDataSize, // out
  25.720 +		       BYTE**    outData)  // out
  25.721 +{
  25.722 +  // setup input/output parameters block
  25.723 +  TPM_TAG tag = TPM_TAG_RQU_AUTH1_COMMAND;
  25.724 +  UINT32 paramSize = 0;
  25.725 +  TPM_COMMAND_CODE ordinal = TPM_ORD_UnBind;
  25.726 +  TPM_RESULT returnCode = TPM_SUCCESS;
  25.727 +  
  25.728 +  // setup the TPM driver input and output buffers
  25.729 +  TDDL_RESULT hRes = TDDL_E_FAIL;
  25.730 +  TDDL_UINT32  InLength = TCPA_MAX_BUFFER_LENGTH;
  25.731 +  TDDL_UINT32  OutLength = TCPA_MAX_BUFFER_LENGTH;
  25.732 +  
  25.733 +  // check input params
  25.734 +  if (inData == NULL || privAuth == NULL || outDataSize == NULL || *outData == NULL)
  25.735 +    return TPM_BAD_PARAMETER;
  25.736 +  
  25.737 +  // Convert Byte Input parameter in the input byte stream InBuf
  25.738 +  InLength = BSG_PackList(InBuf, 5, 
  25.739 +			  BSG_TPM_TAG, &tag, 
  25.740 +			  BSG_TYPE_UINT32, &paramSize, 
  25.741 +			  BSG_TPM_COMMAND_CODE, &ordinal, 
  25.742 +			  BSG_TYPE_UINT32, &keyHandle, 
  25.743 +			  BSG_TYPE_UINT32, &inDataSize);
  25.744 +  memcpy(InBuf+InLength, inData, inDataSize);
  25.745 +  InLength += inDataSize;
  25.746 +  InLength += packAuth(InBuf+InLength, privAuth);
  25.747 +  // fill paramSize again as we now have the correct size
  25.748 +  BSG_Pack(BSG_TYPE_UINT32, &InLength, InBuf+2);
  25.749 +  
  25.750 +  vtpmloginfo(VTPM_LOG_TCS_DEEP, "\n\tSending paramSize = %d", InLength);
  25.751 +  
  25.752 +  // call the TPM driver
  25.753 +  if ((hRes = TDDL_TransmitData(InBuf, InLength, OutBuf, &OutLength)) == TDDL_SUCCESS) {
  25.754 +    // unpack OutBuf to get the tag, paramSize, & returnCode
  25.755 +    int i = BSG_UnpackList(OutBuf, 3, 
  25.756 +			   BSG_TPM_TAG, &tag, 
  25.757 +			   BSG_TYPE_UINT32, &paramSize, 
  25.758 +			   BSG_TPM_COMMAND_CODE, &returnCode);
  25.759 +    
  25.760 +    if (returnCode == TPM_SUCCESS && tag == TPM_TAG_RSP_AUTH1_COMMAND) {
  25.761 +      // Extract the remaining output parameters
  25.762 +      i += BSG_Unpack(BSG_TYPE_UINT32, OutBuf+i, outDataSize);
  25.763 +      if (TCS_Malloc(hContext, *outDataSize, outData) == TPM_FAIL)
  25.764 +        return TPM_SIZE;
  25.765 +    
  25.766 +      memcpy(*outData, OutBuf+i, *outDataSize);
  25.767 +      i += *outDataSize;
  25.768 +      unpackAuth(privAuth, OutBuf+i);
  25.769 +      
  25.770 +      vtpmloginfo(VTPM_LOG_TCS_DEEP, "Received paramSize : %d\n", paramSize);
  25.771 +    } else 
  25.772 +      vtpmlogerror(VTPM_LOG_TCS, "TCSP_UnBind Failed with return code %s\n", tpm_get_error_name(returnCode));
  25.773 +  }
  25.774 +  
  25.775 +  return(returnCode);
  25.776 +}
  25.777 +
  25.778 +TPM_RESULT TCSP_CreateWrapKey(TCS_CONTEXT_HANDLE hContext,   // in
  25.779 +			      TCS_KEY_HANDLE  hWrappingKey,  // in
  25.780 +			      TPM_ENCAUTH  KeyUsageAuth,  // in
  25.781 +			      TPM_ENCAUTH  KeyMigrationAuth, // in
  25.782 +			      UINT32*    pcKeySize,   // in, out
  25.783 +			      BYTE**    prgbKey,   // in, out
  25.784 +			      TCS_AUTH*   pAuth)    // in, out
  25.785 +{
  25.786 +  // setup input/output parameters block
  25.787 +  TPM_TAG tag = TPM_TAG_RQU_AUTH1_COMMAND;
  25.788 +  UINT32 paramSize = 0;
  25.789 +  TPM_COMMAND_CODE ordinal = TPM_ORD_CreateWrapKey;
  25.790 +  TPM_RESULT returnCode = TPM_SUCCESS;
  25.791 +  
  25.792 +  // setup the TPM driver input and output buffers
  25.793 +  TDDL_RESULT hRes = TDDL_E_FAIL;
  25.794 +  TDDL_UINT32  InLength = TCPA_MAX_BUFFER_LENGTH;
  25.795 +  TDDL_UINT32  OutLength = TCPA_MAX_BUFFER_LENGTH;
  25.796 +  
  25.797 +  // check input params
  25.798 +  if (pcKeySize == NULL || *prgbKey == NULL || pAuth == NULL)
  25.799 +    return TPM_BAD_PARAMETER;
  25.800 +  
  25.801 +  
  25.802 +  // Convert Byte Input parameter in the input byte stream InBuf
  25.803 +  InLength = BSG_PackList(InBuf, 6, 
  25.804 +			  BSG_TPM_TAG, &tag, 
  25.805 +			  BSG_TYPE_UINT32, &paramSize, 
  25.806 +			  BSG_TPM_COMMAND_CODE, &ordinal, 
  25.807 +			  BSG_TYPE_UINT32, &hWrappingKey, 
  25.808 +			  BSG_TPM_ENCAUTH, KeyUsageAuth, 
  25.809 +			  BSG_TPM_ENCAUTH, KeyMigrationAuth); 
  25.810 +  memcpy(InBuf+InLength, *prgbKey, *pcKeySize);
  25.811 +  InLength += *pcKeySize;
  25.812 +  InLength += packAuth(InBuf+InLength, pAuth);
  25.813 +  // fill paramSize again as we now have the correct size
  25.814 +  BSG_Pack(BSG_TYPE_UINT32, &InLength, InBuf+2);
  25.815 +  
  25.816 +  vtpmloginfo(VTPM_LOG_TCS_DEEP, "Sending paramSize = %d\n", InLength);
  25.817 +  
  25.818 +  // call the TPM driver
  25.819 +  if ((hRes = TDDL_TransmitData(InBuf, InLength, OutBuf, &OutLength)) == TDDL_SUCCESS) {
  25.820 +    // unpack OutBuf to get the tag, paramSize, & returnCode
  25.821 +    int i = BSG_UnpackList(OutBuf, 3, 
  25.822 +			   BSG_TPM_TAG, &tag, 
  25.823 +			   BSG_TYPE_UINT32, &paramSize, 
  25.824 +			   BSG_TPM_RESULT, &returnCode);
  25.825 +    
  25.826 +    if (returnCode == TPM_SUCCESS && tag == TPM_TAG_RSP_AUTH1_COMMAND) {
  25.827 +      // Extract the remaining output parameters
  25.828 +      TPM_KEY wrappedKey;
  25.829 +      
  25.830 +      i += BSG_Unpack(BSG_TPM_KEY, OutBuf+i, &wrappedKey);
  25.831 +      unpackAuth(pAuth, OutBuf+i);
  25.832 +      
  25.833 +      // Fill prgbKey
  25.834 +      BYTE tempBuf[1024];
  25.835 +      *pcKeySize = BSG_Pack(BSG_TPM_KEY, &wrappedKey, tempBuf);
  25.836 +      if (TCS_Malloc(hContext, *pcKeySize, prgbKey) == TPM_FAIL) 
  25.837 +        return TPM_SIZE;
  25.838 +      
  25.839 +      memcpy(*prgbKey, tempBuf, *pcKeySize);
  25.840 +      
  25.841 +      vtpmloginfo(VTPM_LOG_TCS_DEEP, "Received paramSize : %d\n", paramSize);
  25.842 +    } else 
  25.843 +      vtpmlogerror(VTPM_LOG_TCS, "TCSP_CreateWrapKey Failed with return code %s\n", tpm_get_error_name(returnCode)); 
  25.844 +  }
  25.845 +  
  25.846 +  return(returnCode);
  25.847 +}
  25.848 +
  25.849 +TPM_RESULT TCSP_LoadKeyByBlob(TCS_CONTEXT_HANDLE hContext,    // in
  25.850 +			      TCS_KEY_HANDLE  hUnwrappingKey,   // in
  25.851 +			      UINT32    cWrappedKeyBlobSize, // in
  25.852 +			      BYTE*    rgbWrappedKeyBlob,  // in
  25.853 +			      TCS_AUTH*   pAuth,     // in, out
  25.854 +			      TCS_KEY_HANDLE*  phKeyTCSI,    // out
  25.855 +			      TCS_KEY_HANDLE*  phKeyHMAC)    // out
  25.856 +{
  25.857 +  // setup input/output parameters block
  25.858 +  TPM_TAG tag = TPM_TAG_RQU_AUTH1_COMMAND;
  25.859 +  UINT32 paramSize = 0;
  25.860 +  TPM_COMMAND_CODE ordinal = TPM_ORD_LoadKey;
  25.861 +  TPM_RESULT returnCode = TPM_SUCCESS;
  25.862 +  
  25.863 +  // setup the TPM driver input and output buffers
  25.864 +  TDDL_RESULT hRes = TDDL_E_FAIL;
  25.865 +  TDDL_UINT32  InLength = TCPA_MAX_BUFFER_LENGTH;
  25.866 +  TDDL_UINT32  OutLength = TCPA_MAX_BUFFER_LENGTH;
  25.867 +  
  25.868 +  // check input params
  25.869 +  if (rgbWrappedKeyBlob == NULL || pAuth == NULL || phKeyTCSI == NULL || phKeyHMAC == NULL) 
  25.870 +    return TPM_BAD_PARAMETER; 
  25.871 +  
  25.872 +  *phKeyHMAC = hUnwrappingKey; // the parent key is the one that the TPM use to make the HMAC calc
  25.873 +  
  25.874 +  // Convert Byte Input parameter in the input byte stream InBuf
  25.875 +  InLength = BSG_PackList(InBuf, 4, 
  25.876 +			  BSG_TPM_TAG, &tag, 
  25.877 +			  BSG_TYPE_UINT32, &paramSize, 
  25.878 +			  BSG_TPM_COMMAND_CODE, &ordinal, 
  25.879 +			  BSG_TYPE_UINT32, &hUnwrappingKey);
  25.880 +  memcpy(InBuf+InLength, rgbWrappedKeyBlob, cWrappedKeyBlobSize);
  25.881 +  InLength += cWrappedKeyBlobSize;
  25.882 +  InLength += packAuth(InBuf+InLength, pAuth);
  25.883 +  // fill paramSize again as we now have the correct size
  25.884 +  BSG_Pack(BSG_TYPE_UINT32, &InLength, InBuf+2);
  25.885 +  
  25.886 +  vtpmloginfo(VTPM_LOG_TCS_DEEP, "Sending paramSize = %d\n", InLength);
  25.887 +  
  25.888 +  // call the TPM driver
  25.889 +  if ((hRes = TDDL_TransmitData(InBuf, InLength, OutBuf, &OutLength)) == TDDL_SUCCESS) {
  25.890 +    // unpack OutBuf to get the tag, paramSize, & returnCode
  25.891 +    int i = BSG_UnpackList(OutBuf, 3, 
  25.892 +			   BSG_TPM_TAG, &tag, 
  25.893 +			   BSG_TYPE_UINT32, &paramSize, 
  25.894 +			   BSG_TPM_COMMAND_CODE, &returnCode);
  25.895 +    
  25.896 +    if (returnCode == TPM_SUCCESS && tag == TPM_TAG_RSP_AUTH1_COMMAND) {
  25.897 +      // Extract the remaining output parameters
  25.898 +      i += BSG_Unpack(BSG_TYPE_UINT32, 
  25.899 +		      OutBuf+i, 
  25.900 +		      phKeyTCSI);
  25.901 +      unpackAuth(pAuth, OutBuf+i);
  25.902 +      
  25.903 +      if (!AddHandleToList((CONTEXT_HANDLE *)hContext, TPM_RT_KEY, *phKeyTCSI)) {
  25.904 +        vtpmlogerror(VTPM_LOG_TCS, "New KeyHandle not recorded\n");
  25.905 +      }
  25.906 +      
  25.907 +      vtpmloginfo(VTPM_LOG_TCS_DEEP, "Received paramSize : %d\n", paramSize);
  25.908 +     } else 
  25.909 +      vtpmlogerror(VTPM_LOG_TCS, "TCSP_LoadKeyByBlob Failed with return code %s\n", tpm_get_error_name(returnCode));
  25.910 +  }
  25.911 +  
  25.912 +  return(returnCode);
  25.913 +}
  25.914 +
  25.915 +TPM_RESULT TCSP_EvictKey(TCS_CONTEXT_HANDLE hContext, // in
  25.916 +			 TCS_KEY_HANDLE  hKey)  // in
  25.917 +{
  25.918 +  // setup input/output parameters block
  25.919 +  TPM_TAG tag = TPM_TAG_RQU_COMMAND;
  25.920 +  UINT32 paramSize = 0;
  25.921 +  TPM_COMMAND_CODE ordinal = TPM_ORD_EvictKey;
  25.922 +  TPM_RESULT returnCode = TPM_SUCCESS;
  25.923 +  
  25.924 +  // setup the TPM driver input and output buffers
  25.925 +  TDDL_RESULT hRes = TDDL_E_FAIL;
  25.926 +  TDDL_UINT32  InLength = TCPA_MAX_BUFFER_LENGTH;
  25.927 +  TDDL_UINT32  OutLength = TCPA_MAX_BUFFER_LENGTH;
  25.928 +  
  25.929 +  // Convert Byte Input parameter in the input byte stream InBuf
  25.930 +  InLength = BSG_PackList(InBuf, 4, 
  25.931 +			  BSG_TPM_TAG, &tag, 
  25.932 +			  BSG_TYPE_UINT32, &paramSize, 
  25.933 +			  BSG_TPM_COMMAND_CODE, &ordinal, 
  25.934 +			  BSG_TYPE_UINT32, &hKey);
  25.935 +  // fill paramSize again as we now have the correct size
  25.936 +  BSG_Pack(BSG_TYPE_UINT32, &InLength, InBuf+2);
  25.937 +  
  25.938 +  vtpmloginfo(VTPM_LOG_TCS_DEEP, "Sending paramSize = %d\n", InLength);
  25.939 +  
  25.940 +  // call the TPM driver
  25.941 +  if ((hRes = TDDL_TransmitData(InBuf, InLength, OutBuf, &OutLength)) == TDDL_SUCCESS) {
  25.942 +    // unpack OutBuf to get the tag, paramSize, & returnCode
  25.943 +    BSG_UnpackList(OutBuf, 3, 
  25.944 +			   BSG_TPM_TAG, &tag, 
  25.945 +			   BSG_TYPE_UINT32, &paramSize, 
  25.946 +			   BSG_TPM_COMMAND_CODE, &returnCode);
  25.947 +    
  25.948 +    if (!DeleteHandleFromList((CONTEXT_HANDLE *)hContext, hKey)) {
  25.949 +      vtpmlogerror(VTPM_LOG_TCS, "KeyHandle not removed from list\n");
  25.950 +    }	 
  25.951 +    
  25.952 +    if (returnCode == TPM_SUCCESS && tag == TPM_TAG_RSP_COMMAND) {
  25.953 +      vtpmloginfo(VTPM_LOG_TCS_DEEP, "Received paramSize : %d\n", paramSize);
  25.954 +    } else {
  25.955 +      vtpmlogerror(VTPM_LOG_TCS, "TCSP_EvictKey Failed with return code %s\n", tpm_get_error_name(returnCode));
  25.956 +    }
  25.957 +  }
  25.958 +  
  25.959 +  return(returnCode);
  25.960 +}
  25.961 +
  25.962 +TPM_RESULT TCSP_GetRandom(TCS_CONTEXT_HANDLE hContext,  // in
  25.963 +			  UINT32*    bytesRequested, // in, out
  25.964 +			  BYTE**    randomBytes) // out
  25.965 +{
  25.966 +  // setup input/output parameters block
  25.967 +  TPM_TAG tag = TPM_TAG_RQU_COMMAND;
  25.968 +  UINT32 paramSize = 0;
  25.969 +  TPM_COMMAND_CODE ordinal = TPM_ORD_GetRandom;
  25.970 +  TPM_RESULT returnCode = TPM_SUCCESS;
  25.971 +  
  25.972 +  // setup the TPM driver input and output buffers
  25.973 +  TDDL_RESULT hRes = TDDL_E_FAIL;
  25.974 +  TDDL_UINT32  InLength = TCPA_MAX_BUFFER_LENGTH;
  25.975 +  TDDL_UINT32  OutLength = TCPA_MAX_BUFFER_LENGTH;
  25.976 +  
  25.977 +  // check input params
  25.978 +  if (bytesRequested == NULL || *randomBytes == NULL){
  25.979 +    return TPM_BAD_PARAMETER;
  25.980 +  }
  25.981 +  
  25.982 +  // Convert Byte Input parameter in the input byte stream InBuf
  25.983 +  InLength = BSG_PackList(InBuf, 4, 
  25.984 +			  BSG_TPM_TAG, &tag, 
  25.985 +			  BSG_TYPE_UINT32, &paramSize, 
  25.986 +			  BSG_TPM_COMMAND_CODE, &ordinal, 
  25.987 +			  BSG_TYPE_UINT32, bytesRequested);
  25.988 +  // fill paramSize again as we now have the correct size
  25.989 +  BSG_Pack(BSG_TYPE_UINT32, &InLength, InBuf+2);
  25.990 +  
  25.991 +  vtpmloginfo(VTPM_LOG_TCS_DEEP, "Sending paramSize = %d\n", InLength);
  25.992 +  
  25.993 +  // call the TPM driver
  25.994 +  if ((hRes = TDDL_TransmitData(InBuf, InLength, OutBuf, &OutLength)) == TDDL_SUCCESS) {
  25.995 +    // unpack OutBuf to get the tag, paramSize, & returnCode
  25.996 +    int i = BSG_UnpackList(OutBuf, 3, 
  25.997 +			   BSG_TPM_TAG, &tag, 
  25.998 +			   BSG_TYPE_UINT32, &paramSize, 
  25.999 +			   BSG_TPM_COMMAND_CODE, &returnCode);
 25.1000 +    
 25.1001 +    if (returnCode == TPM_SUCCESS && tag == TPM_TAG_RSP_COMMAND) {
 25.1002 +      // Extract the remaining output parameters
 25.1003 +      BSG_Unpack(BSG_TYPE_UINT32, OutBuf+i, bytesRequested);
 25.1004 +      if (TCS_Malloc(hContext, *bytesRequested, randomBytes) == TPM_FAIL) {
 25.1005 +        return TPM_SIZE;
 25.1006 +      }
 25.1007 +      memcpy(*randomBytes, OutBuf+i+sizeof(UINT32), *bytesRequested);
 25.1008 +      
 25.1009 +      vtpmloginfo(VTPM_LOG_TCS_DEEP, "Received paramSize : %d\n", paramSize);
 25.1010 +    } else {
 25.1011 +      vtpmlogerror(VTPM_LOG_TCS, "TCSP_GetRandom Failed with return code %s\n", tpm_get_error_name(returnCode));
 25.1012 +    }
 25.1013 +  }
 25.1014 +  
 25.1015 +  return(returnCode);
 25.1016 +}
 25.1017 +
 25.1018 +
 25.1019 +TPM_RESULT TCSP_ReadPubek(TCS_CONTEXT_HANDLE   hContext,               // in
 25.1020 +			  TPM_NONCE            antiReplay,             // in
 25.1021 +			  UINT32*              pubEndorsementKeySize,  // out
 25.1022 +			  BYTE**               pubEndorsementKey,      // out
 25.1023 +			  TPM_DIGEST*          checksum)               // out
 25.1024 +{
 25.1025 +  // setup input/output parameters block
 25.1026 +  TPM_TAG tag = TPM_TAG_RQU_COMMAND;
 25.1027 +  UINT32 paramSize = 0;
 25.1028 +  TPM_COMMAND_CODE ordinal = TPM_ORD_ReadPubek;
 25.1029 +  TPM_RESULT returnCode = TPM_SUCCESS;
 25.1030 +  
 25.1031 +  // setup the TPM driver input and output buffers
 25.1032 +  TDDL_RESULT hRes = TDDL_E_FAIL;
 25.1033 +  TDDL_UINT32  InLength = TCPA_MAX_BUFFER_LENGTH;
 25.1034 +  TDDL_UINT32   OutLength = TCPA_MAX_BUFFER_LENGTH;
 25.1035 +  
 25.1036 +  // check input params
 25.1037 +  if (pubEndorsementKeySize == NULL || pubEndorsementKey == NULL || checksum == NULL) {
 25.1038 +    return TPM_BAD_PARAMETER;
 25.1039 +  }
 25.1040 +  
 25.1041 +  // Convert Byte Input parameter in the input byte stream InBuf
 25.1042 +  InLength = BSG_PackList(InBuf, 4, 
 25.1043 +			  BSG_TPM_TAG, &tag, 
 25.1044 +			  BSG_TYPE_UINT32, &paramSize, 
 25.1045 +			  BSG_TPM_COMMAND_CODE, &ordinal, 
 25.1046 +			  BSG_TPM_NONCE, &antiReplay);
 25.1047 +  // fill paramSize again as we now have the correct size
 25.1048 +  BSG_Pack(BSG_TYPE_UINT32, &InLength, InBuf+2);
 25.1049 +  
 25.1050 +  vtpmloginfo(VTPM_LOG_TCS_DEEP, "Sending paramSize = %d\n", InLength);
 25.1051 +  
 25.1052 +  // call the TPM driver
 25.1053 +  if ((hRes = TDDL_TransmitData(InBuf, InLength, OutBuf, &OutLength)) == TDDL_SUCCESS) {
 25.1054 +    // unpack OutBuf to get the tag, paramSize, & returnCode
 25.1055 +    int i = BSG_UnpackList(OutBuf, 3, 
 25.1056 +			   BSG_TPM_TAG, &tag, 
 25.1057 +			   BSG_TYPE_UINT32, &paramSize, 
 25.1058 +			   BSG_TPM_COMMAND_CODE, &returnCode);
 25.1059 +    
 25.1060 +    if (returnCode == TPM_SUCCESS && tag == TPM_TAG_RSP_COMMAND) {
 25.1061 +      // Extract the remaining output parameters
 25.1062 +      TPM_PUBKEY pubEK;
 25.1063 +      i += BSG_UnpackList(OutBuf+i, 2, 
 25.1064 +			  BSG_TPM_PUBKEY, &pubEK, 
 25.1065 +			  BSG_TPM_DIGEST, checksum);
 25.1066 +      
 25.1067 +      // fill EndorsementKey
 25.1068 +      BYTE tempBuf[1024];
 25.1069 +      *pubEndorsementKeySize = BSG_Pack(BSG_TPM_PUBKEY, &pubEK, tempBuf);
 25.1070 +      if (TCS_Malloc(hContext, *pubEndorsementKeySize, pubEndorsementKey) == TPM_FAIL) {
 25.1071 +        return TPM_SIZE;
 25.1072 +      }
 25.1073 +      memcpy(*pubEndorsementKey, tempBuf, *pubEndorsementKeySize);
 25.1074 +      
 25.1075 +      vtpmloginfo(VTPM_LOG_TCS_DEEP, "Received paramSize : %d\n", paramSize);
 25.1076 +    } else {
 25.1077 +      vtpmlogerror(VTPM_LOG_TCS, "TCSP_ReadPubek Failed with return code %s\n", tpm_get_error_name(returnCode));
 25.1078 +    }
 25.1079 +  }
 25.1080 +  
 25.1081 +  return(returnCode);
 25.1082 +}
 25.1083 +
 25.1084 +TPM_RESULT TCSP_RawTransmitData(   UINT32 inDataSize,  // in
 25.1085 +				   BYTE *inData,       // in
 25.1086 +				   UINT32 *outDataSize,// in/out
 25.1087 +				   BYTE *outData) {    // out     
 25.1088 +  
 25.1089 +  TDDL_RESULT hRes;
 25.1090 +  
 25.1091 +  vtpmloginfo(VTPM_LOG_TCS, "Calling TransmitData directly.\n");
 25.1092 +  //FIXME: Add Context Management
 25.1093 +  hRes = TDDL_TransmitData( inData, 
 25.1094 +			    inDataSize, 
 25.1095 +			    outData, 
 25.1096 +			    outDataSize);
 25.1097 +  
 25.1098 +  if (hRes == TDDL_SUCCESS) {
 25.1099 +    return TPM_SUCCESS;
 25.1100 +  } else {
 25.1101 +    vtpmlogerror(VTPM_LOG_TCS, "TCSP_RawTransmitData Failed with return code %s\n", tpm_get_error_name(TPM_IOERROR));
 25.1102 +    return TPM_IOERROR;
 25.1103 +  }
 25.1104 +  
 25.1105 +}
    26.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    26.2 +++ b/tools/vtpm_manager/tcs/tcs.h	Tue Aug 30 11:39:25 2005 -0800
    26.3 @@ -0,0 +1,238 @@
    26.4 +// ===================================================================
    26.5 +// 
    26.6 +// Copyright (c) 2005, Intel Corp.
    26.7 +// All rights reserved.
    26.8 +//
    26.9 +// Redistribution and use in source and binary forms, with or without 
   26.10 +// modification, are permitted provided that the following conditions 
   26.11 +// are met:
   26.12 +//
   26.13 +//   * Redistributions of source code must retain the above copyright 
   26.14 +//     notice, this list of conditions and the following disclaimer.
   26.15 +//   * Redistributions in binary form must reproduce the above 
   26.16 +//     copyright notice, this list of conditions and the following 
   26.17 +//     disclaimer in the documentation and/or other materials provided 
   26.18 +//     with the distribution.
   26.19 +//   * Neither the name of Intel Corporation nor the names of its 
   26.20 +//     contributors may be used to endorse or promote products derived
   26.21 +//     from this software without specific prior written permission.
   26.22 +//
   26.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   26.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   26.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   26.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   26.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   26.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   26.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   26.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   26.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   26.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   26.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   26.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   26.35 +// ===================================================================
   26.36 +// 
   26.37 +// tcs.h
   26.38 +// 
   26.39 +//  This file declares the TCS API
   26.40 +// 
   26.41 +// ==================================================================
   26.42 +
   26.43 +#ifndef __TCS_H__
   26.44 +#define __TCS_H__
   26.45 +
   26.46 +#include "tcg.h"
   26.47 +#include "buffer.h"
   26.48 +
   26.49 +#define HANDLE_NULL 0
   26.50 +
   26.51 +// ------------------------------------------------------------------
   26.52 +// Exposed API
   26.53 +// ------------------------------------------------------------------
   26.54 +
   26.55 +TPM_RESULT TCS_create();
   26.56 +void TCS_destroy();
   26.57 +
   26.58 +TPM_RESULT TCS_OpenContext( /* OUT */ TCS_CONTEXT_HANDLE* hContext );
   26.59 +
   26.60 +TPM_RESULT TCS_CloseContext ( /* IN */ TCS_CONTEXT_HANDLE hContext );
   26.61 +
   26.62 +TPM_RESULT TCS_Malloc ( TCS_CONTEXT_HANDLE hContext, // in
   26.63 +			UINT32   MemSize, // in
   26.64 +			BYTE**   ppMemPtr ); //out
   26.65 +
   26.66 +TPM_RESULT TCS_FreeMemory ( TCS_CONTEXT_HANDLE hContext, // in
   26.67 +			    BYTE*    pMemory);  // in
   26.68 +
   26.69 +// ------------------------------------------------------------------
   26.70 +// Exposed API
   26.71 +// ------------------------------------------------------------------
   26.72 +
   26.73 +// TPM v1.1B Command Set
   26.74 +
   26.75 +// Authorzation
   26.76 +TPM_RESULT TCSP_OIAP( TCS_CONTEXT_HANDLE hContext, // in
   26.77 +		      TCS_AUTHHANDLE*  authHandle, // out 
   26.78 +		      TPM_NONCE*   nonce0  // out
   26.79 +		      );
   26.80 +
   26.81 +TPM_RESULT TCSP_OSAP (  TCS_CONTEXT_HANDLE hContext,  // in
   26.82 +			TPM_ENTITY_TYPE entityType,  // in
   26.83 +			UINT32    entityValue, // in
   26.84 +			TPM_NONCE   nonceOddOSAP, // in
   26.85 +			TCS_AUTHHANDLE*  authHandle,  // out 
   26.86 +			TPM_NONCE*   nonceEven,  // out
   26.87 +			TPM_NONCE*   nonceEvenOSAP // out
   26.88 +			);
   26.89 +
   26.90 +TPM_RESULT TCSP_TakeOwnership (  TCS_CONTEXT_HANDLE hContext,   // in
   26.91 +				 UINT16    protocolID,   // in
   26.92 +				 UINT32    encOwnerAuthSize, // in 
   26.93 +				 BYTE*    encOwnerAuth,  // in
   26.94 +				 UINT32    encSrkAuthSize,  // in
   26.95 +				 BYTE*    encSrkAuth,   // in
   26.96 +				 UINT32*    SrkSize,   // in, out
   26.97 +				 BYTE**    Srk,    // in, out
   26.98 +				 TCS_AUTH*   ownerAuth   // in, out
   26.99 +				 );
  26.100 +
  26.101 +TPM_RESULT TCSP_DisablePubekRead (  TCS_CONTEXT_HANDLE hContext, // in
  26.102 +                                    TCS_AUTH*   ownerAuth // in, out
  26.103 +                                    );
  26.104 +
  26.105 +TPM_RESULT TCSP_TerminateHandle (  TCS_CONTEXT_HANDLE hContext, // in
  26.106 +				   TCS_AUTHHANDLE  handle  // in
  26.107 +				   );
  26.108 +
  26.109 +TPM_RESULT TCSP_FlushSpecific (  TCS_CONTEXT_HANDLE hContext, // in
  26.110 +				 TCS_AUTHHANDLE  handle,  // in
  26.111 +				 TPM_RESOURCE_TYPE resourceType //in 
  26.112 +				 );
  26.113 +
  26.114 +// TPM Mandatory
  26.115 +TPM_RESULT TCSP_Extend (  TCS_CONTEXT_HANDLE hContext, // in
  26.116 +			  TPM_PCRINDEX  pcrNum,  // in
  26.117 +			  TPM_DIGEST   inDigest, // in
  26.118 +			  TPM_PCRVALUE*   outDigest // out
  26.119 +			  );
  26.120 +
  26.121 +TPM_RESULT TCSP_PcrRead (  TCS_CONTEXT_HANDLE hContext, // in
  26.122 +			   TPM_PCRINDEX  pcrNum,  // in
  26.123 +			   TPM_PCRVALUE*  outDigest // out
  26.124 +			   );
  26.125 +
  26.126 +TPM_RESULT TCSP_Quote (  TCS_CONTEXT_HANDLE hContext,  // in
  26.127 +			 TCS_KEY_HANDLE  keyHandle,  // in
  26.128 +			 TPM_NONCE   antiReplay,  // in
  26.129 +			 UINT32*    PcrDataSize, // in, out
  26.130 +			 BYTE**    PcrData,  // in, out
  26.131 +			 TCS_AUTH*   privAuth,  // in, out
  26.132 +			 UINT32*    sigSize,  // out
  26.133 +			 BYTE**    sig    // out
  26.134 +			 );
  26.135 +
  26.136 +TPM_RESULT TCSP_Seal (  TCS_CONTEXT_HANDLE hContext,  // in
  26.137 +			TCS_KEY_HANDLE  keyHandle,  // in
  26.138 +			TPM_ENCAUTH  encAuth,  // in
  26.139 +			UINT32    pcrInfoSize, // in
  26.140 +			BYTE*    PcrInfo,  // in
  26.141 +			UINT32    inDataSize,  // in
  26.142 +			BYTE*    inData,   // in
  26.143 +			TCS_AUTH*   pubAuth,  // in, out
  26.144 +			UINT32*    SealedDataSize, // out
  26.145 +			BYTE**    SealedData  // out
  26.146 +			);
  26.147 +
  26.148 +TPM_RESULT TCSP_Unseal (  TCS_CONTEXT_HANDLE hContext,  // in
  26.149 +			  TCS_KEY_HANDLE  parentHandle, // in
  26.150 +			  UINT32    SealedDataSize, // in
  26.151 +			  BYTE*    SealedData,  // in
  26.152 +			  TCS_AUTH*   parentAuth,  // in, out
  26.153 +			  TCS_AUTH*   dataAuth,  // in, out
  26.154 +			  UINT32*    DataSize,  // out
  26.155 +			  BYTE**    Data   // out
  26.156 +			  );
  26.157 +
  26.158 +TPM_RESULT TCSP_DirWriteAuth (  TCS_CONTEXT_HANDLE hContext,  // in
  26.159 +				TPM_DIRINDEX  dirIndex,  // in
  26.160 +				TPM_DIRVALUE  newContents, // in
  26.161 +				TCS_AUTH*   ownerAuth  // in, out
  26.162 +				);
  26.163 +
  26.164 +TPM_RESULT TCSP_DirRead (  TCS_CONTEXT_HANDLE hContext, // in
  26.165 +			   TPM_DIRINDEX  dirIndex, // in
  26.166 +			   TPM_DIRVALUE*  dirValue // out
  26.167 +			   );
  26.168 +
  26.169 +TPM_RESULT TCSP_UnBind (  TCS_CONTEXT_HANDLE hContext,  // in
  26.170 +			  TCS_KEY_HANDLE  keyHandle,  // in
  26.171 +			  UINT32    inDataSize,  // in
  26.172 +			  BYTE*    inData,   // in
  26.173 +			  TCS_AUTH*   privAuth,  // in, out
  26.174 +			  UINT32*    outDataSize, // out
  26.175 +			  BYTE**    outData   // out
  26.176 +			  );
  26.177 +
  26.178 +TPM_RESULT TCSP_CreateWrapKey (  TCS_CONTEXT_HANDLE hContext,   // in
  26.179 +				 TCS_KEY_HANDLE  hWrappingKey,  // in
  26.180 +				 TPM_ENCAUTH  KeyUsageAuth,  // in
  26.181 +				 TPM_ENCAUTH  KeyMigrationAuth, // in
  26.182 +				 UINT32*    pcKeySize,   // in, out
  26.183 +				 BYTE**    prgbKey,   // in, out
  26.184 +				 TCS_AUTH*   pAuth    // in, out
  26.185 +				 );
  26.186 +
  26.187 +TPM_RESULT TCSP_LoadKeyByBlob (  TCS_CONTEXT_HANDLE hContext,    // in
  26.188 +				 TCS_KEY_HANDLE  hUnwrappingKey,   // in
  26.189 +				 UINT32    cWrappedKeyBlobSize, // in
  26.190 +				 BYTE*    rgbWrappedKeyBlob,  // in
  26.191 +				 TCS_AUTH*   pAuth,     // in, out
  26.192 +				 TCS_KEY_HANDLE*  phKeyTCSI,    // out
  26.193 +				 TCS_KEY_HANDLE*  phKeyHMAC    // out
  26.194 +				 );
  26.195 +
  26.196 +TPM_RESULT TCSP_GetPubKey (  TCS_CONTEXT_HANDLE hContext,  // in
  26.197 +			     TCS_KEY_HANDLE  hKey,   // in
  26.198 +			     TCS_AUTH*   pAuth,   // in, out
  26.199 +			     UINT32*    pcPubKeySize, // out
  26.200 +			     BYTE**    prgbPubKey  // out
  26.201 +			     ); 
  26.202 +
  26.203 +TPM_RESULT TCSP_EvictKey (  TCS_CONTEXT_HANDLE hContext, // in
  26.204 +			    TCS_KEY_HANDLE  hKey  // in
  26.205 +			    );
  26.206 +
  26.207 +TPM_RESULT TCSP_Sign (  TCS_CONTEXT_HANDLE hContext,  // in
  26.208 +			TCS_KEY_HANDLE  keyHandle,  // in
  26.209 +			UINT32    areaToSignSize, // in
  26.210 +			BYTE*    areaToSign,  // in
  26.211 +			TCS_AUTH*   privAuth,  // in, out
  26.212 +			UINT32*    sigSize,  // out
  26.213 +			BYTE**    sig    // out
  26.214 +			);
  26.215 +
  26.216 +TPM_RESULT TCSP_GetRandom (  TCS_CONTEXT_HANDLE hContext,  // in
  26.217 +			     UINT32*    bytesRequested, // in, out
  26.218 +			     BYTE**    randomBytes  // out
  26.219 +			     );
  26.220 +
  26.221 +TPM_RESULT TCSP_StirRandom (  TCS_CONTEXT_HANDLE hContext, // in
  26.222 +			      UINT32    inDataSize, // in
  26.223 +			      BYTE*    inData  // in
  26.224 +			      );
  26.225 +
  26.226 +TPM_RESULT TCSP_ReadPubek (  TCS_CONTEXT_HANDLE hContext,    // in
  26.227 +			     TPM_NONCE   antiReplay,    // in
  26.228 +			     UINT32*    pubEndorsementKeySize, // out
  26.229 +			     BYTE**    pubEndorsementKey,  // out
  26.230 +			     TPM_DIGEST*  checksum    // out
  26.231 +			     );
  26.232 +
  26.233 +
  26.234 +// Non-Standard TCSP call to give direct access to TransmitData.
  26.235 +// Key and Auth Management is done before transfering command to TDDL.
  26.236 +TPM_RESULT TCSP_RawTransmitData(UINT32 inDataSize,  // in
  26.237 +				BYTE *inData,       // in
  26.238 +				UINT32 *outDataSize,// in/out
  26.239 +				BYTE *outData);     // out
  26.240 +
  26.241 +#endif //TCS_H
    27.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    27.2 +++ b/tools/vtpm_manager/tcs/tpmddl.h	Tue Aug 30 11:39:25 2005 -0800
    27.3 @@ -0,0 +1,69 @@
    27.4 +// ===================================================================
    27.5 +// 
    27.6 +// Copyright (c) 2005, Intel Corp.
    27.7 +// All rights reserved.
    27.8 +//
    27.9 +// Redistribution and use in source and binary forms, with or without 
   27.10 +// modification, are permitted provided that the following conditions 
   27.11 +// are met:
   27.12 +//
   27.13 +//   * Redistributions of source code must retain the above copyright 
   27.14 +//     notice, this list of conditions and the following disclaimer.
   27.15 +//   * Redistributions in binary form must reproduce the above 
   27.16 +//     copyright notice, this list of conditions and the following 
   27.17 +//     disclaimer in the documentation and/or other materials provided 
   27.18 +//     with the distribution.
   27.19 +//   * Neither the name of Intel Corporation nor the names of its 
   27.20 +//     contributors may be used to endorse or promote products derived
   27.21 +//     from this software without specific prior written permission.
   27.22 +//
   27.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   27.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   27.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   27.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   27.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   27.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   27.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   27.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   27.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   27.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   27.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   27.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   27.35 +// ===================================================================
   27.36 +// 
   27.37 +// tpmddl.c
   27.38 +// 
   27.39 +//  This file defines the TDDLI API
   27.40 +//
   27.41 +// ==================================================================
   27.42 +
   27.43 +#ifndef __TPMDDL_H__
   27.44 +#define __TPMDDL_H__
   27.45 +
   27.46 +#define TDDL_CAP_PROP_MANUFACTURER 0x0001
   27.47 +
   27.48 +#define TDDL_E_FAIL 1
   27.49 +#define TDDL_E_SUCCESS 0
   27.50 +#define TDDL_SUCCESS 0
   27.51 +
   27.52 +typedef unsigned int TDDL_UINT32;
   27.53 +typedef TDDL_UINT32 TDDL_RESULT;
   27.54 +typedef unsigned char TDDL_BYTE;
   27.55 +
   27.56 +TDDL_RESULT TDDL_Open();
   27.57 +void TDDL_Close();
   27.58 +TDDL_RESULT TDDL_TransmitData( TDDL_BYTE* in,
   27.59 +			       TDDL_UINT32 insize,
   27.60 +			       TDDL_BYTE* out,
   27.61 +			       TDDL_UINT32* outsize);
   27.62 +TDDL_RESULT TDDL_GetStatus();
   27.63 +TDDL_RESULT TDDL_GetCapability( TDDL_UINT32 cap,
   27.64 +				TDDL_UINT32 sub,
   27.65 +				TDDL_BYTE* buffer,
   27.66 +				TDDL_UINT32* size);
   27.67 +TDDL_RESULT TDDL_SetCapability( TDDL_UINT32 cap,
   27.68 +				TDDL_UINT32 sub,
   27.69 +				TDDL_BYTE* buffer,
   27.70 +				TDDL_UINT32* size);
   27.71 +
   27.72 +#endif // __TPMDDL_H__
    28.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    28.2 +++ b/tools/vtpm_manager/tcs/transmit.c	Tue Aug 30 11:39:25 2005 -0800
    28.3 @@ -0,0 +1,131 @@
    28.4 +// ===================================================================
    28.5 +// 
    28.6 +// Copyright (c) 2005, Intel Corp.
    28.7 +// All rights reserved.
    28.8 +//
    28.9 +// Redistribution and use in source and binary forms, with or without 
   28.10 +// modification, are permitted provided that the following conditions 
   28.11 +// are met:
   28.12 +//
   28.13 +//   * Redistributions of source code must retain the above copyright 
   28.14 +//     notice, this list of conditions and the following disclaimer.
   28.15 +//   * Redistributions in binary form must reproduce the above 
   28.16 +//     copyright notice, this list of conditions and the following 
   28.17 +//     disclaimer in the documentation and/or other materials provided 
   28.18 +//     with the distribution.
   28.19 +//   * Neither the name of Intel Corporation nor the names of its 
   28.20 +//     contributors may be used to endorse or promote products derived
   28.21 +//     from this software without specific prior written permission.
   28.22 +//
   28.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   28.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   28.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   28.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   28.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   28.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   28.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   28.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   28.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   28.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   28.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   28.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   28.35 +// ===================================================================
   28.36 +
   28.37 +#include <unistd.h>
   28.38 +#include <stdio.h>
   28.39 +#include <errno.h>
   28.40 +#include <fcntl.h>
   28.41 +
   28.42 +#include "tcg.h"
   28.43 +#include "buffer.h"
   28.44 +#include "log.h"
   28.45 +#include "tpmddl.h"
   28.46 +
   28.47 +// flag to track whether TDDL has been opened
   28.48 +static int g_TDDL_open = 0;
   28.49 +static int g_fd = -1;              // the fd to the TPM
   28.50 +
   28.51 +TPM_RESULT
   28.52 +TDDL_TransmitData( TDDL_BYTE* in,
   28.53 +		   TDDL_UINT32 insize,
   28.54 +		   TDDL_BYTE* out,
   28.55 +		   TDDL_UINT32* outsize) {
   28.56 +  TPM_RESULT status = TPM_SUCCESS;
   28.57 +  TDDL_UINT32 i;
   28.58 +  
   28.59 +  vtpmloginfo(VTPM_LOG_TXDATA, "Sending buffer = 0x");
   28.60 +  for(i = 0 ; i < insize ; i++) 
   28.61 +    vtpmloginfomore(VTPM_LOG_TXDATA, "%2.2x ", in[i]);
   28.62 +
   28.63 +  vtpmloginfomore(VTPM_LOG_TXDATA, "\n");
   28.64 +  
   28.65 +  ssize_t size = 0;
   28.66 +  int fd = g_fd;
   28.67 +  
   28.68 +  // send the request
   28.69 +  size = write (fd, in, insize);
   28.70 +  if (size < 0) {
   28.71 +    vtpmlogerror(VTPM_LOG_TXDATA, "write() failed");
   28.72 +    ERRORDIE (TPM_IOERROR);
   28.73 +  }
   28.74 +  else if ((TDDL_UINT32) size < insize) {
   28.75 +    vtpmlogerror(VTPM_LOG_TXDATA, "Wrote %d instead of %d bytes!\n", size, insize);
   28.76 +    // ... ?
   28.77 +  }
   28.78 +
   28.79 +  // read the response
   28.80 +  size = read (fd, out, TCPA_MAX_BUFFER_LENGTH);
   28.81 +  if (size < 0) {
   28.82 +    vtpmlogerror(VTPM_LOG_TXDATA, "read() failed");
   28.83 +    ERRORDIE (TPM_IOERROR);
   28.84 +  }
   28.85 +  
   28.86 +  vtpmloginfo(VTPM_LOG_TXDATA, "Receiving buffer = 0x");
   28.87 +  for(i = 0 ; i < size ; i++) 
   28.88 +    vtpmloginfomore(VTPM_LOG_TXDATA, "%2.2x ", out[i]);
   28.89 +
   28.90 +  vtpmloginfomore(VTPM_LOG_TXDATA, "\n");
   28.91 +
   28.92 +  *outsize = size;
   28.93 +  // close connection
   28.94 +  goto egress;
   28.95 +  
   28.96 + abort_egress:
   28.97 + egress:
   28.98 +  return status;
   28.99 +}
  28.100 +
  28.101 +TPM_RESULT TDDL_Open() {
  28.102 +  
  28.103 +  TDDL_RESULT status = TDDL_SUCCESS;
  28.104 +  int fd = -1;
  28.105 +  
  28.106 +  if (g_TDDL_open)
  28.107 +    return TPM_FAIL;
  28.108 +  
  28.109 +  fd = open ("/dev/tpm0", O_RDWR);
  28.110 +  if (fd < 0) {
  28.111 +    vtpmlogerror(VTPM_LOG_TXDATA, "TPM open failed");
  28.112 +    return TPM_IOERROR;
  28.113 +  }
  28.114 +  
  28.115 +  g_fd = fd;
  28.116 +  g_TDDL_open = 1;
  28.117 +  
  28.118 +  return status;
  28.119 +}
  28.120 +
  28.121 +void TDDL_Close() {
  28.122 +  if (! g_TDDL_open)
  28.123 +        return;
  28.124 +
  28.125 +  if (g_fd>= 0) {
  28.126 +    if (close(g_fd) < 0) 
  28.127 +      vtpmlogerror(VTPM_LOG_TXDATA, "closeing tpm failed");
  28.128 +    
  28.129 +    g_fd = -1;
  28.130 +  }
  28.131 +    
  28.132 +  g_TDDL_open = 0;
  28.133 +  
  28.134 +}
    29.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    29.2 +++ b/tools/vtpm_manager/util/Makefile	Tue Aug 30 11:39:25 2005 -0800
    29.3 @@ -0,0 +1,18 @@
    29.4 +XEN_ROOT = ../../..
    29.5 +include $(XEN_ROOT)/tools/vtpm_manager/Rules.mk
    29.6 +
    29.7 +BIN		= libTCGUtils.a
    29.8 +
    29.9 +all: build
   29.10 +
   29.11 +build: $(BIN)
   29.12 +
   29.13 +install: build
   29.14 +
   29.15 +clean:
   29.16 +	rm -f *.a *.so *.o *.rpm $(DEP_FILES)
   29.17 +
   29.18 +mrproper: clean
   29.19 +
   29.20 +$(BIN): $(OBJS)
   29.21 +	$(AR) rcs $(BIN) $(OBJS)
    30.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    30.2 +++ b/tools/vtpm_manager/util/bsg.c	Tue Aug 30 11:39:25 2005 -0800
    30.3 @@ -0,0 +1,830 @@
    30.4 +// ===================================================================
    30.5 +// 
    30.6 +// Copyright (c) 2005, Intel Corp.
    30.7 +// All rights reserved.
    30.8 +//
    30.9 +// Redistribution and use in source and binary forms, with or without 
   30.10 +// modification, are permitted provided that the following conditions 
   30.11 +// are met:
   30.12 +//
   30.13 +//   * Redistributions of source code must retain the above copyright 
   30.14 +//     notice, this list of conditions and the following disclaimer.
   30.15 +//   * Redistributions in binary form must reproduce the above 
   30.16 +//     copyright notice, this list of conditions and the following 
   30.17 +//     disclaimer in the documentation and/or other materials provided 
   30.18 +//     with the distribution.
   30.19 +//   * Neither the name of Intel Corporation nor the names of its 
   30.20 +//     contributors may be used to endorse or promote products derived
   30.21 +//     from this software without specific prior written permission.
   30.22 +//
   30.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   30.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   30.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   30.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   30.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   30.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   30.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   30.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   30.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   30.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   30.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   30.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   30.35 +// ===================================================================
   30.36 +// 
   30.37 +// bsg.cpp
   30.38 +// 
   30.39 +//  This file will handle all the TPM Byte Stream functions
   30.40 +// 
   30.41 +// ==================================================================
   30.42 +
   30.43 +#include <stdio.h>
   30.44 +#include <string.h>
   30.45 +#include <stdarg.h>
   30.46 +#include <malloc.h>
   30.47 +#include "tcg.h"
   30.48 +#include "crypto.h"
   30.49 +#include "bsg.h"
   30.50 +#include "log.h"
   30.51 +
   30.52 +static int g_log_recursion_level = 0;
   30.53 +
   30.54 +// a largest buffer size. if we get a buf size bigger than this when unpacking,
   30.55 +// will complain!
   30.56 +#define BSG_MAX_BUF_SIZE (1<<18)
   30.57 +
   30.58 +#define bsglog(fmt, ...) do { \
   30.59 +    int __i; \
   30.60 +    for (__i=0; __i < g_log_recursion_level; __i++) {		     \
   30.61 +      vtpmloginfomore (VTPM_LOG_BSG, "%s", "  ");			     \
   30.62 +    }								       \
   30.63 +    vtpmloginfomore (VTPM_LOG_BSG, fmt, __VA_ARGS__);			       \
   30.64 +  } while (0)
   30.65 +
   30.66 +
   30.67 +// FIXME:  trigger the selfcheck--need to use glibc hook to do this
   30.68 +//BOOL dummy1 = BSG_static_selfcheck();
   30.69 +
   30.70 +
   30.71 +// Interpretting Types
   30.72 +// -------------------
   30.73 +// 
   30.74 +// Incoming Types are composed of two parts {format, info} squished into a
   30.75 +// BSG_UINT32.  The first 4 bits is a format spec indicating what type of
   30.76 +// data it is.  If the first 4 bits are zero the info corresponds to a value in
   30.77 +// BSG_s_fmt[]. This is a structure whose composition is described in
   30.78 +// BSG_s_fmt[]. If the value is non-zero, info corresponds to the size of the
   30.79 +// data (in bytes) being passed in. For example a UINT32 being passed in would
   30.80 +// have a format of (__FMT_CONST | 4). If both, the format and info are zero,
   30.81 +// this is interpretted as the end of the structure, and the result is returned.
   30.82 +
   30.83 +// these flags are mutually exclusive, so I'll just make them
   30.84 +// format values which indicate the semantics of the 'info' part and the source
   30.85 +// data. The above description has been accordingly adjusted.
   30.86 +
   30.87 +// format values for determining what type of data the incoming type is
   30.88 +// it's a 4 bit value, occupying the high 4 bits
   30.89 +#define __FMT_CONST (1UL << 28) // Constant sized value
   30.90 +#define __FMT_DATA  (2UL << 28) // Believed to be raw data NOT {size,data}
   30.91 +#define __FMT_SIZE  (3UL << 28) // A size. Used in FMT_SIZE??_DATA.
   30.92 +#define __FMT_HSIZE (4UL << 28) // A number of handles
   30.93 +#define __FMT_PACKED (5UL << 28) // 'info' is unused; the source data consists
   30.94 +                                 // of {size32, data} but we're to pack only the
   30.95 +                                 // data as that is already packed, and so
   30.96 +                                 // can/must be unpacked without
   30.97 +                                 // explicitly reading it size
   30.98 +
   30.99 +#define __FMT_MASK  0x0FFFFFFFUL // this masks out the 4-bit format
  30.100 +#define __FMT_MASK_SIZE(type)   ((type) & __FMT_MASK)
  30.101 +#define __FMT_MASK_FORMAT(type) ((type) & (~__FMT_MASK))
  30.102 +
  30.103 +// constant (8/16/32-bits)
  30.104 +#define FMT_U8 (__FMT_CONST | 1UL)
  30.105 +#define FMT_U16 (__FMT_CONST | 2UL)
  30.106 +#define FMT_U32 (__FMT_CONST | 4UL)
  30.107 +
  30.108 +// const with a compiler-computed size
  30.109 +#define FMT_SIZEOF(type) (__FMT_CONST | sizeof(type))
  30.110 +
  30.111 +// other data (size bytes) 
  30.112 +// Used primarily for DIGESTS -> FMT_DATA(20)
  30.113 +#define FMT_DATA(size) (__FMT_DATA | ((BSG_UINT32) (size) & __FMT_MASK))
  30.114 +
  30.115 +// 16/32-bit size followed by N bytes of data
  30.116 +#define FMT_SIZE16_DATA (__FMT_SIZE | 2UL)
  30.117 +#define FMT_SIZE32_DATA (__FMT_SIZE | 4UL)
  30.118 +
  30.119 +// 16-bit size followed by N key handles
  30.120 +#define FMT_SIZE16_HANDLES (__FMT_HSIZE | 2UL)
  30.121 +
  30.122 +#define DIGEST_SIZE 20 
  30.123 +typedef BSG_UINT32 BSG_HANDLE;
  30.124 +
  30.125 +// TCPA_AUTH has 11 fields!
  30.126 +#define MAX_FIELDS 11
  30.127 +typedef struct BSG_Format
  30.128 +{
  30.129 +  BSG_Type type;
  30.130 +  const char* name;
  30.131 +  BSG_UINT32 fields[MAX_FIELDS + 1];
  30.132 +} BSG_Format;
  30.133 +
  30.134 +/*
  30.135 + * TCPA structure data formats
  30.136 + */
  30.137 +// this has to be manually kept in sync with the
  30.138 +// Type enum!! the static_selfcheck() function should be used regularly!
  30.139 +static BSG_Format s_fmt[] =
  30.140 +{
  30.141 +  {BSG_TYPE_UINT32, "BSG_TYPE_UINT32", {FMT_U32, 0}},
  30.142 +  {BSG_TYPE_UINT16, "BSG_TYPE_UINT16", {FMT_U16, 0}},
  30.143 +  {BSG_TYPE_BYTE, "BSG_TYPE_BYTE", {FMT_U8, 0}},
  30.144 +  {BSG_TYPE_BOOL, "BSG_TYPE_BOOL", {FMT_U8, 0}},
  30.145 +  {BSG_TPM_SIZE32_DATA, "BSG_TPM_SIZE32_DATA", {FMT_SIZE32_DATA, 0}},
  30.146 +  {BSG_TPM_TAG, "BSG_TPM_TAG", {FMT_SIZEOF(TPM_TAG), 0}},
  30.147 +  {BSG_TPM_HANDLE, "BSG_TPM_HANDLE", {FMT_SIZEOF(TPM_HANDLE), 0}},
  30.148 +  {BSG_TPM_RESULT, "BSG_TPM_RESULT", {FMT_SIZEOF(TPM_RESULT), 0}},
  30.149 +  {BSG_TPM_RESOURCE_TYPE, "BSG_TPM_RESOURCE_TYPE", {FMT_SIZEOF(TPM_RESOURCE_TYPE), 0}},
  30.150 +  {BSG_TPM_COMMAND_CODE, "BSG_TPM_COMMAND_CODE", {FMT_U32, 0}},
  30.151 +  {BSG_TPM_AUTH_DATA_USAGE, "BSG_TPM_AUTH_DATA_USAGE", {FMT_U8, 0}},
  30.152 +  {BSG_TPM_ALGORITHM_ID, "BSG_TPM_ALGORITHM_ID", {FMT_U32, 0}},
  30.153 +  {BSG_TPM_PROTOCOL_ID, "BSG_TPM_PROTOCOL_ID", {FMT_SIZEOF(TPM_PROTOCOL_ID), 0}},
  30.154 +  {BSG_TPM_KEY_USAGE, "BSG_TPM_KEY_USAGE", {FMT_U16, 0}},
  30.155 +  {BSG_TPM_ENC_SCHEME, "BSG_TPM_ENC_SCHEME", {FMT_U16, 0}},
  30.156 +  {BSG_TPM_SIG_SCHEME, "BSG_TPM_SIG_SCHEME", {FMT_U16, 0}},
  30.157 +  {BSG_TPM_MIGRATE_SCHEME, "BSG_TPM_MIGRATE_SCHEME", {FMT_U16, 0}},
  30.158 +  {BSG_TPM_KEY_FLAGS, "BSG_TPM_KEY_FLAGS", {FMT_U32, 0}},
  30.159 +    
  30.160 +  {BSG_TPM_AUTHDATA, "BSG_TPM_AUTHDATA", {FMT_DATA(DIGEST_SIZE), 0}},
  30.161 +  {BSG_TPM_SECRET, "BSG_TPM_SECRET", {BSG_TPM_AUTHDATA, 0}},
  30.162 +  {BSG_TPM_ENCAUTH, "BSG_TPM_ENCAUTH", {BSG_TPM_AUTHDATA, 0}},
  30.163 +  {BSG_TPM_PAYLOAD_TYPE, "BSG_TPM_PAYLOAD_TYPE", {FMT_SIZEOF(TPM_PAYLOAD_TYPE), 0}},
  30.164 +  
  30.165 +  {BSG_TPM_VERSION, "BSG_TPM_VERSION", {FMT_DATA(4), 0}}, // vers 1.2
  30.166 +  {BSG_TPM_DIGEST, "BSG_TPM_DIGEST", {FMT_DATA(DIGEST_SIZE), 0}},
  30.167 +  {BSG_TPM_COMPOSITE_HASH, "BSG_TPM_COMPOSITE_HASH", {BSG_TPM_DIGEST, 0}},
  30.168 +  {BSG_TPM_CHOSENID_HASH, "BSG_TPM_CHOSENID_HASH", {BSG_TPM_DIGEST, 0}},
  30.169 +  
  30.170 +  {BSG_TPM_NONCE, "BSG_TPM_NONCE", {FMT_DATA(DIGEST_SIZE), 0}},
  30.171 +  {BSG_TPM_KEY_HANDLE, "BSG_TPM_KEY_HANDLE", {FMT_SIZEOF(TPM_KEY_HANDLE), 0}},
  30.172 +  {BSG_TPM_KEY_HANDLE_LIST, "BSG_TPM_KEY_HANDLE_LIST",
  30.173 +   {FMT_SIZE16_HANDLES, 0}},
  30.174 +  
  30.175 +  {BSG_TPM_KEY_PARMS, "BSG_TPM_KEY_PARMS", {
  30.176 +      BSG_TPM_ALGORITHM_ID,
  30.177 +      BSG_TPM_ENC_SCHEME,
  30.178 +      BSG_TPM_SIG_SCHEME,
  30.179 +      FMT_SIZE32_DATA,
  30.180 +      0}},
  30.181 +  {BSG_TPM_RSA_KEY_PARMS, "BSG_TPM_RSA_KEY_PARMS", {
  30.182 +      FMT_U32, FMT_U32, FMT_SIZE32_DATA, 0}},
  30.183 +  {BSG_TPM_STORE_PUBKEY, "BSG_TPM_STORE_PUBKEY", {FMT_SIZE32_DATA, 0}},
  30.184 +  {BSG_TPM_PUBKEY, "BSG_TPM_PUBKEY", {BSG_TPM_KEY_PARMS, BSG_TPM_STORE_PUBKEY, 0}},
  30.185 +  {BSG_TPM_KEY, "BSG_TPM_KEY", {
  30.186 +      BSG_TPM_VERSION,
  30.187 +      BSG_TPM_KEY_USAGE,
  30.188 +      BSG_TPM_KEY_FLAGS,
  30.189 +      BSG_TPM_AUTH_DATA_USAGE,
  30.190 +      BSG_TPM_KEY_PARMS,
  30.191 +      FMT_SIZE32_DATA,        // the PCR_INFO
  30.192 +      BSG_TPM_STORE_PUBKEY,
  30.193 +      FMT_SIZE32_DATA,        // the encrypted part
  30.194 +      0}},
  30.195 +  
  30.196 +  {BSG_TPM_MIGRATIONKEYAUTH, "BSG_TPM_MIGRATIONKEYAUTH", {
  30.197 +      BSG_TPM_PUBKEY,
  30.198 +      BSG_TPM_MIGRATE_SCHEME,
  30.199 +      BSG_TPM_DIGEST, 0}},
  30.200 +  
  30.201 +  {BSG_TCPA_AUDIT_EVENT, "TCPA_AUDIT_EVENT", {
  30.202 +      BSG_TPM_COMMAND_CODE,
  30.203 +      BSG_TPM_RESULT, 0 }},
  30.204 +  
  30.205 +  {BSG_TCPA_EVENT_CERT, "TCPA_EVENT_CERT", {
  30.206 +      BSG_TPM_DIGEST,
  30.207 +      BSG_TPM_DIGEST,
  30.208 +      FMT_DATA(2),
  30.209 +      FMT_SIZE32_DATA, 0}},
  30.210 +  
  30.211 +  {BSG_TPM_PCR_SELECTION, "BSG_TPM_PCR_SELECTION", {FMT_SIZE16_DATA, 0} },
  30.212 +  {BSG_TPM_PCR_COMPOSITE, "BSG_TPM_PCR_COMPOSITE", { BSG_TPM_PCR_SELECTION,
  30.213 +						     FMT_SIZE32_DATA,
  30.214 +						     0} },
  30.215 +
  30.216 +  {BSG_TPM_PCR_INFO, "BSG_TPM_PCR_INFO", { BSG_TPM_PCR_SELECTION,
  30.217 +					   BSG_TPM_COMPOSITE_HASH, 
  30.218 +					   BSG_TPM_COMPOSITE_HASH,
  30.219 +					   0} },
  30.220 +  
  30.221 +  
  30.222 +  {BSG_TPM_STORED_DATA, "BSG_TPM_STORED_DATA", {
  30.223 +      BSG_TPM_VERSION,
  30.224 +      FMT_SIZE32_DATA,
  30.225 +      FMT_SIZE32_DATA,
  30.226 +      0}},
  30.227 +  {BSG_TPM_SYMMETRIC_KEY, "BSG_TPM_SYMMETRIC_KEY", {
  30.228 +      BSG_TPM_ALGORITHM_ID,
  30.229 +      BSG_TPM_ENC_SCHEME,
  30.230 +      FMT_SIZE16_DATA,
  30.231 +      0}},
  30.232 +  {BSG_TPM_STORE_PRIVKEY, "BSG_TPM_STORE_PRIVKEY", {FMT_SIZE32_DATA, 0}},
  30.233 +  {BSG_TPM_STORE_ASYMKEY, "BSG_TPM_STORE_ASYMKEY", {
  30.234 +      BSG_TPM_PAYLOAD_TYPE,
  30.235 +      BSG_TPM_SECRET,
  30.236 +      BSG_TPM_SECRET,
  30.237 +      BSG_TPM_DIGEST,
  30.238 +      BSG_TPM_STORE_PRIVKEY,
  30.239 +      0}},
  30.240 +  {BSG_TPM_MIGRATE_ASYMKEY, "BSG_TPM_MIGRATE_ASYMKEY", {
  30.241 +      BSG_TPM_PAYLOAD_TYPE,
  30.242 +      BSG_TPM_SECRET,
  30.243 +      BSG_TPM_DIGEST,
  30.244 +      FMT_U32,
  30.245 +      BSG_TPM_STORE_PRIVKEY,
  30.246 +      0}},
  30.247 +  
  30.248 +  {BSG_TPM_QUOTE_INFO, "BSG_TPM_QUOTE_INFO", {
  30.249 +      BSG_TPM_VERSION,
  30.250 +      FMT_DATA(4),
  30.251 +      BSG_TPM_COMPOSITE_HASH,
  30.252 +      BSG_TPM_NONCE,
  30.253 +      0}},
  30.254 +  
  30.255 +  {BSG_TPM_IDENTITY_CONTENTS, "BSG_TPM_IDENTITY_CONTENTS", {
  30.256 +      BSG_TPM_VERSION,
  30.257 +      FMT_U32,
  30.258 +      BSG_TPM_CHOSENID_HASH,
  30.259 +      BSG_TPM_PUBKEY,
  30.260 +      0}},
  30.261 +  
  30.262 +  {BSG_TPM_PCRVALUE, "BSG_TPM_PCRVALUE", {FMT_DATA(DIGEST_SIZE), 0}},
  30.263 +  
  30.264 +  {BSG_TCPA_PCR_FLAGS, "TCPA_PCR_FLAGS", {
  30.265 +      FMT_U8,
  30.266 +      FMT_U8,
  30.267 +      0}},
  30.268 +  
  30.269 +  {BSG_TCS_AUTH, "TCS_AUTH", {
  30.270 +      BSG_TYPE_UINT32, 
  30.271 +      BSG_TPM_NONCE, 
  30.272 +      BSG_TPM_NONCE, 
  30.273 +      BSG_TYPE_BOOL, 
  30.274 +      BSG_TPM_AUTHDATA, 
  30.275 +      0}},
  30.276 +  
  30.277 +  {BSG_TPM_KEY_NONSENSITIVE, "BSG_TPM_KEY_NONSENSITIVE", {
  30.278 +      BSG_TPM_VERSION,
  30.279 +      BSG_TPM_KEY_USAGE,
  30.280 +      BSG_TPM_KEY_FLAGS,
  30.281 +      BSG_TPM_AUTH_DATA_USAGE,
  30.282 +      BSG_TPM_KEY_PARMS,
  30.283 +      FMT_SIZE32_DATA,
  30.284 +      BSG_TPM_STORE_PUBKEY,
  30.285 +      0}},
  30.286 +  
  30.287 +  {BSG_PACKED, "BSG_PACKED", {
  30.288 +      __FMT_PACKED,
  30.289 +      0 }},
  30.290 +  
  30.291 +  {BSG_TYPE_MAX, "", {0}},
  30.292 +};
  30.293 +
  30.294 +
  30.295 +static const BSG_Format* find_format (BSG_Type t) {
  30.296 +  BSG_Format * f = s_fmt;
  30.297 +  
  30.298 +  if (t >= BSG_TYPE_MAX) {
  30.299 +    return NULL;
  30.300 +  }
  30.301 +  
  30.302 +  // WARNING: this depends on the enum and s_fmt[] array being in sync! make
  30.303 +  // sure to run the static_selfcheck() to make sure
  30.304 +  f = s_fmt + (t - BSG_TYPE_FIRST);
  30.305 +  
  30.306 +  return f;
  30.307 +}
  30.308 +
  30.309 +//
  30.310 +// a consistency-checking routine which can be run at compile time
  30.311 +// (ie. immediately after compilation)
  30.312 +//
  30.313 +// tasks:
  30.314 +// - verify that s_fmt has one entry per Type t, and that entry is at s_fmt[t]
  30.315 +//
  30.316 +// conditions:
  30.317 +// - need that s_fmt[0] is the first type listed in the Type enum! ie the first
  30.318 +//   Type has value 0, not 1
  30.319 +//
  30.320 +// FIXME: should have a function be passed in here which is called if the test
  30.321 +// fails. Then the caller can decide what to do: abort, notify, whatever
  30.322 +// 
  30.323 +BOOL BSG_static_selfcheck ()
  30.324 +{
  30.325 +  int i;
  30.326 +
  30.327 +  for (i=BSG_TYPE_FIRST; i <= BSG_TYPE_MAX; i++) {
  30.328 +    if (s_fmt[i - BSG_TYPE_FIRST].type != i) {
  30.329 +      bsglog ("%s\n", "BSG: static_selfcheck failed!\n");
  30.330 +      bsglog ("failure at %i, allegedly %s\n",
  30.331 +	      i, s_fmt[i - BSG_TYPE_FIRST].name);
  30.332 +      abort();
  30.333 +      return FALSE;
  30.334 +    }
  30.335 +  }
  30.336 +  
  30.337 +  bsglog ("%s\n", "BSG: static_selfcheck success!");
  30.338 +  return TRUE;
  30.339 +}
  30.340 +
  30.341 +
  30.342 +/**
  30.343 + * Flatten a TCPA structure into a buffer in big-endian format
  30.344 + * @type: TCPA structure type
  30.345 + * @src: (IN) TCPA structure (OUT) end of TCPA structure
  30.346 + * @dst: (OUT) flattened data
  30.347 + * Returns: Flattened size or -1 for unknown types
  30.348 + */
  30.349 +// make it so that it can just run through the whole process and return
  30.350 +// the packed size, without packing anything. this will be done if dst is NULL.
  30.351 +static int BSG_Pack_private(BSG_Type type, const BSG_BYTE** src, BSG_BYTE* dst)
  30.352 +{
  30.353 +  // check incoming parameters
  30.354 +  if (*src == NULL)
  30.355 +    return 0;
  30.356 +  
  30.357 +  const BSG_BYTE* s = *src;
  30.358 +  BSG_BYTE* d = dst;
  30.359 +  
  30.360 +  BSG_UINT32 size   = __FMT_MASK_SIZE(type);
  30.361 +  BSG_UINT32 format = __FMT_MASK_FORMAT(type);
  30.362 +  
  30.363 +  if (format == __FMT_CONST) // We are dealing with a fixed length value eg. UINT32
  30.364 +    {
  30.365 +      BSG_UINT32 val = 0;
  30.366 +      switch (size) {
  30.367 +      case 1: val = * (BYTE*) s; break;
  30.368 +      case 2: val = * (unsigned short*) s; break;
  30.369 +      case 4: val = * (BSG_UINT32*) s; break;
  30.370 +      }
  30.371 +      if (dst)
  30.372 +	BSG_PackConst(val, size, d);
  30.373 +
  30.374 +      s += size;
  30.375 +      d += size;
  30.376 +    } else if (format == __FMT_DATA) { // We are dealing with raw data. Not sure when
  30.377 +    // this is used.
  30.378 +    
  30.379 +      if (dst) {
  30.380 +        bsglog ("BSG: __FMT_DATA size %d, src %p, dst %p\n", size, s, d);
  30.381 +        memcpy(d, s, size);
  30.382 +      }
  30.383 +
  30.384 +      s += size;
  30.385 +      d += size;
  30.386 +  } else if (format == __FMT_SIZE || format == __FMT_HSIZE) { // It's a size, followed by that much data or handles
  30.387 +    
  30.388 +    BSG_UINT32 psize = 0;
  30.389 +    switch (size) {
  30.390 +    case 1: psize = * (BYTE*) s; break;
  30.391 +    case 2: psize = * (unsigned short*) s; break;
  30.392 +    case 4: psize = * (BSG_UINT32*) s; break;
  30.393 +    }
  30.394 +        
  30.395 +    if (dst)
  30.396 +      BSG_PackConst(psize, size, d);
  30.397 +
  30.398 +    s += size;
  30.399 +    d += size;
  30.400 +    
  30.401 +    // now 's' points to an address, so cast it to BSG_BYTE**
  30.402 +    const BSG_BYTE* pdata = * ((BSG_BYTE**) s);
  30.403 +    s += sizeof(BSG_BYTE*);
  30.404 +    
  30.405 +    if (format == __FMT_HSIZE) {// This is a list of psize Handles
  30.406 +      if (dst) {
  30.407 +	BSG_HANDLE* d2 = (BSG_HANDLE*) d;
  30.408 +	BSG_HANDLE* p2 = (BSG_HANDLE*) pdata;
  30.409 +	BSG_UINT32 i;
  30.410 +	for (i = 0; i < psize; i++) 
  30.411 +	  d2[i] = BSG_UnpackConst((BSG_BYTE*)(p2 + i), 4);
  30.412 +	
  30.413 +      }
  30.414 +      d += psize * sizeof(BSG_HANDLE);
  30.415 +    } else {// If it's not psize handles, it's psize data.
  30.416 +      if (psize > 0) {
  30.417 +	if (dst) {
  30.418 +	  bsglog ("BSG: __FMT_SIZE, size=%d, src=%p, dst=%p\n",
  30.419 +		  psize, pdata, d);
  30.420 +	  memcpy(d, pdata, psize);
  30.421 +	}
  30.422 +      }
  30.423 +      d += psize;
  30.424 +    }
  30.425 +  } else if (format == __FMT_PACKED) {
  30.426 +    // the source buffer is a pack_constbuf_t, which has a size and a
  30.427 +    // pointer. just copy the buffer value, the size is not included in the
  30.428 +    // output stream.
  30.429 +    pack_constbuf_t * buf = (pack_constbuf_t*) s;
  30.430 +    
  30.431 +    if (dst) {
  30.432 +      bsglog ("BSG: __FMT_PACKED, size=%d, src=%p, dst=%p\n",
  30.433 +	      buf->size, buf->data, d);
  30.434 +      memcpy(d, buf->data, buf->size);
  30.435 +    }
  30.436 +        
  30.437 +    s += buf->size;
  30.438 +    d += buf->size;
  30.439 +  } else if (format == 0) {// No flags are set. This is a structure & it should
  30.440 +                          // be looked up in the bsg_s_fmt[]
  30.441 +    
  30.442 +    const BSG_Format* x = find_format (type);
  30.443 +    if (x == NULL) {
  30.444 +      vtpmloginfo(VTPM_LOG_BSG, "BSG_Pack: cannot find type %d\n", type);
  30.445 +      return -1;
  30.446 +    }
  30.447 +    
  30.448 +    if (dst)
  30.449 +      bsglog ("BSG_Pack type %s\n", x->name);
  30.450 +    
  30.451 +    
  30.452 +    // iterate through the fields
  30.453 +    const BSG_UINT32* f = x->fields;
  30.454 +    for (; *f; f++) {
  30.455 +      int fsize;
  30.456 +      
  30.457 +      g_log_recursion_level++;
  30.458 +      fsize = BSG_Pack_private((BSG_Type) *f, &s, dst ? d : NULL);
  30.459 +      g_log_recursion_level--;
  30.460 +      
  30.461 +      if (fsize <= 0)
  30.462 +	return fsize;
  30.463 +      
  30.464 +      d += fsize;
  30.465 +    }
  30.466 +  } else {
  30.467 +    vtpmlogerror(VTPM_LOG_BSG, "BSG_Pack(): Unknown format %d\n", format);
  30.468 +    return -1;
  30.469 +  }
  30.470 +  
  30.471 +  *src = s;
  30.472 +  return (d - dst);
  30.473 +}
  30.474 +
  30.475 +/**
  30.476 + * Unflatten a TCPA structure from a buffer in big-endian format
  30.477 + * @type: TCPA structure type
  30.478 + * @src: flattened data
  30.479 + * @dst: (IN) TCPA structure (OUT) end of TCPA structure
  30.480 + * Returns: Flattened size
  30.481 + * Note: Returns flattened size NOT the unpacked structure size
  30.482 + */
  30.483 +static int BSG_Unpack_private(BSG_Type type, const BSG_BYTE* src, BSG_BYTE** dst) {
  30.484 +  // check incoming parameters
  30.485 +  if (src == NULL)
  30.486 +    return 0;
  30.487 +  
  30.488 +  
  30.489 +  const BSG_BYTE* s = src;
  30.490 +  BSG_BYTE* d = dst ? *dst:NULL;
  30.491 +  if (dst && !d)
  30.492 +    dst = NULL;
  30.493 +  
  30.494 +  BSG_UINT32 size = __FMT_MASK_SIZE(type);
  30.495 +  BSG_UINT32 format = __FMT_MASK_FORMAT(type);
  30.496 +  
  30.497 +  if (format == __FMT_CONST) {// We are dealing with a fixed length value ie. UINT32
  30.498 +
  30.499 +    BSG_UINT32 val = BSG_UnpackConst(s, size);
  30.500 +
  30.501 +    if (dst) {
  30.502 +      switch (size) {
  30.503 +      case 1: *(BYTE *) d = (BSG_BYTE) val; break;
  30.504 +      case 2: *(unsigned short*) d = (unsigned short) val; break;
  30.505 +      case 4: *(BSG_UINT32*) d = (BSG_UINT32) val; break;
  30.506 +      }
  30.507 +    }
  30.508 +
  30.509 +    s += size;
  30.510 +    d += size;
  30.511 +  } else if (format == __FMT_DATA) {// We are dealing with raw data. Not sure when this is used.
  30.512 +    if (dst)
  30.513 +      memcpy(d, s, size);
  30.514 +
  30.515 +    d += size;
  30.516 +    s += size;
  30.517 +  } else if (format == __FMT_SIZE || format == __FMT_HSIZE) {// It's a size, followed by that much data or handles
  30.518 +    
  30.519 +    BSG_UINT32 psize = BSG_UnpackConst(s, size);
  30.520 +    
  30.521 +    if (psize > BSG_MAX_BUF_SIZE) {
  30.522 +      vtpmlogerror(VTPM_LOG_BSG, "BSG_Unpack runs into var-sized data bigger than %u bytes!!\n",
  30.523 +	       BSG_MAX_BUF_SIZE);
  30.524 +      return -1;
  30.525 +    }
  30.526 +    
  30.527 +    if (dst) {
  30.528 +      switch (size) {
  30.529 +      case 1: *(BYTE *) d = (BSG_BYTE) psize; break;
  30.530 +      case 2: *(unsigned short*) d = (unsigned short) psize; break;
  30.531 +      case 4: *(BSG_UINT32*) d = (BSG_UINT32) psize; break;
  30.532 +      }
  30.533 +    }
  30.534 +
  30.535 +    s += size;
  30.536 +    d += size;
  30.537 +    
  30.538 +    BSG_BYTE* pdata = NULL;
  30.539 +    
  30.540 +    if (psize) {
  30.541 +      if (format == __FMT_HSIZE) { // This is a list of psize Handles
  30.542 +	if (dst) {
  30.543 +	  BSG_HANDLE* s2 = (BSG_HANDLE*) s;
  30.544 +	  pdata = (BSG_BYTE *)malloc(psize * sizeof(BSG_HANDLE));
  30.545 +          if (!pdata)
  30.546 +            return -1;
  30.547 +          
  30.548 +	  BSG_HANDLE* p2 = (BSG_HANDLE*) pdata;
  30.549 +	  BSG_UINT32 i;
  30.550 +	  for (i = 0; i < psize; i++) {
  30.551 +	    BSG_PackConst(s2[i], 4, (BSG_BYTE*)(p2 + i));
  30.552 +	  }
  30.553 +	}
  30.554 +	s += psize * sizeof(BSG_HANDLE);
  30.555 +      } else { // If it's not psize handles, it's psize data.
  30.556 +	if (dst) {
  30.557 +	  pdata = (BSG_BYTE *)malloc(sizeof(BSG_BYTE) * psize);
  30.558 +          if (!pdata)
  30.559 +            return -1;
  30.560 +	  memcpy(pdata, s, psize);
  30.561 +	}
  30.562 +	s += psize;
  30.563 +      }
  30.564 +    }
  30.565 +    if (dst)
  30.566 +      *(void**) d = pdata;
  30.567 +
  30.568 +    d += sizeof(void*);
  30.569 +  } else if (format == __FMT_PACKED) {
  30.570 +
  30.571 +    // this doesn't make sense for unpacking!
  30.572 +    vtpmlogerror(VTPM_LOG_BSG, "BSG_Unpack() called with format __FMT_PACKED. "
  30.573 +							   "This does not make sense\n");
  30.574 +    
  30.575 +    return -1;
  30.576 +  } else if (format == 0) {// No flags are set. This is a structure & it should
  30.577 +                          // be looked up in the bsg_s_fmt[]
  30.578 +
  30.579 +    const BSG_Format* x = find_format (type);
  30.580 +    if (x == NULL) {
  30.581 +      vtpmlogerror(VTPM_LOG_BSG, "BSG_Unpack: cannot find type %d\n", type);
  30.582 +      return -1;
  30.583 +    }
  30.584 +    
  30.585 +    const BSG_UINT32* f = x->fields;
  30.586 +    for (; *f; f++) {
  30.587 +      int fsize = BSG_Unpack_private((BSG_Type) *f, s, dst ? &d:NULL);
  30.588 +      if (fsize <= 0)
  30.589 +	return fsize;
  30.590 +      s += fsize;
  30.591 +    }
  30.592 +  }
  30.593 +
  30.594 +  if (dst)
  30.595 +    *dst = d;
  30.596 +  return (s - src);
  30.597 +}
  30.598 +
  30.599 +/**
  30.600 + * Free memory associated with unpacked TCPA structure
  30.601 + * @type: TCPA structure type
  30.602 + * @src: (IN) TCPA structure (OUT) end of TCPA structure
  30.603 + * Note: Destroy should be called on all structures created with Unpack
  30.604 + *       to ensure that any allocated memory is freed
  30.605 + */
  30.606 +static void BSG_Destroy_private(BSG_Type type, BSG_BYTE** src) {
  30.607 +  BSG_BYTE* s = *src;
  30.608 +  
  30.609 +  BSG_UINT32 size = __FMT_MASK_SIZE(type);
  30.610 +  BSG_UINT32 format = __FMT_MASK_FORMAT(type);
  30.611 +  
  30.612 +  if ((src == NULL) || (*src == NULL)) {
  30.613 +        vtpmlogerror(VTPM_LOG_BSG, "BSG_Destroy() called with NULL src\n");
  30.614 +    return;
  30.615 +  }
  30.616 +
  30.617 +  if (format == __FMT_CONST || format == __FMT_DATA)
  30.618 +    s += size;
  30.619 +  else if (format == __FMT_SIZE || format == __FMT_HSIZE) {
  30.620 +    s += size;
  30.621 +    BSG_BYTE* ptr = *(BSG_BYTE**) s;
  30.622 +    if (ptr)
  30.623 +      free(ptr);
  30.624 +    s += sizeof(void*);
  30.625 +  } else if (format == __FMT_PACKED) {
  30.626 +
  30.627 +    // this doesn't make sense for unpacking, hence also for Destroy()
  30.628 +    vtpmlogerror(VTPM_LOG_BSG, "BSG_Destroy() called with format __FMT_PACKED. "
  30.629 +							   "This does not make sense\n");
  30.630 +    
  30.631 +    return;
  30.632 +  } else if (format == 0) {
  30.633 +    const BSG_Format* x = find_format (type);
  30.634 +    if (x == NULL) {
  30.635 +      vtpmlogerror(VTPM_LOG_BSG, "BSG_Destroy: cannot find type %d\n", type);
  30.636 +      return;
  30.637 +    }
  30.638 +    
  30.639 +    const BSG_UINT32* f = x->fields;
  30.640 +    for (; *f; f++)
  30.641 +      BSG_Destroy_private((BSG_Type) *f, &s);
  30.642 +  }
  30.643 +
  30.644 +  *src = s;
  30.645 +}
  30.646 +
  30.647 +int BSG_Pack(BSG_Type type, const void* src, BSG_BYTE* dst)
  30.648 +{
  30.649 +  const BSG_BYTE* src2 = (const BSG_BYTE*) src;
  30.650 +  return BSG_Pack_private(type, &src2, dst);
  30.651 +}
  30.652 +
  30.653 +int BSG_Unpack(BSG_Type type, const BSG_BYTE* src, void* dst)
  30.654 +{
  30.655 +  BSG_BYTE* dst2 = (BSG_BYTE*) dst;
  30.656 +  return BSG_Unpack_private(type, src, dst ? &dst2:NULL);
  30.657 +}
  30.658 +
  30.659 +void BSG_Destroy(BSG_Type type, void* src)
  30.660 +{
  30.661 +  BSG_BYTE* src2 = (BSG_BYTE*) src;
  30.662 +  BSG_Destroy_private(type, &src2);
  30.663 +}
  30.664 +    
  30.665 +/**
  30.666 + * Pack a 8/16/32-bit constant into a buffer in big-endian format
  30.667 + * @val: constant value
  30.668 + * @size: constant size in bytes (1, 2, or 4)
  30.669 + * @dst: (OUT) buffer
  30.670 + */
  30.671 +void BSG_PackConst(BSG_UINT32 val, int size, BSG_BYTE* dst) {
  30.672 +  bsglog ("BSG: PackConst on %d of size %i into address %p\n", val, size, dst);
  30.673 +  
  30.674 +  switch (size) {
  30.675 +  case 4:
  30.676 +    dst[0] = (BSG_BYTE)((val >> 24) & 0xff);
  30.677 +    dst[1] = (BSG_BYTE)((val >> 16) & 0xff);
  30.678 +    dst[2] = (BSG_BYTE)((val >> 8) & 0xff);
  30.679 +    dst[3] = (BSG_BYTE)(val & 0xff);
  30.680 +    break;
  30.681 +  case 2:
  30.682 +    dst[0] = (BSG_BYTE)((val >> 8) & 0xff);
  30.683 +    dst[1] = (BSG_BYTE)(val & 0xff);
  30.684 +    break;
  30.685 +  case 1:
  30.686 +    dst[0] = (BSG_BYTE)(val & 0xff);
  30.687 +    break;
  30.688 +  }
  30.689 +}
  30.690 +
  30.691 +/**
  30.692 + * Unpack a 8/16/32-bit constant from a buffer in big-endian format
  30.693 + * @src: buffer
  30.694 + * @size: constant size in bytes (1, 2, or 4)
  30.695 + */
  30.696 +BSG_UINT32 BSG_UnpackConst(const BSG_BYTE* src, int size) {
  30.697 +  BSG_UINT32 val = 0;
  30.698 +  
  30.699 +  if (src == NULL) 
  30.700 +    return 0;
  30.701 +  
  30.702 +  switch (size) {
  30.703 +  case 4:
  30.704 +    val = (((BSG_UINT32) src[0]) << 24
  30.705 +	   | ((BSG_UINT32) src[1]) << 16
  30.706 +	   | ((BSG_UINT32) src[2]) << 8
  30.707 +	   | (BSG_UINT32) src[3]);
  30.708 +    break;
  30.709 +  case 2:
  30.710 +    val = (((BSG_UINT32) src[0]) << 8 | (BSG_UINT32) src[1]);
  30.711 +    break;
  30.712 +  case 1:
  30.713 +    val = (BSG_UINT32) src[0];
  30.714 +    break;
  30.715 +  }  
  30.716 +  return val;
  30.717 +}
  30.718 +
  30.719 +// Pack a list of parameters. Beware not to send values, but rather you must
  30.720 +// send a pointer to your values Instead. This includes UINT32's.
  30.721 +int BSG_PackList( BSG_BYTE* dst, int ParamCount, ... ) {
  30.722 +  int ParamNumber;
  30.723 +  BSG_Type format; 
  30.724 +  BSG_BYTE* val = NULL;
  30.725 +  int size=0;
  30.726 +  
  30.727 +  va_list paramList;
  30.728 +  va_start( paramList, ParamCount );
  30.729 +
  30.730 +  for( ParamNumber = 1; ParamNumber <= ParamCount; ParamNumber++) {
  30.731 +    //Strangeness with int is because gcc wanted an int rather than a enum of ints.
  30.732 +    format =  (BSG_Type) va_arg( paramList, int );
  30.733 +    val = va_arg( paramList, BSG_BYTE* );    
  30.734 +    size += BSG_Pack(format, val, dst == NULL ? NULL : dst + size);
  30.735 +  }
  30.736 +  
  30.737 +  va_end (paramList);
  30.738 +  
  30.739 +  return size;
  30.740 +}
  30.741 +
  30.742 +// Unpack a list of parameters. 
  30.743 +int BSG_UnpackList( const BSG_BYTE* src, int ParamCount, ... ) {
  30.744 +  int ParamNumber = 0;
  30.745 +  BSG_Type format; 
  30.746 +  BSG_BYTE* val = NULL;
  30.747 +  int size = 0;
  30.748 +  
  30.749 +  va_list paramList;
  30.750 +  va_start( paramList, ParamCount );
  30.751 +  
  30.752 +  for( ParamNumber = 1; ParamNumber <= ParamCount; ParamNumber++) {
  30.753 +    format = (BSG_Type) va_arg( paramList, int );
  30.754 +    val  = va_arg( paramList, BSG_BYTE* );
  30.755 +    
  30.756 +    size += BSG_Unpack(format, src + size, val);
  30.757 +  }
  30.758 +  
  30.759 +  va_end( paramList );   
  30.760 +  
  30.761 +  return size;
  30.762 +}
  30.763 +
  30.764 +// Destroy any memory allocated by calls to unpack 
  30.765 +void BSG_DestroyList(int ParamCount, ... ) {
  30.766 +  int ParamNumber = 0;
  30.767 +  BSG_Type argType; 
  30.768 +  BSG_BYTE* paramValue = NULL;
  30.769 +  
  30.770 +  va_list paramList;
  30.771 +  va_start( paramList, ParamCount );
  30.772 +  
  30.773 +  for( ParamNumber = 1; ParamNumber <= ParamCount; ParamNumber++) {
  30.774 +    argType = (BSG_Type) va_arg( paramList, int );
  30.775 +    paramValue  = va_arg( paramList, BSG_BYTE* );
  30.776 +    
  30.777 +    BSG_Destroy(argType, paramValue);
  30.778 +  }
  30.779 +  
  30.780 +  va_end( paramList );   
  30.781 +  
  30.782 +  return;
  30.783 +}
  30.784 +
  30.785 +
  30.786 +// and a tuple version
  30.787 +TPM_RESULT BSG_DestroyTuple (int numParams, pack_tuple_t params[]) {
  30.788 +  int i;
  30.789 +  
  30.790 +  for (i = 0; i < numParams; i++)
  30.791 +    BSG_Destroy (params[i].type, params[i].addr);
  30.792 +
  30.793 +  return TPM_SUCCESS;
  30.794 +}
  30.795 +
  30.796 +
  30.797 +//
  30.798 +// wrappers of Pack and PackList which malloc the ouput buffer. to be freed
  30.799 +// by the caller later
  30.800 +//
  30.801 +
  30.802 +int BSG_PackMalloc (BSG_Type type, const void* src, BSG_BYTE** o_dst) {
  30.803 +  int size = BSG_Pack (type, src, NULL);
  30.804 +  BSG_BYTE * dest = (BSG_BYTE*) malloc (size);
  30.805 +  if (dest == NULL)
  30.806 +    return -1;
  30.807 +
  30.808 +  size = BSG_Pack(type, src, dest);
  30.809 +  *o_dst = dest;
  30.810 +  return size;
  30.811 +}
  30.812 +
  30.813 +
  30.814 +
  30.815 +int BSG_PackListMalloc(BSG_BYTE** outBuffer, int ParamCount, ... ) {
  30.816 +  va_list args;
  30.817 +  int size;
  30.818 +  
  30.819 +  va_start (args, ParamCount);
  30.820 +  size = BSG_PackList (NULL, ParamCount, args);
  30.821 +  va_end (args);
  30.822 +  
  30.823 +  BSG_BYTE * dest = (BSG_BYTE*) malloc (size);
  30.824 +  if (dest == NULL)
  30.825 +    return -1;
  30.826 +
  30.827 +  va_start (args, ParamCount);
  30.828 +  size = BSG_PackList (dest, ParamCount, args);
  30.829 +  va_end (args);
  30.830 +  
  30.831 +  *outBuffer = dest;
  30.832 +  return size;
  30.833 +}
    31.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    31.2 +++ b/tools/vtpm_manager/util/bsg.h	Tue Aug 30 11:39:25 2005 -0800
    31.3 @@ -0,0 +1,166 @@
    31.4 +// ===================================================================
    31.5 +// 
    31.6 +// Copyright (c) 2005, Intel Corp.
    31.7 +// All rights reserved.
    31.8 +//
    31.9 +// Redistribution and use in source and binary forms, with or without 
   31.10 +// modification, are permitted provided that the following conditions 
   31.11 +// are met:
   31.12 +//
   31.13 +//   * Redistributions of source code must retain the above copyright 
   31.14 +//     notice, this list of conditions and the following disclaimer.
   31.15 +//   * Redistributions in binary form must reproduce the above 
   31.16 +//     copyright notice, this list of conditions and the following 
   31.17 +//     disclaimer in the documentation and/or other materials provided 
   31.18 +//     with the distribution.
   31.19 +//   * Neither the name of Intel Corporation nor the names of its 
   31.20 +//     contributors may be used to endorse or promote products derived
   31.21 +//     from this software without specific prior written permission.
   31.22 +//
   31.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   31.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   31.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   31.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   31.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   31.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   31.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   31.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   31.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   31.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   31.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   31.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   31.35 +// ===================================================================
   31.36 +// 
   31.37 +// bsg.h
   31.38 +// 
   31.39 +//  This file contains API's for the TPM Byte Stream functions
   31.40 +//
   31.41 +// ==================================================================
   31.42 +
   31.43 +#ifndef __BSG_H__
   31.44 +#define __BSG_H__
   31.45 +
   31.46 +#include <stdarg.h>
   31.47 +#include "buffer.h"
   31.48 +
   31.49 +typedef unsigned int BSG_UINT32;
   31.50 +typedef unsigned char BSG_BYTE;
   31.51 +
   31.52 +// forward decl
   31.53 +struct pack_const_tuple_t;
   31.54 +
   31.55 +struct pack_tuple_t;
   31.56 +
   31.57 +
   31.58 +/**
   31.59 + * Byte stream generator
   31.60 + */
   31.61 +// this has to be manually kept in sync with the
   31.62 +// s_fmt array!!
   31.63 +// but now we have a self-check function which can make sure things are well
   31.64 +// (if used!) 
   31.65 +typedef enum BSG_Type
   31.66 +{ 
   31.67 +  BSG_TYPE_FIRST = 1,
   31.68 +  BSG_TYPE_UINT32 = 1, // start at 1 so that Type 0 only serves as an
   31.69 +                       // unused/special value
   31.70 +  BSG_TYPE_UINT16,
   31.71 +  BSG_TYPE_BYTE,
   31.72 +  BSG_TYPE_BOOL,
   31.73 +  BSG_TPM_SIZE32_DATA,  // a 32 bit unsigned size, followed by
   31.74 +                        // a pointer to that much data. can pass a
   31.75 +                        // struct pack_buf_t as the param
   31.76 +  BSG_TPM_TAG,
   31.77 +  BSG_TPM_HANDLE,
   31.78 +  BSG_TPM_RESULT,
   31.79 +  BSG_TPM_RESOURCE_TYPE,
   31.80 +  BSG_TPM_COMMAND_CODE,
   31.81 +  BSG_TPM_AUTH_DATA_USAGE,
   31.82 +  BSG_TPM_ALGORITHM_ID,
   31.83 +  BSG_TPM_PROTOCOL_ID,
   31.84 +  BSG_TPM_KEY_USAGE,
   31.85 +  BSG_TPM_ENC_SCHEME,
   31.86 +  BSG_TPM_SIG_SCHEME,
   31.87 +  BSG_TPM_MIGRATE_SCHEME,
   31.88 +  BSG_TPM_KEY_FLAGS,
   31.89 +  BSG_TPM_AUTHDATA,
   31.90 +  BSG_TPM_SECRET,
   31.91 +  BSG_TPM_ENCAUTH,
   31.92 +  BSG_TPM_PAYLOAD_TYPE,
   31.93 +  
   31.94 +  BSG_TPM_VERSION,
   31.95 +  BSG_TPM_DIGEST,
   31.96 +  BSG_TPM_COMPOSITE_HASH,
   31.97 +  BSG_TPM_CHOSENID_HASH,
   31.98 +  BSG_TPM_NONCE,
   31.99 +  BSG_TPM_KEY_HANDLE,
  31.100 +  BSG_TPM_KEY_HANDLE_LIST,
  31.101 +  BSG_TPM_KEY_PARMS,
  31.102 +  BSG_TPM_RSA_KEY_PARMS,
  31.103 +  BSG_TPM_STORE_PUBKEY,
  31.104 +  BSG_TPM_PUBKEY,
  31.105 +  BSG_TPM_KEY,
  31.106 +  
  31.107 +  BSG_TPM_MIGRATIONKEYAUTH,
  31.108 +  BSG_TCPA_AUDIT_EVENT,
  31.109 +  BSG_TCPA_EVENT_CERT,
  31.110 +  BSG_TPM_PCR_SELECTION,
  31.111 +  BSG_TPM_PCR_COMPOSITE,
  31.112 +  BSG_TPM_PCR_INFO,
  31.113 +  BSG_TPM_STORED_DATA,
  31.114 +  BSG_TPM_SYMMETRIC_KEY,
  31.115 +  BSG_TPM_STORE_PRIVKEY,
  31.116 +  BSG_TPM_STORE_ASYMKEY,
  31.117 +  BSG_TPM_MIGRATE_ASYMKEY,
  31.118 +  BSG_TPM_QUOTE_INFO,
  31.119 +  BSG_TPM_IDENTITY_CONTENTS,
  31.120 +  BSG_TPM_PCRVALUE,
  31.121 +  BSG_TCPA_PCR_FLAGS,
  31.122 +  BSG_TCS_AUTH,
  31.123 +  
  31.124 +  // this is the BSG_TPM_KEY struct without the encData field
  31.125 +  BSG_TPM_KEY_NONSENSITIVE,
  31.126 +  
  31.127 +  BSG_PACKED,
  31.128 +  
  31.129 +  BSG_TYPE_MAX
  31.130 +} BSG_Type;
  31.131 +
  31.132 +struct pack_const_tuple_t {
  31.133 +  BSG_Type type;
  31.134 +  const void * addr;
  31.135 +};
  31.136 +
  31.137 +
  31.138 +typedef struct pack_tuple_t {
  31.139 +  BSG_Type type;
  31.140 +  void * addr;
  31.141 +} pack_tuple_t;
  31.142 +
  31.143 +int BSG_Pack(BSG_Type type, const void* src, BSG_BYTE* dst);
  31.144 +int BSG_Unpack(BSG_Type type, const BSG_BYTE* src, void* dst);
  31.145 +void BSG_Destroy(BSG_Type type, void* src);
  31.146 +
  31.147 +// wrappers of Pack and PackList which malloc the ouput buffer. to be freed
  31.148 +// by the caller later. returns size of allocated buffer, or -1 in case
  31.149 +// allocation failed
  31.150 +int BSG_PackMalloc (BSG_Type type, const void* src, BSG_BYTE** o_dst);
  31.151 +int BSG_PackListMalloc (BSG_BYTE** outBuffer, int ParamCount, ... );
  31.152 +
  31.153 +// a va_list version of PackList
  31.154 +int BSG_PackList(BSG_BYTE* outBuffer, int ParamCount, ... );
  31.155 +int BSG_UnpackList(const BSG_BYTE* inBuffer, int ParamCount, ... );
  31.156 +void BSG_DestroyList(int ParamCount, ... );
  31.157 +
  31.158 +// wrapper of PackList which uses a buffer_t
  31.159 +TPM_RESULT BSG_PackListBuf (buffer_t * o_buf, int ParamCount, ...);
  31.160 +
  31.161 +// and a tuple version
  31.162 +TPM_RESULT BSG_DestroyTuple (int numParams, pack_tuple_t params[]);
  31.163 +
  31.164 +void BSG_PackConst(BSG_UINT32 val, int size, BSG_BYTE* dst);
  31.165 +BSG_UINT32 BSG_UnpackConst(const BSG_BYTE* src, int size);
  31.166 +
  31.167 +BOOL BSG_static_selfcheck ();
  31.168 +
  31.169 +#endif
    32.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    32.2 +++ b/tools/vtpm_manager/util/buffer.c	Tue Aug 30 11:39:25 2005 -0800
    32.3 @@ -0,0 +1,213 @@
    32.4 +// ===================================================================
    32.5 +// 
    32.6 +// Copyright (c) 2005, Intel Corp.
    32.7 +// All rights reserved.
    32.8 +//
    32.9 +// Redistribution and use in source and binary forms, with or without 
   32.10 +// modification, are permitted provided that the following conditions 
   32.11 +// are met:
   32.12 +//
   32.13 +//   * Redistributions of source code must retain the above copyright 
   32.14 +//     notice, this list of conditions and the following disclaimer.
   32.15 +//   * Redistributions in binary form must reproduce the above 
   32.16 +//     copyright notice, this list of conditions and the following 
   32.17 +//     disclaimer in the documentation and/or other materials provided 
   32.18 +//     with the distribution.
   32.19 +//   * Neither the name of Intel Corporation nor the names of its 
   32.20 +//     contributors may be used to endorse or promote products derived
   32.21 +//     from this software without specific prior written permission.
   32.22 +//
   32.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   32.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   32.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   32.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   32.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   32.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   32.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   32.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   32.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   32.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   32.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   32.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   32.35 +// ===================================================================
   32.36 +
   32.37 +
   32.38 +#include <stdarg.h>
   32.39 +#include <string.h>
   32.40 +#include <stdlib.h>
   32.41 +#include <stdio.h>
   32.42 +#include <sys/param.h>
   32.43 +
   32.44 +#include "tcg.h"
   32.45 +#include "bsg.h"
   32.46 +#include "buffer.h"
   32.47 +
   32.48 +static TPM_RESULT buffer_priv_realloc (buffer_t * buf, tpm_size_t newsize);
   32.49 +
   32.50 +//
   32.51 +// buffer functions!
   32.52 +//
   32.53 +
   32.54 +TPM_RESULT buffer_init (buffer_t * buf, tpm_size_t initsize, const BYTE* initval) {
   32.55 +  if (initsize == 0) {
   32.56 +    memset(buf, 0, sizeof(*buf));
   32.57 +    return TPM_SUCCESS;
   32.58 +  }
   32.59 +  
   32.60 +  
   32.61 +  buf->bytes = (BYTE*) malloc (initsize);
   32.62 +  if (buf->bytes == NULL) 
   32.63 +    return TPM_RESOURCES;
   32.64 +  
   32.65 +  buf->size = initsize;
   32.66 +  buf->alloc_size = initsize;
   32.67 +  
   32.68 +  if (initval)
   32.69 +    memcpy (buf->bytes, initval, initsize);
   32.70 +  
   32.71 +  buf->is_owner = TRUE;
   32.72 +  
   32.73 +  return TPM_SUCCESS;
   32.74 +}
   32.75 +
   32.76 +TPM_RESULT buffer_init_convert (buffer_t * buf, tpm_size_t initsize, BYTE* initval) {
   32.77 +  
   32.78 +  buf->size = initsize;
   32.79 +  buf->alloc_size = initsize;
   32.80 +  buf->bytes = initval;
   32.81 +  
   32.82 +  buf->is_owner = TRUE;
   32.83 +  
   32.84 +  return TPM_SUCCESS;
   32.85 +}
   32.86 +
   32.87 +TPM_RESULT buffer_init_copy (buffer_t * buf, const buffer_t * src) {
   32.88 +  TPM_RESULT status = buffer_init (buf, src->size, src->bytes);
   32.89 +  buf->is_owner = TRUE;
   32.90 +  
   32.91 +  return status;
   32.92 +}
   32.93 +
   32.94 +
   32.95 +
   32.96 +// make an alias to a constant array
   32.97 +TPM_RESULT buffer_init_const (buffer_t * buf, tpm_size_t size, const BYTE* val) {
   32.98 +  // TODO: try to enforce the const things somehow!
   32.99 +  buf->bytes = (BYTE*) val;
  32.100 +  buf->size = size;
  32.101 +  buf->alloc_size = 0;        // this field is now unneeded
  32.102 +  
  32.103 +  buf->is_owner = FALSE;
  32.104 +  
  32.105 +  return TPM_SUCCESS;
  32.106 +}
  32.107 +
  32.108 +// make an alias into buf, with given offset and length
  32.109 +// if len = 0, make the alias go to the end of buf
  32.110 +TPM_RESULT buffer_init_alias (buffer_t * buf, const buffer_t * b,
  32.111 +                              tpm_size_t offset, tpm_size_t len) {
  32.112 +  if (offset + len > b->size) {
  32.113 +    return TPM_NOSPACE;
  32.114 +  }
  32.115 +  
  32.116 +  buf->bytes = b->bytes + offset;
  32.117 +  buf->size = len > 0 ? len : b->size - offset;
  32.118 +  
  32.119 +  //VS/ buf->alloc_size = 0;
  32.120 +  if (len ==0)
  32.121 +    buf->alloc_size = b->alloc_size - offset;
  32.122 +  else 
  32.123 +    buf->alloc_size = MIN(b->alloc_size - offset, len);
  32.124 +  
  32.125 +        
  32.126 +  buf->is_owner = FALSE;
  32.127 +  
  32.128 +  return TPM_SUCCESS;
  32.129 +}
  32.130 +    
  32.131 +
  32.132 +// copy into the start of dest
  32.133 +TPM_RESULT buffer_copy (buffer_t * dest, const buffer_t* src)
  32.134 +{
  32.135 +  TPM_RESULT status = TPM_SUCCESS;
  32.136 +    
  32.137 +  if (dest->alloc_size < src->size) {  
  32.138 +    status = buffer_priv_realloc (dest, src->size);
  32.139 +    STATUSCHECK (status);
  32.140 +  }
  32.141 +  
  32.142 +  memcpy (dest->bytes, src->bytes, src->size);
  32.143 +  dest->size = src->size;
  32.144 +  
  32.145 +  //VS/ dest->is_owner = TRUE;
  32.146 +  
  32.147 + abort_egress:
  32.148 +
  32.149 +  return status;
  32.150 +}
  32.151 +
  32.152 +
  32.153 +
  32.154 +BOOL buffer_eq (const buffer_t * a, const buffer_t * b) {
  32.155 +  return (a->size == b->size && memcmp (a->bytes, b->bytes, a->size) == 0);
  32.156 +}
  32.157 +
  32.158 +
  32.159 +void buffer_memset (buffer_t * buf, BYTE b) {
  32.160 +  memset (buf->bytes, b, buf->size);
  32.161 +}
  32.162 +
  32.163 +
  32.164 +TPM_RESULT buffer_append_raw (buffer_t * buf, tpm_size_t len, const BYTE* bytes) {
  32.165 +  TPM_RESULT status = TPM_SUCCESS;
  32.166 +  
  32.167 +  if (buf->alloc_size < buf->size + len) {
  32.168 +    status = buffer_priv_realloc (buf, buf->size + len);
  32.169 +    STATUSCHECK (status);
  32.170 +  }
  32.171 +  
  32.172 +  memcpy (buf->bytes + buf->size, bytes, len);
  32.173 +  
  32.174 +  buf->size += len;
  32.175 +  
  32.176 +  goto egress;
  32.177 +  
  32.178 + abort_egress:
  32.179 +  
  32.180 + egress:
  32.181 +  
  32.182 +  return status;
  32.183 +}
  32.184 +
  32.185 +tpm_size_t buffer_len (const buffer_t* buf) {
  32.186 +  return buf->size;
  32.187 +}
  32.188 +
  32.189 +TPM_RESULT buffer_free (buffer_t * buf) {
  32.190 +  if (buf && buf->is_owner && buf->bytes != NULL) {
  32.191 +    free (buf->bytes);
  32.192 +    buf->bytes = NULL;
  32.193 +  }
  32.194 +  
  32.195 +  return TPM_SUCCESS;
  32.196 +}
  32.197 +
  32.198 +TPM_RESULT buffer_priv_realloc (buffer_t * buf, tpm_size_t newsize) {
  32.199 +  
  32.200 +  // we want to realloc to twice the size, or the new size, whichever
  32.201 +  // bigger
  32.202 +  
  32.203 +  BYTE * tmpbuf = NULL;
  32.204 +  
  32.205 +  newsize = MAX (buf->alloc_size * 2, newsize);
  32.206 +  
  32.207 +  tmpbuf = (BYTE*) realloc (buf->bytes, newsize);
  32.208 +  if (tmpbuf == NULL) 
  32.209 +    return TPM_SIZE;
  32.210 +  
  32.211 +  
  32.212 +  buf->bytes = tmpbuf;
  32.213 +  buf->alloc_size = newsize;
  32.214 +  
  32.215 +  return TPM_SUCCESS;
  32.216 +}
    33.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    33.2 +++ b/tools/vtpm_manager/util/buffer.h	Tue Aug 30 11:39:25 2005 -0800
    33.3 @@ -0,0 +1,103 @@
    33.4 +// ===================================================================
    33.5 +// 
    33.6 +// Copyright (c) 2005, Intel Corp.
    33.7 +// All rights reserved.
    33.8 +//
    33.9 +// Redistribution and use in source and binary forms, with or without 
   33.10 +// modification, are permitted provided that the following conditions 
   33.11 +// are met:
   33.12 +//
   33.13 +//   * Redistributions of source code must retain the above copyright 
   33.14 +//     notice, this list of conditions and the following disclaimer.
   33.15 +//   * Redistributions in binary form must reproduce the above 
   33.16 +//     copyright notice, this list of conditions and the following 
   33.17 +//     disclaimer in the documentation and/or other materials provided 
   33.18 +//     with the distribution.
   33.19 +//   * Neither the name of Intel Corporation nor the names of its 
   33.20 +//     contributors may be used to endorse or promote products derived
   33.21 +//     from this software without specific prior written permission.
   33.22 +//
   33.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   33.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   33.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   33.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   33.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   33.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   33.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   33.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   33.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   33.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   33.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   33.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   33.35 +// ===================================================================
   33.36 +
   33.37 +#ifndef __VTPM_BUFFER_H__
   33.38 +#define __VTPM_BUFFER_H__
   33.39 +
   33.40 +#include <stddef.h>             // for pointer NULL
   33.41 +#include "tcg.h"
   33.42 +
   33.43 +// structure to enable use of FMT_SIZE32_DATA in BSG_Unpack
   33.44 +typedef struct pack_buf_t {
   33.45 +  UINT32 size;
   33.46 +  BYTE * data;
   33.47 +} pack_buf_t;
   33.48 +
   33.49 +// and a const version for Pack
   33.50 +typedef struct pack_constbuf_t {
   33.51 +  UINT32 size;
   33.52 +  const BYTE* data;
   33.53 +} pack_constbuf_t;
   33.54 +
   33.55 +typedef UINT32 tpm_size_t;
   33.56 +
   33.57 +// first version, probably will be expanded...
   33.58 +
   33.59 +#define NULL_BUF {0,0,0,0}
   33.60 +
   33.61 +typedef struct {
   33.62 +  // private!!
   33.63 +  tpm_size_t size, alloc_size;
   33.64 +  BYTE * bytes;
   33.65 +  
   33.66 +  BOOL is_owner;              // do we own this buffer, and need to free it?
   33.67 +} buffer_t;
   33.68 +
   33.69 +// allocate the buffer if initsize > 0, copying over initval if provided
   33.70 +TPM_RESULT buffer_init (buffer_t * buf,
   33.71 +                        tpm_size_t initsize,
   33.72 +                        const BYTE* initval);
   33.73 +
   33.74 +// Create a new buffer from a BYTE *. Use buffer_free to destroy original BYTE *
   33.75 +TPM_RESULT buffer_init_convert (buffer_t * buf, 
   33.76 +                                tpm_size_t initsize, 
   33.77 +                                BYTE* initval);
   33.78 +
   33.79 +// make an alias to a constant array, no copying
   33.80 +TPM_RESULT buffer_init_const (buffer_t * buf, tpm_size_t size, const BYTE* val);
   33.81 +
   33.82 +// make an alias into buf, with given offset and length
   33.83 +// if len = 0, make the alias go to the end of buf
   33.84 +TPM_RESULT buffer_init_alias (buffer_t * buf, const buffer_t * b,
   33.85 +                              tpm_size_t offset, tpm_size_t);
   33.86 +
   33.87 +// "copy constructor"
   33.88 +TPM_RESULT buffer_init_copy (buffer_t * buf, const buffer_t * src);
   33.89 +
   33.90 +
   33.91 +// copy into the start of a
   33.92 +TPM_RESULT buffer_copy (buffer_t * dest, const buffer_t* src);
   33.93 +
   33.94 +// are they equal?
   33.95 +BOOL buffer_eq (const buffer_t * a, const buffer_t * b);
   33.96 +
   33.97 +// set the buffer to a constant byte
   33.98 +void buffer_memset (buffer_t * buf, BYTE b);
   33.99 +
  33.100 +tpm_size_t buffer_len (const buffer_t* buf);
  33.101 +
  33.102 +TPM_RESULT buffer_free (buffer_t * buf);
  33.103 +
  33.104 +TPM_RESULT buffer_append_raw (buffer_t * buf, tpm_size_t len, const BYTE* bytes);
  33.105 +
  33.106 +#endif // _TOOLS_H_
    34.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    34.2 +++ b/tools/vtpm_manager/util/depend	Tue Aug 30 11:39:25 2005 -0800
    34.3 @@ -0,0 +1,7 @@
    34.4 +hashtable.o: hashtable.c hashtable.h hashtable_private.h
    34.5 +hashtable_itr.o: hashtable_itr.c hashtable.h hashtable_private.h \
    34.6 +  hashtable_itr.h
    34.7 +bsg.o: bsg.c tcg.h ../crypto/crypto.h ../crypto/sym_crypto.h buffer.h \
    34.8 +  bsg.h log.h
    34.9 +log.o: log.c buffer.h tcg.h
   34.10 +buffer.o: buffer.c tcg.h bsg.h buffer.h
    35.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    35.2 +++ b/tools/vtpm_manager/util/hashtable.c	Tue Aug 30 11:39:25 2005 -0800
    35.3 @@ -0,0 +1,310 @@
    35.4 +/*
    35.5 + * Copyright (c) 2005, Intel Corp
    35.6 + * Copyright (c) 2002, Christopher Clark <firstname.lastname@cl.cam.ac.uk> 
    35.7 + * All rights reserved.
    35.8 + * 
    35.9 + * Redistribution and use in source and binary forms, with or without
   35.10 + * modification, are permitted provided that the following conditions
   35.11 + * are met:
   35.12 + * 
   35.13 + * * Redistributions of source code must retain the above copyright
   35.14 + * notice, this list of conditions and the following disclaimer.
   35.15 + * 
   35.16 + * * Redistributions in binary form must reproduce the above copyright
   35.17 + * notice, this list of conditions and the following disclaimer in the
   35.18 + * documentation and/or other materials provided with the distribution.
   35.19 + * 
   35.20 + * * Neither the name of the original author; nor the names of any contributors
   35.21 + * may be used to endorse or promote products derived from this software
   35.22 + * without specific prior written permission.
   35.23 + * 
   35.24 + * 
   35.25 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   35.26 + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   35.27 + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   35.28 + * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER
   35.29 + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   35.30 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   35.31 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   35.32 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   35.33 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   35.34 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   35.35 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   35.36 +*/
   35.37 +
   35.38 +#include "hashtable.h"
   35.39 +#include "hashtable_private.h"
   35.40 +#include <stdlib.h>
   35.41 +#include <stdio.h>
   35.42 +#include <string.h>
   35.43 +#include <math.h>
   35.44 +
   35.45 +/*
   35.46 +Credit for primes table: Aaron Krowne
   35.47 + http://br.endernet.org/~akrowne/
   35.48 + http://planetmath.org/encyclopedia/GoodHashTablePrimes.html
   35.49 +*/
   35.50 +static const unsigned int primes[] = {
   35.51 +53, 97, 193, 389,
   35.52 +769, 1543, 3079, 6151,
   35.53 +12289, 24593, 49157, 98317,
   35.54 +196613, 393241, 786433, 1572869,
   35.55 +3145739, 6291469, 12582917, 25165843,
   35.56 +50331653, 100663319, 201326611, 402653189,
   35.57 +805306457, 1610612741
   35.58 +};
   35.59 +const unsigned int prime_table_length = sizeof(primes)/sizeof(primes[0]);
   35.60 +const float max_load_factor = 0.65;
   35.61 +
   35.62 +/*****************************************************************************/
   35.63 +struct hashtable *
   35.64 +create_hashtable(unsigned int minsize,
   35.65 +                 unsigned int (*hashf) (void*),
   35.66 +                 int (*eqf) (void*,void*))
   35.67 +{
   35.68 +    struct hashtable *h;
   35.69 +    unsigned int pindex, size = primes[0];
   35.70 +    /* Check requested hashtable isn't too large */
   35.71 +    if (minsize > (1u << 30)) return NULL;
   35.72 +    /* Enforce size as prime */
   35.73 +    for (pindex=0; pindex < prime_table_length; pindex++) {
   35.74 +        if (primes[pindex] > minsize) { size = primes[pindex]; break; }
   35.75 +    }
   35.76 +    h = (struct hashtable *)malloc(sizeof(struct hashtable));
   35.77 +    if (NULL == h) return NULL; /*oom*/
   35.78 +    h->table = (struct entry **)malloc(sizeof(struct entry*) * size);
   35.79 +    if (NULL == h->table) { free(h); return NULL; } /*oom*/
   35.80 +    memset(h->table, 0, size * sizeof(struct entry *));
   35.81 +    h->tablelength  = size;
   35.82 +    h->primeindex   = pindex;
   35.83 +    h->entrycount   = 0;
   35.84 +    h->hashfn       = hashf;
   35.85 +    h->eqfn         = eqf;
   35.86 +    h->loadlimit    = (unsigned int) ceil(size * max_load_factor);
   35.87 +#ifdef HASHTABLE_THREADED    
   35.88 +    pthread_mutex_init(&h->mutex, NULL);
   35.89 +#endif
   35.90 +    return h;
   35.91 +}
   35.92 +
   35.93 +/*****************************************************************************/
   35.94 +unsigned int
   35.95 +hash(struct hashtable *h, void *k)
   35.96 +{
   35.97 +    unsigned int i = h->hashfn(k);
   35.98 +    i += ~(i << 9);
   35.99 +    i ^=  ((i >> 14) | (i << 18)); /* >>> */
  35.100 +    i +=  (i << 4);
  35.101 +    i ^=  ((i >> 10) | (i << 22)); /* >>> */
  35.102 +    return i;
  35.103 +}
  35.104 +
  35.105 +/*****************************************************************************/
  35.106 +static int
  35.107 +hashtable_expand(struct hashtable *h)
  35.108 +{
  35.109 +    /* Double the size of the table to accomodate more entries */
  35.110 +    struct entry **newtable;
  35.111 +    struct entry *e;
  35.112 +    struct entry **pE;
  35.113 +    unsigned int newsize, i, index;
  35.114 +    /* Check we're not hitting max capacity */
  35.115 +    if (h->primeindex == (prime_table_length - 1)) return 0;
  35.116 +    newsize = primes[++(h->primeindex)];
  35.117 +
  35.118 +    newtable = (struct entry **)malloc(sizeof(struct entry*) * newsize);
  35.119 +    if (NULL != newtable)
  35.120 +    {
  35.121 +        memset(newtable, 0, newsize * sizeof(struct entry *));
  35.122 +        /* This algorithm is not 'stable'. ie. it reverses the list
  35.123 +         * when it transfers entries between the tables */
  35.124 +        for (i = 0; i < h->tablelength; i++) {
  35.125 +            while (NULL != (e = h->table[i])) {
  35.126 +                h->table[i] = e->next;
  35.127 +                index = indexFor(newsize,e->h);
  35.128 +                e->next = newtable[index];
  35.129 +                newtable[index] = e;
  35.130 +            }
  35.131 +        }
  35.132 +        free(h->table);
  35.133 +        h->table = newtable;
  35.134 +    }
  35.135 +    /* Plan B: realloc instead */
  35.136 +    else 
  35.137 +    {
  35.138 +        newtable = (struct entry **)
  35.139 +                   realloc(h->table, newsize * sizeof(struct entry *));
  35.140 +        if (NULL == newtable) { (h->primeindex)--; return 0; }
  35.141 +        h->table = newtable;
  35.142 +        memset(newtable[h->tablelength], 0, newsize - h->tablelength);
  35.143 +        for (i = 0; i < h->tablelength; i++) {
  35.144 +            for (pE = &(newtable[i]), e = *pE; e != NULL; e = *pE) {
  35.145 +                index = indexFor(newsize,e->h);
  35.146 +                if (index == i)
  35.147 +                {
  35.148 +                    pE = &(e->next);
  35.149 +                }
  35.150 +                else
  35.151 +                {
  35.152 +                    *pE = e->next;
  35.153 +                    e->next = newtable[index];
  35.154 +                    newtable[index] = e;
  35.155 +                }
  35.156 +            }
  35.157 +        }
  35.158 +    }
  35.159 +    h->tablelength = newsize;
  35.160 +    h->loadlimit   = (unsigned int) ceil(newsize * max_load_factor);
  35.161 +    return -1;
  35.162 +}
  35.163 +
  35.164 +/*****************************************************************************/
  35.165 +unsigned int
  35.166 +hashtable_count(struct hashtable *h)
  35.167 +{
  35.168 +    unsigned int count;
  35.169 +#ifdef HASHTABLE_THREADED
  35.170 +    pthread_mutex_lock(&h->mutex);
  35.171 +#endif    
  35.172 +    count = h->entrycount;
  35.173 +#ifdef HASHTABLE_THREADED
  35.174 +    pthread_mutex_unlock(&h->mutex);
  35.175 +#endif
  35.176 +    return count;
  35.177 +}
  35.178 +
  35.179 +/*****************************************************************************/
  35.180 +int
  35.181 +hashtable_insert(struct hashtable *h, void *k, void *v)
  35.182 +{
  35.183 +    /* This method allows duplicate keys - but they shouldn't be used */
  35.184 +    unsigned int index;
  35.185 +    struct entry *e;
  35.186 +#ifdef HASHTABLE_THREADED
  35.187 +    pthread_mutex_lock(&h->mutex);
  35.188 +#endif   
  35.189 +    if (++(h->entrycount) > h->loadlimit)
  35.190 +    {
  35.191 +        /* Ignore the return value. If expand fails, we should
  35.192 +         * still try cramming just this value into the existing table
  35.193 +         * -- we may not have memory for a larger table, but one more
  35.194 +         * element may be ok. Next time we insert, we'll try expanding again.*/
  35.195 +        hashtable_expand(h);
  35.196 +    }
  35.197 +    e = (struct entry *)malloc(sizeof(struct entry));
  35.198 +    if (NULL == e) { --(h->entrycount); return 0; } /*oom*/
  35.199 +    e->h = hash(h,k);
  35.200 +    index = indexFor(h->tablelength,e->h);
  35.201 +    e->k = k;
  35.202 +    e->v = v;
  35.203 +    e->next = h->table[index];
  35.204 +    h->table[index] = e;
  35.205 +#ifdef HASHTABLE_THREADED
  35.206 +    pthread_mutex_unlock(&h->mutex);
  35.207 +#endif   
  35.208 +    return -1;
  35.209 +}
  35.210 +
  35.211 +/*****************************************************************************/
  35.212 +void * /* returns value associated with key */
  35.213 +hashtable_search(struct hashtable *h, void *k)
  35.214 +{
  35.215 +#ifdef HASHTABLE_THREADED
  35.216 +    pthread_mutex_lock(&h->mutex);
  35.217 +#endif   
  35.218 +    struct entry *e;
  35.219 +    unsigned int hashvalue, index;
  35.220 +    hashvalue = hash(h,k);
  35.221 +    index = indexFor(h->tablelength,hashvalue);
  35.222 +    e = h->table[index];
  35.223 +    while (NULL != e)
  35.224 +    {
  35.225 +        /* Check hash value to short circuit heavier comparison */
  35.226 +        if ((hashvalue == e->h) && (h->eqfn(k, e->k))) {
  35.227 +#ifdef HASHTABLE_THREADED
  35.228 +          pthread_mutex_unlock(&h->mutex);
  35.229 +#endif   
  35.230 +          return e->v;
  35.231 +        }
  35.232 +        e = e->next;
  35.233 +    }
  35.234 +#ifdef HASHTABLE_THREADED
  35.235 +    pthread_mutex_unlock(&h->mutex);
  35.236 +#endif   
  35.237 +    return NULL;
  35.238 +}
  35.239 +
  35.240 +/*****************************************************************************/
  35.241 +void * /* returns value associated with key */
  35.242 +hashtable_remove(struct hashtable *h, void *k)
  35.243 +{
  35.244 +    /* TODO: consider compacting the table when the load factor drops enough,
  35.245 +     *       or provide a 'compact' method. */
  35.246 +#ifdef HASHTABLE_THREADED
  35.247 +    pthread_mutex_lock(&h->mutex);
  35.248 +#endif   
  35.249 +    struct entry *e;
  35.250 +    struct entry **pE;
  35.251 +    void *v;
  35.252 +    unsigned int hashvalue, index;
  35.253 +
  35.254 +    hashvalue = hash(h,k);
  35.255 +    index = indexFor(h->tablelength,hash(h,k));
  35.256 +    pE = &(h->table[index]);
  35.257 +    e = *pE;
  35.258 +    while (NULL != e)
  35.259 +    {
  35.260 +        /* Check hash value to short circuit heavier comparison */
  35.261 +        if ((hashvalue == e->h) && (h->eqfn(k, e->k)))
  35.262 +        {
  35.263 +            *pE = e->next;
  35.264 +            h->entrycount--;
  35.265 +            v = e->v;
  35.266 +            freekey(e->k);
  35.267 +            free(e);
  35.268 +            return v;
  35.269 +        }
  35.270 +        pE = &(e->next);
  35.271 +        e = e->next;
  35.272 +    }
  35.273 +#ifdef HASHTABLE_THREADED
  35.274 +    pthread_mutex_unlock(&h->mutex);
  35.275 +#endif   
  35.276 +    return NULL;
  35.277 +}
  35.278 +
  35.279 +/*****************************************************************************/
  35.280 +/* destroy */
  35.281 +void
  35.282 +hashtable_destroy(struct hashtable *h, int free_values)
  35.283 +{
  35.284 +#ifdef HASHTABLE_THREADED
  35.285 +    pthread_mutex_lock(&h->mutex);
  35.286 +#endif   
  35.287 +    unsigned int i;
  35.288 +    struct entry *e, *f;
  35.289 +    struct entry **table = h->table;
  35.290 +    if (free_values)
  35.291 +    {
  35.292 +        for (i = 0; i < h->tablelength; i++)
  35.293 +        {
  35.294 +            e = table[i];
  35.295 +            while (NULL != e)
  35.296 +            { f = e; e = e->next; freekey(f->k); free(f->v); free(f); }
  35.297 +        }
  35.298 +    }
  35.299 +    else
  35.300 +    {
  35.301 +        for (i = 0; i < h->tablelength; i++)
  35.302 +        {
  35.303 +            e = table[i];
  35.304 +            while (NULL != e)
  35.305 +            { f = e; e = e->next; freekey(f->k); free(f); }
  35.306 +        }
  35.307 +    }
  35.308 +    free(h->table);
  35.309 +#ifdef HASHTABLE_THREADED
  35.310 +    pthread_mutex_destroy(&h->mutex);
  35.311 +#endif   
  35.312 +    free(h);
  35.313 +}
    36.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    36.2 +++ b/tools/vtpm_manager/util/hashtable.h	Tue Aug 30 11:39:25 2005 -0800
    36.3 @@ -0,0 +1,199 @@
    36.4 +/*
    36.5 + * Copyright (c) 2005, Intel Corp
    36.6 + * Copyright (c) 2002, Christopher Clark <firstname.lastname@cl.cam.ac.uk> 
    36.7 + * All rights reserved.
    36.8 + * 
    36.9 + * Redistribution and use in source and binary forms, with or without
   36.10 + * modification, are permitted provided that the following conditions
   36.11 + * are met:
   36.12 + * 
   36.13 + * * Redistributions of source code must retain the above copyright
   36.14 + * notice, this list of conditions and the following disclaimer.
   36.15 + * 
   36.16 + * * Redistributions in binary form must reproduce the above copyright
   36.17 + * notice, this list of conditions and the following disclaimer in the
   36.18 + * documentation and/or other materials provided with the distribution.
   36.19 + * 
   36.20 + * * Neither the name of the original author; nor the names of any contributors
   36.21 + * may be used to endorse or promote products derived from this software
   36.22 + * without specific prior written permission.
   36.23 + * 
   36.24 + * 
   36.25 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   36.26 + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   36.27 + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   36.28 + * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER
   36.29 + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   36.30 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   36.31 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   36.32 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   36.33 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   36.34 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   36.35 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   36.36 +*/
   36.37 +
   36.38 +
   36.39 +#ifndef __HASHTABLE_CWC22_H__
   36.40 +#define __HASHTABLE_CWC22_H__
   36.41 +
   36.42 +struct hashtable;
   36.43 +
   36.44 +/* Example of use:
   36.45 + *
   36.46 + *      struct hashtable  *h;
   36.47 + *      struct some_key   *k;
   36.48 + *      struct some_value *v;
   36.49 + *
   36.50 + *      static unsigned int         hash_from_key_fn( void *k );
   36.51 + *      static int                  keys_equal_fn ( void *key1, void *key2 );
   36.52 + *
   36.53 + *      h = create_hashtable(16, hash_from_key_fn, keys_equal_fn);
   36.54 + *      k = (struct some_key *)     malloc(sizeof(struct some_key));
   36.55 + *      v = (struct some_value *)   malloc(sizeof(struct some_value));
   36.56 + *
   36.57 + *      (initialise k and v to suitable values)
   36.58 + * 
   36.59 + *      if (! hashtable_insert(h,k,v) )
   36.60 + *      {     exit(-1);               }
   36.61 + *
   36.62 + *      if (NULL == (found = hashtable_search(h,k) ))
   36.63 + *      {    printf("not found!");                  }
   36.64 + *
   36.65 + *      if (NULL == (found = hashtable_remove(h,k) ))
   36.66 + *      {    printf("Not found\n");                 }
   36.67 + *
   36.68 + */
   36.69 +
   36.70 +/* Macros may be used to define type-safe(r) hashtable access functions, with
   36.71 + * methods specialized to take known key and value types as parameters.
   36.72 + * 
   36.73 + * Example:
   36.74 + *
   36.75 + * Insert this at the start of your file:
   36.76 + *
   36.77 + * DEFINE_HASHTABLE_INSERT(insert_some, struct some_key, struct some_value);
   36.78 + * DEFINE_HASHTABLE_SEARCH(search_some, struct some_key, struct some_value);
   36.79 + * DEFINE_HASHTABLE_REMOVE(remove_some, struct some_key, struct some_value);
   36.80 + *
   36.81 + * This defines the functions 'insert_some', 'search_some' and 'remove_some'.
   36.82 + * These operate just like hashtable_insert etc., with the same parameters,
   36.83 + * but their function signatures have 'struct some_key *' rather than
   36.84 + * 'void *', and hence can generate compile time errors if your program is
   36.85 + * supplying incorrect data as a key (and similarly for value).
   36.86 + *
   36.87 + * Note that the hash and key equality functions passed to create_hashtable
   36.88 + * still take 'void *' parameters instead of 'some key *'. This shouldn't be
   36.89 + * a difficult issue as they're only defined and passed once, and the other
   36.90 + * functions will ensure that only valid keys are supplied to them.
   36.91 + *
   36.92 + * The cost for this checking is increased code size and runtime overhead
   36.93 + * - if performance is important, it may be worth switching back to the
   36.94 + * unsafe methods once your program has been debugged with the safe methods.
   36.95 + * This just requires switching to some simple alternative defines - eg:
   36.96 + * #define insert_some hashtable_insert
   36.97 + *
   36.98 + */
   36.99 +
  36.100 +/*****************************************************************************
  36.101 + * create_hashtable
  36.102 +   
  36.103 + * @name                    create_hashtable
  36.104 + * @param   minsize         minimum initial size of hashtable
  36.105 + * @param   hashfunction    function for hashing keys
  36.106 + * @param   key_eq_fn       function for determining key equality
  36.107 + * @return                  newly created hashtable or NULL on failure
  36.108 + */
  36.109 +
  36.110 +struct hashtable *
  36.111 +create_hashtable(unsigned int minsize,
  36.112 +                 unsigned int (*hashfunction) (void*),
  36.113 +                 int (*key_eq_fn) (void*,void*));
  36.114 +
  36.115 +/*****************************************************************************
  36.116 + * hashtable_insert
  36.117 +   
  36.118 + * @name        hashtable_insert
  36.119 + * @param   h   the hashtable to insert into
  36.120 + * @param   k   the key - hashtable claims ownership and will free on removal
  36.121 + * @param   v   the value - does not claim ownership
  36.122 + * @return      non-zero for successful insertion
  36.123 + *
  36.124 + * This function will cause the table to expand if the insertion would take
  36.125 + * the ratio of entries to table size over the maximum load factor.
  36.126 + *
  36.127 + * This function does not check for repeated insertions with a duplicate key.
  36.128 + * The value returned when using a duplicate key is undefined -- when
  36.129 + * the hashtable changes size, the order of retrieval of duplicate key
  36.130 + * entries is reversed.
  36.131 + * If in doubt, remove before insert.
  36.132 + */
  36.133 +
  36.134 +int 
  36.135 +hashtable_insert(struct hashtable *h, void *k, void *v);
  36.136 +
  36.137 +#define DEFINE_HASHTABLE_INSERT(fnname, keytype, valuetype) \
  36.138 +int fnname (struct hashtable *h, keytype *k, valuetype *v) \
  36.139 +{ \
  36.140 +    return hashtable_insert(h,k,v); \
  36.141 +}
  36.142 +
  36.143 +/*****************************************************************************
  36.144 + * hashtable_search
  36.145 +   
  36.146 + * @name        hashtable_search
  36.147 + * @param   h   the hashtable to search
  36.148 + * @param   k   the key to search for  - does not claim ownership
  36.149 + * @return      the value associated with the key, or NULL if none found
  36.150 + */
  36.151 +
  36.152 +void *
  36.153 +hashtable_search(struct hashtable *h, void *k);
  36.154 +
  36.155 +#define DEFINE_HASHTABLE_SEARCH(fnname, keytype, valuetype) \
  36.156 +valuetype * fnname (struct hashtable *h, keytype *k) \
  36.157 +{ \
  36.158 +    return (valuetype *) (hashtable_search(h,k)); \
  36.159 +}
  36.160 +
  36.161 +/*****************************************************************************
  36.162 + * hashtable_remove
  36.163 +   
  36.164 + * @name        hashtable_remove
  36.165 + * @param   h   the hashtable to remove the item from
  36.166 + * @param   k   the key to search for  - does not claim ownership
  36.167 + * @return      the value associated with the key, or NULL if none found
  36.168 + */
  36.169 +
  36.170 +void * /* returns value */
  36.171 +hashtable_remove(struct hashtable *h, void *k);
  36.172 +
  36.173 +#define DEFINE_HASHTABLE_REMOVE(fnname, keytype, valuetype) \
  36.174 +valuetype * fnname (struct hashtable *h, keytype *k) \
  36.175 +{ \
  36.176 +    return (valuetype *) (hashtable_remove(h,k)); \
  36.177 +}
  36.178 +
  36.179 +
  36.180 +/*****************************************************************************
  36.181 + * hashtable_count
  36.182 +   
  36.183 + * @name        hashtable_count
  36.184 + * @param   h   the hashtable
  36.185 + * @return      the number of items stored in the hashtable
  36.186 + */
  36.187 +unsigned int
  36.188 +hashtable_count(struct hashtable *h);
  36.189 +
  36.190 +
  36.191 +/*****************************************************************************
  36.192 + * hashtable_destroy
  36.193 +   
  36.194 + * @name        hashtable_destroy
  36.195 + * @param   h   the hashtable
  36.196 + * @param       free_values     whether to call 'free' on the remaining values
  36.197 + */
  36.198 +
  36.199 +void
  36.200 +hashtable_destroy(struct hashtable *h, int free_values);
  36.201 +
  36.202 +#endif /* __HASHTABLE_CWC22_H__ */
    37.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    37.2 +++ b/tools/vtpm_manager/util/hashtable_itr.c	Tue Aug 30 11:39:25 2005 -0800
    37.3 @@ -0,0 +1,231 @@
    37.4 +/*
    37.5 + * Copyright (c) 2005, Intel Corp
    37.6 + * Copyright (c) 2002, Christopher Clark <firstname.lastname@cl.cam.ac.uk> 
    37.7 + * All rights reserved.
    37.8 + * 
    37.9 + * Redistribution and use in source and binary forms, with or without
   37.10 + * modification, are permitted provided that the following conditions
   37.11 + * are met:
   37.12 + * 
   37.13 + * * Redistributions of source code must retain the above copyright
   37.14 + * notice, this list of conditions and the following disclaimer.
   37.15 + * 
   37.16 + * * Redistributions in binary form must reproduce the above copyright
   37.17 + * notice, this list of conditions and the following disclaimer in the
   37.18 + * documentation and/or other materials provided with the distribution.
   37.19 + * 
   37.20 + * * Neither the name of the original author; nor the names of any contributors
   37.21 + * may be used to endorse or promote products derived from this software
   37.22 + * without specific prior written permission.
   37.23 + * 
   37.24 + * 
   37.25 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   37.26 + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   37.27 + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   37.28 + * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER
   37.29 + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   37.30 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   37.31 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   37.32 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   37.33 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   37.34 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   37.35 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   37.36 +*/
   37.37 +
   37.38 +#include "hashtable.h"
   37.39 +#include "hashtable_private.h"
   37.40 +#include "hashtable_itr.h"
   37.41 +#include <stdlib.h> /* defines NULL */
   37.42 +
   37.43 +/*****************************************************************************/
   37.44 +/* hashtable_iterator    - iterator constructor */
   37.45 +
   37.46 +struct hashtable_itr *
   37.47 +hashtable_iterator(struct hashtable *h)
   37.48 +{
   37.49 +    unsigned int i, tablelength;
   37.50 +    struct hashtable_itr *itr = (struct hashtable_itr *)
   37.51 +        malloc(sizeof(struct hashtable_itr));
   37.52 +    if (NULL == itr) return NULL;
   37.53 +#ifdef HASHTABLE_THREADED
   37.54 +    pthread_mutex_lock(&h->mutex);
   37.55 +#endif   
   37.56 +    itr->h = h;
   37.57 +    itr->e = NULL;
   37.58 +    itr->parent = NULL;
   37.59 +    tablelength = h->tablelength;
   37.60 +    itr->index = tablelength;
   37.61 +    if (0 == h->entrycount) {
   37.62 +#ifdef HASHTABLE_THREADED
   37.63 +      pthread_mutex_unlock(&h->mutex);
   37.64 +#endif   
   37.65 +      return itr;
   37.66 +    }
   37.67 +
   37.68 +    for (i = 0; i < tablelength; i++)
   37.69 +    {
   37.70 +        if (NULL != h->table[i])
   37.71 +        {
   37.72 +            itr->e = h->table[i];
   37.73 +            itr->index = i;
   37.74 +            break;
   37.75 +        }
   37.76 +    }
   37.77 +#ifdef HASHTABLE_THREADED
   37.78 +    pthread_mutex_unlock(&h->mutex);
   37.79 +#endif   
   37.80 +    return itr;
   37.81 +}
   37.82 +
   37.83 +/*****************************************************************************/
   37.84 +/* key      - return the key of the (key,value) pair at the current position */
   37.85 +/* value    - return the value of the (key,value) pair at the current position */
   37.86 +
   37.87 +void *
   37.88 +hashtable_iterator_key(struct hashtable_itr *i)
   37.89 +{ return i->e->k; }
   37.90 +
   37.91 +void *
   37.92 +hashtable_iterator_value(struct hashtable_itr *i)
   37.93 +{ return i->e->v; }
   37.94 +
   37.95 +/*****************************************************************************/
   37.96 +/* advance - advance the iterator to the next element
   37.97 + *           returns zero if advanced to end of table */
   37.98 +
   37.99 +int
  37.100 +hashtable_iterator_advance(struct hashtable_itr *itr)
  37.101 +{
  37.102 +#ifdef HASHTABLE_THREADED
  37.103 +    pthread_mutex_lock(&itr->h->mutex);
  37.104 +#endif   
  37.105 +    unsigned int j,tablelength;
  37.106 +    struct entry **table;
  37.107 +    struct entry *next;
  37.108 +    int ret;
  37.109 +    if (NULL == itr->e) { /* stupidity check */
  37.110 +      ret = 0; 
  37.111 +      goto egress;
  37.112 +    }
  37.113 +
  37.114 +    next = itr->e->next;
  37.115 +    if (NULL != next)
  37.116 +    {
  37.117 +        itr->parent = itr->e;
  37.118 +        itr->e = next;
  37.119 +        ret = -1;
  37.120 +        goto egress;
  37.121 +    }
  37.122 +
  37.123 +    tablelength = itr->h->tablelength;
  37.124 +    itr->parent = NULL;
  37.125 +    if (tablelength <= (j = ++(itr->index)))
  37.126 +    {
  37.127 +        itr->e = NULL;
  37.128 +        ret = 0;
  37.129 +        goto egress;
  37.130 +    }
  37.131 +    table = itr->h->table;
  37.132 +    while (NULL == (next = table[j]))
  37.133 +    {
  37.134 +        if (++j >= tablelength)
  37.135 +        {
  37.136 +            itr->index = tablelength;
  37.137 +            itr->e = NULL;
  37.138 +            ret = 0;
  37.139 +            goto egress;
  37.140 +        }
  37.141 +    }
  37.142 +    itr->index = j;
  37.143 +    itr->e = next;
  37.144 +    ret = -1;
  37.145 +
  37.146 + egress:
  37.147 +#ifdef HASHTABLE_THREADED
  37.148 +    pthread_mutex_unlock(&itr->h->mutex);
  37.149 +#endif   
  37.150 +    return ret;
  37.151 +}
  37.152 +
  37.153 +/*****************************************************************************/
  37.154 +/* remove - remove the entry at the current iterator position
  37.155 + *          and advance the iterator, if there is a successive
  37.156 + *          element.
  37.157 + *          If you want the value, read it before you remove:
  37.158 + *          beware memory leaks if you don't.
  37.159 + *          Returns zero if end of iteration. */
  37.160 +
  37.161 +int
  37.162 +hashtable_iterator_remove(struct hashtable_itr *itr)
  37.163 +{
  37.164 +#ifdef HASHTABLE_THREADED
  37.165 +    pthread_mutex_lock(&itr->h->mutex);
  37.166 +#endif 
  37.167 +    struct entry *remember_e, *remember_parent;
  37.168 +    int ret;
  37.169 +
  37.170 +    /* Do the removal */
  37.171 +    if (NULL == (itr->parent))
  37.172 +    {
  37.173 +        /* element is head of a chain */
  37.174 +        itr->h->table[itr->index] = itr->e->next;
  37.175 +    } else {
  37.176 +        /* element is mid-chain */
  37.177 +        itr->parent->next = itr->e->next;
  37.178 +    }
  37.179 +    /* itr->e is now outside the hashtable */
  37.180 +    remember_e = itr->e;
  37.181 +    itr->h->entrycount--;
  37.182 +    freekey(remember_e->k);
  37.183 +
  37.184 +    /* Advance the iterator, correcting the parent */
  37.185 +    remember_parent = itr->parent;
  37.186 +    ret = hashtable_iterator_advance(itr);
  37.187 +    if (itr->parent == remember_e) { itr->parent = remember_parent; }
  37.188 +    free(remember_e);
  37.189 +#ifdef HASHTABLE_THREADED
  37.190 +    pthread_mutex_unlock(&itr->h->mutex);
  37.191 +#endif 
  37.192 +    return ret;
  37.193 +}
  37.194 +
  37.195 +/*****************************************************************************/
  37.196 +int /* returns zero if not found */
  37.197 +hashtable_iterator_search(struct hashtable_itr *itr,
  37.198 +                          struct hashtable *h, void *k)
  37.199 +{
  37.200 +#ifdef HASHTABLE_THREADED
  37.201 +    pthread_mutex_lock(&h->mutex);
  37.202 +#endif 
  37.203 +    struct entry *e, *parent;
  37.204 +    unsigned int hashvalue, index;
  37.205 +    int ret;
  37.206 +    
  37.207 +    hashvalue = hash(h,k);
  37.208 +    index = indexFor(h->tablelength,hashvalue);
  37.209 +
  37.210 +    e = h->table[index];
  37.211 +    parent = NULL;
  37.212 +    while (NULL != e)
  37.213 +    {
  37.214 +        /* Check hash value to short circuit heavier comparison */
  37.215 +        if ((hashvalue == e->h) && (h->eqfn(k, e->k)))
  37.216 +        {
  37.217 +            itr->index = index;
  37.218 +            itr->e = e;
  37.219 +            itr->parent = parent;
  37.220 +            itr->h = h;
  37.221 +            ret= -1;
  37.222 +            goto egress;
  37.223 +        }
  37.224 +        parent = e;
  37.225 +        e = e->next;
  37.226 +    }
  37.227 +  ret = 0;
  37.228 +    
  37.229 +egress:
  37.230 +#ifdef HASHTABLE_THREADED
  37.231 +    pthread_mutex_lock(&h->mutex);
  37.232 +#endif 
  37.233 +    return ret;
  37.234 +}
    38.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    38.2 +++ b/tools/vtpm_manager/util/hashtable_itr.h	Tue Aug 30 11:39:25 2005 -0800
    38.3 @@ -0,0 +1,104 @@
    38.4 +/*
    38.5 + * Copyright (c) 2005, Intel Corp
    38.6 + * Copyright (c) 2002, Christopher Clark <firstname.lastname@cl.cam.ac.uk> 
    38.7 + * All rights reserved.
    38.8 + * 
    38.9 + * Redistribution and use in source and binary forms, with or without
   38.10 + * modification, are permitted provided that the following conditions
   38.11 + * are met:
   38.12 + * 
   38.13 + * * Redistributions of source code must retain the above copyright
   38.14 + * notice, this list of conditions and the following disclaimer.
   38.15 + * 
   38.16 + * * Redistributions in binary form must reproduce the above copyright
   38.17 + * notice, this list of conditions and the following disclaimer in the
   38.18 + * documentation and/or other materials provided with the distribution.
   38.19 + * 
   38.20 + * * Neither the name of the original author; nor the names of any contributors
   38.21 + * may be used to endorse or promote products derived from this software
   38.22 + * without specific prior written permission.
   38.23 + * 
   38.24 + * 
   38.25 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   38.26 + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   38.27 + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   38.28 + * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER
   38.29 + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   38.30 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   38.31 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   38.32 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   38.33 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   38.34 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   38.35 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   38.36 +*/
   38.37 +
   38.38 +
   38.39 +#ifndef __HASHTABLE_ITR_CWC22__
   38.40 +#define __HASHTABLE_ITR_CWC22__
   38.41 +#include "hashtable.h"
   38.42 +#include "hashtable_private.h" /* needed to enable inlining */
   38.43 +
   38.44 +/*****************************************************************************/
   38.45 +/* This struct is only concrete here to allow the inlining of two of the
   38.46 + * accessor functions. */
   38.47 +struct hashtable_itr
   38.48 +{
   38.49 +    struct hashtable *h;
   38.50 +    struct entry *e;
   38.51 +    struct entry *parent;
   38.52 +    unsigned int index;
   38.53 +};
   38.54 +
   38.55 +
   38.56 +/*****************************************************************************/
   38.57 +/* hashtable_iterator
   38.58 + */
   38.59 +
   38.60 +struct hashtable_itr *
   38.61 +hashtable_iterator(struct hashtable *h);
   38.62 +
   38.63 +/*****************************************************************************/
   38.64 +/* hashtable_iterator_key
   38.65 + * - return the value of the (key,value) pair at the current position */
   38.66 +
   38.67 +void *hashtable_iterator_key(struct hashtable_itr *i);
   38.68 +
   38.69 +/*****************************************************************************/
   38.70 +/* value - return the value of the (key,value) pair at the current position */
   38.71 +
   38.72 +void *hashtable_iterator_value(struct hashtable_itr *i);
   38.73 +
   38.74 +/*****************************************************************************/
   38.75 +/* advance - advance the iterator to the next element
   38.76 + *           returns zero if advanced to end of table */
   38.77 +
   38.78 +int
   38.79 +hashtable_iterator_advance(struct hashtable_itr *itr);
   38.80 +
   38.81 +/*****************************************************************************/
   38.82 +/* remove - remove current element and advance the iterator to the next element
   38.83 + *          NB: if you need the value to free it, read it before
   38.84 + *          removing. ie: beware memory leaks!
   38.85 + *          returns zero if advanced to end of table */
   38.86 +
   38.87 +int
   38.88 +hashtable_iterator_remove(struct hashtable_itr *itr);
   38.89 +
   38.90 +/*****************************************************************************/
   38.91 +/* search - overwrite the supplied iterator, to point to the entry
   38.92 + *          matching the supplied key.
   38.93 +            h points to the hashtable to be searched.
   38.94 + *          returns zero if not found. */
   38.95 +int
   38.96 +hashtable_iterator_search(struct hashtable_itr *itr,
   38.97 +                          struct hashtable *h, void *k);
   38.98 +
   38.99 +#define DEFINE_HASHTABLE_ITERATOR_SEARCH(fnname, keytype) \
  38.100 +int fnname (struct hashtable_itr *i, struct hashtable *h, keytype *k) \
  38.101 +{ \
  38.102 +    return (hashtable_iterator_search(i,h,k)); \
  38.103 +}
  38.104 +
  38.105 +
  38.106 +
  38.107 +#endif /* __HASHTABLE_ITR_CWC22__*/
    39.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    39.2 +++ b/tools/vtpm_manager/util/hashtable_private.h	Tue Aug 30 11:39:25 2005 -0800
    39.3 @@ -0,0 +1,90 @@
    39.4 +/*
    39.5 + * Copyright (c) 2005, Intel Corp
    39.6 + * Copyright (c) 2002, Christopher Clark <firstname.lastname@cl.cam.ac.uk> 
    39.7 + * All rights reserved.
    39.8 + * 
    39.9 + * Redistribution and use in source and binary forms, with or without
   39.10 + * modification, are permitted provided that the following conditions
   39.11 + * are met:
   39.12 + * 
   39.13 + * * Redistributions of source code must retain the above copyright
   39.14 + * notice, this list of conditions and the following disclaimer.
   39.15 + * 
   39.16 + * * Redistributions in binary form must reproduce the above copyright
   39.17 + * notice, this list of conditions and the following disclaimer in the
   39.18 + * documentation and/or other materials provided with the distribution.
   39.19 + * 
   39.20 + * * Neither the name of the original author; nor the names of any contributors
   39.21 + * may be used to endorse or promote products derived from this software
   39.22 + * without specific prior written permission.
   39.23 + * 
   39.24 + * 
   39.25 + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   39.26 + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   39.27 + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   39.28 + * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER
   39.29 + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   39.30 + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   39.31 + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   39.32 + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   39.33 + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   39.34 + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   39.35 + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   39.36 +*/
   39.37 +
   39.38 +#ifndef __HASHTABLE_PRIVATE_CWC22_H__
   39.39 +#define __HASHTABLE_PRIVATE_CWC22_H__
   39.40 +
   39.41 +#include "hashtable.h"
   39.42 +#ifdef HASHTABLE_THREADED
   39.43 +#include <pthread.h>
   39.44 +#endif
   39.45 +
   39.46 +/*****************************************************************************/
   39.47 +struct entry
   39.48 +{
   39.49 +    void *k, *v;
   39.50 +    unsigned int h;
   39.51 +    struct entry *next;
   39.52 +};
   39.53 +
   39.54 +struct hashtable {
   39.55 +    unsigned int tablelength;
   39.56 +    struct entry **table;
   39.57 +    unsigned int entrycount;
   39.58 +    unsigned int loadlimit;
   39.59 +    unsigned int primeindex;
   39.60 +    unsigned int (*hashfn) (void *k);
   39.61 +    int (*eqfn) (void *k1, void *k2);
   39.62 +#ifdef HASHTABLE_THREADED
   39.63 +    pthread_mutex_t mutex;
   39.64 +#endif
   39.65 +};
   39.66 +
   39.67 +/*****************************************************************************/
   39.68 +unsigned int
   39.69 +hash(struct hashtable *h, void *k);
   39.70 +
   39.71 +/*****************************************************************************/
   39.72 +/* indexFor */
   39.73 +static inline unsigned int
   39.74 +indexFor(unsigned int tablelength, unsigned int hashvalue) {
   39.75 +    return (hashvalue % tablelength);
   39.76 +};
   39.77 +
   39.78 +/* Only works if tablelength == 2^N */
   39.79 +/*static inline unsigned int
   39.80 +indexFor(unsigned int tablelength, unsigned int hashvalue)
   39.81 +{
   39.82 +    return (hashvalue & (tablelength - 1u));
   39.83 +}
   39.84 +*/
   39.85 +
   39.86 +/*****************************************************************************/
   39.87 +#define freekey(X) free(X)
   39.88 +/*define freekey(X) ; */
   39.89 +
   39.90 +
   39.91 +/*****************************************************************************/
   39.92 +
   39.93 +#endif /* __HASHTABLE_PRIVATE_CWC22_H__*/
    40.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    40.2 +++ b/tools/vtpm_manager/util/log.c	Tue Aug 30 11:39:25 2005 -0800
    40.3 @@ -0,0 +1,142 @@
    40.4 +// ===================================================================
    40.5 +// 
    40.6 +// Copyright (c) 2005, Intel Corp.
    40.7 +// All rights reserved.
    40.8 +//
    40.9 +// Redistribution and use in source and binary forms, with or without 
   40.10 +// modification, are permitted provided that the following conditions 
   40.11 +// are met:
   40.12 +//
   40.13 +//   * Redistributions of source code must retain the above copyright 
   40.14 +//     notice, this list of conditions and the following disclaimer.
   40.15 +//   * Redistributions in binary form must reproduce the above 
   40.16 +//     copyright notice, this list of conditions and the following 
   40.17 +//     disclaimer in the documentation and/or other materials provided 
   40.18 +//     with the distribution.
   40.19 +//   * Neither the name of Intel Corporation nor the names of its 
   40.20 +//     contributors may be used to endorse or promote products derived
   40.21 +//     from this software without specific prior written permission.
   40.22 +//
   40.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   40.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   40.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   40.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   40.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   40.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   40.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   40.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   40.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   40.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   40.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   40.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   40.35 +// ===================================================================
   40.36 +
   40.37 +#include <stdlib.h>
   40.38 +#include <string.h>
   40.39 +#include <stdio.h>
   40.40 +
   40.41 +#include "buffer.h"
   40.42 +#include "tcg.h"
   40.43 +
   40.44 +// Helper code for the consts, eg. to produce messages for error codes.
   40.45 +
   40.46 +typedef struct error_code_entry_t {
   40.47 +  TPM_RESULT code;
   40.48 +  char * code_name;
   40.49 +  char * msg;
   40.50 +} error_code_entry_t;
   40.51 +
   40.52 +static const error_code_entry_t error_msgs [] = {    
   40.53 +  { TPM_SUCCESS, "TPM_SUCCESS", "Successful completion of the operation" },
   40.54 +  { TPM_AUTHFAIL, "TPM_AUTHFAIL", "Authentication failed" },
   40.55 +  { TPM_BADINDEX, "TPM_BADINDEX", "The index to a PCR, DIR or other register is incorrect" },
   40.56 +  { TPM_BAD_PARAMETER, "TPM_BAD_PARAMETER", "One or more parameter is bad" },
   40.57 +  { TPM_AUDITFAILURE, "TPM_AUDITFAILURE", "An operation completed successfully but the auditing of that operation failed." },
   40.58 +  { TPM_CLEAR_DISABLED, "TPM_CLEAR_DISABLED", "The clear disable flag is set and all clear operations now require physical access" },
   40.59 +  { TPM_DEACTIVATED, "TPM_DEACTIVATED", "The TPM is deactivated" },
   40.60 +  { TPM_DISABLED, "TPM_DISABLED", "The TPM is disabled" },
   40.61 +  { TPM_DISABLED_CMD, "TPM_DISABLED_CMD", "The target command has been disabled" },
   40.62 +  { TPM_FAIL, "TPM_FAIL", "The operation failed" },
   40.63 +  { TPM_BAD_ORDINAL, "TPM_BAD_ORDINAL", "The ordinal was unknown or inconsistent" },
   40.64 +  { TPM_INSTALL_DISABLED, "TPM_INSTALL_DISABLED", "The ability to install an owner is disabled" },
   40.65 +  { TPM_INVALID_KEYHANDLE, "TPM_INVALID_KEYHANDLE", "The key handle presented was invalid" },
   40.66 +  { TPM_KEYNOTFOUND, "TPM_KEYNOTFOUND", "The target key was not found" },
   40.67 +  { TPM_INAPPROPRIATE_ENC, "TPM_INAPPROPRIATE_ENC", "Unacceptable encryption scheme" },
   40.68 +  { TPM_MIGRATEFAIL, "TPM_MIGRATEFAIL", "Migration authorization failed" },
   40.69 +  { TPM_INVALID_PCR_INFO, "TPM_INVALID_PCR_INFO", "PCR information could not be interpreted" },
   40.70 +  { TPM_NOSPACE, "TPM_NOSPACE", "No room to load key." },
   40.71 +  { TPM_NOSRK, "TPM_NOSRK", "There is no SRK set" },
   40.72 +  { TPM_NOTSEALED_BLOB, "TPM_NOTSEALED_BLOB", "An encrypted blob is invalid or was not created by this TPM" },
   40.73 +  { TPM_OWNER_SET, "TPM_OWNER_SET", "There is already an Owner" },
   40.74 +  { TPM_RESOURCES, "TPM_RESOURCES", "The TPM has insufficient internal resources to perform the requested action." },
   40.75 +  { TPM_SHORTRANDOM, "TPM_SHORTRANDOM", "A random string was too short" },
   40.76 +  { TPM_SIZE, "TPM_SIZE", "The TPM does not have the space to perform the operation." },
   40.77 +  { TPM_WRONGPCRVAL, "TPM_WRONGPCRVAL", "The named PCR value does not match the current PCR value." },
   40.78 +  { TPM_BAD_PARAM_SIZE, "TPM_BAD_PARAM_SIZE", "The paramSize argument to the command has the incorrect value" },
   40.79 +  { TPM_SHA_THREAD, "TPM_SHA_THREAD", "There is no existing SHA-1 thread." },
   40.80 +  { TPM_SHA_ERROR, "TPM_SHA_ERROR", "The calculation is unable to proceed because the existing SHA-1 thread has already encountered an error." },
   40.81 +  { TPM_FAILEDSELFTEST, "TPM_FAILEDSELFTEST", "Self-test has failed and the TPM has shutdown." },
   40.82 +  { TPM_AUTH2FAIL, "TPM_AUTH2FAIL", "The authorization for the second key in a 2 key function failed authorization" },
   40.83 +  { TPM_BADTAG, "TPM_BADTAG", "The tag value sent to for a command is invalid" },
   40.84 +  { TPM_IOERROR, "TPM_IOERROR", "An IO error occurred transmitting information to the TPM" },
   40.85 +  { TPM_ENCRYPT_ERROR, "TPM_ENCRYPT_ERROR", "The encryption process had a problem." },
   40.86 +  { TPM_DECRYPT_ERROR, "TPM_DECRYPT_ERROR", "The decryption process did not complete." },
   40.87 +  { TPM_INVALID_AUTHHANDLE, "TPM_INVALID_AUTHHANDLE", "An invalid handle was used." },
   40.88 +  { TPM_NO_ENDORSEMENT, "TPM_NO_ENDORSEMENT", "The TPM does not a EK installed" },
   40.89 +  { TPM_INVALID_KEYUSAGE, "TPM_INVALID_KEYUSAGE", "The usage of a key is not allowed" },
   40.90 +  { TPM_WRONG_ENTITYTYPE, "TPM_WRONG_ENTITYTYPE", "The submitted entity type is not allowed" },
   40.91 +  { TPM_INVALID_POSTINIT, "TPM_INVALID_POSTINIT", "The command was received in the wrong sequence relative to TPM_Init and a subsequent TPM_Startup" },
   40.92 +  { TPM_INAPPROPRIATE_SIG, "TPM_INAPPROPRIATE_SIG", "Signed data cannot include additional DER information" },
   40.93 +  { TPM_BAD_KEY_PROPERTY, "TPM_BAD_KEY_PROPERTY", "The key properties in TPM_KEY_PARMs are not supported by this TPM" },
   40.94 +  
   40.95 +  { TPM_BAD_MIGRATION, "TPM_BAD_MIGRATION", "The migration properties of this key are incorrect." },
   40.96 +  { TPM_BAD_SCHEME, "TPM_BAD_SCHEME", "The signature or encryption scheme for this key is incorrect or not permitted in this situation." },
   40.97 +  { TPM_BAD_DATASIZE, "TPM_BAD_DATASIZE", "The size of the data (or blob) parameter is bad or inconsistent with the referenced key" },
   40.98 +  { TPM_BAD_MODE, "TPM_BAD_MODE", "A mode parameter is bad, such as capArea or subCapArea for TPM_GetCapability, phsicalPresence parameter for TPM_PhysicalPresence, or migrationType for TPM_CreateMigrationBlob." },
   40.99 +  { TPM_BAD_PRESENCE, "TPM_BAD_PRESENCE", "Either the physicalPresence or physicalPresenceLock bits have the wrong value" },
  40.100 +  { TPM_BAD_VERSION, "TPM_BAD_VERSION", "The TPM cannot perform this version of the capability" },
  40.101 +  { TPM_NO_WRAP_TRANSPORT, "TPM_NO_WRAP_TRANSPORT", "The TPM does not allow for wrapped transport sessions" },
  40.102 +  { TPM_AUDITFAIL_UNSUCCESSFUL, "TPM_AUDITFAIL_UNSUCCESSFUL", "TPM audit construction failed and the underlying command was returning a failure code also" },
  40.103 +  { TPM_AUDITFAIL_SUCCESSFUL, "TPM_AUDITFAIL_SUCCESSFUL", "TPM audit construction failed and the underlying command was returning success" },
  40.104 +  { TPM_NOTRESETABLE, "TPM_NOTRESETABLE", "Attempt to reset a PCR register that does not have the resettable attribute" },
  40.105 +  { TPM_NOTLOCAL, "TPM_NOTLOCAL", "Attempt to reset a PCR register that requires locality and locality modifier not part of command transport" },
  40.106 +  { TPM_BAD_TYPE, "TPM_BAD_TYPE", "Make identity blob not properly typed" },
  40.107 +  { TPM_INVALID_RESOURCE, "TPM_INVALID_RESOURCE", "When saving context identified resource type does not match actual resource" },
  40.108 +  { TPM_NOTFIPS, "TPM_NOTFIPS", "The TPM is attempting to execute a command only available when in FIPS mode" },
  40.109 +  { TPM_INVALID_FAMILY, "TPM_INVALID_FAMILY", "The command is attempting to use an invalid family ID" },
  40.110 +  { TPM_NO_NV_PERMISSION, "TPM_NO_NV_PERMISSION", "The permission to manipulate the NV storage is not available" },
  40.111 +  { TPM_REQUIRES_SIGN, "TPM_REQUIRES_SIGN", "The operation requires a signed command" },
  40.112 +  { TPM_KEY_NOTSUPPORTED, "TPM_KEY_NOTSUPPORTED", "Wrong operation to load an NV key" },
  40.113 +  { TPM_AUTH_CONFLICT, "TPM_AUTH_CONFLICT", "NV_LoadKey blob requires both owner and blob authorization" },
  40.114 +  { TPM_AREA_LOCKED, "TPM_AREA_LOCKED", "The NV area is locked and not writtable" },
  40.115 +  { TPM_BAD_LOCALITY, "TPM_BAD_LOCALITY", "The locality is incorrect for the attempted operation" },
  40.116 +  { TPM_READ_ONLY, "TPM_READ_ONLY", "The NV area is read only and can't be written to" },
  40.117 +  { TPM_PER_NOWRITE, "TPM_PER_NOWRITE", "There is no protection on the write to the NV area" },
  40.118 +  { TPM_FAMILYCOUNT, "TPM_FAMILYCOUNT", "The family count value does not match" },
  40.119 +  { TPM_WRITE_LOCKED, "TPM_WRITE_LOCKED", "The NV area has already been written to" },
  40.120 +  { TPM_BAD_ATTRIBUTES, "TPM_BAD_ATTRIBUTES", "The NV area attributes conflict" },
  40.121 +  { TPM_INVALID_STRUCTURE, "TPM_INVALID_STRUCTURE", "The structure tag and version are invalid or inconsistent" },
  40.122 +  { TPM_KEY_OWNER_CONTROL, "TPM_KEY_OWNER_CONTROL", "The key is under control of the TPM Owner and can only be evicted by the TPM Owner." },
  40.123 +  { TPM_BAD_COUNTER, "TPM_BAD_COUNTER", "The counter handle is incorrect" },
  40.124 +  { TPM_NOT_FULLWRITE, "TPM_NOT_FULLWRITE", "The write is not a complete write of the area" },
  40.125 +  { TPM_CONTEXT_GAP, "TPM_CONTEXT_GAP", "The gap between saved context counts is too large" },
  40.126 +  { TPM_MAXNVWRITES, "TPM_MAXNVWRITES", "The maximum number of NV writes without an owner has been exceeded" },
  40.127 +  { TPM_NOOPERATOR, "TPM_NOOPERATOR", "No operator authorization value is set" },
  40.128 +  { TPM_RESOURCEMISSING, "TPM_RESOURCEMISSING", "The resource pointed to by context is not loaded" },
  40.129 +  { TPM_DELEGATE_LOCK, "TPM_DELEGATE_LOCK", "The delegate administration is locked" },
  40.130 +  { TPM_DELEGATE_FAMILY, "TPM_DELEGATE_FAMILY", "Attempt to manage a family other then the delegated family" },
  40.131 +  { TPM_DELEGATE_ADMIN, "TPM_DELEGATE_ADMIN", "Delegation table management not enabled" },
  40.132 +  { TPM_TRANSPORT_EXCLUSIVE, "TPM_TRANSPORT_EXCLUSIVE", "There was a command executed outside of an exclusive transport session" },
  40.133 +};
  40.134 +
  40.135 +
  40.136 +// helper function for the error codes:
  40.137 +const char* tpm_get_error_name (TPM_RESULT code) {
  40.138 +  // just do a linear scan for now
  40.139 +  unsigned i;
  40.140 +  for (i = 0; i < sizeof(error_msgs)/sizeof(error_msgs[0]); i++) 
  40.141 +    if (code == error_msgs[i].code) 
  40.142 +      return error_msgs[i].code_name;
  40.143 +  
  40.144 +    return "Failed to find code name for given code";
  40.145 +}
    41.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    41.2 +++ b/tools/vtpm_manager/util/log.h	Tue Aug 30 11:39:25 2005 -0800
    41.3 @@ -0,0 +1,92 @@
    41.4 +// ===================================================================
    41.5 +// 
    41.6 +// Copyright (c) 2005, Intel Corp.
    41.7 +// All rights reserved.
    41.8 +//
    41.9 +// Redistribution and use in source and binary forms, with or without 
   41.10 +// modification, are permitted provided that the following conditions 
   41.11 +// are met:
   41.12 +//
   41.13 +//   * Redistributions of source code must retain the above copyright 
   41.14 +//     notice, this list of conditions and the following disclaimer.
   41.15 +//   * Redistributions in binary form must reproduce the above 
   41.16 +//     copyright notice, this list of conditions and the following 
   41.17 +//     disclaimer in the documentation and/or other materials provided 
   41.18 +//     with the distribution.
   41.19 +//   * Neither the name of Intel Corporation nor the names of its 
   41.20 +//     contributors may be used to endorse or promote products derived
   41.21 +//     from this software without specific prior written permission.
   41.22 +//
   41.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   41.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   41.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   41.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   41.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   41.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   41.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   41.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   41.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   41.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   41.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   41.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   41.35 +// ===================================================================
   41.36 +
   41.37 +#ifndef __VTPM_LOG_H__
   41.38 +#define __VTPM_LOG_H__
   41.39 +
   41.40 +#include <stdint.h>             // for uint32_t
   41.41 +#include <stddef.h>             // for pointer NULL
   41.42 +
   41.43 +// =========================== LOGGING ==============================
   41.44 +
   41.45 +// the logging module numbers
   41.46 +#define VTPM_LOG_CRYPTO      1
   41.47 +#define VTPM_LOG_BSG         2
   41.48 +#define VTPM_LOG_TXDATA      3
   41.49 +#define VTPM_LOG_TCS         4
   41.50 +#define VTPM_LOG_TCS_DEEP    5
   41.51 +#define VTPM_LOG_VTSP        6
   41.52 +#define VTPM_LOG_VTPM        7
   41.53 +#define VTPM_LOG_VTPM_DEEP   8
   41.54 +
   41.55 +static char *module_names[] = { "",
   41.56 +                                "CRYPTO",
   41.57 +                                "BSG",
   41.58 +                                "TXDATA",
   41.59 +                                "TCS",
   41.60 +                                "TCS",
   41.61 +                                "VTSP",
   41.62 +                                "VTPM",
   41.63 +                                "VTPM"
   41.64 +                              };
   41.65 +
   41.66 +// Default to standard logging
   41.67 +#ifndef LOGGING_MODULES
   41.68 +#define LOGGING_MODULES (BITMASK(VTPM_LOG_VTPM))
   41.69 +#endif
   41.70 +
   41.71 +// bit-access macros
   41.72 +#define BITMASK(idx)      ( 1U << (idx) )
   41.73 +#define GETBIT(num,idx)   ( ((num) & BITMASK(idx)) >> idx )
   41.74 +#define SETBIT(num,idx)   (num) |= BITMASK(idx)
   41.75 +#define CLEARBIT(num,idx) (num) &= ( ~ BITMASK(idx) )
   41.76 +
   41.77 +#define vtpmloginfo(module, fmt, args...) \
   41.78 +  if (GETBIT (LOGGING_MODULES, module) == 1) {				\
   41.79 +    fprintf (stdout, "INFO[%s]: " fmt, module_names[module], ##args); \
   41.80 +  }
   41.81 +
   41.82 +#define vtpmloginfomore(module, fmt, args...) \
   41.83 +  if (GETBIT (LOGGING_MODULES, module) == 1) {			      \
   41.84 +    fprintf (stdout, fmt,##args);				      \
   41.85 +  }
   41.86 +                               
   41.87 +#define vtpmlogerror(module, fmt, args...) \
   41.88 +  fprintf (stderr, "ERROR[%s]: " fmt, module_names[module], ##args);
   41.89 +                               
   41.90 +//typedef UINT32 tpm_size_t;
   41.91 +                        
   41.92 +// helper function for the error codes:
   41.93 +const char* tpm_get_error_name (TPM_RESULT code);
   41.94 +
   41.95 +#endif // _VTPM_LOG_H_
    42.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
    42.2 +++ b/tools/vtpm_manager/util/tcg.h	Tue Aug 30 11:39:25 2005 -0800
    42.3 @@ -0,0 +1,486 @@
    42.4 +// ===================================================================
    42.5 +// 
    42.6 +// Copyright (c) 2005, Intel Corp.
    42.7 +// All rights reserved.
    42.8 +//
    42.9 +// Redistribution and use in source and binary forms, with or without 
   42.10 +// modification, are permitted provided that the following conditions 
   42.11 +// are met:
   42.12 +//
   42.13 +//   * Redistributions of source code must retain the above copyright 
   42.14 +//     notice, this list of conditions and the following disclaimer.
   42.15 +//   * Redistributions in binary form must reproduce the above 
   42.16 +//     copyright notice, this list of conditions and the following 
   42.17 +//     disclaimer in the documentation and/or other materials provided 
   42.18 +//     with the distribution.
   42.19 +//   * Neither the name of Intel Corporation nor the names of its 
   42.20 +//     contributors may be used to endorse or promote products derived
   42.21 +//     from this software without specific prior written permission.
   42.22 +//
   42.23 +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
   42.24 +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
   42.25 +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
   42.26 +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
   42.27 +// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   42.28 +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   42.29 +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
   42.30 +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   42.31 +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   42.32 +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
   42.33 +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   42.34 +// OF THE POSSIBILITY OF SUCH DAMAGE.
   42.35 +// ===================================================================
   42.36 +// 
   42.37 +// tcg.h
   42.38 +// 
   42.39 +//  This file contains all the structure and type definitions
   42.40 +//
   42.41 +// ==================================================================
   42.42 +
   42.43 +#ifndef __TCG_H__
   42.44 +#define __TCG_H__
   42.45 +
   42.46 +// This pragma is used to disallow structure padding
   42.47 +#pragma pack(push, 1)
   42.48 +
   42.49 +// *************************** TYPEDEFS *********************************
   42.50 +typedef unsigned char BYTE;
   42.51 +typedef unsigned char BOOL;
   42.52 +typedef unsigned short UINT16;
   42.53 +typedef unsigned int UINT32;
   42.54 +typedef unsigned long long UINT64;
   42.55 +
   42.56 +typedef UINT32 TPM_RESULT;
   42.57 +typedef UINT32 TPM_PCRINDEX;
   42.58 +typedef UINT32 TPM_DIRINDEX;
   42.59 +typedef UINT32 TPM_HANDLE;
   42.60 +typedef TPM_HANDLE TPM_AUTHHANDLE;
   42.61 +typedef TPM_HANDLE TCPA_HASHHANDLE;
   42.62 +typedef TPM_HANDLE TCPA_HMACHANDLE;
   42.63 +typedef TPM_HANDLE TCPA_ENCHANDLE;
   42.64 +typedef TPM_HANDLE TPM_KEY_HANDLE;
   42.65 +typedef TPM_HANDLE TCPA_ENTITYHANDLE;
   42.66 +typedef UINT32 TPM_RESOURCE_TYPE;
   42.67 +typedef UINT32 TPM_COMMAND_CODE;
   42.68 +typedef UINT16 TPM_PROTOCOL_ID;
   42.69 +typedef BYTE TPM_AUTH_DATA_USAGE;
   42.70 +typedef UINT16 TPM_ENTITY_TYPE;
   42.71 +typedef UINT32 TPM_ALGORITHM_ID;
   42.72 +typedef UINT16 TPM_KEY_USAGE;
   42.73 +typedef UINT16 TPM_STARTUP_TYPE;
   42.74 +typedef UINT32 TPM_CAPABILITY_AREA;
   42.75 +typedef UINT16 TPM_ENC_SCHEME;
   42.76 +typedef UINT16 TPM_SIG_SCHEME;
   42.77 +typedef UINT16 TPM_MIGRATE_SCHEME;
   42.78 +typedef UINT16 TPM_PHYSICAL_PRESENCE;
   42.79 +typedef UINT32 TPM_KEY_FLAGS;
   42.80 +
   42.81 +#define TPM_DIGEST_SIZE 20  // Don't change this
   42.82 +typedef BYTE TPM_AUTHDATA[TPM_DIGEST_SIZE];
   42.83 +typedef TPM_AUTHDATA TPM_SECRET;
   42.84 +typedef TPM_AUTHDATA TPM_ENCAUTH;
   42.85 +typedef BYTE TPM_PAYLOAD_TYPE;
   42.86 +typedef UINT16 TPM_TAG;
   42.87 +
   42.88 +// Data Types of the TCS
   42.89 +typedef UINT32 TCS_AUTHHANDLE;  // Handle addressing a authorization session
   42.90 +typedef UINT32 TCS_CONTEXT_HANDLE; // Basic context handle
   42.91 +typedef UINT32 TCS_KEY_HANDLE;  // Basic key handle
   42.92 +
   42.93 +// ************************* STRUCTURES **********************************
   42.94 +
   42.95 +typedef struct TPM_VERSION {
   42.96 +  BYTE major;
   42.97 +  BYTE minor;
   42.98 +  BYTE revMajor;
   42.99 +  BYTE revMinor;
  42.100 +} TPM_VERSION;
  42.101 + 
  42.102 +static const TPM_VERSION TPM_STRUCT_VER_1_1 = { 1,1,0,0 };
  42.103 +
  42.104 +typedef struct TPM_DIGEST {
  42.105 +  BYTE digest[TPM_DIGEST_SIZE];
  42.106 +} TPM_DIGEST;
  42.107 +
  42.108 +typedef TPM_DIGEST TPM_PCRVALUE;
  42.109 +typedef TPM_DIGEST TPM_COMPOSITE_HASH;
  42.110 +typedef TPM_DIGEST TPM_DIRVALUE;
  42.111 +typedef TPM_DIGEST TPM_HMAC;
  42.112 +typedef TPM_DIGEST TPM_CHOSENID_HASH;
  42.113 +
  42.114 +typedef struct TPM_NONCE {
  42.115 +  BYTE nonce[TPM_DIGEST_SIZE];
  42.116 +} TPM_NONCE;
  42.117 +
  42.118 +typedef struct TPM_KEY_PARMS {
  42.119 +  TPM_ALGORITHM_ID algorithmID;
  42.120 +  TPM_ENC_SCHEME encScheme;
  42.121 +  TPM_SIG_SCHEME sigScheme;
  42.122 +  UINT32 parmSize;
  42.123 +  BYTE* parms;
  42.124 +} TPM_KEY_PARMS;
  42.125 +
  42.126 +typedef struct TPM_RSA_KEY_PARMS {  
  42.127 +  UINT32 keyLength; 
  42.128 +  UINT32 numPrimes; 
  42.129 +  UINT32 exponentSize;
  42.130 +  BYTE* exponent;
  42.131 +} TPM_RSA_KEY_PARMS;
  42.132 +
  42.133 +typedef struct TPM_STORE_PUBKEY {
  42.134 +  UINT32 keyLength;
  42.135 +  BYTE* key;
  42.136 +} TPM_STORE_PUBKEY;
  42.137 +
  42.138 +typedef struct TPM_PUBKEY {
  42.139 +  TPM_KEY_PARMS algorithmParms;
  42.140 +  TPM_STORE_PUBKEY pubKey;
  42.141 +} TPM_PUBKEY;
  42.142 +
  42.143 +typedef struct TPM_KEY {
  42.144 +  TPM_VERSION         ver;
  42.145 +  TPM_KEY_USAGE       keyUsage;
  42.146 +  TPM_KEY_FLAGS       keyFlags;
  42.147 +  TPM_AUTH_DATA_USAGE authDataUsage;
  42.148 +  TPM_KEY_PARMS       algorithmParms; 
  42.149 +  UINT32              PCRInfoSize;
  42.150 +  BYTE*               PCRInfo; // this should be a TPM_PCR_INFO, or NULL
  42.151 +  TPM_STORE_PUBKEY    pubKey;
  42.152 +  UINT32              encDataSize;
  42.153 +  BYTE*               encData;
  42.154 +} TPM_KEY;
  42.155 +
  42.156 +typedef struct TPM_PCR_SELECTION { 
  42.157 +  UINT16 sizeOfSelect;        /// in bytes
  42.158 +  BYTE* pcrSelect;
  42.159 +} TPM_PCR_SELECTION;
  42.160 +
  42.161 +typedef struct TPM_PCR_COMPOSITE { 
  42.162 +  TPM_PCR_SELECTION select;
  42.163 +  UINT32 valueSize;
  42.164 +  TPM_PCRVALUE* pcrValue;
  42.165 +} TPM_PCR_COMPOSITE;
  42.166 +
  42.167 +
  42.168 +typedef struct TPM_PCR_INFO {
  42.169 +  TPM_PCR_SELECTION pcrSelection;
  42.170 +  TPM_COMPOSITE_HASH digestAtRelease;
  42.171 +  TPM_COMPOSITE_HASH digestAtCreation;
  42.172 +} TPM_PCR_INFO;
  42.173 +
  42.174 +
  42.175 +typedef struct TPM_BOUND_DATA {
  42.176 +  TPM_VERSION ver;
  42.177 +  TPM_PAYLOAD_TYPE payload;
  42.178 +  BYTE* payloadData;
  42.179 +} TPM_BOUND_DATA;
  42.180 +
  42.181 +typedef struct TPM_STORED_DATA { 
  42.182 +  TPM_VERSION ver;
  42.183 +  UINT32 sealInfoSize;
  42.184 +  BYTE* sealInfo;
  42.185 +  UINT32 encDataSize;
  42.186 +  BYTE* encData;
  42.187 +} TPM_STORED_DATA;
  42.188 +
  42.189 +typedef struct TCS_AUTH {
  42.190 +  TCS_AUTHHANDLE  AuthHandle;
  42.191 +  TPM_NONCE   NonceOdd;   // system 
  42.192 +  TPM_NONCE   NonceEven;   // TPM 
  42.193 +  BOOL   fContinueAuthSession;
  42.194 +  TPM_AUTHDATA  HMAC;
  42.195 +} TCS_AUTH;
  42.196 +
  42.197 +// **************************** CONSTANTS *********************************
  42.198 +
  42.199 +// BOOL values
  42.200 +#define TRUE 0x01
  42.201 +#define FALSE 0x00
  42.202 +
  42.203 +#define TCPA_MAX_BUFFER_LENGTH 0x2000
  42.204 +
  42.205 +//
  42.206 +// TPM_COMMAND_CODE values
  42.207 +#define TPM_PROTECTED_ORDINAL 0x00000000UL
  42.208 +#define TPM_UNPROTECTED_ORDINAL 0x80000000UL
  42.209 +#define TPM_CONNECTION_ORDINAL 0x40000000UL
  42.210 +#define TPM_VENDOR_ORDINAL 0x20000000UL
  42.211 +
  42.212 +#define TPM_ORD_OIAP                     (10UL + TPM_PROTECTED_ORDINAL)
  42.213 +#define TPM_ORD_OSAP                     (11UL + TPM_PROTECTED_ORDINAL)
  42.214 +#define TPM_ORD_ChangeAuth               (12UL + TPM_PROTECTED_ORDINAL)
  42.215 +#define TPM_ORD_TakeOwnership            (13UL + TPM_PROTECTED_ORDINAL)
  42.216 +#define TPM_ORD_ChangeAuthAsymStart      (14UL + TPM_PROTECTED_ORDINAL)
  42.217 +#define TPM_ORD_ChangeAuthAsymFinish     (15UL + TPM_PROTECTED_ORDINAL)
  42.218 +#define TPM_ORD_ChangeAuthOwner          (16UL + TPM_PROTECTED_ORDINAL)
  42.219 +#define TPM_ORD_Extend                   (20UL + TPM_PROTECTED_ORDINAL)
  42.220 +#define TPM_ORD_PcrRead                  (21UL + TPM_PROTECTED_ORDINAL)
  42.221 +#define TPM_ORD_Quote                    (22UL + TPM_PROTECTED_ORDINAL)
  42.222 +#define TPM_ORD_Seal                     (23UL + TPM_PROTECTED_ORDINAL)
  42.223 +#define TPM_ORD_Unseal                   (24UL + TPM_PROTECTED_ORDINAL)
  42.224 +#define TPM_ORD_DirWriteAuth             (25UL + TPM_PROTECTED_ORDINAL)
  42.225 +#define TPM_ORD_DirRead                  (26UL + TPM_PROTECTED_ORDINAL)
  42.226 +#define TPM_ORD_UnBind                   (30UL + TPM_PROTECTED_ORDINAL)
  42.227 +#define TPM_ORD_CreateWrapKey            (31UL + TPM_PROTECTED_ORDINAL)
  42.228 +#define TPM_ORD_LoadKey                  (32UL + TPM_PROTECTED_ORDINAL)
  42.229 +#define TPM_ORD_GetPubKey                (33UL + TPM_PROTECTED_ORDINAL)
  42.230 +#define TPM_ORD_EvictKey                 (34UL + TPM_PROTECTED_ORDINAL)
  42.231 +#define TPM_ORD_CreateMigrationBlob      (40UL + TPM_PROTECTED_ORDINAL)
  42.232 +#define TPM_ORD_ReWrapKey                (41UL + TPM_PROTECTED_ORDINAL)
  42.233 +#define TPM_ORD_ConvertMigrationBlob     (42UL + TPM_PROTECTED_ORDINAL)
  42.234 +#define TPM_ORD_AuthorizeMigrationKey    (43UL + TPM_PROTECTED_ORDINAL)
  42.235 +#define TPM_ORD_CreateMaintenanceArchive (44UL + TPM_PROTECTED_ORDINAL)
  42.236 +#define TPM_ORD_LoadMaintenanceArchive   (45UL + TPM_PROTECTED_ORDINAL)
  42.237 +#define TPM_ORD_KillMaintenanceFeature   (46UL + TPM_PROTECTED_ORDINAL)
  42.238 +#define TPM_ORD_LoadManuMaintPub         (47UL + TPM_PROTECTED_ORDINAL)
  42.239 +#define TPM_ORD_ReadManuMaintPub         (48UL + TPM_PROTECTED_ORDINAL)
  42.240 +#define TPM_ORD_CertifyKey               (50UL + TPM_PROTECTED_ORDINAL)
  42.241 +#define TPM_ORD_Sign                     (60UL + TPM_PROTECTED_ORDINAL)
  42.242 +#define TPM_ORD_GetRandom                (70UL + TPM_PROTECTED_ORDINAL)
  42.243 +#define TPM_ORD_StirRandom               (71UL + TPM_PROTECTED_ORDINAL)
  42.244 +#define TPM_ORD_SelfTestFull             (80UL + TPM_PROTECTED_ORDINAL)
  42.245 +#define TPM_ORD_SelfTestStartup          (81UL + TPM_PROTECTED_ORDINAL)
  42.246 +#define TPM_ORD_CertifySelfTest          (82UL + TPM_PROTECTED_ORDINAL)
  42.247 +#define TPM_ORD_ContinueSelfTest         (83UL + TPM_PROTECTED_ORDINAL)
  42.248 +#define TPM_ORD_GetTestResult            (84UL + TPM_PROTECTED_ORDINAL)
  42.249 +#define TPM_ORD_Reset                    (90UL + TPM_PROTECTED_ORDINAL)
  42.250 +#define TPM_ORD_OwnerClear               (91UL + TPM_PROTECTED_ORDINAL)
  42.251 +#define TPM_ORD_DisableOwnerClear        (92UL + TPM_PROTECTED_ORDINAL)
  42.252 +#define TPM_ORD_ForceClear               (93UL + TPM_PROTECTED_ORDINAL)
  42.253 +#define TPM_ORD_DisableForceClear        (94UL + TPM_PROTECTED_ORDINAL)
  42.254 +#define TPM_ORD_GetCapabilitySigned      (100UL + TPM_PROTECTED_ORDINAL)
  42.255 +#define TPM_ORD_GetCapability            (101UL + TPM_PROTECTED_ORDINAL)
  42.256 +#define TPM_ORD_GetCapabilityOwner       (102UL + TPM_PROTECTED_ORDINAL)
  42.257 +#define TPM_ORD_OwnerSetDisable          (110UL + TPM_PROTECTED_ORDINAL)
  42.258 +#define TPM_ORD_PhysicalEnable           (111UL + TPM_PROTECTED_ORDINAL)
  42.259 +#define TPM_ORD_PhysicalDisable          (112UL + TPM_PROTECTED_ORDINAL)
  42.260 +#define TPM_ORD_SetOwnerInstall          (113UL + TPM_PROTECTED_ORDINAL)
  42.261 +#define TPM_ORD_PhysicalSetDeactivated   (114UL + TPM_PROTECTED_ORDINAL)
  42.262 +#define TPM_ORD_SetTempDeactivated       (115UL + TPM_PROTECTED_ORDINAL)
  42.263 +#define TPM_ORD_CreateEndorsementKeyPair (120UL + TPM_PROTECTED_ORDINAL)
  42.264 +#define TPM_ORD_MakeIdentity             (121UL + TPM_PROTECTED_ORDINAL)
  42.265 +#define TPM_ORD_ActivateIdentity         (122UL + TPM_PROTECTED_ORDINAL)
  42.266 +#define TPM_ORD_ReadPubek                (124UL + TPM_PROTECTED_ORDINAL)
  42.267 +#define TPM_ORD_OwnerReadPubek           (125UL + TPM_PROTECTED_ORDINAL)
  42.268 +#define TPM_ORD_DisablePubekRead         (126UL + TPM_PROTECTED_ORDINAL)
  42.269 +#define TPM_ORD_GetAuditEvent            (130UL + TPM_PROTECTED_ORDINAL)
  42.270 +#define TPM_ORD_GetAuditEventSigned      (131UL + TPM_PROTECTED_ORDINAL)
  42.271 +#define TPM_ORD_GetOrdinalAuditStatus    (140UL + TPM_PROTECTED_ORDINAL)
  42.272 +#define TPM_ORD_SetOrdinalAuditStatus    (141UL + TPM_PROTECTED_ORDINAL)
  42.273 +#define TPM_ORD_Terminate_Handle         (150UL + TPM_PROTECTED_ORDINAL)
  42.274 +#define TPM_ORD_Init                     (151UL + TPM_PROTECTED_ORDINAL)
  42.275 +#define TPM_ORD_SaveState                (152UL + TPM_PROTECTED_ORDINAL)
  42.276 +#define TPM_ORD_Startup                  (153UL + TPM_PROTECTED_ORDINAL)
  42.277 +#define TPM_ORD_SetRedirection           (154UL + TPM_PROTECTED_ORDINAL)
  42.278 +#define TPM_ORD_SHA1Start                (160UL + TPM_PROTECTED_ORDINAL)
  42.279 +#define TPM_ORD_SHA1Update               (161UL + TPM_PROTECTED_ORDINAL)
  42.280 +#define TPM_ORD_SHA1Complete             (162UL + TPM_PROTECTED_ORDINAL)
  42.281 +#define TPM_ORD_SHA1CompleteExtend       (163UL + TPM_PROTECTED_ORDINAL)
  42.282 +#define TPM_ORD_FieldUpgrade             (170UL + TPM_PROTECTED_ORDINAL)
  42.283 +#define TPM_ORD_SaveKeyContext           (180UL + TPM_PROTECTED_ORDINAL)
  42.284 +#define TPM_ORD_LoadKeyContext           (181UL + TPM_PROTECTED_ORDINAL)
  42.285 +#define TPM_ORD_SaveAuthContext          (182UL + TPM_PROTECTED_ORDINAL)
  42.286 +#define TPM_ORD_LoadAuthContext          (183UL + TPM_PROTECTED_ORDINAL)
  42.287 +#define TSC_ORD_PhysicalPresence         (10UL + TPM_CONNECTION_ORDINAL)
  42.288 +
  42.289 +
  42.290 +
  42.291 +//
  42.292 +// TPM_RESULT values
  42.293 +//
  42.294 +// just put in the whole table from spec 1.2
  42.295 +              
  42.296 +#define TPM_BASE   0x0 // The start of TPM return codes
  42.297 +#define TPM_VENDOR_ERROR 0x00000400 // Mask to indicate that the error code is vendor specific for vendor specific commands
  42.298 +#define TPM_NON_FATAL  0x00000800 // Mask to indicate that the error code is a non-fatal failure.
  42.299 +
  42.300 +#define TPM_SUCCESS   TPM_BASE // Successful completion of the operation
  42.301 +#define TPM_AUTHFAIL      TPM_BASE + 1 // Authentication failed
  42.302 +#define TPM_BADINDEX      TPM_BASE + 2 // The index to a PCR, DIR or other register is incorrect
  42.303 +#define TPM_BAD_PARAMETER     TPM_BASE + 3 // One or more parameter is bad
  42.304 +#define TPM_AUDITFAILURE     TPM_BASE + 4 // An operation completed successfully but the auditing of that operation failed.
  42.305 +#define TPM_CLEAR_DISABLED     TPM_BASE + 5 // The clear disable flag is set and all clear operations now require physical access
  42.306 +#define TPM_DEACTIVATED     TPM_BASE + 6 // The TPM is deactivated
  42.307 +#define TPM_DISABLED      TPM_BASE + 7 // The TPM is disabled
  42.308 +#define TPM_DISABLED_CMD     TPM_BASE + 8 // The target command has been disabled
  42.309 +#define TPM_FAIL       TPM_BASE + 9 // The operation failed
  42.310 +#define TPM_BAD_ORDINAL     TPM_BASE + 10 // The ordinal was unknown or inconsistent
  42.311 +#define TPM_INSTALL_DISABLED   TPM_BASE + 11 // The ability to install an owner is disabled
  42.312 +#define TPM_INVALID_KEYHANDLE  TPM_BASE + 12 // The key handle presented was invalid
  42.313 +#define TPM_KEYNOTFOUND     TPM_BASE + 13 // The target key was not found
  42.314 +#define TPM_INAPPROPRIATE_ENC  TPM_BASE + 14 // Unacceptable encryption scheme
  42.315 +#define TPM_MIGRATEFAIL     TPM_BASE + 15 // Migration authorization failed
  42.316 +#define TPM_INVALID_PCR_INFO   TPM_BASE + 16 // PCR information could not be interpreted
  42.317 +#define TPM_NOSPACE      TPM_BASE + 17 // No room to load key.
  42.318 +#define TPM_NOSRK       TPM_BASE + 18 // There is no SRK set
  42.319 +#define TPM_NOTSEALED_BLOB     TPM_BASE + 19 // An encrypted blob is invalid or was not created by this TPM
  42.320 +#define TPM_OWNER_SET      TPM_BASE + 20 // There is already an Owner
  42.321 +#define TPM_RESOURCES      TPM_BASE + 21 // The TPM has insufficient internal resources to perform the requested action.
  42.322 +#define TPM_SHORTRANDOM     TPM_BASE + 22 // A random string was too short
  42.323 +#define TPM_SIZE       TPM_BASE + 23 // The TPM does not have the space to perform the operation.
  42.324 +#define TPM_WRONGPCRVAL     TPM_BASE + 24 // The named PCR value does not match the current PCR value.
  42.325 +#define TPM_BAD_PARAM_SIZE     TPM_BASE + 25 // The paramSize argument to the command has the incorrect value
  42.326 +#define TPM_SHA_THREAD      TPM_BASE + 26 // There is no existing SHA-1 thread.
  42.327 +#define TPM_SHA_ERROR      TPM_BASE + 27 // The calculation is unable to proceed because the existing SHA-1 thread has already encountered an error.
  42.328 +#define TPM_FAILEDSELFTEST     TPM_BASE + 28 // Self-test has failed and the TPM has shutdown.
  42.329 +#define TPM_AUTH2FAIL      TPM_BASE + 29 // The authorization for the second key in a 2 key function failed authorization
  42.330 +#define TPM_BADTAG       TPM_BASE + 30 // The tag value sent to for a command is invalid
  42.331 +#define TPM_IOERROR      TPM_BASE + 31 // An IO error occurred transmitting information to the TPM
  42.332 +#define TPM_ENCRYPT_ERROR     TPM_BASE + 32 // The encryption process had a problem.
  42.333 +#define TPM_DECRYPT_ERROR     TPM_BASE + 33 // The decryption process did not complete.
  42.334 +#define TPM_INVALID_AUTHHANDLE TPM_BASE + 34 // An invalid handle was used.
  42.335 +#define TPM_NO_ENDORSEMENT     TPM_BASE + 35 // The TPM does not a EK installed
  42.336 +#define TPM_INVALID_KEYUSAGE   TPM_BASE + 36 // The usage of a key is not allowed
  42.337 +#define TPM_WRONG_ENTITYTYPE   TPM_BASE + 37 // The submitted entity type is not allowed
  42.338 +#define TPM_INVALID_POSTINIT   TPM_BASE + 38 // The command was received in the wrong sequence relative to TPM_Init and a subsequent TPM_Startup
  42.339 +#define TPM_INAPPROPRIATE_SIG  TPM_BASE + 39 // Signed data cannot include additional DER information
  42.340 +#define TPM_BAD_KEY_PROPERTY   TPM_BASE + 40 // The key properties in TPM_KEY_PARMs are not supported by this TPM
  42.341 +
  42.342 +#define TPM_BAD_MIGRATION      TPM_BASE + 41 // The migration properties of this key are incorrect.
  42.343 +#define TPM_BAD_SCHEME       TPM_BASE + 42 // The signature or encryption scheme for this key is incorrect or not permitted in this situation.
  42.344 +#define TPM_BAD_DATASIZE      TPM_BASE + 43 // The size of the data (or blob) parameter is bad or inconsistent with the referenced key
  42.345 +#define TPM_BAD_MODE       TPM_BASE + 44 // A mode parameter is bad, such as capArea or subCapArea for TPM_GetCapability, phsicalPresence parameter for TPM_PhysicalPresence, or migrationType for TPM_CreateMigrationBlob.
  42.346 +#define TPM_BAD_PRESENCE      TPM_BASE + 45 // Either the physicalPresence or physicalPresenceLock bits have the wrong value
  42.347 +#define TPM_BAD_VERSION      TPM_BASE + 46 // The TPM cannot perform this version of the capability
  42.348 +#define TPM_NO_WRAP_TRANSPORT     TPM_BASE + 47 // The TPM does not allow for wrapped transport sessions
  42.349 +#define TPM_AUDITFAIL_UNSUCCESSFUL TPM_BASE + 48 // TPM audit construction failed and the underlying command was returning a failure code also
  42.350 +#define TPM_AUDITFAIL_SUCCESSFUL   TPM_BASE + 49 // TPM audit construction failed and the underlying command was returning success
  42.351 +#define TPM_NOTRESETABLE      TPM_BASE + 50 // Attempt to reset a PCR register that does not have the resettable attribute
  42.352 +#define TPM_NOTLOCAL       TPM_BASE + 51 // Attempt to reset a PCR register that requires locality and locality modifier not part of command transport
  42.353 +#define TPM_BAD_TYPE       TPM_BASE + 52 // Make identity blob not properly typed
  42.354 +#define TPM_INVALID_RESOURCE     TPM_BASE + 53 // When saving context identified resource type does not match actual resource
  42.355 +#define TPM_NOTFIPS       TPM_BASE + 54 // The TPM is attempting to execute a command only available when in FIPS mode
  42.356 +#define TPM_INVALID_FAMILY      TPM_BASE + 55 // The command is attempting to use an invalid family ID
  42.357 +#define TPM_NO_NV_PERMISSION     TPM_BASE + 56 // The permission to manipulate the NV storage is not available
  42.358 +#define TPM_REQUIRES_SIGN      TPM_BASE + 57 // The operation requires a signed command
  42.359 +#define TPM_KEY_NOTSUPPORTED     TPM_BASE + 58 // Wrong operation to load an NV key
  42.360 +#define TPM_AUTH_CONFLICT      TPM_BASE + 59 // NV_LoadKey blob requires both owner and blob authorization
  42.361 +#define TPM_AREA_LOCKED      TPM_BASE + 60 // The NV area is locked and not writtable
  42.362 +#define TPM_BAD_LOCALITY      TPM_BASE + 61 // The locality is incorrect for the attempted operation
  42.363 +#define TPM_READ_ONLY       TPM_BASE + 62 // The NV area is read only and can't be written to
  42.364 +#define TPM_PER_NOWRITE      TPM_BASE + 63 // There is no protection on the write to the NV area
  42.365 +#define TPM_FAMILYCOUNT      TPM_BASE + 64 // The family count value does not match
  42.366 +#define TPM_WRITE_LOCKED      TPM_BASE + 65 // The NV area has already been written to
  42.367 +#define TPM_BAD_ATTRIBUTES      TPM_BASE + 66 // The NV area attributes conflict
  42.368 +#define TPM_INVALID_STRUCTURE     TPM_BASE + 67 // The structure tag and version are invalid or inconsistent
  42.369 +#define TPM_KEY_OWNER_CONTROL     TPM_BASE + 68 // The key is under control of the TPM Owner and can only be evicted by the TPM Owner.
  42.370 +#define TPM_BAD_COUNTER      TPM_BASE + 69 // The counter handle is incorrect
  42.371 +#define TPM_NOT_FULLWRITE      TPM_BASE + 70 // The write is not a complete write of the area
  42.372 +#define TPM_CONTEXT_GAP      TPM_BASE + 71 // The gap between saved context counts is too large
  42.373 +#define TPM_MAXNVWRITES      TPM_BASE + 72 // The maximum number of NV writes without an owner has been exceeded
  42.374 +#define TPM_NOOPERATOR       TPM_BASE + 73 // No operator authorization value is set
  42.375 +#define TPM_RESOURCEMISSING     TPM_BASE + 74 // The resource pointed to by context is not loaded
  42.376 +#define TPM_DELEGATE_LOCK      TPM_BASE + 75 // The delegate administration is locked
  42.377 +#define TPM_DELEGATE_FAMILY     TPM_BASE + 76 // Attempt to manage a family other then the delegated family
  42.378 +#define TPM_DELEGATE_ADMIN      TPM_BASE + 77 // Delegation table management not enabled
  42.379 +#define TPM_TRANSPORT_EXCLUSIVE    TPM_BASE + 78 // There was a command executed outside of an exclusive transport session
  42.380 +
  42.381 +// TPM_TAG values
  42.382 +#define TPM_TAG_RQU_COMMAND 0x00c1
  42.383 +#define TPM_TAG_RQU_AUTH1_COMMAND 0x00c2
  42.384 +#define TPM_TAG_RQU_AUTH2_COMMAND 0x00c3
  42.385 +#define TPM_TAG_RSP_COMMAND 0x00c4
  42.386 +#define TPM_TAG_RSP_AUTH1_COMMAND 0x00c5
  42.387 +#define TPM_TAG_RSP_AUTH2_COMMAND 0x00c6
  42.388 +
  42.389 +// TPM_PAYLOAD_TYPE values
  42.390 +#define TPM_PT_ASYM 0x01
  42.391 +#define TPM_PT_BIND 0x02
  42.392 +#define TPM_PT_MIGRATE 0x03
  42.393 +#define TPM_PT_MAINT 0x04
  42.394 +#define TPM_PT_SEAL 0x05
  42.395 +
  42.396 +// TPM_ENTITY_TYPE values
  42.397 +#define TPM_ET_KEYHANDLE 0x0001
  42.398 +#define TPM_ET_OWNER 0x0002
  42.399 +#define TPM_ET_DATA 0x0003
  42.400 +#define TPM_ET_SRK 0x0004
  42.401 +#define TPM_ET_KEY 0x0005
  42.402 +
  42.403 +/// TPM_ResourceTypes
  42.404 +#define TPM_RT_KEY      0x00000001
  42.405 +#define TPM_RT_AUTH     0x00000002
  42.406 +#define TPM_RT_TRANS    0x00000004
  42.407 +#define TPM_RT_CONTEXT  0x00000005
  42.408 +
  42.409 +// TPM_PROTOCOL_ID values
  42.410 +#define TPM_PID_OIAP 0x0001
  42.411 +#define TPM_PID_OSAP 0x0002
  42.412 +#define TPM_PID_ADIP 0x0003
  42.413 +#define TPM_PID_ADCP 0x0004
  42.414 +#define TPM_PID_OWNER 0x0005
  42.415 +
  42.416 +// TPM_ALGORITHM_ID values
  42.417 +#define TPM_ALG_RSA 0x00000001
  42.418 +#define TPM_ALG_DES 0x00000002
  42.419 +#define TPM_ALG_3DES 0X00000003
  42.420 +#define TPM_ALG_SHA 0x00000004
  42.421 +#define TPM_ALG_HMAC 0x00000005
  42.422 +#define TCPA_ALG_AES 0x00000006
  42.423 +
  42.424 +// TPM_ENC_SCHEME values
  42.425 +#define TPM_ES_NONE 0x0001
  42.426 +#define TPM_ES_RSAESPKCSv15 0x0002
  42.427 +#define TPM_ES_RSAESOAEP_SHA1_MGF1 0x0003
  42.428 +
  42.429 +// TPM_SIG_SCHEME values
  42.430 +#define TPM_SS_NONE 0x0001
  42.431 +#define TPM_SS_RSASSAPKCS1v15_SHA1 0x0002
  42.432 +#define TPM_SS_RSASSAPKCS1v15_DER 0x0003
  42.433 +
  42.434 +// TPM_KEY_USAGE values
  42.435 +#define TPM_KEY_EK 0x0000 
  42.436 +#define TPM_KEY_SIGNING 0x0010
  42.437 +#define TPM_KEY_STORAGE 0x0011
  42.438 +#define TPM_KEY_IDENTITY 0x0012
  42.439 +#define TPM_KEY_AUTHCHANGE 0X0013
  42.440 +#define TPM_KEY_BIND 0x0014
  42.441 +#define TPM_KEY_LEGACY 0x0015
  42.442 +
  42.443 +// TPM_AUTH_DATA_USAGE values
  42.444 +#define TPM_AUTH_NEVER 0x00
  42.445 +#define TPM_AUTH_ALWAYS 0x01
  42.446 +
  42.447 +// Key Handle of owner and srk
  42.448 +#define TPM_OWNER_KEYHANDLE 0x40000001
  42.449 +#define TPM_SRK_KEYHANDLE 0x40000000
  42.450 +
  42.451 +// ---------------------- Functions for checking TPM_RESULTs -----------------
  42.452 +
  42.453 +// FIXME: Review use of these and delete unneeded ones.
  42.454 +
  42.455 +// these are really badly dependent on local structure:
  42.456 +// DEPENDS: local var 'status' of type TPM_RESULT
  42.457 +// DEPENDS: label 'abort_egress' which cleans up and returns the status
  42.458 +#define ERRORDIE(s) do { status = s; \
  42.459 +                         fprintf (stderr, "*** ERRORDIE in %s, line %i\n", __func__, __LINE__); \
  42.460 +                         goto abort_egress; } \
  42.461 +                    while (0)
  42.462 +
  42.463 +// ASSUME: the return value used after the abort_egress label has been set
  42.464 +// already (eg. the 'status' local var)
  42.465 +#define STATUSCHECK(s) if (s != TPM_SUCCESS) { \
  42.466 +                            fprintf (stderr, "*** ERR in %s, line %i\n", __func__, __LINE__); \
  42.467 +                            goto abort_egress; \
  42.468 +                        }
  42.469 +
  42.470 +// DEPENDS: local var 'status' of type TPM_RESULT
  42.471 +// DEPENDS: label 'abort_egress' which cleans up and returns the status
  42.472 +// Try command c. If it fails, set status to s and goto shame.
  42.473 +#define TPMTRY(s,c) if (c != TPM_SUCCESS) { \
  42.474 +                       status = s; \
  42.475 +                       goto abort_egress; \
  42.476 +                    }
  42.477 +
  42.478 +// Try command c. If it fails, print error message, set status to actual return code. Goto shame
  42.479 +#define TPMTRYRETURN(c) do { status = c; \
  42.480 +                             if (status != TPM_SUCCESS) { \
  42.481 +                               printf("ERROR in %s:%i code: %s.\n", __func__, __LINE__, tpm_get_error_name(status)); \
  42.482 +                               goto abort_egress; \
  42.483 +                             } \
  42.484 +                        } while(0)    
  42.485 +
  42.486 +
  42.487 +#pragma pack(pop)
  42.488 +
  42.489 +#endif //__TCPA_H__