/****************************************************************************** *Func Name : PTPV2_ANN_PrintAnn *Description : announce报文打印接口 *Input : PTPV2_ANNOUNCE_MSG_S *pstAnnMsg: 消息头 * TCPIP_PTP_ADDRINFO_S *pstAddrInfo: 接收/发送报文的地址以及UDP信息 * ULONG ulFlag: 标记:0-发送报文;非0-接收报文 *Output : *Return : *Caution : *Calls : *Called by : *----------------------------------------------------------------------------- * Modification History * DATE NAME DESCRIPTION * 2014-05-14 dutianyi Create *******************************************************************************/ VOID PTPV2_ANN_PrintAnn(PTPV2_ANNOUNCE_MSG_S *pstAnnMsg, TCPIP_PTP_ADDRINFO_S *pstAddrInfo, ULONG ulFlag) { CHAR szBuf[LEN_512] = {0}; /* 缓冲区长度512个字节,存放报文信息 */ CHAR szInOrOut[10] = {0}; INT32 i32Offset = 0; if ((NULL == pstAnnMsg) || (NULL == pstAddrInfo)) { return; } if (0 == ulFlag) { i32Offset = TCPIP_SNPRINTF0(szInOrOut, 10, P0("send")); } else { i32Offset = TCPIP_SNPRINTF0(szInOrOut, 10, P0("receive")); } /* 先打印提示信息 */ (VOID)TCPIP_SNPRINTF(szBuf + i32Offset, LEN_512 - i32Offset, P1("\r\n----------announce msg %s begin----------",szInOrOut)); TCPIP_InfoOutput(szBuf); (VOID)TCPIP_Mem_Set(szBuf, 0, LEN_512); /* 打印消息头 */ PTPV2_PrintHeader((PTPV2_MSGHEADER_S *)pstAnnMsg, pstAddrInfo); i32Offset = TCPIP_SNPRINTF0(szBuf, LEN_512, P0("\r\nANNOUNCE INFO:")); /* 打印announce消息的其他内容 */ i32Offset += TCPIP_SNPRINTF(szBuf + i32Offset, LEN_512 - i32Offset, P8("\r\n originTimestamp : Nano-%u,Low-%u,High-%u \r\n utcoffset : %d\r\n grandmasterPri1 : %u\r\n grandmasterQuality : Accuracy-%u,class-%u,offset-%u ", pstAnnMsg->stOriginTimestamp.ulNanoseconds, pstAnnMsg->stOriginTimestamp.ulSecondsLow, pstAnnMsg->stOriginTimestamp.usSecondsHigh, VOS_NTOHS(pstAnnMsg->sCurrentUtcOffset), pstAnnMsg->ucGrandmasterPriority1, pstAnnMsg->stGrandmasterClockQuality.ucClockAccuracy, pstAnnMsg->stGrandmasterClockQuality.ucClockClass, VOS_NTOHS(pstAnnMsg->stGrandmasterClockQuality.usOffsetScaledLogVariance))); i32Offset += TCPIP_SNPRINTF(szBuf + i32Offset, LEN_512 - i32Offset, P11("\r\n grandmasterPri2 : %u\r\n grandmasterId : %02x%02x%02x%02x%02x%02x%02x%02x\r\n stepsremoved : %u\r\n timesource : %u", pstAnnMsg->ucGrandmasterPriority2, pstAnnMsg->stGrandmasterIdentity[0], pstAnnMsg->stGrandmasterIdentity[1], pstAnnMsg->stGrandmasterIdentity[2], pstAnnMsg->stGrandmasterIdentity[3], pstAnnMsg->stGrandmasterIdentity[4], pstAnnMsg->stGrandmasterIdentity[5], pstAnnMsg->stGrandmasterIdentity[6], pstAnnMsg->stGrandmasterIdentity[7], VOS_NTOHS(pstAnnMsg->usStepsRemoved), pstAnnMsg->ucTimeSource)); (VOID)TCPIP_SNPRINTF(szBuf + i32Offset, LEN_512 - i32Offset, P1("\r\n----------announce msg %s end------------",szInOrOut)); TCPIP_InfoOutput(szBuf); }
/* Initialise the token. */ void inittoken (void) { if (destructive) { if (verbosity >= 1) { printf ("Formatting the token and setting the PIN and SO-PIN as specified\n"); } TESTRV ("Formatting the token", P11("C_InitToken") (slotid, (CK_UTF8CHAR_PTR) ascii_pin_so, strlen (ascii_pin_so), (CK_UTF8CHAR_PTR) TOKENLABEL_32CHARS)); } else { CU_PASS ("Skipping token initialisation in non-destructive test mode. Existing USER/SO PIN values must be as set in source."); } }
/* Bail out is the routine that does some cleaning up upon exit(). */ void bailout (void) { if (p11) { TESTRV ("Finalising PKCS #11 library", P11("C_Finalize") (NULL_PTR)); dlclose (p11); p11 = NULL; } if (cu_open) { CU_cleanup_registry (); cu_open = 0; } }
int main() { double V0[] = {1,0,0,1,0,0}; std::vector<double> Vertices0(V0, V0+6); Triangle<2>::SetGlobalCoordinatesArray(Vertices0); Triangle<2> P10(1,2,3); ShapesP12D::Bulk P10Shapes(&P10); std::cout << "Parametric triangle\n"; PrintData(P10Shapes); std::cout << "\nTwice Parametric triangle\n"; double V1[] = {2,0,0,2,0,0}; std::vector<double> Vertices1(V1, V1+6); Triangle<2>::SetGlobalCoordinatesArray(Vertices1); Triangle<2> P11(1,2,3); ShapesP12D::Bulk P11Shapes(&P11); PrintData(P11Shapes); std::cout << "\nReordered nodes of twice parametric triangle\n"; double V2[] = {0,0,2,0,0,2}; std::vector<double> Vertices2(V2, V2+6); Triangle<2>::SetGlobalCoordinatesArray(Vertices2); Triangle<2> P12(1,2,3); ShapesP12D::Bulk P12Shapes(&P12); PrintData(P12Shapes); std::cout << "\n Equilateral triangle with area sqrt(3)\n"; double V3[] = {0,0,2,0,1,sqrt(3)}; std::vector<double> Vertices3(V3, V3+6); Triangle<2>::SetGlobalCoordinatesArray(Vertices3); Triangle<2> P13(1,2,3); ShapesP12D::Bulk P13Shapes(&P13); PrintData(P13Shapes); std::cout << "\n Irregular triangle with area sqrt(3)\n"; double V4[] = {0,0,2,0,2.5,sqrt(3)}; std::vector<double> Vertices4(V4, V4+6); Triangle<2>::SetGlobalCoordinatesArray(Vertices4); Triangle<2> P14(1,2,3); ShapesP12D::Bulk P14Shapes(&P14); PrintData(P14Shapes); }
__CD__BEGIN Vector3D my_tri_tri_intersect(const Triangle& t1, const Triangle& t2) { Plane p1(t1.v1,t1.v2,t1.v3); int other_side=0; { float f1=p1.Classify(t2.v1); float f2=p1.Classify(t2.v2); float f3=p1.Classify(t2.v3); float f12=f1*f2; float f23=f2*f3; if (f12>0.0f && f23>0.0f) return Vector3D::Zero; other_side=(f12<0.0f?(f23<0.0f?1:0):2); } Plane p2(t2.v1,t2.v2,t2.v3); Vector3D n12(p1.normal+p2.normal); TriangleDesc td2(t2,p2); const Vector3D& a2=td2[other_side+1]; const Vector3D& b2=td2[other_side]; const Vector3D& c2=td2[other_side+2]; float t21=-(p1.d+p2.d+a2*n12)/((b2-a2)*n12); TriangleDesc td1(t1,p1); Vector3D P21(a2+t21*(b2-a2)); if (td1.pointInTri(P21)) return P21; float t22=-(p1.d+p2.d+c2*n12)/((b2-c2)*n12); Vector3D P22(c2+t22*(b2-c2)); if (td1.pointInTri(P22)) return P22; { float f1=p2.Classify(t1.v1); float f2=p2.Classify(t1.v2); float f3=p2.Classify(t1.v3); float f12=f1*f2; float f23=f2*f3; if (f12>0.0f && f23>0.0f) return Vector3D::Zero; other_side=(f12<0.0f?(f23<0.0f?1:0):2); } const Vector3D& a1=td1[other_side+1]; const Vector3D& b1=td1[other_side]; const Vector3D& c1=td1[other_side+2]; float t11=-(p1.d+p2.d+a1*n12)/((b1-a1)*n12); Vector3D P11(a1+t11*(b1-a1)); if (td2.pointInTri(P11)) return P11; float t12=-(p1.d+p2.d+c1*n12)/((b1-c1)*n12); Vector3D P12(c1+t12*(b1-c1)); if (td2.pointInTri(P12)) return P12; return Vector3D::Zero; }
CK_RV newkeypair (CK_SESSION_HANDLE seshdl, CK_ULONG keybits, CK_OBJECT_HANDLE_PTR pub, CK_OBJECT_HANDLE_PTR priv) { CK_BYTE pubexp [] = { 0x01, 0x00, 0x01 }; // anyEndian anagram! CK_BBOOL ckTrue = CK_TRUE; CK_BBOOL ckFalse = CK_FALSE; CK_MECHANISM mech = { CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0 }; CK_ATTRIBUTE pubtmpl [] = { { CKA_PRIVATE, &ckFalse, sizeof (ckFalse) }, { CKA_MODULUS_BITS, &keybits, sizeof (keybits) }, { CKA_PUBLIC_EXPONENT, &pubexp, sizeof (pubexp) }, { CKA_TOKEN, &ckTrue, sizeof (ckTrue) }, { CKA_LOCAL, &ckTrue, sizeof (ckTrue) }, { CKA_MODIFIABLE, &ckFalse, sizeof (ckFalse) }, { CKA_VERIFY, &ckTrue, sizeof (ckTrue) }, { CKA_VERIFY_RECOVER, &ckFalse, sizeof (ckFalse) }, { CKA_WRAP, &ckFalse, sizeof (ckFalse) }, { CKA_DERIVE, &ckFalse, sizeof (ckFalse) }, { CKA_ENCRYPT, &ckFalse, sizeof (ckFalse) }, }; CK_ATTRIBUTE privtmpl [] = { { CKA_PRIVATE, &ckTrue, sizeof (ckTrue) }, { CKA_TOKEN, &ckTrue, sizeof (ckTrue) }, { CKA_MODIFIABLE, &ckFalse, sizeof (ckFalse) }, { CKA_LOCAL, &ckTrue, sizeof (ckTrue) }, { CKA_SENSITIVE, &ckTrue, sizeof (ckTrue) }, { CKA_ALWAYS_SENSITIVE, &ckTrue, sizeof (ckTrue) }, { CKA_EXTRACTABLE, &ckFalse, sizeof (ckFalse) }, { CKA_NEVER_EXTRACTABLE, &ckTrue, sizeof (ckTrue) }, { CKA_SIGN, &ckTrue, sizeof (ckTrue) }, { CKA_SIGN_RECOVER, &ckFalse, sizeof (ckFalse) }, { CKA_DECRYPT, &ckFalse, sizeof (ckFalse) }, { CKA_UNWRAP, &ckFalse, sizeof (ckFalse) }, { CKA_DERIVE, &ckFalse, sizeof (ckFalse) }, }; if (verbosity >= 3) { printf (" - Creating key pair with %lu bit modulus\n", keybits); } return P11("C_GenerateKeyPair") ( seshdl, &mech, pubtmpl, sizeof (pubtmpl) / sizeof (*pubtmpl), privtmpl, sizeof (privtmpl) / sizeof (*privtmpl), pub, priv); }
int main (int argc, char *argv []) { CK_SLOT_ID slotlist [2]; CK_ULONG slotcount = 2; CU_pSuite st [4]; int opt; int todo; extern char *optarg; /* * Test arguments. */ todo = 1; while (todo && (opt = getopt_long (argc, argv, opts, longopts, NULL))) { switch (opt) { case 'p': // --pin storepin ("user", optarg, ascii_pin_user, sizeof (ascii_pin_user) - 1); break; case 'P': // --so-pin storepin ("SO", optarg, ascii_pin_so, sizeof (ascii_pin_so) - 1); break; case 'l': // --pkcs1llib if (p11) { fprintf (stderr, "You should not open multiple PKCS #11 libraries\n"); exit (1); } p11 = dlopen (optarg, RTLD_NOW | RTLD_GLOBAL); if (!p11) { fprintf (stderr, "%s\n", dlerror ()); exit (1); } break; case 'X': // --destructive if (destructive) { fprintf (stderr, "You should not specify your destructive wishes more than once\n"); exit (1); } destructive = 1; break; case 'f': // --fast-and-frivolous if (thousands < 1000) { fprintf (stderr, "You should not specify the fast option more than once\n"); exit (1); } thousands = 10; hundred = 8; couple = 3; break; case 'v': // --verbose if (optarg) { verbosity = atoi (optarg); if (verbosity < 0) { fprintf (stderr, "You should not specify negative verbosity levels\n"); exit (1); } } else { verbosity++; } break; case 1: // --test-initiation if (skip_initiation == 0) { fprintf (stderr, "You should not specify --test-initiation more than once\n"); exit (1); } skip_initiation = 0; break; case 2: // --skip-fragmentation if (skip_fragmentation) { fprintf (stderr, "You should not specify --skip-fragmentation more than once\n"); exit (1); } skip_fragmentation = 1; break; case 3: // --skip-keysizing if (skip_keysizing) { fprintf (stderr, "You should not specify --skip-keysizing more than once\n"); exit (1); } skip_keysizing = 1; break; case 4: // --skip-signing if (skip_signing) { fprintf (stderr, "You should not specify --skip-signing more than once\n"); exit (1); } skip_signing = 1; break; // case 't': // Token? case -1: // Done -- but are we, really? if ((*ascii_pin_user) && (*ascii_pin_so) && p11) { todo = 0; break; } // else continue... fprintf (stderr, "Please set all values required.\n"); case 'h': case ':': case '?': fprintf (stderr, "Minimal usage: %s --pin 1234 --so-pin 4321 --pkcs11lib /path/to/libpkcs11.so\n", argv [0]); exit (opt != 'h'); } } /* * Register test suites and tests. */ if (CU_initialize_registry () != CUE_SUCCESS) { fprintf (stderr, "Failed to initialise test registry -- this is abnormal\n"); exit (1); } else { cu_open = 1; } st [0] = CU_add_suite ("Test if slot initiation works properly", NULL, NULL); st [1] = CU_add_suite ("Test if memory does not get fragmented", NULL, NULL); st [2] = CU_add_suite ("Test if key sizes work as desired", NULL, NULL); st [3] = CU_add_suite ("Test if signatures are made correctly", NULL, NULL); if (! (st [0] && st [1] && st [2] && st [3])) { fprintf (stderr, "Failed to allocate all test suites -- this is abnormal\n"); exit (1); } if (! skip_initiation) { if (! CU_add_test (st [0], "Initiation test", testslot_initiation)) { fprintf (stderr, "Failed to register test #0 -- this is abnormal\n"); exit (1); } } if (! skip_fragmentation) { if (! CU_add_test (st [1], "Fragmentation test", testslot_fragmentation)) { fprintf (stderr, "Failed to register test #1 -- this is abnormal\n"); exit (1); } } if (! skip_keysizing) { if (! CU_add_test (st [2], "Key sizing test", testslot_keysizing)) { fprintf (stderr, "Failed to register test #2 -- this is abnormal\n"); exit (1); } } if (! skip_signing) { if (! CU_add_test (st [3], "Signing test", testslot_signing)) { fprintf (stderr, "Failed to register test #3 -- this is abnormal\n"); exit (1); } } /* * Initialise the library and demand only one slot with a token. */ TESTRV ("Initialising PKCS #11 library", P11("C_Initialize") (NULL_PTR)); MKFATAL (); atexit (bailout); TESTRV ("Obtaining list of slots", P11("C_GetSlotList") (TRUE, slotlist, &slotcount)); if (slotcount != 1) { fprintf (stderr, "Number of slots is %d, so not equal to 1 -- unsure which to test\n", (int) slotcount); exit (1); } slotid = slotlist [0]; /* * Obtain mechanism information from the token. */ TESTRV ("Getting number of mechanisms from token", P11("C_GetMechanismInfo") (slotid, CKM_RSA_PKCS_KEY_PAIR_GEN, &mech_rsa_pkcs_key_pair_gen)); MKFATAL (); TESTRV ("Getting number of mechanisms from token", P11("C_GetMechanismInfo") (slotid, CKM_RSA_PKCS, &mech_rsa_pkcs)); MKFATAL (); /* TESTRV ("Getting number of mechanisms from token", P11("C_GetMechanismInfo") (slotid, CKM_SHA_1, &mech_sha_1)); MKFATAL (); */ /* * Format the token and run a test. * Do we need an "are you sure?" warning here? */ if (strlen (TOKENLABEL_32CHARS) != 32) { CU_FAIL_FATAL ("Token labels must be 32 characters long -- fix TOKENLABEL_32CHARS and recompile"); } /* * Automatically run all the tests that were registered */ if (verbosity >= 1) { printf ("Beginning test sequence\n"); } CU_list_tests_to_file (); CU_automated_run_tests (); if (verbosity >= 1) { printf ("Ended test sequence\n"); } /* * Unload the PKCS #11 library */ if (p11) { dlclose (p11); p11 = NULL; } /* * Terminate without error-reporting return value. */ if (cu_open) { CU_cleanup_registry (); cu_open = 0; } exit (0); }
/* Test a slot: Given a global slot ID, test the slot given. * This particular routine tests if signatures are correctly made. */ void testslot_signing (void) { CK_SESSION_HANDLE seshdl; CK_BYTE noappinfo; int minbytes, maxbytes; int keytestctr, sigtestctr; /* Announce the start of this test */ if (verbosity >= 1) { printf ("Entering signing test\n"); } /* * Open RW session with slot */ TESTRV ("Opening session for fragmentation test", P11("C_OpenSession") (slotid, CKF_SERIAL_SESSION | CKF_RW_SESSION, (void *) &noappinfo, NULL_PTR, &seshdl)); MKFATAL (); /* * Login to token as USER (possibly after setting up the PIN to use) */ if (destructive) { TESTRV ("Logging into token for setting up PIN", P11("C_Login") (seshdl, CKU_SO, (CK_UTF8CHAR_PTR) ascii_pin_so, strlen (ascii_pin_so))); TESTRV ("Setting up user PIN", P11("C_InitPIN") (seshdl, (CK_UTF8CHAR_PTR) ascii_pin_user, strlen (ascii_pin_user))); TESTRV ("Logging out after setting setting up PIN", P11("C_Logout") (seshdl)); } TESTRV ("Logging into token for signing test", P11("C_Login") (seshdl, CKU_USER, (CK_UTF8CHAR_PTR) ascii_pin_user, strlen (ascii_pin_user))); MKFATAL (); /* * Fetch supported key sizes for this token. Count in bytes, not * bits, to simplify later randomisation of key sizes. */ if (verbosity >= 2) { printf (" * Determine key sizes\n"); } CU_ASSERT_EQUAL (mech_rsa_pkcs.ulMinKeySize % 8, 0); CU_ASSERT_EQUAL (mech_rsa_pkcs.ulMaxKeySize % 8, 0); CU_ASSERT (mech_rsa_pkcs.ulMinKeySize <= mech_rsa_pkcs.ulMaxKeySize); CU_ASSERT (mech_rsa_pkcs.ulMinKeySize <= 512); CU_ASSERT (mech_rsa_pkcs.ulMaxKeySize >= 2048); minbytes = mech_rsa_pkcs.ulMinKeySize / 8; maxbytes = mech_rsa_pkcs.ulMaxKeySize / 8; if (verbosity >= 3) { printf (" - Key sizes supported by this token range from %d to %d bits\n", minbytes * 8, maxbytes * 8); } /* * Iterate over keys a couple of times, creating a new key pair for * each iteration. */ for (keytestctr = 0; keytestctr < couple; keytestctr++) { if (verbosity >= 2) { printf (" * Key test iteration %d\n", keytestctr); } int modbits = 8 * randomish_minmax (minbytes, maxbytes); CK_OBJECT_HANDLE pub, priv; TESTRV ("Creating a new key pair for signature tests", newkeypair (seshdl, modbits, &pub, &priv)); if (! LASTRVOK () ) { // Failure makes the rest of this loop dysfunctional continue; } /* Iterate over signatures about a hundred times. Create * a signature and verify it. */ for (sigtestctr = 0; sigtestctr < hundred; sigtestctr++) { CK_BYTE data [] = "tralala-en-hopsasa"; CK_BYTE *sig = malloc (maxbytes); CK_ULONG siglen; CK_MECHANISM mech = { CKM_RSA_PKCS, NULL_PTR, 0 }; if (verbosity >= 4) { printf ("%3d / %8d\b\b\b\b\b\b\b\b\b\b\b\b\b\b", couple - keytestctr, hundred - sigtestctr); } if (sig == NULL) { CU_FAIL ("Out of memory allocating for signature test"); break; } siglen = maxbytes; TESTRV ("Initiating signature", P11("C_SignInit") (seshdl, &mech, priv)); TESTRV ("Constructing signature", P11("C_Sign") (seshdl, data, sizeof (data), sig, &siglen)); if (siglen * 8 != (CK_ULONG) modbits) { CU_FAIL ("Signature length differs from promised length in signing test"); } else { CU_PASS ("Signature length matches promised length in signing test"); } TESTRV ("Initiating signature verification", P11("C_VerifyInit") (seshdl, &mech, pub)); TESTRV ("Performing signature verification", P11("C_Verify") (seshdl, data, sizeof (data), sig, siglen)); if (! LASTRVOK () ) { CU_FAIL ("Signature was incorrectly made in signing test"); } else { CU_PASS ("Signature was correctly made in signing test"); } free (sig); } /* Destroy the key pair used in this test iteration. */ TESTRV ("Destroying private key in modulus size test", P11("C_DestroyObject") (seshdl, priv)); TESTRV ("Destroying public key in modulus size test", P11("C_DestroyObject") (seshdl, pub)); } /* * Cleanup. */ if (verbosity >= 2) { printf ("Cleaning up token state\n"); } TESTRV ("Logging out after modulus size test", P11("C_Logout") (seshdl)); TESTRV ("Closing session after modulus size test", P11("C_CloseSession") (seshdl)); }
/* Test a slot: Given a global slot ID, test the slot given. * This particular routine tests if keys are created at proper sizes. * Note that the PKCS #1 standard defines modulus bit sizes as multiples * of 8, and that it defines the number of modulus bits by rounding up * the actual number of bits used to an eightfold value. So if the prime * product of the modulus counts 1021 bits, it counts as a 1024 bit key. */ void testslot_keysizing (void) { CK_SESSION_HANDLE seshdl; CK_BYTE noappinfo; CK_ULONG minbytes, maxbytes, curbytes; CK_RV retval; /* Announce the start of this test */ if (verbosity >= 1) { printf ("Entering keysizing test\n"); } /* * Open RW session with slot */ TESTRV ("Opening session for keysizing test", P11("C_OpenSession") (slotid, CKF_SERIAL_SESSION | CKF_RW_SESSION, (void *) &noappinfo, NULL_PTR, &seshdl)); MKFATAL (); /* * Login to token as USER (possibly after setting up the PIN to use) */ if (destructive) { TESTRV ("Logging into token for setting up PIN", P11("C_Login") (seshdl, CKU_SO, (CK_UTF8CHAR_PTR) ascii_pin_so, strlen (ascii_pin_so))); TESTRV ("Setting up user PIN", P11("C_InitPIN") (seshdl, (CK_UTF8CHAR_PTR) ascii_pin_user, strlen (ascii_pin_user))); TESTRV ("Logging out after setting setting up PIN", P11("C_Logout") (seshdl)); } TESTRV ("Logging into token for keysizing test", P11("C_Login") (seshdl, CKU_USER, (CK_UTF8CHAR_PTR) ascii_pin_user, strlen (ascii_pin_user))); MKFATAL (); /* * Fetch supported key sizes for this token. Count in bytes, not * bits, to simplify later randomisation of key sizes. */ if (verbosity >= 2) { printf (" * Determine key sizes\n"); } CU_ASSERT_EQUAL (mech_rsa_pkcs.ulMinKeySize % 8, 0); CU_ASSERT_EQUAL (mech_rsa_pkcs.ulMaxKeySize % 8, 0); CU_ASSERT (mech_rsa_pkcs.ulMinKeySize <= mech_rsa_pkcs.ulMaxKeySize); CU_ASSERT (mech_rsa_pkcs.ulMinKeySize <= 512); CU_ASSERT (mech_rsa_pkcs.ulMaxKeySize >= 2048); minbytes = mech_rsa_pkcs.ulMinKeySize / 8; maxbytes = mech_rsa_pkcs.ulMaxKeySize / 8; if (verbosity >= 3) { printf (" - Key sizes supported by this token range from %lu to %lu bits\n", minbytes * 8, maxbytes * 8); } /* * Iterate over key pair lengths, checking the modulus size of each. */ if (verbosity >= 2) { printf (" * Check modulus size of each possible key pair length\n"); } curbytes = minbytes; while (curbytes <= maxbytes) { int ok = 1; CK_ULONG modbits = curbytes * 8; CK_OBJECT_HANDLE pub, priv; CK_ATTRIBUTE templ [] = { { CKA_MODULUS, NULL_PTR, 0 }, }; uint8_t *modulus; if (verbosity >= 4) { printf ("%8lu\b\b\b\b\b\b\b\b", maxbytes-curbytes); } retval = newkeypair (seshdl, modbits, &pub, &priv); TESTRV ("Creating key pair in modulus size test", retval); ok = ok && (retval == CKR_OK); if (ok) { TESTRV ("Obtaining length of modulus attribute field", P11("C_GetAttributeValue") (seshdl, pub, templ, sizeof (templ) / sizeof (*templ))); ok = ok && LASTRVOK (); } if (ok) { CU_ASSERT_NOT_EQUAL ((CK_ULONG) templ [0].ulValueLen, (CK_ULONG) -1); modulus = malloc (templ [0].ulValueLen); CU_ASSERT_PTR_NOT_NULL (modulus); templ [0].pValue = (CK_VOID_PTR) modulus; TESTRV ("Obtaining modulus attribute field", P11("C_GetAttributeValue") (seshdl, pub, templ, sizeof (templ) / sizeof (*templ))); ok = ok && LASTRVOK (); CU_ASSERT_NOT_EQUAL_FATAL ((CK_ULONG) templ [0].ulValueLen, (CK_ULONG) -1); while ((templ [0].ulValueLen > 0) && (*modulus == 0x00)) { modulus++; templ [0].ulValueLen--; } if (modulus) { free (modulus); modulus = NULL; } CU_ASSERT_EQUAL (curbytes * 8, templ [0].ulValueLen * 8); if (templ [0].ulValueLen == curbytes) { CU_PASS ("Modulus size matches expactations"); } else { CU_FAIL ("Modulus size diverted from expectations"); } } if (retval == CKR_OK) { TESTRV ("Destroying private key in modulus size test", P11("C_DestroyObject") (seshdl, priv)); TESTRV ("Destroying public key in modulus size test", P11("C_DestroyObject") (seshdl, pub)); } curbytes++; } /* * Cleanup. */ if (verbosity >= 2) { printf (" * Cleaning up token state\n"); } TESTRV ("Logging out after modulus size test", P11("C_Logout") (seshdl)); TESTRV ("Closing session after modulus size test", P11("C_CloseSession") (seshdl)); }
/* Test a slot: Given a global slot ID, test the slot given. * This particular routine tests for fragmentation of the token memory. */ void testslot_fragmentation (void) { CK_SESSION_HANDLE seshdl; CK_BYTE noappinfo; struct key { CK_OBJECT_HANDLE pub; CK_OBJECT_HANDLE priv; CK_ULONG modbits; } *keys = NULL; int keypairs = 0, kp; int minbytes, maxbytes; int testctr; CK_RV retval; /* Announce the start of this test */ if (verbosity >= 1) { printf ("Entering fragmentation test\n"); } /* * Open RW session with slot */ TESTRV ("Opening session for fragmentation test", P11("C_OpenSession") (slotid, CKF_SERIAL_SESSION | CKF_RW_SESSION, (void *) &noappinfo, NULL_PTR, &seshdl)); MKFATAL (); /* * Login to token as USER (possibly after setting up the PIN to use) */ if (destructive) { TESTRV ("Logging into token for setting up PIN", P11("C_Login") (seshdl, CKU_SO, (CK_UTF8CHAR_PTR) ascii_pin_so, strlen (ascii_pin_so))); TESTRV ("Setting up user PIN", P11("C_InitPIN") (seshdl, (CK_UTF8CHAR_PTR) ascii_pin_user, strlen (ascii_pin_user))); TESTRV ("Logging out after setting setting up PIN", P11("C_Logout") (seshdl)); } TESTRV ("Logging into token for fragmentation test", P11("C_Login") (seshdl, CKU_USER, (CK_UTF8CHAR_PTR) ascii_pin_user, strlen (ascii_pin_user))); MKFATAL (); /* * Fetch supported key sizes for this token. Count in bytes, not * bits, to simplify later randomisation of key sizes. */ if (verbosity >= 2) { printf (" * Determine key sizes\n"); } CU_ASSERT_EQUAL (mech_rsa_pkcs.ulMinKeySize % 8, 0); CU_ASSERT_EQUAL (mech_rsa_pkcs.ulMaxKeySize % 8, 0); CU_ASSERT (mech_rsa_pkcs.ulMinKeySize <= mech_rsa_pkcs.ulMaxKeySize); CU_ASSERT (mech_rsa_pkcs.ulMinKeySize <= 512); CU_ASSERT (mech_rsa_pkcs.ulMaxKeySize >= 2048); minbytes = mech_rsa_pkcs.ulMinKeySize / 8; maxbytes = mech_rsa_pkcs.ulMaxKeySize / 8; if (verbosity >= 3) { printf (" - Key sizes supported by this token range from %d to %d bits\n", minbytes * 8, maxbytes * 8); } /* * Fill the token with key pairs. Loop until memory runs out, and * there's no more chances for filling up any further by lowering * the maximum key size. */ if (verbosity >= 2) { printf (" * Filling the token with key pairs\n"); } retval = CKR_OK; while ( retval == CKR_OK ) { CK_ULONG keybits; keybits = 8 * randomish_minmax (minbytes, maxbytes); keys = realloc (keys, sizeof (keys [0]) * (keypairs+1)); CU_ASSERT_PTR_NOT_NULL_FATAL (keys); keys [keypairs].modbits = keybits; retval = newkeypair ( seshdl, keys [keypairs].modbits, &keys [keypairs].pub, &keys [keypairs].priv); if (retval == CKR_OK) { // Succeeded creating a key pair. Increase counter. keypairs++; } if (retval != CKR_DEVICE_MEMORY) { TESTRV ("Key pair generation", retval); } else { CU_PASS ("Key pair generation sequence is running into memory limits"); maxbytes = ( keybits / 8 ) - 1; if (minbytes <= maxbytes) { // It is still possible to squeeze something in retval = CKR_OK; } } } /* * Pick random keys, remove and create a new one of the same size. * If memory does not fragment, this should always succeed. * Repeat this test thousands of times (say, 2500x). */ if (verbosity >= 2) { printf (" * Randomly replace key pairs with ones of the same size\n"); } for (testctr = 0; testctr < thousands; testctr++) { int victim = randomish (keypairs); if (verbosity >= 3) { printf (" - Removing a %lu bit key pair, expecting to free the memory for a new one\n", keys [victim].modbits); if (verbosity >= 4) { printf ("%8d\b\b\b\b\b\b\b\b", thousands-testctr); } } TESTRV ("Removing a private key for fragmentation testing", P11("C_DestroyObject") (seshdl, keys [victim].priv)); TESTRV ("Removing a public key for fragmentation testing", P11("C_DestroyObject") (seshdl, keys [victim].pub)); TESTRV ("Creating new key pair that ought to just fit in prior deleted key storage space", newkeypair ( seshdl, keys [victim].modbits, &keys [victim].pub, &keys [victim].priv) ); } /* * Cleanup: Destroy all key pairs, logout, close session. */ if (verbosity >= 2) { printf (" * Cleanup the key pairs on the token\n"); } for (kp=0; kp<keypairs; kp++) { TESTRV ("Removing a private key after fragmentation test", P11("C_DestroyObject") (seshdl, keys [kp].priv)); TESTRV ("Removing a public key after fragmentation test", P11("C_DestroyObject") (seshdl, keys [kp].pub)); } if (keys) { free (keys); keys = NULL; } TESTRV ("Logging out after fragmentation test", P11("C_Logout") (seshdl)); TESTRV ("Closing session after fragmentation test", P11("C_CloseSession") (seshdl)); }
/* Test a slot: Given a global slot ID, test the slot given. * This particular routine tests if all initiatiation runs well. */ void testslot_initiation (void) { CK_SESSION_HANDLE seshdl; CK_BYTE noappinfo; int initestctr; /* Announce the start of this test */ if (verbosity >= 1) { printf ("Entering initiation test\n"); } /* Complain if user PIN and SO PIN are the same -- this will bring * out more subtlety in the tests to follow. */ if (strlen (ascii_pin_user) == strlen (ascii_pin_so)) { if (!memcmp (ascii_pin_user, ascii_pin_so, strlen (ascii_pin_user))) { CU_FAIL ("SO PIN and USER PIN should differ to get the best results from the initiation test"); } } /* * Open RW session with slot */ TESTRV ("Opening session for initiation test", P11("C_OpenSession") (slotid, CKF_SERIAL_SESSION | CKF_RW_SESSION, (void *) &noappinfo, NULL_PTR, &seshdl)); MKFATAL (); /* * Possibly setup the user PIN to use. */ if (destructive) { TESTRV ("Logging into token for setting up PIN", P11("C_Login") (seshdl, CKU_SO, (CK_UTF8CHAR_PTR) ascii_pin_so, strlen (ascii_pin_so))); TESTRV ("Setting up user PIN", P11("C_InitPIN") (seshdl, (CK_UTF8CHAR_PTR) ascii_pin_user, strlen (ascii_pin_user))); TESTRV ("Logging out after setting setting up PIN", P11("C_Logout") (seshdl)); } /* * Close the RW session with the slot */ TESTRV ("Closing RW SO session for setup of initiation test", P11("C_CloseSession") (seshdl)); /* * Iterate over the actual test, running (distorted) scripts. */ for (initestctr=0; initestctr < thousands; initestctr++) { /* * Choices to be made at randomish: * choice_session==0 => fail to open session * choice_login==0 => fail to login * choice_rw/choice_so => failing combination 0/0 */ int choice_session = randomish (10); int choice_login = randomish (10); int choice_rw = randomish (2); int choice_user = randomish (2); if (verbosity >= 4) { printf ("%8d\b\b\b\b\b\b\b\b", thousands-initestctr); } /* * Open session with slot (with 10% chance of failure). */ if (choice_session) { TESTRV ("Opening session for fragmentation test", P11("C_OpenSession") (slotid, CKF_SERIAL_SESSION | (choice_rw? CKF_RW_SESSION: 0), (void *) &noappinfo, NULL_PTR, &seshdl)); MKFATAL (); } /* * Login as the token user or SO (with 10% chance of failure). */ if (choice_login) { GETRV (P11("C_Login") (seshdl, choice_user? CKU_USER: CKU_SO, (CK_UTF8CHAR_PTR) (choice_user? ascii_pin_user: ascii_pin_so), choice_user? strlen (ascii_pin_user): strlen (ascii_pin_so))); if (choice_session) { if (LASTRVOK ()) { CU_PASS ("Properly granted login on an open session"); } else { CU_FAIL ("Incorrectly failed to login on an open session"); } } else { if (LASTRVOK ()) { CU_FAIL ("Incorrectly allowed login on a non-existing session"); } else { CU_PASS ("Properly refused to login on a closed session"); } } if ((!choice_rw) && (!choice_user)) { if (LASTRVOK ()) { CU_FAIL ("Incorrectly allowed to login to RW SO session"); } else { CU_PASS ("Properly refused to login to RW SO session"); } } } /* * Perform operations that will succeed or fail, depending * on the RW/RO session and SO/USER login. Test if the * response is what it should be. Also take choice_session * and choice_login into account. * * The actual operations below are a few that should be * protected, so they are a test that those protective * barriers are in place. This is not an exhaustive test, * and indeed, not all combinations can actually be tested. * This is just a small set of tests that could be * extended at will. */ /* * Operation 1. Initialise the user PIN. * This is only possible during an SO RW session. */ GETRV (P11("C_InitPIN") (seshdl, (CK_UTF8CHAR_PTR) ascii_pin_user, strlen (ascii_pin_user))); if (choice_session && choice_login && choice_rw && !choice_user) { if (LASTRVOK ()) { CU_PASS ("Properly accepted operation #1 during initiation test"); } else { CU_FAIL ("Incorrectly rejected operation #1 during initiation test"); } } else { if (LASTRVOK ()) { CU_FAIL ("Incorrectly accepted operation #1 during initiation test"); } else { CU_PASS ("Properly rejected operation #1 during initiation test"); } } /* * Operation 2. Set another user PIN. * This is only possible during an RW session. * Login need not have succeeded for this to work. */ GETRV (P11("C_SetPIN") (seshdl, (CK_UTF8CHAR_PTR) (choice_login && !choice_user)? ascii_pin_so: ascii_pin_user, (CK_ULONG) (choice_login && !choice_user)? strlen (ascii_pin_so): strlen (ascii_pin_user), (CK_UTF8CHAR_PTR) (choice_login && !choice_user)? ascii_pin_so: ascii_pin_user, (CK_ULONG) (choice_login && !choice_user)? strlen (ascii_pin_so): strlen (ascii_pin_user))); if (choice_session && choice_login && choice_rw) { if (LASTRVOK ()) { CU_PASS ("Properly accepted operation #2 during initiation test"); } else { CU_FAIL ("Incorrectly rejected operation #2 during initiation test"); } } else { if (LASTRVOK ()) { CU_FAIL ("Incorrectly accepted operation #2 during initiation test"); } else { CU_PASS ("Properly rejected operation #2 during initiation test"); } } /* * Logout from the current session. Note errors and check * if they are rightfully reported. */ GETRV (P11("C_Logout") (seshdl)); if (LASTRVOK ()) { if (choice_session && choice_login) { CU_PASS ("Properly accepted logout in initiation test"); } else { CU_FAIL ("Incorrectly rejected operation #2 during initiation test"); } } else { if (LASTRVOK ()) { CU_FAIL ("Incorrectly accepted operation #2 during initiation test"); } else { CU_PASS ("Properly rejected operation #2 during initiation test"); } } /* * Logout from the current session. Note errors and check * if they are rightfully reported. */ GETRV (P11("C_Logout") (seshdl)); if (! LASTRVOK ()) { if (choice_session && choice_login) { CU_FAIL ("Incorrectly failed logout in initiation test"); } } /* * Close the current session. Note errors and check if they * are rightfully reported. */ GETRV (P11("C_CloseSession") (seshdl)); if (LASTRVOK ()) { if (choice_session) { CU_PASS ("Properly accepted session close in initiation test"); } else { CU_FAIL ("Incorrectly accepted session close in initiation test"); } } else { if (choice_session) { CU_FAIL ("Incorrectly failed session close in initiation test"); } else { CU_PASS ("Properly failed session close in initiation test"); } } /* * End of loop for a single initiation test. */ } /* * End of initiation test, comprising of thousands of tests. */ if (verbosity >= 2) { printf (" * Token state returned to normal\n"); } }
int main() { Point center(41,29); // The numbering of the nodes corresponds to gslib's output order Node P5(38,28,0.5740); Node P8(45,29,1.2110); Node P4(41,26,2.1270); Node P3(39,31,8.3400); Node P6(38,31,18.6420); Node P2(39,30,7.9380); Node P7(39,32,2.2840); Node P1(40,31,2.5090); Node P9(37,20,0.5740); Node P10(25,28,1.2110); Node P11(39,26,2.1270); Node P12(32,31,8.3400); Node P13(30,34,18.6420); Node P14(33,35,7.9380); Node P15(42,32,2.2840); Node P16(31,23,2.5090); neighborhood voisin; voisin.add_node(P1); voisin.add_node(P2); voisin.add_node(P3); voisin.add_node(P4); voisin.add_node(P5); voisin.add_node(P6); voisin.add_node(P7); voisin.add_node(P8); voisin.add_node(P9); voisin.add_node(P10); voisin.add_node(P11); voisin.add_node(P12); voisin.add_node(P13); voisin.add_node(P14); voisin.add_node(P15); voisin.add_node(P16); typedef matrix_lib_traits<TNT_lib<double> >::Vector TNTvector; covariance covar; //______________________________ // Simple Kriging //______________________________ std::cout << std::endl <<std::endl; std::cout << "____________________________________________" << std::endl << "Simple kriging" << std::endl << std::endl; TNTvector SK_weights; SK_constraints SK; OK_constraints OK; double sk_variance; TNT::stopwatch chrono; chrono.start(); for(int count = 0 ; count < 50000 ; count ++) { int change=1; if(drand48() <0.5) change = -1; (voisin[0].location())[0] += change; kriging_weights<GSTL_TNT_lib>(SK_weights, center, voisin, covar, OK ); } chrono.stop(); std::cout << "time elapsed using Gauss: " << chrono.read() << std::endl; chrono.reset(); chrono.start(); for(int count = 0 ; count < 50000 ; count ++) { int change=1; if(drand48() <0.5) change = -1; voisin[0].property_value() = 0.5*count; kriging_weights(SK_weights, center, voisin, covar, OK ); } chrono.stop(); std::cout << "time elapsed using LU: " << chrono.read() << std::endl; /* //______________________________ // Ordinary Kriging //______________________________ std::cout << std::endl <<std::endl; std::cout << "____________________________________________" << std::endl << "Ordinary kriging" << std::endl << std::endl; TNTvector OK_weights; OK_constraints OK; double ok_variance; status = kriging_weights(OK_weights, ok_variance, center, voisin, covar, OK); std::cout << "Here are the weights:" << std::endl << OK_weights << std::endl; //______________________________ // Kriging with Trend //______________________________ std::cout << std::endl <<std::endl; std::cout << "____________________________________________" << std::endl << "Kriging with Trend" << std::endl << std::endl; TNTvector KT_weights; KT_constraints<functIter> KT(functArray.begin(),functArray.end()); double kt_variance; status = kriging_weights(KT_weights, kt_variance, center, voisin, covar, KT); std::cout << "Here are the weights:" << std::endl << KT_weights << std::endl; */ return 0; }