Настройка tacacs на ubuntu

Обновлено: 07.07.2024

lsblk - подсветить все разделы чтобы определиться, что монтировать.

Так как Btrfs не может содержать swap-файл, необходимо заранее позаботиться о разделе с подкачкой, если он вам нужен.

Создаём файловую систему на разделе. Для разделов от 1ГБ и меньше, чтобы более эффективно использовать пространство, рекомендуется передать ключ -M к параметрам mkfs.btrfs .

При желании можно задать лэйбл ключом -L.

Затем создадим два подтома под корень и домашние каталоги пользователей.

Отмонтируем корень ФС.

Для того, чтобы монтировать подтом подобно обычному разделу диска, команде mount нужно указывать опцию subvol.

Монтируем корень. Сжатие zstd, или lzo.

Создаём директорию и монтируем в неё наш будущий каталог пользователей.

Дальше действуем по вики, т.е. выбираем зеркала и ставим базовую систему. При генерации initramfs mkinitcpio будет ругаться на отсутствие fsck.btrfs - это нормальное явление. Уберём этот хук fsck из конфига, т.к. для Btrfs он не требуется.

Вот данная строка в файле.

И пересоздадим initramfs.

И ещё момент по поводу загрузчика, не знаю как другие, а grub точно умеет грузиться с Btrfs, так что выбрать лучше именно его. Так же не забудьте установить пакет btrfs-progs и позаботиться о бэкапах.

Монтируем корень ФС.

Каталоги абсолютно идентичны, и пока мы не начнём изменять файлы, снимки места не занимают.

Откат: грузимся с live CD, монтируем корень ФС и переименовываем подтома. Так же подтома можно переименовать прямо в рабочей системе, если загрузка удачна.

Либо грузимся как обычно, а в меню grub указываем подтом с бэкапом rootflags=subvol=backup .

Копирование при записи (CoW). Если использовать команду cp с ключом --reflink=auto , то копия файла не будет занимать место на диске. И впоследствии, допустим, при изменении скопированного файла, записываться на диск будут только изменённые блоки.

“Онлайн” - проверка ФС. При которой осуществляется чтение всех данных/метаданных с перепроверкой контрольных сумм, при наличии ошибок обнаружение их и исправление по возможности.

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

Рекомендуется проводить проверку регулярно (еженедельно). “Оффлайн” - проверка ФС (на отмонтированном разделе). При отсутствии ошибок утилита возвратит 0.

lsblk - подсветить все разделы что бы определиться что монтировать.

Так как Btrfs не может содержать swap-файл, необходимо заранее позаботиться о разделе с подкачкой, если он вам нужен.

Внимание! это отформатирует весь ваш диск, с потерей данных! В данном примере установка идет на весь диск, а не разделы, если вам нужен swap учтите этот момент.

Создадим два подтома под root @ и домашний каталог пользователя @home .

И отмонтируем корень ФС.

Создаём директорию и монтируем в неё наш будущий каталог пользователей.

Устанавливаем базовые пакеты.

Создаем директорию и монтируем boot, если нужно.

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

Выбор часового пояса.

Выберем локаль для системы.

Прописать в /etc/locale.conf .

Русский шрифт в консоли.

Создаём рам-диск mkinitcpio.

В /etc/mkinitcpio.conf , в разделе HOOKS, должен быть прописан хук keyboard keymap , убрать fsck .

В разделе MODULES нужно прописать свой драйвер видеокарты: i915 для Intel, radeon для AMD, nouveau для Nvidia.

TACACS+ is an improvement on its first version TACACS, as TACACS+ is an entirely new protocol and is not compatible with its predecessors, TACACS and XTACACS. TACACS+ uses TCP. Since TACACS+ uses the authentication, authorisation, and accounting (AAA) architecture, these separate components of the protocol can be segregated and handled on separate servers. TACACS+ allows you to set granular access policies for users and groups, commands, location, subnet, or even device type. The TACACS+ protocol also provides detailed logging of users and what commands have been run on specific devices. In addition, the protocol can run on either Windows or UNIX/Linux.

