// Start OTR negotiation if we haven't already done so.
SOSCoderStatus
SOSCoderStart(SOSCoderRef coder, CFErrorRef *error) {
    CFMutableStringRef action = CFStringCreateMutable(kCFAllocatorDefault, 0);
    CFStringRef beginState = NULL;
    SOSCoderStatus result = kSOSCoderFailure;
    CFMutableDataRef startPacket = NULL;

    require_action_quiet(coder->sessRef, coderFailure, CFStringAppend(action, CFSTR("*** no otr session ***")));
    beginState = CFCopyDescription(coder->sessRef);
    require_action_quiet(!coder->waitingForDataPacket, negotiatingOut, CFStringAppend(action, CFSTR("waiting for peer to send first data packet")));
    require_action_quiet(!SecOTRSGetIsReadyForMessages(coder->sessRef), coderFailure, CFStringAppend(action, CFSTR("otr session ready"));
                         result = kSOSCoderDataReturned);
    require_action_quiet(SecOTRSGetIsIdle(coder->sessRef), negotiatingOut, CFStringAppend(action, CFSTR("otr negotiating already")));
    require_action_quiet(startPacket = CFDataCreateMutable(kCFAllocatorDefault, 0), coderFailure, SOSCreateError(kSOSErrorAllocationFailure, CFSTR("alloc failed"), NULL, error));
    require_quiet(SOSOTRSAppendStartPacket(coder->sessRef, startPacket, error), coderFailure);
    CFRetainAssign(coder->pendingResponse, startPacket);

negotiatingOut:
    result = kSOSCoderNegotiating;
coderFailure:
    // Uber state log
    if (result == kSOSCoderFailure && error && *error)
        CFStringAppendFormat(action, NULL, CFSTR(" %@"), *error);
    secnotice("coder", "%@ %s %@ %@ returned %s", beginState,
              SecOTRPacketTypeString(startPacket), action, coder->sessRef, SOSCoderString(result));
    CFReleaseNull(startPacket);
    CFReleaseSafe(beginState);
    CFRelease(action);

    return result;

}
static void testRSAKeyDesc()
{   
    SecKeyRef pubKey = NULL;
    CFStringRef pubRef = NULL;
    long pubLength = 0;
    	
    pubKey = SecKeyCreateRSAPublicKey(kCFAllocatorDefault, rsaPubKey, sizeof(rsaPubKey), kSecKeyEncodingBytes);
    require_quiet( pubKey, fail);
    
    pubRef = CFCopyDescription(pubKey);
    require_quiet(pubRef, fail);
    
    pubLength = CFStringGetLength(pubRef)+1;
    char *publicDescription = (char*)malloc(pubLength);
    require_quiet(publicDescription != NULL, fail);

    if(false == CFStringGetCString(pubRef, publicDescription, pubLength, kCFStringEncodingUTF8))
    {
	free(publicDescription);
	goto fail;
    }
    
    ok_status(strncmp(rsaKeyDescription, publicDescription, strlen(rsaKeyDescription)-17), "rsa key descriptions don't match: %s %s", rsaKeyDescription, publicDescription);
    free(publicDescription);

fail:
    CFReleaseSafe(pubRef);
    CFReleaseSafe(pubKey);
        
}
Beispiel #3
0
/**************************************************************************
 *              debugstr_cf
 */
const char* debugstr_cf(CFTypeRef t)
{
    CFStringRef s;
    const char* ret;

    if (!t) return "(null)";

    if (CFGetTypeID(t) == CFStringGetTypeID())
        s = t;
    else
        s = CFCopyDescription(t);
    ret = CFStringGetCStringPtr(s, kCFStringEncodingUTF8);
    if (ret) ret = debugstr_a(ret);
    if (!ret)
    {
        const UniChar* u = CFStringGetCharactersPtr(s);
        if (u)
            ret = debugstr_wn((const WCHAR*)u, CFStringGetLength(s));
    }
    if (!ret)
    {
        UniChar buf[200];
        int len = min(CFStringGetLength(s), sizeof(buf)/sizeof(buf[0]));
        CFStringGetCharacters(s, CFRangeMake(0, len), buf);
        ret = debugstr_wn(buf, len);
    }
    if (s != t) CFRelease(s);
    return ret;
}
static CFStringRef fileCopyDescription(struct _CFStream *stream, void *info) {
    // This needs work
    _CFFileStreamContext *ctxt = (_CFFileStreamContext *)info;
    if (ctxt->url) {
        return CFCopyDescription(ctxt->url);
    } else {
        return CFStringCreateWithFormat(CFGetAllocator(stream), NULL, CFSTR("fd = %d"), ctxt->fd);
    }
}
static CFStringRef
utilCopyDefaultKeyLabel(void)
{
	// generate a default label from the current date
	CFDateRef dateNow = CFDateCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent());
	CFStringRef defaultLabel = CFCopyDescription(dateNow);
	CFRelease(dateNow);

	return defaultLabel;
}
Boolean XAAttributeLoadFileDescriptor(XAAttributeRef attributeRef, int fd, char *key)
{
	Boolean bRet = 0x00;
	
	UInt8 *bytes = 0x00; size_t size = 0x00; UInt32 position = 0x00; int options = 0x00;
	
	size = fgetxattr(fd, key, (void *)bytes, size, position, options);

	if(size > 0x00)
	{
		bytes = calloc(size, sizeof(*bytes));
		
		size = fgetxattr(fd, key, (void *)bytes, size, position, options);
		
		if(size > 0x00)
		{
			CFAllocatorRef alloc = CFGetAllocator(attributeRef);
			
			CFStringRef sTemp = 0x00;
			
			CFStringRef dTemp = 0x00;
			
			CFDataRef dNice = 0x00;
			
			dNice = CFDataCreateWithBytesNoCopy(alloc, bytes, size, kCFAllocatorMalloc);
			
			sTemp = CFStringCreateWithCString(alloc, key, kCFStringEncodingUTF8);
			
			if(XAPrintableData(bytes, size))
			{
				dTemp = CFStringCreateWithBytes(alloc, bytes, size, kCFStringEncodingUTF8, 0x00);
			}else
			{
				dTemp = CFCopyDescription(dNice);
			}
			
			XAAttributeSetData(attributeRef, dNice);
			
			CFRelease(dNice);
			
			XAAttributeSetName(attributeRef, sTemp);
			
			CFRelease(sTemp);
			
			XAAttributeSetString(attributeRef, dTemp);
			
			CFRelease(dTemp);
			
			bRet = 0x01;
		}
		
	}
	
	return(bRet);
}
Beispiel #7
0
static netfsError
OpenSession9P(CFURLRef url, void *v, CFDictionaryRef opts,
              CFDictionaryRef * info)
{
        CFMutableDictionaryRef dict;
        Context9P *ctx;
        int useGuest, e;

        TRACE();
        ctx = v;
        if (ctx == NULL || url == NULL || info == NULL
            || !CFURLCanBeDecomposed(url))
                return EINVAL;

        DEBUG("url=%s opts=%s", NetFSCFStringtoCString(CFURLGetString(url)),
              NetFSCFStringtoCString(CFCopyDescription(opts)));
        *info = dict = CreateDict9P();
        if (dict == NULL)
                return ENOMEM;

        useGuest = FALSE;
        if (opts != NULL) {
                CFBooleanRef boolean =
                    CFDictionaryGetValue(opts, kNetFSUseGuestKey);
                if (boolean != NULL)
                        useGuest = CFBooleanGetValue(boolean);
        }

        if (useGuest)
                CFDictionarySetValue(dict, kNetFSMountedByGuestKey,
                                     kCFBooleanTrue);
        else {
                ctx->user = CFURLCopyUserName(url);
                ctx->pass = CFURLCopyPassword(url);
                if (ctx->user == NULL || ctx->pass == NULL) {
                        if (ctx->user)
                                CFRelease(ctx->user);
                        if (ctx->pass)
                                CFRelease(ctx->pass);
                        ctx->user = ctx->pass = NULL;
                        goto error;
                }
                DEBUG("user=%s pass=%s", NetFSCFStringtoCString(ctx->user),
                      NetFSCFStringtoCString(ctx->pass));
                CFDictionarySetValue(dict, kNetFSMountedByUserKey, ctx->user);
        }
        return 0;

 error:
        e = errno;
        *info = NULL;
        CFRelease(dict);
        return e;
}
void serviceRemovalCallback(void * target, void * refcon, IOHIDServiceRef service)
{
    CFStringRef string;

    CFDictionaryRemoveValue(__serviceNotifications, service);
    
    printf("SERVICE %s:\n", (char *)kServiceRemoved);
    
    string = CFCopyDescription(service);
    if ( string ) {
        printf("%s\n", CFStringGetCStringPtr(string, kCFStringEncodingMacRoman));
        CFRelease(string);
    }
}
Beispiel #9
0
string cfString(CFTypeRef it, OSStatus err)
{
	if (it == NULL)
		MacOSError::throwMe(err);
	CFTypeID id = CFGetTypeID(it);
	if (id == CFStringGetTypeID())
		return cfString(CFStringRef(it));
	else if (id == CFURLGetTypeID())
		return cfString(CFURLRef(it));
	else if (id == CFBundleGetTypeID())
		return cfString(CFBundleRef(it));
	else
		return cfString(CFCopyDescription(it), true);
}
Beispiel #10
0
static
void _CFNetDiagnosticsPrintObject(CFTypeRef object) {
	char buffer[32768];
	Boolean converted;
	CFStringRef desc;
	
	desc = CFCopyDescription(object);
	if(desc) {
		converted = CFStringGetCString(desc, buffer, 32768, kCFStringEncodingASCII);

		if(converted) {
			printf("%s\n", buffer);
		}
		CFRelease(desc);
	}
}
static void
hash_set(const void *keyRef, const void *valueRef, void *hash) {
  VALUE key = cfstr_to_str(keyRef);
  register VALUE value = Qnil;

  CFTypeID valueType = CFGetTypeID(valueRef);
  if (valueType == CFStringGetTypeID()) {
    value = cfstr_to_str(valueRef);
  } else if (valueRef == kCFBooleanTrue) {
    value = Qtrue;
  } else if (valueRef == kCFBooleanFalse) {
    value = Qfalse;
  } else if (valueType == CFDictionaryGetTypeID()) {
    value = rb_hash_new();
    CFDictionaryApplyFunction(valueRef, hash_set, (void *)value);

  } else if (valueType == CFArrayGetTypeID()) {
    value = rb_ary_new();
    CFIndex i, count = CFArrayGetCount(valueRef);
    for (i = 0; i < count; i++) {
      CFTypeRef elementRef = CFArrayGetValueAtIndex(valueRef, i);
      CFTypeID elementType = CFGetTypeID(elementRef);
      if (elementType == CFStringGetTypeID()) {
        rb_ary_push(value, cfstr_to_str(elementRef));

      } else if (elementType == CFDictionaryGetTypeID()) {
        VALUE hashElement = rb_hash_new();
        CFDictionaryApplyFunction(elementRef, hash_set, (void *)hashElement);
        rb_ary_push(value, hashElement);

      } else {
        CFStringRef descriptionRef = CFCopyDescription(elementRef);
        // obviously not optimal, but we're raising here, so it doesn't really matter
        VALUE description = cfstr_to_str(descriptionRef);
        rb_raise(rb_eTypeError, "Plist array value contains a object type unsupported by Xcodeproj. In: `%s'", RSTRING_PTR(description));
        CFRelease(descriptionRef);
      }
    }

  } else {
    rb_raise(rb_eTypeError, "Plist contains a hash value object type unsupported by Xcodeproj.");
  }

  rb_hash_aset((VALUE)hash, key, value);
}
Beispiel #12
0
static pascal void PrintPropertyListCallback(CFTypeRef key, CFTypeRef node, void *context)
	// A callback routine used by PrintPropertyList to print 
	// a property list in a nicely formatted way.
{
	#pragma unused(key)
	int i;
	int depth;
	
	depth = (int)context;
	
	for (i = 0; i < depth; i++) {
		fprintf(stderr, "  ");
	}

	{
		CFStringRef fullDesc;
		CFStringRef typeDesc;
		CFStringRef valueDesc;

		fullDesc = NULL;		
		typeDesc = CFCopyTypeIDDescription(CFGetTypeID(node));
		valueDesc = NULL;
		if ( CFQPropertyListIsLeaf(node) ) {
			if ( CFGetTypeID(node) == CFStringGetTypeID() ) {
				valueDesc = (CFStringRef) CFRetain(node);
			} else if ( CFGetTypeID(node) == CFNumberGetTypeID() ) {
				valueDesc = (CFStringRef) CFRetain(node);
			} else {
				valueDesc = CFCopyDescription(node);
			}
			fullDesc = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ : %@ [%d] = %@"), key, typeDesc, CFGetRetainCount(node), valueDesc);
		} else {
			fullDesc = CFStringCreateWithFormat(NULL, NULL, CFSTR("%@ : %@ [%d]"), key, typeDesc, CFGetRetainCount(node));
		}
		CFShow(fullDesc);
		CFQRelease(fullDesc);
		CFQRelease(valueDesc);
		CFQRelease(typeDesc);
	}

	if ( ! CFQPropertyListIsLeaf(node) ) {
		CFQPropertyListShallowApplyFunction(node, PrintPropertyListCallback, (void *) (depth + 1) );
	}
}
int sectask_11_sectask_audittoken(int argc, char *const *argv)
{
    SecTaskRef task=NULL;
    CFStringRef appId=NULL;
    CFStringRef signingIdentifier=NULL;

    plan_tests(6);

    init_self_audittoken();

    ok(task=SecTaskCreateWithAuditToken(kCFAllocatorDefault, g_self_audittoken), "SecTaskCreateFromAuditToken");
    require(task, out);

    /* TODO: remove the todo once xcode signs simulator binaries */
SKIP: {
#if TARGET_IPHONE_SIMULATOR
    todo("no entitlements in the simulator binaries yet, until <rdar://problem/12194625>");
#endif
    ok(appId=SecTaskCopyValueForEntitlement(task, kSecEntitlementApplicationIdentifier, NULL), "SecTaskCopyValueForEntitlement");
    skip("appId is NULL", 1, appId);
    ok(CFEqual(appId, CFSTR("com.apple.security.regressions")), "Application Identifier match");
    ok(signingIdentifier=SecTaskCopySigningIdentifier(task, NULL), "SecTaskCopySigningIdentifier");
    ok(CFEqual(signingIdentifier, CFBundleGetIdentifier(CFBundleGetMainBundle())), "CodeSigning Identifier match");
}

    pid_t pid = getpid();
    CFStringRef name = copyProcName(pid);
    CFStringRef pidstr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("[%d]"), pid);
    CFStringRef desc = CFCopyDescription(task);

    ok(CFStringFind(desc, name, 0).location != kCFNotFound, "didn't find name: %@ vs %@", desc, name);
    ok(CFStringFind(desc, pidstr, 0).location != kCFNotFound, "didn't find pidstr: %@ vs %@", desc, pidstr);

    CFReleaseSafe(name);
    CFReleaseSafe(desc);
    CFReleaseSafe(pidstr);

out:
    CFReleaseSafe(task);
    CFReleaseSafe(appId);
    CFReleaseSafe(signingIdentifier);

    return 0;
}
static void serviceClientCallback(void * target, void * refcon, IOHIDServiceClientRef service)
{
    CFStringRef string;
    
    if ( refcon == kServiceAdded ) {
        IOHIDServiceClientRegisterRemovalCallback(service, serviceClientCallback, NULL, (void*)kServiceRemoved);
    }
    
    printf("SERVICE %s:\n", (char *)refcon);
    
    string = CFCopyDescription(service);
    if ( string ) {
        printf("%s\n", CFStringGetCStringPtr(string, kCFStringEncodingMacRoman));
        CFRelease(string);
    }

    if ( __clientType == kIOHIDEventSystemClientTypeRateControlled ) {
        CFNumberRef number;
        uint32_t    primaryUsagePage=0, primaryUsage=0;
        
        number = IOHIDServiceClientCopyProperty(service, CFSTR(kIOHIDServicePrimaryUsagePageKey));
        if ( number ) {
            CFNumberGetValue(number, kCFNumberSInt32Type, &primaryUsagePage);
            CFRelease(number);
        }

        number = IOHIDServiceClientCopyProperty(service, CFSTR(kIOHIDServicePrimaryUsageKey));
        if ( number ) {
            CFNumberGetValue(number, kCFNumberSInt32Type, &primaryUsage);
            CFRelease(number);
        }
        
        if ( primaryUsagePage == __matchingUsagePage && primaryUsage == __matchingUsage ) {
            number = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &__matchingInterval);
            if ( number ) {
                IOHIDServiceClientSetProperty(service, CFSTR(kIOHIDServiceReportIntervalKey), number);
                CFRelease(number);
            }
        }
    }

}
Beispiel #15
0
 std::string Type::Description( void ) const
 {
     CFStringRef  cfDescription;
     std::string  description;
     char       * cStr;
     size_t       length;
     
     if( this->GetCFObject() == nullptr )
     {
         return "(null)";
     }
     
     cfDescription = CFCopyDescription( this->GetCFObject() );
     
     if( cfDescription == nullptr )
     {
         return "(null)";
     }
     
     length = static_cast< size_t >( CFStringGetMaximumSizeForEncoding( CFStringGetLength( cfDescription ), CFStringGetSystemEncoding() ) );
     cStr   = new char [ length + 1 ];
     
     if( cStr == nullptr )
     {
         CFRelease( cfDescription );
         
         return "(null)";
     }
     
     memset( cStr, 0, length + 1 );
     CFStringGetCString( cfDescription, cStr, static_cast< CFIndex >( length + 1 ), CFStringGetSystemEncoding() );
     
     description = std::string( cStr );
     
     delete [] cStr;
     
     CFRelease( cfDescription );
     
     return description;
 }
static void printEntry(const void *key, const void *value, void *context)
{
    struct indent_ctxt * ctxt = context;

#if 1
    // IOKit pretty
    CFDataRef	data;

    indent(false, ctxt->depth, ctxt->stackOfBits);
    printf("  ");
    printCFString( (CFStringRef)key );
    printf(" = ");

    data = IOCFSerialize((CFStringRef)value, kNilOptions);
    if( data) {
        if( 10000 > CFDataGetLength(data))
            printf(CFDataGetBytePtr(data));
        else
            printf("<is BIG>");
        CFRelease(data);
    } else
        printf("<IOCFSerialize failed>");
    printf("\n");

#else
    // CF ugly
    CFStringRef 	 keyStr = (CFStringRef) key;
    CFStringRef 	 valueStr = CFCopyDescription((CFTypeRef) val);
    CFStringRef 	 outStr;

    indent(false, ctxt->depth, ctxt->stackOfBits);
    outStr = CFStringCreateWithFormat(kCFAllocatorDefault, 0,
                CFSTR("  %@ = %@\n"), keyStr, valueStr);
    assert(outStr);
    printCFString(outStr);
    CFRelease(valueStr);
    CFRelease(outStr);
#endif
}
Beispiel #17
0
 std::string Type::Description( void ) const
 {
     CFStringRef  cfDescription;
     std::string  description;
     char       * cStr;
     size_t       length;
     
     if( this->GetCFObject() == NULL )
     {
         return "(null)";
     }
     
     cfDescription = CFCopyDescription( this->GetCFObject() );
     
     if( cfDescription == NULL )
     {
         return "(null)";
     }
     
     length = static_cast< size_t >( CFStringGetMaximumSizeForEncoding( CFStringGetLength( cfDescription ), CFStringGetSystemEncoding() ) );
     
     cStr = static_cast< char * >( calloc( length + 1, 1 ) );
     
     if( cStr == NULL )
     {
         CFRelease( cfDescription );
         
         return "(null)";
     }
     
     CFStringGetCString( cfDescription, cStr, static_cast< CFIndex >( length + 1 ), CFStringGetSystemEncoding() );
     
     description = std::string( cStr );
     
     free( cStr );
     CFRelease( cfDescription );
     
     return description;
 }
SOSCoderStatus SOSCoderWrap(SOSCoderRef coder, CFDataRef message, CFMutableDataRef *codedMessage, CFStringRef clientId, CFErrorRef *error) {
    CFMutableStringRef action = CFStringCreateMutable(kCFAllocatorDefault, 0);
    SOSCoderStatus result = kSOSCoderDataReturned;
    CFStringRef beginState = NULL;
    CFMutableDataRef encoded = NULL;
    OSStatus otrStatus = 0;

    require_action_quiet(coder->sessRef, errOut,
                         CFStringAppend(action, CFSTR("*** using null coder ***"));
                         result = nullCoder(message, codedMessage));
    beginState = CFCopyDescription(coder->sessRef);
    require_action_quiet(SecOTRSGetIsReadyForMessages(coder->sessRef), errOut,
                         CFStringAppend(action, CFSTR("not ready"));
                         result = kSOSCoderNegotiating);
    require_action_quiet(!coder->waitingForDataPacket, errOut,
                         CFStringAppend(action, CFSTR("waiting for peer to send data packet first"));
                         result = kSOSCoderNegotiating);
    require_action_quiet(encoded = CFDataCreateMutable(kCFAllocatorDefault, 0), errOut,
                         SOSCreateErrorWithFormat(kSOSErrorAllocationFailure, NULL, error, NULL, CFSTR("%@ alloc failed"), clientId);
                         result = kSOSCoderFailure);
    require_noerr_action_quiet(otrStatus = SecOTRSSignAndProtectMessage(coder->sessRef, message, encoded), errOut,
                               SOSCreateErrorWithFormat(kSOSErrorEncodeFailure, (error != NULL) ? *error : NULL, error, NULL, CFSTR("%@ cannot protect message: %" PRIdOSStatus), clientId, otrStatus);
                               CFReleaseNull(encoded);
                               result = kSOSCoderFailure);
    *codedMessage = encoded;

errOut:
    // Uber state log
    if (result == kSOSCoderFailure && error && *error)
        CFStringAppendFormat(action, NULL, CFSTR(" %@"), *error);
    secnotice("coder", "%@ %@ %s %@ %@ returned %s", clientId, beginState,
              SecOTRPacketTypeString(encoded), action, coder->sessRef, SOSCoderString(result));
    CFReleaseSafe(beginState);
    CFRelease(action);

    return result;
}
static void servicesAddedCallback(void * target, void * refcon, void * sender, CFArrayRef services)
{
    CFIndex index, count;
    
    for(index=0, count = CFArrayGetCount(services); index<count; index++) {
        IOHIDServiceRef service = (IOHIDServiceRef)CFArrayGetValueAtIndex(services, index);
        CFStringRef string;
        
        IOHIDNotificationRef notification = IOHIDServiceCreateRemovalNotification(service, serviceRemovalCallback, NULL, NULL);
        if ( notification ) {
            CFDictionaryAddValue(__serviceNotifications, service, notification);
            CFRelease(notification);
        }
        
        printf("SERVICE %s:\n", (char *)kServiceAdded);
        
        string = CFCopyDescription(service);
        if ( string ) {
            printf("%s\n", CFStringGetCStringPtr(string, kCFStringEncodingMacRoman));
            CFRelease(string);
        }
    }
    
}
/* Test basic add delete update copy matching stuff. */
static void tests(void)
{
	SecCertificateRef cert0, cert1, cert2, cert3, cert4, cert5, cert6;
	isnt(cert0 = SecCertificateCreateWithBytes(NULL, _c0, sizeof(_c0)),
		NULL, "create cert0");
	isnt(cert1 = SecCertificateCreateWithBytes(NULL, _c1, sizeof(_c1)),
		NULL, "create cert1");

    CFDataRef cert2Data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault,
        _c2, sizeof(_c2), kCFAllocatorNull);
	isnt(cert2 = SecCertificateCreateWithData(kCFAllocatorDefault, cert2Data),
		NULL, "create cert2");
    CFReleaseNull(cert2Data);

	isnt(cert3 = SecCertificateCreateWithBytes(NULL, _phased_c3, sizeof(_phased_c3)),
		NULL, "create cert3");

    CFDataRef cert4data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault,
        pem, sizeof(pem), kCFAllocatorNull);
    ok(cert4 = SecCertificateCreateWithPEM(NULL, cert4data), "create cert from pem");
    CFReleaseNull(cert4data);

	isnt(cert5 = SecCertificateCreateWithBytes(NULL, _elektron_v1_cert_der,
        sizeof(_elektron_v1_cert_der)), NULL, "create cert5");

	isnt(cert6 = SecCertificateCreateWithBytes(NULL, _wapi_as_der,
        sizeof(_wapi_as_der)), NULL, "create cert6");

    ok(SecCertificateIsSelfSignedCA(cert0), "cert0 is CA");
    ok(!SecCertificateIsSelfSignedCA(cert1), "cert1 is not CA");
    ok(SecCertificateIsSelfSignedCA(cert5), "cert5 is v1 CA");

    CFStringRef subjectSummary, issuerSummary;
    isnt(subjectSummary = SecCertificateCopySubjectSummary(cert1), NULL,
        "cert1 has a subject summary");
    isnt(issuerSummary = SecCertificateCopyIssuerSummary(cert1), NULL,
        "cert1 has an issuer summary");

    ok(subjectSummary && CFEqual(subjectSummary, CFSTR("www.verisign.com/CPS Incorp.by Ref. LIABILITY LTD.(c)97 VeriSign, VeriSign International Server CA - Class 3, VeriSign, Inc.")),
        "subject summary is \"www.verisign.com/CPS Incorp.by Ref. LIABILITY LTD.(c)97 VeriSign, VeriSign International Server CA - Class 3, VeriSign, Inc.\"");
    ok(issuerSummary && CFEqual(issuerSummary,
        CFSTR("Class 3 Public Primary Certification Authority")),
        "issuer summary is \"Class 3 Public Primary Certification Authority\"");

    CFArrayRef ntPrincipalNames;
    ok(ntPrincipalNames = SecCertificateCopyNTPrincipalNames(cert2),
        "SecCertificateCopyNTPrincipalNames");
    is(CFArrayGetCount(ntPrincipalNames), 1, "we got 1 princialname back");
    CFStringRef principal = (CFStringRef)CFArrayGetValueAtIndex(ntPrincipalNames, 0);
    ok(CFEqual(principal, CFSTR("*****@*****.**")),
        "first principal is [email protected]");
    CFReleaseSafe(ntPrincipalNames);

	CFReleaseSafe(subjectSummary);
	CFReleaseSafe(issuerSummary);

    isnt(subjectSummary = SecCertificateCopySubjectSummary(cert3), NULL,
        "cert3 has a subject summary");
	/* @@@ this causes a double free without an extra retain in obtainSummaryFromX501Name():
	       summary->description = string = copyDERThingDescription(kCFAllocatorDefault, value, true); */
	CFReleaseSafe(subjectSummary);

    isnt(subjectSummary = SecCertificateCopySubjectSummary(cert4), NULL,
        "cert4 has a subject summary");
    ok(subjectSummary && CFEqual(subjectSummary, CFSTR("S5L8900 Secure Boot")),
        "cert4 is S5L8900 Secure Boot");
	CFReleaseSafe(subjectSummary);

    CFStringRef desc = NULL;
    ok(desc = CFCopyDescription(cert4), "cert4 CFCopyDescription works");

	CFReleaseSafe(cert0);
	CFReleaseSafe(cert1);
	CFReleaseSafe(cert2);
	CFReleaseSafe(cert3);
	CFReleaseSafe(cert4);
	CFReleaseSafe(cert5);
	CFReleaseSafe(cert6);
	CFReleaseNull(desc);
}
Beispiel #21
0
static CFStringRef readDataCopyDescription(struct _CFStream *stream, void *info) {
    return CFCopyDescription(((_CFReadDataStreamContext *)info)->data);
}
SOSCoderStatus SOSCoderUnwrap(SOSCoderRef coder, CFDataRef codedMessage, CFMutableDataRef *message,
                              CFStringRef clientId, CFErrorRef *error) {
    if(codedMessage == NULL) return kSOSCoderDataReturned;
    if(coder->sessRef == NULL) return nullCoder(codedMessage, message);
    CFMutableStringRef action = CFStringCreateMutable(kCFAllocatorDefault, 0);
    /* This should be the "normal" case.  We just use OTR to unwrap the received message. */
    SOSCoderStatus result = kSOSCoderFailure;

    CFStringRef beginState = CFCopyDescription(coder->sessRef);
    enum SecOTRSMessageKind kind = SecOTRSGetMessageKind(coder->sessRef, codedMessage);

    switch (kind) {
        case kOTRNegotiationPacket: {
            /* If we're in here we haven't completed negotiating a session.  Use SecOTRSProcessPacket() to go through
             the negotiation steps and immediately send a reply back if necessary using the sendBlock.  This
             assumes the sendBlock is still available.
             */
            CFMutableDataRef response = CFDataCreateMutable(kCFAllocatorDefault, 0);
            OSStatus ppstatus = errSecSuccess;
            if (response) {
                switch (ppstatus = SecOTRSProcessPacket(coder->sessRef, codedMessage, response)) {
                    case errSecSuccess:
                        if (CFDataGetLength(response) > 1) {
                            CFStringAppendFormat(action, NULL, CFSTR("Sending OTR Response %s"), SecOTRPacketTypeString(response));
                            CFRetainAssign(coder->pendingResponse, response);
                            result = kSOSCoderNegotiating;
                            if (SecOTRSGetIsReadyForMessages(coder->sessRef)) {
                                CFStringAppend(action, CFSTR(" begin waiting for data packet"));
                                coder->waitingForDataPacket = true;
                            }
                        } else if(!SecOTRSGetIsReadyForMessages(coder->sessRef)) {
                            CFStringAppend(action, CFSTR("stuck?"));
                            result = kSOSCoderNegotiating;
                        } else {
                            CFStringAppend(action, CFSTR("completed negotiation"));
                            result = kSOSCoderNegotiationCompleted;
                            coder->waitingForDataPacket = false;
                        }
                        break;
                    case errSecDecode:
                        CFStringAppend(action, CFSTR("resending dh"));
                        result = SOSCoderResendDH(coder, error);
                        break;
                    default:
                        SOSCreateErrorWithFormat(kSOSErrorEncodeFailure, (error != NULL) ? *error : NULL, error, NULL, CFSTR("%@ Cannot negotiate session (%ld)"), clientId, (long)ppstatus);
                        result = kSOSCoderFailure;
                        break;
                };
            } else {
                SOSCreateErrorWithFormat(kSOSErrorAllocationFailure, (error != NULL) ? *error : NULL, error, NULL, CFSTR("%@ Cannot allocate CFData"), clientId);
                result = kSOSCoderFailure;
            }
            
            CFReleaseNull(response);
            
            break;
        }

        case kOTRDataPacket:
            if(!SecOTRSGetIsReadyForMessages(coder->sessRef)) {
                CFStringAppend(action, CFSTR("not ready, resending DH packet"));
				SetCloudKeychainTraceValueForKey(kCloudKeychainNumberOfTimesSyncFailed, 1);
                CFStringAppend(action, CFSTR("not ready for data; resending dh"));
                result = SOSCoderResendDH(coder, error);
            } else {
                if (coder->waitingForDataPacket) {
                    CFStringAppend(action, CFSTR("got data packet we were waiting for "));
                    coder->waitingForDataPacket = false;
                }
                CFMutableDataRef exposed = CFDataCreateMutable(0, 0);
                OSStatus otrResult = SecOTRSVerifyAndExposeMessage(coder->sessRef, codedMessage, exposed);
                CFStringAppend(action, CFSTR("verify and expose message"));
                if (otrResult) {
                    if (otrResult == errSecOTRTooOld) {
                        CFStringAppend(action, CFSTR(" too old"));
                        result = kSOSCoderStaleEvent;
                    } else {
                        SecError(otrResult, error, CFSTR("%@ Cannot expose message: %" PRIdOSStatus), clientId, otrResult);
                        secerror("%@ Decode OTR Protected Packet: %@", clientId, error ? *error : NULL);
                        result = kSOSCoderFailure;
                    }
                } else {
                    CFStringAppend(action, CFSTR("decoded OTR protected packet"));
                    *message = exposed;
                    exposed = NULL;
                    result = kSOSCoderDataReturned;
                }
                CFReleaseNull(exposed);
            }
            break;

        default:
            secerror("%@ Unknown packet type: %@", clientId, codedMessage);
            SOSCreateError(kSOSErrorDecodeFailure, CFSTR("Unknown packet type"), (error != NULL) ? *error : NULL, error);
            result = kSOSCoderFailure;
            break;
    };

    // Uber state log
    if (result == kSOSCoderFailure && error && *error)
        CFStringAppendFormat(action, NULL, CFSTR(" %@"), *error);
    secnotice("coder", "%@ %@ %s %@ %@ returned %s", clientId, beginState,
              SecOTRPacketTypeString(codedMessage), action, coder->sessRef, SOSCoderString(result));
    CFReleaseSafe(beginState);
    CFRelease(action);

    return result;
}
Beispiel #23
0
static netfsError
Mount9P(void *v, CFURLRef url, CFStringRef mntpointstr, CFDictionaryRef opts,
        CFDictionaryRef * info)
{
        CFMutableDictionaryRef dict;
        CFMutableStringRef mntoptsstr;
        CFStringRef str;
        CFNumberRef num;
        Context9P *ctx;
        char *host, *mntpoint, *mntopts;
        int32_t mntflags;
        int e;

        TRACE();
        ctx = v;
        if (ctx == NULL || url == NULL || mntpointstr == NULL || info == NULL
            || !CFURLCanBeDecomposed(url))
                return EINVAL;

        DEBUG("url=%s opts=%s", NetFSCFStringtoCString(CFURLGetString(url)),
              NetFSCFStringtoCString(CFCopyDescription(opts)));
        mntoptsstr = NULL;
        host = mntpoint = mntopts = NULL;
        *info = dict = CreateDict9P();
        if (dict == NULL)
                return ENOMEM;

        str = CFURLCopyHostName(url);
        if (str == NULL)
                goto error;

        host = NetFSCFStringtoCString(str);
        CFRelease(str);
        if (host == NULL)
                goto error;

        mntpoint = NetFSCFStringtoCString(mntpointstr);
        if (mntpoint == NULL)
                goto error;

        mntflags = 0;
        if (opts != NULL) {
                num =
                    (CFNumberRef) CFDictionaryGetValue(opts,
                                                       kNetFSMountFlagsKey);
                CFNumberGetValue(num, kCFNumberSInt32Type, &mntflags);
        }

        mntoptsstr =
            CFStringCreateMutableCopy(kCFAllocatorDefault, 0, CFSTR("-o"));
        if (mntoptsstr == NULL)
                goto error;

        if (ctx->user && ctx->pass)
                CFStringAppendFormat(mntoptsstr, NULL,
                                     CFSTR("uname=%@,pass=%@"), ctx->user,
                                     ctx->pass);
        else
                CFStringAppend(mntoptsstr, CFSTR("noauth"));

        /* query if there's any */
        str = CFURLCopyQueryString(url, CFSTR(""));
        if (str && CFStringGetLength(str) > 0) {
                CFStringAppend(mntoptsstr, CFSTR(","));
                CFStringAppend(mntoptsstr, str);
                CFRelease(str);
        }

        mntopts = NetFSCFStringtoCString(mntoptsstr);
        if (mntopts == NULL)
                goto error;

        DEBUG("host=%s mntpoint=%s mntopts=%s", host, mntpoint, mntopts);
        if (DoMount9P(host, mntpoint, mntopts, mntflags) < 0)
                goto error;

        CFDictionarySetValue(dict, kNetFSMountPathKey, mntpointstr);
        if (ctx->user)
                CFDictionarySetValue(dict, kNetFSMountedByUserKey, ctx->user);
        else
                CFDictionarySetValue(dict, kNetFSMountedByGuestKey,
                                     kCFBooleanTrue);

        if (mntoptsstr)
                CFRelease(mntoptsstr);
        free(host);
        free(mntpoint);
        free(mntopts);
        return 0;

 error:
        e = errno;
        *info = NULL;
        CFRelease(dict);
        if (mntoptsstr)
                CFRelease(mntoptsstr);
        free(host);
        free(mntpoint);
        free(mntopts);
        return e;
}
Beispiel #24
0
static netfsError CreateURL9P(CFDictionaryRef params, CFURLRef * url)
{
        CFMutableStringRef urlstr;
        CFStringRef str;
        int e;

        TRACE();
        if (url == NULL || params == NULL)
                return EINVAL;

        DEBUG("params=%s", NetFSCFStringtoCString(CFCopyDescription(params)));
        urlstr = CFStringCreateMutable(kCFAllocatorDefault, 0);
        if (urlstr == NULL)
                return ENOMEM;

        str = CFDictionaryGetValue(params, kNetFSSchemeKey);
        if (str == NULL)
                goto error;

        CFStringAppend(urlstr, str);
        CFStringAppend(urlstr, CFSTR("://"));

        str = CFDictionaryGetValue(params, kNetFSUserNameKey);
        if (str != NULL) {
                str =
                    CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                            str, NULL,
                                                            CFSTR("@:/?"),
                                                            kCFStringEncodingUTF8);
                CFStringAppend(urlstr, str);
                CFRelease(str);
                str = CFDictionaryGetValue(params, kNetFSPasswordKey);
                if (str != NULL) {
                        str =
                            CFURLCreateStringByAddingPercentEscapes
                            (kCFAllocatorDefault, str, NULL, CFSTR("@:/?"),
                             kCFStringEncodingUTF8);
                        CFStringAppend(urlstr, CFSTR(":"));
                        CFStringAppend(urlstr, str);
                        CFRelease(str);
                }
                CFStringAppend(urlstr, CFSTR("@"));
        }

        str = CFDictionaryGetValue(params, kNetFSHostKey);
        if (str == NULL)
                goto error;

        str =
            CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, str,
                                                    CFSTR("[]"),
                                                    CFSTR("/@:,?=;&+$"),
                                                    kCFStringEncodingUTF8);
        CFStringAppend(urlstr, str);
        CFRelease(str);

        str = CFDictionaryGetValue(params, kNetFSAlternatePortKey);
        if (str != NULL) {
                str =
                    CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                            str, NULL, NULL,
                                                            kCFStringEncodingUTF8);
                CFStringAppend(urlstr, CFSTR(":"));
                CFStringAppend(urlstr, str);
                CFRelease(str);
        }

/*
	str = CFDictionaryGetValue(params, kNetFSPathKey);
	if (str != NULL) {
		str = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, str, NULL, CFSTR("?"), kCFStringEncodingUTF8);
		CFStringAppend(urlstr, str);
		CFRelease(str);
	}
*/
        *url = CFURLCreateWithString(kCFAllocatorDefault, urlstr, NULL);
        if (*url == NULL)
                goto error;

        DEBUG("url=%s", NetFSCFStringtoCString(CFURLGetString(*url)));
        CFRelease(urlstr);
        return 0;

 error:
        e = errno;
        *url = NULL;
        CFRelease(urlstr);
        return e;
}
Beispiel #25
0
void PrintCFTypeInternalFormat(CFTypeRef value, uint32_t depth) {
	bool foundType = false;
	CFStringRef valueType = CFCopyTypeIDDescription(CFGetTypeID(value));
	CFStringRef dictionaryType = CFCopyTypeIDDescription(CFDictionaryGetTypeID());
	if (CFStringCompare(valueType, dictionaryType, 0x0) == kCFCompareEqualTo) {
		foundType = true;
		printf("{\n");
		PrintCFDictionaryInternalFormatting(value, depth+0x1);
		PrintDepth(depth,"}\n");
	}
	CFSafeRelease(dictionaryType);
	
	CFStringRef booleanType = CFCopyTypeIDDescription(CFBooleanGetTypeID());
	if (CFStringCompare(valueType, booleanType, 0x0) == kCFCompareEqualTo) {
		foundType = true;
		printf("%s\n",(CFBooleanGetValue(value) ? "True" : "False"));
	}
	CFSafeRelease(booleanType);
	
	CFStringRef stringType = CFCopyTypeIDDescription(CFStringGetTypeID());
	if (CFStringCompare(valueType, stringType, 0x0) == kCFCompareEqualTo) {
		foundType = true;
		printf("%s\n",(char*)CFStringGetCStringPtr(value,kCFStringEncodingUTF8));
	}
	CFSafeRelease(stringType);
	
	CFStringRef numberType = CFCopyTypeIDDescription(CFNumberGetTypeID());
	if (CFStringCompare(valueType, numberType, 0x0) == kCFCompareEqualTo) {
		foundType = true;
		CFIndex numberType = CFNumberGetType(value);
		switch (numberType) {
			case kCFNumberSInt8Type: {
				SInt8 number;
				CFNumberGetValue(value, numberType, &number);
				printf("%hhd\n",number);
				break;
			};
			case kCFNumberSInt16Type: {
				SInt16 number;
				CFNumberGetValue(value, numberType, &number);
				printf("%hd\n",number);
				break;
			};
			case kCFNumberSInt32Type: {
				SInt32 number;
				CFNumberGetValue(value, numberType, &number);
				printf("%d\n",(int32_t)number);
				break;
			};
			case kCFNumberSInt64Type: {
				SInt64 number;
				CFNumberGetValue(value, numberType, &number);
				printf("%lld\n",number);
				break;
			};
			case kCFNumberFloat32Type: {
				Float32 number;
				CFNumberGetValue(value, numberType, &number);
				printf("%.f\n",number);
				break;
			};
			case kCFNumberFloat64Type: {
				Float64 number;
				CFNumberGetValue(value, numberType, &number);
				printf("%.f\n",number);
				break;
			};
			case kCFNumberCharType: {
				char number;
				CFNumberGetValue(value, numberType, &number);
				printf("%c\n",number);
				break;
			};
			case kCFNumberShortType: {
				short number;
				CFNumberGetValue(value, numberType, &number);
				printf("%hd\n",number);
				break;
			};
			case kCFNumberIntType: {
				int number;
				CFNumberGetValue(value, numberType, &number);
				printf("%d\n",number);
				break;
			};
			case kCFNumberLongType: {
				long number;
				CFNumberGetValue(value, numberType, &number);
				printf("%ld\n",number);
				break;
			};
			case kCFNumberLongLongType: {
				long long number;
				CFNumberGetValue(value, numberType, &number);
				printf("%qd\n",number);
				break;
			};
			case kCFNumberFloatType: {
				float number;
				CFNumberGetValue(value, numberType, &number);
				printf("%.f\n",number);
				break;
			};
			case kCFNumberDoubleType: {
				double number;
				CFNumberGetValue(value, numberType, &number);
				printf("%.f\n",number);
				break;
			};
			case kCFNumberCFIndexType: {
				CFIndex number;
				CFNumberGetValue(value, numberType, &number);
				printf("%ld\n",number);
				break;
			};
			case kCFNumberNSIntegerType: {
				NSInteger number;
				CFNumberGetValue(value, numberType, &number);
				printf("%ld\n",(long)number);
				break;
			};
			case kCFNumberCGFloatType: {
				CGFloat number;
				CFNumberGetValue(value, numberType, &number);
				printf("%.f\n",number);
				break;
			};
			default: {
				break;
			};
		}
	}
	CFSafeRelease(numberType);
	
	CFStringRef arrayType = CFCopyTypeIDDescription(CFArrayGetTypeID());
	if (CFStringCompare(valueType, arrayType, 0x0) == kCFCompareEqualTo) {
		foundType = true;
		CFIndex count = CFArrayGetCount(value);
		printf("[\n");
		for (CFIndex i = 0x0; i < count; i++) {
			CFTypeRef item = CFArrayGetValueAtIndex(value, i);
			PrintDepth(depth+0x1,"");
			PrintCFTypeInternalFormat(item, depth+0x1);
		}
		PrintDepth(depth,"]\n");
	}
	CFSafeRelease(arrayType);
	
	if (!foundType) {
		CFStringRef description = CFCopyDescription(value);
		printf("%s\n",(char*)CFStringGetCStringPtr(description,kCFStringEncodingUTF8));
		CFSafeRelease(description);
	}
	
	CFSafeRelease(valueType);
}
static CFStringRef
_mechanism_copy_description(CFTypeRef value)
{
    mechanism_t mech = (mechanism_t)value;
    return CFCopyDescription(mech->data);
}
static void __deviceCallback(void * context, IOReturn result, void * sender, IOHIDDeviceRef device)
{
    boolean_t   terminated  = context == 0;
    CFStringRef debugString = CFCopyDescription(device);
    char * c_debug_string = NULL;
    
    if( debugString ){
        // DG: Bluetooth "Product" strings have Unicode encoding and no nul terminator and CFStringGetCStringPtr returns NULL
        // Need to manually copy to C string
        CFIndex length = CFStringGetLength(debugString);
        CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, CFStringGetSystemEncoding()) + 1;
        c_debug_string = (char *)malloc(maxSize);
        CFStringGetCString(debugString, c_debug_string, maxSize, CFStringGetSystemEncoding());
        CFRelease(debugString);
    }
    
    static CFMutableDictionaryRef s_timers = NULL;
    
    if ( !s_timers )
        s_timers = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    
    uint64_t uuid = 0;
    CFNumberRef temp = IOHIDDeviceGetProperty( device, CFSTR(kIOHIDUniqueIDKey) );
    if ( temp && CFGetTypeID(temp)  == CFNumberGetTypeID() ) CFNumberGetValue( temp, kCFNumberLongLongType, &uuid );
    CFNumberGetValue( IOHIDDeviceGetProperty( device, CFSTR(kIOHIDUniqueIDKey) ), kCFNumberLongLongType, &uuid );
    
    printf("%-10.10s: %s UniqueID %llu\n", terminated ? "terminated" : "matched", c_debug_string ? c_debug_string : "", uuid );
    
    if ( c_debug_string )
        free(c_debug_string);
    
    if ( terminated ) {
        CFDictionaryRemoveValue(gOutputElements, device);
        
        
        CFRunLoopTimerRef timer = (CFRunLoopTimerRef)CFDictionaryGetValue(s_timers, device);
        if ( timer ) {
            CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes);
        }
        CFDictionaryRemoveValue(s_timers, device);
        
    } else {
        CFArrayRef              outputElements  = NULL;
        CFMutableDictionaryRef  matching        = NULL;
        
        if ( gPrintDescriptor ) {
            CFDataRef descriptor = NULL;
            
            descriptor = IOHIDDeviceGetProperty(device, CFSTR(kIOHIDReportDescriptorKey));
            if ( descriptor ) {
                PrintHIDDescriptor(CFDataGetBytePtr(descriptor), CFDataGetLength(descriptor));
            }
        }
        
        if ( gPollInterval != 0.0 ) {
            CFRunLoopTimerContext   context = {.info=device};
            CFRunLoopTimerRef       timer   = CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent(), gPollInterval, 0, 0, __timerCallback, &context);
            
            CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes);
            
            CFDictionaryAddValue(s_timers, device, timer);
            CFRelease(timer);
            
            printf("Adding polling timer @ %4.6f s\n", gPollInterval);
        }
        
        matching = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
        if ( matching ) {
            uint32_t    value   = kIOHIDElementTypeOutput;
            CFNumberRef number  = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &value);
            
            if ( number ) {
                CFDictionarySetValue(matching, CFSTR(kIOHIDElementTypeKey), number);
                
                outputElements = IOHIDDeviceCopyMatchingElements(device, matching, 0);
                if ( outputElements ) {
                    CFDictionarySetValue(gOutputElements, device, outputElements);
                    CFRelease(outputElements);
                }
                
                CFRelease(number);
            }
            CFRelease(matching);
        }
    }
static void sendMessages(int howMany, SecOTRSessionRef *bobSession, SecOTRSessionRef *aliceSession, bool serialize)
{
    for(int count = howMany; count > 0; --count) {
        const char* aliceToBob = "aliceToBob";
        CFDataRef rawAliceToBob = CFDataCreate(kCFAllocatorDefault, (const uint8_t*)aliceToBob, (CFIndex) strlen(aliceToBob));
        CFMutableDataRef protectedAliceToBob = CFDataCreateMutable(kCFAllocatorDefault, 0);
        CFMutableDataRef bobDecode = CFDataCreateMutable(kCFAllocatorDefault, 0);

        ok_status(SecOTRSSignAndProtectMessage(*aliceSession, rawAliceToBob, protectedAliceToBob), "encode message");
        ok_status(SecOTRSVerifyAndExposeMessage(*bobSession, protectedAliceToBob, bobDecode), "Decode message");


        if (serialize) {
            serializeAndDeserialize(bobSession);
            serializeAndDeserialize(aliceSession);
        }

        ok(CFDataGetLength(rawAliceToBob) == CFDataGetLength(bobDecode)
           && 0 == memcmp(CFDataGetBytePtr(rawAliceToBob), CFDataGetBytePtr(bobDecode), (size_t)CFDataGetLength(rawAliceToBob)), "Didn't match!");

        CFReleaseNull(rawAliceToBob);
        CFReleaseNull(protectedAliceToBob);
        CFReleaseNull(bobDecode);

        const char* bobToAlice = "i liked your silly message from me to you";
        CFDataRef rawBobToAlice = CFDataCreate(kCFAllocatorDefault, (const uint8_t*)bobToAlice, (CFIndex) strlen(bobToAlice));
        CFMutableDataRef protectedBobToAlice = CFDataCreateMutable(kCFAllocatorDefault, 0);
        CFMutableDataRef aliceDecode = CFDataCreateMutable(kCFAllocatorDefault, 0);

        ok_status(SecOTRSSignAndProtectMessage(*aliceSession, rawBobToAlice, protectedBobToAlice), "encode reply");
        ok_status(SecOTRSVerifyAndExposeMessage(*bobSession, protectedBobToAlice, aliceDecode), "decode reply");

        if (serialize) {
            serializeAndDeserialize(bobSession);
            serializeAndDeserialize(aliceSession);
        }

        ok(CFDataGetLength(rawBobToAlice) == CFDataGetLength(aliceDecode)
           && 0 == memcmp(CFDataGetBytePtr(rawBobToAlice), CFDataGetBytePtr(aliceDecode), (size_t)CFDataGetLength(rawBobToAlice)), "reply matched");

        CFReleaseNull(rawAliceToBob);
        CFReleaseNull(rawBobToAlice);
        CFReleaseNull(protectedBobToAlice);
        CFReleaseNull(protectedAliceToBob);
        CFReleaseNull(aliceDecode);

        rawAliceToBob = CFDataCreate(kCFAllocatorDefault, (const uint8_t*)aliceToBob, (CFIndex) strlen(aliceToBob));
         protectedAliceToBob = CFDataCreateMutable(kCFAllocatorDefault, 0);
         bobDecode = CFDataCreateMutable(kCFAllocatorDefault, 0);

        ok_status(SecOTRSSignAndProtectMessage(*aliceSession, rawAliceToBob, protectedAliceToBob), "encode message");
        ok_status(SecOTRSVerifyAndExposeMessage(*bobSession, protectedAliceToBob, bobDecode), "Decode message");

        if (serialize) {
            serializeAndDeserialize(bobSession);
            serializeAndDeserialize(aliceSession);
        }

        ok(CFDataGetLength(rawAliceToBob) == CFDataGetLength(bobDecode)
           && 0 == memcmp(CFDataGetBytePtr(rawAliceToBob), CFDataGetBytePtr(bobDecode), (size_t)CFDataGetLength(rawAliceToBob)), "Didn't match!");

        CFReleaseNull(rawAliceToBob);
        CFReleaseNull(protectedAliceToBob);
        CFReleaseNull(bobDecode);

         bobToAlice = "i liked your silly message from me to you";
         rawBobToAlice = CFDataCreate(kCFAllocatorDefault, (const uint8_t*)bobToAlice, (CFIndex) strlen(bobToAlice));
         protectedBobToAlice = CFDataCreateMutable(kCFAllocatorDefault, 0);
         aliceDecode = CFDataCreateMutable(kCFAllocatorDefault, 0);

        ok_status(SecOTRSSignAndProtectMessage(*aliceSession, rawBobToAlice, protectedBobToAlice), "encode reply");
        ok_status(SecOTRSVerifyAndExposeMessage(*bobSession, protectedBobToAlice, aliceDecode), "decode reply");

        if (serialize) {
            serializeAndDeserialize(bobSession);
            serializeAndDeserialize(aliceSession);
        }

        ok(CFDataGetLength(rawBobToAlice) == CFDataGetLength(aliceDecode)
           && 0 == memcmp(CFDataGetBytePtr(rawBobToAlice), CFDataGetBytePtr(aliceDecode), (size_t)CFDataGetLength(rawBobToAlice)), "reply matched");

        CFReleaseNull(rawAliceToBob);
        CFReleaseNull(rawBobToAlice);
        CFReleaseNull(protectedBobToAlice);
        CFReleaseNull(protectedAliceToBob);
        CFReleaseNull(aliceDecode);



        CFStringRef stateString = CFCopyDescription(*bobSession);
        ok(stateString, "getting state from bob");
        CFReleaseNull(stateString);

        stateString = CFCopyDescription(*aliceSession);
        ok(stateString, "getting state from alice");
        CFReleaseNull(stateString);
    }
}