11using System ;
2+ using System . IO ;
23using System . Net . Http ;
34using System . Net . Security ;
45using System . Security . Cryptography . X509Certificates ;
@@ -11,6 +12,7 @@ public class KubernetesClientUtil
1112 public const int ClientRetryCount = 3 ;
1213 public const int ClientRetryIntervalInSeconds = 5 ;
1314 private const string caPath = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" ;
15+ private const string serviceCAPath = "/var/run/secrets/kubernetes.io/serviceaccount/service-ca.crt" ;
1416
1517 public static void ExecuteWithRetry ( Action action )
1618 {
@@ -27,6 +29,7 @@ public static bool ServerCertificateValidationCallback(
2729 X509Chain certChain ,
2830 SslPolicyErrors sslPolicyErrors )
2931 {
32+ Console . WriteLine ( $ "sslPolicyErrors: { sslPolicyErrors } ") ;
3033 if ( sslPolicyErrors == SslPolicyErrors . None )
3134 {
3235 // certificate is already valid
@@ -36,6 +39,7 @@ public static bool ServerCertificateValidationCallback(
3639 {
3740 // only remaining error state is RemoteCertificateChainErrors
3841 // check custom CA
42+ bool caresult = true ;
3943 var privateChain = new X509Chain ( ) ;
4044 privateChain . ChainPolicy . RevocationMode = X509RevocationMode . NoCheck ;
4145
@@ -52,11 +56,44 @@ public static bool ServerCertificateValidationCallback(
5256 // root CA cert is not always trusted.
5357 chainStatus . Status != X509ChainStatusFlags . UntrustedRoot )
5458 {
55- return false ;
59+ Console . WriteLine ( $ "ca crt: { chainStatus . Status } ") ;
60+ caresult = false ;
61+ break ;
5662 }
5763 }
5864
59- return true ;
65+ if ( caresult )
66+ {
67+ return true ;
68+ }
69+
70+ if ( File . Exists ( serviceCAPath ) )
71+ {
72+ var serviceCAprivateChain = new X509Chain ( ) ;
73+ serviceCAprivateChain . ChainPolicy . RevocationMode = X509RevocationMode . NoCheck ;
74+
75+ var serviceCA = new X509Certificate2 ( serviceCAPath ) ;
76+ // https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.x509chainpolicy?view=netcore-2.2
77+ // Add CA cert to the chain store to include it in the chain check.
78+ serviceCAprivateChain . ChainPolicy . ExtraStore . Add ( serviceCA ) ;
79+ // Build the chain for `certificate` which should be the self-signed kubernetes api-server cert.
80+ serviceCAprivateChain . Build ( certificate ) ;
81+
82+ foreach ( X509ChainStatus chainStatus in serviceCAprivateChain . ChainStatus )
83+ {
84+ if ( chainStatus . Status != X509ChainStatusFlags . NoError &&
85+ // root CA cert is not always trusted.
86+ chainStatus . Status != X509ChainStatusFlags . UntrustedRoot )
87+ {
88+ Console . WriteLine ( $ "service crt: { chainStatus . Status } ") ;
89+ return false ;
90+ }
91+ }
92+
93+ return true ;
94+ }
95+
96+ return false ;
6097 }
6198 else
6299 {
0 commit comments