pfSense + OpenVPN autenticando no Active Directory

pfSense + OpenVPN autenticando no Active Directory

pfSense + OpenVPN autenticando no Active Directory

Hello my Friends (TI) 🙂

Dando continuidade aos trabalhos hoje trago a vocês mais um tutorial sobre pfSense + OpenVPN que eu acredito que será muito útil para quem deseja aplicar as configurações de autenticação de sua VPN client to site através de Active Directory.

Para seguir a leitura deste tutorial recomendo que você primeiramente veja como configurar a Integração pfSense com Active Directory pois sem esta etapa você não irá conseguir entender e aplicar o tema aqui abordado.

Para iniciar a configuração do OpenVPN clique em VPN e selecione OpenVPN.

Agora iremos iniciar o Wizard do OpenVPN para realizar a primeira configuração.

Em nosso laboratório iremos configurar a autenticação dos usuários da VPN cliente to site através do LDAP, ou seja autenticando com usuários do Active Directory

c
Zsense
System
COMMUNITY
https://10.254.0.1
Interfaces Firewall Services. VPN. Status. Diagnostics
Help
Wizard / OpenVPN Remote Access Server Setup /
OpenVPN Remote Access Server Setup
This wizard will provide guidance through an OpenVPN Remote Access Server Setup .
The wizard may be stopped at any time by clicking the logo image at the top of the screen.
Select an Authentication Backend Type
Type of Server
Local User Access
RADIUS
pfSense + OpenVPN – Wizard

Após selecionada a opção LDAP e ter clicado em Next será apresentada o Step 1, como temos apenas uma configuração do Active Directory neste laboratório apenas o nome “AD” será apresentado, clique em Next.

Zsense
System
COMMUNITY EDITION
https://
10.254.0.1 'Wizard openvpn_wizard.xml
Interfaces Firewall Services. VPN- Status. Diagnostics
Help
Wizard / OpenVPN Remote Access Server Setup / LDAP Server Selection
LDAP Server Selection
OpenVPN Remote Access Server Setup Wizard
LDAP Authentication Server List
Add new LDAP server
Next
pfSense + OpenVPN – Configurando Auteticação através do AD

Seguindo o Wizard será necessário criar o Certificate Authority CA, preencha os campos conforme o print.

Descriptive name: pfSense-CA (Nome para Autoridade Certificadora)
Lifetime: 3650 (Neste cenário estamos utilizando 10 anos, porem você pode reduzir conforme sua necessidade)
Country Code: BR
State or Province: Sao Paulo
City: Sao Paulo
Organization: Friends Corp

c
Zsense
System
COMMUNITY EDITION
https://10.254 0.1
Interfaces Firewall Services VPN- Status. Diagnostics
Help
Wizard / OpenVPN Remote Access Server Setup/ Add Certificate Authority
Certificate Authority Selection
OpenVPN Remote Access Server Setup Wizard
Create a New Certificate Authority (CA) Certificate
Descriptive name
Key length
Lifetime
State or Province
Organization
e-CA
A name for administrative reference, to identify this certificate This is the same as common-name field for other
Certificates.
2048 bit
Size of the key which will be generated. The larger the key, the more security it offers, but larger keys take considerably more
time to generate, and take slightly longer to validate leading to a slight slowdown in setting up new sessions (not always
noticeable). As of 2016, 2048 bit is the minimum and most common selection and 4096 is the maximum in common use.
For more information see keylength.com
Lifetime in days This is commonly set to 3650 (Approximately 10 years.)
Two-letter ISO country code (e.g. US, ALI, CA)
Full State or Province name, not abbreviated (e.g. Kentucky, Indiana, Ontario).
Sao Pa
City or other Locality name (e.g. Louisville, Indianapolis, Toronto).
FriendsTl Corp
Organization name, often the Company or Group name.
Criando um nova Autoridade Certificadora – pfSense

Na próxima tela possivelmente será necessário preencher apenas o Descriptive Name.

