Перейти к содержанию

Навигация

CryptodevATECCx08 Auth/en: различия между версиями

Новая страница: «Getting messages from the "test" topic on the example.com server»
(Новая страница: «To access the crypto device needs a library libateccssl1.1, install it with the command:»)
(Новая страница: «Getting messages from the "test" topic on the example.com server»)
 
(не показано 48 промежуточных версий этого же участника)
Строка 13: Строка 13:
'''apt install libateccssl1.1'''
'''apt install libateccssl1.1'''


Далее нужно отредактировать файл '''/etc/ssl/openssl.cnf''', добавив в нем следующие строчки:
Next you need to edit the  ''/etc/ssl/openssl.cnf''' file, adding the following lines:


<pre>
<pre>
Строка 28: Строка 28:
</pre>
</pre>


Теперь приступим к созданию сертификатов.
Now let's start creating certificates.
Для начала создадим свой центр сертификации (Certification Authority, '''CA'''):
First, we will create our own Certification Authority ('''CA'''):


Для этого сгенерируем ключевую пару:
To do this, generate a key pair:
<pre>openssl genrsa -out ca.key 2048</pre>
<pre>openssl genrsa -out ca.key 2048</pre>


И сертификат нашего '''CA''':
And certificate of our '''CA''':


<pre>openssl req -x509 -new -days 3650 -key ca.key -out ca.crt -subj "/CN=MY CA"</pre>
<pre>openssl req -x509 -new -days 3650 -key ca.key -out ca.crt -subj "/CN=MY CA"</pre>


'''CA''' является основой безопасности в данной схеме, поэтому эти операции выполняем на машине доступ к которой
'''CA''' is the basis of security in this scheme, so these operations are performed on the machine that is accessed
есть только у владельца '''CA'''.
only the owner of the '''CA'''.


Далее на конроллере WB создаем запрос на сертификат устройства:
Next, create a request for a device certificate on the Wiren Board controller:


<pre>openssl req -new -engine ateccx08 -keyform engine -key ATECCx08:00:04:C0:00 -subj "/CN=wirenboard-AP6V5MDG" -out device_AP6V5MDG.csr</pre>
<pre>openssl req -new -engine ateccx08 -keyform engine -key ATECCx08:00:04:C0:00 -subj "/CN=wirenboard-AP6V5MDG" -out device_AP6V5MDG.csr</pre>


В этой команде мы указываем, что запрос подписывается приватным ключом, находящимся в криптоустройстве ateccx08 ключом
In this command, we specify that the request is signed with a private key that is in the ateccx08 crypto device
с идентификатором '''ATECCx08:00:04:C0:00''' и публичным именем wirenboard-AP6V5MDG. Запрос помещаем в файл device_AP6V5MDG.csr.
with ID '''ateccx08:00:04:C0:00''' and public name wirenboard-AP6V5MDG. The request is placed in the file device_AP6V5MDG.csr.


Имя можно выбрать любое уникальное, удобно для этой цели спользовать идентификатор устройства, который по умолчанию прописывается
You can choose any unique name, it is convenient for this purpose to use the device ID, which is prescribed by default
в файле /etc/hostname:
in /etc/hostname:


<pre>
<pre>
Строка 56: Строка 56:
</pre>
</pre>


Далее этот запрос подписываем в нашем центре сертификации:
Next, we sign this request in our certification authority:
openssl x509 -req -in device_AP6V5MDG.csr -CA ca.crt -CAkey ca.key -out device_AP6V5MDG.crt -days 365 -CAcreateserial
openssl x509 -req -in device_AP6V5MDG.csr -CA ca.crt -CAkey ca.key-out device_AP6V5MDG.crt -days 365 -CAcreateserial


В этой команде мы уазываем файл запроса, и файлы CA необходимые для подписи. В итоге получаем сертификат устройства device_AP6V5MDG.crt.
In this command, we specify the request file and the CA files required for signing. The result is a device certificate device_AP6V5MDG.crt.
Файл '''device_AP6V5MDG.crt''' копируем на контроллер WB, он будет необходим для авторизацци.
File '''device_AP6V5MDG.crt''' copy to the Wiren Board controller, it will be necessary for authorization.


Давайте посмотрим, что содержится в файлах сертификатов CA и устройства:
Let's see what is there in the CA and device certificate files:


<pre>
<pre>
Строка 107: Строка 107:
</pre>
</pre>


Видим, что сертификат выписан Центром сертификации с именем "MY CA" на 1 год, начная с "Feb 4 14:50:14 2019 GMT" (для этого мы указывали -days 365 в команде подписи),
We see that the certificate is issued by a Certification Authority named "MY CA" for 1 year, starting with "Feb 4 14:50:14 2019 GMT" (for this we specified -days 365 in the signature team),
устройству с именем '''wirenboard-AP6V5MDG''', имеющим приватный ключ соответствующий публичному Subject Public Key Info.
a device named '''wirenboard-AP6V5MDG''' that has a private key corresponding to the  Subject Public Key Info.
Сертификат подписан цифровой подписью.  
The certificate is digitally signed.  


Цифровая подпись гарантирует, что никакая часть сертификата не может быть незаметно изменена. В случае изменения проверка публичным
A digital signature ensures that no part of the certificate can be tampered. In case of a change, a public inspection with
ключом '''CA''' даст ошибку.
the key '''CA''' will show an error.


<pre>
<pre>
Строка 177: Строка 177:
</pre>
</pre>


Видим, что сертификат подписан сам своим-же приватным ключом (Issuer: CN = MY CA, Subject: CN = MY CA)
We see that the certificate is signed by its own private key (Issuer: CN = MY CA, Subject: CN = MY CA)
и выписан на 10 лет: начная с "Feb 4 14:30:01 2019 GMT" (для этого мы указывали -days 3650 в команде подписи)
and discharged for 10 years: starting with "Feb 4 14:30:01 2019 GMT" (for this we indicated -days 3650 in the signature team)


Таким образом цепочка доверия (проверки) выстраивается следующим образом:
Thus, the chain of trust (verification) is built as follows:


Сертификат устройства подписан сертификатом CA и может быть им проверен:
The device certificate is signed by a CA certificate and can be verified by it:
<pre>
<pre>
openssl verify -CAfile ca.crt device_AP6V5MDG.crt  
openssl verify -CAfile ca.crt device_AP6V5MDG.crt  
Строка 188: Строка 188:
</pre>
</pre>


Ну а сам сертификат подписан "собой":
Well, the certificate is signed "by itself"
<pre>
<pre>
openssl verify -CAfile ca.crt ca.crt
openssl verify -CAfile ca.crt ca.crt
Строка 196: Строка 196:




== Настройка nginx. ==
== Nginx configuration ==


Допустим в интернете есть сервер, который должен обрабатывать запросы только от устройств обладающих сертификатами,
For example, suppose you have a server on the Internet that must process requests only from devices that have certificates,
выписанными нашим CA.
issued by our CA.
Для включения такой проверки в конфигурационном файле nginx необходимо в секции http или server прописать следующие строчки:
To enable this check in the nginx configuration file, you need to write the following lines in the http or server section:


<pre>
<pre>
Строка 207: Строка 207:
</pre>
</pre>


Теперь nginx будет требовать от клиента сертификат, который должен проходить проверку с помощью ca.crt, иначе сервер
Nginx will now require a certificate from the client that must be validated by a ca.crt, otherwise the server
вернет клиенту ошибку 400:
returns an error 400 to the client:


<pre>
<pre>
Строка 222: Строка 222:
</pre>
</pre>


Теперь сделаем так, чтобы HTTP запросы с контроллера WB проходили данную проверку.
Now let's make http requests from WB controller pass this check.
Для простоты будем использовать nginx и на клиентской стороне. Это даст возможность работать
For simplicity, we will use nginx on the client side. This will give the opportunity to work
с защищенными серверами клиентам не умеющим делать SSL соединения.
with secure servers for clients who can't make SSL connections.


Для начала создадим на неиспользуемом локальном порту http сервер, который будет делать
First, we will create a server on the unused local http port, which will do the following
всю https "магию" за нас:
all https "magic" for us:


<pre>
<pre>
Строка 242: Строка 242:
</pre>
</pre>


Добавим пользователя www-data в группу i2c для доступа к криптоустройству:
Add the www-data user to the i2c group to access the crypto device:
<pre>
<pre>
usermod -G www-data
usermod -G www-data
</pre>
</pre>


Выполним команду '''service nginx restart''' для обновления конфигурации.
Run the command '''service nginx restart''' to update the configuration.


Теперь при обращении по http на локальный порт 8080 зашифрованные запросы с аутентификационной
Now, when you access http on the local port 8080, encrypted requests with authentication  information will be sent to the server example.com
информацией будут отправлятся на сервер example.com.


<pre>
<pre>
Строка 261: Строка 260:
</pre>
</pre>


== Настройка openvpn ==
== Openvpn configuration ==


Для начала установим пакет:
First, install the package:


<pre>
<pre>
Строка 269: Строка 268:
</pre>
</pre>


Cоздадим файл req.cnf - он нам потребуется для создания сертификата сервера.  
Create file named req.cnf - we need it to make a server certificate.
<pre>
<pre>
[ v3_req ]
[ v3_req ]
Строка 277: Строка 276:
</pre>
</pre>


Серверу openvpn также требуется файл с параметрами DH, сделаем его.
The openvpn server also needs a file with DH parameters, let's make it.
<pre>
<pre>
openssl dhparam -out dh2048.pem 2048
openssl dhparam -out dh2048.pem 2048
</pre>
</pre>


Создание данного файла может потребовать несколько минут.  
It may take a few minutes to create this file.  


Далее сделаем приватный ключ нашего сервера и запрос на сертификат. Предполагаем, для примера, что
Next, make a private key of our server and request a certificate. We assume, for example, that
сервер имеет имя example.com:
server has name example.com:


<pre>  
<pre>  
Строка 293: Строка 292:
</pre>
</pre>


Подписываем запрос в нашем центре сертификации:
Sign the request in our certification authority:


<pre>
<pre>
Строка 299: Строка 298:
</pre>
</pre>


Теперь приступим к настройке openvpn сервера на машине example.com.
Now let's start setting up openvpn server on the machine example.com


Копируем файлы '''ca.crt''', '''example.crt''', '''example.key''' и '''dh2048.pem''' и редактируем файл конфигурации openvpn сервера.
Copy the file '''ca.crt''', '''example.crt''', '''example.key''' and '''dh2048.pem''' and edit the openvpn server configuration file.
По умолчанию конфигурационный файл лежит в файле /etc/openvpn/server.conf
By default, the configuration file is in /etc/openvpn/server.conf


<pre>
<pre>
Строка 328: Строка 327:
</pre>
</pre>


Добавим пользователя openvpn в группу i2c для доступа к криптоустройству:
Add the openvpn user to the i2c group to access the crypto device:


<pre>
<pre>
Строка 334: Строка 333:
</pre>
</pre>


после этого запускаем сервер командой
after that, start the server with the command
service openvpn start.
service openvpn start.


Далее на контроллере создаем файл конфигурации клиента:
Next, create a client configuration file on the controller:
client.ovpn:
client.ovpn:
<pre>
<pre>
Строка 359: Строка 358:
-------------------------------------------------------------------------
-------------------------------------------------------------------------
</pre>
</pre>
Обратите внимание на строчку group i2c. Она необходима для работы с криптоустройством.
Note the line group i2c. It is necessary to work with the crypto device.


После этого запускаем клиента:
Then run the client:


<pre>
<pre>
Строка 367: Строка 366:
</pre>
</pre>


Если все хорошо, то в системе должен появиться интерфейс tun0 с адресом из подсети 10.8.0.0/24:
If all is well, then the system should appear tun0 interface with the address from the subnet 10.8.0.0/24:


<pre>
<pre>
Строка 380: Строка 379:
</pre>
</pre>


Для проверки работоспособности запускаем ping:
To check the performance run ping:


<pre>
<pre>
Строка 389: Строка 388:
</pre>
</pre>


== Настройка mosquitto ==
== Mosquitto settings ==


UPD:
UPD:
Строка 469: Строка 468:




Генерируем приватный ключ и запрос на сертификат:
Generate a private key and certificate request:


<pre>
<pre>
Строка 481: Строка 480:
</pre>
</pre>


Копируем файлы '''ca.crt''', '''mosquitto.crt''', '''mosquitto.key''' на сервер и редактируем файл конфигурации '''/etc/mosquitto/conf.d/server.conf'''
Copy the file '''ca.crt''', '''mosquitto.crt''', '''mosquitto.key''' to the server and edit the configuration file '''/etc/mosquito/conf.d/server.conf'''


<pre>
<pre>
Строка 491: Строка 490:
</pre>
</pre>


Запускаем серис:
Start service:
<pre>
<pre>
service mosquitto start
service mosquitto start
</pre>
</pre>


Также, если требуется, можно сделать чтобы локальный mosquitto сервер на контроллере
Also, if required, you can make the local mosquitto server on the controller
форвардил некоторые топики на удаленный сервер. Для этого создаем файл бриджа: '''/etc/mosquitto/bridge.conf'''
forwarder some topics on a remote server. To do this, create a bridge file: '''/etc/mosquitto/bridge.conf'''


<pre>
<pre>
Строка 509: Строка 508:
</pre>
</pre>


После перезапуска локального сервиса mosquitto топики /test/.. будут отправлятся на удаленный сервер example.com
After restarting the local service mosquito topics /test/.. will be sent to the remote server example.com
по защищенному ssl каналу.
secure ssl channel.


Примеры клиентских команд mosquitto.
Examples of client mosquitto commands.
Отправка сообщения "message" в топик "test" на сервере example.com  
Sending a message to the "test" topic on the  example.com server


<pre>
<pre>
Строка 519: Строка 518:
</pre>
</pre>


Получение сообщений из топика "test" на сервере example.com
Getting messages from the "test" topic on the example.com server


<pre>
<pre>
mosquitto_sub -h example.com --cert device_AP6V5MDG.crt --key 'engine:ateccx08:ATECCx08:00:04:C0:00' -t "test" --cafile ca.crt
mosquitto_sub -h example.com --cert device_AP6V5MDG.crt --key 'engine:ateccx08:ATECCx08:00:04:C0:00' -t "test" --cafile ca.crt
</pre>
</pre>
12 063

правки