void MifarePCSCCommands::loadKey(boost::shared_ptr<Location> location, boost::shared_ptr<Key> key, MifareKeyType keytype) { EXCEPTION_ASSERT_WITH_LOG(location, std::invalid_argument, "location cannot be null."); EXCEPTION_ASSERT_WITH_LOG(key, std::invalid_argument, "key cannot be null."); boost::shared_ptr<MifareLocation> mLocation = boost::dynamic_pointer_cast<MifareLocation>(location); boost::shared_ptr<MifareKey> mKey = boost::dynamic_pointer_cast<MifareKey>(key); EXCEPTION_ASSERT_WITH_LOG(mLocation, std::invalid_argument, "location must be a MifareLocation."); EXCEPTION_ASSERT_WITH_LOG(mKey, std::invalid_argument, "key must be a MifareKey."); boost::shared_ptr<KeyStorage> key_storage = key->getKeyStorage(); if (boost::dynamic_pointer_cast<ComputerMemoryKeyStorage>(key_storage)) { loadKey(0, keytype, key->getData(), key->getLength()); } else if (boost::dynamic_pointer_cast<ReaderMemoryKeyStorage>(key_storage)) { // Don't load the key when reader memory, except if specified if (!key->isEmpty()) { boost::shared_ptr<ReaderMemoryKeyStorage> rmKs = boost::dynamic_pointer_cast<ReaderMemoryKeyStorage>(key_storage); loadKey(rmKs->getKeySlot(), keytype, key->getData(), key->getLength(), rmKs->getVolatile()); } } else { THROW_EXCEPTION_WITH_LOG(LibLogicalAccessException, "The key storage type is not supported for this card/reader."); } }
void MifareSTidSTRCommands::loadKey(boost::shared_ptr<Location> location, boost::shared_ptr<Key> key, MifareKeyType keytype) { INFO_("Loading key... location {%s} key type {0x%x(%d)}", location->serialize().c_str(), keytype, keytype); EXCEPTION_ASSERT_WITH_LOG(location, std::invalid_argument, "location cannot be null."); EXCEPTION_ASSERT_WITH_LOG(key, std::invalid_argument, "key cannot be null."); boost::shared_ptr<MifareLocation> mLocation = boost::dynamic_pointer_cast<MifareLocation>(location); boost::shared_ptr<MifareKey> mKey = boost::dynamic_pointer_cast<MifareKey>(key); EXCEPTION_ASSERT_WITH_LOG(mLocation, std::invalid_argument, "location must be a MifareLocation."); EXCEPTION_ASSERT_WITH_LOG(mKey, std::invalid_argument, "key must be a MifareKey."); boost::shared_ptr<KeyStorage> key_storage = key->getKeyStorage(); if (boost::dynamic_pointer_cast<ComputerMemoryKeyStorage>(key_storage)) { INFO_SIMPLE_("Using computer memory key storage !"); loadKey(static_cast<unsigned char>(mLocation->sector), keytype, key->getData(), key->getLength(), true); } else if (boost::dynamic_pointer_cast<ReaderMemoryKeyStorage>(key_storage)) { INFO_SIMPLE_("Using reader memory key storage !"); // Don't load the key when reader memory, except if specified if (!key->isEmpty()) { THROW_EXCEPTION_WITH_LOG(LibLogicalAccessException, "It's not possible to change a key at specific index through host/reader connection. Please use SKB configuration card instead."); } } else { THROW_EXCEPTION_WITH_LOG(LibLogicalAccessException, "The key storage type is not supported for this card/reader."); } }
static int crypto( const char *key, bool decrypt, const bytes_t &bytes, bytes_t &crypt ) { CRYPTO_malloc_debug_init(); CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); RAND_seed(rnd_seed, sizeof(rnd_seed)); /* or OAEP may fail */ RSA *rsa = NULL; int rval = loadKey(key, decrypt, &rsa); if ( rval == 0 ) rval = crypto(rsa, decrypt, bytes, crypt); RSA_free(rsa); ERR_print_errors_fp(stdout); CRYPTO_cleanup_all_ex_data(); EVP_cleanup(); ERR_remove_state(0); CRYPTO_mem_leaks_fp(stderr); return ( rval ); }
unique_ptr<KeyHandle> BackEndFile::doGetKeyHandle(const Name& keyName) const { if (!doHasKey(keyName)) return nullptr; return make_unique<KeyHandleMem>(loadKey(keyName)); }
bool BackEndFile::doHasKey(const Name& keyName) const { if (!boost::filesystem::exists(m_impl->toFileName(keyName))) return false; try { loadKey(keyName); return true; } catch (const std::runtime_error&) { return false; } }
ConstBufferPtr BackEndFile::doExportKey(const Name& keyName, const char* pw, size_t pwLen) { shared_ptr<PrivateKey> key; try { key = loadKey(keyName); } catch (const PrivateKey::Error&) { BOOST_THROW_EXCEPTION(Error("Cannot export private key")); } OBufferStream os; key->savePkcs8(os, pw, pwLen); return os.buf(); }
/** * Set up a connection with the ccnd router * * During this setup we establish a basic connection with the router service * over an IP connection. * This is also a good time to setup the ccn name for the content we will * produce; that is the prefix name and the timestamp [Tnow], since the * segment portion of the name is added just as the packet is being sent. * * Lastly we also load our security keys and create our signing parameters. * * \param me context sink element for which the socket is for */ static void setup_ccn (Gstccnxsink * me) { struct ccn *ccn; GST_DEBUG ("CCNxSink: setup name..."); if ((me->name = ccn_charbuf_create ()) == NULL) { GST_ELEMENT_ERROR (me, RESOURCE, READ, (NULL), ("name alloc failed")); return; } if (ccn_name_from_uri (me->name, me->uri) < 0) { GST_ELEMENT_ERROR (me, RESOURCE, READ, (NULL), ("name from uri failed")); return; } GST_DEBUG ("CCNxSink: creating ccn object"); if ((ccn = ccn_create ()) == NULL) { GST_ELEMENT_ERROR (me, RESOURCE, READ, (NULL), ("ccn_create failed")); return; } me->ccn = ccn; GST_DEBUG ("CCNxSink: connecting"); if (-1 == ccn_connect (me->ccn, ccndHost ())) { GST_ELEMENT_ERROR (me, RESOURCE, READ, (NULL), ("ccn_connect failed to %s", ccndHost ())); return; } GST_DEBUG ("CCNxSink: setting name version"); if (0 > ccn_create_version (ccn, me->name, CCN_V_REPLACE | CCN_V_NOW | CCN_V_HIGH, 0, 0)) { GST_ELEMENT_ERROR (me, RESOURCE, READ, (NULL), ("ccn_create_version() failed")); return; } GST_DEBUG ("CCNxSink: setting up keystore"); /* me->keystore = fetchStore(); if( me->keystore ) me->keylocator = makeLocator( ccn_keystore_public_key(me->keystore) ); */ loadKey (me->ccn, &me->sp); GST_DEBUG ("CCNxSink: done; have keys!"); }
Status LayerSound::loadSoundAtFrame( QString strFilePath, int frameNumber ) { if ( !QFile::exists( strFilePath ) ) { return Status::FILE_NOT_FOUND; } QFileInfo info( strFilePath ); if ( !info.isFile() ) { strFilePath = ""; } SoundClip* clip = new SoundClip; clip->init( strFilePath ); clip->setPos( frameNumber ); loadKey( clip ); return Status::OK; }
bool MifarePCSCCommands::loadKey(unsigned char keyno, MifareKeyType keytype, const void* key, size_t keylen, bool vol) { bool r = false; unsigned char result[256]; size_t resultlen = 256; getPCSCReaderCardAdapter()->sendAPDUCommand(0xFF, 0x82, (vol ? 0x00 : 0x20), static_cast<char>(keyno), static_cast<unsigned char>(keylen), reinterpret_cast<const unsigned char*>(key), keylen, result, &resultlen); if (!vol && (result[resultlen - 2] == 0x63) && (result[resultlen - 1] == 0x86)) { if (keyno == 0) { r = loadKey(keyno, keytype, key, keylen, true); } } else { r = true; } return r; }
int main(int argc, char * argv[]) { char * migrationkeyfile = NULL; char * filename = NULL; char * migrationKeyPassword = NULL; unsigned char migrationkeyUsageAuth[TPM_DIGEST_SIZE]; unsigned char * passptr = NULL; uint32_t ret = 0; int i = 0; keydata migrationkey; int verbose = FALSE; uint32_t migrationkeyhandle = 0; unsigned char * buffer = NULL; uint32_t bufferSize = 0; i = 1; TPM_setlog(0); while (i < argc) { if (!strcmp("-if",argv[i])) { i++; if (i < argc) { filename = argv[i]; } else { printf("Missing parameter for -if.\n"); usage(); exit(-1); } } else if (!strcmp("-pwdm",argv[i])) { i++; if (i < argc) { migrationKeyPassword = argv[i]; } else { printf("Missing parameter for -pwdm.\n"); usage(); exit(-1); } } else if (!strcmp("-hm",argv[i])) { i++; if (i < argc) { sscanf(argv[i],"%x",&migrationkeyhandle); } else { printf("Missing parameter for -hm.\n"); usage(); exit(-1); } } else if (!strcmp("-ik",argv[i])) { i++; if (i < argc) { migrationkeyfile = argv[i]; } else { printf("Missing parameter for -ik.\n"); usage(); exit(-1); } } else if (!strcmp("-v",argv[i])) { verbose = TRUE; 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 == migrationkeyfile || NULL == filename || -1 == (int)migrationkeyhandle) { printf("Missing or wrong parameter.\n"); usage(); exit(-1); } if (NULL != migrationKeyPassword) { TSS_sha1(migrationKeyPassword, strlen(migrationKeyPassword), migrationkeyUsageAuth); passptr = migrationkeyUsageAuth; } /* * load the key to be migrated from a file. */ ret = 0; buffer = readFile(filename, &bufferSize); if (NULL != buffer) { unsigned int offset = 0; unsigned char * encblob = NULL; uint32_t encsize = 0; unsigned char * rndblob = NULL; uint32_t rndsize = 0; uint32_t keysize = 0; unsigned char * keyblob = NULL; keydata tobemigkey; STACK_TPM_BUFFER(tb) rndsize = LOAD32(buffer,offset); offset += 4; if (offset > bufferSize) { printf("Bad input file. Exiting.\n"); return -1; } rndblob = &buffer[offset]; offset += rndsize; if (offset > bufferSize) { printf("Bad input file. Exiting.\n"); return -1; } encsize = LOAD32(buffer,offset); offset += 4; if (offset > bufferSize) { printf("Bad input file. Exiting.\n"); return -1; } encblob = &buffer[offset]; offset += encsize; if (offset > bufferSize) { printf("Bad input file. Exiting.\n"); return -1; } keysize = LOAD32(buffer,offset); offset += 4; if (offset > bufferSize) { printf("Bad input file. Exiting.\n"); return -1; } keyblob = &buffer[offset]; offset += keysize; if (offset != bufferSize) { printf("Bad input file. Exiting"); return -1; } SET_TPM_BUFFER(&tb, keyblob, keysize); TSS_KeyExtract(&tb,0,&tobemigkey); /* * load the migration key from the destination * TPM from a file. Need the public key part of * that key. */ ret = loadKey(migrationkeyfile, &migrationkey); if (0 == ret) { STACK_TPM_BUFFER(keyblob) uint32_t keyblen = 0; unsigned char * reencData = malloc(encsize); uint32_t reencDataSize = encsize; if (NULL == encblob || NULL == reencData) { printf("Could not get memory for encryted private key blob.\n"); exit (-1); } ret = TPM_WriteKeyPub(&keyblob, &migrationkey); if (ret & ERR_MASK) { printf("Could not serialize the keydata!\n"); free(reencData); exit(-1); } keyblen = ret; ret = TPM_MigrateKey(migrationkeyhandle, passptr, keyblob.buffer, keyblen, encblob, encsize, reencData, &reencDataSize); if (0 == ret) { STACK_TPM_BUFFER(keybuf) // serialize the key to be migrated ret = TPM_WriteKey(&keybuf,&tobemigkey); if (ret > 0) { unsigned int keybuflen = ret; FILE * f = fopen(filename,"wb"); if (NULL != f) { struct tpm_buffer *filebuf = TSS_AllocTPMBuffer(10240); if (NULL != filebuf) { int l; l = TSS_buildbuff("@ @ @",filebuf, rndsize, rndblob, reencDataSize, reencData, keybuflen, keybuf.buffer); fwrite(filebuf->buffer, l, 1, f); fclose(f); printf("Wrote migration blob and associated data to file.\n"); ret = 0; TSS_FreeTPMBuffer(filebuf); } else { printf("Error. Could not allocate memory.\n"); ret = -1; } } } } else { printf("MigrateKey returned '%s' (0x%x).\n", TPM_GetErrMsg(ret), ret); } free(reencData); } else { printf("Error. Could not load the migration key."); } } else { printf("Error. Could not load the blob from file '%s'.\n", filename); } return ret; }
//parseMessage(tConn->recv.data, tConn->recv.mark, &tConn->resp, ipstr, pHWADDR, tConn->keys); int parseMessage(struct connection *pConn, unsigned char *pIpBin, unsigned int pIpBinLen, char *pHWID) { int tReturn = 0; // 0 = good, 1 = Needs More Data, -1 = close client socket. if(pConn->resp.data == NULL) { initBuffer(&(pConn->resp), MAX_SIZE); } char *tContent = getFromHeader(pConn->recv.data, "Content-Length", NULL); if(tContent != NULL) { int tContentSize = atoi(tContent); if(pConn->recv.marker == 0 || strlen(pConn->recv.data+pConn->recv.marker) != tContentSize) { if(isLogEnabledFor(HEADER_LOG_LEVEL)) { slog(HEADER_LOG_LEVEL, "Content-Length: %s value -> %d\n", tContent, tContentSize); if(pConn->recv.marker != 0) { slog(HEADER_LOG_LEVEL, "ContentPtr has %d, but needs %d\n", strlen(pConn->recv.data+pConn->recv.marker), tContentSize); } } // check if value in tContent > 2nd read from client. return 1; // means more content-length needed } } else { slog(LOG_DEBUG_VV, "No content, header only\n"); } // "Creates" a new Response Header for our response message addToShairBuffer(&(pConn->resp), "RTSP/1.0 200 OK\r\n"); if(isLogEnabledFor(LOG_INFO)) { int tLen = strchr(pConn->recv.data, ' ') - pConn->recv.data; if(tLen < 0 || tLen > 20) { tLen = 20; } slog(LOG_INFO, "********** RECV %.*s **********\n", tLen, pConn->recv.data); } if(pConn->password != NULL) { } if(buildAppleResponse(pConn, pIpBin, pIpBinLen, pHWID)) // need to free sig { slog(LOG_DEBUG_V, "Added AppleResponse to Apple-Challenge request\n"); } // Find option, then based on option, do different actions. if(strncmp(pConn->recv.data, "OPTIONS", 7) == 0) { propogateCSeq(pConn); addToShairBuffer(&(pConn->resp), "Public: ANNOUNCE, SETUP, RECORD, PAUSE, FLUSH, TEARDOWN, OPTIONS, GET_PARAMETER, SET_PARAMETER\r\n"); } else if(!strncmp(pConn->recv.data, "ANNOUNCE", 8)) { char *tContent = pConn->recv.data + pConn->recv.marker; int tSize = 0; char *tHeaderVal = getFromContent(tContent, "a=aesiv", &tSize); // Not allocated memory, just pointing if(tSize > 0) { int tKeySize = 0; char tEncodedAesIV[tSize + 2]; getTrimmed(tHeaderVal, tSize, TRUE, TRUE, tEncodedAesIV); slog(LOG_DEBUG_VV, "AESIV: [%.*s] Size: %d Strlen: %d\n", tSize, tEncodedAesIV, tSize, strlen(tEncodedAesIV)); char *tDecodedIV = decode_base64((unsigned char*) tEncodedAesIV, tSize, &tSize); // grab the key, copy it out of the receive buffer tHeaderVal = getFromContent(tContent, "a=rsaaeskey", &tKeySize); char tEncodedAesKey[tKeySize + 2]; // +1 for nl, +1 for \0 getTrimmed(tHeaderVal, tKeySize, TRUE, TRUE, tEncodedAesKey); slog(LOG_DEBUG_VV, "AES KEY: [%s] Size: %d Strlen: %d\n", tEncodedAesKey, tKeySize, strlen(tEncodedAesKey)); // remove base64 coding from key char *tDecodedAesKey = decode_base64((unsigned char*) tEncodedAesKey, tKeySize, &tKeySize); // Need to free DecodedAesKey // Grab the formats int tFmtpSize = 0; char *tFmtp = getFromContent(tContent, "a=fmtp", &tFmtpSize); // Don't need to free tFmtp = getTrimmedMalloc(tFmtp, tFmtpSize, TRUE, FALSE); // will need to free slog(LOG_DEBUG_VV, "Format: %s\n", tFmtp); RSA *rsa = loadKey(); // Decrypt the binary aes key char *tDecryptedKey = malloc(RSA_size(rsa) * sizeof(char)); // Need to Free Decrypted key //char tDecryptedKey[RSA_size(rsa)]; if(RSA_private_decrypt(tKeySize, (unsigned char *)tDecodedAesKey, (unsigned char*) tDecryptedKey, rsa, RSA_PKCS1_OAEP_PADDING) >= 0) { slog(LOG_DEBUG, "Decrypted AES key from RSA Successfully\n"); } else { slog(LOG_INFO, "Error Decrypting AES key from RSA\n"); } free(tDecodedAesKey); RSA_free(rsa); setKeys(pConn->keys, tDecodedIV, tDecryptedKey, tFmtp); propogateCSeq(pConn); } } else if(!strncmp(pConn->recv.data, "SETUP", 5)) { // Setup pipes // struct comms *tComms = pConn->hairtunes; // if (! (pipe(tComms->in) == 0 && pipe(tComms->out) == 0)) // { // slog(LOG_INFO, "Error setting up hairtunes communications...some things probably wont work very well.\n"); // } // Setup fork char tPort[8] = "6000"; // get this from dup()'d stdout of child pid printf("******** SETUP!!!!!\n"); #ifndef BOXEE int tPid = fork(); if(tPid == 0) { #endif int tDataport=0; char tCPortStr[8] = "59010"; char tTPortStr[8] = "59012"; int tSize = 0; char *tFound =getFromSetup(pConn->recv.data, "control_port", &tSize); getTrimmed(tFound, tSize, 1, 0, tCPortStr); tFound = getFromSetup(pConn->recv.data, "timing_port", &tSize); getTrimmed(tFound, tSize, 1, 0, tTPortStr); slog(LOG_DEBUG_VV, "converting %s and %s from str->int\n", tCPortStr, tTPortStr); int tControlport = atoi(tCPortStr); int tTimingport = atoi(tTPortStr); slog(LOG_DEBUG_V, "Got %d for CPort and %d for TPort\n", tControlport, tTimingport); char *tRtp = NULL; char *tPipe = NULL; char *tAoDriver = NULL; char *tAoDeviceName = NULL; char *tAoDeviceId = NULL; struct keyring *tKeys = pConn->keys; #ifndef BOXEE // ************************************************* // ** Setting up Pipes, AKA no more debug/output ** // ************************************************* dup2(tComms->in[0],0); // Input to child closePipe(&(tComms->in[0])); closePipe(&(tComms->in[1])); dup2(tComms->out[1], 1); // Output from child closePipe(&(tComms->out[1])); closePipe(&(tComms->out[0])); pConn->keys = NULL; pConn->hairtunes = NULL; // Free up any recv buffers, etc.. if(pConn->clientSocket != -1) { close(pConn->clientSocket); pConn->clientSocket = -1; } cleanupBuffers(pConn); #endif hairtunes_init(tKeys->aeskey, tKeys->aesiv, tKeys->fmt, tControlport, tTimingport, tDataport, tRtp, tPipe, tAoDriver, tAoDeviceName, tAoDeviceId); #ifndef BOXEE // Quit when finished. slog(LOG_DEBUG, "Returned from hairtunes init....returning -1, should close out this whole side of the fork\n"); return -1; } else if(tPid >0) { // Ensure Connection has access to the pipe. closePipe(&(tComms->in[0])); closePipe(&(tComms->out[1])); char tFromHairtunes[80]; int tRead = read(tComms->out[0], tFromHairtunes, 80); if(tRead <= 0) { slog(LOG_INFO, "Error reading port from hairtunes function, assuming default port: %d\n", tPort); } else { int tSize = 0; char *tPortStr = getFromHeader(tFromHairtunes, "port", &tSize); if(tPortStr != NULL) { getTrimmed(tPortStr, tSize, TRUE, FALSE, tPort); } else { slog(LOG_INFO, "Read %d bytes, Error translating %s into a port\n", tRead, tFromHairtunes); } } int tSize; #endif // READ Ports from here?close(pConn->hairtunes_pipes[0]); propogateCSeq(pConn); tSize = 0; char *tTransport = getFromHeader(pConn->recv.data, "Transport", &tSize); addToShairBuffer(&(pConn->resp), "Transport: "); addNToShairBuffer(&(pConn->resp), tTransport, tSize); // Append server port: addToShairBuffer(&(pConn->resp), ";server_port="); addToShairBuffer(&(pConn->resp), tPort); addToShairBuffer(&(pConn->resp), "\r\nSession: DEADBEEF\r\n"); #ifndef BOXEE } else { slog(LOG_INFO, "Error forking process....dere' be errors round here.\n"); return -1; } #endif } else if(!strncmp(pConn->recv.data, "TEARDOWN", 8)) { // Be smart? Do more finish up stuff... addToShairBuffer(&(pConn->resp), "Connection: close\r\n"); propogateCSeq(pConn); #ifndef BOXEE close(pConn->hairtunes->in[1]); slog(LOG_DEBUG, "Tearing down connection, closing pipes\n"); #else hairtunes_cleanup(); #endif //close(pConn->hairtunes->out[0]); tReturn = -1; // Close client socket, but sends an ACK/OK packet first } else if(!strncmp(pConn->recv.data, "FLUSH", 5)) { // TBD FLUSH #ifndef BOXEE write(pConn->hairtunes->in[1], "flush\n", 6); #else hairtunes_flush(); #endif propogateCSeq(pConn); } else if(!strncmp(pConn->recv.data, "SET_PARAMETER", 13)) { propogateCSeq(pConn); int tSize = 0; char *tVol = getFromHeader(pConn->recv.data, "volume", &tSize); slog(LOG_DEBUG_VV, "About to write [vol: %.*s] data to hairtunes\n", tSize, tVol); // TBD VOLUME #ifndef BOXEE write(pConn->hairtunes->in[1], "vol: ", 5); write(pConn->hairtunes->in[1], tVol, tSize); write(pConn->hairtunes->in[1], "\n", 1); #else hairtunes_setvolume(atof(tVol)); #endif slog(LOG_DEBUG_VV, "Finished writing data write data to hairtunes\n"); } else { slog(LOG_DEBUG, "\n\nUn-Handled recv: %s\n", pConn->recv.data); propogateCSeq(pConn); } addToShairBuffer(&(pConn->resp), "\r\n"); return tReturn; }
// Handles compiling the Apple-Challenge, HWID, and Server IP Address // Into the response the airplay client is expecting. int buildAppleResponse(struct connection *pConn, unsigned char *pIpBin, unsigned int pIpBinLen, char *pHWID) { // Find Apple-Challenge char *tResponse = NULL; int tFoundSize = 0; char* tFound = getFromHeader(pConn->recv.data, "Apple-Challenge", &tFoundSize); if(tFound != NULL) { char tTrim[tFoundSize + 2]; getTrimmed(tFound, tFoundSize, TRUE, TRUE, tTrim); slog(LOG_DEBUG_VV, "HeaderChallenge: [%s] len: %d sizeFound: %d\n", tTrim, strlen(tTrim), tFoundSize); int tChallengeDecodeSize = 16; char *tChallenge = decode_base64((unsigned char *)tTrim, tFoundSize, &tChallengeDecodeSize); slog(LOG_DEBUG_VV, "Challenge Decode size: %d expected 16\n", tChallengeDecodeSize); int tCurSize = 0; unsigned char tChalResp[38]; memcpy(tChalResp, tChallenge, tChallengeDecodeSize); tCurSize += tChallengeDecodeSize; memcpy(tChalResp+tCurSize, pIpBin, pIpBinLen); tCurSize += pIpBinLen; memcpy(tChalResp+tCurSize, pHWID, HWID_SIZE); tCurSize += HWID_SIZE; int tPad = 32 - tCurSize; if (tPad > 0) { memset(tChalResp+tCurSize, 0, tPad); tCurSize += tPad; } char *tTmp = encode_base64((unsigned char *)tChalResp, tCurSize); slog(LOG_DEBUG_VV, "Full sig: %s\n", tTmp); free(tTmp); // RSA Encrypt RSA *rsa = loadKey(); // Free RSA int tSize = RSA_size(rsa); unsigned char tTo[tSize]; RSA_private_encrypt(tCurSize, (unsigned char *)tChalResp, tTo, rsa, RSA_PKCS1_PADDING); // Wrap RSA Encrypted binary in Base64 encoding tResponse = encode_base64(tTo, tSize); int tLen = strlen(tResponse); while(tLen > 1 && tResponse[tLen-1] == '=') { tResponse[tLen-1] = '\0'; } free(tChallenge); RSA_free(rsa); } if(tResponse != NULL) { // Append to current response addToShairBuffer(&(pConn->resp), "Apple-Response: "); addToShairBuffer(&(pConn->resp), tResponse); addToShairBuffer(&(pConn->resp), "\r\n"); free(tResponse); return TRUE; } return FALSE; }
/** * Tell the GST source element it is time to prepare to do work * * This is one of the last functions GStreamer will call when the pipeline * is being put together. It is the last place the element has a chance to * allocate resources and in our case startup our background task for network * connectivity. * After this function returns, we are ready to start processing data from the pipeliine. * * We allocate some of the last minute buffers, and setup a connection to the network; * this is used primarily by the background task, but we need access to it for name initialization. * * Next we initialize our fifo queue, and startup the background task. * * Lastly we return to the GST to begin processing information. * * \param bsrc -> to the context source element * \return true if the initialization went well and we are ready to process data, false otherwise */ static gboolean gst_ccnxsrc_start (GstBaseSrc * bsrc) { Gstccnxsrc *src; CcnxInterestState *istate; struct ccn_charbuf *p_name = NULL; uintmax_t *p_seg = NULL; gint i_ret = 0; gboolean b_ret = FALSE; src = GST_CCNXSRC (bsrc); GST_DEBUG ("starting, getting connections"); /* setup the connection to ccnx */ if ((src->ccn = ccn_create ()) == NULL) { GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), ("ccn_create failed")); return FALSE; } if (-1 == ccn_connect (src->ccn, ccndHost ())) { GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), ("ccn_connect failed to %s", ccndHost ())); return FALSE; } loadKey (src->ccn, &src->sp); /* A closure is what defines what to do when an inbound interest or data arrives */ if ((src->ccn_closure = calloc (1, sizeof (struct ccn_closure))) == NULL) { GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), ("closure alloc failed")); return FALSE; } /* We setup the closure to keep our context [src] and to call the incoming_content() function */ src->ccn_closure->data = src; src->ccn_closure->p = incoming_content; /* Allocate buffers and construct the name from the uri the user gave us */ GST_INFO ("step 1"); if ((p_name = ccn_charbuf_create ()) == NULL) { GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), ("p_name alloc failed")); return FALSE; } if ((src->p_name = ccn_charbuf_create ()) == NULL) { GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), ("src->p_name alloc failed")); return FALSE; } if ((i_ret = ccn_name_from_uri (p_name, src->uri)) < 0) { GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), ("name from uri failed for \"%s\"", src->uri)); return FALSE; } /* Find out what the latest one of these is called, and keep it in our context */ ccn_charbuf_append (src->p_name, p_name->buf, p_name->length); i_ret = ccn_resolve_version (src->ccn, src->p_name, CCN_V_HIGHEST, CCN_VERSION_TIMEOUT); GST_INFO ("step 20 - name so far..."); // hDump(src->p_name->buf, src->p_name->length); src->i_seg = 0; if (i_ret == 0) { /* name is versioned, so get the meta data to obtain the length */ p_seg = get_segment (src->ccn, src->p_name, CCN_HEADER_TIMEOUT); if (p_seg != NULL) { src->i_seg = *p_seg; GST_INFO ("step 25 - next seg: %d", src->i_seg); free (p_seg); } } ccn_charbuf_destroy (&p_name); /* Even though the recent segment published is likely to be >> 0, we still need to ask for segment 0 */ /* because it seems to contain valuable stream information. Attempts to skip segment 0 resulted in no */ /* proper rendering of the stream on my screen during testing */ i_ret = request_segment (src, 0); if (i_ret < 0) { GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), ("interest sending failed")); return FALSE; } src->post_seg = 0; istate = allocInterestState (src); if (!istate) { // This should not happen, but maybe GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), ("trouble allocating interest state structure")); return FALSE; } istate->seg = 0; istate->state = OInterest_waiting; /* Now start up the background work which will fetch all the rest of the R/T segments */ eventTask = gst_task_create (ccn_event_thread, src); if (NULL == eventTask) { GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), ("creating event thread failed")); return FALSE; } src->fifo_cond = g_cond_new (); src->fifo_lock = g_mutex_new (); gst_task_set_lock (eventTask, &task_mutex); eventCond = g_cond_new (); eventLock = g_mutex_new (); b_ret = gst_task_start (eventTask); if (FALSE == b_ret) { GST_ELEMENT_ERROR (src, RESOURCE, READ, (NULL), ("starting event thread failed")); return FALSE; } GST_DEBUG ("event thread started"); /* Done! */ return TRUE; }
void SpriteData::selectSpriteDef(QString key) { loadKey(key); mpSelectedSpriteDef = &mSpriteHash[key]; }
void Tree::insert(const Key &k, TID tid) { N *node = nullptr; N *nextNode = root; N *parentNode = nullptr; uint8_t parentKey, nodeKey = 0; uint32_t level = 0; while (true) { parentNode = node; parentKey = nodeKey; node = nextNode; uint32_t nextLevel = level; uint8_t nonMatchingKey; Prefix remainingPrefix; switch (checkPrefixPessimistic(node, k, nextLevel, nonMatchingKey, remainingPrefix, this->loadKey)) { // increases level case CheckPrefixPessimisticResult::NoMatch: { assert(nextLevel < k.getKeyLen()); //prevent duplicate key // 1) Create new node which will be parent of node, Set common prefix, level to this node auto newNode = new N4(node->getPrefix(), nextLevel - level); // 2) add node and (tid, *k) as children newNode->insert(k[nextLevel], N::setLeaf(tid)); newNode->insert(nonMatchingKey, node); // 3) update parentNode to point to the new node N::change(parentNode, parentKey, newNode); // 4) update prefix of node node->setPrefix(remainingPrefix, node->getPrefixLength() - ((nextLevel - level) + 1)); return; } case CheckPrefixPessimisticResult::Match: break; } assert(nextLevel < k.getKeyLen()); //prevent duplicate key level = nextLevel; nodeKey = k[level]; nextNode = N::getChild(nodeKey, node); if (nextNode == nullptr) { N::insertA(node, parentNode, parentKey, nodeKey, N::setLeaf(tid)); return; } if (N::isLeaf(nextNode)) { Key key; loadKey(N::getLeaf(nextNode), key); level++; assert(level < key.getKeyLen()); //prevent inserting when prefix of key exists already uint32_t prefixLength = 0; while (key[level + prefixLength] == k[level + prefixLength]) { prefixLength++; } auto n4 = new N4(&k[level], prefixLength); n4->insert(k[level + prefixLength], N::setLeaf(tid)); n4->insert(key[level + prefixLength], nextNode); N::change(node, k[level - 1], n4); return; } level++; } }
int main(int argc, char **argv) { // unfortunately we can't just IGN on non-SysV systems struct sigaction sa; sa.sa_handler = handle_sigchld; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); if (sigaction(SIGCHLD, &sa, NULL) < 0) { perror("sigaction"); return 1; } // EZP_XXX: Using LAN MAC char buf[SHORT_BUF_LEN]; unsigned int mac[6]={0,0,0,0,0,0}; ezplib_get_attr_val("lan_hwaddr_rule_default", 0, "hwaddr", buf, sizeof(buf), EZPLIB_USE_CLI); sscanf(buf,"%2X:%2X:%2X:%2X:%2X:%2X", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]); unsigned char tHWID[HWID_SIZE] = {mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]}; char tHWID_Hex[HWID_SIZE * 2 + 1]; memset(tHWID_Hex, 0, sizeof(tHWID_Hex)); char tServerName[56] = "ShairPort"; char tPassword[56] = ""; struct addrinfo *tAddrInfo; int tSimLevel = 0; int tUseKnownHWID = FALSE; int tDaemonize = FALSE; int tPort = PORT; char *arg; while ( (arg = *++argv) ) { if(!strcmp(arg, "-a")) { strncpy(tServerName, *++argv, 55); argc--; } else if(!strncmp(arg, "--apname=", 9)) { strncpy(tServerName, arg+9, 55); } else if(!strcmp(arg, "-p")) { strncpy(tPassword, *++argv, 55); argc--; } else if(!strncmp(arg, "--password="******"-o")) { tPort = atoi(*++argv); argc--; } else if(!strncmp(arg, "--server_port=", 14)) { tPort = atoi(arg+14); } else if(!strcmp(arg, "-b")) { bufferStartFill = atoi(*++argv); argc--; } else if(!strncmp(arg, "--buffer=", 9)) { bufferStartFill = atoi(arg + 9); } else if(!strcmp(arg, "-k")) { tUseKnownHWID = TRUE; } else if(!strcmp(arg, "-q") || !strncmp(arg, "--quiet", 7)) { kCurrentLogLevel = 0; } else if(!strcmp(arg, "-d")) { tDaemonize = TRUE; kCurrentLogLevel = 0; } else if(!strcmp(arg, "-v")) { kCurrentLogLevel = LOG_DEBUG; } else if(!strcmp(arg, "-v2")) { kCurrentLogLevel = LOG_DEBUG_V; } else if(!strcmp(arg, "-vv") || !strcmp(arg, "-v3")) { kCurrentLogLevel = LOG_DEBUG_VV; } else if(!strcmp(arg, "-h") || !strcmp(arg, "--help")) { slog(LOG_INFO, "ShairPort version 0.05 C port - Airport Express emulator\n"); slog(LOG_INFO, "Usage:\nshairport [OPTION...]\n\nOptions:\n"); slog(LOG_INFO, " -a, --apname=AirPort Sets Airport name\n"); slog(LOG_INFO, " -p, --password=secret Sets Password (not working)\n"); slog(LOG_INFO, " -o, --server_port=5002 Sets Port for Avahi/dns-sd/howl\n"); slog(LOG_INFO, " -b, --buffer=282 Sets Number of frames to buffer before beginning playback\n"); slog(LOG_INFO, " -d Daemon mode\n"); slog(LOG_INFO, " -q, --quiet Supresses all output.\n"); slog(LOG_INFO, " -v,-v2,-v3,-vv Various debugging levels\n"); slog(LOG_INFO, "\n"); return 0; } } /* if ( bufferStartFill < 30 || bufferStartFill > BUFFER_FRAMES ) { fprintf(stderr, "buffer value must be > 30 and < %d\n", BUFFER_FRAMES); return(0); } */ if(tDaemonize) { int tPid = fork(); if(tPid < 0) { exit(1); // Error on fork } else if(tPid > 0) { exit(0); } else { setsid(); int tIdx = 0; for(tIdx = getdtablesize(); tIdx >= 0; --tIdx) { close(tIdx); } tIdx = open(DEVNULL, O_RDWR); dup(tIdx); dup(tIdx); } } srandom ( time(NULL) ); int tIdx = 0; for(tIdx=0;tIdx<HWID_SIZE;tIdx++) { if(tIdx > 0) { if(!tUseKnownHWID) { int tVal = ((random() % 80) + 33); tHWID[tIdx] = tVal; } } sprintf(tHWID_Hex+(tIdx*2), "%02X",tHWID[tIdx]); } slog(LOG_INFO, "LogLevel: %d\n", kCurrentLogLevel); slog(LOG_INFO, "AirName: %s\n", tServerName); slog(LOG_INFO, "HWID: %.*s\n", HWID_SIZE, tHWID+1); slog(LOG_INFO, "HWID_Hex(%d): %s\n", strlen(tHWID_Hex), tHWID_Hex); loadKey(); if(tSimLevel >= 1) { #ifdef SIM_INCL sim(tSimLevel, tTestValue, tHWID); #endif return(1); } else { slog(LOG_DEBUG_V, "Starting connection server: specified server port: %d\n", tPort); int tServerSock = setupListenServer(&tAddrInfo, tPort); if(tServerSock < 0) { freeaddrinfo(tAddrInfo); slog(LOG_INFO, "Error setting up server socket on port %d, try specifying a different port\n", tPort); exit(1); } int tClientSock = 0; while(1) { slog(LOG_DEBUG_V, "Waiting for clients to connect\n"); tClientSock = acceptClient(tServerSock, tAddrInfo); if(tClientSock > 0) { int tPid = fork(); if(tPid == 0) { freeaddrinfo(tAddrInfo); tAddrInfo = NULL; slog(LOG_DEBUG, "...Accepted Client Connection..\n"); close(tServerSock); handleClient(tClientSock, tPassword, (char*)tHWID); //close(tClientSock); return 0; } else { slog(LOG_DEBUG_VV, "Child now busy handling new client\n"); wait(NULL); close(tClientSock); } } else { // failed to init server socket....try waiting a moment... sleep(2); } } } slog(LOG_DEBUG_VV, "Finished, and waiting to clean everything up\n"); sleep(1); if(tAddrInfo != NULL) { freeaddrinfo(tAddrInfo); } return 0; }
int main(int argc, const char * argv[]) { int returnvalue; settimestamp(TRUE); set_sigchld_handler(); returnvalue = 0; switch(getParam(argc, argv)) { case ENCRYPT: { //encode char buffer[BUF_SIZE]; char * result; unsigned int i; setKey(loadKey("test.key")); while(!feof(stdin)) { if(fgets(buffer, BUF_SIZE, stdin) == 0) break; buffer[strlen(buffer)] = '\0'; printf("%s\n", encrypt_msg(buffer)); } break; } case DECRYPT: { char buffer[BUF_SIZE]; setKey(loadKey("test.key")); while(!feof(stdin)) { if(fgets(buffer, BUF_SIZE, stdin) == 0) break; printf("%s\n", decrypt_msg(buffer)); } break; } case GENERATE_KEY: { //generate key unsigned int len; if(argc == 3) sscanf(argv[2], "%i", &len); else len=64; printf("%s\n", generateKey(len)); break; } case BASE64ENCODE: { char buffer[BUF_SIZE]; while(!feof(stdin)) { if(fgets(buffer, BUF_SIZE, stdin) == 0) break; printf("%s\n", base64encode(buffer, strlen(buffer))); } break; } case BASE64DECODE: { char buffer[BUF_SIZE]; while(!feof(stdin)) { if(fgets(buffer, BUF_SIZE, stdin) == 0) break; printf("%s\n", base64decode(buffer).data); } break; } case SERVER: { daemonize(); if(argc > 2) { setlogdir(argv[2]); } else { setlogdir("~/logs"); } initlogfile(SERVER_LOG); serverlog("server started"); //sleep(60); //debug... returnvalue = start_server(); serverlog("server stopped"); terminate_log(); break; } case NOPARAM: default: { //print usage: printf("usage: %s <option>\noptions: [ -g <length> | -d | -e ]\n", argv[0]); break; } } return 0; }
int main(int argc, char *argv[]) { /* { fix start } */ ltc_mp = ltm_desc; /* { fix end } */ int sockfd = 0; struct sockaddr_in serv_addr; if(argc != 2) { printf("\n Usage: %s <ip of server> \n",argv[0]); return 1; } if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Error : Could not create socket \n"); return 1; } memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(5002); if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0) { printf("\n inet_pton error occured\n"); return 1; } if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\n Error : Connect Failed \n"); return 1; } initEncrypt(); ecc_key encryptKey; loadKey(&encryptKey, "bpublic.key"); ecc_key decryptKey; loadKey(&decryptKey, "aprivate.key"); /* { userString start } */ printf("Enter message to send\n"); unsigned char message[256]; fgets((char*)message,256,stdin); /* { userString end } */ /* { sendNonceA start } */ int nonceA = randomNumber(); printf("nonceA = %i\n",nonceA); printf("Encrypting nonceA with bpub\n"); unsigned char nonceA_enc[2048]; unsigned long outLength = 2048; ecc_encrypt((unsigned char*)&nonceA, sizeof(int), nonceA_enc, &outLength,&encryptKey); printf("Sending nonceA\n"); write(sockfd, nonceA_enc, outLength); /* { sendNonceA end } */ /* { resiveSessionKey start } */ unsigned char recvBuff[1024]; unsigned long msgLength; msgLength = recv(sockfd, recvBuff, sizeof(recvBuff),0); struct SessionKey sKey; unsigned long inLength = sizeof(struct SessionKey); ecc_decrypt(recvBuff,msgLength,(unsigned char*)&sKey,&inLength,&decryptKey); printf("Received sKey, nonceA = %i, key = %i\n", sKey.nonceA, sKey.key); /* { resiveSessionKey end } */ /* { resendKey start } */ my_aes_setup(sKey.key); sKey.nonceA ++; printf("Sending nonceA = %i encrypted with AES\n", sKey.nonceA); outLength = 2048; aes_encrypt((unsigned char*)&sKey.nonceA,sizeof(int),nonceA_enc, &outLength); write(sockfd, nonceA_enc, outLength); /* { resendKey end } */ /* { sendMessage start } */ printf("Sending message encrypted with AES\n"); printf("%s", message); outLength = 2048; unsigned char message_enc[2048]; aes_encrypt(message, strlen((char*)message), message_enc, &outLength); write(sockfd, message_enc, outLength); /* { sendMessage end } */ return -1; }