/* static */ void _HttpContextHandleCanAcceptBytes(HttpContextRef context) { DBG(("Sending data to the view\n")); // Get the start of the buffer to send. const UInt8* start = CFDataGetBytePtr(context->_sendBytes); // Get number of bytes ready to be send int size = CFDataGetLength(context->_sendBytes); // Writing resets the timer. CFRunLoopTimerSetNextFireDate(context->_timer, CFAbsoluteTimeGetCurrent() + kTimeOutInSeconds); // If there data in the buffer to send, take care of sending the data. if (size != 0) { // Write all of the bytes redy to be sent CFIndex bytesWritten = CFWriteStreamWrite(context->_outStream, start, size); DBG(("%d bytes sent\n", bytesWritten)); // If successfully sent the data, remove the bytes from the buffer. if (bytesWritten > 0) CFDataDeleteBytes(context->_sendBytes, CFRangeMake(0, bytesWritten)); } }
static uint8_t* AppendEncryptedSignature(SecOTRSessionRef session, const cc_unit* s, bool usePrime, CFMutableDataRef appendTo) { CFMutableDataRef signature = CFDataCreateMutable(kCFAllocatorDefault, 0); CFMutableDataRef mbData = CFDataCreateMutable(kCFAllocatorDefault, 0); CFMutableDataRef mb = CFDataCreateMutable(kCFAllocatorDefault, 0); SecFDHKAppendPublicSerialization(session->_myKey, mbData); SecPDHKAppendSerialization(session->_theirKey, mbData); CFIndex publicKeyOffset = CFDataGetLength(mbData); SecOTRPublicIdentityRef myPublic = SecOTRPublicIdentityCopyFromPrivate(kCFAllocatorDefault, session->_me, NULL); AppendPublicKey(mbData, myPublic); CFReleaseNull(myPublic); AppendLong(mbData, session->_keyID); DeriveAndAppendSHA256HMAC(mb, kExponentiationUnits, s, usePrime ? kM1Prime : kM1, (size_t)CFDataGetLength(mbData), CFDataGetBytePtr(mbData)); CFDataDeleteBytes(mbData, CFRangeMake(0, publicKeyOffset)); CFMutableDataRef xb = mbData; mbData = NULL; SecOTRFIAppendSignature(session->_me, mb, signature, NULL); CFReleaseNull(mb); AppendCFDataAsDATA(xb, signature); CFReleaseNull(signature); CFIndex dataLength = CFDataGetLength(xb); CFIndex signatureStartIndex = CFDataGetLength(appendTo); /* 64 bits cast: We are appending the signature we just generated, which is never bigger than 2^32 bytes. */ assert(((unsigned long)dataLength)<=UINT32_MAX); /* debug check, correct as long as CFIndex is a signed long */ AppendLong(appendTo, (uint32_t)dataLength); uint8_t *destination = CFDataIncreaseLengthAndGetMutableBytes(appendTo, dataLength); uint8_t c[kOTRAuthKeyBytes]; DeriveOTR128BitPairFromS(kCs, kExponentiationUnits, s, sizeof(c), usePrime ? NULL : c, sizeof(c), usePrime ? c : NULL); AES_CTR_IV0_Transform(sizeof(c), c, (size_t)dataLength, CFDataGetBytePtr(xb), destination); bzero(c, sizeof(c)); CFReleaseNull(xb); return CFDataGetMutableBytePtr(appendTo) + signatureStartIndex; }
// First 160 bits of the HMAC static inline void AppendSHA256HMAC_160(CFMutableDataRef appendTo, size_t keySize, const uint8_t* key, size_t howMuch, const uint8_t* from) { AppendSHA256HMAC(appendTo, keySize, key, howMuch, from); const CFIndex bytesToRemove = CCSHA256_OUTPUT_SIZE - kSHA256HMAC160Bytes; const CFRange rangeToDelete = CFRangeMake(CFDataGetLength(appendTo) - bytesToRemove, bytesToRemove); CFDataDeleteBytes(appendTo, rangeToDelete); }
static CFDataRef createIVFromPassword(CFStringRef password) { CFDataRef hashedPassword, retval; CFMutableDataRef iv; if((hashedPassword = digestString(password)) == NULL) return NULL; iv = CFDataCreateMutableCopy(kCFAllocatorDefault, CFDataGetLength(hashedPassword)+1, hashedPassword); CFDataDeleteBytes(iv, CFRangeMake(IVBYTECOUNT, CFDataGetLength(iv)-IVBYTECOUNT)); retval = CFDataCreateCopy(kCFAllocatorDefault, iv); CFRelease(hashedPassword); CFRelease(iv); return retval; }
void write_buffer(CFStringRef inData) { #ifdef DEBUG syslog(LOG_ERR,"Writing buffer to file."); #endif if (CFWriteStreamGetStatus(logStream)!=kCFStreamStatusOpen) { CFWriteStreamSetProperty(logStream,kCFStreamPropertyAppendToFile,kCFBooleanTrue); CFWriteStreamOpen(logStream); } if (!CFBooleanGetValue(doEncrypt)) { CFWriteStreamWrite(logStream,(const UInt8*)CFStringGetCStringPtr(inData,CFStringGetFastestEncoding(inData)),CFStringGetLength(inData)); return; } int buff_pos = 0; while (1) { int avail_space = 8-CFDataGetLength(encrypt_buffer); //space rem in buffer int rem_to_copy = CFStringGetLength(inData)-buff_pos; //stuff in data that needs to be copied int to_copy = rem_to_copy<avail_space?rem_to_copy:avail_space; //amount left to encryp, or avail space if (avail_space) { UInt8 tmp_buff[8]; CFStringGetBytes(inData,CFRangeMake(buff_pos,to_copy),kCFStringEncodingNonLossyASCII,0,false,tmp_buff,8,NULL); CFDataAppendBytes(encrypt_buffer,tmp_buff,to_copy); avail_space -= to_copy; if (avail_space>0) // small buffer? still space left? break; buff_pos += to_copy; //move along the buffer } UInt8 enc_buff[8]; BF_ecb_encrypt(CFDataGetBytePtr(encrypt_buffer),enc_buff,&encrypt_bf_key,BF_ENCRYPT); CFWriteStreamWrite(logStream,enc_buff,8); CFDataDeleteBytes(encrypt_buffer,CFRangeMake(0,8)); if (buff_pos==CFStringGetLength(inData)) //just in case buffer happens to fit perfectly break; } return; }
static void ConnectionGotData( CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void * data, void * info ) // This is a a CFSocket callback indicating that data has arrived on the // socket. It's only called if the user has registered the associated // connection for listening. The parameter are as per the CFSocket // documentation. As this is a callback of type kCFSocketDataCallBack, // data contains newly arrived data that CFSocket has already read for us. { #pragma unused(address) CFDataRef newData; ConnectionRef conn; assert(s != NULL); assert(type == kCFSocketDataCallBack); // Cast data to a CFDataRef, newData. newData = (CFDataRef) data; assert(newData != NULL); assert( CFGetTypeID(newData) == CFDataGetTypeID() ); // Cast info to a ConnectionRef. conn = (ConnectionRef) info; assert(conn->fMagic == kConnectionStateMagic); if ( CFDataGetLength(newData) == 0 ) { // End of data stream; the server is dead. fprintf(stderr, "ConnectionGotData: Server died unexpectedly.\n"); // Tell the client. (void) conn->fCallback(conn, NULL, conn->fCallbackRefCon); // Shut 'er down Clancy, she's pumping mud! ConnectionShutdown(conn); } else { // We have new data from the server. Appending to our buffer. CFDataAppendBytes(conn->fBufferedPackets, CFDataGetBytePtr(newData), CFDataGetLength(newData)); // Now see if there are any complete packets in the buffer; and, // if so, deliver them to the client. do { PacketHeader * thisPacket; Boolean success; if ( CFDataGetLength(conn->fBufferedPackets) < sizeof(PacketHeader) ) { // Not enough data for the packet header; we're done. break; } thisPacket = (PacketHeader *) CFDataGetBytePtr(conn->fBufferedPackets); if ( thisPacket->fMagic != kPacketMagic ) { fprintf(stderr, "ConnectionGotData: Server sent us a packet with bad magic (%.4s).\n", (char *) &thisPacket->fMagic); ConnectionShutdown(conn); break; } if (thisPacket->fSize > kPacketMaximumSize) { fprintf(stderr, "ConnectionGotData: Server sent us a packet that's just too big (%" PRIu32 ").\n", thisPacket->fSize); ConnectionShutdown(conn); break; } if ( CFDataGetLength(conn->fBufferedPackets) < thisPacket->fSize ) { // Not enough data for the packet body; we're done. break; } // Tell the client about the packet. success = conn->fCallback(conn, thisPacket, conn->fCallbackRefCon); if ( ! success ) { ConnectionShutdown(conn); break; } // Delete this packet from the front of our packet buffer. I horror at // the inefficiency of this, but it is sample code after all. CFDataDeleteBytes(conn->fBufferedPackets, CFRangeMake(0, thisPacket->fSize)); } while (true); } }
void DaemonTimerCallback( CFRunLoopTimerRef timer, void *info ) { /*********Wait if not logging**********/ Boolean validKey; CFPreferencesAppSynchronize(PREF_DOMAIN); CFBooleanRef isLogging = (CFPreferencesGetAppBooleanValue(CFSTR("Logging"),PREF_DOMAIN,&validKey))?kCFBooleanTrue:kCFBooleanFalse; if (!validKey) { isLogging = kCFBooleanTrue; CFPreferencesSetAppValue(CFSTR("Logging"),isLogging,PREF_DOMAIN); } if (!CFBooleanGetValue(isLogging)) return; /********* Check the buffer **********/ int buffsize=0; int keys=0; getBufferSizeAndKeys(&buffsize,&keys); #ifdef DEBUG syslog(LOG_ERR,"Buffsize %d, Keys %d.",buffsize,keys); #endif if (!keys) // no keyboards logged return; if (buffsize < MAX_BUFF_SIZE/10) return; /********* Get the buffer **********/ CFStringRef the_buffer = getBuffer(); /********* Check defaults/file **********/ CFStringRef curPathName = (CFStringRef)CFPreferencesCopyAppValue(PATHNAME_PREF_KEY,PREF_DOMAIN); if (!curPathName) // path has been deleted { pathName = CFSTR(DEFAULT_PATHNAME); CFPreferencesSetAppValue(PATHNAME_PREF_KEY,pathName,PREF_DOMAIN); logStream = CFWriteStreamCreateWithFile(kCFAllocatorDefault,CFURLCreateWithFileSystemPath(kCFAllocatorDefault,pathName,kCFURLPOSIXPathStyle,false)); if (!logStream) { syslog(LOG_ERR,"Error: Couldn't open file stream while running."); return; } } else if (CFStringCompare(curPathName,pathName,0)!=kCFCompareEqualTo) // path has changed { pathName = curPathName; logStream = CFWriteStreamCreateWithFile(kCFAllocatorDefault,CFURLCreateWithFileSystemPath(kCFAllocatorDefault,pathName,kCFURLPOSIXPathStyle,false)); if (!logStream) { syslog(LOG_ERR,"Error: Couldn't open file stream while running."); return; } CFDataDeleteBytes(encrypt_buffer,CFRangeMake(0,CFDataGetLength(encrypt_buffer))); } if (!fileExists(pathName)) // when file is deleted, we resync the encryption & keymap preferences { CFPreferencesAppSynchronize(PREF_DOMAIN); updateEncryption(); updateKeymap(); logStream = CFWriteStreamCreateWithFile(kCFAllocatorDefault,CFURLCreateWithFileSystemPath(kCFAllocatorDefault,pathName,kCFURLPOSIXPathStyle,false)); if (!logStream) { syslog(LOG_ERR,"Error: Couldn't open file stream while running."); return; } stamp_file(CFSTR("LogKext Daemon created new logfile")); } if (outOfSpace(pathName)) { stamp_file(CFSTR("Not enough disk space remaining!")); return; } /********* Finally, write the buffer **********/ write_buffer(the_buffer); CFRelease(the_buffer); return; }
void Zirk2PortClient::ClearData() { CFRange range = CFRangeMake(0, CFDataGetLength(mData)); CFDataDeleteBytes(mData, range); }
size_t der_sizeof_dictionary(CFDictionaryRef dict, CFErrorRef *error) { struct size_context context = { .success = true, .size = 0, .error = error }; CFDictionaryApplyFunction(dict, add_key_value_size, &context); if (!context.success) return 0; return ccder_sizeof(CCDER_CONSTRUCTED_SET, context.size); } static uint8_t* der_encode_key_value(CFPropertyListRef key, CFPropertyListRef value, CFErrorRef *error, const uint8_t* der, uint8_t *der_end) { return ccder_encode_constructed_tl(CCDER_CONSTRUCTED_SEQUENCE, der_end, der, der_encode_plist(key, error, der, der_encode_plist(value, error, der, der_end))); } struct encode_context { bool success; CFErrorRef * error; CFMutableArrayRef list; CFAllocatorRef allocator; }; static void add_sequence_to_array(const void *key_void, const void *value_void, void *context_void) { struct encode_context *context = (struct encode_context *) context_void; if (context->success) { CFTypeRef key = (CFTypeRef) key_void; CFTypeRef value = (CFTypeRef) value_void; size_t der_size = der_sizeof_key_value(key, value, context->error); if (der_size == 0) { context-> success = false; } else { CFMutableDataRef encoded_kv = CFDataCreateMutable(context->allocator, der_size); CFDataSetLength(encoded_kv, der_size); uint8_t* const encode_begin = CFDataGetMutableBytePtr(encoded_kv); uint8_t* encode_end = encode_begin + der_size; encode_end = der_encode_key_value(key, value, context->error, encode_begin, encode_end); if (encode_end != NULL) { CFDataDeleteBytes(encoded_kv, CFRangeMake(0, (encode_end - encode_begin))); CFArrayAppendValue(context->list, encoded_kv); } else { context-> success = false; } CFReleaseNull(encoded_kv); } } } static CFComparisonResult cfdata_compare_contents(const void *val1, const void *val2, void *context __unused) { return CFDataCompare((CFDataRef) val1, (CFDataRef) val2); } uint8_t* der_encode_dictionary(CFDictionaryRef dictionary, CFErrorRef *error, const uint8_t *der, uint8_t *der_end) { CFMutableArrayRef elements = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); struct encode_context context = { .success = true, .error = error, .list = elements }; CFDictionaryApplyFunction(dictionary, add_sequence_to_array, &context); if (!context.success) { CFReleaseNull(elements); return NULL; } CFRange allOfThem = CFRangeMake(0, CFArrayGetCount(elements)); CFArraySortValues(elements, allOfThem, cfdata_compare_contents, NULL); uint8_t* original_der_end = der_end; for(CFIndex position = CFArrayGetCount(elements); position > 0;) { --position; CFDataRef data = CFArrayGetValueAtIndex(elements, position); der_end = ccder_encode_body(CFDataGetLength(data), CFDataGetBytePtr(data), der, der_end); } CFReleaseNull(elements); return ccder_encode_constructed_tl(CCDER_CONSTRUCTED_SET, original_der_end, der, der_end); }
void Blob::deleteRange(Range range) { gfx_assert(range.location < length() && range.max() < length(), str("out of bounds range")); CFDataDeleteBytes(getStorage(), range); }