public static String resolve(String host, int addrType) { try { Lookup lookup = new Lookup(host, addrType); SimpleResolver resolver = new SimpleResolver("114.114.114.114"); resolver.setTimeout(5); lookup.setResolver(resolver); Record[] result = lookup.run(); if (result == null) return null; List<Record> records = java.util.Arrays.asList(result); java.util.Collections.shuffle(records); for (Record record : records) { if (addrType == Type.A) { return ((ARecord) record).getAddress().getHostAddress(); } else if (addrType == Type.AAAA) { return ((AAAARecord) record).getAddress().getHostAddress(); } } } catch (Exception ex) { return null; } return null; }
public static String reverseDNSLookup(final InetAddress adr) { try { final Name name = ReverseMap.fromAddress(adr); final Lookup lookup = new Lookup(name, Type.PTR); lookup.setResolver(new SimpleResolver()); lookup.setCache(null); final Record[] records = lookup.run(); if (lookup.getResult() == Lookup.SUCCESSFUL) for (final Record record : records) if (record instanceof PTRRecord) { final PTRRecord ptr = (PTRRecord) record; return ptr.getTarget().toString(); } } catch (final Exception e) { } return null; }
/** * Dns lookup more efficient than the INetAddress.getHostName(ip) * * @param hostIp * @return * @throws IOException */ public String dnsLookup(final String hostIp) { try { final Name name = ReverseMap.fromAddress(hostIp); final int type = Type.PTR; final int dclass = DClass.IN; final Record rec = Record.newRecord(name, type, dclass); final Message query = Message.newQuery(rec); final Message response = _resolver.send(query); final Record[] answers = response.getSectionArray(Section.ANSWER); if (answers.length > 0) { String ret = answers[0].rdataToString(); if (ret.endsWith(".")) { ret = ret.substring(0, ret.length() - 1); } return ret; } } catch (final IOException e) { LOGGER.warn("Failed to resolve hostname for " + hostIp, e); } return UNKNOWN_HOST; }
/** * Attempts to resolve an SMTP server address, given the destination e-mail address. * * @param email The e-mail address used for the lookup. * @return An optional, potentially containing */ protected Optional<String> resolve(String email) { Optional<String> domainOptional = extractDomain(email); if (!domainOptional.isPresent()) { return Optional.empty(); } String mailDomain = domainOptional.get(); try { Lookup dnsLookup = new Lookup(mailDomain, Type.MX); List<Record> records = Arrays.asList(dnsLookup.run()); if (records.isEmpty()) { return Optional.empty(); } return chooseBestRecord(records); } catch (TextParseException e) { e.printStackTrace(); } return Optional.empty(); }
@Override public Collection<InetAddress> resolveRemapped(String remappedHost) { // special case for IP literals: return the InetAddress without doing a dnsjava lookup. dnsjava seems to handle ipv4 literals // reasonably well, but does not handle ipv6 literals (with or without [] brackets) correctly. // note this does not work properly for ipv6 literals with a scope identifier, which is a known issue for InetAddresses.isInetAddress(). // (dnsjava also handles the situation incorrectly) if (InetAddresses.isInetAddress(remappedHost)) { return Collections.singletonList(InetAddresses.forString(remappedHost)); } // retrieve IPv4 addresses, then retrieve IPv6 addresses only if no IPv4 addresses are found. the current implementation always uses the // first returned address, so there is no need to look for IPv6 addresses if an IPv4 address is found. Collection<InetAddress> ipv4addresses = resolveHostByType(remappedHost, Type.A); if (!ipv4addresses.isEmpty()) { return ipv4addresses; } else { return resolveHostByType(remappedHost, Type.AAAA); } }
@Test public void testPublishDomainCreate_publishesNameServers() throws Exception { HostResource host1 = persistActiveHost("ns1.example.tld"); HostResource host2 = persistActiveHost("ns2.example.tld"); DomainResource domain = persistActiveDomain("example.tld") .asBuilder() .setNameservers(ImmutableSet.of(Key.create(host1), Key.create(host2))) .build(); persistResource(domain); writer.publishDomain("example.tld"); writer.commit(); verify(mockResolver).send(updateCaptor.capture()); Update update = updateCaptor.getValue(); assertThatUpdatedZoneIs(update, "tld."); assertThatUpdateDeletes(update, "example.tld.", Type.ANY); assertThatUpdateAdds(update, "example.tld.", Type.NS, "ns1.example.tld.", "ns2.example.tld."); assertThatTotalUpdateSetsIs(update, 2); // The delete and NS sets }
@Test public void testPublishAtomic_oneUpdate() throws Exception { HostResource host1 = persistActiveHost("ns.example1.tld"); DomainResource domain1 = persistActiveDomain("example1.tld") .asBuilder() .setNameservers(ImmutableSet.of(Key.create(host1))) .build(); persistResource(domain1); HostResource host2 = persistActiveHost("ns.example2.tld"); DomainResource domain2 = persistActiveDomain("example2.tld") .asBuilder() .setNameservers(ImmutableSet.of(Key.create(host2))) .build(); persistResource(domain2); writer.publishDomain("example1.tld"); writer.publishDomain("example2.tld"); writer.commit(); verify(mockResolver).send(updateCaptor.capture()); Update update = updateCaptor.getValue(); assertThatUpdatedZoneIs(update, "tld."); assertThatUpdateDeletes(update, "example1.tld.", Type.ANY); assertThatUpdateDeletes(update, "example2.tld.", Type.ANY); assertThatUpdateAdds(update, "example1.tld.", Type.NS, "ns.example1.tld."); assertThatUpdateAdds(update, "example2.tld.", Type.NS, "ns.example2.tld."); assertThatTotalUpdateSetsIs(update, 4); // The delete and NS sets for each TLD }
@Test public void testPublishDomainCreate_publishesDelegationSigner() throws Exception { DomainResource domain = persistActiveDomain("example.tld") .asBuilder() .setNameservers(ImmutableSet.of(Key.create(persistActiveHost("ns1.example.tld")))) .setDsData( ImmutableSet.of( DelegationSignerData.create(1, 3, 1, base16().decode("0123456789ABCDEF")))) .build(); persistResource(domain); writer.publishDomain("example.tld"); writer.commit(); verify(mockResolver).send(updateCaptor.capture()); Update update = updateCaptor.getValue(); assertThatUpdatedZoneIs(update, "tld."); assertThatUpdateDeletes(update, "example.tld.", Type.ANY); assertThatUpdateAdds(update, "example.tld.", Type.NS, "ns1.example.tld."); assertThatUpdateAdds(update, "example.tld.", Type.DS, "1 3 1 0123456789ABCDEF"); assertThatTotalUpdateSetsIs(update, 3); // The delete, the NS, and DS sets }
@Test public void testPublishDomainWhenNotActive_removesDnsRecords() throws Exception { DomainResource domain = persistActiveDomain("example.tld") .asBuilder() .addStatusValue(StatusValue.SERVER_HOLD) .setNameservers(ImmutableSet.of(Key.create(persistActiveHost("ns1.example.tld")))) .build(); persistResource(domain); writer.publishDomain("example.tld"); writer.commit(); verify(mockResolver).send(updateCaptor.capture()); Update update = updateCaptor.getValue(); assertThatUpdatedZoneIs(update, "tld."); assertThatUpdateDeletes(update, "example.tld.", Type.ANY); assertThatTotalUpdateSetsIs(update, 1); // Just the delete set }
@Test public void testPublishHostDelete_removesGlueRecords() throws Exception { persistDeletedHost("ns1.example.tld", clock.nowUtc().minusDays(1)); persistResource( persistActiveDomain("example.tld") .asBuilder() .setNameservers(ImmutableSet.of(Key.create(persistActiveHost("ns1.example.com")))) .build()); writer.publishHost("ns1.example.tld"); writer.commit(); verify(mockResolver).send(updateCaptor.capture()); Update update = updateCaptor.getValue(); assertThatUpdatedZoneIs(update, "tld."); assertThatUpdateDeletes(update, "example.tld.", Type.ANY); assertThatUpdateDeletes(update, "ns1.example.tld.", Type.ANY); assertThatUpdateAdds(update, "example.tld.", Type.NS, "ns1.example.com."); assertThatTotalUpdateSetsIs(update, 3); }
@Test public void testSentMessageTooLongThrowsException() throws Exception { Update oversize = new Update(Name.fromString("tld", Name.root)); for (int i = 0; i < 2000; i++) { oversize.add( ARecord.newRecord( Name.fromString("test-extremely-long-name-" + i + ".tld", Name.root), Type.A, DClass.IN)); } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); when(mockSocket.getOutputStream()).thenReturn(outputStream); IllegalArgumentException thrown = expectThrows(IllegalArgumentException.class, () -> resolver.send(oversize)); assertThat(thrown).hasMessageThat().contains("message larger than maximum"); }
@Override public List<SRVRecord> lookupSRVRecords(String name) throws TextParseException { List<SRVRecord> res = new ArrayList<SRVRecord>(); Lookup lookup = new Lookup(name, Type.SRV); Record[] recs = lookup.run(); if (recs == null) return res; for (Record record : recs) { org.xbill.DNS.SRVRecord srvRecord = (org.xbill.DNS.SRVRecord) record; if (srvRecord != null && srvRecord.getTarget() != null) { String host = srvRecord.getTarget().toString(); int port = srvRecord.getPort(); int priority = srvRecord.getPriority(); int weight = srvRecord.getWeight(); SRVRecord r = new SRVRecord(host, port, priority, weight); res.add(r); } } return res; }
/** * @param ip, like "192.168.1.1" * @return the complete DNS record for that IP. */ @Converter public static Record toRecord(String ip) throws IOException { Resolver res = new ExtendedResolver(); Name name = ReverseMap.fromAddress(ip); int type = Type.PTR; int dclass = DClass.IN; Record rec = Record.newRecord(name, type, dclass); Message query = Message.newQuery(rec); Message response = res.send(query); Record[] answers = response.getSectionArray(Section.ANSWER); if (answers.length == 0) { return null; } else { return answers[0]; } }
public static String resolve(String host, boolean enableIPv6) { String addr; if (enableIPv6 && isIPv6Support()) { addr = resolve(host, Type.AAAA); if (addr != null) { return addr; } } addr = resolve(host, Type.A); if (addr != null) { return addr; } addr = resolve(host); return addr; }
public List<DNSServiceRecord> getMultiSRV(String key) throws ConfigException { String qkey = fullyQualify(key); List<DNSServiceRecord> result = new ArrayList<DNSServiceRecord>(); List<Record> list = m_records.get(makeHostKey(qkey)); if (list == null) { throw new NotFoundException("No such record: " + makeHostKey(qkey)); } for (Record r : list) { if (r.getType() != Type.SRV) { continue; } result.add(new DNSServiceRecord(((SRVRecord) r).rdataToString())); } return result; }
private List<InetAddress> resolve(String key) throws UnknownHostException { List<InetAddress> result = new ArrayList<InetAddress>(); List<Record> list = m_records.get(key); if (list != null) for (Record r : list) if (r.getType() == Type.A) result.add(InetAddress.getByName(r.rdataToString())); else if ((r.getType() == Type.CNAME)) { List<Record> cnamelist = m_records.get(r.rdataToString()); for (Record r1 : cnamelist) { result.add(InetAddress.getByName(r1.rdataToString())); } } return result; }
public static void main(String[] args) throws Exception { try (DatagramSocket socket = new DatagramSocket()) { Message message = new Message(); Header header = message.getHeader(); header.setOpcode(Opcode.QUERY); header.setID(1); header.setRcode(Rcode.NOERROR); header.setFlag(Flags.RD); message.addRecord(Record.newRecord(new Name("www.xqbase.com."), Type.A, DClass.IN), Section.QUESTION); byte[] data = message.toWire(); DatagramPacket packet = new DatagramPacket(data, data.length, new InetSocketAddress("localhost", 53)); socket.send(packet); data = new byte[65536]; packet = new DatagramPacket(data, data.length); socket.setSoTimeout(2000); socket.receive(packet); Message response = new Message(Bytes.left(data, packet.getLength())); System.out.println(response); } }
private String[] findAddressesRecursive(Set<Name> stack, Name target) throws IOException { String[] ipv4Addresses = null; String[] ipv6Addresses = null; Message ipv4 = lookup(stack, getRoots(), Message.newQuery(Record.newRecord(target, Type.A, DClass.IN))); if (ipv4 != null) ipv4Addresses = findAddresses(target, ipv4.getSectionArray(Section.ANSWER)); Message ipv6 = lookup(stack, getRoots(), Message.newQuery(Record.newRecord(target, Type.AAAA, DClass.IN))); if (ipv6 != null) ipv6Addresses = findAddresses(target, ipv6.getSectionArray(Section.ANSWER)); String[] addresses = new String[0]; if (ipv4Addresses != null) addresses = ipv4Addresses; if (ipv6Addresses != null) { String[] concatAddresses = new String[addresses.length + ipv6Addresses.length]; System.arraycopy(addresses, 0, concatAddresses, 0, addresses.length); System.arraycopy(ipv6Addresses, 0, concatAddresses, addresses.length, ipv6Addresses.length); addresses = concatAddresses; } if (addresses.length == 0) return null; return addresses; }
private String[] findAddresses(Name target, Record[] records) { ArrayList<String> addresses = new ArrayList<String>(); for (Record record : records) { if (target == null || target.equals(record.getName())) { int recordType = record.getType(); if (Type.A == recordType) addresses.add(((ARecord)record).getAddress().getHostAddress()); else if (Type.AAAA == recordType) addresses.add(((AAAARecord)record).getAddress().getHostAddress()); } } if (addresses.size() == 0) return null; return addresses.toArray(new String[addresses.size()]); }
private void doUpdate(AdapterOperation op) { OnmsNode node = null; log().debug("doUpdate: operation: " + op.getType().name()); try { node = m_nodeDao.get(op.getNodeId()); DnsRecord record = new DnsRecord(node); log().debug("doUpdate: DnsRecord: hostname: " + record.getHostname() + " zone: " + record.getZone() + " ip address " + record.getIp().getHostAddress()); DnsRecord oldRecord = m_nodeDnsRecordMap.get(Integer.valueOf(node.getId())); Update update = new Update(Name.fromString(record.getZone())); if (oldRecord != null && oldRecord.getHostname() != record.getHostname()) { update.delete(Name.fromString(oldRecord.getHostname()), Type.A); } update.replace(Name.fromString(record.getHostname()), Type.A, 3600, record.getIp().getHostAddress()); m_resolver.send(update); m_nodeDnsRecordMap.put(Integer.valueOf(op.getNodeId()), record); } catch (Throwable e) { log().error("addNode: Error handling node added event.", e); sendAndThrow(op.getNodeId(), e); } }
private void doDelete(AdapterOperation op) { try { DnsRecord record = m_nodeDnsRecordMap.get(Integer.valueOf(op.getNodeId())); if (record != null) { Update update = new Update(Name.fromString(record.getZone())); update.delete(Name.fromString(record.getHostname()), Type.A); m_resolver.send(update); m_nodeDnsRecordMap.remove(Integer.valueOf(op.getNodeId())); } } catch (Throwable e) { log().error("deleteNode: Error handling node deleted event.", e); sendAndThrow(op.getNodeId(), e); } }
private void doUpdate(AdapterOperation op) { log().debug("doUpdate: operation: " + op.getType().name()); for (ReverseDnsRecord record : m_reverseDnsProvisioningAdapterService.get(op.getNodeId()) ) { log().debug("doUpdate: ReverseDnsRecord: hostname: " + record.getHostname() + " zone: " + record.getZone() + " ip address: " + record.getIp().getHostAddress()); try { Update update = new Update(Name.fromString(record.getZone())); Name ptrRecord=ReverseMap.fromAddress(record.getIp()); update.replace(ptrRecord, Type.PTR, 3600, record.getHostname()); m_resolver.send(update); m_reverseDnsProvisioningAdapterService.update(op.getNodeId(),record); } catch (Exception e) { log().error("updateNode: Error handling updated event.", e); sendAndThrow(op.getNodeId(), e); } } }
@Test public void testDnsJavaWithDnsServer() throws TextParseException, UnknownHostException { final Lookup l = new Lookup("example.com", Type.AAAA); final SimpleResolver resolver = new SimpleResolver("::1"); resolver.setPort(9153); l.setResolver(resolver); l.run(); System.out.println("result: " + l.getResult()); final Record[] answers = l.getAnswers(); assertEquals(answers.length, 1); final Record record = answers[0]; System.err.println(record.getTTL()); if(l.getResult() == Lookup.SUCCESSFUL) { System.out.println(l.getAnswers()[0].rdataToString()); } assertTrue(l.getResult() == Lookup.SUCCESSFUL); }
@Test @JUnitDNSServer(port=9153, zones={}) public void testNoAnswer() throws Exception { final Lookup l = new Lookup("example.com", Type.AAAA); final SimpleResolver resolver = new SimpleResolver("::1"); resolver.setPort(9153); l.setResolver(resolver); l.run(); System.out.println("result: " + l.getResult()); final Record[] answers = l.getAnswers(); assertNotNull(answers); assertEquals(answers.length, 1); final Record record = answers[0]; System.err.println(record.getTTL()); if(l.getResult() == Lookup.SUCCESSFUL) { System.out.println(l.getAnswers()[0].rdataToString()); } assertTrue(l.getResult() == Lookup.SUCCESSFUL); }
public static List<ForwardLookupResult> getARecord(String hostName, String domainName) throws TextParseException { List<ForwardLookupResult> entries = null; if (hostName != null && !hostName.isEmpty() && domainName != null && !domainName.isEmpty()) { Record[] recs = new Lookup(hostName, Type.A).run(); if (recs != null) { if (recs.length > 0) { entries = new ArrayList<>(); for (Record record : recs) { ForwardLookupResult foundSubDomain = new ForwardLookupResult(domainName); foundSubDomain.setHostName(hostName); String ipAddress = ((ARecord) record).getAddress().getHostAddress(); foundSubDomain.setIpAddress(ipAddress); foundSubDomain.setLookupType("A"); entries.add(foundSubDomain); } } } } return entries; }
public static List<ForwardLookupResult> getAAAARecord(String hostName, String domainName) throws TextParseException { List<ForwardLookupResult> entries = null; if (hostName != null && !hostName.isEmpty() && domainName != null && !domainName.isEmpty()) { Record[] recs = new Lookup(hostName, Type.AAAA).run(); if (recs != null) { if (recs.length > 0) { entries = new ArrayList<>(); for (Record record : recs) { ForwardLookupResult foundSubDomain = new ForwardLookupResult(domainName); foundSubDomain.setHostName(hostName); String ipAddress = ((AAAARecord) record).getAddress().getHostAddress(); foundSubDomain.setIpAddress(ipAddress); foundSubDomain.setLookupType("A"); entries.add(foundSubDomain); } } } } return entries; }
public static List<ARecordResult> getARecord(String hostName) throws TextParseException { List<ARecordResult> entries = null; Record[] recs = new Lookup(hostName, Type.A).run(); if (recs != null) { if (recs.length > 0) { entries = new ArrayList<>(); for (Record record : recs) { ARecordResult foundSubDomain = new ARecordResult(NetworkTools.getDomainFromHost(hostName)); foundSubDomain.setHostName(hostName); String ipAddress = ((ARecord) record).getAddress().getHostAddress(); foundSubDomain.setIpAddress(ipAddress); foundSubDomain.setLookupType("A"); entries.add(foundSubDomain); } } } return entries; }
public static String getDomainFromHost(String host) { String tmpHost = host; if (host.isEmpty()) { return ""; } while (true) { try { if (!tmpHost.startsWith("www.")) { Record[] recs = new Lookup(tmpHost, Type.SOA).run(); if (recs != null) { return tmpHost; } } if (tmpHost.contains(".")) { tmpHost = tmpHost.split("\\.", 2)[1]; } else { break; } } catch (TextParseException ex) { Logger.getLogger("networkTools.getDomainFromHost").log(Level.SEVERE, null, ex); break; } } return ""; }
public List<ARecordResult> getARecord(String hostName) throws TextParseException { List<ARecordResult> entries = null; Record[] recs = new Lookup(hostName, Type.A).run(); if (recs != null) { if (recs.length > 0) { entries = new ArrayList<>(); for (Record record : recs) { ARecordResult foundSubDomain = new ARecordResult(NetworkTools.getDomainFromHost(hostName)); foundSubDomain.setHostName(hostName); String ipAddress = ((ARecord) record).getAddress().getHostAddress(); foundSubDomain.setIpAddress(ipAddress); foundSubDomain.setLookupType("A"); entries.add(foundSubDomain); } } } return entries; }
/** * Store a {@link KeyEntry} in the cache. The entry will be ignored if it's * rrset isn't a DNSKEY rrset or if it doesn't have the SECURE security * status. * * @param ke The key entry to cache. * @return The passed {@link KeyEntry} to allow method chaining. */ public KeyEntry store(KeyEntry ke) { if (ke.getRRset() != null) { if (ke.getRRset().getType() != Type.DNSKEY) { return ke; } if (ke.getRRset().getSecurityStatus() != SecurityStatus.SECURE) { return ke; } } String k = this.key(ke.getName(), ke.getDClass()); CacheEntry ce = new CacheEntry(ke, this.maxTtl); this.cache.put(k, ce); return ke; }
private void processDNSKEYResponse(Message request, SMessage response, FindKeyState state) { Name qname = request.getQuestion().getName(); int qclass = request.getQuestion().getDClass(); SRRset dnskeyRrset = response.findAnswerRRset(qname, Type.DNSKEY, qclass); if (dnskeyRrset == null) { // If the DNSKEY rrset was missing, this is the end of the line. state.keyEntry = KeyEntry.newBadKeyEntry(qname, qclass, DEFAULT_TA_BAD_KEY_TTL); state.keyEntry.setBadReason(R.get("dnskey.no_rrset", qname)); return; } state.keyEntry = this.valUtils.verifyNewDNSKEYs(dnskeyRrset, state.dsRRset, DEFAULT_TA_BAD_KEY_TTL); // If the key entry isBad or isNull, then we can move on to the next // state. if (!state.keyEntry.isGood()) { return; } // The DNSKEY validated, so cache it as a trusted key rrset. this.keyCache.store(state.keyEntry); // If good, we stay in the FINDKEY state. this.processFindKey(state); }
/** * Given an SRRset that is signed by a DNSKEY found in the key_rrset, verify * it. This will return the status (either BOGUS or SECURE) and set that * status in rrset. * * @param rrset The SRRset to verify. * @param keyRrset The set of keys to verify against. * @return The status (BOGUS or SECURE). */ public SecurityStatus verifySRRset(SRRset rrset, SRRset keyRrset) { String rrsetName = rrset.getName() + "/" + Type.string(rrset.getType()) + "/" + DClass.string(rrset.getDClass()); if (rrset.getSecurityStatus() == SecurityStatus.SECURE) { logger.trace("verifySRRset: rrset <" + rrsetName + "> previously found to be SECURE"); return SecurityStatus.SECURE; } SecurityStatus status = this.verifier.verify(rrset, keyRrset); if (status != SecurityStatus.SECURE) { logger.debug("verifySRRset: rrset <" + rrsetName + "> found to be BAD"); status = SecurityStatus.BOGUS; } else { logger.trace("verifySRRset: rrset <" + rrsetName + "> found to be SECURE"); } rrset.setSecurityStatus(status); return status; }
/** * Determines whether the given {@link NSECRecord} proves that there is no * {@link DSRecord} for <code>qname</code>. * * @param nsec The NSEC that should prove the non-existence. * @param qname The name for which the prove is made. * @return {@link SecurityStatus#BOGUS} when the NSEC is from the child * domain or indicates that there indeed is a DS record, * {@link SecurityStatus#INSECURE} when there is not even a prove * for a NS record, {@link SecurityStatus#SECURE} when there is no * DS record. */ public static SecurityStatus nsecProvesNoDS(NSECRecord nsec, Name qname) { // Could check to make sure the qname is a subdomain of nsec if ((nsec.hasType(Type.SOA) && !Name.root.equals(qname)) || nsec.hasType(Type.DS)) { // SOA present means that this is the NSEC from the child, not the // parent (so it is the wrong one) -> cannot happen because the // keyset is always from the parent zone and doesn't validate the // NSEC // DS present means that there should have been a positive response // to the DS query, so there is something wrong. return SecurityStatus.BOGUS; } if (!nsec.hasType(Type.NS)) { // If there is no NS at this point at all, then this doesn't prove // anything one way or the other. return SecurityStatus.INSECURE; } // Otherwise, this proves no DS. return SecurityStatus.SECURE; }
/** * Determines if at least one of the DS records in the RRset has a supported * algorithm. * * @param dsRRset The RR set to search in. * @return True when at least one DS record uses a supported algorithm, * false otherwise. */ static boolean atLeastOneSupportedAlgorithm(RRset dsRRset) { Iterator<?> it = dsRRset.rrs(); while (it.hasNext()) { Record r = (Record)it.next(); if (r.getType() == Type.DS) { if (isAlgorithmSupported(((DSRecord)r).getAlgorithm())) { return true; } // do nothing, there could be another DS we understand } } return false; }
/** * Determines if at least one of the DS records in the RRset has a supported * digest algorithm. * * @param dsRRset The RR set to search in. * @return True when at least one DS record uses a supported digest * algorithm, false otherwise. */ static boolean atLeastOneDigestSupported(RRset dsRRset) { Iterator<?> it = dsRRset.rrs(); while (it.hasNext()) { Record r = (Record)it.next(); if (r.getType() == Type.DS) { if (isDigestSupported(((DSRecord)r).getDigestID())) { return true; } // do nothing, there could be another DS we understand } } return false; }
@Test public void testUnsignedThatMustBeSigned() throws IOException { Name query = Name.fromString("www.ingotronic.ch."); // prepare a faked, unsigned response message that must have a signature // to be valid Message message = new Message(); message.addRecord(Record.newRecord(query, Type.A, DClass.IN), Section.QUESTION); message.addRecord(new ARecord(query, Type.A, DClass.IN, InetAddress.getByName(localhost)), Section.ANSWER); add("www.ingotronic.ch./A", message); Message response = resolver.send(createMessage("www.ingotronic.ch./A")); assertFalse("AD flag must not be set", response.getHeader().getFlag(Flags.AD)); assertEquals(Rcode.SERVFAIL, response.getRcode()); assertEquals("validate.bogus.missingsig", getReason(response)); }
@Test public void testModifiedSignature() throws IOException { Name query = Name.fromString("www.ingotronic.ch."); // prepare a faked, unsigned response message that must have a signature // to be valid Message message = new Message(); message.addRecord(Record.newRecord(query, Type.A, DClass.IN), Section.QUESTION); message.addRecord(new ARecord(query, Type.A, DClass.IN, InetAddress.getByName(localhost)), Section.ANSWER); message.addRecord(new RRSIGRecord(query, DClass.IN, 0, Type.A, Algorithm.RSASHA256, 5, new Date(System.currentTimeMillis() + 5000), new Date(System.currentTimeMillis() - 5000), 1234, Name.fromString("ingotronic.ch."), new byte[] { 1, 2, 3 }), Section.ANSWER); add("www.ingotronic.ch./A", message); Message response = resolver.send(createMessage("www.ingotronic.ch./A")); assertFalse("AD flag must not be set", response.getHeader().getFlag(Flags.AD)); assertEquals(Rcode.SERVFAIL, response.getRcode()); assertTrue(getReason(response).startsWith("failed.answer.positive:{ www.ingotronic.ch.")); }
protected String getReason(Message m) { for (RRset set : m.getSectionRRsets(Section.ADDITIONAL)) { if (set.getName().equals(Name.root) && set.getType() == Type.TXT && set.getDClass() == ValidatingResolver.VALIDATION_REASON_QCLASS) { StringBuilder sb = new StringBuilder(); @SuppressWarnings("unchecked") List<String> strings = (List<String>)((TXTRecord)set.first()).getStrings(); for (String part : strings){ sb.append(part); } return sb.toString(); } } return null; }
/** * @see org.apache.james.dnsservice.api.DNSService#getByName(String) */ public InetAddress getByName(String host) throws UnknownHostException { String name = allowIPLiteral(host); try { // Check if its local if (name.equalsIgnoreCase(localHostName) || name.equalsIgnoreCase(localCanonicalHostName) || name.equals(localAddress)) { return getLocalHost(); } return org.xbill.DNS.Address.getByAddress(name); } catch (UnknownHostException e) { Record[] records = lookupNoException(name, Type.A, "A"); if (records != null && records.length >= 1) { ARecord a = (ARecord) records[0]; return InetAddress.getByAddress(name, a.getAddress().getAddress()); } else throw e; } }
/** * @see org.apache.james.dnsservice.api.DNSService#getAllByName(String) */ public InetAddress[] getAllByName(String host) throws UnknownHostException { String name = allowIPLiteral(host); try { // Check if its local if (name.equalsIgnoreCase(localHostName) || name.equalsIgnoreCase(localCanonicalHostName) || name.equals(localAddress)) { return new InetAddress[] { getLocalHost() }; } InetAddress addr = org.xbill.DNS.Address.getByAddress(name); return new InetAddress[] { addr }; } catch (UnknownHostException e) { Record[] records = lookupNoException(name, Type.A, "A"); if (records != null && records.length >= 1) { InetAddress[] addrs = new InetAddress[records.length]; for (int i = 0; i < records.length; i++) { ARecord a = (ARecord) records[i]; addrs[i] = InetAddress.getByAddress(name, a.getAddress().getAddress()); } return addrs; } else throw e; } }