Ошибка internal error no matching private keys available

I have a .key file, when I do openssl rsa -text -in file.key Also I have a .cer file and when I do openssl x509 -text -in file.cer But if as pointed here I run the command like: openssl x509 -text -inform DER -in file.cer But that doesn't seem to work with the key, because […]

На чтение 9 мин. Просмотров 12 Опубликовано 15.12.2019

I have a .key file, when I do

openssl rsa -text -in file.key

Also I have a .cer file and when I do

openssl x509 -text -in file.cer

But if as pointed here I run the command like:

openssl x509 -text -inform DER -in file.cer

But that doesn’t seem to work with the key, because when I run

openssl rsa -text -inform DER -in aaa010101aaa__csd_10.key

How can I get the private key and its certificate?

Содержание

  1. 4 Answers 4
  2. No certificate matches private key
  3. RE: No certificate matches private key

4 Answers 4

It looks like you have a certificate in DER format instead of PEM . This is why it works correctly when you provide the -inform PEM command line argument (which tells openssl what input format to expect).

It’s likely that your private key is using the same encoding. It looks as if the openssl rsa command also accepts a -inform argument, so try:

A PEM encoded file is a plain-text encoding that looks something like:

While DER is a binary encoding format.

Update

Sometimes keys are distributed in PKCS#8 format (which can be either PEM or DER encoded). Try this and see what you get:

When installing a certificate on Apache web server, you might receive an error “SSL Library Error: 185073780 error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch” during restart of Apache service.

Most often, this error appears if you are using an incorrect private key along with the certificate you received from the Certificate Authority. In order for Apache to accept certificate, it should be used with the private key generated along with the CSR code submitted for the certificate activation.

You can check whether the certificate matches the private key using the following openssl commands:

openssl x509 -in /path/to/certificate.crt -noout -modulus | openssl sha1
openssl rsa -in /path/to/private.key -noout -modulus | openssl sha1

The first command is applied to the certificate file, which you received from the Certificate Authority. The second one is for the private key.

Note: Make sure you indicate the correct path to the certificate and key files. You can take either relative or absolute path.Alternatively, you can check sha256 or md5 moduli of the key and certificate pair, replacing the hash function at the end of the command.

If the outputs of the commands differ (like in the screenshot above), this means that the chosen private key does not match the certificate.

You may also check whether the certificate matches the private key using this online tool. Copy the contents of the certificate and key files to the corresponding fields in the form and click “Match”. The site will show whether or not the certificate can be installed with the provided private key.

You will need to find another private key file on the server. The command below may help you:

This command will find all files on the server with .key extensions. Make sure you are logged in as root user, otherwise you may need to add sudo in front of the command.

Once the keys are found, check their moduli using the openssl rsa command listed above to locate one that matches.
If a private key with a modulus matching the certificate cannot be found, a new CSR code will need to be generated and the certificate reissued. Refer to these instructions on how to generate a new CSR code on your server and reissue the certificate.

One more possible cause of the error might refer to Apache starting from version 2.4.8. SSLCertificateChainFile directive became obsolete with version 2.4.8, when SSLCertificateFile was extended to also load intermediate CA certificates from the server certificate file. It allows the certificate file to contain the certificate as well as intermediate certificates. It is important that the end-entity certificate issued for a domain is placed as the first certificate in this file, while intermediate certificates should be placed lower starting from the one that signs the end-entity certificate. Otherwise, you may also receive the key values mismatch error.

Classic List Threaded

No certificate matches private key

I’m trying to create an SSL certificate for a Cisco Wireless LAN controller and keep getting the error “No certificate matches private key”.

These are the steps I have taken:

1. Generate the private key and CSR with the command openssl req –newkey rsa:2048 –subj “/C=XX/O=XX/OU=XX/OU=XX/OU=XX/CN=mydevice” –keyout mykey.pem –out req.pem –nodes –config openssl.cnf

2. Sent the req.pem file in an email to the CA. The body of the email gave region, org, device serial, contact info, etc.

3. The CA returned device.P7b, intermediate.P7b, and root.P7b certificate files

4. Using a text editor I opened the received cert files and copied all of their contents into a single All-certs.pem file. They were place in the proper device/intermediate/root order with the correct delimiters around them.

5. Both All-certs.pem and mykey.pem files are located in the bin folder with the openSSL executable

6. I executed the command pkcs12 -export -in All-certs.pem -inkey mykey.pem -out All-certs.p12 –clcerts

7. I receive the error “No certificate matches private key”

I know that openSSL is seeing the files because I get “no such file or directory errors” when they are not in the bin folder

I have also verified the files are a matching set by comparing their hashes with the following commands

x509 -noout -modulus -in All-certs.pem | openssl md5

rsa -noout -modulus -in mykey.pem | openssl md5

A small team of us have been beating our heads over this for about a week so any assistance is greatly appreciated.

Brian Goulet
Wireless Communications Engineer

Enterprise Network Engineering
Harris IT Services
298 Seavy Street, Portsmouth, NH 03804

CONFIDENTIALITY NOTICE: This email and any attachments may contain material that is «Harris Proprietary Information,» confidential, privileged, and/or attorney work product for the sole use of the intended recipient. Any review, reliance, distribution, disclosure, or forwarding without expressed permission is strictly prohibited. If you are not the intended recipient, please contact sender and delete all copies without reading, printing or saving in any manner.

RE: No certificate matches private key

>From: [hidden email] On Behalf Of Goulet, Brian
>Sent: Friday, 25 January, 2013 15:53

>I’m trying to create an SSL certificate for
>and keep getting the error «No certificate matches private key».
>These are the steps I have taken:
>1. Generate the private key and CSR with the command
>openssl req -newkey rsa:2048 -subj
«/C=XX/O=XX/OU=XX/OU=XX/OU=XX/CN=mydevice»
>-keyout mykey.pem -out req.pem -nodes -config openssl.cnf
>2. Sent the req.pem file in an email to the CA. The body
>of the email gave region, org, device serial, contact info, etc.
>3. The CA returned device.P7b, intermediate.P7b, and root.P7b
>certificate files
>4. Using a text editor I opened the received cert files and
>copied all of their contents into a single All-certs.pem file.
>They were place in the proper device/intermediate/root order with
>the correct delimiters around them.

correct means dashes BEGIN/END CERTIFICATE, NOT BEGIN/END PKCS7 ?
It is confusing for the CA to give you files named *.p7b which are
actually cert and not PKCS7, a related but different structure,
when the main point of the p7b structure is that you can transmit
the whole chain in a single file/PDU; but as long as the contents
are actually the certs that’s good, and if the x509 operation below
reads without error at least one must be (a cert).

And all the delimiter lines are complete lines, right? With some
editors especially on Windows that’s easy to get wrong.

>5. Both All-certs.pem and mykey.pem files are located in
>the bin folder with the openSSL executable

>6. I executed the command pkcs12 -export -in All-certs.pem
>-inkey mykey.pem -out All-certs.p12 -clcerts

*command* pkcs12 not program openssl with *argument* pkcs12 ?
Did you (or someone) nonstandardly build the commandline aka
utility operations, in the apps directory, as «not MONOLITH»?
Above you said «the openSSL executable» as if there is only one.
Or do you have an alias or script or somesuch named pkcs12 that
actually runs program openssl with argument pkcs12?

-clcerts only affects pkcs12 import, it is ignored for export.

Personally I wouldn’t name that output file All-certs.p12,
but that’s just taste not an error.

>7. I receive the error «No certificate matches private key»

>I know that openSSL is seeing the files because I get «no such file
>or directory errors» when they are not in the bin folder

>I have also verified the files are a matching set by comparing their
>hashes with the following commands

>x509 -noout -modulus -in All-certs.pem | openssl md5
>rsa -noout -modulus -in mykey.pem | openssl md5

Again command x509 or rsa, not program openssl with that argument?

But substantively you’re right; the sequence you did should work.

I would check a little more completely:
openssl rsa -in mykey.pem -pubout -out temp1
openssl req -in req.pem -noout -pubkey -out temp2
openssl x509 -in All-certs.pem -noout -pubkey -out temp3
# or -in device.p7b which apparently isn’t truly p7b
*the whole* of temp1,2,3 should be identical.

Assuming they match, I don’t see any choice better than debugging
in EVP_PKEY_cmp, and below, to see what’s going wrong.

https://www.lexium.ru/2014/06/nesovpadenie-sertifikata-i-privatnogo-klyucha-na-servere-apache/

В продолжение темы о наиболее часто возникающих вопросах и проблемах при генерации CSR запроса на сервере Apache, а также при установке SSL-сертификата на нем, поговорим об ошибке «x509_check_private_key:key values mismatch».
Такая ошибка говорит о том, что сертификат и приватный ключ не совпадают.
Если клиент не осведомлен о том, в какой момент генерируется приватный ключ и где он сохраняется, то, вероятно, он получит такую ошибку.

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

Открытый (публичный) ключ передается в центр сертификации вместе с CSR запросом, который подписывается удостоверяющим центром, т.е. на основе которого впоследствии выпускается сам SSL-сертификат.

Затем подписанный публичный ключ необходимо установить одновременно с приватным ключом таким образом, чтобы эта пара ключей совпала. Несоответствие приватного и открытого ключей приведет к ошибке «x509_check_private_key:key values mismatch».

На совпадение или несовпадение приватного и публичного ключей Вам могут помочь указать поля под названием «MODULUS» и «PUBLIC EXPONENT».
Чтобы это проверить, просто запустите следующие две команды для приватного и публичного ключей:

openssl x509 -noout -text -in [path of public key]
openssl rsa -noout -text -in [path of private key]

Если поля «MODULUS» и «PUBLIC EXPONENT» совпадают для каждого из ключей, то и сами ключи соответствуют паре.

В случае, если поля не совпадают, вероятнее всего, Вы используете неверный приватный ключ.
Решений здесь может быть несколько, вот, некоторые из них:
1. Попробовать найти верный приватный ключ и повторить попытку;
2. Сгенерировать новый CSR запрос с новым приватным ключом и отправить запрос на перевыпуск сертификата.

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

Одним из таких партнеров является компания ЛидерТелекм, первая в России получившая статус Symantec WSS специалист, а также первый и единственный в РФ и странах СНГ стратегически партнер Comodo.

В компании ЛидерТелеком Вы можете приобрести такие SSL-сертификаты, как:
Comodo SSL- сертификаты: http://www.instantssl.su/
UCC SAN – сертификаты: http://www.getucc.ru/
Thawte сертификаты: http://www.thawte.su/
Symantec (Verisign) сертификаты: http://symantec.leadertelecom.ru/


Offline

yamaoto

 


#1
Оставлено
:

9 октября 2014 г. 12:36:14(UTC)

yamaoto

Статус: Новичок

Группы: Участники

Зарегистрирован: 09.10.2014(UTC)
Сообщений: 3
Российская Федерация
Откуда: Якутск

При попытке получения доступа к секретному ключу происходит ошибка:
System.Security.Cryptography.CryptographicException: Неправильный параметр набора ключей.
at CryptoPro.Sharpei.CPUtils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)

А именно в том случае если код запущен в сервисе WCF внутри ASP.NET сайта.

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

Пробовал получить доступ как из хранилища сертификатов стандартными как средствами

Код:


var store = new X509Store(StoreName.My, location);
store.Open(OpenFlags.ReadOnly);
var certs = store.Certificates.Cast<X509Certificate2>().Where(crt =>crt.SerialNumber ==serialNumber.Trim()).ToList();
var cert = certs[0];
if (!CryptoHelper.IsGostCertificate(cert))
	throw new SecurityException(string.Format("Certificate '{0}' is cant' use for GOST algorithms", cert.Subject));
if (!cert.HasPrivateKey)
{
	throw new SecurityException(string.Format("Certificate '{0} has no private key", cert.Subject));
}
var gostCert = cert.PrivateKey as Gost3410CryptoServiceProvider;

так и через Gost3410CryptoServiceProvider

Код:


var parameters = new CspParameters(75, cryptoProviderName, containerName);
parameters.Flags = CspProviderFlags.UseExistingKey | CspProviderFlags.NoPrompt | CspProviderFlags.UseMachineKeyStore;
parameters.KeyPassword = password;

var provider = new Gost3410CryptoServiceProvider(parameters);

Сертификаты установлены в хранилище компьютера (проверял кучу раз)
Ключ лежит в eToken Java (так же пробовал скопировать его в хранилище реестра криптопро — тот же эффект)
Пробовал запуск пула приложений IIS от имени администратора которым заходил сам, от имени NETWORK_SERVICE, и стандартным пользователем пула

в ветке реестра нет чего-либо

Код:

HKEY_LOCAL_MACHINESOFTWARECrypto ProSettingsKeys

а в ветке

Код:

HKEY_LOCAL_MACHINESOFTWARECrypto ProSettingsUsersS-1-5-21-***-500

есть разделы KeyDevices и Random
Третий день уже разбираюсь в чем суть, голова уже не варит d'oh!

Параметры системы:

  • Приложение работает на .Net 4.0
  • Windows Server 2008R2 Standard x64
  • IIS 7.5
  • КриптоПро CSP 3.6.7777 (версия ядра СКЗИ 3.6.5365 КС1)
  • КриптоПро .Net 1.0.5320.0
  • Лицензии КриптоПро все тестовые, до декабря
  • На сервере присутствует VipNet и SecretNet


Вверх


Online

Андрей Писарев

 


#2
Оставлено
:

9 октября 2014 г. 13:15:47(UTC)

Андрей *

Статус: Сотрудник

Группы: Участники

Зарегистрирован: 26.07.2011(UTC)
Сообщений: 11,757
Мужчина
Российская Федерация

Сказал «Спасибо»: 451 раз
Поблагодарили: 1840 раз в 1423 постах

Криптопровайдер от ОАО «Информационные Технологии и Коммуникационные Системы» — обязателен?

Техническую поддержку оказываем тут
Наша база знаний


Вверх

WWW


Offline

yamaoto

 


#3
Оставлено
:

9 октября 2014 г. 17:35:43(UTC)

yamaoto

Статус: Новичок

Группы: Участники

Зарегистрирован: 09.10.2014(UTC)
Сообщений: 3
Российская Федерация
Откуда: Якутск

Автор: Андрей * Перейти к цитате

Криптопровайдер от ОАО «Информационные Технологии и Коммуникационные Системы» — обязателен?

Да, обязателен.

Проблемы могут быть из-за его несовместимости с КриптоПро?


Вверх


Offline

yamaoto

 


#4
Оставлено
:

13 октября 2014 г. 11:16:31(UTC)

yamaoto

Статус: Новичок

Группы: Участники

Зарегистрирован: 09.10.2014(UTC)
Сообщений: 3
Российская Федерация
Откуда: Якутск

Попробовали запустить на новой машине MS WS2008R2 Standard x64 en без VipNet’a SecretNet
выходит таже самая ошибка

Код:


System.Security.Cryptography.CryptographicException: Keyset does not exist
at CryptoPro.Sharpei.CPUtils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
at CryptoPro.Sharpei.CPUtils.GetKeyPairHelper(CPCspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandleCP& safeProvHandle, SafeKeyHandleCP& safeKeyHandle)
at CryptoPro.Sharpei.Gost3410CryptoServiceProvider.GetKeyPair()

ключ находится в реестре компьютера, сертификат тоже установлен в «личное» компьютера
ну и как было в предыдущей машине — этот же код запущенный вне IIS работает безупречно.

скриншот сертификатов:
скрин

проверка сертификата:
скрин2

Код:


Check container succeed        	no errors were detected
Private key container          	
  name                         	websrv3
  unique name                  	REGISTRY\websrv3
  FQCN                         	\.REGISTRYwebsrv3
  container integrity check    	succeed
Exchange key                   	available
  public key export            	succeed
  public key import            	succeed
  signing                      	succeed
  verifying                    	succeed
  exchange key agreement       	succeed
  key export                   	allowed
  algorithm                    	GOST R 34.10-2001 DH
                               	GOST R 34.10-2001, default exchange parameters
                               	GOST R 34.11-94, default parameters
  certificate in container     	match private key
  certificate in store         	My
                               	  E=websrv3, CN=websrv3, OU=websrv3, O=websrv3, L=websrv3, S=websrv3, C=RU
                               		    REGISTRY\websrv3; Crypto-Pro GOST R 34.10-2001 Cryptographic Service Provider; 75
                               	REQUEST
                               	  E=websrv3, CN=websrv3, OU=websrv3, O=websrv3, L=websrv3, C=RU
                               		    REGISTRY\websrv3; Crypto-Pro GOST R 34.10-2001 Cryptographic Service Provider; 75
  certificate name             	websrv3
  subject                      	E=websrv3, CN=websrv3, OU=websrv3, O=websrv3, L=websrv3, S=websrv3, C=RU
  issuer                       	E=support@cryptopro.ru, C=RU, L=Moscow, O=CRYPTO-PRO LLC, CN=CRYPTO-PRO Test Center 2
  valid from                   	Sunday, October 12, 2014 11:07:33 PM
  valid to                     	Monday, October 12, 2015 11:17:33 PM
  serial number                	1200 005E 3F83 E3E1 9085 A458 8F00 0000 005E 3F
Signature key                  	not available
  keys loading                 	succeed

Вверх


Offline

Максим Коллегин

 


#5
Оставлено
:

16 октября 2014 г. 12:45:12(UTC)

Максим Коллегин

Статус: Сотрудник

Группы: Администраторы

Зарегистрирован: 12.12.2007(UTC)
Сообщений: 6,259
Мужчина
Откуда: КРИПТО-ПРО

Сказал «Спасибо»: 21 раз
Поблагодарили: 661 раз в 584 постах

Дайте учетке IIS полный доступ к контейнеру ключей. Обсуждалось неоднократно.

Знания в базе знаний, поддержка в техподдержке


Вверх

WWW


Offline

Максим Коллегин

 


#6
Оставлено
:

13 июля 2015 г. 14:14:59(UTC)

Максим Коллегин

Статус: Сотрудник

Группы: Администраторы

Зарегистрирован: 12.12.2007(UTC)
Сообщений: 6,259
Мужчина
Откуда: КРИПТО-ПРО

Сказал «Спасибо»: 21 раз
Поблагодарили: 661 раз в 584 постах

Написал статью в FAQ

Знания в базе знаний, поддержка в техподдержке


Вверх

WWW


Offline

STP

 


#7
Оставлено
:

24 февраля 2016 г. 10:36:23(UTC)

STP

Статус: Новичок

Группы: Участники

Зарегистрирован: 24.02.2016(UTC)
Сообщений: 2
Российская Федерация
Откуда: Москва

Коллеги, у меня аналогичная проблема
При попытке доступа из webAPP получаю ошибку «Неправильный параметр набора ключей«
Всё настроено по FAQ

ПО:
Win2008R2
КП CSP 3.6.6497 КС2
Rutoken

Замечания:
Поигравшись выяснил, что есть баг в КП CSP 3.6 КС2 при назначении прав на закрытые ключи.
Так как КС2 хранит ключи в службе хранения ключей, назначаю права через оснастку Сертифиакты-ЛокальныйКомпьютер-сертификат-«управление закрытыми ключами». Но после нажатия кнопок «Применить» или «ок» слетают заданные права (при повторном открытии окна с параметрами доступа там дефолтные настройки). При этом если не закрывать оснастку Сертификаты, то webApp начинает работать как должен.

Какие могут быть мыли как это исправить?


Вверх


Offline

Максим Коллегин

 


#8
Оставлено
:

24 февраля 2016 г. 11:53:57(UTC)

Максим Коллегин

Статус: Сотрудник

Группы: Администраторы

Зарегистрирован: 12.12.2007(UTC)
Сообщений: 6,259
Мужчина
Откуда: КРИПТО-ПРО

Сказал «Спасибо»: 21 раз
Поблагодарили: 661 раз в 584 постах

Автор: STP Перейти к цитате

Поигравшись выяснил, что есть баг в КП CSP 3.6 КС2 при назначении прав на закрытые ключи.
Так как КС2 хранит ключи в службе хранения ключей, назначаю права через оснастку Сертифиакты-ЛокальныйКомпьютер-сертификат-«управление закрытыми ключами». Но после нажатия кнопок «Применить» или «ок» слетают заданные права (при повторном открытии окна с параметрами доступа там дефолтные настройки). При этом если не закрывать оснастку Сертификаты, то webApp начинает работать как должен.

Какие могут быть мыли как это исправить?

Какая версия CSP 3.6? В 3.9 пробовали?

Знания в базе знаний, поддержка в техподдержке


Вверх

WWW


Offline

STP

 


#9
Оставлено
:

24 февраля 2016 г. 12:31:31(UTC)

STP

Статус: Новичок

Группы: Участники

Зарегистрирован: 24.02.2016(UTC)
Сообщений: 2
Российская Федерация
Откуда: Москва

Версия КП CSP 3.6.6497 КС2 (СКЗИ 3.6.5359), данная версия нам задана в рамках большего проекта по внедрению уц.
В 3.9 не пробовали.
На предыдущей инсталляции win2003R2 стоит КП 3.6.6497 KC1, там такой проблемы нет.


Вверх


Offline

alexvg75

 


#10
Оставлено
:

14 июня 2016 г. 11:19:09(UTC)

alexvg75

Статус: Новичок

Группы: Участники

Зарегистрирован: 14.06.2016(UTC)
Сообщений: 1
Российская Федерация

Доброго дня!
Столкнулись с той же проблемой. При запуске вебсервера от локального пользователя подписи успешно добавляются, но если настроить запуск вебсервера как службы, то выдает ошибку.
При попытке следовать по шагам описанным для IIS, на этапе установки прав для доступа к закрытым ключам получаем тоже, что описал STP — права сбрасываются.
Windows 7
КриптоПРО 3.9.8001 КС1
Установлен xampp и приложение, которое должно подписывать документы. Нужен запуск приложения через службу, при этом не важно будет ли это апач или IIS.
Было бы очень замечательно, если бы кто-то смог поделился мыслями, опытом, путями обхода. Как я понимаю вся проблема в правах на закрытый ключ.
Заранее большое спасибо за любые идеи.


Вверх

Пользователи, просматривающие эту тему

Guest

Быстрый переход
 

Вы не можете создавать новые темы в этом форуме.

Вы не можете отвечать в этом форуме.

Вы не можете удалять Ваши сообщения в этом форуме.

Вы не можете редактировать Ваши сообщения в этом форуме.

Вы не можете создавать опросы в этом форуме.

Вы не можете голосовать в этом форуме.

First of all, I’ve seen this thread but it’s unrelated and having different issue.

I have the following settings fragment in my Kafka properties file:

ssl.keystore.type=PEM
ssl.keystore.key=/path/to/private.key
ssl.keystore.certificate.chain=/path/to/certificate.pem

ssl.truststore.type=PEM
ssl.truststore.certificates=/path/to/ca.pem

ssl.endpoint.identification.algorithm=

Note that ssl.endpoint.identification.algorithm is used because single-server certificate is used for each server in a cluster, therefore I have to bypass SSL hostname verification this way.

When starting Kafka, I am getting the following:

org.apache.kafka.common.KafkaException: org.apache.kafka.common.errors.InvalidConfigurationException: Invalid PEM keystore configs
at org.apache.kafka.common.network.SaslChannelBuilder.configure(SaslChannelBuilder.java:184)
at org.apache.kafka.common.network.ChannelBuilders.create(ChannelBuilders.java:192)
at org.apache.kafka.common.network.ChannelBuilders.serverChannelBuilder(ChannelBuilders.java:107)
at kafka.network.Processor.<init>(SocketServer.scala:853)
at kafka.network.SocketServer.newProcessor(SocketServer.scala:442)
at kafka.network.SocketServer.$anonfun$addDataPlaneProcessors$1(SocketServer.scala:299)
at scala.collection.immutable.Range.foreach$mVc$sp(Range.scala:190)
at kafka.network.SocketServer.addDataPlaneProcessors(SocketServer.scala:297)
at kafka.network.SocketServer.$anonfun$createDataPlaneAcceptorsAndProcessors$1(SocketServer.scala:262)
at kafka.network.SocketServer.$anonfun$createDataPlaneAcceptorsAndProcessors$1$adapted(SocketServer.scala:259)
at scala.collection.IterableOnceOps.foreach(IterableOnce.scala:563)
at scala.collection.IterableOnceOps.foreach$(IterableOnce.scala:561)
at scala.collection.AbstractIterable.foreach(Iterable.scala:919)
at kafka.network.SocketServer.createDataPlaneAcceptorsAndProcessors(SocketServer.scala:259)
at kafka.network.SocketServer.startup(SocketServer.scala:131)
at kafka.server.KafkaServer.startup(KafkaServer.scala:285)
at kafka.Kafka$.main(Kafka.scala:109)
at kafka.Kafka.main(Kafka.scala)
Caused by: org.apache.kafka.common.errors.InvalidConfigurationException: Invalid PEM keystore configs
Caused by: org.apache.kafka.common.errors.InvalidConfigurationException: No matching PRIVATE KEY entries in PEM file

Thing is — private.key, certificate.pem and ca.pem are valid files and working with other applications/client libraries. Out of them I used to create keystore/truststore and it works fine. When using keystore/truststore, I’ve also used these 3 files to connect to Kafka from Python and it worked just fine. I confirm these files are valid and have no issues with other applications.

Also note that private key is PKCS#8 type, which is expected by Kafka:

-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----

What am I doing wrong?

This is a quick howto post that can help not only penetration testers, but also network engineers, administrators and other specialists who work with network equipment, old storages, embedded systems, kiosk devices, and variety of other legacy systems with SSH interface (tcp/22).

We are going talk about SSH compatibility issues and those pesky SSH unable to negotiate login errors, No matching host key found errors and more. And in the end we will present solution for fixing all of there errors once and for all.

  • Introduction
  • The problem
  • SSH login error examples
    • No matching key exchange method found. Their offer: diffie-hellman-group1-sha1
    • No matching cipher found. Their offer: aes256-cbc,aes192-cbc,aes128-cbc,3des-cbc
    • No matching host key type found. Their offer: ssh-dss
    • DH GEX group out of range
  • Ultimate SSH login solution (fix everything)
  • Final words

Introduction

Since this is website is primarily about pentesting, I’m going to describe the issue from a perspective of a penetration tester.

One of the typical activities performed during infrastructure penetration tests are login attacks against SSH interfaces (aka. SSH login bruteforcing).

The idea behind SSH login bruteforcing is to identify systems and devices in the network configured with weak and/or default credentials.

There always happen to be some systems in the network that can be broken into this way. And this is true even for mature environments. Pentesters typically find these cases using automated tools such as:

  • Metasploit
  • Medusa
  • Hydra
  • Nmap

Now, the larger the environment, the higher is the number of valid credentials that are usually found. The following list is definitely not a rarity to find in a mid-size or larger environment:

SSH login bruteforce with Medusa

But before reporting any of these findings, we should first verify them. Some of the results might be false positives and it would also look nice in the report if we managed to identify what all those systems and devices are.

So how do we do that? I don’t know how you do it, but I typically manually inspect every single instance using the standard ssh client (OpenSSH) that is available in my system (usually Kali Linux) and examine each case by hand.

The problem

But the problem is this: Many times the SSH client fails to connect to the remote system due to a SSH negotiation error. Some of the typical error messages are:

  • No matching cipher found. Their offer: aes256-cbc,aes192-cbc,aes128-cbc,3des-cbc
  • No matching key exchange method found. Their offer: diffie-hellman-group1-sha1
  • No matching host key type found. Their offer: ssh-dss
  • DH GEX group out of range

For example:

# ssh [email protected]
Unable to negotiate with 10.5.21.113 port 22: no matching host key type found. Their offer: ssh-dss

SSH unable to negotiate: no matching host key type found. Their offer: ssh-dss

Why these errors happen? In most cases this is because we are connecting to legacy devices with outdated cryptography support – old Cisco routers, network equipment, outdated appliances and so on.

These legacy devices only support weak and outdated cipher suites, legacy key exchange methods etc. And our ssh client doesn’t trust those old methods any more (by default), so we cannot connect.

So what do we do?

Good news is that we can typically always find a workaround (solution) on the Internet which solves our particular problem connecting to the device – typically by adding an extra option to the ssh client on the command line:

# ssh -oHostKeyAlgorithms=+ssh-dss [email protected]

SSH unable to negotiate fix

But this approach is tiresome and soon can become exhausting, especially if we have many systems to check and if there are many different devices throwing different errors.

Let’s review some of these typical problems and their workarounds, before jumping to the solution.

SSH login error examples

Here are some of the typical SSH login compatibility issues with their workarounds.

No matching key exchange method found. Their offer: diffie-hellman-group1-sha1

Typical SSH error message:

# ssh [email protected]
Unable to negotiate with 10.200.180.62 port 22: no matching key exchange method found. Their offer: diffie-hellman-group1-sha1

Workaround (found here):

# ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 [email protected]

No matching cipher found. Their offer: aes256-cbc,aes192-cbc,aes128-cbc,3des-cbc

Typical SSH error message:

# ssh [email protected]
Unable to negotiate with 192.168.2.44 port 22: no matching cipher found. Their offer: aes256-cbc,aes192-cbc,aes128-cbc,3des-cbc

Workaround (found here):

# ssh -c aes256-cbc [email protected]

No matching host key type found. Their offer: ssh-dss

Typical SSH error message:

# ssh [email protected]
Unable to negotiate with 192.168.2.100 port 22: no matching host key type found. Their offer: ssh-dss

Workaround (found here or here):

# ssh -oHostKeyAlgorithms=+ssh-dss [email protected]

DH GEX group out of range

Typical SSH error message:

# ssh [email protected]
ssh_dispatch_run_fatal: Connection to 10.2.100.41 port 22: DH GEX group out of range

Workaround (found here or here):

# ssh -o KexAlgorithms=diffie-hellman-group1-sha1,[email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1 [email protected]

Sometimes these workarounds solve one problem only to discover that there is yet another / different problem afterwards which we have to google again and add another command line option.

But no more! Here’s how we can solve all these SSH login negotiation problems once and for all.

Ultimate SSH login solution (fix everything)

To fix all these SSH compatibility issues, we can simply temporarily enable all legacy cryptography methods that our SSH client currently supports. That means enable all:

  • Message authentication codes (MACs)
  • Key exchange methods
  • Host key algorithms
  • Ciphers

To get the list of all supported algorithms, ciphers and methods that our SSH client currently supports, we can use the ‘-Q’ option like this:

ssh -Q mac
ssh -Q kex
ssh -Q key
ssh -Q cipher

For example:

List of supported Machine Authentication Codes in SSH client

And now all we have to do is to re-format it a bit and put it into our SSH client configuration file in our HOME folder ~/.ssh/config.

So, here is the ultimate fix for all SSH login negotiation errors:

{
echo -n 'Ciphers '
ssh -Q cipher | tr 'n' ',' | sed -e 's/,$//'; echo

echo -n 'MACs '
ssh -Q mac | tr 'n' ',' | sed -e 's/,$//'; echo

echo -n 'HostKeyAlgorithms '
ssh -Q key | tr 'n' ',' | sed -e 's/,$//'; echo

echo -n 'KexAlgorithms '
ssh -Q kex | tr 'n' ',' | sed -e 's/,$//'; echo

} >> ~/.ssh/config

The command above will add the following options to your SSH client configuration:

Ciphers 3des-cbc,aes128-cbc,aes192-cbc,aes256-cbc,[email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],[email protected]
MACs hmac-sha1,hmac-sha1-96,hmac-sha2-256,hmac-sha2-512,hmac-md5,hmac-md5-96,[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected]
HostKeyAlgorithms ssh-ed25519,[email protected],ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,[email protected],[email protected],[email protected],[email protected],[email protected]
KexAlgorithms diffie-hellman-group1-sha1,diffie-hellman-group14-sha1,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group-exchange-sha256,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,curve25519-sha256,[email protected],[email protected]

Depending on your particular SSH client version it may look a little different, but the point is that it will enable ALL methods and ciphers that your current SSH client supports.

Now we should be able to connect to any legacy device or system on the network without any problem.

Final words

Make sure that this arrangement is only temporary – do not ever use this on a production system as a long term solution. Make sure to revert the changes once you don’t need them any more.

The solution presented here works by enabling all ciphers, key exchange methods and algorithms that were disabled in our OpenSSH client due to their security flaws and weaknesses.

In case this solution still hasn’t fixed your particular SSH negotiation login problem, you simply have to get another (older) version of the OpenSSH client or get another SSH client.

If this post was useful for you and you would like more tips like this, please subscribe to our mailing list and follow us on Twitter and Facebook and get notified about new additions!

Certificate installation on Apache webserver at times triggers the error message “Certificate routines:X509_check_private_key:key values mismatch”.

This usually happens during an Apache service restart.

As a part of our Server Management Services, we help our Customers to fix SSL related errors regularly.

Let us today discuss the possible causes and fixes for this error.

What causes “certificate routines:X509_check_private_key:key values mismatch” error?

As discussed earlier, restart of the Apache service while installing a certificate on the webserver at times yield a key values mismatch error. A typical error message looks like the one below:

[Fri Mar 07 14:59:57 2014] [error] SSL Library Error: 185073780 error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch

The most common reason for this error include

  1. Private key mismatch during the restart of the Apache service.
  2. Improper order of concatenation of the certificates

Private key mismatch

A major reason for this error is the usage of an incorrect private key along with the certificate received from the Certificate Authority. In reality, it implies that the private key in the VirtualHost section of the .conf file didn’t match the SSL Certificate in the same section.

For the webserver to accept a certificate, we should use the same private key along with the CSR code given for the certificate activation.

We can check whether the certificate matches the private key using the following OpenSSL commands:

openssl x509 -in /path/to/certificate.crt -noout -modulus | openssl sha1
openssl rsa -in /path/to/private.key -noout -modulus | openssl sha1

Replace the file names in the commands with the exact one for the certificate and private key. The first command applies to the certificate file from the Certificate Authority. The second one is for the private key.

If the outputs of the commands differ, this means that the chosen private key does not match the certificate.

Thus we will need to find another private key file on the server. The command below  will help us with it:

find / -name “*.key”

This command will find all files on the server with .key extensions. Once the keys are found, check their moduli using the OpenSSL rsa command listed above to locate one that matches.

If a private key with a modulus matching the certificate cannot be found, we need to generate a new CSR code and reissue the certificate.

Sometimes, we can fix the issue by creating a new CSR from the existing private key file. The command for this operation is:

openssl req -new -key your_domain_com.key -out your_domain_com.csr

 Improper order of concatenation of the certificates

Prior to Apache version 2.4.8, SSLCertificateFile was extended to load intermediate CA certificates from the server certificate file as well. It allowed the certificate file to contain the certificate as well as intermediate certificates.

Thus, it is important to place the end-entity certificate for a domain as the first certificate in this file, while intermediate certificates should be placed lower starting from the one that signs the end-entity certificate. Otherwise,it triggers the key values mismatch error.

This order correct order should be as follows: end-entity certificate (your_domain.crt) -> first intermediate -> second intermediate -> root.

[Need any further assistance in fixing SSL errors? – We’re available 24*7]

Conclusion

In short, “Certificate routines:X509_check_private_key:key values mismatch” triggers during SSL certificate installation. Today, we saw how our Support Engineers fix this error.

unematt

Posts: 7
Joined: 2017/10/16 18:14:36

SSL issues

Hello, I am about to pull my hair out trying to solve this ssl issue!! I have a SSL cert from comodo and I’ve installed it in /etc/pki/tls. I’ve added the entries into the vhost file for my site but when its enabled, I get SSL Library Error: error:140A80B1:SSL routines:SSL_CTX_check_private_key:no certificate assigned. I’ve checked the cert and they key matches the crt file and the MD5 hash.

Any help would be awesome!!

httpd.conf:

Code: Select all

ServerRoot "/opt/rh/httpd24/root/etc/httpd"
Listen 80
#Listen 443
Include conf.modules.d/*.conf
User apache
Group apache
ServerAdmin root@localhost
DocumentRoot "/opt/rh/httpd24/root/var/www/html"
<Directory "/opt/rh/httpd24/root/var/www">
Options +SymLinksIfOwnerMatch
    AllowOverride all
    # Allow open access:
    Require all granted
</Directory>

# Further relax access to the default document root:
<Directory "/opt/rh/httpd24/root/var/www/html">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks
Options +SymLinksIfOwnerMatch
    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    AllowOverride all

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
    <IfModule dir_module>
    DirectoryIndex index.php index.html index.htm home.html home.htm
    <Files ".ht*">
    Require all denied
</Files>
</IfModule>
</Directory>
ErrorLog "logs/error_log"
LogLevel warn

<IfModule log_config_module>
    #
    # The following directives define some format nicknames for use with
    # a CustomLog directive (see below).
    #
    LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"" combined
    LogFormat "%h %l %u %t "%r" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i" %I %O" combinedio
    </IfModule>

    #
    # The location and format of the access logfile (Common Logfile Format).
    # If you do not define any access logfiles within a <VirtualHost>
    # container, they will be logged here.  Contrariwise, if you *do*
    # define per-<VirtualHost> access logfiles, transactions will be
    # logged therein and *not* in this file.
    #
    #CustomLog "logs/access_log" common

    #
    # If you prefer a logfile with access, agent, and referer information
    # (Combined Logfile Format) you can use the following directive.
    #
    CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
ScriptAlias /cgi-bin/ "/opt/rh/httpd24/root/var/www/cgi-bin/"

</IfModule>
<Directory "/opt/rh/httpd24/root/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>
<IfModule mime_module>
TypesConfig /etc/mime.types
 AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz
 AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
</IfModule>
AddDefaultCharset UTF-8

<IfModule mime_magic_module>
    #
    # The mod_mime_magic module allows the server to use various hints from the
    # contents of the file itself to determine its type.  The MIMEMagicFile
    # directive tells the module where the hint definitions are located.
    #
    MIMEMagicFile conf/magic
</IfModule>
EnableSendfile on

# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
IncludeOptional conf.d/*.conf

vhost.conf:

Code: Select all

<Directory /usr/share/www>
        AllowOverride All
        Options FollowSymLinks
        Require all granted
        Order deny,allow
        Allow from all
<IfVersion < 2.4>
    Allow from all
</IfVersion>
<IfVersion >= 2.4>
    Require all granted
</IfVersion>
        # rewrite for backward compability of public links
        RedirectMatch "^/pydio_public/(.*)" "/pydio/public/$1"
</Directory>

<VirtualHost files.bencor.info:80>
        DocumentRoot "/usr/share/www"
        ServerName test.bencor.info
</VirtualHost>
<VirtualHost files.bencor.info:443>
        ServerName files.bencor.info
        ServerAdmin massimo.mucci@bencorinc.com
####### HOME PAGE: PYDIO #######
#       SSLEngine on
        SSLCertificateFile /etc/pki/tls/files_bencor_info.crt
        SSLCertificateKeyFile /etc/pki/tls/files_bencor_info.key
        SSLCertificateChainFile /etc/pki/tls/files_bencor_info.ca-bundle
        DocumentRoot /usr/share/www
        ErrorLog logs/rd_error_log
        TransferLog logs/rd_access_log
</VirtualHost>

Error:
[Wed Oct 18 15:23:48.663773 2017] [ssl:emerg] [pid 22528] AH02572: Failed to configure at least one certificate and key for files.bencor.info:443
[Wed Oct 18 15:23:48.663870 2017] [ssl:emerg] [pid 22528] SSL Library Error: error:140A80B1:SSL routines:SSL_CTX_check_private_key:no certificate assigned

Sorry for the long post, I know the config is a bit messy. I’m not sure if I’ve missed something small or not..


User avatar

avij

Retired Moderator
Posts: 3046
Joined: 2010/12/01 19:25:52
Location: Helsinki, Finland
Contact:

Re: SSL issues

Post

by avij » 2017/10/18 21:24:38

You have SSLEngine on commented out. Perhaps you should try enabling that.


unematt

Posts: 7
Joined: 2017/10/16 18:14:36

Re: SSL issues

Post

by unematt » 2017/10/18 21:45:57

I have that disabled so that apache starts. This site is up currently.


unematt

Posts: 7
Joined: 2017/10/16 18:14:36

Re: SSL issues

Post

by unematt » 2017/10/19 13:36:04

Also, heres the ssl.conf:

Code: Select all

# When we also provide SSL we have to listen to the 
# the HTTPS port in addition.
#
#Listen 443 https

##
##  SSL Global Context
##
##  All SSL configuration in this context applies both to
##  the main server and all SSL-enabled virtual hosts.
##

#   Pass Phrase Dialog:
#   Configure the pass phrase gathering process.
#   The filtering dialog program (`builtin' is a internal
#   terminal dialog) has to provide the pass phrase on stdout.
SSLPassPhraseDialog builtin

#   Inter-Process Session Cache:
#   Configure the SSL Session Cache: First the mechanism 
#   to use and second the expiring timeout (in seconds).
SSLSessionCache         shmcb:/opt/rh/httpd24/root/var/run/httpd/sslcache(512000)
SSLSessionCacheTimeout  300

#   Pseudo Random Number Generator (PRNG):
#   Configure one or more sources to seed the PRNG of the 
#   SSL library. The seed data should be of good random quality.
#   WARNING! On some platforms /dev/random blocks if not enough entropy
#   is available. This means you then cannot use the /dev/random device
#   because it would lead to very long connection times (as long as
#   it requires to make more entropy available). But usually those
#   platforms additionally provide a /dev/urandom device which doesn't
#   block. So, if available, use this one instead. Read the mod_ssl User
#   Manual for more details.
SSLRandomSeed startup file:/dev/urandom  256
SSLRandomSeed connect builtin
#SSLRandomSeed startup file:/dev/random  512
#SSLRandomSeed connect file:/dev/random  512
#SSLRandomSeed connect file:/dev/urandom 512

#
# Use "SSLCryptoDevice" to enable any supported hardware
# accelerators. Use "openssl engine -v" to list supported
# engine names.  NOTE: If you enable an accelerator and the
# server does not start, consult the error logs and ensure
# your accelerator is functioning properly. 
#
SSLCryptoDevice builtin
#SSLCryptoDevice ubsec

##
## SSL Virtual Host Context
##

<VirtualHost _default_:443>

# General setup for the virtual host, inherited from global configuration
#DocumentRoot "/var/www/html"
#ServerName www.example.com:443

# Use separate log files for the SSL virtual host; note that LogLevel
# is not inherited from httpd.conf.
ErrorLog logs/ssl_error_log
TransferLog logs/ssl_access_log
LogLevel warn

#   SSL Engine Switch:
#   Enable/Disable SSL for this virtual host.
#SSLEngine on

#   SSL Protocol support:
# List the enable protocol levels with which clients will be able to
# connect.  Disable SSLv2 access by default:
SSLProtocol all -SSLv2

#   SSL Cipher Suite:
#   List the ciphers that the client is permitted to negotiate.
#   See the mod_ssl documentation for a complete list.
SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5

#   Speed-optimized SSL Cipher configuration:
#   If speed is your main concern (on busy HTTPS servers e.g.),
#   you might want to force clients to specific, performance
#   optimized ciphers. In this case, prepend those ciphers
#   to the SSLCipherSuite list, and enable SSLHonorCipherOrder.
#   Caveat: by giving precedence to RC4-SHA and AES128-SHA
#   (as in the example below), most connections will no longer
#   have perfect forward secrecy - if the server's key is
#   compromised, captures of past or future traffic must be
#   considered compromised, too.
#SSLCipherSuite RC4-SHA:AES128-SHA:HIGH:MEDIUM:!aNULL:!MD5
#SSLHonorCipherOrder on 

#   Server Certificate:
# Point SSLCertificateFile at a PEM encoded certificate.  If
# the certificate is encrypted, then you will be prompted for a
# pass phrase.  Note that a kill -HUP will prompt again.  A new
# certificate can be generated using the genkey(1) command.
#SSLCertificateFile /etc/ssl/certs/files_bencor_info.crt

#   Server Private Key:
#   If the key is not combined with the certificate, use this
#   directive to point at the key file.  Keep in mind that if
#   you've both a RSA and a DSA private key you can configure
#   both in parallel (to also allow the use of DSA ciphers, etc.)
#SSLCertificateKeyFile /etc/ssl/certs/bencor.key

#   Server Certificate Chain:
#   Point SSLCertificateChainFile at a file containing the
#   concatenation of PEM encoded CA certificates which form the
#   certificate chain for the server certificate. Alternatively
#   the referenced file can be the same as SSLCertificateFile
#   when the CA certificates are directly appended to the server
#   certificate for convinience.
#SSLCertificateChainFile /etc/ssl/certs/files_bencor_info.ca-bundle ***

#   Certificate Authority (CA):
#   Set the CA certificate verification path where to find CA
#   certificates for client authentication or alternatively one
#   huge file containing all of them (file must be PEM encoded)
#SSLCACertificateFile /etc/ssl/certs/files_bencor_info.crt

#   Client Authentication (Type):
#   Client certificate verification type and depth.  Types are
#   none, optional, require and optional_no_ca.  Depth is a
#   number which specifies how deeply to verify the certificate
#   issuer chain before deciding the certificate is not valid.
#SSLVerifyClient require
#SSLVerifyDepth  10

#   Access Control:
#   With SSLRequire you can do per-directory access control based
#   on arbitrary complex boolean expressions containing server
#   variable checks and other lookup directives.  The syntax is a
#   mixture between C and Perl.  See the mod_ssl documentation
#   for more details.
#<Location />
#SSLRequire (    %{SSL_CIPHER} !~ m/^(EXP|NULL)/ 
#            and %{SSL_CLIENT_S_DN_O} eq "Snake Oil, Ltd." 
#            and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"} 
#            and %{TIME_WDAY} >= 1 and %{TIME_WDAY} <= 5 
#            and %{TIME_HOUR} >= 8 and %{TIME_HOUR} <= 20       ) 
#           or %{REMOTE_ADDR} =~ m/^192.76.162.[0-9]+$/
#</Location>

#   SSL Engine Options:
#   Set various options for the SSL engine.
#   o FakeBasicAuth:
#     Translate the client X.509 into a Basic Authorisation.  This means that
#     the standard Auth/DBMAuth methods can be used for access control.  The
#     user name is the `one line' version of the client's X.509 certificate.
#     Note that no password is obtained from the user. Every entry in the user
#     file needs this password: `xxj31ZMTZzkVA'.
#   o ExportCertData:
#     This exports two additional environment variables: SSL_CLIENT_CERT and
#     SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
#     server (always existing) and the client (only existing when client
#     authentication is used). This can be used to import the certificates
#     into CGI scripts.
#   o StdEnvVars:
#     This exports the standard SSL/TLS related `SSL_*' environment variables.
#     Per default this exportation is switched off for performance reasons,
#     because the extraction step is an expensive operation and is usually
#     useless for serving static content. So one usually enables the
#     exportation for CGI and SSI requests only.
#   o StrictRequire:
#     This denies access when "SSLRequireSSL" or "SSLRequire" applied even
#     under a "Satisfy any" situation, i.e. when it applies access is denied
#     and no other module can change it.
#   o OptRenegotiate:
#     This enables optimized SSL connection renegotiation handling when SSL
#     directives are used in per-directory context. 
#SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
<Files ~ ".(cgi|shtml|phtml|php3?)$">
    SSLOptions +StdEnvVars
</Files>
<Directory "/var/www/cgi-bin">
    SSLOptions +StdEnvVars
</Directory>

#   SSL Protocol Adjustments:
#   The safe and default but still SSL/TLS standard compliant shutdown
#   approach is that mod_ssl sends the close notify alert but doesn't wait for
#   the close notify alert from client. When you need a different shutdown
#   approach you can use one of the following variables:
#   o ssl-unclean-shutdown:
#     This forces an unclean shutdown when the connection is closed, i.e. no
#     SSL close notify alert is send or allowed to received.  This violates
#     the SSL/TLS standard but is needed for some brain-dead browsers. Use
#     this when you receive I/O errors because of the standard approach where
#     mod_ssl sends the close notify alert.
#   o ssl-accurate-shutdown:
#     This forces an accurate shutdown when the connection is closed, i.e. a
#     SSL close notify alert is send and mod_ssl waits for the close notify
#     alert of the client. This is 100% SSL/TLS standard compliant, but in
#     practice often causes hanging connections with brain-dead browsers. Use
#     this only for browsers where you know that their SSL implementation
#     works correctly. 
#   Notice: Most problems of broken clients are also related to the HTTP
#   keep-alive facility, so you usually additionally want to disable
#   keep-alive for those clients, too. Use variable "nokeepalive" for this.
#   Similarly, one has to force some clients to use HTTP/1.0 to workaround
#   their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
#   "force-response-1.0" for this.
BrowserMatch "MSIE [2-5]" 
         nokeepalive ssl-unclean-shutdown 
         downgrade-1.0 force-response-1.0

#   Per-Server Logging:
#   The home of a custom SSL log file. Use this when you want a
#   compact non-error SSL logfile on a virtual host basis.
CustomLog logs/ssl_request_log 
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x "%r" %b"

</VirtualHost>                    

I left some things commented out as I have them in the vhost file.


dcrdev

Posts: 70
Joined: 2015/10/25 23:42:17

Re: SSL issues

Post

by dcrdev » 2017/10/19 14:49:29

The certificates you placed in /etc/pki/tls, did you copy them in there or move them? If the latter it’s likely you are using the incorrect selinux context; which would be an issue if you have selinux enabled.

Use the following to fix it:

Also your private key should really be in:

Your certs in:

Have you checked the permissions on both the private key and certificate, does the apache user have read access on them?

Other than that, would be helpful if you could provide a full log and also the output of:


unematt

Posts: 7
Joined: 2017/10/16 18:14:36

Re: SSL issues

Post

by unematt » 2017/10/19 15:04:36

I have SELinux disabled currently.

I moved the certs and keys into the locations you suggested and checked the permissions.

Code: Select all

[root@files tls]# ls -ls private/
total 8
4 -rwx------  1 apache apache 1704 Oct 18 10:27 files_bencor_info.key
4 -rw-------. 1 apache apache 1675 Mar  1  2017 localhost.key
[root@files tls]# ls -ls certs/
total 28
0 lrwxrwxrwx  1 apache apache   49 Mar  1  2017 ca-bundle.crt -> /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
0 lrwxrwxrwx  1 apache apache   55 Mar  1  2017 ca-bundle.trust.crt -> /etc/pki/ca-trust/extracted/openssl/ca-bundle.trust.crt
8 -rwx------  1 apache apache 4111 Feb 11  2014 files_bencor_info.ca-bundle
4 -rwx------  1 apache apache 2057 Oct 18 00:00 files_bencor_info.crt
0 drwx------  2 apache apache   85 Oct 18 10:25 keys.old
4 -rwx------. 1 apache apache 1468 Mar  1  2017 localhost.crt
4 -rwx------  1 apache apache  610 Aug  4 01:41 make-dummy-cert
4 -rwx------  1 apache apache 2516 Aug  4 01:41 Makefile
4 -rwx------  1 apache apache  829 Aug  4 01:41 renew-dummy-cert

Heres what systemctl says:

Code: Select all

[root@files httpd]# systemctl status httpd24-httpd -l
● httpd24-httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd24-httpd.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Thu 2017-10-19 09:52:17 CDT; 11s ago
  Process: 34588 ExecStop=/opt/rh/httpd24/root/usr/sbin/httpd-scl-wrapper $OPTIONS -k graceful-stop (code=exited, status=0/SUCCESS)
  Process: 34586 ExecStart=/opt/rh/httpd24/root/usr/sbin/httpd-scl-wrapper $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
 Main PID: 34586 (code=exited, status=1/FAILURE)

Oct 19 09:52:16 files.bencor.info systemd[1]: Starting The Apache HTTP Server...
Oct 19 09:52:16 files.bencor.info systemd[1]: httpd24-httpd.service: main process exited, code=exited, status=1/FAILURE
Oct 19 09:52:17 files.bencor.info httpd-scl-wrapper[34588]: httpd (no pid file) not running
Oct 19 09:52:17 files.bencor.info systemd[1]: Failed to start The Apache HTTP Server.
Oct 19 09:52:17 files.bencor.info systemd[1]: Unit httpd24-httpd.service entered failed state.
Oct 19 09:52:17 files.bencor.info systemd[1]: httpd24-httpd.service failed.

Uncommenting and adding the certs in the ssl.conf gave a different error:

Code: Select all

[root@files httpd]# systemctl status httpd24-httpd -l
● httpd24-httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd24-httpd.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Thu 2017-10-19 09:47:02 CDT; 6s ago
  Process: 34433 ExecStop=/opt/rh/httpd24/root/usr/sbin/httpd-scl-wrapper $OPTIONS -k graceful-stop (code=exited, status=1/FAILURE)
  Process: 34431 ExecStart=/opt/rh/httpd24/root/usr/sbin/httpd-scl-wrapper $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
 Main PID: 34431 (code=exited, status=1/FAILURE)

Oct 19 09:47:02 files.bencor.info systemd[1]: Starting The Apache HTTP Server...
Oct 19 09:47:02 files.bencor.info httpd-scl-wrapper[34431]: AH00526: Syntax error on line 116 of /opt/rh/httpd24/root/etc/httpd/conf.d/ssl.conf:
Oct 19 09:47:02 files.bencor.info httpd-scl-wrapper[34431]: SSLCertificateChainFile takes one argument, SSL Server CA Certificate Chain file ('/path/to/file' - PEM encoded)
Oct 19 09:47:02 files.bencor.info systemd[1]: httpd24-httpd.service: main process exited, code=exited, status=1/FAILURE
Oct 19 09:47:02 files.bencor.info httpd-scl-wrapper[34433]: AH00526: Syntax error on line 116 of /opt/rh/httpd24/root/etc/httpd/conf.d/ssl.conf:
Oct 19 09:47:02 files.bencor.info httpd-scl-wrapper[34433]: SSLCertificateChainFile takes one argument, SSL Server CA Certificate Chain file ('/path/to/file' - PEM encoded)
Oct 19 09:47:02 files.bencor.info systemd[1]: httpd24-httpd.service: control process exited, code=exited status=1
Oct 19 09:47:02 files.bencor.info systemd[1]: Failed to start The Apache HTTP Server.
Oct 19 09:47:02 files.bencor.info systemd[1]: Unit httpd24-httpd.service entered failed state.
Oct 19 09:47:02 files.bencor.info systemd[1]: httpd24-httpd.service failed.

dcrdev wrote:The certificates you placed in /etc/pki/tls, did you copy them in there or move them? If the latter it’s likely you are using the incorrect selinux context; which would be an issue if you have selinux enabled.

Use the following to fix it:

Also your private key should really be in:

Your certs in:

Have you checked the permissions on both the private key and certificate, does the apache user have read access on them?

Other than that, would be helpful if you could provide a full log and also the output of:


dcrdev

Posts: 70
Joined: 2015/10/25 23:42:17

Re: SSL issues

Post

by dcrdev » 2017/10/19 15:12:43

Ok so now we’re getting somewhere:

  • You have «***» at the end of SSLCertificateChainFile on line 116
  • Are you’re certificates pem encoded? If not: openssl x509 -inform der -in files_bencor_info.crt -out files_bencor_info.pem


unematt

Posts: 7
Joined: 2017/10/16 18:14:36

Re: SSL issues

Post

by unematt » 2017/10/19 15:43:52

I think they are PEM encoded, but no .pem file.

When I tried to encode them I got:

Code: Select all

[root@files certs]#  openssl x509 -inform der -in files_bencor_info.crt -out files_bencor_info.pem
unable to load certificate
140134402181024:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1199:
140134402181024:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:374:Type=X509


dcrdev

Posts: 70
Joined: 2015/10/25 23:42:17

Re: SSL issues

Post

by dcrdev » 2017/10/19 15:46:47

Ok can you run cat on the certificate and post the output here — obviously remove the actual encoded certificate portion; I’m just interested in the headers.

BTW did you check line 116? It shouldn’t have «***» at the end of it.


unematt

Posts: 7
Joined: 2017/10/16 18:14:36

Re: SSL issues

Post

by unematt » 2017/10/19 15:57:13

Yes, I removed the ***

I just tried leaving the SSLCertificateChainFile /etc/pki/tls/files_bencor_info.ca-bundle commented out

Code: Select all

Oct 19 10:45:07 files.bencor.info httpd-scl-wrapper[35321]: AH00526: Syntax error on line 100 of /opt/rh/httpd24/root/etc/httpd/conf.d/ssl.conf:
Oct 19 10:45:07 files.bencor.info httpd-scl-wrapper[35321]: SSLCertificateFile: file '/etc/pki/tls/files_bencor_info.crt' does not exist or is empty
Oct 19 10:45:07 files.bencor.info systemd[1]: httpd24-httpd.service: main process exited, code=exited, status=1/FAILURE
Oct 19 10:45:07 files.bencor.info httpd-scl-wrapper[35323]: AH00526: Syntax error on line 100 of /opt/rh/httpd24/root/etc/httpd/conf.d/ssl.conf:
Oct 19 10:45:07 files.bencor.info httpd-scl-wrapper[35323]: SSLCertificateFile: file '/etc/pki/tls/files_bencor_info.crt' does not exist or is empty
Oct 19 10:45:07 files.bencor.info systemd[1]: httpd24-httpd.service: control process exited, code=exited status=1

I know the file is not empty as I compared the files when talking to comodo about the cert issue.

The crt file has:

Code: Select all

[root@files httpd]# cat /etc/pki/tls/certs/files_bencor_info.crt 
-----BEGIN CERTIFICATE-----
Blah Blah

-----END CERTIFICATE-----

The ca-bundle file has the same contents but twice, including the begin cert header.


@soullivaneuh

On a new computer (nexy), I tried to import my main GPG key like that:

❯ keybase pgp export -q 04460cd228df9e0d42f07643992eb6fafd4e6361 --secret
▶ ERROR No matching keys found

As you can see, it does not work. But I can still download the private key from the keybase.io app and import it manually. It makes no sense to me, what is the issue?

Plus, it seems I still can’t use it directly, for exemple for passwordstore:

❯ pass path/to/auth
gpg: decryption failed: No secret key

But the needed key is here:

sec   rsa4096 2019-03-06 [SC]
      04460CD228DF9E0D42F07643992EB6FAFD4E6361
uid           [ unknown] Sullivan Senechal <soullivaneuh@gmail.com>
uid           [ unknown] Sullivan Senechal <sullivan.senechal@gmail.com>
ssb   rsa2048 2019-03-06 [E] [expires: 2027-03-04]
ssb   rsa2048 2019-03-06 [SA] [expires: 2027-03-04]

FYI: All works for the other key.

@maxtaco

Please keybase log send . CC @zapu

@soullivaneuh

@maxtaco Here it is: 6b770312cc9ce6a2500b521c.

@soullivaneuh

So I finally removed my second key and then did:

keybase pgp export | gpg --import
keybase pgp export --secret | gpg --import

It works and «solve» my problem.

If you don’t find any issue from my log, feel free to close this one. 👍

@zapu

Sorry, no clue what went wrong here. The log does not reach that far back to show the failures you’ve experienced. I also tried this on a fresh account with different combinations of keys and could import/export successfully.

@QimatLuo

Got the same issue. my log id: 05cd7600b630fad82befcb1c

@kanutope

I have got the same issue on my ‘older’ first installation. Can’t find a trace of a ‘second key’.

Executing ‘keybase pgp export -s’ and comparing the ‘keybase.service.log’ files on both installation, I find a difference:

old computer/installation (▶ ERROR No matching keys found)

skb_keyring.go:123] 60fa + Loading SKB keyring: . . ./Keybase/secretkeys.pawawa.mpack
skb_keyring.go:181] 60fc | Indexed 2 secret keys

new computer/installation

skb_keyring.go:123] 8bdc + Loading SKB keyring: . . ./Keybase/secretkeys.pawawa.mpack
skb_keyring.go:181] 8bde | Indexed 3 secret keys

@zapu

Hey @kanutope thank you for reaching out to us.

Was the key in question imported into Keybase using the keybase.io website or keybase pgp import --push-secret? Can you send the logs (using keybase log send) immediately after using the command on both «old computer» and «new computer» and pasting log IDs here? Thank you.

@kanutope

Hey @zapu thanks for your swift reply :-)

  • pgp key was (re)created on the ‘NEW’ installation.
  • I have repeated the pgp export -s, on both NEW (successful) and OLD (failing) installation.
  • log sent (NEW): 77d27f6eafaece1ae5c60f1c .
  • log sent (OLD): da3e7e25bef99eca2a7f601c .

Cheers!

@maxtaco

I am pretty sure this is the expected behavior. The pgp private key isn’t server synced.

@zapu

So there are two keychains available for every Keybase user: one that is local, and one that stores keys on Keybase server, encrypted with user passphrase. If you only synced / imported to local keychain on machine ‘NEW’ (when generating it), it will not be automatically available on other machines.

@maxtaco

Try keybase pgp push-private and keybase pgp pull-private

@kanutope

Hi @maxtaco
I did keybase pgp push-private on NEW and keybase pgp pull-private on OLD.
private/.keys/pgp created successfully after ‘push’.
With ‘pull’, ran into ‘▶ ERROR GPG error: exit status 2’.
Made keybase log send => a1a28b061ec8820fa4c58a1c .
I am investigating the server.log file — there might be something wrong with my GnuPG installation.

@kanutope

Looking into keybase.server.log file, I saw /usr/local/bin/gpg --no-tty --import was failing.
I went to …/private/.keys/pgp, and tried ‘manual’ import gpg --import < <key>.asc, and that one succeeded, after requesting for my passphrase.

@maxtaco

If our small company were 10x the size we could accommodate every breaking change of every minor version of gpg on every platform under every package manager. But alas.

@kanutope

hi @maxtaco — I don’t know whether it has to do with the gpg version. I checked again, and the ‘manual’ import succeeded thanks to the GPG_TTY variable being set (independently of the --no-tty option.
Thanks for your support. Cheers!
Just a last observation: I’ve gotten my secret PGP key transferred to the OLD machine, though the keybase pgp export -s still returns the «No matching keys found» error.

@kanutope

  • solved *

Revoking the OLD machine and scratching the entire Keybase user data did not resolve the issue.

Though, got it working after reading through keybase/keybase-issues#2793 and performing
gpg --export-secret-key 1A9342D586065111 | keybase pgp import --push-secret.
Message returned:
▶ INFO Key 01018488fbae49e539f76f2f198d252bac7223ca8cdd2b8bef51cd1d364962c039930a already exists. Only importing the private key.

@matt0x6F

Let me be the first to say, there is something absolutely wrong here.

Log ID: a6f0f31d67eccd8373ae641c

I tried importing my key several times and it works non-deterministically.

~  97  21:19:38  ✔  keybase pgp export -q 36DF664C07A67A08 --secret | gpg --allow-secret-key-import
gpg: WARNING: no command supplied.  Trying to guess what you mean ...
▶ ERROR No matching keys found
gpg: processing message failed: Unknown system error
~  98  21:21:39  ↵ 2|2  keybase pgp export -q 36DF664C07A67A08 --secret | gpg --allow-secret-key
gpg: WARNING: no command supplied.  Trying to guess what you mean ...
▶ ERROR No matching keys found
gpg: processing message failed: Unknown system error
~  99  21:21:46  ↵ 2|2  keybase pgp export -q 36DF664C07A67A08 --secret | gpg --allow-secret-key --import
gpg: key 36DF664C07A67A08: "Matt Ouille <matthew.ouille@gmail.com>" not changed
gpg: key 36DF664C07A67A08/36DF664C07A67A08: error sending to agent: Inappropriate ioctl for device
gpg: error building skey array: Inappropriate ioctl for device
gpg: Total number processed: 1
gpg:              unchanged: 1
gpg:       secret keys read: 1
~  100  21:22:16  ↵ 0|2  export GPG_TTY=$(tty)
~  101  21:22:39  ✔  vim ~/.zshenv
~  102  21:22:54  ✔  keybase pgp export -q 36DF664C07A67A08 --secret | gpg --allow-secret-key --import
▶ ERROR No matching keys found
gpg: no valid OpenPGP data found.
gpg: Total number processed: 0
~  103  21:23:00  ↵ 2|2  keybase pgp export -q 36DF664C07A67A08 --secret | gpg --allow-secret-key --import
▶ ERROR No matching keys found
gpg: no valid OpenPGP data found.
gpg: Total number processed: 0
~  103  21:23:03  ↵ 2|2  keybase pgp export -q 36DF664C07A67A08 --secret | gpg --allow-secret-key --import
▶ ERROR No matching keys found
gpg: no valid OpenPGP data found.
gpg: Total number processed: 0
~  103  21:23:04  ↵ 2|2  keybase pgp export -q 36DF664C07A67A08 --secret | gpg --allow-secret-key --import
~  103  21:23:12  ↵ 2|2  keybase pgp export -q 36DF664C07A67A08 --secret | gpg --allow-secret-key --import
▶ ERROR No matching keys found
gpg: no valid OpenPGP data found.
gpg: Total number processed: 0
~  103  21:23:14  ↵ 2|2  keybase pgp export -q 36DF664C07A67A08 --secret | gpg --allow-secret-key --import
▶ ERROR No matching keys found
gpg: no valid OpenPGP data found.
gpg: Total number processed: 0
~  103  21:23:16  ↵ 2|2  keybase pgp export -q 36DF664C07A67A08 --secret | gpg --allow-secret-key --import
▶ ERROR No matching keys found
gpg: no valid OpenPGP data found.
gpg: Total number processed: 0
~  103  21:23:17  ↵ 2|2  keybase pgp export -q 36DF664C07A67A08 --secret | gpg --allow-secret-key --import
▶ ERROR No matching keys found
gpg: no valid OpenPGP data found.
gpg: Total number processed: 0
~  103  21:23:18  ↵ 2|2  keybase pgp export -q 36DF664C07A67A08 --secret | gpg --allow-secret-key --import
gpg: key 36DF664C07A67A08: "Matt Ouille <matthew.ouille@gmail.com>" not changed
gpg: key 36DF664C07A67A08: secret key imported
gpg: Total number processed: 1
gpg:              unchanged: 1
gpg:       secret keys read: 1
gpg:   secret keys imported: 1
~  103  21:23:46  ✔  keybase log send

@zapu

That seems similar to a bug in pgp decrypt that we have fixed previously. I’ll take a look, thank you.

@maxtaco

could also be a local pinentry/gpg misconfigure

i hate to ask for this @mattouille, but will do so anyway. please have some sympathy for us, gpg is basically impossible to support, given it breaks with every minor version and that every combination of platform, package manager and dotfiles provides additional bugs and misconfigurations, and demands further workarounds.

@maxtaco

(…also as @zapu says, there is a bug that we’ve recently fixed….)

@matt0x6F

@maxtaco I definitely have empathy for your situation and I apologize if I came off like I didn’t.

Some context
I use Keybase to manage my PGP key which signs all of my commits for work and another which signs my personal commits. Keybase has basically become an integral part of my development process both professionally and personally.

Yesterday my hard drive failed and I ended up having to rebuild my OS, which means going through the process of exporting my keys from Keybase. Normally this process is very smooth and predictable and I spent the better part of an hour messing with it before I figured out it was failing non-deterministically.

I’m not frustrated with Keybase, you all, or anything of the sort — just the scenario I was in. That’s the frustrated tone you’re reading.

I still love Keybase and I’m thankful every day for you all maintaining it.

I left off the most important part of all: I use Keybase PGP because I don’t like dealing with GPG.

@maxtaco

Understood, thanks @mattouille for the clarification! Hopefully the next build solves the issue in general. But for now, is the workaround of trying n times good enough for you to recover your important data?

BTW, I currently use keybase pgp push-private to sync my PGP private keys via KBFS. This would be useful in the case of a disk crash.

@matt0x6F

Interesting. I guess I had always looked at my desktop GPG provided pgp keys as «temporary» (or as long as this OS install lasts) and I was treating my Keybase generated ones as empirical.

Also, yes, once it’s installed I don’t need to mess with it and it eventually succeeded.

@erwanor

Hi friends, currently experiencing this issue on a fresh install!

Log id: a47bffd64aae0fed89393e1c

Love keybase!

@erikhuizinga

I’ve also experienced this on

$ keybase version
Client:  5.9.2-20220131221715+a25f15e42b
Service: 5.9.2-20220131221715+a25f15e42b

Log ID: 3e359fc39634b724430e6d1c

@erikhuizinga

Workaround for my use case, i.e. moving private GPG keys from machine A to B.

  1. On machine A, run keybase pgp push-private --all -f.
  2. On machine B list all keys using keybase fs ls -l /keybase/private/$you/.keys/pgp.
  3. For each key file, run keybase fs read /keybase/private/$you/.keys/pgp/$key | gpg --allow-secret-key-import --import.
  4. Optionally remove private keys from Keybase.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Ошибка internal error 52624
  • Ошибка internal error 2163 r drive
  • Ошибка internal error 0x89
  • Ошибка internal error 0x01 ini file not found at
  • Ошибка intel cpu ucode loading error что это

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии