Пример #1
0
static void
carp_hmac_prepare(struct carp_softc *sc)
{
	uint8_t version = CARP_VERSION, type = CARP_ADVERTISEMENT;
	uint8_t vhid = sc->sc_vhid & 0xff;
	struct ifaddr *ifa;
	int i, found;
#ifdef INET
	struct in_addr last, cur, in;
#endif
#ifdef INET6
	struct in6_addr last6, cur6, in6;
#endif

	CARP_LOCK_ASSERT(sc);

	/* Compute ipad from key. */
	bzero(sc->sc_pad, sizeof(sc->sc_pad));
	bcopy(sc->sc_key, sc->sc_pad, sizeof(sc->sc_key));
	for (i = 0; i < sizeof(sc->sc_pad); i++)
		sc->sc_pad[i] ^= 0x36;

	/* Precompute first part of inner hash. */
	SHA1Init(&sc->sc_sha1);
	SHA1Update(&sc->sc_sha1, sc->sc_pad, sizeof(sc->sc_pad));
	SHA1Update(&sc->sc_sha1, (void *)&version, sizeof(version));
	SHA1Update(&sc->sc_sha1, (void *)&type, sizeof(type));
	SHA1Update(&sc->sc_sha1, (void *)&vhid, sizeof(vhid));
#ifdef INET
	cur.s_addr = 0;
	do {
		found = 0;
		last = cur;
		cur.s_addr = 0xffffffff;
		CARP_FOREACH_IFA(sc, ifa) {
			in.s_addr = ifatoia(ifa)->ia_addr.sin_addr.s_addr;
			if (ifa->ifa_addr->sa_family == AF_INET &&
			    ntohl(in.s_addr) > ntohl(last.s_addr) &&
			    ntohl(in.s_addr) < ntohl(cur.s_addr)) {
				cur.s_addr = in.s_addr;
				found++;
			}
		}
		if (found)
			SHA1Update(&sc->sc_sha1, (void *)&cur, sizeof(cur));
	} while (found);
Пример #2
0
int rl_multi_string_sha1(struct rlite *db, unsigned char digest[20], long number)
{
	unsigned char *data;
	long datalen;
	SHA1_CTX sha;
	SHA1Init(&sha);

	void *tmp;
	rl_list *list;
	rl_list_iterator *iterator = NULL;
	int retval;
	RL_CALL(rl_read, RL_FOUND, db, &rl_data_type_list_long, number, &rl_list_type_long, &tmp, 0);
	list = tmp;

	RL_CALL(rl_list_iterator_create, RL_OK, db, &iterator, list, 1);

	long size = 0;
	while ((retval = rl_list_iterator_next(iterator, &tmp)) == RL_OK) {
		if (size == 0) {
			size = *(long *)tmp;
			rl_free(tmp);
			continue;
		}
		RL_CALL(rl_string_get, RL_OK, db, &data, *(long *)tmp);
		datalen = size > db->page_size ? db->page_size : size;
		SHA1Update(&sha, data, datalen);
		size -= datalen;
		rl_free(tmp);
	}
	iterator = NULL;

	if (retval != RL_END) {
		goto cleanup;
	}

	RL_CALL(rl_list_nocache_destroy, RL_OK, db, list);

	SHA1Final(digest, &sha);
	retval = RL_OK;
cleanup:
	if (iterator) {
		rl_list_iterator_destroy(db, iterator);
	}
	return retval;
}
Пример #3
0
	std::string sha1_sum_data(const void* data, size_t len)
	{
		SHA1_CTX ctx;
		unsigned char hash[20];
		const char *cset = "0123456789abcdef";
		int j;

		SHA1Init(&ctx);
		SHA1Update(&ctx, (const unsigned char*)data, len);
		SHA1Final(hash, &ctx);
		char digest[40];
		for (j = 0; j < 20; j++)
		{
			digest[j * 2] = cset[((hash[j] & 0xF0) >> 4)];
			digest[j * 2 + 1] = cset[(hash[j] & 0xF)];
		}
		return std::string(digest, 40);
	}
Пример #4
0
/* Perform the SHA1 of the input string. We use this both for hasing script
 * bodies in order to obtain the Lua function name, and in the implementation
 * of redis.sha1().
 *
 * 计算输入字符串的 SHA1 校验和,用于计算函数名,也用于 redis.sha1()
 *
 * 'digest' should point to a 41 bytes buffer: 40 for SHA1 converted into an
 * hexadecimal number, plus 1 byte for null term. */
void sha1hex(char *digest, char *script, size_t len)
{
    SHA1_CTX ctx;
    unsigned char hash[20];
    char *cset = "0123456789abcdef";
    int j;

    SHA1Init(&ctx);
    SHA1Update(&ctx,(unsigned char*)script,len);
    SHA1Final(hash,&ctx);

    for (j = 0; j < 20; j++)
    {
        digest[j*2] = cset[((hash[j]&0xF0)>>4)];
        digest[j*2+1] = cset[(hash[j]&0xF)];
    }
    digest[40] = '\0';
}
Пример #5
0
/*
 * fips_sha1_build_context()
 *
 * Description:
 *	This function allocates and initializes SHA1 context
 *	context.
 */
SHA1_CTX *
fips_sha1_build_context(void)
{
	SHA1_CTX *sha1_context;


#ifndef _KERNEL
	if ((sha1_context = malloc(sizeof (SHA1_CTX))) == NULL)
#else
	if ((sha1_context = kmem_zalloc(sizeof (SHA1_CTX),
	    KM_SLEEP)) == NULL)
#endif
		return (NULL);

	SHA1Init(sha1_context);

	return (sha1_context);

}
Пример #6
0
char *
sha1_hash(const char *s, size_t size)
{
    static char shabuf[SHABUFLEN + 1];
    unsigned char digestbuf[SHA1_DIGEST_LENGTH];
    int i;
    SHA1_CTX digest;

    SHA1Init(&digest);
    SHA1Update(&digest, (unsigned char *) s, size);
    SHA1Update(&digest, (unsigned char *) cloak_key, cloak_key_len);
    SHA1Final(digestbuf, &digest);

    for (i = 0; i < SHA1_DIGEST_LENGTH; i++)
	snprintf(shabuf+2*i, sizeof(shabuf) - 2*i, "%02x", digestbuf[i]);
    shabuf[SHABUFLEN] = '\0';

    return shabuf;
}
Пример #7
0
void
HMAC_SHA1_Final(u_int8_t digest[SHA1_DIGEST_LENGTH], HMAC_SHA1_CTX *ctx)
{
	u_int8_t k_opad[SHA1_BLOCK_LENGTH];
	int i;

	SHA1Final(digest, &ctx->ctx);

	bzero(k_opad, SHA1_BLOCK_LENGTH);
	bcopy(ctx->key, k_opad, ctx->key_len);
	for (i = 0; i < SHA1_BLOCK_LENGTH; i++)
		k_opad[i] ^= 0x5c;

	SHA1Init(&ctx->ctx);
	SHA1Update(&ctx->ctx, k_opad, SHA1_BLOCK_LENGTH);
	SHA1Update(&ctx->ctx, digest, SHA1_DIGEST_LENGTH);
	SHA1Final(digest, &ctx->ctx);

	bzero(k_opad, sizeof k_opad);
}
Пример #8
0
static int
sha1_digest_init(crypto_ctx_t *ctx, crypto_mechanism_t *mechanism,
    crypto_req_handle_t req)
{
	if (mechanism->cm_type != SHA1_MECH_INFO_TYPE)
		return (CRYPTO_MECHANISM_INVALID);

	/*
	 * Allocate and initialize SHA1 context.
	 */
	ctx->cc_provider_private = kmem_alloc(sizeof (sha1_ctx_t),
	    crypto_kmflag(req));
	if (ctx->cc_provider_private == NULL)
		return (CRYPTO_HOST_MEMORY);

	PROV_SHA1_CTX(ctx)->sc_mech_type = SHA1_MECH_INFO_TYPE;
	SHA1Init(&PROV_SHA1_CTX(ctx)->sc_sha1_ctx);

	return (CRYPTO_SUCCESS);
}
Пример #9
0
void Digest::reset(void)
{
    if(hashtype) {
        switch(*((char *)hashtype)) {
        case 'm':
            if(!context)
                context = new MD5_CTX;
            MD5Init((MD5_CTX*)context);
            break;
        case 's':
            if(!context)
                context = new SHA1_CTX;
            SHA1Init((SHA1_CTX*)context);
            break;
        default:
            break;
        }
    }
    bufsize = 0;
}
Пример #10
0
static qbool FMod_IsModelModified (const char *name, const int flags, const byte *buf, const size_t len)
{
	int i;
	unsigned char hash[DIGEST_SIZE];
	SHA1_CTX context;
	qbool found = false;


	SHA1Init (&context);
	SHA1Update (&context, (unsigned char *) buf, len);
	SHA1Final (hash, &context);

	for (i = 0; i < check_models_num; i++) {
		if (strcmp(name, check_models[i].name) == 0) {
			if (check_models[i].flags == flags) {
				found = true;
				break;
			}
		}
	}

	if (found) {
		if (memcmp(check_models[i].hash, hash, DIGEST_SIZE) == 0) {
			// original model
			return false;
		}
		else {
			check_models_hashes_entry_t *cur = check_models[i].hash_alt;
			while (cur) {
				if (memcmp(cur->hash, hash, DIGEST_SIZE) == 0) {
					// alternative legal model
					return false;
				}
				cur = cur->next;
			}
		}
	}

	// no match found
	return true;
}
Пример #11
0
// Calculates the MAC, hmacdigest will contain the result
// Assumes that the last call to HMACBlock was done with len<64
void HMACDone(void) {
  uint8_t i;
  unsigned char temp[SHA1_DIGESTSIZE];
  
  // terminate inner digest and store it
  SHA1Done();
  memcpy(temp, shadigest, SHA1_DIGESTSIZE);
  
  // prepare key for outer digest
  // buffer will contain the original key xor 0x5c
  for (i=0;i<SHA1_BLOCKSIZE;i++) {
    hmackey[i] ^= 0x6a;
  }
  
  // initialize SHA1 and hash key
  SHA1Init();
  SHA1Block(hmackey, SHA1_BLOCKSIZE);
  // hash inner digest and terminate hash
  SHA1Block(temp, SHA1_DIGESTSIZE);
  SHA1Done();
}
Пример #12
0
Файл: IoSHA1.c Проект: ADTSH/io
IoSHA1 *IoSHA1_proto(void *state)
{
	IoObject *self = IoObject_new(state);
	IoObject_tag_(self, IoSHA1_newTag(state));

	IoObject_setDataPointer_(self, calloc(1, sizeof(IoSHA1Data)));
	SHA1Init(&(DATA(self)->context));

	IoState_registerProtoWithId_(state, self, protoId);

	{
		IoMethodTable methodTable[] = {
		{"appendSeq", IoSHA1_appendSeq},
		{"sha1", IoSHA1_sha1},
		{"sha1String", IoSHA1_sha1String},
		{"hmac", IoSHA1_hmac},
		{NULL, NULL},
		};
		IoObject_addMethodTable_(self, methodTable);
	}
	return self;
}
Пример #13
0
int GenerateBytes (
unsigned char *block,
unsigned int blockLen,
RANDOM_STRUCT *randStruct
)
{
SHA1_CTX context;
unsigned int available, i;
  
  if (randStruct->bytesNeeded)
    return (0x0408);
  
  available = randStruct->outputAvailable;
  
	while (blockLen > available) {
		memcpy ((unsigned char *)block,
		        (unsigned char *)&randStruct->output[20-available], available);
		block += available;
		blockLen -= available;

		/* generate new output */
		SHA1Init (&context);
		SHA1Update (&context, randStruct->state, 20);
		SHA1Final (randStruct->output, &context);
		available = 16;

		/* increment state */
		for (i = 0; i < 20; i++)
		if (randStruct->state[19-i]++)
			break;
	}

	memcpy ((unsigned char *)block,
	        (unsigned char *)&randStruct->output[16-available], blockLen);
	randStruct->outputAvailable = available - blockLen;

	return (0);
}
Пример #14
0
DIGEST *crypto_digest_new(JCR *jcr, crypto_digest_t type)
{
   DIGEST *digest;

   digest = (DIGEST *)malloc(sizeof(DIGEST));
   digest->type = type;
   digest->jcr = jcr;

   switch (type) {
   case CRYPTO_DIGEST_MD5:
      MD5Init(&digest->md5);
      break;
   case CRYPTO_DIGEST_SHA1:
      SHA1Init(&digest->sha1);
      break;
   default:
      Jmsg1(jcr, M_ERROR, 0, _("Unsupported digest type=%d specified\n"), type);
      free(digest);
      return NULL;
   }

   return (digest);
}
Пример #15
0
aes_encrypt_ctx *cpx_iv_aes_ctx(struct cpx *cpx)
{
	if (ISSET(cpx->cpx_flags, CPX_IV_AES_CTX_INITIALIZED))
	return &cpx->cpx_iv_aes_ctx;

	SHA1_CTX sha1ctxt;
	uint8_t digest[SHA_DIGEST_LENGTH]; /* Kiv */

	/* First init the cp_cache_iv_key[] */
	SHA1Init(&sha1ctxt);

	/*
	 * We can only use this when the keys are generated in the AP; As a result
	 * we only use the first 32 bytes of key length in the cache key
	 */
	SHA1Update(&sha1ctxt, cpx->cpx_cached_key, cpx->cpx_key_len);
	SHA1Final(digest, &sha1ctxt);

	cpx_set_aes_iv_key(cpx, digest);
	SET(cpx->cpx_flags, CPX_IV_AES_CTX_VFS);

	return &cpx->cpx_iv_aes_ctx;
}
Пример #16
0
static void ikev2_calculate_sighash(struct state *st,
				    enum phase1_role role,
				    unsigned char *idhash,
				    chunk_t firstpacket,
				    unsigned char *sig_octets)
{
	SHA1_CTX ctx_sha1;
	const chunk_t *nonce;
	const char    *nonce_name;

	if (role == INITIATOR) {
		/* on initiator, we need to hash responders nonce */
		nonce = &st->st_nr;
		nonce_name = "inputs to hash2 (responder nonce)";
	} else {
		nonce = &st->st_ni;
		nonce_name = "inputs to hash2 (initiator nonce)";
	}

	DBG(DBG_CRYPT,
	    DBG_dump_chunk("inputs to hash1 (first packet)", firstpacket);
	    DBG_dump_chunk(nonce_name, *nonce);
	    DBG_dump("idhash", idhash,
		     st->st_oakley.prf_hasher->hash_digest_len));

	SHA1Init(&ctx_sha1);
	SHA1Update(&ctx_sha1,
		   firstpacket.ptr,
		   firstpacket.len);
	SHA1Update(&ctx_sha1, nonce->ptr, nonce->len);

	/* we took the PRF(SK_d,ID[ir]'), so length is prf hash length */
	SHA1Update(&ctx_sha1, idhash,
		   st->st_oakley.prf_hasher->hash_digest_len);

	SHA1Final(sig_octets, &ctx_sha1);
}
Пример #17
0
	int sha1sum_file(const std::string& file, std::string& hash)
	{
		FILE *fp;
		if ((fp = fopen(file.c_str(), "rb")) == NULL)
		{
			return -1;
		}
		SHA1_CTX ctx;
		SHA1Init(&ctx);
		const uint32 buf_size = 65536;
		unsigned char buf[buf_size];
		while (1)
		{
			int ret = fread(buf, 1, buf_size, fp);
			if (ret > 0)
			{
				SHA1Update(&ctx, buf, ret);
			}
			if (ret < (int)buf_size)
			{
				break;
			}
		}
		fclose(fp);
		unsigned char hashstr[20];
		SHA1Final(hashstr, &ctx);

		char result[256];
		uint32 offset = 0;
		for (uint32 i = 0; i < 20; i++)
		{
			int ret = sprintf(result + offset, "%02x", hashstr[i]);
			offset += ret;
		}
		hash = result;
		return 0;
	}
Пример #18
0
int
sha1test(void)
{
	SHA1_CTX sha;
	int fail;
	int i;
	int j;
	uint8_t digest[20];
	uint8_t rdigest[20];

	/*
	 * Perform SHA-1 tests
	 */
	for (j = 0; j < 4; ++j) {
		fail = 0;
		(void) printf("Test #%d ", j+1);

		SHA1Init(&sha);

		for (i = 0; i < repeatcount[j]; ++i) {
			SHA1Update(&sha, (unsigned char *)testarray[j],
			    strlen(testarray[j]));
		}

		SHA1Final(digest, &sha);

		getxdata(rdigest, resultarray[j], 20);
		if (bcmp(digest, rdigest, 20) != 0) {
			(void) printf("FAILED\n");
			fail++;
		} else {
			(void) printf("PASSED\n");
		}
	}

	return (fail);
}
Пример #19
0
static int32 auth8651bGeneralApiTestItem(uint32 mode, uint8 * input, uint32 pktLen, uint8 * key, uint32 keyLen) {
	MD5_CTX md5Context;
	SHA1_CTX sha1Context;

	if(rtl8651b_authEngine(mode, input, pktLen, key, keyLen, asicDigest) == FAILED)
		return FAILED;//When authentication engine cannot calculate digest, the testing is surely failed
	authSim(mode, input, pktLen, key, keyLen, simDigest);
	if(memcmp(simDigest, asicDigest, (mode&0x1)? RTL8651B_SHA1_DIGEST_LENGTH: RTL8651B_MD5_DIGEST_LENGTH) != 0) {
		switch(mode) {
			case HASH_MD5:
				MD5Init(&md5Context);
				MD5Update(&md5Context, input, pktLen);
				MD5Final(swDigest, &md5Context);
			break;
			case HASH_SHA1:
				SHA1Init(&sha1Context);
				SHA1Update(&sha1Context, input, pktLen);
				SHA1Final(swDigest, &sha1Context);
			break;
			case HMAC_MD5:
				HMACMD5(input, pktLen, key, keyLen, swDigest);
			break;
			case HMAC_SHA1:
				HMACSHA1(input, pktLen, key, keyLen, swDigest);
			break;
		}
		if(memcmp(simDigest, swDigest, (mode&0x1)? RTL8651B_SHA1_DIGEST_LENGTH: RTL8651B_MD5_DIGEST_LENGTH) != 0)
			displayDigestMismatch(authModeString[mode], input, pktLen, key, keyLen, "SW", swDigest, "SIM", simDigest, (mode&0x1)? RTL8651B_SHA1_DIGEST_LENGTH: RTL8651B_MD5_DIGEST_LENGTH);
		else	 {
			displayDigestMismatch(authModeString[mode], input, pktLen, key, keyLen, "SIM", simDigest, "ASIC", asicDigest, (mode&0x1)? RTL8651B_SHA1_DIGEST_LENGTH: RTL8651B_MD5_DIGEST_LENGTH);
			triggerGpio();
			//rtl8651b_authEngineData(mode, input, pktLen, key, keyLen);
		}
		return FAILED;
	}
	return SUCCESS;	
}
Пример #20
0
static int
__archive_libc_sha1init(archive_sha1_ctx *ctx)
{
  SHA1Init(ctx);
  return (ARCHIVE_OK);
}
Пример #21
0
//可重用,用于唯一 id
void getRandomHexChars(char *p, unsigned int len) {
    char *charset = "0123456789abcdef";
    unsigned int j;

    /* Global state. */
    static int seed_initialized = 0;
    static unsigned char seed[20]; /* The SHA1 seed, from /dev/urandom. */
    static uint64_t counter = 0; /* The counter we hash with the seed. */

    if (!seed_initialized) {
        /* Initialize a seed and use SHA1 in counter mode, where we hash
         * the same seed with a progressive counter. For the goals of this
         * function we just need non-colliding strings, there are no
         * cryptographic security needs. */
        FILE *fp = fopen("/dev/urandom","r");
        if (fp && fread(seed,sizeof(seed),1,fp) == 1)
            seed_initialized = 1;
        if (fp) fclose(fp);
    }

    if (seed_initialized) {
        while(len) {
            unsigned char digest[20];
            SHA1_CTX ctx;
            unsigned int copylen = len > 20 ? 20 : len;

            SHA1Init(&ctx);
            SHA1Update(&ctx, seed, sizeof(seed));
            SHA1Update(&ctx, (unsigned char*)&counter,sizeof(counter));
            SHA1Final(digest, &ctx);
            counter++;

            memcpy(p,digest,copylen);
            /* Convert to hex digits. */
            for (j = 0; j < copylen; j++) p[j] = charset[p[j] & 0x0F];
            len -= copylen;
            p += copylen;
        }
    } else {
        /* If we can't read from /dev/urandom, do some reasonable effort
         * in order to create some entropy, since this function is used to
         * generate run_id and cluster instance IDs */
        char *x = p;
        unsigned int l = len;
        struct timeval tv;
        pid_t pid = getpid();

        /* Use time and PID to fill the initial array. */
        gettimeofday(&tv,NULL);
        if (l >= sizeof(tv.tv_usec)) {
            memcpy(x,&tv.tv_usec,sizeof(tv.tv_usec));
            l -= sizeof(tv.tv_usec);
            x += sizeof(tv.tv_usec);
        }
        if (l >= sizeof(tv.tv_sec)) {
            memcpy(x,&tv.tv_sec,sizeof(tv.tv_sec));
            l -= sizeof(tv.tv_sec);
            x += sizeof(tv.tv_sec);
        }
        if (l >= sizeof(pid)) {
            memcpy(x,&pid,sizeof(pid));
            l -= sizeof(pid);
            x += sizeof(pid);
        }
        /* Finally xor it with rand() output, that was already seeded with
         * time() at startup, and convert to hex digits. */
        for (j = 0; j < len; j++) {
            p[j] ^= rand();
            p[j] = charset[p[j] & 0x0F];
        }
    }
}
Пример #22
0
struct crypto_hash * crypto_hash_init(enum crypto_hash_alg alg, const u8 *key,
                                      size_t key_len)
{
    struct crypto_hash *ctx;
    u8 k_pad[64];
    u8 tk[20];
    size_t i;

    ctx = os_zalloc(sizeof(*ctx));
    if (ctx == NULL)
        return NULL;

    ctx->alg = alg;

    switch (alg) {
    case CRYPTO_HASH_ALG_MD5:
        MD5Init(&ctx->u.md5);
        break;
    case CRYPTO_HASH_ALG_SHA1:
        SHA1Init(&ctx->u.sha1);
        break;
    case CRYPTO_HASH_ALG_HMAC_MD5:
        if (key_len > sizeof(k_pad)) {
            MD5Init(&ctx->u.md5);
            MD5Update(&ctx->u.md5, key, key_len);
            MD5Final(tk, &ctx->u.md5);
            key = tk;
            key_len = 16;
        }
        os_memcpy(ctx->key, key, key_len);
        ctx->key_len = key_len;

        os_memcpy(k_pad, key, key_len);
        os_memset(k_pad + key_len, 0, sizeof(k_pad) - key_len);
        for (i = 0; i < sizeof(k_pad); i++)
            k_pad[i] ^= 0x36;
        MD5Init(&ctx->u.md5);
        MD5Update(&ctx->u.md5, k_pad, sizeof(k_pad));
        break;
    case CRYPTO_HASH_ALG_HMAC_SHA1:
        if (key_len > sizeof(k_pad)) {
            SHA1Init(&ctx->u.sha1);
            SHA1Update(&ctx->u.sha1, key, key_len);
            SHA1Final(tk, &ctx->u.sha1);
            key = tk;
            key_len = 20;
        }
        os_memcpy(ctx->key, key, key_len);
        ctx->key_len = key_len;

        os_memcpy(k_pad, key, key_len);
        os_memset(k_pad + key_len, 0, sizeof(k_pad) - key_len);
        for (i = 0; i < sizeof(k_pad); i++)
            k_pad[i] ^= 0x36;
        SHA1Init(&ctx->u.sha1);
        SHA1Update(&ctx->u.sha1, k_pad, sizeof(k_pad));
        break;
    default:
        os_free(ctx);
        return NULL;
    }

    return ctx;
}
Пример #23
0
int crypto_hash_finish(struct crypto_hash *ctx, u8 *mac, size_t *len)
{
    u8 k_pad[64];
    size_t i;

    if (ctx == NULL)
        return -2;

    if (mac == NULL || len == NULL) {
        os_free(ctx);
        return 0;
    }

    switch (ctx->alg) {
    case CRYPTO_HASH_ALG_MD5:
        if (*len < 16) {
            *len = 16;
            os_free(ctx);
            return -1;
        }
        *len = 16;
        MD5Final(mac, &ctx->u.md5);
        break;
    case CRYPTO_HASH_ALG_SHA1:
        if (*len < 20) {
            *len = 20;
            os_free(ctx);
            return -1;
        }
        *len = 20;
        SHA1Final(mac, &ctx->u.sha1);
        break;
    case CRYPTO_HASH_ALG_HMAC_MD5:
        if (*len < 16) {
            *len = 16;
            os_free(ctx);
            return -1;
        }
        *len = 16;

        MD5Final(mac, &ctx->u.md5);

        os_memcpy(k_pad, ctx->key, ctx->key_len);
        os_memset(k_pad + ctx->key_len, 0,
                  sizeof(k_pad) - ctx->key_len);
        for (i = 0; i < sizeof(k_pad); i++)
            k_pad[i] ^= 0x5c;
        MD5Init(&ctx->u.md5);
        MD5Update(&ctx->u.md5, k_pad, sizeof(k_pad));
        MD5Update(&ctx->u.md5, mac, 16);
        MD5Final(mac, &ctx->u.md5);
        break;
    case CRYPTO_HASH_ALG_HMAC_SHA1:
        if (*len < 20) {
            *len = 20;
            os_free(ctx);
            return -1;
        }
        *len = 20;

        SHA1Final(mac, &ctx->u.sha1);

        os_memcpy(k_pad, ctx->key, ctx->key_len);
        os_memset(k_pad + ctx->key_len, 0,
                  sizeof(k_pad) - ctx->key_len);
        for (i = 0; i < sizeof(k_pad); i++)
            k_pad[i] ^= 0x5c;
        SHA1Init(&ctx->u.sha1);
        SHA1Update(&ctx->u.sha1, k_pad, sizeof(k_pad));
        SHA1Update(&ctx->u.sha1, mac, 20);
        SHA1Final(mac, &ctx->u.sha1);
        break;
    }

    os_free(ctx);

    return 0;
}
Пример #24
0
/**
 * モジュールを実行します。
 */
NyLPC_TBool NyLPC_cModWebSocket_execute(NyLPC_TcModWebSocket_t* i_inst,NyLPC_TcHttpdConnection_t* i_connection)
{
	union{
		NyLPC_TcHttpBasicHeaderParser_t parser;
		SHA1_CTX sh1;
	}sh;

	//リクエストParse済へ遷移(この関数の後はModが責任を持ってリクエストを返却)
	NyLPC_cHttpdConnection_setReqStatusParsed(i_connection);



	//排他ロック
	NyLPC_cHttpdConnection_lock(i_connection);
	{//parser

		//初期化
		work.header.version=0;
		work.header.sub_protocol_id=0;
		NyLPC_cStr_initialize(&work.header._tstr,work.header._tstr_buf,STRBUF_MAX);

		NyLPC_cHttpBasicHeaderParser_initialize(&sh.parser,&handler);

		//プリフェッチしたデータを流す
		NyLPC_cHttpBasicHeaderParser_parseInit(&sh.parser,&(work.header.super));
		NyLPC_cHttpdConnection_pushPrefetchInfo(i_connection,&sh.parser,&work.header.super);
		//後続をストリームから取り込む
		if(!NyLPC_cHttpBasicHeaderParser_parseStream(&sh.parser,NyLPC_cHttpdConnection_refStream(i_connection),&(work.header.super))){
			NyLPC_cHttpdUtils_sendErrorResponse(i_connection,500);
			NyLPC_OnErrorGoto(Error1);
		}
		if(!NyLPC_cHttpBasicHeaderParser_parseFinish(&sh.parser,&(work.header.super))){
			NyLPC_cHttpdUtils_sendErrorResponse(i_connection,500);
			NyLPC_OnErrorGoto(Error1);
		}
		//HeaderParserはここで破棄(URLEncode,cSTRも)
		NyLPC_cHttpBasicHeaderParser_finalize(&sh.parser);

		NyLPC_cStr_finalize(&single_header._tstr);


		//HTTP/1.1であること。Connection:Upgradeはチェックしない。
		if(work.header.super.startline.req.version!=NyLPC_THttpVersion_11)
		{
			NyLPC_cHttpdUtils_sendErrorResponse(i_connection,400);
			NyLPC_OnErrorGoto(Error2);
		}
		if(NyLPC_cHttpdConnection_getMethod(i_connection)!=NyLPC_THttpMethodType_GET){
			NyLPC_cHttpdUtils_sendErrorResponse(i_connection,400);
			NyLPC_OnErrorGoto(Error2);
		}
		//WebSocket version 13であること
		if(work.header.version!=13){
			NyLPC_cHttpdUtils_sendErrorResponse(i_connection,400);
			NyLPC_OnErrorGoto(Error2);
		}

		//レスポンスの生成(生データを直接ストリームへ書きこむ)
		if(!NyLPC_iHttpPtrStream_write(NyLPC_cHttpdConnection_refStream(i_connection),
			"HTTP/1.1 101 Switching Protocols\r\n"	//32+2
			"Upgrade: websocket\r\n" 				//18+2
			"Connection: Upgrade\r\n"				//19+2
			"Sec-WebSocket-Accept: "				//22
			,32+2+18+2+19+2+22)){
			NyLPC_OnErrorGoto(Error3);
		}
		//SH1キーの生成
		SHA1Init(&sh.sh1);
		SHA1Update(&sh.sh1,(const unsigned char*)work.header.key,strlen(work.header.key));
		SHA1Update(&sh.sh1,(const unsigned char*)"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",36);
		//ワークメモリ32バイトはstrの使いまわし
		SHA1Final((unsigned char*)(work.header._tstr_buf),&sh.sh1);
		//BASE64化(single_header.keyへ出力)
		NyLPC_cBase64_encode(work.header._tstr_buf,20,work.header.key);
		if(!NyLPC_iHttpPtrStream_write(NyLPC_cHttpdConnection_refStream(i_connection),work.header.key,28)){
			NyLPC_OnErrorGoto(Error3);
		}
		//SubProtocolの認証が有る場合
		if(work.header.sub_protocol_id!=0){
			if(!NyLPC_iHttpPtrStream_write(NyLPC_cHttpdConnection_refStream(i_connection)
				,"\r\nSec-WebSocket-Protocol: "	//24
				,24)){
				NyLPC_OnErrorGoto(Error3);
			}
			if(!NyLPC_iHttpPtrStream_write(NyLPC_cHttpdConnection_refStream(i_connection)
				,work.header._ref_sub_protocol
				,strlen(work.header._ref_sub_protocol)))
			{
				NyLPC_OnErrorGoto(Error3);
			}
		}
		//Sec-WebSocket-Protocol
		if(!NyLPC_iHttpPtrStream_write(NyLPC_cHttpdConnection_refStream(i_connection),"\r\n\r\n",4)){
			NyLPC_OnErrorGoto(Error3);
		}
		//connection phase
		i_inst->_payload_st=NyLPC_TcModWebSocket_ST_START_PAYLOAD;
	}
//占有解除
	NyLPC_cHttpdConnection_unlock(i_connection);
	//参照コネクションの設定
	i_inst->_ref_connection=i_connection;
	NyLPC_iHttpPtrStream_flush(NyLPC_cHttpdConnection_refStream(i_inst->_ref_connection));
	return NyLPC_TBool_TRUE;
Error3:
Error2:
	//VM排他ロックの解除
	NyLPC_cHttpdConnection_unlock(i_connection);
	return NyLPC_TBool_FALSE;
Error1:
	NyLPC_cHttpBasicHeaderParser_finalize(&parser);
	NyLPC_cStr_finalize(&single_header._tstr);
	//VM排他ロックの解除
	NyLPC_cHttpdConnection_unlock(i_connection);
	return NyLPC_TBool_FALSE;
}
Пример #25
0
int
do_integriforce_check(secadm_rule_t *rule, struct vattr *vap,
                      struct vnode *vp, struct ucred *ucred)
{
    SHA256_CTX sha256ctx;
    SHA1_CTX sha1ctx;
    struct iovec iov;
    struct uio uio;
    unsigned char *buf, hash[SHA256_DIGEST_LENGTH];
    size_t total, amt, hashsz;
    int err;

    switch (rule->sr_integriforce_data->si_cache) {
    case 0:
        break;

    case 1:
        return (0);

    default:
        if (rule->sr_integriforce_data->si_mode == 0) {
            printf("[SECADM] Warning: hash did not match for file"
                   " (%s)\n", rule->sr_integriforce_data->si_path);
            return (0);
        } else {
            printf("[SECADM] Error: hash did not match for file"
                   " (%s). Blocking execution.\n",
                   rule->sr_integriforce_data->si_path);
            return (EPERM);
        }
    }

    err = VOP_OPEN(vp, FREAD, ucred, curthread, NULL);
    if (err) {
        return (0);
    }

    buf = malloc(8192, M_SECADM, M_NOWAIT);
    if (buf == NULL) {
        VOP_CLOSE(vp, FREAD, ucred, curthread);
        return (0);
    }

    switch (rule->sr_integriforce_data->si_type) {
    case secadm_hash_sha1:
        hashsz = SHA1_RESULTLEN;
        SHA1Init(&sha1ctx);
        break;
    case secadm_hash_sha256:
        hashsz = SHA256_DIGEST_LENGTH;
        SHA256_Init(&sha256ctx);
        break;
    default:
        VOP_CLOSE(vp, FREAD, ucred, curthread);
        free(buf, M_SECADM);
        return (0);
    }

    total = vap->va_size;
    while (total > 0) {
        amt = MIN(total, 8192);
        iov.iov_base = buf;
        iov.iov_len = amt;
        uio.uio_iov = &iov;
        uio.uio_iovcnt = 1;
        uio.uio_offset = vap->va_size - total;
        uio.uio_resid = amt;
        uio.uio_segflg = UIO_SYSSPACE;
        uio.uio_rw = UIO_READ;
        uio.uio_td = curthread;
        err = VOP_READ(vp, &uio, 0, ucred);
        if (err) {
            VOP_CLOSE(vp, FREAD, ucred, curthread);
            free(buf, M_SECADM);
            return (0);
        }

        switch (rule->sr_integriforce_data->si_type) {
        case secadm_hash_sha1:
            SHA1Update(&sha1ctx, buf, amt);
            break;
        case secadm_hash_sha256:
            SHA256_Update(&sha256ctx, buf, amt);
            break;
        default:
            break;
        }

        total -= amt;
    }

    free(buf, M_SECADM);
    VOP_CLOSE(vp, FREAD, ucred, curthread);

    switch (rule->sr_integriforce_data->si_type) {
    case secadm_hash_sha1:
        SHA1Final(hash, &sha1ctx);
        break;
    case secadm_hash_sha256:
        SHA256_Final(hash, &sha256ctx);
        break;
    default:
        break;
    }

    if (memcmp(rule->sr_integriforce_data->si_hash, hash, hashsz)) {
        switch (rule->sr_integriforce_data->si_mode) {
        case 0:
            printf("[SECADM] Warning: hash did not match for file"
                   " (%s)\n",
                   rule->sr_integriforce_data->si_path);
            err = 0;
            break;
        default:
            printf("[SECADM] Error: hash did not match for file"
                   " (%s). Blocking execution.\n",
                   rule->sr_integriforce_data->si_path);
            err = EPERM;
            break;
        }

        rule->sr_integriforce_data->si_cache = 2;
    } else {
        rule->sr_integriforce_data->si_cache = 1;
    }

    return (err);
}
Пример #26
0
int ipsec_sa_init(struct ipsec_sa *ipsp)
{
	int error = 0;
	char sa[SATOT_BUF];
	size_t sa_len;

#ifdef CONFIG_KLIPS_DEBUG
	char ipaddr_txt[ADDRTOA_BUF];
	char ipaddr2_txt[ADDRTOA_BUF];
#endif
#if defined (CONFIG_KLIPS_AUTH_HMAC_MD5) || \
	defined (CONFIG_KLIPS_AUTH_HMAC_SHA1)
	unsigned char kb[AHMD596_BLKLEN];
	int i;
#endif

	if (ipsp == NULL) {
		KLIPS_PRINT(debug_pfkey,
			    "ipsec_sa_init: "
			    "ipsp is NULL, fatal\n");
		SENDERR(EINVAL);
	}

	sa_len = KLIPS_SATOT(debug_pfkey, &ipsp->ips_said, 0, sa, sizeof(sa));

	KLIPS_PRINT(debug_pfkey,
		    "ipsec_sa_init: "
		    "(pfkey defined) called for SA:%s\n",
		    sa_len ? sa : " (error)");

	KLIPS_PRINT(debug_pfkey,
		    "ipsec_sa_init: "
		    "calling init routine of %s%s%s\n",
		    IPS_XFORM_NAME(ipsp));

	switch (ipsp->ips_said.proto) {
#ifdef CONFIG_KLIPS_IPIP
	case IPPROTO_IPIP: {
		ipsp->ips_xformfuncs = ipip_xform_funcs;
#ifdef CONFIG_KLIPS_DEBUG
		sin_addrtot(ipsp->ips_addr_s, 0, ipaddr_txt,
			    sizeof(ipaddr_txt));
		sin_addrtot(ipsp->ips_addr_d, 0, ipaddr2_txt,
			    sizeof(ipaddr2_txt));
		KLIPS_PRINT(debug_pfkey,
			    "ipsec_sa_init: "
			    "(pfkey defined) IPIP ipsec_sa set for %s->%s.\n",
			    ipaddr_txt,
			    ipaddr2_txt);
#endif
	}
	break;
#endif          /* !CONFIG_KLIPS_IPIP */

#ifdef CONFIG_KLIPS_AH
	case IPPROTO_AH:

		ipsp->ips_xformfuncs = ah_xform_funcs;

#ifdef CONFIG_KLIPS_OCF
		if (ipsec_ocf_sa_init(ipsp, ipsp->ips_authalg, 0))
			break;
#endif

#ifdef CONFIG_KLIPS_ALG
		error = ipsec_alg_auth_key_create(ipsp);
		if ((error < 0) && (error != -EPROTO))
			SENDERR(-error);

		if (error == -EPROTO) {
			/* perform manual key generation,
			   ignore this particular error */
			error = 0;
#endif              /* CONFIG_KLIPS_ALG */

		switch (ipsp->ips_authalg) {
# ifdef CONFIG_KLIPS_AUTH_HMAC_MD5
		case AH_MD5: {
			unsigned char *akp;
			unsigned int aks;
			MD5_CTX *ictx;
			MD5_CTX *octx;

			if (ipsp->ips_key_bits_a != (AHMD596_KLEN * 8)) {
				KLIPS_PRINT(debug_pfkey,
					    "ipsec_sa_init: "
					    "incorrect key size: %d bits -- must be %d bits\n" /*octets (bytes)\n"*/,
					    ipsp->ips_key_bits_a, AHMD596_KLEN *
					    8);
				SENDERR(EINVAL);
			}

#  if KLIPS_DIVULGE_HMAC_KEY
			KLIPS_PRINT(debug_pfkey && sysctl_ipsec_debug_verbose,
				    "ipsec_sa_init: "
				    "hmac md5-96 key is 0x%08x %08x %08x %08x\n",
				    ntohl(*(((__u32 *)ipsp->ips_key_a) + 0)),
				    ntohl(*(((__u32 *)ipsp->ips_key_a) + 1)),
				    ntohl(*(((__u32 *)ipsp->ips_key_a) + 2)),
				    ntohl(*(((__u32 *)ipsp->ips_key_a) + 3)));
#  endif                        /* KLIPS_DIVULGE_HMAC_KEY */

			ipsp->ips_auth_bits = AHMD596_ALEN * 8;

			/* save the pointer to the key material */
			akp = ipsp->ips_key_a;
			aks = ipsp->ips_key_a_size;

			KLIPS_PRINT(debug_pfkey && sysctl_ipsec_debug_verbose,
				    "ipsec_sa_init: "
				    "allocating %lu bytes for md5_ctx.\n",
				    (unsigned long) sizeof(struct md5_ctx));
			if ((ipsp->ips_key_a = (caddr_t)
					       kmalloc(sizeof(struct md5_ctx),
						       GFP_ATOMIC)) == NULL) {
				ipsp->ips_key_a = akp;
				SENDERR(ENOMEM);
			}
			ipsp->ips_key_a_size = sizeof(struct md5_ctx);

			for (i = 0; i < DIVUP(ipsp->ips_key_bits_a, 8); i++)
				kb[i] = akp[i] ^ HMAC_IPAD;
			for (; i < AHMD596_BLKLEN; i++)
				kb[i] = HMAC_IPAD;

			ictx = &(((struct md5_ctx*)(ipsp->ips_key_a))->ictx);
			osMD5Init(ictx);
			osMD5Update(ictx, kb, AHMD596_BLKLEN);

			for (i = 0; i < AHMD596_BLKLEN; i++)
				kb[i] ^= (HMAC_IPAD ^ HMAC_OPAD);

			octx = &(((struct md5_ctx*)(ipsp->ips_key_a))->octx);
			osMD5Init(octx);
			osMD5Update(octx, kb, AHMD596_BLKLEN);

#  if KLIPS_DIVULGE_HMAC_KEY
			KLIPS_PRINT(debug_pfkey && sysctl_ipsec_debug_verbose,
				    "ipsec_sa_init: "
				    "MD5 ictx=0x%08x %08x %08x %08x octx=0x%08x %08x %08x %08x\n",
				    ((__u32*)ictx)[0],
				    ((__u32*)ictx)[1],
				    ((__u32*)ictx)[2],
				    ((__u32*)ictx)[3],
				    ((__u32*)octx)[0],
				    ((__u32*)octx)[1],
				    ((__u32*)octx)[2],
				    ((__u32*)octx)[3] );
#  endif                        /* KLIPS_DIVULGE_HMAC_KEY */

			/* zero key buffer -- paranoid */
			memset(akp, 0, aks);
			kfree(akp);
		}
		break;
# endif                 /* CONFIG_KLIPS_AUTH_HMAC_MD5 */
# ifdef CONFIG_KLIPS_AUTH_HMAC_SHA1
		case AH_SHA: {
			unsigned char *akp;
			unsigned int aks;
			SHA1_CTX *ictx;
			SHA1_CTX *octx;

			if (ipsp->ips_key_bits_a != (AHSHA196_KLEN * 8)) {
				KLIPS_PRINT(debug_pfkey,
					    "ipsec_sa_init: "
					    "incorrect key size: %d bits -- must be %d bits\n" /*octets (bytes)\n"*/,
					    ipsp->ips_key_bits_a, AHSHA196_KLEN *
					    8);
				SENDERR(EINVAL);
			}

#  if KLIPS_DIVULGE_HMAC_KEY
			KLIPS_PRINT(debug_pfkey && sysctl_ipsec_debug_verbose,
				    "ipsec_sa_init: "
				    "hmac sha1-96 key is 0x%08x %08x %08x %08x\n",
				    ntohl(*(((__u32 *)ipsp->ips_key_a) + 0)),
				    ntohl(*(((__u32 *)ipsp->ips_key_a) + 1)),
				    ntohl(*(((__u32 *)ipsp->ips_key_a) + 2)),
				    ntohl(*(((__u32 *)ipsp->ips_key_a) + 3)));
#  endif                        /* KLIPS_DIVULGE_HMAC_KEY */

			ipsp->ips_auth_bits = AHSHA196_ALEN * 8;

			/* save the pointer to the key material */
			akp = ipsp->ips_key_a;
			aks = ipsp->ips_key_a_size;

			KLIPS_PRINT(debug_pfkey && sysctl_ipsec_debug_verbose,
				    "ipsec_sa_init: "
				    "allocating %lu bytes for sha1_ctx.\n",
				    (unsigned long) sizeof(struct sha1_ctx));
			if ((ipsp->ips_key_a = (caddr_t)
					       kmalloc(sizeof(struct sha1_ctx),
						       GFP_ATOMIC)) == NULL) {
				ipsp->ips_key_a = akp;
				SENDERR(ENOMEM);
			}
			ipsp->ips_key_a_size = sizeof(struct sha1_ctx);

			for (i = 0; i < DIVUP(ipsp->ips_key_bits_a, 8); i++)
				kb[i] = akp[i] ^ HMAC_IPAD;
			for (; i < AHMD596_BLKLEN; i++)
				kb[i] = HMAC_IPAD;

			ictx = &(((struct sha1_ctx*)(ipsp->ips_key_a))->ictx);
			SHA1Init(ictx);
			SHA1Update(ictx, kb, AHSHA196_BLKLEN);

			for (i = 0; i < AHSHA196_BLKLEN; i++)
				kb[i] ^= (HMAC_IPAD ^ HMAC_OPAD);

			octx = &(((struct sha1_ctx*)(ipsp->ips_key_a))->octx);
			SHA1Init(octx);
			SHA1Update(octx, kb, AHSHA196_BLKLEN);

#  if KLIPS_DIVULGE_HMAC_KEY
			KLIPS_PRINT(debug_pfkey && sysctl_ipsec_debug_verbose,
				    "ipsec_sa_init: "
				    "SHA1 ictx=0x%08x %08x %08x %08x octx=0x%08x %08x %08x %08x\n",
				    ((__u32*)ictx)[0],
				    ((__u32*)ictx)[1],
				    ((__u32*)ictx)[2],
				    ((__u32*)ictx)[3],
				    ((__u32*)octx)[0],
				    ((__u32*)octx)[1],
				    ((__u32*)octx)[2],
				    ((__u32*)octx)[3] );
#  endif                        /* KLIPS_DIVULGE_HMAC_KEY */
			/* zero key buffer -- paranoid */
			memset(akp, 0, aks);
			kfree(akp);
		}
		break;
# endif                 /* CONFIG_KLIPS_AUTH_HMAC_SHA1 */
		default:
			KLIPS_PRINT(debug_pfkey,
				    "ipsec_sa_init: "
				    "authalg=%d support not available in the kernel",
				    ipsp->ips_authalg);
			SENDERR(EINVAL);
		}
#ifdef CONFIG_KLIPS_ALG
			/* closure of the -EPROTO condition above */
		}
#endif
		break;
#endif          /* CONFIG_KLIPS_AH */

#ifdef CONFIG_KLIPS_ESP
	case IPPROTO_ESP:
		ipsp->ips_xformfuncs = esp_xform_funcs;
		{
#ifdef CONFIG_KLIPS_OCF
			if (ipsec_ocf_sa_init(ipsp, ipsp->ips_authalg,
					      ipsp->ips_encalg))
				break;
#endif

#ifdef CONFIG_KLIPS_ALG
			error = ipsec_alg_enc_key_create(ipsp);
			if (error < 0)
				SENDERR(-error);

			error = ipsec_alg_auth_key_create(ipsp);
			if ((error < 0) && (error != -EPROTO))
				SENDERR(-error);

			if (error == -EPROTO) {
				/* perform manual key generation,
				   ignore this particular error */
				error = 0;
#endif                  /* CONFIG_KLIPS_ALG */

			switch (ipsp->ips_authalg) {
#if defined (CONFIG_KLIPS_AUTH_HMAC_MD5) || \
				defined (CONFIG_KLIPS_AUTH_HMAC_SHA1)
				unsigned char *akp;
				unsigned int aks;
#endif
# ifdef CONFIG_KLIPS_AUTH_HMAC_MD5
			case AH_MD5: {
				MD5_CTX *ictx;
				MD5_CTX *octx;

				if (ipsp->ips_key_bits_a !=
				    (AHMD596_KLEN * 8)) {
					KLIPS_PRINT(debug_pfkey,
						    "ipsec_sa_init: "
						    "incorrect authorisation key size: %d bits -- must be %d bits\n" /*octets (bytes)\n"*/,
						    ipsp->ips_key_bits_a,
						    AHMD596_KLEN * 8);
					SENDERR(EINVAL);
				}

#  if KLIPS_DIVULGE_HMAC_KEY
				KLIPS_PRINT(
					debug_pfkey && sysctl_ipsec_debug_verbose,
					"ipsec_sa_init: "
					"hmac md5-96 key is 0x%08x %08x %08x %08x\n",
					ntohl(*(((__u32 *)(ipsp->ips_key_a)) +
						0)),
					ntohl(*(((__u32 *)(ipsp->ips_key_a)) +
						1)),
					ntohl(*(((__u32 *)(ipsp->ips_key_a)) +
						2)),
					ntohl(*(((__u32 *)(ipsp->ips_key_a)) +
						3)));
#  endif                                /* KLIPS_DIVULGE_HMAC_KEY */
				ipsp->ips_auth_bits = AHMD596_ALEN * 8;

				/* save the pointer to the key material */
				akp = ipsp->ips_key_a;
				aks = ipsp->ips_key_a_size;

				KLIPS_PRINT(
					debug_pfkey && sysctl_ipsec_debug_verbose,
					"ipsec_sa_init: "
					"allocating %lu bytes for md5_ctx.\n",
					(unsigned long) sizeof(struct
							       md5_ctx));
				if ((ipsp->ips_key_a = (caddr_t)
					kmalloc(sizeof(struct md5_ctx),
						GFP_ATOMIC)) == NULL) {
					ipsp->ips_key_a = akp;
					SENDERR(ENOMEM);
				}
				ipsp->ips_key_a_size = sizeof(struct md5_ctx);

				for (i = 0; i < DIVUP(ipsp->ips_key_bits_a, 8);
				     i++)
					kb[i] = akp[i] ^ HMAC_IPAD;
				for (; i < AHMD596_BLKLEN; i++)
					kb[i] = HMAC_IPAD;

				ictx = &(((struct md5_ctx*)(ipsp->ips_key_a))
					  ->ictx);
				osMD5Init(ictx);
				osMD5Update(ictx, kb, AHMD596_BLKLEN);

				for (i = 0; i < AHMD596_BLKLEN; i++)
					kb[i] ^= (HMAC_IPAD ^ HMAC_OPAD);

				octx = &(((struct md5_ctx*)(ipsp->ips_key_a))
					  ->octx);
				osMD5Init(octx);
				osMD5Update(octx, kb, AHMD596_BLKLEN);

#  if KLIPS_DIVULGE_HMAC_KEY
				KLIPS_PRINT(
					debug_pfkey && sysctl_ipsec_debug_verbose,
					"ipsec_sa_init: "
					"MD5 ictx=0x%08x %08x %08x %08x octx=0x%08x %08x %08x %08x\n",
					((__u32*)ictx)[0],
					((__u32*)ictx)[1],
					((__u32*)ictx)[2],
					((__u32*)ictx)[3],
					((__u32*)octx)[0],
					((__u32*)octx)[1],
					((__u32*)octx)[2],
					((__u32*)octx)[3] );
#  endif                                /* KLIPS_DIVULGE_HMAC_KEY */
				/* paranoid */
				memset(akp, 0, aks);
				kfree(akp);
				break;
			}
# endif                         /* CONFIG_KLIPS_AUTH_HMAC_MD5 */
# ifdef CONFIG_KLIPS_AUTH_HMAC_SHA1
			case AH_SHA: {
				SHA1_CTX *ictx;
				SHA1_CTX *octx;

				if (ipsp->ips_key_bits_a !=
				    (AHSHA196_KLEN * 8)) {
					KLIPS_PRINT(debug_pfkey,
						    "ipsec_sa_init: "
						    "incorrect authorisation key size: %d bits -- must be %d bits\n" /*octets (bytes)\n"*/,
						    ipsp->ips_key_bits_a,
						    AHSHA196_KLEN * 8);
					SENDERR(EINVAL);
				}

#  if KLIPS_DIVULGE_HMAC_KEY
				KLIPS_PRINT(
					debug_pfkey && sysctl_ipsec_debug_verbose,
					"ipsec_sa_init: "
					"hmac sha1-96 key is 0x%08x %08x %08x %08x\n",
					ntohl(*(((__u32 *)ipsp->ips_key_a) +
						0)),
					ntohl(*(((__u32 *)ipsp->ips_key_a) +
						1)),
					ntohl(*(((__u32 *)ipsp->ips_key_a) +
						2)),
					ntohl(*(((__u32 *)ipsp->ips_key_a) +
						3)));
#  endif                                /* KLIPS_DIVULGE_HMAC_KEY */
				ipsp->ips_auth_bits = AHSHA196_ALEN * 8;

				/* save the pointer to the key material */
				akp = ipsp->ips_key_a;
				aks = ipsp->ips_key_a_size;

				KLIPS_PRINT(
					debug_pfkey && sysctl_ipsec_debug_verbose,
					"ipsec_sa_init: "
					"allocating %lu bytes for sha1_ctx.\n",
					(unsigned long) sizeof(struct
							       sha1_ctx));
				if ((ipsp->ips_key_a = (caddr_t)
					kmalloc(sizeof(struct sha1_ctx),
						GFP_ATOMIC)) == NULL) {
					ipsp->ips_key_a = akp;
					SENDERR(ENOMEM);
				}
				ipsp->ips_key_a_size = sizeof(struct sha1_ctx);

				for (i = 0; i < DIVUP(ipsp->ips_key_bits_a, 8);
				     i++)
					kb[i] = akp[i] ^ HMAC_IPAD;
				for (; i < AHMD596_BLKLEN; i++)
					kb[i] = HMAC_IPAD;

				ictx = &(((struct sha1_ctx*)(ipsp->ips_key_a))
					  ->ictx);
				SHA1Init(ictx);
				SHA1Update(ictx, kb, AHSHA196_BLKLEN);

				for (i = 0; i < AHSHA196_BLKLEN; i++)
					kb[i] ^= (HMAC_IPAD ^ HMAC_OPAD);

				octx = &((struct sha1_ctx*)(ipsp->ips_key_a))
					->octx;
				SHA1Init(octx);
				SHA1Update(octx, kb, AHSHA196_BLKLEN);

#  if KLIPS_DIVULGE_HMAC_KEY
				KLIPS_PRINT(
					debug_pfkey && sysctl_ipsec_debug_verbose,
					"ipsec_sa_init: "
					"SHA1 ictx=0x%08x %08x %08x %08x octx=0x%08x %08x %08x %08x\n",
					((__u32*)ictx)[0],
					((__u32*)ictx)[1],
					((__u32*)ictx)[2],
					((__u32*)ictx)[3],
					((__u32*)octx)[0],
					((__u32*)octx)[1],
					((__u32*)octx)[2],
					((__u32*)octx)[3] );
#  endif                                /* KLIPS_DIVULGE_HMAC_KEY */
				memset(akp, 0, aks);
				kfree(akp);
				break;
			}
# endif                         /* CONFIG_KLIPS_AUTH_HMAC_SHA1 */
			case AH_NONE:
				break;
			default:
				KLIPS_PRINT(debug_pfkey,
					    "ipsec_sa_init: "
					    "authalg=%d support not available in the kernel.\n",
					    ipsp->ips_authalg);
				SENDERR(EINVAL);
			}
#ifdef CONFIG_KLIPS_ALG
			/* closure of the -EPROTO condition above */
		}
#endif

			ipsp->ips_iv_size =
				ipsp->ips_alg_enc->ixt_common.ixt_support.
				ias_ivlen / 8;

			/* Create IV */
			if (ipsp->ips_iv_size) {
				if ((ipsp->ips_iv = (caddr_t)
					kmalloc(ipsp->ips_iv_size,
						GFP_ATOMIC)) == NULL)
					SENDERR(ENOMEM);
				prng_bytes(&ipsec_prng, (char *)ipsp->ips_iv,
					   ipsp->ips_iv_size);
				ipsp->ips_iv_bits = ipsp->ips_iv_size * 8;
			}
		}
		break;
#endif          /* !CONFIG_KLIPS_ESP */
#ifdef CONFIG_KLIPS_IPCOMP
	case IPPROTO_COMP:

		ipsp->ips_xformfuncs = ipcomp_xform_funcs;

		ipsp->ips_comp_adapt_tries = 0;
		ipsp->ips_comp_adapt_skip = 0;
		ipsp->ips_comp_ratio_cbytes = 0;
		ipsp->ips_comp_ratio_dbytes = 0;

#ifdef CONFIG_KLIPS_OCF
		if (ipsec_ocf_comp_sa_init(ipsp, ipsp->ips_encalg))
			break;
#endif

		ipsp->ips_comp_adapt_tries = 0;
		ipsp->ips_comp_adapt_skip = 0;
		ipsp->ips_comp_ratio_cbytes = 0;
		ipsp->ips_comp_ratio_dbytes = 0;
		break;
#endif          /* CONFIG_KLIPS_IPCOMP */
	default:
		printk(KERN_ERR "KLIPS sa initialization: "
		       "proto=%d unknown.\n",
		       ipsp->ips_said.proto);
		SENDERR(EINVAL);
	}

errlab:
	return error;
}
Пример #27
0
static void
SHA1Init_int(void *ctx)
{
	SHA1Init(ctx);
}
Пример #28
0
int cli_fmap_scandesc(cli_ctx *ctx, cli_file_t ftype, uint8_t ftonly, struct cli_matched_type **ftoffset, unsigned int acmode, struct cli_ac_result **acres, unsigned char *refhash)
{
	const unsigned char *buff;
	int ret = CL_CLEAN, type = CL_CLEAN, bytes, compute_hash[CLI_HASH_AVAIL_TYPES];
	unsigned int i = 0, bm_offmode = 0;
	uint32_t maxpatlen, offset = 0;
	struct cli_ac_data gdata, tdata;
	struct cli_bm_off toff;
	cli_md5_ctx md5ctx;
	SHA256_CTX sha256ctx;
	SHA1Context sha1ctx;
	unsigned char digest[CLI_HASH_AVAIL_TYPES][32];
	struct cli_matcher *groot = NULL, *troot = NULL;
	struct cli_target_info info;
	fmap_t *map = *ctx->fmap;
	struct cli_matcher *hdb, *fp;
	const char *virname = NULL;
	uint32_t viroffset = 0;
	uint32_t viruses_found = 0;

    if(!ctx->engine) {
	cli_errmsg("cli_scandesc: engine == NULL\n");
	return CL_ENULLARG;
    }

    if(!ftonly)
	groot = ctx->engine->root[0]; /* generic signatures */

    if(ftype) {
	for(i = 1; i < CLI_MTARGETS; i++) {
	    if(cli_mtargets[i].target == ftype) {
		troot = ctx->engine->root[i];
		break;
	    }
	}
    }

    if(ftonly) {
	if(!troot)
	    return CL_CLEAN;

	maxpatlen = troot->maxpatlen;
    } else {
	if(troot)
	    maxpatlen = MAX(troot->maxpatlen, groot->maxpatlen);
	else
	    maxpatlen = groot->maxpatlen;
    }

    targetinfo(&info, i, map);

    if(!ftonly)
	if((ret = cli_ac_initdata(&gdata, groot->ac_partsigs, groot->ac_lsigs, groot->ac_reloff_num, CLI_DEFAULT_AC_TRACKLEN)) || (ret = cli_ac_caloff(groot, &gdata, &info))) {
	    if(info.exeinfo.section)
		free(info.exeinfo.section);
	    cli_hashset_destroy(&info.exeinfo.vinfo);
	    return ret;
	}

    if(troot) {
	if((ret = cli_ac_initdata(&tdata, troot->ac_partsigs, troot->ac_lsigs, troot->ac_reloff_num, CLI_DEFAULT_AC_TRACKLEN)) || (ret = cli_ac_caloff(troot, &tdata, &info))) {
	    if(!ftonly)
		cli_ac_freedata(&gdata);
	    if(info.exeinfo.section)
		free(info.exeinfo.section);
	    cli_hashset_destroy(&info.exeinfo.vinfo);
	    return ret;
	}
	if(troot->bm_offmode) {
	    if(map->len >= CLI_DEFAULT_BM_OFFMODE_FSIZE) {
		if((ret = cli_bm_initoff(troot, &toff, &info))) {
		    if(!ftonly)
			cli_ac_freedata(&gdata);
		    cli_ac_freedata(&tdata);
		    if(info.exeinfo.section)
			free(info.exeinfo.section);
		    cli_hashset_destroy(&info.exeinfo.vinfo);
		    return ret;
		}
		bm_offmode = 1;
	    }
	}
    }

    hdb = ctx->engine->hm_hdb;
    fp = ctx->engine->hm_fp;

    if(!ftonly && hdb) {
	if(!refhash) {
	    if(cli_hm_have_size(hdb, CLI_HASH_MD5, map->len) || cli_hm_have_size(fp, CLI_HASH_MD5, map->len)) {
		cli_md5_init(&md5ctx);
		compute_hash[CLI_HASH_MD5] = 1;
	    } else
		compute_hash[CLI_HASH_MD5] = 0;
	} else {
	    compute_hash[CLI_HASH_MD5] = 0;
	    memcpy(digest[CLI_HASH_MD5], refhash, 16);
	}

	if(cli_hm_have_size(hdb, CLI_HASH_SHA1, map->len) || cli_hm_have_wild(hdb, CLI_HASH_SHA1)
		|| cli_hm_have_size(fp, CLI_HASH_SHA1, map->len) || cli_hm_have_wild(fp, CLI_HASH_SHA1) ) {
	    SHA1Init(&sha1ctx);
	    compute_hash[CLI_HASH_SHA1] = 1;
	} else
	    compute_hash[CLI_HASH_SHA1] = 0;

	if(cli_hm_have_size(hdb, CLI_HASH_SHA256, map->len) || cli_hm_have_wild(hdb, CLI_HASH_SHA256)
		|| cli_hm_have_size(fp, CLI_HASH_SHA256, map->len) || cli_hm_have_wild(fp, CLI_HASH_SHA256)) {
	    sha256_init(&sha256ctx);
	    compute_hash[CLI_HASH_SHA256] = 1;
	} else
	    compute_hash[CLI_HASH_SHA256] = 0;
    }

    while(offset < map->len) {
	bytes = MIN(map->len - offset, SCANBUFF);
	if(!(buff = fmap_need_off_once(map, offset, bytes)))
	    break;
	if(ctx->scanned)
	    *ctx->scanned += bytes / CL_COUNT_PRECISION;

    if (ctx->engine->cb_progress && map->handle_is_fd && !ctx->engine->cb_progress((ssize_t) map->handle, bytes, ctx->engine->cb_progress_ctx))
        return CL_BREAK;

	if(troot) {
            virname = NULL;
            viroffset = 0;
	    ret = matcher_run(troot, buff, bytes, &virname, &tdata, offset, &info, ftype, ftoffset, acmode, acres, map, bm_offmode ? &toff : NULL, &viroffset, ctx);

	    if (virname) {
		/* virname already appended by matcher_run */
		viruses_found = 1;
	    }
	    if((ret == CL_VIRUS && !SCAN_ALL) || ret == CL_EMEM) {
		if(!ftonly)
		    cli_ac_freedata(&gdata);
		cli_ac_freedata(&tdata);
		if(bm_offmode)
		    cli_bm_freeoff(&toff);
		if(info.exeinfo.section)
		    free(info.exeinfo.section);
		cli_hashset_destroy(&info.exeinfo.vinfo);
		return ret;
	    }
	}

	if(!ftonly) {
	    virname = NULL;
	    viroffset = 0;
	    ret = matcher_run(groot, buff, bytes, &virname, &gdata, offset, &info, ftype, ftoffset, acmode, acres, map, NULL, &viroffset, ctx);

            if (virname) {
		/* virname already appended by matcher_run */
		viruses_found = 1;
	    }
	    if((ret == CL_VIRUS && !SCAN_ALL) || ret == CL_EMEM) {
		cli_ac_freedata(&gdata);
		if(troot) {
		    cli_ac_freedata(&tdata);
		    if(bm_offmode)
			cli_bm_freeoff(&toff);
		}
		if(info.exeinfo.section)
		    free(info.exeinfo.section);
		cli_hashset_destroy(&info.exeinfo.vinfo);
		return ret;
	    } else if((acmode & AC_SCAN_FT) && ret >= CL_TYPENO) {
		if(ret > type)
		    type = ret;
	    }

	    if(hdb && !SCAN_ALL) {
		const void *data = buff + maxpatlen * (offset!=0);
		uint32_t data_len = bytes - maxpatlen * (offset!=0);

		if(compute_hash[CLI_HASH_MD5])
		    cli_md5_update(&md5ctx, data, data_len);
		if(compute_hash[CLI_HASH_SHA1])
		    SHA1Update(&sha1ctx, data, data_len);
		if(compute_hash[CLI_HASH_SHA256])
		    sha256_update(&sha256ctx, data, data_len);
	    }
	}

	if(SCAN_ALL && viroffset) {
	    offset = viroffset;
	    continue;
	}
	if(bytes < SCANBUFF) break;
	offset += bytes - maxpatlen;
    }

    if(!ftonly && hdb) {
	enum CLI_HASH_TYPE hashtype, hashtype2;

	if(compute_hash[CLI_HASH_MD5])
	    cli_md5_final(digest[CLI_HASH_MD5], &md5ctx);
	if(refhash)
	    compute_hash[CLI_HASH_MD5] = 1;
	if(compute_hash[CLI_HASH_SHA1])
	    SHA1Final(&sha1ctx, digest[CLI_HASH_SHA1]);
	if(compute_hash[CLI_HASH_SHA256])
	    sha256_final(&sha256ctx, digest[CLI_HASH_SHA256]);

	virname = NULL;
	for(hashtype = CLI_HASH_MD5; hashtype < CLI_HASH_AVAIL_TYPES; hashtype++) {
	    const char * virname_w = NULL;
	    int found = 0;

	    /* If no hash, skip to next type */
	    if(!compute_hash[hashtype])
		continue;

	    /* Do hash scan */
	    if((ret = cli_hm_scan(digest[hashtype], map->len, &virname, hdb, hashtype)) == CL_VIRUS) {
		found += 1;
	    }
	    if(!found || SCAN_ALL) {
		if ((ret = cli_hm_scan_wild(digest[hashtype], &virname_w, hdb, hashtype)) == CL_VIRUS)
		    found += 2;
	    }

	    /* If found, do immediate hash-only FP check */
	    if (found && fp) {
		for(hashtype2 = CLI_HASH_MD5; hashtype2 < CLI_HASH_AVAIL_TYPES; hashtype2++) {
		    if(!compute_hash[hashtype2])
			continue;
		    if(cli_hm_scan(digest[hashtype2], map->len, NULL, fp, hashtype2) == CL_VIRUS) {
			found = 0;
			ret = CL_CLEAN;
			break;
		    }
		    else if(cli_hm_scan_wild(digest[hashtype2], NULL, fp, hashtype2) == CL_VIRUS) {
			found = 0;
			ret = CL_CLEAN;
			break;
		    }
		}
	    }

	    /* If matched size-based hash ... */
	    if (found % 2) {
		viruses_found = 1;
		cli_append_virus(ctx, virname);
		if (!SCAN_ALL)
		    break;
		virname = NULL;
	    }
	    /* If matched size-agnostic hash ... */
	    if (found > 1) {
		viruses_found = 1;
		cli_append_virus(ctx, virname_w);
		if (!SCAN_ALL)
		    break;
	    }
	}
    }

    if(troot) {
	if(ret != CL_VIRUS || SCAN_ALL)
	    ret = cli_lsig_eval(ctx, troot, &tdata, &info, refhash);
	if (ret == CL_VIRUS)
	    viruses_found++;
	cli_ac_freedata(&tdata);
	if(bm_offmode)
	    cli_bm_freeoff(&toff);
    }

    if(groot) {
	if(ret != CL_VIRUS || SCAN_ALL)
	    ret = cli_lsig_eval(ctx, groot, &gdata, &info, refhash);
	cli_ac_freedata(&gdata);
    }

    if(info.exeinfo.section)
	free(info.exeinfo.section);
    cli_hashset_destroy(&info.exeinfo.vinfo);

    if (SCAN_ALL && viruses_found)
	return CL_VIRUS;
    if(ret == CL_VIRUS)
	return CL_VIRUS;

    return (acmode & AC_SCAN_FT) ? type : CL_CLEAN;
}
Пример #29
0
int cli_checkfp(unsigned char *digest, size_t size, cli_ctx *ctx)
{
	char md5[33];
	unsigned int i;
	const char *virname;
        SHA1Context sha1;
        SHA256_CTX sha256;
        fmap_t *map;
        const char *ptr;
        uint8_t shash1[SHA1_HASH_SIZE*2+1];
        uint8_t shash256[SHA256_HASH_SIZE*2+1];
	int have_sha1, have_sha256, do_dsig_check = 1;

    if(cli_hm_scan(digest, size, &virname, ctx->engine->hm_fp, CLI_HASH_MD5) == CL_VIRUS) {
	cli_dbgmsg("cli_checkfp(md5): Found false positive detection (fp sig: %s), size: %d\n", virname, (int)size);
	return CL_CLEAN;
    }
    else if(cli_hm_scan_wild(digest, &virname, ctx->engine->hm_fp, CLI_HASH_MD5) == CL_VIRUS) {
	cli_dbgmsg("cli_checkfp(md5): Found false positive detection (fp sig: %s), size: *\n", virname);
	return CL_CLEAN;
    }

    if(cli_debug_flag || ctx->engine->cb_hash) {
	for(i = 0; i < 16; i++)
	    sprintf(md5 + i * 2, "%02x", digest[i]);
	md5[32] = 0;
	cli_dbgmsg("FP SIGNATURE: %s:%u:%s\n", md5, (unsigned int) size,
		   cli_get_last_virus(ctx) ? cli_get_last_virus(ctx) : "Name");
    }

    if(cli_get_last_virus(ctx))
	do_dsig_check = strncmp("W32S.", cli_get_last_virus(ctx), 5);

    map = *ctx->fmap;
    have_sha1 = cli_hm_have_size(ctx->engine->hm_fp, CLI_HASH_SHA1, size)
	 || cli_hm_have_wild(ctx->engine->hm_fp, CLI_HASH_SHA1)
	 || (cli_hm_have_size(ctx->engine->hm_fp, CLI_HASH_SHA1, 1) && do_dsig_check);
    have_sha256 = cli_hm_have_size(ctx->engine->hm_fp, CLI_HASH_SHA256, size)
	 || cli_hm_have_wild(ctx->engine->hm_fp, CLI_HASH_SHA256);
    if(have_sha1 || have_sha256) {
	if((ptr = fmap_need_off_once(map, 0, size))) {
	    if(have_sha1) {
		SHA1Init(&sha1);
		SHA1Update(&sha1, ptr, size);
		SHA1Final(&sha1, &shash1[SHA1_HASH_SIZE]);
		if(cli_hm_scan(&shash1[SHA1_HASH_SIZE], size, &virname, ctx->engine->hm_fp, CLI_HASH_SHA1) == CL_VIRUS) {
		    cli_dbgmsg("cli_checkfp(sha1): Found false positive detection (fp sig: %s)\n", virname);
		    return CL_CLEAN;
		}
		if(cli_hm_scan_wild(&shash1[SHA1_HASH_SIZE], &virname, ctx->engine->hm_fp, CLI_HASH_SHA1) == CL_VIRUS) {
		    cli_dbgmsg("cli_checkfp(sha1): Found false positive detection (fp sig: %s)\n", virname);
		    return CL_CLEAN;
		}
		if(do_dsig_check && cli_hm_scan(&shash1[SHA1_HASH_SIZE], 1, &virname, ctx->engine->hm_fp, CLI_HASH_SHA1) == CL_VIRUS) {
		    cli_dbgmsg("cli_checkfp(sha1): Found false positive detection via catalog file\n");
		    return CL_CLEAN;
		}
	    }
	    if(have_sha256) {
		sha256_init(&sha256);
		sha256_update(&sha256, ptr, size);
		sha256_final(&sha256, &shash256[SHA256_HASH_SIZE]);
		if(cli_hm_scan(&shash256[SHA256_HASH_SIZE], size, &virname, ctx->engine->hm_fp, CLI_HASH_SHA256) == CL_VIRUS) {
		    cli_dbgmsg("cli_checkfp(sha256): Found false positive detection (fp sig: %s)\n", virname);
		    return CL_CLEAN;
		}
		if(cli_hm_scan_wild(&shash256[SHA256_HASH_SIZE], &virname, ctx->engine->hm_fp, CLI_HASH_SHA256) == CL_VIRUS) {
		    cli_dbgmsg("cli_checkfp(sha256): Found false positive detection (fp sig: %s)\n", virname);
		    return CL_CLEAN;
		}
	    }
	}
    }

#ifdef HAVE__INTERNAL__SHA_COLLECT
    if((ctx->options & CL_SCAN_INTERNAL_COLLECT_SHA) && ctx->sha_collect>0) {
        if((ptr = fmap_need_off_once(map, 0, size))) {
	    if(!have_sha256) {
		sha256_init(&sha256);
		sha256_update(&sha256, ptr, size);
		sha256_final(&sha256, &shash256[SHA256_HASH_SIZE]);
	    }
            for(i=0; i<SHA256_HASH_SIZE; i++)
                sprintf((char *)shash256+i*2, "%02x", shash256[SHA256_HASH_SIZE+i]);

	    if(!have_sha1) {
		SHA1Init(&sha1);
		SHA1Update(&sha1, ptr, size);
		SHA1Final(&sha1, &shash1[SHA1_HASH_SIZE]);
	    }
            for(i=0; i<SHA1_HASH_SIZE; i++)
                sprintf((char *)shash1+i*2, "%02x", shash1[SHA1_HASH_SIZE+i]);

	    cli_errmsg("COLLECT:%s:%s:%u:%s:%s\n", shash256, shash1, size, cli_get_last_virus(ctx), ctx->entry_filename);
        } else
            cli_errmsg("can't compute sha\n!");
        ctx->sha_collect = -1;
    }
#endif

    if(do_dsig_check) {
	switch(cli_checkfp_pe(ctx, shash1)) {
	case CL_CLEAN:
	    cli_dbgmsg("cli_checkfp(pe): PE file whitelisted due to valid embedded digital signature\n");
	    return CL_CLEAN;
	case CL_VIRUS:
	    if(cli_hm_scan(shash1, 2, &virname, ctx->engine->hm_fp, CLI_HASH_SHA1) == CL_VIRUS) {
		cli_dbgmsg("cli_checkfp(pe): PE file whitelisted by catalog file\n");
		return CL_CLEAN;
	    }
	}
    }
    if (ctx->engine->cb_hash)
	ctx->engine->cb_hash(fmap_fd(*ctx->fmap), size, md5, cli_get_last_virus(ctx), ctx->cb_ctx);

    return CL_VIRUS;
}
Пример #30
0
static Datum
uuid_generate_internal(int v, unsigned char *ns, char *ptr, int len)
{
	char		strbuf[40];

	switch (v)
	{
		case 0:			/* constant-value uuids */
			strlcpy(strbuf, ptr, 37);
			break;

		case 1:			/* time/node-based uuids */
			{
#ifdef HAVE_UUID_E2FS
				uuid_t		uu;

				uuid_generate_time(uu);
				uuid_unparse(uu, strbuf);

				/*
				 * PTR, if set, replaces the trailing characters of the uuid;
				 * this is to support v1mc, where a random multicast MAC is
				 * used instead of the physical one
				 */
				if (ptr && len <= 36)
					strcpy(strbuf + (36 - len), ptr);
#else							/* BSD */
				uuid_t		uu;
				uint32_t	status = uuid_s_ok;
				char	   *str = NULL;

				uuid_create(&uu, &status);

				if (status == uuid_s_ok)
				{
					uuid_to_string(&uu, &str, &status);
					if (status == uuid_s_ok)
					{
						strlcpy(strbuf, str, 37);

						/*
						 * PTR, if set, replaces the trailing characters of
						 * the uuid; this is to support v1mc, where a random
						 * multicast MAC is used instead of the physical one
						 */
						if (ptr && len <= 36)
							strcpy(strbuf + (36 - len), ptr);
					}
					if (str)
						free(str);
				}

				if (status != uuid_s_ok)
					ereport(ERROR,
							(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
							 errmsg("uuid library failure: %d",
									(int) status)));
#endif
				break;
			}

		case 3:			/* namespace-based MD5 uuids */
		case 5:			/* namespace-based SHA1 uuids */
			{
				dce_uuid_t	uu;
#ifdef HAVE_UUID_BSD
				uint32_t	status = uuid_s_ok;
				char	   *str = NULL;
#endif

				if (v == 3)
				{
					MD5_CTX		ctx;

					MD5Init(&ctx);
					MD5Update(&ctx, ns, sizeof(uu));
					MD5Update(&ctx, (unsigned char *) ptr, len);
					/* we assume sizeof MD5 result is 16, same as UUID size */
					MD5Final((unsigned char *) &uu, &ctx);
				}
				else
				{
					SHA1_CTX	ctx;
					unsigned char sha1result[SHA1_RESULTLEN];

					SHA1Init(&ctx);
					SHA1Update(&ctx, ns, sizeof(uu));
					SHA1Update(&ctx, (unsigned char *) ptr, len);
					SHA1Final(sha1result, &ctx);
					memcpy(&uu, sha1result, sizeof(uu));
				}

				/* the calculated hash is using local order */
				UUID_TO_NETWORK(uu);
				UUID_V3_OR_V5(uu, v);

#ifdef HAVE_UUID_E2FS
				/* uuid_unparse expects local order */
				UUID_TO_LOCAL(uu);
				uuid_unparse((unsigned char *) &uu, strbuf);
#else							/* BSD */
				uuid_to_string(&uu, &str, &status);

				if (status == uuid_s_ok)
					strlcpy(strbuf, str, 37);

				if (str)
					free(str);

				if (status != uuid_s_ok)
					ereport(ERROR,
							(errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
							 errmsg("uuid library failure: %d",
									(int) status)));
#endif
				break;
			}

		case 4:			/* random uuid */
		default:
			{
#ifdef HAVE_UUID_E2FS
				uuid_t		uu;

				uuid_generate_random(uu);
				uuid_unparse(uu, strbuf);
#else							/* BSD */
				snprintf(strbuf, sizeof(strbuf),
						 "%08lx-%04x-%04x-%04x-%04x%08lx",
						 (unsigned long) arc4random(),
						 (unsigned) (arc4random() & 0xffff),
						 (unsigned) ((arc4random() & 0xfff) | 0x4000),
						 (unsigned) ((arc4random() & 0x3fff) | 0x8000),
						 (unsigned) (arc4random() & 0xffff),
						 (unsigned long) arc4random());
#endif
				break;
			}
	}

	return DirectFunctionCall1(uuid_in, CStringGetDatum(strbuf));
}