org.xbill.DNS.Section Java Examples

The following examples show how to use org.xbill.DNS.Section. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IpAddressUtil.java    From megatron-java with Apache License 2.0 6 votes vote down vote up
private static String reverseDnsLookupUsingDnsJavaSimpleResolver(long ipAddress) throws IOException {
    String result = null;
    byte[] address = convertLongAddressToBuf(ipAddress);
    Name name = ReverseMap.fromAddress(InetAddress.getByAddress(address));
    Record record = Record.newRecord(name, Type.PTR, DClass.IN);
    Message query = Message.newQuery(record);
    Message response = simpleResolver.send(query);
    Record[] answers = response.getSectionArray(Section.ANSWER);
    if (answers.length != 0) {
        // If PTR-record exists this will be at index 1 or above (more than one PTR-record may exist)
        Record answer = (answers.length > 1) ? answers[1] : answers[0];  
        result = answer.rdataToString();
        // remove trailing "."
        result = result.endsWith(".") ? result.substring(0, result.length() - 1) : result;
    } else {
        throw new IOException("Empty DNS response.");
    }
    return result;
}
 
Example #2
Source File: SimpleDoTResolver.java    From androdns with Apache License 2.0 6 votes vote down vote up
private Message
sendAXFR(Message query) throws IOException {
    Name qname = query.getQuestion().getName();
    ZoneTransferIn xfrin = ZoneTransferIn.newAXFR(qname, address, tsig);
    xfrin.setTimeout((int)(getTimeout() / 1000));
    xfrin.setLocalAddress(localAddress);
    try {
        xfrin.run();
    }
    catch (ZoneTransferException e) {
        throw new WireParseException(e.getMessage());
    }
    List records = xfrin.getAXFR();
    Message response = new Message(query.getHeader().getID());
    response.getHeader().setFlag(Flags.AA);
    response.getHeader().setFlag(Flags.QR);
    response.addRecord(query.getQuestion(), Section.QUESTION);
    Iterator it = records.iterator();
    while (it.hasNext())
        response.addRecord((Record)it.next(), Section.ANSWER);
    return response;
}
 
Example #3
Source File: DNSLookupService.java    From openvisualtraceroute with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source File: Dig.java    From open-rmbt with Apache License 2.0 6 votes vote down vote up
static void	doAXFR(Message response) throws IOException {
	System.out.println("; java dig 0.0 <> " + name + " axfr");
	if (response.isSigned()) {
		System.out.print(";; TSIG ");
		if (response.isVerified())
			System.out.println("ok");
		else
			System.out.println("failed");
	}

	if (response.getRcode() != Rcode.NOERROR) {
		System.out.println(response);
		return;
	}

	Record [] records = response.getSectionArray(Section.ANSWER);
	for (int i = 0; i < records.length; i++)
		System.out.println(records[i]);

	System.out.print(";; done (");
	System.out.print(response.getHeader().getCount(Section.ANSWER));
	System.out.print(" records, ");
	System.out.print(response.getHeader().getCount(Section.ADDITIONAL));
	System.out.println(" additional)");
}
 
Example #5
Source File: XBillDnsSrvResolverTest.java    From dns-java with Apache License 2.0 6 votes vote down vote up
private Message messageWithNodes(String query, String[] names) throws TextParseException {
  Name queryName = Name.fromString(query);
  Record question = Record.newRecord(queryName, Type.SRV, DClass.IN);
  Message queryMessage = Message.newQuery(question);
  Message result = new Message();
  result.setHeader(queryMessage.getHeader());
  result.addRecord(question, Section.QUESTION);

  for (String name1 : names) {
    result.addRecord(
        new SRVRecord(queryName, DClass.IN, 1, 1, 1, 8080, Name.fromString(name1)),
        Section.ANSWER);
  }

  return result;
}
 
Example #6
Source File: dig.java    From dnsjava with BSD 2-Clause "Simplified" License 6 votes vote down vote up
static void doAXFR(Message response) {
  System.out.println("; java dig 0.0 <> " + name + " axfr");
  if (response.isSigned()) {
    System.out.print(";; TSIG ");
    if (response.isVerified()) {
      System.out.println("ok");
    } else {
      System.out.println("failed");
    }
  }

  if (response.getRcode() != Rcode.NOERROR) {
    System.out.println(response);
    return;
  }

  for (Record record : response.getSection(Section.ANSWER)) {
    System.out.println(record);
  }

  System.out.print(";; done (");
  System.out.print(response.getHeader().getCount(Section.ANSWER));
  System.out.print(" records, ");
  System.out.print(response.getHeader().getCount(Section.ADDITIONAL));
  System.out.println(" additional)");
}
 
Example #7
Source File: update.java    From dnsjava with BSD 2-Clause "Simplified" License 6 votes vote down vote up
void doProhibit(Tokenizer st) throws IOException {
  Tokenizer.Token token;
  Name name;
  Record record;
  int type;

  name = st.getName(zone);
  token = st.get();
  if (token.isString()) {
    if ((type = Type.value(token.value)) < 0) {
      throw new IOException("Invalid type: " + token.value);
    }
  } else {
    type = Type.ANY;
  }
  record = Record.newRecord(name, type, DClass.NONE, 0);
  query.addRecord(record, Section.PREREQ);
  print(record);
}
 
Example #8
Source File: update.java    From dnsjava with BSD 2-Clause "Simplified" License 5 votes vote down vote up
void doDelete(Tokenizer st) throws IOException {
  Tokenizer.Token token;
  String s;
  Name name;
  Record record;
  int type;

  name = st.getName(zone);
  token = st.get();
  if (token.isString()) {
    s = token.value;
    if (DClass.value(s) >= 0) {
      s = st.getString();
    }
    if ((type = Type.value(s)) < 0) {
      throw new IOException("Invalid type: " + s);
    }
    token = st.get();
    boolean iseol = token.isEOL();
    st.unget();
    if (!iseol) {
      record = Record.fromString(name, type, DClass.NONE, 0, st, zone);
    } else {
      record = Record.newRecord(name, type, DClass.ANY, 0);
    }
  } else {
    record = Record.newRecord(name, Type.ANY, DClass.ANY, 0);
  }

  query.addRecord(record, Section.UPDATE);
  print(record);
}
 
Example #9
Source File: jnamed.java    From dnsjava with BSD 2-Clause "Simplified" License 5 votes vote down vote up
byte[] buildErrorMessage(Header header, int rcode, Record question) {
  Message response = new Message();
  response.setHeader(header);
  for (int i = 0; i < 4; i++) {
    response.removeAllRecords(i);
  }
  if (rcode == Rcode.SERVFAIL) {
    response.addRecord(question, Section.QUESTION);
  }
  header.setRcode(rcode);
  return response.toWire();
}
 
Example #10
Source File: jnamed.java    From dnsjava with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void addGlue(Message response, Name name, int flags) {
  RRset a = findExactMatch(name, Type.A, DClass.IN, true);
  if (a == null) {
    return;
  }
  addRRset(name, response, a, Section.ADDITIONAL, flags);
}
 
Example #11
Source File: jnamed.java    From dnsjava with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void addCacheNS(Message response, Cache cache, Name name) {
  SetResponse sr = cache.lookupRecords(name, Type.NS, Credibility.HINT);
  if (!sr.isDelegation()) {
    return;
  }
  RRset nsRecords = sr.getNS();
  for (Record r : nsRecords.rrs()) {
    response.addRecord(r, Section.AUTHORITY);
  }
}
 
Example #12
Source File: OpenAliasHelper.java    From xmrwallet with Apache License 2.0 5 votes vote down vote up
@Override
protected Boolean doInBackground(String... args) {
    //main();
    if (args.length != 1) return false;
    String name = args[0];
    if ((name == null) || (name.isEmpty()))
        return false; //pointless trying to lookup nothing
    Timber.d("Resolving %s", name);
    try {
        SimpleResolver sr = new SimpleResolver(DNSSEC_SERVERS[new Random().nextInt(DNSSEC_SERVERS.length)]);
        ValidatingResolver vr = new ValidatingResolver(sr);
        vr.setTimeout(0, DNS_LOOKUP_TIMEOUT);
        vr.loadTrustAnchors(new ByteArrayInputStream(ROOT.getBytes("ASCII")));
        Record qr = Record.newRecord(Name.fromConstantString(name + "."), Type.TXT, DClass.IN);
        Message response = vr.send(Message.newQuery(qr));
        final int rcode = response.getRcode();
        if (rcode != Rcode.NOERROR) {
            Timber.i("Rcode: %s", Rcode.string(rcode));
            for (RRset set : response.getSectionRRsets(Section.ADDITIONAL)) {
                if (set.getName().equals(Name.root) && set.getType() == Type.TXT
                        && set.getDClass() == ValidatingResolver.VALIDATION_REASON_QCLASS) {
                    Timber.i("Reason:  %s", ((TXTRecord) set.first()).getStrings().get(0));
                }
            }
            return false;
        } else {
            dnssec = response.getHeader().getFlag(Flags.AD);
            for (Record record : response.getSectionArray(Section.ANSWER)) {
                if (record.getType() == Type.TXT) {
                    txts.addAll(((TXTRecord) record).getStrings());
                }
            }
        }
    } catch (IOException | IllegalArgumentException ex) {
        return false;
    }
    return true;
}
 