Although TACACS+ was developed by Cisco Systems, it is actually an open standard as defined by RFC1482 and has been incorporated into a number of different vendors including Alcatel/Lucent, Arbor, Brocade/Foundry, Cisco/Linksys, Extreme, HP/3Com, Huawei, IBM, Juniper/Netscreen, Netgear and any others.

The setup I had for testing was a simple one; I had 2 EXSi Ubuntu 14.04LTS hosts, one as the TACACS+ server with the second being used as Jump-box to access a Juniper SRX220 that will be configured for TACACS authentication.

You will run sudo/root privileges

Server Configuration

Fortunately, with the newer version of Ubuntu, from apt-get repository you can easily download the tacacs+ package it will also install libtacacs+1

Having installed the package now we can run the command ps -ef | grep tac_plus and it will show us the location of the configuration file and if the process is running:

The important files are tac_plus and tac_pwd:

  • tac_plus is the TACACS+ daemon. You can run daemon via the cli
  • tac_pwd is used to generate a Data Encryption Standard (DES) or Message-Digest 5 (MD5) hash from clear text. DES is the defualt, to generate a MD5 hash you need to add -m flag.

We will need to configure the tac_plus.conf file, but firstly we will need to back-up the original file to refer back to if there is any issues

Accounting

You have to create this file yourself. This can be done by running the command sudo touch /var/log/tac_plus.acct

Secret Key

Users

You’ll need to define the users that will have access to the device. Each user needs to be associated to a group and have their password defined. The password has to be set as either a MD5 or DES hash. By using tac_pwd use can get your hashed output:

Groups

As you can guess, groups are where you define the level of access and what commands will be used by the group. The commands, for my example, are used to define actions that are largely accepted by most vendors with the expectation of Juniper (from my knowledge but correct me if I’m wrong), although I wont be confirming the configuration works in this post. I have checked with a Cisco device and they worked as expected.

We have a few parameters that are important remember:

In my example I have two groups, admin and read-only, the admin group will have full access permitted and the read-only group, as the name suggests, will have read-only access and will be denied from any configuration, clear or restart commands.

My completed tac_plus file can be seen here.

For more in-depth detail and additional parameters that can be configured in this file, you can find them via the man pages using the command man tac_plus or online Ubuntu tac_plus Manual Documentation Additional commands that will be useful to remember:

With that we have a TACACS+ server configured 🙂

Before getting into the configuration of the SRX, I stated earlier that there’s a Juniper Specific stanza in tac_plus.conf file. When authenticating users against a TACACS+ server on juniper devices and you’ll need to apply Juniper Networks Vendor-Specific TACACS+ Attributes.

These attributes can be either:

  1. Specified in the tac_plus.conf file by using regular expressions to list all the commands that the user has permitted or denied. A user will need to be created on the device with that user being referred under the local-user-name statement. The stanza would look something:
  2. Configure a class that has states all the permitted or denied permissions, this class will be linked to a user. Both need to be configured on the device. Once this has been created you’ll need to refer, said user, under the local-user-name

The Junos OS retrieves these attributes through an authorization request of the TACACS+ server after authenticating a user. For my example, I went with the latter. Now we’ll jump onto the SRX220 and get that sorted with TACACS+ AAA configuration.

Juniper Configuration

Firstly, you will have to set the TACACS+ server with its secret key. For standard practice and force of habit, I have set the single connection and forced the source-address of the SRX. By using the single connection statement, this means that instead of multiple TCP sessions connecting to the device from a server, a single session is maintained between them. In addition, for best practice an authentication order should be set so that if there was an issue or loss of connectivity to the TACACS+ server, you’ll be able to fall back to locally defined users.

With the TACACS+ server we’re able log different events that take place on the device and get those commands sent to the server. From my experience the accounting events that you would most want logged are logins, configuration changes and interactive commands. This is set under system accounting stanza

Next, under the system login stanza, you need to create a class that has a list of permission available to the user(s) that are going to be associated to it. The user(s) are what are used in the tac_plus.conf file. In my example I created two classes, one with all permission super-user-local and the other user with read-only and basic troubleshooting options (ie ping, traceroute, telnet etc) read-only-user-local. These associated this classes with 2 users remote-admin and remote-read-only

You can learn more about the different permissions flags available here on Juniper TechLibrary

Verifications

If we check the /var/log/tac_plus.acct file we’ll be able to see all the permitted commands by each user. This is additional confirmation that the users have successfully authenticated against the TACACS+ server and their related permissions authorised to the device.

And with that all, we have a fully configured and working AAA TACACS+ server 🙂

Reference

Keeran Marquis

Keeran Marquis is a Network Engineer. His main goal is to learn everything within the Networking field, pick up a little bit of scripting, be a poor man sysadmin and share whatever he knows! All Posts are his own views, opinions and experiences, no guarantees they will work for you but point you in the right direction 🙂

Latest posts by Keeran Marquis (see all)

7 thoughts on “Configuring TACACS+ Server on Ubuntu 14.04LTS”

A very well explained and produced article. It just so happens that I am working on a tacacs+ server for my JNCIP environment (JNCIP-SP) and this happens to be tailored to exactly what I am looking for. Thanks again for your help!

Hi Keeran
Excellent article. It helped me to understand how to configure TACACS in a Juniper box.
Thanks!

group = admin default service = permit
service = exec priv_lvl = 15
>
>

Cheers for that! ill update the post accordingly 🙂

Have a small question on the below configuration :
I am in need of getting the name field value from server.

i would have to give a strong pass, unfortunately i never tested this when i made the post 🙁

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Исходные данные:
Сервер, с debian wheezy на борту, на котором уже стоит tacacs+ и tftp, установленные мной же из репозиториев.

Приступаем к установке и настройке нового tacacs+ (естественно, удаляем старый tacacs+).
Собирать его мы будем с помощью checkinstall. Нам понадобятся некоторые библиотеки и gcc-multilib. Ставим:
apt-get install flex bison libtool gcc-multilib checkinstall
Подготавливаем к сборке:
./configure
И собираем:
checkinstall

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

tacacs-sourse — каталог, куда мы распаковали исходники.

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

Далее, самая интересная часть — конфигурирование.
На сети, я использовал tacacs+ для cisco, juniper, zelax, qutech.

Но, приступим к конфигурации самого tacacs+:
Для начала, стоит создать каталог, где будет храниться файл конфигурации, у меня это /etc/tacacs+/. Далее, создадим сам файл конфигурации, у меня — tacacs.conf. Выставляем права 600 на папку и файл, чтобы никто посторонний не смог подсмотреть конфиг.

Далее, приведу простенький пример конфигурационного файла с комментариями:


Пользовательские пароли храним зашифрованным в md5 либо DES. Согласно документации это можно сделать так:


Как вы заметили, всем пользователям по умолчанию даются привилегии 15 уровня (cisco). Однако, пользователи группы noob всё равно смогут выполнить только явно разрешенные им команды. Мне кажется это удобным, не надо постоянно вводить пароль на привилегированный режим.

Возможности ACL тут шире, чем в стандартном tacacs+, но и синтаксис здорово отличается. Для более детального изучение стоит покурить man. В рамках этой статьи останавливаться на ACL я не буду.

И так, мы получили вполне рабочий tacas+. Попробуем его запустить:

В процессах мы увидим нечто такое:
71745 ? Ss 0:00 tac_plus: 0 connections, accepting up to 480 more
71746 ? Ss 0:00 tac_plus: 0 connections
71747 ? Ss 0:00 tac_plus: 0 connection

Правда удобно видеть сколько пользователей в данный момент пользуются системой (особенно, когда хочешь её остановить)?

Даем скрипту права на исполнение (chmod +x). Обзываем его например tac_plus и кидаем в /etc/init.d. Все. Теперь можно стопарить, запускать, рестартовать tacas+ с помощью service tac_plus start/stop/restart.

И для полного феншую добавим tacacs+ в автозагрузку:
update-rc.d tac_plus defaults .

