10 dns questions solved with dig

How to Use Dig to Test DNS Records

If you’ve set up a domain name with DigitalOcean, you can use dig to query the information.

To test that your «A» records are set correctly, type:

dig your_domain_name.com

If you would like to check if your mail servers are directing correctly, type:

dig your_domain_name.com MX

In general, you can issue the type of record that you would like to query after the domain name in the query.

If you would like to receive information about all of the records, type:

dig your_domain_name.com ANY

This will return any records that match the base domain you set up. These will include «SOA» records, «NS» records, «A» records, and «MX» records.

Note: Due to the way that TTL and DNS works, it sometimes takes awhile for the changes you create to propagate to the name servers. If you have created a record and do not see it, wait until the TTL reaches 0 to see if your record shows up.

If you would like to only return the actual IP the domain points to, you can type:

dig your_domain_name.com +short

Using the «host» Command Instead of «dig»

An alternative to dig is a command called «host». This command functions in a very similar way to dig, with many of the same options.

The basic syntax is:

host domain_name_or_IP_address

Notice how you do not need a flag to change the functionality from regular DNS lookup to reverse DNS lookup.

As with dig, you can specify the type of record you are interested in. This is done with the «-t» flag.

To return the mx records of google, you can type:

host -t mx google.com
google.com mail is handled by 50 alt4.aspmx.l.google.com.
google.com mail is handled by 10 aspmx.l.google.com.
google.com mail is handled by 40 alt3.aspmx.l.google.com.
google.com mail is handled by 30 alt2.aspmx.l.google.com.
google.com mail is handled by 20 alt1.aspmx.l.google.com.

Other types of records can be retrieved just as easily.

You can return all records with the «-a» flag. I will not post the output of this command, because it can be quite long:

host -a google.com

If you need additional information about the host, you can turn on verbose output with the «-v» flag:

host -v google.com

This will provide extended information.

Протокол TSIG

TSIG (Transaction SIGnature) — это протокол, который обеспечивает идентификацию и целостность данных. Для этого в нем реализована технология подписи транзакций. Для всех запросов, ответов и прочих сообщений к DNS при помощи механизма проверки целостности информации (HMAC) высчитывается сигнатура на основе общего секретного ключа (shared key).

При правильно работающем механизме TSIG и сервер, и клиент добавляют TSIG в раздел дополнительных данных пакета с запросом к DNS. Тем самым они подтверждают, что обладают верным секретным ключом, что сообщение не изменилось по пути и ему можно доверять.

Протокол TSIG поддерживают все популярные серверы DNS, такие как NSD, PowerDNS, Knot и, разумеется, BIND.

WARNING

Вся информация носит только ознакомительный характер. Ни автор, ни редакция не несут ответственности за ее ненадлежащее использование.

Информация об уязвимости

В начале июня 2017 года исследователи безопасности из компании Synacktiv обнаружили брешь в реализации протокола TSIG в BIND. Уязвимость позволяет атакующему, который знает название ключа TSIG, обойти проверку протокола и вычислять легитимную сигнатуру для произвольных сообщений к DNS-серверу.

Проблема заключается в том, что, когда клиент отправляет пакет, который содержит TSIG-дайджест заведомо неверной длины, в ответ сервер все равно вернет валидно подписанный пакет, используя переданный дайджест в качестве префикса. Это позволяет атакующему узнать сигнатуру валидного запроса и тем самым пройти проверки легитимности.

Сама уязвимость была протестирована в версиях BIND 9.9.10, 9.10.5 и 9.11.1. Однако ISC в бюллетене безопасности указывает, что уязвимы следующие версии продуктов:

  • от 9.4.0 до 9.8.8;
  • от 9.9.0 до 9.9.10­P1;
  • от 9.10.0 до 9.10.5­P1;
  • от 9.11.0 до 9.11.1­P1;
  • от 9.9.3­S1 до 9.9.10­S2;
  • от 9.10.5­S1 до 9.10.5­S2.

Так что если ты счастливый обладатель одной из них, то скорее обновляйся.

Тестовый стенд

Чтобы в полной мере насладиться изучением проблемы, нужно эмулировать идеальные условия ее возникновения. Для этого по старинке возьмем Docker.

В интернете ты можешь найти массу способов установки и настройки BIND, а здесь я пробегусь по ключевым моментам, которые позволят воссоздать ситуацию, когда атака возможна.

Первое, что нужно сделать после установки BIND, — это сконфигурировать новую зону в DNS-сервере. В этом нам поможет файл .

Создаем TSIG-ключ, даем ему произвольное имя и указываем алгоритм, который будет использоваться для генерации сигнатур при общении клиента с сервером DNS (и наоборот).

Для успешной эксплуатации уязвимости атакующему нужно угадать ключ и алгоритм хеширования.

Далее настраиваем саму зону (я задал ) и определяем, для каких запросов нужно использовать валидацию через протокол TSIG и соответствующий ключ.

Помимо прочего, нам понадобится какой-нибудь сниффер, например tcpdump.

Если не хочешь со всем этим возиться, то просто скачивай готовый файл Docker из моего репозитория. В нем используется уязвимая версия BIND 9.10.5. Запускай скрипт , он сделает все необходимое, тебе останется только запустить сам сервер командой .

Go-go-go!

Общие детали

Для начала посмотрим, как выглядит легитимный запрос на zone transfer. Это делается утилитой dig, но сначала поставим tcpdump в режим мониторинга трафика DNS. Чтобы включить TSIG в запросах, нужно указать ключ с помощью опции . Формат такой: .

Снифаем трафик запроса AXFR

Поймалось несколько пакетов, давай посмотрим на них.

Пакет с ответом на AXFR-запрос

На скрине видно TSIG, который сгенерировал сервер на основе нашего ключа. Формат ответа описан в . Согласно спецификации все запросы при общении должны быть подписаны. Сама подпись генерируется на основе следующих компонентов:

  • размер MAC (Message authentication code, дайджест) запроса. Под него выделяется два байта;
  • MAC-запрос;
  • DNS-сообщение ответа;
  • ключ TSIG-ответа.

Далее в этой же RFC в указано, что если запрос вызвал ошибку и эта ошибка не имеет отношения непосредственно к TSIG, то в ответ должен улететь пакет с подписью, которая будет сгенерирована в соответствии с указанными выше параметрами.

Вариант 1. Присоединись к сообществу «Xakep.ru», чтобы читать все материалы на сайте

Членство в сообществе в течение указанного срока откроет тебе доступ ко ВСЕМ материалам «Хакера», увеличит личную накопительную скидку и позволит накапливать профессиональный рейтинг Xakep Score!
Подробнее

Вариант 2. Открой один материал

Заинтересовала статья, но нет возможности стать членом клуба «Xakep.ru»? Тогда этот вариант для тебя!
Обрати внимание: этот способ подходит только для статей, опубликованных более двух месяцев назад.

Я уже участник «Xakep.ru»

Dig command basic syntax

When you are going to use any command you must know the basic syntax. Dig command basic syntax is useful and necessary.

If you will not follow the basic syntax, you will not get the appropriate result. You can use the following command to know more about dig command

$dig -h or$man dig

Basic syntax as follows:

dig

ServerIt is the domain name or IP address of the name server to query. This can be an IPv4 address in dotted-decimal notation or an IPv6 address in colon-delimited notation. When the supplied server argument is a hostname, dig resolves that name before querying that name server. If no server argument is provided, dig consults /etc/resolv.conf; if an address is found there, it queries the name server at that address. If either of the -4 or -6 options are in use, then only addresses for the corresponding transport will be tried. If no usable addresses are found, dig will send the query to the localhost. The reply from the name server that responds is displayed.

Name: is the name of the resource record that is to be looked up.

Type: indicates what type of query is required — ANY, A, MX, SIG, etc. type can be any valid query type. If no type argument is supplied, dig will perform a lookup for an A record.

Usage of the dig command.

First on the terminal use the command

dig -h

This command would show all the options used in dig

In a similar way, many of the given commands can be used. For eg, let’s use authority now.

Examples of dig in a Sentence

Verb

Some animal has been digging in the garden.

They dug into the sand with their hands.

He dug down about 10 feet before he hit water. Dig a hole three feet deep.

The first step in building a house is to dig the foundation.

The prisoners escaped by digging a tunnel under the fence. digging clams on the beach

These detectives won’t stop digging until they find out what happened. Noun

She gave me a dig in the ribs to get my attention.

She participated in a dig last summer.

See More

Recent Examples on the Web: Verb But those who dig a little deeper into the town will find a surprising number of hiking trails that lead to beautiful outdoor destinations.

oregonlive, «4 hikes to explore around Camas, a surprising natural escape in the suburbs,» 22 Aug. 2020 Put on long gloves and try to dig the torpedograss out by removing the underground rhizomes.

Tom Maccubbin, orlandosentinel.com, «How to grow pineapples from shoots,» 22 Aug. 2020 This best-selling bra is indeed worthy of its name, with a front closure (way easier to put on), a back made out of hosiery for smoothing and comfort, and dig-free Smart Straps that will keep you feeling supported all day.

Krystin Arneson, CNN Underscored, «Spanx bras, leggings and more are up to 50% off right now,» 20 Aug. 2020 Pop-Up Fire Pit: No hole to dig, no nature to disturb.

Ryan D’agostino, Car and Driver, «Winnebago Builds a More Accessible RV to Help Everyone Get Away,» 16 Aug. 2020 Out in the fields women worked with hoes, and men with spades, to plant potatoes or dig wells.

The Economist, «The tale of a village László Bogdán died on July 14th,» 1 Aug. 2020 Not all are recommended, such as an Instagram post in which one person was hitting a volleyball off a roof and someone was in the driveway trying to dig the ball.

Greg Riddle, Dallas News, «Dallas-area volleyball teams get creative when forced outdoors by county restrictions,» 30 July 2020 Deep sea mining works by having vehicles on the ocean floor dig directly into the seabed, and this process releases silt, clay, and other sediments that are immediately carried away by the flow of water.

Caroline Delbert, Popular Mechanics, «Scientists: Sea Floor Mining Is Basically as Bad as It Sounds,» 13 July 2020 Wildland firefighters work shoulder-to-shoulder—sometimes using hand tools to dig break lines beyond which the fire cannot go — crowd together in small vehicles, and sleep in close quarters near the fire.

Jeanne Dorin Mcdowell, Smithsonian Magazine, «How COVID-19 Will Change the Way We Fight Wildfires,» 7 July 2020 Recent Examples on the Web: Noun Pelosi told the Washington Post that Markey’s campaign crossed a line with a recent ad that included a dig at the Kennedy family dynasty.

Abby Smith, Washington Examiner, «Daily on Energy: Odds rise for sweeping Democratic climate legislation,» 21 Aug. 2020 Nagy even jogged over from team drills to inject a dig.

Colleen Kane, chicagotribune.com, «The key to energizing Bears wide receivers and defensive backs at training camp? An ‘authentic’ WWE championship belt, of course.,» 19 Aug. 2020 On Friday, the show responded to the apparent dig by tweeting a video featuring Marge herself.

Jodi Guglielmi, PEOPLE.com, «Marge Simpson Responds to Trump Adviser’s Kamala Harris Dig: I Feel ‘Disrespected’,» 14 Aug. 2020 Now, the creators of The Simpsons are letting Marge respond to the dig.

Nick Romano, EW.com, «Marge from The Simpsons is ‘pissed off’ at Trump advisor for Kamala Harris jab,» 14 Aug. 2020 Their dig site is a cave that looks out over the southern Indian Ocean.

Dallas News, «North Texas researchers find opportunities amid the challenges of the COVID-19 pandemic,» 13 Aug. 2020 One day after Brooks Koepka took a subtle but unmistakable dig at Dustin Johnson, and his history of struggling to close out majors, Rory McIlroy rose to Johnson’s defense.

Ron Kroichick, SFChronicle.com, «Rory McIlroy ‘taken aback’ by Brooks Koepka’s verbal shot at Dustin Johnson,» 9 Aug. 2020 In this case, the leather mouse emerged from a bag of scrap leather first discovered during a 1993 dig at the residence of a commanding officer.

Alex Fox, Smithsonian Magazine, «Ancient Leather ‘Mouse’ Highlights the Romans’ Sense of Humor,» 19 May 2020 In an amusing dig at media gullibility, the reporters instantly swallow their skepticism when a scientist (Sean Whalen) whips out a graph to explain Herschel’s remarkable state of preservation.

David Rooney, The Hollywood Reporter, «‘An American Pickle’: Film Review,» 3 Aug. 2020

Grabbing SOA information

As a DNS administrator, I sometimes make changes and want to see if any
of my name servers are still pushing the old data. The
provides a clear accounting of your public servers.

Interpreting TTL numbers

I love for many reasons, one of which
is that it provides referrer strings in my web logs that make it easy to
figure out what sort of queries lead people to pages on this site.

Somewhat unexpectedly, I’ve seen a lot of queries asking for information
about TTL (time-to-live) numbers. I would have never guessed that TTL
would be a topic of interest, but you learn something new every day. So,
by popular demand, here’s a brief intro to TTL.

If you ask your local DNS server for an Internet address, the server
figures out where to find an authoritative answer and then asks for it.
Once the server receives an answer, it will keep the answer in a local
cache so that if you ask for the same address again a short time later,
it can give you the answer quickly rather than searching the Internet
for it all over again.

When domain administrators configure their DNS records, they decide how
long the records should remain in remote caches. This is the TTL number
(usually expressed in number of seconds).

Typically, a remote server will only cache those records for the length
of time specified by the TTL. After that, the remote server will flush
its local cache and ask again for an authoritative answer.

When you use dig to query a DNS server concerning a certain record, the
server will tell dig the time (in seconds) that record will remain in
cache.

For example, as of this writing, the TTL for the MX records for the
gmail.com domain is 300 seconds. The gmail.com admins are asking that
remote servers cache their MX records for no more than five minutes. So
when you first ask for that record set, dig will report a TTL of 300.

If you ask a few seconds later, you’ll see the TTL number reduced by
approximately the number of seconds you waited to ask again.

If your timing is good, you can catch the record at the very end of its
life.

After that, the DNS server you’re querying will “forget” the answer to
that question, so the whole cycle will start over again (in this
example, at 300 seconds) the next time you perform that query.

Dig Syntax

In its simplest form, the syntax of the dig utility will look like this:

dig   

– the IP address or hostname of the name server to query.

If the server argument is the hostname then dig will resolve the hostname before proceeding with querying the name server.

It is optional and if you don’t provide a server argument then dig uses the name server listed in /etc/resolv.conf.

– the name of the resource record that is to be looked up.

– the type of query requested by dig. For example, it can be an A record, MX record, SOA record or any other types. By default dig performs a lookup for an A record if no type argument is specified.

Для чего нужен ДНС?

В современном мире мы можем подключаться не только к серверам, компьютерам, но и к различным устройствам. Сейчас IP-адреса могут быть у часов, весов даже у чайников.

DNS — система доменных имен. Она связывает доменные имена с цифровыми адресами и служит для интерпретации доменных имен в IP-адреса.

Для подключения к устройству, кто устанавливает соединения должен знать IP-адрес назначения. Если соединения устанавливает человек, например открывает браузер и пытается открыть какой-нибудь сайт, то для человека запоминать айпи адреса сервера сайта достаточно сложно, поэтому в 80-х годах придумали систему доменных имен.

Сервера DNS знают под каким именем зарегистрирован тот или иной IP-адрес. И когда Вы вводите  название сайта в адресной строке браузера, запрос обрабатывается DNS сервером и отправляется по адресу.