Example #13
Source File: update.java    From dnsjava with BSD 2-Clause "Simplified" License 5 votes vote down vote up
void doRequire(Tokenizer st) throws IOException {
  Tokenizer.Token token;
  Name name;
  Record record;
  int type;

  name = st.getName(zone);
  token = st.get();
  if (token.isString()) {
    if ((type = Type.value(token.value)) < 0) {
      throw new IOException("Invalid type: " + token.value);
    }
    token = st.get();
    boolean iseol = token.isEOL();
    st.unget();
    if (!iseol) {
      record = Record.fromString(name, type, defaultClass, 0, st, zone);
    } else {
      record = Record.newRecord(name, type, DClass.ANY, 0);
    }
  } else {
    record = Record.newRecord(name, Type.ANY, DClass.ANY, 0);
  }

  query.addRecord(record, Section.PREREQ);
  print(record);
}
 
Example #14
Source File: XBillDnsSrvResolverTest.java    From dns-java with Apache License 2.0 5 votes vote down vote up
private Message messageWithRCode(String query, int rcode) throws TextParseException {
  Name queryName = Name.fromString(query);
  Record question = Record.newRecord(queryName, Type.SRV, DClass.IN);
  Message queryMessage = Message.newQuery(question);
  Message result = new Message();
  result.setHeader(queryMessage.getHeader());
  result.addRecord(question, Section.QUESTION);

  result.getHeader().setRcode(rcode);

  return result;
}
 
Example #15
Source File: DnsUpdateWriterTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private ImmutableList<Record> findUpdateRecords(
    Update update, String resourceName, int recordType) {
  for (RRset set : update.getSectionRRsets(Section.UPDATE)) {
    if (set.getName().toString().equals(resourceName) && set.getType() == recordType) {
      return fixIterator(Record.class, set.rrs());
    }
  }
  assertWithMessage(
          "No record set found for resource '%s' type '%s'",
          resourceName, Type.string(recordType))
      .fail();
  throw new AssertionError();
}
 
Example #16
Source File: update.java    From dnsjava with BSD 2-Clause "Simplified" License 4 votes vote down vote up
void doAdd(Tokenizer st) throws IOException {
  Record record = parseRR(st, defaultClass, defaultTTL);
  query.addRecord(record, Section.UPDATE);
  print(record);
}
 
Example #17
Source File: update.java    From dnsjava with BSD 2-Clause "Simplified" License 4 votes vote down vote up
void doGlue(Tokenizer st) throws IOException {
  Record record = parseRR(st, defaultClass, defaultTTL);
  query.addRecord(record, Section.ADDITIONAL);
  print(record);
}
 
Example #18
Source File: update.java    From dnsjava with BSD 2-Clause "Simplified" License 4 votes vote down vote up
boolean doAssert(Tokenizer st) throws IOException {
  String field = st.getString();
  String expected = st.getString();
  String value = null;
  boolean flag = true;
  int section;

  if (response == null) {
    print("No response has been received");
    return true;
  }
  if (field.equalsIgnoreCase("rcode")) {
    int rcode = response.getHeader().getRcode();
    if (rcode != Rcode.value(expected)) {
      value = Rcode.string(rcode);
      flag = false;
    }
  } else if (field.equalsIgnoreCase("serial")) {
    List<Record> answers = response.getSection(Section.ANSWER);
    if (answers.isEmpty() || !(answers.get(0) instanceof SOARecord)) {
      print("Invalid response (no SOA)");
    } else {
      SOARecord soa = (SOARecord) answers.get(0);
      long serial = soa.getSerial();
      if (serial != Long.parseLong(expected)) {
        value = Long.toString(serial);
        flag = false;
      }
    }
  } else if (field.equalsIgnoreCase("tsig")) {
    if (response.isSigned()) {
      if (response.isVerified()) {
        value = "ok";
      } else {
        value = "failed";
      }
    } else {
      value = "unsigned";
    }
    if (!value.equalsIgnoreCase(expected)) {
      flag = false;
    }
  } else if ((section = Section.value(field)) >= 0) {
    int count = response.getHeader().getCount(section);
    if (count != Integer.parseInt(expected)) {
      value = Integer.toString(count);
      flag = false;
    }
  } else {
    print("Invalid assertion keyword: " + field);
  }

  if (!flag) {
    print("Expected " + field + " " + expected + ", received " + value);
    while (true) {
      Tokenizer.Token token = st.get();
      if (!token.isString()) {
        break;
      }
      print(token.value);
    }
    st.unget();
  }
  return flag;
}
 
