Exemplo n.º 1
0
int main(void)
{
    unsigned char buffer[1024];
    unsigned int i = 0;
    unsigned int ones = 0, zeroes = 0;
    unsigned int pattern2[4] = {0,0,0,0};

    TPM_setlog(0);

    printf("Counting number of '1's and '0's of the rng.\n");
    while (i < 10) {
        uint32_t bufferSize = sizeof(buffer);
        unsigned int j = 0;
        uint32_t ret;
        ret = TPM_GetRandom(bufferSize,
                            buffer, &bufferSize);
        if (0 != ret) {
            printf("Error %s from TPM_GetRandom.\n",
                   TPM_GetErrMsg(ret));
            exit (ret);
        }
        while (j < bufferSize) {
            unsigned int c = countOnes(buffer[j]);
            ones += c;
            zeroes += (8-c);
            pattern2[0] += matchPattern(buffer[j], 0x0, 2);
            pattern2[1] += matchPattern(buffer[j], 0x1, 2);
            pattern2[2] += matchPattern(buffer[j], 0x2, 2);
            pattern2[3] += matchPattern(buffer[j], 0x3, 2);
            j++;
        }
        ret = TPM_StirRandom(buffer, 10);
        if (0 != ret) {
            printf("Error %s from TPM_StirRandom.\n",
                   TPM_GetErrMsg(ret));
            exit(ret);
        }
        i++;
    }
    printf("Percentage of '1': %d percent.\n", (ones*100)/(ones+zeroes));
    printf("Percentage of '00' bits:  %d percent\n",
           (pattern2[0]*200)/(ones+zeroes));
    printf("Percentage of '01' bits:  %d percent\n",
           (pattern2[1]*200)/(ones+zeroes));
    printf("Percentage of '10' bits:  %d percent\n",
           (pattern2[2]*200)/(ones+zeroes));
    printf("Percentage of '11' bits:  %d percent\n",
           (pattern2[3]*200)/(ones+zeroes));
    return 0;
}
Exemplo n.º 2
0
int main(int argc, char *argv[])
{
    int ret = 0;
    int			i;			/* argc iterator */

    TPM_setlog(0);	    /* turn off verbose output */

    for (i=1 ; i<argc ; i++) {
        if (!strcmp(argv[i], "-h")) {
            printUsage();
        }
        else if (!strcmp(argv[i], "-v")) {
            TPM_setlog(1);
        }
        else {
            printf("\n%s is not a valid option\n", argv[i]);
            printUsage();
        }
    }

    if (ret == 0) {
        ret = TPM_Init();
        if (ret != 0) {
            printf("Error %s from TPM_Init.\n",
                   TPM_GetErrMsg(ret));
        }
    }
    exit(ret);
}
Exemplo n.º 3
0
static int prepare_subcap(uint32_t cap,
                          struct tpm_buffer *subcap,
                          uint32_t scap)
{
	int handled = 0;
	uint32_t ret;
	if (TPM_CAP_CHECK_LOADED == cap) {
		struct keydata k;
		memset(&k, 0, sizeof(k));
		handled = 1;
		k.keyFlags = 0;
		k.keyUsage = TPM_KEY_LEGACY;
		k.pub.algorithmParms.algorithmID = scap;
		k.pub.algorithmParms.encScheme = TPM_ES_NONE;
		k.pub.algorithmParms.sigScheme = TPM_SS_RSASSAPKCS1v15_INFO;
		k.pub.algorithmParms.u.rsaKeyParms.keyLength = 2048   ;      /* RSA modulus size 2048 bits */
		k.pub.algorithmParms.u.rsaKeyParms.numPrimes = 2;            /* required */
		k.pub.algorithmParms.u.rsaKeyParms.exponentSize   = 0;       /* RSA exponent - default 0x010001 */
		k.pub.pubKey.keyLength = 0;       /* key not specified here */
		k.pub.pcrInfo.size = 0;           /* no PCR's used at this time */
		ret = TPM_WriteKeyInfo(subcap, &k);
		if (ret & ERR_MASK) {
		        printf("Error from writing key info: %s\n",
		               TPM_GetErrMsg(ret));
		}
	}
	return handled;
}
Exemplo n.º 4
0
static long getPhysicalCMDEnable(TPM_BOOL *physicalPresenceCMDEnable)
{
    uint32_t ret = 0;
    STACK_TPM_BUFFER( subcap );
    STACK_TPM_BUFFER( resp );
    STACK_TPM_BUFFER( tb );
    TPM_PERMANENT_FLAGS permanentFlags;
    
    if (ret == 0) {
	STORE32(subcap.buffer, 0, TPM_CAP_FLAG_PERMANENT  );
	subcap.used = 4;
	ret = TPM_GetCapability(TPM_CAP_FLAG,
				&subcap,
				&resp);
	if (ret != 0) {
	    printf("Error %s from TPM_GetCapability\n",
		   TPM_GetErrMsg(ret));
	}
    }
    if (ret == 0) {
	TSS_SetTPMBuffer(&tb, resp.buffer, resp.used);
	ret = TPM_ReadPermanentFlags(&tb, 0, &permanentFlags, resp.used);
	if ( ( ret & ERR_MASK ) != 0 || ret > resp.used) {
	    printf("TPM_ReadPermanentFlags: ret %08x, responselen %d\n", ret, resp.used);
	    printf("TPM_ReadPermanentFlags: Error parsing response!\n");
	}
	else {
	    ret = 0;
	}
    }
    if (ret == 0) {
	*physicalPresenceCMDEnable = permanentFlags.physicalPresenceCMDEnable;
    }
    return ret;
}
Exemplo n.º 5
0
int main(int argc, char *argv[])
{
	int ret;
	int	i;		/* argc iterator */
	TPM_setlog(0);      	/* turn off verbose output */
   
	for (i=1 ; i<argc ; i++) {
	    if (!strcmp(argv[i], "-h")) {
		printUsage();
	    }
	    else if (!strcmp(argv[i], "-v")) {
		TPM_setlog(1);
	    }
	    else {
		printf("\n%s is not a valid option\n", argv[i]);
		printUsage();
	    }
	}
	ret = TPM_DisableForceClear();
	if (0 != ret) {
		printf("DisableForceClear returned error '%s' (%d).\n",
		       TPM_GetErrMsg(ret),
		       ret);
	}
	exit(ret);
}
Exemplo n.º 6
0
int main(int argc, char *argv[])
{
	int 			ret = 0;
	int i = 1;

	TPM_setlog(0);      /* turn off verbose output */
	
	for (i=1 ; i<argc ; i++) {
	    if (!strcmp(argv[i], "-h")) {
		printUsage();
	    }
	    else if (!strcmp(argv[i], "-v")) {
		TPM_setlog(1);
	    }
	    else {
		printf("\n%s is not a valid option\n", argv[i]);
		printUsage();
	    }
	}
	ret = TPM_SetOwnerInstall(1);
	if (ret != 0) {
		printf(" ERROR: %s from TPM_SetOwnerInstall\n",
		TPM_GetErrMsg(ret));
	}
	exit(ret);
}
Exemplo n.º 7
0
int main(int argc, char *argv[])
{
	int ret;
	struct stat sbuf;	
	uint32_t parhandle;	/* handle of parent key */
	unsigned char blob[4096];	/* resulting sealed blob */
	unsigned int bloblen;	/* blob length */
	unsigned char passptr1[20] = {0};
	int fd, outlen;
	char totp[7];
	parhandle = 0x40000000;

	fd = open(argv[1], O_RDONLY);
	if (fd < 0) {
		perror("Unable to open file");
		return -1;
	}

	ret = fstat(fd, &sbuf);
	if (ret) {
		perror("Unable to stat file");
		return -1;
	}
	bloblen = sbuf.st_size;
	ret = read(fd, blob, bloblen);

	if (ret != bloblen) {
		fprintf(stderr, "Unable to read data\n");
		return -1;
	}
	ret = TPM_Unseal(parhandle,	/* KEY Entity Value */
			 passptr1,	/* Key Password */
			 NULL,
			 blob, bloblen,
			 key, &outlen);

	if (ret == 24) {
		fprintf(stderr, "TPM refused to decrypt key - boot process attests that it is modified\n");
		return -1;
	}

	if (ret != 0) {
		printf("Error %s from TPM_Unseal\n", TPM_GetErrMsg(ret));
		exit(6);
	}

	if (outlen != keylen) {
		fprintf(stderr, "Returned buffer is incorrect length\n");
		return -1;
	}

	ret = oath_totp_generate(key, keylen, time(NULL), 30, 0, 6, totp);
	if (ret != 0) {
		fprintf(stderr, "Error generating totp value\n");
		return -1;
	}
	printf("%s\n", totp);
}
Exemplo n.º 8
0
int main(int argc, char *argv[])
   {
   int ret;
   unsigned char passhash[TPM_HASH_SIZE];     /* hash of parent key password */
   unsigned char datahash[TPM_HASH_SIZE];     /* hash of data file */
   unsigned char sig[4096];        /* resulting signature */
   uint32_t  siglen;           /* signature length */
   unsigned char *passptr;
   FILE *sigfile;
   
   TPM_setlog(0);                  /* turn off verbose output */
   ParseArgs(argc, argv);
   if ((keyhandle == 0) ||
       (message == NULL) ||
       (sigfilename == NULL)) {
       printf("Missing parameter\n");
       printUsage();
   }

   /*
   ** use the SHA1 hash of the password string as the Key Authorization Data
   */
   if (keypass != NULL)
      {
      TSS_sha1(keypass,strlen(keypass),passhash);
      passptr = passhash;
      }
   else passptr = NULL;
   /*
   ** hash the message
   */
   TSS_sha1(message,strlen(message),datahash);

   ret = TPM_Sign(keyhandle,              /* Key Handle */
                  passptr,                /* key Password */
                  datahash,sizeof (datahash),     /* data to be signed, length */
                  sig,&siglen);           /* buffer to receive sig, int to receive sig length */
   if (ret != 0)
      {
      printf("Error %s from TPM_Sign\n",TPM_GetErrMsg(ret));
      exit(1);
      }
   sigfile = fopen(sigfilename, "wb");
   if (sigfile == NULL)
      {
      printf("Unable to open output file '%s'\n", sigfilename);
      exit(4);
      }
   ret = fwrite(sig,1,siglen,sigfile);
   if (ret != (int)siglen)
      {
      printf("I/O Error while writing output file '%s'\n", sigfilename);
      exit(5); 
      }
   fclose(sigfile);
   exit(0);
   }