SIMPLE USAGE

       A typical invocation of dig looks like:

          dig @server name type

       where:

       server is the name or IP address of the name server to query. This  can
              be an IPv4 address in dotted-decimal notation or an IPv6 address
              in colon-delimited notation. When the supplied  server  argument
              is  a hostname, dig resolves that name before querying that name
              server.

              If   no   server   argument   is    provided,    dig    consults
              /etc/resolv.conf;  if  an address is found there, it queries the
              name server at that address. If either of the -4 or  -6  options
              are  in use, then only addresses for the corresponding transport
              will be tried. If no usable addresses are found, dig  will  send
              the query to the local host. The reply from the name server that
              responds is displayed.

       name   is the name of the resource record that is to be looked up.

       type   indicates what type of query is required MDASH ANY, A, MX,  SIG,
              etc.   type  can be any valid query type. If no type argument is
              supplied, dig will perform a lookup for an A record.


Опции nslookup

При выполнении запросов мы можем использовать следующие опции:

Опция Описание
Применяются для команды и интерактивного режима
all Выводит параметры текущего запроса и настроек сервера DNS.
class=X Задает класс запроса, который указывает группу протоколов информации. Возможны варианты:
1. IN — Internet. Более, чем в 99% случаев используется он.
2. CHAOS, HESIOD — данные классы используются, крайне, редко.
3. ANY — запрос по всем возможным классам.
d2 Выводит полной информации по осуществлению запроса.
nod2 Обычный вывод (по умолчанию).
debug Покажет отладочную информацию по запросу.
nodebug Запрос без отображения отладочной информации (по умолчанию).
defname При запросе к хосту не FQDN автоматически подставит домен, который находится в настройках системы (DNS-суффикс).
nodefname Не подставлять домен.
domain=’NAME’ Задает домен, который должен быть подставлен к имени хоста (альтернатива DNS-суффиксу).
querytype=TYPE Указывает на тип запроса или тип записи, например, А, mx, txt и так далее. Аналогична опции type.
recurse Рекурсивный запрос (информация запрашивается у других серверов, если ее нет на используемом в запросе).
norecurse Запрет на использование рекурсивного запроса.
retry=X В случае долгого ответа, параметр позволяет указать количество повторов опроса.
root Назначает текущий DNS в качестве корневого сервера по умолчанию.
root=NAME Позволяет задать корневой сервер.
search Добавлять DNS-имена к имени хоста из списка доменов (сам список задается опцией srchlist).
nosearch Не использовать список доменов для подстановки к имени хоста.
srchlist=N1[/N2/…/N6] Задает список доменов, который нужно подставлять при использовании опции search.
timeout=X Задает время в секундах, сколько утилита должна ждать ответа от сервера.
type=X Указывает на тип записи, которую будем опрашивать. Например, для получения записи AAAA мы вводим опцию type=АААА.
vc Позволяет использовать виртуальную схему при отправке запросов. К сожалению, я не нашел подробного описания, что это значит.
novc Не использовать виртуальную схему при отправке запросов.
Работают только в интерактивном режиме (задается без SET)
lsserver NAME Задает имя сервера DNS. При определении имени NAME используется начальная настройка DNS.
server NAME Задает имя сервера DNS. При определении имени NAME используется текущее значение для DNS.

Также мы можем вызвать описание для nslookup.

а) в системах на базе Windows:

nslookup

> help 

б) в Linux:

man nslookup

Использование опций

При вводе команды nslookup к опциям добавляем дефис, например:

nslookup -timeout=1 -type=MX dmosk.ru

Если мы работаем с nslookup в интерактивном режиме, то опции задаются с помощью команды set:

> set debug

> dmosk.ru

* первая команда задает опцию для выполнения подробных запросов. Вторая — делает запрос для домена dmosk.ru.

Do bulk lookups?

If you want to look up a large number of hostnames, you can put them in
a file (one name per line) and use the option to query each one in
turn.

As far as I can tell, versions up to and including 9.2.3 are
unable to do reverse lookups using the option.

Verifying DNS mappings

An improperly configured DNS setup can be really annoying. You want to
make sure that your mappings work both ways:

  1. Each hostname should resolve to an address, and that address ought
    to resolve back to the proper hostname.

  2. If an address on your subnet(s) has been assigned a reverse pointer
    to a hostname, that hostname ought to point back to the original
    address.

There are exceptions to those two rules, of course. A CNAME will resolve
to another hostname first, and only then to an address. Sometimes
multiple hostnames will point to the same address, but that address will
have only one reverse pointer.

Still, it’s good to know that your basic mappings work as expected.

You can script such a test if you build a file containing your known
hostnames. The example script below is pretty simple; it will break if
fed a CNAME, and it’ll report a failure somewhere if multiple hostnames
point to the same address. Let’s assume the file containing your
hostnames is named .

Dig command followed by the domain name

dig authority www.google.com

in the above command, the result indicates that the authoritative search went from ns2->ns1->ns4->ns3, which means name server 2 has more authority over the search according to the context of the domain name over name server 1.

Another Example:

Now let us fool around with some other commands

dig nssearch www.facebook.com  **searches for name servers**

dig additional www.facebook.com **controls all additional queries **

dig nsid www.facebook.com ** searches for the name servers ID**

Similarly , there are other options that can be used for several other purposes. Here we go folks yet another command prominent in information gathering.

MODULE 4:- Information Gathering

  1. How to use dnsenum for dns enumeration – Kali
  2. How to use dig command in Kali Linux
  3. whois Kali Linux commands with example
  4. Enumerating DNS Records through dnsenum tool in Kali Linux
  5. Email Harvesting by theharvester tool in Kali Linux
  6. Google Hacking | Open Web Information Gathering
  7. dnsmap | DNS Domain name system brute force attacks
  8. Zone Transfer using dnswalk tool
  9. Website information Gathering through Nikto tool
  10. Search Senstive Data through Metagoofil Kali Linux 2.0
  11. 8 Steps to run Maltego Kali Linux – beginner guide

Cómo usar el comando dig

Veamos los usos básicos del comando:

Consultar un nombre de dominio

Para realizar una búsqueda de DNS para un nombre de dominio, simplemente escribe dicho dominio junto al comando dig:

dig hostinger.com

Por defecto, el comando dig mostrará el registro A cuando no se especifiquen otras opciones. Además, la salida contendrá más información, como la versión de dig instalada, detalles técnicos sobre las respuestas, estadísticas sobre la consulta, una sección de preguntas, entre otros.

Ver respuestas cortas

El comando dig incluye una gran cantidad de información útil en diferentes secciones, pero puede haber ocasiones en las que desees solo el resultado  en sí de la consulta. En estos casos puedes utilizar la opción +short, que mostrará solo la dirección IP (registro A) del nombre de dominio:

dig hostinger.com +short

Ver respuestas detalladas

Si deseas ver específicamente la sección de respuestas a detalle puedes dejar de mostrar toda la sección con la opción +noall y ver solo la sección de respuestas con la opción +answer, todo esto junto al comando dig.

dig hostinger.com +noall +answer

Especificar servidores de nombres

Por defecto, el comando dig consultará los nombres de servidores listados en /etc/resolv.conf para realizar la búsqueda de DNS que le solicites. Puedes cambiar esta configuración predeterminada utilizando el símbolo @ seguido del hostname o la dirección IP del servidor.

El comando dig que te mostramos a continuación envía la consulta DNS al nombre de servidor de Google (8.8.8.8) mediante la opción @8.8.8.8.

dig @8.8.8.8 hostinger.com

Consultar todos los registros DNS

Para consultar todos los tipos de registros DNS disponibles asociados con un dominio, usa la opción ANY. Esta opción incluirá en los resultados todos los tipos de registros disponibles:

dig hostinger.com ANY

Buscar por tipo de registro

Si deseas buscar un registro específico, simplemente agrega el tipo de registro al final del comando.

Por ejemplo, para consultar y obtener solo el intercambio de correo – MX – en la sección de respuesta asociada a un dominio, puedes usar el siguiente comando de dig:

dig hostinger.in MX

De manera similar, para ver los otros registros asociados a un dominio, especifica el tipo de registro al final del comando dig:

dig hostinger.com txt (Consulta el registro TXT)
dig hostinger.com cname (Consulta el registro CNAME)
dig hostinger.com ns (Consulta el registro NS)
dig hostinger.com A (Consulta el registro A)

Trazar ruta (path) de DNS

Dig permite rastrear la ruta de búsqueda DNS utilizando la opción +trace. Esta opción realiza consultas iterativas para resolver la búsqueda de nombres. Consultará los nombres de servidores a partir de la raíz y posteriormente atravesará el árbol del espacio de nombres mediante consultas iterativas siguiendo las referencias en el camino:

dig hostinger.com +trace

Búsqueda inversa de DNS

La búsqueda inversa de DNS te permite buscar el dominio y el nombre de host asociados a una dirección IP. Para realizar una búsqueda inversa de DNS con el comando dig utiliza la opción –x seguida de la dirección IP correspondiente. En el siguiente ejemplo, dig realizará una búsqueda inversa de DNS de la dirección IP asociada a google.com:

dig +answer -x 172.217.166.46

Recuerda que si un registro PTR no está definido para una dirección IP, entonces no es posible hacer una búsqueda inversa de DNS, ya que el registro PTR es el que apunta directamente al dominio o nombre de host.

Consultas por lotes

Con la herramienta dig, puedes realizar una búsqueda de DNS para una lista de dominios en lugar de hacer lo mismo para cada uno individualmente. Para esto, debes proporcionar al comando una lista de nombres de dominio, uno por línea, en un archivo. Una vez que el archivo esté listo, especifica el nombre con la opción -f:

vi nombre_dominio.txt
hostinger.com
google.com
ubuntu.com
dig -f nombre_dominio.txt +short

Control de comportamiento de Dig

El resultado arrojado por el comando se puede personalizar permanentemente configurando las opciones en el archivo ~/.digrc que se ejecuta automáticamente con el comando.

Supongamos que solo deseas ver la sección de respuestas, para esto debes especificar las opciones requeridas en el archivo ~/.digrc, para que no tengas que escribirlas mientras ejecutas la consulta.

echo "+noall +answer" > ~/.digrc

Ahora podrás realizar una búsqueda del servidor DNS para un dominio. El resultado te confirmará que dig se ejecuta con las opciones establecidas en el archivo ~/.digrc.

ПРОСТОЕ ИСПОЛЬЗОВАНИЕ

Типичный вызовкопать землю похоже:

dig @server name type

где:

сервер

это имя или IP-адрес сервера имен для запроса. Это может быть IPv4-адрес в десятичной системе с десятичной запятой или IPv6-адрес в нотации с двоеточием. Когда поставляемый сервер аргумент — имя хоста,копать землю разрешает это имя перед запросом этого сервера имен. Если нет сервер аргумент предоставляется,копать землю консультируется /etc/resolv.conf и запрашивает перечисленные там серверы имен. Отображается ответ от сервера имен, который отвечает.

название

это имя записи ресурса, которая должна быть просмотрена.

тип

указывает, какой тип запроса требуется — ANY, A, MX, SIG и т. д. тип может быть любым допустимым типом запроса. Если нет тип аргумент предоставляется,копать землю будет выполнять поиск записи A.

ОПЦИИ

-b опция устанавливает исходный IP-адрес запроса для адрес , Это должен быть действительный адрес на одном из сетевых интерфейсов хоста.

Класс запросов по умолчанию (IN для Интернета) переопределяется-с вариант. учебный класс любой допустимый класс, такой как HS для записей Hesiod или CH для записей CHAOSNET.

