summaryrefslogtreecommitdiff
path: root/src/libknot/tsig-op.c
blob: cb280abb7b4f638481a821be624e12eb271b6df6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
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
400
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
/*  Copyright (C) 2011 CZ.NIC, z.s.p.o. <knot-dns@labs.nic.cz>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <assert.h>
#include <stdint.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <time.h>

#include "common.h"
#include "common/base64.h"
#include "tsig.h"
#include "tsig-op.h"
#include "util/wire.h"
#include "util/debug.h"
#include "consts.h"


const int KNOT_TSIG_MAX_DIGEST_SIZE = 64;    // size of HMAC-SHA512 digest
const uint16_t KNOT_TSIG_FUDGE_DEFAULT = 300;  // default Fudge value
enum b64_const {
	B64BUFSIZE = 65535
};

static int knot_tsig_check_algorithm(const knot_rrset_t *tsig_rr)
{
	if (tsig_rr == NULL) {
		return KNOT_EINVAL;
	}
	
	const knot_dname_t *alg_name = tsig_rdata_alg_name(tsig_rr);
	if (!alg_name) {
		return KNOT_EMALF;
	}

	tsig_algorithm_t alg = tsig_alg_from_name(alg_name);
	if (alg == 0) {
		/*!< \todo is this error OK? */
		dbg_tsig("TSIG: unknown algorithm.\n");
		return KNOT_TSIG_EBADSIG;
	}

	return KNOT_EOK;
}

static int knot_tsig_check_key(const knot_rrset_t *tsig_rr,
                               const knot_key_t *tsig_key)
{
	if (tsig_rr == NULL || tsig_key == NULL) {
		return KNOT_EINVAL;
	}
	
	const knot_dname_t *tsig_name = knot_rrset_owner(tsig_rr);
	if (!tsig_name) {
		return KNOT_EMALF;
	}

	char *name = knot_dname_to_str(tsig_name);
	if (!name) {
		return KNOT_EMALF;
	}

	if (knot_dname_compare(tsig_name, tsig_key->name) != 0) {
		/*!< \todo which error. */
		dbg_tsig("TSIG: unknown key: %s\n", name);
		free(name);
		return KNOT_TSIG_EBADKEY;
	}

	free(name);
	return KNOT_EOK;
}

static int knot_tsig_compute_digest(const uint8_t *wire, size_t wire_len,
                                    uint8_t *digest, size_t *digest_len,
                                    const knot_key_t *key)
{
	if (!wire || !digest || !digest_len || !key) {
		dbg_tsig("TSIG: digest: bad args.\n");
		return KNOT_EINVAL;
	}

	if (!key->name) {
		dbg_tsig("TSIG: digest: no algorithm\n");
		return KNOT_EMALF;
	}

	tsig_algorithm_t tsig_alg = key->algorithm;
	if (tsig_alg == 0) {
		dbg_tsig("TSIG: digest: unknown algorithm\n");
		return KNOT_TSIG_EBADSIG;
	}

	/* Decode key from Base64. */
	char decoded_key[B64BUFSIZE];
	memset(decoded_key, 0, sizeof(decoded_key));
	
	size_t decoded_key_size = B64BUFSIZE;
	int ret = base64_decode(key->secret, strlen(key->secret),
	                        decoded_key,
	                        &decoded_key_size);
	if (ret != 1) {
		dbg_tsig("TSIG: New decode function failed! (%d)\n", ret);
		return KNOT_ERROR;
	}
	
	if (decoded_key_size < 0) {
		dbg_tsig("TSIG: Could not decode Base64\n");
		return KNOT_ERROR;
	}
	
	dbg_tsig_detail("TSIG: decoded key size: %d\n", decoded_key_size);
	dbg_tsig_detail("TSIG: decoded key:\n");
	dbg_tsig_hex_detail(decoded_key, decoded_key_size);
	dbg_tsig_detail("Wire for signing is %zu bytes long.\n", wire_len);

	/* Compute digest. */
	HMAC_CTX ctx;

	switch (tsig_alg) {
		case KNOT_TSIG_ALG_HMAC_MD5:
			HMAC_Init(&ctx, decoded_key,
			          decoded_key_size, EVP_md5());
			break;
		case KNOT_TSIG_ALG_HMAC_SHA1:
			HMAC_Init(&ctx, decoded_key,
			          decoded_key_size, EVP_sha1());
			break;
		case KNOT_TSIG_ALG_HMAC_SHA256:
			HMAC_Init(&ctx, decoded_key,
			          decoded_key_size, EVP_sha256());
			break;
		default:
			return KNOT_ENOTSUP;
	} /* switch */

	unsigned tmp_dig_len = *digest_len;
	HMAC_Update(&ctx, (const unsigned char *)wire, wire_len);
	HMAC_Final(&ctx, digest, &tmp_dig_len);
	*digest_len = tmp_dig_len;
	
	HMAC_CTX_cleanup(&ctx);

	return KNOT_EOK;
}

static int knot_tsig_check_time_signed(const knot_rrset_t *tsig_rr,
                                       uint64_t prev_time_signed)
{
	if (!tsig_rr) {
		dbg_tsig("TSIG: check_time_signed: NULL argument.\n");
		return KNOT_EINVAL;
	}

	/* Get the time signed and fudge values. */
	uint64_t time_signed = tsig_rdata_time_signed(tsig_rr);
	if (time_signed == 0) {
		return KNOT_TSIG_EBADTIME;
	}
	uint16_t fudge = tsig_rdata_fudge(tsig_rr);
	if (fudge == 0) {
		return KNOT_TSIG_EBADTIME;
	}

	/* Get the current time. */
	time_t curr_time = time(NULL);

	/*!< \todo bleeding eyes. */
	double diff = difftime(curr_time, (time_t)time_signed);

	if (diff > fudge || diff < -fudge) {
		return KNOT_TSIG_EBADTIME;
	}

	diff = difftime((time_t)time_signed, prev_time_signed);

	if (diff < 0) {
		return KNOT_TSIG_EBADTIME;
	}

	return KNOT_EOK;
}

static int knot_tsig_write_tsig_variables(uint8_t *wire,
                                          const knot_rrset_t *tsig_rr)
{
	if (wire == NULL || tsig_rr == NULL) {
		dbg_tsig("TSIG: write tsig variables: NULL arguments.\n");
		return KNOT_EINVAL;
	}
	
	/* Copy TSIG variables - starting with key name. */
	const knot_dname_t *tsig_owner = knot_rrset_owner(tsig_rr);
	if (!tsig_owner) {
		dbg_tsig("TSIG: write variables: no owner.\n");
		return KNOT_EINVAL;
	}

	int offset = 0;

	memcpy(wire + offset, knot_dname_name(tsig_owner),
	       sizeof(uint8_t) * knot_dname_size(tsig_owner));
	dbg_tsig_verb("TSIG: write variables: written owner (tsig alg): \n");
	dbg_tsig_hex_verb(wire + offset, knot_dname_size(tsig_owner));
	offset += knot_dname_size(tsig_owner);

	/*!< \todo which order? */

	/* Copy class. */
	knot_wire_write_u16(wire + offset, knot_rrset_class(tsig_rr));
	dbg_tsig_verb("TSIG: write variables: written CLASS: %u - ",
	               knot_rrset_class(tsig_rr));
	dbg_tsig_hex_detail(wire + offset, sizeof(uint16_t));
	offset += sizeof(uint16_t);

	/* Copy TTL - always 0. */
	knot_wire_write_u32(wire + offset, knot_rrset_ttl(tsig_rr));
	dbg_tsig_verb("TSIG: write variables: written TTL: %u - ",
	              knot_rrset_ttl(tsig_rr));
	dbg_tsig_hex_detail(wire + offset, sizeof(uint32_t));
	offset += sizeof(uint32_t);

	/* Copy alg name. */
	const knot_dname_t *alg_name = tsig_rdata_alg_name(tsig_rr);
	if (!alg_name) {
		dbg_tsig("TSIG: write variables: no algorithm name.\n");
		return KNOT_EINVAL;
	}

	/* The algorithm name must be in canonical form, i.e. in lowercase. */
	if (knot_dname_to_lower_copy(alg_name, (char *)(wire + offset),
	        knot_dname_size(alg_name)) != KNOT_EOK)
	{
		dbg_tsig("TSIG: write variables: cannot convert algorithm "
		         "to lowercase.\n");
		return KNOT_EINVAL;
	}

#if defined(KNOT_TSIG_DEBUG) && defined(DEBUG_ENABLE_VERBOSE)
//	char *_algstr = knot_dname_to_str(alg_name);
	dbg_tsig_verb("TSIG: write variables: written alg name: %s\n",
	              wire + offset);
//	free(_algstr);
#endif

//	memcpy(wire + offset, knot_dname_name(alg_name),
//	       sizeof(uint8_t) * knot_dname_size(alg_name));
	offset += knot_dname_size(alg_name);

	/* Following data are written in network order. */
	/* Time signed. */
	knot_wire_write_u48(wire + offset, tsig_rdata_time_signed(tsig_rr));
	offset += 6;
	dbg_tsig_verb("TSIG: write variables: time signed: %llu \n",
	              tsig_rdata_time_signed(tsig_rr));
	dbg_tsig_hex_detail(wire + offset - 6, 6);
	/* Fudge. */
	knot_wire_write_u16(wire + offset, tsig_rdata_fudge(tsig_rr));
	offset += sizeof(uint16_t);
	dbg_tsig_verb("TSIG: write variables: fudge: %hu\n",
	              tsig_rdata_fudge(tsig_rr));
	/* TSIG error. */
	knot_wire_write_u16(wire + offset, tsig_rdata_error(tsig_rr));
	offset += sizeof(uint16_t);
	/* Get other data length. */
	uint16_t other_data_length = tsig_rdata_other_data_length(tsig_rr);
	/* Get other data. */
	const uint8_t *other_data = tsig_rdata_other_data(tsig_rr);
	if (!other_data) {
		dbg_tsig("TSIG: write variables: no other data.\n");
		return KNOT_EINVAL;
	}

	/*
	 * We cannot write the whole other_data, as it contains its length in
	 * machine order.
	 */
	knot_wire_write_u16(wire + offset, other_data_length);
	offset += sizeof(uint16_t);

	/* Skip the length. */
	dbg_tsig_verb("Copying other data.\n");
	memcpy(wire + offset, other_data, other_data_length);

	return KNOT_EOK;
}

static int knot_tsig_wire_write_timers(uint8_t *wire,
                                       const knot_rrset_t *tsig_rr)
{
	if (wire == NULL || tsig_rr == NULL) {
		dbg_tsig("TSIG: write timers: NULL arguments.\n");
		return KNOT_EINVAL;
	}
	
	//write time signed
	knot_wire_write_u48(wire, tsig_rdata_time_signed(tsig_rr));
	//write fudge
	knot_wire_write_u16(wire + 6, tsig_rdata_fudge(tsig_rr));

	return KNOT_EOK;
}

static int knot_tsig_create_sign_wire(const uint8_t *msg, size_t msg_len,
				      /*size_t msg_max_len, */const uint8_t *request_mac,
		                      size_t request_mac_len,
		                      uint8_t *digest, size_t *digest_len,
				      const knot_rrset_t *tmp_tsig,
		                      const knot_key_t *key)
{
	if (!msg || !key || digest_len == NULL) {
		dbg_tsig("TSIG: create wire: bad args.\n");
		return KNOT_EINVAL;
	}

	/* Create tmp TSIG. */
	int ret = KNOT_EOK;

	/*
	 * Create tmp wire, it should contain message
	 * plus request mac plus tsig varibles.
	 */
	dbg_tsig_verb("Counting wire size: %zu, %zu, %zu.\n",
	              msg_len, request_mac_len,
	              tsig_rdata_tsig_variables_length(tmp_tsig));
	size_t wire_len = sizeof(uint8_t) *
			(msg_len + request_mac_len + ((request_mac_len > 0)
			 ? 2 : 0) +
			tsig_rdata_tsig_variables_length(tmp_tsig));
	uint8_t *wire = malloc(wire_len);
	if (!wire) {
		ERR_ALLOC_FAILED;
		return KNOT_ENOMEM;
	}

	memset(wire, 0, wire_len);

	uint8_t *pos = wire;

	/* Copy the request MAC - should work even if NULL. */
	if (request_mac_len > 0) {
		dbg_tsig_verb("Copying request MAC size\n");
		knot_wire_write_u16(pos, request_mac_len);
		pos += 2;
	}
	dbg_tsig_verb("Copying request mac.\n");
	memcpy(pos, request_mac, sizeof(uint8_t) * request_mac_len);
	dbg_tsig_detail("TSIG: create wire: request mac:\n");
	dbg_tsig_hex_detail(pos, request_mac_len);
	pos += request_mac_len;
	/* Copy the original message. */
	dbg_tsig_verb("Copying original message.\n");
	memcpy(pos, msg, msg_len);
	pos += msg_len;
	/* Copy TSIG variables. */
	dbg_tsig_verb("Writing TSIG variables.\n");
	ret = knot_tsig_write_tsig_variables(pos, tmp_tsig);
	if (ret != KNOT_EOK) {
		dbg_tsig("TSIG: create wire: failed to write TSIG "
		         "variables: %s\n", knot_strerror(ret));
		free(wire);
		return ret;
	}

	/* Compute digest. */
	ret = knot_tsig_compute_digest(wire, wire_len, digest, digest_len, key);
	if (ret != KNOT_EOK) {
		dbg_tsig("TSIG: create wire: failed to compute digest: %s\n",
		         knot_strerror(ret));
		*digest_len = 0;
		free(wire);
		return ret;
	}

	free(wire);

	return KNOT_EOK;
}

static int knot_tsig_create_sign_wire_next(const uint8_t *msg, size_t msg_len,
                                           const uint8_t *prev_mac,
                                           size_t prev_mac_len,
                                           uint8_t *digest, size_t *digest_len,
                                           const knot_rrset_t *tmp_tsig,
                                           const knot_key_t *key)
{
	if (!msg || !key || digest_len == NULL) {
		dbg_tsig("TSIG: create wire: bad args.\n");
		return KNOT_EINVAL;
	}

	/* Create tmp TSIG. */
	int ret = KNOT_EOK;

	/*
	 * Create tmp wire, it should contain message
	 * plus request mac plus tsig varibles.
	 */
	dbg_tsig_verb("Counting wire size: %zu, %zu, %zu.\n",
	              msg_len, prev_mac_len,
	              tsig_rdata_tsig_timers_length());
	size_t wire_len = sizeof(uint8_t) *
	                (msg_len + prev_mac_len +
			tsig_rdata_tsig_timers_length() + 2);
	uint8_t *wire = malloc(wire_len);
	if (!wire) {
		ERR_ALLOC_FAILED;
		return KNOT_ENOMEM;
	}

	memset(wire, 0, wire_len);

	/* Copy the request MAC - should work even if NULL. */
	dbg_tsig_verb("Copying request mac size.\n");
	knot_wire_write_u16(wire, prev_mac_len);
	dbg_tsig_verb("Copying request mac.\n");
	memcpy(wire + 2, prev_mac, sizeof(uint8_t) * prev_mac_len);
	dbg_tsig_detail("TSIG: create wire: request mac:\n");
	dbg_tsig_hex_detail(wire + 2, prev_mac_len);
	/* Copy the original message. */
	dbg_tsig_verb("Copying original message.\n");
	memcpy(wire + prev_mac_len + 2, msg, msg_len);
	/* Copy TSIG variables. */
	
	dbg_tsig_verb("Writing TSIG timers.\n");
	ret = knot_tsig_wire_write_timers(wire + prev_mac_len + msg_len + 2, 
	                                  tmp_tsig);
	if (ret != KNOT_EOK) {
		dbg_tsig("TSIG: create wire: failed to write TSIG "
		         "timers: %s\n", knot_strerror(ret));
		free(wire);
		return ret;
	}

	/* Compute digest. */
	ret = knot_tsig_compute_digest(wire, wire_len,
	                               digest, digest_len, key);
	if (ret != KNOT_EOK) {
		dbg_tsig("TSIG: create wire: failed to compute digest: %s\n",
		         knot_strerror(ret));
		*digest_len = 0;
		free(wire);
		return ret;
	}

	free(wire);

	return KNOT_EOK;
}

int knot_tsig_sign(uint8_t *msg, size_t *msg_len,
                   size_t msg_max_len, const uint8_t *request_mac,
                   size_t request_mac_len,
                   uint8_t *digest, size_t *digest_len,
                   const knot_key_t *key, uint16_t tsig_rcode,
                   uint64_t request_time_signed)
{
	if (!msg || !msg_len || !key || digest == NULL || digest_len == NULL) {
		return KNOT_EINVAL;
	}

	knot_dname_t *key_name_copy = knot_dname_deep_copy(key->name);
	if (!key_name_copy) {
		dbg_tsig("TSIG: key_name_copy = NULL\n");
		return KNOT_ENOMEM;
	}

	knot_rrset_t *tmp_tsig =
		knot_rrset_new(key_name_copy,
			       KNOT_RRTYPE_TSIG, KNOT_CLASS_ANY, 0);
	/* Should be retained by rrsig or freed, release. */
	knot_dname_release(key_name_copy);
	if (!tmp_tsig) {
		dbg_tsig("TSIG: tmp_tsig = NULL\n");
		return KNOT_ENOMEM;
	}

	/* Create rdata for TSIG RR. */
	knot_rdata_t *rdata = knot_rdata_new();
	if (!rdata) {
		dbg_tsig("TSIG: rdata = NULL\n");
		knot_rrset_free(&tmp_tsig);
		return KNOT_ENOMEM;
	}

	knot_rrset_add_rdata(tmp_tsig, rdata);

	/* Create items for TSIG RR. */
	knot_rrtype_descriptor_t *desc =
		knot_rrtype_descriptor_by_type(KNOT_RRTYPE_TSIG);
	assert(desc);

	knot_rdata_item_t *items =
		malloc(sizeof(knot_rdata_item_t) * desc->length);
	if (!items) {
		dbg_tsig("TSIG: items = NULL\n");
		ERR_ALLOC_FAILED;
		knot_rrset_free(&tmp_tsig);
		knot_rdata_free(&rdata);
		return KNOT_ENOMEM;
	}

	memset(items, 0, sizeof(knot_rdata_item_t) * desc->length);

	int ret = knot_rdata_set_items(rdata, items, desc->length);
	if (ret != KNOT_EOK) {
		dbg_tsig("TSIG: rdata_set_items returned %s\n",
		         knot_strerror(ret));
		free(items);
		knot_rrset_free(&tmp_tsig);
		knot_rdata_free(&rdata);
		return ret;
	}
	free(items);

	tsig_rdata_set_alg(tmp_tsig, key->algorithm);

	/* Distinguish BADTIME response. */
	if (tsig_rcode == KNOT_TSIG_RCODE_BADTIME) {
		/* Set error */
		tsig_rdata_set_tsig_error(tmp_tsig, tsig_rcode);
		/* Set client's time signed into the time signed field. */
		tsig_rdata_set_time_signed(tmp_tsig, request_time_signed);

		/* Store current time into Other data. */
		uint8_t time_signed[6];
		time_t curr_time = time(NULL);

		uint64_t time64 = curr_time;
		knot_wire_write_u48(time_signed, time64);

		tsig_rdata_set_other_data(tmp_tsig, 6, time_signed);
	} else {
		tsig_rdata_store_current_time(tmp_tsig);
		tsig_rdata_set_tsig_error(tmp_tsig, 0);

		/* Set other len. */
		tsig_rdata_set_other_data(tmp_tsig, 0, 0);
	}

	tsig_rdata_set_fudge(tmp_tsig, KNOT_TSIG_FUDGE_DEFAULT);

	/* Set original ID */
	tsig_rdata_set_orig_id(tmp_tsig, knot_wire_get_id(msg));

	uint8_t digest_tmp[KNOT_TSIG_MAX_DIGEST_SIZE];
	size_t digest_tmp_len = 0;

	dbg_tsig_detail("tmp_tsig before sign_wire():\n");
	knot_rrset_dump(tmp_tsig, 0);

	ret = knot_tsig_create_sign_wire(msg, *msg_len, /*msg_max_len,*/
	                                     request_mac, request_mac_len,
	                                     digest_tmp, &digest_tmp_len,
					     tmp_tsig, key);
	if (ret != KNOT_EOK) {
		dbg_tsig("TSIG: could not create wire or sign wire: %s\n",
		         knot_strerror(ret));
		knot_rrset_deep_free(&tmp_tsig, 1, 1, 1);
		return ret;
	}

	/* Set the digest. */
	size_t tsig_wire_len = msg_max_len - *msg_len;
	dbg_tsig("TSIG: msg_len=%zu, msg_max_len=%zu, tsig_max_len=%zu\n",
		 *msg_len, msg_max_len, tsig_wire_len);
	int rr_count = 0;
	tsig_rdata_set_mac(tmp_tsig, digest_tmp_len, digest_tmp);

	/* Write RRSet to wire */
	ret = knot_rrset_to_wire(tmp_tsig, msg + *msg_len,
	                         &tsig_wire_len, &rr_count);
	if (ret != KNOT_EOK) {
		dbg_tsig("TSIG: rrset_to_wire = %s\n", knot_strerror(ret));
		*digest_len = 0;
		knot_rrset_deep_free(&tmp_tsig, 1, 1, 1);
		return ret;
	}

	knot_rrset_deep_free(&tmp_tsig, 1, 1, 1);

	*msg_len += tsig_wire_len;

	uint16_t arcount = knot_wire_get_arcount(msg);
	knot_wire_set_arcount(msg, ++arcount);
	
	// everything went ok, save the digest to the output parameter
	memcpy(digest, digest_tmp, digest_tmp_len);
	*digest_len = digest_tmp_len;

	return KNOT_EOK;
}

int knot_tsig_sign_next(uint8_t *msg, size_t *msg_len, size_t msg_max_len,
                        const uint8_t *prev_digest, size_t prev_digest_len,
                        uint8_t *digest, size_t *digest_len,
                        const knot_key_t *key, uint8_t *to_sign,
                        size_t to_sign_len)
{
	if (!msg || !msg_len || !key || !key || !digest || !digest_len) {
		return KNOT_EINVAL;
	}
	
	uint8_t digest_tmp[KNOT_TSIG_MAX_DIGEST_SIZE];
	size_t digest_tmp_len = 0;

	/* Create tmp TSIG. */
	knot_rrset_t *tmp_tsig =
		knot_rrset_new(key->name, KNOT_RRTYPE_TSIG, KNOT_CLASS_ANY, 0);
	if (!tmp_tsig) {
		return KNOT_ENOMEM;
	}
	
	/* Create rdata for TSIG RR. */
	knot_rdata_t *rdata = knot_rdata_new();
	if (!rdata) {
		dbg_tsig("TSIG: rdata = NULL\n");
		knot_rrset_free(&tmp_tsig);
		return KNOT_ENOMEM;
	}
	
	int ret = 0;

	ret = knot_rrset_add_rdata(tmp_tsig, rdata);
	if (ret != KNOT_EOK) {
		dbg_tsig("TSIG: could not add rdata\n");
		knot_rrset_free(&tmp_tsig);
		knot_rdata_free(&rdata);
		return ret;
	}

	/* Create items for TSIG RR. */
	knot_rrtype_descriptor_t *desc =
		knot_rrtype_descriptor_by_type(KNOT_RRTYPE_TSIG);
	assert(desc);

	knot_rdata_item_t *items =
		malloc(sizeof(knot_rdata_item_t) * desc->length);
	if (!items) {
		dbg_tsig("TSIG: items = NULL\n");
		ERR_ALLOC_FAILED;
		knot_rrset_free(&tmp_tsig);
		knot_rdata_free(&rdata);
		return KNOT_ENOMEM;
	}

	memset(items, 0, sizeof(knot_rdata_item_t) * desc->length);

	ret = knot_rdata_set_items(rdata, items, desc->length);
	if (ret != KNOT_EOK) {
		dbg_tsig("TSIG: rdata_set_items returned %s\n",
		         knot_strerror(ret));
		knot_rrset_free(&tmp_tsig);
		knot_rdata_free(&rdata);
		free(items);
		return ret;
	}
	free(items);

	tsig_rdata_store_current_time(tmp_tsig);
	tsig_rdata_set_fudge(tmp_tsig, KNOT_TSIG_FUDGE_DEFAULT);
	
	/* Create wire to be signed. */
	size_t wire_len = prev_digest_len + to_sign_len
	                  + KNOT_TSIG_TIMERS_LENGTH + 2;
	uint8_t *wire = malloc(wire_len);
	if (!wire) {
		ERR_ALLOC_FAILED;
		knot_rrset_free(&tmp_tsig);
		knot_rdata_deep_free(&rdata, KNOT_RRTYPE_TSIG, 0);
		return KNOT_ENOMEM;
	}
	memset(wire, 0, wire_len);

	/* Write previous digest length. */
	knot_wire_write_u16(wire, prev_digest_len);
	/* Write previous digest. */
	memcpy(wire + 2, prev_digest, sizeof(uint8_t) * prev_digest_len);
	/* Write original message. */
	memcpy(wire + prev_digest_len + 2, to_sign, to_sign_len);
	/* Write timers. */
	knot_tsig_wire_write_timers(wire + prev_digest_len + to_sign_len + 2,
	                            tmp_tsig);

	dbg_tsig_detail("Previous digest: \n");
	dbg_tsig_hex_detail(prev_digest, prev_digest_len);

	dbg_tsig_detail("Timers: \n");
	dbg_tsig_hex_detail(wire + prev_digest_len + *msg_len,
			    KNOT_TSIG_TIMERS_LENGTH);

	ret = knot_tsig_compute_digest(wire, wire_len,
	                               digest_tmp, &digest_tmp_len, key);
	
	/* No matter how the function did, this data is no longer needed. */
	free(wire);
	if (ret != KNOT_EOK) {
		knot_rrset_deep_free(&tmp_tsig, 1, 1, 1);
		*digest_len = 0;
		return ret;
	}
	
	if (digest_tmp_len > *digest_len) {
		knot_rrset_deep_free(&tmp_tsig, 1, 1, 1);
		*digest_len = 0;
		return KNOT_ESPACE;
	}

	/* Set the MAC. */
	tsig_rdata_set_mac(tmp_tsig, digest_tmp_len, digest_tmp);
	
	/* Set algorithm. */
	tsig_rdata_set_alg(tmp_tsig, key->algorithm);
	
	/* Set original id. */
	tsig_rdata_set_orig_id(tmp_tsig, knot_wire_get_id(msg));

	/* Set TSIG error. */
	tsig_rdata_set_tsig_error(tmp_tsig, 0);
	
	/* Set other data. */
	tsig_rdata_set_other_data(tmp_tsig, 0, NULL);

	dbg_tsig_verb("Message max length: %zu, message length: %zu\n",
	              msg_max_len, *msg_len);

	size_t tsig_wire_size = msg_max_len - *msg_len;
	int rr_count = 0;
	ret = knot_rrset_to_wire(tmp_tsig, msg + *msg_len,
	                         &tsig_wire_size, &rr_count);
	if (ret != KNOT_EOK) {
		knot_rrset_deep_free(&tmp_tsig, 1, 1, 1);
		*digest_len = 0;
		return ret;
	}

	/* This should not happen, at least one rr has to be converted. */
	if (rr_count == 0) {
		knot_rrset_deep_free(&tmp_tsig, 1, 1, 1);
		return KNOT_EINVAL;
	}

	knot_rrset_deep_free(&tmp_tsig, 1, 1, 1);

	*msg_len += tsig_wire_size;
	uint16_t arcount = knot_wire_get_arcount(msg);
	knot_wire_set_arcount(msg, ++arcount);
	
	memcpy(digest, digest_tmp, digest_tmp_len);
	*digest_len = digest_tmp_len;

	return KNOT_EOK;
}

static int knot_tsig_check_digest(const knot_rrset_t *tsig_rr,
                                  const uint8_t *wire, size_t size,
                                  const uint8_t *request_mac,
                                  size_t request_mac_len,
                                  const knot_key_t *tsig_key,
                                  uint64_t prev_time_signed,
                                  int use_times)
{
	if (!tsig_rr || !wire || !tsig_key) {
		return KNOT_EINVAL;
	}

	/* Check time signed. */
	int ret = knot_tsig_check_time_signed(tsig_rr, prev_time_signed);
	if (ret != KNOT_EOK) {
		return ret;
	}

	dbg_tsig_verb("TSIG: time checked.\n");

	/* Check that libknot knows the algorithm. */
	ret = knot_tsig_check_algorithm(tsig_rr);
	if (ret != KNOT_EOK) {
		return ret;
	}

	dbg_tsig_verb("TSIG: algorithm checked.\n");

	/* Check that key is valid, ie. the same as given in args. */
	ret = knot_tsig_check_key(tsig_rr, tsig_key);
	if (ret != KNOT_EOK) {
		return ret;
	}

	dbg_tsig_verb("TSIG: key validity checked.\n");

	/* Time OK algorithm OK, key name OK - do digest. */
	/* Calculate the size of TSIG RR. */
	size_t tsig_len = tsig_wire_actsize(tsig_rr);

	/* Strip the TSIG. */
	size -= tsig_len;

	uint8_t *wire_to_sign = malloc(sizeof(uint8_t) * size);
	if (!wire_to_sign) {
		ERR_ALLOC_FAILED;
		return KNOT_ENOMEM;
	}

	memset(wire_to_sign, 0, sizeof(uint8_t) * size);
	memcpy(wire_to_sign, wire, size);

	/* Decrease arcount. */
	knot_wire_set_arcount(wire_to_sign,
	                      knot_wire_get_arcount(wire_to_sign) - 1);

	uint8_t digest_tmp[KNOT_TSIG_MAX_DIGEST_SIZE];
	size_t digest_tmp_len = 0;
	assert(tsig_rr->rdata);
	
	if (use_times) {
		ret = knot_tsig_create_sign_wire_next(wire_to_sign, size, 
		                                 request_mac, request_mac_len,
		                                 digest_tmp, &digest_tmp_len, 
		                                 tsig_rr, tsig_key);
	} else {
		ret = knot_tsig_create_sign_wire(wire_to_sign, size, 
		                                 request_mac, request_mac_len,
		                                 digest_tmp, &digest_tmp_len, 
		                                 tsig_rr, tsig_key);
	}

	assert(tsig_rr->rdata);
	free(wire_to_sign);

	if (ret != KNOT_EOK) {
		dbg_tsig("Failed to create wire format for checking: %s.\n",
		         knot_strerror(ret));
		return ret;
	}

	dbg_tsig_verb("TSIG: digest calculated\n");

	/* Compare MAC from TSIG RR RDATA with just computed digest. */

	/*!< \todo move to function. */
	const knot_dname_t *alg_name = tsig_rdata_alg_name(tsig_rr);
	tsig_algorithm_t alg = tsig_alg_from_name(alg_name);

	/*! \todo [TSIG] TRUNCATION */
	uint16_t mac_length = tsig_rdata_mac_length(tsig_rr);
	const uint8_t *tsig_mac = tsig_rdata_mac(tsig_rr);

	if (mac_length != tsig_alg_digest_length(alg)) {
		dbg_tsig("TSIG: calculated digest length and given length do "
		         "not match!\n");
		return KNOT_TSIG_EBADSIG;
	}

	dbg_tsig_verb("TSIG: calc digest : ");
	dbg_tsig_hex_verb(digest_tmp, digest_tmp_len);

	dbg_tsig_verb("TSIG: given digest: ");
	dbg_tsig_hex_verb(tsig_mac, mac_length);

	if (strncasecmp((char *)(tsig_mac), (char *)digest_tmp,
	                mac_length) != 0) {
		return KNOT_TSIG_EBADSIG;
	}

	return KNOT_EOK;
}

int knot_tsig_server_check(const knot_rrset_t *tsig_rr,
                           const uint8_t *wire, size_t size,
                           const knot_key_t *tsig_key)
{
	dbg_tsig("tsig_server_check()\n");
	return knot_tsig_check_digest(tsig_rr, wire, size, NULL, 0, tsig_key,
	                              0, 0);
}

int knot_tsig_client_check(const knot_rrset_t *tsig_rr,
                           const uint8_t *wire, size_t size,
                           const uint8_t *request_mac, size_t request_mac_len,
                           const knot_key_t *tsig_key,
                           uint64_t prev_time_signed)
{
	dbg_tsig("tsig_client_check()\n");
	return knot_tsig_check_digest(tsig_rr, wire, size, request_mac,
	                              request_mac_len, tsig_key,
	                              prev_time_signed, 0);
}

int knot_tsig_client_check_next(const knot_rrset_t *tsig_rr,
                                const uint8_t *wire, size_t size,
                                const uint8_t *prev_digest,
                                size_t prev_digest_len,
                                const knot_key_t *tsig_key,
                                uint64_t prev_time_signed)
{
	dbg_tsig("tsig_client_check_next()\n");
	return knot_tsig_check_digest(tsig_rr, wire, size, prev_digest,
	                              prev_digest_len, tsig_key,
	                              prev_time_signed, 1);
	return KNOT_ENOTSUP;
}

int knot_tsig_add(uint8_t *msg, size_t *msg_len, size_t msg_max_len,
                  uint16_t tsig_rcode, const knot_rrset_t *tsig_rr)
{
	/*! \todo Revise!! */

	if (!msg || !msg_len || !tsig_rr) {
		return KNOT_EINVAL;
	}

	/*! \todo What key to use, when we do not sign? Does this even work? */
	knot_dname_t *key_name =
			knot_dname_deep_copy(knot_rrset_owner(tsig_rr));
	if (key_name == NULL) {
		dbg_tsig("TSIG: failed to copy owner\n");
		return KNOT_ERROR;
	}

	knot_rrset_t *tmp_tsig =
		knot_rrset_new(key_name, KNOT_RRTYPE_TSIG, KNOT_CLASS_ANY, 0);
	if (!tmp_tsig) {
		dbg_tsig("TSIG: tmp_tsig = NULL\n");
		knot_dname_free(&key_name);
		return KNOT_ENOMEM;
	}
	
	/* Already referenced in tmp_tsig, release. */
	knot_dname_release(key_name);

	/* Create rdata for TSIG RR. */
	knot_rdata_t *rdata = knot_rdata_new();
	if (!rdata) {
		dbg_tsig("TSIG: rdata = NULL\n");
		knot_rrset_deep_free(&tmp_tsig, 1, 1, 1);
		return KNOT_ENOMEM;
	}

	knot_rrset_add_rdata(tmp_tsig, rdata);

	/* Create items for TSIG RR. */
	knot_rrtype_descriptor_t *desc =
		knot_rrtype_descriptor_by_type(KNOT_RRTYPE_TSIG);
	assert(desc);

	knot_rdata_item_t *items =
		malloc(sizeof(knot_rdata_item_t) * desc->length);
	if (items == NULL) {
		dbg_tsig("TSIG: items = NULL\n");
		knot_rrset_deep_free(&tmp_tsig, 1, 1, 1);
		return KNOT_ENOMEM;
	}

	memset(items, 0, sizeof(knot_rdata_item_t) * desc->length);

	int ret = knot_rdata_set_items(rdata, items, desc->length);
	free(items);
	if (ret != KNOT_EOK) {
		dbg_tsig("TSIG: rdata_set_items returned %s\n",
		         knot_strerror(ret));
		knot_rrset_deep_free(&tmp_tsig, 1, 1, 1);
		return ret;
	}

	knot_dname_t *alg_name =
			knot_dname_deep_copy(tsig_rdata_alg_name(tsig_rr));
	if (alg_name == NULL) {
		dbg_tsig("TSIG: failed to copy alg name\n");
		knot_rrset_deep_free(&tmp_tsig, 1, 1, 1);
		return KNOT_ERROR;
	}

	tsig_rdata_set_alg_name(tmp_tsig, alg_name);
	tsig_rdata_set_time_signed(tmp_tsig, tsig_rdata_time_signed(tsig_rr));

	/* Comparing to BIND it was found out that the Fudge should always be
	 * set to the server's value.
	 */
	tsig_rdata_set_fudge(tmp_tsig, KNOT_TSIG_FUDGE_DEFAULT);
	tsig_rdata_set_mac(tmp_tsig, 0, NULL);
	knot_dname_release(alg_name); /* Already copied in tsig_rdata_set_alg_name() */

	/* Set original ID */
	tsig_rdata_set_orig_id(tmp_tsig, knot_wire_get_id(msg));

	/* Set error */
	tsig_rdata_set_tsig_error(tmp_tsig, tsig_rcode);

	assert(tsig_rcode != KNOT_TSIG_RCODE_BADTIME);
	/* Set other len. */
	tsig_rdata_set_other_data(tmp_tsig, 0, 0);

	size_t tsig_wire_len = msg_max_len - *msg_len;
	int rr_count = 0;

	/* Write RRSet to wire */
	ret = knot_rrset_to_wire(tmp_tsig, msg + *msg_len,
	                         &tsig_wire_len, &rr_count);
	if (ret != KNOT_EOK) {
		dbg_tsig("TSIG: rrset_to_wire = %s\n", knot_strerror(ret));
		knot_rrset_deep_free(&tmp_tsig, 1, 1, 1);
		return ret;
	}

	/* key_name already referenced in RRSet, no need to free separately. */
	knot_rrset_deep_free(&tmp_tsig, 1, 1, 1);

	*msg_len += tsig_wire_len;

	uint16_t arcount = knot_wire_get_arcount(msg);
	knot_wire_set_arcount(msg, ++arcount);

	return KNOT_EOK;
}