Exemplo n.º 1
0
static int tls_create_trust_from_certs(const SSLCertificate *cert, SecTrustRef *trustRef)
{
    int err;
    CFMutableArrayRef certArray = NULL;
    CFDataRef certData = NULL;
    SecCertificateRef cfCert = NULL;

    if(cert==NULL) {
        test_printf("No certs, do not create SecTrustRef\n");
        *trustRef = NULL;
        return 0;
    }

    certArray = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
    while(cert) {
        base64_dump(cert->derCert, "CERTIFICATE");
        require_action((certData = CFDataCreate(kCFAllocatorDefault, cert->derCert.data, cert->derCert.length)), out, err = errSecAllocate);
        require_action((cfCert = SecCertificateCreateWithData(kCFAllocatorDefault, certData)), out, err = errSecAllocate);
        CFArrayAppendValue(certArray, cfCert);
        CFReleaseNull(cfCert);
        CFReleaseNull(certData);
        cert=cert->next;
    }

    require_noerr((err=SecTrustCreateWithCertificates(certArray, NULL, trustRef)), out);

out:
    CFReleaseSafe(certData);
    CFReleaseSafe(cfCert);
    CFReleaseSafe(certArray);

    return err;
}
const uint8_t* der_decode_array(CFAllocatorRef allocator, CFOptionFlags mutability,
                                CFArrayRef* array, CFErrorRef *error,
                                const uint8_t* der, const uint8_t *der_end)
{
    if (NULL == der)
        return NULL;

    CFMutableArrayRef result = CFArrayCreateMutable(allocator, 0, &kCFTypeArrayCallBacks);

    const uint8_t *elements_end;
    const uint8_t *current_element = ccder_decode_sequence_tl(&elements_end, der, der_end);
    
    while (current_element != NULL && current_element < elements_end) {
        CFPropertyListRef element = NULL;
        current_element = der_decode_plist(allocator, mutability, &element, error, current_element, elements_end);
        if (current_element) {
            CFArrayAppendValue(result, element);
            CFReleaseNull(element);
        }
    }

    if (current_element) {
        *array = result;
        result = NULL;
    }

    CFReleaseNull(result);
    return current_element;
}
static const uint8_t* der_decode_key_value(CFAllocatorRef allocator, CFOptionFlags mutability,
                                           CFPropertyListRef* key, CFPropertyListRef* value, CFErrorRef *error,
                                           const uint8_t* der, const uint8_t *der_end)
{
    const uint8_t *payload_end = 0;
    const uint8_t *payload = ccder_decode_constructed_tl(CCDER_CONSTRUCTED_SEQUENCE, &payload_end, der, der_end);

    if (NULL == payload) {
        SecCFDERCreateError(kSecDERErrorUnknownEncoding, CFSTR("Unknown data encoding, expected CCDER_CONSTRUCTED_SEQUENCE"), NULL, error);
        return NULL;
    }

    CFTypeRef keyObject = NULL;
    CFTypeRef valueObject = NULL;


    payload = der_decode_plist(allocator, mutability, &keyObject, error, payload, payload_end);
    payload = der_decode_plist(allocator, mutability, &valueObject, error, payload, payload_end);

    if (payload != NULL) {
        *key = keyObject;
        *value = valueObject;
    } else {
        CFReleaseNull(keyObject);
        CFReleaseNull(valueObject);
    }
    return payload;
}
static void SOSRecoveryKeyBagDestroy(CFTypeRef aObj) {
    SOSRecoveryKeyBagRef rb = (SOSRecoveryKeyBagRef) aObj;
    
    CFReleaseNull(rb->accountDSID);
    CFReleaseNull(rb->generation);
    CFReleaseNull(rb->recoveryKeyBag);
}
static void ensureKeychainExists(void) {
    CFDictionaryRef query = CFDictionaryCreate(0, &kSecClass, &kSecClassInternetPassword, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CFTypeRef results = NULL;
    is_status(SecItemCopyMatching(query, &results), errSecItemNotFound, "expected nothing got %@", results);
    CFReleaseNull(query);
    CFReleaseNull(results);
}
Exemplo n.º 6
0
/* Convert cert in DER format into an CFArray of SecCertificateRef */
CFArrayRef
tls_get_peer_certs(const SSLCertificate *certs)
{
    const SSLCertificate *cert;

    CFMutableArrayRef certArray = NULL;
    CFDataRef certData = NULL;
    SecCertificateRef cfCert = NULL;

    certArray = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
    require(certArray, out);
    cert = certs;
    while(cert) {
        require((certData = CFDataCreate(kCFAllocatorDefault, cert->derCert.data, cert->derCert.length)), out);
        require((cfCert = SecCertificateCreateWithData(kCFAllocatorDefault, certData)), out);
        CFArrayAppendValue(certArray, cfCert);
        CFReleaseNull(cfCert);
        CFReleaseNull(certData);
        cert=cert->next;
    }

    return certArray;

out:
    CFReleaseNull(cfCert);
    CFReleaseNull(certData);
    CFReleaseNull(certArray);
    return NULL;
}
Exemplo n.º 7
0
static CFDictionaryRef
SecItemCopyAttributeDictionary(CFTypeRef ref) {
	CFDictionaryRef refDictionary = NULL;
	CFTypeID typeID = CFGetTypeID(ref);
	if (typeID == SecKeyGetTypeID()) {
		refDictionary = SecKeyCopyAttributeDictionary((SecKeyRef)ref);
	} else if (typeID == SecCertificateGetTypeID()) {
		refDictionary =
			SecCertificateCopyAttributeDictionary((SecCertificateRef)ref);
	} else if (typeID == SecIdentityGetTypeID()) {
        assert(false);
        SecIdentityRef identity = (SecIdentityRef)ref;
        SecCertificateRef cert = NULL;
        SecKeyRef key = NULL;
        if (!SecIdentityCopyCertificate(identity, &cert) &&
            !SecIdentityCopyPrivateKey(identity, &key)) 
        {
            CFDataRef data = SecCertificateCopyData(cert);
            CFDictionaryRef key_dict = SecKeyCopyAttributeDictionary(key);
            
            if (key_dict && data) {
                refDictionary = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, key_dict);
                CFDictionarySetValue((CFMutableDictionaryRef)refDictionary, 
                    CFSTR(CERTIFICATE_DATA_COLUMN_LABEL), data);
            }
            CFReleaseNull(key_dict);
            CFReleaseNull(data);
        }
        CFReleaseNull(cert);
        CFReleaseNull(key);
    } else {
		refDictionary = NULL;
	}
	return refDictionary;
}
static void tests(void)
{
    SOSCircleRef circle = SOSCircleCreate(NULL, CFSTR("TEST DOMAIN"), NULL);
    
    ok(NULL != circle, "Circle creation");

    ok(0 == SOSCircleCountPeers(circle), "Zero peers");

    //SecKeyRef publicKey = NULL;
    SecKeyRef dev_a_key = NULL;
    SecKeyRef dev_b_key = NULL;
    CFErrorRef error = NULL;
    CFDataRef cfpassword = CFDataCreate(NULL, (uint8_t *) "FooFooFoo", 10);
    
    if(cfpassword == NULL) printf("WTF\n");
    
    CFDataRef parameters = SOSUserKeyCreateGenerateParameters(&error);
    ok(parameters, "No parameters!");
    ok(error == NULL, "Error: (%@)", error);
    CFReleaseNull(error);

    SecKeyRef user_privkey = SOSUserKeygen(cfpassword, parameters, &error);
    CFReleaseNull(parameters);

    SOSFullPeerInfoRef peer_a_full_info = SOSCreateFullPeerInfoFromName(CFSTR("Peer A"), &dev_a_key, NULL);
    
    SOSFullPeerInfoRef peer_b_full_info = SOSCreateFullPeerInfoFromName(CFSTR("Peer B"), &dev_b_key, NULL);
    
    ok(SOSCircleRequestAdmission(circle, user_privkey, peer_a_full_info, NULL));
    ok(SOSCircleRequestAdmission(circle, user_privkey, peer_a_full_info, NULL));
    ok(SOSCircleRequestAdmission(circle, user_privkey, peer_a_full_info, NULL));

    ok(SOSCircleAcceptRequest(circle, user_privkey, peer_a_full_info, SOSFullPeerInfoGetPeerInfo(peer_a_full_info), NULL));
    
    ok(!SOSCircleRequestAdmission(circle, user_privkey, peer_a_full_info, NULL));
    ok(SOSCircleRequestAdmission(circle, user_privkey, peer_b_full_info, NULL));
    
    ok(SOSCircleCountPeers(circle) == 1, "Peer count");

    size_t size = SOSCircleGetDEREncodedSize(circle, &error);
    uint8_t buffer[size];
    uint8_t* start = SOSCircleEncodeToDER(circle, &error, buffer, buffer + sizeof(buffer));
    
    ok(start, "successful encoding");
    ok(start == buffer, "Used whole buffer");
    
    const uint8_t *der = buffer;
    SOSCircleRef inflated = SOSCircleCreateFromDER(NULL, &error, &der, buffer + sizeof(buffer));
    
    ok(inflated, "inflated");
    ok(CFEqualSafe(inflated, circle), "Compares");
    
    
    ok(SOSCircleRemovePeer(circle, user_privkey, peer_a_full_info, SOSFullPeerInfoGetPeerInfo(peer_a_full_info), NULL));
    ok(SOSCircleCountPeers(circle) == 0, "Peer count");
    
    CFReleaseNull(dev_a_key);
    CFReleaseNull(cfpassword);
}
void asynchttp_free(asynchttp_t *http) {
    if (http) {
        CFReleaseNull(http->request);
        CFReleaseNull(http->response);
        CFReleaseNull(http->data);
        CFReleaseNull(http->stream);
        dispatch_release_null(http->timer);
    }
}
static void persistentRefIs(CFDataRef pref, CFDataRef data) {
    CFMutableDictionaryRef dict = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
    CFTypeRef result = NULL;
    CFDictionaryAddValue(dict, kSecValuePersistentRef, pref);
    CFDictionaryAddValue(dict, kSecReturnData, kCFBooleanTrue);
    ok_status(SecItemCopyMatching(dict, &result), "lookup item data by persistent ref");
    ok(CFEqual(data, result), "result %@ equals expected data %@", result, data);
    CFReleaseNull(result);
    CFReleaseNull(dict);
}
Exemplo n.º 11
0
void SOSCoderDispose(SOSCoderRef coder)
{
    if (coder) {
        CFReleaseNull(coder->sessRef);
        CFReleaseNull(coder->pendingResponse);
        CFReleaseNull(coder->peer_id);
        free(coder);
    }
    coder = NULL;
}
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;
}
Exemplo n.º 13
0
bool SOSAccountSetHSAPubKeyExpected(SOSAccountRef account, CFDataRef pubKeyBytes, CFErrorRef *error) {
    bool retval = false;
    SecKeyRef publicKey = SecKeyCreateFromPublicBytes(NULL, kSecECDSAAlgorithmID, CFDataGetBytePtr(pubKeyBytes), CFDataGetLength(pubKeyBytes));
    CFStringRef peerID = SOSCopyIDOfKey(publicKey, error);
    require(sosAccountSetPreApprovedInfo(account, peerID, error), errOut);
    retval = true;
errOut:
    CFReleaseNull(publicKey);
    CFReleaseNull(peerID);
    return retval;
}
static int countPeers(SOSAccountRef account, bool active) {
    CFErrorRef error = NULL;
    CFArrayRef peers;
    
    if(active) peers = SOSAccountCopyActivePeers(account, &error);
    else peers = SOSAccountCopyPeers(account, &error);
    int retval = (int) CFArrayGetCount(peers);
    CFReleaseNull(error);
    CFReleaseNull(peers);
    return retval;
}
/* Test basic add delete update copy matching stuff. */
static void tests(SecKeyDescriptor *descriptor)
{
    const uint8_t *keyData = (const uint8_t *)"abc";
    CFIndex keyDataLength = 3;
    SecKeyEncoding encoding = kSecKeyEncodingRaw;
    ok(customKey = SecKeyCreate(kCFAllocatorDefault,
        descriptor, keyData, keyDataLength, encoding),
        "create custom key");
    is(customKey, initedCustomKey, "CustomKeyInit got the right key");

    SecPadding padding = kSecPaddingPKCS1;
    const uint8_t *src = (const uint8_t *)"defgh";
    size_t srcLen = 5;
    uint8_t dst[5];
    size_t dstLen = 5;

    ok_status(SecKeyDecrypt(customKey, padding, src, srcLen, dst, &dstLen),
        "SecKeyDecrypt");
    ok_status(SecKeyEncrypt(customKey, padding, src, srcLen, dst, &dstLen),
        "SecKeyEncrypt");
    ok_status(SecKeyRawSign(customKey, padding, src, srcLen, dst, &dstLen),
        "SecKeyRawSign");
    ok_status(SecKeyRawVerify(customKey, padding, src, srcLen, dst, dstLen),
        "SecKeyRawVerify");
    is(SecKeyGetSize(customKey, kSecKeyKeySizeInBits), (size_t)5*8, "SecKeyGetSize");

    CFDictionaryRef attrDict = NULL;
    ok(attrDict = SecKeyCopyAttributeDictionary(customKey),
        "SecKeyCopyAttributeDictionary");
    CFReleaseNull(attrDict);

    CFDataRef pubdata = NULL;
    ok(SecKeyCopyPublicBytes(customKey, &pubdata) != 0, "SecKeyCopyPublicBytes");
    CFReleaseNull(pubdata);

    CFDataRef wrapped;
    wrapped = _SecKeyCopyWrapKey(customKey, kSecKeyWrapPublicKeyPGP, pubdata, NULL, NULL, NULL);
    ok(wrapped == NULL, "_SecKeyCopyWrapKey");
    CFReleaseNull(wrapped);

    wrapped = _SecKeyCopyUnwrapKey(customKey, kSecKeyWrapPublicKeyPGP, pubdata, NULL, NULL, NULL);
    ok(wrapped == NULL, "_SecKeyCopyUnwrapKey");
    CFReleaseNull(wrapped);

    //ok(SecKeyGeneratePair(customKey, ), "SecKeyGeneratePair");
    ok(SecKeyGetTypeID() != 0, "SecKeyGetTypeID works");

    if (customKey) {
        CFRelease(customKey);
        customKey = NULL;
    }
}
Exemplo n.º 16
0
bool SOSTransportMessageSendMessageIfNeeded(SOSTransportMessageRef transport, CFStringRef circle_id, CFStringRef peer_id, CFErrorRef *error) {
    
    SOSEnginePeerMessageSentBlock sent = NULL;
    CFDataRef message_to_send = NULL;
    bool ok = false;
    SOSPeerRef peer = SOSPeerCreateWithEngine(SOSTransportMessageGetEngine(transport), peer_id);
    CFDataRef coderData = SOSEngineGetCoderData(SOSTransportMessageGetEngine(transport), peer_id);
    require(coderData, fail);
    
    SOSCoderRef coder = SOSCoderCreateFromData(coderData, error);
    require(coder, fail);
    SOSPeerSetCoder(peer, coder);
    
    ok = SOSPeerCoderSendMessageIfNeeded(peer, &message_to_send, circle_id, peer_id, &sent, error);
    coder = SOSPeerGetCoder(peer);
    
    if (message_to_send)    {
        CFDictionaryRef peer_dict = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
                                                                 peer_id, message_to_send,
                                                                 NULL);
        CFDictionaryRef circle_peers = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
                                                                    circle_id, peer_dict,
                                                                    NULL);
        
        ok = ok && SOSTransportMessageSendMessages(transport, circle_peers, error);
        
        SOSPeerCoderConsume(&sent, ok);
        
        CFReleaseSafe(peer_dict);
        CFReleaseSafe(circle_peers);
    }
    
    
    Block_release(sent);
    
    
    CFReleaseSafe(message_to_send);
    
    coderData = SOSCoderCopyDER(coder, error);
    
    if(!SOSEngineSetCoderData(SOSTransportMessageGetEngine(transport), peer_id, coderData, error)){
        secerror("SOSTransportMessageSendMessageIfNeeded, Could not save peer state");
    }
    CFReleaseNull(coderData);
    
    if (coder)
        SOSCoderDispose(coder);
    
fail:
    CFReleaseNull(peer);
    return ok;
}
static bool acceptApplicants(SOSAccountRef account, CFIndex count) {
    bool retval = false;
    CFErrorRef error = NULL;
    CFArrayRef applicants = SOSAccountCopyApplicants(account, &error);
    ok(applicants && CFArrayGetCount(applicants) == count, "See %ld applicants %@ (%@)", count, applicants, error);
    CFReleaseNull(error);
    require_quiet(CFArrayGetCount(applicants) == count, xit);
    ok((retval=SOSAccountAcceptApplicants(account, applicants, &error)), "Accept applicants into the fold");
    CFReleaseNull(error);
    CFReleaseSafe(applicants);
xit:
    return retval;
}
Exemplo n.º 18
0
SOSCoderRef SOSCoderCreate(SOSPeerInfoRef peerInfo, SOSFullPeerInfoRef myPeerInfo, CFErrorRef *error) {        
    CFAllocatorRef allocator = CFGetAllocator(peerInfo);
    
    SOSCoderRef coder = calloc(1, sizeof(struct __OpaqueSOSCoder));
    CFErrorRef localError = NULL;

    SecOTRFullIdentityRef myRef = NULL;
    SecOTRPublicIdentityRef peerRef = NULL;
    SecKeyRef privateKey = NULL;
    SecKeyRef publicKey = NULL;

    if (myPeerInfo && peerInfo) {
        privateKey = SOSFullPeerInfoCopyDeviceKey(myPeerInfo, &localError);
        require_quiet(privateKey, errOut);

        myRef = SecOTRFullIdentityCreateFromSecKeyRef(allocator, privateKey, &localError);
        require_quiet(myRef, errOut);
        
        CFReleaseNull(privateKey);
    
        publicKey = SOSPeerInfoCopyPubKey(peerInfo);
        
        peerRef = SecOTRPublicIdentityCreateFromSecKeyRef(allocator, publicKey, &localError);
        require_quiet(peerRef, errOut);
        
        coder->sessRef = SecOTRSessionCreateFromID(allocator, myRef, peerRef);

        require(coder->sessRef, errOut);
        
        coder->waitingForDataPacket = false;
        coder->pendingResponse = NULL;
        
        CFReleaseNull(publicKey);
        CFReleaseNull(privateKey);
        CFReleaseNull(myRef);
        CFReleaseNull(peerRef);
    } else {
        secnotice("coder", "NULL Coder requested, no transport security");
    }

    SOSCoderStart(coder, NULL);

    return coder;

errOut:
    secerror("Coder create failed: %@\n", localError ? localError : (CFTypeRef)CFSTR("No local error in SOSCoderCreate"));
    secerror("Coder create failed: %@\n", error ? *error : (CFTypeRef)CFSTR("WTF NULL?"));
    CFReleaseNull(myRef);
    CFReleaseNull(peerRef);
    CFReleaseNull(publicKey);
    CFReleaseNull(privateKey);

    free(coder);
    return NULL;
}
Exemplo n.º 19
0
static CFStringRef SOSRecoveryKeyBagCopyFormatDescription(CFTypeRef aObj, CFDictionaryRef formatOptions) {
    SOSRecoveryKeyBagRef rb = (SOSRecoveryKeyBagRef) aObj;
    CFStringRef gcString = SOSGenerationCountCopyDescription(rb->generation);
    CFStringRef rkbID = SOSCopyIDOfDataBufferWithLength(rb->recoveryKeyBag, 8, NULL);

    CFMutableStringRef description = CFStringCreateMutable(kCFAllocatorDefault, 0);
    
    CFStringAppendFormat(description, NULL, CFSTR("<SOSRecoveryKeyBag@%p DSID: %@ version: %d  gencount: %@  RecoveryKeyID: %@ "), rb, rb->accountDSID, (int) rb->rkbVersion, gcString, rkbID);
    CFStringAppend(description, CFSTR(">"));
    
    CFReleaseNull(gcString);
    CFReleaseNull(rkbID);
    return description;
}
Exemplo n.º 20
0
static bool SOSTestAcceptApplicant(SOSAccountRef acceptor, CFIndex appsExpected, CFErrorRef *error) {
    bool retval = true;
    CFArrayRef applicants = SOSAccountCopyApplicants(acceptor, error);
    CFStringRef acceptorName = SOSAccountCopyName(acceptor);
    
    ok(applicants && CFArrayGetCount(applicants) == appsExpected, "See %ld applicant %@ (%@)", appsExpected, applicants, *error);
    if(CFArrayGetCount(applicants) != appsExpected) retval = false;
    ok(retval && (retval = SOSAccountAcceptApplicants(acceptor, applicants, error)), "%@ accepts (%@)", acceptorName, *error);
    CFReleaseNull(*error);
    CFReleaseNull(applicants);
    CFReleaseNull(acceptorName);
    
    return retval;
}
Exemplo n.º 21
0
const uint8_t* der_decode_dictionary(CFAllocatorRef allocator, CFOptionFlags mutability,
                                     CFDictionaryRef* dictionary, CFErrorRef *error,
                                     const uint8_t* der, const uint8_t *der_end)
{
    if (NULL == der)
        return NULL;

    const uint8_t *payload_end = 0;
    const uint8_t *payload = ccder_decode_constructed_tl(CCDER_CONSTRUCTED_SET, &payload_end, der, der_end);

    if (NULL == payload) {
        SecCFDERCreateError(kSecDERErrorUnknownEncoding, CFSTR("Unknown data encoding, expected CCDER_CONSTRUCTED_SET"), NULL, error);
        return NULL;
    }
    
    
    CFMutableDictionaryRef dict = CFDictionaryCreateMutable(allocator, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    
    if (NULL == dict) {
        SecCFDERCreateError(kSecDERErrorAllocationFailure, CFSTR("Failed to create dictionary"), NULL, error);
        payload = NULL;
        goto exit;
    }

    while (payload != NULL && payload < payload_end) {
        CFTypeRef key = NULL;
        CFTypeRef value = NULL;
        
        payload = der_decode_key_value(allocator, mutability, &key, &value, error, payload, payload_end);
        
        if (payload) {
            CFDictionaryAddValue(dict, key, value);
        }
        
        CFReleaseNull(key);
        CFReleaseNull(value);
    }
    
    
exit:
    if (payload == payload_end) {
        *dictionary = dict;
        dict = NULL;
    }

    CFReleaseNull(dict);

    return payload;
}
Exemplo n.º 22
0
bool SOSAccountSendIKSPSyncList(SOSAccountRef account, CFErrorRef *error){
    bool result = true;
    __block CFErrorRef localError = NULL;
    __block CFMutableArrayRef ids = NULL;
    SOSCircleRef circle = NULL;
    
    require_action_quiet(SOSAccountIsInCircle(account, NULL), xit,
                         SOSCreateError(kSOSErrorNoCircle, CFSTR("This device is not in circle"),
                                        NULL, &localError));
    
    circle  = SOSAccountGetCircle(account, error);
    ids = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
    
    SOSCircleForEachValidPeer(circle, account->user_public, ^(SOSPeerInfoRef peer) {
        if (!SOSAccountIsThisPeerIDMe(account, SOSPeerInfoGetPeerID(peer))) {
            if(SOSPeerInfoShouldUseIDSTransport(SOSFullPeerInfoGetPeerInfo(account->my_identity), peer) &&
               SOSPeerInfoShouldUseIDSMessageFragmentation(SOSFullPeerInfoGetPeerInfo(account->my_identity), peer) &&
               !SOSPeerInfoShouldUseACKModel(SOSFullPeerInfoGetPeerInfo(account->my_identity), peer)){
                SOSTransportMessageIDSSetFragmentationPreference(account->ids_message_transport, kCFBooleanTrue);
                CFStringRef deviceID = SOSPeerInfoCopyDeviceID(peer);
                if(deviceID != NULL){
                    CFArrayAppendValue(ids, deviceID);
                }
                CFReleaseNull(deviceID);
            }
        }
    });
bool SOSAccountPublishCloudParameters(SOSAccountRef account, CFErrorRef* error){
    bool success = false;
    CFIndex cloud_der_len = der_sizeof_cloud_parameters(
                                                        account->user_public,
                                                        account->user_key_parameters,
                                                        error);
    CFMutableDataRef cloudParameters =
    CFDataCreateMutableWithScratch(kCFAllocatorDefault, cloud_der_len);
    
    if (der_encode_cloud_parameters(account->user_public, account->user_key_parameters, error,
                                    CFDataGetMutableBytePtr(cloudParameters),
                                    CFDataGetMutablePastEndPtr(cloudParameters)) != NULL) {

        CFErrorRef changeError = NULL;
        if (SOSTrasnportKeyParameterPublishCloudParameters(account->key_transport, cloudParameters, error)) {
            success = true;
        } else {
            SOSCreateErrorWithFormat(kSOSErrorSendFailure, changeError, error, NULL,
                                     CFSTR("update parameters key failed [%@]"), cloudParameters);
        }
        CFReleaseSafe(changeError);
    } else {
        SOSCreateError(kSOSErrorEncodeFailure, CFSTR("Encoding parameters failed"), NULL, error);
    }
    
    CFReleaseNull(cloudParameters);
    
    return success;
}
CFDataRef SOSUserKeyCreateGenerateParameters(CFErrorRef *error) {
    size_t saltlen = SALTMAX;
    uint8_t salt[saltlen];

    size_t iterations = ITERATIONMIN;
    size_t keysize = 256;

    if(CCRandomCopyBytes(kCCRandomDefault, salt, sizeof(salt)) != kCCSuccess) {
        SOSCreateError(kSOSErrorProcessingFailure, CFSTR("CCRandomCopyBytes failed"), NULL, error);
        return NULL;
    }

    CFMutableDataRef result = CFDataCreateMutable(kCFAllocatorDefault, 0);
    CFDataSetLength(result, der_sizeof_pbkdf2_params(saltlen, salt, iterations, keysize));

    uint8_t * encode = der_encode_pbkdf2_params(saltlen, salt, iterations, keysize,
                                                CFDataGetBytePtr(result),
                                                CFDataGetMutableBytePtr(result) + CFDataGetLength(result));

    if (!encode)
        CFReleaseNull(result);

    if (result) {
        secnotice("keygen", "Created new parameters: iterations %zd, keysize %zd: %@", iterations, keysize, result);
    }

    return result;
}
Exemplo n.º 25
0
static void debugShowSignerInfo(SecCmsSignedDataRef signedData)
{
#ifndef NDEBUG
    int numberOfSigners = SecCmsSignedDataSignerInfoCount (signedData);
    dtprintf("numberOfSigners : %d\n", numberOfSigners);
    int ix;
    for (ix=0;ix < numberOfSigners;ix++)
    {
        SecCmsSignerInfoRef sigi = SecCmsSignedDataGetSignerInfo(signedData,ix);
        if (sigi)
        {
            CFStringRef commonName = SecCmsSignerInfoGetSignerCommonName(sigi);
            const char *signerhdr = "      signer    : ";
            if (commonName)
            {
                char *cn = cfStringToChar(commonName);
                dtprintf("%s%s\n", signerhdr, cn);
                if (cn)
                    free(cn);
                CFReleaseNull(commonName);
            }
            else
                dtprintf("%s<NULL>\n", signerhdr);
         }
    }
#endif
}
Exemplo n.º 26
0
static OSStatus
EAPSecIdentityListCreate(CFArrayRef * ret_array)
{
    const void *		keys[] = {
	kSecClass,
	kSecReturnRef,
	kSecMatchLimit
    };
    CFDictionaryRef		query;
    CFTypeRef			results = NULL;
    OSStatus			status = errSecSuccess;
    const void *		values[] = {
	kSecClassIdentity,
	kCFBooleanTrue,
	kSecMatchLimitAll
    };

    query = CFDictionaryCreate(NULL, keys, values,
			       array_size(keys),
			       &kCFTypeDictionaryKeyCallBacks,
			       &kCFTypeDictionaryValueCallBacks);
    ok_status(status = SecItemCopyMatching(query, &results), "SecItemCopyMatching");
    CFReleaseNull(query);
    if (status == errSecSuccess) {
	*ret_array = results;
    }
    return (status);
}
Exemplo n.º 27
0
/*
 * Free a privKey object.
 */
extern OSStatus sslFreePrivKey(SSLPrivKey **privKey)
{
	if (privKey && *privKey) {
		CFReleaseNull(SECKEYREF(*privKey));
	}
	return noErr;
}
Exemplo n.º 28
0
static void asynchttp_complete(asynchttp_t *http) {
    secdebug("http", "http: %p", http);
    /* Shutdown streams and timer, we're about to invoke our client callback. */
    if (http->stream) {
        CFReadStreamSetClient(http->stream, kCFStreamEventNone, NULL, NULL);
        CFReadStreamSetDispatchQueue(http->stream, NULL);
        CFReadStreamClose(http->stream);
        CFReleaseNull(http->stream);
    }
    if (http->timer) {
        dispatch_source_cancel(http->timer);
        dispatch_release_null(http->timer);
    }

    if (http->completed) {
        /* This should probably move to our clients. */
        CFTimeInterval maxAge = NULL_TIME;
        if (http->response) {
            CFStringRef cacheControl = CFHTTPMessageCopyHeaderFieldValue(
                http->response, CFSTR("cache-control"));
            if (cacheControl) {
                CFStringRef maxAgeValue = copyParseMaxAge(cacheControl);
                CFRelease(cacheControl);
                if (maxAgeValue) {
                    secdebug("http", "http header max-age: %@", maxAgeValue);
                    maxAge = CFStringGetDoubleValue(maxAgeValue);
                    CFRelease(maxAgeValue);
                }
            }
        }
        http->completed(http, maxAge);
    }
}
Exemplo n.º 29
0
// Der encoding/decoding
const uint8_t* der_decode_RecoveryKeyBag(CFAllocatorRef allocator,
                                         SOSRecoveryKeyBagRef* RecoveryKeyBag, CFErrorRef *error,
                                         const uint8_t* der, const uint8_t *der_end) {
    if (der == NULL) return der;
    const uint8_t *result = NULL;
    
    SOSRecoveryKeyBagRef rb = CFTypeAllocate(SOSRecoveryKeyBag, struct __OpaqueSOSRecoveryKeyBag, allocator);
    require_quiet(SecAllocationError(rb, error, CFSTR("Recovery bag allocation failed")), fail);
    
    const uint8_t *sequence_end = NULL;
    der = ccder_decode_sequence_tl(&sequence_end, der, der_end);
    require_quiet(sequence_end == der_end, fail);
    
    der = der_decode_string(kCFAllocatorDefault, kCFPropertyListImmutable, &rb->accountDSID, error, der, sequence_end);
    rb->generation = SOSGenCountCreateFromDER(kCFAllocatorDefault, error, &der, sequence_end);
    der = ccder_decode_uint64(&rb->rkbVersion, der, sequence_end);
    der = der_decode_data(allocator, kCFPropertyListImmutable, &rb->recoveryKeyBag, error, der, sequence_end);
    
    require_quiet(SecRequirementError(der == der_end, error, CFSTR("Extra space in sequence")), fail);
    if (RecoveryKeyBag) CFTransferRetained(*RecoveryKeyBag, rb);
    result = der;
fail:
    CFReleaseNull(rb);
    return result;
}
// Takes the "context" policies to extract the revocation and apply it to timeStamp.
CFArrayRef
SecPolicyCreateAppleTimeStampingAndRevocationPolicies(CFTypeRef policyOrArray)
{
    /* can't use SECAPI macros, since this function does not return OSStatus */
    CFArrayRef resultPolicyArray=NULL;
    try {
        // Set default policy
        CFRef<CFArrayRef> policyArray = cfArrayize(policyOrArray);
        CFRef<SecPolicyRef> defaultPolicy = SecPolicyCreateWithOID(kSecPolicyAppleTimeStamping);
        CFRef<CFMutableArrayRef> appleTimeStampingPolicies = makeCFMutableArray(1,defaultPolicy.get());

        // Parse the policy and add revocation related ones
        CFIndex numPolicies = CFArrayGetCount(policyArray);
        for(CFIndex dex=0; dex<numPolicies; dex++) {
            SecPolicyRef secPol = (SecPolicyRef)CFArrayGetValueAtIndex(policyArray, dex);
            SecPointer<Policy> pol = Policy::required(SecPolicyRef(secPol));
            const CssmOid &oid = pol->oid();
            if ((oid == CssmOid::overlay(CSSMOID_APPLE_TP_REVOCATION))
                || (oid == CssmOid::overlay(CSSMOID_APPLE_TP_REVOCATION_CRL))
                || (oid == CssmOid::overlay(CSSMOID_APPLE_TP_REVOCATION_OCSP)))
            {
                CFArrayAppendValue(appleTimeStampingPolicies, secPol);
            }
        }
        // Transfer of ownership
        resultPolicyArray=appleTimeStampingPolicies.yield();
    }
    catch (...) {
        CFReleaseNull(resultPolicyArray);
    };
    return resultPolicyArray;
}