-f вариант делаеткопать землюработать в пакетном режиме, читая список запросов поиска для обработки из файла имя файла , Файл содержит несколько запросов, по одному на строку. Каждая запись в файле должна быть организована таким же образом, чтобы они представлялись в виде запросов ккопать землю используя интерфейс командной строки.

Если необходимо запросить номер нестандартного порта,-п используется опция. порт # это номер порта, которыйкопать землю будет отправлять свои запросы вместо стандартного номера порта DNS 53. Этот параметр будет использоваться для проверки сервера имен, который был настроен для прослушивания запросов на нестандартном номере порта.

-t опция задает тип запроса тип , Это может быть любой допустимый тип запроса, который поддерживается в BIND9. Тип запроса по умолчанию «A», если только-Икс для подачи обратного поиска. Передачу зоны можно запросить, указав тип AXFR. Когда требуется инкрементная передача зоны (IXFR) тип задано ixfr = N. Инкрементная передача зоны будет содержать изменения, внесенные в зону, поскольку серийный номер в записи SOA зоны был N .

Обратный поиск — сопоставление адресов с именами — упрощается-Икс вариант. адр является IPv4-адресом в десятичной системе с точками или адресом IPv6 с разделителем двоеточия. Когда этот параметр используется, нет необходимости предоставлять название , учебный класс а также тип аргументы.копать землю автоматически выполняет поиск имени типа 11.12.13.10.in-addr.arpa и устанавливает тип и класс запроса в PTR и IN соответственно. По умолчанию адреса IPv6 просматриваются с использованием домена IP6.ARPA и бинарных меток, как определено в RFC2874. Чтобы использовать старый метод RFC1886 с использованием доменов IP6.INT и метки «nibble», укажите-n (грызть).

Чтобы подписать DNS-запросы, отправленныекопать землю и их ответы с использованием сигнатур транзакций (TSIG), укажите ключевой файл TSIG, используя-k вариант. Вы также можете указать ключ TSIG в командной строке, используя-y вариант; название это имя ключа TSIG и ключ является фактическим ключом. Ключ представляет собой строку с кодировкой base-64, обычно генерируемуюDNSSEC-кейген(8)

Следует соблюдать осторожность при использовании-y вариант для многопользовательских систем, поскольку ключ может быть виден на выходе изп.с.(1) или в файле истории оболочки. При использовании аутентификации TSIG скопать землю, сервер имен, который запрашивается, должен знать ключ и алгоритм, который используется

В BIND это делается путем предоставления соответствующихключ а такжесервер заявления в named.conf .

Простой вывод команды dig

По-умолчанию при обычном запросе выводятся А записи, как показано ниже в выводе

$ dig google.com

; <<>> DiG 9.11.3-1ubuntu1.11-Ubuntu <<>> google.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 35727
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494
;; QUESTION SECTION:
;google.com.                    IN      A

;; ANSWER SECTION:
google.com.             73      IN      A       172.217.16.142

;; Query time: 16 msec
;; SERVER: 127.0.0.53#53(127.0.0.53)
;; WHEN: Sun Jan 05 12:00:54 +03 2020
;; MSG SIZE  rcvd: 55

Команда dig содержит следующие секции:

Заголовок (Header): Здесь отображается версия dig, глобальные параметры, используемые командой dig, и несколько дополнительных сведений о заголовке.
Секция запроса (QUESTION SECTION): Отображает вопрос, который он задал DNS. То есть это Ваш запрос.
Секция ответа (ANSWER SECTION): Отображает ответ, который он получает от DNS. A записи в нашем случае.
Секция полномочий (AUTHORITY SECTION): Здесь отображается сервер DNS, который имеет полномочия отвечать на этот запрос. Отображает доступные NS серверы для google.com в нашем случае.
Секции дополнительные (ADDITIONAL SECTION): Здесь отображается IP адреса серверов имен, перечисленных в разделе полномочия.
В секции Статистика (Stats section) внизу отображается немного информации о команде dig включая сколько времени потребовалось для выполнения этого запроса.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *