bool platform_gpio_input_get( const platform_gpio_t* gpio ) { bool result = false; uint32_t regValue; uint32_t mask = (uint32_t)1 << gpio->pin; platform_mcu_powersave_disable(); require_quiet( gpio != NULL, exit); regValue = GpioGetReg( GPIO_A_IN + gpio->port ); result = ((regValue&mask) == 0 )? false : true; exit: platform_mcu_powersave_enable(); return result; }
static int64_t SecTrustStoreCountAll(SecTrustStoreRef ts) { __block int64_t result = -1; require_quiet(ts, errOutNotLocked); dispatch_sync(ts->queue, ^{ sqlite3_stmt *countAllStmt = NULL; int s3e = sqlite3_prepare(ts->s3h, countAllSQL, sizeof(countAllSQL), &countAllStmt, NULL); if (s3e == SQLITE_OK) { s3e = sqlite3_step(countAllStmt); if (s3e == SQLITE_ROW) { result = sqlite3_column_int64(countAllStmt, 0); } } if (countAllStmt) { verify_noerr(sqlite3_finalize(countAllStmt)); } });
BOOL CFirstPage::OnSetActive() { CPrinterSetupWizardSheet * psheet; CString greetingText; psheet = reinterpret_cast<CPrinterSetupWizardSheet*>(GetParent()); require_quiet( psheet, exit ); psheet->SetWizardButtons(PSWIZB_NEXT); m_greeting.SetFont(&m_largeFont); greetingText.LoadString(IDS_GREETING); m_greeting.SetWindowText(greetingText); exit: return CPropertyPage::OnSetActive(); }
uint8_t* der_encode_RecoveryKeyBag(SOSRecoveryKeyBagRef RecoveryKeyBag, CFErrorRef *error, const uint8_t *der, uint8_t *der_end) { uint8_t *result = NULL; if (der_end == NULL) return der_end; if(RecoveryKeyBag && RecoveryKeyBag->recoveryKeyBag && RecoveryKeyBag->accountDSID && RecoveryKeyBag->generation) { der_end = ccder_encode_constructed_tl(CCDER_CONSTRUCTED_SEQUENCE, der_end, der, der_encode_string(RecoveryKeyBag->accountDSID, error, der, SOSGenCountEncodeToDER(RecoveryKeyBag->generation, error, der, ccder_encode_uint64(RecoveryKeyBag->rkbVersion, der, der_encode_data(RecoveryKeyBag->recoveryKeyBag, error, der, der_end))))); require_quiet(der_end == der, errOut); result = der_end; } else { SOSCreateError(kSOSErrorEncodeFailure, CFSTR("Null RecoveryKeyBag"), NULL, error); } errOut: return result; }
// Return true (1) if the signature verifies. static bool SOSPeerInfoVerify(SOSPeerInfoRef peer, CFErrorRef *error) { bool result = false; const struct ccdigest_info *di = ccsha256_di(); uint8_t hbuf[di->output_size]; SecKeyRef pubKey = SOSPeerInfoCopyPubKey(peer); require_action_quiet(pubKey, error_out, SOSErrorCreate(kSOSErrorNoKey, error, NULL, CFSTR("Couldn't find pub key for %@"), peer)); require_quiet(SOSDescriptionHash(peer, di, hbuf, error), error_out); require_action_quiet(sosVerifyHash(pubKey, di, hbuf, peer->signature), error_out, SOSErrorCreate(kSOSErrorBadSignature, error, NULL, CFSTR("Signature didn't verify for %@"), peer)); result = true; error_out: CFReleaseNull(pubKey); return result; }
CFTypeRef SecTaskCopyValueForEntitlement(SecTaskRef task, CFStringRef entitlement, CFErrorRef *error) { CFTypeRef value = NULL; require(check_task(task), out); /* Load entitlements if necessary */ if (task->entitlementsLoaded == false) { require_quiet(SecTaskLoadEntitlements(task, error), out); } if (task->entitlements != NULL) { value = CFDictionaryGetValue(task->entitlements, entitlement); /* Return something the caller must release */ if (value != NULL) { CFRetain(value); } } out: return value; }
static IOReturn PrintSpeedForDisc ( io_object_t opticalMedia ) { IOReturn error = kIOReturnError; CFMutableDictionaryRef properties = NULL; CFStringRef bsdNode = NULL; const char * bsdName = NULL; error = IORegistryEntryCreateCFProperties ( opticalMedia, &properties, kCFAllocatorDefault, kNilOptions ); require ( ( error == kIOReturnSuccess ), ErrorExit ); bsdNode = ( CFStringRef ) CFDictionaryGetValue ( properties, CFSTR ( kIOBSDNameKey ) ); require ( ( bsdNode != NULL ), ReleaseProperties ); bsdName = CFStringGetCStringPtr ( bsdNode, CFStringGetSystemEncoding ( ) ); require ( ( bsdName != NULL ), ReleaseProperties ); error = PrintSpeedForBSDNode ( bsdName ); require ( ( error == kIOReturnSuccess ), ReleaseProperties ); ReleaseProperties: require_quiet ( ( properties != NULL ), ErrorExit ); CFRelease ( properties ); properties = NULL; ErrorExit: return error; }
void CSecondPage::InitBrowseList() { CPrinterSetupWizardSheet * psheet; CString text; psheet = reinterpret_cast<CPrinterSetupWizardSheet*>(GetParent()); require_quiet( psheet, exit ); // Initialize so that nothing is selected when we add to the list psheet->SetSelectedPrinter( NULL ); m_gotChoice = false; m_browseList.Select( NULL, TVGN_FIRSTVISIBLE ); // // load the no printers message until something shows up in the browse list // text.LoadString(IDS_NO_PRINTERS); LoadTextAndDisableWindow( text ); // // disable the next button until there's a printer to select // psheet->SetWizardButtons(PSWIZB_BACK); // // disable the printer information box // SetPrinterInformationState( FALSE ); m_descriptionField.SetWindowText( L"" ); m_locationField.SetWindowText( L"" ); exit: return; }
void CSecondPage::OnResolveService( Service * service ) { CPrinterSetupWizardSheet * psheet = reinterpret_cast<CPrinterSetupWizardSheet*>(GetParent()); require_quiet( psheet, exit ); check( service ); Queue * q = service->SelectedQueue(); check( q ); // // and set it to selected // m_selectedName = service->printer->name; // // and update the printer information box // SetPrinterInformationState( TRUE ); m_descriptionField.SetWindowText( q->description ); m_locationField.SetWindowText( q->location ); // // reset the cursor // SetCursor(psheet->m_active); exit: return; }
smcp_status_t smcp_outbound_begin_response(coap_code_t code) { smcp_status_t ret; smcp_t const self = smcp_get_current_instance(); ret = SMCP_STATUS_OK; require_action_string(!self->did_respond, bail, ret = SMCP_STATUS_RESPONSE_NOT_ALLOWED, "Attempted to send more than one response!" ); // If we have already started responding, don't bother. require_quiet(!self->is_responding, bail); if (self->is_processing_message) { self->outbound.next_tid = smcp_inbound_get_msg_id(); } ret = smcp_outbound_begin( self, code, (self->inbound.packet->tt==COAP_TRANS_TYPE_NONCONFIRMABLE)?COAP_TRANS_TYPE_NONCONFIRMABLE:COAP_TRANS_TYPE_ACK ); require_noerr(ret, bail); self->is_responding = true; if (self->is_processing_message) { require_noerr(ret=smcp_outbound_set_msg_id(smcp_inbound_get_msg_id()),bail); } bail: if (ret != SMCP_STATUS_OK) { self->is_responding = false; } return ret; }
/* Quick thought: we can eliminate this method if we search anchor sources before all others and we remember if we got a cert from an anchorsource. */ static bool SecSystemAnchorSourceContains(SecCertificateSourceRef source, SecCertificateRef certificate) { #ifndef SECITEM_SHIM_OSX CFDataRef nic = SecCertificateGetNormalizedSubjectContent(certificate); /* 64 bits cast: the worst that can happen here is we truncate the length and match an actual anchor. It does not matter since we would be returning the wrong anchors */ assert((unsigned long)CFDataGetLength(nic)<UINT_MAX); /* Debug check. correct as long as CFIndex is signed long */ const struct subject_to_ix_t *i2x = subject_to_anchor_ix((const char *)CFDataGetBytePtr(nic), (unsigned int)CFDataGetLength(nic)); require_quiet(i2x, errOut); CFIndex cert_length = SecCertificateGetLength(certificate); const UInt8 *cert_data = SecCertificateGetBytePtr(certificate); int anchor_ix = i2x->anchor_ix; do { if (cert_length == anchorslist[anchor_ix].length && !memcmp(anchorslist[anchor_ix].data, cert_data, cert_length)) return true; } while ((anchor_ix = anchorslist[anchor_ix].next_same_subject)); errOut: #endif return false; }
BOOL CSecondPage::OnKillActive() { OSStatus err = kNoErr; if ( m_selected ) { CPrinterSetupWizardSheet * psheet; psheet = reinterpret_cast<CPrinterSetupWizardSheet*>(GetParent()); require_quiet( psheet, exit ); psheet->SetSelectedPrinter( m_selected ); m_printers.remove( m_selected ); m_selected = NULL; } err = StopBrowse(); require_noerr( err, exit ); exit: return CPropertyPage::OnKillActive(); }
uid_t TSystemUtils::FindUIDToUse ( void ) { uid_t uid = 0; gid_t gid = 0; CFStringRef userName = NULL; SCDynamicStoreRef storeRef = NULL; storeRef = ::SCDynamicStoreCreate ( kCFAllocatorDefault, CFSTR ( "cddafs.util" ), NULL, NULL ); require ( ( storeRef != NULL ), ErrorExit ); userName = ::SCDynamicStoreCopyConsoleUser ( storeRef, &uid, &gid ); require ( ( userName != NULL ), ReleaseDynamicStore ); ::CFRelease ( userName ); ReleaseDynamicStore: require_quiet ( ( storeRef != NULL ), ErrorExit ); ::CFRelease ( storeRef ); storeRef = NULL; ErrorExit: return uid; }
void DNSSD_API CSecondPage::OnQuery( DNSServiceRef inRef, DNSServiceFlags inFlags, uint32_t inInterfaceIndex, DNSServiceErrorType inErrorCode, const char * inFullName, uint16_t inRRType, uint16_t inRRClass, uint16_t inRDLen, const void * inRData, uint32_t inTTL, void * inContext) { DEBUG_UNUSED( inTTL ); DEBUG_UNUSED( inRRClass ); DEBUG_UNUSED( inRRType ); DEBUG_UNUSED( inFullName ); DEBUG_UNUSED( inInterfaceIndex ); DEBUG_UNUSED( inRef ); Service * service = NULL; Queue * q; CSecondPage * self; bool qtotalDefined = false; bool moreComing = (bool) (inFlags & kDNSServiceFlagsMoreComing); OSStatus err = kNoErr; require_noerr( inErrorCode, exit ); service = reinterpret_cast<Service*>( inContext ); require_quiet( service, exit); self = service->printer->window; require_quiet( self, exit ); if ( ( inFlags & kDNSServiceFlagsAdd ) && ( inRDLen > 0 ) && ( inRData != NULL ) ) { const char * inTXT = ( const char * ) inRData; // // create a new queue // try { q = new Queue; } catch (...) { q = NULL; } require_action( q, exit, err = E_OUTOFMEMORY ); err = service->printer->window->ParseTextRecord( service, inRDLen, inTXT, qtotalDefined, q->name, q->priority ); require_noerr( err, exit ); if ( !qtotalDefined ) { q->name = L""; } // // add this queue // service->queues.push_back( q ); if ( service->queues.size() == service->qtotal ) { // // else if moreComing is not set, then we're going // to assume that we're done // self->StopOperation( service->serviceRef ); // // sort the queues // service->queues.sort( OrderQueueFunc ); // // we've completely resolved this service // self->OnResolveService( service ); } } exit: if ( err && service && ( service->serviceRef != NULL ) ) { service->printer->window->StopOperation( service->serviceRef ); } return; }
void DNSSD_API CPrinterSetupWizardSheet::OnBrowse( DNSServiceRef inRef, DNSServiceFlags inFlags, uint32_t inInterfaceIndex, DNSServiceErrorType inErrorCode, const char * inName, const char * inType, const char * inDomain, void * inContext ) { DEBUG_UNUSED(inRef); CPrinterSetupWizardSheet * self; bool moreComing = (bool) (inFlags & kDNSServiceFlagsMoreComing); CPropertyPage * active; Printer * printer = NULL; Service * service = NULL; OSStatus err = kNoErr; require_noerr( inErrorCode, exit ); self = reinterpret_cast <CPrinterSetupWizardSheet*>( inContext ); require_quiet( self, exit ); active = self->GetActivePage(); require_quiet( active, exit ); // Have we seen this printer before? printer = self->Lookup( inName ); if ( printer ) { service = printer->LookupService( inType ); } if ( inFlags & kDNSServiceFlagsAdd ) { if (printer == NULL) { // If not, then create a new one printer = self->OnAddPrinter( inInterfaceIndex, inName, inType, inDomain, moreComing ); require_action( printer, exit, err = kUnknownErr ); } if ( !service ) { err = self->OnAddService( printer, inInterfaceIndex, inName, inType, inDomain ); require_noerr( err, exit ); } else { service->refs++; } } else if ( printer ) { check( service ); err = self->OnRemoveService( service ); require_noerr( err, exit ); if ( printer->services.size() == 0 ) { err = self->OnRemovePrinter( printer, moreComing ); require_noerr( err, exit ); } } exit: return; }
void CThirdPage::OnBnClickedHaveDisk() { CPrinterSetupWizardSheet * psheet; Printer * printer; Service * service; Manufacturers manufacturers; CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY|OFN_FILEMUSTEXIST, L"Setup Information (*.inf)|*.inf||", this); psheet = reinterpret_cast<CPrinterSetupWizardSheet*>(GetParent()); require_quiet( psheet, exit ); printer = psheet->GetSelectedPrinter(); require_quiet( printer, exit ); service = printer->services.front(); require_quiet( service, exit ); for ( ;; ) { if ( dlg.DoModal() == IDOK ) { CString filename = dlg.GetPathName(); LoadPrintDriverDefsFromFile( manufacturers, filename, true ); // Sanity check if ( manufacturers.size() > 0 ) { PopulateUI( manufacturers ); if ( MatchPrinter( manufacturers, printer, service, false ) != kNoErr ) { CString errorMessage; CString errorCaption; errorMessage.LoadString( IDS_NO_MATCH_INF_FILE ); errorCaption.LoadString( IDS_NO_MATCH_INF_FILE_CAPTION ); MessageBox( errorMessage, errorCaption, MB_OK ); } break; } else { CString errorMessage; CString errorCaption; errorMessage.LoadString( IDS_BAD_INF_FILE ); errorCaption.LoadString( IDS_BAD_INF_FILE_CAPTION ); MessageBox( errorMessage, errorCaption, MB_OK ); } } else { break; } } exit: FreeManufacturers( manufacturers ); return; }
void CSecondPage::OnTvnSelchangedBrowseList(NMHDR *pNMHDR, LRESULT *pResult) { LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR); CPrinterSetupWizardSheet * psheet; Printer * printer; int err = 0; psheet = reinterpret_cast<CPrinterSetupWizardSheet*>(GetParent()); require_action( psheet, exit, err = kUnknownErr ); // The strange code here is to workaround a bug in the CTreeCtrl, whereupon the item // we selected isn't passed through correctly to this callback routine. if ( !m_gotChoice ) { printer = psheet->GetSelectedPrinter(); // If we really haven't selected a printer, then re-select NULL and exit if ( !printer ) { m_browseList.SelectItem( NULL ); goto exit; } // If we already have selected a printer, fake like we've clicked on it, but only // if the CTreeCtrl hasn't already selected it else if ( printer->item != m_browseList.GetSelectedItem() ) { m_gotChoice = true; m_browseList.SelectItem( printer->item ); goto exit; } } HTREEITEM item = m_browseList.GetSelectedItem(); require_quiet( item, exit ); printer = reinterpret_cast<Printer*>(m_browseList.GetItemData( item ) ); require_quiet( printer, exit ); // // this call will trigger a resolve. When the resolve is complete, // our OnResolve will be called. // err = psheet->StartResolve( printer ); require_noerr( err, exit ); // // And clear out the printer information box // SetPrinterInformationState( FALSE ); m_descriptionField.SetWindowText(L""); m_locationField.SetWindowText(L""); exit: if (err != 0) { CString text; CString caption; text.LoadString(IDS_ERROR_SELECTING_PRINTER_TEXT); caption.LoadString(IDS_ERROR_SELECTING_PRINTER_CAPTION); MessageBox(text, caption, MB_OK|MB_ICONEXCLAMATION); } *pResult = 0; }
SOSAccountRef SOSAccountCreateFromDER_V1(CFAllocatorRef allocator, SOSDataSourceFactoryRef factory, CFErrorRef* error, const uint8_t** der_p, const uint8_t *der_end) { SOSAccountRef account = NULL; const uint8_t *sequence_end; *der_p = ccder_decode_constructed_tl(CCDER_CONSTRUCTED_SEQUENCE, &sequence_end, *der_p, der_end); { CFDictionaryRef decoded_gestalt = NULL; *der_p = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListImmutable, &decoded_gestalt, error, *der_p, der_end); if (*der_p == 0) return NULL; account = SOSAccountCreateBasic(allocator, decoded_gestalt, factory); CFReleaseNull(decoded_gestalt); } CFArrayRef array = NULL; *der_p = der_decode_array(kCFAllocatorDefault, 0, &array, error, *der_p, sequence_end); *der_p = ccder_decode_bool(&account->user_public_trusted, *der_p, sequence_end); *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &account->user_public, error, *der_p, sequence_end); *der_p = der_decode_data_or_null(kCFAllocatorDefault, &account->user_key_parameters, error, *der_p, sequence_end); *der_p = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListMutableContainers, (CFDictionaryRef *) &account->retired_peers, error, *der_p, sequence_end); if (*der_p != sequence_end) *der_p = NULL; __block bool success = true; require_quiet(array && *der_p, fail); CFArrayForEach(array, ^(const void *value) { if (success) { if (isString(value)) { CFDictionaryAddValue(account->circles, value, kCFNull); } else { CFDataRef circleData = NULL; CFDataRef fullPeerInfoData = NULL; if (isData(value)) { circleData = (CFDataRef) value; } else if (isArray(value)) { CFArrayRef pair = (CFArrayRef) value; CFTypeRef circleObject = CFArrayGetValueAtIndex(pair, 0); CFTypeRef fullPeerInfoObject = CFArrayGetValueAtIndex(pair, 1); if (CFArrayGetCount(pair) == 2 && isData(circleObject) && isData(fullPeerInfoObject)) { circleData = (CFDataRef) circleObject; fullPeerInfoData = (CFDataRef) fullPeerInfoObject; } } if (circleData) { SOSCircleRef circle = SOSCircleCreateFromData(kCFAllocatorDefault, circleData, error); require_action_quiet(circle, fail, success = false); CFStringRef circleName = SOSCircleGetName(circle); CFDictionaryAddValue(account->circles, circleName, circle); if (fullPeerInfoData) { SOSFullPeerInfoRef full_peer = SOSFullPeerInfoCreateFromData(kCFAllocatorDefault, fullPeerInfoData, error); require_action_quiet(full_peer, fail, success = false); CFDictionaryAddValue(account->circle_identities, circleName, full_peer); CFReleaseNull(full_peer); } fail: CFReleaseNull(circle); } } } });
CFDataRef SecOTRSessionCreateRemote_internal(CFDataRef publicAccountData, CFDataRef publicPeerId, CFDataRef privateAccountData, CFErrorRef *error) { SOSDataSourceFactoryRef ds = SecItemDataSourceFactoryGetDefault(); SOSAccountRef privateAccount = NULL; SOSAccountRef publicAccount = NULL; CFStringRef publicKeyString = NULL; SecKeyRef privateKeyRef = NULL; SecKeyRef publicKeyRef = NULL; SecOTRFullIdentityRef privateIdentity = NULL; SecOTRPublicIdentityRef publicIdentity = NULL; CFDataRef result = NULL; SecOTRSessionRef ourSession = NULL; require_quiet(ds, fail); require_quiet(publicPeerId, fail); privateAccount = (privateAccountData == NULL) ? CFRetainSafe(SOSKeychainAccountGetSharedAccount()) : SOSAccountCreateFromData(kCFAllocatorDefault, privateAccountData, ds, error); require_quiet(privateAccount, fail); privateKeyRef = SOSAccountCopyDeviceKey(privateAccount, error); require_quiet(privateKeyRef, fail); CFReleaseNull(privateAccount); privateIdentity = SecOTRFullIdentityCreateFromSecKeyRef(kCFAllocatorDefault, privateKeyRef, error); require_quiet(privateIdentity, fail); CFReleaseNull(privateKeyRef); publicKeyString = CFStringCreateFromExternalRepresentation(kCFAllocatorDefault, publicPeerId, kCFStringEncodingUTF8); require_quiet(publicKeyString, fail); publicAccount = (publicAccountData == NULL) ? CFRetainSafe(SOSKeychainAccountGetSharedAccount()) : SOSAccountCreateFromData(kCFAllocatorDefault, publicAccountData, ds, error); require_quiet(publicAccount, fail); publicKeyRef = SOSAccountCopyPublicKeyForPeer(publicAccount, publicKeyString, error); require_quiet(publicKeyRef, fail); CFReleaseNull(publicAccount); publicIdentity = SecOTRPublicIdentityCreateFromSecKeyRef(kCFAllocatorDefault, publicKeyRef, error); require_quiet(publicIdentity, fail); CFReleaseNull(publicKeyRef); ourSession = SecOTRSessionCreateFromID(kCFAllocatorDefault, privateIdentity, publicIdentity); CFMutableDataRef exportSession = CFDataCreateMutable(kCFAllocatorDefault, 0); SecOTRSAppendSerialization(ourSession, exportSession); result = exportSession; exportSession = NULL; fail: CFReleaseNull(ourSession); CFReleaseNull(publicKeyString); CFReleaseNull(privateAccount); CFReleaseNull(publicAccount); CFReleaseNull(privateKeyRef); CFReleaseNull(publicKeyRef); CFReleaseNull(publicIdentity); CFReleaseNull(privateIdentity); return result; }
BOOL CThirdPage::OnSetActive() { CPrinterSetupWizardSheet * psheet; Printer * printer; Service * service; psheet = reinterpret_cast<CPrinterSetupWizardSheet*>(GetParent()); require_quiet( psheet, exit ); psheet->SetWizardButtons( PSWIZB_BACK ); printer = psheet->GetSelectedPrinter(); require_quiet( printer, exit ); service = printer->services.front(); require_quiet( service, exit ); // // call OnInitPage once // if (!m_initialized) { OnInitPage(); m_initialized = true; } // // <rdar://problem/4580061> mDNS: Printers added using Bonjour should be set as the default printer. // if ( DefaultPrinterExists() ) { m_defaultPrinterCtrl.SetCheck( BST_UNCHECKED ); printer->deflt = false; } else { m_defaultPrinterCtrl.SetCheck( BST_CHECKED ); printer->deflt = true; } // // update the UI with the printer name // m_printerName.SetWindowText(printer->displayName); // // populate the list controls with the manufacturers and models // from ntprint.inf // PopulateUI( m_manufacturers ); // // and try and match the printer // if ( psheet->GetLastPage() == psheet->GetPage(0) ) { MatchPrinter( m_manufacturers, printer, service, true ); if ( ( m_manufacturerSelected != NULL ) && ( m_modelSelected != NULL ) ) { GetParent()->PostMessage(PSM_SETCURSEL, 2 ); } } else { SelectMatch(printer, service, m_manufacturerSelected, m_modelSelected); } exit: return CPropertyPage::OnSetActive(); }
static OSStatus SecRSAPublicKeyRawVerify(SecKeyRef key, SecPadding padding, const uint8_t *signedData, size_t signedDataLen, const uint8_t *sig, size_t sigLen) { OSStatus result = errSSLCrypto; ccrsa_pub_ctx_t pubkey; pubkey.pub = key->key; cc_unit s[ccrsa_ctx_n(pubkey)]; ccn_read_uint(ccrsa_ctx_n(pubkey), s, sigLen, sig); ccrsa_pub_crypt(pubkey, s, s); ccn_swap(ccrsa_ctx_n(pubkey), s); const uint8_t* sBytes = (uint8_t*) s; const uint8_t* sEnd = (uint8_t*) (s + ccrsa_ctx_n(pubkey)); switch (padding) { case kSecPaddingNone: // Skip leading zeros as long as s is bigger than signedData. while (((ptrdiff_t)signedDataLen < (sEnd - sBytes)) && (*sBytes == 0)) ++sBytes; break; case kSecPaddingPKCS1: { // Verify and skip PKCS1 padding: // // 0x00, 0x01 (RSA_PKCS1_PAD_SIGN), 0xFF .. 0x00, signedData // size_t m_size = ccn_write_uint_size(ccrsa_ctx_n(pubkey), ccrsa_ctx_m(pubkey)); size_t prefix_zeros = ccn_sizeof_n(ccrsa_ctx_n(pubkey)) - m_size; while (prefix_zeros--) require_quiet(*sBytes++ == 0x00, errOut); require_quiet(*sBytes++ == 0x00, errOut); require_quiet(*sBytes++ == RSA_PKCS1_PAD_SIGN, errOut); while (*sBytes == 0xFF) { require_quiet(++sBytes < sEnd, errOut); } // Required to have at least 8 0xFFs require_quiet((sBytes - (uint8_t*)s) - 2 >= 8, errOut); require_quiet(*sBytes == 0x00, errOut); require_quiet(++sBytes < sEnd, errOut); break; } case kSecPaddingOAEP: result = errSecParam; goto errOut; default: result = errSecUnimplemented; goto errOut; } // Compare the rest. require_quiet((sEnd - sBytes) == (ptrdiff_t)signedDataLen, errOut); require_quiet(memcmp(sBytes, signedData, signedDataLen) == 0, errOut); result = errSecSuccess; errOut: cc_zero(ccrsa_ctx_n(pubkey), s); return result; }
static CFStringRef SecECPublicKeyCopyKeyDescription(SecKeyRef key) { ccec_pub_ctx_t ecPubkey; CFStringRef keyDescription = NULL; size_t xlen, ylen, ix; CFMutableStringRef xString = NULL; CFMutableStringRef yString = NULL; ecPubkey.pub = key->key; //curve long curveType = (long)SecECKeyGetNamedCurve(key); char* curve= NULL; switch (curveType) { case 23: curve = "kSecECCurveSecp256r1"; break; case 24: curve = "kSecECCurveSecp384r1"; break; case 25: curve = "kSecECCurveSecp521r1"; break; case -1: curve = "kSecECCurveNone"; break; default: curve = "kSecECCurveNone"; break; } uint8_t *xunit = (uint8_t*)ccec_ctx_x(ecPubkey); require_quiet( NULL != xunit, fail); xlen = (size_t)strlen((char*)xunit); xString = CFStringCreateMutable(kCFAllocatorDefault, xlen * 2); require_quiet( NULL != xString, fail); for (ix = 0; ix < xlen; ++ix) { CFStringAppendFormat(xString, NULL, CFSTR("%02X"), xunit[ix]); } uint8_t *yunit = (uint8_t*)ccec_ctx_y(ecPubkey); require_quiet( NULL != yunit, fail); ylen = (size_t)strlen((char*)yunit); yString = CFStringCreateMutable(kCFAllocatorDefault, ylen*2); require_quiet( NULL != yString, fail); for(ix = 0; ix < ylen; ++ix) { CFStringAppendFormat(yString, NULL, CFSTR("%02X"), yunit[ix]); } keyDescription = CFStringCreateWithFormat(kCFAllocatorDefault,NULL,CFSTR( "<SecKeyRef curve type: %s, algorithm id: %lu, key type: %s, version: %d, block size: %zu bits, y: %@, x: %@, addr: %p>"), curve, (long)SecKeyGetAlgorithmID(key), key->key_class->name, key->key_class->version, (8*SecKeyGetBlockSize(key)), yString, xString, key); fail: CFReleaseSafe(xString); CFReleaseSafe(yString); if(!keyDescription) keyDescription = CFStringCreateWithFormat(kCFAllocatorDefault,NULL,CFSTR("<SecKeyRef curve type: %s, algorithm id: %lu, key type: %s, version: %d, block size: %zu bits, addr: %p>"), curve,(long)SecKeyGetAlgorithmID(key), key->key_class->name, key->key_class->version, (8*SecKeyGetBlockSize(key)), key); return keyDescription; }
static OSStatus SecRSAPublicKeyRawEncrypt(SecKeyRef key, SecPadding padding, const uint8_t *plainText, size_t plainTextLen, uint8_t *cipherText, size_t *cipherTextLen) { OSStatus result = errSecParam; ccrsa_pub_ctx_t pubkey; pubkey.pub = key->key; cc_unit s[ccrsa_ctx_n(pubkey)]; const size_t m_size = ccn_write_uint_size(ccrsa_ctx_n(pubkey), ccrsa_ctx_m(pubkey)); require(cipherTextLen, errOut); require(*cipherTextLen >= m_size, errOut); uint8_t* sBytes = (uint8_t*) s; switch (padding) { case kSecPaddingNone: require_noerr_quiet(ccn_read_uint(ccrsa_ctx_n(pubkey), s, plainTextLen, plainText), errOut); require_quiet(ccn_cmp(ccrsa_ctx_n(pubkey), s, ccrsa_ctx_m(pubkey)) < 0, errOut); break; case kSecPaddingPKCS1: { // Create PKCS1 padding: // // 0x00, 0x01 (RSA_PKCS1_PAD_ENCRYPT), 0xFF .. 0x00, signedData // const int kMinimumPadding = 1 + 1 + 8 + 1; require_quiet(plainTextLen < m_size - kMinimumPadding, errOut); size_t prefix_zeros = ccn_sizeof_n(ccrsa_ctx_n(pubkey)) - m_size; while (prefix_zeros--) *sBytes++ = 0x00; size_t pad_size = m_size - plainTextLen; *sBytes++ = 0x00; *sBytes++ = RSA_PKCS1_PAD_ENCRYPT; ccrng_generate(ccrng_seckey, pad_size - 3, sBytes); // Remove zeroes from the random pad const uint8_t* sEndOfPad = sBytes + (pad_size - 3); while (sBytes < sEndOfPad) { if (*sBytes == 0x00) *sBytes = 0xFF; // Michael said 0xFF was good enough. ++sBytes; } *sBytes++ = 0x00; memcpy(sBytes, plainText, plainTextLen); ccn_swap(ccrsa_ctx_n(pubkey), s); break; } case kSecPaddingOAEP: { const struct ccdigest_info* di = ccsha1_di(); const size_t encodingOverhead = 2 + 2 * di->output_size; require_action(m_size > encodingOverhead, errOut, result = errSecParam); require_action_quiet(plainTextLen < m_size - encodingOverhead, errOut, result = errSSLCrypto); require_noerr_action(ccrsa_oaep_encode(di, ccrng_seckey, m_size, s, plainTextLen, plainText), errOut, result = errSecInternal); break; } default: goto errOut; } ccrsa_pub_crypt(pubkey, s, s); ccn_write_uint_padded(ccrsa_ctx_n(pubkey), s, m_size, cipherText); *cipherTextLen = m_size; result = errSecSuccess; errOut: ccn_zero(ccrsa_ctx_n(pubkey), s); return result; }
bool asyncHttpPost(CFURLRef responder, CFDataRef requestData /* , bool force_nocache */ , asynchttp_t *http) { bool result = true; /* True, we didn't schedule any work. */ /* resources to release on exit */ CFURLRef getURL = NULL; /* Interesting tidbit from rfc5019 When sending requests that are less than or equal to 255 bytes in total (after encoding) including the scheme and delimiters (http://), server name and base64-encoded OCSPRequest structure, clients MUST use the GET method (to enable OCSP response caching). OCSP requests larger than 255 bytes SHOULD be submitted using the POST method. Interesting tidbit from rfc2616: Note: Servers ought to be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations might not properly support these lengths. Given the second note I'm assuming that the note in rfc5019 is about the length of the URI, not the length of the entire HTTP request. If we need to consider the entire request we need to have 17 bytes less, or 17 + 25 = 42 if we are appending a "Cache-Control: no-cache CRLF" header field. The 17 and 42 above are based on the request encoding from rfc2616 Method SP Request-URI SP HTTP-Version CRLF (header CRLF)* CRLF so in our case it's: GET SP URI SP HTTP/1.1 CRLF CRLF 17 + len(URI) bytes or GET SP URI SP HTTP/1.1 CRLF Cache-Control: SP no-cache CRLF CRLF 42 + len(URI) bytes */ /* First let's try creating a GET request. */ getURL = createGetURL(responder, requestData); if (getURL && CFURLGetBytes(getURL, NULL, 0) < 256) { /* Get URI is less than 256 bytes encoded, making it safe even for older proxy or caching servers, so let's use HTTP GET. */ secdebug("http", "GET[%ld] %@", CFURLGetBytes(getURL, NULL, 0), getURL); require_quiet(http->request = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("GET"), getURL, kCFHTTPVersion1_1), errOut); } else { /* GET Request too big to ensure error free transmission, let's create a HTTP POST http->request instead. */ secdebug("http", "POST %@ CRLF body", responder); require_quiet(http->request = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("POST"), responder, kCFHTTPVersion1_1), errOut); /* Set the body and required header fields. */ CFHTTPMessageSetBody(http->request, requestData); CFHTTPMessageSetHeaderFieldValue(http->request, kContentType, kAppOcspRequest); } #if 0 if (force_nocache) { CFHTTPMessageSetHeaderFieldValue(http->request, CFSTR("Cache-Control"), CFSTR("no-cache")); } #endif result = asynchttp_request(NULL, http); errOut: CFReleaseSafe(getURL); return result; }
static OSStatus SecRSAPublicKeyRawDecrypt(SecKeyRef key, SecPadding padding, const uint8_t *cipherText, size_t cipherTextLen, uint8_t *plainText, size_t *plainTextLen) { OSStatus result = errSSLCrypto; ccrsa_pub_ctx_t pubkey; pubkey.pub = key->key; cc_unit s[ccrsa_ctx_n(pubkey)]; require_action_quiet(cipherText != NULL, errOut, result = errSecParam); require_action_quiet(plainText != NULL, errOut, result = errSecParam); require_action_quiet(plainTextLen != NULL, errOut, result = errSecParam); ccn_read_uint(ccrsa_ctx_n(pubkey), s, cipherTextLen, cipherText); ccrsa_pub_crypt(pubkey, s, s); ccn_swap(ccrsa_ctx_n(pubkey), s); const uint8_t* sBytes = (uint8_t*) s; const uint8_t* sEnd = (uint8_t*) (s + ccrsa_ctx_n(pubkey)); switch (padding) { case kSecPaddingNone: // Skip leading zeros // We return the bytes for a number and // trim leading zeroes while (sBytes < sEnd && *sBytes == 0x00) ++sBytes; break; case kSecPaddingPKCS1: { // Verify and skip PKCS1 padding: // // 0x00, 0x01 (RSA_PKCS1_PAD_ENCRYPT), 0xFF .. 0x00, signedData // size_t m_size = ccn_write_uint_size(ccrsa_ctx_n(pubkey), ccrsa_ctx_m(pubkey)); size_t prefix_zeros = ccn_sizeof_n(ccrsa_ctx_n(pubkey)) - m_size; while (prefix_zeros--) require_quiet(*sBytes++ == 0x00, errOut); require_quiet(*sBytes++ == 0x00, errOut); require_quiet(*sBytes++ == RSA_PKCS1_PAD_ENCRYPT, errOut); while (*sBytes != 0x00) { require_quiet(++sBytes < sEnd, errOut); } // Required to have at least 8 0xFFs require_quiet((sBytes - (uint8_t*)s) - 2 >= 8, errOut); require_quiet(*sBytes == 0x00, errOut); require_quiet(++sBytes < sEnd, errOut); break; } case kSecPaddingOAEP: result = errSecParam; default: goto errOut; } // Return the rest. require_action((sEnd - sBytes) <= (ptrdiff_t)*plainTextLen, errOut, result = errSecParam); *plainTextLen = sEnd - sBytes; memcpy(plainText, sBytes, *plainTextLen); result = errSecSuccess; errOut: ccn_zero(ccrsa_ctx_n(pubkey), s); return result; }
void DNSSD_API CSecondPage::OnResolve( DNSServiceRef inRef, DNSServiceFlags inFlags, uint32_t inInterfaceIndex, DNSServiceErrorType inErrorCode, const char * inFullName, const char * inHostName, uint16_t inPort, uint16_t inTXTSize, const char * inTXT, void * inContext ) { DEBUG_UNUSED(inFullName); DEBUG_UNUSED(inInterfaceIndex); DEBUG_UNUSED(inFlags); DEBUG_UNUSED(inRef); CSecondPage * self; Service * service; Queue * q; bool qtotalDefined = false; uint32_t qpriority = kDefaultPriority; CString qname; int idx; OSStatus err; require_noerr( inErrorCode, exit ); service = reinterpret_cast<Service*>( inContext ); require_quiet( service, exit); check( service->refs != 0 ); self = service->printer->window; require_quiet( self, exit ); err = self->StopOperation( service->serviceRef ); require_noerr( err, exit ); // // hold on to the hostname... // err = UTF8StringToStringObject( inHostName, service->hostname ); require_noerr( err, exit ); // // <rdar://problem/3739200> remove the trailing dot on hostname // idx = service->hostname.ReverseFind('.'); if ((idx > 1) && ((service->hostname.GetLength() - 1) == idx)) { service->hostname.Delete(idx, 1); } // // hold on to the port // service->portNumber = ntohs(inPort); // // parse the text record. // err = self->ParseTextRecord( service, inTXTSize, inTXT, qtotalDefined, qname, qpriority ); require_noerr( err, exit ); if ( service->qtotal == 1 ) { // // create a new queue // try { q = new Queue; } catch (...) { q = NULL; } require_action( q, exit, err = E_OUTOFMEMORY ); if ( qtotalDefined ) { q->name = qname; } q->priority = qpriority; service->queues.push_back( q ); // // we've completely resolved this service // self->OnResolveService( service ); } else { // // if qtotal is more than 1, then we need to get additional // text records. if not, then this service is considered // resolved // err = DNSServiceQueryRecord(&service->serviceRef, 0, inInterfaceIndex, inFullName, kDNSServiceType_TXT, kDNSServiceClass_IN, OnQuery, (void*) service ); require_noerr( err, exit ); err = self->StartOperation( service->serviceRef ); require_noerr( err, exit ); } exit: return; }
static OSStatus SecRSAPrivateKeyRawSign(SecKeyRef key, SecPadding padding, const uint8_t *dataToSign, size_t dataToSignLen, uint8_t *sig, size_t *sigLen) { OSStatus result = errSecParam; ccrsa_full_ctx_t fullkey; fullkey.full = key->key; size_t m_size = ccn_write_uint_size(ccrsa_ctx_n(fullkey), ccrsa_ctx_m(fullkey)); cc_unit s[ccrsa_ctx_n(fullkey)]; uint8_t* sBytes = (uint8_t*) s; require(sigLen, errOut); require(*sigLen >= m_size, errOut); switch (padding) { case kSecPaddingNone: require_noerr_quiet(ccn_read_uint(ccrsa_ctx_n(fullkey), s, dataToSignLen, dataToSign), errOut); require_quiet(ccn_cmp(ccrsa_ctx_n(fullkey), s, ccrsa_ctx_m(fullkey)) < 0, errOut); break; case kSecPaddingPKCS1: { // Create PKCS1 padding: // // 0x00, 0x01 (RSA_PKCS1_PAD_SIGN), 0xFF .. 0x00, signedData // const int kMinimumPadding = 1 + 1 + 8 + 1; require(dataToSignLen < m_size - kMinimumPadding, errOut); size_t prefix_zeros = ccn_sizeof_n(ccrsa_ctx_n(fullkey)) - m_size; while (prefix_zeros--) *sBytes++ = 0x00; size_t pad_size = m_size - dataToSignLen; *sBytes++ = 0x00; *sBytes++ = RSA_PKCS1_PAD_SIGN; size_t ff_size; for(ff_size = pad_size - 3; ff_size > 0; --ff_size) *sBytes++ = 0xFF; *sBytes++ = 0x00; // Get the user data into s looking like a ccn. memcpy(sBytes, dataToSign, dataToSignLen); ccn_swap(ccrsa_ctx_n(fullkey), s); break; } case kSecPaddingOAEP: result = errSecParam; default: goto errOut; } ccrsa_priv_crypt(ccrsa_ctx_private(fullkey), s, s); // Pad with leading zeros to fit in modulus size ccn_write_uint_padded(ccrsa_ctx_n(fullkey), s, m_size, sig); *sigLen = m_size; result = errSecSuccess; errOut: ccn_zero(ccrsa_ctx_n(fullkey), s); return result; }
// Printer::EventHandler implementation OSStatus CSecondPage::OnAddPrinter( uint32_t inInterfaceIndex, const char * inName, const char * inType, const char * inDomain, bool moreComing) { Printer * printer; Service * service; CPrinterSetupWizardSheet * psheet; DWORD printerNameCount; bool newPrinter = false; OSStatus err = kNoErr; check( IsWindow( m_hWnd ) ); m_browseList.SetRedraw(FALSE); psheet = reinterpret_cast<CPrinterSetupWizardSheet*>(GetParent()); require_quiet( psheet, exit ); printer = Lookup( inName ); if (printer == NULL) { try { printer = new Printer; } catch (...) { printer = NULL; } require_action( printer, exit, err = E_OUTOFMEMORY ); printer->window = this; printer->name = inName; err = UTF8StringToStringObject(inName, printer->displayName); check_noerr( err ); printer->actualName = printer->displayName; printer->installed = false; printer->deflt = false; printer->resolving = 0; // // Compare this name against printers that are already installed // to avoid name clashes. Rename as necessary // to come up with a unique name. // printerNameCount = 2; for (;;) { PrinterNameMap::iterator it; it = m_printerNames.find(printer->actualName); if (it != m_printerNames.end()) { printer->actualName.Format(L"%s (%d)", printer->displayName, printerNameCount); } else { break; } printerNameCount++; } newPrinter = true; } check( printer ); service = printer->LookupService( inType ); if ( service != NULL ) { service->refs++; } else { try { service = new Service; } catch (...) { service = NULL; } require_action( service, exit, err = E_OUTOFMEMORY ); service->printer = printer; service->ifi = inInterfaceIndex; service->type = inType; service->domain = inDomain; service->qtotal = 1; service->refs = 1; service->serviceRef = NULL; printer->services.push_back( service ); // // if the printer is selected, then we'll want to start a // resolve on this guy // if ( m_selected == printer ) { StartResolve( service ); } } if ( newPrinter ) { printer->item = m_browseList.InsertItem(printer->displayName); m_browseList.SetItemData( printer->item, (DWORD_PTR) printer ); m_printers.push_back( printer ); m_browseList.SortChildren(TVI_ROOT); if ( printer->name == m_selectedName ) { m_browseList.SelectItem( printer->item ); } // // if the searching item is still in the list // get rid of it // // note that order is important here. Insert the printer // item before removing the placeholder so we always have // an item in the list to avoid experiencing the bug // in Microsoft's implementation of CTreeCtrl // if (m_emptyListItem != NULL) { m_browseList.DeleteItem(m_emptyListItem); m_emptyListItem = NULL; m_browseList.EnableWindow(TRUE); } } exit: if (!moreComing) { m_browseList.SetRedraw(TRUE); m_browseList.Invalidate(); } return err; }
static OSStatus SecRSAPrivateKeyRawDecrypt(SecKeyRef key, SecPadding padding, const uint8_t *cipherText, size_t cipherTextLen, uint8_t *plainText, size_t *plainTextLen) { OSStatus result = errSSLCrypto; ccrsa_full_ctx_t fullkey; fullkey.full = key->key; size_t m_size = ccn_write_uint_size(ccrsa_ctx_n(fullkey), ccrsa_ctx_m(fullkey)); cc_unit s[ccrsa_ctx_n(fullkey)]; uint8_t recoveredData[ccn_sizeof_n(ccrsa_ctx_n(fullkey))]; ccn_read_uint(ccrsa_ctx_n(fullkey), s, cipherTextLen, cipherText); ccrsa_priv_crypt(ccrsa_ctx_private(fullkey), s, s); const uint8_t* sBytes = (uint8_t*) s; const uint8_t* sEnd = (uint8_t*) (s + ccrsa_ctx_n(fullkey)); require(plainTextLen, errOut); switch (padding) { case kSecPaddingNone: ccn_swap(ccrsa_ctx_n(fullkey), s); // Skip Zeros since our contract is to do so. while (sBytes < sEnd && *sBytes == 0x00) ++sBytes; break; case kSecPaddingPKCS1: { ccn_swap(ccrsa_ctx_n(fullkey), s); // Verify and skip PKCS1 padding: // // 0x00, 0x01 (RSA_PKCS1_PAD_ENCRYPT), 0xFF .. 0x00, signedData // size_t prefix_zeros = ccn_sizeof_n(ccrsa_ctx_n(fullkey)) - m_size; while (prefix_zeros--) require_quiet(*sBytes++ == 0x00, errOut); require_quiet(*sBytes++ == 0x00, errOut); require_quiet(*sBytes++ == RSA_PKCS1_PAD_ENCRYPT, errOut); while (*sBytes != 0x00) { require_quiet(++sBytes < sEnd, errOut); } // Required to have at least 8 non-zeros require_quiet((sBytes - (uint8_t*)s) - 2 >= 8, errOut); require_quiet(*sBytes == 0x00, errOut); require_quiet(++sBytes < sEnd, errOut); break; } case kSecPaddingOAEP: { size_t length = sizeof(recoveredData); require_noerr_quiet(ccrsa_oaep_decode(ccsha1_di(), ccn_write_uint_size(ccrsa_ctx_n(fullkey),ccrsa_ctx_m(fullkey)), s, &length, recoveredData), errOut); sBytes = recoveredData; sEnd = recoveredData + length; break; } default: goto errOut; } require((sEnd - sBytes) <= (ptrdiff_t)*plainTextLen, errOut); *plainTextLen = sEnd - sBytes; memcpy(plainText, sBytes, *plainTextLen); result = errSecSuccess; errOut: bzero(recoveredData, sizeof(recoveredData)); ccn_zero(ccrsa_ctx_n(fullkey), s); return result; }