int testStressThreadsComplex( void ) { HANDLE hThreads[ NO_COMPLEX_THREADS ]; int i; cryptAddRandom( NULL, CRYPT_RANDOM_SLOWPOLL ); for( i = 0; i < 1000; i++ ) { unsigned dwThreadId; int j; hThreads[ 0 ] = ( HANDLE ) \ _beginthreadex( NULL, 0, encTest, &i, 0, &dwThreadId ); hThreads[ 1 ] = ( HANDLE ) \ _beginthreadex( NULL, 0, signTest, &i, 0, &dwThreadId ); hThreads[ 2 ] = ( HANDLE ) \ _beginthreadex( NULL, 0, encTest, &i, 0, &dwThreadId ); hThreads[ 3 ] = ( HANDLE ) \ _beginthreadex( NULL, 0, signTest, &i, 0, &dwThreadId ); WaitForMultipleObjects( NO_COMPLEX_THREADS, hThreads, TRUE, INFINITE ); for( j = 0; j < NO_COMPLEX_THREADS; j++ ) CloseHandle( hThreads[ j ] ); } return 0; }
static void testContinuousThreads( void ) { unsigned threadID1, threadID2; #ifdef UNIX_THREADS pthread_t thread1, thread2; #else HANDLE hThread1, hThread2; #endif /* Different threading models */ cryptAddRandom( "xyzzy", 5 ); #ifdef UNIX_THREADS pthread_create( &thread1, NULL, envelopeDataThread, ( void * ) 1 ); pthread_create( &thread2, NULL, envelopeDataThread, ( void * ) 2 ); #else hThread1 = ( HANDLE ) _beginthreadex( NULL, 0, envelopeDataThread, ( void * ) 1, 0, &threadID1 ); hThread2 = ( HANDLE ) _beginthreadex( NULL, 0, envelopeDataThread, ( void * ) 2, 0, &threadID2 ); #endif /* Different threading models */ delayThread( 30 ); printf( "Hit a key..." ); fflush( stdout ); getchar(); cryptEnd(); exit( EXIT_SUCCESS ); }
int scInit() { #if defined(HAVE_LIBCRYPT) if( cryptInit() ) return( SC_EXIT_LIB_ERROR); if( cryptAddRandom( NULL, CRYPT_RANDOM_SLOWPOLL ) ) return( SC_EXIT_LIB_ERROR); #endif /* HAVE_LIBCRYPT */ return( SC_EXIT_OK ); }
main(int argc, char **argv){ int ret; /* Return code */ int i; /* Loop iterator */ int bytesCopied; /* Bytes output by cryptlib enc/dec ops */ int reqAttrib; /* Crypt required attributed */ CRYPT_ENVELOPE dataEnv; /* Envelope for enc/dec */ CRYPT_KEYSET keyset; /* GPG keyset */ CRYPT_CONTEXT symContext; /* Key context */ char *keyPtr; /* Pointer to key */ char label[100]; /* Private key label */ int labelLength; /* Length of label */ char passbuf[1024]; /* Buffer for GPG key passphrase */ struct termios ts, ots; /* Strutures for saving/modifying term attribs */ char *clrDataPtr; /* Pointer to clear text */ int clrDataSize; /* Size of clear text */ int clrDataFd; /* Pointer to clear text file */ char *encDataPtr; /* Pointer to encrypted data */ int encDataSize; /* Size of encrypted data */ int encDataFd; /* Pointer to encrypted text file */ struct stat encDataFileInfo; /* fstat return for encrypted data file */ struct passwd *userInfo; /* Password info for input user */ char *keyFile; /* GPG key ring file name */ uid_t ownerID = getuid(); struct passwd *owner_pws = getpwuid(ownerID); char* owner_pwname = owner_pws->pw_name;//get the user login name; char* owner_pwdir = owner_pws->pw_dir; char *fileKeyName; *fileKeyName = malloc(strlen(owner_pwname)+strlen(argv[2]+10)); strcpy(fileKeyName,argv[2]); strcat(fileKeyName,".enc."); strcat(fileKeyName,owner_pwname); strcat(fileKeyName,".key"); printf("%s\n",fileKeyName); char *outputFileKeyName = malloc(strlen(argv[1])+strlen(argv[2])+20); strcpy(outputFileKeyName,argv[2]); strcat(outputFileKeyName,".enc."); strcat(outputFileKeyName,argv[1]); strcat(outputFileKeyName,".key"); printf("%s\n",outputFileKeyName); /*============================================== Check Check Check Check Check Check ============================================== */ if (argc!=3) {printf("Wrong number of arguments\n");exit(1);} char *fileName = malloc(strlen(argv[2])+5); strcpy(fileName,argv[2]); strcat(fileName,".enc"); fileChecker(fileName); /*============================================= Open DATAFILE and get data ============================================= */ encDataFd=open(fileKeyName,O_RDONLY); if (encDataFd<=0){perror("open encData1");exit(encDataFd);} ret=fstat(encDataFd,&encDataFileInfo); if (ret!=0){perror("fstat encDataFd");exit(ret);} encDataSize=encDataFileInfo.st_size; encDataPtr=malloc(encDataFileInfo.st_size); if (encDataPtr==NULL){perror("malloc encData");exit(__LINE__);} ret=read(encDataFd,encDataPtr,encDataSize); if (ret!=encDataSize){perror("read encData");exit(ret);} close(encDataFd); /*============================================== Cryptlib initialization ============================================== */ //cryptInit(); //ret=cryptAddRandom( NULL , CRYPT_RANDOM_SLOWPOLL); //checkCryptNormal(ret,"cryptAddRandom",__LINE__); /*================================================= Decrypt the key ================================================= */ keyFile=malloc( strlen(owner_pwdir ) + strlen("/.gnupg/secring.gpg") + 1); if (keyFile==NULL){perror("malloc");exit(__LINE__);} strcpy(keyFile,owner_pwdir); strcat(keyFile,"/.gnupg/secring.gpg"); printf("Getting secret key from <%s>\n",keyFile); //Decrypt key cryptInit(); ret=cryptAddRandom( NULL , CRYPT_RANDOM_SLOWPOLL); checkCryptNormal(ret,"cryptAddRandom",__LINE__); ret=cryptKeysetOpen(&keyset, CRYPT_UNUSED, CRYPT_KEYSET_FILE, keyFile, CRYPT_KEYOPT_READONLY); free(keyFile); checkCryptNormal(ret,"cryptKeysetOpen",__LINE__); ret=cryptCreateEnvelope(&dataEnv, CRYPT_UNUSED, CRYPT_FORMAT_AUTO); checkCryptNormal(ret,"cryptCreateEnvelope",__LINE__); ret=cryptSetAttribute(dataEnv, CRYPT_ENVINFO_KEYSET_DECRYPT, keyset); checkCryptNormal(ret,"cryptSetAttribute",__LINE__); ret=cryptPushData(dataEnv,encDataPtr,encDataSize,&bytesCopied); /* Expect non-zero return -- indicates need private key */ ret=cryptGetAttribute(dataEnv, CRYPT_ATTRIBUTE_CURRENT, &reqAttrib); if (reqAttrib != CRYPT_ENVINFO_PRIVATEKEY) {printf("Decrypt error\n");exit(ret);} ret=cryptGetAttributeString(dataEnv, CRYPT_ENVINFO_PRIVATEKEY_LABEL, label, &labelLength); label[labelLength]='\0'; checkCryptNormal(ret,"cryptGetAttributeString",__LINE__); /*=============================================== Get the passphrase =============================================== */ tcgetattr(STDIN_FILENO, &ts); ots = ts; ts.c_lflag &= ~ECHO; ts.c_lflag |= ECHONL; tcsetattr(STDIN_FILENO, TCSAFLUSH, &ts); tcgetattr(STDIN_FILENO, &ts); if (ts.c_lflag & ECHO) { fprintf(stderr, "Failed to turn off echo\n"); tcsetattr(STDIN_FILENO, TCSANOW, &ots); exit(1); } printf("Enter password for <%s>: ",label); fflush(stdout); fgets(passbuf, 1024, stdin); tcsetattr(STDIN_FILENO, TCSANOW, &ots); ret=cryptSetAttributeString(dataEnv, CRYPT_ENVINFO_PASSWORD, passbuf, strlen(passbuf)-1); if (ret != CRYPT_OK) { if (ret=CRYPT_ERROR_WRONGKEY) { printf("Wrong Key\n"); exit(ret); }else{ printf("cryptSetAttributeString line %d returned <%d>\n",__LINE__,ret); exit(ret); } } ret=cryptFlushData(dataEnv); checkCryptNormal(ret,"cryptFlushData",__LINE__); clrDataSize=KEYSIZE; clrDataPtr=malloc(clrDataSize); if (clrDataPtr==NULL){perror("malloc");exit(__LINE__);} bzero(clrDataPtr,clrDataSize); ret=cryptPopData(dataEnv,clrDataPtr,clrDataSize,&bytesCopied); checkCryptNormal(ret,"cryptPopData",__LINE__); ret=cryptDestroyEnvelope(dataEnv); checkCryptNormal(ret,"cryptDestroyEnvelope",__LINE__); cryptKeysetClose(keyset); checkCryptNormal(ret,"cryptKeysetClose",__LINE__); printf("Bytes decrypted <%d>\n",bytesCopied); for (i=0;i<bytesCopied;i++){printf("%c",clrDataPtr[i]);} ret=cryptEnd(); checkCryptNormal(ret,"cryptEnd",__LINE__); /*==================================================== Part2 Encrypt the key with user's private key ==================================================== */ /*============================================== Cryptlib initialization ============================================== */ cryptInit(); ret=cryptAddRandom( NULL , CRYPT_RANDOM_SLOWPOLL); checkCryptNormal(ret,"cryptAddRandom",__LINE__); /*==================================================== Get key file name ==================================================== */ keyFile=malloc( strlen(owner_pwdir ) + strlen("/.gnupg/pubring.gpg") + 1); if (keyFile==NULL){perror("malloc");exit(__LINE__);} strcpy(keyFile,owner_pwdir); strcat(keyFile,"/.gnupg/pubring.gpg"); printf("Getting secret key from <%s>\n",keyFile); /*==================================================== Encrypt key with GPG public key Email address is for recipient =================================================== */ ret=cryptKeysetOpen(&keyset, CRYPT_UNUSED, CRYPT_KEYSET_FILE, keyFile, CRYPT_KEYOPT_READONLY); free(keyFile); checkCryptNormal(ret,"cryptKeysetOpen",__LINE__); ret=cryptCreateEnvelope(&dataEnv, CRYPT_UNUSED, CRYPT_FORMAT_PGP); checkCryptNormal(ret,"cryptCreateEnvelope",__LINE__); ret=cryptSetAttribute(dataEnv, CRYPT_ENVINFO_KEYSET_ENCRYPT, keyset); checkCryptNormal(ret,"cryptSetAttribute",__LINE__); ret=cryptSetAttributeString(dataEnv, CRYPT_ENVINFO_RECIPIENT, argv[1],strlen(argv[1])); checkCryptNormal(ret,"cryptSetAttributeString",__LINE__); ret=cryptSetAttribute(dataEnv, CRYPT_ENVINFO_DATASIZE, KEYSIZE); ret=cryptPushData(dataEnv,clrDataPtr,KEYSIZE,&bytesCopied); checkCryptNormal(ret,"cryptPushData",__LINE__); ret=cryptFlushData(dataEnv); checkCryptNormal(ret,"cryptFlushData",__LINE__); encDataSize=strlen(clrDataPtr)+1+1028; encDataPtr=malloc(encDataSize); if (encDataPtr==NULL){perror("malloc");exit(__LINE__);} ret=cryptPopData(dataEnv,encDataPtr,encDataSize,&bytesCopied); printf("cryptPopData returned <%d> bytes of encrypted data\n",bytesCopied); encDataSize=bytesCopied; ret=cryptDestroyEnvelope(dataEnv); checkCryptNormal(ret,"cryptDestroyEnvelope",__LINE__); cryptKeysetClose(keyset); checkCryptNormal(ret,"cryptKeysetClose",__LINE__); /*============================================== write it to output file. ============================================== */ printf("%s\n",outputFileKeyName); encDataFd=open(outputFileKeyName,O_RDWR|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR); if (encDataFd<=0){perror("open encDataFd");exit(encDataFd);} ret=write(encDataFd,encDataPtr,bytesCopied); if (ret!=bytesCopied){perror("write encData");exit(ret);} close(encDataFd); int chmodStat = chmod (outputFileKeyName, S_IWRITE| S_IREAD| S_IRGRP | S_IWGRP); if(chmodStat<0){ perror("failed to chmod"); exit(-1); } free(encDataPtr); }
int main(int argc, char const *argv[]) { struct passwd *pws; /* info for input user */ char *pwname; /* username */ char *pwdir; /* home directory */ char *encFile; char *encKey; int encKeyFd; //file state char *encKeyPtr; /* Pointer to encrypted data */ int encKeySize; /* Buffer bytes availble for decrypt */ struct stat fileStat; /* Struce for checking file attributes */ char *keyFile; /* GPG key ring file name */ char *gpgPrivateKeyPtr; int ret; /* Return code */ int i; /* Loop iterator */ int bytesCopied; /* Bytes output by cryptlib enc/dec ops */ int reqAttrib; /* Crypt required attributed */ CRYPT_ENVELOPE dataEnv; /* Envelope for enc/dec */ CRYPT_KEYSET keyset; /* GPG keyset */ CRYPT_CONTEXT symContext; /* Key context */ char label[100]; /* Private key label */ int labelLength; /* Length of label */ char passbuf[1024]; /* Buffer for GPG key passphrase */ struct termios ts, ots; /* Strutures for saving/modifying term attribs */ char *encDataPtr; /* Pointer to encrypted data */ int encDataSize; /* Size of encrypted data */ struct passwd *userInfo; /* Password info for input user */ int encFileFd; /* Destination (Encrypted) File Descriptor */ int encFileSize; /* Bytes of encrypted data */ char * encFilePtr; /* Pointer to enc text */ char *clrFilePtr; /* Pointer to clear text */ int clrFileSize; /* Bytes of clear text */ char *clrKeyPtr; int clrKeySize; struct stat encFileInfo; uid = getuid(); pws = getpwuid(uid); pwname = pws->pw_name;//get the user login name; pwdir = pws->pw_dir;//get the user dir path //Check arguments number if (argc!=2) { printf("slient exit\n"); exit (1); } //Get encrepted file encFile = malloc(strlen(argv[1]) + 4); strcpy(encFile, argv[1]); strcat(encFile, ".enc"); //Get gpg encrepted key name encKey = malloc(strlen(encFile) + strlen(pwname) +5 ); strcpy(encKey,encFile); strcat(encKey, "."); strcat(encKey, pwname); strcat(encKey, ".key"); //Open gpg encrepted key encKeyFd=open(encKey, O_RDONLY); if (encKeyFd<=0){perror("(2) open encKeyFd2");exit(encKeyFd);} ret=fstat(encKeyFd,&fileStat); if (ret!=0){perror("fstat encKeyFd");exit(ret);} encKeySize=fileStat.st_size; encKeyPtr=malloc(encKeySize); if (encKeyPtr==NULL){perror("malloc encData");exit(__LINE__);} ret=read(encKeyFd,encKeyPtr,encKeySize); if (ret!=encKeySize){perror("read encData");exit(ret);} close(encKeyFd); //Get the private key name gpgPrivateKeyPtr=malloc(strlen(pwdir) + strlen("/.gnupg/secring.gpg") + 1); getPrivateKeyName(gpgPrivateKeyPtr,uid); //Decrypt key cryptInit(); ret=cryptAddRandom( NULL , CRYPT_RANDOM_SLOWPOLL); checkCryptNormal(ret,"cryptAddRandom",__LINE__); ret=cryptKeysetOpen(&keyset, CRYPT_UNUSED, CRYPT_KEYSET_FILE, gpgPrivateKeyPtr, CRYPT_KEYOPT_READONLY); free(gpgPrivateKeyPtr); checkCryptNormal(ret,"cryptKeysetOpen",__LINE__); ret=cryptCreateEnvelope(&dataEnv, CRYPT_UNUSED, CRYPT_FORMAT_AUTO); checkCryptNormal(ret,"cryptCreateEnvelope",__LINE__); ret=cryptSetAttribute(dataEnv, CRYPT_ENVINFO_KEYSET_DECRYPT, keyset); checkCryptNormal(ret,"cryptSetAttribute",__LINE__); ret=cryptPushData(dataEnv,encKeyPtr,encKeySize,&bytesCopied); /* Expect non-zero return -- indicates need private key */ ret=cryptGetAttribute(dataEnv, CRYPT_ATTRIBUTE_CURRENT, &reqAttrib); if (reqAttrib != CRYPT_ENVINFO_PRIVATEKEY) {printf("Decrypt error\n");exit(ret);} ret=cryptGetAttributeString(dataEnv, CRYPT_ENVINFO_PRIVATEKEY_LABEL, label, &labelLength); label[labelLength]='\0'; checkCryptNormal(ret,"cryptGetAttributeString",__LINE__); /*=============================================== Get the passphrase =============================================== */ tcgetattr(STDIN_FILENO, &ts); ots = ts; ts.c_lflag &= ~ECHO; ts.c_lflag |= ECHONL; tcsetattr(STDIN_FILENO, TCSAFLUSH, &ts); tcgetattr(STDIN_FILENO, &ts); if (ts.c_lflag & ECHO) { fprintf(stderr, "Failed to turn off echo\n"); tcsetattr(STDIN_FILENO, TCSANOW, &ots); exit(1); } printf("Enter password for <%s>: ",label); fflush(stdout); fgets(passbuf, 1024, stdin); tcsetattr(STDIN_FILENO, TCSANOW, &ots); ret=cryptSetAttributeString(dataEnv, CRYPT_ENVINFO_PASSWORD, passbuf, strlen(passbuf)-1); if (ret != CRYPT_OK) { if (ret=CRYPT_ERROR_WRONGKEY) { printf("Wrong Key\n"); exit(ret); }else{ printf("cryptSetAttributeString line %d returned <%d>\n",__LINE__,ret); exit(ret); } } ret=cryptFlushData(dataEnv); checkCryptNormal(ret,"cryptFlushData",__LINE__); clrKeySize=KEYSIZE; clrKeyPtr=malloc(clrKeySize); if (clrKeyPtr==NULL){perror("malloc");exit(__LINE__);} bzero(clrKeyPtr,clrKeySize); ret=cryptPopData(dataEnv,clrKeyPtr,clrKeySize,&bytesCopied); checkCryptNormal(ret,"cryptPopData",__LINE__); ret=cryptDestroyEnvelope(dataEnv); checkCryptNormal(ret,"cryptDestroyEnvelope",__LINE__); cryptKeysetClose(keyset); checkCryptNormal(ret,"cryptKeysetClose",__LINE__); printf("Bytes decrypted <%d>\n",bytesCopied); // for (i=0;i<bytesCopied;i++){printf("%c",clrKeyPtr[i]);} ret=cryptEnd(); checkCryptNormal(ret,"cryptEnd",__LINE__); //read enc file encFileFd=open(encFile, O_RDONLY); if (encFileFd<=0){perror("(2) open encFileFd1");exit(encFileFd);} ret=fstat(encFileFd,&encFileInfo); if (ret!=0){perror("fstat encFileFd");exit(ret);} encFileSize=encFileInfo.st_size; encFilePtr=malloc(encFileSize); if (encFilePtr==NULL){perror("malloc encData");exit(__LINE__);} ret=read(encFileFd,encFilePtr,encFileSize); if (ret!=encFileSize){perror("read encData");exit(ret);} close(encFileFd); //Decrypt and get the content of decrepted file cryptInit(); ret=cryptAddRandom( NULL , CRYPT_RANDOM_SLOWPOLL); checkCryptNormal(ret,"cryptAddRandom",__LINE__); cryptCreateEnvelope(&dataEnv, CRYPT_UNUSED, CRYPT_FORMAT_AUTO); checkCryptNormal(ret,"cryptCreateEnvelope",__LINE__); cryptPushData(dataEnv,encFilePtr,encFileSize,&bytesCopied); checkCryptNormal(ret,"cryptPushData",__LINE__); cryptCreateContext(&symContext,CRYPT_UNUSED,SYMMETRIC_ALG); checkCryptNormal(ret,"cryptCreateContext",__LINE__); cryptSetAttributeString(symContext, CRYPT_CTXINFO_KEY,clrKeyPtr,clrKeySize); checkCryptNormal(ret,"cryptSetAttributeString",__LINE__); cryptSetAttribute(dataEnv,CRYPT_ENVINFO_SESSIONKEY,symContext); checkCryptNormal(ret,"cryptSetAttribute",__LINE__); ret=cryptDestroyContext(symContext); checkCryptNormal(ret,"cryptDestroyContext",__LINE__); cryptFlushData(dataEnv); clrFileSize=KEYSIZE+1028; clrFilePtr=malloc(encDataSize); ret=cryptPopData(dataEnv,clrFilePtr,clrFileSize,&bytesCopied); checkCryptNormal(ret,"cryptPopData",__LINE__); ret=cryptDestroyEnvelope(dataEnv); checkCryptNormal(ret,"cryptDestroyEnvelope",__LINE__); printf("<%d> bytes of decrypted data\n",bytesCopied); for (i=0;i<bytesCopied;i++){printf("%c",clrFilePtr[i]);} printf("\n"); fflush(stdout); ret=cryptEnd(); checkCryptNormal(ret,"cryptEnd",__LINE__); return 0; }
int main( int argc, char **argv ) { const char *zargPtr = NULL; BOOLEAN sessionTestError = FALSE, loopbackTestError = FALSE; int flags, status; void testSystemSpecific1( void ); void testSystemSpecific2( void ); /* If we're running in test mode, run the test code and exit */ #ifdef CONFIG_SUITEB_TESTS return( suiteBMain( argc, argv ) ); #endif /* CONFIG_SUITEB_TESTS */ /* Print a general banner to let the user know what's going on */ printf( "testlib - cryptlib %d-bit self-test framework.\n", ( int ) sizeof( long ) * 8 ); /* Cast for gcc */ puts( "Copyright Peter Gutmann 1995 - 2012." ); puts( "" ); /* Skip the program name and process any command-line arguments */ argv++; argc--; status = processArgs( argc, argv, &flags, &zargPtr ); if( !status ) exit( EXIT_FAILURE ); #ifdef USE_TCHECK THREAD_DEBUG_SUSPEND(); #endif /* USE_TCHECK */ /* Make sure that various system-specific features are set right */ testSystemSpecific1(); /* VisualAge C++ doesn't set the TZ correctly. The check for this isn't as simple as it would seem since most IBM compilers define the same preprocessor values even though it's not documented anywhere, so we have to enable the tzset() call for (effectively) all IBM compilers and then disable it for ones other than VisualAge C++ */ #if ( defined( __IBMC__ ) || defined( __IBMCPP__ ) ) && !defined( __VMCMS__ ) tzset(); #endif /* VisualAge C++ */ /* Initialise cryptlib */ printf( "Initialising cryptlib..." ); status = cryptInit(); if( cryptStatusError( status ) ) { printf( "\ncryptInit() failed with error code %d, line %d.\n", status, __LINE__ ); exit( EXIT_FAILURE ); } puts( "done." ); #ifndef TEST_RANDOM /* In order to avoid having to do a randomness poll for every test run, we bypass the randomness-handling by adding some junk. This is only enabled when cryptlib is built in debug mode so it won't work with any production systems */ #if defined( __MVS__ ) || defined( __VMCMS__ ) #pragma convlit( resume ) cryptAddRandom( "xyzzy", 5 ); #pragma convlit( suspend ) #else cryptAddRandom( "xyzzy", 5 ); #endif /* Special-case EBCDIC handling */ #endif /* TEST_RANDOM */ /* Perform a general sanity check to make sure that the self-test is being run the right way */ if( !checkFileAccess() ) { cryptEnd(); exit( EXIT_FAILURE ); } /* Make sure that further system-specific features that require cryptlib to be initialised to check are set right */ #ifndef _WIN32_WCE testSystemSpecific2(); #endif /* WinCE */ #ifdef USE_TCHECK THREAD_DEBUG_RESUME(); #endif /* USE_TCHECK */ /* For general testing purposes we can insert test code at this point to test special cases that aren't covered in the general tests below */ testKludge( zargPtr ); #ifdef SMOKE_TEST /* Perform a general smoke test of the kernel */ smokeTest(); #endif /* SMOKE_TEST */ /* Test each block of cryptlib functionality */ if( ( flags & DO_SELFTEST ) && !testSelfTest() ) goto errorExit; if( ( flags & DO_LOWLEVEL ) && !testLowLevel() ) goto errorExit; if( ( flags & DO_RANDOM ) && !testRandom() ) goto errorExit; if( ( flags & DO_CONFIG ) && !testConfig() ) goto errorExit; if( ( flags & DO_DEVICE ) && !testDevice() ) goto errorExit; if( ( flags & DO_MIDLEVEL ) && !testMidLevel() ) goto errorExit; if( ( flags & DO_CERT ) && !testCert() ) goto errorExit; if( ( flags & DO_KEYSETFILE ) && !testKeysetFile() ) goto errorExit; if( ( flags & DO_KEYSETDBX ) && !testKeysetDatabase() ) goto errorExit; if( ( flags & DO_CERTPROCESS ) && !testCertMgmt() ) goto errorExit; if( ( flags & DO_HIGHLEVEL ) && !testHighLevel() ) goto errorExit; if( ( flags & DO_ENVELOPE ) && !testEnveloping() ) goto errorExit; if( ( flags & DO_SESSION ) && !testSessions() ) { sessionTestError = TRUE; goto errorExit; } if( ( flags & DO_SESSIONLOOPBACK ) && !testSessionsLoopback() ) { loopbackTestError = TRUE; goto errorExit; } if( ( flags & DO_USER ) && !testUsers() ) goto errorExit; /* Shut down cryptlib */ status = cryptEnd(); if( cryptStatusError( status ) ) { if( status == CRYPT_ERROR_INCOMPLETE ) { puts( "cryptEnd() failed with error code CRYPT_ERROR_INCOMPLETE, " "a code path in the\nself-test code resulted in an error " "return without a full cleanup of objects.\nIf you were " "running the multithreaded loopback tests this may be " "because one\nor more threads lost sync with other threads " "and exited without cleaning up\nits objects. This " "happens occasionally due to network timing issues or\n" "thread scheduling differences." ); } else { printf( "cryptEnd() failed with error code %d, line %d.\n", status, __LINE__ ); } goto errorExit1; } puts( "All tests concluded successfully." ); return( EXIT_SUCCESS ); /* All errors end up here */ errorExit: cryptEnd(); errorExit1: puts( "\nThe test was aborted due to an error being detected. If you " "want to report\nthis problem, please provide as much information " "as possible to allow it to\nbe diagnosed, for example the call " "stack, the location inside cryptlib where\nthe problem occurred, " "and the values of any variables that might be\nrelevant." ); if( sessionTestError ) { puts( "\nThe error occurred during one of the network session tests, " "if the error\nmessage indicates a network-level problem such " "as ECONNREFUSED, ECONNRESET,\nor a timeout or read error then " "this is either due to a transient\nnetworking problem or a " "firewall interfering with network connections. This\nisn't a " "cryptlib error, and doesn't need to be reported." ); } if( loopbackTestError ) { puts( "\nThe error occurred during one of the multi-threaded network " "loopback\ntests, this was probably due to the different threads " "losing synchronisation.\nFor the secure sessions this usually " "results in read/write, timeout, or\nconnection-closed errors " "when one thread is pre-empted for too long. For the\n" "certificate-management sessions it usually results in an error " "related to the\nserver being pre-empted for too long by database " "updates. Since the self-\ntest exists only to exercise " "cryptlib's capabilities, it doesn't bother with\ncomplex thread " "synchronisation during the multi-threaded loopback tests.\nThis " "type of error is non-fatal, and should disappear if the test is " "re-run." ); } cleanExit( EXIT_FAILURE ); return( EXIT_FAILURE ); /* Get rid of compiler warnings */ }
int main( int argc, char **argv ) { const char *zargPtr = NULL; BOOLEAN doSelftest = FALSE, doLowlevel = FALSE, doRandom = FALSE; BOOLEAN doConfig = FALSE, doMidlevel = FALSE, doCert = FALSE; BOOLEAN doKeyset = FALSE, doCertprocess = FALSE, doHighlevel = FALSE; BOOLEAN doEnvelope = FALSE, doSession = FALSE, doSessionLoopback = FALSE; BOOLEAN doAll = FALSE, moreArgs = TRUE; BOOLEAN sessionTestError = FALSE, loopbackTestError = FALSE; int status; void testSystemSpecific1( void ); void testSystemSpecific2( void ); /* Print a general banner to let the user know what's going on */ printf( "testlib - cryptlib %d-bit self-test framework.\n", sizeof( long ) * 8 ); puts( "Copyright Peter Gutmann 1995 - 2010." ); puts( "" ); /* Skip the program name */ argv++; argc--; /* No args means test everything */ if( argc <= 0 ) doAll = TRUE; /* Check for arguments */ while( argc > 0 && *argv[ 0 ] == '-' && moreArgs ) { const char *argPtr = argv[ 0 ] + 1; while( *argPtr ) { switch( toupper( *argPtr ) ) { case '-': moreArgs = FALSE; /* GNU-style end-of-args flag */ break; case 'B': doSelftest = TRUE; break; case 'C': doCert = TRUE; break; case 'E': doEnvelope = TRUE; break; case 'F': doSessionLoopback = TRUE; break; case 'H': usageExit(); break; case 'I': doHighlevel = TRUE; break; case 'K': doKeyset = TRUE; break; case 'L': doLowlevel = TRUE; break; case 'M': doMidlevel = TRUE; break; case 'O': doConfig = TRUE; break; case 'P': doCertprocess = TRUE; break; case 'R': doRandom = TRUE; break; case 'S': doSession = TRUE; break; case 'Z': zargPtr = argPtr + 1; if( *zargPtr == '\0' ) { puts( "Error: Missing argument for -z option." ); exit( EXIT_FAILURE ); } while( argPtr[ 1 ] ) argPtr++; /* Skip rest of arg */ break; default: printf( "Error: Unknown argument '%c'.\n", *argPtr ); return( EXIT_FAILURE ); } argPtr++; } argv++; argc--; } #ifdef USE_TCHECK THREAD_DEBUG_SUSPEND(); #endif /* USE_TCHECK */ /* Make sure that various system-specific features are set right */ testSystemSpecific1(); /* VisualAge C++ doesn't set the TZ correctly. The check for this isn't as simple as it would seem since most IBM compilers define the same preprocessor values even though it's not documented anywhere, so we have to enable the tzset() call for (effectively) all IBM compilers and then disable it for ones other than VisualAge C++ */ #if ( defined( __IBMC__ ) || defined( __IBMCPP__ ) ) && !defined( __VMCMS__ ) tzset(); #endif /* VisualAge C++ */ /* Initialise cryptlib */ printf( "Initialising cryptlib..." ); status = cryptInit(); if( cryptStatusError( status ) ) { printf( "\ncryptInit() failed with error code %d, line %d.\n", status, __LINE__ ); exit( EXIT_FAILURE ); } puts( "done." ); #ifndef TEST_RANDOM /* In order to avoid having to do a randomness poll for every test run, we bypass the randomness-handling by adding some junk. This is only enabled when cryptlib is built in debug mode so it won't work with any production systems */ #if defined( __MVS__ ) || defined( __VMCMS__ ) #pragma convlit( resume ) cryptAddRandom( "xyzzy", 5 ); #pragma convlit( suspend ) #else cryptAddRandom( "xyzzy", 5 ); #endif /* Special-case EBCDIC handling */ #endif /* TEST_RANDOM */ /* Perform a general sanity check to make sure that the self-test is being run the right way */ if( !checkFileAccess() ) goto errorExit; /* Make sure that further system-specific features that require cryptlib to be initialised to check are set right */ #ifndef _WIN32_WCE testSystemSpecific2(); #endif /* WinCE */ #ifdef USE_TCHECK THREAD_DEBUG_RESUME(); #endif /* USE_TCHECK */ /* For general testing purposes we can insert test code at this point to test special cases that aren't covered in the general tests below */ testKludge( zargPtr ); #ifdef SMOKE_TEST /* Perform a general smoke test of the kernel */ smokeTest(); #endif /* SMOKE_TEST */ /* Test each block of cryptlib functionality */ if( ( doSelftest || doAll ) && !testSelfTest() ) goto errorExit; if( ( doLowlevel || doAll ) && !testLowLevel() ) goto errorExit; if( ( doRandom || doAll ) && !testRandom() ) goto errorExit; if( ( doConfig || doAll ) && !testConfig() ) goto errorExit; if( ( doSelftest || doAll ) && !testDevice() ) goto errorExit; if( ( doMidlevel || doAll ) && !testMidLevel() ) goto errorExit; if( ( doCert || doAll ) && !testCert() ) goto errorExit; if( ( doKeyset || doAll ) && !testKeyset() ) goto errorExit; if( ( doCertprocess || doAll ) && !testCertMgmt() ) goto errorExit; if( ( doHighlevel || doAll ) && !testHighLevel() ) goto errorExit; if( ( doEnvelope || doAll ) && !testEnveloping() ) goto errorExit; if( ( doSession || doAll ) && !testSessions() ) { sessionTestError = TRUE; goto errorExit; } if( ( doSessionLoopback || doAll ) && !testSessionsLoopback() ) { loopbackTestError = TRUE; goto errorExit; } if( ( doAll ) && !testUsers() ) goto errorExit; /* Shut down cryptlib */ status = cryptEnd(); if( cryptStatusError( status ) ) { if( status == CRYPT_ERROR_INCOMPLETE ) { puts( "cryptEnd() failed with error code CRYPT_ERROR_INCOMPLETE, " "a code path in the\nself-test code resulted in an error " "return without a full cleanup of objects.\nIf you were " "running the multithreaded loopback tests this may be " "because one\nor more threads lost sync with other threads " "and exited without cleaning up\nits objects. This " "happens occasionally due to network timing issues or\n" "thread scheduling differences." ); } else { printf( "cryptEnd() failed with error code %d, line %d.\n", status, __LINE__ ); } goto errorExit1; } puts( "All tests concluded successfully." ); return( EXIT_SUCCESS ); /* All errors end up here */ errorExit: cryptEnd(); errorExit1: puts( "\nThe test was aborted due to an error being detected. If you " "want to report\nthis problem, please provide as much information " "as possible to allow it to\nbe diagnosed, for example the call " "stack, the location inside cryptlib where\nthe problem occurred, " "and the values of any variables that might be\nrelevant." ); if( sessionTestError ) { puts( "\nThe error occurred during one of the network session tests, " "if the error\nmessage indicates a network-level problem such " "as ECONNREFUSED, ECONNRESET,\nor a timeout or read error then " "this is either due to a transient\nnetworking problem or a " "firewall interfering with network connections. This\nisn't a " "cryptlib error, and doesn't need to be reported." ); } #ifdef WINDOWS_THREADS if( loopbackTestError ) { puts( "\nThe error occurred during one of the multi-threaded network " "loopback\ntests, this was probably due to the different threads " "losing synchronisation.\nFor the secure sessions this usually " "results in read/write, timeout, or\nconnection-closed errors " "when one thread is pre-empted for too long. For the\n" "certificate-management sessions it usually results in an error " "related to the\nserver being pre-empted for too long by database " "updates. Since the self-\ntest exists only to exercise " "cryptlib's capabilities, it doesn't bother with\ncomplex thread " "synchronisation during the multi-threaded loopback tests.\nThis " "type of error is non-fatal, and should disappear if the test is " "re-run." ); } #endif /* WINDOWS_THREADS */ #if defined( __WINDOWS__ ) && !defined( NDEBUG ) /* The pseudo-CLI VC++ output windows are closed when the program exits so we have to explicitly wait to allow the user to read them */ puts( "\nHit a key..." ); getchar(); #endif /* __WINDOWS__ && !NDEBUG */ return( EXIT_FAILURE ); }
main(int argc, char **argv){ int i; /* Loop iterator */ int ret; /* Return value */ int total; /* Total key bytes */ int bytesCopied; /* Bytes output by cryptlib enc/dec ops */ int urandFd; /* Pointer to /dev/urandom */ char *keyPtr; /* Pointer to key */ CRYPT_ENVELOPE dataEnv; /* Envelope for encrypt/decrypt */ CRYPT_CONTEXT symContext; /* Key context */ char *clrDataPtr; /* Pointer to clear text */ int clrDataSize; /* Bytes of clear text */ int clrDataFd; /* Pointer to clear text file */ struct stat clrDataFileInfo; /* fstat return for clear text file */ int encDataFd; /* Pointer to encrypted text file */ char *encDataPtr; /* Pointer to encrypted data */ int encDataSize; /* Buffer bytes availble for decrypt */ struct stat encDataFileInfo; /* fstat return for encrypted data file */ if (argc!=3) {printf("Wrong number of arguments\n");exit(__LINE__);} /*============================================== Cryptlib initialization ============================================== */ cryptInit(); ret=cryptAddRandom( NULL , CRYPT_RANDOM_SLOWPOLL); checkCryptNormal(ret,"cryptAddRandom",__LINE__); /*============================================= Open DATAFILE and get data ============================================= */ clrDataFd=open(argv[1],O_RDONLY); if (clrDataFd<=0){perror("open clrData");exit(clrDataFd);} ret=fstat(clrDataFd,&clrDataFileInfo); if (ret!=0){perror("fstat clrDataFd");exit(ret);} clrDataSize=clrDataFileInfo.st_size; clrDataPtr=malloc(clrDataFileInfo.st_size); if (clrDataPtr==NULL){perror("malloc clrData");exit(__LINE__);} ret=read(clrDataFd,clrDataPtr,clrDataSize); if (ret!=clrDataSize){perror("read clrData");exit(ret);} close(clrDataFd); /*============================================== (1) Generate the key ============================================== */ keyPtr=malloc(KEYSIZE); if (keyPtr==NULL){perror("malloc keyPtr");exit(__LINE__);} urandFd=open("/dev/urandom",O_RDONLY); if (urandFd<=0){perror("open urandFd");exit(urandFd);} total=0;ret=0; while (total<KEYSIZE){ ret=read(urandFd,&keyPtr[total],KEYSIZE-total);total+=ret; if (ret < 0){perror("read urand");exit(ret);} } close(urandFd); /*============================================== (2) Encrypt data from file with the key and write it to output file. ============================================== */ ret=cryptCreateEnvelope(&dataEnv, CRYPT_UNUSED, CRYPT_FORMAT_CRYPTLIB); checkCryptNormal(ret,"cryptCreateEnvelope",__LINE__); ret=cryptCreateContext(&symContext, CRYPT_UNUSED, SYMMETRIC_ALG); checkCryptNormal(ret,"cryptCreateContext",__LINE__); ret=cryptSetAttributeString(symContext, CRYPT_CTXINFO_KEY,keyPtr,KEYSIZE); checkCryptNormal(ret,"cryptSetAttributeString",__LINE__); ret=cryptSetAttribute(dataEnv, CRYPT_ENVINFO_SESSIONKEY, symContext); checkCryptNormal(ret,"cryptSetAttribute",__LINE__); ret=cryptDestroyContext(symContext); checkCryptNormal(ret,"cryptDestroyContext",__LINE__); ret=cryptSetAttribute(dataEnv, CRYPT_ENVINFO_DATASIZE, clrDataSize); checkCryptNormal(ret,"cryptSetAttribute",__LINE__); ret=cryptPushData(dataEnv,clrDataPtr,clrDataSize,&bytesCopied); checkCryptNormal(ret,"cryptAddRandom",__LINE__); cryptFlushData(dataEnv); encDataSize=clrDataFileInfo.st_size+2048; encDataPtr=malloc(encDataSize); if (encDataPtr==NULL){perror("malloc encData");exit(__LINE__);} ret=cryptPopData(dataEnv,encDataPtr,encDataSize,&bytesCopied); checkCryptNormal(ret,"cryptPopData",__LINE__); printf("<%d> bytes of encrypted data\n",bytesCopied); ret=cryptDestroyEnvelope(dataEnv); checkCryptNormal(ret,"cryptDestroyEnvelope",__LINE__); encDataFd=open(argv[2],O_RDWR|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR); if (encDataFd<=0){perror("open encDataFd");exit(encDataFd);} ret=write(encDataFd,encDataPtr,bytesCopied); if (ret!=bytesCopied){perror("write encData");exit(ret);} close(encDataFd); free(encDataPtr); /*====================================================== Get decrypted data from file and write to stdout ====================================================== */ encDataFd=open(argv[2],O_RDONLY); if (encDataFd<=0){perror("(2) open encDataFd");exit(encDataFd);} ret=fstat(encDataFd,&encDataFileInfo); if (ret!=0){perror("fstat encDataFd");exit(ret);} encDataSize=encDataFileInfo.st_size; encDataPtr=malloc(encDataSize); if (encDataPtr==NULL){perror("malloc encData");exit(__LINE__);} ret=read(encDataFd,encDataPtr,encDataSize); if (ret!=encDataSize){perror("read encData");exit(ret);} close(encDataFd); cryptCreateEnvelope(&dataEnv, CRYPT_UNUSED, CRYPT_FORMAT_AUTO); checkCryptNormal(ret,"cryptCreateEnvelope",__LINE__); cryptPushData(dataEnv,encDataPtr,encDataSize,&bytesCopied); checkCryptNormal(ret,"cryptPushData",__LINE__); cryptCreateContext(&symContext,CRYPT_UNUSED,SYMMETRIC_ALG); checkCryptNormal(ret,"cryptCreateContext",__LINE__); cryptSetAttributeString(symContext, CRYPT_CTXINFO_KEY,keyPtr,KEYSIZE); checkCryptNormal(ret,"cryptSetAttributeString",__LINE__); cryptSetAttribute(dataEnv,CRYPT_ENVINFO_SESSIONKEY,symContext); checkCryptNormal(ret,"cryptSetAttribute",__LINE__); ret=cryptDestroyContext(symContext); checkCryptNormal(ret,"cryptDestroyContext",__LINE__); cryptFlushData(dataEnv); ret=cryptPopData(dataEnv,clrDataPtr,clrDataSize,&bytesCopied); checkCryptNormal(ret,"cryptPopData",__LINE__); ret=cryptDestroyEnvelope(dataEnv); checkCryptNormal(ret,"cryptDestroyEnvelope",__LINE__); printf("<%d> bytes of decrypted data\n",bytesCopied); for (i=0;i<bytesCopied;i++){printf("%c",clrDataPtr[i]);} printf("\n"); fflush(stdout); ret=cryptEnd(); checkCryptNormal(ret,"cryptEnd",__LINE__); }
int suiteBMain( int argc, char **argv ) { const char *stringArg; BOOLEAN isServer, sendHTTPheader; int testNo, intArg, status; void testSystemSpecific1( void ); void testSystemSpecific2( void ); printf( "testlib - cryptlib %d-bit Suite B test framework.\n", ( int ) sizeof( long ) * 8 ); /* Cast for gcc */ puts( "Copyright Peter Gutmann 1995 - 2011." ); puts( "" ); /* Skip the program name and process any command-line arguments */ argv++; argc--; status = processArgs( argc, argv, &testNo, &stringArg, &intArg, &isServer, &sendHTTPheader ); if( !status ) exit( EXIT_FAILURE ); /* Make sure that various system-specific features are set right */ testSystemSpecific1(); /* Initialise cryptlib */ status = cryptInit(); if( cryptStatusError( status ) ) { printf( "\ncryptInit() failed with error code %d, line %d.\n", status, __LINE__ ); exit( EXIT_FAILURE ); } /* In order to avoid having to do a randomness poll for every test run, we bypass the randomness-handling by adding some junk. This is only enabled when cryptlib is built in debug mode so it won't work with any production systems */ cryptAddRandom( "xyzzy", 5 ); /* Perform a general sanity check to make sure that the self-test is being run the right way */ if( !checkFileAccess() ) exit( EXIT_FAILURE ); /* Make sure that further system-specific features that require cryptlib to be initialised to check are set right */ testSystemSpecific2(); /* If the test number is negative, it's a special-case non-test operation */ if( testNo < 0 ) { switch( testNo ) { case -1: status = generateKey( intArg, stringArg ); if( status == TRUE ) printf( "Wrote %d-bit certificate request to " "file '%s'.\n\n", intArg, stringArg ); break; case -2: status = updateKey( intArg, stringArg ); if( status == TRUE ) printf( "Updated %d-bit key with certificate from " "file '%s'.\n\n", intArg, stringArg ); break; } } else { /* Run the selected test */ status = suitebTest( isServer, testNo, stringArg, intArg, sendHTTPheader ); } /* Clean up and exit */ cryptEnd(); return( ( status == TRUE ) ? EXIT_SUCCESS : EXIT_FAILURE ); }