Exemplo n.º 9
0
int main(int argc, char *argv[])
{
	unsigned char data[TPM_HASH_SIZE];
	int ret;
	int index = -1;
	int j = 0;
	int i = 1;
	
	TPM_setlog(0);

	while (i < argc) {
	    if (!strcmp("-ix",argv[i])) {
		i++;
		if (i < argc) {
		    if (1 != sscanf(argv[i],"%x",&index)) {
			printf("Could not parse the index number.\n");
			exit(-1);
		    }
		} else {
		    printf("Missing parameter for -ix.\n");
		    usage();
		}
	    }
	    else if (!strcmp("-v",argv[i])) {
		TPM_setlog(1);
	    }
	    else if (!strcmp("-h",argv[i])) {
		usage();
	    }
	    else {
		printf("\n%s is not a valid option\n",argv[i]);
		usage();
	    }
	    i++;
	}
	if (index == -1) {
	    printf("Missing -ix parameter\n");
	    usage();
	}

	ret = TPM_DirRead(index, data);


	if (0 != ret) {
		printf("DirRead returned error '%s'.\n",
		       TPM_GetErrMsg(ret));
	} else {
		printf("Content of DIR %d: ",index);
		while (j < (int)sizeof(data)) {
			printf("%02x",data[j]);
			j++;
		}
		printf("\n");
	}
	
	exit(ret);
}
Exemplo n.º 10
0
static uint32_t swapInKey(uint32_t handle)
{	
	char *filename = createKeyFilename(handle);
	STACK_TPM_BUFFER(context);
	unsigned char * mycontext = NULL;
	uint32_t contextSize;
	uint32_t newhandle;
	uint32_t ret;

	if (NULL == filename) {
		ret = ERR_MEM_ERR;
	}
	
	ret = TPM_ReadFile(filename,&mycontext,&contextSize);
	if ((ret & ERR_MASK)) {
#if 0
		printf("level: %d\n",g_num_transports);
#endif
		printf("Could not read from keyfile %s.\n",filename);
		return ret;
	}
	SET_TPM_BUFFER(&context, mycontext, contextSize);
	free(mycontext);
	
	ret = TPM_LoadContext(handle,
		              1,
		              &context,
		              &newhandle);

	if (ret != 0) {
		printf("Got error '%s' while swapping in key 0x%08x.\n",
		       TPM_GetErrMsg(ret),
		       handle);
	}
	if (handle != newhandle) {
		printf("keyswap: "
		       "new handle 0x%08x not the same as old one 0x%08x.\n",
		       newhandle, handle);
	}
	if (ret == 0) {
		unlink(filename);
	}
	free(filename);
#if 0
	if (ret == 0) {
		printf("Swapped in key with handle %08x.\n",handle);
	} else {
		printf("Could NOT swap in key with handle %08x.\n",handle);
	}
#endif
	
	return ret;
}
Exemplo n.º 11
0
int main(int argc, char *argv[])
{
	int ret = 0;
	unsigned char *passptr1;
	char * password = NULL;
	unsigned char passhash1[20];    /* hash of password */
	int i = 1;

	TPM_setlog(0);
	while (i  < argc) {
		if (!strcmp(argv[i],"-pwdk")) {
			i++;
			if (i >= argc) {
				printf("Parameter missing!\n");
				usage();
			}
			password = argv[i];
		} else 
		if (!strcmp(argv[i],"-v")) {
			TPM_setlog(1);
		} else 
		    if (!strcmp(argv[i],"-h")) {
			usage();
		} else {
			printf("\n%s is not a valid option\n", argv[i]);
			usage();
		}
		i++;
	}

	if (password != NULL) {
		TSS_sha1(password,strlen(password),passhash1);
		passptr1 = passhash1;
	} else {
	    printf("Missing parameter -pwdk\n");
	    exit(-1);
	}

	ret = TPM_RevokeTrust(passptr1);
	if (0 != ret) {
		printf("Error %s from TPM_RevokeTrust\n",
		       TPM_GetErrMsg(ret));
	}
 	exit(ret);
}
Exemplo n.º 12
0
int main(int argc, char *argv[])
{
	int ret;
	(void)argc;
	(void)argv;

	TPM_setlog(0);
   
	ret = TPM_ResetEstablishmentBit();


	if (0 != ret) {
		printf("ResetEstablishmentBit returned error '%s' (%d).\n",
		       TPM_GetErrMsg(ret),
		       ret);
	}
	

	exit(ret);
}
Exemplo n.º 13
0
static int addKeyToMSAList(TPM_MSA_COMPOSITE * msalist, char * filename)
{
	int ret  = 0;
	
	int len = strlen(filename);
	
	if (!strcmp(&filename[len-4],".pem")) {
		printf("Cannot deal with .pem files, yet.\n");
		ret = -1;
	} else
	if (!strcmp(&filename[len-4],".key") ||
	    !strcmp(&filename[len-4],".pub")) {
		struct keydata key;
		memset(&key, 0x0, sizeof(key));
		ret = TPM_ReadKeyfile(filename, &key);
		if ((ret & ERR_MASK)) {
			memset(&key, 0x0, sizeof(key));
			ret = TPM_ReadPubKeyfile(filename, &key.pub);
			if ((ret & ERR_MASK)) {
				printf("Error reading keyfile: %s\n", 
				       TPM_GetErrMsg(ret));
				return ret;
			}
		}
		if (ret == 0) {
			msalist->MSAlist++;
			msalist->migAuthDigest =
			          realloc(msalist->migAuthDigest,
			                  msalist->MSAlist * TPM_HASH_SIZE);
			TPM_HashPubKey(&key,
			               (unsigned char *)msalist->migAuthDigest + 
			               (msalist->MSAlist-1)* TPM_DIGEST_SIZE);
		}
	} else {
		printf("File '%s' in unknown format. Not .key or .pem.\n",
		       filename);
		ret = -1;
	}
	
	return ret;
}
Exemplo n.º 14
0
int main(int argc, char *argv[])
   {
   int ret = 0;
   uint32_t handle;
   int listsize;
   int offset;
   int	i;		/* argc iterator */
   TPM_setlog(0);      	/* turn off verbose output */
   
   for (i=1 ; i<argc ; i++) {
       if (!strcmp(argv[i], "-h")) {
	   printUsage();
       }
       else if (!strcmp(argv[i], "-v")) {
	   TPM_setlog(1);
       }
       else {
	   printf("\n%s is not a valid option\n", argv[i]);
	   printUsage();
       }
   }
   STACK_TPM_BUFFER(response);
   if (ret == 0) {
       ret = TPM_GetCapability(0x0000007,NULL,&response);
       if (ret != 0)
           {
               printf("Error %s from TPM_GetCapability\n",TPM_GetErrMsg(ret));
               exit(1);
           }
       listsize = LOAD16(response.buffer,0);
       offset = 2;
       for (i = 0; i < listsize; ++i)
           {
               handle = LOAD32(response.buffer,offset);
               printf("Key handle %02d %08x\n",i,handle);
               offset += 4;
           }
   }
   exit(0);
   }
Exemplo n.º 15
0
int main(int argc, char *argv[])
{
    int 	ret = 0;
    int		i;			/* argc iterator */
    TPM_BOOL	state = TRUE;

    TPM_setlog(0);      /* turn off verbose output */

    for (i=1 ; (i<argc) && (ret == 0) ; i++) {
	if (strcmp(argv[i],"-c") == 0) {
	    state = FALSE;
	}
	else if (strcmp(argv[i],"-s") == 0) {
	    state = TRUE;
	}
	else if (strcmp(argv[i],"-h") == 0) {
	    ret = ERR_BAD_ARG;
	    print_usage();
	}
	else if (strcmp(argv[i],"-v") == 0) {
	    TPM_setlog(1); 
	}
	else {
	    printf("\n%s is not a valid option\n", argv[i]);
	    ret = ERR_BAD_ARG;
	    print_usage();
	}
    }
    if (ret == 0) {
	ret = TPM_PhysicalSetDeactivated(state);
	if (ret != 0) {
	    printf("TPM_PhysicalSetDeactivated returned '%s' (%d).\n",
		   TPM_GetErrMsg(ret),
		   ret);
	}
    }
    return ret;
}
Exemplo n.º 16
0
int main(int argc, char *argv[])
{
	int ret;
	struct stat sbuf;	
	uint32_t parhandle;	/* handle of parent key */
	unsigned char blob[4096];	/* resulting sealed blob */
	unsigned int bloblen = 322;	/* blob length */
	unsigned char passptr1[20] = {0};
	int fd, outlen, i;
	char totp[7];
	parhandle = 0x40000000;

	ret = TPM_NV_ReadValue(0x00004d47, 0, 322, blob, &bloblen, NULL);
	if (ret) {
		for (i=1; i<argc; i++) {
			fd = open(argv[1], O_RDONLY);
			if (fd < 0) {
				argv++;
			}
		}

		if (fd < 0) {
			perror("Unable to open file");
			return -1;
		}

		ret = fstat(fd, &sbuf);
		if (ret) {
			perror("Unable to stat file");
			return -1;
		}

		bloblen = sbuf.st_size;
		ret = read(fd, blob, bloblen);

		if (ret != bloblen) {
			fprintf(stderr, "Unable to read data\n");
			return -1;
		}

		if (strncmp(argv[1], efivarfs, strlen(efivarfs)) == 0) {
			bloblen -= sizeof(int);
			memmove (blob, blob + sizeof(int), bloblen);
		}
	}

	ret = TPM_Unseal(parhandle,	/* KEY Entity Value */
			 passptr1,	/* Key Password */
			 NULL,
			 blob, bloblen,
			 key, &outlen);

	if (ret == 24) {
		fprintf(stderr, "TPM refused to decrypt key - boot process attests that it is modified\n");
		return -1;
	}

	if (ret != 0) {
		printf("Error %s from TPM_Unseal\n", TPM_GetErrMsg(ret));
		exit(6);
	}

	if (outlen != keylen) {
		fprintf(stderr, "Returned buffer is incorrect length\n");
		return -1;
	}

	if (0)
	{
		printf("Decrypted secret:");
		for(int i = 0 ; i < outlen ; i++)
			printf(" %02x", key[i]);
		printf("\n");
	}

	uint32_t token = oauth_calc(time(NULL), key, keylen); //, time(NULL), 30, 0, 6, totp);

	printf("%06d\n", token);
}
Exemplo n.º 17
0
int main(int argc, char * argv[]) {
	char * ownerpass = NULL;
	char * counterpass = NULL;
	uint32_t parhandle;             /* handle of parent key */
	unsigned char * passptr1 = NULL;
	unsigned char * passptr2 = NULL;
	unsigned char passhash1[20];
	unsigned char passhash2[20];	
	uint32_t ret;
	int i =	0;
	uint32_t label = 0xffffffff;
	uint32_t counterId = 0;
	unsigned char counterValue[TPM_COUNTER_VALUE_SIZE];
	
	i = 1;
	
	TPM_setlog(0);
	
	while (i < argc) {
	    if (!strcmp("-pwdo",argv[i])) {
		i++;
		if (i < argc) {
		    ownerpass = argv[i];
		} else {
		    printf("Missing parameter for -pwdo\n");
		    usage();
		}
	    }
	    else if (!strcmp("-la",argv[i])) {
		i++;
		if (i < argc) {
		    label = atoi(argv[i]);
		} else {
		    printf("Missing parameter for -la\n");
		    usage();
		}
	    }
	    else if (!strcmp("-pwdc",argv[i])) {
		i++;
		if (i < argc) {
		    counterpass = argv[i];
		} else {
		    printf("Missing parameter for -pwdc\n");
		    usage();
		}
	    }
	    else if (!strcmp("-v",argv[i])) {
		TPM_setlog(1);
	    }
	    else if (!strcmp(argv[i], "-h")) {
		usage();
	    }
	    else {
		printf("\n%s is not a valid option\n",argv[i]);
		usage();
	    }
	    i++;
	}

	if ((ownerpass == NULL) ||
	    (counterpass == NULL) ||
	    (label == 0xffffffff)) {
	    printf("Input parameters wrong or missing!\n");
	    usage();
	}
	printf("Using ownerpass : %s\n",ownerpass);
	printf("Using counterpass: %s\n",counterpass);
	
	/*
	 * convert parent key handle from hex
	 */
	parhandle = 0x00000000;

	TSS_sha1(ownerpass,strlen(ownerpass),passhash1);
	passptr1 = passhash1;

	TSS_sha1(counterpass,strlen(counterpass),passhash2);
	passptr2 = passhash2;

	/*
	 * Create a counter
	 */
	ret = TPM_CreateCounter(parhandle,
	                        passptr1,
	                        label,
	                        passptr2,
	                        &counterId,
	                        counterValue);

	if (0 != ret) {
		printf("Got error %s (0x%x) from TPM_CreateCounter.\n",
		       TPM_GetErrMsg(ret),
		       ret);
	} else {
		
		printf("New counter id: %d\n",counterId);
		i = 0;
		printf("Counter start value: ");
		while (i < TPM_COUNTER_VALUE_SIZE) {
			printf("%02X",counterValue[i]);
			i++;
		}
		printf("\n");
	}

	return ret;
}
Exemplo n.º 18
0
int main(int argc, char *argv[])
{
	unsigned char nonce[TPM_NONCE_SIZE];
	unsigned char digest[TPM_DIGEST_SIZE];
	unsigned char calcdigest[TPM_DIGEST_SIZE];
	uint32_t ret;
	struct keydata key;
	STACK_TPM_BUFFER(serKeyData)
	uint32_t serKeySize;
	char * pubKeyFile = NULL;
	uint32_t buffersize;
	char * buffer = NULL;
	int index = 1;

	if (argc >= 3 && 0 == strcmp(argv[index],"-v")) {
		TPM_setlog(1);
		index++;
	} else {
		TPM_setlog(0);
	}

	if (index >= argc) {
		usage();
		exit(-1);
	}

	pubKeyFile = argv[index];

	if (NULL == pubKeyFile) {
		usage();
		exit(-1);
	}

	TSS_gennonce(nonce);

	ret = TPM_ReadKeyfile(pubKeyFile, &key);

	if ( ( ret & ERR_MASK ) != 0 ) {
		printf("Error - could not read key file.\n");
		exit (-1);
	}

	ret = TPM_WriteKeyPub(&serKeyData, &key);
	if ( ( ret & ERR_MASK ) != 0 ) {
		exit (-1);
	}

	serKeySize = ret;

	ret = TPM_ReadManuMaintPub(nonce, digest);

	if ( 0 != ret ) {
		printf("Error %s from ReadManuMainPub.\n",
		       TPM_GetErrMsg(ret));
		exit(ret);
	}


	/*
	 * Now check the digest against the serialized public key
	 * and the hash.
	 */
	buffersize = serKeySize + sizeof(nonce);
	buffer = malloc(buffersize);
	if (NULL == buffer) {
		exit (-1);
	}
	
	memcpy(buffer, 
	       serKeyData.buffer, 
	       serKeySize);
	memcpy(&buffer[serKeySize],
	       nonce,
	       sizeof(nonce));

	TSS_sha1(buffer, buffersize, calcdigest);

	free(buffer);

	if (0 == memcmp(calcdigest, digest, sizeof(digest))) {
		printf("The same public key is in the TPM.\n");
		ret = 0;
	} else {
		printf("Another public key is in the TPM.\n");
		ret = -1;
	}
		
	exit(ret);
}
Exemplo n.º 19
0
int main(int argc, char * argv[]) {
	char * counterpass = NULL;
	unsigned char * passptr1 = NULL;
	unsigned char passhash1[20];
	uint32_t ret;
	int i = 0;
	uint32_t id = 0xffffffff;
	unsigned char buffer[10];
	
	i = 1;
	
	TPM_setlog(0);
	
	while (i < argc) {
		if (!strcmp("-ix",argv[i])) {
			i++;
			if (i < argc) {
				id = atoi(argv[i]);
			} else {
				printf("Missing mandatory parameter for -ix.\n");
				usage();
				exit(-1);
			}
		} else
		if (!strcmp("-pwdc",argv[i])) {
			i++;
			if (i < argc) {
				counterpass = argv[i];
			} else {
				printf("Missing parameter for -pwdc.\n");
				usage();
				exit(-1);
			}
		} else
		if (!strcmp("-v",argv[i])) {
			TPM_setlog(1);
		} else
		if (!strcmp("-h",argv[i])) {
		        usage();
		        exit(-1);
		} else {
		        printf("\n%s is not a valid option\n",argv[i]);
			usage();
			exit(-1);
		}
		i++;
	}

	if (NULL == counterpass || id == 0xffffffff) {
		printf("Input parameters wrong or missing!\n");
		usage();
		exit(-1);
	}
	
	
	printf("Using counterpass: %s\n",counterpass);
	
	TSS_sha1(counterpass,strlen(counterpass),passhash1);
	passptr1 = passhash1;

	/*
	 * increment a counter
	 */
	for (i = 0 , ret = TPM_RETRY ; (ret == TPM_RETRY) && (i < 7) ; i++) {
	    ret = TPM_IncrementCounter(id,
				       passptr1,
				       buffer);
	    /* must be able to increment once every 5 seconds */
	    if (ret == TPM_RETRY) {
#ifdef TPM_POSIX
		sleep(1);
#endif
#ifdef TPM_WINDOWS
		Sleep(1000);
#endif
	    }
	}
	if (0 != ret) {
		printf("Got error '%s' (0x%x) from TPM_IncrementCounter.\n",
		       TPM_GetErrMsg(ret),
		       ret);
	} else {
		printf("Value of the counter: ");
		i = 0;
		while (i < (int)sizeof(buffer)){
			printf("%02x",buffer[i]);
			i++;
		}
		printf("\n");
	}

	if (ret > 255) {
		ret = -1;
	}

	return ret;
}
Exemplo n.º 20
0
static int check_tpm(void)
{
	unsigned char keybuf[TPM_MAX_KEY_SIZE];
	unsigned char pcrvalue[TPM_AUTH_SIZE];
	unsigned char srkauth[TPM_AUTH_SIZE];
	uint32_t ret, srk_handle;
	unsigned int keylen;
	keydata k, key;
	int tpmfp;

	/* check /dev/tpm0 */
        if ((tpmfp = open("/dev/tpm0", O_RDWR)) < 0) {
		printf("Unable to open /dev/tpm0\n");
                exit(-1);
        }
	close(tpmfp);

	/* try a TPM_Reset (should work even if TPM disabled) */
	if((ret=TPM_Reset())){
		printf("TPM_Reset failed, error %s\n", TPM_GetErrMsg(ret));
		exit(-2);
	}

	/* check if TPM enabled with TPM_PcrRead */
	if((ret=TPM_PcrRead(0L,pcrvalue))){
		printf("TPM_PcrRead failed, error %s\n", TPM_GetErrMsg(ret));
		exit(-3);
	}

	/* check if TPM already has default IBM CSS owner */
	srk_handle=TPM_SRK_HANDLE;
	TSS_sha1((unsigned char *)SRKPASS,8,srkauth);
       	k.keyflags = 0;
       	k.authdatausage = 0;    /* key requires no password */
       	k.privkeylen = 0;       /* no private key specified here */
       	k.pub.algorithm = 0x00000099;   /* BOGUS ALG */
       	k.keyusage = 0x0014;    /* key Usage - 0x0014 = bind */
       	k.pub.encscheme = 0x0003;       /* encryption scheme 3 RSA */
       	k.pub.sigscheme = 0x0001;       /* signature scheme none */
       	k.pub.keybitlen = 2048; /* RSA modulus size 2048 bits */
       	k.pub.numprimes = 2;    /* required */
       	k.pub.expsize = 0;      /* RSA exponent - default 0x010001 */
       	k.pub.keylength = 0;    /* key not specified here */
       	k.pub.pcrinfolen = 0;   /* no PCR's used at this time */
	ret=TPM_CreateWrapKey(srk_handle,srkauth,
		NULL,NULL, &k,&key,keybuf,&keylen);
	if(ret==TPM_AUTHFAIL){
		printf("TPM already has unknown owner\n"),
		exit(-4);
	}
	if(ret==TPM_BAD_KEY_PROPS){
		printf("TPM is already IBM CSS managed\n");
		return(0);
	}
	if(ret==TPM_NOSRK){
			printf("TPM is already owned\n");
			return(1);
		
	}
	printf("Unexpected return code %d\n",ret);
	exit(-5);
}
Exemplo n.º 21
0
int main(int argc, char *argv[])
{
	int ret;
	struct stat sbuf;
	unsigned char keyblob[4096];
	unsigned int keyblen;
	unsigned char outblob[4096];
	unsigned int outblen;
	unsigned int handle;
	unsigned char filename[256];
	unsigned char filename2[256];
	unsigned char parphash[20];
	unsigned char newphash[20];
	unsigned char keyphash[20];
	unsigned char *passptr1;
	FILE *outfile;
	FILE *ainfile;
	keydata key;
	unsigned char *keypass;
	unsigned char *newpass;
	unsigned char *keyname;
	unsigned char *parhndl;

	int nxtarg;

	nxtarg = ParseArgs(argc, argv);
	if (argc < (nxtarg + 4))
		usage();
	TPM_setlog(0);
	parhndl = argv[nxtarg + 0];
	keyname = argv[nxtarg + 1];
	keypass = argv[nxtarg + 2];
	newpass = argv[nxtarg + 3];
	/*
	 ** convert parent key handle from hex
	 */
	ret = sscanf(parhndl, "%x", &handle);
	if (ret != 1) {
		fprintf(stderr, "Invalid argument '%s'\n", parhndl);
		exit(2);
	}
	/*
	 * use SHA1 hash of password string as Parent Key Authorization 
	 */
	if (parpass != NULL) {
		TSS_sha1(parpass, strlen(parpass), parphash);
		passptr1 = parphash;
	} else
		passptr1 = NULL;
	/*
	 ** use SHA1 hash of password string as Key Authorization Data
	 */
	TSS_sha1(keypass, strlen(keypass), keyphash);
	/*
	 ** use  SHA1 hash of password string as New Authorization Data
	 */
	TSS_sha1(newpass, strlen(newpass), newphash);
	/*
	 ** read the key blob
	 */
	ainfile = fopen(keyname, "r");
	if (ainfile == NULL) {
		fprintf(stderr, "Unable to open key file\n");
		exit(3);
	}
	stat(keyname, &sbuf);
	keyblen = (int) sbuf.st_size;
	ret = fread(keyblob, 1, keyblen, ainfile);
	if (ret != keyblen) {
		fprintf(stderr, "Unable to read key file\n");
		exit(4);
	}
	fclose(ainfile);
	TSS_KeyExtract(keyblob, &key);
	ret = TPM_ChangeAuth(handle, passptr1, keyphash, newphash, &key);
	if (ret != 0) {
		fprintf(stderr, "Error %s from TPM_ChangeAuth\n",
			TPM_GetErrMsg(ret));
		exit(5);
	}
	ret = TPM_BuildKey(outblob, &key);
	if ((ret & ERR_MASK) != 0)
		return ret;
	outblen = ret;
	sprintf(filename2, "%s.save", keyname);
	sprintf(filename, "%s", keyname);
	ret = rename(filename, filename2);
	if (ret != 0) {
		fprintf(stderr, "Unable to rename old key file\n");
		exit(6);
	}
	outfile = fopen(filename, "w");
	if (outfile == NULL) {
		fprintf(stderr, "Unable to create new key file\n");
		exit(7);
	}
	ret = fwrite(outblob, 1, outblen, outfile);
	if (ret != outblen) {
		fprintf(stderr, "Unable to write new key file\n");
		exit(8);
	}
	fclose(outfile);
	exit(0);
}
Exemplo n.º 22
0
int main(int argc, char *argv[])
{
	int ret;			/* general return value */
	uint32_t keyhandle = 0;		/* handle of quote key */
	unsigned int  pcrmask = 0;	/* pcr register mask */
	unsigned char passhash1[TPM_HASH_SIZE];	/* hash of key password */
	unsigned char data[TPM_HASH_SIZE];/* nonce data */
	
	STACK_TPM_BUFFER(signature);
	pubkeydata  pubkey;		/* public key structure */
	RSA *rsa;			/* openssl RSA public key */
	unsigned char *passptr;
	TPM_PCR_SELECTION selection;
	TPM_PCR_INFO_SHORT s1;
	TPM_QUOTE_INFO2 quoteinfo;
	STACK_TPM_BUFFER( serQuoteInfo )
	uint32_t pcrs;
	int i;
	uint16_t sigscheme = TPM_SS_RSASSAPKCS1v15_SHA1;
	TPM_BOOL addVersion = FALSE;
	STACK_TPM_BUFFER(versionblob);
	static char *keypass = NULL;

	
	TPM_setlog(0);    /* turn off verbose output from TPM driver */
	for (i=1 ; i<argc ; i++) {
	    if (strcmp(argv[i],"-hk") == 0) {
		i++;
		if (i < argc) {
		    /* convert key handle from hex */
		    if (1 != sscanf(argv[i], "%x", &keyhandle)) {
			printf("Invalid -hk argument '%s'\n",argv[i]);
			exit(2);
		    }
		}
		else {
		    printf("-hk option needs a value\n");
		    printUsage();
		}
	    }
	    else if (!strcmp(argv[i], "-pwdk")) {
		i++;
		if (i < argc) {
		    keypass = argv[i];
		}
		else {
		    printf("Missing parameter to -pwdk\n");
		    printUsage();
		}
	    }
	    else if (strcmp(argv[i],"-bm") == 0) {
		i++;
		if (i < argc) {
		    /* convert key handle from hex */
		    if (1 != sscanf(argv[i], "%x", &pcrmask)) {
			printf("Invalid -bm argument '%s'\n",argv[i]);
			exit(2);
		    }
		}
		else {
		    printf("-bm option needs a value\n");
		    printUsage();
		}
	    }
	    else if (!strcmp(argv[i], "-vinfo")) {
		addVersion = TRUE;
		printf("Adding version info.\n");
	    }
	    else if (!strcmp(argv[i], "-h")) {
		printUsage();
	    }
	    else if (!strcmp(argv[i], "-v")) {
		TPM_setlog(1);
	    }
	    else {
		printf("\n%s is not a valid option\n", argv[i]);
		printUsage();
	    }
	}
	if ((keyhandle == 0) ||
	    (pcrmask == 0)) {
	    printf("Missing argument\n");
	    printUsage();
	}
	memset(&s1, 0x0, sizeof(s1));	
	/*
	** Parse and process the command line arguments
	*/
	/* get the SHA1 hash of the password string for use as the Key Authorization Data */
	if (keypass != NULL) {
	    TSS_sha1((unsigned char *)keypass,strlen(keypass),passhash1);
		passptr = passhash1;
	} else {
		passptr = NULL;
	}
	/* for testing, use the password hash as the test nonce */
	memcpy(data,passhash1,TPM_HASH_SIZE);
	
	ret = TPM_GetNumPCRRegisters(&pcrs);
	if (ret != 0) {
		printf("Error reading number of PCR registers.\n");
		exit(-1);
	}
	if (pcrs > TPM_NUM_PCR) {
		printf("Library does not support that many PCRs.\n");
		exit(-1);
	}

	memset(&selection, 0x0, sizeof(selection));
	selection.sizeOfSelect = pcrs / 8;
	for (i = 0; i < selection.sizeOfSelect; i++) {
		selection.pcrSelect[i] = (pcrmask & 0xff);
		pcrmask >>= 8;
	}

	/*
	** perform the TPM Quote function
	*/
	ret = TPM_Quote2(keyhandle,	/* key handle */
	                 &selection,	/* specify PCR registers */
	                 addVersion,    /* add Version */
	                 passptr,	/* Key Password (hashed), or null */
	                 data,		/* nonce data */
	                 &s1,		/* pointer to pcr info */
	                 &versionblob,	/* pointer to TPM_CAP_VERSION_INFO */
	                 &signature);	/* buffer to receive result, int to receive result length */
	if (ret != 0) {
		printf("Error '%s' from TPM_Quote2\n",TPM_GetErrMsg(ret));
		exit(ret);
	}
	/*
	** Get the public key and convert to an OpenSSL RSA public key
	*/
	ret = TPM_GetPubKey(keyhandle,passptr,&pubkey);
	if (ret != 0) {
		printf("Error '%s' from TPM_GetPubKey\n",TPM_GetErrMsg(ret));
		exit(ret);
	}
	rsa = TSS_convpubkey(&pubkey);
	
	
	/*
	** fill the quote info structure and calculate the hashes needed for verification
	*/
	quoteinfo.tag = TPM_TAG_QUOTE_INFO2;
	memcpy(&(quoteinfo.fixed),"QUT2",4);
	quoteinfo.infoShort = s1;
	memcpy(&(quoteinfo.externalData),data,TPM_NONCE_SIZE);
	unsigned char *corey_ptr = (unsigned char *)&quoteinfo;
	unsigned int x;
	printf("quote info: \n");
	for (x=0;x<128;x++)
	{
	    if (x != 0 && x % 16 == 0)
		printf("\n");
	    printf("%02x ", corey_ptr[x]);
	}
	printf("\n");

	    
	/* create the hash of the quoteinfo structure for signature verification */
	ret = TPM_WriteQuoteInfo2(&serQuoteInfo, &quoteinfo);
	if ( ( ret & ERR_MASK ) != 0) {
		exit(-1);
	}
	printf("serquoteinfo: \n");

	for (x=0;x<128;x++)
	{
	    if (x != 0 && x % 16 == 0)
		printf("\n");
	    printf("%02x ", serQuoteInfo.buffer[x]);
	}
	printf("\n");

	/* append version information if given in response */
	if (addVersion) {
	    printf("addversion is called\n");
	    memcpy(serQuoteInfo.buffer + serQuoteInfo.used,
	           versionblob.buffer,
	           versionblob.used);
	    serQuoteInfo.used += versionblob.used;
	}
	
	ret = TPM_ValidateSignature(sigscheme,
	                            &serQuoteInfo,
	                            &signature,
	                            rsa);
	if (ret != 0) {
		printf("Verification failed\n");
	} else {
		printf("Verification succeeded\n");
	}
	RSA_free(rsa);
	exit(ret);
}
Exemplo n.º 23
0
int main(int argc, char *argv[])
{
	int ret;
	struct stat sbuf;	
	uint32_t parhandle;	/* handle of parent key */
	unsigned char blob[4096];	/* resulting sealed blob */
	unsigned int bloblen = 322;	/* blob length */
	unsigned char passptr1[20] = {0};
	int fd, outlen, i;
	time_t t, delay;

	parhandle = 0x40000000;

	ret = TPM_NV_ReadValue(0x10004d47, 0, 322, blob, &bloblen, NULL);
	if (ret != 0) {
		for (i=1; i<argc; i++) {
			fd = open(argv[1], O_RDONLY);
			if (fd < 0) {
				argv++;
			}
		}

		if (fd < 0) {
			perror("Unable to open file");
			return -1;
		}

		ret = fstat(fd, &sbuf);
		if (ret) {
			perror("Unable to stat file");
			return -1;
		}
		bloblen = sbuf.st_size;
		ret = read(fd, blob, bloblen);

		if (ret != bloblen) {
			fprintf(stderr, "Unable to read data\n");
			return -1;
		}

		if (strncmp(argv[1], efivarfs, strlen(efivarfs)) == 0) {
			bloblen -= sizeof(int);
			memmove (blob, blob + sizeof(int), bloblen);
		}
	}

	ret = TPM_Unseal(parhandle,	/* KEY Entity Value */
			 passptr1,	/* Key Password */
			 NULL,
			 blob, bloblen,
			 key, &outlen);

	if (ret == 24) {
		fprintf(stderr, "TPM refused to decrypt key - boot process attests that it is modified\n");
		return -1;
	}

	if (ret != 0) {
		printf("Error %s from TPM_Unseal\n", TPM_GetErrMsg(ret));
		exit(6);
	}

	if (outlen != keylen) {
		fprintf(stderr, "Returned buffer is incorrect length\n");
		return -1;
	}

	ply_client = ply_boot_client_new();
	ply_loop = ply_event_loop_new();
	if (!ply_boot_client_connect (ply_client, (ply_boot_client_disconnect_handler_t) on_disconnect, NULL)) {
		fprintf(stderr, "Plymouth not running\n");
		return -1;
	}
	ply_boot_client_attach_to_event_loop(ply_client, ply_loop);
	display_totp();

	t = time(NULL);
	delay = 30 - (t % 30);
	ply_event_loop_watch_for_timeout(ply_loop, delay, on_timeout, NULL);

	ply_event_loop_run(ply_loop);
	return 0;
}
Exemplo n.º 24
0
int main(int argc, char **argv)
{
	int fd, size, i, ret;
	uint32_t kh, pcrs;

	unsigned char buf[1024], hash[20], pass[20];
	char *srkpass, *keyfile, ch;

	/* SHA1 hash of TPM's SRK password */
	char *tpmhash = "\x71\x10\xed\xa4\xd0\x9e\x06\x2a\xa5\xe4\xa3"
			"\x90\xb0\xa5\x72\xac\x0d\x2c\x02\x20";
	char *nonce =	"\x80\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0"
			"\x0\x0\x0\x0\x1";
	keydata k;
	RSA *rpub;

	srkpass = keyfile = NULL;
	while ((ch = getopt(argc, argv, "hs:f:")) != -1) {
		switch (ch) {
			case 's':
				srkpass = optarg;
				break;
			case 'f':
				keyfile = optarg;
				break;
			case 'h':
			default:
				usage(argv[0]);
				break;
		}
	}

	if (!srkpass)
		usage(argv[0]);
	if (!keyfile)
		keyfile = "key.blob";

	SHA1(srkpass, strlen(srkpass), pass);

	fd = open(keyfile, O_RDONLY);
	if (fd == -1)
		errx(1, "couldn't open %s\n", keyfile);

	size = read(fd, buf, 1024);
	if (size == -1)
		errx(1, "couldn't read\n");

	size = TSS_KeyExtract(buf, &k);
	printf("keybuf size: %d\n", size);

	close(fd);

	printf("loading . . .\n");
	/* 0x40000000 is the UID for the SRK */
	if (ret = TPM_LoadKey(0x40000000, pass, &k, &kh)) {
		printf("%s\n", TPM_GetErrMsg(ret));
		errx(1, "TPM_LoadKey\n");
	}

	/* Quote PCR 0 */
	printf("quoting . . .\n");
	if (ret = TPM_Quote(kh, (0x00000001 << 0), pass, nonce, &pcomp, buf,
	    &size)) {
		printf("%s\n", TPM_GetErrMsg(ret));
		errx(1, "TPM_Quote\n");
	}

	/* TPM will run out of memory if you forget to evict keys.  This can be
	 * fixed with a good ol' reboot.*/
	printf("evicting. . .\n");
	if (ret = TPM_EvictKey(kh)) {
		printf("%s\n", TPM_GetErrMsg(ret));
		errx(1, "TPM_EvictKey\n");
	}

	/* Compute composite hash */
	SHA1((char*)&pcomp, sizeof(pcomp), hash);

	printf("slen: %d\n", ntohs(pcomp.slen));
	printf("select: 0x%x\n", pcomp.s);
	printf("plen %d\n", ntohl(pcomp.plen));
	printf("pcr hash: ");
	for (i = 0; i < 20; i++)
		printf("%02x ", pcomp.p[i]);
	printf("\n");
	printf("composite hash: ");
	for (i = 0; i < 20; i++)
		printf("%02x ", hash[i]);
	printf("\n");
	printf("signed blob len: %d\n", size);
	printf("signed blob: ");
	for (i = 0; i < size; i++)
		printf("%02x ", buf[i]);
	printf("\n");

	/* See if the signed object matches the composite hash concatenated
	 * with the nonce */
	signedhash.fixed[0] = 1; signedhash.fixed[1] = 1;
	signedhash.fixed[2] = 0; signedhash.fixed[3] = 0;
	signedhash.fixed[4] = 'Q'; signedhash.fixed[5] = 'U';
	signedhash.fixed[6] = 'O'; signedhash.fixed[7] = 'T';
	memcpy(&signedhash.comphash, hash, 20);
	memcpy(&signedhash.nonce, nonce, 20);

	SHA1((char*)&signedhash, sizeof(signedhash), hash);
	/* Gives us an RSA public key from the TPM key */
	rpub = TSS_convpubkey(&k.pub);
	if (!rpub)
		errx(1, "TSS_convpubkey\n");

	if (!RSA_verify(NID_sha1, hash, 20, buf, size, rpub))
		printf("SIGNATURE FAILED\n");
	else
		printf("Signature is correct\n");

	return 0;
}
int main(int argc, char *argv[])
{
	uint32_t startOrdinal = -1;
	int ret;
	int verbose = FALSE;
	TPM_COUNTER_VALUE counter;
	int i = 1;
	char * keypass = NULL;
	unsigned char keyAuth[TPM_HASH_SIZE];
	unsigned char * keyAuthPtr = NULL;
	uint32_t keyhandle = -1;
	STACK_TPM_BUFFER(signature);
	unsigned char digest[TPM_DIGEST_SIZE];
	unsigned char ordinalDigest[TPM_DIGEST_SIZE];
	unsigned char antiReplay[TPM_NONCE_SIZE];
	
	TPM_setlog(0);
	TSS_gennonce(antiReplay);
	
	while (i < argc) {
		if (!strcmp("-s",argv[i])) {
			i++;
			if (i < argc) {
				sscanf(argv[i],"%d",&startOrdinal);
			} else {
				printf("Missing parameter for -s.\n");
				usage();
			}
		} else
		if (!strcmp("-h",argv[i])) {
			i++;
			if (i < argc) {
				sscanf(argv[i],"%x",&keyhandle);
			} else {
				printf("Missing parameter for -h.\n");
				usage();
			}
		} else
		if (!strcmp("-p",argv[i])) {
			i++;
			if (i < argc) {
				keypass = argv[i];
			} else {
				printf("Missing parameter for -p.\n");
				usage();
			}
		} else
		if (!strcmp("-v",argv[i])) {
			verbose = TRUE;
			TPM_setlog(1);
		} else {
		        printf("\n%s is not a valid option\n", argv[i]);
			usage();
		}
		i++;
	}
	(void)verbose;

	if (-1 == (int)startOrdinal ||
	    -1 == (int)keyhandle) {
		printf("Missing command line parameter.\n");
		usage();
	}

	if (NULL != keypass) {
		TSS_sha1(keypass,strlen(keypass),keyAuth);
		keyAuthPtr = keyAuth;
	}
	ret = TPM_GetAuditDigestSigned(keyhandle,
	                               FALSE,
	                               keyAuthPtr,
	                               antiReplay,
	                               &counter,
	                               digest,
	                               ordinalDigest,
	                               &signature);

	if (0 != ret) {
		printf("Error %s from GetAuditDigestSigned.\n",
		       TPM_GetErrMsg(ret));
	} else {
		TPM_SIGN_INFO tsi;
		STACK_TPM_BUFFER(tsi_ser);
		STACK_TPM_BUFFER(serial);
		STACK_TPM_BUFFER(ctr_ser);
		pubkeydata pubkey;
		RSA *rsa;

		i = 0;
		printf("AuditDigest   : ");
		while (i < (int)sizeof(digest)) {
			printf("%02X",digest[i]);
			i++;
		}
		printf("\n");
	
		i = 0;
		printf("OrdinalDigest : ");
		while (i < (int)sizeof(digest)) {
			printf("%02X",ordinalDigest[i]);
			i++;
		}
		printf("\n");

		ret = TPM_GetPubKey(keyhandle, keyAuthPtr, &pubkey);
		if (ret != 0) {
			printf("Could not get public key of signing key.\n");
			exit(-1);
		}
		rsa = TSS_convpubkey(&pubkey);
		if (!rsa) {
			printf("Could not convert public key.\n");
			exit(-1);
		}
		
		tsi.tag = TPM_TAG_SIGNINFO;
		memcpy(tsi.fixed, "ADIG", 4);
		memcpy(tsi.replay, antiReplay, sizeof(antiReplay));
		/* D4=ordinalDigest */
		TPM_WriteCounterValue(&ctr_ser, &counter);
		memcpy(&serial.buffer[0], digest, sizeof(digest));
		memcpy(&serial.buffer[sizeof(digest)],
		                          ctr_ser.buffer, ctr_ser.used);
		memcpy(&serial.buffer[sizeof(digest)+ctr_ser.used],
		                          ordinalDigest, sizeof(ordinalDigest));
		serial.used = sizeof(digest) + ctr_ser.used + sizeof(ordinalDigest);
		tsi.data.size = serial.used;
		tsi.data.buffer = serial.buffer; 
		ret = TPM_WriteSignInfo(&tsi_ser, &tsi);
		if ((ret & ERR_MASK)) {
			printf("Error serializing TPM_SIGN_INFO.\n");
			exit(-1);
		}
		ret = TPM_ValidateSignature(TPM_SS_RSASSAPKCS1v15_SHA1,
		                            &tsi_ser,
		                            &signature,
		                            rsa);
		if (ret != 0) {
			printf("Error validating signature.\n");
			exit(-1);
		}
		printf("Signature verification successful.\n");
	}
	exit(ret);
}
Exemplo n.º 26
0
int main(int argc, char *argv[])
{
	int ret;
	char base32_key[BASE32_LEN(keylen)+1];
	unsigned char uefiblob[4100];
	unsigned char blob[4096];	/* resulting sealed blob */
	unsigned int bloblen;	/* blob length */
	unsigned char wellknown[20] = {0};
	unsigned char totpstring[64];
	uint32_t pcrmask =  0x000003BF; // PCRs 0-5 and 7-9
	const char * hostname = "TPMTOTP";

	char *outfile_name;
	FILE *infile;
	FILE *outfile;
	QRcode *qrcode;
#ifdef CONFIG_TSS
	TSS_HCONTEXT context;
#endif

	if (generate_key()) {
		return -1;
	}

	pcrvals = malloc(NUM_PCRS * sizeof(uint8_t*));
	CHECK_MALLOC(pcrvals);

	static int base32_flag = 0;
	static int qr_flag = 1;
	static int nvram_flag = 0;
	int option_index = 0;

	static struct option long_options[] = {
	     {"pcrs",  required_argument, 0, 'p'},
	     {"nvram", no_argument, &nvram_flag, 1},
	     {"no-qrcode", no_argument, &qr_flag, 0},
	     {"base32", no_argument, &base32_flag, 1},
	     {"help", no_argument, 0, 'h'},
	     {0,0,0,0}

	};

	if (argc == 1) {
	     print_help();
	     return -1;
	}

	int c;

	while ((c = getopt_long(argc, argv, "p:nbh", long_options, &option_index)) != -1) {

		switch (c) {
		case 0: // Flag only
			break;

		case 'p':
			pcrmask = parse_pcrs(optarg);
			if (pcrmask == (uint32_t) -1)
				return -1;
			break;

		case 'h':
			print_help();
			return 0;

		case 'b':
			base32_flag = 1;
			break;

		case 'n':
			nvram_flag = 1;
			break;

		case 's':
			qr_flag = 0;
			break;

		case '?': // Unrecognized Option
			print_help();
			return -1;

		default:
			print_help();
		}

	}
	
	if (!nvram_flag) {
		if (optind == argc) {
			fprintf(stderr, "Output name required!\n");
			print_help();
			return -1;
		} else {
			outfile_name = argv[optind];
		}
	}

	base32_encode(key, keylen, base32_key);
	base32_key[BASE32_LEN(keylen)] = NULL;

#ifdef CONFIG_TSS
	ret = Tspi_Context_Create(&context);
	if (ret != TSS_SUCCESS) {
		fprintf(stderr, "Unable to create TPM context\n");
		return -1;
	}
	ret = Tspi_Context_Connect(context, NULL);
	if (ret != TSS_SUCCESS) {
		fprintf(stderr, "Unable to connect to TPM\n");
		return -1;
	}
	ret = TSPI_SealCurrPCR(context, // context
			      0x40000000, // SRK
			      pcrmask,
			      wellknown,  // Well-known SRK secret
			      wellknown,  // Well-known SEAL secret
			      key, keylen,	/* data to be sealed */
			      blob, &bloblen);	/* buffer to receive result */
#else
	ret = TPM_SealCurrPCR(
			      0x40000000, // SRK
			      pcrmask,
			      wellknown,  // Well-known SRK secret
			      wellknown,  // Well-known SEAL secret
			      key, keylen,	/* data to be sealed */
			      blob, &bloblen);	/* buffer to receive result */
#endif
	if (ret != 0) {
		fprintf(stderr, "Error %s from TPM_Seal\n",
			TPM_GetErrMsg(ret));
		//goto out;
	}

	sprintf(totpstring, "otpauth://totp/%s?secret=%s", hostname, base32_key);
	//sprintf(totpstring, "%s", base32_key);

	if (base32_flag) {
		printf("%s\n", base32_key);
	}

	printf("%s\n", totpstring);
	if (qr_flag) {
		qrcode = QRcode_encodeString(totpstring, 0, QR_ECLEVEL_L,
					     QR_MODE_8, 1);
		writeANSI(qrcode);
	}

	if (nvram_flag) {
		uint32_t nvindex = 0x00004d47;
		uint32_t permissions = TPM_NV_PER_OWNERREAD|TPM_NV_PER_OWNERWRITE;
#ifdef CONFIG_TSS
		TSS_HNVSTORE nvObject;
		TSS_FLAG nvattrs = 0;

		ret = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_NV,
						nvattrs, &nvObject);
		if (ret != TSS_SUCCESS) {
			fprintf(stderr, "Unable to create nvram object: %x\n",
				ret);
			goto out;
		}
		ret = Tspi_SetAttribUint32(nvObject, TSS_TSPATTRIB_NV_INDEX, 0,
					   nvindex);
		if (ret != TSS_SUCCESS) {
			fprintf(stderr, "Unable to set index\n");
			goto out;
		}
		ret = Tspi_SetAttribUint32(nvObject,
					   TSS_TSPATTRIB_NV_PERMISSIONS, 0,
				   permissions);
		if (ret != TSS_SUCCESS) {
			fprintf(stderr, "Unable to set permissions\n");
			goto out;
		}
		ret = Tspi_SetAttribUint32(nvObject, TSS_TSPATTRIB_NV_DATASIZE,
					   0, bloblen);
		if (ret != TSS_SUCCESS) {
			fprintf(stderr, "Unable to set size\n");
			goto out;
		}
		ret = Tspi_NV_DefineSpace(nvObject, NULL, NULL);
		if (ret != TSS_SUCCESS && ret != (0x3000 | TSS_E_NV_AREA_EXIST)) {
			fprintf(stderr, "Unable to define space: %x\n", ret);
			goto out;
		}
		ret = Tspi_NV_WriteValue(nvObject, 0, bloblen, blob);
		if (ret != TSS_SUCCESS) {
			fprintf(stderr, "Unable to write to nvram\n");
			goto out;
		}
#else
		unsigned char * ownauth = wellknown;
		unsigned char * areaauth = wellknown;
		TPM_PCR_INFO_SHORT *pcrInfoRead = NULL;
		TPM_PCR_INFO_SHORT *pcrInfoWrite = NULL;

		ret = TPM_NV_DefineSpace2(
			ownauth,
			nvindex,
			bloblen,
			permissions,
			areaauth,
			pcrInfoRead,
			pcrInfoWrite);
		//if (ret != TPM_SUCCESS && ret != (0x3000 | TSS_E_NV_AREA_EXIST)) {
		if (ret != TPM_SUCCESS) {
			fprintf(stderr, "Unable to define space: %x\n", ret);
			goto out;
		}

		ret = TPM_NV_WriteValue(
			nvindex,
			0,
			blob,
			bloblen,
			ownauth
		);
		if (ret != TPM_SUCCESS) {
			fprintf(stderr, "Unable to write to nvram\n");
			goto out;
		}
#endif
	} else {
		outfile = fopen(outfile_name, "w");
		if (outfile == NULL) {
			fprintf(stderr, "Unable to open output file '%s'\n",
				outfile_name);
			goto out;
		}
		if (strncmp(outfile_name, efivarfs, strlen(efivarfs)) == 0) {
			int attributes = 7; // NV, RT, BS
			memcpy(uefiblob, &attributes, sizeof(int));
			memcpy(uefiblob + sizeof(int), blob, bloblen);
			bloblen += sizeof(int);
			ret = fwrite(uefiblob, 1, bloblen, outfile);
		} else {
			ret = fwrite(blob, 1, bloblen, outfile);
		}
		if (ret != bloblen) {
			fprintf(stderr,
				"I/O Error while writing output file '%s'\n",
				outfile_name);
			goto out;
		}
	}

out:

#ifdef CONFIG_TSS
	Tspi_Context_FreeMemory(context, NULL);
	Tspi_Context_Close(context);
#endif

	exit(ret);
}
Exemplo n.º 27
0
int main(int argc, char *argv[])
{
    uint32_t ret;
    STACK_TPM_BUFFER(resp);
    int index = 0;
    STACK_TPM_BUFFER( subcap );;
	
    TPM_setlog(0);		/* turn off verbose output */

    ParseArgs(argc, argv);

    while ((int)matrx[index].cap != -1) {
	if (cap == matrx[index].cap) {
	    break;
	}
	index++;
    }
    if (-1 == (int)matrx[index].cap) {
	printf("Unknown or unsupported capability!\n");
	exit(-1);
    }
	
    subcap.used = 0;
    if (matrx[index].subcap_size > 0) {
	if ((int)scap == -1) {
	    printf("Need subcap parameter for this capability!\n");
	    exit(-1);
	}
	if (0 == prepare_subcap(cap, &subcap, scap)) {
	    if (2 == matrx[index].subcap_size) {
		STORE16(subcap.buffer,0,scap);
		subcap.used = 2;
	    } else
		if (matrx[index].subcap_size >= 4) {
		    STORE32(subcap.buffer,0,scap);
		    subcap.used  = 4;
		}
	}
    }
	
#if 0
    /* This was for VTPM extensions and needs retest */
    if (cap == TPM_CAP_MFR) {
	int idx2 = 0;
	while ((int)mfr_matrix[idx2].cap != -1) {
	    if (mfr_matrix[idx2].cap == scap) {
		break;
	    }
	    idx2++;
	}
	if (mfr_matrix[idx2].subcap_size > 0) {
	    uint32_t used = subcap.used +
			    mfr_matrix[idx2].subcap_size;
	    while (subcap.used < used) {
		if (argc <= nxtarg) {
		    printf("Need one more parameter for this "
			   "capability!\n");
		    exit(-1);
		}
		if (!strncmp("0x",argv[nxtarg],2)) {
		    sscanf(argv[nxtarg],"%x",&sscap);
		} else {
		    sscanf(argv[nxtarg],"%d",&sscap);
		}
		nxtarg++;
		if (2 == matrx[index].subcap_size) {
		    STORE16(subcap.buffer,
			    subcap.used,sscap);
		    subcap.used += 2;
		} else
		    if (matrx[index].subcap_size >= 4) {
			STORE32(subcap.buffer,
				subcap.used,sscap);
			subcap.used += 4;
		    }
	    }
	}
    }


#endif
    if (0 == sikeyhandle) {
	ret = TPM_GetCapability(cap,
				&subcap,
				&resp);

	if (0 != ret) {
	    printf("TPM_GetCapability returned %s.\n",
		   TPM_GetErrMsg(ret));
	    exit(ret);
	}
    } else {
	unsigned char antiReplay[TPM_HASH_SIZE];
	unsigned char signature[2048];
	uint32_t signaturelen = sizeof(signature);
	pubkeydata pubkey;
	RSA * rsa;
	unsigned char sighash[TPM_HASH_SIZE];
	unsigned char * buffer = NULL;
	unsigned char * sigkeyhashptr = NULL;
	unsigned char sigkeypasshash[TPM_HASH_SIZE];

	if (NULL != sikeypass) {
	    TSS_sha1(sikeypass,strlen(sikeypass),sigkeypasshash);
	    sigkeyhashptr = sigkeypasshash;
	}

	TSS_gennonce(antiReplay);
		
	ret = TPM_GetPubKey(sikeyhandle,
			    sigkeyhashptr,
			    &pubkey);

	if (0 != ret) {
	    printf("Error while trying to access the signing key's public key.\n");
	    exit(-1);
	}
		
	rsa = TSS_convpubkey(&pubkey);
		
	ret = TPM_GetCapabilitySigned(sikeyhandle,
				      sigkeyhashptr,
				      antiReplay,
				      cap,
				      &subcap,
				      &resp,
				      signature, &signaturelen);

	if (0 != ret) {
	    printf("TPM_GetCapabilitySigned returned %s.\n",
		   TPM_GetErrMsg(ret));
	    exit(ret);
	}

	buffer = malloc(resp.used+TPM_NONCE_SIZE);
	if (NULL == buffer) {
	    printf("Could not allocate buffer.\n");
	    exit(-1);
	}
	memcpy(&buffer[0], resp.buffer, resp.used);
	memcpy(&buffer[resp.used], antiReplay, TPM_NONCE_SIZE);

	TSS_sha1(buffer,
		 resp.used+TPM_NONCE_SIZE,
		 sighash);
	free(buffer);

	ret = RSA_verify(NID_sha1,
			 sighash,TPM_HASH_SIZE,
			 signature,signaturelen,
			 rsa);
	if (1 != ret) {
	    printf("Error: Signature verification failed.\n");
	    exit(-1);
	}
    }

    if (0 == resp.used) {
	printf("Empty response.\n");
    } else {

	if (-1 == (int)scap) {
	    printf("Result for capability 0x%x is : ",cap);
	} else {
	    printf("Result for capability 0x%x, subcapability 0x%x is : ",cap,scap);
	}
	if (TYPE_BOOL == matrx[index].result_size) {
	    if (resp.buffer[0] == 0) {
		printf("FALSE\n");
	    } else {
		printf("TRUE\n");
	    }
	} else
	    if (TYPE_UINT32 == matrx[index].result_size) {
		uint32_t rsp;
		rsp = LOAD32(resp.buffer,0);
		printf("0x%08X  = %d\n",rsp,rsp);
	    } else
		if (TYPE_UINT32_ARRAY == matrx[index].result_size) {
		    int i = 0;
		    printf("\n");
		    while (i+3 < (int)resp.used) {
			uint32_t rsp = LOAD32(resp.buffer,i);
			i+=4;
			if (TPM_CAP_NV_LIST == cap) {
			    /* don't zero extend, grep needs the exact value for test suite */
			    printf("%d. Index : %d = 0x%x.\n",
				   i/4,
				   rsp,
				   rsp);
			} else
			    if (TPM_CAP_KEY_HANDLE == cap) {
				printf("%d. keyhandle : %d.\n",
				       i/4,
				       rsp);
				} else {
				    printf("%d. item : %d.\n",
					   i/4,
					   rsp);
				}
		    }
		} else
		    if (TYPE_STRUCTURE == matrx[index].result_size) {
			switch(cap) {
			  case TPM_CAP_FLAG:
			      {
				  if (scap == TPM_CAP_FLAG_PERMANENT) {
				      TPM_PERMANENT_FLAGS pf;
				      STACK_TPM_BUFFER(tb)
					  TSS_SetTPMBuffer(&tb, resp.buffer, resp.used);
				      ret = TPM_ReadPermanentFlags(&tb, 0, &pf, resp.used);
				      if ( ( ret & ERR_MASK ) != 0 || ret > resp.used) {
					  printf("ret=%x, responselen=%d\n",ret,resp.used);
					  printf("Error parsing response!\n");
					  exit(-1);
				      }
						
				      printf("\n");
				      showPermanentFlags(&pf, resp.used);
				  } else 
				      if (scap == TPM_CAP_FLAG_VOLATILE) {
					  TPM_STCLEAR_FLAGS sf;
					  STACK_TPM_BUFFER(tb);
					  TSS_SetTPMBuffer(&tb, resp.buffer, resp.used);
					  ret = TPM_ReadSTClearFlags(&tb, 0, &sf);
					  if ( ( ret & ERR_MASK ) != 0 || ret > resp.used) {
					      printf("ret=%x, responselen=%d\n",ret,resp.used);
					      printf("Error parsing response!\n");
					      exit(-1);
					  }
						
					  printf("\n");
					  showVolatileFlags(&sf);
						
				      }
			      }
			      break;
				
			  case TPM_CAP_KEY_HANDLE:
			      {
				  uint16_t num = LOAD16(resp.buffer, 0);
				  uint32_t i = 0;
				  uint32_t handle;
				  printf("\n");
				  while (i < num) {
				      handle = LOAD32(resp.buffer,2+i*4);
				      printf("%d. handle: 0x%08X\n",
					     i,
					     handle);
				      i++;
				  }
			      }
			      break;
			  case TPM_CAP_NV_INDEX:
			      {
				  //char scratch_info[256];
				  unsigned char scratch_info[256];
				  uint32_t scratch_info_len;
				  TPM_NV_DATA_PUBLIC ndp;
				  uint32_t i, c;
				  STACK_TPM_BUFFER(tb)
				      TSS_SetTPMBuffer(&tb, resp.buffer, resp.used);
				  ret = TPM_ReadNVDataPublic(&tb,
							     0,
							     &ndp);
				  if ( ( ret & ERR_MASK) != 0) {
				      printf("Could not deserialize the TPM_NV_DATA_PUBLIC structure.\n");
				      exit(-1);
				  }
				  printf("permission.attributes : %08X\n",(unsigned int)ndp.permission.attributes);
				  printf("ReadSTClear           : %02X\n",ndp.bReadSTClear);
				  printf("WriteSTClear          : %02X\n",ndp.bWriteSTClear);
				  printf("WriteDefine           : %02X\n",ndp.bWriteDefine);
				  printf("dataSize              : %08X = %d",(unsigned int)ndp.dataSize,
					 (unsigned int)ndp.dataSize);

				  c = 0;
				  for (i = 0; i < ndp.pcrInfoRead.pcrSelection.sizeOfSelect*8; i++) {
				      if (ndp.pcrInfoRead.pcrSelection.pcrSelect[(i / 8)] & (1 << (i & 0x7))) {
					      if (!c)
						  printf("\nRead PCRs selected: ");
					      else
						  printf(", ");
					      printf("%d", i);
					      c++;

				      }
				  }

				  if (c) {
				      char pcrmap[4], *pf;

				      memcpy(pcrmap, ndp.pcrInfoRead.pcrSelection.pcrSelect,
					     ndp.pcrInfoRead.pcrSelection.sizeOfSelect);

				 //     printf("\npcrmap: %02x%02x%02x%02x\n", pcrmap[0], pcrmap[1],
				//	     pcrmap[2], pcrmap[3]);

				      ret = TSS_GenPCRInfo(*(uint32_t *)pcrmap,
							   scratch_info,
							   &scratch_info_len);

				      printf("\nRead PCR Composite: ");
				      for (i = 0; i < 20; i++)
					  printf("%02x", ndp.pcrInfoRead.digestAtRelease[i] & 0xff);
				      printf("\n");
#if 1
				      pf = &scratch_info[5];
				      printf("\nCurrent PCR composite: ");
				      for (i = 0; i < 20; i++)
					  //printf("%02x", scratch_info.digestAtRelease[i] & 0xff);
					  printf("%02x", pf[i] & 0xff);
				      printf("\n");
#endif
				      if (!ret) {
					      printf("Matches current TPM state: ");

					      if (!memcmp(&scratch_info[5],
							  &ndp.pcrInfoRead.digestAtRelease,
							  20)) {
						      printf("Yes\n");
					      } else {
						      printf("No\n");
					      }
				      }
				  }


				  c = 0;
				  for (i = 0; i < ndp.pcrInfoWrite.pcrSelection.sizeOfSelect*8; i++) {
				      if (ndp.pcrInfoWrite.pcrSelection.pcrSelect[(i / 8)] & (1 << (i & 0x7))) {
					      if (!c)
						  printf("\nWrite PCRs selected: ");
					      else
						  printf(", ");
					      printf("%d", i);
					      c++;

				      }
				  }

				  if (c) {
				      printf("\nWrite PCR Composite: ");
				      for (i = 0; i < 20; i++)
					  printf("%02x", ndp.pcrInfoWrite.digestAtRelease[i] & 0xff);
				      printf("\n");
				  }
			      }
			      break;
			  case TPM_CAP_HANDLE:
			      {
				  uint16_t num = LOAD16(resp.buffer, 0);
				  uint16_t x = 0;
				  while (x < num) {
				      uint32_t handle = LOAD32(resp.buffer,
							       sizeof(num)+4*x);
				      printf("%02d. 0x%08X\n",x,handle);
				      x++;
				  }
			      }
			      break;
			  case TPM_CAP_VERSION_VAL:
			      {
				  int i = 0;
				  TPM_CAP_VERSION_INFO cvi;
				  STACK_TPM_BUFFER(tb)
				      TSS_SetTPMBuffer(&tb, resp.buffer, resp.used);
				  ret = TPM_ReadCapVersionInfo(&tb,
							       0,
							       &cvi);
				  if ( ( ret & ERR_MASK) != 0) {
				      printf("Could not read the version info structure.\n");
				      exit(-1);
				  }
					
				  printf("\n");
				  printf("major      : 0x%02X\n",cvi.version.major);
				  printf("minor      : 0x%02X\n",cvi.version.minor);
				  printf("revMajor   : 0x%02X\n",cvi.version.revMajor);
				  printf("revMinor   : 0x%02X\n",cvi.version.revMinor);
				  printf("specLevel  : 0x%04X\n",cvi.specLevel);
				  printf("errataRev  : 0x%02X\n",cvi.errataRev);
	
				  printf("VendorID   : ");
				  while (i < 4) {
				      printf("%02X ",cvi.tpmVendorID[i]);
				      i++;
				  }
				  printf("\n");
				  /* Print vendor ID in text if printable */
				  for (i=0 ; i<4 ; i++) {
				      if (isprint(cvi.tpmVendorID[i])) {
					  if (i == 0) {
					      printf("VendorID   : ");
					  }
					  printf("%c", cvi.tpmVendorID[i]);
				      }
				      else {
					  break;
				      }
				  }	    
				  printf("\n");

				  printf("[not displaying vendor specific information]\n");
			      }
			      break;
#if 0	/* kgold: I don't think these are valid cap values */
			  case TPM_CAP_FLAG_PERMANENT:
			      {
				  TPM_PERMANENT_FLAGS pf;
				  STACK_TPM_BUFFER(tb)
				      TSS_SetTPMBuffer(&tb, resp.buffer, resp.used);

				  if (resp.used == 21) {
				      ret = TPM_ReadPermanentFlagsPre103(&tb, 0, &pf);
				  } else {
				      ret = TPM_ReadPermanentFlags(&tb, 0, &pf);
				  }
				  if ( ( ret & ERR_MASK ) != 0 || ret > resp.used) {
				      printf("ret=%x, responselen=%d\n",ret,resp.used);
				      printf("Error parsing response!\n");
				      exit(-1);
				  }
						
				  printf("\n");
				  showPermanentFlags(&pf, resp.used);
			      }
			      break;
				
			  case TPM_CAP_FLAG_VOLATILE:
			      {
				  TPM_STCLEAR_FLAGS sf;
				  STACK_TPM_BUFFER(tb);
				  TSS_SetTPMBuffer(&tb, resp.buffer, resp.used);
				  ret = TPM_ReadSTClearFlags(&tb, 0, &sf);
				  if ( ( ret & ERR_MASK ) != 0 || ret > resp.used) {
				      printf("ret=%x, responselen=%d\n",ret,resp.used);
				      printf("Error parsing response!\n");
				      exit(-1);
				  }
						
				  printf("\n");
				  showVolatileFlags(&sf);
			      }
			      break;
#endif
			  case TPM_CAP_DA_LOGIC:
			      {
				  uint32_t ctr;
				  TPM_BOOL lim = FALSE;
				  TPM_DA_INFO dainfo;
				  TPM_DA_INFO_LIMITED dainfo_lim;
				  STACK_TPM_BUFFER(tb);
				  TSS_SetTPMBuffer(&tb, resp.buffer, resp.used);
				  ret = TPM_ReadDAInfo(&tb, 0, &dainfo);
				  if ( ( ret & ERR_MASK) != 0 || ret > resp.used) {
				      ret = TPM_ReadDAInfoLimited(&tb, 0, &dainfo_lim);
				      if ( (ret & ERR_MASK ) != 0 || ret > resp.used) {
					  printf("ret=%x, responselen=%d\n",ret,resp.used);
					  printf("Error parsing response!\n");
					  exit(-1);
				      } else {
					  lim = TRUE;
				      }
				  }
					
				  printf("\n");
				  if (lim) {
				      printf("State      : %d\n",dainfo_lim.state);
				      printf("Actions    : 0x%08x\n",dainfo_lim.actionAtThreshold.actions);
						
				      ctr = 0;
				      while (ctr < dainfo_lim.vendorData.size) {
					  printf("%02x ",(unsigned char)dainfo_lim.vendorData.buffer[ctr]);
					  ctr++;
				      }
				  } else {
				      printf("State              : %d\n",dainfo.state);
				      printf("currentCount       : %d\n",dainfo.currentCount);
				      printf("thresholdCount     : %d\n",dainfo.thresholdCount);
				      printf("Actions            : 0x%08x\n",dainfo.actionAtThreshold.actions);
				      printf("actionDependValue  : %d\n",dainfo.actionDependValue);
						
#if 0
				      ctr = 0;
				      while (ctr < dainfo_lim.vendorData.size) {
					  printf("%02x ",(unsigned char)dainfo_lim.vendorData.buffer[ctr]);
					  ctr++;
				      }
#endif
				  }
			      }
			      break;
			}
		    } else
			if (TYPE_VARIOUS == matrx[index].result_size) {
			    switch(cap) {
			
			      case TPM_CAP_MFR:
				switch (scap) {
				  case TPM_CAP_PROCESS_ID:
				      {
					  uint32_t rsp;
					  rsp = LOAD32(resp.buffer,0);
					  printf("%d\n",rsp);
				      }
				      break;
				}
				break; /* TPM_CAP_MFR */
			
			      default:
				/* Show booleans */
				if (scap == TPM_CAP_PROP_OWNER ||
				    scap == TPM_CAP_PROP_DAA_INTERRUPT
				    ) {
				    if (0 == resp.buffer[0]) {
					printf("FALSE\n");
				    } else {
					printf("TRUE\n");
				    }
				} else /* check for array of 4 UINTs */
				    if (scap == TPM_CAP_PROP_TIS_TIMEOUT /* ||
									    scap == TPM_CAP_PROP_TIMEOUTS      */) {
					int i = 0;
					while (i < 4) {
					    uint32_t val = LOAD32(resp.buffer,i * 4);
					    printf("%d ",
						   val);
					    i++;
					}
					printf("\n");
				    } else /* check for TPM_STARTUP_EFFECTS */
					if (scap == TPM_CAP_PROP_STARTUP_EFFECT) {
					    TPM_STARTUP_EFFECTS se = 0;
					    ret = TPM_ReadStartupEffects(resp.buffer, 
									 &se);
					    if ( ( ret & ERR_MASK ) != 0 ) {
						printf("Could not read startup effects structure.\n");
						exit(-1);
					    }
					    printf("0x%08X=%d\n",
						   (unsigned int)se,
						   (unsigned int)se);
					    printf("\n");
					    printf("Startup effects:\n");
					    printf("Effect on audit digest: %s\n", (se & (1 << 7)) 
						   ? "none"
						   : "active");
					    printf("Audit Digest on TPM_Startup(ST_CLEAR): %s\n", ( se & (1 << 6)) 
						   ? "set to NULL" 
						   : "not set to NULL" );
		
					    printf("Audit Digest on TPM_Startup(any)     : %s\n", ( se & (1 << 5))
						   ? "set to NULL"
						   : "not set to NULL" );
					    printf("TPM_RT_KEY resource initialized on TPM_Startup(ST_ANY)     : %s\n", (se & ( 1 << 4))
						   ? "yes"
						   : "no");
					    printf("TPM_RT_AUTH resource initialized on TPM_Startup(ST_STATE)  : %s\n", (se & ( 1 << 3))
						   ? "yes"
						   : "no");
					    printf("TPM_RT_HASH resource initialized on TPM_Startup(ST_STATE)  : %s\n", (se & ( 1 << 2))
						   ? "yes"
						   : "no");
					    printf("TPM_RT_TRANS resource initialized on TPM_Startup(ST_STATE) : %s\n", (se & ( 1 << 1))
						   ? "yes"
						   : "no");
					    printf("TPM_RT_CONTEXT session initialized on TPM_Startup(ST_STATE): %s\n", (se & ( 1 << 0))
						   ? "yes"
						   : "no");
					} else /* check for  array of 3 UINTs */
					    if (scap == TPM_CAP_PROP_DURATION) {
						int i = 0;
						while (i < 4*3) {
						    uint32_t val = LOAD32(resp.buffer,i);
						    printf("%d ",
							   val);
						    i+= 4;
						}
						printf("\n");
					    } else /* check for TPM_COUNT_ID */
						if (scap == TPM_CAP_PROP_ACTIVE_COUNTER) {
						    uint32_t val = LOAD32(resp.buffer,0);
						    printf("0x%08X=%d",val,val);
						    if (0xffffffff == val) {
							printf(" (no counter is active)");
						    }
						    printf("\n");
						} else { /* just a single UINT32 */
						    printf("%ld=0x%08lX.\n",
							   (long)LOAD32(resp.buffer, 0),
							   (long)LOAD32(resp.buffer, 0));
						}
			    }
			}
    }		
	
    printf("\n");
    exit(0);
}
Exemplo n.º 28
0
int main(int argc, char * argv[]) {
	char * data = NULL;
	char * filename = NULL;
	int i = 1;
	int offset = 0;
	uint32_t len;
	uint32_t ret = 0;
	unsigned char hashbuffer[TPM_HASH_SIZE];
	unsigned char pcrValue[TPM_HASH_SIZE];
	int index = -1;
	TPM_BOOL verbose = FALSE;
	uint32_t maxNumBytes = 0;	/* return from TPM_SHA1Start */

	TPM_setlog(0);
	
	while (i < argc) {
		if (!strcmp("-ic",argv[i])) {
			i++;
			if (i < argc) {
				data = argv[i];
			} else {
				printf("Missing mandatory parameter for -ic.\n");
				usage();
			}
		} else
		if (!strcmp("-if",argv[i])) {
			i++;
			if (i < argc) {
				filename = argv[i];
			} else {
				printf("Missing mandatory parameter for -if.\n");
				usage();
			}
		} else
		if (!strcmp("-ix",argv[i])) {
			i++;
			if (i < argc) {
				index = atoi(argv[i]);
			} else {
				printf("Missing mandatory parameter for -ix.\n");
				usage();
			}
		} else
		if (!strcmp("-v",argv[i])) {
			TPM_setlog(1);
			verbose = TRUE;
		} else
		    if (!strcmp("-h",argv[i])) {
			usage();
		} else {
			printf("\n%s is not a valid option\n", argv[i]);
			usage();
		}
		i++;
	}

	if (NULL == data && filename == NULL) {
		printf("Input parameters wrong or missing!\n");
		usage();
	}
	/* Common processing, for data or file */
	ret = TPM_SHA1Start(&maxNumBytes);
	if (0 != ret) {
	    printf("Error from TPM_SHA1Start(): %d (0x%x)\n",
		   ret,
		   ret);
	    exit(-1);
	}
	if (maxNumBytes < 64) {
	    printf("The size parameter returned from SHA1Start() is bad.\n");
	    exit(-1);
	}

	/* If the connection is to a hardware device, the driver limits the buffer size to
	   2048, even if the TPM can support a larger size.

	   The -20 is presumably for the TPM command packet tag, paramSize, ordinal,
	   numBytes, although this only adds up to 14 bytes.
	*/
#if defined TPM_USE_CHARDEV || defined XCRYPTO_USE_CCA
	maxNumBytes = MIN(maxNumBytes, (2 * 1024) - 20);
	maxNumBytes &= ~63;
#else
	/* Even if the connection is to a socket, it may be then through a proxy to a
	   hardware device.  Setting this env variable flag again limits the buffer to
	   2048. */
	if (getenv("TPM_HW_DRIVER") != NULL) {
	    maxNumBytes = MIN(maxNumBytes, (2 * 1024) - 20);
	    maxNumBytes &= ~63;
	}
#endif

	
	if (NULL != data) {
		len = strlen(data);
		printf("SHA1 hash for '%s': ",data);
		offset = 0;
		while (len > 64) {
			unsigned int chunksize;
			chunksize = MIN(maxNumBytes, len & ~63);

			if (verbose)
				printf("Chunksize to hash: %d\n",chunksize);

			ret = TPM_SHA1Update(&data[offset], chunksize);
			if (ret != 0) {
				printf("Error %s from SHA1Update.\n",
				       TPM_GetErrMsg(ret));
				exit(ret);
			}
			offset += chunksize;
			len -= chunksize;
		}

		if (index >= 0) {
			ret = TPM_SHA1CompleteExtend(&data[offset],len,
			                             index,
			                             hashbuffer,
			                             pcrValue);
		} else {
			ret = TPM_SHA1Complete(&data[offset],len,hashbuffer);
		}
		if (0 == ret) {
			printf("Hash: ");
			i = 0;
			while (i < (int)sizeof(hashbuffer)) {
				printf("%02x",hashbuffer[i]);
				i++;
			}
			printf("\n");
		
			if (index >= 0) {
				printf("New value of PCR: ");
				i = 0;
				while (i < (int)sizeof(pcrValue)) {
					printf("%02x",pcrValue[i]);
					i++;
				}
				printf("\n");
			}
		} else {
			printf("Error '%s' from SHA1Complete/SHA1CompleteExtend.\n",
			       TPM_GetErrMsg(ret));
		}
	}
	
	if (NULL != filename) {
		FILE * f = fopen(filename,"rb");
		if (NULL != f) {
			int n = 0;
			uint32_t chunksize;
			char *buf;
			uint32_t total = 0;
			printf("SHA1 hash for file '%s': \n",filename);

			buf = malloc(maxNumBytes);
			if (!buf) {
				printf("Could not allocated buffer.\n");
				exit(-1);
			}

			while ((n = fread(buf,1,maxNumBytes,f)) >= 64) {

				chunksize = MIN(maxNumBytes, 
				                (uint32_t)(n & ~63));
				
				if (verbose)
					printf("Chunksize to hash: %d\n",
					       chunksize);
				ret = TPM_SHA1Update(buf,chunksize);
				if (ret != 0) {
					printf("Error %s from SHA1Update.\n",
					       TPM_GetErrMsg(ret));
					exit(-1);
				}

				total += chunksize;
				if ((chunksize - n)) {
					offset = chunksize;
					n &= 63;
					break;
				}
			}
			total += n;
			
			if (index >= 0) {
				ret = TPM_SHA1CompleteExtend(&buf[offset],n,
				                             index,
				                             hashbuffer,
				                             pcrValue);
			} else {
				ret = TPM_SHA1Complete(&buf[offset],n,hashbuffer);
			}

			fclose(f);
			free(buf);

			if (0 == ret) {
				printf("Hash: ");
				i = 0;
				while (i < (int)sizeof(hashbuffer)) {
					printf("%02x",hashbuffer[i]);
					i++;
				}
				printf("\n");
			
				if (index >= 0) {
					printf("New value of PCR: ");
					i = 0;
					while (i < (int)sizeof(pcrValue)) {
						printf("%02x",pcrValue[i]);
						i++;
					}
					printf("\n");
				}
			} else {
				printf("Error '%s' from SHA1Complete/SHA1CompleteExtend.\n",
				       TPM_GetErrMsg(ret));
			}
		} else {
			printf("Could not find file '%s'.\n",filename);
		}
	}
	return 0;
}
Exemplo n.º 29
0
int main(int argc, char *argv[])
   {
   int ret;
   char *ownpass = NULL;
   char *newpass = NULL;
   unsigned char  ownphash[TPM_HASH_SIZE];
   unsigned char  newphash[TPM_HASH_SIZE];
   int 	i;
   
   TPM_setlog(0);

   for (i=1 ; i<argc ; i++) {
       if (!strcmp(argv[i], "-pwdo")) {
	   i++;
	   if (i < argc) {
	       ownpass = argv[i];
	   }
	   else {
	       printf("Missing parameter to -pwdo\n");
	       printUsage();
	   }
       }
       else if (!strcmp(argv[i], "-pwdn")) {
	   i++;
	   if (i < argc) {
	       newpass = argv[i];
	   }
	   else {
	       printf("Missing parameter to -pwdn\n");
	       printUsage();
	   }
       }
       else if (strcmp(argv[i],"-own") == 0) {
	   ownflag = 1;
       }
       else if (!strcmp(argv[i], "-h")) {
	   printUsage();
       }
       else if (!strcmp(argv[i], "-v")) {
	   TPM_setlog(1);
       }
       else {
	   printf("\n%s is not a valid option\n", argv[i]);
	   printUsage();
       }
   }
   if ((ownpass == NULL) ||
       (newpass == NULL)) {
       printf("Missing password argument\n");
       exit(2);
   }
   /*
   ** use the SHA1 hash of the password string as the TPM Owner Password
   */
   TSS_sha1((unsigned char*)ownpass,strlen(ownpass),ownphash);
   /*
   ** use the SHA1 hash of the password string as the New Authorization Data
   */
   TSS_sha1((unsigned char*)newpass,strlen(newpass),newphash);
   if (ownflag)
      {
      ret = TPM_ChangeOwnAuth(ownphash,newphash);
      if (ret != 0)
         {
         printf("Error %s from TPM_ChangeOwnAuth\n",TPM_GetErrMsg(ret));
         exit(1);
         }
      }
   else
      {
      ret = TPM_ChangeSRKAuth(ownphash,newphash);
      if (ret != 0)
         {
         printf("Error %s from TPM_ChangeSRKAuth\n",TPM_GetErrMsg(ret));
         exit(1);
         }
      }
   exit(0);
   }
Exemplo n.º 30
0
int main(int argc, char *argv[])
   {
   int ret;
   uint32_t parhandle;             /* handle of parent key */
   unsigned char passhash[TPM_HASH_SIZE];     /* hash of parent key password */
   unsigned char datahash[TPM_HASH_SIZE];     /* hash of data file */
   unsigned char sig[4096];        /* resulting signature */
   uint32_t  siglen;           /* signature length */
   unsigned char *passptr;
   char *indata;
   FILE *sigfile;
   
   int nxtarg;
   
   nxtarg = ParseArgs(argc, argv);
   if (argc < (nxtarg + 3) ) usage();
   TPM_setlog(0);                  /* turn off verbose output */
   /*
   ** convert parent key handle from hex
   */
   ret = sscanf(argv[nxtarg+0],"%x",&parhandle);
   if (ret != 1)
      {
      printf("Invalid argument '%s'\n",argv[nxtarg+0]);
      exit(2);
      }
   /*
   ** use the SHA1 hash of the password string as the Key Authorization Data
   */
   if (keypass != NULL)
      {
      TSS_sha1(keypass,strlen(keypass),passhash);
      passptr = passhash;
      }
   else passptr = NULL;
   /*
   ** read and hash the message
   */
   indata = argv[nxtarg+1];
   if (indata == NULL)
      {
      printf("Unable to get input data'\n");
      exit(-2);
      }
   TSS_sha1(indata,strlen(indata),datahash);

   ret = TPM_Sign(parhandle,              /* Key Handle */
                  passptr,                /* key Password */
                  datahash,sizeof (datahash),     /* data to be signed, length */
                  sig,&siglen);           /* buffer to receive sig, int to receive sig length */
   if (ret != 0)
      {
      printf("Error %s from TPM_Sign\n",TPM_GetErrMsg(ret));
      exit(1);
      }
   sigfile = fopen(argv[nxtarg+2],"wb");
   if (sigfile == NULL)
      {
      printf("Unable to open output file '%s'\n",argv[nxtarg+2]);
      exit(4);
      }
   ret = fwrite(sig,1,siglen,sigfile);
   if (ret != (int)siglen)
      {
      printf("I/O Error while writing output file '%s'\n",argv[nxtarg+2]);
      exit(5);
      }
   fclose(sigfile);
   exit(0);
   }