1 /*------------------------------------------------------------------------------
2  *
3  * Copyright (c) 2011-2021, EURid vzw. All rights reserved.
4  * The YADIFA TM software product is provided under the BSD 3-clause license:
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  *        * Redistributions of source code must retain the above copyright
11  *          notice, this list of conditions and the following disclaimer.
12  *        * Redistributions in binary form must reproduce the above copyright
13  *          notice, this list of conditions and the following disclaimer in the
14  *          documentation and/or other materials provided with the distribution.
15  *        * Neither the name of EURid nor the names of its contributors may be
16  *          used to endorse or promote products derived from this software
17  *          without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
23  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  *
31  *------------------------------------------------------------------------------
32  *
33  */
34 
35 /** @defgroup ### #######
36  *  @ingroup dnscore
37  *  @brief
38  *
39  * @{
40  */
41 
42 #include "dnscore/dnscore-config.h"
43 #include <unistd.h>
44 #include <sys/time.h>
45 #include <sys/types.h>
46 #include <sys/stat.h>
47 #include <fcntl.h>
48 #include <dirent.h>
49 
50 #include "dnscore/xfr_input_stream.h"
51 
52 #include "dnscore/zalloc.h"
53 #include "dnscore/packet_reader.h"
54 #include "dnscore/format.h"
55 #include "dnscore/file_input_stream.h"
56 #include "dnscore/file_output_stream.h"
57 #include "dnscore/buffer_input_stream.h"
58 #include "dnscore/buffer_output_stream.h"
59 #include "dnscore/fdtools.h"
60 #include "dnscore/pipe_stream.h"
61 #include "dnscore/message.h"
62 #include "dnscore/pool.h"
63 #include "dnscore/random.h"
64 #include "dnscore/thread_pool.h"
65 #include "dnscore/tcp_io_stream.h"
66 
67 /* it depends if host is DARWIN or LINUX */
68 #ifdef HAVE_SYS_SYSLIMITS_H
69 #ifndef __FreeBSD__
70 #include <sys/syslimits.h>
71 #endif
72 #elif HAVE_LINUX_LIMITS_H
73 #include <linux/limits.h>
74 #endif /* HAVE_SYS_SYSLIMITS_H */
75 
76 #define MODULE_MSG_HANDLE g_system_logger
77 
78 #define DEBUG_XFR_INPUT_STREAM 0
79 
80 typedef struct xfr_input_stream_data xfr_input_stream_data;
81 
82 #define XFRISDTA_TAG 0x4154445349524658
83 #define XFRISSOA_TAG 0x414f535349524658
84 #define XFRPOOL_TAG 0x4c4f4f50524658
85 
86 struct xfr_input_stream_data
87 {
88     output_stream pipe_stream_output;
89     input_stream pipe_stream_input;
90     input_stream source_stream;
91     output_stream source_output_stream;
92     packet_unpack_reader_data reader;
93 
94     message_data *message;
95     const u8 *origin;
96     u8 *pool;   // 64KB
97 
98     u8 *first_soa_record;
99     u32 first_soa_record_size;
100 
101     u16 ancount;
102     u16 xfr_mode;
103     u32 record_index;                   // index of the record in the stream
104 
105     u32 last_serial;
106     u32 last_refresh;
107     u32 last_retry;
108     u32 last_expire;
109     u32 last_nttl;
110 
111     u64 mesg_hdr_mask;
112     u64 mesg_hdr_result;
113     u64 next_hdr_mask;
114     u64 next_hdr_result;
115 
116     ya_result last_error;
117     bool eos;
118     bool ixfr_mark;
119     bool owns_message;
120     bool owns_input_stream;
121 #if DNSCORE_HAS_TSIG_SUPPORT
122     bool last_message_had_tsig;
123     bool need_cleanup_tsig;
124 #endif
125 };
126 
127 static pool_s xfr_pool;
128 static mutex_t xfr_pool_init_mtx = MUTEX_INITIALIZER;
129 static bool xfr_pool_initialised = FALSE;
130 
xfr_pool_alloc(void * args)131 static void *xfr_pool_alloc(void *args)
132 {
133     (void)args;
134     void *p;
135     MALLOC_OBJECT_ARRAY(p, u8, 0x1010a, XFRPOOL_TAG);
136     // void *p = malloc(0x1010a);
137     return p;
138 }
139 
xfr_pool_free(void * ptr,void * args)140 static void xfr_pool_free(void *ptr, void* args)
141 {
142     (void)args;
143     free(ptr);
144 }
145 
146 /**
147  * Reads from the (tcp) input stream for an xfr
148  * Detects the xfr type
149  * Copies into the right file
150  *
151  * @return error code
152  */
153 
154 //#if HAS_NON_AA_AXFR_SUPPORT
155 
156 /*
157  * Non-RFC-compliant masks (allows AA bit not set)
158  *
159  * It seems (some?) Microsoft DNS answers to an AXFR query without setting the AA bit
160  *
161  * The RFC 5936 states that in the case of an AXFR answer with no error (RCODE set to 0),
162  * the AA bit MUST be set.
163  *
164  */
165 
166 #ifdef WORDS_BIGENDIAN
167 #define AXFR_MESSAGE_LENIENT_HEADER_MASK    (( (u64) 0 )                                    | \
168                                      (((u64) (QR_BITS  | TC_BITS )) << 40 )| \
169                                      (((u64) ( RA_BITS | RCODE_BITS )) << 32 )      | \
170                                      ( (u64) 1LL << 16 ))
171 
172 #define AXFR_MESSAGE_LENIENT_HEADER_RESULT  (( (u64) (QR_BITS ) << 40 )            | \
173                                      ( ((u64) 1LL) << 16 ))
174 
175 #define AXFR_NEXT_MESSAGE_LENIENT_HEADER_MASK (( (u64) 0LL )                                   | \
176                                       (((u64) ( QR_BITS  | TC_BITS )) << 40 )| \
177                                       (((u64) ( RCODE_BITS )) << 32 ))
178 
179 
180 #define AXFR_NEXT_MESSAGE_LENIENT_HEADER_RESULT   (((u64) ( QR_BITS  )) << 40 )
181 
182 #else
183 #define AXFR_MESSAGE_LENIENT_HEADER_MASK     (( (u64) 0LL )                                   | \
184                                       (((u64) ( QR_BITS  | TC_BITS )) << 16 )| \
185                                       (((u64) ( RCODE_BITS )) << 24 )       | \
186                                       (((u64) 1LL) << 40 ))
187 
188 #define AXFR_MESSAGE_LENIENT_HEADER_RESULT   ((((u64) ( QR_BITS  )) << 16 )| \
189                                       (((u64) 1LL) << 40 ))
190 
191 #define AXFR_NEXT_MESSAGE_LENIENT_HEADER_MASK     (( (u64) 0LL )                                   | \
192                                       (((u64) ( QR_BITS  | TC_BITS )) << 16 )| \
193                                       (((u64) ( RCODE_BITS )) << 24 ))
194 
195 
196 #define AXFR_NEXT_MESSAGE_LENIENT_HEADER_RESULT   (((u64) ( QR_BITS  )) << 16 )
197 
198 #endif
199 
200 //#else
201 
202 /*
203  * RFC compliant masks (AA bit must be set)
204  */
205 
206 #ifdef WORDS_BIGENDIAN
207 #define AXFR_MESSAGE_HEADER_MASK    (( (u64) 0 )                                    | \
208                                      (((u64) (QR_BITS | AA_BITS | TC_BITS )) << 40 )| \
209                                      (((u64) ( RA_BITS | RCODE_BITS )) << 32 )      | \
210                                      ( (u64) 1LL << 16 ))
211 
212 #define AXFR_MESSAGE_HEADER_RESULT  (( (u64) (QR_BITS | AA_BITS) << 40 )            | \
213                                      ( ((u64) 1LL) << 16 ))
214 
215 #define AXFR_NEXT_MESSAGE_HEADER_MASK (( (u64) 0LL )                                   | \
216                                       (((u64) ( QR_BITS | AA_BITS | TC_BITS )) << 40 )| \
217                                       (((u64) ( RCODE_BITS )) << 32 ))
218 
219 
220 #define AXFR_NEXT_MESSAGE_HEADER_RESULT   (((u64) ( QR_BITS | AA_BITS )) << 40 )
221 
222 #else
223 #define AXFR_MESSAGE_HEADER_MASK     (( (u64) 0LL )                                   | \
224                                       (((u64) ( QR_BITS | AA_BITS | TC_BITS )) << 16 )| \
225                                       (((u64) ( RCODE_BITS )) << 24 )       | \
226                                       (((u64) 1LL) << 40 ))
227 
228 #define AXFR_MESSAGE_HEADER_RESULT   ((((u64) ( QR_BITS | AA_BITS )) << 16 )| \
229                                       (((u64) 1LL) << 40 ))
230 
231 #define AXFR_NEXT_MESSAGE_HEADER_MASK     (( (u64) 0LL )                                   | \
232                                       (((u64) ( QR_BITS | AA_BITS | TC_BITS )) << 16 )| \
233                                       (((u64) ( RCODE_BITS )) << 24 ))
234 
235 
236 #define AXFR_NEXT_MESSAGE_HEADER_RESULT   (((u64) ( QR_BITS | AA_BITS )) << 16 )
237 
238 #endif
239 
240 //#endif
241 
242 /*
243  * Reads the content of a message from the reader field in data (packet reader)
244  * The ancount field in data contains the number of records to read
245  * Every record read is written to the output pipe
246  */
247 
248 static ya_result
xfr_input_stream_read_packet(xfr_input_stream_data * data)249 xfr_input_stream_read_packet(xfr_input_stream_data *data)
250 {
251     //message_data *message = data->message;
252     packet_unpack_reader_data *reader = &data->reader;
253     u8 *record = data->pool; // no persistence of content needed
254     s32 record_len;
255     ya_result return_value = SUCCESS;
256 
257 #if DEBUG_XFR_INPUT_STREAM
258     log_debug("xfr_input_stream_read_packet(%p) ancount=%hd record_index=%u", data, data->ancount, data->record_index);
259 #endif
260 
261     while((data->ancount > 0) && (pipe_stream_write_available(&data->pipe_stream_output) > 2048 ))
262     {
263         --data->ancount;
264 
265         if(FAIL(record_len = packet_reader_read_record(reader, record, RDATA_MAX_LENGTH + 1)))
266         {
267             if(record_len != UNSUPPORTED_TYPE)
268             {
269                 data->eos = TRUE;
270 
271                 return_value = record_len;
272 
273                 break;
274             }
275 
276             log_err("xfr_input_stream: skipped unsupported record #%d %{recordwire}", data->record_index, record);
277 
278             data->record_index++;
279             continue;
280         }
281 
282 #if DEBUG_XFR_INPUT_STREAM
283         log_debug("xfr_input_stream: <%u %{recordwire}", data->record_index, record);
284 #endif
285 
286         const u8 *ptr = record + dnsname_len(record);
287 
288         u16 rtype = GET_U16_AT(*ptr);
289 
290         switch(rtype)
291         {
292             case TYPE_SOA:
293             {
294                 /* handle SOA case */
295 
296                 if(!dnsname_equals(record, data->origin))
297                 {
298                     data->eos = TRUE;
299 
300                     return_value = MAKE_DNSMSG_ERROR(FP_XFR_QUERYERROR); // OWNER OF SOA RECORD SHOULD BE ORIGIN (protocol error)
301 
302                     return return_value;
303                 }
304 
305                 ptr += 10;                  /* type class ttl rdata_size */
306                 ptr += dnsname_len(ptr);
307                 ptr += dnsname_len(ptr);
308                 u32 soa_serial = ntohl(GET_U32_AT(*ptr));
309 
310                 if(data->xfr_mode == TYPE_ANY) // the type of stream has not been decided yet
311                 {
312                     if(data->record_index == 1)
313                     {
314                         // second record is an SOA: this is an IXFR, the first record is not sent up
315 
316 #if DEBUG_XFR_INPUT_STREAM
317                         log_debug("xfr_input_stream: #%u %{recordwire} ; (IXFR START)", data->record_index, data->first_soa_record);
318 #endif
319 
320                         data->xfr_mode = TYPE_IXFR;
321                     }
322                     else
323                     {
324                         // second record is not an SOA: this is an AXFR, the first record is sent up
325 
326 #if DEBUG_XFR_INPUT_STREAM
327                         log_debug("xfr_input_stream: #%u %{recordwire} ; (AXFR START)", data->record_index, record);
328 #endif
329 
330                         output_stream_write(&data->pipe_stream_output, data->first_soa_record, data->first_soa_record_size);
331                         data->xfr_mode = TYPE_AXFR;
332                     }
333                 }
334 
335                 if(soa_serial == data->last_serial)
336                 {
337                     // the SOA serial has the same value as the last record we expect
338                     // if it's an AXFR or this is the second time it happens on an IXFR, then it's then end of the stream
339 
340                     if(data->xfr_mode == TYPE_AXFR || ((data->xfr_mode == TYPE_IXFR) && data->ixfr_mark))
341                     {
342                         return_value = SUCCESS;
343 
344                         /*
345                          * The last record of an AXFR must be written,
346                          * the last record of an IXFR must not.
347                          */
348 
349                         if(data->xfr_mode == TYPE_AXFR)
350                         {
351 #if DEBUG_XFR_INPUT_STREAM
352                             log_debug("xfr_input_stream: #%u %{recordwire} ; (AXFR END)", data->record_index, record);
353 #endif
354 
355                             return_value = output_stream_write(&data->pipe_stream_output, record, record_len);
356                         }
357 #if DEBUG_XFR_INPUT_STREAM
358                         else
359                         {
360                             log_debug("xfr_input_stream: #%u %{recordwire} ; (IXFR END)", data->record_index, record);
361                         }
362 #endif
363 
364                         // done
365                         data->eos = TRUE;
366 
367                         return return_value; // reached the end
368                     }
369 
370                     // IXFR needs to find the mark twice
371 
372 #if DEBUG_XFR_INPUT_STREAM
373                     log_debug("xfr_input_stream: #%u %{recordwire} ; (IXFR LAST)", data->record_index, record);
374 #endif
375 
376                     data->ixfr_mark = TRUE;
377                 }
378 
379                 break;
380             }
381 
382             case TYPE_IXFR:
383             case TYPE_AXFR:
384             case TYPE_OPT:
385             case TYPE_ANY:
386                 return INVALID_PROTOCOL;
387             default:
388             {
389                 if(data->record_index == 1)
390                 {
391                     // special case to detect an AXFR returned by an IXFR query
392 
393                     if(data->xfr_mode == TYPE_ANY)
394                     {
395                         data->xfr_mode = TYPE_AXFR;
396 
397                         if(FAIL(return_value = output_stream_write(&data->pipe_stream_output, data->first_soa_record, data->first_soa_record_size)))
398                         {
399                             return return_value;
400                         }
401                     }
402                     else
403                     {
404                         return_value = INVALID_STATE_ERROR; // XFR mode should be "ANY"
405                         return return_value;    // invalid status
406                     }
407                 }
408 
409                 break;
410             }
411         }
412 
413 #if DEBUG_XFR_INPUT_STREAM
414         log_debug("xfr_input_stream: >%u %{recordwire}", data->record_index, record);
415 #endif
416 
417         if(FAIL(return_value = output_stream_write(&data->pipe_stream_output, record, record_len)))
418         {
419             data->eos = TRUE;
420 
421             break;
422         }
423 
424         if(return_value != (s32)record_len)
425         {
426             return UNEXPECTED_EOF;
427         }
428 
429         data->record_index++;
430     }
431 
432     return return_value;
433 }
434 
435 static ya_result
xfr_input_stream_fill(input_stream * is,u32 len)436 xfr_input_stream_fill(input_stream *is, u32 len)
437 {
438     xfr_input_stream_data *data = (xfr_input_stream_data*)is->data;
439     input_stream *source_stream = &data->source_stream;
440     message_data *mesg = data->message;
441 #if DNSCORE_HAS_TSIG_SUPPORT
442     const tsig_item *tsig = message_tsig_get_key(mesg);
443 #endif
444     packet_unpack_reader_data *pr = &data->reader;
445 
446     if(FAIL(data->last_error))
447     {
448         return data->last_error;
449     }
450 
451     ya_result ret = SUCCESS;
452 
453     while(pipe_stream_read_available(&data->pipe_stream_input) < (s32)len)
454     {
455         /* read the packet and write on the output (so it can be read back on the input) */
456 
457         if(FAIL(ret = xfr_input_stream_read_packet(data)))
458         {
459             break;
460         }
461 
462         if(data->eos)
463         {
464             break;
465         }
466 
467         if(data->ancount > 0)
468         {
469             break;
470         }
471 
472         /* next TCP chunk */
473 
474 #if DEBUG
475         message_debug_trash_buffer(mesg);
476 #endif
477 
478         u16 tcplen;
479 
480         ret = input_stream_read_nu16(source_stream, &tcplen); /* this is wrong ... */
481 
482         if(ret != 2)
483         {
484 #if DEBUG
485             log_debug("xfr_input_stream_read: next message is %ld bytes long", ret);
486 #endif
487             break;
488         }
489 
490         if(tcplen == 0)
491         {
492             ret = UNEXPECTED_EOF;
493             break;
494         }
495 
496         if(FAIL(ret = input_stream_read_fully(source_stream, message_get_buffer(mesg), tcplen)))
497         {
498             break;
499         }
500 
501         message_set_size(mesg, ret);
502 
503 #if DEBUG_XFR_INPUT_STREAM
504         LOGGER_EARLY_CULL_PREFIX(MSG_INFO) message_log(MODULE_MSG_HANDLE, MSG_INFO, mesg);
505 #endif
506 
507 
508 #if DEBUG
509         memset(&message_get_buffer(mesg)[tcplen], 0xdd, DNSPACKET_MAX_LENGTH + 1 - tcplen);
510 #endif
511         /*
512          * Check the headers
513          */
514 
515         const u64 *h64 = (u64*)message_get_buffer(mesg);
516         const u64 m64 = data->next_hdr_mask; // AXFR_NEXT_MESSAGE_HEADER_MASK;
517         const u64 r64 = data->next_hdr_result; // AXFR_NEXT_MESSAGE_HEADER_RESULT;
518 
519         if(((*h64&m64) != r64) || (message_get_authority_count_ne(mesg) != 0))
520         {
521             u8 code = message_get_rcode(mesg);
522 
523             if(code != 0)
524             {
525                 ret = MAKE_DNSMSG_ERROR(code);
526             }
527             else
528             {
529                 ret = UNPROCESSABLE_MESSAGE;
530             }
531 
532             break;
533         }
534 #if DNSCORE_HAS_TSIG_SUPPORT
535         if((data->last_message_had_tsig = (tsig != NULL)))
536         {
537             /* verify the TSIG
538              *
539              * AR > 0
540              * skip ALL the records until the last AR
541              * it MUST be a TSIG
542              * It's the first TSIG answering to our query
543              * verify it
544              *
545              */
546 
547             message_tsig_clear_key(mesg);
548 
549             if(FAIL(ret = tsig_message_extract(mesg)))
550             {
551                 break;
552             }
553 
554             if((ret == 1) && (message_tsig_get_key(mesg) != tsig))
555             {
556                 /* This is not the one we started with */
557 
558                 log_debug("xfr_input_stream: signature key does not match");
559 
560                 ret = TSIG_BADSIG;
561                 break;
562             }
563 
564             if(FAIL(ret = tsig_verify_tcp_next_message(mesg)))
565             {
566                 break;
567             }
568         }
569 #endif
570         message_header *header = message_get_header(mesg);
571 
572         data->ancount = ntohs(header->ancount);
573 
574         packet_reader_init_from_message_at(pr, mesg, DNS_HEADER_LENGTH);
575 
576         u16 n = ntohs(header->qdcount);
577 
578         while(n > 0)
579         {
580             if(FAIL(ret = packet_reader_skip_fqdn(pr))) // this is the domain already used for this query
581             {
582                 break;
583             }
584 
585             if(FAIL(ret = packet_reader_skip(pr, 4)))
586             {
587                 break;
588             }
589 
590             n--;
591         }
592     } // for(;;) /* process all TCP chunks */
593 
594     return ret;
595 }
596 
597 static ya_result
xfr_input_stream_read(input_stream * is,void * buffer_,u32 len)598 xfr_input_stream_read(input_stream *is, void *buffer_, u32 len)
599 {
600     xfr_input_stream_data *data = (xfr_input_stream_data*)is->data;
601     message_data *mesg = data->message;
602 #if DNSCORE_HAS_TSIG_SUPPORT
603     const tsig_item *tsig = message_tsig_get_key(mesg);
604 #endif
605 
606     if(FAIL(data->last_error))
607     {
608         return data->last_error;
609     }
610 
611     u8 *buffer = (u8*)buffer_;
612 
613     ya_result return_value = xfr_input_stream_fill(is, len);
614 
615     /* while there is not enough bytes on the input */
616 
617     if(ISOK(return_value))
618     {
619         if((return_value = pipe_stream_read_available(&data->pipe_stream_input)) > 0) // never fails
620         {
621             if(FAIL(return_value = input_stream_read(&data->pipe_stream_input, buffer, len)))
622             {
623 #if DNSCORE_HAS_TSIG_SUPPORT
624                 if(data->need_cleanup_tsig)
625                 {
626                     tsig_verify_tcp_last_message(mesg);
627                     data->need_cleanup_tsig = FALSE;
628                 }
629 #endif
630             }
631         }
632         else
633         {
634             // here, return_value == 0
635 #if DNSCORE_HAS_TSIG_SUPPORT
636             if(tsig != NULL)
637             {
638                 tsig_verify_tcp_last_message(mesg);
639                 data->need_cleanup_tsig = FALSE;
640 
641                 if(!data->last_message_had_tsig)
642                 {
643                     /*
644                      * The stream didn't end with a TSIG
645                      * It's bad.
646                      *
647                      */
648 
649                     log_err("xfr_input_stream: TSIG enabled answer didn't ended with a signed packet");
650 
651                     return_value = TSIG_BADSIG;
652                 }
653             }
654 #endif
655         }
656     }
657     else
658     {
659 #if DNSCORE_HAS_TSIG_SUPPORT
660         // cleanup
661         tsig_verify_tcp_last_message(mesg);
662         data->need_cleanup_tsig = FALSE;
663 #endif
664     }
665 
666     data->last_error = return_value;
667 
668     return return_value;
669 }
670 
671 static ya_result
xfr_input_stream_skip(input_stream * is,u32 len)672 xfr_input_stream_skip(input_stream *is, u32 len)
673 {
674     /*
675      * The reader is too complicated to implement a skip, so skip is a wrapped read
676      */
677 
678     u32 remaining = len;
679     ya_result return_value = SUCCESS;
680 
681     u8 buffer[512];
682 
683     while(remaining > 0)
684     {
685         u32 n = MIN(remaining, sizeof(buffer));
686 
687         return_value = xfr_input_stream_read(is, buffer, n);
688 
689         if(return_value <= 0) /* FAIL or EOF */
690         {
691             break;
692         }
693 
694         remaining -= return_value;
695     }
696 
697     if(len != remaining)
698     {
699         return_value = len - remaining;
700     }
701 
702     return return_value;
703 }
704 
705 static void
xfr_input_stream_close(input_stream * is)706 xfr_input_stream_close(input_stream *is)
707 {
708     xfr_input_stream_data *data = (xfr_input_stream_data*)is->data;
709 
710 #if DNSCORE_HAS_TSIG_SUPPORT
711     if(data->need_cleanup_tsig)
712     {
713         message_clear_hmac(data->message);
714 
715         if(ISOK(data->last_error))
716         {
717 #if DEBUG
718             log_warn("xfr: %{dnsname}: TSIG has not been cleared (DEBUG)", data->origin);
719 #else
720             log_debug("xfr: %{dnsname}: TSIG has not been cleared (%r)", data->origin, data->last_error);
721 #endif
722         }
723         data->need_cleanup_tsig = FALSE;
724     }
725 #endif
726 
727 #if DEBUG_XFR_INPUT_STREAM
728     log_debug("xfr_input_stream: %{dnsname}: close, last serial is %i //////////////////////////////", data->origin, data->last_serial);
729 #endif
730 
731     pool_release(&xfr_pool, data->pool);
732 
733     output_stream_close(&data->pipe_stream_output);
734     input_stream_close(&data->pipe_stream_input);
735     free(data->first_soa_record);
736 
737     if(data->owns_message)
738     {
739         message_free(data->message);
740     }
741 
742     if(data->owns_input_stream)
743     {
744         input_stream_close(&data->source_stream);
745         output_stream_close(&data->source_output_stream);
746     }
747 
748 #if DEBUG
749     memset(data, 0xfe, sizeof(xfr_input_stream_data));
750 #endif
751 
752     ZFREE(data, xfr_input_stream_data); // used to be leaked ?
753 
754     input_stream_set_void(is);
755 }
756 
757 static const input_stream_vtbl xfr_input_stream_vtbl =
758 {
759     xfr_input_stream_read,
760     xfr_input_stream_skip,
761     xfr_input_stream_close,
762     "xfr_input_stream",
763 };
764 
765 /**
766  *
767  * @param is the input stream with the AXFR or IXFR, wire format
768  * @param flags mostly XFR_ALLOW_AXFR or XFR_ALLOW_IXFR
769  * @param origin the domain of the zone
770  * @param base_data_path the folder where to put the journal (or journal hash directories and journal)
771  * @param current_serial the serial currently available
772  * @param loaded_serial a pointer to get the serial available after loading
773  * @param message the message that led to this download
774  *
775  * @return an error code, TYPE_AXFR, TYPE_IXFR, TYPE_NONE
776  */
777 
778 ya_result
xfr_input_stream_init(input_stream * filtering_stream,const u8 * origin,input_stream * xfr_source_stream,message_data * mesg,u32 current_serial,xfr_copy_flags flags)779 xfr_input_stream_init(input_stream* filtering_stream, const u8 *origin, input_stream *xfr_source_stream, message_data *mesg, u32 current_serial, xfr_copy_flags flags)
780 {
781     yassert(filtering_stream != NULL && origin != NULL && xfr_source_stream != NULL && mesg != NULL);
782 
783     mutex_lock(&xfr_pool_init_mtx);
784     if(!xfr_pool_initialised)
785     {
786         xfr_pool_initialised = TRUE;
787         pool_init(&xfr_pool, xfr_pool_alloc, xfr_pool_free, NULL, "xfr stream data pool");
788     }
789     mutex_unlock(&xfr_pool_init_mtx);
790 
791     input_stream *is = xfr_source_stream;
792 
793     packet_unpack_reader_data pr;
794     u8 *buffer;
795     u8 *record;
796     u8 *ptr;
797     u8 *pool = NULL;   // 128KB
798 #if DNSCORE_HAS_TSIG_SUPPORT
799     const tsig_item *tsig;
800 #endif
801     ya_result record_len;
802     ya_result return_value;
803     u32 origin_len;
804     u32 last_serial = 0;
805 
806     u16 tcplen;
807     u16 qtype;
808     u16 qclass;
809 
810     u16 old_mac_size;
811 
812     bool last_message_had_tsig;
813     bool need_cleanup_tsig = FALSE;
814 
815 #if DNSCORE_HAS_TSIG_SUPPORT
816     u8 old_mac[64];
817 #endif
818 
819 #if DEBUG_XFR_INPUT_STREAM
820     log_debug("xfr_input_stream: %{dnsname}: init, current serial is %i //////////////////////////////", origin, current_serial);
821 #endif
822 
823     /*
824      * ensure the stream will be unusable if the initialisation fails
825      */
826 
827     input_stream_set_sink(filtering_stream);
828 
829     /*
830      * Start by reading the first packet, and determine if it's an AXFR or an IXFR (for the name)
831      * note: it's read and converted to the host endianness
832      */
833 
834     if(!is_fd_input_stream(is))
835     {
836         // expected file input stream
837         return INVALID_ARGUMENT_ERROR;
838     }
839 
840     //buffer_input_stream_init(is, is, 4096);
841 
842     /* TCP length */
843 
844     if(FAIL(return_value = input_stream_read_nu16(is, &tcplen)))
845     {
846         return return_value;
847     }
848 
849     if(return_value != 2)
850     {
851         return UNEXPECTED_EOF;
852     }
853 
854     /* if the length is not enough, return the most appropriate error code */
855 
856     origin_len = dnsname_len(origin);
857 
858     if(tcplen < DNS_HEADER_LENGTH + origin_len + 4)
859     {
860         return_value = UNEXPECTED_EOF;
861 
862         if(tcplen >= DNS_HEADER_LENGTH)
863         {
864             u8 tmp_hdr[DNS_HEADER_LENGTH];
865 
866             if(ISOK(return_value = input_stream_read_fully(is, tmp_hdr, DNS_HEADER_LENGTH)))
867             {
868                 return_value = MAKE_DNSMSG_ERROR(MESSAGE_RCODE(tmp_hdr));
869             }
870         }
871 
872         return return_value;
873     }
874 
875     pool = pool_alloc(&xfr_pool);
876 
877     /* read the whole message */
878 
879     buffer = message_get_buffer(mesg);
880     record = pool; // no persistence required
881 
882     if(FAIL(return_value = input_stream_read_fully(is, buffer, tcplen)))
883     {
884         pool_release(&xfr_pool, pool);
885 
886         return return_value;
887     }
888 
889     message_set_size(mesg, return_value);
890 
891 #if DEBUG_XFR_INPUT_STREAM
892     LOGGER_EARLY_CULL_PREFIX(MSG_INFO) message_log(MODULE_MSG_HANDLE, MSG_INFO, mesg);
893 #endif
894 
895     /* check the message makes sense */
896 
897     bool axfr_strict_authority = (flags & XFR_LOOSE_AUTHORITY) == 0;
898 
899     const u64 *h64 = (u64*)buffer;
900     u64 m64 = axfr_strict_authority ? AXFR_MESSAGE_HEADER_MASK : AXFR_MESSAGE_LENIENT_HEADER_MASK;
901     u64 r64 = axfr_strict_authority ? AXFR_MESSAGE_HEADER_RESULT : AXFR_MESSAGE_LENIENT_HEADER_RESULT;
902 
903     if(((*h64&m64) != r64) || (message_get_authority_count_ne(mesg) != 0))
904     {
905         u8 code = message_get_rcode(mesg);
906 
907         if(code != 0)
908         {
909             return_value = MAKE_DNSMSG_ERROR(code);
910         }
911         else
912         {
913             return_value = UNPROCESSABLE_MESSAGE;
914         }
915 
916         pool_release(&xfr_pool, pool);
917 
918         return return_value;
919     }
920 
921     if(message_get_rcode(mesg) != RCODE_NOERROR)
922     {
923         pool_release(&xfr_pool, pool);
924         return MAKE_DNSMSG_ERROR(message_get_rcode(mesg));
925     }
926 
927     packet_reader_init_from_message(&pr, mesg);
928 
929     if(FAIL(packet_reader_read_fqdn(&pr, record, RDATA_MAX_LENGTH + 1)))
930     {
931         pool_release(&xfr_pool, pool);
932         return INVALID_PROTOCOL;
933     }
934 
935     if(!dnsname_equals(record, origin))
936     {
937         pool_release(&xfr_pool, pool);
938 
939         return INVALID_PROTOCOL;
940     }
941 
942     if(FAIL(return_value = packet_reader_read_u16(&pr, &qtype)))
943     {
944         pool_release(&xfr_pool, pool);
945 
946         return return_value;
947     }
948 
949     if(return_value != 2)
950     {
951         pool_release(&xfr_pool, pool);
952 
953         return UNEXPECTED_EOF;
954     }
955 
956     /*
957      * check that we are allowed to process this particular kind of transfer
958      * note : this does not determine what is REALLY begin transferred
959      */
960 
961     switch(qtype)
962     {
963         case TYPE_AXFR:
964         {
965             if((flags & XFR_ALLOW_AXFR) == 0)
966             {
967                 pool_release(&xfr_pool, pool);
968 
969                 return INVALID_PROTOCOL;
970             }
971             break;
972         }
973         case TYPE_IXFR:
974         {
975             if((flags & XFR_ALLOW_IXFR) == 0)
976             {
977                 pool_release(&xfr_pool, pool);
978 
979                 return INVALID_PROTOCOL;
980             }
981             break;
982         }
983         default:
984         {
985             pool_release(&xfr_pool, pool);
986 
987             return INVALID_PROTOCOL;
988         }
989     }
990 
991     if(FAIL(return_value = packet_reader_read_u16(&pr, &qclass)))
992     {
993         pool_release(&xfr_pool, pool);
994 
995         return return_value;
996     }
997 
998     if(qclass != CLASS_IN)
999     {
1000         // wrong answer
1001 
1002         pool_release(&xfr_pool, pool);
1003 
1004         return INVALID_PROTOCOL;
1005     }
1006 
1007     /* check for TSIG and verify */
1008 
1009     u16 ancount = ntohs(MESSAGE_AN(buffer));
1010 
1011 #if DNSCORE_HAS_TSIG_SUPPORT
1012     if((last_message_had_tsig = ((tsig = message_tsig_get_key(mesg)) != NULL)))
1013     {
1014         /* verify the TSIG
1015          *
1016          * AR > 0
1017          * skip ALL the records until the last AR
1018          * it MUST be a TSIG
1019          * It's the first TSIG answering to our query
1020          * verify it
1021          *
1022          */
1023 
1024         message_tsig_clear_key(mesg);
1025 
1026         old_mac_size = message_tsig_mac_get_size(mesg);
1027         message_tsig_mac_copy(mesg, old_mac);
1028 
1029         if(FAIL(return_value = tsig_message_extract(mesg)))
1030         {
1031             log_debug("xfr_input_stream: error extracting the signature");
1032 
1033             pool_release(&xfr_pool, pool);
1034 
1035             return return_value;
1036         }
1037 
1038         if(return_value == 0)
1039         {
1040             log_debug("xfr_input_stream: no signature when one was requested");
1041 
1042             pool_release(&xfr_pool, pool);
1043 
1044             return TSIG_BADSIG; /* no signature, when one was requested, is a bad signature */
1045         }
1046 
1047         if(tsig != message_tsig_get_key(mesg))
1048         {
1049             /* This is not the one we started with */
1050 
1051             log_debug("xfr_input_stream: signature key does not match");
1052 
1053             pool_release(&xfr_pool, pool);
1054 
1055             return TSIG_BADSIG;
1056         }
1057 
1058         /// check that the tsig in the message matches theh one that was sent
1059 
1060         if(FAIL(return_value = tsig_verify_tcp_first_message(mesg, old_mac, old_mac_size)))
1061         {
1062             pool_release(&xfr_pool, pool);
1063 
1064             return return_value;
1065         }
1066 
1067         pr.packet_size = message_get_size(mesg);
1068 
1069         need_cleanup_tsig = TRUE;
1070     }
1071 #endif
1072 
1073     log_debug("xfr_input_stream: expecting %5d answer records", ancount);
1074 
1075     /*
1076      * read the SOA (it MUST be an SOA)
1077      */
1078 
1079     if(FAIL(record_len = packet_reader_read_record(&pr, record, RDATA_MAX_LENGTH + 1)))
1080     {
1081         pool_release(&xfr_pool, pool);
1082 
1083         return record_len;
1084     }
1085 
1086     if(!dnsname_equals(record, origin))
1087     {
1088         pool_release(&xfr_pool, pool);
1089 
1090         return INVALID_PROTOCOL;
1091     }
1092 
1093     ptr = &record[origin_len];
1094 
1095     if(GET_U16_AT(*ptr) != TYPE_SOA)
1096     {
1097         pool_release(&xfr_pool, pool);
1098 
1099         return INVALID_PROTOCOL;
1100     }
1101 
1102     ptr += 8; /* type class ttl */
1103 
1104     u16 rdata_size = ntohs(GET_U16_AT(*ptr));
1105 
1106     if(rdata_size < 22)
1107     {
1108         pool_release(&xfr_pool, pool);
1109 
1110         return INVALID_PROTOCOL;
1111     }
1112 
1113     rdata_size -= 16;
1114 
1115     ptr += 2; /* rdata size */
1116 
1117     s32 len = dnsname_len(ptr);
1118 
1119     if(len >= rdata_size)
1120     {
1121         pool_release(&xfr_pool, pool);
1122 
1123         return INVALID_PROTOCOL;
1124     }
1125     rdata_size -= len;
1126     ptr += len;
1127 
1128     len = dnsname_len(ptr);
1129     if(len >= rdata_size)
1130     {
1131         pool_release(&xfr_pool, pool);
1132 
1133         return INVALID_PROTOCOL;
1134     }
1135     rdata_size -= len;
1136 
1137     if(rdata_size != 4)
1138     {
1139         pool_release(&xfr_pool, pool);
1140 
1141         return INVALID_PROTOCOL;
1142     }
1143 
1144     ptr += len;
1145 
1146     // if the serial of the SOA is the same one as we know, then there is no
1147     // need to download the zone
1148 
1149     last_serial = ntohl(GET_U32_AT(ptr[0]));
1150 
1151     if(last_serial == current_serial)
1152     {
1153         pool_release(&xfr_pool, pool);
1154 
1155         return ZONE_ALREADY_UP_TO_DATE;
1156     }
1157 
1158     u32 last_refresh = ntohl(GET_U32_AT(ptr[4]));
1159     u32 last_retry = ntohl(GET_U32_AT(ptr[8]));
1160     u32 last_expire = ntohl(GET_U32_AT(ptr[12]));
1161     u32 last_nttl = ntohl(GET_U32_AT(ptr[16]));
1162 
1163     xfr_input_stream_data *data;
1164     ZALLOC_OBJECT_OR_DIE( data, xfr_input_stream_data, XFRISDTA_TAG);
1165     ZEROMEMORY(data, sizeof(xfr_input_stream_data));
1166 
1167     /*
1168      * We have got the first SOA
1169      * Next time we find this SOA (second next time for IXFR) the stream, it will be the end of the stream
1170      */
1171 
1172     /*
1173      * The stream can be AXFR or IXFR.
1174      * The only way to know this is to look at the records, maybe on many packets.
1175      * If there are two SOA (different serial numbers) for the start, then it's an IXFR, else it's an AXFR.
1176      *
1177      * OPEN A PIPE STREAM "XFRs"
1178      *
1179      * Save the first SOA
1180      */
1181 
1182     MALLOC_OR_DIE(u8*, data->first_soa_record, record_len, XFRISSOA_TAG);
1183     MEMCOPY(data->first_soa_record, record, record_len);
1184     data->first_soa_record_size = record_len;
1185 
1186     filtering_stream->vtbl = &xfr_input_stream_vtbl;
1187     filtering_stream->data = data;
1188 
1189     u32 pipe_buffer_size = 0x10000;
1190 
1191     pipe_stream_init(&data->pipe_stream_output, &data->pipe_stream_input, pipe_buffer_size);
1192     MEMCOPY(&data->reader, &pr, sizeof(packet_unpack_reader_data));
1193 
1194     data->origin = origin;
1195     data->message = mesg;
1196 
1197     data->pool = pool;
1198 
1199     data->ancount = ancount - 1;
1200     data->record_index++;
1201     data->last_serial = last_serial;
1202     data->last_refresh = last_refresh;
1203     data->last_retry = last_retry;
1204     data->last_expire = last_expire;
1205     data->last_nttl = last_nttl;
1206 
1207     if(axfr_strict_authority)
1208     {
1209         data->mesg_hdr_mask = AXFR_MESSAGE_HEADER_MASK;
1210         data->mesg_hdr_result = AXFR_MESSAGE_HEADER_RESULT;
1211         data->next_hdr_mask = AXFR_NEXT_MESSAGE_HEADER_MASK;
1212         data->next_hdr_result = AXFR_NEXT_MESSAGE_HEADER_RESULT;
1213     }
1214     else
1215     {
1216         data->mesg_hdr_mask = AXFR_MESSAGE_LENIENT_HEADER_MASK;
1217         data->mesg_hdr_result = AXFR_MESSAGE_LENIENT_HEADER_RESULT;
1218         data->next_hdr_mask = AXFR_NEXT_MESSAGE_LENIENT_HEADER_MASK;
1219         data->next_hdr_result = AXFR_NEXT_MESSAGE_LENIENT_HEADER_RESULT;
1220     }
1221 
1222     data->xfr_mode = TYPE_ANY;
1223     data->ixfr_mark = FALSE;
1224     data->last_message_had_tsig = last_message_had_tsig;
1225     data->source_stream = *is;
1226     data->need_cleanup_tsig = need_cleanup_tsig;
1227     data->owns_message = FALSE;
1228     data->owns_input_stream = FALSE;
1229 
1230     /*
1231      * Then we read all records for all packets
1232      * If we find an SOA ...
1233      *      AXFR: it has to be the last serial and it is the end of the stream.
1234      *      IXFR: if it's not the last serial it has to go from step to step
1235      *            AND once we have reached the "last serial" once, the next hit is the end of the stream.
1236      */
1237 
1238     data->eos = FALSE;
1239 
1240     /*
1241      * In order to know what the type is, read the first packet.
1242      */
1243 
1244     if(ISOK(return_value = xfr_input_stream_fill(filtering_stream, pipe_buffer_size / 2)))
1245     {
1246         if(ISOK(return_value = xfr_input_stream_read_packet(data)))
1247         {
1248             return return_value;
1249         }
1250     }
1251 
1252     xfr_input_stream_close(filtering_stream);
1253 
1254     return return_value;
1255 }
1256 
1257 ya_result
xfr_input_stream_init_with_query(input_stream * filtering_stream,const host_address * server,const u8 * origin,s32 ttl,const u8 * soa_rdata,int soa_rdata_size,xfr_copy_flags flags)1258 xfr_input_stream_init_with_query(input_stream* filtering_stream, const host_address *server, const u8 *origin, s32 ttl, const u8 *soa_rdata, int soa_rdata_size, xfr_copy_flags flags)
1259 {
1260     input_stream is;
1261     output_stream os;
1262     random_ctx rndctx = thread_pool_get_random_ctx();
1263     message_data *mesg = message_new_instance();
1264     ya_result ret;
1265     u32 serial;
1266     u16 id;
1267 
1268     if(FAIL(ret = rr_soa_get_serial(soa_rdata, soa_rdata_size, &serial)))
1269     {
1270         return ret;
1271     }
1272 
1273      id = (u16)random_next(rndctx);
1274 
1275     message_make_ixfr_query(mesg, id, origin, ttl, soa_rdata_size, soa_rdata);
1276 
1277 #if DNSCORE_HAS_TSIG_SUPPORT
1278     if(server->tsig != NULL)
1279     {
1280         if(FAIL(ret = message_sign_query(mesg, server->tsig)))
1281         {
1282             message_free(mesg);
1283             return ret;
1284         }
1285     }
1286 #endif
1287 
1288     /*
1289      * connect & send
1290      */
1291 
1292     while(FAIL(ret = tcp_input_output_stream_connect_host_address(server, &is, &os, 3)))
1293     {
1294         if(ret != MAKE_ERRNO_ERROR(EINTR))
1295         {
1296             message_free(mesg);
1297             return ret;
1298         }
1299     }
1300 
1301     if(FAIL(ret = message_write_tcp(mesg, &os)))
1302     {
1303         input_stream_close(&is);
1304         output_stream_close(&os);
1305 
1306         message_free(mesg);
1307 
1308         return ret;
1309     }
1310 
1311     output_stream_flush(&os);
1312 
1313     int fd = fd_input_stream_get_filedescriptor(&is);
1314 
1315     tcp_set_sendtimeout(fd, 10, 0);
1316     tcp_set_recvtimeout(fd, 10, 0);
1317 
1318     if(FAIL(xfr_input_stream_init(filtering_stream, origin, &is, mesg, serial, flags)))
1319     {
1320         input_stream_close(&is);
1321         output_stream_close(&os);
1322 
1323         message_free(mesg);
1324 
1325         return ret;
1326     }
1327 
1328     xfr_input_stream_data *data = (xfr_input_stream_data*)filtering_stream->data;
1329     data->owns_message = TRUE;
1330     data->owns_input_stream = TRUE;
1331     data->source_output_stream = os;
1332 
1333     return SUCCESS;
1334 }
1335 
1336 ya_result
xfr_input_stream_get_type(input_stream * in_xfr_input_stream)1337 xfr_input_stream_get_type(input_stream *in_xfr_input_stream)
1338 {
1339     xfr_input_stream_data *data = (xfr_input_stream_data*)in_xfr_input_stream->data;
1340     return data->xfr_mode;
1341 }
1342 
1343 const u8*
xfr_input_stream_get_origin(input_stream * in_xfr_input_stream)1344 xfr_input_stream_get_origin(input_stream *in_xfr_input_stream)
1345 {
1346     xfr_input_stream_data *data = (xfr_input_stream_data*)in_xfr_input_stream->data;
1347     return data->origin;
1348 }
1349 
1350 u32
xfr_input_stream_get_serial(input_stream * in_xfr_input_stream)1351 xfr_input_stream_get_serial(input_stream *in_xfr_input_stream)
1352 {
1353     xfr_input_stream_data *data = (xfr_input_stream_data*)in_xfr_input_stream->data;
1354     return data->last_serial;
1355 }
1356 
1357 u32
xfr_input_stream_get_refresh(input_stream * in_xfr_input_stream)1358 xfr_input_stream_get_refresh(input_stream *in_xfr_input_stream)
1359 {
1360     xfr_input_stream_data *data = (xfr_input_stream_data*)in_xfr_input_stream->data;
1361     return data->last_refresh;
1362 }
1363 
1364 void
xfr_input_stream_finalize()1365 xfr_input_stream_finalize()
1366 {
1367     mutex_lock(&xfr_pool_init_mtx);
1368     if(xfr_pool_initialised)
1369     {
1370         pool_finalize(&xfr_pool);
1371         xfr_pool_initialised = FALSE;
1372     }
1373     mutex_unlock(&xfr_pool_init_mtx);
1374 }
1375 
1376 /** @} */
1377