1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2012 Apple Computer, Inc. All rights reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 // ***************************************************************************
19 // DNSSECSupport.c: Platform specific support for DNSSEC like fetching root
20 // trust anchor and dnssec probes etc.
21 // ***************************************************************************
23 #include "mDNSEmbeddedAPI.h"
24 #include "DNSCommon.h" // For mDNS_Lock, mDNS_Random
26 #include "DNSSECSupport.h"
28 #include <CommonCrypto/CommonDigest.h> // For Hash algorithms SHA1 etc.
30 // Following are needed for fetching the root trust anchor dynamically
31 #include <CoreFoundation/CoreFoundation.h>
32 #include <libxml2/libxml/parser.h>
33 #include <libxml2/libxml/tree.h>
34 #include <libxml2/libxml/xmlmemory.h>
38 #define ROOT_TA_UPDATE_INTERVAL (30 * 24 * 3600) // seconds
40 // After 100 days, the test anchors are not valid. Just an arbitrary number
41 // to configure validUntil.
42 #define TEST_TA_EXPIRE_INTERVAL (100 * 24 * 4600)
44 // When we can't fetch the root TA due to network errors etc., we start off a timer
45 // to fire at 60 seconds and then keep doubling it till we fetch it
46 #define InitialTAFetchInterval 60
49 DNSQuestion DNSSECProbeQuestion
;
52 mDNSlocal
int RegisterNotification(mDNS
*const m
, unsigned int interval
);
54 mDNSlocal
void LinkTrustAnchor(mDNS
*const m
, TrustAnchor
*ta
)
59 TrustAnchor
**t
= &m
->TrustAnchors
;
68 for (i
= 0; i
< ta
->digestLen
; i
++)
70 length
+= mDNS_snprintf(buffer
+length
, sizeof(buffer
)-1-length
, "%x", p
[i
]);
72 LogInfo("LinkTrustAnchor: Zone %##s, keytag %d, alg %d, digestType %d, digestLen %d, digest %s", ta
->zone
.c
, ta
->rds
.keyTag
,
73 ta
->rds
.alg
, ta
->rds
.digestType
, ta
->digestLen
, buffer
);
76 mDNSlocal
void DelTrustAnchor(mDNS
*const m
, const domainname
*zone
)
78 TrustAnchor
**ta
= &m
->TrustAnchors
;
81 while (*ta
&& !SameDomainName(&(*ta
)->zone
, zone
))
84 // First time, we won't find the TrustAnchor in the list as it has
90 *ta
= (*ta
)->next
; // Cut this record from the list
93 mDNSPlatformMemFree(tmp
->rds
.digest
);
94 mDNSPlatformMemFree(tmp
);
97 mDNSlocal
void AddTrustAnchor(mDNS
*const m
, const domainname
*zone
, mDNSu16 keytag
, mDNSu8 alg
, mDNSu8 digestType
, int diglen
,
100 TrustAnchor
*ta
, *tmp
;
101 mDNSu32 t
= (mDNSu32
) time(NULL
);
103 // Check for duplicates
104 tmp
= m
->TrustAnchors
;
107 if (SameDomainName(zone
, &tmp
->zone
) && tmp
->rds
.keyTag
== keytag
&& tmp
->rds
.alg
== alg
&& tmp
->rds
.digestType
== digestType
&&
108 !memcmp(tmp
->rds
.digest
, digest
, diglen
))
110 LogMsg("AddTrustAnchors: Found a duplicate");
116 ta
= (TrustAnchor
*)mDNSPlatformMemAllocate(sizeof(TrustAnchor
));
119 LogMsg("AddTrustAnchor: malloc failure ta");
122 ta
->rds
.keyTag
= keytag
;
124 ta
->rds
.digestType
= digestType
;
125 ta
->rds
.digest
= digest
;
126 ta
->digestLen
= diglen
;
128 ta
->validUntil
= t
+ TEST_TA_EXPIRE_INTERVAL
;
129 AssignDomainName(&ta
->zone
, zone
);
132 LinkTrustAnchor(m
, ta
);
135 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
136 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
137 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : -1)
139 mDNSlocal mDNSu8
*ConvertDigest(char *digest
, int digestType
, int *diglen
)
146 case SHA1_DIGEST_TYPE
:
147 *diglen
= CC_SHA1_DIGEST_LENGTH
;
149 case SHA256_DIGEST_TYPE
:
150 *diglen
= CC_SHA256_DIGEST_LENGTH
;
153 LogMsg("ConvertDigest: digest type %d not supported", digestType
);
156 dig
= mDNSPlatformMemAllocate(*diglen
);
159 LogMsg("ConvertDigest: malloc failure");
163 for (j
=0,i
=0; i
<*diglen
*2; i
+=2)
166 l
= HexVal(digest
[i
]);
167 h
= HexVal(digest
[i
+1]);
168 if (l
<0 || h
<0) { LogMsg("ConvertDigest: Cannot convert digest"); return NULL
;}
169 dig
[j
++] = (mDNSu8
)((l
<< 4) | h
);
174 // All the children are in a linked list
176 // <TrustAnchor> has two children: <Zone> and <KeyDigest>
177 // <KeyDigest> has four children <KeyTag> <Algorithm> <DigestType> <Digest>
179 // Returns false if failed to parse the element i.e., malformed xml document.
180 // Validity of the actual values itself is done outside the function.
181 mDNSlocal mDNSBool
ParseElementChildren(xmlDocPtr tadoc
, xmlNode
*node
, TrustAnchor
*ta
)
184 xmlChar
*val1
, *val2
, *val
;
185 char *invalid
= NULL
;
187 val
= val1
= val2
= NULL
;
189 for (cur_node
= node
; cur_node
; cur_node
= cur_node
->next
)
194 val
= xmlNodeListGetString(tadoc
, cur_node
->xmlChildrenNode
, 1);
197 LogInfo("ParseElementChildren: NULL value for %s", cur_node
->name
);
200 if (!xmlStrcmp(cur_node
->name
, (const xmlChar
*)"Zone"))
202 // MaeDomainNameFromDNSNameString does not work for "."
203 if (!xmlStrcmp(val
, (const xmlChar
*)"."))
207 else if (!MakeDomainNameFromDNSNameString(&ta
->zone
, (char *)val
))
209 LogMsg("ParseElementChildren: Cannot parse Zone %s", val
);
214 LogInfo("ParseElementChildren: Element %s, value %##s", cur_node
->name
, ta
->zone
.c
);
217 else if (!xmlStrcmp(cur_node
->name
, (const xmlChar
*)"KeyTag"))
219 ta
->rds
.keyTag
= strtol((const char *)val
, &invalid
, 10);
220 if (*invalid
!= '\0')
222 LogMsg("ParseElementChildren: KeyTag invalid character %d", *invalid
);
227 LogInfo("ParseElementChildren: Element %s, value %d", cur_node
->name
, ta
->rds
.keyTag
);
230 else if (!xmlStrcmp(cur_node
->name
, (const xmlChar
*)"Algorithm"))
232 ta
->rds
.alg
= strtol((const char *)val
, &invalid
, 10);
233 if (*invalid
!= '\0')
235 LogMsg("ParseElementChildren: Algorithm invalid character %c", *invalid
);
240 LogInfo("ParseElementChildren: Element %s, value %d", cur_node
->name
, ta
->rds
.alg
);
243 else if (!xmlStrcmp(cur_node
->name
, (const xmlChar
*)"DigestType"))
245 ta
->rds
.digestType
= strtol((const char *)val
, &invalid
, 10);
246 if (*invalid
!= '\0')
248 LogMsg("ParseElementChildren: Algorithm invalid character %c", *invalid
);
253 LogInfo("ParseElementChildren: Element %s, value %d", cur_node
->name
, ta
->rds
.digestType
);
256 else if (!xmlStrcmp(cur_node
->name
, (const xmlChar
*)"Digest"))
259 mDNSu8
*dig
= ConvertDigest((char *)val
, ta
->rds
.digestType
, &diglen
);
262 LogInfo("ParseElementChildren: Element %s, digest %s", cur_node
->name
, val
);
263 ta
->digestLen
= diglen
;
264 ta
->rds
.digest
= dig
;
268 LogMsg("ParseElementChildren: Element %s, NULL digest", cur_node
->name
);
272 else if (!xmlStrcmp(cur_node
->name
, (const xmlChar
*)"KeyDigest"))
275 val1
= xmlGetProp(cur_node
, (const xmlChar
*)"validFrom");
278 char *s
= strptime((const char *)val1
, "%Y-%m-%dT%H:%M:%S", &tm
);
281 LogMsg("ParseElementChildren: Parsing ValidFrom failed %s", val1
);
286 ta
->validFrom
= (mDNSu32
)timegm(&tm
);
289 val2
= xmlGetProp(cur_node
, (const xmlChar
*)"validUntil");
292 char *s
= strptime((const char *)val2
, "%Y-%m-%dT%H:%M:%S", &tm
);
295 LogMsg("ParseElementChildren: Parsing ValidFrom failed %s", val2
);
300 ta
->validUntil
= (mDNSu32
)timegm(&tm
);
305 // If there is no validUntil, set it to the next probing interval
306 mDNSu32 t
= (mDNSu32
) time(NULL
);
307 ta
->validUntil
= t
+ ROOT_TA_UPDATE_INTERVAL
;
309 LogInfo("ParseElementChildren: ValidFrom time %u, validUntil %u", (unsigned)ta
->validFrom
, (unsigned)ta
->validUntil
);
329 mDNSlocal mDNSBool
ValidateTrustAnchor(TrustAnchor
*ta
)
331 time_t currTime
= time(NULL
);
333 // Currently only support trust anchor for root.
334 if (!SameDomainName(&ta
->zone
, (const domainname
*)"\000"))
336 LogInfo("ParseElementChildren: Zone %##s not root", ta
->zone
.c
);
340 switch (ta
->rds
.digestType
)
342 case SHA1_DIGEST_TYPE
:
343 if (ta
->digestLen
!= CC_SHA1_DIGEST_LENGTH
)
345 LogMsg("ValidateTrustAnchor: Invalid digest len %d for SHA1", ta
->digestLen
);
349 case SHA256_DIGEST_TYPE
:
350 if (ta
->digestLen
!= CC_SHA256_DIGEST_LENGTH
)
352 LogMsg("ValidateTrustAnchor: Invalid digest len %d for SHA256", ta
->digestLen
);
357 LogMsg("ValidateTrustAnchor: digest type %d not supported", ta
->rds
.digestType
);
362 LogMsg("ValidateTrustAnchor: digest NULL for %d", ta
->rds
.digestType
);
367 case CRYPTO_RSA_SHA512
:
368 case CRYPTO_RSA_SHA256
:
369 case CRYPTO_RSA_NSEC3_SHA1
:
370 case CRYPTO_RSA_SHA1
:
373 LogMsg("ValidateTrustAnchor: Algorithm %d not supported", ta
->rds
.alg
);
377 if (DNS_SERIAL_LT(currTime
, ta
->validFrom
))
379 LogMsg("ValidateTrustAnchor: Invalid ValidFrom time %u, currtime %u", (unsigned)ta
->validFrom
, (unsigned)currTime
);
382 if (DNS_SERIAL_LT(ta
->validUntil
, currTime
))
384 LogMsg("ValidateTrustAnchor: Invalid ValidUntil time %u, currtime %u", (unsigned)ta
->validUntil
, (unsigned)currTime
);
390 mDNSlocal mDNSBool
ParseElement(xmlDocPtr tadoc
, xmlNode
* a_node
, TrustAnchor
*ta
)
392 xmlNode
*cur_node
= NULL
;
394 for (cur_node
= a_node
; cur_node
; cur_node
= cur_node
->next
)
396 if (cur_node
->type
== XML_ELEMENT_NODE
)
398 // There could be multiple KeyDigests per TrustAnchor. We keep parsing till we
399 // reach the last one or we encounter an error in parsing the document.
400 if (!xmlStrcmp(cur_node
->name
, (const xmlChar
*)"KeyDigest"))
403 mDNSPlatformMemFree(ta
->rds
.digest
);
404 ta
->rds
.digestType
= 0;
407 if (!ParseElementChildren(tadoc
, cur_node
->children
, ta
))
409 if (!ParseElement(tadoc
, cur_node
->children
, ta
))
416 mDNSlocal
void TAComplete(mDNS
*const m
, void *context
)
418 TrustAnchor
*ta
= (TrustAnchor
*)context
;
420 DelTrustAnchor(m
, &ta
->zone
);
421 LinkTrustAnchor(m
, ta
);
424 mDNSlocal
void FetchRootTA(mDNS
*const m
)
426 CFStringRef urlString
= CFSTR("https://data.iana.org/root-anchors/root-anchors.xml");
428 CFStringRef fileRef
= NULL
;
429 const char *xmlFileName
= NULL
;
432 static unsigned int RootTAFetchInterval
= InitialTAFetchInterval
;
436 TrustAnchor
*ta
= (TrustAnchor
*)mDNSPlatformMemAllocate(sizeof(TrustAnchor
));
439 LogMsg("FetchRootTA: TrustAnchor alloc failed");
442 memset(ta
, 0, sizeof(TrustAnchor
));
444 url
= CFURLCreateWithString(NULL
, urlString
, NULL
);
447 LogMsg("FetchRootTA: CFURLCreateWithString error");
448 mDNSPlatformMemFree(ta
);
452 // If we can't fetch the XML file e.g., network problems, trigger a timer. All other failures
453 // should hardly happen in practice for which schedule the normal interval to refetch the TA.
454 if (!CFURLCreateDataAndPropertiesFromResource(kCFAllocatorDefault
, url
, &xmlData
, NULL
, NULL
, NULL
))
456 LogInfo("FetchRootTA: CFURLCreateDataAndPropertiesFromResource error");
458 mDNSPlatformMemFree(ta
);
459 RegisterNotification(m
, RootTAFetchInterval
);
460 RootTAFetchInterval
*= 2 + 1;
464 // get the name of the last component from the url, libxml will use it if
465 // it has to report an error
466 fileRef
= CFURLCopyLastPathComponent(url
);
469 xmlFileName
= CFStringGetCStringPtr(fileRef
, kCFStringEncodingUTF8
);
472 if (!CFStringGetCString(fileRef
, buf
, sizeof(buf
), kCFStringEncodingUTF8
) )
473 strlcpy(buf
, "nofile.xml", sizeof(buf
));
474 xmlFileName
= (const char *)buf
;
478 // Parse the XML and get the CFXMLTree.
479 xmlDocPtr tadoc
= xmlReadMemory((const char*)CFDataGetBytePtr(xmlData
),
480 (int)CFDataGetLength(xmlData
), xmlFileName
, NULL
, 0);
488 LogMsg("FetchRootTA: xmlReadMemory failed");
492 xmlNodePtr root
= xmlDocGetRootElement(tadoc
);
495 LogMsg("FetchRootTA: Cannot get root element");
499 if (ParseElement(tadoc
, root
, ta
) && ValidateTrustAnchor(ta
))
501 // Do the actual addition of TA on the main queue.
502 mDNSPlatformDispatchAsync(m
, ta
, TAComplete
);
507 mDNSPlatformMemFree(ta
->rds
.digest
);
508 mDNSPlatformMemFree(ta
);
513 RegisterNotification(m
, ROOT_TA_UPDATE_INTERVAL
);
514 RootTAFetchInterval
= InitialTAFetchInterval
;
519 #if APPLE_OSX_mDNSResponder && !TARGET_OS_IPHONE
520 mDNSlocal
void DNSSECProbeCallback(mDNS
*const m
, DNSQuestion
*question
, const ResourceRecord
*const answer
, QC_result AddRecord
)
526 if ((m
->timenow
- question
->StopTime
) >= 0)
529 LogDNSSEC("DNSSECProbeCallback: Question %##s (%s) timed out", question
->qname
.c
, DNSTypeName(question
->qtype
));
530 mDNS_StopQuery(m
, question
);
535 // Wait till we get the DNSSEC results. If we get a negative response e.g., no DNS servers, the
536 // question will be restarted by the core and we should have the DNSSEC results eventually.
537 if (AddRecord
!= QC_dnssec
)
539 LogDNSSEC("DNSSECProbeCallback: Question %##s (%s)", question
->qname
.c
, DNSTypeName(question
->qtype
), RRDisplayString(m
, answer
));
543 LogDNSSEC("DNSSECProbeCallback: Question %##s (%s), DNSSEC status %s", question
->qname
.c
, DNSTypeName(question
->qtype
),
544 DNSSECStatusName(question
->ValidationStatus
));
546 mDNS_StopQuery(m
, question
);
549 // Send a DNSSEC probe just for the sake of collecting DNSSEC statistics.
550 mDNSexport
void DNSSECProbe(mDNS
*const m
)
554 if (DNSSECProbeQuestion
.ThisQInterval
!= -1)
557 rand
= mDNSRandom(0x3FFFFFFF) % 100;
558 // Probe 5% of the time
562 mDNS_DropLockBeforeCallback();
563 InitializeQuestion(m
, &DNSSECProbeQuestion
, mDNSInterface_Any
, (const domainname
*)"\003com", kDNSType_DS
, DNSSECProbeCallback
, mDNSNULL
);
564 DNSSECProbeQuestion
.ValidatingResponse
= 0;
565 DNSSECProbeQuestion
.ValidationRequired
= DNSSEC_VALIDATION_SECURE
;
567 BumpDNSSECStats(m
, kStatsActionIncrement
, kStatsTypeProbe
, 1);
568 mDNS_StartQuery(m
, &DNSSECProbeQuestion
);
569 mDNS_ReclaimLockAfterCallback();
571 #endif // APPLE_OSX_mDNSResponder && !TARGET_OS_IPHONE
573 // For now we fetch the root trust anchor and update the local copy
574 mDNSexport
void UpdateTrustAnchors(mDNS
*const m
)
576 // Register for a notification to fire immediately which in turn will update
578 if (RegisterNotification(m
, 1))
580 LogMsg("UpdateTrustAnchors: ERROR!! failed to register for notification");
584 mDNSlocal
int RegisterNotification(mDNS
*const m
, unsigned int interval
)
586 int len
= strlen("com.apple.system.notify.service.timer:+") + 21; // 21 bytes to accomodate the interval
591 // Starting "interval" second from now (+ below indicates relative) register for a notification
592 blen
= mDNS_snprintf(buffer
, sizeof(buffer
), "com.apple.system.notify.service.timer:+%us", interval
);
593 if (blen
>= sizeof(buffer
))
595 LogMsg("RegisterNotification: Buffer too small blen %d, buffer size %d", blen
, sizeof(buffer
));
598 LogInfo("RegisterNotification: buffer %s", buffer
);
601 notify_cancel(m
->notifyToken
);
604 status
= notify_register_dispatch(buffer
, &m
->notifyToken
,
605 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT
, 0),
606 ^(int t
) { (void) t
; FetchRootTA(m
); });
608 if (status
!= NOTIFY_STATUS_OK
)
610 LogMsg("RegisterNotification: notify_register_dispatch failed");
616 mDNSexport mStatus
DNSSECPlatformInit(mDNS
*const m
)
620 m
->TrustAnchors
= mDNSNULL
;
623 // Add a couple of trust anchors for testing purposes.
624 mDNSlocal
const domainname
*testZone
= (const domainname
*)"\007example";
626 char *digest
= "F122E47B5B7D2B6A5CC0A21EADA11D96BB9CC927";
627 mDNSu8
*dig
= ConvertDigest(digest
, 1, &diglen
);
628 AddTrustAnchor(m
, testZone
, 23044, 5, 1, diglen
, dig
);
630 char *digest1
= "D795AE5E1AFB200C6139474199B70EAD3F3484553FD97BE5A43704B8A4791F21";
631 dig
= ConvertDigest(digest1
, 2, &diglen
);
632 AddTrustAnchor(m
, testZone
, 23044, 5, 2, diglen
, dig
);
634 // Add the TA for root zone manually here. We will dynamically fetch the root TA and
635 // update it shortly. If that fails e.g., disconnected from the network, we still
636 // have something to work with.
637 char *digest2
= "49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDDE32F24E8FB5";
638 dig
= ConvertDigest(digest2
, 2, &diglen
);
639 AddTrustAnchor(m
, (const domainname
*)"\000", 19036, 8, 2, diglen
, dig
);
641 #if !TARGET_OS_IPHONE
642 DNSSECProbeQuestion
.ThisQInterval
= -1;
644 return mStatus_NoError
;