Commit message: - Fix Integer Overflows in Size Calculations,
  reported by X41 D-Sec.
CVE: CVE-2019-25038
CWE: CWE-190
Vulnerability description: Unbound before 1.9.5 allows an integer overflow in a size calculation in dnscrypt/dnscrypt.c. NOTE: The vendor disputes that this is a vulnerability. Although the code may be vulnerable, a running Unbound installation cannot be remotely or locally exploited

Project: unbound
File: respip.c

respip_nodata_answer(uint16_t qtype, enum respip_action action,
	const struct reply_info *rep, size_t rrset_id,
	struct reply_info** new_repp, struct regional* region)
{
	struct reply_info* new_rep;

	if(action == respip_refuse || action == respip_always_refuse) {
		new_rep = make_new_reply_info(rep, region, 0, 0);
		if(!new_rep)
			return 0;
		FLAGS_SET_RCODE(new_rep->flags, LDNS_RCODE_REFUSED);
		*new_repp = new_rep;
		return 1;
	} else if(action == respip_static || action == respip_redirect ||
		action == respip_always_nxdomain ||
		action == respip_inform_redirect) {
		/* Since we don't know about other types of the owner name,
		 * we generally return NOERROR/NODATA unless an NXDOMAIN action
		 * is explicitly specified. */
		int rcode = (action == respip_always_nxdomain)?
			LDNS_RCODE_NXDOMAIN:LDNS_RCODE_NOERROR;

		/* We should empty the answer section except for any preceding
		 * CNAMEs (in that case rrset_id > 0).  Type-ANY case is
		 * special as noted in respip_data_answer(). */
		if(qtype == LDNS_RR_TYPE_ANY)
			rrset_id = 0;
		new_rep = make_new_reply_info(rep, region, rrset_id, rrset_id);
		if(!new_rep)
			return 0;
		FLAGS_SET_RCODE(new_rep->flags, rcode);
		*new_repp = new_rep;
		return 1;
	}

	return 1;
}

Project: unbound
File: dnscrypt.c

dnscrypt_server_curve(const dnsccert *cert,
                      uint8_t client_nonce[crypto_box_HALF_NONCEBYTES],
                      uint8_t nmkey[crypto_box_BEFORENMBYTES],
                      struct sldns_buffer* buffer,
                      uint8_t udp,
                      size_t max_udp_size)
{
    size_t dns_reply_len = sldns_buffer_limit(buffer);
    size_t max_len = dns_reply_len + DNSCRYPT_MAX_PADDING \
        + DNSCRYPT_REPLY_HEADER_SIZE;
    size_t max_reply_size = max_udp_size - 20U - 8U;
    uint8_t nonce[crypto_box_NONCEBYTES];
    uint8_t *boxed;
    uint8_t *const buf = sldns_buffer_begin(buffer);
    size_t len = sldns_buffer_limit(buffer);

    if(udp){
        if (max_len > max_reply_size)
            max_len = max_reply_size;
    }


    memcpy(nonce, client_nonce, crypto_box_HALF_NONCEBYTES);
    memcpy(nonce + crypto_box_HALF_NONCEBYTES, client_nonce,
           crypto_box_HALF_NONCEBYTES);

    boxed = buf + DNSCRYPT_REPLY_BOX_OFFSET;
    memmove(boxed + crypto_box_MACBYTES, buf, len);
    len = dnscrypt_pad(boxed + crypto_box_MACBYTES, len,
                       max_len - DNSCRYPT_REPLY_HEADER_SIZE, nonce,
                       cert->keypair->crypt_secretkey);
    sldns_buffer_set_at(buffer,
                        DNSCRYPT_REPLY_BOX_OFFSET - crypto_box_BOXZEROBYTES,
                        0, crypto_box_ZEROBYTES);

    // add server nonce extension
    add_server_nonce(nonce);

    if(cert->es_version[1] == 2) {
#ifdef USE_DNSCRYPT_XCHACHA20
        if (crypto_box_curve25519xchacha20poly1305_easy_afternm
            (boxed, boxed + crypto_box_MACBYTES, len, nonce, nmkey) != 0) {
            return -1;
        }
#else
        return -1;
#endif
    } else {
        if (crypto_box_easy_afternm
            (boxed, boxed + crypto_box_MACBYTES, len, nonce, nmkey) != 0) {
            return -1;
        }
    }

    sldns_buffer_write_at(buffer,
                          0,
                          DNSCRYPT_MAGIC_RESPONSE,
                          DNSCRYPT_MAGIC_HEADER_LEN);
    sldns_buffer_write_at(buffer,
                          DNSCRYPT_MAGIC_HEADER_LEN,
                          nonce,
                          crypto_box_NONCEBYTES);
    sldns_buffer_set_limit(buffer, len + DNSCRYPT_REPLY_HEADER_SIZE);
    return 0;
}

Project: unbound
File: respip.c

respip_set_delete(struct respip_set* set)
{
	if(!set)
		return;
	regional_destroy(set->region);
	free(set);
}

Project: unbound
File: dnscrypt.c

dnsc_nonces_sizefunc(void *k, void* ATTR_UNUSED(d))
{
    struct nonce_cache_key* nk = (struct nonce_cache_key*)k;
    size_t key_size = sizeof(struct nonce_cache_key)
        + lock_get_mem(&nk->entry.lock);
    (void)nk; /* otherwise ssk is unused if no threading, or fixed locksize */
    return key_size;
}

Project: unbound
File: respip.c

respip_inform_super(struct module_qstate* qstate, int id,
	struct module_qstate* super)
{
	struct respip_qstate* rq = (struct respip_qstate*)super->minfo[id];
	struct reply_info* new_rep = NULL;

	rq->state = RESPIP_SUBQUERY_FINISHED;

	/* respip subquery should have always been created with a valid reply
	 * in super. */
	log_assert(super->return_msg && super->return_msg->rep);

	/* return_msg can be NULL when, e.g., the sub query resulted in
	 * SERVFAIL, in which case we regard it as a failure of the original
	 * query.  Other checks are probably redundant, but we check them
	 * for safety. */
	if(!qstate->return_msg || !qstate->return_msg->rep ||
		qstate->return_rcode != LDNS_RCODE_NOERROR)
		goto fail;

	if(!respip_merge_cname(super->return_msg->rep, &qstate->qinfo,
		qstate->return_msg->rep, super->client_info,
		super->env->need_to_validate, &new_rep, super->region))
		goto fail;
	super->return_msg->rep = new_rep;
	return;

  fail:
	super->return_rcode = LDNS_RCODE_SERVFAIL;
	super->return_msg = NULL;
	return;
}

Project: unbound
File: dnscrypt.c

sodium_misuse_handler(void)
{
	fatal_exit(
		"dnscrypt: libsodium could not be initialized, this typically"
		" happens when no good source of entropy is found. If you run"
		" unbound in a chroot, make sure /dev/urandom is available. See"
		" https://www.unbound.net/documentation/unbound.conf.html");
}

Project: unbound
File: dnscrypt.c

dnsc_chroot_path(struct config_file *cfg, char *path)
{
    char *nm;
    nm = path;
    if(cfg->chrootdir && cfg->chrootdir[0] && strncmp(nm,
        cfg->chrootdir, strlen(cfg->chrootdir)) == 0)
        nm += strlen(cfg->chrootdir);
    return nm;
}

Project: unbound
File: respip.c

make_new_reply_info(const struct reply_info* rep, struct regional* region,
	size_t an_numrrsets, size_t copy_rrsets)
{
	struct reply_info* new_rep;
	size_t i;

	/* create a base struct.  we specify 'insecure' security status as
	 * the modified response won't be DNSSEC-valid.  In our faked response
	 * the authority and additional sections will be empty (except possible
	 * EDNS0 OPT RR in the additional section appended on sending it out),
	 * so the total number of RRsets is an_numrrsets. */
	new_rep = construct_reply_info_base(region, rep->flags,
		rep->qdcount, rep->ttl, rep->prefetch_ttl,
		rep->serve_expired_ttl, an_numrrsets, 0, 0, an_numrrsets,
		sec_status_insecure);
	if(!new_rep)
		return NULL;
	if(!reply_info_alloc_rrset_keys(new_rep, NULL, region))
		return NULL;
	for(i=0; i<copy_rrsets; i++)
		new_rep->rrsets[i] = rep->rrsets[i];

	return new_rep;
}

Project: unbound
File: respip.c

respip_get_mem(struct module_env* env, int id)
{
	(void)env;
	(void)id;
	return 0;
}

Project: unbound
File: dnscrypt.c

dnsc_shared_secrets_lookup(struct slabhash* cache,
                           uint8_t key[DNSCRYPT_SHARED_SECRET_KEY_LENGTH],
                           uint32_t hash)
{
    return slabhash_lookup(cache, hash, key, 0);
}

