Skip to content

gh-109945: Enable spec of multiple curves/groups for TLS #119244

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: main
Choose a base branch
from

Conversation

planetf1
Copy link

@planetf1 planetf1 commented May 20, 2024

Co-authored-by: Martin Schmatz

This change makes it possible to allow multiple groups to be specified in a colon separated string. See issues for more detail

The implementation choice is to modify the existing function rather than introduce a new one.

Changes:

  • add new logic to set SSL curves when OpenSSL >=3
  • add additional testcases to verify argument format (check exception)
  • add additional testcases to verify multiple curves if OpenSSL >=3
  • added Blurb
  • Added docs

Current Status:

  • Ready for review

Addressed:

  • Initially opening as draft to check contributor guidelines, code layout etc.
  • Some further testcases are commented out which check format. These caused an exception I need to check
  • some sanitizer tests failing - to be investigated

Note to reviewers:

  • in additional to normal checks please see closely the explanation of how the new function responds to bad curves in the OpenSSL>3 cases - is this ok?
  • I noticed additional files created in Lib/lib2to3/ which I presume should not be checked in
  • I can squash changes to one/less commit as/if required (or maintainer can squash when merged)

@ghost
Copy link

ghost commented May 20, 2024

All commit authors signed the Contributor License Agreement.
CLA signed

@bedevere-app
Copy link

bedevere-app bot commented May 20, 2024

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

@bedevere-app
Copy link

bedevere-app bot commented May 20, 2024

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

@planetf1
Copy link
Author

FYI am aware of the test failure. Will be working on update for that. (apologies for delay) + arranging CLA.

@planetf1
Copy link
Author

planetf1 commented May 22, 2024

The test failure occurs within test_set_ecdh_curve which tests a follows:

    @unittest.skipUnless(ssl.HAS_ECDH, "ECDH disabled on this OpenSSL build")
    def test_set_ecdh_curve(self):
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        ctx.set_ecdh_curve("prime256v1")
        ctx.set_ecdh_curve(b"prime256v1")
        self.assertRaises(TypeError, ctx.set_ecdh_curve)
        self.assertRaises(TypeError, ctx.set_ecdh_curve, None)
        self.assertRaises(ValueError, ctx.set_ecdh_curve, "foo")
        self.assertRaises(ValueError, ctx.set_ecdh_curve, b"foo")

This raises two issues

a) If the change in this PR is to be included, the unit tests should be updated to also include lists of curves - no problem

More relevant is

b) The current tests assert that an exception is raised if an invalid curve is specified (which is not in the initial code)

There are a few ways of handling this

  1. I could parse the list of curves, checking each one for validity and raising an exception either on first failure, or after finding all errors. (ie strtok loop, OBJ_snnid checks). This would keep the behaviour effectively the same as the current version, with precisely reported errors, but is the most complex. (and some concern about any loop iterating through the list ad implementation questions, such as is using of string.h / strtok_r ok?)
  2. There are lots of places in the ssl code in general where we use _setSSLError and just return NULL without formatting a python error - even in the original code this occurs. The test could be changed to permit this -- but this is a change in behaviour
  3. In addition to _setSSLError when we fail to set the curves, I could add something like PyErr_Format(PyExc_ValueError,"unknown elliptic curves %R", name);. This keeps the behaviour closest for the test case, and is the simplest implementation, but does mean other ssl failures now raise an exception where they didn't previously.

Not being very familiar with the code I'm interested in feedback as to what the most appropriate way of handling this would be? Is the additional complexity of the first option the most appropriate & desirable?

@bedevere-app
Copy link

bedevere-app bot commented Jun 3, 2024

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

1 similar comment
@bedevere-app
Copy link

bedevere-app bot commented Jun 3, 2024

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

@planetf1 planetf1 force-pushed the issue109945 branch 2 times, most recently from 0a9c417 to 07c0a4a Compare June 4, 2024 09:04
@planetf1
Copy link
Author

planetf1 commented Jun 4, 2024

The current PR proposal builds cleanly. However is an area that needs discussion

Previously an invalid (no NID) curve would result in a value exception, whilst any other kind of SSL error would not, though it would set the ssl error. This passed tests cleanly.

Since we now can have multiple curves, one option is to simple call the underlying SSL function to set the curves. This makes it difficult to distinguish between the two cases, meaning that the code returns a valueerror in both cases (for invalid curves)

In working through this, I also noticed that the thread sanitizer checks FAIL when _setSSLError() is called. Before this code change we still did call this, just in less cases, and via a code path that the unix tests didn't check. With the code change the new code (minus the most recent commit) would set this on every exception (as above). My conclusion is that this function isn't thread safe? So is that a more general bug that needs investigation?

For now the _setSSLError() is removed, however I think it should be reinstated once understood.

@planetf1 planetf1 marked this pull request as ready for review June 4, 2024 11:39
@planetf1
Copy link
Author

planetf1 commented Jul 1, 2024

Rebased. Would very much appreciate any review comments . Thanks!

@planetf1
Copy link
Author

Aware of one doc validation error from my news blurb

Adds support for multiple curves to be specified in SSLContext.set_ecdh_curve() for OpenSSL 3.0 and above by setting curve_name to a colon separated list of curves. This allows multiple curves to be passed on a TLS client hello.

/home/runner/work/cpython/cpython/build/NEWS:70: WARNING: py:func reference target not found: warnings.filterswarnings

planetf1 and others added 12 commits July 17, 2024 15:29
Signed-off-by: Nigel Jones <jonesn@uk.ibm.com>
Signed-off-by: Nigel Jones <jonesn@uk.ibm.com>
Signed-off-by: Nigel Jones <jonesn@uk.ibm.com>
Signed-off-by: Nigel Jones <jonesn@uk.ibm.com>
Signed-off-by: Nigel Jones <jonesn@uk.ibm.com>
Signed-off-by: Nigel Jones <jonesn@uk.ibm.com>
Signed-off-by: Nigel Jones <jonesn@uk.ibm.com>
Signed-off-by: Nigel Jones <jonesn@uk.ibm.com>
Signed-off-by: Nigel Jones <jonesn@uk.ibm.com>
Signed-off-by: Nigel Jones <jonesn@uk.ibm.com>
Signed-off-by: Nigel Jones <jonesn@uk.ibm.com>
Signed-off-by: Nigel Jones <jonesn@uk.ibm.com>
self.assertRaises(ValueError, ctx.set_ecdh_curve, b"prime256v1:bar")
self.assertRaises(ValueError, ctx.set_ecdh_curve, "foo:prime256v1")
self.assertRaises(ValueError, ctx.set_ecdh_curve, b"foo:prime256v1")
#self.assertRaises(ValueError, ctx.set_ecdh_curve, ":")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's up with the commented out test cases? are these not valuable? it seems like a set of edge cases worth covering to define behavior on unusual inputs.

@gpshead
Copy link
Member

gpshead commented Jul 19, 2024

FYI - I'm looping in @sethmlarson for additional eyeballs on whether or not they think this makes sense given it is a _ssl module change.

@sethmlarson
Copy link
Contributor

Going to also ping @woodruffw and @jvdprng since they're working on an adjacent project.

@@ -4399,8 +4400,10 @@ _ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
SSL_CTX_set_tmp_ecdh(self->ctx, key);
EC_KEY_free(key);
#else
if (!SSL_CTX_set1_groups(self->ctx, &nid, 1)) {
_setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
int res = SSL_CTX_set1_groups_list(self->ctx, PyBytes_AS_STRING(name_bytes));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SSL_CTX_set1_groups_list also supports another syntax, adding a ? before the curve name makes it "optional", quoting the docs:

If a group name is preceded with the ? character, it will be ignored if an implementation is missing.

This isn't tested in our test suite, it would be useful to test that so future contributors know that syntax exists.

@@ -1375,11 +1375,29 @@ def test_set_ecdh_curve(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.set_ecdh_curve("prime256v1")
ctx.set_ecdh_curve(b"prime256v1")
# Only OpenSSL 3 and above supported for multiple curves
if (IS_OPENSSL_3_0_0 >= 3):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IS_OPENSSL_3_0_0 is a boolean, meaning this branch will always fail?

@@ -1769,6 +1769,10 @@ to speed up repeated connections from the same clients.
a well-known elliptic curve, for example ``prime256v1`` for a widely
supported curve.

For OpenSSL 3.0 and above *curve_name* parameter can be a colon separated
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will need a "new in version 3.14" admonition.

@woodruffw
Copy link
Contributor

Going to also ping @woodruffw and @jvdprng since they're working on an adjacent project.

Thank you for the ping!

I'd like to understand the motivation a little better here: is the current cipher suite configuration insufficient? And is there a reason why ssl needs an explicit configuration for this, instead of allowing the client/server to negotiate a compatible cipher suite?

@sethmlarson
Copy link
Contributor

I'd like to understand the motivation a little better here: is the current cipher suite configuration insufficient? And is there a reason why ssl needs an explicit configuration for this, instead of allowing the client/server to negotiate a compatible cipher suite?

This API is for configuring the curves to offer during ECDH key exchange, not the ciphers.

@woodruffw
Copy link
Contributor

This API is for configuring the curves to offer during ECDH key exchange, not the ciphers.

Whoops!

That makes more sense, although I'm still curious about the intended application here -- IME it's not common for user-level TLS APIs (with the notable exception of OpenSSL) to expose curve selection as a configurable parameter, instead preferring to keep that as a implementation detail of negotiation (with the assumption that the TLS implementation either ensures a baseline level of security or the user configures a higher level "security margin" setting that influences the curve selection.)

TL;DR: My basic concern is that this exposes an API that's uncommon among TLS APIs, is a low level option that is typically only influenced by higher level APIs, and is a potential footgun. But one could easily argue that many of OpenSSL's APIs are footguns and thus there is ample precedent for exposing this 🙂

@planetf1
Copy link
Author

planetf1 commented Aug 5, 2024

Quick update - thanks for the review comments - apologies for the delay: just back from a few week's vacation, so will work through & respond specifically. Appreciated.

@ronf
Copy link
Contributor

ronf commented Jun 23, 2025

Regarding use cases, one reason for this is to be able to control whether or not a given connection will attempt to use post-quantum crypto algorithms during the key exchange (such as the hybrid X25519MLKEM768), or plain elliptic curve (such as X25519 by itself). OpenSSL 3.5 defaults to both of these, with a preference for the hybrid PQC algorithm. If an application doesn't want to pay the extra cost for PQC, they could use this mechanism to select only plain EC curves, removing the PQC algorithms from the list.

That said, we might want to think about naming the SSLContext method set_groups() rather than set_ecdh_curve() if we're going to use the OpenSSL SSL_CTX_set1_groups() function here. Alternately, we keep set_ecdh_curve() as only accepting EC curves (or maybe even jus the single curve it accepts now) and make support for multiple groups (including the fancier syntax with things like question mark and star for setting which key shares to generate) only in the new set_groups() method.

@davidkel
Copy link

davidkel commented Jun 25, 2025

@gpshead @sethmlarson @woodruffw I would say I am keen to see this in Python and I think I agree with @ronf that I think it might be better to have this as a different api rather than overloading the set_ecdh_curve() api as it really doesn't describe what is actually happening here. Admittedly it is governed by what OpenSSL expects and can parse and in OpenSSL 3.5 the group string that it can process has become far more powerful. As well as prefixes such as ? and - there is now a prefix * to control which keyshares should be sent, also you can now group curves together by using a tuple separator (to group similar strength mechanisms). So it is really powerful now and allows it to be able to meet NIST requirements for using Quantumsafe Key exchange mechanisms. If you look at various network servers such as HAProxy or NGINX these provide ways to provide your own group string but just passes this to OpenSSL to process and I think People who write Python network servers will want to be able to offer the same ability through their configuration rather than changing the OpenSSL config file or trying to use an ENV var to point to another OpenSSL config file (which may require specialist permissions).

There is a further extension to this which I think is also important and that is observability. It is becoming more important to be able to determine which group was negotiated, which cipher was selected etc to be able to determine the level of security being used to make sure it is adequate and quantumsafe and I would try to include some more apis to access this information so a Python server/client can log this information.

I worked with @planetf1 and know he won't be returning to this, but I would like to see if I can pick it up (if anyone has some pointers around adding and testing new apis the the ssl module that would be great as I see there is some form of code generation going on) and want to guage what everyone thinks so any feedback would be great.

@ronf
Copy link
Contributor

ronf commented Jun 30, 2025

There is a further extension to this which I think is also important and that is observability. It is becoming more important to be able to determine which group was negotiated, which cipher was selected etc to be able to determine the level of security being used to make sure it is adequate and quantumsafe and I would try to include some more apis to access this information so a Python server/client can log this information.

Agreed on this! There's an OpenSSL API SSL_get0_group_name() which can be called to get back the name of the group which was selected for performing the key agreement. Ideally, in addition to changing this code to call SSL_CTX_set1_groups(), there would be a new method which can call SSL_get0_group_name(). Note that this would be called on an SSL object, not an SSL_CTX, though. As such, it would probably need to be available as something like SSLSocket.group(), similar to the SSLSocket.cipher() method which exists today.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants