- Install the VNC Remote Access Server on Oracle Linux 8
- Introduction
- Background
- Objectives
- Prerequisite
- Install a graphical desktop environment
- Install the VNC packages
- Set the VNC password
- Configure the VNC service
- Set up the VNC service
- Configure X509 encryption (optional)
- Configure firewall rules (optional)
- Open a VNC client and test your deployment
- Video demonstration
- For More Information
- More Learning Resources
- Установка VNC сервера, и настройка его работы поверх SSH
- Приступим
- Создание скрипта автостарта vnc сервера.
- использование созданного нами скрипта:
- Шифрование трафика
- Пускаем VNC поверх SSH:
- При использовании Windows и putty агента:
Install the VNC Remote Access Server on Oracle Linux 8
Introduction
This tutorial shows you how to install and set up the VNC remote access server software on an Oracle Linux 8 system to enable you to remotely operate a graphical desktop environment.
Background
Virtual Network Computing (VNC) is a graphical desktop sharing system that controls remote machines by sending keyboard and mouse events over the network. VNC is particularly useful for remotely controlling Oracle Linux servers that have a graphical desktop environment installed.
You can connect to a VNC server by using any compatible software client. VNC is suitable for thin client computing where multiple dumb terminals can share the same hardware resources that are hosted on an Oracle Linux server.
This tutorial uses TigerVNC to illustrate how to remotely connect to systems. However, you can use a different VNC software of your choice. Some alternative software is listed at the end of the tutorial.
TigerVNC Server was rebased from 1.9.0 to 1.10.1 in Oracle Linux 8 Update 3. This newer version is configured differently to previous versions and no longer requires the creation of systemd unit files. The instructions provided here assume that you are using the latest version.
Objectives
In this tutorial you:
- Install a graphical desktop environment along with the VNC service
- Set the VNC Password for a user on the system
- Configure the VNC service for a specific user
- Start and enablve the VNC service across subsequent boots
- Optionally enable x509 encryption for direct VNC access
- Optionally create firewall rules to allow direct VNC access
- Access the VNC server from a remote client, either directly or using an SSH tunnel
Prerequisite
- Any system with Oracle Linux 8 installed
- Client software such as TigerVNC
Install a graphical desktop environment
Install a GNOME desktop environment and all of its dependencies.
Set graphical mode as the default login type for user accounts, then reboot the server.
Uncomment the following line in the /etc/gdm/custom.conf file to ensure that VNC uses X.org instead of Wayland:
Install the VNC packages
Install the VNC server package and all of its dependencies.
Set the VNC password
Create a VNC password for the user account that you intend to use for remote sessions.
The command prompts you for a password and then prompts you again to validate the password. Optionally you are able to set a ‘view-only’ password that allows you to share the screen but not allow control over the mouse or keyboard.
This action generates configuration information specific to the user account in $HOME/.vnc/ . If this directory already exists from a previous installation, you can either remove the directory prior to running the vncpasswd command; or you can restore the SELinux context on the directory to ensure that you do not have any issues with SELinux for this service. For example:
Configure the VNC service
Append the user account and the X Server display for the VNC service to /etc/tigervnc/vncserver.users file:
Also append the default desktop and screen resolution to the /etc/tigervnc/vncserver-config-defaults file:
By default, the VNC server terminates when the last user signs out. You can manually force the VNC server to persist by creating the /etc/systemd/system/vncserver@.service.d/10-restart.conf file as the root user, and then adding the following content:
Set up the VNC service
Reload the systemd service, then enable and start the VNC server by using X Server display 1:
Configure X509 encryption (optional)
By default, VNC is not an encrypted protocol and you should use an SSH tunnel to access it across an unprotected network. You can configure X509 TLS to encrypt your VNC session, however this requires that your client software supports X509Vnc encryption and has access to the CA certificate used to sign your certificates.
If you do not have a CA signed certificate, you can use self-signed certificates, but your client system must have a copy of the public certificate to be able to connect. To create a self-signed certificate, run:
Edit the user’s custom VNC configuration options in `
/.vnc/config`. If the file does not exist yet, you may need to create it yourself. Update the configuration to enable x509Vnc encryption and to provide the full path to the X509 key file and that x509 certificate file. For example, assuming that the username is opc, the following configuration should work correctly:
Note that you must provide the full path to the key and certificate files. You cannot depend on shell expansion or use variables for this purpose.
When you have finished editing the configuration, you can restart the service:
Configure firewall rules (optional)
If you are using X509 encryption and you are running a custom firewall profile or an Oracle Cloud Infrastructure instance, you can open the firewall port for the VNC service (5901) on your firewall or in your security lists for your network.
If you are using X509 encryption and the firewalld service is running on the host, you can add access for the VNC service. Then, reload the default firewall service.
Note: VNC is not an encrypted protocol and you should not open the firewall to this port and connect directly to a VNC server over an unprotected network. Although we list this step as optional, it is not generally advised and you should consider using SSH tunneling or some other mechanism to protect the connection.
Open a VNC client and test your deployment
If your client is running Oracle Linux 8, you can install the TigerVNC software client:
On the client machine, use the VNC software to connect to the remote Oracle Linux server domain or IP address. Make sure to specify the correct port. The default VNC port is 5900, but that number is incremented according to the configured display number. Thus, display 1 corresponds to 5901, display 2 to 5902, and so on.
Note that if you enabled X509 encryption, you may need to provide the CA certificate used to sign your keys, or if you used a self-signed certificate you can use the public certificate as the CA certificate. Some clients may be willing to allow you to simply accept a self-signed certificate automatically.
If you encounter connectivity problems, troubleshoot these issues by connecting to the remote server over an SSH connection that has been configured for an SSH tunnel. Then, use the tigervnc client to connect to the local host:
Video demonstration
The video demonstration and tutorial provided at https://www.youtube.com/watch?v=Z5vhER7K34E may also be useful if you need more information on configuring a VNC server.
For More Information
Other related resources include:
- Tiger VNC Server configuration documentation in /usr/share/doc/tigervnc/HOWTO.md/
- GNOME desktop sharing with Vino at https://wiki.gnome.org/Projects/Vino
- KDE desktop sharing with Krfb at https://kde.org/applications/internet/org.kde.krfb
- Using VNC client software such as:
- Vinagre; or
- KRDC
- Oracle Linux Documentation
The basic steps included in this tutorial are available in the shell script at ol8-vnc-setup.sh
More Learning Resources
Explore other labs on docs.oracle.com/learn or access more free learning content on the Oracle Learning YouTube channel. Additionally, visit education.oracle.com/learning-explorer to become an Oracle Learning Explorer.
For product documentation, visit Oracle Help Center.
Install the VNC Remote Access Server on Oracle Linux 8
Copyright © 2021, Oracle and/or its affiliates.
Источник
Установка VNC сервера, и настройка его работы поверх SSH
Да, отчего-то не все клиенты хотят работать в таком удобном и черном терминале, панель полностью не удовлетворяет их эстетические потребности, и вообще — «где мой такой любимый и удобный VNC?». вопрос привычки и вкуса
В данной статье будет рассмотрен пример установки и настройки VNC server и графической оболочки (GUI) на примере OC Debian 8 jessie.
Вводная: на руках имеется чистый Debian 8 и жгучее желание получить на выходе защищенный vnc-доступ к серверу.
Приступим
Обновим список доступных пакетов.
Если система свежеустановленная — стоит обновиться.
(!)Бездумно запускать данную команду не на свежеустановленном сервере не стоит, чревато сломанными зависимостями и перспективой работы напильником.
Устанавливаем Xfce и VNC server (любители GNOME, KDE, LXDE, etc. устанавливают оболочку по своему вкусу).
Создаем пользователя от которого будем запускать vnc сервер.
Устанавливаем sudo (в Debian данный пакет не установлен по умолчанию).
Добавляем пользователя vnc в группу sudo.
Переходим под пользователя vnc.
Запускаем vnc сервер.
Если это первый запуск vnc сервера, будет создан конфиг файл и запрошены некоторые параметры:
по умолчанию порт vnc сервера будет 5901, порт каждого следующего дисплея будет увеличиваться на 1 (5902,5903. ).
Проверить запущен ли VNC сервер и на каком порту слушает можно следующей командой.
Убить конкретный дисплей можно так:
:1 — какой дисплей нужно убить.
Создание скрипта автостарта vnc сервера.
Сначала убьем запущенный дисплей :1 (если он запущен).
создаем скрипт запуска
Добавляем следующие строки в файл:
если требуется — в скрипте можно изменить глубину цвета или разрешение экрана.
Делаем файл исполняемым.
использование созданного нами скрипта:
Теперь нужно позаботиться о том, чтобы настроенный нами vnc стартовал после загрузки сервера (запланированной и не очень).
Для этого создаем файл по следующему пути.
Добавляем следующий текст в файл:
[Unit] — указываем описание скрипта (так же можно указать требуемые зависимости и порядок запуска при загрузке).
[Service] — указываем какими командами запускать сервис, под каким пользователем, и тип сервиса.
[Install] — указываем на каком уровне должен запускаться скрипт (runlevel 3 — многопользовательский режим без графики).
Включаем юнит в автозагрузку при старте системы.
Смотрим статус созданного нами юнита.
Дергаем systemd для поиска новых или измененных юнитов.
Шифрование трафика
Голый VNC не шифрует трафик, и оставлять его в таком виде не стоит.
Кроме того, если на Ваш IP выйдут боты из Китая и начнут стучатся по портам, даже если пароль установлен действительно качественный (учтите, что пароль на vnc сессию ограничен 8 символами) и его не взломают, попасть на сервер посредством VNC будет затруднительно, из-за постоянной ошибки на количество неверных попыток авторизации.
Using password file /home/vnc/.vnc/passwd
Warning: password truncated to the length of 8.
Would you like to enter a view-only password (y/n)? n
Пускаем VNC поверх SSH:
Теперь для подключения к серверу сначала нужно создать тунель.
Под *nix:
Теперь возможно подключение посредством vnc клиента, указав вместо IP удаленного сервера localhost и порт на котором слушает vnc-server.
При использовании Windows и putty агента:
После запуска putty переходим Connection -> SSH -> Tunnels.
В поле Source Port вбиваем порт на котором слушает VNC сервер — 5901, в поле Destination вписываем — localhost:5901 и жмем кнопку Add.
должно получиться как на картинке.
Теперь возвращаемся на вкладку Session вписываем IP сервера и порт 22 (тут же можно и сохранить конфигурацию подключения), жмем Open.
паранойи мало не бывает К осторожности нужно приучать сразу, хоть теперь и попасть на наш сервер посредством VNC извне невозможно (для начала нужно залогиниться по ssh и создать тунель), все же стоит задуматься о дополнительной безопасности ssh подключений (помните — китайские боты не дремлют).
Установим и настроим fail2ban.
По умолчанию защита от брутфорса для SSH включена, что нам собственно и требуется.
при превышении заданного числа неудачных вводов пароля подряд (по умолчанию — 6) бан IP, с которого были попытки подбора на заданное время (по умолчанию — 600 секунд).
Устанавливаем пакет из репозитория.
Основной интересующий нас файл настроек находится по пути /etc/fail2ban/jail.conf
Блок настроек для подключения по ssh:
ignoreip — IP адреса, которые не должны быть заблокированы. Можно задать список IP адресов разделённых пробелами, маску подсети, или имя DNS сервера.
bantime — время бана в секундах, по истечении которого IP адрес удаляется из списка заблокированных.
maxretry — количество подозрительных совпадений, после которых применяется правило. В контексте ssh — это число неудавшихся попыток логина, после которых происходит блокировка.
enabled — значение true указывает что данный jail активен, false выключает действие изолятора.
port — указывает на каком порту или портах запущен целевой сервис. Стандартный порт SSH сервера — 22, или его буквенное наименование — ssh.
filter — имя фильтра с регулярными выражениями, по которым идёт поиск «подозрительных совпадений» в журналах сервиса. Фильтру sshd соответствует файл /etc/fail2ban/filter.d/sshd.conf.
logpath — путь к файлу журнала, который программа Fail2ban будет обрабатывать с помощью заданного ранее фильтра. Вся история удачных и неудачных входов в систему, в том числе и по SSH, по умолчанию записывается в log файл /var/log/auth.log.
Дефолтная настройка удовлетворяет наши требования (6 неверных попыток авторизации по shh и IP летит в бан на 600 секунд), но я бы советовал добавить свой IP в доверенный список.
Обидно будет ждать почти два часа, в случае шестикратной ошибки ввода пароля со своего IP (шанс данного кейса отнюдь не нулевой).
Открываем конфиг файл.
В строке ignoreip = 127.0.0.1/8, адрес 127.0.0.1/8 заменяем на свой IP.
Выходим из редактора nano (ctrl+x, отвечаем y на вопрос сохранения внесенных изменений).
Перегружаем сервис для применения изменений в правилах.
В случае срабатывания бана в логах fail2ban, можно заметить строку предупреждения:
И попытки подключения с данного адреса будут отбиваться сервером автоматически до истечения срока бана.
Готово, настройка VNC сервера завершена.
Источник