What is tftp server in linux

What is tftp server in linux

The Trivial File Transfer Protocol (TFTP) provides a minimalistic means for transferring files. It is generally used as a part of PXE booting or for updating configuration and firmware on devices which have limited memory such as routers, IP phones and printers.

Contents

Server

There are several TFTP server implementations, some are listed below and iputils also includes a version of tftp.

tftp-hpa

To modify service parameters edit /etc/conf.d/tftpd .

URL rewriting

This server includes a useful URL rewriting feature via the —map-file option ( —mapfile in some versions). It allows requests to be altered via regular expressions so the files on the server do not have to match the view the client sees, and different files can be returned to different clients even if they request the same file.

Configure a map by adding —map-file /etc/tftpd.map to /etc/conf.d/tftpd and creating a file such as this:

This example file will result in each TFTP request being prefixed with the remote IP address. For example if the machine at 192.168.0.1 requests «boot.bin» and the TFTP server root is /srv/tftp then the file /srv/tftp/192.168.0.1/boot.bin will be returned (or /srv/tftp/::ffff:192.168.0.1/boot.bin if the server is listening on an IPv6 port).

The available map file options are documented in in.tftpd(8) § FILENAME REMAPPING .

Debugging

The —verbosity 5 option can be used to turn on all debugging messages. This is very useful for diagnosing why a machine will not successfully boot from the network, as the debug messages list all requests for files, whether rewrite rules were used, where the files were read from on the filesystem and whether the request was successful or not.

It is not possible to log messages to stdout/stderr, as only syslog is supported. This means the messages can be viewed with journalctl or similar.

Источник

TFTP в Linux. Организация сервера TFTP

В репозиториях операционных систем на базе ядра Linux вы найдете множество серверов, реализующих протокол TFTP: некоторые делают упор на простоте конфигурации и малом потребление ресурсов, другие предоставляют расширенные возможности, но все они созданы с одной целью — принимать и отдавать файлы. Мы будем рассматривать настройку TFTP сервера в Linux на примере atftpd — сервера TFTP с расширенными возможностями. Будьте уверены, освоив atftpd, вы без труда справитесь с любым другим TFTP сервером в Linux.

Установка atftp в Linux

Попытка установить сервер atftpd из репозиториев приведет к установке еще одного сервера — одного из супер-серверов inet — демона, запускающего программы по событию, в данном случае по факту появления на 69 порту UDP запросов на подключение. Вы скажите: «А что же тут плохого?». Вообщем-то ничего, но если вы используете Debian версии 8 и выше или Ubuntu версии 15.04 и выше, то вы наверняка слышали о SystemD. SystemD — новый менеджер инициализации, пришедший на смену init. На конец 2015 года поддержка SystemD не реализована для серверов TFTP — мы сделаем это вручную. Поэтому, лучше устанавливать TFTP сервер из исходных текстов и сразу перейти в соответствующий раздел нашей статьи, но если вы всё же решили поизвести установку atftpd из репозиторией комадой

apt-get install atftpd

незабудьте остановить подтянувшийся inet и, собственно, сам atftpd

systemctl stop atftpd inetd

А также выключить их

systemctl disable atftpd inetd

Для избежания недоразумений также рекоменду удалить скрипт запуска atftpd из /etc/init.d/

И стереть его упоминание из конфигурационного файла inet с помощью, например редактора nano:

nano /etc/inetd.conf #удалите строчку, начинающуюся с tftp

Избежать всего этого поможет сборка TFTP сервера из исходных текстов. Для этого нужно скачать архив с исходниками например c сайта sourceforge с помощью wget

wget http://downloads.sourceforge.net/project/atftp/atftp-0.7.1.tar.gz #версия может отличаться

tar -xzvf atftp-0.7.1.tar.gz #версия может отличаться

Перейти в каталог с распакованным содержимым

cd atftp-0.7.1 #версия может отличаться

Выполнить конфигурационный скрипт, указав в качестве папки назначения /opt/atftp (вы, конечно, можете выбрать любую другую папку)

Создать эту папку

И, наконец, собранные файлы, закинуть в папку назначения

На последок почистим за собой

cd ..
rm -R atftp-0.7.1

и создадим символические ссылки на исполняемые файлы

ln -svi /opt/atftp/sbin/atftpd /sbin/
ln -svi /opt/atftp/bin/atftp /usr/bin/

Настройка TFTP сервера atftpd

TFTP сервер atftpd не читает никакой конфигурационный файл. Вместо этого все параметры ему передаются в качестве ключей запуска, например:

—logfile /PATH_TO_FLE #задает файл в который atftpd будет писать лог

—verbose=FROM_1_TO_7 # задает уровень документирования событий

—user USER.GROUP #задает от имени какого пользователя и группы будет запущен atftpd

—port PORT_NUMBER #задает UDP порт, который будет слушать сервер

—bind-address SERVER_IP_ADDRESS #задает IP адрес, который будет слушать сервер

В конце командной строки atftpd следует передать полный абсолютный путь до папки, в которой и будет осуществляться вся деятельность TFTP сервера в вашей ОС Linux

Далее мы рассмотрим несколько примеров сценариев запуска atftpd, в зависимости от которых нам понадобяться те или иные ключи запуска

Запуск atftpd из командной строки

Этот способ подойдет тем, хочет единовременно запустить TFTP сервер, отдать или принять файл и завершиться.

Минимальный набор команд будет такой:

atftpd —daemon —no-fork /mnt/share

Вы наверняка заметили два новых ключа запуска: «daemon» и «no-fork». Ключ «—daemon» заставляет atftpd «висеть» в ожидании соединения, а ключ «—no-fork» предотвращает его переход в фон. Когда все операции с передачей файлов будут завершены, мы сможете просто нажать Ctrl+C для завершения atftpd. Если же ключ «—no-fork» не использовать, то завершить процесс можно будет командой

Читайте также:  How to restart wsl linux

Стоить отметить тот факт, что чтобы папка, которую мы передали TFTP серверу для работы, была доступна не только на чтение, но и на запись, нужно выдать это право обезличенному пользователю (anonymous), так как TFTP, как протокол, вообще не предусматривает никакой аутенфикации:

chmod -R o=rwx /mnt/share #папка может отличаться

Запуск atftpd автоматически при старте системы

Если вы хотите, чтобы atftpd запускался автоматически при старте компьютера, в системах на базе SystemD следует создать в дирректории /lib/systemd/system/ unit-файл atftpd.service для SystemD вот такого минимально содержания:

[Unit]
Description=Extended TFTP server

[Service]
Type=forking
ExecStart=/opt/sbin/atftpd —daemon /mnt/share

В параметре ExecStart нужно указать ту папку и бинарный файл atftpd, в которую вы его устанавливали, а также все ключи запуска, которые считаете нужными. Заметьте, что ключ «—no-fork» в данном случае противопоказан, а вот «—daemon» обязателен, так как по сценарию планируется, что atftpd будет «висеть» в системе постоянно, ожидая соединения

После того, как файл будет создан, нужно, чтобы SystemD перечитал свою конфигурацию

а затем активировать уже сам сервис:

systemctl enable atftpd.service

Теперь atftpd будет запускаться автоматически при старте системы. Вручную его можно запускать и останавливать командами

systemctl stop atftpd.service

systemctl start atftpd.service

Запуск atftpd автоматически по запросу

Мы с вами рассмотрели ситуацию, когда TFTP сервер atftpd, запущенный единожды при старте компьютера, остается «висеть» в системе, ожидая новых подключений. При этом вначале статьи упоминули, что при установке из репозиторией atftp тянет за забой супер-сервер inet, способный запускать atftpd только тогда, когда запрос реально поступает на сервер. Это очень удобно с той точки зрения, что пока TFTP не используется — он остановлен и не потребляет системных ресурсов. Так же мы отметили тот факт, что SystemD имеет такую функциональность «из коробки», и что необходимости теперь и в самом супер-сервере inet нет. Осталось научить SystemD это делать. Для этого SystemD должен сам слушать входящий порт на предмет поступления запросов и, в случае обнаружения, запустить atftpd и отдать ему сокет. Кроме того, после обработки соединения atftpd должен еще и корректно завершиться. Чтобы SystemD стал прослушить соответствующий UDP сокет, нужно создать unit-файл, описывающий этот сокет, и положить его туда же — в /lib/systemd/system/. При этом его имя должно соответствовать имени сервис-файла, который ему придеться запускать, за исключением суффикса, который нужно поменять с «.service» на «.socket». В нашем случае файл должен называться atftpd.socket. Создадим его вот с таким содержанием:

[Unit]
Description=TFTP socker for atftpd

Запись ListenDatagram=0.0.0.0:69 означает, что SystemD будет слушать порт UDP 69 на всех доступных ему IP адресах. Вы вправе (да и так будет лучше) указать конкретный IP адрес вашего сервера — это улучшит безопасность.

Но это еще не все. Раз мы выбрали способ запуска по событию, мы не хотим более, чтобы atftpd запускался автоматически при старте системы. Выключим его:

systemctl disable atftpd.service

И сам service-файл /lib/systemd/system/atftpd.service тоже подкорректируем:

  • убираем ключ «—daemon» — мы больше не хотим, чтобы atftpd «висел» в системе постоянно
  • добавляем ключ «—tftpd-timeout 10» — TFTP сервер корректно завершиться, если в течение 10 сек. к нему не поступит более обращений
  • добавляем параметр StandartInput=socket в секцию [Service], чтобы SystemD передавал сокет с данными на вход atftpd
  • удаляем секцию [Install] целиком — мы больше не хотим, чтобы atftpd запускался при старте системы

Должно получиться что-то вроде этого:

[Unit]
Description=Extended TFTP server

[Service]
ExecStart=/opt/atftp/sbin/atftpd —verbose=7 —logfile /var/log/atftpd —tftpd-timeout 10 /mnt/share
StandardInput=socket

Не забываем перечитывать конфигурацию SystemD:

И активируем наш сокет-файл

systemctl enable atftpd.socket

Можно перезагрузиться, можно включить сокет вручную:

systemctl start atftpd.socket

netstat -lupvn | grep 69

Можно увидеть, что порт 69 прослушивает некий «init», который на самом деле является символической ссылкой на SystemD

udp 0 0 0.0.0.0:69 0.0.0.0:* 1/init

При этот, если вы обратитесь к серверу каким-нибудь tftp клиентом, SystemD запустит atftpd и передаст ему клиента. А после того, как передача файлов завершиться, atftpd по истечению таймаута корректно завершиться.

Источник

Ubuntu Documentation

A network administrator may find the need to deploy a TFTP server quickly and cost effectively. The reader may find that there is more than one TFTP server package available for Ubuntu systems.

including tftpd, atftpd, and tftpd-hpa. tftpd-hpa was chosen in this scenario because of its relative «up-to-date-ness» and availability of documentation.

Introduction

This document will guide the reader on how to setup a TFTP server that will allow clients to both download and upload files.

(This process has been completely tested and verified on 11/18/2015 using Ubuntu 14.04.3 Server and the latest version of tftpd-hpa available from the apt repositories (tftpd-hpa_5.2-7ubuntu3_amd64.deb))

Installation

Once the installation is complete, you will have a running TFTP server on your system that will be listening on all active network interfaces, on both IPv4 and IPv6. All you will be able to do is download files from the TFTP server. Uploading will not work. We will fix that in the Configuration section below.
You can confirm this by running.

The default configuration file for tftpd-hpa is /etc/default/tftpd-hpa.
The default root directory where files will be stored is /var/lib/tftpboot.

Configuration

Edit tftpd-hpa Configuration File

As mentioned before, all you will be able to do at this point is download files from the TFTP server. If you want to upload to the TFTP server, read on. To begin with, make a copy of the default tftpd-hpa configuration file.

Then, edit the tftpd-hpa configuration file.

Читайте также:  Постоянно открывается папка проводник windows 10

and change the line that reads.

and save the file and exit the vi editor.

Modify Permissions on TFTP Root Directory

The root directory where files must be stored in order to access them via TFTP is /var/lib/tftpboot. If you want to be able to upload to that directory, then perform the following command.

Restart the tftpd-hpa Service

To make the changes take effect, the tftpd-hpa service must be restarted. This can be accomplished by performing the following command.

At this point you should now have a TFTP server that allows you to both download and upload files.

Additional Information

tftpd-hpa seems to be somewhat tied to traditional tftpd. For more information try.

An external links section can be used to point users towards general information about the subject matter of the page, such as a wikipedia entry or project homepage. This section is optional.

http://chschneider.eu/linux/server/tftpd-hpa.shtml — The first «how to» that I used to go through this process.

TFTP (последним исправлял пользователь tony-fischer 2015-11-19 21:50:29)

The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details

Источник

tftpd(8) — Linux man page

tftpd — IPv4 Trivial File Transfer Protocol server

Synopsis

Description

tftpd is a server for the Trivial File Transfer Protocol. The TFTP protocol is extensively used to support remote booting of diskless devices. The server is normally started by inetd, but can also run standalone.

Options

—ipv4, -4 Connect with IPv4 only, even if IPv6 support was compiled in. —ipv6, -6 Connect with IPv6 only, if compiled in. -l, —listen Run the server in standalone (listen) mode, rather than run from inetd. In listen mode, the —timeout option is ignored, and the —address option can be used to specify a specific local address or port to listen to. —foreground, -L Similar to —listen but do not detach from the foreground process. Implies —listen. —address [address][:port], -a [address][:port] Specify a specific address and port to listen to when called with the —listen or —foreground option. The default is to listen to the tftp port specified in /etc/services on all local addresses.

Please note: Numeric IPv6 adresses must be enclosed in square brackets to avoid ambiguity with the optional port information. —create, -c Allow new files to be created. By default, tftpd will only allow upload of files that already exist. Files are created with default permissions allowing anyone to read or write them, unless the —permissive or —umask options are specified. —secure, -s Change root directory on startup. This means the remote host does not need to pass along the directory as part of the transfer, and may add security. When —secure is specified, exactly one directory should be specified on the command line. The use of this option is recommended for security as well as compatibility with some boot ROMs which cannot be easily made to include a directory name in its request. —user username, -u username Specify the username which tftpd will run as; the default is «nobody». The user ID, group ID, and (if possible on the platform) the supplementary group IDs will be set to the ones specified in the system permission database for this username. —umask umask, -U umask Sets the umask for newly created files to the specified value. The default is zero (anyone can read or write) if the —permissive option is not specified, or inherited from the invoking process if —permissive is specified. —permissive, -p Perform no additional permissions checks above the normal system-provided access controls for the user specified via the —user option. —timeout timeout, -t timeout When run from inetd this specifies how long, in seconds, to wait for a second connection before terminating the server. inetd will then respawn the server when another request comes in. The default is 900 (15 minutes.) —retransmit timeout, -T timeout Determine the default timeout, in microseconds, before the first packet is retransmitted. This can be modified by the client if the timeout or utimeout option is negotiated. The default is 1000000 (1 second.) —mapfile remap-file, -m remap-file Specify the use of filename remapping. The remap-file is a file containing the remapping rules. See the section on filename remapping below. This option may not be compiled in, see the output of in.tftpd -V to verify whether or not it is available. —verbose, -v Increase the logging verbosity of tftpd. This flag can be specified multiple times for even higher verbosity. —verbosity value Set the verbosity value to value. —refuse tftp-option, -r tftp-option Indicate that a specific RFC 2347 TFTP option should never be accepted. —blocksize max-block-size, -B max-block-size Specifies the maximum permitted block size. The permitted range for this parameter is from 512 to 65464. Some embedded clients request large block sizes and yet do not handle fragmented packets correctly; for these clients, it is recommended to set this value to the smallest MTU on your network minus 32 bytes (20 bytes for IP, 8 for UDP, and 4 for TFTP; less if you use IP options on your network.) For example, on a standard Ethernet (MTU 1500) a value of 1468 is reasonable. —port-range port:port, -R port:port Force the server port number (the Transaction ID) to be in the specified range of port numbers. —version, -V Print the version number and configuration to standard output, then exit gracefully.

Читайте также:  Preview pdf mac os

Rfc 2347 Option Negotiation

This version of tftpd supports RFC 2347 option negotation. Currently implemented options are: blksize (RFC 2348) Set the transfer block size to anything less than or equal to the specified option. This version of tftpd can support any block size up to the theoretical maximum of 65464 bytes. blksize2 (nonstandard) Set the transfer block size to anything less than or equal to the specified option, but restrict the possible responses to powers of 2. The maximum is 32768 bytes (the largest power of 2 less than or equal to 65464.) tsize (RFC 2349) Report the size of the file that is about to be transferred. This version of tftpd only supports the tsize option for binary (octet) mode transfers. timeout (RFC 2349) Set the time before the server retransmits a packet, in seconds. utimeout (nonstandard) Set the time before the server retransmits a packet, in microseconds. The —refuse option can be used to disable specific options; this may be necessary to work around bugs in specific TFTP client implementations. For example, some TFTP clients have been found to request the blksize option, but crash with an error if they actually get the option accepted by the server.

Filename Remapping

The —mapfile option specifies a file which contains filename remapping rules. Each non-comment line (comments begin with hash marks, #) contains an operation, specified below; a regex, a regular expression in the style of egrep; and optionally a replacement pattern. The operation indicated by operation is performed if the regex matches all or part of the filename. Rules are processed from the top down, and by default, all rules are processed even if there is a match.

The operation can be any combination of the following letters: r

Replace the substring matched by regex by the replacement pattern. The replacement pattern may contain escape sequences; see below.

Repeat this rule until it no longer matches. This is always used with r.

Match the regex case-insensitively. By default it is case sensitive.

If this rule matches, end rule processing after executing the rule.

If this rule matches, start rule processing over from the very first rule after executing this rule.

If this rule matches, refuse the request and send an access denied error to the client.

This rule applies to GET (RRQ) requests only.

This rule applies to PUT (WRQ) requests only.

Inverse the sense of this rule, i.e. execute the operation only if the regex doesn’t match. Cannot used together with r. The following escape sequences are recognized as part of the replacement pattern: \0

The entire string matched by the regex. \1 to \9 The strings matched by each of the first nine parenthesized subexpressions, \( . \), of the regex pattern. \i

The IP address of the requesting host, in dotted-quad notation (e.g. 192.0.2.169).

The IP address of the requesting host, in hexadecimal notation (e.g. C00002A9).

Literal backslash. \whitespace Literal whitespace. \#

Literal hash mark.

Turns all subsequent letters to upper case.

Turns all subsequent letters to lower case.

Cancels the effect of \U or \L. If the mapping file is changed, you need to send SIGHUP to any outstanding tftpd process.

Security

The use of TFTP services does not require an account or password on the server system. Due to the lack of authentication information, tftpd will allow only publicly readable files (o+r) to be accessed, unless the —permissive option is specified. Files may be written only if they already exist and are publicly writable, unless the —create option is specified. 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. Typically, some kind of firewall or packet-filter solution should be employed. If appropriately compiled (see the output of in.tftpd —version) tftpd will query the hosts_access(5) database for access control information. This may be slow; sites requiring maximum performance may want to compile without this option and rely on firewalling or kernel-based packet filters instead.

The server should be set to run as the user with the lowest possible privilege; please see the —user flag. It is probably a good idea to set up a specific user account for tftpd, rather than letting it run as «nobody», to guard against privilege leaks between applications.

Access to files can, and should, be restricted by invoking tftpd with a list of directories by including pathnames as server program arguments on the command line. In this case access is restricted to files whole names are prefixed by one of the given directories. If possible, it is recommended that the —secure flag is used to set up a chroot() environment for the server to run in once a connection has been set up.

Finally, the filename remapping (—mapfile flag) support can be used to provide a limited amount of additional access control.

Conforming To

RFC 1123, Requirements for Internet Hosts — Application and Support.
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.

Author

This version of tftpd is maintained by H. Peter Anvin . It was derived from, but has substantially diverged from, an OpenBSD source base, with added patches by Markus Gutschke and Gero Kulhman.

Источник

Оцените статью