Архив метки: FreeBSD

sm-mta: STARTTLS=server, error: cannot read DH parameters(/etc/mail/certs/dh.param)

Имеем FreeBSD 10.1 RELEASE. В логах при старте sendmail видим ругань вида:

Dec 26 09:32:03 server sm-mta[66555]: STARTTLS=server, error: cannot read DH parameters(/etc/mail/certs/dh.param): error

Исправляем:

openssl dhparam -out /etc/mail/certs/dh.param -2 1024

Падение ProFTPD на сервере FreeBSD

На новом сервере под управлением операционной системы FreeBSD 10.1-RELEASE потребовалось установить ProFTPD. В портах версия proftpd-1.3.5_4. Собрал. Установил. Через некоторое время выяснилось, что сервер хоть и стартует без ошибок — но через несколько секунд завершает свою работу не выводя никаких сообщений ни на консоль ни в лог файлы. Гуглим. У других наблюдается схожая проблема.
Решение: добавляем в Makefile строку LDFLAGS+= -pthread и переустанавливаем proftpd.

# uname -r
10.1-RELEASE
# pkg info | grep proftpd
proftpd-1.3.5_4                Highly configurable FTP daemon
# cd /usr/ports/ftp/proftpd
# echo "LDFLAGS+= -pthread" >> Makefile
# make config
# make
# /usr/local/etc/rc.d/proftpd stop
proftpd not running?
# make reinstall clean

Запускаем, проверяем.

# /usr/local/etc/rc.d/proftpd start
# ps -ax | grep proftpd
57942  -  Ss    0:00.00 proftpd: (accepting connections) (proftpd)

Решение найдено здесь.

_______________

Зимнее время 26 октября 2014 года.

Согласно федеральному закону Российской Федерации от 21 июля 2014 г. N 248-ФЗ, в закон об истечении времени под номером N 107-ФЗ от 3-го июня 2011 года, были внесены изменения, в связи с которыми 26 октября 2014 года осуществляется перевод часов и устанавливаются соответствующие часовые зоны и значения времени.

Читать далее

Использование команды find.

Поиск файлов по имени:

find /var/www/ -name "file.conf"
find /var/www/ -name "*.conf"

Поиск без учёта регистра:

find /var/www/ -iname file.conf

Поиск по размеру файлов

find /home/user -size +10M

Поиск по маске прав

find ./ -perm 700

Файлы созданные или изменённые в течении последних 5 дней

find /home/user -type f -mtime -5

Файлы созданные или изменённые в течении последних 5 минут

find /home/user -type f -mmin -5

Найти файлы созданные или изменённые старше 30 дней (поиск устаревших файлов):

find /home/user -type f -mtime +30

Время последнего обращения к которым более 5 дней

find /usr/bin -type f -atime +5

Поиск строки в файлах

find ./ -type f -exec grep -i -H "STRING"  {} \;

Найти все файлы php в который встречается строка STRING:

find ./ -type f -name "*.php" -exec grep -i -H "STRING"  {} \;

grep с опцией -R для поиска файлов по содержимому:

grep "STRING" -R /path/for/find

Замена текста в файлах

find ./ -type f -name "*.conf" -exec sed -i s/OLDTEXT/NEWTEXT/g {} \;

Установка прав доступа 644 на все файлы в текущей директории и всех поддиректориях:

find ./ -type f -exec chmod 644 {} \;

Установка прав доступа 755 на все папки в текущей директории и всех поддиректориях:

find ./ -type d -exec chmod 755 {} \;

su без пароля

Правим файл /etc/pam.d/su, строку:

auth            requisite       pam_group.so            no_warn group=wheel root_only fail_safe

приводи к виду (убираем root_only):

auth            requisite       pam_group.so            no_warn group=wheel fail_safe

И добавляем строку:

auth           sufficient      pam_permit.so

Получаем, что любой пользователь из группа wheel может делать su на любого пользователя без пароля.

Скрипт рекурсивного переименования файлов и каталогов в нижний регистр

#!/usr/local/bin/bash
function process_dir()
{
  #используем локальные переменные, ибо функция рекурсивна
  local dir=$1

local item
  for item in "$dir"/*
  do
    # пустая директория/* будет расширена '*', e.g.: /какаято/папка/*
    # делаем проверку на существование:
    [[ ! -e $item ]] && return

    # если директория, обрабатываем рекурсивно
    [[ -d $item ]] && process_dir $item

    # теперь отделим имя файла от пути и создадим
    # эквивалент имени файла "маленькими буквами"
    local path=${item%/*}
    local name=${item##*/}
    local lcase_name=$(tr 'A-Z' 'a-z' <<< $name)

    # для облегчения работы, проверим в нижнем ли регистре имя файла
    if [[ $name != $lcase_name ]]; then
      # если файл уже в нижнем регистре, то нам надо быть аккуратнее
      if [[ -e $path/$lcase_name ]]; then
        # если это директория и существующий файл - тоже директория, используем слияние
        if [[ -d $path/$lcase_name && -d $path/$name ]]; then
          # если мы все успешно переместили, удалим оставшиеся в большом регистре файлы
          local can_delete_dir=1
          local subdir_item
          for subdir_item in "$path/$name"/*
          do
            # если директория пустая, сразу удаляем
            [[ ! -e $subdir_item ]] && break
            local subdir_name=${subdir_item##*/}
            # проверяем также дублирование файлов
            if [[ -e $path/$lcase_name/$subdir_name ]]; then
              echo "CONFLICT: Cannot move item $subdir_item to $path/$lcase_name as that destination already exists"
              # тут мы не можем удалить файлы
              can_delete_dir=0
            else
              # у нас получится переместить файлы
              echo "MERGE: $subdir_item to $path/$lcase_name/$subdir_name"
              mv "$subdir_item" "$path/$lcase_name/"
            fi
          done
          # если мы все успешно переместили, удаляем директорию
          if [[ $can_delete_dir -eq 1 ]]; then
            echo "DELETE: $path/$name having merged all its contents elsewhere"
            rm $path/$name
          fi
        else
          # если такой же файл существует, не перезаписываем, а выводим сообщение об ошибке и продолжаем
          echo "CONFLICT: Cannot rename file $path/$name to $path/$lcase_name as that file already exists"
        fi
      else
        # в этой директории нет имен файлов, удовлетворяющих нашим условиям - переименовываем
        echo "RENAME: $path/$name to $path/$lcase_name"
        mv "$path/$name" "$path/$lcase_name"
      fi
    fi
  done
}

start_dir="$1"
[[ -n $start_dir && -e $start_dir ]] || { echo "Please supply the starting directory as a parameter to the script";
exit 1; }

# обрезать все окончания с '/'
start_dir=${start_dir%/}
process_dir "$start_dir"

FreeBSD и CVE-2014-0160

Подробная информация о уязвимости и методах исправления тут.

=============================================================================
FreeBSD-SA-14:06.openssl                                    Security Advisory
                                                          The FreeBSD Project

Topic:          OpenSSL multiple vulnerabilities

Category:       contrib
Module:         openssl
Announced:      2014-04-08
Affects:        All supported versions of FreeBSD.
Corrected:      2014-04-08 18:27:39 UTC (stable/10, 10.0-STABLE)
                2014-04-08 18:27:46 UTC (releng/10.0, 10.0-RELEASE-p1)
                2014-04-08 23:16:19 UTC (stable/9, 9.2-STABLE)
                2014-04-08 23:16:05 UTC (releng/9.2, 9.2-RELEASE-p4)
                2014-04-08 23:16:05 UTC (releng/9.1, 9.1-RELEASE-p11)
                2014-04-08 23:16:19 UTC (stable/8, 8.4-STABLE)
                2014-04-08 23:16:05 UTC (releng/8.4, 8.4-RELEASE-p8)
                2014-04-08 23:16:05 UTC (releng/8.3, 8.3-RELEASE-p15)
CVE Name:       CVE-2014-0076, CVE-2014-0160

For general information regarding FreeBSD Security Advisories,
including descriptions of the fields above, security branches, and the
following sections, please visit .

0.   Revision History

v1.0  2014-04-08 Initial release.
v1.1  2014-04-08 Added patch applying step in Solutions section.

I.   Background

FreeBSD includes software from the OpenSSL Project.  The OpenSSL Project is
a collaborative effort to develop a robust, commercial-grade, full-featured
Open Source toolkit implementing the Secure Sockets Layer (SSL v2/v3)
and Transport Layer Security (TLS v1) protocols as well as a full-strength
general purpose cryptography library.

The Heartbeat Extension provides a new protocol for TLS/DTLS allowing the
usage of keep-alive functionality without performing a renegotiation and a
basis for path MTU (PMTU) discovery for DTLS.

Elliptic Curve Digital Signature Algorithm (ECDSA) is a variant of the
Digital Signature Algorithm (DSA) which uses Elliptic Curve Cryptography.
OpenSSL uses the Montgomery Ladder Approach to compute scalar multiplication
in a fixed amount of time, which does not leak any information through timing
or power.

II.  Problem Description

The code used to handle the Heartbeat Extension does not do sufficient boundary
checks on record length, which allows reading beyond the actual payload.
[CVE-2014-0160].  Affects FreeBSD 10.0 only.

A flaw in the implementation of Montgomery Ladder Approach would create a
side-channel that leaks sensitive timing information. [CVE-2014-0076]

III. Impact

An attacker who can send a specifically crafted packet to TLS server or client
with an established connection can reveal up to 64k of memory of the remote
system.  Such memory might contain sensitive information, including key
material, protected content, etc. which could be directly useful, or might
be leveraged to obtain elevated privileges.  [CVE-2014-0160]

A local attacker might be able to snoop a signing process and might recover
the signing key from it.  [CVE-2014-0076]

IV.  Workaround

No workaround is available, but systems that do not use OpenSSL to implement
the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1)
protocols implementation and do not use the ECDSA implementation from OpenSSL
are not vulnerable.

V.   Solution

Perform one of the following:

1) Upgrade your vulnerable system to a supported FreeBSD stable or
release / security branch (releng) dated after the correction date.

2) To update your vulnerable system via a source code patch:

The following patches have been verified to apply to the applicable
FreeBSD release branches.

a) Download the relevant patch from the location below, and verify the
detached PGP signature using your PGP utility.

[FreeBSD 8.x and FreeBSD 9.x]
# fetch http://security.FreeBSD.org/patches/SA-14:06/openssl.patch
# fetch http://security.FreeBSD.org/patches/SA-14:06/openssl.patch.asc
# gpg --verify openssl.patch.asc

[FreeBSD 10.0]
# fetch http://security.FreeBSD.org/patches/SA-14:06/openssl-10.patch
# fetch http://security.FreeBSD.org/patches/SA-14:06/openssl-10.patch.asc
# gpg --verify openssl-10.patch.asc

b) Execute the following commands as root:

# cd /usr/src
# patch < /path/to/patch

Recompile the operating system using buildworld and installworld as
described in .

Restart all deamons using the library, or reboot the system.

3) To update your vulnerable system via a binary patch:

Systems running a RELEASE version of FreeBSD on the i386 or amd64
platforms can be updated via the freebsd-update(8) utility:

# freebsd-update fetch
# freebsd-update install

IMPORTANT: the update procedure above does not update OpenSSL from the
Ports Collection or from a package, known as security/openssl, which
has to be updated separately via ports or package.  Users who have
installed security/openssl should update to at least version 1.0.1_10.

VI.  Correction details

The following list contains the correction revision numbers for each
affected branch.

Branch/path                                                      Revision
- -------------------------------------------------------------------------
stable/8/                                                         r264285
releng/8.3/                                                       r264284
releng/8.4/                                                       r264284
stable/9/                                                         r264285
releng/9.1/                                                       r264284
releng/9.2/                                                       r264284
stable/10/                                                        r264266
releng/10.0/                                                      r264267
- -------------------------------------------------------------------------

To see which files were modified by a particular revision, run the
following command, replacing NNNNNN with the revision number, on a
machine with Subversion installed:

# svn diff -cNNNNNN --summarize svn://svn.freebsd.org/base

Or visit the following URL, replacing NNNNNN with the revision number:



VII. References







The latest revision of this advisory is available at

Установка системы мониторинга Observium в FreeBSD.

Задался целью установить систему мониторинга Observium под FreeBSD. Сайт проекта — observium.org. Разработчики поддерживают ограниченное количество платформ, а именно: Debian, Ubuntu, RHEL, CentOS. К сожалению, FreeBSD в это число не входит. В портах старая версия — 0.11.5.2261_1 — актуальная — Observium Community Edition 0.13.10.4585.
Устанавливать будем на чистую систему FreeBSD 9.2 RELEASE.
Читать далее