One place for hosting & domains

      StrongSwan

      Como configurar um servidor VPN IKEv2 com o StrongSwan no Ubuntu 20.04


      Uma versão anterior deste tutorial foi escrita por Justin Ellingwood e Namo

      Introdução

      Uma rede virtual privada, ou VPN, permite que você criptografe com segurança o tráfego enquanto ele viaja através de redes não confiáveis, como aquelas em uma cafeteria, uma sala de conferências ou um aeroporto.

      O Internet Key Exchange v2, ou IKEv2, é um protocolo que permite o tunelamento IPSec direto entre o servidor e o cliente. Em implementações de VPNs com IKEv2, o IPSec fornece criptografia para o tráfego de rede. O IKEv2 é nativamente suportado em algumas plataformas (OS X 10.11+, iOS 9.1+ e Windows 10) sem a necessidade de aplicativos adicionais, e ele cuida de engasgos de clientes muito bem.

      Neste tutorial, você irá configurar um servidor VPN IKEv2 usando o StrongSwan em um servidor Ubuntu 20.04. Em seguida, você irá aprender como se conectar a ele com os clientes do Windows, macOS, Ubuntu, iOS e Android.

      Pré-requisitos

      Para completar este tutorial, você precisará de:

      Passo 1 — Instalando o StrongSwan

      Primeiramente, vamos instalar o StrongSwan, um daemon IPSec de código aberto que vamos configurar como nosso servidor VPN. Também vamos instalar o componente de infraestrutura de chave pública (PKI) para que possamos criar uma autoridade de certificação (CA) para fornecer credenciais para nossa infraestrutura.

      Comece atualizando o cache de pacotes local:

      Em seguida, instale o software digitando:

      • sudo apt install strongswan strongswan-pki libcharon-extra-plugins libcharon-extauth-plugins

      O pacote libcharon-extauth-plugins adicional é usado para garantir que vários clientes possam se autenticar em seu servidor usando um nome de usuário e uma frase secreta compartilhados.

      Agora que tudo está instalado, vamos seguir em frente para criar nossos certificados.

      Passo 2 — Criando uma Autoridade de Certificação

      Um servidor com IKEv2 exige que um certificado se identifique para os clientes. Para ajudar a criar o certificado exigido, o pacote strongswan-pki vem com um utilitário chamado pki para gerar uma autoridade de certificação e certificados de servidor.

      Para começar, vamos criar alguns diretórios para armazenar todos os ativos em que iremos trabalhar. A estrutura do diretório corresponde a alguns dos diretórios em /etc/ipsec.d, para onde vamos mover todos os itens que eventualmente criarmos:

      • mkdir -p ~/pki/{cacerts,certs,private}

      Em seguida, vamos bloquear as permissões para que nossos arquivos privados não possam ser vistos por outros usuários:

      Agora que temos uma estrutura de diretório para armazenar tudo, podemos gerar uma chave raiz. Esta é uma chave RSA 4096-bit que será usada para assinar nossa autoridade de certificação raiz.

      Execute estes comandos para gerar a chave:

      • pki --gen --type rsa --size 4096 --outform pem > ~/pki/private/ca-key.pem

      Depois disso, podemos seguir em frente para criar nossa autoridade de certificação root usando a chave que acabamos de gerar para assinar o certificado root:

      • pki --self --ca --lifetime 3650 --in ~/pki/private/ca-key.pem
      • --type rsa --dn "CN=VPN root CA" --outform pem > ~/pki/cacerts/ca-cert.pem

      O sinalizador --lifetime 3650 é usado para garantir que o certificado root da autoridade de certificação seja válido por 10 anos. O certificado root para uma autoridade não muda de maneira típica, uma vez que ele teria que ser redistribuído para todos os servidores e clientes que dependem dele. Sendo assim, 10 anos é um valor de validade padrão seguro.

      É possível alterar o valor de nome diferenciado (DN) para outra coisa se você preferir. O nome comum (campo CN) aqui é apenas o indicador, então ele não precisa corresponder a nada em sua infraestrutura.

      Agora que temos nossa autoridade de certificação root em funcionamento, podemos criar um certificado que o servidor VPN usará.

      Passo 3 — Gerando um certificado para o Servidor VPN

      Agora vamos criar um certificado e chave para o servidor VPN. Este certificado permitirá que o cliente verifique a autenticidade do servidor utilizando o certificado CA que acabamos de gerar.

      Primeiramente, crie uma chave privada para o servidor VPN com o seguinte comando:

      • pki --gen --type rsa --size 4096 --outform pem > ~/pki/private/server-key.pem

      Agora, crie e assine o certificado do servidor VPN com a chave de autoridade de certificação que você criou no passo anterior. Execute o comando a seguir, mas altere o campo Common Name (CN) e o campo Subject Alternate Name (SAN) para o nome DNS do seu servidor VPN ou endereço IP:

      • pki --pub --in ~/pki/private/server-key.pem --type rsa
      • | pki --issue --lifetime 1825
      • --cacert ~/pki/cacerts/ca-cert.pem
      • --cakey ~/pki/private/ca-key.pem
      • --dn "CN=server_domain_or_IP" --san server_domain_or_IP
      • --flag serverAuth --flag ikeIntermediate --outform pem
      • > ~/pki/certs/server-cert.pem

      Nota: se estiver usando um endereço IP em vez de um nome DNS, será necessário especificar várias entradas --san. A linha no bloco de comando anterior onde você especifica o nome diferenciado (--dn ...) precisará ser modificada com a entrada extra, assim como na seguinte linha extraída:

      --dn "CN=IP address --san @IP_address --san IP_address 
      

      A razão pela qual essa entrada extra --san @IP_address é necessária é que alguns clientes irão verificar se o certificado TLS possui tanto uma entrada DNS quanto uma entrada de endereço IP para um servidor ao verificar sua identidade.

      A opção --flag serverAuth é usada para indicar que o certificado será usado explicitamente para a autenticação de servidor, antes de o túnel criptografado ser estabelecido. A opção --flag ikeIntermediate é usada para dar suporte a clientes macOS mais antigos.

      Agora que geramos todos os arquivos TLS/SSL que o StrongSwan necessita, podemos mover os arquivos para seus lugares no diretório /etc/ipsec.d digitando:

      • sudo cp -r ~/pki/* /etc/ipsec.d/

      Neste passo, criamos um par de certificados que será usado para proteger as comunicações entre o cliente e o servidor. Também assinamos os certificados com a chave CA, para que o cliente possa verificar a autenticidade do servidor VPN utilizando o certificado CA. Com todos esses certificados prontos, vamos seguir para a configuração do software.

      Passo 4 — Configurando o StrongSwan

      O StrongSwan tem um arquivo de configuração padrão com alguns exemplos, mas a maior parte da configuração terá que ser feita por nossa conta. Vamos fazer um backup do arquivo para referência antes de começar do zero:

      • sudo mv /etc/ipsec.conf{,.original}

      Crie e abra um novo arquivo de configuração em branco usando seu editor de texto preferido. Aqui, usaremos o nano:

      • sudo nano /etc/ipsec.conf

      Nota: conforme for trabalhando nessa seção para configurar a porção do servidor da sua VPN, você encontrará configurações que se referem a lados left (esquerdo) e right (direito) de uma conexão. Quando se trabalha com VPNs IPSec, o lado esquerdo por convenção refere-se ao sistema local que você está configurando, neste caso o servidor. As diretivas laterais direita nessas configurações se referirão a clientes remotos, como telefones e outros computadores.

      Quando você for configurar clientes mais adiante neste tutorial, os arquivos de configuração do cliente se referirão a si mesmos usando várias diretivas left, e o servidor será referido usando a terminologia right.

      Primeiramente, vamos dizer ao StrongSwan para registrar os status do daemon para correção de erros e permitir conexões duplicadas. Adicione estas linhas ao arquivo:

      /etc/ipsec.conf

      config setup
          charondebug="ike 1, knl 1, cfg 0"
          uniqueids=no
      

      Depois, vamos criar uma seção de configuração para nossa VPN. Também vamos dizer ao StrongSwan para criar os Túneis da VPN com IKEv2 e para carregar automaticamente essa seção de configuração quando for iniciado. Adicione as linhas a seguir ao arquivo:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          auto=add
          compress=no
          type=tunnel
          keyexchange=ikev2
          fragmentation=yes
          forceencaps=yes
      

      Também vamos configurar a detecção de ponto morto para limpar conexões pendentes, caso o cliente se desconecte de maneira inesperada. Adicione estas linhas:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          dpdaction=clear
          dpddelay=300s
          rekey=no
      

      Em seguida, vamos configurar os parâmetros IPSec do lado “esquerdo” do servidor. Cada um dos seguintes parâmetros garante que o servidor esteja configurado para aceitar conexões de clientes e se identificar corretamente. Você irá adicionar cada uma dessas configurações ao arquivo /etc/ipsec.conf assim que estiver familiarizado com o que eles são e por que são usados:

      • left=%any O valor %any garante que o servidor usará a interface de rede onde ele recebe conexões de entrada para posterior comunicação com clientes. Por exemplo, se você estiver conectando um cliente por uma rede privada, o servidor usará o endereço IP privado onde ele recebe tráfego para o resto da conexão.
      • leftid=@server_domain_or_IP Essa opção controla o nome que o servidor apresenta aos clientes. Quando combinada com a próxima opção leftcert, a opção leftid garante que o nome configurado do servidor e o nome diferenciado (DN) que está contido no certificado público correspondam.
      • leftcert=server-cert.pem Essa opção indica o caminho para o certificado público do servidor que você configurou no Passo 3. Sem ele, o servidor não será capaz de autenticar-se com clientes ou terminar de negociar a configuração do IKEv2.
      • leftsendcert=always O valor always (sempre) garante que qualquer cliente que se conecte ao servidor receba sempre uma cópia do certificado público do servidor como parte da configuração de conexão inicial.
      • leftsubnet=0.0.0.0/0 A última opção do lado “esquerdo” que você adicionará informa aos clientes sobre as sub-redes que são alcançáveis por trás do servidor. Neste caso, 0.0.0.0/0 é usado para representar todo o conjunto de endereços IPv4, o que significa que o servidor irá pedir aos clientes para enviar todo o seu tráfego pela VPN por padrão.

      Agora que você está familiarizado com cada uma das opções relevantes do lado “esquerdo”, adicione todas elas ao arquivo desta forma:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          left=%any
          leftid=@server_domain_or_IP
          leftcert=server-cert.pem
          leftsendcert=always
          leftsubnet=0.0.0.0/0
      

      Nota: quando configurar o ID do servidor (leftid), inclua apenas o caractere @ se o seu servidor de VPN for identificado por um nome de domínio:

      /etc/ipsec.conf

          . . .    leftid=@vpn.example.com
          . . .
      

      Se o servidor for identificado pelo seu endereço IP, apenas coloque o endereço IP em:

      /etc/ipsec.conf

          . . .
          leftid=your_server_ip
          . . .
      

      Em seguida, podemos configurar os parâmetros IPSec do lado “direito” do cliente. Cada um dos parâmetros a seguir informa ao servidor como aceitar conexões de clientes, como os clientes devem se autenticar no servidor e os intervalos de endereços IP privados e servidores DNS que os clientes usarão. Adicione cada uma dessas configurações ao arquivo /etc/ipsec.conf assim que estiver familiarizado com o que elas são e por que são usadas:

      • right=%any A opção %any para o lado right da conexão instrui o servidor a aceitar conexões recebidas de qualquer cliente remoto.
      • rightid=%any Essa opção garante que o servidor não irá rejeitar conexões de clientes que fornecem uma identidade antes que o túnel criptografado seja estabelecido.
      • rightauth=eap-mschapv2 Essa opção configura o método de autenticação que os clientes usarão para se autenticar no servidor. O eap-mschapv2 é usado aqui para garantir ampla compatibilidade para suportar clientes como Windows, macOS e dispositivos Android.
      • rightsourceip=10.10.10.0/24 Essa opção instrui o servidor a atribuir endereços IP privados aos clientes a partir da pool de IPs 10.10.10.0/24 especificada.
      • rightdns=8.8.8.8,8.8.4.4 Esses endereços IP são resolvedores de DNS públicos do Google. Eles podem ser alterados para outros resolvedores públicos, resolvedores do servidor VPN ou qualquer outro resolvedor que os clientes consigam acessar.
      • rightsendcert=never Essa opção instrui o servidor que os clientes não precisam enviar por conta própria um certificado para se autenticar.

      Agora que você está familiarizado com as opções do lado “direito” necessárias para a VPN, adicione as seguintes linhas ao /etc/ipsec.conf:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          right=%any
          rightid=%any
          rightauth=eap-mschapv2
          rightsourceip=10.10.10.0/24
          rightdns=8.8.8.8,8.8.4.4
          rightsendcert=never
      

      Agora, vamos dizer ao StrongSwan para pedir ao cliente as credenciais de usuário ao se conectarem:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          eap_identity=%identity
      

      Por fim, adicione as seguintes linhas para dar suporte a clientes Linux, Windows, macOS, iOS e Android. Estas linhas especificam os vários algoritmos de intercâmbio de chave, hash, autenticação e criptografia (comumente conhecidos como Pacotes de codificação) que o StrongSwan permitirá que diferentes clientes usem:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          ike=chacha20poly1305-sha512-curve25519-prfsha512,aes256gcm16-sha384-prfsha384-ecp384,aes256-sha1-modp1024,aes128-sha1-modp1024,3des-sha1-modp1024!
          esp=chacha20poly1305-sha512,aes256gcm16-ecp384,aes256-sha256,aes256-sha1,3des-sha1!
      

      Cada pacote de codificação suportado é separado dos outros por uma vírgula. Por exemplo, chacha20poly1305-sha512-curve25519-prfsha512 é um pacote, e aes256gcm16-sha384-prfsha384-ecp384 é outro. Os pacotes de codificação listados aqui são selecionados para garantir a mais ampla compatibilidade entre os clientes Windows, macOS, iOS, Android e Linux.

      O arquivo de configuração completo deve se parecer com este:

      /etc/ipsec.conf

      config setup
          charondebug="ike 1, knl 1, cfg 0"
          uniqueids=no
      
      conn ikev2-vpn
          auto=add
          compress=no
          type=tunnel
          keyexchange=ikev2
          fragmentation=yes
          forceencaps=yes
          dpdaction=clear
          dpddelay=300s
          rekey=no
          left=%any
          leftid=@server_domain_or_IP
          leftcert=server-cert.pem
          leftsendcert=always
          leftsubnet=0.0.0.0/0
          right=%any
          rightid=%any
          rightauth=eap-mschapv2
          rightsourceip=10.10.10.0/24
          rightdns=8.8.8.8,8.8.4.4
          rightsendcert=never
          eap_identity=%identity
          ike=chacha20poly1305-sha512-curve25519-prfsha512,aes256gcm16-sha384-prfsha384-ecp384,aes256-sha1-modp1024,aes128-sha1-modp1024,3des-sha1-modp1024!
          esp=chacha20poly1305-sha512,aes256gcm16-ecp384,aes256-sha256,aes256-sha1,3des-sha1!
      

      Salve e feche o arquivo assim que verificar se adicionou cada linha corretamente. Se usou o nano, faça isso pressionando as teclas CTRL+X, Y e depois ENTER.

      Agora que configuramos os parâmetros VPN, vamos seguir em frente para criar uma conta que permita que nossos usuários se conectem ao servidor.

      Passo 5 — Configurando a autenticação da VPN

      Nosso servidor VPN agora está configurado para aceitar conexões de clientes, mas ainda não temos nenhuma credencial configurada. Vamos ter que configurar algumas coisas em um arquivo de configuração especial chamado ipsec.secrets:

      • Precisamos dizer ao StrongSwan onde encontrar a chave privada do certificado do nosso servidor, de modo que o servidor consiga autenticar os clientes.
      • Também precisamos configurar uma lista de usuários que serão autorizados a se conectar à VPN.

      Vamos abrir o arquivo secrets para edição:

      • sudo nano /etc/ipsec.secrets

      Primeiramente, vamos dizer ao StrongSwan onde encontrar nossa chave privada:

      /etc/ipsec.secrets

      : RSA "server-key.pem"
      

      Então, vamos definir as credenciais do usuário. Você pode inventar qualquer nome de usuário ou senha que você queira:

      /etc/ipsec.secrets

      your_username : EAP "your_password"
      

      Salve e feche o arquivo. Agora que terminamos de trabalhar com os parâmetros VPN, vamos reiniciar o serviço VPN para que nossas configurações seja aplicada:

      • sudo systemctl restart strongswan-starter

      Agora que o servidor VPN foi configurado completamente com ambas as opções de servidor e credenciais de usuário, é hora de seguir em frente para configurar a parte mais importante: o firewall.

      Passo 6 — Configurando o encaminhamento de IP do Firewall e do Kernel

      Com a configuração do StrongSwan concluída, precisamos configurar o firewall para permitir o tráfego VPN e encaminhá-lo.

      Se você seguiu o tutorial pré-requisito de configuração inicial do servidor, deve ter um firewall UFW habilitado. Se ainda não tiver o UFW configurado, comece adicionando uma regra para permitir conexões SSH através do firewall. Isso é feito para que sua sessão atual não feche quando o UFW for habilitado:

      Em seguida, habilite o firewall digitando:

      Após isso, adicione uma regra para permitir o tráfego UDP nas portas IPSec padrão, 500 e 4500:

      • sudo ufw allow 500,4500/udp

      Em seguida, vamos abrir um dos arquivos de configuração do UFW para adicionar algumas políticas de baixo nível para roteamento e encaminhamento de pacotes IPSec. No entanto, antes que possamos fazer isso, precisamos encontrar qual interface de rede em nosso servidor é usada para o acesso à internet. Encontre essa interface consultando o dispositivo associado à rota padrão:

      Sua interface pública deve vir após a palavra “dev”. Por exemplo, este resultado mostra a interface chamada eth0, que está destacada no exemplo a seguir:

      Output

      default via your_server_ip dev eth0 proto static

      Quando tiver sua interface de rede pública, abra o arquivo /etc/ufw/before.rules no seu editor de texto. As regras nesse arquivo são adicionadas ao firewall antes do resto das regras habituais de entrada e saída. Elas são usadas para configurar a conversão de endereços de rede (NAT) para que o servidor possa encaminhar corretamente as conexões de entrada e saída para clientes e a internet.

      • sudo nano /etc/ufw/before.rules

      Perto do topo do arquivo (antes da linha *filter), adicione o seguinte bloco de configuração. Altere cada instância de eth0 na configuração acima para corresponder ao nome de interface que você encontrou com ip route. As linhas *nat criam regras para que o firewall possa rotear e manipular corretamente o tráfego entre os clientes VPN e a internet. A linha *mangle ajusta o tamanho máximo do segmento de pacotes para evitar possíveis problemas com certos clientes VPN:

      /etc/ufw/before.rules

      *nat
      -A POSTROUTING -s 10.10.10.0/24 -o eth0 -m policy --pol ipsec --dir out -j ACCEPT
      -A POSTROUTING -s 10.10.10.0/24 -o eth0 -j MASQUERADE
      COMMIT
      
      *mangle
      -A FORWARD --match policy --pol ipsec --dir in -s 10.10.10.0/24 -o eth0 -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1536 -j TCPMSS --set-mss 1360
      COMMIT
      
      *filter
      :ufw-before-input - [0:0]
      :ufw-before-output - [0:0]
      :ufw-before-forward - [0:0]
      :ufw-not-local - [0:0]
      . . .
      

      Em seguida, após as linhas de definição *filter e de cadeia, adicione mais um bloco de configuração:

      /etc/ufw/before.rules

      . . .
      *filter
      :ufw-before-input - [0:0]
      :ufw-before-output - [0:0]
      :ufw-before-forward - [0:0]
      :ufw-not-local - [0:0]
      
      -A ufw-before-forward --match policy --pol ipsec --dir in --proto esp -s 10.10.10.0/24 -j ACCEPT
      -A ufw-before-forward --match policy --pol ipsec --dir out --proto esp -d 10.10.10.0/24 -j ACCEPT
      

      Essas linhas dizem ao firewall para encaminhar o tráfego ESP (Encapsulating Security Payload) para que os clientes VPN possam se conectar. O ESP proporciona segurança adicional para nossos pacotes VPN, enquanto eles estiverem passando por redes não confiáveis.

      Quando tiver terminado, salve e feche o arquivo após ter verificado se adicionou cada linha corretamente. Se usou o nano, faça isso pressionando as teclas CTRL+X, Y e depois ENTER.

      Antes de reiniciarmos o firewall, vamos alterar alguns parâmetros do kernel de rede para permitir o roteamento de uma interface para outra. O arquivo que controla essas configurações é chamado /etc/ufw/sysctl.conf. Precisaremos configurar algumas coisas no arquivo.

      Primeiro, o encaminhamento de pacotes IPv4 precisa ser ligado para que o tráfego possa se mover entre a VPN e as interfaces de rede voltadas ao público no servidor. Em seguida, vamos desabilitar a Path MTU Discovery (PMTUD), ou Descoberta da unidade máxima de transmissão do caminho, para evitar problemas de fragmentação de pacotes. Por fim, não vamos aceitar redirecionamentos ICMP nem enviar redirecionamentos ICMP para evitar ataques man-in-the-middle.

      Abra o arquivo de configuração do kernel do UFW usando o nano ou seu editor de texto preferido:

      • sudo nano /etc/ufw/sysctl.conf

      Agora, adicione a definição net/ipv4/ip_forward=1 no final do arquivo para habilitar o encaminhamento de pacotes entre interfaces:

      /etc/ufw/sysctl.conf

      . . .
      net/ipv4/ip_forward=1
      

      Depois disso, bloqueie o envio e recebimento de pacotes de redirecionamento ICMP adicionando as seguintes linhas no final do arquivo:

      /etc/ufw/sysctl.conf

      . . .
      net/ipv4/conf/all/accept_redirects=0
      net/ipv4/conf/all/send_redirects=0
      

      Por fim, desative a descoberta MTU do caminho adicionando esta linha no fim do arquivo:

      /etc/ufw/sysctl.conf

      . . .
      net/ipv4/ip_no_pmtu_disc=1
      

      Salve o arquivo quando terminar. Agora, podemos habilitar todas as nossas alterações desativando e reativando o firewall, já que o UFW aplica essas configurações sempre que ele é reiniciado:

      • sudo ufw disable
      • sudo ufw enable

      Será solicitado que você confirme o processo. Digite Y para habilitar o UFW novamente com as novas configurações.

      Passo 7 — Testando a conexão VPN no Windows, macOS, Ubuntu, iOS e Android

      Agora que você tem tudo configurado, é hora do teste. Primeiro, você precisará copiar o certificado CA que você criou e instalá-lo no(s) seu(s) dispositivo(s) cliente que serão conectados à VPN. A maneira mais simples de fazer isso é fazendo login no seu servidor e gerando o conteúdo do arquivo de certificação:

      • cat /etc/ipsec.d/cacerts/ca-cert.pem

      Você verá um resultado similar a este:

      Output

      -----BEGIN CERTIFICATE----- MIIFNDCCAxygAwIBAgIIHCsidG5mXzgwDQYJKoZIhvcNAQEMBQAwODELMAkGA1UE . . . H2YUdz8XNHrJHvMQKWFpi0rlEcMs+MSXPFWE3Q7UbaZJ/h8wpSldSUbQRUlphExJ dJ4PX+MUJO/vjG1/ie6Kh25xbBAc3qNq8siiJZDwrg6vjEK7eiZ1rA== -----END CERTIFICATE-----

      Copie este resultado para o seu computador, incluindo as linhas -----BEGIN CERTIFICATE----- e -----ENDCERTIFICATE----- e salve-o em um arquivo com um nome reconhecível, como ca-cert.pem. Certifique-se de que o arquivo que você criar tenha a extensão .pem.

      De forma alternativa, utilize o SFTP para transferir o arquivo para seu computador.

      Assim que tiver o arquivo ca-cert.pem baixado no seu computador, você pode configurar a conexão com a VPN.

      Conectando-se com o Windows

      Existem várias maneiras de importar o certificado root e configurar o Windows para se conectar a uma VPN. O primeiro método usa ferramentas gráficas para cada passo. O segundo método usa comandos do PowerShell, que podem ser controlados e modificados para se adequar à configuração de sua VPN.

      Nota: essas instruções foram testadas em instalações do Windows 10 executando as versões 1903 e 1909.

      Configurando o Windows com ferramentas gráficas

      Primeiramente, importe o certificado raiz, seguindo estes passos:

      1. Pressione WINDOWS+R para trazer a janela Executar e digite mmc.exe“**** para iniciar o Console de Gerenciamento do Windows.
      2. Do menu Arquivo, navegue até Adicionar ou Remover Snap-in, selecione Certificados da lista de snap-ins disponíveis, e clique em Adicionar.
      3. Queremos que a VPN funcione com qualquer usuário, logo selecione Conta de Computador e clique em Avançar.
      4. Estamos configurando coisas no computador local, então selecione Computador Local e, depois, clique em Concluir.
      5. Sob o nó Raiz do Console, expanda a entrada Certificados (Computador Local), expanda Autoridades de Certificação de Raíz Confiáveis** e, em seguida, selecione a entrada Certificados: de Certificados Exibição
      6. A partir do menu Ação, selecione Todas as Tarefas e clique Importar para exibir o Assistente de Importação de Certificados. Clique em Avançar para passar da introdução.
      7. Na tela Arquivo a ser importado, pressione o botão Pesquisar. Certifique-se de alterar o tipo de arquivo de “X.509 Certificate (.cer;.crt)” para “Todos os arquivos (. )”, e selecione o arquivo ca-cert.pem que você salvou. Então, clique em Avançar.
      8. Certifique-se de que Armazenagem de Certificados foi configurada em Autoridades Confiáveis para Certificação Raiz, e clique em Avançar.
      9. Clique em Concluir para importar o certificado.

      Então, configure a VPN com estes passos:

      1. Abra o Painel de Controle, navegue até o Centro de Redes e Compartilhamento.
      2. Clique em Configurar uma nova conexão ou rede, depois selecione Conectar a um local de trabalho.
      3. Selecione Usar minha conexão com a Internet (VPN).
      4. Digite os detalhes do servidor VPN. Digite o nome de domínio ou endereço IP do servidor no campo Endereço de internet, depois, preencha o Nome do destino com algo que descreva sua conexão VPN. Então,clique em Feito.

      Configurando o Windows usando o PowerShell

      Para importar o certificado de CA root usando o PowerShell, abra primeiro um prompt PowerShell com privilégios de administrador. Para fazer isso, clique com o botão direito no ícone do menu Start e selecione o Windows PowerShell (Admin). Você também pode abrir um prompt de comando como administrador e digitar powershell.

      Em seguida, importaremos o certificado usando o cmdlet Import-Certificate do PowerShell. No comando a seguir, o primeiro argumento -CertStoreLocation irá garantir que o certificado seja importado no armazenamento Autoridades de Certificação Raiz Confiáveis de modo que todos os programas e usuários consigam verificar o certificado do servidor VPN. O argumento -FilePath deve apontar para a localização onde você copiou o certificado. No exemplo a seguir, o caminho é C:UserssammyDocumentsca-cert.pem. Certifique-se de editar o comando para que corresponda à localização que você usou.

      • Import-Certificate `
      • -CertStoreLocation cert:LocalMachineRoot `
      • -FilePath C:userssammyDocumentsca-cert.pem

      O comando gerará algo parecido com o seguinte:

      Output

      PSParentPath: Microsoft.PowerShell.SecurityCertificate::LocalMachineRoot Thumbprint Subject ---------- ------- DB00813B4087E9367861E8463A60CEA0ADC5F002 CN=VPN root CA

      Agora, para configurar a VPN usando o PowerShell, execute o comando a seguir. Coloque o nome DNS ou endereço IP do seu servidor na linha -ServerAddress. Os diversos sinalizadores garantirão que o Windows seja configurado corretamente com os parâmetros de segurança apropriados que correspondam às opções que você definiu em /etc/ipsec.conf.

      • Add-VpnConnection -Name "VPN Connection" `
      • -ServerAddress "server_domain_or_IP" `
      • -TunnelType "IKEv2" `
      • -AuthenticationMethod "EAP" `
      • -EncryptionLevel "Maximum" `
      • -RememberCredential `

      Se o comando for bem sucedido, não haverá nenhum resultado. Para confirmar que a VPN está configurada corretamente, use o cmdlet Get-VPNConnection:

      • Get-VpnConnection -Name "VPN Connection"

      Você receberá um resultado como o seguinte:

      Output

      Name : VPN Connection ServerAddress : your_server_ip AllUserConnection : False Guid : {B055A1AB-175C-4028-B4A8-D34309A2B20E} TunnelType : Ikev2 AuthenticationMethod : {Eap} EncryptionLevel : Maximum L2tpIPsecAuth : UseWinlogonCredential : False EapConfigXmlStream : #document ConnectionStatus : Disconnected RememberCredential : True SplitTunneling : False DnsSuffix : IdleDisconnectSeconds : 0

      Por padrão, o Windows escolhe algoritmos mais antigos e mais lentos. Execute o cmdlet Set-VpnConnectionIPsecConfiguration para atualizar os parâmetros de criptografia que o Windows usará para a troca de chaves do IKEv2 e para criptografar pacotes:

      • Set-VpnConnectionIPsecConfiguration -Name "VPN Connection" `
      • -AuthenticationTransformConstants GCMAES256 `
      • -CipherTransformConstants GCMAES256 `
      • -DHGroup ECP384 `
      • -IntegrityCheckMethod SHA384 `
      • -PfsGroup ECP384 `
      • -EncryptionMethod GCMAES256

      Nota: se você quiser excluir a conexão VPN e reconfigurá-la com opções diferentes, pode executar o cmdlet Remove-VpnConnection.

      • Remove-VpnConnection -Name "VPN Connection" -Force

      O sinalizador -Force irá ignorar o prompt que pediria que você confirmasse a remoção. Você deve estar desconectado da VPN se for tentar removê-la usando esse comando.

      Conectando-se à VPN

      Depois de ter importado o certificado e configurado a VPN usando qualquer um dos dois métodos, sua nova conexão VPN será visível na lista de redes. Selecione a VPN e clique em Conectar. Você será solicitado a colocar seu nome de usuário e senha. Digite-os, clique em OK e você estará conectado.

      Conectando-se com o macOS

      Siga estes passos para importar o certificado:

      1. Clique duas vezes no arquivo de certificados. Acesso ao Chaveiro irá aparecer com uma janela que diz “Acesso ao Chaveiro está tentando modificar o chaveiro do sistema. Digite sua senha para permitir.”
      2. Digite sua senha, então clique em Modificar o Chaveiro
      3. Clique duas vezes no certificado VPN recém-importado. Isso traz uma pequena janela de propriedades onde você pode especificar os níveis de confiança. Defina Segurança IP (IPSec) para Sempre Confiar e você será solicitado a inserir sua senha novamente. Esta configuração é salva automaticamente após colocar a senha.

      Agora que o certificado foi importado e é confiável, configure a conexão VPN com estes passos:

      1. Vá até as Preferências do Sistema e escolha Rede.
      2. Clique no pequeno botão “mais” no canto inferior esquerdo da lista de redes.
      3. Na notificação que aparece, Defina a Interface como VPN, defina o Tipo** de VPN** como IKEv2 e nomeie a conexão.
      4. No campo Servidor e ID Remoto, digite o nome do domínio ou endereço IP do servidor. Deixe o ID Local em branco.
      5. Clique em Configurações de Autenticação, selecione Nome de usuário, e digite seu nome de usuário e senha que você configurou para seu usuário VPN. Então clique em OK.

      Por fim, clique em Conectar para se conectar à VPN. Agora, você deve estar conectado à VPN.

      Conectando-se com o Ubuntu

      Para se conectar a partir de uma máquina com Ubuntu, você pode configurar e gerenciar o StrongSwan como um serviço ou usar um comando único cada vez que desejar se conectar. São fornecidas instruções para ambos.

      Gerenciando o StrongSwan como um Serviço

      Para gerenciar o StrongSwan como um serviço, você precisará executar os seguintes passos de configuração.

      Primeiro, atualize seu cache de pacotes local usando o apt

      Em seguida, instale o StrongSwan e os plug-ins necessários para a autenticação:

      • sudo apt install strongswan libcharon-extra-plugins

      Agora, você precisará de uma cópia do certificado CA no diretório /etc/ipsec.d/cacerts para que seu cliente possa verificar a identidade do servidor. Execute o comando a seguir para criar uma cópia do arquivo ca-cert.pem nesse local:

      • sudo cp /tmp/ca-cert.pem /etc/ipsec.d/cacerts

      Para garantir que a VPN seja executada apenas sob demanda, use o systemctl para impedir que o StrongSwan seja executado automaticamente:

      • sudo systemctl disable --now strongswan-starter

      Em seguida, configure o nome de usuário e a senha que você usará para se autenticar no servidor VPN. Edite /etc/ipsec.secrets usando o nano ou seu editor preferido:

      • sudo nano /etc/ipsec.conf

      Adicione a linha a seguir, editando os valores de nome de usuário e senha destacados para que correspondam àqueles que você configurou no servidor:

      /etc/ipsec.conf

      your_username : EAP "your_password"
      

      Por fim, edite o arquivo /etc/ipsec.conf para configurar seu cliente de forma que corresponda à configuração do servidor:

      /etc/ipsec.conf

      config setup
      
      conn ikev2-rw
          right=server_domain_or_IP
          # This should match the `leftid` value on your server's configuration
          rightid=server_domain_or_IP
          rightsubnet=0.0.0.0/0
          rightauth=pubkey
          leftsourceip=%config
          leftid=username
          leftauth=eap-mschapv2
          eap_identity=%identity
          auto=start
      

      Para se conectar ao VPN, digite:

      • sudo systemctl start strongswan-starter

      Para se desconectar novamente, digite:

      • sudo systemctl stop strongswan-starter

      Usando o cliente charon-cmd para conexões únicas

      Para gerenciar o StrongSwan como um serviço, você precisará executar os seguintes passos de configuração.

      Primeiro, atualize seu cache de pacotes local usando o apt

      Em seguida, instale o StrongSwan e os plug-ins necessários para a autenticação:

      • sudo apt install strongswan libcharon-extra-plugins

      Agora, você precisará de uma cópia do certificado CA no diretório /etc/ipsec.d/cacerts para que seu cliente possa verificar a identidade do servidor. Execute o comando a seguir para criar uma cópia do arquivo ca-cert.pem nesse local:

      • sudo cp /tmp/ca-cert.pem /etc/ipsec.d/cacerts

      Neste ponto, você pode se conectar ao servidor VPN com o charon-cmd usando o certificado CA do servidor, o endereço IP do servidor VPN e o nome de usuário que você configurou.

      Execute o comando a seguir sempre que quiser se conectar à VPN:

      • sudo charon-cmd --cert ca-cert.pem --host vpn_domain_or_IP --identity your_username

      Quando solicitado, forneça a senha do usuário VPN e você será conectado à VPN. Para desconectar-se, pressione CTRL+C no terminal e espere que a conexão feche.

      Conectando-se com o iOS

      Para configurar a conexão VPN em um dispositivo iOS, siga estes passos:

      1. Envie para si mesmo um e-mail com o certificado root anexado.
      2. Abra o e-mail no seu dispositivo iOS e toque no arquivo do certificado anexado; depois, toque em Instalar e digite a sua senha. Assim que instalar, toque em Feito.
      3. Vá até Configurações, Geral, VPN e toque em Adicionar** Configuração de VPN. Isso irá trazer a tela de configuração de conexão VPN.
      4. Toque em Tipo e selecione IKEv2.
      5. No campo Descrição, escreva um nome curto para a conexão VPN. Isso pode ser o que você quiser.
      6. No campo Servidor e ID Remoto,**** digite o nome do domínio ou endereço IP do servidor. O campo ID Local pode ser deixado em branco.
      7. Digite seu nome de usuário e senha na seção Autenticação e, em seguida toque em**** Feito.
      8. Selecione a conexão VPN que você acabou de criar, toque no botão no alto da página e você estará conectado.

      Conectando-se com o Android

      Siga estes passos para importar o certificado:

      1. Envie um e-mail para si mesmo com o certificado CA anexado. Salve o certificado CA na sua pasta de downloads.
      2. Faça download do StrongSwan VPN client da Play Store.
      3. Abra o aplicativo. Toque no ícone “more” () no canto superior direito e selecione CA certificates.
      4. Toque no ícone “more”(), no canto superior direito novamente. Selecione Importar certificado.
      5. Navegue até o arquivo do certificado CA, em sua pasta de downloads e selecione-o para importá-lo para o aplicativo.

      Agora que o certificado foi importado no aplicativo StrongSwan, você pode configurar a conexão VPN com esses passos:

      1. No aplicativo, clique em ADICIONAR PERFIL VPN, no topo.
      2. Preencha o Servidor com o nome de domínio ou endereço IP público do seu servidor VPN.
      3. Certifique-se de que IKEv2 EAP (Usuário/Senha) está selecionado como o Tipo VPN.
      4. Preencha o Nome de usuário e Senha com as credenciais que você definiu no servidor.
      5. Desmarque Selecionar automaticamente na seção certificado CA e clique em Selecionar o certificado CA.
      6. Toque na aba IMPORTADO, no alto da tela e escolha o CA que você importou (ele será chamado “VPN raiz CA” se você não tiver mudado o “DN” anteriormente).
      7. Se você quiser, preencha o Nome de perfil (opcional) com um nome mais descritivo.

      Quando quiser se conectar à VPN, clique no perfil que você acabou de criar no aplicativo StrongSwan.

      Solucionando problemas de conexão

      Se você não conseguir importar o certificado, certifique-se de que o arquivo tenha a extensão .pem, e não .pem.txt“.

      Se você não conseguir conectar-se à VPN, verifique o nome do servidor ou endereço IP que você usou. O nome de domínio ou endereço IP do servidor deve corresponder ao que você havia configurado como o nome comum (CN) ao criar o certificado. Se eles não corresponderem, a conexão VPN não funcionará. Por exemplo, se for configurar um certificado com o CN de vpn.example.com, você deve usar vpn.example.com ao digitar os detalhes do servidor VPN. Verifique novamente o comando que você usou para gerar o certificado e os valores que você usou ao criar sua conexão VPN.

      Por fim, verifique novamente a configuração da VPN para garantir que o valor leftid tenha sido configurado com o símbolo @ se você estiver usando um nome de domínio:

      /etc/ipsec.conf

          leftid=@vpn.example.com
      

      E, caso esteja usando um endereço IP, certifique-se de que o símbolo @ seja omitido. Além disso, certifique-se de que ao gerar o arquivo server-cert.pem você tenha incluído ambas os sinalizadores --san @IP_address e --san IP_address.

      Conclusão

      Neste tutorial, você construiu um servidor VPN que usa o protocolo IKEv2. Você aprendeu sobre as diretrizes que controlam os lados left e right de uma conexão tanto no servidor quanto nos clientes. Você também configurou um cliente Windows, macOS, iOS, Android ou Linux para se conectar à VPN.

      Para adicionar ou remover usuários, volte para o Passo 5 novamente. Cada linha em /etc/ipsec.secrets é para um usuário. Dessa forma, adicionar,remover usuários ou alterar senhas depende apenas da edição do arquivo.

      Agora, você pode ter certeza de que suas atividades online permanecerão seguras onde quer que você vá e com qualquer dispositivo que use para acessar a internet.



      Source link

      Настройка сервера IKEv2 VPN с StrongSwan в Ubuntu 20.04


      Предыдущая версия данного обучающего руководства была написана Джастином Эллингвудом (Justin Ellingwood) и Намо (Namo)

      Введение

      Виртуальная частная сеть (VPN) позволяет выполнять защищенное шифрование трафика, передаваемого через незащищенные сети, например, в кафе, на конференции или в аэропорту.

      Internet Key Exchange v2 или IKEv2 — это протокол, который позволяет создавать прямые туннели IPSec между сервером и клиентом. IPSec обеспечивает шифрование сетевого трафика в виртуальных частных сетях IKEv2. IKEv2 изначально поддерживается на ряде платформ (OS X 10.11+, iOS 9.1+, Windows 10) без дополнительных приложений и легко решает проблемы с подключением клиентов.

      В этом обучающем руководстве мы настроим сервер IKEv2 VPN с помощью StrongSwan на сервере Ubuntu 20.04. Затем вы узнаете, как подключиться к нему с помощью клиентов Windows, macOS, Ubuntu, iOS и Android.

      Предварительные требования

      Для данного обучающего руководства вам потребуется следующее:

      Шаг 1 — Установка StrongSwan

      Вначале мы установим StrongSwan, демона IPSec с открытым исходным кодом, а затем настроим его как наш сервер VPN. Также мы установим компонент инфраструктуры открытых ключей (PKI), чтобы создать центр сертификации (СА), который будет предоставлять учетные данные для нашей инфраструктуры.

      Начните с обновления кэша локальных пакетов:

      Затем установите программное обеспечение с помощью следующей команды:

      • sudo apt install strongswan strongswan-pki libcharon-extra-plugins libcharon-extauth-plugins

      Дополнительный пакет libcharon-extauth-plugins используется для обеспечения возможности аутентификации различных клиентов для вашего сервера с помощью общего имени пользователя и кодовой фразы.

      После завершения установки перейдем к созданию сертификатов.

      Шаг 2 — Создание центра сертификации

      Для идентификации на клиентских системах серверу IKEv2 требуется сертификат. Для упрощения формирования требуемого сертификата пакет strongswan-pki включает утилиту pki, которая может сгенерировать центр сертификации и сертификаты сервера.

      Для начала создадим несколько каталогов для хранения всех активо, с которыми мы будем работать. Структура каталогов соответствует некоторым каталогам в /etc/ipsec.d, куда мы постепенно переместим все создаваемые элементы:

      • mkdir -p ~/pki/{cacerts,certs,private}

      Затем мы заблокируем разрешения, чтобы другие пользователи не могли видеть наши частные файлы:

      Располагая структурой каталогов для хранения всех элементов, мы можем сгенерировать ключ root. Это будет 4096-битный ключ RSA, который будет использоваться для подписи корневого центра сертификации.

      Запустите следующие команды, чтобы сгенерировать ключ:

      • pki --gen --type rsa --size 4096 --outform pem > ~/pki/private/ca-key.pem

      После этого мы можем переходить к созданию корневого центра сертификации, используя ключ, который мы только что сгенерировали для подписания корневого сертификата:

      • pki --self --ca --lifetime 3650 --in ~/pki/private/ca-key.pem
      • --type rsa --dn "CN=VPN root CA" --outform pem > ~/pki/cacerts/ca-cert.pem

      Флаг --lifetime 3650 используется для обеспечения действительности корневого сертификата центра сертификации на протяжении 10 лет. Корневой сертификат центра обычно не меняется, поскольку его необходимо перераспределять на каждый использующий его сервер и клиент. Исходя из этого, 10 лет — это безопасный срок действия по умолчанию.

      Вы можете изменить значение различимого имени distinguished name (DN) на любое другое имя по своему желанию. Обычное имя (поле CN) здесь используется только как индикатор, поэтому оно не обязательно должно совпадать с чем-либо в вашей инфраструктуре.

      Настроив и запустив корневой центр сертификации, мы можем создать сертификат, который будет использоваться сервером VPN.

      Шаг 3 — Генерирование сертификата для сервера VPN

      Теперь мы создадим сертификат и ключ для сервера VPN. Этот сертификат позволит клиентам проверять подлинность сервера, используя только что сгенерированный нами сертификат CA.

      Вначале создайте закрытый ключ сервера VPN с помощью следующей команды:

      • pki --gen --type rsa --size 4096 --outform pem > ~/pki/private/server-key.pem

      Затем создайте и подпишите сертификат сервера VPN, используя ключ центра сертификации, созданный на предыдущем шаге. Запустите следующую команду, но измените поля Common Name (CN) и Subject Alternate Name (SAN) на имя DNS или IP-адрес вашего сервера VPN:

      • pki --pub --in ~/pki/private/server-key.pem --type rsa
      • | pki --issue --lifetime 1825
      • --cacert ~/pki/cacerts/ca-cert.pem
      • --cakey ~/pki/private/ca-key.pem
      • --dn "CN=server_domain_or_IP" --san server_domain_or_IP
      • --flag serverAuth --flag ikeIntermediate --outform pem
      • > ~/pki/certs/server-cert.pem

      Примечание. Если вы используете IP-адрес вместо имени DNS, вам потребуется указать несколько входов --san. Строка в предыдущем блоке команд, где вы указываете distinguished name (--dn ...), должна быть дополнена еще одной строкой, например следующей:

      --dn "CN=IP address --san @IP_address --san IP_address 
      

      Дополнение --san @IP_address необходимо, так как некоторые клиенты буду проверять наличие в сертификате TLS как записи DNS, так и записи IP-адреса для сервера при проверке его подлинности.

      Опция --flag serverAuth используется для указания того, что сертификат будет использоваться для аутентификации сервера, прежде чем будет установлен зашифрованный туннель. Опция --flag ikeIntermediate используется для поддержки более старых клиентов macOS.

      Теперь мы сгенерировали все файлы TLS/SSL, необходимые StrongSwan, и можем переместить их в каталог /etc/ipsec.d следующим образом:

      • sudo cp -r ~/pki/* /etc/ipsec.d/

      На этом шаге мы создали пару сертификатов, которые будут использоваться для защиты связи между клиентом и сервером. Также мы подписали сертификаты ключом CA, и теперь клиент сможет проверять подлинность сервера VPN, используя сертификат CA. После подготовки всех этих сертификатов мы переходим к настройке программного обеспечения.

      Шаг 4 — Настройка StrongSwan

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

      • sudo mv /etc/ipsec.conf{,.original}

      Создайте и откройте новый пустой файл конфигурации с помощью предпочитаемого текстового редактора. Мы будем использовать nano:

      • sudo nano /etc/ipsec.conf

      Примечание. По мере выполнения данного раздела по конфигурации серверной части VPN вы столкнетесь с настройками, которые относятся к левой и правой сторонам соединения. При работе с VPN IPSec левая сторона, по правилам, обращается к локальной системе, которую вы настраиваете. В данном случае — это сервер. Директивы правой стороны в данных настройках будут обращаться к удаленным клиентам, таким как телефоны или компьютеры.

      Когда вы позже перейдете к настройке клиентов в этом обучающем руководстве, файлы конфигурации клиентов будут обращаться к самим себе, используя различные директивы левой стороны, а к серверу будут обращаться, используя терминологию правой стороны.

      Вначале мы укажем StrongSwan регистрировать состояния демонов для целей отладки и разрешить дублирующиеся соединения. Добавьте в файл следующие строки:

      /etc/ipsec.conf

      config setup
          charondebug="ike 1, knl 1, cfg 0"
          uniqueids=no
      

      Затем мы создадим раздел конфигурации для сервера VPN. Также мы укажем StrongSwan создать туннели IKEv2 VPN и автоматически загружать этот раздел конфигурации при запуске. Добавьте в файл следующие строки:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          auto=add
          compress=no
          type=tunnel
          keyexchange=ikev2
          fragmentation=yes
          forceencaps=yes
      

      Также мы настроем обнаружение отсутствующих узлов, чтобы закрывать неиспользуемые соединения при непредвиденном отключении клиента. Добавьте следующие строки:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          dpdaction=clear
          dpddelay=300s
          rekey=no
      

      Затем мы настроим параметры IPSec «левой» стороны сервера. Каждый из следующих параметров обеспечивает конфигурацию сервера для приема соединений от клиентов и корректной идентификации себя. Вы добавите каждую из этих настроек в файл /etc/ipsec.conf после того, как вы изучите их и поймете, для чего они используются:

      • left=%any Значение %any гарантирует использование сервером сетевого интерфейса при получении входящих соединений для последующей связи с клиентами. Например, если вы подключаете клиента через частную сеть, сервер будет использовать частный IP-адрес, где он получает трафик для остальной части подключения.
      • leftid=@server_domain_or_IP Эта опция контролирует имя, которое сервер показывает клиентам. При совмещении со следующей опцией leftcert, опция leftid обеспечивает совпадение настроенного имени сервера и различимого имени (DN), содержащегося в публичном сертификате.
      • leftcert=server-cert.pem Эта опция — это путь к публичному сертификату для сервера, который вы настроили на шаге 3. Без него сервер не сможет аутентифицировать себя с клиентами или завершить переговоры по настройке IKEv2.
      • leftsendcert=always Значение always гарантирует, что любой клиент, который подключается к серверу, всегда будет получать копию публичного сертификата сервера в рамках настроек первоначального соединения.
      • leftsubnet=0.0.0.0/0 Последняя опция «слева», которую вы добавите, указывает клиентам на подсети, которые доступны за сервером. В этом случае 0.0.0.0/0 используется для представления всего набора адресов IPv4, что означает, что сервер будет указывать клиентам передавать весь свой трафик через VPN по умолчанию.

      Теперь, когда вы ознакомились с каждой из соответствующих опций «слева», добавьте их в файл следующим образом:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          left=%any
          leftid=@server_domain_or_IP
          leftcert=server-cert.pem
          leftsendcert=always
          leftsubnet=0.0.0.0/0
      

      Примечание. При настройке идентификатора сервера (leftid) символ @ нужно указывать только в случае, если ваш сервер VPN будет идентифицироваться по доменному имени:

      /etc/ipsec.conf

          . . .    leftid=@vpn.example.com
          . . .
      

      Если сервер будет идентифицироваться по IP-адресу, просто укажите IP-адрес:

      /etc/ipsec.conf

          . . .
          leftid=your_server_ip
          . . .
      

      Далее мы можем настроить параметры IPSec клиента «справа». Каждый из следующих параметров указывает серверу, как принимать соединения от клиентов, как клиенты должны аутентифицироваться на сервере, а также сообщает диапазоны частных IP-адресов и серверы которые будут использовать клиенты. Добавьте каждую из этих настроек в файл /etc/ipsec.conf после того, как изучите их и поймете, для чего они используются:

      • right=%any Опция %any для стороны соединения right предписывает серверу принимать входящие соединения от удаленных клиентов.
      • rightid=%any Эта опция гарантирует, что сервер не будет отклонять соединения от клиентов, которые предоставляют идентификатор до создания зашифрованного туннеля.
      • rightauth=eap-mschapv2 Эта опция настраивает метод аутентификации, который будут использовать клиенты для аутентификации на сервере. eap-mschapv2 используется здесь для расширения возможностей совместимости и поддержки таких клиентов, как устройства на базе Windows, macOS и Android.
      • rightsourceip=10.10.10.0/24 Эта опция предписывает серверу назначать частные IP-адреса клиентам из указанного пула IP-адресов 10.10.10.0/24.
      • rightdns=8.8.8.8,8.8.4.4 Эти IP-адреса являются публичными интерпретаторами DNS Google. Вместо них можно использовать другие публичные интерпретаторы, интерпретаторы сервера VPN или любые другие, к которым у клиента есть доступ.
      • rightsendcert=never Эта опция сообщает серверу, что клиентам не нужно отправлять сертификат для аутентификации себя.

      Теперь, когда вы ознакомились с необходимыми опциями «справа», добавьте следующие строки в /etc/ipsec.conf:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          right=%any
          rightid=%any
          rightauth=eap-mschapv2
          rightsourceip=10.10.10.0/24
          rightdns=8.8.8.8,8.8.4.4
          rightsendcert=never
      

      Теперь мы укажем StrongSwan запрашивать у клиента учетные данные пользователя при подключении:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          eap_identity=%identity
      

      И наконец, добавьте следующие строки для поддержки клиентов на базе Linux, Windows, macOS, iOS и Android. Эти строки определяют различные алгоритмы обмена ключами, хэширования, аутентификации и шифрования (обычно их называют набор шифров), которые StrongSwan разрешит использовать разным клиентам.

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          ike=chacha20poly1305-sha512-curve25519-prfsha512,aes256gcm16-sha384-prfsha384-ecp384,aes256-sha1-modp1024,aes128-sha1-modp1024,3des-sha1-modp1024!
          esp=chacha20poly1305-sha512,aes256gcm16-ecp384,aes256-sha256,aes256-sha1,3des-sha1!
      

      Каждый поддерживаемый набор шифров отделяется от других запятой. Например, chacha20poly1305-sha512-curve25519-prfsha512 — это один набор, а aes256gcm16-sha384-prfsha384-ecp384 — другой. Перечисленные здесь наборы шифров выбраны для обеспечения самых широких возможностей совместимости с клиентами на базе Windows, macOS, iOS, Android и Linux.

      Полный файл конфигурации должен выглядеть следующим образом:

      /etc/ipsec.conf

      config setup
          charondebug="ike 1, knl 1, cfg 0"
          uniqueids=no
      
      conn ikev2-vpn
          auto=add
          compress=no
          type=tunnel
          keyexchange=ikev2
          fragmentation=yes
          forceencaps=yes
          dpdaction=clear
          dpddelay=300s
          rekey=no
          left=%any
          leftid=@server_domain_or_IP
          leftcert=server-cert.pem
          leftsendcert=always
          leftsubnet=0.0.0.0/0
          right=%any
          rightid=%any
          rightauth=eap-mschapv2
          rightsourceip=10.10.10.0/24
          rightdns=8.8.8.8,8.8.4.4
          rightsendcert=never
          eap_identity=%identity
          ike=chacha20poly1305-sha512-curve25519-prfsha512,aes256gcm16-sha384-prfsha384-ecp384,aes256-sha1-modp1024,aes128-sha1-modp1024,3des-sha1-modp1024!
          esp=chacha20poly1305-sha512,aes256gcm16-ecp384,aes256-sha256,aes256-sha1,3des-sha1!
      

      Сохраните и закройте файл после того, как проверите, что все строки добавлены корректно. Если вы используете nano, нажмите CTRL+X, Y, затем ENTER.

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

      Шаг 5 — Настройка аутентификации VPN

      Теперь наш сервер VPN настроен на принятие подключений клиентов, но мы еще не настроили учетные данные. Нам нужно задать пару настроек в специальном файле конфигурации с именем ipsec.secrets:

      • Нам нужно указать StrongSwan, где можно найти закрытый ключ для нашего сертификата сервера, чтобы сервер мог пройти аутентификацию на стороне клиента.
      • Также нам потребуется список пользователей, которым будет разрешено подключаться к VPN.

      Откроем для редактирования файл secrets

      • sudo nano /etc/ipsec.secrets

      Вначале мы укажем StrongSwan, где можно найти закрытый ключ:

      /etc/ipsec.secrets

      : RSA "server-key.pem"
      

      Затем мы зададим учетные данные пользователя. Вы можете создать любую комбинацию имени пользователя и пароля:

      /etc/ipsec.secrets

      your_username : EAP "your_password"
      

      Сохраните и закройте файл. Мы завершили настройку параметров VPN и теперь можем перезапустить службу VPN, чтобы применить новую конфигурацию:

      • sudo systemctl restart strongswan-starter

      Мы полностью настроили параметры сервера и учетные данные пользователя на сервере VPN и теперь можем перейти к самой важной части: настройке брандмауэра.

      Шаг 6 — Настройка брандмауэра и переадресации IP ядра

      После завершения настройки StrongSwan нам нужно настроить брандмауэр, чтобы разрешить прохождение и перенаправление трафика VPN.

      Если вы следовали указаниям модуля по начальной настройке сервера, у вас должен быть включен брандмауэр UFW. Если вы еще не настроили UFW, вам следует начать с добавления правила, разрешающего соединения SSH через брандмауэр, чтобы ваш текущий сеанс не был прерван при активации UFW:

      Затем активируйте брандмауэр с помощью следующей команды:

      Теперь добавьте правило, которое будет разрешать трафик UDP на стандартных портах IPSec 500 и 4500:

      • sudo ufw allow 500,4500/udp

      Затем мы откроем один из файлов конфигурации UFW, чтобы добавить несколько политик нижнего уровня для маршрутизации и перенаправления пакетов IPSec. Но прежде чем мы сможем сделать это, нам нужно определить, какой сетевой интерфейс на нашем сервере используется для доступа в Интернет. Определите этот интерфейс с помощью запроса устройства, связанного с маршрутом по умолчанию:

      Ваш публичный интерфейс должен содержать слово «dev». Например, в этом результате показан интерфейс с именем eth0, который выделен ниже:

      Output

      default via your_server_ip dev eth0 proto static

      Определив интерфейс публичной сети, откройте файл /etc/ufw/before.rules в своем текстовом редакторе: Правила из этого файла добавляются в брандмауэр перед остальными правилами ввода и вывода. Они используются для настройки перевода сетевых адресов (NAT), чтобы сервер мог корректно настраивать соединения между клиентами и сетью Интернет.

      • sudo nano /etc/ufw/before.rules

      Добавьте в верхнюю часть файла (перед строкой *filter) следующий блок конфигурации: Измените каждый экземпляр eth0 в конфигурации выше для соответствия имени интерфейса, которое вы определили с помощью ip route. Строки *nat создают правила, благодаря которым брандмауэр может обеспечивать маршрутизацию и управление трафиком между клиентами VPN и интернетом. Строка *mangle позволяет настроить максимальный размер сегмента пакета, чтобы предотвратить возможные проблемы с некоторыми клиентами VPN:

      /etc/ufw/before.rules

      *nat
      -A POSTROUTING -s 10.10.10.0/24 -o eth0 -m policy --pol ipsec --dir out -j ACCEPT
      -A POSTROUTING -s 10.10.10.0/24 -o eth0 -j MASQUERADE
      COMMIT
      
      *mangle
      -A FORWARD --match policy --pol ipsec --dir in -s 10.10.10.0/24 -o eth0 -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1536 -j TCPMSS --set-mss 1360
      COMMIT
      
      *filter
      :ufw-before-input - [0:0]
      :ufw-before-output - [0:0]
      :ufw-before-forward - [0:0]
      :ufw-not-local - [0:0]
      . . .
      

      После строки *filter и строк определения цепочки нужно добавить еще один блок конфигурации:

      /etc/ufw/before.rules

      . . .
      *filter
      :ufw-before-input - [0:0]
      :ufw-before-output - [0:0]
      :ufw-before-forward - [0:0]
      :ufw-not-local - [0:0]
      
      -A ufw-before-forward --match policy --pol ipsec --dir in --proto esp -s 10.10.10.0/24 -j ACCEPT
      -A ufw-before-forward --match policy --pol ipsec --dir out --proto esp -d 10.10.10.0/24 -j ACCEPT
      

      Эти строки указывают брандмауэру перенаправлять трафик ESP (защищенная инкапсуляция полезной нагрузки), чтобы дать клиентам VPN возможность подключения. ESP обеспечивает дополнительную защиту пакетов VPN, когда они проходят через ненадежные сети.

      Сохраните и закройте файл после того, как проверите, что все строки добавлены корректно. Если вы используете nano, нажмите CTRL+X, Y, затем ENTER.

      Прежде чем перезапустить брандмауэр, нам нужно изменить некоторые параметры ядра сети, чтобы разрешить маршрутизацию с одного интерфейса на другой. Файл, который контролирует эти настройки, называется /etc/ufw/sysctl.conf. Нам потребуется настроить в файле несколько вещей.

      Для начала необходимо активировать перенаправление пакетов IPv4, чтобы трафик мог перемещаться между VPN и публичными сетями на сервере. Далее мы отключим обнаружение путей MTU, чтобы предотвратить проблемы с фрагментацией пакетов. И наконец, мы запретим перенаправление ICMP и отправку перенаправлений ICMP, чтобы предотвратить атаки через посредников.

      Откройте файл конфигурации параметров ядра UFW, используя nano или предпочитаемый текстовый редактор:

      • sudo nano /etc/ufw/sysctl.conf

      Теперь добавьте следующую настройку net/ipv4/ip_forward=1 в конце файла, чтобы активировать перенаправление пакетов между интерфейсами:

      /etc/ufw/sysctl.conf

      . . .
      net/ipv4/ip_forward=1
      

      Следующий блок, отправляющий и принимающий ICMP , перенаправляет пакеты путем добавления следующих строк в конец файла:

      /etc/ufw/sysctl.conf

      . . .
      net/ipv4/conf/all/accept_redirects=0
      net/ipv4/conf/all/send_redirects=0
      

      И наконец, отключите обнаружение путей MTU, добавив следующую строку в конец файла:

      /etc/ufw/sysctl.conf

      . . .
      net/ipv4/ip_no_pmtu_disc=1
      

      Завершив изменения, сохраните файл. Теперь мы можем активировать все изменения путем отключения и повторного подключения брандмауэра, поскольку UFW применяет эти настройки во время каждой перезагрузки.

      • sudo ufw disable
      • sudo ufw enable

      Вам будет предложено подтвердить процесс. Введите Y, чтобы активировать UFW с новыми настройками.

      Шаг 7 — Тестирование подключения VPN на Windows, macOS, Ubuntu, iOS и Android

      Мы завершили подготовку, и пришло время для тестирования. Вначале нужно скопировать созданный вами сертификат CA и установить его на клиентские устройства, которые будут подключаться к VPN. Для этого удобнее всего выполнить вход на ваш сервер и вывести содержимое файла сертификата:

      • cat /etc/ipsec.d/cacerts/ca-cert.pem

      Вывод будет выглядеть следующим образом:

      Output

      -----BEGIN CERTIFICATE----- MIIFNDCCAxygAwIBAgIIHCsidG5mXzgwDQYJKoZIhvcNAQEMBQAwODELMAkGA1UE . . . H2YUdz8XNHrJHvMQKWFpi0rlEcMs+MSXPFWE3Q7UbaZJ/h8wpSldSUbQRUlphExJ dJ4PX+MUJO/vjG1/ie6Kh25xbBAc3qNq8siiJZDwrg6vjEK7eiZ1rA== -----END CERTIFICATE-----

      Скопируйте эти данные на свой компьютер, включая строки -----BEGIN CERTIFICATE----- и -----END CERTIFICATE-----, и сохраните их в файл с понятным именем, например, ca-cert.pem. Созданный файл должен иметь расширение .pem.

      Также вы можете использовать SFTP, чтобы перенести файл на свой компьютер.

      Когда файл ca-cert.pem будет загружен на ваш компьютер, вы можете настроить подключение к VPN.

      Подключение из Windows

      Существует множество способов импорта корневого сертификата и настройки Windows для подключения к VPN. Первый метод использует графические инструменты для каждого шага. Второй метод использует команды PowerShell, которые могут выполняться с помощью скриптов и меняться в зависимости от конфигурации VPN.

      Примечание. Эти инструкции протестированы на установках Windows 10, использующих версии 1903 и 1909.

      Настройка Windows с помощью графических инструментов

      Вначале импортировать сертификат root, выполнив следующие шаги:

      1. Нажмите WINDOWS+R, чтобы открыть диалоговое окно Выполнить и введите mmc.exe, чтобы открыть консоль управления Windows.
      2. Из меню Файл перейдите в раздел Добавить или удалить оснастку, выберите Сертификаты из списка доступных оснасток и нажмите Добавить.
      3. Чтобы разрешить VPN работать для любых пользователей, выберите Учетная запись компьютера и нажмите Далее.
      4. Поскольку мы выполняем настройку на локальном компьютере, выберите пункт Локальный компьютер и нажмите Готово.
      5. Под узлом Корень консоли откройте запись Сертификаты (локальный компьютер), раскройте Доверенные корневые центры сертификации и выберите запись Сертификаты: Просмотр сертификатов

      6. В меню Действие выберите пункт Все задачи и нажмите Импорт, чтобы открыть мастер импорта сертификатов. Нажмите Далее, чтобы пролистать вводное окно.

      7. На экране Импортируемый файл нажмите кнопку Обзор, убедитесь, что вы изменили тип файла с “X.509 Certificate (.cer;.crt)” на “All Files (.) и выберите сохраненный ранее файл ca-cert.pem. Затем нажмите Далее.

      8. Убедитесь, что Хранилище сертификатов имеет значение Доверенные корневые центры сертификации и нажмите Далее.

      9. Нажмите Готово, чтобы импортировать сертификат.

      Затем выполните следующие шаги по настройке VPN:

      1. Откройте Панель управления и перейдите в Центр управления сетями и общим доступом.
      2. Нажмите Создание и настройка нового подключения или сети и выберите пункт Подключение к рабочем месту.
      3. Выберите пункт Использовать мое подключение к Интернету (VPN).
      4. Введите данные сервера VPN. Введите доменное имя сервера или IP-адрес в поле Адрес в Интернете, затем введите в поле Имя пункта назначения описание своего соединения VPN. Затем нажмите Готово.

      Настройка Windows с помощью PowerShell

      Для импорта корневого сертификата СА с помощью PowerShell сначала откройте командную строку PowerShell с правами администратора. Для этого нажмите правой кнопкой мыши значок Пуск и выберите Windows PowerShell (Admin). Также вы можете открыть командную строку как администратор и ввести powershell.

      Затем мы импортируем сертификат, используя командлет PowerShell Import-Certificate. В следующей команде первый аргумент -CertStoreLocation гарантирует, что сертификат импортируется в хранилище доверенных корневых центров сертификации компьютера, чтобы все программы и пользователи могли проверить сертификат сервера VPN. Аргумент -FilePath должен указать расположение, куда вы скопировали сертификат. В следующем примере путь — это C:UserssammyDocumentsca-cert.pem. Убедитесь, что вы отредактировали команду в соответствии с используемым расположением.

      • Import-Certificate `
      • -CertStoreLocation cert:LocalMachineRoot `
      • -FilePath C:userssammyDocumentsca-cert.pem

      Команда выведет примерно следующее:

      Output

      PSParentPath: Microsoft.PowerShell.SecurityCertificate::LocalMachineRoot Thumbprint Subject ---------- ------- DB00813B4087E9367861E8463A60CEA0ADC5F002 CN=VPN root CA

      Теперь для настройки VPN с помощью PowerShell запустите следующую команду. Подставьте имя DNS или IP-адрес вашего сервера в строку -ServerAddress. Различные флаги обеспечат корректную настройку Windows с необходимыми параметрами безопасности, которые соответствуют опциям, заданным в /etc/ipsec.conf.

      • Add-VpnConnection -Name "VPN Connection" `
      • -ServerAddress "server_domain_or_IP" `
      • -TunnelType "IKEv2" `
      • -AuthenticationMethod "EAP" `
      • -EncryptionLevel "Maximum" `
      • -RememberCredential `

      Если команда выполнена успешно, вы не увидите никакого вывода. Чтобы убедиться, что VPN настроен корректно, используйте командлет Get-VPNConnection:

      • Get-VpnConnection -Name "VPN Connection"

      Вывод будет выглядеть следующим образом:

      Output

      Name : VPN Connection ServerAddress : your_server_ip AllUserConnection : False Guid : {B055A1AB-175C-4028-B4A8-D34309A2B20E} TunnelType : Ikev2 AuthenticationMethod : {Eap} EncryptionLevel : Maximum L2tpIPsecAuth : UseWinlogonCredential : False EapConfigXmlStream : #document ConnectionStatus : Disconnected RememberCredential : True SplitTunneling : False DnsSuffix : IdleDisconnectSeconds : 0

      По умолчанию Windows выбирает более старые и медленные алгоритмы. Запустите командлет Set-VpnConnectionIPsecConfiguration для обновления параметров шифрования, которые будет использовать Windows для обмена ключами IKEv2, а также чтобы провести шифрование пакетов:

      • Set-VpnConnectionIPsecConfiguration -Name "VPN Connection" `
      • -AuthenticationTransformConstants GCMAES256 `
      • -CipherTransformConstants GCMAES256 `
      • -DHGroup ECP384 `
      • -IntegrityCheckMethod SHA384 `
      • -PfsGroup ECP384 `
      • -EncryptionMethod GCMAES256

      Примечание. Если вы хотите удалить соединение VPN и перенастроить его с другими опциями, вы можете запустить командлет Remove-VpnConnection.

      • Remove-VpnConnection -Name "VPN Connection" -Force

      С помощью флага -Force можно пропустить предложение подтвердить удаление. Вы должны быть отключены от VPN, если хотите удалить его с помощью данной команды.

      Подключение к VPN

      После того, как вы импортировали сертификат и настроили VPN любым методом, ваше новое подключение к VPN будет отображаться в списке сетей. Выберите VPN и нажмите Подключиться. Вам будет предложено ввести свои имя пользователя и пароль. Введите эти данные, нажмите OK, и подключение будет установлено.

      Подключение из macOS

      Выполните следующие шаги по импорту сертификата:

      1. Дважды щелкните файл сертификата. Откроется экран «Keychain Access» с диалоговым окном, где будет указано: «Keychain Access is trying to modify the system keychain. Enter your password to allow this».
      2. Введите свой пароль и нажмите Modify Keychain
      3. Дважды щелкните импортированный сертификат VPN. После этого откроется небольшое окно свойств, где вы сможете указать уровни доверия. Укажите для параметра IP Security (IPSec) значение Always Trust (всегда доверять), после чего вам нужно будет снова ввести пароль. Настройка будет сохранена автоматически после ввода пароля.

      После импорта и подтверждения надежности сертификата настройте подключение к VPN, выполнив следующие шаги:

      1. Откройте раздел System Preferences (настройки системы) и выберите пункт Network (сеть).
      2. Нажмите небольшую кнопку «плюс» в нижнем левом углу списка сетей.
      3. В открывшемся всплывающем окне установите для параметра Interface (интерфейс) значение VPN, установите для параметра VPN Type (тип VPN) значение IKEv2 и присвойте имя соединению.
      4. В поле Server (сервер) и Remote ID (удаленный идентификатор) введите доменное имя или IP-адрес сервера. Оставьте поле Local ID (локальный идентификатор) пустым.
      5. Нажмите Authentication Settings (настройки аутентификации), выберите пункт Username (имя пользователя) и введите имя пользователя и пароль, которые вы настроили для своего пользователя VPN. Затем нажмите OK.

      Наконец, нажмите кнопку Connect (подключение) для подключения к VPN. Теперь вы должны быть подключены к VPN.

      Подключение из Ubuntu

      Чтобы подключиться с компьютера под управлением Ubuntu, вы должны настроить и управлять StrongSwan как службой или использовать разовую команду при каждой попытке подключения. Далее приводятся инструкции для обоих случаев.

      Управление StrongSwan как службой

      Чтобы управлять StrongSwan как службой, вам нужно выполнить следующие шаги по настройке.

      Сначала обновите свой локальный кэш пакетов с помощью apt

      Затем установите StrongSwan и необходимые плагины для аутентификации:

      • sudo apt install strongswan libcharon-extra-plugins

      Теперь вам потребуется копия сертификата СА в каталоге /etc/ipsec.d/cacerts, чтобы ваш клиент мог проверить подлинность сервера. Запустите следующую команду, чтобы скопировать файл ca-cert.pem в каталог:

      • sudo cp /tmp/ca-cert.pem /etc/ipsec.d/cacerts

      Чтобы убедиться, что VPN работает только по запросу, используйте systemctl для автоматического отключения StrongSwan:

      • sudo systemctl disable --now strongswan-starter

      Затем настройте имя пользователя и пароль, которые вы будете использовать для аутентификации на сервере VPN. Отредактируйте /etc/ipsec.secrets с помощью nano или любого предпочитаемого редактора:

      • sudo nano /etc/ipsec.conf

      Добавьте следующую строку, редактируя выделенные значения имени пользователя и пароля, чтобы они соответствовали настроенным на сервере:

      /etc/ipsec.conf

      your_username : EAP "your_password"
      

      А теперь отредактируйте файл /etc/ipsec.conf для настройки вашего клиента в соответствии с конфигурацией сервера:

      /etc/ipsec.conf

      config setup
      
      conn ikev2-rw
          right=server_domain_or_IP
          # This should match the `leftid` value on your server's configuration
          rightid=server_domain_or_IP
          rightsubnet=0.0.0.0/0
          rightauth=pubkey
          leftsourceip=%config
          leftid=username
          leftauth=eap-mschapv2
          eap_identity=%identity
          auto=start
      

      Чтобы подключиться к VPN, введите:

      • sudo systemctl start strongswan-starter

      Чтобы снова отключиться, введите:

      • sudo systemctl stop strongswan-starter

      Использование клиента charon-cmd для разовых подключений

      Чтобы управлять StrongSwan как службой, вам нужно выполнить следующие шаги по настройке.

      Сначала обновите свой локальный кэш пакетов с помощью apt

      Затем установите StrongSwan и необходимые плагины для аутентификации:

      • sudo apt install strongswan libcharon-extra-plugins

      Теперь вам потребуется копия сертификата СА в каталоге /etc/ipsec.d/cacerts, чтобы ваш клиент мог проверить подлинность сервера. Запустите следующую команду, чтобы скопировать файл ca-cert.pem в каталог:

      • sudo cp /tmp/ca-cert.pem /etc/ipsec.d/cacerts

      На этом этапе вы можете подключиться к серверу VPN с помощью charon-cmd, используя сертификат СА сервера, IP-адрес сервера VPN и настроенное имя пользователя.

      Запустите следующую команду для подключения к VPN в любое время:

      • sudo charon-cmd --cert ca-cert.pem --host vpn_domain_or_IP --identity your_username

      При запросе укажите пароль пользователя VPN. После этого вы подключитесь к VPN. Чтобы отключиться, нажмите CTRL+C в терминале и дождитесь, пока соединение не будет закрыто.

      Подключение из iOS

      Чтобы настроить соединение VPN на устройстве iOS, выполните следующие действия:

      1. Отправьте себе электронное письмо с прикрепленным корневым сертификатом.
      2. Откройте электронное письмо на устройстве iOS, нажмите на вложенный файл сертификата, затем нажмите Установить и введите код доступа. После установки нажмите Готово.
      3. Откройте Настройки, Общие, VPN и нажмите Добавить конфигурацию VPN. После этого откроется экран конфигурации подключения VPN.
      4. Нажмите Тип и выберите IKEv2.
      5. В поле Описание введите короткое имя подключения VPN. Вы можете выбрать все, что угодно.
      6. В поле Server (сервер) и Remote ID (удаленный идентификатор) введите доменное имя или IP-адрес сервера. Поле Local ID (локальный идентификатор) нельзя оставлять пустым.
      7. Введите имя пользователя и пароль в разделе Аутентификация, а затем нажмите Готово.
      8. Выберите соединение VPN, которое вы только что создали, нажмите переключатель вверху страницы, и подключение будет установлено.

      Подключение из Android

      Выполните следующие шаги по импорту сертификата:

      1. Отправьте себе электронное письмо с прикрепленным сертификатом CA. Сохраните сертификат CA в папку «Загрузки».
      2. Загрузите клиент StrongSwan VPN из магазина Play Store.
      3. Откройте приложение. Нажмите значок «подробнее» () в правом верхнем углу и выберите Сертификаты СА.
      4. Снова нажмите значок «подробнее» в правом верхнем углу. Выберите пункт Импорт сертификата.
      5. Найдите файл сертификата CA в папке «Загрузки» и выберите его для импорта в приложение.

      Теперь сертификат импортирован в приложение StrongSwan, и вы можете настроить соединение VPN следующим образом:

      1. В приложении нажмите ADD VPN PROFILE (добавить профиль VPN) сверху.
      2. Введите в поле Server (сервер) доменное имя или публичный IP-адрес вашего сервера VPN.
      3. Обязательно выберите тип VPN: IKEv2 EAP (Username/Password).
      4. Введите поля Username (имя пользователя) и Password (пароль) учетные данные, определенные на сервере.
      5. Уберите флажок Select automatically (выбирать автоматически) в разделе CA certificate (сертификат CA) и нажмите Select CA certificate (выбрать сертификат CA).
      6. Откройте вкладку IMPORTED (импортированные) вверху экрана и выберите импортированный CA (он будет иметь имя «VPN root CA», если вы до этого не изменяли значение «DN»).
      7. Если хотите, можете ввести в поле Profile name (optional) (имя профиля, необязательно) более понятное имя.

      Когда вы захотите подключится к VPN, нажмите на профиль, созданный в приложении StrongSwan.

      Диагностика и устранение неисправностей подключения

      Если вы не сможете импортировать сертификат, убедитесь, что файл имеет расширение .pem, а не .pem.txt.

      Если вы не можете подключиться к VPN, проверьте используемые имя сервера и IP-адрес. Доменное имя или IP-адрес сервера должны соответствовать настроенным как общее имя (CN) при создании сертификата. Если они не совпадают, соединение VPN не будет работать. Например, если вы настроили сертификат с CN vpn.example.com, вы должны использовать vpn.example.com при вводе данных сервера VPN. Еще раз проверьте команду, которую вы использовали для генерирования сертификата и значения, которые использовали при создании соединения VPN.

      Наконец, проверьте конфигурацию VPN и убедитесь, что значение leftid настроено с символом @, если вы используете доменное имя:

      /etc/ipsec.conf

          leftid=@vpn.example.com
      

      Если вы используете IP-адрес, убедитесь, что символ @ опущен. Также убедитесь, что при генерировании файла server-cert.pem вы включили флаги --san @IP_address и --san IP_address.

      Заключение

      В этом обучающем модуле вы создали сервер VPN, использующий протокол IKEv2. Вы узнали о директивах, которые контролируют левую и правую стороны подключения как на сервере, так и на клиентах. Также вы настроили клиент Windows, macOS, iOS, Android или Linux для подключения к VPN.

      Чтобы добавить или удалить пользователей, снова перейдите на Шаг 5. Каждая строка в /etc/ipsec.secrets предназначена для одного пользователя, поэтому добавление или удаление пользователей или изменение паролей требует редактирования файла.

      Теперь вы можете быть уверены, что ваша деятельность онлайн будет защищена, куда бы вы ни зашли, независимо от устройства, которое вы используете для входа в Интернет.



      Source link

      How to Set Up an IKEv2 VPN Server with StrongSwan on Ubuntu 20.04


      Not using Ubuntu 20.04?


      Choose a different version or distribution.

      A previous version of this tutorial was written by Justin Ellingwood and Namo

      Introduction

      A virtual private network, or VPN, allows you to securely encrypt traffic as it travels through untrusted networks, such as those at the coffee shop, a conference, or an airport.

      Internet Key Exchange v2, or IKEv2, is a protocol that allows for direct IPSec tunneling between the server and client. In IKEv2 VPN implementations, IPSec provides encryption for the network traffic. IKEv2 is natively supported on some platforms (OS X 10.11+, iOS 9.1+, and Windows 10) with no additional applications necessary, and it handles client hiccups quite smoothly.

      In this tutorial, you’ll set up an IKEv2 VPN server using StrongSwan on an Ubuntu 20.04 server. You’ll then learn how to connect to it with Windows, macOS, Ubuntu, iOS, and Android clients.

      Prerequisites

      To complete this tutorial, you will need:

      Step 1 — Installing StrongSwan

      First, we’ll install StrongSwan, an open-source IPSec daemon which we’ll configure as our VPN server. We’ll also install the public key infrastructure (PKI) component so that we can create a Certificate Authority (CA) to provide credentials for our infrastructure.

      Start by updating the local package cache:

      Then install the software by typing:

      • sudo apt install strongswan strongswan-pki libcharon-extra-plugins

      The additional libcharon-extra-plugins package is used to ensure that various clients can authenticate to your server using a shared username and passphrase.

      Now that everything’s installed, let’s move on to creating our certificates.

      Step 2 — Creating a Certificate Authority

      An IKEv2 server requires a certificate to identify itself to clients. To help create the required certificate, the strongswan-pki package comes with a utility called pki to generate a Certificate Authority and server certificates.

      To begin, let’s create a few directories to store all the assets we’ll be working on. The directory structure matches some of the directories in /etc/ipsec.d, where we will eventually move all of the items we create:

      • mkdir -p ~/pki/{cacerts,certs,private}

      Then lock down the permissions so that our private files can’t be seen by other users:

      Now that we have a directory structure to store everything, we can generate a root key. This will be a 4096-bit RSA key that will be used to sign our root certificate authority.

      Execute these commands to generate the key:

      • pki --gen --type rsa --size 4096 --outform pem > ~/pki/private/ca-key.pem

      Following that we can move on to creating our root certificate authority, using the key that we just generated to sign the root certificate:

      • pki --self --ca --lifetime 3650 --in ~/pki/private/ca-key.pem
      • --type rsa --dn "CN=VPN root CA" --outform pem > ~/pki/cacerts/ca-cert.pem

      The --lifetime 3650 flag is used to ensure that the certificate authority’s root certificate will be valid for 10 years. The root certificate for an authority does not change typically, since it would have to be redistributed to every server and client that rely on it, so 10 years is a safe default expiry value.

      You can change the distinguished name (DN) value to something else if you would like. The common name (CN field) here is just the indicator, so it doesn’t have to match anything in your infrastructure.

      Now that we’ve got our root certificate authority up and running, we can create a certificate that the VPN server will use.

      Step 3 — Generating a Certificate for the VPN Server

      We’ll now create a certificate and key for the VPN server. This certificate will allow the client to verify the server’s authenticity using the CA certificate we just generated.

      First, create a private key for the VPN server with the following command:

      • pki --gen --type rsa --size 4096 --outform pem > ~/pki/private/server-key.pem

      Now, create and sign the VPN server certificate with the certificate authority’s key you created in the previous step. Execute the following command, but change the Common Name (CN) and the Subject Alternate Name (SAN) field to your VPN server’s DNS name or IP address:

      • pki --pub --in ~/pki/private/server-key.pem --type rsa
      • | pki --issue --lifetime 1825
      • --cacert ~/pki/cacerts/ca-cert.pem
      • --cakey ~/pki/private/ca-key.pem
      • --dn "CN=server_domain_or_IP" --san server_domain_or_IP
      • --flag serverAuth --flag ikeIntermediate --outform pem
      • > ~/pki/certs/server-cert.pem

      Note: If you are using an IP address instead of a DNS name, you will need to specify multiple --san entries. The line in the previous command block where you specify the distinguished name (--dn ...) will need to be modified with the extra entry like the following excerpted line:

      --dn "CN=IP address --san @IP_address --san IP_address 
      

      The reason for this extra --san @IP_address entry is that some clients will check whether the TLS certificate has both an DNS entry and an IP Address entry for a server when they verify its identity.

      The --flag serverAuth option is used to indicate that the certificate will be used explicitly for server authentication, before the encrypted tunnel is established. The --flag ikeIntermediate option is used to support older macOS clients.

      Now that we’ve generated all of the TLS/SSL files StrongSwan needs, we can move the files into place in the /etc/ipsec.d directory by typing:

      • sudo cp -r ~/pki/* /etc/ipsec.d/

      In this step, we’ve created a certificate pair that will be used to secure communications between the client and the server. We’ve also signed the certificates with the CA key, so the client will be able to verify the authenticity of the VPN server using the CA certificate. With all of these certificates ready, we’ll move on to configuring the software.

      Step 4 — Configuring StrongSwan

      StrongSwan has a default configuration file with some examples, but we will have to do most of the configuration ourselves. Let’s back up the file for reference before starting from scratch:

      • sudo mv /etc/ipsec.conf{,.original}

      Create and open a new blank configuration file using your preferred text editor. Here, we’ll use nano:

      • sudo nano /etc/ipsec.conf

      Note: As you work through this section to configure the server portion of your VPN, you will encounter settings that refer to left and right sides of a connection. When working with IPSec VPNs, the left side by convention refers to the local system that you are configuring, in this case the server. The right side directives in these settings will refer to remote clients, like phones and other computers.

      When you move on to configuring clients later in this tutorial, the client configuration files will refer to themselves using various left directives, and the server will be referred to using right side terminology.

      First, we’ll tell StrongSwan to log daemon statuses for debugging and allow duplicate connections. Add these lines to the file:

      /etc/ipsec.conf

      config setup
          charondebug="ike 1, knl 1, cfg 0"
          uniqueids=no
      

      Then, we’ll create a configuration section for our VPN. We’ll also tell StrongSwan to create IKEv2 VPN Tunnels and to automatically load this configuration section when it starts up. Append the following lines to the file:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          auto=add
          compress=no
          type=tunnel
          keyexchange=ikev2
          fragmentation=yes
          forceencaps=yes
      

      We’ll also configure dead-peer detection to clear any “dangling” connections in case the client unexpectedly disconnects. Add these lines:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          dpdaction=clear
          dpddelay=300s
          rekey=no
      

      Next, we’ll configure the server’s “left” side IPSec parameters. Each of the following parameters ensures that the server is configured to accept connections from clients and to identify itself correctly. You’ll add each of these settings to the /etc/ipsec.conf file once you are familiar with what they are and why they are used:

      • left=%any The %any value ensures that the server will use the network interface where it receives incoming connections for subsequent communication with clients. For example, if you are connecting a client over a private network, the server will use the private IP address where it receives traffic for the rest of the connection.
      • leftid=@server_domain_or_IP This option controls the name that the server presents to clients. When combined with the next option leftcert, the leftid option ensures that the server’s configured name and the Distinguished Name (DN) that is contained in the public certificate match.
      • leftcert=server-cert.pem This option is the path to the public certificate for the server that you configured in Step 3. Without it, the server will not be able to authenticate itself with clients, or finish negotiating the IKEv2 set up.
      • leftsendcert=always The always value ensures that any client that connects to the server will always receive a copy of the server’s public certificate as part of the initial connection set up.
      • leftsubnet=0.0.0.0/0 The last “left” side option that you will add tells clients about the subnets that are reachable behind the server. In this case, 0.0.0.0/0 is used to represent the entire set of IPv4 addresses, meaning that the server will tell clients to send all their traffic over the VPN by default.

      Now that you are familiar with each of the relevant “left” side options, add them all to the file like this:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          left=%any
          leftid=@server_domain_or_IP
          leftcert=server-cert.pem
          leftsendcert=always
          leftsubnet=0.0.0.0/0
      

      Note: When configuring the server ID (leftid), only include the @ character if your VPN server will be identified by a domain name:

      /etc/ipsec.conf

          . . .    leftid=@vpn.example.com
          . . .
      

      If the server will be identified by its IP address, just put the IP address in:

      /etc/ipsec.conf

          . . .
          leftid=your_server_ip
          . . .
      

      Next, we can configure the client’s “right” side IPSec parameters. Each of the following parameters tells the server how to accept connections from clients, how clients should authenticate to the server, and the private IP address ranges and DNS servers that clients will use. Add each of these settings to the /etc/ipsec.conf file once you are familiar with what they are and why they are used:

      • right=%any The %any option for the right side of the connection instructs the server to accept incoming connections from any remote client.
      • rightid=%any This option ensures that the server will not reject connections from clients that provide an identity before the encrypted tunnel is established.
      • rightauth=eap-mschapv2 This option configures the authentication method that clients will use to authenticate to the server. eap-mschapv2 is used here for broad compatibility to support clients like Windows, macOS, and Android devices.
      • rightsourceip=10.10.10.0/24 This option instructs the server to assign private IP addresses to clients from the specified 10.10.10.0/24 pool of IPs.
      • rightdns=8.8.8.8,8.8.4.4 These IP addresses are Google’s public DNS resolvers. They can be changed to use other public resolvers, the VPN server’s resolvers, or any other resolver that clients can reach.
      • rightsendcert=never This option instructs the server that clients do not need to send a certificate to authenticate themselves.

      Now that you are familiar with the required “right” side options for the VPN, add the following lines to /etc/ipsec.conf:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          right=%any
          rightid=%any
          rightauth=eap-mschapv2
          rightsourceip=10.10.10.0/24
          rightdns=8.8.8.8,8.8.4.4
          rightsendcert=never
      

      Now we’ll tell StrongSwan to ask the client for user credentials when they connect:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          eap_identity=%identity
      

      Finally, add the following lines to support Linux, Windows, macOS, iOS, and Android clients. These lines specify the various key exchange, hashing, authentication, and encryption algorithms (commonly referred to as Cipher Suites) that StrongSwan will allow different clients to use:

      /etc/ipsec.conf

      . . .
      conn ikev2-vpn
          . . .
          ike=chacha20poly1305-sha512-curve25519-prfsha512,aes256gcm16-sha384-prfsha384-ecp384,aes256-sha1-modp1024,aes128-sha1-modp1024,3des-sha1-modp1024!
          esp=chacha20poly1305-sha512,aes256gcm16-ecp384,aes256-sha256,aes256-sha1,3des-sha1!
      

      Each supported cipher suite is delineated from the others by a comma. For example chacha20poly1305-sha512-curve25519-prfsha512 is one suite, and aes256gcm16-sha384-prfsha384-ecp384 is another. The cipher suites that are listed here are selected to ensure the widest range of compatibility across Windows, macOS, iOS, Android, and Linux clients.

      The complete configuration file should look like this:

      /etc/ipsec.conf

      config setup
          charondebug="ike 1, knl 1, cfg 0"
          uniqueids=no
      
      conn ikev2-vpn
          auto=add
          compress=no
          type=tunnel
          keyexchange=ikev2
          fragmentation=yes
          forceencaps=yes
          dpdaction=clear
          dpddelay=300s
          rekey=no
          left=%any
          leftid=@server_domain_or_IP
          leftcert=server-cert.pem
          leftsendcert=always
          leftsubnet=0.0.0.0/0
          right=%any
          rightid=%any
          rightauth=eap-mschapv2
          rightsourceip=10.10.10.0/24
          rightdns=8.8.8.8,8.8.4.4
          rightsendcert=never
          eap_identity=%identity
          ike=chacha20poly1305-sha512-curve25519-prfsha512,aes256gcm16-sha384-prfsha384-ecp384,aes256-sha1-modp1024,aes128-sha1-modp1024,3des-sha1-modp1024!
          esp=chacha20poly1305-sha512,aes256gcm16-ecp384,aes256-sha256,aes256-sha1,3des-sha1!
      

      Save and close the file once you’ve verified that you’ve added each line correctly. If you used nano, do so by pressing CTRL + X, Y, then ENTER.

      Now that we’ve configured the VPN parameters, let’s move on to creating an account so our users can connect to the server.

      Step 5 — Configuring VPN Authentication

      Our VPN server is now configured to accept client connections, but we don’t have any credentials configured yet. We’ll need to configure a couple things in a special configuration file called ipsec.secrets:

      • We need to tell StrongSwan where to find the private key for our server certificate, so the server will be able to authenticate to clients.
      • We also need to set up a list of users that will be allowed to connect to the VPN.

      Let’s open the secrets file for editing:

      • sudo nano /etc/ipsec.secrets

      First, we’ll tell StrongSwan where to find our private key:

      /etc/ipsec.secrets

      : RSA "server-key.pem"
      

      Then, we’ll define the user credentials. You can make up any username or password combination that you like:

      /etc/ipsec.secrets

      your_username : EAP "your_password"
      

      Save and close the file. Now that we’ve finished working with the VPN parameters, we’ll restart the VPN service so that our configuration is applied:

      • sudo systemctl restart strongswan-starter

      Now that the VPN server has been fully configured with both server options and user credentials, it’s time to move on to configuring the most important part: the firewall.

      Step 6 — Configuring the Firewall & Kernel IP Forwarding

      With the StrongSwan configuration complete, we need to configure the firewall to allow VPN traffic through and forward it.

      If you followed the prerequisite initial server setup tutorial, you should have a UFW firewall enabled. If you don’t yet have UFW configured, you should start by adding a rule to allow SSH connections through the firewall so your current session doesn’t close when you enable UFW:

      Then enable the firewall by typing:

      Then, add a rule to allow UDP traffic to the standard IPSec ports, 500 and 4500:

      • sudo ufw allow 500,4500/udp

      Next, we will open up one of UFW’s configuration files to add a few low-level policies for routing and forwarding IPSec packets. Before we we can do this, though, we need to find which network interface on our server is used for internet access. Find this interface by querying for the device associated with the default route:

      Your public interface should follow the word “dev”. For example, this result shows the interface named eth0, which is highlighted in the following example:

      Output

      default via your_server_ip dev eth0 proto static

      When you have your public network interface, open the /etc/ufw/before.rules file in your text editor. The rules in this file are added to the firewall before the rest of the usual input and output rules. They are used to configure network address translation (NAT) so that the server can correctly route connections to and from clients and the Internet.

      • sudo nano /etc/ufw/before.rules

      Near the top of the file (before the *filter line), add the following configuration block. Change each instance of eth0 in the above configuration to match the interface name you found with ip route. The *nat lines create rules so that the firewall can correctly route and manipulate traffic between the VPN clients and the internet. The *mangle line adjusts the maximum packet segment size to prevent potential issues with certain VPN clients:

      /etc/ufw/before.rules

      *nat
      -A POSTROUTING -s 10.10.10.0/24 -o eth0 -m policy --pol ipsec --dir out -j ACCEPT
      -A POSTROUTING -s 10.10.10.0/24 -o eth0 -j MASQUERADE
      COMMIT
      
      *mangle
      -A FORWARD --match policy --pol ipsec --dir in -s 10.10.10.0/24 -o eth0 -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1536 -j TCPMSS --set-mss 1360
      COMMIT
      
      *filter
      :ufw-before-input - [0:0]
      :ufw-before-output - [0:0]
      :ufw-before-forward - [0:0]
      :ufw-not-local - [0:0]
      . . .
      

      Next, after the *filter and chain definition lines, add one more block of configuration:

      /etc/ufw/before.rules

      . . .
      *filter
      :ufw-before-input - [0:0]
      :ufw-before-output - [0:0]
      :ufw-before-forward - [0:0]
      :ufw-not-local - [0:0]
      
      -A ufw-before-forward --match policy --pol ipsec --dir in --proto esp -s 10.10.10.0/24 -j ACCEPT
      -A ufw-before-forward --match policy --pol ipsec --dir out --proto esp -d 10.10.10.0/24 -j ACCEPT
      

      These lines tell the firewall to forward ESP (Encapsulating Security Payload) traffic so the VPN clients will be able to connect. ESP provides additional security for our VPN packets as they’re traversing untrusted networks.

      When you’re finished, ave and close the file once you’ve verified that you’ve added each line correctly. If you used nano, do so by pressing CTRL + X, Y, then ENTER.

      Before restarting the firewall, we’ll change some network kernel parameters to allow routing from one interface to another. The file that controls these settings is called /etc/ufw/sysctl.conf. We’ll need to configure a few things in the file including.

      First IPv4 packet forwarding needs to be turned on so that traffic can move between the VPN and public facing network interfaces on the server. Next we’ll disable Path MTU discovery to prevent packet fragmentation problems. Finally we will not accept ICMP redirects nor send ICMP redirects to prevent man-in-the-middle attacks.

      Open UFW’s kernel parameters configuration file using nano or your preferred text editor:

      • sudo nano /etc/ufw/sysctl.conf

      Now add the following net/ipv4/ip_forward=1 setting at the end of the file to enable forwarding packets between interfaces:

      /etc/ufw/sysctl.conf

      . . .
      net/ipv4/ip_forward=1
      

      Next block sending and receiving ICMP redirect packets by adding the following lines to the end of the file:

      /etc/ufw/sysctl.conf

      . . .
      net/ipv4/conf/all/accept_redirects=0
      net/ipv4/conf/all/send_redirects=0
      

      Finally, turn off Path MTU discovery by adding this line to the end of the file:

      /etc/ufw/sysctl.conf

      . . .
      net/ipv4/ip_no_pmtu_disc=1
      

      Save the file when you are finished. Now we can enable all of our changes by disabling and re-enabling the firewall, since UFW applies these settings any time that it restarts:

      • sudo ufw disable
      • sudo ufw enable

      You’ll be prompted to confirm the process. Type Y to enable UFW again with the new settings.

      Step 7 — Testing the VPN Connection on Windows, macOS, Ubuntu, iOS, and Android

      Now that you have everything set up, it’s time to try it out. First, you’ll need to copy the CA certificate you created and install it on your client device(s) that will connect to the VPN. The easiest way to do this is to log into your server and output the contents of the certificate file:

      • cat /etc/ipsec.d/cacerts/ca-cert.pem

      You’ll see output similar to this:

      Output

      -----BEGIN CERTIFICATE----- MIIFNDCCAxygAwIBAgIIHCsidG5mXzgwDQYJKoZIhvcNAQEMBQAwODELMAkGA1UE . . . H2YUdz8XNHrJHvMQKWFpi0rlEcMs+MSXPFWE3Q7UbaZJ/h8wpSldSUbQRUlphExJ dJ4PX+MUJO/vjG1/ie6Kh25xbBAc3qNq8siiJZDwrg6vjEK7eiZ1rA== -----END CERTIFICATE-----

      Copy this output to your computer, including the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- lines, and save it to a file with a recognizable name, such as ca-cert.pem. Ensure the file you create has the .pem extension.

      Alternatively, use SFTP to transfer the file to your computer.

      Once you have the ca-cert.pem file downloaded to your computer, you can set up the connection to the VPN.

      Connecting from Windows

      There are multiple ways to import the root certificate and configure Windows to connect to a VPN. The first method uses graphical tools for each step. The second method uses PowerShell commands, which can be scripted and modified to suit your VPN configuration.

      Note: These instructions have been tested on Windows 10 installations running versions 1903 and 1909.

      Configuring Windows with Graphical Tools

      First, import the root certificate by following these steps:

      1. Press WINDOWS+R to bring up the Run dialog, and enter mmc.exe to launch the Windows Management Console.
      2. From the File menu, navigate to Add or Remove Snap-in, select Certificates from the list of available snap-ins, and click Add.
      3. We want the VPN to work with any user, so select Computer Account and click Next.
      4. We’re configuring things on the local computer, so select Local Computer, then click Finish.
      5. Under the Console Root node, expand the Certificates (Local Computer) entry, expand Trusted Root Certification Authorities, and then select the Certificates entry:
        Certificates view

      6. From the Action menu, select All Tasks and click Import to display the Certificate Import Wizard. Click Next to move past the introduction.

      7. On the File to Import screen, press the Browse button, ensure that you change the file type from “X.509 Certificate (.cer;.crt)” to “All Files (.)”, and select the ca-cert.pem file that you’ve saved. Then click Next.

      8. Ensure that the Certificate Store is set to Trusted Root Certification Authorities, and click Next.

      9. Click Finish to import the certificate.

      Then configure the VPN with these steps:

      1. Launch Control Panel, then navigate to the Network and Sharing Center.
      2. Click on Set up a new connection or network, then select Connect to a workplace.
      3. Select Use my Internet connection (VPN).
      4. Enter the VPN server details. Enter the server’s domain name or IP address in the Internet address field, then fill in Destination name with something that describes your VPN connection. Then click Done.

      Configuring Windows using PowerShell

      To import the root CA certificate using PowerShell, first open a PowerShell prompt with administrator privileges. To do so, right click the Start menu icon and select Windows PowerShell (Admin). You can also open a command prompt as administrator and type powershell.

      Next we’ll import the certificate using the Import-Certificate PowerShell cmdlet. In the following command, the first -CertStoreLocation argument will ensure that the certificate is imported into the computer’s Trusted Root Certification Authorities store so that all programs and users will be able to verify the VPN server’s certificate. The -FilePath argument should point to the location where you copied the certificate. In the following example the path is C:UserssammyDocumentsca-cert.pem. Ensure that you edit the command to match the location that you used.

      • Import-Certificate `
      • -CertStoreLocation cert:LocalMachineRoot `
      • -FilePath C:userssammyDocumentsca-cert.pem

      The command will output something like the following:

      Output

      PSParentPath: Microsoft.PowerShell.SecurityCertificate::LocalMachineRoot Thumbprint Subject ---------- ------- DB00813B4087E9367861E8463A60CEA0ADC5F002 CN=VPN root CA

      Now to configure the VPN using PowerShell, run the following command. Substitute your server’s DNS name or IP address on the -ServerAddress line. The various flags will ensure that Windows is correctly configured with the appropriate security parameters that match the options that you set in /etc/ipsec.conf.

      • Add-VpnConnection -Name "VPN Connection" `
      • -ServerAddress "server_domain_or_IP" `
      • -TunnelType "IKEv2" `
      • -AuthenticationMethod "EAP" `
      • -EncryptionLevel "Maximum" `
      • -RememberCredential `

      If the command is successful there will not be any output. To confirm the VPN is configured correctly, use the Get-VPNConnection cmdlet:

      • Get-VpnConnection -Name "VPN Connection"

      You will receive output like the following:

      Output

      Name : VPN Connection ServerAddress : your_server_ip AllUserConnection : False Guid : {B055A1AB-175C-4028-B4A8-D34309A2B20E} TunnelType : Ikev2 AuthenticationMethod : {Eap} EncryptionLevel : Maximum L2tpIPsecAuth : UseWinlogonCredential : False EapConfigXmlStream : #document ConnectionStatus : Disconnected RememberCredential : True SplitTunneling : False DnsSuffix : IdleDisconnectSeconds : 0

      By default Windows chooses older and slower algorithms. Run the Set-VpnConnectionIPsecConfiguration cmdlet to upgrade the encryption parameters that Windows will use for the IKEv2 key exchange, and to encrypt packets:

      • Set-VpnConnectionIPsecConfiguration -Name "VPN Connection" `
      • -AuthenticationTransformConstants GCMAES256 `
      • -CipherTransformConstants GCMAES256 `
      • -DHGroup ECP384 `
      • -IntegrityCheckMethod SHA384 `
      • -PfsGroup ECP384 `
      • -EncryptionMethod GCMAES256

      Note: If you would like to delete the VPN connection and reconfigure it with different options, you can run the Remove-VpnConnection cmdlet.

      • Remove-VpnConnection -Name "VPN Connection" -Force

      The -Force flag will skip prompting you to confirm the removal. You must be disconnected from the VPN if you attempt to remove it using this command.

      Connecting to the VPN

      Once you have the certificate imported and the VPN configured using either method, your new VPN connection will be visible under the list of networks. Select the VPN and click Connect. You’ll be prompted for your username and password. Type them in, click OK, and you’ll be connected.

      Connecting from macOS

      Follow these steps to import the certificate:

      1. Double-click the certificate file. Keychain Access will pop up with a dialog that says “Keychain Access is trying to modify the system keychain. Enter your password to allow this.”
      2. Enter your password, then click on Modify Keychain
      3. Double-click the newly imported VPN certificate. This brings up a small properties window where you can specify the trust levels. Set IP Security (IPSec) to Always Trust and you’ll be prompted for your password again. This setting saves automatically after entering the password.

      Now that the certificate is imported and trusted, configure the VPN connection with these steps:

      1. Go to System Preferences and choose Network.
      2. Click on the small “plus” button on the lower-left of the list of networks.
      3. In the popup that appears, set Interface to VPN, set the VPN Type to IKEv2, and give the connection a name.
      4. In the Server and Remote ID field, enter the server’s domain name or IP address. Leave the Local ID blank.
      5. Click on Authentication Settings, select Username, and enter your username and password you configured for your VPN user. Then click OK.

      Finally, click on Connect to connect to the VPN. You should now be connected to the VPN.

      Connecting from Ubuntu

      To connect from an Ubuntu machine, you can set up and manage StrongSwan as a service or use a one-off command every time you wish to connect. Instructions are provided for both.

      Managing StrongSwan as a Service

      To manage StrongSwan as a service, you will need to perform the following configuration steps.

      First, update your local package cache using apt

      Next, install StrongSwan and the required plugins for authentication:

      • sudo apt install strongswan libcharon-extra-plugins

      Now you’ll need a copy of the CA certificate in the /etc/ipsec.d/cacerts directory so that your client can verify the server’s identity. Run the following command to copy the ca-cert.pem file into place:

      • sudo cp /tmp/ca-cert.pem /etc/ipsec.d/cacerts

      To ensure the VPN only runs on demand, use systemctl to disable StrongSwan from running automatically:

      • sudo systemctl disable --now strongswan-starter

      Next configure the username and password that you will use to authenticate to the VPN server. Edit /etc/ipsec.secrets using nano or your preferred editor:

      • sudo nano /etc/ipsec.conf

      Add the following line, editing the highlighted username and password values to match the ones that you configured on the server:

      /etc/ipsec.conf

      your_username : EAP "your_password"
      

      Finally, edit the /etc/ipsec.conf file to configure your client to match the server’s configuration:

      /etc/ipsec.conf

      config setup
      
      conn ikev2-rw
          right=server_domain_or_IP
          # This should match the `leftid` value on your server's configuration
          rightid=server_domain_or_IP
          rightsubnet=0.0.0.0/0
          rightauth=pubkey
          leftsourceip=%config
          leftid=username
          leftauth=eap-mschapv2
          eap_identity=%identity
          auto=start
      

      To connect to the VPN, type:

      • sudo systemctl start strongswan-starter

      To disconnect again, type:

      • sudo systemctl stop strongswan-starter

      Using the charon-cmd Client for One-Off Connections

      To manage StrongSwan as a service, you will need to perform the following configuration steps.

      First, update your local package cache using apt

      Next, install StrongSwan and the required plugins for authentication:

      • sudo apt install strongswan libcharon-extra-plugins

      Now you’ll need a copy of the CA certificate in the /etc/ipsec.d/cacerts directory so that your client can verify the server’s identity. Run the following command to copy the ca-cert.pem file into place:

      • sudo cp /tmp/ca-cert.pem /etc/ipsec.d/cacerts

      At this point you can connect to the VPN server with charon-cmd using the server’s CA certificate, the VPN server’s IP address, and the username you configured.

      Run the following command whenever you want to connect to the VPN:

      • sudo charon-cmd --cert ca-cert.pem --host vpn_domain_or_IP --identity your_username

      When prompted, provide the VPN user’s password and you will be connected to the VPN. To disconnect, press CTRL+C in the terminal and wait for the connection to close.

      Connecting from iOS

      To configure the VPN connection on an iOS device, follow these steps:

      1. Send yourself an email with the root certificate attached.
      2. Open the email on your iOS device and tap on the attached certificate file, then tap Install and enter your passcode. Once it installs, tap Done.
      3. Go to Settings, General, VPN and tap Add VPN Configuration. This will bring up the VPN connection configuration screen.
      4. Tap on Type and select IKEv2.
      5. In the Description field, enter a short name for the VPN connection. This could be anything you like.
      6. In the Server and Remote ID field, enter the server’s domain name or IP address. The Local ID field can be left blank.
      7. Enter your username and password in the Authentication section, then tap Done.
      8. Select the VPN connection that you just created, tap the switch on the top of the page, and you’ll be connected.

      Connecting from Android

      Follow these steps to import the certificate:

      1. Send yourself an email with the CA certificate attached. Save the CA certificate to your downloads folder.
      2. Download the StrongSwan VPN client from the Play Store.
      3. Open the app. Tap the “more” icon () in the upper-right corner and select CA certificates.
      4. Tap the “more” icon () in the upper-right corner again. Select Import certificate.
      5. Browse to the CA certificate file in your downloads folder and select it to import it into the app.

      Now that the certificate is imported into the StrongSwan app, you can configure the VPN connection with these steps:

      1. In the app, tap ADD VPN PROFILE at the top.
      2. Fill out the Server with your VPN server’s domain name or public IP address.
      3. Make sure IKEv2 EAP (Username/Password) is selected as the VPN Type.
      4. Fill out the Username and Password with the credentials you defined on the server.
      5. Deselect Select automatically in the CA certificate section and click Select CA certificate.
      6. Tap the IMPORTED tab at the top of the screen and choose the CA you imported (it will be named “VPN root CA” if you didn’t change the “DN” earlier).
      7. If you’d like, fill out Profile name (optional) with a more descriptive name.

      When you wish to connect to the VPN, click on the profile you just created in the StrongSwan application.

      Troubleshooting Connections

      If you are unable to import the certificate, ensure the file has the .pem extension, and not .pem.txt.

      If you’re unable to connect to the VPN, check the server name or IP address you used. The server’s domain name or IP address must match what you’ve configured as the common name (CN) while creating the certificate. If they don’t match, the VPN connection won’t work. For example, if you set up a certificate with the CN of vpn.example.com, you must use vpn.example.com when you enter the VPN server details. Double-check the command you used to generate the certificate, and the values you used when creating your VPN connection.

      Finally, double-check the VPN configuration to ensure the leftid value is configured with the @ symbol if you’re using a domain name:

      /etc/ipsec.conf

          leftid=@vpn.example.com
      

      If you’re using an IP address, ensure that the @ symbol is omitted. Also make sure that when you generated the server-cert.pem file that you included both --san @IP_address and --san IP_address flags.

      Conclusion

      In this tutorial, you’ve built a VPN server that uses the IKEv2 protocol. You learned about the directives that control the left and right sides of a connection on both server and clients. You also configured a Windows, macOS, iOS, Android, or Linux client to connect to the VPN.

      To add or remove users, skip to Step 5 again. Each line in /etc/ipsec.secrets is for one user, so adding or removing users, or changing passwords just requires editing the file.

      Now you can be assured that your online activities will remain secure wherever you go and with any device that you use to access the internet.



      Source link