FreeBSD 11.0 Release. Настройка TFTP-сервера tftpd-hpa.

Системным администраторам в своей работе всегда необходим локальный TFTP сервер. 

Основное назначение TFTP  (англ. Trivial File Transfer Protocol — простой протокол передачи файлов) — обеспечение простой реализации клиента. В связи с этим он используется для загрузки бездисковых рабочих станций, загрузки обновлений и конфигураций для «умных» сетевых устройств, записи статистики с мини-АТС и аппаратных маршрутизаторов и файрволов. (https://ru.wikipedia.org/wiki/TFTP)

TFTP позволяет передавать файлы с одной машины на другую без аутентификации. Несмотря на меньшую гибкость по сравнению с такими протоколами копирования файлов, как SCP или FTP, производители встраиваемых устройств (например, Cisco) по-прежнему применяют TFTP для загрузки конфигурации системы и обновлений. Мы рассмотрим здесь TFTP по той простой причине, что бездисковые клиенты используют TFTP для загрузки ядра операционной системы и получения начальной информации о конфигурации. (http://freebsdguide.ru/_15/_7/)

TFTP основан на транспортном протоколе UDP

TFTP не подходит для использования в Интернете, потому что любой желающий сможет читать и записывать файлы на сервер TFTP! Используйте TFTP исключительно за брандмауэром.

В планах поднять загрузочный сервер,типа https://habrahabr.ru/company/serverclub/blog/250549/

Немного отвлеклись, начнем:

Получаем необходимую информацию, вводим необязательные команды:

# uname -sr
FreeBSD 11.0-RELEASE-p1

Ищем нужный порт:

# whereis tftp-hpa
tftp-hpa: /usr/ports/ftp/tftp-hpa

Непосредственно даем команду на установку, я использую portmaster:

 # portmaster /usr/ports/ftp/tftp-hpa/

В итоге получаем:

Installing tftp-hpa-5.2...
===> SECURITY REPORT:
      This port has installed the following files which may act as network
      servers and may therefore pose a remote security risk to the system.
/usr/local/bin/tftp
/usr/local/libexec/in.tftpd

      This port has installed the following startup scripts which may cause
      these network services to be started at boot time.
/usr/local/etc/rc.d/tftpd

      If there are vulnerabilities in these programs there may be a security
      risk to the system. FreeBSD makes no guarantee about the security of
      ports included in the Ports Collection. Please type 'make deinstall'
      to deinstall the port if this is a concern.

===>>> Installation of ftp/tftp-hpa (tftp-hpa-5.2) complete

Разрешаем запуск TFTPD сервера, передаем необходимые настройки. Для этого добавляем в файл /etc/rc.conf следующие строки:

#ee /etc/rc.conf

tftpd_enable="YES"
tftpd_flags="--ipv4 --secure --create --user tftpd --umask 027 --permissive --address 0.0.0.0:69 /var/tftp"

В настройках указаны дополнительные опции:

—create — разрешает серверу создавать новые файлы,
—ipv4 — предписывает ему ожидать подключений только на адресах IPv4,
—umask — предписывает сбрасывать бит записи для группы и все биты доступа для остальных пользователей,
—permissive — предписывает не проводить никаких проверок прав доступа к файлу сверх производимых операционной системой.

Необходимо создать группу и пользователя, от имени которых будет работать TFTP-демон:

# pw groupadd tftpd
# pw useradd tftpd -c tftp_manager -d /nonexistent -g tftpd -s /usr/sbin/nologin
pw: user 'tftpd' disappeared during update

Выдало ошибку, нашел решение (http://unix.derkeiler.com/Mailing-Lists/FreeBSD/current/2005-02/0637.html):

# pwd_mkdb -p /etc/master.passwd

(http://pascal.tsu.ru/unix/users/users5.html#pwd_mkdb)

# pw useradd tftpd -c tftp_manager -d /nonexistent -g tftpd -s /usr/sbin/nologin
pw: login name `tftpd' already exists
# pw user del tftpd
# pw useradd tftpd -c tftp_manager -d /nonexistent -g tftpd -s /usr/sbin/nologin
pw: group `tftpd' does not exist
# pw groupadd tftpd
# pw useradd tftpd -c tftp_manager -d /nonexistent -g tftpd -s /usr/sbin/nologin

Вот так получилось.

Проверяем все ли создалось:

# vipw
...
tftpd:*:1004:1003::0:0:tftp_manager:/nonexistent:/usr/sbin/nologin
...

Выход из текстового редактора vi :q + ввод.

По-умолчанию все протоколирование будет вестись в файл лог /var/log/xferlog.

Теперь создаем каталог для хранения файлов, устанавливаем необходимые права доступа:

# mkdir /var/tftp
# chown tftpd:tftpd /var/tftp
# chmod u=rwx,g=rx,o= /var/tftp

Запускаем TFTP-демона:

# service tftpd start
Starting tftpd.

Проверяем запустился ли сервис демон:

# ps -x | grep tftp | grep -v grep
54891 - Is 0:00,00 /usr/local/libexec/in.tftpd --ipv4 --secure --create --user tftpd --umask 027 --permissive --address 0.0.0.0:69 /var/tftp -P /var/run/tftpd.pid -l

—-

Если у вас работает файервол, надо разрешить в его настройках доступ к вашему tftp-серверу. Если используете pf, то так:

#tftp
pass in quick on $int_if proto {tcp,udp} from $int_net to $int_addr port 69
pass in quick on $int_if proto {tcp,udp} from $int_net to $int_addr port {1024:65535}
pass in quick on $ext_if proto {tcp,udp} from $some_host to $ext_addr port 69
pass in quick on $ext_if proto {tcp,udp} from $some_host to $ext_addr port {1024:65535}

Где:

  • $int_if – внутренний интерфейс сервера;
  • $ext_if – внешний интерфейс сервера;
  • $int_net – внутренняя сеть (которой вы доверяете);
  • $int_addr – внутренний ip-адрес;
  • $ext_addr – внешний ip-адрес;
  • $some_host – некоторый внешний хост, который будет работать с вашим tftp-сервером.

Документация по TFTPD

TFTPD(8) FreeBSD System Manager’s Manual TFTPD(8)

NAME
tftpd – Internet Trivial File Transfer Protocol server

SYNOPSIS
tftpd [-cdClnow] [-F strftime-format] [-s directory] [-u user] [-U umask]
[directory …]

DESCRIPTION
The tftpd utility is a server which supports the Internet Trivial File
Transfer Protocol (RFC 1350). The TFTP server operates at the port
indicated in the ‘tftp’ service description; see services(5). The server
is normally started by inetd(8).

The use of tftp(1) does not require an account or password on the remote
system. Due to the lack of authentication information, tftpd will allow
only publicly readable files to be accessed. Files containing the string
“/../” or starting with “../” are not allowed. Files may be written only
if they already exist and are publicly writable. Note that this extends
the concept of “public” to include all users on all hosts that can be
reached through the network; this may not be appropriate on all systems,
and its implications should be considered before enabling tftp service.
The server should have the user ID with the lowest possible privilege.

Access to files may be restricted by invoking tftpd with a list of
directories by including up to 20 pathnames as server program arguments
in inetd.conf(5). In this case access is restricted to files whose names
are prefixed by the one of the given directories. The given directories
are also treated as a search path for relative filename requests.

The -s option provides additional security by changing the root directory
of tftpd, thereby prohibiting accesses to outside of the specified
directory. Because chroot(2) requires super-user privileges, tftpd must
be run as root. However, after performing the chroot(2) call, tftpd will
set its user ID to that of the specified user, or “nobody” if no -u
option is specified.

The options are:

-c Changes the default root directory of a connecting host via
chroot(2) based on the connecting IP address. This prevents
multiple clients from writing to the same file at the same time.
If the directory does not exist, the client connection is
refused. The -s option is required for -c and the specified
directory is used as a base.

-C Operates the same as -c except it falls back to directory
specified via -s if a directory does not exist for the client’s
IP.

-F Use this strftime(3) compatible format string for the creation of
the suffix if -W is specified. By default the string «%Y%m%d» is
used.

-d, -d [value]
Enables debug output. If value is not specified, then the debug
level is increased by one for each instance of -d which is
specified.

If value is specified, then the debug level is set to value. The
debug level is a bitmask implemented in
src/libexec/tftpd/tftp-utils.h. Valid values are 0 (DEBUG_NONE),

1 (DEBUG_PACKETS), 2, (DEBUG_SIMPLE), 4 (DEBUG_OPTIONS), and 8
(DEBUG_ACCESS). Multiple debug values can be combined in the
bitmask by logically OR’ing the values. For example, specifying
-d 15 will enable all the debug values.

-l Log all requests using syslog(3) with the facility of LOG_FTP.
Note: Logging of LOG_FTP messages must also be enabled in the
syslog configuration file, syslog.conf(5).

-n Suppress negative acknowledgement of requests for nonexistent
relative filenames.

-o Disable support for RFC2347 style TFTP Options.

-s directory
Cause tftpd to change its root directory to directory. After
doing that but before accepting commands, tftpd will switch
credentials to an unprivileged user.

-u user
Switch credentials to user (default “nobody”) when the -s option
is used. The user must be specified by name, not a numeric UID.

-U umask
Set the umask for newly created files. The default is 022
(S_IWGRP | S_IWOTH).

-w Allow write requests to create new files. By default tftpd
requires that the file specified in a write request exist. Note
that this only works in directories writable by the user
specified with -u option

-W As -w but append a YYYYMMDD.nn sequence number to the end of the
filename. Note that the string YYYYMMDD can be changed with the
-F option.

SEE ALSO
tftp(1), chroot(2), syslog(3), inetd.conf(5), services(5),
syslog.conf(5), inetd(8)

The following RFC’s are supported:

RFC 1350: The TFTP Protocol (Revision 2).

RFC 2347: TFTP Option Extension.

RFC 2348: TFTP Blocksize Option.

RFC 2349: TFTP Timeout Interval and Transfer Size Options.

The non-standard rollover and blksize2 TFTP options are mentioned here:

Extending TFTP, http://www.compuphase.com/tftp.htm.

HISTORY
The tftpd utility appeared in 4.2BSD; the -s option was introduced in
FreeBSD 2.2, the -u option was introduced in FreeBSD 4.2, the -c option
was introduced in FreeBSD 4.3, and the -F and -W options were introduced
in FreeBSD 7.4.

Support for Timeout Interval and Transfer Size Options (RFC2349) was
introduced in FreeBSD 5.0, support for the TFTP Blocksize Option
(RFC2348) and the blksize2 option was introduced in FreeBSD 7.4.

Edwin Groothuis <edwin@FreeBSD.org> performed a major rewrite of the
tftpd and tftp(1) code to support RFC2348.

NOTES
Files larger than 33,553,919 octets (65535 blocks, last one <512 octets)
cannot be correctly transferred without client and server supporting
blocksize negotiation (RFCs 2347 and 2348), or the non-standard TFTP
rollover option. As a kludge, tftpd accepts a sequence of block number
which wrap to zero after 65535, even if the rollover option is not
specified.

Many tftp clients will not transfer files over 16,776,703 octets (32767
blocks), as they incorrectly count the block number using a signed rather
than unsigned 16-bit integer.

FreeBSD 11.0-RELEASE-p1 June 22, 2011 FreeBSD 11.0-RELEASE-p1


Полезные ссылки:

Инструкция по настройке TFTP

Настройка TFTP-сервера tftpd-hpa во FreeBSD

FreeBSD — развертывание сервера для сетевой загрузки

Сервер сетевой загрузки (PXE) на Freebsd ч.1 — Настройка сервера

Загрузочный сервер — как загрузочная флешка, только сервер и по сети

Живительная флешка