c
usense
System
COMMUNITY EDITION
https://10.254.0.1 /wizard.php?xml=openvpn_wizard.xml
Interfaces Firewall Services VPN Status. Diagnostics
Help
Wizard / OpenVPN Remote Access Server Setup/ Add a Server Certificate
Server Certificate Selection
OpenVPN Remote Access Server Setup Wizard
Create a New Server Certificate
Descriptive name
Key length
Lifetime
country code
State or Province
City
Organization
A name for administrative reference, to identify this certificate This is also known as the certificate's "Common Name"
2048 bit
Size of the key which will be generated. The larger the key, the more security it offers, but larger keys take considerably more
time to generate, and take slightly longer to validate to a slight slowdown in setting up new sessions (not always
noticeable). As of 2016, 2048 bit is the minimum and most common selection and 4096 is the maximum in common use.
For more information see keylength.com
398
Lifetime in days. Server certificates should not have a lifetime over 398 days or some platforms may consider the certificate
invalid.
Two-letter ISO country code (e.g. US, ALI, CA)
Sao Paulo
Full State of Province name, not abbreviated (e.g. Kentucky, Indiana, Ontario).
Sao Paulo
City or other Locality name (e.g. Louisville, Indianapolis, Toronto).
FriendsTl Corp
Organization name, often the Company or Group name.
Create new Certificate
Criando o Server Certificate – pfSense + OpenVPN

Em seguida selecione a interface que será utilizada, neste laboratório utilizamos a WAN porem você pode ter renomeado a interfaces de WAN ou até mesmo ter mais de uma.

c
Zsense
System
COMMUNITY EDITION
PA https://
10.254.0.1 'Wizard. .xml
Interfaces Firewall Services VPN- Status. Diagnostics
Help
Wizard / OpenVPN Remote Access Server Setup/ Server Setup
Server Setup
OpenVPN Remote Access Server Setup Wizard
General OpenVPN Server Information
WAN
Local Port
Description
The interface where OpenVPN will listen for incoming connections (typically WAN.)
UDP on IPv4 only
Protocol to use for OpenVPN connections. If unsure, leave this set to UDP
1194
Local port upon which OpenVPN will listen for connections. The default port is 1 194. This can be left at its default unless a
different port needs to be used.
FriensTl - openVPN
A name for this OpenVPN instance, for administrative reference It can be set however desired, but is often used to
distinguish the purpose of the service (e.g. "Remote Technical Staff"). It is also used by OpenVPN Client Export to identify
this VPN on clients.
Configurando a interface WAN que será utilizada

Desça a barra de rolagem até Tunnel Settings e conforme a sua necessidade preencha as configurações.

Tunnel Network: 172.16.0.0/24 (Para este tutorial utilizei outra rede privada pois meu pfSense está sobre um Hype-V)
Local Network: 10.254.0.0/24 (A rede LAN do meu pfSense)

As demais configurações não serão abordadas neste tutorial, porem você pode ler a respeito destas configurações na documentação oficial clicando aqui.

c
Tunnel Settings
Redirect Gateway
Local Network
Allow Conwression
Compression
Type-of-service
Inter-Client
Comnwnication
Duplicate
Connections
O https://10.254.0.1
This is the virtual network used for private communications between this server and client hosts expressed using CIDR
notation (eg_ 10.0.8.0/24)_ The first network address will be assigned to the server virtual interface. The remaining network
addresses will be assigned to connecting clients.
Force all client generated traffic through the tunnel.
10.254.
This is the network that will be accessible from the remote endpoint, expressed as a CIDR range. This may be left blank if
not adding a route to the local network through this tunnel on the remote machine. This is generally set to the LAN network.
Specify the maximum number of clients allowed to concurrently connect to this server.
Refuse any non-stub compression (Most secure)
Allow compression to be used with this VPN instance, which is potentially insecure.
Disable Compression [Omit preference]
Compress tunnel packets using the chosen option. Can save bandwidth, but is potentially insecure and may expose data.
This setting has no effect if compression is not allowed. Adaptive compression will dynamically disable compression for a
period of time if OpenVPN detects that the data in the packets is not being compressed efficiently.
Set the TOS IP header value of tunnel packets to match the encapsulated packets TOS value.
Allow communication beü•een clients connected to this server.
Allow multiple concurrent connections from clients using the same Common Name.
NOTE: This is not generally recommended, but may be needed for some scenarios.
Configurando o tunel

Como estamos utilizando um Active directory podemos também configurar o DNS de sua LAN, preencha as configurações conforme o print e em seguida clique em Next.

DNS Default Domain: friendsti.com.br (Seu dominio local, no meu caso friendsti.com.br)
DNS Server 1: 10.254.0.10 (O IP do servidor de Active Directory que também é o DNS local)
DNS Server 2: 8.8.8.8 (fica a seu critério configurar um segundo DNS local ou até mesmo um público como neste caso)

c
Client Settings
Dynamic IP
Topology
DNS Default Domain
DNS server 1
DNS server 2
DNS server 3
DNS server 4
NTP server 2
NetBIOS options
NetBIOS Node Type
O
https://10.2 54.0.1 openvpn_wizard .xml
Allow connected clients to retain their connections if their IP address changes.
Subnet — One IP address per client in a common subne v
Specifies the method used to supply a virtual adapter IP address to clients •.fien using tun mode on IPv4.
Some clients may require this be set to "subnet' even for IPv6, such as OpenVPN Connect (iOS/Android).
Older versions of OpenVPN (before 2.0_9) or clients such as Yealink phones may require "net30•.
Provide a default domain name to clients.
10.254.0_10
DNS server IP to provide to connecting clients.
DNS server 'P to provide to connecting clients.
DNS server IP to provide to connecting clients.
DNS server IP to provide to connecting clients.
Network Time Protocol server to provide to connecting clients.
Network Time Protocol server to provide to connecting clients.
Enable NetBIOS over TCP/IP.
If this option is not set, all NetBIOS-over-TCP/IP options (including WINS) will be disabled.
Possible options: b-node (broadcasts), (point-to-point name queries to a WINS server), m-node (broadcast then
query name server), and h-node (query name server, then broadcast).
Configuração de DNS do tunel do OpenVPN

Na última configuração deste Wizard recomendo que você selecione Firewall Rule e OpenVPN Rule para que sejam criadas as regras de firewall de forma automática nas interfaces.

c
Zsense
System
COMMUNITY EDITION
PA https://10.254.0.1
Interfaces Firewall Services. VPN. Status. Diagnostics -
Help
Wizard / OpenVPN Remote Access Server Setup / Firewall Rule Configuration
step
Firewall Rule Configuration
OpenVPN Remote Access Server Setup Wizard
Firewall Rule Configuration
Firewall rules control what network traffic is permitted. Rules must be added to allow traffic to the OpenVPN server's IP and
port, as well as allowing traffic from connected clients through the tunnel. These rules can be automatically added here, or
configured manually after completing the Wzard.
Traffic from clients to server
Add a rule to permit connections to this OpenVPN server process from clients anywhere on the Internet.
Traffic from clients through VPN
openVPN rule e
Add a rule to allow all traffic from connected clients to pass inside the VPN tunnel.
Next
Firewall Rule Configuration – pfSense + OpenVPN

Pronto o Wizard da configuração do OpenVPN foi concluído, clique em Finish

Zsense
System
COMMUNITY ENTION
PA https://10.254.0.1
Interfaces Firewall Services. VPN. Status. Diagnostics
Help
Wizard / OpenVPN Remote Access Server Setup / Finished!
Finished!
OpenVPN Remote Access Server Setup Wizard
Configuration Complete!
The configuration is now complete.
To be able to export client configurations, browse to System->Packages and install the OpenVPN Client Export package.
Finish
OpenVPN Wizard concluído

As configurações ainda não acabaram, fique atento aos próximos passos que são muito importantes para que você possa utilizar o pfSense + OpenVPN para autenticar através do Active Directory.

Observe no print a seguir, que é a tela após finish do wizard, que o modo de autenticação é apenas o User Auth ou seja está sua VPN será autenticada apenas com usuário e senha, vamos editar e configurar para que possamos utilizar autenticação através de certificado SSL/TLS e o usuário e senha do seu Active Directory.

c
O
Zsense
System
COMMUNITY EDITION
LOA https://10.254.o.1
/vpn_openvpn_server.php
Interfaces Firewall Services
VPN status
Diagnostics -
Help
VPN / openVPN / servers
Servers Clients Client Specific Overrides
Wizards
Client Export
Shared Key Export
OpenVPN Servers
Interface Protocol / Port
UDP4 / 1194
(TUN)
Tunnel Network
17216.0-0/24
Mode / Crypto
Mode: Remote Access ( User Auth )
CM, CHACHA2CP
POLY1305, AES-256-CBC
Digest: SHA256
D-H Params.• 2048 bits
Description
FriensTl -
openVPN
Editando a configuração do mode de autenticação do OpenVPN

Na configuração Server Mode altere para Remote Access ( SSL/TLS + User Auth ) e clique em salvar.

c
Zsense
System
COMMUNITY EDITION
PA https://10.254 0.1
Interfaces Firewall Services VPN. Status
=edit&id=O
Diagnostics •
Help
VPN / openVPN / servers/ Edit
Servers Clients Client Specific Overrides Wizards
General Information
Client Export
Shared Key Export
Disabled
Server mode
Backend for
authentication
Device mode
Description
Cl Disable this server
Set this option to disable this server without removing it from the list.
Remote Access ( SSL/TLS + User Auth )
PAD
Local Database
UDP on IPv4 only
tun - Layer 3 Tunnel Mode
•tun" mode carries IPv4 and IPv6 (OSI layer 3) and is the most common and compatible mode across all platforms.
tap' mode is capable of carrying 8023 (OSI Layer 2.)
WAN
The interface or Virtual IP address where OpenVPN will receive client connections.
1194
The port used by OpenVPN to receive client connections.
FriensTl - openVPN
A description may be entered here for administrative reference (not parsed).
Editando a configuração do mode de autenticação do OpenVPN

Após aplicado a configuração anterior agora iremos criar o certificado para o usuário que utilizará a VPN, acesse a aba System e clique em Cetificate Manager.

Agora clique em Certificates e depois em “Add”, Preencha o campo Descriptive Name e Common Name exatamante com o sAMAccountName do usuário em seguida clique em Salvar.

Certificates
https://
10.254.0.1 /system_certma nager new
Certificate Revocation
Add/Sign a New Certificate
Descriptive name
Internal Certificate
Certificate authority
est
Conunm Name
Country Code
State or Province
City
Organization
Organizational unit
Certificate Attributes
Attribute Notes
C«tificate Type
Create an internal Certificate
Jean
pfSense-CA
The length to use when generating a new RSA key, in bits.
The Key Length should not be lower than 2048 or some platforms may consider the certificate invalid.
sha2S6
The digest method used when the certificate is signed
The best practice is to use an algorithm stronger than SHAI Some platforms may consider weaker digest algorithms invalid
3650
The length of time the signed certificate will be valid, in days
Server certificates should not have a lifetime over 398 days or some platforms may consider the certificate invalid
jean
The following certificate subject components are optional and may be left blank.
Sao Paulo
Sao Paulo
FriendsTI Corp
e.g My Department Name (optional)
The following attributes are added to certificates and requests when they are created or signed. These attributes behave differently depending on the
selected mode.
For Internal Certificates, these attributes are added directly to the certificate as shown.
user Certificate
Add type-specific usage attributes to the signed certificate Used for placing usage restrictions on, or granting abilities to, the signed certificate.
Type
Value
Conexöes de Rede
Criando certificado do usuário para autenticar na VPN

Nesta próxima etapa será necessário exportar as configurações do usuário, configurações do OpenVPN e o certificado do usuário.

Para isso podemos instalar um pacote chamado OpenVPN Client Export, clique na aba System em seguida Package Manager e localize a opção Available Packages.

No campo Search Term digite “openvpn” e você deve ter um resultado parecido com o deste print abaixo, clique em install no pacote openvpn-client-export e aguarde até a conclusão.

c
O
Zsense
System
COMMUNITY EDITION
e. https://10.254.o.1/pkg_mgr.php
Interfaces Firewall Services. VPN
Status
System/ Package Manager/ Available Packages
Installed Packages Available Packages
Diagnostics
Both
Help
Search
Search
Search term
Packages
openvpn-
client-
WireGuard
openvpn
Clear
Version
1.62
0.1.5_3
Enter a search string or *nix regular expression to search package names and descriptions.
Description
Allows a pre-configured OpenVPN Windows Client or Mac OS Xls Viscosity configuration bundle to be exported
directly from pfSense.
Package Dependencies:
openvpn-client-export-2.5.2 openvpn-25.2_2 zip-3.0_1 p7zip-16.02_3
WireGuard(R) is an extremely simple yet fast and modern VPN that utilizes state-of-the-art cryptography. It aims
to be faster, simpler, leaner, and more useful than IPSec, while avoiding the massive headache. It intends to be
considerably more performant than OpenVPN. WireGuard is designed as a general purpose VPN for running on
embedded interfaces and super computers alike, fit for many different circumstances. Initially released for the
Linux kernel, it is now cross-platform and widely deployable. It is currently under heavy development, but already
it might be regarded as the most secure, easiest to use, and simplest VPN solution in the industry. This package
is EXPERIMENTAL.
Package Dependencies:
C wireguard-tools-l .0.20210914_1 C wireguard-kmod-o.o.20211105
+ Install
+ Install
Instalando pacote openvpn-client-export

Atenção: Você precisa instalar uma unica vez este pacote, nas proximas vezes que for exportar as configurações do usuário basta navegar até a aba VPN em seguida clicar em OpenVPN e depois localizar OpenVPN Client Export.

Localize Client Export e desça a barra de rolagem até OpenVPN Clients, agora basta localizar o usuário e selecionar a versão do cliente que deseja instalar na estação de trabalho. Neste exemplo iremos utilizar a versão mais recente que é a 2.5.2 x64

Realizar a instalação do cliente (Basicamente next next finish…)

OpenVPN Clients
User
Certificate with External Auth
Certificate Name
Export
- Inline Configurations:
Most Clients Android OpenVPN Connect (iOS/Android)
- Bundled Configurations:
Archive Config File Only
- Current Windows Installer (2.5.2-lx01):
64b i t 32-bit
- Legacy Windows Installers (2.4_1 1-Ix01):
10/2016/2019 *7/8/8.1/20120
- Viscosity (Mac OS X and Windows):
Viscosity Bundle Viscosity Inline Config
Exportando o setup do OpenVPN e as configurações do usuário

Após instalado basta procurar na bandeja do Windows próximo do relógio pelo OpenVPN GUI, selecionar a sua configuração e em seguida clicar em conectar.

Observe que no meu caso já estava conectado e nos prints a seguir você pode verificar a evidencia.

FriendsTl.com.br
pfSense-UDP4- I I g4-jean
Importar arquivo...
Configurações...
Conectar
Desconectar
Reco nectar
Mostrar status
Visualizar log
Editar configurações
Limpar Senhas Salvas
rs
Too I s
210C Limpo A
POR
23:02
Conectando na VPN através do cliente OpenVPN numa estação Windows 10

Obs: Esta nomenclatura pfSense-UDP4-11940-jean você pode facilmente modificar acessando o diretório C:\Program Files\OpenVPN\config selecionado o arquivo com .ovpn e renomear.

Após conectado na VPN através do usuário jean você pode observar que o IP da minha estação de trabalho no tunel da VPN é o 172.16.0.2 (CMD) já no Web Configurator adicione o Widget OpenVPN e observe o usuário e IP conectado.

pfSense.friendsti.IocaI - Status X
https://
10.254.0.1
Zsense
COMMUNITY EDITION
O
System
Interfaces
Firewall •
Services •
peo
VPN
Status •
Interfaces
Diagnostics
Help
Status/ Dashboard
System Information
Name
User
System
BIOS
Version
CPU Type
Hardware crypto
Kernel PTI
MDS Mitigation
pfSense.friendsti .local
jean@172.16.02 (LDAP/AD)
Microsoft Azure
Netgate Device ID: 67e68ad8299cc788c5bb
Vendor: American Megatrends Inc.
Version: 090008
Release Date: Fri Dec 7 2018
2.5.2-RELEASE (amd64)
built on Fri Jul 02 EDT 2021
Free8SD 12.2-STA8LE
The system is on the latest version.
Version information updated at Tue Dec 21 22:12:13-03 2021
Intel(R) Core(TM) i5-8365U CPU @ 1.60GHz
2 CPUs: 1 package(s) x 1 core(s) x 2 hardware threads
AES-NI CPU Crypto: Yes (inactive)
QAT Crypto: No
Disabled
Inactive
WAN
LAN
VLAN_172
OpenVPN
FriensTl
Name/Time
Jean
10Gbase-T <full-duplex>
IOGbase-T
10Gbase-T <full-duplex>
peo
192.168.1.107
10.254.0.1
172.254.0.1
peo
- OpenVPN UDP4•.1 194 (1)
2021-12-21
Real/Virtual IP
192.168.1.104:1194
172.16.0.2
Adaptador desconhecido OpenVPN TAP-Windows6:
Sufixo DNS especifico de conexäo.
Endereco IPv6 de link local
Endereco IPv4.
mäscara de Sub-rede
Gateway Padräo.
Adaptador
Estado
Sufixo
de Rede sem Fio Conexäo Local* 1:
da midia.
DNS especifico de conexäo.
friendsti . com.br
few: : ddSd : bbld :fb2 : 694%3ß
172.16.ø.2
255.255 . 255.8
midia desconectada
Dashboard pfSense onde demonstra a conexão através do Widget do OpenVPN

Lembrando que estes são IPs privados pois estou num ambiente de laboratório montado no Hyper-v em meu Laptop, para testes lembre-se de deixar bogon networks desabilitados pois caso contrário você pode ter problemas.

Neste tutorial aprendemos a integrar a nossa cliente VPN SSL que utilizar o OpenVPN com o nosso Active Directory, porem os usuários que fazem parte da OU configuradas lá no primeiro tutorial poderão acessar esta VPN caso alguém compartilhe o certificado e ou alguma pessoa mal intencionada queira utilizar a estação de trabalho de outro colaborador com as suas credencias.

Sendo assim num próximo tutorial irei abordar como podemos segregar estes acessos através dos grupos do Active Directory.

Referências:

OpenVPN

Authenticating OpenVPN Users with RADIUS via Active Directory

Gostou? Curta e compartilhe!

Duvidas, críticas ou elogios deixe nos comentários!

Veja também:

TUTORIAL: COMO CRIAR NAT NO PFSENSE

DICA: PING EXTERNO NA WAN DO PFSENSE

TUTORIAL: VPN IPSEC ENTRE PFSENSE 2.2.4 E PFSENSE 2.3

TUTORIAL: PFSENSE OPENVPN

Jean Oliveira

Profissional de Tecnologia da Informação com 10 anos de experiência em empresas de diversos portes. Ampla experiência em administração de servidores Windows, implantação e administração de serviços AD, DNS, DHCP, DFS, GPO, WDS e WSUS. Forte atuação em suporte e administração de servidores virtuais com Hyper-V e VMWare, conhecimentos avançados em Veeam Backup e Veritas BackupExec. Experiência em suporte e administração de Citrix Virtual Apps e Desktops. Vivencia em monitoramento de redes e servidores com Zabbix e SolarWinds. Conhecimentos avançados em desenvolvimento de scripts para automação de tarefas com PowerShell. Foco na melhoria da experiência do usuário e redução de custos operacionais. Capacidade de análise de problemas em ambientes de missão crítica propondo soluções rápidas e efetivas, profissional dinâmico, comprometido, proativo e diligente.

Related Posts
Comments ( 2 )
  1. Patrick Pesegodinski
    3 de agosto de 2022 at 16:35
    Reply

    Boa Tarde jean.
    você já configurou para filtrar por grupo do ad?
    estou tendo problema, pois ao ativar “Enable extended query” e inserir o grupo para realizar a autenticação, a liberação só ocorre com o usuário inserido na UO da opção “Authentication containers”.
    simplesmente o “extended query” é ignorada.

    estou utizando a versão 2.6.0

    • Jean Oliveira
      Jean Oliveira
      3 de agosto de 2022 at 19:17
      Reply

      Boa noite!
      Ja configurei sim!
      Você seguiu o primeiro tutorial que fiz sobre a integração com o AD? https://friendsti.com.br/integracao-pfsense-com-active-directory/
      Se sim observe a query que vc configurou esta mais ou menos deta forma: |(&(objectCategory=user)(memberOf=CN=G_ADM_OU=FriendsTI,DC=friendsti,DC=com,DC=br))(&(objectCategory=user)(memberOf=CN=G_VPN,OU=FriendsTI,DC=friendsti,DC=com,DC=br))
      Observe que a Query, tem o grupo de ADM que são dos usuários administrador do pfSense e também o grupo G_VPN que são dos usuários de VPN apenas…

Leave a reply
Captcha Click on image to update the captcha .