c语言 - 如果我为 linux 或 Windows 10 或更高版本制作应用程序,如何强制 OpenSSL 使用系统的根 CA?



我正在制作以下代码:

#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <shlwapi.h>
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS

#include <winsock2.h>
#include <ws2tcpip.h>
#include <shlwapi.h>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
//#pragma comment (lib, "Mswsock.lib")
//#pragma comment (lib, "AdvApi32.lib")

#define WIN32_LEAN_AND_MEAN

int verifyCerts( SSL_CTX* ctx )
{
// directory where executable is
char path[MAX_PATH] = "";

memset(path, 0, MAX_PATH);
GetModuleFileName(0, path, MAX_PATH);
PathRemoveFileSpec(path);
sprintf(path,"%s\%s",path,"certificates");
printf("nCert path %sn",path);
sprintf(path,"%s\%s",path,"certificates");
printf("nCert path %sn",path);
int value = SSL_CTX_load_verify_locations(ctx,NULL,path);
}
#else // By default use system's CA root
int verifyCerts( SSL_CTX* ctx )
{

}
#endif
SSL_CTX* InitCTX(void)
{
OpenSSL_add_all_algorithms(); 
SSL_load_error_strings();
const SSL_METHOD* method = SSLv23_method();
SSL_CTX* ctx = SSL_CTX_new(method);
SSL_CTX_set_options(ctx, SSL_OP_ALL | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1);

if (ctx == NULL)
{
ERR_print_errors_fp(stderr);
abort();
}

int value = verifyCerts( ctx );
if(value == 0) {
printf("Certificate errorn");
exit(1);
}
SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER,NULL);
return ctx;
}

在我的情况下,我想做以下事情:

  • 对于windows XP(遗留应用程序(,在我的应用程序旁边提供证书,这样我就可以尽可能地管理我的应用
  • 在任何其他情况下(对于linux系统或windows 10或更高版本(,我都会使用操作系统的默认CA证书(没有hussle来提供我自己的证书(

那么我如何确保后一种情况也适用呢?

#else部分只需放置以下代码:

int verifyCerts( SSL_CTX* ctx )
{    
const char *path = getenv(X509_get_default_cert_dir_env());
if (!path){
path = X509_get_default_cert_dir();
}
return SSL_CTX_load_verify_locations(ctx,NULL,path);
}

这将允许linux系统使用默认的certs路径进行验证。因此,只有在WindowsXP中,我们才能使用自定义的mingw标志。