#ifndef _H_CSUTILITIES
#define _H_CSUTILITIES
#include <Security/Security.h>
#include <security_utilities/hashing.h>
#include <security_utilities/unix++.h>
#include <security_cdsa_utilities/cssmdata.h>
#include <copyfile.h>
#include <asl.h>
#include <cstdarg>
namespace Security {
namespace CodeSigning {
bool isAppleCA(SecCertificateRef cert);
bool isAppleCA(const Hashing::Byte *sha1);
void hashOfCertificate(const void *certData, size_t certLength, SHA1::Digest digest);
void hashOfCertificate(SecCertificateRef cert, SHA1::Digest digest);
bool verifyHash(SecCertificateRef cert, const Hashing::Byte *digest);
template <class _Hash>
size_t hashFileData(UnixPlusPlus::FileDesc fd, _Hash *hasher, size_t limit = 0)
{
unsigned char buffer[4096];
size_t total = 0;
for (;;) {
size_t size = sizeof(buffer);
if (limit && limit < size)
size = limit;
size_t got = fd.read(buffer, size);
total += got;
if (fd.atEnd())
break;
hasher->update(buffer, got);
if (limit && (limit -= got) == 0)
break;
}
return total;
}
template <class _Hash>
size_t hashFileData(const char *path, _Hash *hasher)
{
UnixPlusPlus::AutoFileDesc fd(path);
return hashFileData(fd, hasher);
}
bool certificateHasField(SecCertificateRef cert, const CSSM_OID &oid);
bool certificateHasPolicy(SecCertificateRef cert, const CSSM_OID &policyOid);
class Copyfile {
public:
Copyfile();
~Copyfile() { copyfile_state_free(mState); }
operator copyfile_state_t () const { return mState; }
void set(uint32_t flag, const void *value);
void get(uint32_t flag, void *value);
void operator () (const char *src, const char *dst, copyfile_flags_t flags);
private:
void check(int rc);
private:
copyfile_state_t mState;
};
class MessageTrace {
public:
MessageTrace(const char *domain, const char *signature);
void add(const char *key, const char *format, ...);
void send(const char *format, ...);
private:
aslmsg mAsl;
};
class UidGuard {
public:
UidGuard() : mPrevious(-1) { }
UidGuard(uid_t uid) : mPrevious(-1) { seteuid(uid); }
~UidGuard()
{
if (active())
UnixError::check(::seteuid(mPrevious));
}
bool seteuid(uid_t uid)
{
if (uid == geteuid())
return true; if (!active())
mPrevious = ::geteuid();
return ::seteuid(uid) == 0;
}
bool active() const { return mPrevious != uid_t(-1); }
operator bool () const { return active(); }
uid_t saved() const { assert(active()); return mPrevious; }
private:
uid_t mPrevious;
};
} }
#endif // !_H_CSUTILITIES