Настройте свой собственный DNS-сервер с открытым исходным кодом

Возьмите под контроль свою конфиденциальность в Интернете, запустив собственный DNS-сервер с проектом с открытым исходным кодом Adguard Home.

Сервер доменных имен (DNS) связывает доменное имя (например, example.com) с IP-адресом (например, 93.184.216.34). Таким образом ваш веб-браузер узнает, где в мире искать данные, когда вы вводите URL-адрес или когда поисковая система возвращает URL-адрес для посещения. DNS очень удобен для пользователей Интернета, но не лишен недостатков. Например, платная реклама появляется на веб-страницах, потому что ваш браузер естественным образом использует DNS для определения того, где эта реклама «живет» в Интернете. Точно так же программное обеспечение, которое отслеживает ваше перемещение в Интернете, часто активируется службами, разрешаемыми через DNS. Вы не хотите полностью отключать DNS, потому что это очень полезно. Но вы можете запустить свою собственную службу DNS, чтобы лучше контролировать ее использование.

Я считаю жизненно важным, чтобы вы запускали свой собственный DNS-сервер, чтобы вы могли блокировать рекламу и сохранять конфиденциальность вашего просмотра, вдали от провайдеров, пытающихся проанализировать ваши онлайн-взаимодействия. Я использовал Pi-hole в прошлом и до сих пор рекомендую его. Однако в последнее время я запускаю проект с открытым исходным кодом Adguard Home в своей сети. Я обнаружил, что у него есть некоторые уникальные особенности, которые стоит изучить.

Адгард Главная

Из вариантов DNS с открытым исходным кодом, которые я использовал, Adguard Home является самым простым в настройке и обслуживании. Вы получаете множество решений для разрешения DNS, таких как DNS через TLS, DNS через HTTPS и DNS через QUIC, в рамках одного проекта.

Вы можете настроить Adguard как контейнер или как нативный сервис с помощью одного скрипта:

$ curl -s -S -L \
https://raw.githubusercontent.com/AdguardTeam/AdGuardHome/master/scripts/install.sh

Посмотрите на скрипт, чтобы понять, что он делает. Как только вы освоитесь с процессом установки, запустите его:

$ sh ./install.sh

Некоторые из моих любимых функций AdGuard Home:

Простой интерфейс администратора

Блокируйте рекламу и вредоносное ПО с помощью черного списка Adguard

Параметры для индивидуальной настройки каждого устройства в вашей сети

Принудительный безопасный поиск на определенных устройствах

Установите HTTPS для интерфейса администратора, чтобы ваше удаленное взаимодействие с ним было полностью зашифровано.

Я считаю, что Adguard Home экономит мое время. Его списки блокировки более надежны, чем у Pi-hole. Вы можете быстро и легко настроить его для запуска DNS через HTTPS.

Больше никаких вредоносных программ

Вредоносное ПО — это нежелательный контент на вашем компьютере. Это не всегда непосредственно опасно для вас, но может привести к опасным действиям для третьих лиц. Интернет никогда не предназначался для этого. Я считаю, что вы должны разместить свой собственный DNS-сервис, чтобы сохранить вашу интернет-историю конфиденциальной и недоступной для известных трекеров, таких как Microsoft, Google и Amazon. Попробуйте Adguard Home в своей сети.

Оригинальный источник статьи:   https://opensource.com/

#dns #server #opensource 

Настройте свой собственный DNS-сервер с открытым исходным кодом
津田  淳

津田 淳

1678918860

设置您自己的开源 DNS 服务器

通过使用开源项目 Adguard Home 运行您自己的 DNS 服务器来控制您的互联网隐私。

域名服务器 (DNS) 将域名(如 example.com)与 IP 地址(如 93.184.216.34)相关联。这就是当您输入 URL 或搜索引擎返回 URL 供您访问时,您的网络浏览器如何知道在世界的哪个地方寻找数据。DNS 为互联网用户提供了极大的便利,但也并非没有缺点。例如,付费广告会出现在网页上,因为您的浏览器自然会使用 DNS 来解析这些广告在互联网上“存在”的位置。同样,跟踪您在线活动的软件通常由通过 DNS 解析的服务启用。您不想完全关闭 DNS,因为它非常有用。但是您可以运行自己的 DNS 服务,以便更好地控制它的使用方式。

我认为您运行自己的 DNS 服务器至关重要,这样您就可以阻止广告并保持您的浏览隐私,远离试图分析您的在线交互的提供商。我过去用过Pi-hole ,今天仍然推荐它。然而,最近,我一直在我的网络上运行开源项目Adguard Home。我发现它有一些值得探索的独特功能。

Adguard 主页

在我使用过的开源 DNS 选项中,Adguard Home是最容易设置和维护的。您可以在一个项目中获得许多 DNS 解析解决方案,例如 DNS over TLS、DNS over HTTPS 和 DNS over QUIC。

您可以使用单个脚本将 Adguard 设置为容器或本地服务:

$ curl -s -S -L \
https://raw.githubusercontent.com/AdguardTeam/AdGuardHome/master/scripts/install.sh

查看脚本以便了解它的作用。熟悉安装过程后,运行它:

$ sh ./install.sh

我最喜欢 AdGuard Home 的一些功能:

一个简单的管理界面

使用 Adguard 阻止列表阻止广告和恶意软件

单独配置网络上每个设备的选项

强制在特定设备上进行安全搜索

为管理界面设置 HTTPS,因此您的遥控器与其交互是完全加密的

我发现 Adguard Home 为我节省了时间。它的黑名单比 Pi-hole 上的黑名单更强大。您可以快速轻松地将其配置为通过 HTTPS 运行 DNS。

没有更多的恶意软件

恶意软件是您计算机上不需要的内容。它并不总是对您有直接危险,但它可能会为第三方带来危险活动。这不是互联网曾经打算做的。我认为您应该托管自己的 DNS 服务,以保护您的互联网历史记录的私密性,并避免被 Microsoft、Google 和 Amazon 等已知跟踪器掌握。在您的网络上试用 Adguard Home。

文章原文出处:https:   //opensource.com/

#dns #server #opensource 

设置您自己的开源 DNS 服务器

Как установить, настроить и поддерживать DNS-сервер Linux

DNS ( система доменных имен ) — это система именования компьютеров, служба, которая делает это, — это DNS-сервер, который переводит IP-адрес в удобочитаемый адрес.

Этот процесс является основой Интернета и очень важной службой на вашем сервере, поэтому с этого момента мы обсудим DNS-сервер или, в частности, DNS-сервер Linux, а также способы его установки, настройки и обслуживания.

Файл /etc/hosts

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

В системах Linux эта таблица находится в файле /etc/hosts .

Таким образом, даже если у вас нет DNS-сервера или DNS-сервер недоступен, этот файл может преобразовывать IP-адреса в имена с помощью файла /etc/hosts.

Это означает, что система сначала запрашивает этот файл перед переходом к DNS-серверу, и если она находит домен, она переводит его, не обращаясь к каким-либо DNS-серверам.

Попробуйте отредактировать /etc/hosts и ввести следующее:

127.0.0.1              google.com

Затем перейдите в браузер, введите google.com и посмотрите результаты. Если в вашей системе установлен сервер Apache и работает ваш локальный хост, вместо страницы Google будет отображаться индексная страница локального хоста.

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

Итак, что делает этот файл, так это переводит IP-адреса в имена, но это для той же подключенной сети. Так что насчет внешних сетей и как вести все эти записи для всех систем?

Будет ли каждый управлять своим файлом /etc/hosts и обновлять его самостоятельно? Конечно, нет.

Доменные имена

Когда вы посещаете веб-сайт, вы вводите полное доменное имя (полное доменное имя) или доменное имя, подобное этому: likegeeks.com или www.google.com.

Каждый домен состоит из компонентов домена; точка разделяет эти компоненты.

Текст com — это компонент домена верхнего уровня, google компонент домена второго уровня, а wwwкомпонент домена третьего уровня.

Когда вы посещаете любой веб-сайт, браузер молча добавляет точку в конце, но не виден вам, поэтому домен будет выглядеть как www.google.com. Обратите внимание на точку после .com; эта точка называется корневым доменом.

Но почему мы добавили этот корневой домен или точку?

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

А почему 13?

Потому что землетрясение или стихийное бедствие, случившееся в одном месте в мире, может разрушить корневой сервер, поэтому остальные будут работать до тех пор, пока поврежденный сервер не вернется в сеть.

Эти корневые серверы имен имеют такие имена: a.root-server.net, b.root-server.net и т. д.

Доменные имена верхнего уровня (TLD)

Мы видели компонент домена верхнего уровня, такой как домены com.

Домены верхнего уровня (TLD) делятся на категории на основе географических или функциональных аспектов.

На момент написания этой статьи в сети насчитывается более 800 доменов верхнего уровня.

Категории доменов верхнего уровня:

  • Общий домен верхнего уровня, например (.org, .com, .net, .gov, .edu и т. д.).
  • Домены верхнего уровня с кодом страны, такие как (.us, .ca и т. д.), соответствующие кодам стран для США и Канады соответственно.
  • Новые брендированные домены верхнего уровня, такие как (.linux, .microsoft, .companyname и т. д.).
  • Инфраструктурные домены верхнего уровня, такие как домен .arpa.

Субдомены

Когда вы посещаете такой веб-сайт, как mail.google.com, почта здесь является поддоменом google.com.

Только серверы имен для mail.google.com знают все хосты, существующие под ним, поэтому Google отвечает, есть ли почтовый поддомен или нет, корневые серверы имен не имеют об этом ни малейшего представления.

Типы DNS-серверов

Существует три типа DNS-серверов:

  • Первичные DNS-серверы : они содержат файлы конфигурации домена и отвечают на DNS-запросы.
  • Вторичный DNS-сервер : они работают как резервный и распределяют нагрузку. Первичные серверы знают о существовании вторичных серверов имен и отправляют им обновления.
  • Кэширующий DNS-сервер : все, что они делают, это кэшируют ответы DNS, поэтому вам не нужно снова запрашивать первичный или вторичный DNS-сервер. Вы можете легко заставить свою систему работать как кеширующий сервер, как мы увидим позже в этом посте.

Настройка DNS-сервера Linux

В Linux есть множество пакетов, реализующих функциональность DNS, но мы сосредоточимся на DNS-сервере BIND . Его используют многие серверы по всему миру.

Если вы используете дистрибутив на основе Red Hat, такой как CentOS, вы можете установить его следующим образом:

$ dnf -y install bind

Или в системах на основе Debian, таких как Ubuntu:

$ apt-get install bind9

После завершения установки вы можете запустить ее и включить во время загрузки.

$ systemctl start named

$ systemctl enable named

Настройка привязки

Конфигурация службы находится в файле /etc/named.conf .

Есть несколько операторов, которые BIND использует в этом файле, например:

параметрыиспользуется для глобальной конфигурации BIND.
Ведение журналачто можно регистрировать, а что можно игнорировать. Я рекомендую вам ознакомиться с сервером системного журнала Linux .
зонаопределить зону DNS.
включатьвключить еще один файл в named.conf.

Из оператора options видно, что рабочим каталогом для BIND является каталог /var/named.

Оператор zone позволяет определить зону DNS.

Например, домен google.com, который также имеет поддомены, такие как mail.google.com и analytics.google.com и другие поддомены.

Каждый из этих трех (домен и поддомены) имеет зону, определенную оператором зоны.

Определение основной зоны

Из типов DNS-серверов мы знаем, что существуют первичные, вторичные и кэш-серверы DNS.

Первичный и вторичный одинаково авторитетны в своих ответах, в отличие от кэширующего сервера.

Чтобы определить основную зону, вы можете использовать следующий синтаксис:

/etc/named.confzone     
"likegeeks.com" {
type master;
file likegeeks.com.db
};

Файл, содержащий информацию о зоне, находится в каталоге /var/named , так как это рабочий каталог, как мы знаем из параметров.

Обратите внимание, что используемое вами серверное программное обеспечение или панель хостинга автоматически создает этот файл с этим именем, поэтому, если ваш домен — example.org, файл будет  /var/named/example.org.db .

Тип — master, что означает, что это основная зона.

Определение вторичной зоны

То же, что и определение основной зоны с небольшими изменениями.

zone      "likegeeks.com" {
type slave;
masters Primary Nameserver IP Address Here; ;
file likegeeks.com.db
};

Во вторичной зоне домен такой же, как и в первичной зоне, и тип slave здесь означает, что это вторичная зона , а опция masters для перечисления IP-адресов первичного сервера имен и, наконец, файл — это путь к файлы первичной зоны.

Определение зоны кэширования

Необходимо иметь зону кэширования, так вы уменьшите запросы на DNS-сервере.

Чтобы определить зону кэширования, вам необходимо определить трехзонные разделы:

zone      "." IN {
type hint;
file "root.hint";
};

Первая строка содержит точку, которая является корневым сервером имен. Подсказка типа, означающая запись зоны кэширования, и файл «root.hints» ; указывает файл, содержащий корневые серверы (13-й корневой сервер имен). Вы можете получить последнюю версию корневого сервера имен с http://www.internic.net/zones/named.root .

Вторая зона определена в файле /etc/named.rfc1912.zones и включена в /etc/named.conf через директиву include, которая уже включена по умолчанию.

zone      "localhost" IN {
type master;
file "localhost.db";
};

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

zone      "0.0.127.in-addr.arpa" IN {
type master;
file "127.0.0.rev";
};

Размещение этих трех зон в файле /etc/named.conf заставит вашу систему работать как кэширующий DNS-сервер. Теперь вы должны ввести содержимое файлов, на которые ссылаются, например, geeks.com.db, localhost.db и 127.0.0.rev.

Эти файлы содержат типы записей DNS для каждой зоны с некоторыми параметрами. Так что же это за типы записей DNS и как их писать?

Типы DNS-записей

Файлы базы данных состоят из таких типов записей, как SOA, NS, A, PTR, MX, CNAME и TXT .

Итак, давайте начнем с каждого типа записи и посмотрим, как мы можем его настроить.

SOA: начало авторитетной записи

Запись SOA описывает записи DNS сайта в следующем формате:

example.com.      86400      IN      SOA      ns1.example.com.      mail.example.com.      (
2017012604 ;serial
86400 ;refresh, seconds
7200 ;retry, seconds
3600000 ;expire, seconds
86400 ;minimum, seconds
)

Первая строка начинается с домена example.com. и заканчивается точкой. Это то же самое, что и определение зоны в файле /etc/named.conf.

Имейте в виду, что файлы конфигурации DNS чрезвычайно разборчивы.

Слово IN означает запись в Интернете.

Слово SOA означает начало записи полномочий.

нс1. пример.com . это сервер имен домена.

mail.host.com. адрес электронной почты администратора домена. Вы можете заметить, что знака @ нет, и мы заменили его точкой, и есть завершающая точка.

Строка 2 — это серийный номер, мы используем его, чтобы сообщить серверу имен о времени обновления файла, поэтому, если вы вносите изменения в данные зоны, вы должны увеличить этот номер. Серийный номер имеет формат YYYYMMDDxx, где xx начинается с 00.

Строка 3 — частота обновления в секундах. Как часто вторичные DNS-серверы должны запрашивать первичный сервер для проверки обновлений.

Строка 4 — частота повторных попыток в секундах. Это время ожидания вторичного DNS-сервера после попытки подключения к первичному DNS-серверу, когда он не может связаться с ним. Указанное количество секунд повтора.

Строка 5 — это директива об истечении срока действия. Если вторичный сервер не может подключиться к первичному серверу для обновления, он должен сбросить это значение через указанное количество секунд.

Строка 6 сообщает, что кэширующие серверы не могут подключиться к основному DNS-серверу; они ждут до истечения срока действия записи, эта строка определяет время ожидания.

NS: записи сервера имен

Вы можете использовать запись NS, чтобы указать серверы имен для зоны. Записи NS такие:

IN           NS         ns1.example.com.
IN           NS         ns2.example.com.

Вам не нужно создавать две записи NS, но мы предпочитаем иметь резервные серверы имен.

A и AAAA: адресные записи

Запись A сопоставляет имя хоста с IP-адресом:

support IN          A             192.168.1.5

Если у вас есть хост на support.example.com с адресом 192.168.1.5, вы можете ввести, как в приведенном выше примере.

Примечание: мы написали хост без точки.

PTR: записи указателей

Запись PTR предназначена для обратного разрешения имен, вы указываете IP-адрес, и она возвращает имя хоста.

Это противоположно тому, что делает запись.

192.168.1.5        IN            PTR        support.example.com.

Здесь мы вводим полное имя хоста с завершающей точкой.

MX: записи обмена почтой

Запись MX сообщает о  записях почтового сервера  .

example.com.   IN           MX         10           mail

Домен заканчивается точкой; число 10 — это важность почтового сервера, если у вас несколько почтовых серверов, чем меньше число, тем меньше значение.

CNAME: записи канонических имен

Записи CNAME похожи на ярлыки для имен хостов.

Предположим, у вас есть сайт с именем хоста what-bignameis.example.com, и, поскольку система является веб-сервером, для хоста можно создать псевдоним www или запись CNAME.

Таким образом, вы можете создать запись CNAME, чтобы сделать имя www.example.com:

whatever-bignameis      IN           A                    192.168.1.5
www                     IN           CNAME                whatever-bignameis

Первая строка сообщает DNS-серверу о расположении псевдонима; вторая строка создает псевдоним, указывающий на www.

TXT-записи

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

Вы можете писать записи TXT следующим образом:

example.com.   IN           TXT         " YOUR INFO GOES HERE"

Кроме того, вы можете использовать запись RP для размещения контактной информации.

example.com.   IN           RP           mail.example.com.         example.com.

Значение срока жизни DNS

В /etc/named.conf вверху есть запись $TTL .

Эта запись информирует BIND о значении времени жизни для каждой отдельной записи.

Он принимает значение в секундах, например 14400 секунд (4 часа) , поэтому DNS-серверы кэшируют вашу зону до четырех часов, а затем снова запрашивают ваш DNS-сервер.

Вы можете понизить значение, но значение по умолчанию справедливо, если вы не знаете, что делаете.

Отлов ошибок конфигурации

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

Вы можете диагностировать ошибки DNS-сервера Linux из журнала. Служба BIND через ошибки в /var/log/messages, вы можете использовать команду tail для просмотра журнала ошибок в реальном времени, используя параметр -f.

$tail -f /var/log/messages

Поэтому, когда вы пишете файл зоны или изменяете /etc/named.config и перезапускаете службу, и она показывает ошибку, вы можете легко определить ошибку из журнала.

Хост-команда

После того, как вы успешно добавили или изменили свои записи, вы можете использовать команду host, чтобы проверить, правильно ли разрешен ваш хост.

Если вы дадите ему имя хоста, он ответит соответствующими IP-адресами.

$ host example.com

Кроме того, вы можете выполнять обратный поиск.

$ host 192.168.1.5

Вы можете проверить хост и команду dig .

Whois-команда

Вы можете использовать команду whois, чтобы получить информацию о владельце домена.

Также адреса электронной почты владельца и контактные телефоны.

$ whois example.com

Команда rndc

Вы можете использовать инструмент rndc для безопасного управления сервером имен.

Вы можете проверить статус DNS-сервера Linux следующим образом:

$ rndc status

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

$ rndc reload example.com

Здесь мы перезагружаем файл зоны example.com.

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

$ rndc reload

Или, может быть, вы добавляете новые зоны или меняете конфигурацию сервиса; вы можете перезагрузить конфигурацию следующим образом:

$ rndc reconfig

DNS-преобразователь Linux

Мы увидели, как работает DNS-сервер Linux и как его настроить. Другая часть — это клиент, который связывается с DNS-сервером.

Клиент является решателем; вы можете проверить файл конфигурации /etc/resolv.conf

В дистрибутивах на основе Debian вы можете проверить каталог /etc/resolvconf/resolv.conf.d/ .

Файл /etc/resolv.conf содержит локальные DNS-серверы, используемые системой.

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

Вы можете использовать свой собственный DNS-сервер после запуска службы BIND, просто введите их в файл resolver.conf.

Оригинальный источник статьи:   https://likegeeks.com/

#linux #dns #server 

Как установить, настроить и поддерживать DNS-сервер Linux
津田  淳

津田 淳

1678914600

如何安装、配置和维护 Linux DNS 服务器

DNS(域名系统)是计算机的命名系统,执行此操作的服务是将 IP 地址转换为人类可读地址的 DNS 服务器。

这个过程是 Internet 的骨干,也是服务器中非常重要的服务,因此从那时起,我们将讨论 DNS 服务器或具体的 Linux DNS 服务器以及如何安装、配置和维护它。

/etc/主机文件

每个系统都必须保留其主机名及其 IP 地址表的副本。该文件负责 IP 地址。

在 Linux 系统上,此表是/etc/hosts文件。

因此,即使您没有 DNS 服务器或 DNS 服务器不可用,此文件也可以使用 /etc/hosts 文件将 IP 地址转换为名称。

这意味着系统在转到 DNS 服务器之前首先查询此文件,如果找到域,它将在不转到任何 DNS 服务器的情况下对其进行转换。

尝试编辑 /etc/hosts 并键入以下内容:

127.0.0.1              google.com

然后转到您的浏览器并输入 google.com 并查看结果。如果您的系统上安装了Apache 服务器并且您的 localhost 正在运行,它将显示 localhost 的索引页面而不是 google 页面。

您可以将 google.com 转换为任何网站的任何其他 IP 地址,并查看结果以确保这一点。

所以这个文件所做的是将 IP 地址转换为名称,但这是针对相同的连接网络。那么外部网络又如何维护所有系统的所有这些记录呢?

每个人都会管理自己的 /etc/hosts 文件并自己更新吗?当然不是。

域名

当您访问网站时,您键入 FQDN(完全限定域名)或这样的域名:likegeeks.com 或 www.google.com

每个域由域组件组成;点分隔这些组件。

文本com顶级域组件,google为二级域组件, www为三级域组件

当您访问任何网站时,浏览器会在末尾默默地添加一个点,但您看不到,因此该域将类似于 www.google.com。注意 .com 后面的点;这个称为根域。

但为什么我们要添加这个根域或点呢?

因为这个点由根名称服务器提供服务,所以在这篇文章发布时,世界上有 13 个根名称服务器,你可以将它们视为互联网的大脑,如果它们关闭,世界将没有互联网。

为什么是13?

因为也许世界上某个地方发生地震或自然灾害,可能会毁掉一台根服务器,所以其他服务器一直服务到损坏的服务器恢复上线。

这些根名称服务器的名称如下:a.root-server.net、b.root-server.net 等等。

顶级域名 (TLD)

我们看到了顶级域组件,例如 com 域。

顶级域 (TLD) 根据地理或功能方面分为几类。

在撰写本文时,网络上有 800 多个顶级域。

顶级域类别是:

  • 通用顶级域,例如(.org、.com、.net、.gov、.edu 等)。
  • 国家代码顶级域,如(.us、.ca 等)分别对应美国和加拿大的国家代码。
  • 新品牌顶级域,如(.linux、.microsoft、.companyname 等)。
  • 基础设施顶级域,如 .arpa 域。

子域

当您访问像 mail.google.com 这样的网站时,这里的邮件是 google.com 的子域。

只有 mail.google.com 的名称服务器知道它下面存在的所有主机,因此谷歌会回答是否存在邮件子域,根名称服务器对此一无所知。

DNS 服务器的类型

DNS 服务器分为三种类型:

  • 主 DNS 服务器:它们包含域的配置文件,并响应 DNS 查询。
  • 辅助 DNS 服务器:它们用作备份和负载分配。主服务器知道辅助名称服务器的存在并向它们发送更新。
  • 缓存 DNS 服务器:他们所做的只是缓存 DNS 响应,因此您无需再次询问主 DNS 服务器或辅助 DNS 服务器。您可以轻松地将您的系统用作缓存服务器,正如我们稍后将在本文中看到的那样。

设置 Linux DNS 服务器

Linux 上有许多实现 DNS 功能的包,但我们将重点介绍BIND DNS 服务器。世界各地的许多服务器都在使用它。

如果你使用的是基于 Red Hat 的发行版,比如 CentOS,你可以像这样安装它:

$ dnf -y install bind

或者在基于 Debian 的系统上,比如 Ubuntu:

$ apt-get install bind9

安装完成后,您可以启动它并使其在引导时运行。

$ systemctl start named

$ systemctl enable named

配置绑定

服务配置是/etc/named.conf文件。

BIND 在该文件中使用了一些语句,例如:

选项用于全局 BIND 配置。
记录什么可以记录,什么可以忽略。我建议您查看Linux 系统日志服务器
定义 DNS 区域。
包括在 named.conf 中包含另一个文件。

从选项语句中,您可以看到 BIND 的工作目录是 /var/named 目录。

zone 语句使您能够定义 DNS 区域。

就像域 google.com 一样,它也有子域,如 mail.google.com 和 analytics.google.com 以及其他子域。

这三个(域和子域)中的每一个都有一个由 zone 语句定义的区域。

定义主要区域

我们从 DNS 服务器类型中知道有主 DNS 服务器、辅助 DNS 服务器和缓存 DNS 服务器。

与缓存服务器不同,主要和次要的答案具有同等权威性。

要定义主要区域,您可以使用以下语法:

/etc/named.confzone     
"likegeeks.com" {
type master;
file likegeeks.com.db
};

包含区域信息的文件位于/var/named目录中,因为这是工作目录,正如我们从选项中知道的那样。

请注意,您使用的服务器软件或托管面板会自动为您创建具有此名称的文件,因此如果您的域是 example.org,则该文件将为 /var/named/example.org.db

类型是 master,这意味着这是一个主要区域。

定义次要区域

与主要区域定义相同,变化不大。

zone      "likegeeks.com" {
type slave;
masters Primary Nameserver IP Address Here; ;
file likegeeks.com.db
};

secondary zone中,域与primary zone相同,这里的type slave表示这是一个secondary zone,masters选项列出了primary nameserver的IP地址,最后,文件是路径主要的区域文件。

定义缓存区

有必要有一个缓存区,这样你就可以减少对 DNS 服务器的查询。

要定义缓存区域,您需要定义三区域部分,第一个区域:

zone      "." IN {
type hint;
file "root.hint";
};

第一行包含一个点,这是根名称服务器。类型提示,表示缓存区条目,以及文件“root.hints” 指定包含根服务器(第 13 根名称服务器)的文件。您可以从http://www.internic.net/zones/named.root获取最新的根名称服务器

第二个区域在/etc/named.rfc1912.zones文件中定义,并通过 include 指令包含在 /etc/named.conf 中,默认情况下已包含在内。

zone      "localhost" IN {
type master;
file "localhost.db";
};

第三个区域定义本地主机的反向查找。

zone      "0.0.127.in-addr.arpa" IN {
type master;
file "127.0.0.rev";
};

将这三个区域放在 /etc/named.conf 上将使您的系统用作缓存 DNS 服务器。现在您应该键入引用的文件的内容,如 likegeeks.com.db、localhost.db 和 127.0.0.rev。

这些文件包含每个区域的 DNS 记录类型和一些选项。那么那些 DNS 记录类型是什么以及如何编写它们呢?

DNS 记录类型

数据库文件由SOA、NS、A、PTR、MX、CNAME 和 TXT 等记录类型组成。

因此,让我们从每种记录类型开始,看看我们如何配置它。

SOA:授权记录开始

SOA 记录使用以下格式描述站点的 DNS 条目:

example.com.      86400      IN      SOA      ns1.example.com.      mail.example.com.      (
2017012604 ;serial
86400 ;refresh, seconds
7200 ;retry, seconds
3600000 ;expire, seconds
86400 ;minimum, seconds
)

第一行以域 example.com 开头。并以句号结束。这与 /etc/named.conf 文件中的区域定义相同。

请记住,DNS 配置文件非常挑剔。

IN一词表示互联网记录。

SOA一词的意思是授权记录开始。

ns1。示例.com 是域的名称服务器。

mail.host.com。是域管理员电子邮件。您可能会注意到没有 @ 符号,我们将其替换为句点,并且有一个尾随句点。

第 2 行是序列号,我们用它来告诉名称服务器文件更新时间,所以如果你对区域数据进行更改,你必须增加这个数字。序列号的格式为 YYYYMMDDxx,其中 xx 从 00 开始。

第 3 行是以秒为单位的刷新率。辅助 DNS 服务器查询主服务器以检查更新的频率。

第 4 行是以秒为单位的重试率。这是辅助 DNS 服务器在尝试连接到主 DNS 服务器但无法访问后等待的时间。指定的重试秒数。

第 5 行是过期指令。如果辅助服务器无法连接到主服务器进行更新,它应该在指定的秒数后丢弃该值。

第 6 行告诉缓存服务器无法连接到主 DNS 服务器;他们在条目过期之前等待,这一行定义了等待时间。

NS:名称服务器记录

您可以使用 NS 记录指定区域的名称服务器。NS记录是这样的:

IN           NS         ns1.example.com.
IN           NS         ns2.example.com.

您不必创建两个 NS 记录,但我们更愿意拥有备份名称服务器。

A和AAAA:地址记录

A 记录将主机名映射到 IP 地址:

support IN          A             192.168.1.5

如果您在地址 192.168.1.5 上的 support.example.com 有一个主机,您可以像上面的例子一样输入。

注意:我们写的主机没有句号。

PTR:指针记录

PTR 记录用于进行反向名称解析,您提供一个 IP 地址,它返回主机名。

这与 A 记录的作用相反。

192.168.1.5        IN            PTR        support.example.com.

在这里,我们键入带有结尾句点的完整主机名。

MX:邮件往来记录

MX 记录说明 邮件服务器 记录。

example.com.   IN           MX         10           mail

域以句点结尾;数字 10 是邮件服务器的重要性,如果您有多个邮件服务器,则数字越小越不重要。

CNAME:规范名称记录

CNAME 记录就像主机名的快捷方式。

假设您有一个主机名为 whatever-bignameis.example.com 的站点,并且由于系统是 Web 服务器,可以为主机创建别名 www 或 CNAME 记录。

因此,您可以创建一个 CNAME 记录来创建名称 www.example.com:

whatever-bignameis      IN           A                    192.168.1.5
www                     IN           CNAME                whatever-bignameis

第一行告诉 DNS 服务器别名的位置;第二行创建指向 www 的别名。

TXT记录

您可以在 TXT 记录上放置任何文本,例如您的联系信息或您希望人们在查询您的 DNS 服务器时知道的任何其他信息。

可以这样写TXT记录:

example.com.   IN           TXT         " YOUR INFO GOES HERE"

另外,您可以使用RP 记录来放置联系信息。

example.com.   IN           RP           mail.example.com.         example.com.

DNS TTL 值

在顶部的/etc/named.conf中有$TTL条目。

此条目通知 BIND 每个单独记录的生存时间值。

它需要一个以秒为单位的值,例如14400 秒(4 小时),因此 DNS 服务器会将您的区域缓存最多四个小时,然后再次查询您的 DNS 服务器。

您可以降低该值,但默认值是合理的,除非您知道自己在做什么。

捕获配置错误

当您编写区域文件时,您可能会忘记句点或空格或任何其他错误。

您可以从日志中诊断您的 Linux DNS 服务器错误。BIND 服务通过/var/log/messages 中的错误,您可以使用tail 命令使用-f 选项查看实时错误日志。

$tail -f /var/log/messages

因此,当您编写区域文件或修改 /etc/named.config 并重新启动服务并显示错误时,您可以轻松地从日志中识别错误。

主机命令

成功添加或修改记录后,您可以使用主机命令查看您的主机是否正确解析。

如果你给它一个主机名,它会回答相应的 IP 地址。

$ host example.com

此外,您还可以执行反向查找。

$ host 192.168.1.5

您可以检查主机和挖掘命令

域名查询命令

您可以使用 whois 命令获取域所有者的详细信息。

此外,所有者的电子邮件地址和联系电话号码。

$ whois example.com

rndc 命令

您可以使用 rndc 工具来安全地管理名称服务器。

您可以像这样检查 Linux DNS 服务器的状态:

$ rndc status

此外,如果您对任何区域文件进行了更改,则可以重新加载服务而无需重新启动命名服务。

$ rndc reload example.com

这里我们重新加载 example.com 区域文件。

您可以像这样重新加载所有区域:

$ rndc reload

或者您可能添加新区域或更改服务配置;您可以像这样重新加载配置:

$ rndc reconfig

Linux DNS 解析器

我们已经了解了 Linux DNS 服务器的工作原理以及配置方法。另一部分是正在联系 DNS 服务器的客户端。

客户端是解析器;你可以查看配置文件/etc/resolv.conf

在基于 Debian 的发行版上,您可以检查/etc/resolvconf/resolv.conf.d/目录。

/etc/resolv.conf文件包含系统使用的本地 DNS 服务器

第一行是默认搜索域,第二行是名称服务器的IP地址。

BIND 服务运行后,您可以使用自己的 DNS 服务器,只需在 resolver.conf 文件中键入它们即可。

文章原文出处:https:   //likegeeks.com/

#linux #dns #server 

如何安装、配置和维护 Linux DNS 服务器

Как установить, настроить и защитить FTP-сервер в Linux

FTP или протокол передачи файлов — широко используемый протокол для передачи файлов между компьютерами; один действует как клиент, другой действует как сервер. В этом посте мы поговорим о FTP-сервере в системах Linux, в частности, об очень безопасном FTP-демоне (vsftpd).

Программа vsftpd — это очень популярный FTP-сервер, который сегодня используют многие серверы.

Как работает FTP-сервер?

FTP-сервер работает с архитектурой клиент-сервер для связи и передачи файлов.

FTP — это протокол с отслеживанием состояния, что означает, что соединения между клиентами и серверами остаются открытыми во время сеанса FTP.

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

Существует два типа FTP-соединений, которые вы можете инициировать:

  • Управляющее соединение также называется командным соединением.
  • Подключение для передачи данных.

Когда вы устанавливаете FTP-соединение, TCP-порт 21 открывается для отправки ваших учетных данных для входа; это соединение называется управляющим соединением .

Когда вы передаете файл, начинается подключение для передачи данных .

Существует два типа подключения для передачи данных:

  • Пассивный режим.
  • Активный режим.

Активные соединения инициируются удаленным сервером, а клиент ожидает запросов сервера.

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

Когда FTP-клиент начинает передачу, в вашем FTP-клиенте есть опция, которая определяет, хотите ли вы использовать активное или пассивное FTP-соединение.

Активный режим

Клиент подключается со случайного эфемерного исходного порта к управляющему порту FTP 21 .

Вы можете проверить свой эфемерный диапазон портов с помощью этой команды:

$ cat /proc/sys/net/ipv4/ip_local_port_range

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

Соединения в активном режиме обычно имеют проблемы с брандмауэрами, TCP- порты 20 и 21 должны быть открыты на вашем брандмауэре.

Из-за этих проблем с брандмауэрами активного режима мы можем использовать пассивный режим.

Если вы используете брандмауэр iptables, я рекомендую вам просмотреть брандмауэр Linux iptables  , чтобы узнать, как разрешать определенные порты.

Пассивный режим

В пассивном режиме клиент запускает управляющее соединение со случайного порта на порт назначения  21 на удаленном сервере.

Если FTP-клиент запрашивает файл, он выдает команду PASV FTP. Сервер откроет случайный порт и передаст этот номер порта клиенту.

Вот почему FTP является протоколом, требующим подключения, потому что каждый раз, когда вы устанавливаете соединение для передачи данных (например, передаете файл), сервер выполняет описанный выше процесс, и это делается со всеми клиентами, подключенными к серверу.

В пассивном режиме соединение для управления и передачи данных запускается FTP-клиентом.

Возможности FTP-сервера vsftpd

Для вас доступно несколько FTP-серверов, коммерческих и с открытым исходным кодом.

Vsftpd имеет некоторые функции безопасности, которые делают его на вершине, например:

  • Может работать как обычный пользователь с разделением привилегий.
  • Поддерживает FTP-соединения SSL/TLS.
  • Может заключать пользователей в их домашние каталоги.

Настройка FTP-сервера

В любом случае, некоторые дистрибутивы Linux поставляются с vsftpd, если вы хотите установить его в системах на основе Red Hat, вы можете использовать следующую команду:

$ sudo dnf -y vsftpd

В дистрибутивах на основе Debian, таких как Ubuntu, вы можете установить его следующим образом:

$ sudo apt-get install vsftpd

После установки пакета вы можете запустить службу и разрешить ее запуск во время загрузки.

$ systemctl start vsftpd
$ systemctl enable vsftpd

Файл конфигурации для FTP-сервера vsftpd:

/etc/vsftpd.conf

.

На самом деле FTP-сервер в Linux — один из самых простых серверов, с которыми вы можете работать.

Существует два типа доступа к FTP-серверу:

  • Анонимный FTP-доступ : любой может войти в систему с анонимным именем пользователя без пароля.
  • Логин локального пользователя : всем действительным пользователям в /etc/passwd разрешен доступ к FTP-серверу.

Вы можете разрешить анонимный доступ к FTP-серверу из конфигурации в /etc/vsftpd/vsftpd.conf ,  включив анонимный_enable=YES, если он не включен, и перезагрузите службу.

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

Вы можете установить его, если его нет в вашей системе:

$ dnf -y install ftp

Теперь вы можете получить доступ к своему FTP-серверу следующим образом:

$ ftp localhost

Затем введите анонимное имя пользователя и без пароля, просто нажмите Enter.

Вы увидите приглашение FTP.

ftp>

И теперь вы можете ввести любую FTP-команду для взаимодействия с FTP-сервером.

Подключиться как локальный пользователь

Поскольку в настройках есть опция, разрешающая локальным пользователям доступ к FTP-серверу local_enable =YES , теперь давайте попробуем получить доступ к FTP-серверу, используя локального пользователя:

$ ftp localhost

Затем введите свое локальное имя пользователя и пароль для этого пользователя, и вы увидите сообщение об успешном входе в систему.

Настройте FTP-сервер только как анонимный

Этот тип FTP-сервера полезен, если ваши файлы должны быть доступны для пользователей без каких-либо паролей или логинов.

Вам нужно настроить vsftpd, чтобы разрешить только анонимным пользователям.

Откройте файл /etc/vsftpd/vsftpd.conf и измените следующие параметры на соответствующие значения.

listen=NO
listen_ipv6=NO
anonymous_enable=YES
local_enable=NO
write_enable=NO

Затем нам нужно создать непривилегированную системную учетную запись, чтобы использовать ее для анонимного доступа по FTP.

$ useradd -c " FTP User" -d /var/ftp -r -s /sbin/nologin ftp

Этот пользователь не имеет привилегий в системе, поэтому безопаснее использовать его при доступе к FTP-серверу.

Не забудьте перезапустить FTP-сервер после изменения файла конфигурации.

Вы можете получить доступ к FTP-серверу из браузера, просто набрав ftp://youdomain/.

Безопасность FTP-сервера

Мы можем настроить vsftpd для использования TLS, чтобы файлы, передаваемые по сети, были более безопасными.

Сначала мы генерируем запрос сертификата с помощью команды openssl:

$ openssl genrsa -des3 -out FTP.key

Затем мы генерируем запрос сертификата:

$ openssl req -new -key FTP.key -out certificate.csr

Теперь снимаем пароль с файла ключа:

$ cp FTP.key FTP.key.orig

$ openssl rsa -in FTP.key.orig -out ftp.key

Наконец, мы генерируем наш сертификат:

$ openssl x509 -req -days 365 -in certificate.csr -signkey ftp.key -out mycertificate.crt

Теперь копируем файл сертификата и ключ в /etc/pki/tls/certs:

$ cp ftp.key /etc/pki/tls/certs/

$ cp mycertificate.crt /etc/pki/tls/certs

Теперь все, что нам нужно сделать, это настроить vsftpd для поддержки безопасных соединений.

Откройте файл /etc/vsftpd/vsftpd.conf и добавьте следующие строки :

ssl_enable=YES
allow_anon_ssl=YES
ssl_tlsv1=YES
ssl_sslv2=NO
ssl_sslv3=NO
rsa_cert_file=/etc/pki/tls/certs/mycertificate.crt
rsa_private_key_file=/etc/pki/tls/certs/ftp.key
ssl_ciphers=HIGH
require_ssl_reuse=NO

Перезапустите службу, чтобы отразить эти изменения. Вот и все.

Попробуйте подключиться к вашему FTP-серверу с любого клиента в любой системе, такой как Windows, и выберите защищенное соединение или FTPS, и вы успешно увидите свои папки.

SFTP против FTPS

В последнем примере мы видели FTP поверх уровня SSL (FTPS) и успешно подключились к FTP-серверу. Однако с жестко защищенным брандмауэром трудно управлять этим типом соединения, поскольку FTPS использует несколько номеров портов.

Лучшим решением в этом случае является использование SFTP (FTP через SSH). SFTP  использует только порт 22.

FTP-сервер будет использовать этот порт для всех подключений во время сеансов FTP.

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

Заключение FTP-пользователей

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

Откройте /etc/vsftpd/vsftpd.conf и раскомментируйте следующие параметры:

chroot_local_user=YES
chroot_list_enable=YES
chroot_list_file=/etc/vsftpd.chroot_list

Файл  /etc/vsftpd.chroot_list содержит список пользователей, находящихся в тюрьме, по одному в каждой строке.

Сохраните файлы и перезапустите службу.

$ systemctl restart vsftpd

Команды FTP-сервера Linux

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

Первая команда — это команда pwd, вы можете использовать ее для печати текущего рабочего каталога:

ftp> pwd

Вы можете получить список файлов с помощью команды ls:

ftp> ls

Кроме того, вы можете использовать команду cd для изменения рабочего каталога:

ftp> cd /

Если вы хотите выйти из сеанса FTP, используйте команду bye:

ftp> bye

Мы используем команду lcd для отображения локальной папки, а не папки FTP:

ftp> lcd

Вы можете изменить локальный каталог с помощью команды lcd:

ftp> lcd /home

Вы можете скачать файл с помощью команды get:

ftp> get myfile

Кроме того, вы можете загрузить несколько файлов с помощью команды mget:

ftp> mget file1 file2

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

ftp> delete filename

Используйте команду put для загрузки файла на сервер:

ftp> put filename

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

ftp> mput file1 file2

Вы можете создать каталог с помощью команды mkdir:

ftp> mkdir dirName

Или вы можете удалить каталог с сервера с помощью команды rmdir.

ftp> rmdir dirName

Существует два режима передачи файлов при использовании FTP-сервера, режим ASCII и двоичный режим , вы можете изменить режим следующим образом:

ftp> binary

ftp> ascii

FTP-сервер — один из самых простых серверов в Linux для настройки и работы.

Надеюсь, вы найдете пост полезным и интересным. Продолжают возвращаться.

Спасибо.

Оригинальный источник статьи:   https://likegeeks.com/

#linux #install #configure #ftp #server 

Как установить, настроить и защитить FTP-сервер в Linux
津田  淳

津田 淳

1678909740

如何在 Linux 中安装、配置和保护 FTP 服务器

FTP 或文件传输协议是用于在计算机之间传输文件的常用协议;一个充当客户端,另一个充当服务器。在这篇文章中,我们将讨论 Linux 系统中的 FTP 服务器,特别是 Very Secure FTP Daemon (vsftpd)。

vsftpd 程序是当今许多服务器使用的非常流行的 FTP 服务器。

FTP 服务器如何工作?

FTP 服务器采用客户端-服务器架构进行通信和传输文件。

FTP 是一种状态协议,这意味着客户端和服务器之间的连接在 FTP 会话期间保持打开状态。

要从 FTP 服务器发送或接收文件,可以使用 FTP 命令;这些命令是连续执行的。就像一个队列,一个接一个。

您可以启动两种类型的 FTP 连接:

  • 控制连接也称为命令连接。
  • 数据连接。

当您建立 FTP 连接时,TCP 端口 21 打开以发送您的登录凭据;此连接称为控制连接

传输文件时,数据连接开始。

有两种类型的数据连接:

  • 被动模式。
  • 主动模式。

活动连接由远程服务器发起,客户端等待服务器请求。

客户端向远程服务器发起被动连接,服务器等待请求。

当 FTP 客户端开始传输时,您的 FTP 客户端上有一个选项可以控制您是要使用主动还是被动 FTP 连接。

活动模式

客户端从一个随机的临时源端口连接到FTP 控制端口 21

您可以使用以下命令检查临时端口范围:

$ cat /proc/sys/net/ipv4/ip_local_port_range

当需要传输文件时,远程FTP服务器会打开20端口连接FTP客户端。

主动模式连接通常会遇到防火墙问题,TCP端口 20 和 21应该在您的防火墙上打开。

由于主动模式防火墙的这些问题,我们可以使用被动模式。

如果您使用的是 iptables 防火墙,我建议您查看Linux iptables 防火墙 以了解如何允许特定端口。

被动模式

在被动模式下,客户端启动从随机端口到远程服务器上的目标端口 21的控制连接。

如果 FTP 客户端请求文件,它将发出 PASV FTP 命令。服务器将打开一个随机端口并将此端口号提供给客户端。

这就是为什么 FTP 是一个需要连接的协议的原因,因为每次建立数据连接(如传输文件)时,服务器都会执行上述过程,并且所有客户端都连接到服务器。

在被动模式下,控制和数据连接由 FTP 客户端启动。

vsftpd FTP服务器功能

有几个 FTP 服务器可供您使用,商业的和开源的。

Vsftpd 具有一些安全功能,使其位于顶部,例如:

  • 可以作为具有特权分离的普通用户运行。
  • 支持 SSL/TLS FTP 连接。
  • 可以将用户监禁在他们的主目录中。

FTP服务器设置

一些 Linux 发行版附带了 vsftpd,无论如何,如果你想在基于 Red Hat 的系统上安装它,你可以使用以下命令:

$ sudo dnf -y vsftpd

在像 Ubuntu 这样基于 Debian 的发行版上,你可以像这样安装它:

$ sudo apt-get install vsftpd

安装包后,您可以运行该服务并使其在引导时运行。

$ systemctl start vsftpd
$ systemctl enable vsftpd

vsftpd FTP 服务器的配置文件是

/etc/vsftpd.conf

.

实际上,Linux 中的 FTP 服务器是您可以使用的最简单的服务器之一。

访问FTP服务器有两种方式:

  • 匿名 FTP 访问:任何人都可以使用用户名 anonymous 登录而无需密码。
  • 本地用户登录:允许 /etc/passwd 上的所有有效用户访问 FTP 服务器。

您可以允许从配置中匿名访问 FTP 服务器,在/etc/vsftpd/vsftpd.conf中 启用anonymous_enable=YES(如果未启用)并重新加载您的服务。

现在您可以尝试使用任何 FTP 客户端连接到 FTP 服务器。我将使用简单的 FTP 命令。

如果它不在您的系统上,您可以安装它:

$ dnf -y install ftp

现在您可以像这样访问您的 FTP 服务器:

$ ftp localhost

然后键入用户名 anonymous 并且没有密码,只需按回车键。

您将看到 FTP 提示符。

ftp>

现在,您可以键入任何 FTP 命令来与 FTP 服务器交互。

以本地用户身份连接

由于设置中有允许本地用户访问 FTP 服务器的选项 local_enable =YES,现在让我们尝试使用本地用户访问 FTP 服务器:

$ ftp localhost

然后输入您的本地用户名和该用户的密码,您将看到登录成功消息。

将 FTP 服务器设置为仅匿名

如果您的文件应该可供没有任何密码或登录名的用户使用,则这种 FTP 服务器很有用。

您需要将 vsftpd 配置为仅允许匿名用户。

打开/etc/vsftpd/vsftpd.conf文件,并将以下选项更改为相应的值。

listen=NO
listen_ipv6=NO
anonymous_enable=YES
local_enable=NO
write_enable=NO

然后我们需要创建一个非特权系统帐户以将其用于匿名 FTP 类型的访问。

$ useradd -c " FTP User" -d /var/ftp -r -s /sbin/nologin ftp

该用户在系统上没有权限,因此在访问 FTP 服务器时使用它更安全。

修改配置文件后不要忘记重启 FTP 服务器。

您可以从浏览器访问 FTP 服务器,只需键入 ftp://youdomain/。

FTP服务器安全

我们可以将 vsftpd 配置为使用 TLS,因此通过网络传输的文件更加安全。

首先,我们使用 openssl 命令生成证书请求:

$ openssl genrsa -des3 -out FTP.key

然后我们生成一个证书请求:

$ openssl req -new -key FTP.key -out certificate.csr

现在我们从密钥文件中删除密码:

$ cp FTP.key FTP.key.orig

$ openssl rsa -in FTP.key.orig -out ftp.key

最后,我们生成证书:

$ openssl x509 -req -days 365 -in certificate.csr -signkey ftp.key -out mycertificate.crt

现在我们将证书文件和密钥复制到 /etc/pki/tls/certs:

$ cp ftp.key /etc/pki/tls/certs/

$ cp mycertificate.crt /etc/pki/tls/certs

现在,我们需要做的就是配置 vsftpd 以支持安全连接。

打开/etc/vsftpd/vsftpd.conf文件并添加以下行

ssl_enable=YES
allow_anon_ssl=YES
ssl_tlsv1=YES
ssl_sslv2=NO
ssl_sslv3=NO
rsa_cert_file=/etc/pki/tls/certs/mycertificate.crt
rsa_private_key_file=/etc/pki/tls/certs/ftp.key
ssl_ciphers=HIGH
require_ssl_reuse=NO

重新启动您的服务以反映这些更改。就是这样。

尝试从任何系统(如 Windows)上的任何客户端连接到您的 FTP 服务器,并选择安全连接或 FTPS,您将成功看到您的文件夹。

SFTP 与 FTPS

在上一个示例中,我们看到了 SSL 层上的 FTP (FTPS),并且我们已经成功连接到 FTP 服务器。但是,由于 FTPS 使用多个端口号,因此使用严格保护的防火墙很难管理这种连接。

在这种情况下,最好的解决方案是使用 SFTP(FTP over SSH)。SFTP 仅使用端口 22。

在 FTP 会话期间,FTP 服务器将使用此端口进行所有连接。

如果您使用防火墙,您应该选择 SFTP,因为它只需要一个端口。

监禁 FTP 用户

您可以通过将 FTP 用户关在他们的主目录中并只允许特定用户访问该服务来保护您的 FTP 服务器。

打开 /etc/vsftpd/vsftpd.conf 并取消注释以下选项:

chroot_local_user=YES
chroot_list_enable=YES
chroot_list_file=/etc/vsftpd.chroot_list

文件 /etc/vsftpd.chroot_list包含每行一个被监禁用户的列表。

保存文件并重新启动服务。

$ systemctl restart vsftpd

Linux FTP 服务器命令

您可以使用任何 GUI 客户端上传和下载文件,但您还需要了解一些 FTP 服务器命令。

第一个命令是 pwd 命令,你可以用它来打印当前工作目录:

ftp> pwd

您可以使用 ls 命令列出文件:

ftp> ls

另外,您可以使用 cd 命令更改工作目录:

ftp> cd /

如果要退出 FTP 会话,请使用 bye 命令:

ftp> bye

我们使用 lcd 命令来显示本地文件夹,而不是 FTP 文件夹:

ftp> lcd

您可以使用 lcd 命令更改本地目录:

ftp> lcd /home

您可以使用 get 命令下载文件:

ftp> get myfile

此外,您可以使用 mget 命令下载多个文件:

ftp> mget file1 file2

使用 delete 命令从服务器中删除一个文件:

ftp> delete filename

使用put命令上传文件到服务器:

ftp> put filename

要上传多个文件,请使用 mput 命令:

ftp> mput file1 file2

您可以使用 mkdir 命令创建一个目录:

ftp> mkdir dirName

或者您可以使用 rmdir 命令从服务器中删除一个目录。

ftp> rmdir dirName

使用FTP服务器传输文件有两种模式,ASCII模式二进制模式,你可以这样改变模式:

ftp> binary

ftp> ascii

FTP 服务器是 Linux 中最容易配置和使用的服务器之一。

我希望你觉得这篇文章有用且有趣。继续回来。

谢谢。

文章原文出处:https:   //likegeeks.com/

#linux #install #configure #ftp #server 

如何在 Linux 中安装、配置和保护 FTP 服务器

Set Up Your Own Open Source DNS Server

Take control of your internet privacy by running your own DNS server with the open source project, Adguard Home.

A Domain Name Server (DNS) associates a domain name (like example.com) with an IP address (like 93.184.216.34). This is how your web browser knows where in the world to look for data when you enter a URL or when a search engine returns a URL for you to visit. DNS is a great convenience for internet users, but it's not without drawbacks. For instance, paid advertisements appear on web pages because your browser naturally uses DNS to resolve where those ads "live" on the internet. Similarly, software that tracks your movement online is often enabled by services resolved over DNS. You don't want to turn off DNS entirely because it's very useful. But you can run your own DNS service so you have more control over how it's used.

I believe it's vital that you run your own DNS server so you can block advertisements and keep your browsing private, away from providers attempting to analyze your online interactions. I've used Pi-hole in the past and still recommend it today. However, lately, I've been running the open source project Adguard Home on my network. I found that it has some unique features worth exploring.

Adguard Home

Of the open source DNS options I've used, Adguard Home is the easiest to set up and maintain. You get many DNS resolution solutions, such as DNS over TLS, DNS over HTTPS, and DNS over QUIC, within one single project.

You can set up Adguard as a container or as a native service using a single script:

$ curl -s -S -L \
https://raw.githubusercontent.com/AdguardTeam/AdGuardHome/master/scripts/install.sh

Look at the script so you understand what it does. Once you're comfortable with the install process, run it:

$ sh ./install.sh

Some of my favorite features of AdGuard Home:

An easy admin interface

Block ads and malware with the Adguard block list

Options to configure each device on your network individually

Force safe search on specific devices

Set HTTPS for the admin interface, so your remote interacts with it are fully encrypted

I find that Adguard Home saves me time. Its block lists are more robust than those on Pi-hole. You can quickly and easily configure it to run DNS over HTTPS.

No more malware

Malware is unwanted content on your computer. It's not always directly dangerous to you, but it may enable dangerous activity for third parties. That's not what the internet was ever meant to do. I believe you should host your own DNS service to keep your internet history private and out of the hands of known trackers such as Microsoft, Google, and Amazon. Try Adguard Home on your network.

Original article source at:  https://opensource.com/

#dns #server #opensource 

Set Up Your Own Open Source DNS Server

How to Install, Configure, and Maintain Linux DNS Server

The DNS (Domain Name System) is a naming system for computers, the service that does that is the DNS server which translates an IP address to a human-readable address.

This process is the backbone of the internet and a very important service in your server, so from that point, we will discuss DNS server or specifically Linux DNS server and how to install, configure and maintain it.

The /etc/hosts file

Every system will have to keep its copy of the table of the hostnames and their IP addresses. This file is responsible for IP addresses.

On Linux systems, this table is the /etc/hosts file.

So even if you don’t have a DNS server or DNS server is unavailable, this file can translate IP addresses to names using /etc/hosts file.

That means the system query this file first before going to the DNS server, and if it finds the domain, it will translate it without going to any DNS servers.

Try to edit /etc/hosts and type the following:

127.0.0.1              google.com

Then go to your browser and type google.com and see the results. If you have Apache server installed on your system and your localhost is running, it will show the index page of the localhost instead of the google page.

You can translate google.com to any other IP address of any site and see the result to ensure that.

So what this file is doing is translating IP addresses to names, but this for the same connected network. So what about the outside networks and how to maintain all those records for all systems?

Will everybody manages his own /etc/hosts file and update it himself? Of course not.

Domain names

When you visit a website, you type the FQDN (Fully Qualified Domain Name) or the domain name like this: likegeeks.com or www.google.com

Each domain consists of domain components; the dot separates these components.

The text com is the top-level domain component, and google is the second-level domain component, and www is the third-level domain component

When you visit any website, the browser silently adds a dot at the end, but not visible to you, so the domain will be like www.google.com. Notice the dot after .com; this dot is called the root domain.

But why we added this root domain or the dot?

Because this dot is served by the root name servers, at the time of this post, there are 13 root name servers in the world, you can think of them as the brain of the internet, if they go OFF the world will be without the internet.

And why 13?

Because maybe an earthquake or a natural disaster happens in one place in the world may destroy a root server, so the others serve until the damaged server returns online.

Those root name servers have names like this: a.root-server.net, b.root-server.net, and so on.

Top Level domain names (TLDs)

We saw a top-level domain component, such as com domains.

Top-level domains (TLDs) are divided into categories based on geographical or functional aspects.

There are more than 800 top-level domains on the web at the time of writing this post.

The top-level domains categories are:

  • Generic top-level domain like (.org, .com, .net, .gov, .edu and so on).
  • Country-code top-level domains like (.us, .ca, and so on) corresponding to the country codes for the United States and Canada, respectively.
  • New branded top-level domains like (.linux, .microsoft, .companyname and so on).
  • Infrastructure top-level domains like the .arpa domain.

Subdomains

When you visit a website like mail.google.com, the mail here is a subdomain of google.com.

Only the name servers for mail.google.com know all the hosts existing beneath it, so google answers if there is mail subdomain or not, the root name servers have no clue about that.

Types of DNS servers

There are three types of DNS servers:

  • Primary DNS servers: They contain the domain’s configuration files, and they respond to the DNS queries.
  • Secondary DNS server: They work as a backup and load distribution. Primary servers know the existence of the secondary name servers and send updates to them.
  • Caching DNS server: All they do is caching the DNS responses, so you don’t need to ask the primary or secondary DNS server again. You can make your system work as a caching server easily, as we will see later on this post.

Setting up Linux DNS server

There are many packages on Linux that implement DNS functionality, but we will focus on the BIND DNS server. Many servers around the world use it.

If you are using Red Hat based distro like CentOS, you can install it like this:

$ dnf -y install bind

Or on Debian based systems like Ubuntu:

$ apt-get install bind9

Once the installation completed, you can start it and enable it to run at boot time.

$ systemctl start named

$ systemctl enable named

Configuring BIND

The service configuration is /etc/named.conf file.

There are some statements that BIND uses in that file like:

optionsused for global BIND configuration.
loggingwhat can be logged and what can be ignored. I recommend you review the Linux syslog server.
zonedefine DNS zone.
includeto include another file in named.conf.

From the options statement, you can see that the working directory for BIND is /var/named directory.

The zone statement enables you to define a DNS zone.

Like the domain google.com which also has subdomains like mail.google.com and analytics.google.com and other subdomains.

Every one of these three (the domain and subdomains) has a zone defined by the zone statement.

Defining a primary zone

We know from the DNS server types that there are primary, secondary, and cache DNS servers.

Primary and secondary are equally authoritative in their answers, unlike the caching server.

To define a primary zone, you can use the following syntax:

/etc/named.confzone     
"likegeeks.com" {
type master;
file likegeeks.com.db
};

The file that contains the zone information is located in /var/named directory since this is the working directory, as we know from the options.

Note that the server software or the hosting panel you’re using creates this file with this name automatically for you, so if your domain is example.org, the file will be /var/named/example.org.db.

The type is master, which means this is a primary zone.

Defining a secondary zone

The same as the primary zone definition with little change.

zone      "likegeeks.com" {
type slave;
masters Primary Nameserver IP Address Here; ;
file likegeeks.com.db
};

In the secondary zone, the domain is the same as the primary zone, and the type slave here means this is a secondary zone, and the masters option to list the IP addresses of the primary nameserver and finally, the file is the path of the primary’s zone files.

Defining a caching zone

It is necessary to have a caching zone, so you decrease the queries on the DNS server.

To define a caching zone, you need to define three-zone sections the first one:

zone      "." IN {
type hint;
file "root.hint";
};

The first line contains a dot, which is the root name servers. The type hint, which means a caching zone entry, and the file “root.hints”; specifies the file that contains the root servers ( the 13 root name server). You can get the latest root name server from http://www.internic.net/zones/named.root

The second zone defined in the /etc/named.rfc1912.zones file and included in /etc/named.conf via include directive, which is already included by default.

zone      "localhost" IN {
type master;
file "localhost.db";
};

The third zone defines the reverse lookup for the localhost.

zone      "0.0.127.in-addr.arpa" IN {
type master;
file "127.0.0.rev";
};

Putting these three zones on /etc/named.conf will make your system work as a caching DNS server. Now you should type the content of the files referenced like likegeeks.com.db, localhost.db, and 127.0.0.rev.

These files contain the DNS record types for each zone with some options. So what are those DNS record types and how to write them?

DNS records types

The database files consist of record types like SOA, NS, A, PTR, MX, CNAME, and TXT.

So let’s start with each record type and see how we can configure it.

SOA: Start of Authority Record

The SOA record describes the site’s DNS entries with the following format:

example.com.      86400      IN      SOA      ns1.example.com.      mail.example.com.      (
2017012604 ;serial
86400 ;refresh, seconds
7200 ;retry, seconds
3600000 ;expire, seconds
86400 ;minimum, seconds
)

The first line starts with the domain example.com. and ends with a period. Which is the same as the zone definition in /etc/named.conf file.

Keep in mind that DNS configuration files are extremely picky.

The IN word means Internet record.

The SOA word means Start of Authority record.

The ns1. example.com. is the domain’s name server.

The mail.host.com. is the domain administrator email. You may notice there is no @ sign, and we replaced it with the period, and there is a trailing period.

Line 2 is the serial number, we use it to tell the name server about the file update time, so if you make a change to the zone data, you have to increment this number. The serial number has the format YYYYMMDDxx where xx is starting from 00.

Line 3 is the refresh rate in seconds. How often secondary DNS servers should query the primary server to check for updates.

Line 4 is the retry rate in seconds. This is the time that the secondary DNS server takes for waiting after trying to connect to the primary DNS server and cannot reach it. The specified number of retry seconds.

Line 5 is the expire directive. If the secondary server cannot connect to the primary server for an update, it should discard the value after the specified number of seconds.

Line 6 tells the caching servers can’t connect to the primary DNS server; they wait before expiring an entry, this line defines the wait time.

NS: Name Server records

You can use the NS record to specify the name servers for a zone. The NS records are like this:

IN           NS         ns1.example.com.
IN           NS         ns2.example.com.

You don’t have to create two NS records, but we prefer to have backup name servers.

A and AAAA: address records

The A record maps the hostname to an IP address:

support IN          A             192.168.1.5

If you have a host at support.example.com on address 192.168.1.5, you can type like the above example.

Note: we wrote the host without a period.

PTR: pointer records

The PTR record is for doing the reverse name resolution, you give an IP address, and it returns the hostname.

This is the opposite of what A record does.

192.168.1.5        IN            PTR        support.example.com.

Here we type the full hostname with the trailing period.

MX: Mail exchange records

The MX record tells about the mail server records.

example.com.   IN           MX         10           mail

The domain ends with a period; the number 10 is the importance of the mail server, if you have multiple mail servers, the lower number is the less important.

CNAME: Canonical Name Records

CNAME records are like shortcuts for hostnames.

Suppose you have a site that has a hostname of whatever-bignameis.example.com, and since the system is a web server, an alias of www or CNAME record can be created for the host.

So you can create a CNAME record to make the name www.example.com:

whatever-bignameis      IN           A                    192.168.1.5
www                     IN           CNAME                whatever-bignameis

The first line tells the DNS server about the location of the alias; the second line creates the alias that points to www.

TXT records

You can put any text on TXT records like your contact information or any other information you want the people to know when they query your DNS server.

You can write TXT records like this:

example.com.   IN           TXT         " YOUR INFO GOES HERE"

Also, you can use the RP record to put the contact information.

example.com.   IN           RP           mail.example.com.         example.com.

DNS TTL value

In /etc/named.conf on the top there is $TTL entry.

This entry informs BIND about the time to live value for each individual record.

It takes a value in seconds like 14400 seconds (4 hours), so the DNS servers will cache your zone up to four hours then will query your DNS server again.

You can lower the value, but the default value is fair unless you know what you are doing.

Catching configuration errors

When you write your zone files, maybe you forget a period or space or any other error.

You can diagnose your Linux DNS server errors from the log. The BIND service through errors in /var/log/messages, you can use the tail command to view real-time error log using -f option.

$tail -f /var/log/messages

So when you write a zone file or modify /etc/named.config and restart your service and it shows an error, you can easily identify the error from the log.

Host command

After you have successfully added or modified your records, you can use the host command to see if your host if resolved correctly.

If you give it a hostname, it will answer with the corresponding IP addresses.

$ host example.com

Also, you can perform reverse lookups.

$ host 192.168.1.5

You can check the host and dig command.

Whois command

You can use the whois command to get the domain owner’s details.

Also, the owner’s email addresses, and contact phone numbers.

$ whois example.com

The rndc command

You can use the rndc tool to manage the name server securely.

You can check the status of the Linux DNS server like this:

$ rndc status

Also, if you make a change to any of the zone files, you can reload the service without restart the named service.

$ rndc reload example.com

Here we reload the example.com zone file.

You can reload all zones like this:

$ rndc reload

Or maybe you add new zones or change the configuration of the service; you can reload the configuration like this:

$ rndc reconfig

Linux DNS resolver

We’ve seen how a Linux DNS server works and how to configure it. The other part is the client who is contacting the DNS server.

The client is the resolver; you can check the configuration file /etc/resolv.conf

On Debian based distros, you can check /etc/resolvconf/resolv.conf.d/ directory.

The /etc/resolv.conf file contains the local DNS servers that the system uses.

The first line is for the default search domain, and the second line indicates the IP address of the name server.

You can use your own DNS server once your BIND service running, just type them in the resolver.conf file.

Original article source at:  https://likegeeks.com/

#linux #dns #server 

How to Install, Configure, and Maintain Linux DNS Server

How to Install, Configure, and Secure FTP Server in Linux

FTP or File Transfer Protocol is a commonly-used protocol for transferring files between computers; one act as a client, the other act as a server. In this post, we will talk about the FTP server in Linux systems, specifically Very Secure FTP Daemon (vsftpd).

The vsftpd program is a very popular FTP server that many servers use today.

How does FTP server work?

FTP server works with the client-server architecture to communicate and transfer files.

FTP is a stateful protocol, which means connections between clients and servers stay open during an FTP session.

To send or receive files from an FTP server, you can use FTP commands; these commands are executed consecutively. It is like a queue, one by one.

There are two types of FTP connections you can initiate:

  • Control connection also called a command connection.
  • Data connection.

When you establish an FTP connection, the TCP port 21 opens to send your login credentials; this connection is called control connection.

When you transfer a file, the data connection starts.

There are two types of data connection:

  • Passive mode.
  • Active mode.

Active connections are initiated by the remote server, and the client waits for server requests.

Passive connections initiated by the client to the remote server, and the server waits for requests.

When the FTP client starts a transfer, there is an option on your FTP client that controls whether you want to use active or passive FTP connection.

Active mode

The client connects from a random ephemeral source port to the FTP control port 21.

You can check your ephemeral port range using this command:

$ cat /proc/sys/net/ipv4/ip_local_port_range

When you need to transfer a file, the remote FTP server will open port 20 to connect to the FTP client.

Active mode connections usually have problems with firewalls, TCP ports 20 and 21 should be open on your firewall.

Because of these problems with firewalls of active mode, we can use the passive mode.

If you are using the iptables firewall, I recommend you review the Linux iptables firewall to know how to allow specific ports.

Passive mode

In passive mode, the client starts the control connection from a random port to the destination port 21 on the remote server.

If the FTP client requests a file, it will issue the PASV FTP command. The server will open a random port and give this port number to the client.

That’s why the FTP is a connection-hungry protocol because every time you make a data connection (like transfer a file), the server will do the above process, and this is done with all clients connected to the server.

In passive mode, the control and data connections started by the FTP client.

Vsftpd FTP server features

There are several FTP servers available for you to use, commercial and open source.

Vsftpd has some security features which makes it on the top like:

  • Can run as a normal user with privilege separation.
  • Supports SSL/TLS FTP connections.
  • Can jail users into their home directories.

FTP server setup

Some Linux distros shipped with vsftpd, anyway, if you want to install it on Red Hat based systems, you can use the following command:

$ sudo dnf -y vsftpd

On Debian based distros like Ubuntu, you can install it like this:

$ sudo apt-get install vsftpd

Once you’ve installed the package, you can run the service and enable it to run at boot time.

$ systemctl start vsftpd
$ systemctl enable vsftpd

The configuration file for vsftpd FTP server is

/etc/vsftpd.conf

.

Actually, the FTP server in Linux is one of the easiest servers that you can work with.

There are two types of accessing the FTP server:

  • Anonymous FTP access: anyone can log in with the username anonymous without a password.
  • Local user login: all valid users on /etc/passwd are allowed to access the FTP server.

You can allow anonymous access to the FTP server from the configuration, in /etc/vsftpd/vsftpd.conf by enabling anonymous_enable=YES if it is not enabled and reload your service.

Now you can try to connect to the FTP server using any FTP client. I will use the simple FTP command.

You can install it if it’s not on your system:

$ dnf -y install ftp

Now you can access your FTP server like this:

$ ftp localhost

Then type the username anonymous and with no password, just press enter.

You will see the FTP prompt.

ftp>

And now, you can type any FTP command to interact with the FTP server.

Connect as a local user

Since there is an option in the settings for allowing local users to access FTP server which is local_enable=YES, now let’s try to access the FTP server using a local user:

$ ftp localhost

Then type your local username and the password for that user, and you will see Login successful message.

Setup FTP server as anonymous only

This kind of FTP server is useful if your files should be available for users without any passwords or logins.

You need to configure vsftpd to allow only anonymous users.

Open /etc/vsftpd/vsftpd.conf file, and change the following options with the corresponding values.

listen=NO
listen_ipv6=NO
anonymous_enable=YES
local_enable=NO
write_enable=NO

Then we need to create a non-privileged system account to use it for anonymous FTP-type access.

$ useradd -c " FTP User" -d /var/ftp -r -s /sbin/nologin ftp

This user has no privileges on the system, so it is safer to use it when accessing an FTP server.

Don’t forget to restart your FTP server after you modify the configuration file.

You can access the FTP server from the browser, just type ftp://youdomain/.

FTP server security

We can configure vsftpd to use TLS, so the transferred files over the network is a bit more secure.

First, we generate a certificate request using the openssl command:

$ openssl genrsa -des3 -out FTP.key

Then we generate a certificate request:

$ openssl req -new -key FTP.key -out certificate.csr

Now we remove the password from the key file:

$ cp FTP.key FTP.key.orig

$ openssl rsa -in FTP.key.orig -out ftp.key

Finally, we generate our certificate:

$ openssl x509 -req -days 365 -in certificate.csr -signkey ftp.key -out mycertificate.crt

Now we copy the certificate file and the key and to /etc/pki/tls/certs:

$ cp ftp.key /etc/pki/tls/certs/

$ cp mycertificate.crt /etc/pki/tls/certs

Now, all we need to do is to configure vsftpd to support secure connections.

Open / etc/vsftpd/vsftpd.conf file and add the following lines:

ssl_enable=YES
allow_anon_ssl=YES
ssl_tlsv1=YES
ssl_sslv2=NO
ssl_sslv3=NO
rsa_cert_file=/etc/pki/tls/certs/mycertificate.crt
rsa_private_key_file=/etc/pki/tls/certs/ftp.key
ssl_ciphers=HIGH
require_ssl_reuse=NO

Restart your service to reflect these changes. And that’s it.

Try to connect to your FTP server from any client on any system like Windows and choose the secured connection or FTPS, and you will successfully see your folders.

SFTP vs. FTPS

In the last example, we saw the FTP over the SSL layer (FTPS), and we’ve successfully connected to the FTP server. However, with the tightly secured firewall, it is difficult to manage this kind of connection since FTPS uses multiple port numbers.

The best solution, in this case, is to use SFTP (FTP over SSH).SFTP uses port 22 only.

The FTP server will use this port for all connections during FTP sessions.

If you are using a firewall, you should choose SFTP, since it needs only one port.

Jailing FTP users

You can secure your FTP server by jailing your FTP users in their home directories and allow only specific users to access the service.

Open /etc/vsftpd/vsftpd.conf and uncomment the following options:

chroot_local_user=YES
chroot_list_enable=YES
chroot_list_file=/etc/vsftpd.chroot_list

The file /etc/vsftpd.chroot_list contains the list of jailed users one per line.

Save the files and restart your service.

$ systemctl restart vsftpd

Linux FTP server commands

You can use any GUI client to upload and download your files, but you need to know some FTP server commands also.

The first command is the pwd command,  you can use it to print the current working directory:

ftp> pwd

You can list files using the ls command:

ftp> ls

Also, you can use the cd command to change the working directory:

ftp> cd /

If you want to exit your FTP session, use the bye command:

ftp> bye

We use the lcd command to display the local folder, not the FTP folder:

ftp> lcd

You can change the local directory using the lcd command:

ftp> lcd /home

You can download a file using the get command:

ftp> get myfile

Also, you can download multiple files using the mget command:

ftp> mget file1 file2

Use delete command to delete a file from the server:

ftp> delete filename

Use put command to upload a file to the server:

ftp> put filename

To upload multiple files, use the mput command:

ftp> mput file1 file2

You can create a directory using the mkdir command:

ftp> mkdir dirName

Or you can delete a directory from the server using the rmdir command.

ftp> rmdir dirName

There are two modes for file transfer when using FTP server, ASCII mode, and binary mode, you can change the mode like this:

ftp> binary

ftp> ascii

The FTP server is one of the easiest servers in Linux to configure and work with.

I hope you find the post useful and interesting. Keep coming back.

Thank you.

Original article source at:  https://likegeeks.com/

#linux #install #configure #ftp #server 

How to Install, Configure, and Secure FTP Server in Linux

Как установить, настроить и устранить неполадки веб-сервера Linux

В этом руководстве мы поговорим о веб-сервере Linux или веб-сервере Apache, а также о том, как его установить и настроить для предоставления вашего контента другим.

Веб-сервер — это система, которая манипулирует запросами по протоколу HTTP, вы запрашиваете файл с сервера, и он отвечает запрошенным файлом, что может дать вам представление о том, что веб-серверы предназначены не только для Интернета.

Веб-серверы, встроенные в такие устройства, как принтеры, маршрутизаторы, когда вы открываете страницу конфигурации маршрутизатора, за ней находится веб-сервер.

Когда вы открываете страницу конфигурации принтера, за ней также находится веб-сервер, обслуживающий ваши запросы, поэтому веб-серверы повсюду.

Как работает веб-сервер

Сначала ваш браузер отправляет запрос на сервер.

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

Иногда запрошенный файл представляет собой статическую страницу, такую ​​как страницы HTML, или динамические страницы, такие как PHP, Java, Perl или любой другой серверный язык.

Например, когда вы вводите www.yourDomain.com, браузер запрашивает у DNS-сервера IP-адрес компьютера: www.yourDomain.com. Как только браузер получает ответ от DNS, он запускает TCP-соединение на порту 80 и запрашивает веб-страницу по умолчанию, затем сервер отправляет эту страницу вам, и все.

Реализации веб-сервера Linux

Для вас доступно множество реализаций веб-сервера Linux:

  • сервер Apache
  • Nginx
  • Lighttpd
  • Апач Томкэт
  • Monkey HTTP Daemon (используется специально для встроенных систем)

Есть и другие веб-серверы Linux, но этот список является наиболее используемым веб-сервером.

Наиболее часто используемыми веб-серверами являются Apache и Nginx.

В этом посте мы будем использовать сервер Apache по нескольким причинам:

  • Стабильный.
  • Гибкий.
  • Безопасный.

Мы установим и настроим сервер Apache в Linux, но сначала давайте рассмотрим некоторые основы протокола HTTP.

Понимание HTTP

Когда вы запрашиваете файл или страницу с веб-сервера, клиент сначала подключается к серверу через порт 80. После успешного подключения клиент отправляет HTTP-команды (также методы) на сервер. Эта команда включает заголовок запроса, который включает информацию о клиенте.

Чтобы просмотреть эти заголовки запросов в chrome, откройте chrome devtools, затем откройте сетевую панель и посетите google.com и проверьте заголовки запросов, вы должны увидеть что-то вроде этого:

Заголовок запроса также включает информацию о клиенте, такую ​​как пользовательский агент и принятые форматы.

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

После полного получения заголовка запроса сервер отвечает запрошенным файлом или страницей вместе с заголовком ответа.

Заголовок ответа включает информацию о полученном контенте, его типе и другую информацию.

Вы можете проверить заголовки ответа из сетевой панели браузера.

Установить веб-сервер Apache

Вы можете установить сервер Apache в дистрибутивах на основе Red Hat, используя следующую команду:

$ dnf -y httpd

Или, если вы используете дистрибутив на основе Debian, вы можете установить его следующим образом:

$ apt-get -y install apache2

Служба веб-сервера Apache называется httpd в дистрибутивах на основе Red Hat, таких как CentOS, а в дистрибутивах на основе Debian она называется apache2 .

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

$ iptables -I INPUT 1 -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT

Или, если вы используете firewalld , вы можете использовать следующую команду:

$ firewall-cmd --add-port=80/tcp

Чтобы запустить службу и включить ее при загрузке:

$ systemctl start httpd

$ systemctl enable httpd

Вы можете проверить, работает ли ваша служба или нет, используя следующую команду:

$ systemctl status httpd

Теперь откройте браузер и посетите http://localhost или http://[::1]/, если вы используете IP v6, и если установка прошла успешно, вы должны увидеть свою домашнюю страницу в формате HTML.

Настройка веб-сервера Apache

Вы можете добавлять файлы в Apache в

/var/www/html

каталог для страниц верхнего уровня.

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

Индексной страницей по умолчанию является index.html.

Файлы конфигурации Apache находятся в

/etc/httpd/conf/

каталог.

В системах на основе Debian, таких как Ubuntu, вы можете найти его по адресу

/etc/apache2/apache2.conf

файл.

Мы не можем обсуждать каждый вариант Apache в одном посте, но мы обсудим наиболее важные параметры.

Вы называете их опциями или директивами.

Опция ServerRoot

Этот параметр указывает папку конфигурации для веб-сервера Apache. В дистрибутивах на базе Red Hat параметр ServerRoot — это каталог /etc/httpd/ . В дистрибутивах Debian параметр ServerRoot — /etc/apache2/ .

ServerRoot /etc/httpd

Вариант прослушивания

Опция Listen указывает порт, который веб-сервер Apache будет использовать для ожидания входящих подключений.

Значение по умолчанию для этого параметра — 80 для незащищенных соединений и 443 для защищенных соединений.

Если у вас есть несколько IP-адресов на вашем сервере, вы можете назначить IP-адрес, который должен прослушивать соединение, используя опцию Listen.

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

Вы можете запускать множество HTTP-серверов на одном и том же оборудовании, каждый из которых использует уникальный порт.

Когда сервер работает на нестандартном порту, таком как порт 8080, он потребует, чтобы номер порта был явно указан следующим образом:

www.example.com:8080

Listen 80

Параметр имя_сервера

Этот параметр указывает имя хоста веб-сервера, которое отображается для посетителей.

ServerName FQDN

Параметр DocumentRoot

Параметр DocumentRoot определяет путь, который будет содержать ваши файлы, которые будут обслуживаться.

Путь по умолчанию — /var/www/html.

DocumentRoot /var/www/html

Параметр MaxRequestWorkers

Этот параметр устанавливает максимальное количество одновременных подключений, которые будет получать сервер.

Опция LoadModule

Мы используем эту опцию для загрузки модулей на веб-сервер Apache.

Есть много таких модулей Apache:

mod_cgid : этот модуль запускает сценарии CGI с использованием веб-сервера Apache.

mod_ssl : обеспечивает безопасное соединение по протоколам SSL и TLS.

mod_userdir : этот модуль позволяет вам обслуживать контент из определенных каталогов пользователей.

Если вы хотите отключить загрузку определенного модуля, вы можете прокомментировать строку «Загрузить модуль», содержащую этот модуль.

Или, если вы используете дистрибутивы на основе Debian, такие как Ubuntu, вы можете использовать эти команды:

$ a2enmod modulename

a2enmod включает модуль.

$ a2dismod modulename

Эта команда для отключения модуля.

Все эти команды создают символическую ссылку под

/etc/apache2/mods-enabled

И если вы используете a2dismod, симлинк будет удален.

Если вы включаете или отключаете модуль, вам необходимо перезагрузить или перезапустить веб-сервер Apache.

LoadModule mod_cgid.so

Включить опцию

Эта опция позволяет включать другие файлы конфигурации.

Вы можете хранить всю конфигурацию для разных виртуальных доменов, и Apache включит их во время выполнения.

Include filePath

Опция UserDir

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

Например, если у вас есть пользователь adam, который хочет сделать свой веб-контент доступным через веб-сервер Apache.

Во-первых, мы создаем папку public_html в его домашнем каталоге.

Затем установите разрешение для папки public_html:

$ chmod 644 public_html

Теперь, если мы поместим файл index.html, он будет доступен через браузер следующим образом:

http://ВАШЕХОСТНОЕИМЯ/~адам

UserDir public_html

Опция псевдонима

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

Например, у вас есть файлы вне DocumentRoot, и вы хотите, чтобы они были доступны посетителям.

Alias URL_Path Actual_Path

Опция журнала ошибок

Этот параметр указывает файл журнала ошибок для веб-сервера Apache.

ErrorLog /var/log/httpd/error_log

Вариант виртуального хоста

Этот вариант позволяет размещать несколько веб-сайтов на одном сервере.

Идея состоит в том, что контент обслуживается на основе запрошенного имени хоста.

Чтобы настроить виртуальный хост для хоста www.example.com. Сначала создайте параметр VirtualHost в файле /etc/httpd/conf/httpd.conf .

И укажите DocumentRoot и ServerName следующим образом:

<VirtualHost www.example.com>
 ServerAdmin admin@example.com
 DocumentRoot /home/adam/public_html
 ServerName www.example.com
 ErrorLog /var/log/users/adam/error_log
</VirtualHost>

Имейте в виду, что параметр ServerName должен разрешаться через DNS.

Это наиболее часто используемые параметры Apache.

Типы виртуальных хостов

Существует два типа виртуальных хостов, которые вы можете определить на веб-сервере Apache:

  • Виртуальные хосты на основе имени
  • Виртуальные хосты на основе IP

Директива NameVirtualHost определяет, какие адреса могут быть виртуальными хостами; звездочка (*) означает любое имя или адрес на этом сервере. Вы можете написать их так:

NameVirtualHost *
<VirtualHost *>
 ServerName www.example.com
 DocumentRoot "/home/user1/public_html/"
</VirtualHost>
<VirtualHost *>
 ServerName www.example2.com
 DocumentRoot "/ home/user2/public_html/"
</VirtualHost>

Если у вас более одного IP-адреса и вы хотите использовать SSL-сертификат, веб-сайт должен находиться на выделенном IP-адресе. Вы можете написать виртуальные хосты на основе IP следующим образом:

<VirtualHost 192.168.1.2>
 ServerName www.example.com
 DocumentRoot "/home/user1/public_html/"
</VirtualHost>
<VirtualHost 192.168.1.3>
 ServerName www.example2.com
 DocumentRoot "/ home/user2/public_html/"
</VirtualHost>

Владение процессом Apache

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

Этот факт верен для всех процессов, кроме приложений с установленным битом SETUID; они наследуют разрешения от владельца, а не от родительского процесса. Хорошим примером является файл /bin/su.

Если обычный пользователь запускает программу /bin/su, он не наследует разрешения от adam, а действует как пользователь root, запускающий ее.

Поскольку веб-серверу Apache необходимо привязать порт 80, а для этого нужны привилегии root.

После привязки к порту 80 Apache может работать как обычный пользователь и читать только те файлы, у которых есть права на их чтение.

В зависимости от используемого вами дистрибутива Linux пользователь может быть одним из следующих:

никто, www, apache, www-data или демон.

Я отложил введение еще двух опций для Apache, пока не дошел до этого момента.

Опция пользователя

Параметр «Пользователь» указывает идентификатор пользователя, который веб-сервер будет использовать для ответа на запросы.

User www-data

Групповой вариант

Параметр «Группа» указывает группу, которую веб-сервер Apache будет использовать для чтения файлов.

Group www-data

Безопасность очень важна для сайтов, использующих исполняемые сценарии, такие как сценарии CGI или PHP.

Пользователь, которого вы будете использовать, будет иметь  разрешение на чтение и запись содержимого всех сайтов на сервере. Но мы хотим, чтобы только участники определенного сайта могли читать только его сайт.

Это очень важно, потому что, если злоумышленник взломает ваш сайт, он сможет прочитать все файлы, поскольку у пользователя Apache есть разрешение на это.

Итак, как решить эту проблему?

поддержка suEXEC

Популярным методом является использование suEXEC. suEXEC — это программа, которая запускается с правами root и запускает программы CGI от имени пользователя и группы ID конкретного пользователя, а не пользователя сервера Apache.

Вы можете указать пользователя на каждом виртуальном хосте следующим образом:

<VirtualHost www.example.com>
 SuExecUserGroup adam adamGroup
</VirtualHost>

Вот так просто.

аутентификация Apache

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

В Apache вы можете хранить файл информации об аутентификации с именем . файл htpasswd.

Для этого вы можете использовать команду htpasswd.

Сначала создайте файл .htpasswd с помощью команды htpasswd:

$ htpasswd -c /home/adam/.htpassswd myuser

Вам понадобится опция -c при первом запуске htpasswd, но когда вам нужно добавить больше пользователей, вам не следует использовать -c, потому что это приведет к перезаписи файла.

Затем создайте файл .htaccess в папке public_html и напишите следующее:

<Location /vip>
 AuthName "test"
 AuthType Basic
 AuthUserFile /home/adam/.htpasswd
 Order deny,allow
 require valid-user
</Location>

Требуется AuthName, вы можете использовать любую строку.

AuthType Basic говорит, что вы используете пользовательский файл в стиле htpasswd.

AuthUserFile указывает на файл, содержащий пароль, сгенерированный командой htpasswd.

Строка Order указывает, что Apache должен запрещать доступ по умолчанию и разрешать доступ только пользователям, указанным в файле htpasswd.

Директива require означает, что любой пользователь в файле .htpasswd разрешен.

Устранение неполадок веб-сервера Apache

Если вы изменили файл httpd.conf и перезапустили или перезагрузили веб-сервер Apache, но это не сработало, значит, вы ввели неправильную конфигурацию. Однако это не единственный случай, когда вам необходимо устранить неполадки с Apache. Вы можете просмотреть журналы Apache, чтобы увидеть, как работает служба, чтобы вы могли диагностировать проблему и решить ее.

Двумя основными файлами журналов для Apache являются файлы error_log и access_log .

Вы можете найти эти файлы в

/var/log/apache2/

каталог, если вы используете дистрибутивы на основе Debian.

Файл access_log содержит каждый запрос к веб-серверу Apache с подробной информацией о клиенте, запросившем этот ресурс.

Файл error_log содержит ошибки веб-сервера Apache.

Вы можете использовать команду tail для просмотра файла журнала:

$ tail -f /var/log/httpd/error_log

Я рекомендую вам ознакомиться с сервером системного журнала Linux  , чтобы узнать больше о ведении журнала.

Оригинальный источник статьи:   https://likegeeks.com/

#linux #web #server 

Как установить, настроить и устранить неполадки веб-сервера Linux

如何安装、配置 Linux Web 服务器并排除故障

在本教程中,我们将专门讨论 Linux 网络服务器或 Apache 网络服务器,以及如何安装和配置它以向其他人提供您的内容。

网络服务器是一个通过 HTTP 协议处理请求的系统,你向服务器请求一个文件,它以请求的文件作为响应,这可能会让你觉得网络服务器不仅仅是为了网络。

Web服务器嵌入在打印机、路由器等设备中,当你打开你的路由器配置页面时,背后有一个Web服务器。

当你打开打印机配置页面时,它背后还有一个网络服务器在为你的请求服务,所以网络服务器无处不在。

Web 服务器的工作原理

首先,您的浏览器向服务器发送请求。

服务器从您那里获取请求的文件或页面,并将其映射到服务器的相应文件。服务器将文件连同一些信息(如 MIME 类型、内容长度和其他有用信息)发送回浏览器。

有时,请求的文件是静态页面(如 HTML 页面)或动态页面(如 PHP、Java、Perl 或任何其他服务器端语言)。

例如,当您键入 www.yourDomain.com 时,浏览器会向DNS 服务器查询计算机的 IP 地址:www.yourDomain.com。一旦浏览器从 DNS 得到响应,它就会在端口 80 上启动一个 TCP 连接并请求默认网页,然后服务器将这个页面发送给你,就这样。

Linux Web 服务器实现

有许多 Linux Web 服务器实现可供您使用:

  • 阿帕奇服务器
  • Nginx
  • Lighttpd
  • 阿帕奇汤姆猫
  • Monkey HTTP 守护进程(特别用于嵌入式系统)

有更多的 Linux Web 服务器,但这个列表是使用最多的 Web 服务器。

最常用的 Web 服务器是 Apache 和 Nginx。

在本文中,出于以下几个原因,我们将使用Apache 服务器:

  • 稳定的。
  • 灵活的。
  • 安全的。

我们将在 Linux 上安装和配置 Apache 服务器,但首先,让我们回顾一下 HTTP 协议的一些基础知识。

了解 HTTP

当您从 Web 服务器请求文件或页面时,客户端首先会在端口 80 上连接到服务器。连接成功后,客户端会向服务器发送 HTTP 命令(也包括方法)。此命令包含一个请求标头,其中包含有关客户端的信息。

要在 chrome 中查看这些请求标头,请打开 chrome devtools,然后打开网络面板并访问 google.com 并检查请求标头,您应该会看到如下内容:

请求标头还包括有关客户端的信息,例如用户代理和接受的格式。

Web 服务器可以发送带有请求标头的附加信息。例如,如果您单击将打开另一个网站的链接,标题将包含推荐网站。

在完全接收到请求标头后,服务器以请求的文件或页面以及响应标头进行响应。

响应标头包括有关接收到的内容、其类型和其他信息的信息。

您可以从浏览器网络面板检查响应标头。

安装 Apache 网络服务器

您可以使用以下命令在基于 Red Hat 的发行版上安装 Apache 服务器:

$ dnf -y httpd

或者,如果您使用的是基于 Debian 的发行版,则可以像这样安装它:

$ apt-get -y install apache2

Apache Web 服务器服务在基于 Red Hat 的发行版(如 CentOS)上称为httpd,而在基于 Debian 的发行版中称为apache2

如果你使用像 iptables 这样的防火墙,你应该 为端口 80添加一条规则。

$ iptables -I INPUT 1 -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT

或者,如果您使用的是 firewalld,则可以使用以下命令:

$ firewall-cmd --add-port=80/tcp

要启动您的服务并在启动时启用它:

$ systemctl start httpd

$ systemctl enable httpd

您可以使用以下命令检查您的服务是否正在运行:

$ systemctl status httpd

现在打开您的浏览器并访问http://localhosthttp://[::1]/如果您使用的是 IP v6,如果您的安装顺利,您应该会看到您的 HTML 主页。

配置 Apache 网络服务器

您可以将文件添加到 Apache 中

/var/www/html

顶级页面的目录。

请记住确保放置在该目录中的任何文件或目录都是世界可读的。

默认索引页是 index.html。

Apache 配置文件位于

/etc/httpd/conf/

目录。

在像 Ubuntu 这样基于 Debian 的系统上,你可以在

/etc/apache2/apache2.conf

文件。

我们无法在一篇文章中讨论 Apache 的所有选项,但我们将讨论最重要的选项。

您称它们为选项或指令。

服务器根选项

此选项指定 Apache Web 服务器的配置文件夹。在基于 Red Hat 的发行版上,ServerRoot 选项是/etc/httpd/目录。在 Debian 发行版上,ServerRoot 选项是/etc/apache2/

ServerRoot /etc/httpd

收听选项

Listen 选项指定 Apache Web 服务器将用于等待传入连接的端口。

对于非安全连接,此选项的默认值为80 ,对于安全连接,默认值为 443

如果您的服务器上有多个 IP 地址,您可以使用 Listen 选项分配哪个 IP 应该监听连接。

您可以指定 80 以外的其他端口,只要确保它未被使用即可。

您可以在同一硬件上运行多个 HTTP 服务器,每个服务器都在一个唯一的端口上。

当服务器运行在非标准端口(例如 8080 端口)上时,它会要求端口号像这样显式声明:

www.example.com:8080

Listen 80

服务器名称选项

此选项指定向访问者显示的 Web 服务器的主机名。

ServerName FQDN

DocumentRoot 选项

DocumentRoot 选项定义将包含将提供的文件的路径。

默认路径是 /var/www/html 。

DocumentRoot /var/www/html

MaxRequestWorkers 选项

此选项设置服务器将接收的最大并发连接数。

LoadModule 选项

我们使用此选项将模块加载到 Apache Web 服务器中。

有很多这样的 Apache 模块:

mod_cgid:此模块使用 Apache Web 服务器运行 CGI 脚本。

mod_ssl:通过 SSL 和 TLS 协议提供安全连接。

mod_userdir:此模块允许您提供来自用户特定目录的内容。

如果要禁用加载特定模块,可以注释包含该模块的 Load module 行。

或者,如果您使用基于 Debian 的发行版,例如 Ubuntu,您可以使用这些命令:

$ a2enmod modulename

a2enmod 启用该模块。

$ a2dismod modulename

此命令禁用模块。

所有这些命令所做的就是在下面创建一个符号链接

/etc/apache2/mods-enabled

如果您使用 a2dismod,符号链接将被删除。

如果启用或禁用模块,则必须重新加载或重新启动 Apache Web 服务器。

LoadModule mod_cgid.so

包括选项

此选项允许您包含其他配置文件。

您可以存储不同虚拟域的所有配置,Apache 将在运行时包含它们。

Include filePath

用户目录选项

此选项指定将包含可通过 Web 服务器访问的文件的目录。该目录通常是 public_html 及其在用户主目录中的位置。

例如,如果您有一个用户 adam,他想通过 Apache Web 服务器提供他的 Web 内容。

首先,我们在他的主目录下创建一个 public_html 文件夹。

然后设置public_html文件夹的权限:

$ chmod 644 public_html

现在,如果我们放置一个 index.html 文件,它将可以通过浏览器访问,如下所示:

http://你的主机名/~亚当

UserDir public_html

别名选项

此选项指定位于 DocumentRoot 位置之外且需要由 Apache Web 服务器提供服务的文件的位置。

就像您在 DocumentRoot 之外有文件,并且您希望访问者可以访问它们。

Alias URL_Path Actual_Path

错误日志选项

此选项指定 Apache Web 服务器的错误日志文件。

ErrorLog /var/log/httpd/error_log

虚拟主机选项

此选项允许您在同一台服务器上托管多个网站。

这个想法是根据请求的主机名提供内容。

为主机 www.example.com 设置虚拟主机。首先,在/etc/httpd/conf/httpd.conf文件中创建一个 VirtualHost 选项。

并像这样指定 DocumentRoot 和 ServerName:

<VirtualHost www.example.com>
 ServerAdmin admin@example.com
 DocumentRoot /home/adam/public_html
 ServerName www.example.com
 ErrorLog /var/log/users/adam/error_log
</VirtualHost>

请记住,ServerName 选项必须可通过 DNS 解析。

这些是最常用的 Apache 选项。

虚拟主机类型

您可以在 Apache Web 服务器中定义两种类型的虚拟主机:

  • 基于名称的虚拟主机
  • 基于 IP 的虚拟主机

NameVirtualHost 指令定义哪些地址可以是虚拟主机;星号 (*) 表示此服务器上的任何名称或地址。你可以这样写:

NameVirtualHost *
<VirtualHost *>
 ServerName www.example.com
 DocumentRoot "/home/user1/public_html/"
</VirtualHost>
<VirtualHost *>
 ServerName www.example2.com
 DocumentRoot "/ home/user2/public_html/"
</VirtualHost>

如果您有多个 IP 地址并且想使用 SSL 证书,则该网站必须位于一个专用 IP 地址上。您可以像这样编写基于 IP 的虚拟主机:

<VirtualHost 192.168.1.2>
 ServerName www.example.com
 DocumentRoot "/home/user1/public_html/"
</VirtualHost>
<VirtualHost 192.168.1.3>
 ServerName www.example2.com
 DocumentRoot "/ home/user2/public_html/"
</VirtualHost>

Apache 进程所有权

我们从 Linux的进程管理中知道 ,每个进程都从其父进程继承权限。

除了设置了 SETUID 位的应用程序之外,所有进程都是如此;他们从所有者而不是父进程继承权限。/bin/su 就是一个很好的例子。

如果普通用户运行/bin/su 程序,它不会继承adam 的权限,而是作为root 用户运行它。

由于 Apache Web 服务器需要绑定 80 端口,这需要 root 权限。

绑定80端口后,Apache可以以普通用户身份运行,只读取有读取权限的文件。

根据您使用的 Linux 发行版,用户可能是以下之一:

nobody、www、apache、www-data 或守护进程。

我推迟了为 Apache 引入另外两个选项,直到达到这一点。

用户选项

User 选项指定 Web 服务器将用来回答请求的用户 ID。

User www-data

组选项

Group 选项指定 Apache Web 服务器将用来读取文件的组。

Group www-data

对于使用 CGI 或 PHP 脚本等可执行脚本的站点,安全性非常重要。

您将使用的用户将有权 读取和写入服务器上所有站点的内容。但我们要确保只有特定站点的成员才能阅读他们的站点。

这非常重要,因为如果攻击者破坏了您的网站,他将能够读取所有文件,因为 Apache 用户有权这样做。

那么如何解决这个问题呢?

suEXEC支持

一种流行的方法是使用 suEXEC。suEXEC 是一个以 root 权限运行的程序,它使 CGI 程序以特定用户的用户和组 ID 运行,而不是 Apache 服务器用户。

您可以像这样在每个虚拟主机上指定用户:

<VirtualHost www.example.com>
 SuExecUserGroup adam adamGroup
</VirtualHost>

就这么简单。

Apache 身份验证

您可能希望将某些部分限制为特定访问者。它就像一个受密码保护的目录。

在 Apache 中,您可以将身份验证信息文件存储为. htpasswd 文件。

您可以使用 htpasswd 命令来做到这一点。

首先,使用 htpasswd 命令创建 .htpasswd 文件:

$ htpasswd -c /home/adam/.htpassswd myuser

第一次运行 htpasswd 时需要 -c 选项,但是当需要添加更多用户时,不应使用 -c,因为它会覆盖文件。

然后在public_html文件夹下新建一个.htaccess文件,写入如下内容:

<Location /vip>
 AuthName "test"
 AuthType Basic
 AuthUserFile /home/adam/.htpasswd
 Order deny,allow
 require valid-user
</Location>

AuthName 是必需的,您可以使用任何您想要的字符串。

AuthType Basic 表示您正在使用 htpasswd 样式的用户文件。

AuthUserFile 指向包含从 htpasswd 命令生成的密码的文件。

Order 行表示 Apache 必须默认拒绝访问,并且只允许 htpasswd 文件中指定的用户访问。

require 指令意味着允许 .htpasswd 文件中的任何用户。

Apache 网络服务器故障排除

如果您修改 httpd.conf 文件并重新启动或重新加载 Apache Web 服务器但它没有工作,那么您输入了错误的配置。但是,这并不是您需要对 Apache 进行故障排除的唯一情况。您可以查看 Apache 日志以了解该服务的工作方式,以便诊断问题并解决问题。

Apache 的两个主要日志文件是error_logaccess_log文件。

您可以在中找到这些文件

/var/log/apache2/

如果您使用的是基于 Debian 的发行版,请访问该目录。

access_log 文件包含对 Apache Web 服务器的每个请求,以及有关客户端请求该资源的详细信息。

error_log 文件包含 Apache Web 服务器的错误。

您可以使用tail 命令查看日志文件:

$ tail -f /var/log/httpd/error_log

我建议您查看Linux 系统日志服务器 以了解有关日志记录的更多信息。

文章原文出处:https:   //likegeeks.com/

#linux #web #server 

如何安装、配置 Linux Web 服务器并排除故障
Oral  Brekke

Oral Brekke

1678784400

How to Install, Configure, & Troubleshoot Linux Web Server

In this tutorial, we will talk about the Linux web server or Apache web server specifically and how to install it and configure it to serve your content to others.

A web server is a system that manipulates requests via the HTTP protocol, you request a file from the server, and it responds with the requested file, which might give you an idea that web servers are not only for the web.

Web servers embedded in devices such as printers, routers, when you open your router configuration page, there is a web server behind it.

When you open the printer configuration page, there is also a web server behind it serving your requests, so web servers are everywhere.

How web server works

First, your browser sends a request to the server.

The server takes the requested file or page from you and maps it to the corresponding file from the server. The server sends the file back to the browser with some information such as the MIME type, the length of the content, and other useful information.

Sometimes the requested file is a static page like HTML pages or dynamic pages like PHP, Java, Perl, or any other server-side language.

For example, when you type www.yourDomain.com, the browser queries the DNS server about the IP address of the computer: www.yourDomain.com. Once the browser gets the response from the DNS, it starts a TCP connection on port 80 and asks for the default web page, then the server sends this page to you, and that’s all.

Linux web server implementations

There are many Linux web server implementations available for you to use:

  • Apache server
  • Nginx
  • Lighttpd
  • Apache Tomcat
  • Monkey HTTP Daemon (used especially for embedded systems)

There are more Linux web servers, but this list is the most used web server.

The most used web servers are Apache and Nginx.

In this post, we will use the Apache server for several reasons:

  • Stable.
  • Flexible.
  • Secure.

We’ll install and configure Apache server on Linux, but at first, let’s review some of the basics of HTTP protocol basics.

Understanding HTTP

When you request a file or a page from a web server, the client at first connects to the server on port 80. After a successful connection, the client then sends HTTP commands (also methods) to the server. This command includes a request header, which includes information about the client.

To view these request headers in chrome, open chrome devtools, then open network panel and visit google.com and check the request headers, you should see something like this:

The request header also includes information about the client, like the user agent and the accepted formats.

The web server may send additional information with the request header. For example, if you click on a link that will open another website, the header will include the referral site.

After receiving the request header completely, the server responds with the requested file or page along with a response header.

The response header includes information about the received content, its type, and other information.

You can check the response headers from the browser network panel.

Install Apache web server

You can install Apache server on Red Hat based distros using the following command:

$ dnf -y httpd

Or if you are using a Debian-based distro, you can install it like this:

$ apt-get -y install apache2

The Apache web server service is called httpd on Red Hat based distros like CentOS, while it is called apache2 in Debian based distros.

If you are using a firewall like iptables, you should add a rule for port 80.

$ iptables -I INPUT 1 -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT

Or if you are using firewalld, you can use the following command:

$ firewall-cmd --add-port=80/tcp

To start your service and enable it on boot:

$ systemctl start httpd

$ systemctl enable httpd

You can check if your service is running or not, using the following command:

$ systemctl status httpd

Now open your browser and visit http://localhost or http://[::1]/ if you are using IP v6, and if your installation goes well, you should see your HTML homepage.

Configuring Apache web server

You can add files to Apache in the

/var/www/html

directory for top-level pages.

Just remember to make sure that any files or directories placed in that directory are world-readable.

The default index page is index.html.

The Apache configuration files are in

/etc/httpd/conf/

directory.

On Debian based systems like Ubuntu, you may find it at

/etc/apache2/apache2.conf

file.

We can’t discuss every option for Apache on a single post, but we will discuss the most important options.

You call them options or directives.

ServerRoot option

This option specifies the configuration folder for the Apache web server. On Red Hat based distros, the ServerRoot option is /etc/httpd/ directory. On Debian distros the ServerRoot option is /etc/apache2/.

ServerRoot /etc/httpd

Listen option

The Listen option specifies the port that the Apache web server will use to wait for incoming connections.

The default value for this option is 80 for nonsecure connections and 443 for secured connections.

If you have multiple IP addresses on your server, you can assign which IP should listen for connection using the Listen option.

You can specify a different port other than 80, just make sure that it’s not in use.

You can run many HTTP servers on the same hardware every one on a unique port.

When a server runs on a non-standard port such as port 8080, it will require the port number to be explicitly stated like this:

www.example.com:8080

Listen 80

ServerName option

This option specifies the hostname of the web server that appears to the visitors.

ServerName FQDN

DocumentRoot option

The DocumentRoot option defines the path that will contain your files that will be served.

The default path is /var/www/html .

DocumentRoot /var/www/html

MaxRequestWorkers option

This option sets the maximum number of concurrent connections that the server will receive.

LoadModule option

We use this option to load modules into the Apache web server.

There are a lot of Apache modules like these:

mod_cgid: This module runs CGI scripts using the Apache web server.

mod_ssl: Provides secure connections via SSL and TLS protocols.

mod_userdir: This module allows you to serve content from users’ specific directories.

If you want to disable loading a specific module, you can comment the Load module line that contains that module.

Or if you use Debian based distros like Ubuntu, you can use these commands:

$ a2enmod modulename

The a2enmod enables the module.

$ a2dismod modulename

This command to disable the module.

All these commands do is create a symlink under

/etc/apache2/mods-enabled

And if you use a2dismod, the symlink will be removed.

If you enable or disable a module, you have to reload or restart the Apache web server.

LoadModule mod_cgid.so

Include option

This option allows you to include other configuration files.

You can store all the configuration for different virtual domains, and Apache will include them at runtime.

Include filePath

UserDir option

This option specifies the directory that will contain the files that will be accessible via the web server. This directory is usually is public_html and its location in the user’s home directory.

For example, if you have a user adam who wants to make his web content available via the Apache web server.

First, we make a public_html folder under his home directory.

Then set the permission for the public_html folder:

$ chmod 644 public_html

Now if we put an index.html file, it will be accessible via the browser like this:

http://YOURHOSTNAME/~adam

UserDir public_html

Alias option

This option specifies the location of the files that are outside the DocumentRoot location and need to be served by the Apache web server.

Like you have files outside DocumentRoot, and you want them to be available to the visitors.

Alias URL_Path Actual_Path

ErrorLog option

This option specifies the error log file for the Apache web server.

ErrorLog /var/log/httpd/error_log

VirtualHost option

This option allows you to host multiple websites on the same server.

The idea is that the content is served based on the requested hostname.

To setup a virtual host for the host www.example.com. First, create a VirtualHost option in /etc/httpd/conf/httpd.conf file.

And specify the DocumentRoot and ServerName like this:

<VirtualHost www.example.com>
 ServerAdmin admin@example.com
 DocumentRoot /home/adam/public_html
 ServerName www.example.com
 ErrorLog /var/log/users/adam/error_log
</VirtualHost>

Keep in mind that the ServerName option must be resolvable via DNS.

These are the most used Apache options.

Virtual Host types

There are two types of virtual hosts that you can define in Apache web server:

  • Name-based virtual hosts
  • IP-based virtual hosts

The NameVirtualHost directive defines which addresses can be virtual hosts; the asterisk (*) means any name or address on this server. You can write them like this:

NameVirtualHost *
<VirtualHost *>
 ServerName www.example.com
 DocumentRoot "/home/user1/public_html/"
</VirtualHost>
<VirtualHost *>
 ServerName www.example2.com
 DocumentRoot "/ home/user2/public_html/"
</VirtualHost>

If you have more than one IP address and you want to use an SSL certificate, the website must be on a dedicated IP address. You can write IP-based virtual hosts like this:

<VirtualHost 192.168.1.2>
 ServerName www.example.com
 DocumentRoot "/home/user1/public_html/"
</VirtualHost>
<VirtualHost 192.168.1.3>
 ServerName www.example2.com
 DocumentRoot "/ home/user2/public_html/"
</VirtualHost>

Apache process ownership

We know from the Linux process management that each process inherits its permissions from its parent process.

This fact is true for all processes except for applications with the SETUID bit set; they inherit permissions from the owner, not the parent process. A good example is the /bin/su.

If a normal user runs /bin/su program, it does not inherit permission from adam, but it acts as a root user running it.

Since Apache web server needs to bind port 80, and this needs root privileges.

After binding to port 80, Apache can run as a normal user and only read files that have permissions to read them.

Based on the Linux distro you use, the user could be one of the following:

nobody, www, apache, www-data, or daemon.

I delayed introducing two more options for Apache till reaching that point.

User option

The User option specifies the user ID which the web server will use to answer requests.

User www-data

Group option

The Group option specifies the group that the Apache web server will use to read files.

Group www-data

Security is very important for sites that use executable scripts such as CGI or PHP scripts.

The user you will use will have the permission to read and write the content of all sites on the server. But we want to ensure that only the members of a particular site can read their site only.

This is very important because if an attacker compromises your website, he will be able to read all files since the Apache user has permission to do that.

So how to solve this problem?

suEXEC support

A popular method is to use suEXEC. suEXEC is a program that runs with root permissions and makes CGI programs run as the user and group IDs of a specific user, not the Apache server user.

You can specify the user on each virtual host like this:

<VirtualHost www.example.com>
 SuExecUserGroup adam adamGroup
</VirtualHost>

Just that simple.

Apache authentication

You may want to restrict some parts to specific visitors. It’s like a password-protected directory.

In Apache, you can store the authentication information file called .htpasswd file.

You can use the htpasswd command to do that.

First, create the .htpasswd file using the htpasswd command:

$ htpasswd -c /home/adam/.htpassswd myuser

You need the -c option the first time you run htpasswd, but when you need to add more users, you shouldn’t use -c because it will overwrite the file.

Then create a .htaccess file in the public_html folder and write the following:

<Location /vip>
 AuthName "test"
 AuthType Basic
 AuthUserFile /home/adam/.htpasswd
 Order deny,allow
 require valid-user
</Location>

AuthName is required, you can use any string you want.

AuthType Basic says that you’re using an htpasswd style user file.

AuthUserFile points to the file that contains the generated password from the htpasswd command.

The Order line indicates that Apache must deny access by default, and only allow access for users specified in the htpasswd file.

The require directive means any user in the .htpasswd file is allowed.

Troubleshooting Apache web server

If you modify the httpd.conf file and restart or reload Apache web server and it did not work, then you have typed the wrong configuration. However, this is not the only case that you need to troubleshoot Apache. You may look at the Apache logs to see how the service works so you can diagnose the problem and solve it.

The two main log files for Apache are error_log and access_log files.

You can find these files in

/var/log/apache2/

directory if you are using Debian based distros.

The access_log file contains every request to the Apache web server with the details about the client requested that resource.

The error_log file contains errors of the Apache web server.

You can use the tail command to watch the log file:

$ tail -f /var/log/httpd/error_log

I recommend you review the Linux syslog server to know more about logging.

Original article source at:  https://likegeeks.com/

#linux #web #server 

How to Install, Configure, & Troubleshoot Linux Web Server
Lawrence  Lesch

Lawrence Lesch

1678216860

HFS: A Web File Server to Run on Your Computer

HFS: HTTP File Server (version 3)


Introduction

HFS is the best way via web to access or share files from your disk.

  • It's a server software, share files fresh from your disk. Don't rely on services, be independent!
  • It's all very fast. Try download zipping 100GB, it starts immediately!
  • Easy to use. HFS tries to detect problems and suggest solutions.
  • Share even a single file with our virtual file system, even with a different name, all without touching the real file. Present things the way you want!
  • Watch all activities in real-time.
  • Control bandwidth, decide how much to give.

This is a full rewrite of the Delphi version.

How does it work

  • run HFS on your computer, administration page automatically shows up
  • select what files and folders you want to be accessible
  • possibly create accounts and limit access to files
  • access those files from a phone or another computer just using a browser

Features

  • https
  • unicode
  • virtual file system
  • mobile friendly front-end
  • search
  • accounts
  • resumable downloads
  • resumable uploads
  • download folders as zip archive
  • remote delete
  • simple website serving
  • plug-ins
  • log file
  • speed throttler
  • admin web interface
  • multi-language front-end
  • virtual hosting (plug-in)
  • anti-brute-force (plug-in)

Installation

  1. go to https://github.com/rejetto/hfs/releases
  2. click on Assets
  3. download the right version for your computer
  4. launch hfs file
  5. the browser should automatically open on localhost address, so you can configure the rest in the Admin-panel.
    • if a browser cannot be opened on the computer where you are installing HFS, you should enter this command in HFS console: create-admin <PASSWORD>

If you access Admin-panel via localhost, by default HFS won't require you to login. If you don't like this behavior, disable it in the Admin-panel or enter this console command config localhost_admin false.

Other systems

If your system is not Windows/Linux/Mac, you can try this alternative version:

  1. install node.js
  2. execute: sudo npm -g i hfs
  3. launch: hfs

Configuration and other files will be stored in %HOME%/.vfs

With this installation method, you can update with sudo npm -g update hfs .

Service

If you want to run HFS as a service

  • if you installed with npm on Windows
    • service installation
      • run npx qckwinsvc2 install name="HFS" description="HFS" path="%APPDATA%\npm\node_modules\hfs\src\index.js" args="--cwd %HOMEPATH%\.hfs" now
    • service update
      • run npx qckwinsvc2 uninstall name="HFS"
      • run npm -g update hfs
      • run the service installation again

Internationalization

It is possible to show the Front-end in other languages. In the Languages section of the Admin-panel you'll be able to install lang files. You can find some of these files at https://github.com/rejetto/hfs/tree/main/langs To download a file: open it, right-click on the "Raw" button, Save.

Files must be named hfs-lang-CODE.json (lowercase), where CODE is the ISO code for your language (e.g. pt-br for Brazilian).

Translation is applied automatically based on the configuration of the visitor's browser. Check the language configuration of your browser.

Plug-ins

To install a plugin you just copy its folder inside plugins folder.

Delete it to uninstall.

HFS will ignore all folders with -disabled at the end of the name.

Why you should upgrade from HFS 2.x to 3

As you can see from the list of features, we already have some goods that you cannot find in HFS 2. Other than that, you can also consider:

  • it's more robust: it was designed to be an always-running server, while HFS 1-2 was designed for occasional usage (transfer and quit)
  • passwords are never really stored, just a non-reversible hash is
  • faster search (up to 12x)
  • more flexible permissions

But you may still want to stay with HFS 2.x (so far) for the following reasons

  • smaller
  • more tested
  • classic window interface (can be easier for some people)

Console commands

If you have access to HFS' console, you can enter commands. Start with help to have a full list.

Configuration

Configuration can be done in several ways

  • accessing the Admin-panel with your browser
  • after HFS has started you can enter console command in the form config NAME VALUE
  • passing via command line at start in the form --NAME VALUE
  • directly editing the config.yaml file. As soon as you save it is reloaded and changes are applied

NAME stands for the property name that you want to change. See the complete list below.

Where is it stored

Configuration is stored in the file config.yaml, which is stored in the same folder of hfs.exe if you are using this kind of distribution on Windows, or USER_FOLDER/.hfs on other systems.

You can decide a different file and location by passing --config SOME_FILE at command line, or inside an env called HFS_CONFIG. Any relative path provided is relative to the cwd.

Configuration properties

  • port where to accept http connections. Default is 80.
  • vfs the files and folders you want to expose. For details see the dedicated following section.
  • log path of the log file. Default is access.log.
  • log_rotation frequency of log rotation. Accepted values are daily, weekly, monthly, or empty string to disable. Default is weekly.
  • error_log path of the log file for errors. Default is error.log.
  • errors_in_main_log if you want to use a single file for both kind of entries. Default is false.
  • accounts list of accounts. For details see the dedicated following section.
  • mime command what mime-type to be returned with some files. E.g.: "*.jpg": image/jpeg You can specify multiple entries, or separate multiple file masks with a p|pe. You can use the special value auto to attempt automatic detection.
  • max_kbps throttle output speed. Default is Infinity.
  • max_kbps_per_ip throttle output speed on a per-ip basis. Default is Infinity.
  • zip_calculate_size_for_seconds how long should we wait before the zip archive starts streaming, trying to understand its finale size. Default is 1.
  • open_browser_at_start should HFS open browser on localhost on start? Default is true.
  • https_port listen on a specific port. Default is 443.
  • cert use this file for https certificate. Minimum to start https is to give a cert and a private_key. Default is none.
  • private_key use this file for https private key. Default is none.
  • allowed_referer you can decide what domains can link to your files. Wildcards supported. Default is empty, meaning any.
  • block a list of rules that will block connections. E.g.:
block:
  - ip: 192.168.0.90
  • Syntax supports, other than simple address, * as wildcard and CIDR format.
  • plugins_config this is a generic place where you can find/put configuration for each plugin, at least those that need configuration.
  • enable_plugins if a plugin is not present here, it won't run. Defaults is [ antibrute ].
  • localhost_admin should Admin be accessed without credentials when on localhost. Default is true.
  • proxies number of proxies between server and clients to be trusted about providing clients' IP addresses. Default is 0.
  • keep_unfinished_uploads should unfinished uploads be deleted immediately when interrupted. Default is true.
  • favicon path to file to be used as favicon. Default is none.

Virtual File System (VFS)

The virtual file system is a tree of files and folders, collectively called nodes. By default, a node is a folder, unless you provide for it a source that's a file. Valid keys in a node are:

  • name: this is the name we'll use to display this file/folder. If not provided, HFS will infer it from the source. At least name or source must be provided.
  • source: absolute or relative path of where to get the content
  • children: just for folders, specify its virtual children. Value is a list and its entries are nodes.
  • rename: similar to name, but it's from the parent node point. Use this to change the name of entries that are read from the source, not listed in the VFS. Value is a dictionary, where the key is the original name.
  • mime: specify what mime to use for this resource. Use "auto" for automatic detection.
  • default: to be used with a folder where you want to serve a default html. E.g.: "index.html". Using this will make mime default to "auto".
  • can_read: specify who can download this entry. Value is a WhoCan descriptor, which is one of these values
    • true: anyone can, even people who didn't log in. This is normally the default value.
    • false: no one can.
    • "*": any account can, i.e. anyone who logged in.
    • [ frank, peter ]: the list of accounts who can.
  • can_see: specify who can see this entry. Even if a user can download you can still make the file not appear in the list. Remember that to see in the list you must also be able to download (read), or else you won't see it anyway. Value is a WhoCan descriptor, refer above.
  • can_upload specify who can upload. Applies to folders with a source. Default is none.
  • can_delete specify who can delete. Applies to folders with a source. Default is none.
  • masks: maps a file mask to a set of properties as the one documented in this section. E.g.
"**/*.mp3":
  can_read: false
"*.jpg|*.png": 
  mime: auto

Permissions set on an inner element will override inherited permissions. This means that you can restrict access to folder1, and yet decide to give free access to folder1/subfolder2.

Accounts

All accounts go under accounts: property, as a dictionary where the key is the username. E.g.

accounts:
    admin:
        password: hello123
        belongs: group1
    guest:
        password: guest
    group1:

As soon as the config is read HFS will encrypt passwords (if necessary) in a non-reversible way. It means that password property is replaced with an encrypted property: srp.

As you can see in the example, group1 has no password. This implies that you cannot log in as group1, but still group1 exists and its purpose is to gather multiple accounts and refer to them collectively as group1, so you can quickly share powers among several accounts.

For each account entries, this is the list of properties you can have:

  • ignore_limits to ignore speed limits. Default is false.
  • redirect provide a URL if you want the user to be redirected upon login. Default is none.
  • admin set true if you want to let this account log in to the Admin-panel. Default is false.
  • belongs an array of usernames of other accounts from which to inherit their permissions. Default is none.

Download Details:

Author: Rejetto
Source Code: https://github.com/rejetto/hfs 
License: GPL-3.0 license

#typescript #nodejs #web #file #http #server

HFS: A Web File Server to Run on Your Computer

Установка и настройка прокси-сервера Squid Linux

Установка и настройка прокси-сервера Squid Linux

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

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

Еще одним важным преимуществом прокси-серверов является то, что вы можете настроить прокси с некоторыми настройками для контроля доступа. Например, вы можете ограничить доступ к определенным веб-сайтам.

Если вы раньше работали в Интернете с анонимного прокси-сервера, это прокси-сервер. Вы можете выбрать любой из доступных прокси-серверов Linux, таких как Squid, Varnish, Polipo, TinyProxy и другие. В этом посте мы обсудим самый распространенный прокси-сервер Linux, которым является Squid.

Установить Сквид

Установить прокси-сервер squid очень просто. Для дистрибутива на основе Red Hat вы можете установить его следующим образом:

$ dnf -y install squid

Или, если вы используете дистрибутив на основе Debian, вы можете установить его следующим образом:

$ apt-get -y install squid

Теперь вы можете запустить службу squid и включить ее при запуске:

$ systemctl start squid

$ systemctl enable squid

Для прокси-сервера squid вы можете проверить файл конфигурации в

/etc/squid/squid.conf

Прежде чем мы углубимся в настройку, давайте посмотрим на прокси-сервер в действии.

Просто измените настройку прокси в браузере на IP-адрес прокси и порт 3128 , так как это порт по умолчанию для squid. Вы можете изменить порт по умолчанию, изменив параметр http_port  в файле конфигурации.

Как показано на изображении, я указал в своем браузере на свой прокси-сервер Linux и могу просматривать веб-страницы без каких-либо проблем.

Если вы используете брандмауэр iptables , не забудьте открыть порт сервера squid.

Разрешить диапазон IP-адресов

Если вы откроете файл конфигурации /etc/squid/squid.conf , вы увидите правила, разрешающие IP-адресам подключаться к прокси-серверу, например:

acl localnet src 192.168.0.0/16

Однако вы можете добавить новую запись ACL, чтобы разрешить диапазону IP-адресов подключаться к вашему прокси-серверу:

acl localnet src 212.80.113.0/16

Затем сохраните файл и перезапустите службу squid:

$ systemctl restart squid

Очень легко, правда?

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

Разрешить определенные порты

Вы можете найти все разрешенные порты в файле конфигурации следующим образом:

acl Safe_ports port 80

Рассмотрите возможность добавления правила Safe_ports ACL для любого порта, который нужен вашим клиентам.

Вы можете добавить диапазон портов вместо того, чтобы писать правило для каждого порта, например:

acl Safe_ports port 6000-7000

Не забудьте перезапустить прокси-сервер squid после модификации:

$ systemctl restart squid

Аутентификация пользователей

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

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

$ touch /etc/squid/passwd

Затем измените владельца на демона squid, чтобы он мог получить доступ к файлу:

$ chown squid /etc/squid/passwd

Теперь мы создадим нового пользователя с помощью команды htpasswd:

$ htpasswd /etc/squid/passwd likegeeks

Он дважды попросит вас ввести пароль.

Если вы откроете созданный файл, вы увидите пользователя и хешированный пароль.

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

Добавьте следующие строки ниже портов ACL и больше нигде , чтобы включить аутентификацию:

auth_param basic program /usr/lib64/squid/basic_ncsa_auth /etc/squid/passwd
auth_param basic children 5
auth_param basic realm Squid Basic Authentication
auth_param basic credentialsttl 3 hours
acl auth_users proxy_auth REQUIRED
http_access allow auth_users

Затем перезапустите службу squid и попробуйте снова открыть браузер.

$ systemctl restart squid

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

Блокировать веб-сайты

Вы можете заблокировать веб-сайты от прокси-пользователей, просто создайте отдельный файл, который будет списком доменов, которые вы хотите заблокировать, и укажите этот файл в конфигурации squid следующим образом:

$ touch /etc/squid/blocked

Затем введите все веб-сайты, которые вы хотите заблокировать, по одному в строке в этом файле и сохраните его.

Теперь измените конфигурацию squid, чтобы заблокировать эти веб-сайты в списках acl  и  http_access  .

acl blocked_sites dstdomain "/etc/squid/blocked"

http_access deny blocked_sites

Затем перезапустите службу squid:

$ systemctl restart squid

В Интернете есть много готовых списков, вы можете использовать их в Squid, например, черные списки MESD, черные списки Шаллы.

Изменить содержимое

Поскольку прокси-сервер Linux находится между браузером и Интернетом, это очень хорошая позиция для изменения доставляемого контента.

Вы можете изменить изображения, рекламу или что-то еще, используя модуль url_rewrite_program .

Вы можете сделать больше, но мы не хотим быть злыми.

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

Во-первых, нам нужно установить ImageMagick:

$ dnf -y install imagemagick

Затем мы напишем сценарий, который будет творить чудеса. Скрипт на Perl.

Вы можете найти сценарий здесь .

Этот Perl-скрипт ищет JPG, GIF и PNG изображения в переносимом содержимом, как только он их находит, он использует утилиту mogrify, поставляемую с ImageMagick, для переворачивания изображений и помещения перевернутого изображения в /var/www/html/, который корневой каталог для сервера Apache . Служба apache должна быть запущена, а затем отправить перевернутые изображения в качестве ответа.

Просто убедитесь, что Squid владеет этой папкой:

$ usermod -aG www-data squid

Наконец, вы должны сообщить Squid об этом скрипте. Откройте файл конфигурации и введите следующее:

url_rewrite_program /home/likegeeks/flip.pl

Затем перезапустите службу squid:

$ systemctl restart squid

В Интернете есть много Perl-скриптов, которые играют с контентом, некоторые из них хороши, а некоторые — плохи.

Анонимный просмотр

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

Для этого отключите параметр forwarded_for в

/etc/squid/squid.conf

файл.

forwarded_for off

И добавьте следующие параметры, упомянутые здесь, в конце файла конфигурации.

Затем перезапустите службу:

$ systemctl restart squid

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

Подключение Squid-серверов

Директива cache_peer устанавливает ваши одноранговые кэши и сообщает Squid, как с ними взаимодействовать.

Вы можете написать это так:

cache_peer hostname Server-type http-port icp-port [options]

Первый аргумент — другое имя хоста squid или IP-адрес.

Второй аргумент указывает тип другого сервера.

Третий аргумент — это номер порта.

Четвертый аргумент указывает порт ICP (протокол интернет-кэширования), который равен 3130 . Мы используем этот порт для запроса других серверов кеша.

У cache_peer есть несколько параметров, которые вы можете использовать, например:

proxy-only : Эта опция запрещает Squid сохранять любые ответы, которые он получает от другого сервера Squid.

no-delay : Если какая-либо задержка будет проигнорирована.

login= user:password : Учетные данные для аутентификации на другом сервере. Требуется эта формула логин = пользователь: пароль

connect-timeout : Эта опция указывает время ожидания соединения с другими серверами squid.

Напишите свои параметры, сохраните файл конфигурации и перезапустите службу.

Лог-файлы кальмара

Файлы журналов являются вашим основным источником для диагностики проблем и различных операций Squid.

Есть cache.log, access.log и store.log. Вы можете найти их в каталоге /var/log/squid.

Файл cache.log содержит информационные сообщения о работе Squid. Вы можете найти все ошибки прокси в этом файле.

Файл access.log содержит все HTTP - запросы клиентов.

Файл store.log содержит информацию о переданных объектах.

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

Оригинальный источник статьи: https://likegeeks.com/

#linux #proxy #server 

Установка и настройка прокси-сервера Squid Linux
佐藤  桃子

佐藤 桃子

1678181280

安装和配置 Squid Linux 代理服务器

安装和配置 Squid Linux 代理服务器

Linux 代理服务器或代理服务器通常是保存访问过的网页以供以后请求的服务器,因此如果您尝试访问同一网页或其他任何人,您将从代理服务器获取该页面。

这非常有用,它可以使网上冲浪更快并减少流量,这意味着成本更低。缓存服务器可以将外部流量减少到 45%。

代理服务器的另一个主要优势是,您可以使用一些访问控制设置来配置代理。例如,您可以限制对特定网站的访问。

如果您以前通过匿名代理上网,这就是代理服务器。您可以选择任何可用的 Linux 代理服务器,例如 Squid、Varnish、Polipo、TinyProxy 等。在这篇文章中,我们将讨论最常见的 Linux 代理服务器,即 Squid。

安装鱿鱼

安装 squid 代理服务器非常简单。对于基于 Red Hat 的发行版,您可以像这样安装它:

$ dnf -y install squid

或者,如果您使用的是基于 Debian 的发行版,则可以像这样安装它:

$ apt-get -y install squid

现在您可以启动 squid 服务并在启动时启用它:

$ systemctl start squid

$ systemctl enable squid

squid代理服务器,可以查看配置文件

/etc/squid/squid.conf

在深入了解配置之前,让我们先看看代理服务器的运行情况。

只需将浏览器上的代理设置更改为代理的 IP 地址和端口3128,因为这是 squid 默认端口。 您可以通过更改配置文件中的http_port选项来更改默认端口。

如图所示,我已将浏览器指向我的 Linux 代理服务器,我可以毫无问题地浏览网页。

如果您使用的是iptables 防火墙,请不要忘记打开 squid 服务器端口。

允许 IP 地址范围

如果打开配置文件/etc/squid/squid.conf,您将看到允许 IP 地址连接到代理服务器的规则,如下所示:

acl localnet src 192.168.0.0/16

但是,您可以添加一个新的 ACL 条目以允许一定范围的 IP 地址连接到您的代理服务器:

acl localnet src 212.80.113.0/16

然后保存文件并重启squid服务:

$ systemctl restart squid

很容易,对吧?

此外,如果您从文件中删除任何 ACL,则该范围内的所有 IP 地址都将无法连接到代理服务器。

允许特定端口

您可以找到配置文件中允许的所有端口,如下所示:

acl Safe_ports port 80

考虑为您的客户端需要的任何端口添加 Safe_ports ACL 规则。

您可以添加端口范围,而不是像这样为每个端口编写规则:

acl Safe_ports port 6000-7000

修改后别忘了重启squid代理服务器:

$ systemctl restart squid

验证用户

您可以强制您的用户在使用Apache 身份验证使用您的 Linux 代理服务器之前进行身份验证。

首先,我们创建一个文件来存储用户:

$ touch /etc/squid/passwd

然后将所有权更改为 squid 守护进程,以便它可以访问该文件:

$ chown squid /etc/squid/passwd

现在我们将使用 htpasswd 命令创建一个新用户:

$ htpasswd /etc/squid/passwd likegeeks

它会提示您输入密码两次。

如果打开创建的文件,您将看到用户和散列密码。

然后您更改 squid 配置以告知它应该使用的身份验证。

在 ACL 端口下方添加以下行,并在其他任何地方添加以启用身份验证:

auth_param basic program /usr/lib64/squid/basic_ncsa_auth /etc/squid/passwd
auth_param basic children 5
auth_param basic realm Squid Basic Authentication
auth_param basic credentialsttl 3 hours
acl auth_users proxy_auth REQUIRED
http_access allow auth_users

然后重启squid服务,再次尝试打开浏览器。

$ systemctl restart squid

如您所见,如果您尝试连接到 Linux 代理服务器,它会提示您输入用户名和密码。

屏蔽网站

您可以阻止代理用户访问网站,只需创建一个单独的文件,该文件将是您要阻止的域列表,并从 squid 配置中指向该文件,如下所示:

$ touch /etc/squid/blocked

然后在该文件中每行键入一个要阻止的所有网站并保存。

现在更改 squid 配置以阻止acl 列表和 http_access 列表下的那些网站。

acl blocked_sites dstdomain "/etc/squid/blocked"

http_access deny blocked_sites

然后重启squid服务:

$ systemctl restart squid

网上有很多现成的列表,你可以在 Squid 中使用它们,比如 MESD 黑名单、Shalla 的黑名单。

修改内容

由于 Linux 代理服务器位于浏览器和互联网之间,因此这是更改传送内容的绝佳位置。

您可以使用url_rewrite_program模块更改图像、广告或任何内容。

你可以做得更多,但我们不想作恶。

在我们的示例中,我们将翻转图像并浏览翻转后的图像而不是原始图像。

首先,我们需要安装 ImageMagick:

$ dnf -y install imagemagick

然后我们将编写可以发挥作用的脚本。该脚本在 Perl 中。

您可以在此处找到该脚本。

这个 Perl 脚本在携带的内容中搜索 JPG、GIF 和 PNG 图像,一旦找到它们,它就会使用 ImageMagick 附带的 mogrify 实用程序来翻转图像并将翻转后的图像放在 /var/www/html/ 中Apache 服务器的根目录。apache 服务应该正在运行,然后发送翻转的图像作为响应。

只需确保为此文件夹添加 Squid 的所有权:

$ usermod -aG www-data squid

最后,你必须把这个脚本告诉squid。打开配置文件并键入以下内容:

url_rewrite_program /home/likegeeks/flip.pl

然后重新启动你的鱿鱼服务:

$ systemctl restart squid

网络上有很多 Perl 脚本来处理内容,其中一些是好的,而另一些是邪恶的。

匿名浏览

默认情况下,squid 代理服务器将客户端 IP 地址转发到请求的站点,如果您希望代理匿名浏览用户,您应该发送 squid IP 而不是客户端 IP。

为此,请将forwarded_for选项更改为 off

/etc/squid/squid.conf

文件。

forwarded_for off

并在配置文件末尾添加此处提到的以下选项。

然后重启服务:

$ systemctl restart squid

您可以查看您的公网IP地址;您会注意到您的 IP 是 squid 代理服务器 IP。

连接鱿鱼服务器

cache_peer指令设置你的对等缓存并通知 squid 如何与它们通信。

你可以这样写:

cache_peer hostname Server-type http-port icp-port [options]

第一个参数是另一个 squid 主机名或 IP 地址。

第二个参数指定其他服务器的类型。

第三个参数是端口号。

第 4 个参数指定 ICP 端口(Internet 缓存协议),即3130。我们使用这个端口来查询其他缓存服务器。

cache_peer 有一些您可以使用的选项,例如:

proxy-only:这个选项防止squid 保存它从其他squid 服务器接收到的任何响应。

no-delay:如果有任何延迟,它将被忽略。

login= user:password:另一台服务器的身份验证凭据。它采用这个公式 login =user:password

connect-timeout:此选项指定与其他 squid 服务器的连接超时。

编写您的选项并保存配置文件并重新启动服务。

鱿鱼日志文件

日志文件是问题诊断和各种 squid 操作的主要来源。

有cache.log、access.log、store.log。您可以在 /var/log/squid 目录中找到它们。

cache.log文件包含有关 squid 操作的信息性消息您可以在此文件中找到所有代理错误。

access.log文件包含所有客户端HTTP 请求。

store.log文件包含有关传递的对象的信息

这些文件中的每个条目在生成消息时都有其时间戳。

文章原文出处:https: //likegeeks.com/

#linux #proxy #server 

安装和配置 Squid Linux 代理服务器