示例#1
0
int
generate_challenge(char **r_challenge, char **r_response, RSA * rsa)
{
	unsigned char secret[32], *tmp;
	unsigned long length, ret;

	if(!rsa)
		return -1;

	if(get_randomness(secret, 32) == 0)
	{
		report_crypto_errors();
		return -1;
	}

	*r_response = MyMalloc(65);
	binary_to_hex(secret, *r_response, 32);

	length = RSA_size(rsa);
	tmp = MyMalloc(length);
	ret = RSA_public_encrypt(32, secret, tmp, rsa, RSA_PKCS1_PADDING);

	*r_challenge = MyMalloc((length << 1) + 1);
	binary_to_hex(tmp, *r_challenge, length);
	(*r_challenge)[length << 1] = 0;
	MyFree(tmp);

	if(ret < 0)
	{
		report_crypto_errors();
		return (-1);
	}
	return (0);
}
示例#2
0
static bool verify_credentials(struct cram_auth_request *request,
                               const unsigned char *credentials, size_t size)
{

    unsigned char digest[MD5_RESULTLEN];
    struct hmac_context ctx;
    const char *response_hex;

    if (size != CRAM_MD5_CONTEXTLEN) {
        auth_request_log_error(&request->auth_request, AUTH_SUBSYS_MECH,
                               "invalid credentials length");
        return FALSE;
    }

    hmac_init(&ctx, NULL, 0, &hash_method_md5);
    hmac_md5_set_cram_context(&ctx, credentials);
    hmac_update(&ctx, request->challenge, strlen(request->challenge));
    hmac_final(&ctx, digest);

    response_hex = binary_to_hex(digest, sizeof(digest));

    if (memcmp(response_hex, request->response, sizeof(digest)*2) != 0) {
        auth_request_log_info(&request->auth_request, AUTH_SUBSYS_MECH,
                              "password mismatch");
        return FALSE;
    }

    return TRUE;
}
示例#3
0
static int imapc_mail_get_hdr_hash(struct index_mail *imail)
{
	struct istream *input;
	const unsigned char *data;
	size_t size;
	uoff_t old_offset;
	struct sha1_ctxt sha1_ctx;
	unsigned char sha1_output[SHA1_RESULTLEN];
	const char *sha1_str;

	sha1_init(&sha1_ctx);
	old_offset = imail->data.stream == NULL ? 0 :
		imail->data.stream->v_offset;
	if (mail_get_hdr_stream(&imail->mail.mail, NULL, &input) < 0)
		return -1;
	while (i_stream_read_data(input, &data, &size, 0) > 0) {
		sha1_loop(&sha1_ctx, data, size);
		i_stream_skip(input, size);
	}
	i_stream_seek(imail->data.stream, old_offset);
	sha1_result(&sha1_ctx, sha1_output);

	sha1_str = binary_to_hex(sha1_output, sizeof(sha1_output));
	imail->data.guid = p_strdup(imail->mail.data_pool, sha1_str);
	return 0;
}
示例#4
0
static
void test_static_v1_input_short(void)
{
	ssize_t siz;
	const struct hash_method *hash = hash_method_lookup("sha256");
	unsigned char hash_ctx[hash->context_size];
	unsigned char hash_dgst[hash->digest_size];
	hash->init(hash_ctx);

	test_begin("test_static_v1_input_short");

	struct istream *is_1 = i_stream_create_file(DCRYPT_SRC_DIR"/sample-v1_short.asc", IO_BLOCK_SIZE);
	struct istream *is_2 = i_stream_create_base64_decoder(is_1);
	i_stream_unref(&is_1);
	struct istream *is_3 = i_stream_create_decrypt(is_2, test_v1_kp.priv);
	i_stream_unref(&is_2);
	struct istream *is_4 = i_stream_create_hash(is_3, hash, hash_ctx);
	i_stream_unref(&is_3);

	while((siz = i_stream_read(is_4))>0) { i_stream_skip(is_4, siz); }

	if (is_4->stream_errno != 0)
		i_debug("error: %s", i_stream_get_error(is_4));

	test_assert(is_4->stream_errno == 0);

	i_stream_unref(&is_4);

	hash->result(hash_ctx, hash_dgst);

	test_assert(strcmp(test_sample_v1_short_hash, binary_to_hex(hash_dgst, sizeof(hash_dgst))) == 0);

	test_end();
}
示例#5
0
bool password_generate_encoded(const char *plaintext, const struct password_generate_params *params,
			       const char *scheme, const char **password_r)
{
	const struct password_scheme *s;
	const unsigned char *raw_password;
	enum password_encoding encoding;
	string_t *str;
	size_t size;

	s = password_scheme_lookup(scheme, &encoding);
	if (s == NULL)
		return FALSE;

	s->password_generate(plaintext, params, &raw_password, &size);
	switch (encoding) {
	case PW_ENCODING_NONE:
		*password_r = t_strndup(raw_password, size);
		break;
	case PW_ENCODING_BASE64:
		str = t_str_new(MAX_BASE64_ENCODED_SIZE(size) + 1);
		base64_encode(raw_password, size, str);
		*password_r = str_c(str);
		break;
	case PW_ENCODING_HEX:
		*password_r = binary_to_hex(raw_password, size);
		break;
	}
	return TRUE;
}
示例#6
0
/*******************************************************************-o-******
 * dump_chunk
 *
 * Parameters:
 *	*title	(May be NULL.)
 *	*buf
 *	 size
 */
void
dump_chunk(const char *debugtoken, const char *title, const u_char * buf,
           int size)
{
    u_int           printunit = 64;     /* XXX  Make global. */
    char            chunk[SNMP_MAXBUF], *s, *sp;

    if (title && (*title != '\0')) {
        DEBUGMSGTL((debugtoken, "%s\n", title));
    }


    memset(chunk, 0, SNMP_MAXBUF);
    size = binary_to_hex(buf, size, &s);
    sp = s;

    while (size > 0) {
        if (size > (int) printunit) {
            strncpy(chunk, sp, printunit);
            chunk[printunit] = '\0';
            DEBUGMSGTL((debugtoken, "\t%s\n", chunk));
        } else {
            DEBUGMSGTL((debugtoken, "\t%s\n", sp));
        }

        sp += printunit;
        size -= printunit;
    }


    SNMP_FREE(s);

}                               /* end dump_chunk() */
示例#7
0
static ssize_t i_stream_base64_decoder_read(struct istream_private *stream)
{
	struct base64_decoder_istream *bstream =
		(struct base64_decoder_istream *)stream;
	const unsigned char *data;
	size_t pre_count, post_count, size;
	int ret;

	do {
		ret = i_stream_read_parent(stream);
		if (ret <= 0) {
			if (ret < 0 && stream->istream.stream_errno == 0 &&
			    i_stream_get_data_size(stream->parent) > 0) {
				/* base64 input with a partial block */
				data = i_stream_get_data(stream->parent, &size);
				io_stream_set_error(&stream->iostream,
					"base64 input ends with a partial block: 0x%s",
					binary_to_hex(data, size));
				stream->istream.stream_errno = EINVAL;
			}
			return ret;
		}

		/* encode as many blocks as fits into destination buffer */
		pre_count = stream->pos - stream->skip;
		while ((ret = i_stream_base64_try_decode_block(bstream)) > 0) ;
		post_count = stream->pos - stream->skip;
	} while (ret == 0 && pre_count == post_count);

	if (ret < 0 && pre_count == post_count)
		return ret;

	i_assert(post_count > pre_count);
	return post_count - pre_count;
}
/*******************************************************************-o-******
 * dump_etimelist_entry
 *
 * Parameters:
 *	e
 *	count
 */
void
dump_etimelist_entry(Enginetime e, int count)
{
    u_int           buflen;
    char            tabs[SNMP_MAXBUF], *t = tabs, *s;



    count += 1;
    while (count--) {
        t += sprintf(t, "  ");
    }


    buflen = e->engineID_len;
#ifdef NETSNMP_ENABLE_TESTING_CODE
    if (!(s = dump_snmpEngineID(e->engineID, &buflen))) {
#endif
        binary_to_hex(e->engineID, e->engineID_len, &s);
#ifdef NETSNMP_ENABLE_TESTING_CODE
    }
#endif

    DEBUGMSGTL(("dump_etimelist", "%s\n", tabs));
    DEBUGMSGTL(("dump_etimelist", "%s%s (len=%d) <%d,%d>\n", tabs,
                s, e->engineID_len, e->engineTime, e->engineBoot));
    DEBUGMSGTL(("dump_etimelist", "%s%ld (%ld)", tabs,
                e->lastReceivedEngineTime,
                snmpv3_local_snmpEngineTime() - e->lastReceivedEngineTime));

    SNMP_FREE(s);

}                               /* end dump_etimelist_entry() */
示例#9
0
int dsync_mail_get_hdr_hash(struct mail *mail, const char **hdr_hash_r)
{
	struct istream *hdr_input, *input;
	struct mailbox_header_lookup_ctx *hdr_ctx;
	struct md5_context md5_ctx;
	unsigned char md5_result[MD5_RESULTLEN];
	const unsigned char *data;
	size_t size;
	int ret = 0;

	hdr_ctx = mailbox_header_lookup_init(mail->box, hashed_headers);
	ret = mail_get_header_stream(mail, hdr_ctx, &hdr_input);
	mailbox_header_lookup_unref(&hdr_ctx);
	if (ret < 0)
		return -1;

	input = i_stream_create_lf(hdr_input);

	md5_init(&md5_ctx);
	while (!i_stream_is_eof(input)) {
		if (i_stream_read_data(input, &data, &size, 0) == -1)
			break;
		if (size == 0)
			break;
		md5_update(&md5_ctx, data, size);
		i_stream_skip(input, size);
	}
	if (input->stream_errno != 0)
		ret = -1;
	i_stream_unref(&input);

	md5_final(&md5_ctx, md5_result);
	*hdr_hash_r = binary_to_hex(md5_result, sizeof(md5_result));
	return ret;
}
示例#10
0
int
main(int argc, char **argv)
{
	FILE *kfile;
	RSA *rsa = NULL;
	char ndata[257], ddata[257];
	/* respond privatefile challenge */
	if (argc < 3)
	{
		puts("Usage: respond privatefile challenge [passphrase]");
		return 0;
	}

	if (argc == 4)
	{
		/* This is TOTALLY insecure and not recommended, but for
		** interfacing with irc client scripts, it's either this
		** or don't use a passphrase.
		**
		** The likelihood of a passphrase leaking isn't TOO great,
		** only ps auxww will show it, and even then, only at the
		** precise moment this is called.
		*/
		insecure_mode = 1;
		pass_param = argv[3];
	}

	if (!(kfile = fopen(argv[1], "r")))
	{
		puts("Could not open the private keyfile.");
		return 0;
	}
	
	SSLeay_add_all_ciphers();
	rsa = PEM_read_RSAPrivateKey(kfile, NULL,pass_cb, NULL);
  
	if(!rsa)
	{
		puts("Unable to read your private key, is the passphrase wrong?");
		return 0;
	}

	 fclose(kfile);
	if (hex_to_binary(argv[2], ndata, 128) != 128)
	{
		puts("Bad challenge.");
		return -1;
	}

	if (RSA_private_decrypt(128, (unsigned char*)ndata,
		(unsigned char*)ddata, rsa, RSA_PKCS1_PADDING) == -1)
	{
		puts("Decryption error.");
		return -1;
	}
	binary_to_hex((unsigned char*)ddata, ndata, 32);
	puts(ndata);
	return 0;
}
示例#11
0
static const char *unique_fname(void)
{
	unsigned char randbuf[8];

	random_fill_weak(randbuf, sizeof(randbuf));
	return t_strdup_printf("%s.%s.%s", my_hostname, my_pid,
			       binary_to_hex(randbuf, sizeof(randbuf)));

}
示例#12
0
static
void test_static_v2_input(void)
{
	test_begin("test_static_v2_input");

	ssize_t amt;
	const struct hash_method *hash = hash_method_lookup("sha256");
	unsigned char hash_ctx[hash->context_size];
	unsigned char hash_dgst[hash->digest_size];
	hash->init(hash_ctx);

	struct istream *is_1 = i_stream_create_file(DCRYPT_SRC_DIR"/sample-v2.asc", IO_BLOCK_SIZE);
	struct istream *is_2 = i_stream_create_base64_decoder(is_1);
	i_stream_unref(&is_1);
	struct istream *is_3 = i_stream_create_decrypt(is_2, test_v2_kp.priv);
	i_stream_unref(&is_2);
	struct istream *is_4 = i_stream_create_hash(is_3, hash, hash_ctx);
	i_stream_unref(&is_3);

	while((amt = i_stream_read(is_4))>0) { i_stream_skip(is_4, amt); }

	if (is_4->stream_errno != 0)
		i_debug("error: %s", i_stream_get_error(is_4));

	test_assert(is_4->stream_errno == 0);

	i_stream_unref(&is_4);

	hash->result(hash_ctx, hash_dgst);

	test_assert(strcmp(test_sample_v2_hash, binary_to_hex(hash_dgst, sizeof(hash_dgst))) == 0);

	test_end();

/** this code is left here to show how the sample file is created
	struct istream *is = i_stream_create_file("../lib-fts/udhr_fra.txt", 8192);
	struct istream *is_2 = i_stream_create_hash(is, hash, hash_ctx);
	int fd = open("sample-v2.bin", O_CREAT|O_TRUNC|O_WRONLY, S_IRWXU);
	struct ostream *os = o_stream_create_fd_file(fd, 0, TRUE);
	struct ostream *os_2 = o_stream_create_encrypt(os, "aes-256-gcm-sha256", test_v2_kp.pub, IO_STREAM_ENC_INTEGRITY_AEAD);
	const unsigned char *ptr;
	size_t siz;

	while(i_stream_read_data(is_2, &ptr, &siz, 0)>0) {
		o_stream_nsend(os_2, ptr, siz);
		i_stream_skip(is_2, siz);
	}

	i_assert(o_stream_nfinish(os_2)==0);

	o_stream_close(os_2);
	i_stream_close(is_2);

	hash->result(hash_ctx, hash_dgst);
	printf("%s\n", binary_to_hex(hash_dgst, sizeof(hash_dgst)));
*/
}
示例#13
0
safe_mkstemp_full(string_t *prefix, mode_t mode, uid_t uid, gid_t gid,
		  const char *gid_origin)
{
	size_t prefix_len;
	struct stat st;
	unsigned char randbuf[8];
	mode_t old_umask;
	int fd;

	prefix_len = str_len(prefix);
	for (;;) {
		do {
			random_fill_weak(randbuf, sizeof(randbuf));
			str_truncate(prefix, prefix_len);
			str_append(prefix,
				   binary_to_hex(randbuf, sizeof(randbuf)));
		} while (lstat(str_c(prefix), &st) == 0);

		if (errno != ENOENT) {
			i_error("stat(%s) failed: %m", str_c(prefix));
			str_truncate(prefix, prefix_len);
			return -1;
		}

		old_umask = umask(0666 ^ mode);
		fd = open(str_c(prefix), O_RDWR | O_EXCL | O_CREAT, 0666);
		umask(old_umask);
		if (fd != -1)
			break;

		if (errno != EEXIST) {
			if (errno != ENOENT && errno != EACCES)
				i_error("open(%s) failed: %m", str_c(prefix));
			str_truncate(prefix, prefix_len);
			return -1;
		}
	}
	if (uid == (uid_t)-1 && gid == (gid_t)-1)
		return fd;

	if (fchown(fd, uid, gid) < 0) {
		if (errno == EPERM) {
			i_error("%s", eperm_error_get_chgrp("fchown",
					str_c(prefix), gid, gid_origin));
		} else {
			i_error("fchown(%s, %ld, %ld) failed: %m",
				str_c(prefix),
				uid == (uid_t)-1 ? -1L : (long)uid,
				gid == (gid_t)-1 ? -1L : (long)gid);
		}
		i_close_fd(&fd);
		(void)unlink(str_c(prefix));
		return -1;
	}
	return fd;
}
示例#14
0
/*******************************************************************-o-******
 * test_genKu
 *
 * Returns:
 *	Number of failures.
 *
 *
 * Test generation of usmUser master key from a passphrase.
 *
 * ASSUMES  Passphrase is made of printable characters!
 */
int
test_genKu(void)
{
    int             rval = SNMPERR_SUCCESS,
        failcount = 0,
        properlength = BYTESIZE(SNMP_TRANS_AUTHLEN_HMACMD5), kulen;
    char           *hashname = "usmHMACMD5AuthProtocol.", *s;
    u_char          Ku[LOCAL_MAXBUF];
    oid            *hashtype = usmHMACMD5AuthProtocol;

    OUTPUT("Test of generate_Ku --");

    /*
     * Set passphrase.
     */
    if (!passphrase) {
        passphrase = PASSPHRASE_DEFAULT;
    }
    if (!bequiet)
        fprintf(stdout, "Passphrase%s:\n\t%s\n\n",
                (passphrase == PASSPHRASE_DEFAULT) ? " (default)" : "",
                passphrase);


  test_genKu_again:
    memset(Ku, 0, LOCAL_MAXBUF);
    kulen = LOCAL_MAXBUF;

    rval = generate_Ku(hashtype, USM_LENGTH_OID_TRANSFORM,
                       passphrase, strlen(passphrase), Ku, &kulen);
    FAILED(rval, "generate_Ku().");

    if (kulen != properlength) {
        FAILED(SNMPERR_GENERR, "Ku length is wrong for this hashtype.");
    }

    binary_to_hex(Ku, kulen, &s);
    if (!bequiet)
        fprintf(stdout, "Ku (len=%d):  %s\n", kulen, s);
    free_zero(s, kulen);

    SUCCESS(hashname);
    if (!bequiet)
        fprintf(stdout, "\n");

    if (hashtype == usmHMACMD5AuthProtocol) {
        hashtype = usmHMACSHA1AuthProtocol;
        hashname = "usmHMACSHA1AuthProtocol.";
        properlength = BYTESIZE(SNMP_TRANS_AUTHLEN_HMACSHA1);
        goto test_genKu_again;
    }

    return failcount;

}                               /* end test_genKu() */
示例#15
0
/*
 * log CSV version of trap.
 * dontcare param is there so this function can be passed directly
 * to CONTAINER_FOR_EACH.
 */
static void
_sql_log(sql_buf *sqlb, void* dontcare)
{
    netsnmp_iterator     *it;
    sql_vb_buf           *sqlvb;

    if ((NULL == sqlb) || sqlb->logged)
        return;

    /*
     * log trap info
     * nothing done to protect against data insertion attacks with
     * respect to bad data (commas, newlines, etc)
     */
    snmp_log(LOG_ERR,
             "trap:%d-%d-%d %d:%d:%d,%s,%d,%d,%d,%s,%s,%d,%d,%d,%s,%s,%s,%s\n",
             sqlb->time.year,sqlb->time.month,sqlb->time.day,
             sqlb->time.hour,sqlb->time.minute,sqlb->time.second,
             sqlb->user,
             sqlb->type, sqlb->version, sqlb->reqid, sqlb->oid,
             sqlb->transport, sqlb->security_model, sqlb->msgid,
             sqlb->security_level, sqlb->context,
             sqlb->context_engine, sqlb->security_name,
             sqlb->security_engine);

    sqlb->logged = 1; /* prevent multiple logging */

    it = CONTAINER_ITERATOR(sqlb->varbinds);
    if (NULL == it) {
        snmp_log(LOG_ERR,
                 "error creating iterator; incomplete trap logged\n");
        return;
    }

    /** log varbind info */
    for( sqlvb = ITERATOR_FIRST(it); sqlvb; sqlvb = ITERATOR_NEXT(it)) {
#ifdef NETSNMP_MYSQL_TRAP_VALUE_TEXT
        snmp_log(LOG_ERR,"varbind:%s,%s\n", sqlvb->oid, sqlvb->val);
#else
        char *hex;
        int len = binary_to_hex(sqlvb->val, sqlvb->val_len, &hex);
        if (hex) {
            snmp_log(LOG_ERR,"varbind:%d,%s,%s\n", sqlvb->oid, hex);
            free(hex);
        }
        else {
            snmp_log(LOG_ERR,"malloc failed for varbind hex value\n");
            snmp_log(LOG_ERR,"varbind:%s,\n", sqlvb->oid);
        }
#endif
    }
    ITERATOR_RELEASE(it);
   
}
示例#16
0
文件: test-buffer.c 项目: bdraco/core
static void test_foo(void)
{
	buffer_t *buf = buffer_create_dynamic(default_pool, 100);

	for (int i = 1; i <= 24; i++) {
		buffer_set_used_size(buf, 0);
		buffer_append_c(buf, 0xff);
		buffer_append_c(buf, 0xff);
		buffer_append_c(buf, 0xff);
		buffer_truncate_rshift_bits(buf, i);
		printf("%2d bits: %24s %s\n", i,
		       binary_to_hex(buf->data, buf->used),
		       binary_to_10(buf->data, buf->used));
	}
}
示例#17
0
//==============================================================================
void USB_Device::bulk_write(uint8_t endpoint, size_t count, const uint8_t data[])
{
	log_info("usb, bulk write, count: %u, data: %s", count,
			binary_to_hex(data, count, " ").c_str());

	int transferred = 0;
	endpoint |= LIBUSB_ENDPOINT_OUT;

	ssize_t result = libusb_bulk_transfer(handle_, endpoint, const_cast<uint8_t*>(data), count,
			&transferred, timeout_);
	if (result < 0)
		on_error("libusb_bulk_transfer (out)", result);

	if ((int)count != transferred)
		on_timeout_error("libusb_bulk_transfer (out)", count, transferred);
}
示例#18
0
//==============================================================================
void USB_Device::bulk_read(uint8_t endpoint, size_t count, uint8_t data[])
{
	int transferred = 0;
	endpoint |= LIBUSB_ENDPOINT_IN;

	ssize_t result = libusb_bulk_transfer(handle_, endpoint, data, count,
			&transferred, timeout_);

	log_info("usb, bulk read, count %u: data: %s",
			count, binary_to_hex(data, transferred, " ").c_str());

	if (result < 0)
		on_error("libusb_bulk_transfer (in)", result);

	if ((int)count != transferred)
		on_timeout_error("libusb_bulk_transfer (in)", count, transferred);
}
示例#19
0
const char *auth_token_get(const char *service, const char *session_pid,
			   const char *username, const char *session_id)
{
	struct hmac_context ctx;
	unsigned char result[SHA1_RESULTLEN];

	hmac_init(&ctx, (const unsigned char*)username, strlen(username),
		  &hash_method_sha1);
	hmac_update(&ctx, session_pid, strlen(session_pid));
	if (session_id != NULL && *session_id != '\0')
		hmac_update(&ctx, session_id, strlen(session_id));
	hmac_update(&ctx, service, strlen(service));
	hmac_update(&ctx, auth_token_secret, sizeof(auth_token_secret));
	hmac_final(&ctx, result);

	return binary_to_hex(result, sizeof(result));
}
示例#20
0
//==============================================================================
void USB_Device::control_read(uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue,
		uint16_t wIndex, uint8_t data[], size_t count)
{
	bmRequestType |= LIBUSB_ENDPOINT_IN;

	log_info("usb, control read, request_type: %02Xh, request: %02Xh, value: %04Xh, index: %04Xh, count: %u",
			bmRequestType, bRequest, wValue, wIndex, count);

	ssize_t result = libusb_control_transfer(handle_, bmRequestType, bRequest,
			wValue, wIndex, data, count, timeout_);
	if (result < 0)
		on_error("libusb_control_transfer (in)", result);

	if (count && (ssize_t)count != result)
		on_timeout_error("libusb_control_transfer (in)", count, result);

	log_info("usb, control read, data: %s", binary_to_hex(data, count, " ").c_str());
}
static int
i_stream_qp_try_decode_input(struct qp_decoder_istream *bstream, bool eof)
{
    struct istream_private *stream = &bstream->istream;
    const unsigned char *data;
    size_t size, avail, buffer_avail, pos;
    buffer_t buf;
    int ret;

    data = i_stream_get_data(stream->parent, &size);
    if (size == 0)
        return 0;

    /* normally the decoded quoted-printable content can't be larger than
       the encoded content, but because we always use CRLFs, it may use
       twice as much space by only converting LFs to CRLFs. */
    i_stream_try_alloc(stream, size, &avail);
    buffer_avail = stream->buffer_size - stream->pos;

    if (size > buffer_avail/2) {
        /* can't fit everything to destination buffer.
           write as much as we can. */
        size = buffer_avail/2;
        if (size == 0)
            return -2;
    }

    buffer_create_from_data(&buf, stream->w_buffer + stream->pos,
                            buffer_avail);
    ret = !eof ? quoted_printable_decode(data, size, &pos, &buf) :
          quoted_printable_decode_final(data, size, &pos, &buf);
    if (ret < 0) {
        io_stream_set_error(&stream->iostream,
                            "Invalid quoted-printable data: 0x%s",
                            binary_to_hex(data+pos, I_MAX(size-pos, 8)));
        stream->istream.stream_errno = EINVAL;
        return -1;
    }

    stream->pos += buf.used;
    i_stream_skip(stream->parent, pos);
    return pos > 0 ? 1 : 0;
}
static ssize_t i_stream_qp_decoder_read(struct istream_private *stream)
{
    struct qp_decoder_istream *bstream =
        (struct qp_decoder_istream *)stream;
    const unsigned char *data;
    size_t pre_count, post_count, size;
    int ret;
    size_t prev_size = 0;

    do {
        ret = i_stream_read_parent(stream, &prev_size);
        if (ret <= 0) {
            if (ret != -1 || stream->istream.stream_errno != 0)
                return 0;

            ret = i_stream_qp_try_decode_input(bstream, TRUE);
            if (ret == 0) {
                /* ended with =[whitespace] but without LF */
                stream->istream.eof = TRUE;
                return -1;
            }
            /* partial qp input */
            i_assert(ret < 0);
            data = i_stream_get_data(stream->parent, &size);
            io_stream_set_error(&stream->iostream,
                                "quoted-printable input ends with a partial block: 0x%s",
                                binary_to_hex(data, size));
            stream->istream.stream_errno = EINVAL;
            return -1;
        }

        /* encode as much data as fits into destination buffer */
        pre_count = stream->pos - stream->skip;
        while ((ret = i_stream_qp_try_decode_input(bstream, FALSE)) > 0) ;
        post_count = stream->pos - stream->skip;
    } while (ret == 0 && pre_count == post_count);

    if (ret < 0)
        return ret;

    i_assert(post_count > pre_count);
    return post_count - pre_count;
}
示例#23
0
//==============================================================================
void CC_UnitDriver::read_xdata_memory(uint16_t address, size_t count, ByteVector &data)
{
    log_info("programmer, read xdata memory at %04Xh, count: %u", address, count);

    uint8_t header[] = {
        0x40, 0x55, 0x00, 0x72, 0x56, 0xE5, 0x92, 0xBE, 0x57, 0x75,
        0x92, 0x00, 0x74, 0x56, 0xE5, 0x83, 0x76, 0x56, 0xE5, 0x82
    };

    uint8_t footer[] 	= { 0xD4, 0x57, 0x90, 0xC2, 0x57, 0x75, 0x92, 0x90, 0x56, 0x74 };

    uint8_t load_dtpr[] = { 0xBE, 0x57, 0x90, 0x00, 0x00 };
    uint8_t mov_a_dtpr[] = { 0x4E, 0x55, 0xE0 };
    uint8_t inc_dtpr[] 	= { 0x5E, 0x55, 0xA3 };

    ByteVector command;
    vector_append(command, header, sizeof(header));

    load_dtpr[sizeof(load_dtpr) - 1] = address;
    load_dtpr[sizeof(load_dtpr) - 2] = address >> 8;
    vector_append(command, load_dtpr, sizeof(load_dtpr));

    for (size_t i = 0; i < count; i++)
    {
        if (i == (count - 1) || !((i + 1) % 64))
            mov_a_dtpr[0] |= 1;
        else
            mov_a_dtpr[0] &= ~1;

        vector_append(command, mov_a_dtpr, sizeof(mov_a_dtpr));
        vector_append(command, inc_dtpr, sizeof(inc_dtpr));
    }
    vector_append(command, footer, sizeof(footer));

    data.resize(count);

    usb_device_.bulk_write(endpoint_out_, command.size(), &command[0]);
    usb_device_.bulk_read(endpoint_in_, count, &data[0]);

    log_info("programmer, read xdata memory, data: %s", binary_to_hex(&data[0], count, " ").c_str());
}
示例#24
0
static int
hardlink_replace(const char *src, const char *dest, ino_t src_inode)
{
	const char *p, *destdir, *tmppath;
	unsigned char randbuf[8];
	struct stat st;

	p = strrchr(dest, '/');
	i_assert(p != NULL);
	destdir = t_strdup_until(dest, p);

	random_fill_weak(randbuf, sizeof(randbuf));
	tmppath = t_strdup_printf("%s/temp.%s.%s.%s",
				  destdir, my_hostname, my_pid,
				  binary_to_hex(randbuf, sizeof(randbuf)));
	if (link(src, tmppath) < 0) {
		if (errno == EMLINK)
			return 0;
		i_error("link(%s, %s) failed: %m", src, tmppath);
		return -1;
	}
	if (stat(tmppath, &st) < 0) {
		i_error("stat(%s) failed: %m", tmppath);
		return -1;
	}
	if (st.st_ino != src_inode) {
		if (unlink(tmppath) < 0)
			i_error("unlink(%s) failed: %m", tmppath);
		return 0;
	}
	if (rename(tmppath, dest) < 0) {
		i_error("rename(%s, %s) failed: %m", src, tmppath);
		if (unlink(tmppath) < 0)
			i_error("unlink(%s) failed: %m", tmppath);
		return -1;
	}
	return 1;
}
示例#25
0
static void test_binary_to_hex(void)
{
	static unsigned char input[] = { 0xff, 0x00, 0x01, 0xb3 };
	static char *output_lcase = "ff0001b3";
	static char *output_ucase = "FF0001B3";
	string_t *str;

	test_begin("binary to hex");
	test_assert(strcmp(binary_to_hex(input, sizeof(input)), output_lcase) == 0);
	test_end();

	test_begin("binary to hex ucase");
	test_assert(strcmp(binary_to_hex_ucase(input, sizeof(input)), output_ucase) == 0);
	test_end();

	test_begin("binary to hex ucase");
	str = t_str_new(32);
	str_append_c(str, '<');
	binary_to_hex_append(str, input, sizeof(input));
	str_append_c(str, '>');
	test_assert(strcmp(str_c(str), t_strconcat("<", output_lcase, ">", NULL)) == 0);
	test_end();
}
示例#26
0
static int
i_stream_base64_try_decode_block(struct base64_decoder_istream *bstream)
{
	struct istream_private *stream = &bstream->istream;
	const unsigned char *data;
	size_t size, avail, buffer_avail, pos;
	buffer_t buf;

	data = i_stream_get_data(stream->parent, &size);
	if (size == 0)
		return 0;

	i_stream_try_alloc(stream, (size+3)/4*3, &avail);
	buffer_avail = stream->buffer_size - stream->pos;

	if ((size + 3) / 4 * 3 > buffer_avail) {
		/* can't fit everything to destination buffer.
		   write as much as we can. */
		size = (buffer_avail / 3) * 4;
		if (size == 0)
			return -2;
	}

	buffer_create_from_data(&buf, stream->w_buffer + stream->pos,
				buffer_avail);
	if (base64_decode(data, size, &pos, &buf) < 0) {
		io_stream_set_error(&stream->iostream,
			"Invalid base64 data: 0x%s",
			binary_to_hex(data+pos, I_MIN(size-pos, 8)));
		stream->istream.stream_errno = EINVAL;
		return -1;
	}

	stream->pos += buf.used;
	i_stream_skip(stream->parent, pos);
	return pos > 0 ? 1 : 0;
}
示例#27
0
_SCAPI_NOT_CONFIGURED
#endif							/*  */



/*******************************************************************-o-******
 * sc_generate_keyed_hash
 *
 * Parameters:
 *	 authtype	Type of authentication transform.
 *	 authtypelen
 *	*key		Pointer to key (Kul) to use in keyed hash.
 *	 keylen		Length of key in bytes.
 *	*message	Pointer to the message to hash.
 *	 msglen		Length of the message.
 *	*MAC		Will be returned with allocated bytes containg hash.
 *	*maclen		Length of the hash buffer in bytes; also indicates
 *				whether the MAC should be truncated.
 *      
 * Returns:
 *	SNMPERR_SUCCESS			Success.
 *	SNMPERR_GENERR			All errs
 *
 *
 * A hash of the first msglen bytes of message using a keyed hash defined
 * by authtype is created and stored in MAC.  MAC is ASSUMED to be a buffer
 * of at least maclen bytes.  If the length of the hash is greater than
 * maclen, it is truncated to fit the buffer.  If the length of the hash is
 * less than maclen, maclen set to the number of hash bytes generated.
 *
 * ASSUMED that the number of hash bits is a multiple of 8.
 */
int
sc_generate_keyed_hash(	oid	*authtype,	size_t authtypelen,
			u_char	*key,		u_int  keylen,
			u_char	*message,	u_int  msglen,
			u_char	*MAC,		size_t *maclen)
#if  defined(USE_INTERNAL_MD5) || defined(USE_OPENSSL)
{
  int		 rval	 = SNMPERR_SUCCESS;
  int		 properlength;

  u_char	 buf[SNMP_MAXBUF_SMALL];
#if  defined(USE_OPENSSL)
  int		 buf_len = sizeof(buf);
  u_char	*bufp = buf;
#endif
  
  DEBUGTRACE;

#ifdef SNMP_TESTING_CODE
{
  int i;
  DEBUGMSG(("sc_generate_keyed_hash", "sc_generate_keyed_hash(): key=0x"));
  for(i=0; i< keylen; i++)
    DEBUGMSG(("sc_generate_keyed_hash", "%02x", key[i] & 0xff));
  DEBUGMSG(("sc_generate_keyed_hash"," (%d)\n", keylen));
}
#endif /* SNMP_TESTING_CODE */

/*
 * Sanity check.
 */
 if ( !authtype || !key || !message || !MAC || !maclen
      || (keylen<=0) || (msglen<=0) || (*maclen<=0)
      || (authtypelen != USM_LENGTH_OID_TRANSFORM) )
   {
     QUITFUN(SNMPERR_GENERR, sc_generate_keyed_hash_quit);
   }
 
 properlength = sc_get_properlength(authtype, authtypelen);
 if (properlength == SNMPERR_GENERR)
   return properlength;
 
 if ( ((int)keylen < properlength) ) {
   QUITFUN(SNMPERR_GENERR, sc_generate_keyed_hash_quit);
 }
 

#ifdef USE_OPENSSL
 /*
  * Determine transform type.
  */
   if (ISTRANSFORM(authtype, HMACMD5Auth))
     HMAC(EVP_md5(), key, keylen, message, msglen,  
	  buf, &buf_len);
   else if (ISTRANSFORM(authtype, HMACSHA1Auth)) 
     HMAC(EVP_sha1(), key, keylen, message, msglen,  
	  buf, &buf_len);
   else {
     QUITFUN(SNMPERR_GENERR, sc_generate_keyed_hash_quit);
   }
   if (buf_len != properlength) {
     QUITFUN(rval, sc_generate_keyed_hash_quit);
   }
   if (*maclen > buf_len) 
     *maclen = buf_len;
   memcpy(MAC, buf, *maclen);
#else 
 if ((int)*maclen > properlength)
   *maclen = properlength;
 if (MDsign(message, msglen, MAC, *maclen, key, keylen)) {
   rval = SNMPERR_GENERR;
   goto sc_generate_keyed_hash_quit;
 }
#endif /* USE_OPENSSL */

#ifdef SNMP_TESTING_CODE
 {
   char    *s;
   int      len = binary_to_hex(MAC, *maclen, &s);
   
   DEBUGMSGTL(("scapi","Full v3 message hash: %s\n", s));
   SNMP_ZERO(s, len);
   SNMP_FREE(s);
 }
#endif
 
 sc_generate_keyed_hash_quit:
 SNMP_ZERO(buf, SNMP_MAXBUF_SMALL);
 return rval;
}  /* end sc_generate_keyed_hash() */
/*******************************************************************-o-******
 */
int
main(int argc, char **argv)
{
	int	  rval		= SNMPERR_SUCCESS;
	size_t	  oldKu_len	= SNMP_MAXBUF_SMALL,
		  newKu_len	= SNMP_MAXBUF_SMALL,
		  oldkul_len	= SNMP_MAXBUF_SMALL,
		  newkul_len	= SNMP_MAXBUF_SMALL,
		  keychange_len	= SNMP_MAXBUF_SMALL;

	char      *s = NULL;
	u_char	  oldKu[SNMP_MAXBUF_SMALL],
		  newKu[SNMP_MAXBUF_SMALL],
		  oldkul[SNMP_MAXBUF_SMALL],
		  newkul[SNMP_MAXBUF_SMALL],
		  keychange[SNMP_MAXBUF_SMALL];

	int       i;
	int       arg = 1;

 	local_progname = argv[0];


 
	/*
	 * Parse.
	 */
	for(; (arg < argc) && (argv[arg][0] == '-') ; arg++){
		switch(argv[arg][1]){
		case 'D':  snmp_set_do_debugging(1);	break;
		case 'E':  engineid = (u_char *)argv[++arg];	break;
		case 'f':  forcepassphrase = 1;		break;
		case 'N':  newpass = argv[++arg];	break;
		case 'O':  oldpass = argv[++arg];	break;
		case 'P':  promptindicator = 0;		break;
		case 't':  transform_type_input = argv[++arg];	break;
		case 'v':  verbose = 1;			break;
		case 'V':  visible = 1;			break;
		case 'h':
			rval = 0;
		default:
			usage_to_file(stdout);
			exit(rval);
		}
	}

	if ( !transform_type_input ) {
		fprintf(stderr, "The -t option is mandatory.\n");
		usage_synopsis(stdout);
		exit(1000);
	}



	/*
	 * Convert and error check transform_type.
	 */
	if ( !strcmp(transform_type_input, "md5") ) {
		transform_type = usmHMACMD5AuthProtocol;

	} else if ( !strcmp(transform_type_input, "sha1") ) {
		transform_type = usmHMACSHA1AuthProtocol;

	} else {
		fprintf(stderr,
			"Unrecognized hash transform: \"%s\".\n",
			transform_type_input);
		usage_synopsis(stderr);
		QUITFUN(rval = SNMPERR_GENERR, main_quit);
	}

	if (verbose) {
		fprintf(stderr, "Hash:\t\t%s\n",
			(transform_type == usmHMACMD5AuthProtocol)
				? "usmHMACMD5AuthProtocol"
				: "usmHMACSHA1AuthProtocol"
			);
	}



	/* 
	 * Build engineID.  Accept hex engineID as the bits
	 * "in-and-of-themselves", otherwise create an engineID with the
	 * given string as text.
	 *
	 * If no engineID is given, lookup the first IP address for the
	 * localhost and use that (see setup_engineID()).
	 */
	if ( engineid && (tolower(*(engineid+1)) == 'x') ) {
		engineid_len = hex_to_binary2(	engineid+2,
						strlen((char *)engineid)-2,
						(char **) &engineid);
                DEBUGMSGTL(("encode_keychange","engineIDLen: %d\n", engineid_len));
	} else {
		engineid_len = setup_engineID(&engineid, (char *)engineid);

	} 

#ifdef SNMP_TESTING_CODE
	if (verbose) {
		fprintf(stderr, "EngineID:\t%s\n",
			/* XXX = */ dump_snmpEngineID(engineid, &engineid_len));
	}
#endif


	/*
	 * Get passphrases from user.
	 */
	rval = get_user_passphrases();
	QUITFUN(rval, main_quit);

	if ( strlen(oldpass) < USM_LENGTH_P_MIN ) {
		fprintf(stderr, "Old passphrase must be greater than %d "
				"characters in length.\n",
				USM_LENGTH_P_MIN);
		QUITFUN(rval = SNMPERR_GENERR, main_quit);

	} else if ( strlen(newpass) < USM_LENGTH_P_MIN ) {
		fprintf(stderr, "New passphrase must be greater than %d "
				"characters in length.\n",
				USM_LENGTH_P_MIN);
		QUITFUN(rval = SNMPERR_GENERR, main_quit);
	}

	if (verbose) {
		fprintf(stderr,
			"Old passphrase:\t%s\nNew passphrase:\t%s\n",
			oldpass, newpass);
	}



	/* 
	 * Compute Ku and Kul's from old and new passphrases, then
	 * compute the keychange string & print it out.
	 */
	rval = sc_init();
	QUITFUN(rval, main_quit);


	rval = generate_Ku(	transform_type, USM_LENGTH_OID_TRANSFORM,
				(u_char *)oldpass, strlen(oldpass),
				oldKu, &oldKu_len);
	QUITFUN(rval, main_quit);


	rval = generate_Ku(	transform_type, USM_LENGTH_OID_TRANSFORM,
				(u_char *)newpass, strlen(newpass),
				newKu, &newKu_len);
	QUITFUN(rval, main_quit);


        DEBUGMSGTL(("encode_keychange", "EID (%d): ", engineid_len));
        for(i=0; i < (int)engineid_len; i++)
          DEBUGMSGTL(("encode_keychange", "%02x",(int) (engineid[i])));
        DEBUGMSGTL(("encode_keychange","\n"));

        DEBUGMSGTL(("encode_keychange", "old Ku (%d) (from %s): ", oldKu_len, oldpass));
        for(i=0; i < (int)oldKu_len; i++)
          DEBUGMSGTL(("encode_keychange", "%02x",(int) (oldKu[i])));
        DEBUGMSGTL(("encode_keychange","\n"));

	rval = generate_kul(	transform_type, USM_LENGTH_OID_TRANSFORM,
				engineid, engineid_len,
				oldKu, oldKu_len,
				oldkul, &oldkul_len);
	QUITFUN(rval, main_quit);


        DEBUGMSGTL(("encode_keychange", "generating old Kul (%d) (from Ku): ", oldkul_len));
        for(i=0; i < (int)oldkul_len; i++)
          DEBUGMSGTL(("encode_keychange", "%02x",(int) (oldkul[i])));
        DEBUGMSGTL(("encode_keychange","\n"));

	rval = generate_kul(	transform_type, USM_LENGTH_OID_TRANSFORM,
				engineid, engineid_len,
				newKu, newKu_len,
				newkul, &newkul_len);
	QUITFUN(rval, main_quit);
        
        DEBUGMSGTL(("encode_keychange", "generating new Kul (%d) (from Ku): ", oldkul_len));
        for(i=0; i < (int)newkul_len; i++)
          DEBUGMSGTL(("encode_keychange", "%02x",newkul[i]));
        DEBUGMSGTL(("encode_keychange","\n"));

	rval = encode_keychange(transform_type, USM_LENGTH_OID_TRANSFORM,
				oldkul, oldkul_len,
				newkul, newkul_len,
				keychange, &keychange_len);
	QUITFUN(rval, main_quit);



	binary_to_hex(keychange, keychange_len, &s);
	printf("%s%s\n",
		(verbose) ? "KeyChange string:\t" : "", /* XXX stdout */
		s);


	/*
	 * Cleanup.
	 */
main_quit:
	snmp_call_callbacks(SNMP_CALLBACK_LIBRARY, SNMP_CALLBACK_SHUTDOWN,
                            NULL);
        

	SNMP_ZERO(oldpass,	strlen(oldpass));
	SNMP_ZERO(newpass,	strlen(newpass));

	SNMP_ZERO(oldKu,	oldKu_len);
	SNMP_ZERO(newKu,	newKu_len);

	SNMP_ZERO(oldkul,	oldkul_len);
	SNMP_ZERO(newkul,	newkul_len);

	SNMP_ZERO(s, strlen(s));

	return rval;

} /* end main() */
示例#29
0
文件: scapitest.c 项目: OPSF/uClinux
/*******************************************************************-o-******
 * test_dokeyedhash
 *
 * Returns:
 *	Number of failures.
 *
 *
 * Test keyed hashes with a variety of MAC length requests.
 *
 *
 * NOTE Both tests intentionally use the same secret
 *
 * FIX	Get input or output from some other package which hashes...
 * XXX	Could cut this in half with a little indirection...
 */
int
test_dokeyedhash(void)
{
    int             rval = SNMPERR_SUCCESS, failcount = 0, bigstring_len = strlen(BIGSTRING), secret_len = strlen(BIGSECRET), properlength, mlcount = 0,        /* MAC Length count.   */
                    hblen;      /* Hash Buffer length. */

    u_int           hashbuf_len[MLCOUNT_MAX] = {
        LOCAL_MAXBUF,
        BYTESIZE(SNMP_TRANS_AUTHLEN_HMACSHA1),
        BYTESIZE(SNMP_TRANS_AUTHLEN_HMACMD5),
        BYTESIZE(SNMP_TRANS_AUTHLEN_HMAC96),
        7,
        0,
    };

    u_char          hashbuf[LOCAL_MAXBUF];
    char           *s;

  test_dokeyedhash_again:

    OUTPUT("Keyed hash test using MD5 --");

    memset(hashbuf, 0, LOCAL_MAXBUF);
    hblen = hashbuf_len[mlcount];
    properlength = BYTESIZE(SNMP_TRANS_AUTHLEN_HMACMD5);

    rval =
        sc_generate_keyed_hash(usmHMACMD5AuthProtocol,
                               USM_LENGTH_OID_TRANSFORM, BIGSECRET,
                               secret_len, BIGSTRING, bigstring_len,
                               hashbuf, &hblen);
    FAILED(rval, "sc_generate_keyed_hash().");

    if (hashbuf_len[mlcount] > properlength) {
        if (hblen != properlength) {
            FAILED(SNMPERR_GENERR, "Wrong MD5 hash length returned.  (1)");
        }

    } else if (hblen != hashbuf_len[mlcount]) {
        FAILED(SNMPERR_GENERR, "Wrong MD5 hash length returned.  (2)");
    }

    rval =
        sc_check_keyed_hash(usmHMACMD5AuthProtocol,
                            USM_LENGTH_OID_TRANSFORM, BIGSECRET,
                            secret_len, BIGSTRING, bigstring_len, hashbuf,
                            hblen);
    FAILED(rval, "sc_check_keyed_hash().");

    binary_to_hex(hashbuf, hblen, &s);
    fprintf(stdout, "hash buffer (len=%d, request=%d):   %s\n",
            hblen, hashbuf_len[mlcount], s);
    SNMP_FREE(s);

    SUCCESS("Keyed hash test using MD5.");



    OUTPUT("Keyed hash test using SHA1 --");

    memset(hashbuf, 0, LOCAL_MAXBUF);
    hblen = hashbuf_len[mlcount];
    properlength = BYTESIZE(SNMP_TRANS_AUTHLEN_HMACSHA1);

    rval =
        sc_generate_keyed_hash(usmHMACSHA1AuthProtocol,
                               USM_LENGTH_OID_TRANSFORM, BIGSECRET,
                               secret_len, BIGSTRING, bigstring_len,
                               hashbuf, &hblen);
    FAILED(rval, "sc_generate_keyed_hash().");

    if (hashbuf_len[mlcount] > properlength) {
        if (hblen != properlength) {
            FAILED(SNMPERR_GENERR,
                   "Wrong SHA1 hash length returned.  (1)");
        }

    } else if (hblen != hashbuf_len[mlcount]) {
        FAILED(SNMPERR_GENERR, "Wrong SHA1 hash length returned.  (2)");
    }

    rval =
        sc_check_keyed_hash(usmHMACSHA1AuthProtocol,
                            USM_LENGTH_OID_TRANSFORM, BIGSECRET,
                            secret_len, BIGSTRING, bigstring_len, hashbuf,
                            hblen);
    FAILED(rval, "sc_check_keyed_hash().");

    binary_to_hex(hashbuf, hblen, &s);
    fprintf(stdout, "hash buffer (len=%d, request=%d):   %s\n",
            hblen, hashbuf_len[mlcount], s);
    SNMP_FREE(s);

    SUCCESS("Keyed hash test using SHA1.");



    /*
     * Run the basic hash tests but vary the size MAC requests.
     */
    if (hashbuf_len[++mlcount] != 0) {
        goto test_dokeyedhash_again;
    }


    return failcount;

}                               /* end test_dokeyedhash() */
示例#30
0
const char *mail_guid_128_to_string(const uint8_t guid_128[MAIL_GUID_128_SIZE])
{
	return binary_to_hex(guid_128, MAIL_GUID_128_SIZE);
}