Linux – ntpd

por | 28 octubre, 2015

ntpd pertenece a una suite de utilidades Linux usadas para la operación NTP. Estas utilidades son:

ntp-wait es útil durante el arranque para detener la secuencia de inicio hasta que ntpd ha establecido la hora. ntp-wait espera hasta que se produzca la primera sincronización con un servidor ntp por parte del demonio ntpd para continuar. ntp-wait es un scrip hecho en Perl, que se instalaba originalmente con el metapaquete de ntp. Luego estubo disponible como paquete ntp-perl.

El equivalente a utilizar actualmete es «ntpd –wait-sync» el cual hace que ntpd se demonice como proceso hijo pero el proceso padre no retorna inmediatamente sino que espera a que exista la primera sincronización o expire un timeout.

ntptrace traza el camino de servidores NTP hasta la fuente primaria.

ntpd es un demonio NTP que se ejecuta en segundo plano y mantiene sincronizada la fecha y la hora basandose en la respuesta de los servidores NTP configurados. También actua como servidor NTP.

ntpdate es un cliente que establece la fecha y la hora basandose en la respuesta de un servidor NTP. Este comando es obsoleto. ntpdate efectúa una sincronización de tipo «one-shot», sincroniza una vez y sale de la aplicación. En su lugar se debe utilizar ntpd -q el cual sincroniza y sale sin demonizar.

ntpdc se usa para consultar el estado actual del demonio NTP y solicitar cambios en dicho estado.

ntpq es una utilidad usada para monitorizar las operaciones de ntpd y determinar el rendimiento.

ntptime lee y muestra las variables del núcleo relacionadas con el tiempo.

tickadj lee, y opcionalmente modifica, varias variables relacionas con el almacenamiento del tiempo en los núcleos antiguos que no tienen soporte para almacenaje del tiempo con precisión.

ntp-genkeys genera los ficheros de datos criptográficos usados por los esquemas de autenticación y de identificación de NTPv4.

ntpd es un programa que actúa en modo demonio y sirve para configurar y mantener la hora y fecha del sistema en sincronismo con un servidor NTP. ntpd actúa en el reloj del sistema, no actualiza el reloj hardware local (para ello usar una orden hwclock con la opción –systohc) sino la referencia horaria del sistema.

ntpd intercambia mensajes, mediante protocolo NTP con uno o varios servidores a determinados intervalos (poll intervals). A partir de que el demonio arranca se efectúan varios intercambios de mensajes entre él y los servidores disponibles. Para evitar la sobrecarga de la red este intervalo se incrementa posteriormente y se vuelva aleatorio en varios segundos. El intervalo inicial es de 64 seg. Pueden pasar varios minutos antes de que se configure el reloj. El retraso inicial que se comenta puede ser reducido usando la opción iburst.

Una vez que la máquina que ejecuta ntpd se ha sincronizado contra un servidor, el sistema operativo corrige en chip del reloj (el RTC o también llamado chip time-of-year (TOY)) paso a paso. En caso de que no exista este chip o marque una diferencia de más 1000 segundos con respecto al tiempo del servidor, ntpd lo toma como situación de error y no se configura el reloj, el operador deberá ajustarlo a mano. La opción –g permite evitar este chequeo y el rejoj se ajustará a la hora del servidor sin importar el tiempo del chip. No obstante y como protección contra fallos de hardware o de la batería del reloj una vez que el reloj se ha ajustado un error de más de 1000 segundos causará que ntpd termine de todas maneras.

En circunstancias normales ntpd ajusta la hora en pequeños pasos para evitar las discontinuidades. Los algoritmos ntpd descartan “sample offsets” (offsets de muestreos o más bien diferencias con las lecturas) de más de 128 ms. El offset es la diferencia de la lectura del servidor con el valor local que se tiene en ese momento. A menos que el intervalo durante el cual no hay valores de offsets de muestreos menores de 128 ms exceda de 900s. Después del primer muestreo no importa el offset, se pasa el reloj a la hora indicada. Esto reduce el ratio de falsas alarmas

Una vez sincronizado, en circunstancias normales es muy improbable que se den desincronizaciones de más de 128 ms, incluso en circunstancias de congestión de red.

Hay veces, sobre todo en la primera sincronización, en la que se puede dar un salto hacia atrás en el cliente, porque esté adelantado con respecto al servidor. Esto hay veces que no es aceptable para el cliente. Si especificamos la opción –x el reloj se ajustará siempre mediante pasos consecutivos para evitar esto.

El archivo ntp.drift contiene la última estimación del error de la frecuencia del reloj. Cuando ntpd arranca y este archivo no existe, ntpd entra en un modo especial para intentar adaptarse rápidamente al error particular de frecuencia y tiempo del oscilador del reloj. Esto dura aproximadamente 15 minutos tras los cuales el demonio entra en su modo normal de funcionamento, en donde el tiempo y frecuencia son continuamente monitorizados relativos al servidor. Después de una hora el archivo de frecuencias se crea y el offset de frecuencia acatual se graba en él. Cuando ntpd arranca y el archivo existe, la frecuencia ntpd se inicializa desde el fichero y entra en modo normal de funcionamiento. Posteriormente el offtset de frecuencia actual se actualiza al archivo cada hora.

ntpd se ejecuta por defecto en modo contínuo interrogando a los servidores disponibles a intervalos determinados de manera compleja. El equipo mide las fluctuaciones y retardos imprevistos y la frecuencia del oscilador y determina en mejor intervalo de sondeo usando un algoritmo heurístico. Habitualmente, dependiendo del entorno operativo, este intervalo comienza siendo 64 seg. y se va incrementando en pasos de 1024 seg. Una pequeña variación aleatoria se introduce en dicho intervalo de lecturas a fin de evitar saturación en momentos puntuales. Además si un servidor de vuelve inalcanzable, el intervalo de sondeo se incrementa en pasos de 1024 seg. para reducir la sobrecarga de red.

ntpd puede ser ejecutado en modo comando en vez de en modo dominio usando la opción -q. Es algo similar al comando ntpdate. Pero ntpdate no tiene procesamiento de errores ni el proceso de señales ni usa los algoritmos de ntpd. Con la opción –q, ntpd sale de ejecución una vez que ha conseguido configurar el reloj por primera vez. El procedimiento para la configuración inicial del reloj es el mismo que en modo demonio.

Para muchas aplicaciones puede ser útil especificar la opción iBurst con la cual una andanada de mensajes con intercambiados y el reloj queda configurado en unos 10 seg. Si no hay respuesta del servidor en 2 seg. el demonio da timeout y sale de ejecución. Después de un periodo del luto adecuado ntpdate sera abandonado.

Otra característica de ntpd es funcionar en un modo que se podría llamar de gestión de frecuencia del reloj. Esto es posible con sistemas cuyo núcleo soporte el ajuste de frecuencia de reloj, como Solaris y Linux. Primero ntpd se ejecuta en modo demonio al objeto de medir y registrar el desplazamiento intrínseco de la frecuencia. Pueden pasar varias horas hasta que se establezca la frecuencia y el archivo de compensación. Entonces el ntpd se detiene y se ejecuta en modo one-time cuando sea requerido. En cada arranque la frecuencia se lee desde el archivo y se inicializa la frecuencia en el núcleo.

Sintaxis

ntpd [ -46aAbdDgLnNqx ] [ -c conffile ] [ -f driftfile ] [ -i jaildir ] [ -k keyfile ] [ -l logfile ] [ -p pidfile ] [ -P priority ] [ -r broadcastdelay ] [-s statsdir ] [ -t key ] [ -u user[:group] ] [ -v variable ] [ -V variable ]

Opciones en línea de comandos

-4     Force DNS resolution of host names to the IPv4 namespace.
-6     Force DNS resolution of host names to the IPv6 namespace.
-a     Require cryptographic authentication for broadcast client, multicast client and symmetric passive associations. This is the default.
-A     Do not require cryptographic authentication for broadcast client, multicast client and symmetric passive associations. This is almost never a good idea.
-b     Enable the client to synchronize to broadcast servers.
-c conffile Specify   the   name and path of the configuration file, default /etc/ntp.conf.
-d     Specify debugging mode. This option may occur more than once, with each occurrence indicating greater detail of display.
-D level Specify debugging level directly.
-f driftfile Specify the name and path of the frequency file. This is the same operation as the driftfile driftfile configuration command.
-g     Normally, ntpd exits with a message to the system log if the offset exceeds the panic threshold, which is 1000 s by default. This option allows the time to be set to any value without restriction; however, this can happen only once. If the threshold is exceeded after that, ntpd will exit with a message to the system log. This option can be used with the -q and -x options. See the tinker command for other options.
-i jaildir Chroot the server to the directory jaildir. This option also implies that the server attempts to drop root privileges at startup (otherwise,chroot gives very little additional security). You may need to also specify a -u option.
-k keyfile Specify   the name and path of the symmetric key file, default /etc/ntp/keys. This is the same operation as the keys keyfile configuration command.
-l logfile Specify the name and path of the log file. The default is the system log file. This is the same operation as the logfile logfile configuration command.
-L     Do not listen to virtual IPs. The default is to listen.
-n     Don’t fork.
-N     To the extent permitted by the operating system, run the ntpd at the highest priority.
-p pidfile Specify the name and path of the file used to record the ntpd proces ID. This is the same operation as the pidfile pidfile configuration command.
-P priority To the extent permitted by the operating system, run the ntpd at the specified priority.
-q     Exit the ntpd just after the first time the clock is set. This behavior mimics that of the ntpdate program, which is to be retired. The -g and -x options can be used with this option. Note: The kernel time discipline is disabled with this option.
-r broadcastdelay Specify the default propagation delay from the broadcast/multicast server to this client. This is necessary only if the delay cannot be computed automatically by the protocol.
-s statsdir Specify the directory path for files created by the statistics facility. This is the same operation as the statsdir statsdir configuration command.
-t key Add a key number to the trusted key list. This option can occur more than once.
-u user[:group] Specify a user, and optionally a group, to switch to.
-v variable
-V variable Add a system variable listed by default.
-x     Normally, the time is slewed if the offset is less than the step threshold, which is 128 ms by default, and stepped if above the thresh-old. This option sets the threshold to 600 s, which is well within the accuracy window to set the clock manually. Note: Since the slew rate of typical Unix kernels is limited to 0.5 ms/s, each second of adjustment requires an amortization interval of 2000 s. Thus, an adjustment as much as 600 s will take almost 14 days to complete. This option can be used with the -g and -q options. See the tinker command for other options. Note: The kernel time discipline is disabled with this option.

El archivo ntp.conf

ntpd lee por defecto el archivo de configuración /etc/ntp.conf cuando arranca el demonio. En este archivo se le puede indicar modos de funcionamiento, fuentes de sincronización, etc. El archivo consiste en una serie de palabras clave iniciales seguida de una serie de argumentos separados por espacios. Los comandos no pueden continuar en la línea siguiente. A continuación se describen las opciones más importantes.

restrict

La opción restrict sirve para controlar qué máquinas pueden acceder al servicio NTP que proporciona ntpd. La sintaxis es:

restrict [Host o rango IP] [opciones]

Host o rango IP especifica el host o la red IP afectada por el comando.

Las opciones pueden ser:

ignore

Deniega todos los paquetes, incluyendo peticiones ntpq y ntpdc.

kod

If this flag is set when an access violation occurs, a kiss-o’-death (KoD) packet is sent. KoD packets are rate limited to no more than one per second. If another KoD packet occurs within one second after the last one, the packet is dropped

limited

Deny service if the packet spacing violates the lower limits specified in the discard command. A history of clients is kept using the monitoring capability of ntpd. Thus, monitoring is always active as long as there is a restriction entry with the limited flag.

lowpriotrap

Declare traps set by matching hosts to be low priority. The number of traps a server can maintain is limited (the current limit is 3). Traps are usually assigned on a first come, first served basis, with later trap requestors being denied service. This flag modifies the assignment algorithm by allowing low priority traps to be overridden by later requests for normal priority traps.

nomodify

Deny ntpq and ntpdc queries which attempt to modify the state of the Server (i.e., run time reconfiguration). Queries which return information are permitted.

noquery

Deny ntpq and ntpdc queries. Time service is not affected.

nopeer

Deny packets which would result in mobilizing a new association. This includes broadcast, symmetric-active and manycast client packets when a configured association does not exist.

noserve

Deny all packets except ntpq and ntpdc queries.

notrap

Decline to provide mode 6 control message trap service to matching hosts. The trap service is a subsystem of the ntpdq control message protocol which is intended for use by remote event logging programs.

notrust

Deny packets unless the packet is cryptographically authenticated.

ntpport

This is actually a match algorithm modifier, rather than a restriction flag. Its presence causes the restriction entry to be matched only if the source port in the packet is the standard NTP UDP port (123). Both ntpport and non-ntpport may be specified. The ntpport is considered more specific and is sorted later in the list.

versión

Deniega paquetes que no concuerdan con la versión actual de NTP.

Ejemplos:

restrict default ignore     Deniega el acceso a todo por defecto

restrict 192.168.1.0 mask 255.255.255.0 notrust nomodify notrap

Asociaciones: server, peer, broadcast, manycastclient

En todos los casos la sintaxis es

  comando address [options ...]

server

El comando server especifica qué servidores se van a utilizar para sincronizar contra ellos, anotando un servidor por línea. Si se especifica un servidor con el argumento prefer dicho servidor se prefiere sobre los demás. No obstante la respuesta de su servidor preferido se descartará si difiere sustancialmente de la respuesta recibida por parte del resto de los servidores especificados; en caso contrario sólo se tendrá en cuenta la respuesta del servidor preferido sin importar la información suministrada por el resto (ver opciones).

Ejemplos:

server es.pool.ntp.org maxpool 12         # area del paísserver europe.pool.ntp.org maxpool 12     # area del continente

peer

En el modo peer cada uno de los servidores puede sincronizar con el otro según la precisión de sus relojes. El servidor con menor precisión sincronizará contra el de mayor precisión y se pondrá un stratum inferior.

broadcast

For type b and m addresses (only), this command mobilizes a persistent broadcast mode association. Multiple commands can be used to specify multiple local broadcast interfaces (subnets) and/or multiple multicast groups. Note that local broadcast messages go only to the interface associated with the subnet specified, but multicast messages go to all interfaces.

In broadcast mode the local server sends periodic broadcast messages to a client population at the address specified, which is usually the broadcast address on (one of) the local network(s) or a multicast address assigned to NTP. The IANA has assigned the multicast group address IPv4 224.0.1.1 and IPv6 ff05::101 (site local) exclusively to NTP, but other nonconflicting addresses can be used to contain the messages within administrative boundaries. Ordinarily, this specification applies only to the local server operating as a sender; for operation as a broadcast client, see the broadcastclient or multicastclient commands below.

manycastclient

Permite sincronizar contra un servidor NTP mediante un grupo multicast. Es decir, se efectúa una suscripción a un grupo multicast. (el servidor tendría un comando de tipo manycastserver). El servidor remoto es descubierto mediante mensajes broadcast/multicast. El cliente selecciona al servidor con mejor tiempo.

Las opciones para todas estas asociaciones son:

autokey

All packets sent to and received from the server or peer are to include authentication fields encrypted using the autokey scheme described in the Authentication Options page. This option is valid with all commands.

burst

When the server is reachable, send a burst of eight packets instead of the usual one. The packet spacing is normally 2 s; however, the spacing between the first and second packets can be changed with the calldelay command to allow additional time for a modem or ISDN call to complete. This option is valid with only the server command and is a recommended option with this command when the maxpoll option is 11 or greater.

iburst

When the server is unreachable, send a burst of eight packets instead of the usual one. The packet spacing is normally 2 s; however, the spacing between the first and second packets can be changed with the calldelay command to allow additional time for a modem or ISDN call to complete. This option is valid with only the server command and is a recommended option with this command.

key key

All packets sent to and received from the server or peer are to include authentication fields encrypted using the specified key identifier with values from 1 to 65534, inclusive. The default is to include no encryption field. This option is valid with all commands.

minpoll minpoll

maxpoll maxpoll

These options specify the minimum and maximum poll intervals for NTP messages, in seconds as a power of two. The maximum poll interval defaults to 10 (1,024 s), but can be increased by the maxpoll option to an upper limit of 17 (36.4 h). The minimum poll interval defaults to 6 (64 s), but can be decreased by the minpoll option to a lower limit of 4 (16 s). These option are valid only with the server and peer commands.

noselect

Marks the server as unused, except for display purposes. The server is discarded by the selection algorithm. This option is valid only with the server and peer commands.

preempt

Specifies the association as preemptable rather than the default persistent. This option is valied only with the server command.

prefer

Marks the server as preferred. All other things being equal, this host will be chosen for synchronization among a set of correctly operating hosts. See the Mitigation Rules and the prefer Keyword page for further information. This option is valid only with the server and peer commands.

true

Force the association to assume truechimer status; that is, always survive the selection and clustering algorithms. This option can be used with any association, but is most useful for reference clocks with large jitter on the serial port and precision pulse-per-second (PPS) signals. Caution: this option defeats the algorithms designed to cast out falsetickers and can allow these sources to set the system clock. This option is valid only with the server and peer commands.

ttl ttl

This option is used only with broadcast server and manycast client modes. It specifies the time-to-live ttl to use on broadcast server and multicast server and the maximum ttl for the expanding ring search with manycast client packets. Selection of the proper value, which defaults to 127, is something of a black art and should be coordinated with the network administrator.

version version

Specifies the version number to be used for outgoing NTP packets. Versions 1-4 are the choices, with version 4 the default. This option is valid only with the server, peer and broadcast commands.

Existen además otros comandos que se podrían considerar auxiliares:

broadcastclient

multicastclient

manycastserver

fudge

driftfile

La opción driftfile especifica qué fichero se utiliza para almacenar el desplazamiento de la frecuencia de reloj de la máquina. El programa ntpd utiliza este valor para automáticamente compensar el desvío que experimenta de forma natural el reloj de la máquina, permitiendo mantener una precisión acotada incluso cuando se pierde la comunicación con el resto de referencias externas.

El archivo driftfile tambiés se utiliza para almacenar la información sobre respuestas anteriores de servidores NTP. Este fichero contiene información útil para la implementación de NTP. No debería ser modificada por ningún otro proceso.

keys

trustedkey

requestkey

controlkey

 

 

 

 

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *