예제 #1
0
CFStringRef SDMMD_CreateUUID()
{
	CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
	CFStringRef str = CFUUIDCreateString(kCFAllocatorDefault, uuid);
	CFSafeRelease(uuid);
	return str;
}
예제 #2
0
static void get_uuid(char *str)
{
#ifdef HAVE_WINDOWS_H
    UUID guid;
    UuidCreate(&guid);
    sprintf(str, "%08lX-%04X-%04x-%02X%02X-%02X%02X%02X%02X%02X%02X",
	guid.Data1, guid.Data2, guid.Data3,
	guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
	guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
#elif defined(HAVE_CFUUIDCREATE)
    CFUUIDRef       myUUID;
    CFStringRef     myUUIDString;
    char            strBuffer[100];
    myUUID = CFUUIDCreate(kCFAllocatorDefault);
    myUUIDString = CFUUIDCreateString(kCFAllocatorDefault, myUUID);/* This is the safest way to obtain a C string from a CFString.*/
    CFStringGetCString(myUUIDString, str, SMPD_MAX_DBS_NAME_LEN, kCFStringEncodingASCII);
    CFRelease(myUUIDString);
#elif defined(HAVE_UUID_GENERATE)
    uuid_t guid;
    uuid_generate(guid);
    uuid_unparse(guid, str);
#else
    sprintf(str, "%X%X%X%X", rand(), rand(), rand(), rand());
#endif
}
예제 #3
0
int	main()
{
	CFUUIDRef uuid;
	CFStringRef str;
	char cstr[256];
	
	// create a new UUID
	uuid = CFUUIDCreate(NULL);
	
	// get string representation, as a CFString
	str = CFUUIDCreateString(NULL, uuid);
	
	// convert it to a C string
	CFStringGetCString(str, cstr, sizeof(cstr), kCFStringEncodingASCII);

	// print the C string
	printf("%s\n", cstr);

	// print in a form suitable for use in code, a call to CFUUIDGetConstantUUIDWithBytes
	printf("CFUUIDGetConstantUUIDWithBytes(NULL, ");
	CFUUIDBytes uib = CFUUIDGetUUIDBytes(uuid);
	Byte *p = &uib.byte0;
	for (int i = 0; i < 16; ++i) {
		printf("0x%02X", (int)*p++);
		if (i != 15)
			printf(", ");
	}
	printf(")\n");
	return 0;
}
예제 #4
0
	bool Semaphore::Create(vint initialCount, vint maxCount, const WString& name)
	{
		if (internalData) return false;
		if (initialCount > maxCount) return false;

		internalData = new SemaphoreData;
#if defined(__APPLE__)
        
		AString auuid;
		if(name.Length() == 0)
		{
			CFUUIDRef cfuuid = CFUUIDCreate(kCFAllocatorDefault);
			CFStringRef cfstr = CFUUIDCreateString(kCFAllocatorDefault, cfuuid);
			auuid = CFStringGetCStringPtr(cfstr, kCFStringEncodingASCII);

			CFRelease(cfstr);
			CFRelease(cfuuid);
		}
		auuid = auuid.Insert(0, "/");
		// OSX SEM_NAME_LENGTH = 31
		if(auuid.Length() >= 30)
			auuid = auuid.Sub(0, 30);
        
		if ((internalData->semNamed = sem_open(auuid.Buffer(), O_CREAT, O_RDWR, initialCount)) == SEM_FAILED)
		{
			delete internalData;
			internalData = 0;
			return false;
		}
        
#else
		if (name == L"")
		{
			if(sem_init(&internalData->semUnnamed, 0, (int)initialCount) == -1)
			{
				delete internalData;
				internalData = 0;
				return false;
			}
		}
        	else
        	{
			AString astr = wtoa(name);
            
			if ((internalData->semNamed = sem_open(astr.Buffer(), O_CREAT, 0777, initialCount)) == SEM_FAILED)
			{
				delete internalData;
				internalData = 0;
				return false;
			}
		}
#endif

		Release(initialCount);
		return true;
	}
예제 #5
0
TEST( CFPP_WriteStream, CTOR_AutoPointer )
{
    CF::WriteStream s1( CF::AutoPointer( CFWriteStreamCreateWithFile( NULL, CF::URL( "file:///etc/hosts" ) ) ) );
    CF::WriteStream s2( CF::AutoPointer( CFUUIDCreate( NULL ) ) );
    CF::WriteStream s3( CF::AutoPointer( NULL ) );
    
    ASSERT_TRUE(  s1.IsValid() );
    ASSERT_FALSE( s2.IsValid() );
    ASSERT_FALSE( s3.IsValid() );
}
예제 #6
0
파일: uuid.cpp 프로젝트: alyst/zorba
void uuid::create( uuid *result ) {
#if defined( __APPLE__ )
  CFUUIDRef uuid_ref = CFUUIDCreate( NULL );
  CFUUIDBytes uuid_bytes = CFUUIDGetUUIDBytes( uuid_ref );
  CFRelease( uuid_ref );
  ::memcpy( result->data, &uuid_bytes, sizeof result->data );
#elif defined( ZORBA_HAVE_UUID_H )
  uuid_generate( result->data );
#elif defined( _WIN32 )
  UuidCreateSequential( (UUID*)result->data );
#endif /* _WIN32 */
}
예제 #7
0
string Utils::get_uuid4() {
  CFUUIDRef cf_uuid_ref = CFUUIDCreate(kCFAllocatorDefault);
  CFStringRef cf_uuid_str_ref = CFUUIDCreateString(kCFAllocatorDefault, cf_uuid_ref);

  string uuid(CFStringGetCStringPtr(cf_uuid_str_ref, kCFStringEncodingUTF8));
  transform(uuid.begin(), uuid.end(), uuid.begin(), ::tolower);

  CFRelease(cf_uuid_ref);
  CFRelease(cf_uuid_str_ref);

  return uuid;
}
예제 #8
0
cc_int32 cci_os_identifier_new_uuid (cci_uuid_string_t *out_uuid_string)
{
    cc_int32 err = ccNoError;
    cci_uuid_string_t uuid_string = NULL;
    CFUUIDRef uuid = NULL;
    CFStringRef uuid_stringref = NULL;
    CFStringEncoding encoding = kCFStringEncodingUTF8;
    CFIndex length = 0;

    if (!out_uuid_string) { err = cci_check_error (ccErrBadParam); }

    if (!err) {
        uuid = CFUUIDCreate (kCFAllocatorDefault);
        if (!uuid) { err = cci_check_error (ccErrNoMem); }
    }

    if (!err) {
        uuid_stringref = CFUUIDCreateString (kCFAllocatorDefault, uuid);
        if (!uuid_stringref) { err = cci_check_error (ccErrNoMem); }
    }

    if (!err) {
        length = CFStringGetMaximumSizeForEncoding (CFStringGetLength (uuid_stringref),
                                                    encoding) + 1;

        uuid_string = malloc (length);
        if (!uuid_string) { err = cci_check_error (ccErrNoMem); }
    }

    if (!err) {
        if (!CFStringGetCString (uuid_stringref, uuid_string, length, encoding)) {
            err = cci_check_error (ccErrNoMem);
        }
    }

    if (!err) {
        *out_uuid_string = uuid_string;
        uuid_string = NULL; /* take ownership */
    }

    if (uuid_string   ) { free (uuid_string); }
    if (uuid_stringref) { CFRelease (uuid_stringref); }
    if (uuid          ) { CFRelease (uuid); }

    return cci_check_error (err);
}
예제 #9
0
TEST( CFPP_WriteStream, OperatorAssignAutoPointer )
{
    CF::WriteStream s1;
    CF::WriteStream s2( CF::URL( "file:///etc/hosts" ) );
    CF::WriteStream s3( CF::URL( "file:///etc/hosts" ) );
    
    ASSERT_FALSE( s1.IsValid() );
    ASSERT_TRUE(  s2.IsValid() );
    ASSERT_TRUE(  s3.IsValid() );
    
    s1 = CF::AutoPointer( CFWriteStreamCreateWithFile( NULL, CF::URL( "file:///etc/hosts" ) ) );
    s2 = CF::AutoPointer( CFUUIDCreate( NULL ) );
    s3 = CF::AutoPointer( NULL );
    
    ASSERT_TRUE(  s1.IsValid() );
    ASSERT_FALSE( s2.IsValid() );
    ASSERT_FALSE( s3.IsValid() );
}
예제 #10
0
String createCanonicalUUIDString()
{
#if PLATFORM(QT)
    QUuid uuid = QUuid::createUuid();
    String canonicalUuidStr = uuid.toString().mid(1, 36).toLower(); // remove opening and closing bracket and make it lower.
    ASSERT(canonicalUuidStr[uuidVersionIdentifierIndex] == uuidVersionRequired);
    return canonicalUuidStr;
#elif OS(WINDOWS)
    GUID uuid = { 0 };
    HRESULT hr = CoCreateGuid(&uuid);
    if (FAILED(hr))
        return String();
    wchar_t uuidStr[40];
    int num = StringFromGUID2(uuid, reinterpret_cast<LPOLESTR>(uuidStr), ARRAYSIZE(uuidStr));
    ASSERT(num == 39);
    String canonicalUuidStr = String(uuidStr + 1, num - 3).lower(); // remove opening and closing bracket and make it lower.
    ASSERT(canonicalUuidStr[uuidVersionIdentifierIndex] == uuidVersionRequired);
    return canonicalUuidStr;
#elif OS(DARWIN)
    CFUUIDRef uuid = CFUUIDCreate(0);
    CFStringRef uuidStrRef = CFUUIDCreateString(0, uuid);
    String uuidStr(uuidStrRef);
    CFRelease(uuidStrRef);
    CFRelease(uuid);
    String canonicalUuidStr = uuidStr.lower(); // make it lower.
    ASSERT(canonicalUuidStr[uuidVersionIdentifierIndex] == uuidVersionRequired);
    return canonicalUuidStr;
#elif OS(LINUX)
    FILE* fptr = fopen("/proc/sys/kernel/random/uuid", "r");
    if (!fptr)
        return String();
    char uuidStr[37];
    char* result = fgets(uuidStr, sizeof(uuidStr), fptr);
    fclose(fptr);
    if (!result)
        return String();
    String canonicalUuidStr = String(uuidStr).lower(); // make it lower.
    ASSERT(canonicalUuidStr[uuidVersionIdentifierIndex] == uuidVersionRequired);
    return canonicalUuidStr;
#else
    notImplemented();
    return String();
#endif
}
예제 #11
0
/* Generates a UUID. The original version is truncated, so this is not 100%
 * guaranteed to be unique. However, the `PBXObject#generate_uuid` method
 * checks that the UUID does not exist yet, in the project, before using it.
 *
 * @note Meant for internal use only.
 *
 * @return [String] A 24 characters long UUID.
 */
static VALUE
generate_uuid(void) {
  CFUUIDRef uuid = CFUUIDCreate(NULL);
  CFStringRef strRef = CFUUIDCreateString(NULL, uuid);
  CFRelease(uuid);

  CFArrayRef components = CFStringCreateArrayBySeparatingStrings(NULL, strRef, CFSTR("-"));
  CFRelease(strRef);
  strRef = CFStringCreateByCombiningStrings(NULL, components, CFSTR(""));
  CFRelease(components);

  UniChar buffer[24];
  CFStringGetCharacters(strRef, CFRangeMake(0, 24), buffer);
  CFStringRef strRef2 = CFStringCreateWithCharacters(NULL, buffer, 24);

  VALUE str = cfstr_to_str(strRef2);
  CFRelease(strRef);
  CFRelease(strRef2);
  return str;
}
예제 #12
0
// Generate a unique user ID.  We're using a GUID form,
// but not jumping through hoops to make it cryptographically
// secure.  We just want it to distinguish unique users.
static nsresult
InitUserID(nsACString& aUserID)
{
  nsID id;

  // copied shamelessly from nsUUIDGenerator.cpp
#if defined(XP_WIN)
  HRESULT hr = CoCreateGuid((GUID*)&id);
  if (NS_FAILED(hr))
    return NS_ERROR_FAILURE;
#elif defined(XP_MACOSX)
  CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
  if (!uuid)
    return NS_ERROR_FAILURE;

  CFUUIDBytes bytes = CFUUIDGetUUIDBytes(uuid);
  memcpy(&id, &bytes, sizeof(nsID));

  CFRelease(uuid);
#else
  // UNIX or some such thing
  id.m0 = random();
  id.m1 = random();
  id.m2 = random();
  *reinterpret_cast<PRUint32*>(&id.m3[0]) = random();
  *reinterpret_cast<PRUint32*>(&id.m3[4]) = random();
#endif

  char* id_cstr = id.ToString();
  NS_ENSURE_TRUE(id_cstr, NS_ERROR_OUT_OF_MEMORY);
  nsDependentCString id_str(id_cstr);
  aUserID = Substring(id_str, 1, id_str.Length()-2);

  PR_Free(id_cstr);
  return NS_OK;
}
bool PolicyEngine::temporarySigning(SecStaticCodeRef code, AuthorityType type, CFURLRef path, SecAssessmentFlags matchFlags)
{
	if (matchFlags == 0) {	// playback; consult authority table for matches
		DiskRep *rep = SecStaticCode::requiredStatic(code)->diskRep();
		std::string screen;
		if (CFRef<CFDataRef> info = rep->component(cdInfoSlot)) {
			SHA1 hash;
			hash.update(CFDataGetBytePtr(info), CFDataGetLength(info));
			screen = createWhitelistScreen('I', hash);
		} else if (rep->mainExecutableImage()) {
			screen = "N";
		} else {
			SHA1 hash;
			hashFileData(rep->mainExecutablePath().c_str(), &hash);
			screen = createWhitelistScreen('M', hash);
		}
		SQLite::Statement query(*this,
			"SELECT flags FROM authority "
			"WHERE type = :type"
			" AND NOT flags & :flag"
			" AND CASE WHEN filter_unsigned IS NULL THEN remarks = :remarks ELSE filter_unsigned = :screen END");
		query.bind(":type").integer(type);
		query.bind(":flag").integer(kAuthorityFlagDefault);
		query.bind(":screen") = screen;
		query.bind(":remarks") = cfString(path);
		if (!query.nextRow())	// guaranteed no matching rule
			return false;
		matchFlags = SQLite3::int64(query[0]);
	}

	try {
		// ad-hoc sign the code and attach the signature
		CFRef<CFDataRef> signature = CFDataCreateMutable(NULL, 0);
		CFTemp<CFDictionaryRef> arguments("{%O=%O, %O=#N}", kSecCodeSignerDetached, signature.get(), kSecCodeSignerIdentity);
		CFRef<SecCodeSignerRef> signer;
		MacOSError::check(SecCodeSignerCreate(arguments, (matchFlags & kAuthorityFlagWhitelistV2) ? kSecCSSignOpaque : kSecCSSignV1, &signer.aref()));
		MacOSError::check(SecCodeSignerAddSignature(signer, code, kSecCSDefaultFlags));
		MacOSError::check(SecCodeSetDetachedSignature(code, signature, kSecCSDefaultFlags));
		
		SecRequirementRef dr = NULL;
		SecCodeCopyDesignatedRequirement(code, kSecCSDefaultFlags, &dr);
		CFStringRef drs = NULL;
		SecRequirementCopyString(dr, kSecCSDefaultFlags, &drs);

		// if we're in GKE recording mode, save that signature and report its location
		if (SYSPOLICY_RECORDER_MODE_ENABLED()) {
			int status = recorder_code_unable;	// ephemeral signature (not recorded)
			if (geteuid() == 0) {
				CFRef<CFUUIDRef> uuid = CFUUIDCreate(NULL);
				std::string sigfile = RECORDER_DIR + cfStringRelease(CFUUIDCreateString(NULL, uuid)) + ".tsig";
				try {
					UnixPlusPlus::AutoFileDesc fd(sigfile, O_WRONLY | O_CREAT);
					fd.write(CFDataGetBytePtr(signature), CFDataGetLength(signature));
					status = recorder_code_adhoc;	// recorded signature
					SYSPOLICY_RECORDER_MODE_ADHOC_PATH(cfString(path).c_str(), type, sigfile.c_str());
				} catch (...) { }
			}

			// now report the D probe itself
			CFRef<CFDictionaryRef> info;
			MacOSError::check(SecCodeCopySigningInformation(code, kSecCSDefaultFlags, &info.aref()));
			CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
			SYSPOLICY_RECORDER_MODE(cfString(path).c_str(), type, "",
				cdhash ? CFDataGetBytePtr(cdhash) : NULL, status);
		}
		
		return true;	// it worked; we're now (well) signed
	} catch (...) { }
	
	return false;
}
예제 #14
0
//
// Executable code.
// Read from disk, evaluate properly, cache as indicated. The whole thing, so far.
//
void PolicyEngine::evaluateCode(CFURLRef path, AuthorityType type, SecAssessmentFlags flags, CFDictionaryRef context, CFMutableDictionaryRef result,
	bool handleUnsignedCode /* = true */)
{
	FileQuarantine qtn(cfString(path).c_str());
	if (qtn.flag(QTN_FLAG_HARD))
		MacOSError::throwMe(errSecCSFileHardQuarantined);
	
	CFRef<SecStaticCodeRef> code;
	MacOSError::check(SecStaticCodeCreateWithPath(path, kSecCSDefaultFlags, &code.aref()));
	OSStatus rc = noErr;	// last validation error
	
	const SecCSFlags validationFlags = kSecCSEnforceRevocationChecks;
	
	WhitelistPrescreen whitelistScreen(code); // pre-screening filter for whitelist pre-screening (only)

	SQLite::Statement query(*this,
		"SELECT allow, requirement, id, label, expires, flags, disabled, filter_unsigned, remarks FROM scan_authority"
		" WHERE type = :type"
		" ORDER BY priority DESC;");
	query.bind(":type").integer(type);
	SQLite3::int64 latentID = 0;		// first (highest priority) disabled matching ID
	std::string latentLabel;			// ... and associated label, if any
	while (query.nextRow()) {
		bool allow = int(query[0]);
		const char *reqString = query[1];
		SQLite3::int64 id = query[2];
		const char *label = query[3];
		double expires = query[4];
		sqlite3_int64 ruleFlags = query[5];
		SQLite3::int64 disabled = query[6];
		const char *filter = query[7];
		const char *remarks = query[8];
		
		CFRef<SecRequirementRef> requirement;
		MacOSError::check(SecRequirementCreateWithString(CFTempString(reqString), kSecCSDefaultFlags, &requirement.aref()));
		rc = SecStaticCodeCheckValidity(code, validationFlags, requirement);
		
		// ad-hoc sign unsigned code, skip of Gatekeeper is off or the rule is disabled; but always do it for whitelist recording
		if (rc == errSecCSUnsigned && handleUnsignedCode && (!(disabled || overrideAssessment()) || SYSPOLICY_RECORDER_MODE_ENABLED())) {
			if (!SYSPOLICY_RECORDER_MODE_ENABLED()) {
				// apply whitelist pre-screening to speed things up for non-matches
				if (ruleFlags & kAuthorityFlagDefault)	// can't ever match standard rules with unsigned code
					continue;
				if (whitelistScreen.reject(filter, remarks))	// apply whitelist pre-filter
					continue;
			}
			try {
				// ad-hoc sign the code and attach the signature
				CFRef<CFDataRef> signature = CFDataCreateMutable(NULL, 0);
				CFTemp<CFDictionaryRef> arguments("{%O=%O, %O=#N}", kSecCodeSignerDetached, signature.get(), kSecCodeSignerIdentity);
				CFRef<SecCodeSignerRef> signer;
				MacOSError::check(SecCodeSignerCreate(arguments, kSecCSDefaultFlags, &signer.aref()));
				MacOSError::check(SecCodeSignerAddSignature(signer, code, kSecCSDefaultFlags));
				MacOSError::check(SecCodeSetDetachedSignature(code, signature, kSecCSDefaultFlags));
								
				// if we're in GKE recording mode, save that signature and report its location
				if (SYSPOLICY_RECORDER_MODE_ENABLED()) {
					int status = recorder_code_unable;	// ephemeral signature (not recorded)
					if (geteuid() == 0) {
						CFRef<CFUUIDRef> uuid = CFUUIDCreate(NULL);
						std::string sigfile = RECORDER_DIR + cfStringRelease(CFUUIDCreateString(NULL, uuid)) + ".tsig";
						try {
							UnixPlusPlus::AutoFileDesc fd(sigfile, O_WRONLY | O_CREAT);
							fd.write(CFDataGetBytePtr(signature), CFDataGetLength(signature));
							status = recorder_code_adhoc;	// recorded signature
							SYSPOLICY_RECORDER_MODE_ADHOC_PATH(cfString(path).c_str(), type, sigfile.c_str());
						} catch (...) { }
					}

					// now report the D probe itself
					CFRef<CFDictionaryRef> info;
					MacOSError::check(SecCodeCopySigningInformation(code, kSecCSDefaultFlags, &info.aref()));
					CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
					SYSPOLICY_RECORDER_MODE(cfString(path).c_str(), type, "",
						cdhash ? CFDataGetBytePtr(cdhash) : NULL, status);
				}
				
				// rerun the validation to update state
				rc = SecStaticCodeCheckValidity(code, validationFlags | kSecCSBasicValidateOnly, requirement);
			} catch (...) { }
		}

		switch (rc) {
		case noErr: // well signed and satisfies requirement...
			break;	// ... continue below
		case errSecCSSignatureFailed:
			if (!codeInvalidityExceptions(code, result)) {
				if (SYSPOLICY_ASSESS_OUTCOME_BROKEN_ENABLED())
					SYSPOLICY_ASSESS_OUTCOME_BROKEN(cfString(path).c_str(), type, false);
				MacOSError::throwMe(rc);
			}
			if (SYSPOLICY_ASSESS_OUTCOME_BROKEN_ENABLED())
				SYSPOLICY_ASSESS_OUTCOME_BROKEN(cfString(path).c_str(), type, true);
			// treat as unsigned to fix problems in the field
		case errSecCSUnsigned:
			if (handleUnsignedCode) {
				cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict);
				addAuthority(result, "no usable signature");
			}
			return;
		case errSecCSReqFailed: // requirement missed, but otherwise okay
			continue;
		default: // broken in some way; all tests will fail like this so bail out
			MacOSError::throwMe(rc);
		}
		if (disabled) {
			if (latentID == 0) {
				latentID = id;
				if (label)
					latentLabel = label;
			}
			continue;	// the loop
		}
	
		CFRef<CFDictionaryRef> info;	// as needed
		if (flags & kSecAssessmentFlagRequestOrigin) {
			if (!info)
				MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
			if (CFArrayRef chain = CFArrayRef(CFDictionaryGetValue(info, kSecCodeInfoCertificates)))
				setOrigin(chain, result);
		}
		if (!(ruleFlags & kAuthorityFlagInhibitCache) && !(flags & kSecAssessmentFlagNoCache)) {	// cache inhibit
			if (!info)
				MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
			if (SecTrustRef trust = SecTrustRef(CFDictionaryGetValue(info, kSecCodeInfoTrust))) {
				CFRef<CFDictionaryRef> xinfo;
				MacOSError::check(SecTrustCopyExtendedResult(trust, &xinfo.aref()));
				if (CFDateRef limit = CFDateRef(CFDictionaryGetValue(xinfo, kSecTrustExpirationDate))) {
					this->recordOutcome(code, allow, type, min(expires, dateToJulian(limit)), id);
				}
			}
		}
		if (allow) {
			if (SYSPOLICY_ASSESS_OUTCOME_ACCEPT_ENABLED()) {
				if (!info)
					MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
				CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
				SYSPOLICY_ASSESS_OUTCOME_ACCEPT(cfString(path).c_str(), type, label, cdhash ? CFDataGetBytePtr(cdhash) : NULL);
			}
		} else {
			if (SYSPOLICY_ASSESS_OUTCOME_DENY_ENABLED() || SYSPOLICY_RECORDER_MODE_ENABLED()) {
				if (!info)
					MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
				CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
				std::string cpath = cfString(path);
				const void *hashp = cdhash ? CFDataGetBytePtr(cdhash) : NULL;
				SYSPOLICY_ASSESS_OUTCOME_DENY(cpath.c_str(), type, label, hashp);
				SYSPOLICY_RECORDER_MODE(cpath.c_str(), type, label, hashp, recorder_code_untrusted);
			}
		}
		cfadd(result, "{%O=%B}", kSecAssessmentAssessmentVerdict, allow);
		addAuthority(result, label, id);
		return;
	}

	if (rc == errSecCSUnsigned) {	// skipped all applicable rules due to pre-screening
		cfadd(result, "{%O=#F}", kSecAssessmentAssessmentVerdict);
		addAuthority(result, "no usable signature");
		return;
	}
	
	// no applicable authority (but signed, perhaps temporarily). Deny by default
	CFRef<CFDictionaryRef> info;
	MacOSError::check(SecCodeCopySigningInformation(code, kSecCSSigningInformation, &info.aref()));
	if (flags & kSecAssessmentFlagRequestOrigin) {
		if (CFArrayRef chain = CFArrayRef(CFDictionaryGetValue(info, kSecCodeInfoCertificates)))
			setOrigin(chain, result);
	}
	if (SYSPOLICY_ASSESS_OUTCOME_DEFAULT_ENABLED() || SYSPOLICY_RECORDER_MODE_ENABLED()) {
		CFDataRef cdhash = CFDataRef(CFDictionaryGetValue(info, kSecCodeInfoUnique));
		const void *hashp = cdhash ? CFDataGetBytePtr(cdhash) : NULL;
		std::string cpath = cfString(path);
		SYSPOLICY_ASSESS_OUTCOME_DEFAULT(cpath.c_str(), type, latentLabel.c_str(), hashp);
		SYSPOLICY_RECORDER_MODE(cpath.c_str(), type, latentLabel.c_str(), hashp, 0);
	}
	if (!(flags & kSecAssessmentFlagNoCache))
		this->recordOutcome(code, false, type, this->julianNow() + NEGATIVE_HOLD, latentID);
	cfadd(result, "{%O=%B}", kSecAssessmentAssessmentVerdict, false);
	addAuthority(result, latentLabel.c_str(), latentID);
}
예제 #15
0
파일: dump.c 프로젝트: aosm/Heimdal
static krb5_error_code
od_dump_entry(krb5_context kcontext, HDB *db, hdb_entry_ex *entry, void *data)
{
    CFErrorRef error = NULL;
    CFDictionaryRef dict;
    CFStringRef fn, uuidstr;
    CFUUIDRef uuid;
    CFURLRef url;

    dict = HeimODDumpHdbEntry(&entry->entry, &error);
    if (dict == NULL) {
	if (error)
	    CFRelease(error);
	return 0;
    }

    uuid = CFUUIDCreate(NULL);
    if (uuid == NULL) {
	krb5_warnx(kcontext, "out of memory");
        CFRelease(dict);
	return 0;
    }
    
    uuidstr = CFUUIDCreateString(NULL, uuid);
    CFRelease(uuid);
    if (uuidstr == NULL) {
	krb5_warnx(kcontext, "out of memory");
        CFRelease(dict);
	return 0;
    }

    fn = CFStringCreateWithFormat(NULL, NULL, CFSTR("%s/%@.plist"), (char *)data, uuidstr);
    CFRelease(uuidstr);
    if (fn == NULL) {
	krb5_warnx(kcontext, "out of memory");
        CFRelease(dict);
	return 0;
    }

    url = CFURLCreateWithFileSystemPath(NULL, fn,  kCFURLPOSIXPathStyle, false);
    CFRelease(fn);
    if (url == NULL) {
	krb5_warnx(kcontext, "out of memory");
        CFRelease(dict);
	return 0;
    }

    CFDataRef xmldata = CFPropertyListCreateData(NULL, dict, kCFPropertyListXMLFormat_v1_0, 0, NULL);
    CFRelease(dict);
    if (xmldata == NULL) {
	CFRelease(url);
	krb5_warnx(kcontext, "out of memory");
	return 0;
    }

    CFWriteStreamRef stream = CFWriteStreamCreateWithFile(NULL, url);
    if (stream) {
	if (CFWriteStreamOpen(stream))
	    CFWriteStreamWrite(stream, CFDataGetBytePtr(xmldata), CFDataGetLength(xmldata));
	CFWriteStreamClose(stream);
	CFRelease(stream);
    }

    CFRelease(url);
    CFRelease(xmldata);

    return 0;
}
static void testkeywrap(unsigned long keySizeInBits, CFTypeRef alg)
{
    SecKeyRef pubKey = NULL, privKey = NULL;
    size_t keySizeInBytes = (keySizeInBits + 7) / 8;
    CFNumberRef kzib;
    int32_t keysz32 = (int32_t)keySizeInBits;

    CFUUIDRef ourUUID = CFUUIDCreate(kCFAllocatorDefault);
    CFStringRef uuidString = CFUUIDCreateString(kCFAllocatorDefault, ourUUID);
    CFMutableStringRef publicName = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, uuidString);
    CFMutableStringRef privateName = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, uuidString);

    CFReleaseNull(ourUUID);
    CFReleaseNull(uuidString);

    CFStringAppend(publicName, CFSTR("-Public-41"));
    CFStringAppend(privateName, CFSTR("-Private-41"));

    CFDictionaryRef pubd = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
                                                        kSecAttrLabel, publicName,
                                                        NULL);
    CFDictionaryRef privd = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
                                                         kSecAttrLabel, privateName,
                                                         NULL);

    CFReleaseNull(publicName);
    CFReleaseNull(privateName);

    kzib = CFNumberCreate(NULL, kCFNumberSInt32Type, &keysz32);
    CFDictionaryRef kgp = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
                                                       kSecAttrKeyType, kSecAttrKeyTypeEC,
                                                       kSecAttrKeySizeInBits, kzib,
                                                       kSecAttrIsPermanent, kCFBooleanFalse,
                                                       kSecPublicKeyAttrs, pubd,
                                                       kSecPrivateKeyAttrs, privd,
                                                       NULL);
    CFReleaseNull(pubd);
    CFReleaseNull(privd);
    CFReleaseNull(kzib);

    OSStatus status;
    ok_status(status = SecKeyGeneratePair(kgp, &pubKey, &privKey),
              "Generate %ld bit (%ld byte) persistent RSA keypair (status = %d)",
              keySizeInBits, keySizeInBytes, (int)status);
    CFReleaseNull(kgp);

    CFErrorRef localError;

    CFDataRef secret = CFDataCreate(NULL, (void *)"0123456789012345", 16);
    ok(secret, "secret");

    CFDataRef fp = CFDataCreate(NULL, (void *)"01234567890123456789", 20);
    ok(fp, "fingerprint");


    int8_t sym_alg_data = 8;
    CFNumberRef symalg = CFNumberCreate(NULL, kCFNumberSInt8Type, &sym_alg_data);
    CFDictionaryRef param = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
                                                         _kSecKeyWrapPGPWrapAlg, alg,
                                                         _kSecKeyWrapPGPSymAlg, symalg,
                                                         _kSecKeyWrapPGPFingerprint, fp,
                                                         NULL);

    CFDataRef wrapped = _SecKeyCopyWrapKey(pubKey, kSecKeyWrapPublicKeyPGP, secret, param, NULL, &localError);
    ok(wrapped, "wrap key: %@", localError);

    CFDataRef unwrapped = _SecKeyCopyUnwrapKey(privKey, kSecKeyWrapPublicKeyPGP, wrapped, param, NULL, &localError);
    ok(unwrapped, "unwrap key: %@", localError);

    CFReleaseNull(symalg);

    ok(CFEqual(unwrapped, secret), "keys still same");

    CFReleaseNull(fp);
    CFReleaseNull(secret);
    CFReleaseNull(unwrapped);
    CFReleaseNull(wrapped);
    CFReleaseNull(param);
    CFReleaseNull(privKey);
    CFReleaseNull(pubKey);
}
static void testkeygen2(size_t keySizeInBits) {
	SecKeyRef pubKey = NULL, privKey = NULL;
	size_t keySizeInBytes = (keySizeInBits + 7) / 8;
	CFNumberRef kzib;
    int32_t keysz32 = (int32_t)keySizeInBits;

    CFUUIDRef ourUUID = CFUUIDCreate(kCFAllocatorDefault);
    CFStringRef uuidString = CFUUIDCreateString(kCFAllocatorDefault, ourUUID);
    CFMutableStringRef publicName = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, uuidString);
    CFMutableStringRef privateName = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, uuidString);

    CFReleaseNull(ourUUID);
    CFReleaseNull(uuidString);

    CFStringAppend(publicName, CFSTR("-Public-41"));
    CFStringAppend(privateName, CFSTR("-Private-41"));

    CFMutableDictionaryRef pubd = CFDictionaryCreateMutableForCFTypesWith(kCFAllocatorDefault,
                                                                          kSecAttrLabel, publicName,
                                                                          NULL);
    CFMutableDictionaryRef privd = CFDictionaryCreateMutableForCFTypesWith(kCFAllocatorDefault,
                                                                           kSecAttrLabel, privateName,
                                                                           NULL);

	kzib = CFNumberCreate(NULL, kCFNumberSInt32Type, &keysz32);
    CFDictionaryRef kgp = CFDictionaryCreateForCFTypes(kCFAllocatorDefault,
                                                       kSecAttrKeyType, kSecAttrKeyTypeEC,
                                                       kSecAttrKeySizeInBits, kzib,
                                                       kSecAttrIsPermanent, kCFBooleanTrue,
                                                       kSecPublicKeyAttrs, pubd,
                                                       kSecPrivateKeyAttrs, privd,
                                                       NULL);

    CFReleaseNull(kzib);

	OSStatus status;
	ok_status(status = SecKeyGeneratePair(kgp, &pubKey, &privKey),
              "Generate %ld bit (%ld byte) persistent RSA keypair",
              keySizeInBits, keySizeInBytes);

    CFReleaseNull(kgp);

SKIP: {
    skip("keygen failed", 8, status == errSecSuccess);
    ok(pubKey, "pubkey returned");
    ok(privKey, "privKey returned");
    is(SecKeyGetSize(pubKey, kSecKeyKeySizeInBits), (size_t) keySizeInBits, "public key size is ok");
    is(SecKeyGetSize(privKey, kSecKeyKeySizeInBits), (size_t) keySizeInBits, "private key size is ok");

    SecKeyRef pubKey2, privKey2;
    CFDictionaryAddValue(pubd, kSecClass, kSecClassKey);
    CFDictionaryAddValue(pubd, kSecReturnRef, kCFBooleanTrue);
    CFDictionaryAddValue(privd, kSecClass, kSecClassKey);
    CFDictionaryAddValue(privd, kSecReturnRef, kCFBooleanTrue);
    CFDictionaryAddValue(privd, kSecAttrCanSign, kCFBooleanTrue);
    ok_status(SecItemCopyMatching(pubd, (CFTypeRef *)&pubKey2),
              "retrieve pub key by label");
    ok(pubKey2, "got valid object");
    ok_status(SecItemCopyMatching(privd, (CFTypeRef *)&privKey2),
              "retrieve priv key by label and kSecAttrCanSign");
    ok(privKey2, "got valid object");

    /* Sign something. */
    uint8_t something[20] = {0x80, 0xbe, 0xef, 0xba, 0xd0, };
    size_t sigLen = SecKeyGetSize(privKey2, kSecKeySignatureSize);
    uint8_t sig[sigLen];
    ok_status(SecKeyRawSign(privKey2, kSecPaddingPKCS1,
                            something, sizeof(something), sig, &sigLen), "sign something");
    ok_status(SecKeyRawVerify(pubKey2, kSecPaddingPKCS1,
                              something, sizeof(something), sig, sigLen), "verify sig on something");

    /* Cleanup. */
    CFReleaseNull(pubKey2);
    CFReleaseNull(privKey2);
}

    /* delete from keychain - note: do it before releasing publicName and privateName
       because pubd and privd have no retain/release callbacks */
    ok_status(SecItemDelete(pubd), "delete generated pub key");
    ok_status(SecItemDelete(privd), "delete generated priv key");

	/* Cleanup. */
	CFReleaseNull(pubKey);
	CFReleaseNull(privKey);

    CFReleaseNull(publicName);
    CFReleaseNull(privateName);

	CFReleaseNull(pubd);
	CFReleaseNull(privd);
}
예제 #18
0
NS_IMETHODIMP
nsUUIDGenerator::GenerateUUIDInPlace(nsID* id)
{
    // The various code in this method is probably not threadsafe, so lock
    // across the whole method.
    nsAutoLock lock(mLock);

#if defined(WINCE)
    // WINCE only has CoCreateGuid if DCOM support is compiled into the BSP;
    // there's usually very little reason for DCOM to be present!

    if (!CeGenRandom(sizeof(nsID), (BYTE*) id))
        return NS_ERROR_FAILURE;

    /* Put in the version */
    id->m2 &= 0x0fff;
    id->m2 |= 0x4000;

    /* Put in the variant */
    id->m3[0] &= 0x3f;
    id->m3[0] |= 0x80;

#elif defined(XP_WIN)
    HRESULT hr = CoCreateGuid((GUID*)id);
    if (NS_FAILED(hr))
        return NS_ERROR_FAILURE;
#elif defined(XP_MACOSX)
    CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
    if (!uuid)
        return NS_ERROR_FAILURE;

    CFUUIDBytes bytes = CFUUIDGetUUIDBytes(uuid);
    memcpy(id, &bytes, sizeof(nsID));

    CFRelease(uuid);
#else /* not windows or OS X; generate randomness using random(). */
    /* XXX we should be saving the return of setstate here and switching
     * back to it; instead, we use the value returned when we called
     * initstate, since older glibc's have broken setstate() return values
     */
#ifndef ANDROID
    setstate(mState);
#endif

    PRSize bytesLeft = sizeof(nsID);
    while (bytesLeft > 0) {
#ifdef ANDROID
        long rval = arc4random();
        const int mRBytes = 4;
#else
        long rval = random();
#endif


        PRUint8 *src = (PRUint8*)&rval;
        // We want to grab the mRBytes least significant bytes of rval, since
        // mRBytes less than sizeof(rval) means the high bytes are 0.
#ifdef IS_BIG_ENDIAN
        src += sizeof(rval) - mRBytes;
#endif
        PRUint8 *dst = ((PRUint8*) id) + (sizeof(nsID) - bytesLeft);
        PRSize toWrite = (bytesLeft < mRBytes ? bytesLeft : mRBytes);
        for (PRSize i = 0; i < toWrite; i++)
            dst[i] = src[i];

        bytesLeft -= toWrite;
    }

    /* Put in the version */
    id->m2 &= 0x0fff;
    id->m2 |= 0x4000;

    /* Put in the variant */
    id->m3[0] &= 0x3f;
    id->m3[0] |= 0x80;

#ifndef ANDROID
    /* Restore the previous RNG state */
    setstate(mSavedState);
#endif
#endif

    return NS_OK;
}