Example #19
Source File: jnamed.java    From dnsjava with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void addSOA(Message response, Zone zone) {
  response.addRecord(zone.getSOA(), Section.AUTHORITY);
}
 
Example #20
Source File: jnamed.java    From dnsjava with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void addNS(Message response, Zone zone, int flags) {
  RRset nsRecords = zone.getNS();
  addRRset(nsRecords.getName(), response, nsRecords, Section.AUTHORITY, flags);
}
 
Example #21
Source File: jnamed.java    From dnsjava with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void addAdditional(Message response, int flags) {
  addAdditional2(response, Section.ANSWER, flags);
  addAdditional2(response, Section.AUTHORITY, flags);
}
 
Example #22
Source File: jnamed.java    From dnsjava with BSD 2-Clause "Simplified" License 4 votes vote down vote up
byte[] generateReply(Message query, byte[] in, Socket s) {
  Header header;
  boolean badversion;
  int maxLength;
  int flags = 0;

  header = query.getHeader();
  if (header.getFlag(Flags.QR)) {
    return null;
  }
  if (header.getRcode() != Rcode.NOERROR) {
    return errorMessage(query, Rcode.FORMERR);
  }
  if (header.getOpcode() != Opcode.QUERY) {
    return errorMessage(query, Rcode.NOTIMP);
  }

  Record queryRecord = query.getQuestion();

  TSIGRecord queryTSIG = query.getTSIG();
  TSIG tsig = null;
  if (queryTSIG != null) {
    tsig = TSIGs.get(queryTSIG.getName());
    if (tsig == null || tsig.verify(query, in, null) != Rcode.NOERROR) {
      return formerrMessage(in);
    }
  }

  OPTRecord queryOPT = query.getOPT();
  if (s != null) {
    maxLength = 65535;
  } else if (queryOPT != null) {
    maxLength = Math.max(queryOPT.getPayloadSize(), 512);
  } else {
    maxLength = 512;
  }

  if (queryOPT != null && (queryOPT.getFlags() & ExtendedFlags.DO) != 0) {
    flags = FLAG_DNSSECOK;
  }

  Message response = new Message(query.getHeader().getID());
  response.getHeader().setFlag(Flags.QR);
  if (query.getHeader().getFlag(Flags.RD)) {
    response.getHeader().setFlag(Flags.RD);
  }
  response.addRecord(queryRecord, Section.QUESTION);

  Name name = queryRecord.getName();
  int type = queryRecord.getType();
  int dclass = queryRecord.getDClass();
  if (type == Type.AXFR && s != null) {
    return doAXFR(name, query, tsig, queryTSIG, s);
  }
  if (!Type.isRR(type) && type != Type.ANY) {
    return errorMessage(query, Rcode.NOTIMP);
  }

  byte rcode = addAnswer(response, name, type, dclass, 0, flags);
  if (rcode != Rcode.NOERROR && rcode != Rcode.NXDOMAIN) {
    return errorMessage(query, rcode);
  }

  addAdditional(response, flags);

  if (queryOPT != null) {
    int optflags = (flags == FLAG_DNSSECOK) ? ExtendedFlags.DO : 0;
    OPTRecord opt = new OPTRecord((short) 4096, rcode, (byte) 0, optflags);
    response.addRecord(opt, Section.ADDITIONAL);
  }

  response.setTSIG(tsig, Rcode.NOERROR, queryTSIG);
  return response.toWire(maxLength);
}
 
Example #23
Source File: DnsUpdateWriterTest.java    From nomulus with Apache License 2.0 4 votes vote down vote up
private void assertThatTotalUpdateSetsIs(Update update, int count) {
  assertThat(update.getSectionRRsets(Section.UPDATE)).hasLength(count);
}
 
Example #24
Source File: DnsUpdateWriterTest.java    From nomulus with Apache License 2.0 4 votes vote down vote up
private void assertThatUpdatedZoneIs(Update update, String zoneName) {
  Record[] zoneRecords = update.getSectionArray(Section.ZONE);
  assertThat(zoneRecords[0].getName().toString()).isEqualTo(zoneName);
}
 
Example #25
Source File: SimpleDoTResolver.java    From androdns with Apache License 2.0 4 votes vote down vote up
private void
applyEDNS(Message query) {
    if (queryOPT == null || query.getOPT() != null)
        return;
    query.addRecord(queryOPT, Section.ADDITIONAL);
}