Project: unbound
File: respip.c

respip_views_apply_cfg(struct views* vs, struct config_file* cfg,
	int* have_view_respip_cfg)
{
	struct config_view* cv;
	struct view* v;
	int ret;

	for(cv = cfg->views; cv; cv = cv->next) {

		/** if no respip config for this view then there's
		  * nothing to do; note that even though respip data must go
		  * with respip action, we're checking for both here because
		  * we want to catch the case where the respip action is missing
		  * while the data is present */
		if(!cv->respip_actions && !cv->respip_data)
			continue;

		if(!(v = views_find_view(vs, cv->name, 1))) {
			log_err("view '%s' unexpectedly missing", cv->name);
			return 0;
		}
		if(!v->respip_set) {
			v->respip_set = respip_set_create();
			if(!v->respip_set) {
				log_err("out of memory");
				lock_rw_unlock(&v->lock);
				return 0;
			}
		}
		ret = respip_set_apply_cfg(v->respip_set, NULL, 0, NULL,
			cv->respip_actions, cv->respip_data);
		lock_rw_unlock(&v->lock);
		if(!ret) {
			log_err("Error while applying respip configuration "
				"for view '%s'", cv->name);
			return 0;
		}
		*have_view_respip_cfg = (*have_view_respip_cfg ||
			v->respip_set->ip_tree.count);
		cv->respip_actions = NULL;
		cv->respip_data = NULL;
	}
	return 1;
}

Project: unbound
File: dnscrypt.c

add_server_nonce(uint8_t *nonce)
{
    uint64_t ts;
    uint64_t tsn;
    uint32_t suffix;
    ts = dnscrypt_hrtime();
    // TODO? dnscrypt-wrapper does some logic with context->nonce_ts_last
    // unclear if we really need it, so skipping it for now.
    tsn = (ts << 10) | (randombytes_random() & 0x3ff);
#if (BYTE_ORDER == LITTLE_ENDIAN)
    tsn =
        (((uint64_t)htonl((uint32_t)tsn)) << 32) | htonl((uint32_t)(tsn >> 32));
#endif
    memcpy(nonce + crypto_box_HALF_NONCEBYTES, &tsn, 8);
    suffix = randombytes_random();
    memcpy(nonce + crypto_box_HALF_NONCEBYTES + 8, &suffix, 4);
}

Project: unbound
File: dnscrypt.c

dnsc_delete(struct dnsc_env *env)
{
	if(!env) {
		return;
	}
	verbose(VERB_OPS, "DNSCrypt: Freeing environment.");
	sodium_free(env->signed_certs);
	sodium_free(env->rotated_certs);
	sodium_free(env->certs);
	sodium_free(env->keypairs);
	lock_basic_destroy(&env->shared_secrets_cache_lock);
	lock_basic_destroy(&env->nonces_cache_lock);
	slabhash_delete(env->shared_secrets_cache);
	slabhash_delete(env->nonces_cache);
	free(env);
}

Project: unbound
File: respip.c

respip_data_answer(const struct resp_addr* raddr, enum respip_action action,
	uint16_t qtype, const struct reply_info* rep,
	size_t rrset_id, struct reply_info** new_repp, int tag,
	struct config_strlist** tag_datas, size_t tag_datas_size,
	char* const* tagname, int num_tags,
	struct ub_packed_rrset_key** redirect_rrsetp, struct regional* region)
{
	struct ub_packed_rrset_key* rp = raddr->data;
	struct reply_info* new_rep;
	*redirect_rrsetp = NULL;

	if(action == respip_redirect && tag != -1 &&
		(size_t)tag<tag_datas_size && tag_datas[tag]) {
		struct query_info dataqinfo;
		struct ub_packed_rrset_key r;

		/* Extract parameters of the original answer rrset that can be
		 * rewritten below, in the form of query_info.  Note that these
		 * can be different from the info of the original query if the
		 * rrset is a CNAME target.*/
		memset(&dataqinfo, 0, sizeof(dataqinfo));
		dataqinfo.qname = rep->rrsets[rrset_id]->rk.dname;
		dataqinfo.qname_len = rep->rrsets[rrset_id]->rk.dname_len;
		dataqinfo.qtype = ntohs(rep->rrsets[rrset_id]->rk.type);
		dataqinfo.qclass = ntohs(rep->rrsets[rrset_id]->rk.rrset_class);

		memset(&r, 0, sizeof(r));
		if(local_data_find_tag_datas(&dataqinfo, tag_datas[tag], &r,
			region)) {
			verbose(VERB_ALGO,
				"response-ip redirect with tag data [%d] %s",
				tag, (tag<num_tags?tagname[tag]:"null"));
			/* use copy_rrset() to 'normalize' memory layout */
			rp = copy_rrset(&r, region);
			if(!rp)
				return -1;
		}
	}
	if(!rp)
		return 0;

	/* If we are using response-ip-data, we need to make a copy of rrset
	 * to replace the rrset's dname.  Note that, unlike local data, we
	 * rename the dname for other actions than redirect.  This is because
	 * response-ip-data isn't associated to any specific name. */
	if(rp == raddr->data) {
		rp = copy_rrset(rp, region);
		if(!rp)
			return -1;
		rp->rk.dname = rep->rrsets[rrset_id]->rk.dname;
		rp->rk.dname_len = rep->rrsets[rrset_id]->rk.dname_len;
	}

	/* Build a new reply with redirect rrset.  We keep any preceding CNAMEs
	 * and replace the address rrset that triggers the action.  If it's
	 * type ANY query, however, no other answer records should be kept
	 * (note that it can't be a CNAME chain in this case due to
	 * sanitizing). */
	if(qtype == LDNS_RR_TYPE_ANY)
		rrset_id = 0;
	new_rep = make_new_reply_info(rep, region, rrset_id + 1, rrset_id);
	if(!new_rep)
		return -1;
	rp->rk.flags |= PACKED_RRSET_FIXEDTTL; /* avoid adjusting TTL */
	new_rep->rrsets[rrset_id] = rp;

	*redirect_rrsetp = rp;
	*new_repp = new_rep;
	return 1;
}

Project: unbound
File: respip.c

respip_rewrite_reply(const struct query_info* qinfo,
	const struct respip_client_info* cinfo, const struct reply_info* rep,
	struct reply_info** new_repp, struct respip_action_info* actinfo,
	struct ub_packed_rrset_key** alias_rrset, int search_only,
	struct regional* region)
{
	const uint8_t* ctaglist;
	size_t ctaglen;
	const uint8_t* tag_actions;
	size_t tag_actions_size;
	struct config_strlist** tag_datas;
	size_t tag_datas_size;
	struct view* view = NULL;
	struct respip_set* ipset = NULL;
	size_t rrset_id = 0;
	enum respip_action action = respip_none;
	int tag = -1;
	const struct resp_addr* raddr = NULL;
	int ret = 1;
	struct ub_packed_rrset_key* redirect_rrset = NULL;

	if(!cinfo)
		goto done;
	ctaglist = cinfo->taglist;
	ctaglen = cinfo->taglen;
	tag_actions = cinfo->tag_actions;
	tag_actions_size = cinfo->tag_actions_size;
	tag_datas = cinfo->tag_datas;
	tag_datas_size = cinfo->tag_datas_size;
	view = cinfo->view;
	ipset = cinfo->respip_set;

	/** Try to use response-ip config from the view first; use
	  * global response-ip config if we don't have the view or we don't
	  * have the matching per-view config (and the view allows the use
	  * of global data in this case).
	  * Note that we lock the view even if we only use view members that
	  * currently don't change after creation.  This is for safety for
	  * future possible changes as the view documentation seems to expect
	  * any of its member can change in the view's lifetime.
	  * Note also that we assume 'view' is valid in this function, which
	  * should be safe (see unbound bug #1191) */
	if(view) {
		lock_rw_rdlock(&view->lock);
		if(view->respip_set) {
			if((raddr = respip_addr_lookup(rep,
				&view->respip_set->ip_tree, &rrset_id))) {
				/** for per-view respip directives the action
				 * can only be direct (i.e. not tag-based) */
				action = raddr->action;
			}
		}
		if(!raddr && !view->isfirst)
			goto done;
	}
	if(!raddr && ipset && (raddr = respip_addr_lookup(rep, &ipset->ip_tree,
		&rrset_id))) {
		action = (enum respip_action)local_data_find_tag_action(
			raddr->taglist, raddr->taglen, ctaglist, ctaglen,
			tag_actions, tag_actions_size,
			(enum localzone_type)raddr->action, &tag,
			ipset->tagname, ipset->num_tags);
	}
	if(raddr && !search_only) {
		int result = 0;

		/* first, see if we have response-ip or tag action for the
		 * action except for 'always' variants. */
		if(action != respip_always_refuse
			&& action != respip_always_transparent
			&& action != respip_always_nxdomain
			&& (result = respip_data_answer(raddr, action,
			qinfo->qtype, rep, rrset_id, new_repp, tag, tag_datas,
			tag_datas_size, ipset->tagname, ipset->num_tags,
			&redirect_rrset, region)) < 0) {
			ret = 0;
			goto done;
		}

		/* if no action data applied, take action specific to the
		 * action without data. */
		if(!result && !respip_nodata_answer(qinfo->qtype, action, rep,
			rrset_id, new_repp, region)) {
			ret = 0;
			goto done;
		}
	}
  done:
	if(view) {
		lock_rw_unlock(&view->lock);
	}
	if(ret) {
		/* If we're redirecting the original answer to a
		 * CNAME, record the CNAME rrset so the caller can take
		 * the appropriate action.  Note that we don't check the
		 * action type; it should normally be 'redirect', but it
		 * can be of other type when a data-dependent tag action
		 * uses redirect response-ip data.
		 */
		if(redirect_rrset &&
			redirect_rrset->rk.type == ntohs(LDNS_RR_TYPE_CNAME) &&
			qinfo->qtype != LDNS_RR_TYPE_ANY)
			*alias_rrset = redirect_rrset;
		/* on success, populate respip result structure */
		ret = populate_action_info(actinfo, action, raddr,
			redirect_rrset, tag, ipset, search_only, region);
	}
	return ret;
}

Project: unbound
File: respip.c

generate_cname_request(struct module_qstate* qstate,
	struct ub_packed_rrset_key* alias_rrset)
{
	struct module_qstate* subq = NULL;
	struct query_info subqi;

	memset(&subqi, 0, sizeof(subqi));
	get_cname_target(alias_rrset, &subqi.qname, &subqi.qname_len);
	if(!subqi.qname)
		return 0;    /* unexpected: not a valid CNAME RDATA */
	subqi.qtype = qstate->qinfo.qtype;
	subqi.qclass = qstate->qinfo.qclass;
	fptr_ok(fptr_whitelist_modenv_attach_sub(qstate->env->attach_sub));
	return (*qstate->env->attach_sub)(qstate, &subqi, BIT_RD, 0, 0, &subq);
}

Project: unbound
File: respip.c

resp_addr_get_action(const struct resp_addr* addr)
{
	return addr ? addr->action : respip_none;
}

Project: unbound
File: dnscrypt.c

dnsc_handle_curved_request(struct dnsc_env* dnscenv,
                           struct comm_reply* repinfo)
{
    struct comm_point* c = repinfo->c;

    repinfo->is_dnscrypted = 0;
    if( !c->dnscrypt ) {
        return 1;
    }
    // Attempt to decrypt the query. If it is not crypted, we may still need
    // to serve the certificate.
    verbose(VERB_ALGO, "handle request called on DNSCrypt socket");
    if ((repinfo->dnsc_cert = dnsc_find_cert(dnscenv, c->buffer)) != NULL) {
        if(dnscrypt_server_uncurve(dnscenv,
                                   repinfo->dnsc_cert,
                                   repinfo->client_nonce,
                                   repinfo->nmkey,
                                   c->buffer) != 0){
            verbose(VERB_ALGO, "dnscrypt: Failed to uncurve");
            comm_point_drop_reply(repinfo);
            return 0;
        }
        repinfo->is_dnscrypted = 1;
        sldns_buffer_rewind(c->buffer);
    }
    return 1;
}

Project: unbound
File: respip.c

respip_addr_lookup(const struct reply_info *rep, struct rbtree_type* iptree,
	size_t* rrset_id)
{
	size_t i;
	struct resp_addr* ra;
	struct sockaddr_storage ss;
	socklen_t addrlen;

	for(i=0; i<rep->an_numrrsets; i++) {
		size_t j;
		const struct packed_rrset_data* rd;
		uint16_t rtype = ntohs(rep->rrsets[i]->rk.type);

		if(rtype != LDNS_RR_TYPE_A && rtype != LDNS_RR_TYPE_AAAA)
			continue;
		rd = rep->rrsets[i]->entry.data;
		for(j = 0; j < rd->count; j++) {
			if(!rdata2sockaddr(rd, rtype, j, &ss, &addrlen))
				continue;
			ra = (struct resp_addr*)addr_tree_lookup(iptree, &ss,
				addrlen);
			if(ra) {
				*rrset_id = i;
				return ra;
			}
		}
	}

	return NULL;
}

Project: unbound
File: respip.c

respip_deinit(struct module_env* env, int id)
{
	(void)env;
	(void)id;
}

Project: unbound
File: dnscrypt.c

dnsc_handle_uncurved_request(struct comm_reply *repinfo)
{
    if(!repinfo->c->dnscrypt) {
        return 1;
    }
    sldns_buffer_copy(repinfo->c->dnscrypt_buffer, repinfo->c->buffer);
    if(!repinfo->is_dnscrypted) {
        return 1;
    }
	if(dnscrypt_server_curve(repinfo->dnsc_cert,
                             repinfo->client_nonce,
                             repinfo->nmkey,
                             repinfo->c->dnscrypt_buffer,
                             repinfo->c->type == comm_udp,
                             repinfo->max_udp_size) != 0){
		verbose(VERB_ALGO, "dnscrypt: Failed to curve cached missed answer");
		comm_point_drop_reply(repinfo);
		return 0;
	}
    return 1;
}

Project: unbound
File: dnscrypt.c

dnsc_key_to_fingerprint(char fingerprint[80U], const uint8_t * const key)
{
    const size_t fingerprint_size = 80U;
    size_t       fingerprint_pos = (size_t) 0U;
    size_t       key_pos = (size_t) 0U;

    for (;;) {
        assert(fingerprint_size > fingerprint_pos);
        snprintf(&fingerprint[fingerprint_pos],
                        fingerprint_size - fingerprint_pos, "%02X%02X",
                        key[key_pos], key[key_pos + 1U]);
        key_pos += 2U;
        if (key_pos >= crypto_box_PUBLICKEYBYTES) {
            break;
        }
        fingerprint[fingerprint_pos + 4U] = ':';
        fingerprint_pos += 5U;
    }
}

Project: unbound
File: dnscrypt.c

key_get_es_version(uint8_t version[2])
{
    struct es_version {
        uint8_t es_version[2];
        const char *name;
    };

    const int num_versions = 2;
    struct es_version es_versions[] = {
        {{0x00, 0x01}, "X25519-XSalsa20Poly1305"},
        {{0x00, 0x02}, "X25519-XChacha20Poly1305"},
    };
    int i;
    for(i=0; i < num_versions; i++){
        if(es_versions[i].es_version[0] == version[0] &&
           es_versions[i].es_version[1] == version[1]){
            return es_versions[i].name;
        }
    }
    return NULL;
}

Project: unbound
File: respip.c

new_rrset(struct regional* region, uint16_t rrtype, uint16_t rrclass)
{
	struct packed_rrset_data* pd;
	struct ub_packed_rrset_key* rrset = regional_alloc_zero(
		region, sizeof(*rrset));
	if(!rrset) {
		log_err("out of memory");
		return NULL;
	}
	rrset->entry.key = rrset;
	pd = regional_alloc_zero(region, sizeof(*pd));
	if(!pd) {
		log_err("out of memory");
		return NULL;
	}
	pd->trust = rrset_trust_prim_noglue;
	pd->security = sec_status_insecure;
	rrset->entry.data = pd;
	rrset->rk.dname = regional_alloc_zero(region, 1);
	if(!rrset->rk.dname) {
		log_err("out of memory");
		return NULL;
	}
	rrset->rk.dname_len = 1;
	rrset->rk.type = htons(rrtype);
	rrset->rk.rrset_class = htons(rrclass);
	return rrset;
}

Project: unbound
File: respip.c

resp_addr_get_rrset(struct resp_addr* addr)
{
	return addr ? addr->data : NULL;
}

Project: unbound
File: dnscrypt.c

dnscrypt_server_uncurve(struct dnsc_env* env,
                        const dnsccert *cert,
                        uint8_t client_nonce[crypto_box_HALF_NONCEBYTES],
                        uint8_t nmkey[crypto_box_BEFORENMBYTES],
                        struct sldns_buffer* buffer)
{
    size_t len = sldns_buffer_limit(buffer);
    uint8_t *const buf = sldns_buffer_begin(buffer);
    uint8_t nonce[crypto_box_NONCEBYTES];
    struct dnscrypt_query_header *query_header;
    // shared secret cache
    uint8_t key[DNSCRYPT_SHARED_SECRET_KEY_LENGTH];
    struct lruhash_entry* entry;
    uint32_t hash;

    uint32_t nonce_hash;

    if (len <= DNSCRYPT_QUERY_HEADER_SIZE) {
        return -1;
    }

    query_header = (struct dnscrypt_query_header *)buf;

    /* Detect replay attacks */
    nonce_hash = dnsc_nonce_cache_key_hash(
        query_header->nonce,
        cert->magic_query,
        query_header->publickey);

    lock_basic_lock(&env->nonces_cache_lock);
    entry = dnsc_nonces_lookup(
        env->nonces_cache,
        query_header->nonce,
        cert->magic_query,
        query_header->publickey,
        nonce_hash);

    if(entry) {
        lock_rw_unlock(&entry->lock);
        env->num_query_dnscrypt_replay++;
        lock_basic_unlock(&env->nonces_cache_lock);
        return -1;
    }

    dnsc_nonce_cache_insert(
        env->nonces_cache,
        query_header->nonce,
        cert->magic_query,
        query_header->publickey,
        nonce_hash);
    lock_basic_unlock(&env->nonces_cache_lock);

    /* Find existing shared secret */
    hash = dnsc_shared_secrets_cache_key(key,
                                         cert->es_version[1],
                                         query_header->publickey,
                                         cert->keypair->crypt_secretkey);
    entry = dnsc_shared_secrets_lookup(env->shared_secrets_cache,
                                       key,
                                       hash);

    if(!entry) {
        lock_basic_lock(&env->shared_secrets_cache_lock);
        env->num_query_dnscrypt_secret_missed_cache++;
        lock_basic_unlock(&env->shared_secrets_cache_lock);
        if(cert->es_version[1] == 2) {
#ifdef USE_DNSCRYPT_XCHACHA20
            if (crypto_box_curve25519xchacha20poly1305_beforenm(
                        nmkey, query_header->publickey,
                        cert->keypair->crypt_secretkey) != 0) {
                return -1;
            }
#else
            return -1;
#endif
    } else {
        if (crypto_box_beforenm(nmkey,
                                query_header->publickey,
                                cert->keypair->crypt_secretkey) != 0) {
            return -1;
        }
    }
    // Cache the shared secret we just computed.
    dnsc_shared_secret_cache_insert(env->shared_secrets_cache,
                                    key,
                                    hash,
                                    nmkey);
    } else {
        /* copy shared secret and unlock entry */
        memcpy(nmkey, entry->data, crypto_box_BEFORENMBYTES);
        lock_rw_unlock(&entry->lock);
    }

    memcpy(nonce, query_header->nonce, crypto_box_HALF_NONCEBYTES);
    memset(nonce + crypto_box_HALF_NONCEBYTES, 0, crypto_box_HALF_NONCEBYTES);

    if(cert->es_version[1] == 2) {
#ifdef USE_DNSCRYPT_XCHACHA20
        if (crypto_box_curve25519xchacha20poly1305_open_easy_afternm
                (buf,
                buf + DNSCRYPT_QUERY_BOX_OFFSET,
                len - DNSCRYPT_QUERY_BOX_OFFSET, nonce,
                nmkey) != 0) {
            return -1;
        }
#else
        return -1;
#endif
    } else {
        if (crypto_box_open_easy_afternm
            (buf,
             buf + DNSCRYPT_QUERY_BOX_OFFSET,
             len - DNSCRYPT_QUERY_BOX_OFFSET, nonce,
             nmkey) != 0) {
            return -1;
        }
    }

    len -= DNSCRYPT_QUERY_HEADER_SIZE;

    while (*sldns_buffer_at(buffer, --len) == 0)
        ;

    if (*sldns_buffer_at(buffer, len) != 0x80) {
        return -1;
    }

    memcpy(client_nonce, nonce, crypto_box_HALF_NONCEBYTES);

    sldns_buffer_set_position(buffer, 0);
    sldns_buffer_set_limit(buffer, len);

    return 0;
}

Project: unbound
File: dnscrypt.c

dnsc_nonces_lookup(struct slabhash* cache,
                   const uint8_t nonce[crypto_box_HALF_NONCEBYTES],
                   const uint8_t magic_query[DNSCRYPT_MAGIC_HEADER_LEN],
                   const uint8_t pk[crypto_box_PUBLICKEYBYTES],
                   uint32_t hash)
{
    struct nonce_cache_key k;
    memset(&k, 0, sizeof(k));
    k.entry.hash = hash;
    memcpy(k.nonce, nonce, crypto_box_HALF_NONCEBYTES);
    memcpy(k.magic_query, magic_query, DNSCRYPT_MAGIC_HEADER_LEN);
    memcpy(k.client_publickey, pk, crypto_box_PUBLICKEYBYTES);

    return slabhash_lookup(cache, hash, &k, 0);
}

Project: unbound
File: dnscrypt.c

dnsc_create(void)
{
	struct dnsc_env *env;
#ifdef SODIUM_MISUSE_HANDLER
	sodium_set_misuse_handler(sodium_misuse_handler);
#endif
	if (sodium_init() == -1) {
		fatal_exit("dnsc_create: could not initialize libsodium.");
	}
	env = (struct dnsc_env *) calloc(1, sizeof(struct dnsc_env));
	lock_basic_init(&env->shared_secrets_cache_lock);
	lock_protect(&env->shared_secrets_cache_lock,
                 &env->num_query_dnscrypt_secret_missed_cache,
                 sizeof(env->num_query_dnscrypt_secret_missed_cache));
	lock_basic_init(&env->nonces_cache_lock);
	lock_protect(&env->nonces_cache_lock,
                 &env->nonces_cache,
                 sizeof(env->nonces_cache));
	lock_protect(&env->nonces_cache_lock,
                 &env->num_query_dnscrypt_replay,
                 sizeof(env->num_query_dnscrypt_replay));

	return env;
}

Project: unbound
File: respip.c

respip_set_create(void)
{
	struct respip_set* set = calloc(1, sizeof(*set));
	if(!set)
		return NULL;
	set->region = regional_create();
	if(!set->region) {
		free(set);
		return NULL;
	}
	addr_tree_init(&set->ip_tree);
	return set;
}

Project: unbound
File: dnscrypt.c

dnsc_nonces_delkeyfunc(void *k, void* ATTR_UNUSED(arg))
{
    struct nonce_cache_key* nk = (struct nonce_cache_key*)k;
    lock_rw_destroy(&nk->entry.lock);
    free(nk);
}

Project: unbound
File: respip.c

respip_enter_rr(struct regional* region, struct resp_addr* raddr,
		const char* rrstr, const char* netblock)
{
	uint8_t* nm;
	uint16_t rrtype = 0, rrclass = 0;
	time_t ttl = 0;
	uint8_t rr[LDNS_RR_BUF_SIZE];
	uint8_t* rdata = NULL;
	size_t rdata_len = 0;
	char buf[65536];
	char bufshort[64];
	struct packed_rrset_data* pd;
	struct sockaddr* sa;
	int ret;
	if(raddr->action != respip_redirect
		&& raddr->action != respip_inform_redirect) {
		log_err("cannot parse response-ip-data %s: response-ip "
			"action for %s is not redirect", rrstr, netblock);
		return 0;
	}
	ret = snprintf(buf, sizeof(buf), ". %s", rrstr);
	if(ret < 0 || ret >= (int)sizeof(buf)) {
		strlcpy(bufshort, rrstr, sizeof(bufshort));
		log_err("bad response-ip-data: %s...", bufshort);
		return 0;
	}
	if(!rrstr_get_rr_content(buf, &nm, &rrtype, &rrclass, &ttl, rr, sizeof(rr),
		&rdata, &rdata_len)) {
		log_err("bad response-ip-data: %s", rrstr);
		return 0;
	}
	free(nm);
	sa = (struct sockaddr*)&raddr->node.addr;
	if (rrtype == LDNS_RR_TYPE_CNAME && raddr->data) {
		log_err("CNAME response-ip data (%s) can not co-exist with other "
			"response-ip data for netblock %s", rrstr, netblock);
		return 0;
	} else if (raddr->data &&
		raddr->data->rk.type == htons(LDNS_RR_TYPE_CNAME)) {
		log_err("response-ip data (%s) can not be added; CNAME response-ip "
			"data already in place for netblock %s", rrstr, netblock);
		return 0;
	} else if((rrtype != LDNS_RR_TYPE_CNAME) &&
		((sa->sa_family == AF_INET && rrtype != LDNS_RR_TYPE_A) ||
		(sa->sa_family == AF_INET6 && rrtype != LDNS_RR_TYPE_AAAA))) {
		log_err("response-ip data %s record type does not correspond "
			"to netblock %s address family", rrstr, netblock);
		return 0;
	}

	if(!raddr->data) {
		raddr->data = new_rrset(region, rrtype, rrclass);
		if(!raddr->data)
			return 0;
	}
	pd = raddr->data->entry.data;
	return rrset_insert_rr(region, pd, rdata, rdata_len, ttl, rrstr);
}

Project: unbound
File: dnscrypt.c

dnsc_shared_secrets_deldatafunc(void* d, void* ATTR_UNUSED(arg))
{
    uint8_t* data = (uint8_t*)d;
    free(data);
}

Project: unbound
File: respip.c

respip_operate(struct module_qstate* qstate, enum module_ev event, int id,
	struct outbound_entry* outbound)
{
	struct respip_qstate* rq = (struct respip_qstate*)qstate->minfo[id];

	log_query_info(VERB_QUERY, "respip operate: query", &qstate->qinfo);
	(void)outbound;

	if(event == module_event_new || event == module_event_pass) {
		if(!rq) {
			rq = regional_alloc_zero(qstate->region, sizeof(*rq));
			if(!rq)
				goto servfail;
			rq->state = RESPIP_INIT;
			qstate->minfo[id] = rq;
		}
		if(rq->state == RESPIP_SUBQUERY_FINISHED) {
			qstate->ext_state[id] = module_finished;
			return;
		}
		verbose(VERB_ALGO, "respip: pass to next module");
		qstate->ext_state[id] = module_wait_module;
	} else if(event == module_event_moddone) {
		/* If the reply may be subject to response-ip rewriting
		 * according to the query type, check the actions.  If a
		 * rewrite is necessary, we'll replace the reply in qstate
		 * with the new one. */
		enum module_ext_state next_state = module_finished;

		if((qstate->qinfo.qtype == LDNS_RR_TYPE_A ||
			qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA ||
			qstate->qinfo.qtype == LDNS_RR_TYPE_ANY) &&
			qstate->return_msg && qstate->return_msg->rep) {
			struct respip_action_info actinfo = {respip_none, NULL};
			struct reply_info* new_rep = qstate->return_msg->rep;
			struct ub_packed_rrset_key* alias_rrset = NULL;

			if(!respip_rewrite_reply(&qstate->qinfo,
				qstate->client_info, qstate->return_msg->rep,
				&new_rep, &actinfo, &alias_rrset, 0,
				qstate->region)) {
				goto servfail;
			}
			if(actinfo.action != respip_none) {
				/* save action info for logging on a
				 * per-front-end-query basis */
				if(!(qstate->respip_action_info =
					regional_alloc_init(qstate->region,
						&actinfo, sizeof(actinfo))))
				{
					log_err("out of memory");
					goto servfail;
				}
			} else {
				qstate->respip_action_info = NULL;
			}
			if (new_rep == qstate->return_msg->rep &&
				(actinfo.action == respip_deny ||
				actinfo.action == respip_inform_deny)) {
				/* for deny-variant actions (unless response-ip
				 * data is applied), mark the query state so
				 * the response will be dropped for all
				 * clients. */
				qstate->is_drop = 1;
			} else if(alias_rrset) {
				if(!generate_cname_request(qstate, alias_rrset))
					goto servfail;
				next_state = module_wait_subquery;
			}
			qstate->return_msg->rep = new_rep;
		}
		qstate->ext_state[id] = next_state;
	} else
		qstate->ext_state[id] = module_finished;

	return;

  servfail:
	qstate->return_rcode = LDNS_RCODE_SERVFAIL;
	qstate->return_msg = NULL;
}

Project: unbound
File: respip.c

respip_clear(struct module_qstate* qstate, int id)
{
	qstate->minfo[id] = NULL;
}

Project: unbound
File: dnscrypt.c

dnsc_load_local_data(struct dnsc_env* dnscenv, struct config_file *cfg)
{
    size_t i, j;
	// Insert 'local-zone: "2.dnscrypt-cert.example.com" deny'
    if(!cfg_str2list_insert(&cfg->local_zones,
                            strdup(dnscenv->provider_name),
                            strdup("deny"))) {
        log_err("Could not load dnscrypt local-zone: %s deny",
                dnscenv->provider_name);
        return -1;
    }

    // Add local data entry of type:
    // 2.dnscrypt-cert.example.com 86400 IN TXT "DNSC......"
    for(i=0; i<dnscenv->signed_certs_count; i++) {
        const char *ttl_class_type = " 86400 IN TXT \"";
        int rotated_cert = 0;
	uint32_t serial;
	uint16_t rrlen;
	char* rr;
        struct SignedCert *cert = dnscenv->signed_certs + i;
		// Check if the certificate is being rotated and should not be published
        for(j=0; j<dnscenv->rotated_certs_count; j++){
            if(cert == dnscenv->rotated_certs[j]) {
                rotated_cert = 1;
                break;
            }
        }
		memcpy(&serial, cert->serial, sizeof serial);
		serial = htonl(serial);
        if(rotated_cert) {
            verbose(VERB_OPS,
                "DNSCrypt: not adding cert with serial #%"
                PRIu32
                " to local-data as it is rotated",
                serial
            );
            continue;
        }
	if((unsigned)strlen(dnscenv->provider_name) >= (unsigned)0xffff0000) {
		/* guard against integer overflow in rrlen calculation */
		verbose(VERB_OPS, "cert #%" PRIu32 " is too long", serial);
		continue
	}
        rrlen = strlen(dnscenv->provider_name) +
                         strlen(ttl_class_type) +
                         4 * sizeof(struct SignedCert) + // worst case scenario
                         1 + // trailing double quote
                         1;
        rr = malloc(rrlen);
        if(!rr) {
            log_err("Could not allocate memory");
            return -2;
        }
        snprintf(rr, rrlen - 1, "%s 86400 IN TXT \"", dnscenv->provider_name);
        for(j=0; j<sizeof(struct SignedCert); j++) {
			int c = (int)*((const uint8_t *) cert + j);
            if (isprint(c) && c != '"' && c != '\\') {
                snprintf(rr + strlen(rr), rrlen - 1 - strlen(rr), "%c", c);
            } else {
                snprintf(rr + strlen(rr), rrlen - 1 - strlen(rr), "\\%03d", c);
            }
        }
        verbose(VERB_OPS,
			"DNSCrypt: adding cert with serial #%"
			PRIu32
			" to local-data to config: %s",
			serial, rr
		);
        snprintf(rr + strlen(rr), rrlen - 1 - strlen(rr), "\"");
        cfg_strlist_insert(&cfg->local_data, strdup(rr));
        free(rr);
    }
    return dnscenv->signed_certs_count;
}

Project: unbound
File: respip.c

respip_get_funcblock(void)
{
	return &respip_block;
}

Project: unbound
File: dnscrypt.c

dnsc_nonces_compfunc(void *m1, void *m2)
{
    struct nonce_cache_key *k1 = m1, *k2 = m2;
    return
        sodium_memcmp(
            k1->nonce,
            k2->nonce,
            crypto_box_HALF_NONCEBYTES) != 0 ||
        sodium_memcmp(
            k1->magic_query,
            k2->magic_query,
            DNSCRYPT_MAGIC_HEADER_LEN) != 0 ||
        sodium_memcmp(
            k1->client_publickey, k2->client_publickey,
            crypto_box_PUBLICKEYBYTES) != 0;
}

Project: unbound
File: respip.c

respip_data_cfg(struct respip_set* set, const char* ipstr, const char* rrstr)
{
	struct resp_addr* node;

	node=respip_find_or_create(set, ipstr, 0);
	if(!node || node->action == respip_none) {
		log_err("cannot parse response-ip-data %s: "
			"response-ip node for %s not found", rrstr, ipstr);
		return 0;
	}
	return respip_enter_rr(set->region, node, rrstr, ipstr);
}

Project: unbound
File: respip.c

populate_action_info(struct respip_action_info* actinfo,
	enum respip_action action, const struct resp_addr* raddr,
	const struct ub_packed_rrset_key* ATTR_UNUSED(rrset),
	int ATTR_UNUSED(tag), const struct respip_set* ATTR_UNUSED(ipset),
	int ATTR_UNUSED(action_only), struct regional* region)
{
	if(action == respip_none || !raddr)
		return 1;
	actinfo->action = action;

	/* for inform variants, make a copy of the matched address block for
	 * later logging.  We make a copy to proactively avoid disruption if
	 *  and when we allow a dynamic update to the respip tree. */
	if(action == respip_inform || action == respip_inform_deny) {
		struct respip_addr_info* a =
			regional_alloc_zero(region, sizeof(*a));
		if(!a) {
			log_err("out of memory");
			return 0;
		}
		a->addr = raddr->node.addr;
		a->addrlen = raddr->node.addrlen;
		a->net = raddr->node.net;
		actinfo->addrinfo = a;
	}

	return 1;
}

Project: unbound
File: respip.c

copy_rrset(const struct ub_packed_rrset_key* key, struct regional* region)
{
	struct ub_packed_rrset_key* ck = regional_alloc(region,
		sizeof(struct ub_packed_rrset_key));
	struct packed_rrset_data* d;
	struct packed_rrset_data* data = key->entry.data;
	size_t dsize, i;
	uint8_t* nextrdata;

	/* derived from packed_rrset_copy_region(), but don't use
	 * packed_rrset_sizeof() and do exclude RRSIGs */
	if(!ck)
		return NULL;
	ck->id = key->id;
	memset(&ck->entry, 0, sizeof(ck->entry));
	ck->entry.hash = key->entry.hash;
	ck->entry.key = ck;
	ck->rk = key->rk;
	ck->rk.dname = regional_alloc_init(region, key->rk.dname,
		key->rk.dname_len);
	if(!ck->rk.dname)
		return NULL;

	if((unsigned)data->count >= 0xffff00U)
		return NULL; /* guard against integer overflow in dsize */
	dsize = sizeof(struct packed_rrset_data) + data->count *
		(sizeof(size_t)+sizeof(uint8_t*)+sizeof(time_t));
	for(i=0; i<data->count; i++) {
		if((unsigned)dsize >= 0x0fffffffU ||
			(unsigned)data->rr_len[i] >= 0x0fffffffU)
			return NULL; /* guard against integer overflow */
		dsize += data->rr_len[i];
	}
	d = regional_alloc(region, dsize);
	if(!d)
		return NULL;
	*d = *data;
	d->rrsig_count = 0;
	ck->entry.data = d;

	/* derived from packed_rrset_ptr_fixup() with copying the data */
	d->rr_len = (size_t*)((uint8_t*)d + sizeof(struct packed_rrset_data));
	d->rr_data = (uint8_t**)&(d->rr_len[d->count]);
	d->rr_ttl = (time_t*)&(d->rr_data[d->count]);
	nextrdata = (uint8_t*)&(d->rr_ttl[d->count]);
	for(i=0; i<d->count; i++) {
		d->rr_len[i] = data->rr_len[i];
		d->rr_ttl[i] = data->rr_ttl[i];
		d->rr_data[i] = nextrdata;
		memcpy(d->rr_data[i], data->rr_data[i], data->rr_len[i]);
		nextrdata += d->rr_len[i];
	}

	return ck;
}

Project: unbound
File: dnscrypt.c

dnsc_find_cert(struct dnsc_env* dnscenv, struct sldns_buffer* buffer)
{
	const dnsccert *certs = dnscenv->certs;
	struct dnscrypt_query_header *dnscrypt_header;
	size_t i;

	if (sldns_buffer_limit(buffer) < DNSCRYPT_QUERY_HEADER_SIZE) {
		return NULL;
	}
	dnscrypt_header = (struct dnscrypt_query_header *)sldns_buffer_begin(buffer);
	for (i = 0U; i < dnscenv->signed_certs_count; i++) {
		if (memcmp(certs[i].magic_query, dnscrypt_header->magic_query,
                   DNSCRYPT_MAGIC_HEADER_LEN) == 0) {
			return &certs[i];
		}
	}
	return NULL;
}

Project: unbound
File: respip.c

respip_global_apply_cfg(struct respip_set* set, struct config_file* cfg)
{
	int ret = respip_set_apply_cfg(set, cfg->tagname, cfg->num_tags,
		cfg->respip_tags, cfg->respip_actions, cfg->respip_data);
	cfg->respip_data = NULL;
	cfg->respip_actions = NULL;
	cfg->respip_tags = NULL;
	return ret;
}

Project: unbound
File: dnscrypt.c

dnsc_shared_secrets_cache_key(uint8_t* key,
                              uint8_t esversion,
                              uint8_t* pk,
                              uint8_t* sk)
{
    key[0] = esversion;
    memcpy(key + 1, pk, crypto_box_PUBLICKEYBYTES);
    memcpy(key + 1 + crypto_box_PUBLICKEYBYTES, sk, crypto_box_SECRETKEYBYTES);
    return hashlittle(key, DNSCRYPT_SHARED_SECRET_KEY_LENGTH, 0);
}

Project: unbound
File: respip.c

respip_init(struct module_env* env, int id)
{
	(void)env;
	(void)id;
	return 1;
}

Project: unbound
File: dnscrypt.c

dnsc_shared_secrets_compfunc(void *m1, void *m2)
{
    return sodium_memcmp(m1, m2, DNSCRYPT_SHARED_SECRET_KEY_LENGTH);
}

Project: unbound
File: dnscrypt.c

dnsc_shared_secrets_delkeyfunc(void *k, void* ATTR_UNUSED(arg))
{
    struct shared_secret_cache_key* ssk = (struct shared_secret_cache_key*)k;
    lock_rw_destroy(&ssk->entry.lock);
    free(ssk);
}

Project: unbound
File: dnscrypt.c

dnsc_nonce_cache_key_hash(const uint8_t nonce[crypto_box_HALF_NONCEBYTES],
                          const uint8_t magic_query[DNSCRYPT_MAGIC_HEADER_LEN],
                          const uint8_t pk[crypto_box_PUBLICKEYBYTES])
{
    uint32_t h = 0;
    h = hashlittle(nonce, crypto_box_HALF_NONCEBYTES, h);
    h = hashlittle(magic_query, DNSCRYPT_MAGIC_HEADER_LEN, h);
    return hashlittle(pk, crypto_box_PUBLICKEYBYTES, h);
}

Project: unbound
File: respip.c

respip_action_cfg(struct respip_set* set, const char* ipstr,
	const char* actnstr)
{
	struct resp_addr* node;
	enum respip_action action;

	if(!(node=respip_find_or_create(set, ipstr, 1)))
		return 0;
	if(node->action != respip_none) {
		verbose(VERB_QUERY, "duplicate response-ip action for '%s', overridden.",
			ipstr);
	}
        if(strcmp(actnstr, "deny") == 0)
                action = respip_deny;
        else if(strcmp(actnstr, "redirect") == 0)
                action = respip_redirect;
        else if(strcmp(actnstr, "inform") == 0)
                action = respip_inform;
        else if(strcmp(actnstr, "inform_deny") == 0)
                action = respip_inform_deny;
        else if(strcmp(actnstr, "inform_redirect") == 0)
                action = respip_inform_redirect;
        else if(strcmp(actnstr, "always_transparent") == 0)
                action = respip_always_transparent;
        else if(strcmp(actnstr, "always_refuse") == 0)
                action = respip_always_refuse;
        else if(strcmp(actnstr, "always_nxdomain") == 0)
                action = respip_always_nxdomain;
        else {
                log_err("unknown response-ip action %s", actnstr);
                return 0;
        }
	node->action = action;
	return 1;
}

Project: unbound
File: dnscrypt.c

dnsc_shared_secrets_sizefunc(void *k, void* ATTR_UNUSED(d))
{
    struct shared_secret_cache_key* ssk = (struct shared_secret_cache_key*)k;
    size_t key_size = sizeof(struct shared_secret_cache_key)
        + lock_get_mem(&ssk->entry.lock);
    size_t data_size = crypto_box_BEFORENMBYTES;
    (void)ssk; /* otherwise ssk is unused if no threading, or fixed locksize */
    return key_size + data_size;
}

Project: unbound
File: dnscrypt.c

dnsc_nonces_deldatafunc(void* ATTR_UNUSED(d), void* ATTR_UNUSED(arg))
{
    return;
}

Project: unbound
File: dnscrypt.c

dnsc_apply_cfg(struct dnsc_env *env, struct config_file *cfg)
{
    if(dnsc_parse_certs(env, cfg) <= 0) {
        fatal_exit("dnsc_apply_cfg: no cert file loaded");
    }
    if(dnsc_parse_keys(env, cfg) <= 0) {
        fatal_exit("dnsc_apply_cfg: no key file loaded");
    }
    randombytes_buf(env->hash_key, sizeof env->hash_key);
    env->provider_name = cfg->dnscrypt_provider;

    if(dnsc_load_local_data(env, cfg) <= 0) {
        fatal_exit("dnsc_apply_cfg: could not load local data");
    }
    lock_basic_lock(&env->shared_secrets_cache_lock);
    env->shared_secrets_cache = slabhash_create(
        cfg->dnscrypt_shared_secret_cache_slabs,
        HASH_DEFAULT_STARTARRAY,
        cfg->dnscrypt_shared_secret_cache_size,
        dnsc_shared_secrets_sizefunc,
        dnsc_shared_secrets_compfunc,
        dnsc_shared_secrets_delkeyfunc,
        dnsc_shared_secrets_deldatafunc,
        NULL
    );
    lock_basic_unlock(&env->shared_secrets_cache_lock);
    if(!env->shared_secrets_cache){
        fatal_exit("dnsc_apply_cfg: could not create shared secrets cache.");
    }
    lock_basic_lock(&env->nonces_cache_lock);
    env->nonces_cache = slabhash_create(
        cfg->dnscrypt_nonce_cache_slabs,
        HASH_DEFAULT_STARTARRAY,
        cfg->dnscrypt_nonce_cache_size,
        dnsc_nonces_sizefunc,
        dnsc_nonces_compfunc,
        dnsc_nonces_delkeyfunc,
        dnsc_nonces_deldatafunc,
        NULL
    );
    lock_basic_unlock(&env->nonces_cache_lock);
    return 0;
}

Project: unbound
File: respip.c

respip_set_get_tree(struct respip_set* set)
{
	if(!set)
		return NULL;
	return &set->ip_tree;
}

Project: unbound
File: dnscrypt.c

dnsc_nonce_cache_insert(struct slabhash *cache,
                        const uint8_t nonce[crypto_box_HALF_NONCEBYTES],
                        const uint8_t magic_query[DNSCRYPT_MAGIC_HEADER_LEN],
                        const uint8_t pk[crypto_box_PUBLICKEYBYTES],
                        uint32_t hash)
{
    struct nonce_cache_key* k =
        (struct nonce_cache_key*)calloc(1, sizeof(*k));
    if(!k) {
        free(k);
        return;
    }
    lock_rw_init(&k->entry.lock);
    memcpy(k->nonce, nonce, crypto_box_HALF_NONCEBYTES);
    memcpy(k->magic_query, magic_query, DNSCRYPT_MAGIC_HEADER_LEN);
    memcpy(k->client_publickey, pk, crypto_box_PUBLICKEYBYTES);
    k->entry.hash = hash;
    k->entry.key = k;
    k->entry.data = NULL;
    slabhash_insert(cache,
                    hash, &k->entry,
                    NULL,
                    NULL);
}

Project: unbound
File: respip.c

respip_merge_cname(struct reply_info* base_rep,
	const struct query_info* qinfo, const struct reply_info* tgt_rep,
	const struct respip_client_info* cinfo, int must_validate,
	struct reply_info** new_repp, struct regional* region)
{
	struct reply_info* new_rep;
	struct reply_info* tmp_rep = NULL; /* just a placeholder */
	struct ub_packed_rrset_key* alias_rrset = NULL; /* ditto */
	uint16_t tgt_rcode;
	size_t i, j;
	struct respip_action_info actinfo = {respip_none, NULL};

	/* If the query for the CNAME target would result in an unusual rcode,
	 * we generally translate it as a failure for the base query
	 * (which would then be translated into SERVFAIL).  The only exception
	 * is NXDOMAIN and YXDOMAIN, which are passed to the end client(s).
	 * The YXDOMAIN case would be rare but still possible (when
	 * DNSSEC-validated DNAME has been cached but synthesizing CNAME
	 * can't be generated due to length limitation) */
	tgt_rcode = FLAGS_GET_RCODE(tgt_rep->flags);
	if((tgt_rcode != LDNS_RCODE_NOERROR &&
		tgt_rcode != LDNS_RCODE_NXDOMAIN &&
		tgt_rcode != LDNS_RCODE_YXDOMAIN) ||
		(must_validate && tgt_rep->security <= sec_status_bogus)) {
		return 0;
	}

	/* see if the target reply would be subject to a response-ip action. */
	if(!respip_rewrite_reply(qinfo, cinfo, tgt_rep, &tmp_rep, &actinfo,
		&alias_rrset, 1, region))
		return 0;
	if(actinfo.action != respip_none) {
		log_info("CNAME target of redirect response-ip action would "
			"be subject to response-ip action, too; stripped");
		*new_repp = base_rep;
		return 1;
	}

	/* Append target reply to the base.  Since we cannot assume
	 * tgt_rep->rrsets is valid throughout the lifetime of new_rep
	 * or it can be safely shared by multiple threads, we need to make a
	 * deep copy. */
	new_rep = make_new_reply_info(base_rep, region,
		base_rep->an_numrrsets + tgt_rep->an_numrrsets,
		base_rep->an_numrrsets);
	if(!new_rep)
		return 0;
	for(i=0,j=base_rep->an_numrrsets; i<tgt_rep->an_numrrsets; i++,j++) {
		new_rep->rrsets[j] = copy_rrset(tgt_rep->rrsets[i], region);
		if(!new_rep->rrsets[j])
			return 0;
	}

	FLAGS_SET_RCODE(new_rep->flags, tgt_rcode);
	*new_repp = new_rep;
	return 1;
}

Project: unbound
File: dnscrypt.c

dnsc_parse_certs(struct dnsc_env *env, struct config_file *cfg)
{
	struct config_strlist *head, *head2;
	size_t signed_cert_id;
	size_t rotated_cert_id;
	char *nm;

	env->signed_certs_count = 0U;
	env->rotated_certs_count = 0U;
	for (head = cfg->dnscrypt_provider_cert; head; head = head->next) {
		env->signed_certs_count++;
	}
	for (head = cfg->dnscrypt_provider_cert_rotated; head; head = head->next) {
		env->rotated_certs_count++;
	}
	env->signed_certs = sodium_allocarray(env->signed_certs_count,
										  sizeof *env->signed_certs);

	env->rotated_certs = sodium_allocarray(env->rotated_certs_count,
										  sizeof env->signed_certs);
	signed_cert_id = 0U;
	rotated_cert_id = 0U;
	for(head = cfg->dnscrypt_provider_cert; head; head = head->next, signed_cert_id++) {
		nm = dnsc_chroot_path(cfg, head->str);
		if(dnsc_read_from_file(
				nm,
				(char *)(env->signed_certs + signed_cert_id),
				sizeof(struct SignedCert)) != 0) {
			fatal_exit("dnsc_parse_certs: failed to load %s: %s", head->str, strerror(errno));
		}
		for(head2 = cfg->dnscrypt_provider_cert_rotated; head2; head2 = head2->next) {
			if(strcmp(head->str, head2->str) == 0) {
				*(env->rotated_certs + rotated_cert_id) = env->signed_certs + signed_cert_id;
				rotated_cert_id++;
				verbose(VERB_OPS, "Cert %s is rotated and will not be distributed via DNS", head->str);
				break;
			}
		}
		verbose(VERB_OPS, "Loaded cert %s", head->str);
	}
	return signed_cert_id;
}

Project: unbound
File: dnscrypt.c

dnsc_parse_keys(struct dnsc_env *env, struct config_file *cfg)
{
	struct config_strlist *head;
	size_t cert_id, keypair_id;
	size_t c;
	char *nm;

	env->keypairs_count = 0U;
	for (head = cfg->dnscrypt_secret_key; head; head = head->next) {
		env->keypairs_count++;
	}

	env->keypairs = sodium_allocarray(env->keypairs_count,
		sizeof *env->keypairs);
	env->certs = sodium_allocarray(env->signed_certs_count,
		sizeof *env->certs);

	cert_id = 0U;
	keypair_id = 0U;
	for(head = cfg->dnscrypt_secret_key; head; head = head->next, keypair_id++) {
		char fingerprint[80];
		int found_cert = 0;
		KeyPair *current_keypair = &env->keypairs[keypair_id];
		nm = dnsc_chroot_path(cfg, head->str);
		if(dnsc_read_from_file(
				nm,
				(char *)(current_keypair->crypt_secretkey),
				crypto_box_SECRETKEYBYTES) != 0) {
			fatal_exit("dnsc_parse_keys: failed to load %s: %s", head->str, strerror(errno));
		}
		verbose(VERB_OPS, "Loaded key %s", head->str);
		if (crypto_scalarmult_base(current_keypair->crypt_publickey,
			current_keypair->crypt_secretkey) != 0) {
			fatal_exit("dnsc_parse_keys: could not generate public key from %s", head->str);
		}
		dnsc_key_to_fingerprint(fingerprint, current_keypair->crypt_publickey);
		verbose(VERB_OPS, "Crypt public key fingerprint for %s: %s", head->str, fingerprint);
		// find the cert matching this key
		for(c = 0; c < env->signed_certs_count; c++) {
			if(memcmp(current_keypair->crypt_publickey,
				env->signed_certs[c].server_publickey,
				crypto_box_PUBLICKEYBYTES) == 0) {
				dnsccert *current_cert = &env->certs[cert_id++];
				found_cert = 1;
				current_cert->keypair = current_keypair;
				memcpy(current_cert->magic_query,
				       env->signed_certs[c].magic_query,
					sizeof env->signed_certs[c].magic_query);
				memcpy(current_cert->es_version,
				       env->signed_certs[c].version_major,
				       sizeof env->signed_certs[c].version_major
				);
				dnsc_key_to_fingerprint(fingerprint,
							current_cert->keypair->crypt_publickey);
				verbose(VERB_OPS, "Crypt public key fingerprint for %s: %s",
					head->str, fingerprint);
				verbose(VERB_OPS, "Using %s",
					key_get_es_version(current_cert->es_version));
#ifndef USE_DNSCRYPT_XCHACHA20
				if (current_cert->es_version[1] == 0x02) {
				    fatal_exit("Certificate for XChacha20 but libsodium does not support it.");
				}
#endif

            		}
        	}
		if (!found_cert) {
		    fatal_exit("dnsc_parse_keys: could not match certificate for key "
			       "%s. Unable to determine ES version.",
			       head->str);
		}
	}
	return cert_id;
}

Project: unbound
File: respip.c

respip_find_or_create(struct respip_set* set, const char* ipstr, int create)
{
	struct resp_addr* node;
	struct sockaddr_storage addr;
	int net;
	socklen_t addrlen;

	if(!netblockstrtoaddr(ipstr, 0, &addr, &addrlen, &net)) {
		log_err("cannot parse netblock: '%s'", ipstr);
		return NULL;
	}
	node = (struct resp_addr*)addr_tree_find(&set->ip_tree, &addr, addrlen, net);
	if(!node && create) {
		node = regional_alloc_zero(set->region, sizeof(*node));
		if(!node) {
			log_err("out of memory");
			return NULL;
		}
		node->action = respip_none;
		if(!addr_tree_insert(&set->ip_tree, &node->node, &addr,
			addrlen, net)) {
			/* We know we didn't find it, so this should be
			 * impossible. */
			log_warn("unexpected: duplicate address: %s", ipstr);
		}
	}
	return node;
}

Project: unbound
File: respip.c

respip_set_is_empty(const struct respip_set* set)
{
	return set ? set->ip_tree.count == 0 : 1;
}

Project: unbound
File: dnscrypt.c

dnscrypt_hrtime(void)
{
    struct timeval tv;
    uint64_t ts = (uint64_t)0U;
    int ret;

    ret = gettimeofday(&tv, NULL);
    if (ret == 0) {
        ts = (uint64_t)tv.tv_sec * 1000000U + (uint64_t)tv.tv_usec;
    } else {
        log_err("gettimeofday: %s", strerror(errno));
    }
    return ts;
}

Project: unbound
File: respip.c

respip_inform_print(struct respip_addr_info* respip_addr, uint8_t* qname,
	uint16_t qtype, uint16_t qclass, struct local_rrset* local_alias,
	struct comm_reply* repinfo)
{
	char srcip[128], respip[128], txt[512];
	unsigned port;

	if(local_alias)
		qname = local_alias->rrset->rk.dname;
	port = (unsigned)((repinfo->addr.ss_family == AF_INET) ?
		ntohs(((struct sockaddr_in*)&repinfo->addr)->sin_port) :
		ntohs(((struct sockaddr_in6*)&repinfo->addr)->sin6_port));
	addr_to_str(&repinfo->addr, repinfo->addrlen, srcip, sizeof(srcip));
	addr_to_str(&respip_addr->addr, respip_addr->addrlen,
		respip, sizeof(respip));
	snprintf(txt, sizeof(txt), "%s/%d inform %s@%u", respip,
		respip_addr->net, srcip, port);
	log_nametypeclass(0, txt, qname, qtype, qclass);
}

Project: unbound
File: respip.c

rdata2sockaddr(const struct packed_rrset_data* rd, uint16_t rtype, size_t i,
	struct sockaddr_storage* ss, socklen_t* addrlenp)
{
	/* unbound can accept and cache odd-length AAAA/A records, so we have
	 * to validate the length. */
	if(rtype == LDNS_RR_TYPE_A && rd->rr_len[i] == 6) {
		struct sockaddr_in* sa4 = (struct sockaddr_in*)ss;

		memset(sa4, 0, sizeof(*sa4));
		sa4->sin_family = AF_INET;
		memcpy(&sa4->sin_addr, rd->rr_data[i] + 2,
			sizeof(sa4->sin_addr));
		*addrlenp = sizeof(*sa4);
		return 1;
	} else if(rtype == LDNS_RR_TYPE_AAAA && rd->rr_len[i] == 18) {
		struct sockaddr_in6* sa6 = (struct sockaddr_in6*)ss;

		memset(sa6, 0, sizeof(*sa6));
		sa6->sin6_family = AF_INET6;
		memcpy(&sa6->sin6_addr, rd->rr_data[i] + 2,
			sizeof(sa6->sin6_addr));
		*addrlenp = sizeof(*sa6);
		return 1;
	}
	return 0;
}

Project: unbound
File: dnscrypt.c

dnsc_read_from_file(char *fname, char *buf, size_t count)
{
    int fd;
    fd = open(fname, O_RDONLY);
    if (fd == -1) {
        return -1;
    }
    if (read(fd, buf, count) != (ssize_t)count) {
        close(fd);
        return -2;
    }
    close(fd);
    return 0;
}

Project: unbound
File: dnscrypt.c

dnscrypt_pad(uint8_t *buf, const size_t len, const size_t max_len,
             const uint8_t *nonce, const uint8_t *secretkey)
{
    uint8_t *buf_padding_area = buf + len;
    size_t padded_len;
    uint32_t rnd;

    // no padding
    if (max_len < len + DNSCRYPT_MIN_PAD_LEN)
        return len;

    assert(nonce[crypto_box_HALF_NONCEBYTES] == nonce[0]);

    crypto_stream((unsigned char *)&rnd, (unsigned long long)sizeof(rnd), nonce,
                  secretkey);
    padded_len =
        len + DNSCRYPT_MIN_PAD_LEN + rnd % (max_len - len -
                                            DNSCRYPT_MIN_PAD_LEN + 1);
    padded_len += DNSCRYPT_BLOCK_SIZE - padded_len % DNSCRYPT_BLOCK_SIZE;
    if (padded_len > max_len)
        padded_len = max_len;

    memset(buf_padding_area, 0, padded_len - len);
    *buf_padding_area = 0x80;

    return padded_len;
}

Project: unbound
File: respip.c

respip_tag_cfg(struct respip_set* set, const char* ipstr,
	const uint8_t* taglist, size_t taglen)
{
	struct resp_addr* node;

	if(!(node=respip_find_or_create(set, ipstr, 1)))
		return 0;
	if(node->taglist) {
		log_warn("duplicate response-address-tag for '%s', overridden.",
			ipstr);
	}
	node->taglist = regional_alloc_init(set->region, taglist, taglen);
	if(!node->taglist) {
		log_err("out of memory");
		return 0;
	}
	node->taglen = taglen;
	return 1;
}

Project: unbound
File: respip.c

respip_set_apply_cfg(struct respip_set* set, char* const* tagname, int num_tags,
	struct config_strbytelist* respip_tags,
	struct config_str2list* respip_actions,
	struct config_str2list* respip_data)
{
	struct config_strbytelist* p;
	struct config_str2list* pa;
	struct config_str2list* pd;

	set->tagname = tagname;
	set->num_tags = num_tags;

	p = respip_tags;
	while(p) {
		struct config_strbytelist* np = p->next;

		log_assert(p->str && p->str2);
		if(!respip_tag_cfg(set, p->str, p->str2, p->str2len)) {
			config_del_strbytelist(p);
			return 0;
		}
		free(p->str);
		free(p->str2);
		free(p);
		p = np;
	}

	pa = respip_actions;
	while(pa) {
		struct config_str2list* np = pa->next;
		log_assert(pa->str && pa->str2);
		if(!respip_action_cfg(set, pa->str, pa->str2)) {
			config_deldblstrlist(pa);
			return 0;
		}
		free(pa->str);
		free(pa->str2);
		free(pa);
		pa = np;
	}

	pd = respip_data;
	while(pd) {
		struct config_str2list* np = pd->next;
		log_assert(pd->str && pd->str2);
		if(!respip_data_cfg(set, pd->str, pd->str2)) {
			config_deldblstrlist(pd);
			return 0;
		}
		free(pd->str);
		free(pd->str2);
		free(pd);
		pd = np;
	}
	addr_tree_init_parents(&set->ip_tree);

	return 1;
}

Project: unbound
File: dnscrypt.c

dnsc_shared_secret_cache_insert(struct slabhash *cache,
                                uint8_t key[DNSCRYPT_SHARED_SECRET_KEY_LENGTH],
                                uint32_t hash,
                                uint8_t nmkey[crypto_box_BEFORENMBYTES])
{
    struct shared_secret_cache_key* k =
        (struct shared_secret_cache_key*)calloc(1, sizeof(*k));
    uint8_t* d = malloc(crypto_box_BEFORENMBYTES);
    if(!k || !d) {
        free(k);
        free(d);
        return;
    }
    memcpy(d, nmkey, crypto_box_BEFORENMBYTES);
    lock_rw_init(&k->entry.lock);
    memcpy(k->key, key, DNSCRYPT_SHARED_SECRET_KEY_LENGTH);
    k->entry.hash = hash;
    k->entry.key = k;
    k->entry.data = d;
    slabhash_insert(cache,
                    hash, &k->entry,
                    d,
                    NULL);
}