Задача

В наличии имеется работающий Citrix Netscaler 11.1 и ферма XenDesktop 7.15.
Нужно сделать двухфакторную аутентификацию с Google Authenticator.
При входе пользователь должен вводить свои доменные учетные данные и, в случае, если он входит в соответствующую группу, у него запрашивается код с токена.

Решение

Установка и конфигурирование FreeRadius и Google Authenticator

FreeRadius я буду устанавливать на Ubuntu 18.04.
Для начала загоним систему в домен - вот таким образом .

sudo apt-get update && sudo apt-get upgrade -y

Установим необходимые компоненты:

sudo apt-get install freeradius libpam-google-authenticator

Для начала нужно дать побольше прав сервису freeradius. Для этого, откроем файлик /etc/freeradius/3.0/radiusd.conf и закомментируем там строки:

user = freerad
group = freerad

В результате, сервис будет работать с правами пользователя, который его запустил. То есть, по дефолту - root.
В противном случае - при попытке аутентификации в логе /var/log/auth.log будет такое:

radiusd(pam_google_authenticator)[....]: Failed to change user id to "username"

Дальше - отредактируем файлик /etc/freeradius/3.0/users и сделаем PAM дефолтным методом авторизации:

sudo nano /etc/freeradius/3.0/users

В конец файла добавим:

DEFAULT Auth-Type :=PAM

Теперь отредактируем файлик /etc/freeradius/3.0/sites-enabled/default и включим PAM для дефолтного инстанса.

sudo nano /etc/freeradius/3.0/sites-enabled/default

В разделе Authentication → Pluggable Authentication Modules раскомментируем строку:

pam

Добавим модуль pam в список включенных:

sudo ln -s /etc/freeradius/3.0/mods-available/pam /etc/freeradius/3.0/mods-enabled/

Отредактируем файл /etc/pam.d/radiusd. В нем надо закомментировать всё и добавить строки:

auth requisite pam_google_authenticator.so forward_pass debug
#auth [success=1 default=ignore] pam_winbind.so krb5_auth krb5_ccache_type=FILE cached_login use_first_pass
#auth required pam_unix.so use_first_pass

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

Сделаем бекап файла clients.conf:

sudo mv /etc/freeradius/3.0/clients.conf /etc/freeradius/3.0/clients.conf.orig

и создадим новый файл:

sudo nano /etc/freeradius/3.0/clients.conf

В него пропишем в качестве клиентов все NSIP адреса netscaler'ов:

client 192.168.2.221 {
        secret = mysecret
        shortname = NS
}

или подсеть:

client 192.168.2.0/24 {
        secret = mysecret
        shortname = NS_Subnet
}

и localhost для тестирования:

client 127.0.0.1 {
        secret = testing123
        shortname = TEST
}

Для тестирования нужно создать локального пользователя (или доменного) и залогиниться под ним.
В моем случае это будет testuser

Для получения токена от имени тестового пользователя нужно выполнить команду

google-authenticator

и ответить не несколько простых вопросов:

$ google-authenticator

Do you want authentication tokens to be time-based (y/n) y
Warning: pasting the following URL into your browser exposes the OTP secret to Google:
  https://www.google.com/chart?chs=200x200&chld=M.....

Your new secret key is: ASOFVIZNKRE...
Your verification code is 245107
Your emergency scratch codes are:
  40986613
  75840190
  36494819
  18860443
  79617944

Do you want me to update your "/home/DOMAIN/testuser/.google_authenticator" file? (y/n) y

Do you want to disallow multiple uses of the same authentication
token? This restricts you to one login about every 30s, but it increases
your chances to notice or even prevent man-in-the-middle attacks (y/n) y

By default, a new token is generated every 30 seconds by the mobile app.
In order to compensate for possible time-skew between the client and the server,
we allow an extra token before and after the current time. This allows for a
time skew of up to 30 seconds between authentication server and client. If you
experience problems with poor time synchronization, you can increase the window
from its default size of 3 permitted codes (one previous code, the current
code, the next code) to 17 permitted codes (the 8 previous codes, the current
code, and the 8 next codes). This will permit for a time skew of up to 4 minutes
between client and server.
Do you want to do so? (y/n) y

If the computer that you are logging into isn't hardened against brute-force
login attempts, you can enable rate-limiting for the authentication module.
By default, this limits attackers to no more than 3 login attempts every 30s.
Do you want to enable rate-limiting? (y/n) y

В результате в консоли появится вся необходимая для импорта токена информация. Импортируем его в приложение на смартфоне.

Проверить, что связка FreeRadius + Google Authenticator работает можно с помощью команды radtest.
Команда для проверки будет такой:

radtest _username_ _userpassword_+_token_ _hostname_ 1812 testing123
  • _username_ - логин пользователя
  • _userpassword_+_token_ - пароль и цифры с токена в одну строку без пробела
  • _hostname_ - это адрес RADIUS сервера
  • 1812 - порт на котором работает сервис
  • testing123 - это RADIUS secret, прописанный для клиента 127.0.0.1 в файле /etc/freeradius/3.0/clients.conf.

Конфигурирование NetScaler 11

Можно создать Primary и Secondary политики. При этом, пользователь должен будет успешно аутентифицироваться в соответствии с обоими политиками.
















Установим необходимые компоненты:

sudo apt-get install ntp build-essential libpam0g-dev freeradius git libqrencode3 autoconf

Получаем исходники google authenticator libpam

git clone https://github.com/google/google-authenticator-libpam.git

собираем и ставим

./bootstrap.sh
./configure
make
sudo make install

Варианты решения

Как настроить двухфактоную аутентификацию с Netscaler написано много где. Мне понравился такой вот мануал:
https://www.techdrabble.com/citrix/netscaler/14-2factor-with-google-authenticator-and-netscaler

Однако, этот вариант не позволяет двухфакторно аутентифицировать только пользователей из заданной группы.
Вот тут: https://discussions.citrix.com/topic/332144-radius-authentication-based-on-group-membership-while-preserving-ldap-only-users/ люди обсуждают такую конфигурацию.
И предлагают: What about doing Group extraction for RADIUS, so NS retrieves this list, then create a Group on the NS that matches the AD group and then bind the policy to the group?
А вот тут написано что делать:https://support.citrix.com/article/CTX203775
https://www.carlstalhood.com/netscaler-gateway-12-radius-authentication/

http://www.wrightccs.com/
Free
SMS or pregenerated password list Allows passwordless login, using only SMS.

https://token2.com 5 users free, 2-3 EUR per user. Perpetual
Hardware tokens, Software Tokens
Simple maintenance due to self-enroll feature.
High availability cluster.

https://duo.com/pricing
10 users - free. $3-9 per user, per month
Hardware tokens, Software Tokens, SMS, Voice Calls, etc…

strong, two-factor authentication with mobile phones. Настраивается RADIUS сервер и к нему подключается этот аутентификатор
http://motp.sourceforge.net/
http://huseynov.com/index.php?post=implementing-two-factor-authentication-with-citrix-xenapp-web-interface-5x-using-mobile-otp-and-motp-as-server-at-zero-cost

Enter your comment. Wiki syntax is allowed:
 
  • citrix/netscaler_two_factor_authentication_solutions.txt
  • Last modified: 2019/02/11 09:13
  • by 127.0.0.1