Skip to content

Commit 397e72c

Browse files
Prefer using non-deprecated EC OSSL APIs where possible (dotnet#127190)
Adds new native entry points that use the modern OpenSSL 3.0 `EVP_PKEY` parameter and keygen APIs for EC key generation, import, and export, avoiding the deprecated `EC_KEY` APIs where possible. On pre-3.0 OpenSSL, the existing `EC_KEY` code paths are preserved as fallbacks. All new lightup APIs are guarded with `API_EXISTS` under `FEATURE_DISTRO_AGNOSTIC_SSL`. Unified EC APIs (EC_GROUP_get/set_curve, EC_POINT_get/set_affine_coordinates) are promoted to REQUIRED (available since OpenSSL 1.1.1, which is the minimum supported version). --------- Co-authored-by: Copilot Autofix powered by AI <[email protected]>
1 parent 125cc59 commit 397e72c

18 files changed

Lines changed: 2623 additions & 534 deletions

File tree

‎src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EcDsa.ImportExport.cs‎

Lines changed: 125 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -11,34 +11,53 @@ internal static partial class Interop
1111
{
1212
internal static partial class Crypto
1313
{
14-
[LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyCreateByKeyParameters", StringMarshalling = StringMarshalling.Utf8)]
15-
private static partial int EcKeyCreateByKeyParameters(
16-
out SafeEcKeyHandle key,
14+
[LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPKeyCreateByEcParameters", StringMarshalling = StringMarshalling.Utf8)]
15+
private static partial int EvpPKeyCreateByEcParameters(
16+
out SafeEvpPKeyHandle pkey,
1717
string oid,
1818
byte[]? qx, int qxLength,
1919
byte[]? qy, int qyLength,
20-
byte[]? d, int dLength);
20+
byte[]? d, int dLength,
21+
out int keySize);
2122

22-
internal static SafeEcKeyHandle EcKeyCreateByKeyParameters(
23+
internal static SafeEvpPKeyHandle EvpPKeyCreateByEcParameters(
2324
string oid,
24-
byte[]? qx, int qxLength,
25-
byte[]? qy, int qyLength,
26-
byte[]? d, int dLength)
25+
byte[]? qx,
26+
byte[]? qy,
27+
byte[]? d,
28+
out int keySize)
2729
{
28-
SafeEcKeyHandle key;
29-
int rc = EcKeyCreateByKeyParameters(out key, oid, qx, qxLength, qy, qyLength, d, dLength);
30-
if (rc == -1)
30+
SafeEvpPKeyHandle pkey;
31+
int rc = EvpPKeyCreateByEcParameters(
32+
out pkey, oid,
33+
qx, qx?.Length ?? 0,
34+
qy, qy?.Length ?? 0,
35+
d, d?.Length ?? 0,
36+
out keySize);
37+
38+
if (rc == 2)
3139
{
32-
key?.Dispose();
40+
pkey?.Dispose();
3341
Interop.Crypto.ErrClearError();
34-
3542
throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, oid));
3643
}
37-
return key;
44+
45+
if (rc != 1 || pkey == null || pkey.IsInvalid)
46+
{
47+
Exception ex = Interop.Crypto.CreateOpenSslCryptographicException();
48+
pkey?.Dispose();
49+
throw ex;
50+
}
51+
52+
// EvpPKeyCreateByEcParameters may have polluted the error queue, but key was good in the end.
53+
// Clean up the error queue.
54+
Interop.Crypto.ErrClearError();
55+
56+
return pkey;
3857
}
3958

40-
[LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EcKeyCreateByExplicitParameters")]
41-
internal static partial SafeEcKeyHandle EcKeyCreateByExplicitParameters(
59+
[LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPKeyCreateByEcExplicitParameters")]
60+
private static partial int EvpPKeyCreateByEcExplicitParameters(
4261
ECCurve.ECCurveType curveType,
4362
byte[]? qx, int qxLength,
4463
byte[]? qy, int qyLength,
@@ -48,11 +67,18 @@ internal static partial SafeEcKeyHandle EcKeyCreateByExplicitParameters(
4867
byte[] b, int bLength,
4968
byte[] gx, int gxLength,
5069
byte[] gy, int gyLength,
51-
byte[] order, int nLength,
70+
byte[] order, int orderLength,
5271
byte[]? cofactor, int cofactorLength,
53-
byte[]? seed, int seedLength);
54-
55-
internal static SafeEcKeyHandle EcKeyCreateByExplicitCurve(ECCurve curve)
72+
byte[]? seed, int seedLength,
73+
out SafeEvpPKeyHandle pkey,
74+
out int keySize);
75+
76+
internal static SafeEvpPKeyHandle EvpPKeyCreateByEcExplicitParameters(
77+
ECCurve curve,
78+
byte[]? qx,
79+
byte[]? qy,
80+
byte[]? d,
81+
out int keySize)
5682
{
5783
byte[] p;
5884
if (curve.IsPrime)
@@ -68,32 +94,65 @@ internal static SafeEcKeyHandle EcKeyCreateByExplicitCurve(ECCurve curve)
6894
throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
6995
}
7096

71-
SafeEcKeyHandle key = Interop.Crypto.EcKeyCreateByExplicitParameters(
97+
int rc = EvpPKeyCreateByEcExplicitParameters(
7298
curve.CurveType,
73-
null, 0,
74-
null, 0,
75-
null, 0,
99+
qx, qx?.Length ?? 0,
100+
qy, qy?.Length ?? 0,
101+
d, d?.Length ?? 0,
76102
p, p.Length,
77103
curve.A!, curve.A!.Length,
78104
curve.B!, curve.B!.Length,
79105
curve.G.X!, curve.G.X!.Length,
80106
curve.G.Y!, curve.G.Y!.Length,
81107
curve.Order!, curve.Order!.Length,
82-
curve.Cofactor, curve.Cofactor!.Length,
83-
curve.Seed, curve.Seed == null ? 0 : curve.Seed.Length);
108+
curve.Cofactor, curve.Cofactor?.Length ?? 0,
109+
curve.Seed, curve.Seed?.Length ?? 0,
110+
out SafeEvpPKeyHandle pkey,
111+
out keySize);
84112

85-
if (key == null || key.IsInvalid)
113+
if (rc != 1 || pkey == null || pkey.IsInvalid)
86114
{
87-
Exception e = Interop.Crypto.CreateOpenSslCryptographicException();
88-
key?.Dispose();
89-
throw e;
115+
Exception ex = Interop.Crypto.CreateOpenSslCryptographicException();
116+
pkey?.Dispose();
117+
throw ex;
90118
}
91119

92-
// EcKeyCreateByExplicitParameters may have polluted the error queue, but key was good in the end.
120+
// EvpPKeyCreateByEcExplicitParameters may have polluted the error queue, but key was good in the end.
93121
// Clean up the error queue.
94122
Interop.Crypto.ErrClearError();
95123

96-
return key;
124+
return pkey;
125+
}
126+
127+
[LibraryImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EvpPKeyGenerateByEcCurveOid", StringMarshalling = StringMarshalling.Utf8)]
128+
private static partial int EvpPKeyGenerateByEcCurveOid(
129+
out SafeEvpPKeyHandle pkey,
130+
string oid,
131+
out int keySize);
132+
133+
internal static SafeEvpPKeyHandle EvpPKeyGenerateByEcCurveOid(string oid, out int keySize)
134+
{
135+
int rc = EvpPKeyGenerateByEcCurveOid(out SafeEvpPKeyHandle pkey, oid, out keySize);
136+
137+
if (rc == 2)
138+
{
139+
pkey?.Dispose();
140+
Interop.Crypto.ErrClearError();
141+
throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, oid));
142+
}
143+
144+
if (rc != 1 || pkey == null || pkey.IsInvalid)
145+
{
146+
Exception ex = Interop.Crypto.CreateOpenSslCryptographicException();
147+
pkey?.Dispose();
148+
throw ex;
149+
}
150+
151+
// EvpPKeyGenerateByEcCurveOid may have polluted the error queue, but key was good in the end.
152+
// Clean up the error queue.
153+
Interop.Crypto.ErrClearError();
154+
155+
return pkey;
97156
}
98157

99158
[LibraryImport(Libraries.CryptoNative)]
@@ -104,11 +163,12 @@ internal static bool EvpPKeyHasCurveName(SafeEvpPKeyHandle pkey)
104163
int rc = CryptoNative_EvpPKeyGetEcGroupNid(pkey, out int nidCurveName);
105164
if (rc == 1)
106165
{
107-
// Key is invalid or doesn't have a curve
108-
return (nidCurveName != Interop.Crypto.NID_undef);
166+
return nidCurveName != Interop.Crypto.NID_undef;
109167
}
110168

111-
throw Interop.Crypto.CreateOpenSslCryptographicException();
169+
// rc == 0 means the group name could not be retrieved
170+
// (e.g., explicit curve or OpenSSL < 3.0). Treat as no curve name.
171+
return false;
112172
}
113173

114174
/// <summary>
@@ -122,7 +182,36 @@ internal static bool EvpPKeyHasCurveName(SafeEvpPKeyHandle pkey)
122182
return nidCurveName != Interop.Crypto.NID_undef ? CurveNidToOidValue(nidCurveName) : null;
123183
}
124184

125-
throw Interop.Crypto.CreateOpenSslCryptographicException();
185+
// rc == 0 means the group name could not be retrieved
186+
// (e.g., explicit curve or OpenSSL < 3.0).
187+
return null;
188+
}
189+
190+
[LibraryImport(Libraries.CryptoNative)]
191+
private static partial int CryptoNative_EvpPKeyEcHasExplicitEncoding(SafeEvpPKeyHandle pkey);
192+
193+
/// <summary>
194+
/// Returns <see langword="true"/> if the key has explicit encoding, <see langword="false"/> if named.
195+
/// </summary>
196+
/// <exception cref="CryptographicException">The encoding could not be determined from the key.</exception>
197+
internal static bool EvpPKeyEcHasExplicitEncoding(SafeEvpPKeyHandle pkey)
198+
{
199+
int result = CryptoNative_EvpPKeyEcHasExplicitEncoding(pkey);
200+
201+
if (result < 0)
202+
{
203+
throw CreateOpenSslCryptographicException();
204+
}
205+
206+
return result == 1;
207+
}
208+
209+
[LibraryImport(Libraries.CryptoNative)]
210+
private static partial int CryptoNative_EvpPKeyGetEcKeySize(SafeEvpPKeyHandle pkey);
211+
212+
internal static int EvpPKeyGetEcKeySize(SafeEvpPKeyHandle pkey)
213+
{
214+
return CryptoNative_EvpPKeyGetEcKeySize(pkey);
126215
}
127216

128217
[LibraryImport(Libraries.CryptoNative)]

‎src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanOpenSsl.Derive.cs‎

Lines changed: 5 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -88,20 +88,7 @@ public override byte[] DeriveRawSecretAgreement(ECDiffieHellmanPublicKey otherPa
8888
Debug.Assert(otherPartyPublicKey != null);
8989
Debug.Assert(_key is not null); // Callers should validate prior.
9090

91-
bool thisIsNamed;
92-
93-
using (SafeEcKeyHandle ecKey = Interop.Crypto.EvpPkeyGetEcKey(_key.Value))
94-
{
95-
if (ecKey == null || ecKey.IsInvalid)
96-
{
97-
// This may happen when EVP_PKEY was created by provider and getting EC_KEY is not possible.
98-
thisIsNamed = Interop.Crypto.EvpPKeyHasCurveName(_key.Value);
99-
}
100-
else
101-
{
102-
thisIsNamed = Interop.Crypto.EcKeyHasCurveName(ecKey);
103-
}
104-
}
91+
bool thisIsNamed = !Interop.Crypto.EvpPKeyEcHasExplicitEncoding(_key.Value);
10592

10693
ECDiffieHellmanOpenSslPublicKey? otherKey = otherPartyPublicKey as ECDiffieHellmanOpenSslPublicKey;
10794
bool disposeOtherKey = false;
@@ -118,7 +105,7 @@ public override byte[] DeriveRawSecretAgreement(ECDiffieHellmanPublicKey otherPa
118105
otherKey = new ECDiffieHellmanOpenSslPublicKey(otherParameters);
119106
}
120107

121-
bool otherIsNamed = otherKey.HasCurveName;
108+
bool otherIsNamed = !otherKey.HasExplicitEncoding;
122109

123110
// We need to always duplicate handle in case this operation is done by multiple threads and one of them disposes the handle
124111
SafeEvpPKeyHandle? ourKey = _key.Value;
@@ -143,10 +130,7 @@ public override byte[] DeriveRawSecretAgreement(ECDiffieHellmanPublicKey otherPa
143130
}
144131
else if (otherIsNamed)
145132
{
146-
using (ECOpenSsl tmp = new ECOpenSsl(otherKey.ExportExplicitParameters()))
147-
{
148-
theirKey = tmp.CreateEvpPKeyHandle();
149-
}
133+
theirKey = ECOpenSsl.ImportECKey(otherKey.ExportExplicitParameters(), out _);
150134
}
151135
else
152136
{
@@ -155,11 +139,8 @@ public override byte[] DeriveRawSecretAgreement(ECDiffieHellmanPublicKey otherPa
155139
// This is generally not expected to fail except:
156140
// - when key can't be accessed but is available (i.e. TPM)
157141
// - private key is actually missing
158-
using (ECOpenSsl tmp = new ECOpenSsl(ExportExplicitParameters(true)))
159-
{
160-
ourKey = tmp.CreateEvpPKeyHandle();
161-
disposeOurKey = true;
162-
}
142+
ourKey = ECOpenSsl.ImportECKey(ExportExplicitParameters(true), out _);
143+
disposeOurKey = true;
163144
}
164145
catch (CryptographicException)
165146
{

‎src/libraries/Common/src/System/Security/Cryptography/ECDiffieHellmanOpenSslPublicKey.cs‎

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ namespace System.Security.Cryptography
88
{
99
internal sealed class ECDiffieHellmanOpenSslPublicKey : ECDiffieHellmanPublicKey
1010
{
11-
private ECOpenSsl? _key;
11+
private SafeEvpPKeyHandle? _key;
1212

1313
internal ECDiffieHellmanOpenSslPublicKey(SafeEvpPKeyHandle pkeyHandle)
1414
{
@@ -17,27 +17,12 @@ internal ECDiffieHellmanOpenSslPublicKey(SafeEvpPKeyHandle pkeyHandle)
1717
if (pkeyHandle.IsInvalid)
1818
throw new ArgumentException(SR.Cryptography_OpenInvalidHandle, nameof(pkeyHandle));
1919

20-
// If ecKey is valid it has already been up-ref'd, so we can just use this handle as-is.
21-
SafeEcKeyHandle key = Interop.Crypto.EvpPkeyGetEcKey(pkeyHandle);
22-
23-
if (key == null || key.IsInvalid)
24-
{
25-
key?.Dispose();
26-
27-
// This may happen when EVP_PKEY was created by provider and getting EC_KEY is not possible.
28-
// Since you cannot mix EC_KEY and EVP_PKEY params API we need to export and re-import the public key.
29-
ECParameters ecParams = ECOpenSsl.ExportParameters(pkeyHandle, includePrivateParameters: false);
30-
_key = new ECOpenSsl(ecParams);
31-
}
32-
else
33-
{
34-
_key = new ECOpenSsl(key);
35-
}
20+
_key = pkeyHandle.DuplicateHandle();
3621
}
3722

3823
internal ECDiffieHellmanOpenSslPublicKey(ECParameters parameters)
3924
{
40-
_key = new ECOpenSsl(parameters);
25+
_key = ECOpenSsl.ImportECKey(parameters, out _);
4126
}
4227

4328
#pragma warning disable 0672 // Member overrides an obsolete member.
@@ -60,14 +45,31 @@ public override ECParameters ExportExplicitParameters() =>
6045
public override ECParameters ExportParameters() =>
6146
ECOpenSsl.ExportParameters(GetKey(), includePrivateParameters: false);
6247

63-
internal bool HasCurveName => Interop.Crypto.EcKeyHasCurveName(GetKey());
48+
internal bool HasCurveName => Interop.Crypto.EvpPKeyHasCurveName(GetKey());
49+
50+
internal bool HasExplicitEncoding
51+
{
52+
get
53+
{
54+
ThrowIfDisposed();
55+
return Interop.Crypto.EvpPKeyEcHasExplicitEncoding(GetKey());
56+
}
57+
}
6458

6559
internal int KeySize
6660
{
6761
get
6862
{
6963
ThrowIfDisposed();
70-
return _key.KeySize;
64+
65+
int keySize = Interop.Crypto.EvpPKeyGetEcKeySize(_key);
66+
67+
if (keySize == 0)
68+
{
69+
throw new CryptographicException(SR.Cryptography_InvalidHandle);
70+
}
71+
72+
return keySize;
7173
}
7274
}
7375

@@ -84,8 +86,7 @@ protected override void Dispose(bool disposing)
8486

8587
internal SafeEvpPKeyHandle DuplicateKeyHandle()
8688
{
87-
SafeEcKeyHandle currentKey = GetKey();
88-
return Interop.Crypto.CreateEvpPkeyFromEcKey(currentKey);
89+
return GetKey().DuplicateHandle();
8990
}
9091

9192
[MemberNotNull(nameof(_key))]
@@ -94,10 +95,10 @@ private void ThrowIfDisposed()
9495
ObjectDisposedException.ThrowIf(_key is null, this);
9596
}
9697

97-
private SafeEcKeyHandle GetKey()
98+
private SafeEvpPKeyHandle GetKey()
9899
{
99100
ThrowIfDisposed();
100-
return _key.Value;
101+
return _key;
101102
}
102103
}
103104
}

0 commit comments

Comments
 (0)