update.c 14.6 KB
Newer Older
1 2
#include <config.h>

3 4
#include "knot/nameserver/update.h"
#include "knot/nameserver/internet.h"
5
#include "knot/nameserver/process_query.h"
6
#include "knot/dnssec/zone-sign.h"
7
#include "common/debug.h"
8
#include "knot/dnssec/zone-events.h"
9
#include "knot/updates/ddns.h"
10 11
#include "common/descriptor.h"
#include "knot/server/zones.h"
12

13 14
/* Forward decls. */
static int zones_process_update_auth(zone_t *zone, knot_pkt_t *query,
15
                              knot_rcode_t *rcode, const struct sockaddr_storage *addr,
16 17
                              knot_tsig_key_t *tsig_key);

18 19 20 21
/* AXFR-specific logging (internal, expects 'qdata' variable set). */
#define UPDATE_LOG(severity, msg...) \
	QUERY_LOG(severity, qdata, "UPDATE", msg)

22
static int update_forward(knot_pkt_t *pkt, struct query_data *qdata)
23
{
24
	/*! \todo This will be reimplemented when RESPONSE and REQUEST processors
25
	 *        are written. */
26

27 28
	zone_t* zone = (zone_t *)qdata->zone;
	knot_pkt_t *query = qdata->query;
29 30

	/* Check transport type. */
31 32 33
	unsigned flags = XFR_FLAG_TCP;
	if (qdata->param->proc_flags & NS_QUERY_LIMIT_SIZE) {
		flags = XFR_FLAG_UDP;
34 35 36 37 38
	}

	/* Prepare task. */
	knot_ns_xfr_t *rq = xfr_task_create(zone, XFR_TYPE_FORWARD, flags);
	if (!rq) {
39
		return NS_PROC_FAIL;
40
	}
41
	xfr_task_setaddr(rq, &zone->xfr_in.master, &zone->xfr_in.via);
42 43

	/* Copy query originator data. */
44
	rq->fwd_src_fd = qdata->param->query_socket;
45
	memcpy(&rq->fwd_addr, qdata->param->query_source, sizeof(struct sockaddr_storage));
46 47 48 49 50 51
	rq->packet_nr = knot_wire_get_id(query->wire);

	/* Duplicate query to keep it in memory during forwarding. */
	rq->query = knot_pkt_new(NULL, query->size, NULL);
	if (!rq->query) {
		xfr_task_free(rq);
52
		return NS_PROC_FAIL;
53 54
	}
	memcpy(rq->query->wire, query->wire, query->size);
55
	rq->query->size = query->size;
56 57

	/* Retain pointer to zone and issue. */
58 59
	xfrhandler_t *xfr = qdata->param->server->xfr;
	int ret = xfr_enqueue(xfr, rq);
60 61 62 63
	if (ret != KNOT_EOK) {
		xfr_task_free(rq);
	}

64 65 66
	/* No immediate response. */
	pkt->size = 0;
	return NS_PROC_DONE;
67
}
68 69 70

static int update_prereq_check(struct query_data *qdata)
{
71
	knot_pkt_t *query = qdata->query;
72
	const knot_zone_contents_t *contents = qdata->zone->contents;
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

	/*
	 * 2) DDNS Prerequisities Section processing (RFC2136, Section 3.2).
	 *
	 * \note Permissions section means probably policies and fine grained
	 *       access control, not transaction security.
	 */
	knot_rcode_t rcode = KNOT_RCODE_NOERROR;
	knot_ddns_prereq_t *prereqs = NULL;
	int ret = knot_ddns_process_prereqs(query, &prereqs, &rcode);
	if (ret == KNOT_EOK) {
		ret = knot_ddns_check_prereqs(contents, &prereqs, &rcode);
		knot_ddns_prereqs_free(&prereqs);
	}
	qdata->rcode = rcode;

	return ret;
}

92 93 94 95 96 97 98 99 100 101
static int update_process(knot_pkt_t *resp, struct query_data *qdata)
{
	/* Check prerequisites. */
	int ret = update_prereq_check(qdata);
	if (ret != KNOT_EOK) {
		return ret;
	}

	/*! \todo Reusing the API for compatibility reasons. */
	knot_rcode_t rcode = qdata->rcode;
102
	ret = zones_process_update_auth((zone_t *)qdata->zone, qdata->query,
103
	                                &rcode,
104
	                                qdata->param->query_source,
105 106 107 108 109
	                                qdata->sign.tsig_key);
	qdata->rcode = rcode;
	return ret;
}

110
int update_answer(knot_pkt_t *pkt, struct query_data *qdata)
111 112 113 114
{
	/* RFC1996 require SOA question. */
	NS_NEED_QTYPE(qdata, KNOT_RRTYPE_SOA, KNOT_RCODE_FORMERR);

115 116
	/* Check valid zone, transaction security and contents. */
	NS_NEED_ZONE(qdata, KNOT_RCODE_NOTAUTH);
117

118
	/* Allow pass-through of an unknown TSIG in DDNS forwarding (must have zone). */
119
	zone_t *zone = (zone_t *)qdata->zone;
120
	if (zone->xfr_in.has_master) {
121
		return update_forward(pkt, qdata);
122
	}
123

124 125 126 127
	/* Need valid transaction security. */
	NS_NEED_AUTH(zone->update_in, qdata);
	NS_NEED_ZONE_CONTENTS(qdata, KNOT_RCODE_SERVFAIL); /* Check expiration. */

128 129 130
	/*
	 * Check if UPDATE not running already.
	 */
131
	if (pthread_mutex_trylock(&zone->ddns_lock) != 0) {
132 133 134
		qdata->rcode = KNOT_RCODE_SERVFAIL;
		log_zone_error("Failed to process UPDATE for "
		               "zone %s: Another UPDATE in progress.\n",
135
		               zone->conf->name);
136 137
		return NS_PROC_FAIL;
	}
138

139 140 141 142
	struct timeval t_start = {0}, t_end = {0};
	gettimeofday(&t_start, NULL);
	UPDATE_LOG(LOG_INFO, "Started (serial %u).", knot_zone_serial(qdata->zone->contents));

143
	/* Reserve space for TSIG. */
144
	knot_pkt_reserve(pkt, tsig_wire_maxsize(qdata->sign.tsig_key));
145

146
	/* Process UPDATE. */
147
	int ret = update_process(pkt, qdata);
148

149
	pthread_mutex_unlock(&zone->ddns_lock);
150 151 152 153 154 155 156 157 158 159 160 161 162

	/* Evaluate */
	switch(ret) {
	case KNOT_EOK:    /* Last response. */
		gettimeofday(&t_end, NULL);
		UPDATE_LOG(LOG_INFO, "Finished in %.02fs.",
		           time_diff(&t_start, &t_end) / 1000.0);
		return NS_PROC_DONE;
		break;
	default:          /* Generic error. */
		UPDATE_LOG(LOG_ERR, "%s", knot_strerror(ret));
		return NS_PROC_FAIL;
	}
163
}
164

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
/*
 * This function should:
 * 1) Create zone shallow copy and the changes structure.
 * 2) Call knot_ddns_process_update().
 *    - If something went bad, call xfrin_rollback_update() and return an error.
 *    - If everything went OK, continue.
 * 3) Finalize the updated zone.
 *
 * NOTE: Mostly copied from xfrin_apply_changesets(). Should be refactored in
 *       order to get rid of duplicate code.
 */
int knot_ns_process_update(const knot_pkt_t *query,
                           knot_zone_contents_t *old_contents,
                           knot_zone_contents_t **new_contents,
                           knot_changesets_t *chgs, knot_rcode_t *rcode,
                           uint32_t new_serial)
{
	if (query == NULL || old_contents == NULL || chgs == NULL ||
	    EMPTY_LIST(chgs->sets) || new_contents == NULL || rcode == NULL) {
		return KNOT_EINVAL;
	}

	dbg_ns("Applying UPDATE to zone...\n");

	// 1) Create zone shallow copy.
	dbg_ns_verb("Creating shallow copy of the zone...\n");
	knot_zone_contents_t *contents_copy = NULL;
	int ret = xfrin_prepare_zone_copy(old_contents, &contents_copy);
	if (ret != KNOT_EOK) {
		dbg_ns("Failed to prepare zone copy: %s\n",
		          knot_strerror(ret));
		*rcode = KNOT_RCODE_SERVFAIL;
		return ret;
	}

	// 2) Apply the UPDATE and create changesets.
	dbg_ns_verb("Applying the UPDATE and creating changeset...\n");
	ret = knot_ddns_process_update(contents_copy, query,
	                               knot_changesets_get_last(chgs),
	                               chgs->changes, rcode, new_serial);
	if (ret != KNOT_EOK) {
		dbg_ns("Failed to apply UPDATE to the zone copy or no update"
		       " made: %s\n", (ret < 0) ? knot_strerror(ret)
		                                : "No change made.");
		xfrin_rollback_update(old_contents, &contents_copy,
		                      chgs->changes);
		return ret;
	}

	// 3) Finalize zone
	dbg_ns_verb("Finalizing updated zone...\n");
	ret = xfrin_finalize_updated_zone(contents_copy, false,
	                                  NULL);
	if (ret != KNOT_EOK) {
		dbg_ns("Failed to finalize updated zone: %s\n",
		       knot_strerror(ret));
		xfrin_rollback_update(old_contents, &contents_copy,
		                      chgs->changes);
		*rcode = (ret == KNOT_EMALF) ? KNOT_RCODE_FORMERR
		                             : KNOT_RCODE_SERVFAIL;
		return ret;
	}

	*new_contents = contents_copy;

	return KNOT_EOK;
}

static int replan_zone_sign_after_ddns(zone_t *zone, uint32_t refresh_at)
{
	assert(zone);

237
	if (zone->dnssec.timer->tv.tv_sec <= refresh_at) {
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
		return KNOT_EOK;
	}

	zones_cancel_dnssec(zone);
	return zones_schedule_dnssec(zone, refresh_at);
}

/*! \brief Process UPDATE query.
 *
 * Functions expects that the query is already authenticated
 * and TSIG signature is verified.
 *
 * \note Set parameter 'rcode' according to answering procedure.
 * \note Function expects RCU to be locked.
 *
 * \retval KNOT_EOK if successful.
 * \retval error if not.
 */
static int zones_process_update_auth(zone_t *zone, knot_pkt_t *query,
257
                              knot_rcode_t *rcode, const struct sockaddr_storage *addr,
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
                              knot_tsig_key_t *tsig_key)
{
	assert(zone);
	assert(query);
	assert(rcode);
	assert(addr);

	int ret = KNOT_EOK;

	/* Create log message prefix. */
	char *keytag = NULL;
	if (tsig_key) {
		keytag = knot_dname_to_str(tsig_key->name);
	}
	char *r_str = xfr_remote_str(addr, keytag);
	char *msg  = sprintf_alloc("UPDATE of '%s' from %s",
	                           zone->conf->name, r_str ? r_str : "'unknown'");
	free(r_str);
	free(keytag);

	/*!
	 * We must prepare a changesets_t structure even though there will
	 * be only one changeset - because of the API.
	 */
	knot_changesets_t *chgsets = knot_changesets_create();
	if (chgsets == NULL) {
		*rcode = KNOT_RCODE_SERVFAIL;
		log_zone_error("%s Cannot create changesets structure.\n", msg);
		free(msg);
		return ret;
	}

	// Process the UPDATE packet, apply to zone, create changesets.
	if (knot_changesets_create_changeset(chgsets) == NULL) {
		return KNOT_ENOMEM;
	}
	*rcode = KNOT_RCODE_SERVFAIL; /* SERVFAIL unless it applies correctly. */

	uint32_t new_serial = zones_next_serial(zone);

	knot_zone_contents_t *new_contents = NULL;
	knot_zone_contents_t *old_contents = zone->contents;
	ret = knot_ns_process_update(query, old_contents, &new_contents,
	                             chgsets, rcode, new_serial);
	if (ret != KNOT_EOK) {
		if (ret > 0) {
			log_zone_notice("%s: No change to zone made.\n", msg);
			*rcode = KNOT_RCODE_NOERROR;
		}

		knot_changesets_free(&chgsets);
		free(msg);
		return (ret < 0) ? ret : KNOT_EOK;
	}

	knot_changesets_t *sec_chs = NULL;
	knot_changeset_t *sec_ch = NULL;
	uint32_t refresh_at = 0;

	assert(zone->conf);
	if (zone->conf->dnssec_enable) {
		sec_chs = knot_changesets_create();
		sec_ch = knot_changesets_create_changeset(sec_chs);
		if (sec_chs == NULL || sec_ch == NULL) {
			xfrin_rollback_update(zone->contents, &new_contents,
			                      chgsets->changes);
			knot_changesets_free(&chgsets);
			free(msg);
			return KNOT_ENOMEM;
		}
	}

	// Apply changeset to zone created by DDNS processing

	hattrie_t *sorted_changes = NULL;

	if (zone->conf->dnssec_enable) {
		/*!
		 * Check if the UPDATE changed DNSKEYs. If yes, resign the whole
		 * zone, if not, sign only the changeset.
		 * Do the same if NSEC3PARAM changed.
		 */
		if (zones_dnskey_changed(old_contents, new_contents) ||
		    zones_nsec3param_changed(old_contents, new_contents)) {
			ret = knot_dnssec_zone_sign(new_contents, zone->conf,
			                            sec_ch,
			                            KNOT_SOA_SERIAL_KEEP,
			                            &refresh_at, new_serial);
		} else {
			// Sign the created changeset
			ret = knot_dnssec_sign_changeset(new_contents, zone->conf,
			                      knot_changesets_get_last(chgsets),
			                      sec_ch, KNOT_SOA_SERIAL_KEEP,
			                      &refresh_at,
			                      new_serial, &sorted_changes);
		}

		if (ret != KNOT_EOK) {
			log_zone_error("%s: Failed to sign incoming update (%s)"
			               "\n", msg, knot_strerror(ret));
			xfrin_rollback_update(zone->contents, &new_contents,
					      chgsets->changes);
			knot_changesets_free(&chgsets);
			knot_changesets_free(&sec_chs);
			free(msg);
			return ret;
		}
	}

	// Merge changesets
	journal_t *transaction = NULL;
	ret = zones_merge_and_store_changesets(zone, chgsets, sec_chs,
	                                       &transaction);
	if (ret != KNOT_EOK) {
		log_zone_error("%s: Failed to store changesets (%s)\n",
		               msg, knot_strerror(ret));
		xfrin_rollback_update(zone->contents, &new_contents,
		                      chgsets->changes);
		zones_free_merged_changesets(chgsets, sec_chs);
		free(msg);
		return ret;
	}

	bool new_signatures = !knot_changeset_is_empty(sec_ch);
	// Apply DNSSEC changeset
	if (new_signatures) {
		ret = xfrin_apply_changesets_dnssec(old_contents,
		                                    new_contents,
		                                    sec_chs,
		                                    chgsets,
		                                    sorted_changes);
		knot_zone_clear_sorted_changes(sorted_changes);
		hattrie_free(sorted_changes);
		if (ret != KNOT_EOK) {
			log_zone_error("%s: Failed to sign incoming update %s\n",
			               msg, knot_strerror(ret));
			zones_store_changesets_rollback(transaction);
			zones_free_merged_changesets(chgsets, sec_chs);
			return ret;
		}

		// Plan zone resign if needed
400
		assert(zone->dnssec.timer);
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
		ret = replan_zone_sign_after_ddns(zone, refresh_at);
		if (ret != KNOT_EOK) {
			log_zone_error("%s: Failed to replan zone sign %s\n",
			               msg, knot_strerror(ret));
			zones_store_changesets_rollback(transaction);
			zones_free_merged_changesets(chgsets, sec_chs);
			return ret;
		}
	} else {
		// Set NSEC3 nodes if no new signatures were created (or auto DNSSEC is off)
		ret = knot_zone_contents_adjust_nsec3_pointers(new_contents);
		if (ret != KNOT_EOK) {
			zones_store_changesets_rollback(transaction);
			zones_free_merged_changesets(chgsets, sec_chs);
			xfrin_rollback_update(zone->contents, &new_contents,
			                      chgsets->changes);
			free(msg);
			return ret;
		}
	}

	// Commit transaction.
	if (transaction) {
		ret = zones_store_changesets_commit(transaction);
		if (ret != KNOT_EOK) {
			log_zone_error("%s: Failed to commit stored "
			               "changesets: %s."
			               "\n", msg, knot_strerror(ret));
			xfrin_rollback_update(zone->contents, &new_contents,
			                      chgsets->changes);
			zones_free_merged_changesets(chgsets, sec_chs);
			free(msg);
			return ret;
		}
	}

	// Switch zone contents.
	zone_retain(zone);      /* Retain pointer for safe RCU unlock. */
	rcu_read_unlock();      /* Unlock for switch. */
	ret = xfrin_switch_zone(zone, new_contents, XFR_TYPE_UPDATE);
	rcu_read_lock();        /* Relock */
	zone_release(zone);     /* Release held pointer. */
	if (ret != KNOT_EOK) {
		log_zone_error("%s Failed to replace current zone - %s\n",
		               msg, knot_strerror(ret));
		// Cleanup old and new contents
		xfrin_rollback_update(zone->contents, &new_contents,
		                      chgsets->changes);

		/* Free changesets, but not the data. */
		zones_free_merged_changesets(chgsets, sec_chs);
		return KNOT_ERROR;
	}

	// Cleanup.
	xfrin_cleanup_successful_update(chgsets->changes);
	if (sec_chs) {
		xfrin_cleanup_successful_update(sec_chs->changes);
	}

	// Free changesets, but not the data.
	zones_free_merged_changesets(chgsets, sec_chs);
	assert(ret == KNOT_EOK);
	*rcode = KNOT_RCODE_NOERROR; /* Mark as successful. */
	if (new_signatures) {
		log_zone_info("%s: Signed.\n", msg);
	}

	free(msg);
	msg = NULL;

	/* Trim extra heap. */
	mem_trim();

	/* Sync zonefile immediately if configured. */
	if (zone->conf->dbsync_timeout == 0) {
477
		zones_schedule_zonefile_sync(zone, 0);
478 479 480 481 482
	}

	return ret;
}

483
#undef UPDATE_LOG