Серверная часть готова. Перейдем к настройке активного оборудования. На самом деле, тут все просто, отличился лишь juniper. Для cisco конфиг думаю смысла приводить нет (для zelax и qutech он практически идентичен), а вот для juniper приведу. Кстати, в документации описано, как подружить juniper и tacacs+. В свое время, мне пришлось здорово с этим повозиться.

Конфиг для juniper:

Даже с включенным tacacs+, вы сможете попасть на juniper под учетной записью root. Это делается для того, чтобы вы могли попасть в shell. По учеткам tacacs+ вы попадаете сразу в cli.

Так же, настоятельно рекомендую выделять подсеть управления и навешивать на все устройства ACL, с доступом только с этой подсети.

А сейчас, приведу несколько скриншотов:

image

image

З.Ы. К вопросу стабильности. На прошлой работе систему юзало куча администраторов и было несколько тысяч устройств. Все было, в принципе, хорошо.
На текущем месте — это несколько десятков устройств и пяток пользователей, все прекрасно.

In this blog post, I will cover on how to build and configure TACACS+ on Ubuntu Server using tac_plus. While this is an old blog post, the instructions covered here are still valid in Ubuntu Server 16.04 LTS. I highly recommend that you integrate two-factor authentication (2FA) as well, which is covered here .

Related: Adding Two-Factor Authentication (2FA) to TACACS+ running on Ubuntu 16.04

Tac_plus is a TACACS+ daemon for Linux that is based on the original Cisco TACACS+ source code.

Related: Deploying TACACS+ on a Docker container

The main difference between the two protocols is how they encrypt the packet. RADIUS only encrypts the password and the rest are unencrypted, so the username, authorized services, and accounting can be captured. On the other hand, TACACS+ encrypts the entire packet which is more secure. If you are tasked to deploy AAA in your organization, make sure that you opt with the TACACS+ implementation and not RADIUS.

In this tutorial, you will need the following:

Instructions

Below are the steps in successfully implementing TACACS+ to your routers and switches.

Download, Install and Update

Download, install and update Ubuntu 11.04 Server Edition on your machine(s). While one machine is enough, I suggest deploying two for backup. If getting another physical/virtual machine is an issue, then do not worry about it. There is a backup user account that will be created in this tutorial, so when the TACACS+ is not available Network Administrators/Technicians/Engineers can still authenticate and issue commands.

Download and install TACACS+. To download TACACS+, issue the command below:

Edit tac_plus Configuration File

Using VI editor to edit the configuration file. Feel free to use nano or other text editors available.

The default configuration of the TACACS+ accounting log is /var/log/tac_plus.acct. Feel free to change this to your liking. However, I suggest you change the read and write permissions using chmod, so that only certain users or groups are allowed to edit or view the file.

Define TACACS+ Key

Define your TACACS+ key here. Remember this key since it will be used later on your AAA configuration.

User Accounts And Groups

In this section, I will create three user accounts and assign them to their proper group.

Network engineers have all commands available to them. The default service = permit parameter tells TACACS+ daemon that all commands are allowed for this group. The login = file /etc/passwd parameter tells the daemon to look for the user account and password matches in the file. If it matches, allow the account to log in to the router and switch. The enable = file /etc/passwd tells the daemon that it needs to match the password of the user account. If it matches, allow to enter privileged EXEC mode, also known as enable mode.

Permissions

Creating a test user account and the group might be a good idea, so you can test things out that have been added to this configuration. This particular test user will only have a cleartext password.

Restart tac_plus Daemon

Most of the time in Linux/Unix environment, you need to restart the daemon before your configuration will take effect.

User Accounts

It is now time to create the user account under Linux.

Change Password

If I am showing you how to add a Linux user account, then I should be showing you how to remove an account as well, since all organizations lose good and/or bad employees all the time. Not deleting an account is a big no-no and obviously a huge security risk.

Changing IP Address

Look for the following:

Once found, change it to something similar:

Again, if you change something it needs to be restarted.

Cisco Configuration

The how to configure AAA on Cisco routers and switches is covered here and the how to configure AAA on Cisco ASA is covered here . To create ACL on tac_plus, please see this post .

Final Words

I hope this tutorial has been helpful and thank you for reading!

Are you ready to improve your network security?

Читайте также: