#include "test_common.h"
#ifdef WIN32
#include "getopt.h"
#else 
extern char *optarg;
#endif

void usage(void);
CK_RV test_crypto();
int test_tls_key_and_mac_derive(CK_SESSION_HANDLE sess);

CK_SLOT_ID SlotId;

CK_SLOT_ID_PTR SlotList = NULL;
CK_ULONG SlotCount = 0;

int main(int argc, char *argv[]) {
   CK_RV rc = 1;
   CK_FLAGS flags = 0;
   unsigned long slot_num = 0;  
   int i;

   // parse the command line parameters
	for (i=1; i<argc; i++) {
		if (strcmp("-api", argv[i]) == 0) {
			i++;
			api_path = argv[i];
		} else if (strcmp("-user_pin", argv[i]) == 0) {
			i++;
			user_pin = argv[i];
		}
	}

   // load the PKCS11 library 
	rc = init(api_path, &funcs, NULL);
   if (rc != CKR_OK) {
      fprintf(stderr, "ERROR calling init, rc = %p.\n", (void *)rc);
      return rc;
   }
	rc = get_slot_list(funcs, 
                    &SlotList, 
                    &SlotCount);
	if (rc != CKR_OK) {
		printf("get_slot_list failed, rc = 0x%x\n", rc );
		return rc;
	}
	rc = find_slot_with_token(funcs, 
                           SlotList, 
                           SlotCount, 
                           &SlotId);
	if (rc != CKR_OK) {
		printf("find_slot_with_token failed, rc = 0x%x\n", rc );
		return rc;
	}
//	for (i=0; i<20; i++) {
		// test the crypto functions 
		rc = test_crypto();
		if (rc != CKR_OK) {
			fprintf(stderr, "ERROR call to lissi failed.\n");
			return rc;
		}
//	}
	return CKR_OK;
}


void usage(void)
{
   fprintf(stderr, "Usage: lissi [-c <slotId>]\n"
      "Default slotID is 0\n"
      "To get a list of slotIDs, call pkcs11_cfg -s\n");
   exit(-1);
}

CK_RV test_crypto() 
{
   CK_RV rc, ret;
   CK_SESSION_HANDLE hSession;
	CK_MECHANISM_INFO minfo;

   // open a R/W cryptoki session, CKR_SERIAL_SESSION is a legacy bit we have to set
   rc = funcs->C_OpenSession(SlotId, CKF_RW_SESSION | CKF_SERIAL_SESSION, NULL_PTR,
         NULL_PTR, &hSession);
   if (rc != CKR_OK) {
      fprintf(stderr, "ERROR call to C_OpenSession failed, rc = %p\n", (void *)rc);
      goto out;
   }
  fprintf(stderr, "C_OpenSession success\n");
/*
   // log in as normal user 
   rc = funcs->C_Login(hSession, CKU_USER, user_pin, strlen(user_pin));
   if (rc != CKR_OK) {
      fprintf(stderr, "ERROR call to C_Login failed, rc = %p\n", (void *)rc);
      goto out_close;
   }
  fprintf(stderr, "C_Login success\n");
*/
	rc = funcs->C_GetMechanismInfo(SlotId, CKM_TLS_GOST_KEY_AND_MAC_DERIVE, &minfo);
	if (rc != CKR_OK) {
		fprintf(stderr, "\n======== Mechanism CKM_TLS_GOST_KEY_AND_MAC_DERIVE not supported ===========\n");
	} else {
		fprintf(stderr, "\n==================== CKM_TLS_GOST_KEY_AND_MAC_DERIVE test ==================\n");
		rc = test_tls_key_and_mac_derive(hSession);
		if (rc != CKR_OK) {
			fprintf(stderr, "ERROR CKM_TLS_GOST_KEY_AND_MAC_DERIVE failed, rc = %p\n", (void *)rc);
		} else {
			fprintf(stderr, "CKM_TLS_GOST_KEY_AND_MAC_DERIVE test passed.\n");
		}
	}

//out_close:
   if( (ret = funcs->C_CloseSession(hSession)) != CKR_OK ) {
      fprintf(stderr, "Error: C_CloseSession failed with %p\n", (void *)ret);
	  rc = ret;
   }
   else {
      fprintf(stderr, "C_CloseSession success\n");
   }

out:
   return rc;
}

int test_tls_key_and_mac_derive(CK_SESSION_HANDLE sess)
{
    char str[1024];
	int rc = 0;
	CK_BYTE value[1024];
	CK_ULONG len;
   	CK_MECHANISM mechanism_desc = 
	{CKM_TLS_GOST_KEY_AND_MAC_DERIVE, NULL, 0};
   	CK_MECHANISM_PTR mechanism = &mechanism_desc;

	CK_OBJECT_HANDLE keyh = CK_INVALID_HANDLE;
	static CK_OBJECT_CLASS oclass = CKO_SECRET_KEY;
	static CK_KEY_TYPE generic_key_type = CKK_GENERIC_SECRET;
	static CK_KEY_TYPE secret_key_type = CKK_GOST28147;
	static CK_BBOOL ltrue = CK_TRUE;
	static CK_BBOOL lfalse = CK_FALSE;
	CK_ATTRIBUTE attr;

	CK_OBJECT_HANDLE paramh = CK_INVALID_HANDLE;

//	static CK_OBJECT_CLASS param_oclass = CKO_DOMAIN_PARAMETERS;
//	static CK_KEY_TYPE param_key_type = CKK_GOSTR3411;

	static CK_BYTE client_random[] = {
		0x48,0xdc,0xdb,0x79,0xfb,0x11,0x16,0xaf,
		0xed,0x6a,0x72,0xda,0xbf,0x7a,0xb2,0x76,
		0x8c,0x35,0xa7,0x54,0x52,0xda,0xa1,0x00,
		0x47,0x83,0x29,0x72,0xa9,0x8d,0xd9,0x78
	};
	static CK_BYTE server_random[] = {
		0x48,0xdc,0xda,0xaa,0x83,0xeb,0x5c,0x08,
		0x51,0x20,0xc6,0x8e,0x29,0xb4,0x30,0xff,
		0xc5,0x9e,0x4f,0x1c,0xa9,0x75,0xa7,0x35,
		0x62,0x89,0x29,0x17,0x28,0x70,0x56,0x06
	};
	static CK_BYTE master[] = {
		0x68,0x0d,0x31,0x53,0x6a,0x20,0x68,0x50,
		0xca,0x66,0x01,0x3f,0xb6,0xfa,0xe3,0x26,
		0x51,0xb5,0xba,0x03,0x16,0xa3,0xdf,0xc1,
		0x33,0x99,0xd0,0x61,0xda,0x74,0x12,0x4e,
		0x96,0x6f,0x9a,0x1c,0x25,0x24,0x89,0x42,
		0xa9,0xeb,0x0c,0x56,0xe1,0x04,0xbb,0x6a
	};
	static CK_BYTE ClientMacSecret[] = {
		0x12,0x9d,0xf5,0xe1,0x00,0xfe,0x51,0xf5,
		0xe9,0xf3,0xcf,0xff,0x4f,0x02,0xcc,0xc9,
		0x4a,0xe8,0x32,0x11,0xbd,0x35,0x63,0xa8,
		0xe2,0xa9,0x71,0xd2,0x61,0x24,0x7b,0x23
	};
	static CK_BYTE ServerMacSecret[] = {
		0xc0,0xfc,0x04,0x6f,0xa2,0xc6,0x30,0x97,
		0xa2,0x90,0x8a,0x47,0x56,0x26,0x9d,0xc9,
		0xe9,0x87,0x71,0x41,0xc4,0x3d,0x81,0x81,
		0xb0,0x30,0x8f,0xea,0xa3,0x86,0x4f,0xae
	};
	static CK_BYTE ClientKey[] = {
		0x0e,0xfc,0x85,0x03,0x2b,0x40,0xbd,0x65,
		0xce,0x39,0x70,0xb0,0xed,0xd2,0x48,0xdd,
		0x6e,0xfc,0x97,0x29,0xb4,0xd5,0xd8,0x91,
		0x42,0x7a,0xd0,0x55,0x9c,0x7c,0x6e,0x61
	};
	static CK_BYTE ServerKey[] = {
		0x17,0x34,0xe4,0x2c,0x8e,0x9c,0x6f,0xda,
		0x3c,0x30,0xbb,0xc8,0xfa,0xe7,0x8d,0x76,
		0x11,0x0c,0xfc,0x5b,0xeb,0x00,0x92,0xb2,
		0xed,0x36,0x3e,0x27,0x60,0x12,0x50,0xa5
	};
	static CK_BYTE IVs[] = {
		0x99,0x38,0xb5,0x71,0x78,0x47,0x92,0xba,
		0xc4,0x43,0xb9,0xd3,0x24,0x75,0x09,0x79
	};

    static CK_BYTE client_random_2[] = 
    {
        0x4c, 0x5f, 0xc4, 0xac, 0xee, 0xe1, 0x9f, 0xfb, 
        0x6c, 0x1a, 0x65, 0x56, 0x87, 0x03, 0x33, 0x77, 
        0x54, 0xfc, 0x90, 0x70, 0x78, 0xc2, 0xa5, 0x03, 
        0x34, 0x4e, 0x57, 0x99, 0x8f, 0x50, 0x16, 0x4f
    };
    static CK_BYTE server_random_2[] = 
    {
        0x4c, 0x5f, 0xc5, 0x41, 0xc5, 0x7e, 0xc8, 0x52, 
        0xab, 0x79, 0x48, 0xb9, 0x0d, 0x04, 0xf8, 0x04,
        0x13, 0x55, 0xfd, 0x78, 0xcc, 0xc2, 0xcd, 0xa4, 
        0x32, 0x3c, 0xcc, 0x4c, 0xb0, 0x47, 0x3d, 0x1c
    };
    static CK_BYTE master_2[] = 
    {
        0x44, 0xa4, 0x42, 0x6d, 0x62, 0x7e, 0x0b, 0x69, 
        0x07, 0xee, 0x10, 0x77, 0x04, 0xf5, 0x30, 0x99,
        0x9b, 0x7e, 0x06, 0xb4, 0x6e, 0x9b, 0xde, 0x39, 
        0x07, 0xec, 0x82, 0x1f, 0xc2, 0x37, 0x27, 0xfd,
        0x43, 0x93, 0x86, 0xbc, 0x8f, 0xd3, 0xdb, 0x74, 
        0x51, 0xb5, 0xe6, 0x9f, 0x77, 0x20, 0x78, 0xaa
    };

	// CryptoPro GOST 3411 HASH 1 Param Set OID
	static CK_BYTE oid_hash_1[] = { 
		0x06, 0x07, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x1e, 0x01 
	};
	static CK_BYTE gost28147_params_A[] = { 
		0x06, 0x07, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x1f, 0x01 
	};

	static CK_ATTRIBUTE master_key_template[] = {
		{ CKA_VALUE, master, sizeof(master) },
		{ CKA_CLASS, &oclass, sizeof(oclass) },
		{ CKA_KEY_TYPE, &generic_key_type, sizeof(generic_key_type) },
		{ CKA_DERIVE, &ltrue, sizeof(ltrue) },
		{ CKA_SENSITIVE, &lfalse, sizeof(lfalse) },
		{ CKA_EXTRACTABLE, &ltrue, sizeof(ltrue) }
	};

	static CK_ATTRIBUTE secret_key_template[] = {
		{ CKA_CLASS, &oclass, sizeof(oclass) },
		{ CKA_KEY_TYPE, &secret_key_type, sizeof(secret_key_type) },
		{ CKA_GOST28147_PARAMS, gost28147_params_A, sizeof(gost28147_params_A) },
		{ CKA_ENCRYPT, &ltrue, sizeof(ltrue) },
		{ CKA_DECRYPT, &ltrue, sizeof(ltrue) },
		{ CKA_SIGN, &ltrue, sizeof(ltrue) },
		{ CKA_VERIFY, &ltrue, sizeof(ltrue) },
		{ CKA_SENSITIVE, &lfalse, sizeof(lfalse) },
		{ CKA_EXTRACTABLE, &ltrue, sizeof(ltrue) }
	};

	static CK_ATTRIBUTE master_key_template_2[] = {
		{ CKA_VALUE, master_2, sizeof(master_2) },
		{ CKA_CLASS, &oclass, sizeof(oclass) },
		{ CKA_DERIVE, &ltrue, sizeof(ltrue) },
		{ CKA_SIGN, &ltrue, sizeof(ltrue) },
		{ CKA_VERIFY, &ltrue, sizeof(ltrue) },
		{ CKA_KEY_TYPE, &generic_key_type, sizeof(generic_key_type) },
		{ CKA_SENSITIVE, &lfalse, sizeof(lfalse) },
		{ CKA_EXTRACTABLE, &ltrue, sizeof(ltrue) }
	};

	static CK_BYTE IVClient[8];
	static CK_BYTE IVServer[8];
	static CK_SSL3_KEY_MAT_OUT km = {
			CK_INVALID_HANDLE, CK_INVALID_HANDLE,
			CK_INVALID_HANDLE, CK_INVALID_HANDLE,
			IVClient, IVServer
	};

	static CK_TLS_GOST_KEY_MAT_PARAMS params_gost =
	{
		{ 
		    256, 256, 64, CK_FALSE, 
		    { 
				client_random, sizeof(client_random), 
				server_random, sizeof(server_random) 
			},
		    &km 
		},
		oid_hash_1,
		sizeof(oid_hash_1)
	};

	static CK_TLS_GOST_KEY_MAT_PARAMS params_gost_2 =
	{
		{ 
		    256, 256, 64, CK_FALSE, 
		    { 
				client_random_2, sizeof(client_random_2), 
				server_random_2, sizeof(server_random_2) 
			},
		    &km 
		},
		oid_hash_1,
		sizeof(oid_hash_1)
	};

	mechanism->pParameter = &params_gost;
	mechanism->ulParameterLen = sizeof(params_gost);

	rc = funcs->C_CreateObject(sess, 
		master_key_template, sizeof(master_key_template)/sizeof(CK_ATTRIBUTE), 
		&keyh);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_CreateObject failed: 0x%x\n", rc);
		return rc;
	}

	rc = funcs->C_DeriveKey(sess, mechanism, keyh, 
		secret_key_template, sizeof(secret_key_template)/sizeof(CK_ATTRIBUTE), 
		NULL_PTR);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_DeriveKey failed: 0x%x\n", rc);
		return rc;
	}
	attr.type = CKA_VALUE; 
	attr.pValue = value; 
	attr.ulValueLen = sizeof(value);
	rc = funcs->C_GetAttributeValue(sess, km.hClientMacSecret, &attr, 1);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_GetAttributeValue failed: 0x%x\n", rc);
		return rc;
	}
	len = attr.ulValueLen;

	CHECK(ClientMacSecret);

	attr.type = CKA_VALUE; 
	attr.pValue = value; 
	attr.ulValueLen = sizeof(value);
	rc = funcs->C_GetAttributeValue(sess, km.hServerMacSecret, &attr, 1);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_GetAttributeValue failed: 0x%x\n", rc);
		return rc;
	}
	len = attr.ulValueLen;

	CHECK(ServerMacSecret);

	attr.type = CKA_VALUE; 
	attr.pValue = value; 
	attr.ulValueLen = sizeof(value);
	rc = funcs->C_GetAttributeValue(sess, km.hClientKey, &attr, 1);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_GetAttributeValue failed: 0x%x\n", rc);
		return rc;
	}
	len = attr.ulValueLen;

	CHECK(ClientKey);

	attr.type = CKA_VALUE; 
	attr.pValue = value; 
	attr.ulValueLen = sizeof(value);
	rc = funcs->C_GetAttributeValue(sess, km.hServerKey, &attr, 1);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_GetAttributeValue failed: 0x%x\n", rc);
		return rc;
	}
	len = attr.ulValueLen;

	CHECK(ServerKey);

	memcpy(value, IVClient, 8);
	memcpy(value + 8, IVServer, 8);
	len = 16;

	CHECK(IVs);

	rc = funcs->C_DestroyObject(sess, km.hClientMacSecret);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_DestroyObject failed: 0x%x\n", rc);
		return rc;
	}
	rc = funcs->C_DestroyObject(sess, km.hServerMacSecret);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_DestroyObject failed: 0x%x\n", rc);
		return rc;
	}
	rc = funcs->C_DestroyObject(sess, km.hClientKey);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_DestroyObject failed: 0x%x\n", rc);
		return rc;
	}
	rc = funcs->C_DestroyObject(sess, km.hServerKey);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_DestroyObject failed: 0x%x\n", rc);
		return rc;
	}

	rc = funcs->C_DestroyObject(sess, keyh);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_DestroyObject failed: 0x%x\n", rc);
		return rc;
	}
	
    // Orlov test

    print_bytes(master_2, sizeof(master_2), str);
    printf("Master:\n%s\n", str);
    print_bytes(client_random_2, sizeof(client_random_2), str);
    printf("Client random:\n%s\n", str);
    print_bytes(server_random_2, sizeof(server_random_2), str);
    printf("Server random:\n%s\n", str);
    print_bytes(oid_hash_1, sizeof(oid_hash_1), str);
    printf("oid_hash_1:\n%s\n", str);
	mechanism->pParameter = &params_gost_2;
	mechanism->ulParameterLen = sizeof(params_gost_2);

	rc = funcs->C_CreateObject(sess, 
		master_key_template_2, sizeof(master_key_template_2)/sizeof(CK_ATTRIBUTE), 
		&keyh);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_CreateObject failed: 0x%x\n", rc);
		return rc;
	}

	rc = funcs->C_DeriveKey(sess, mechanism, keyh, 
		secret_key_template, sizeof(secret_key_template)/sizeof(CK_ATTRIBUTE), 
		NULL_PTR);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_DeriveKey failed: 0x%x\n", rc);
		return rc;
	}

	attr.type = CKA_VALUE; 
	attr.pValue = value; 
	attr.ulValueLen = sizeof(value);
	rc = funcs->C_GetAttributeValue(sess, km.hClientMacSecret, &attr, 1);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_GetAttributeValue failed: 0x%x\n", rc);
		return rc;
	}
	len = attr.ulValueLen;

    print_bytes(attr.pValue, attr.ulValueLen, str);
    printf("ClientMacSecret:\n%s\n", str);
//	CHECK(ClientMacSecret);

	attr.type = CKA_VALUE; 
	attr.pValue = value; 
	attr.ulValueLen = sizeof(value);
	rc = funcs->C_GetAttributeValue(sess, km.hServerMacSecret, &attr, 1);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_GetAttributeValue failed: 0x%x\n", rc);
		return rc;
	}
	len = attr.ulValueLen;

    print_bytes(attr.pValue, attr.ulValueLen, str);
    printf("ServerMacSecret:\n%s\n", str);
//	CHECK(ServerMacSecret);

	attr.type = CKA_VALUE; 
	attr.pValue = value; 
	attr.ulValueLen = sizeof(value);
	rc = funcs->C_GetAttributeValue(sess, km.hClientKey, &attr, 1);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_GetAttributeValue failed: 0x%x\n", rc);
		return rc;
	}
	len = attr.ulValueLen;

    print_bytes(attr.pValue, attr.ulValueLen, str);
    printf("ClientKey:\n%s\n", str);
//	CHECK(ClientKey);

	attr.type = CKA_VALUE; 
	attr.pValue = value; 
	attr.ulValueLen = sizeof(value);
	rc = funcs->C_GetAttributeValue(sess, km.hServerKey, &attr, 1);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_GetAttributeValue failed: 0x%x\n", rc);
		return rc;
	}
	len = attr.ulValueLen;

    print_bytes(attr.pValue, attr.ulValueLen, str);
    printf("ServerKey:\n%s\n", str);
//	CHECK(ServerKey);

	memcpy(value, IVClient, 8);
	memcpy(value + 8, IVServer, 8);
	len = 16;

    print_bytes(attr.pValue, 8, str);
    printf("IVClient:\n%s\n", str);
    print_bytes((CK_BYTE_PTR)attr.pValue+8, 8, str);
    printf("IVServer:\n%s\n", str);
//	CHECK(IVs);

	rc = funcs->C_DestroyObject(sess, km.hClientMacSecret);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_DestroyObject failed: 0x%x\n", rc);
		return rc;
	}
	rc = funcs->C_DestroyObject(sess, km.hServerMacSecret);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_DestroyObject failed: 0x%x\n", rc);
		return rc;
	}
	rc = funcs->C_DestroyObject(sess, km.hClientKey);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_DestroyObject failed: 0x%x\n", rc);
		return rc;
	}
	rc = funcs->C_DestroyObject(sess, km.hServerKey);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_DestroyObject failed: 0x%x\n", rc);
		return rc;
	}

	rc = funcs->C_DestroyObject(sess, keyh);
	if (rc != CKR_OK) {
		fprintf(stderr, "C_DestroyObject failed: 0x%x\n", rc);
		return rc;
	}
	
	return rc;
}




