Skip to content

[Tigron]: x509 helper #4138

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

Merged
merged 2 commits into from
Apr 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
170 changes: 170 additions & 0 deletions mod/tigron/utils/testca/ca.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
/*
Copyright The containerd Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package testca provides helpers to create a self-signed CA certificate, and the ability to generate
// signed certificates from it.
// PLEASE NOTE THIS IS NOT A PRODUCTION SAFE NOR VERIFIED WAY TO MANAGE CERTIFICATES FOR SERVERS.
package testca

import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"io"
"math/big"
"net"
"time"

"github.com/containerd/nerdctl/mod/tigron/internal/assertive"
"github.com/containerd/nerdctl/mod/tigron/test"
"github.com/containerd/nerdctl/mod/tigron/tig"
)

const (
keyLength = 4096
caRoot = "ca"
certsRoot = "certs"
organization = "tigron volatile testing organization"
lifetime = 24 * time.Hour
serialSize = 60
)

// NewX509 creates a new, self-signed, signing certificate under data.Temp()/ca
// From that Cert as a CA, you can then generate signed certificates.
// Note that the common name of the cert will be set to the test name.
func NewX509(data test.Data, helpers test.Helpers) *Cert {
template := &x509.Certificate{
Subject: pkix.Name{
Organization: []string{organization},
CommonName: helpers.T().Name(),
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(lifetime),
IsCA: true,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
}

return (&Cert{}).GenerateCustomX509(data, helpers, caRoot, template)
}

// Cert allows the consumer to retrieve the cert and key path, to be used by other processes, like servers for example.
type Cert struct {
KeyPath string
CertPath string
key *rsa.PrivateKey
cert *x509.Certificate
}

// GenerateServerX509 produces a certificate usable by a server.
// additional can be used to provide additional ips to be added to the certificate.
func (ca *Cert) GenerateServerX509(data test.Data, helpers test.Helpers, host string, additional ...string) *Cert {
template := &x509.Certificate{
Subject: pkix.Name{
Organization: []string{organization},
CommonName: host,
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(lifetime),
KeyUsage: x509.KeyUsageCRLSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
DNSNames: additional,
}

additional = append([]string{host}, additional...)
for _, h := range additional {
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
}
}

return ca.GenerateCustomX509(data, helpers, certsRoot, template)
}

// GenerateCustomX509 signs a random x509 certificate template.
// Note that if SerialNumber is specified, it must be safe to use on the filesystem as this will be used in the name
// of the certificate file.
func (ca *Cert) GenerateCustomX509(
data test.Data,
helpers test.Helpers,
underDirectory string,
template *x509.Certificate,
) *Cert {
silentT := assertive.WithSilentSuccess(helpers.T())
key, certPath, keyPath := createCert(silentT, data, underDirectory, template, ca.cert, ca.key)

return &Cert{
CertPath: certPath,
KeyPath: keyPath,
key: key,
cert: template,
}
}

func createCert(
testing tig.T,
data test.Data,
dir string,
template, caCert *x509.Certificate,
caKey *rsa.PrivateKey,
) (key *rsa.PrivateKey, certPath, keyPath string) {
if caCert == nil {
caCert = template
}

if caKey == nil {
caKey = key
}

key, err := rsa.GenerateKey(rand.Reader, keyLength)
assertive.ErrorIsNil(testing, err, "key generation should succeed")

signedCert, err := x509.CreateCertificate(rand.Reader, template, caCert, &key.PublicKey, caKey)
assertive.ErrorIsNil(testing, err, "certificate creation should succeed")

serial := template.SerialNumber
if serial == nil {
serial = serialNumber()
}

data.Temp().Dir(dir)
certPath = data.Temp().Path(dir, serial.String()+".cert")
keyPath = data.Temp().Path(dir, serial.String()+".key")

data.Temp().SaveToWriter(func(writer io.Writer) error {
return pem.Encode(writer, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
}, keyPath)

data.Temp().SaveToWriter(func(writer io.Writer) error {
return pem.Encode(writer, &pem.Block{Type: "CERTIFICATE", Bytes: signedCert})
}, keyPath)

return key, certPath, keyPath
}

func serialNumber() *big.Int {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), serialSize)

serial, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
panic(err)
}

return serial
}
20 changes: 20 additions & 0 deletions pkg/containerdutil/image_store.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
Copyright The containerd Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package containerdutil

type ImageStore struct {
}
161 changes: 0 additions & 161 deletions pkg/testutil/nerdtest/ca/ca.go

This file was deleted.

10 changes: 3 additions & 7 deletions pkg/testutil/nerdtest/registry/cesanta.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ import (

"github.com/containerd/nerdctl/mod/tigron/expect"
"github.com/containerd/nerdctl/mod/tigron/test"
"github.com/containerd/nerdctl/mod/tigron/utils/testca"

"github.com/containerd/nerdctl/v2/pkg/inspecttypes/dockercompat"
"github.com/containerd/nerdctl/v2/pkg/testutil/nerdtest/ca"
"github.com/containerd/nerdctl/v2/pkg/testutil/nerdtest/platform"
"github.com/containerd/nerdctl/v2/pkg/testutil/nettestutil"
"github.com/containerd/nerdctl/v2/pkg/testutil/portlock"
Expand Down Expand Up @@ -119,7 +119,7 @@ func ensureContainerStarted(helpers test.Helpers, con string) {
}
}

func NewCesantaAuthServer(data test.Data, helpers test.Helpers, ca *ca.CA, port int, user, pass string, tls bool) *TokenAuthServer {
func NewCesantaAuthServer(data test.Data, helpers test.Helpers, ca *testca.Cert, port int, user, pass string, tls bool) *TokenAuthServer {
// listen on 0.0.0.0 to enable 127.0.0.1
listenIP := net.ParseIP("0.0.0.0")
hostIP, err := nettestutil.NonLoopbackIPv4()
Expand Down Expand Up @@ -165,7 +165,7 @@ func NewCesantaAuthServer(data test.Data, helpers test.Helpers, ca *ca.CA, port
err = cc.Save(configFileName)
assert.NilError(helpers.T(), err, fmt.Errorf("failed writing configuration: %w", err))

cert := ca.NewCert(hostIP.String())
cert := ca.GenerateServerX509(data, helpers, hostIP.String())
// FIXME: this will fail in many circumstances. Review strategy on how to acquire a free port.
// We probably have better code for that already somewhere.
port, err = portlock.Acquire(port)
Expand All @@ -177,13 +177,9 @@ func NewCesantaAuthServer(data test.Data, helpers test.Helpers, ca *ca.CA, port
cleanup := func(data test.Data, helpers test.Helpers) {
helpers.Ensure("rm", "-f", containerName)
errPortRelease := portlock.Release(port)
errCertClose := cert.Close()
if errPortRelease != nil {
helpers.T().Error(errPortRelease.Error())
}
if errCertClose != nil {
helpers.T().Error(errCertClose.Error())
}
}

setup := func(data test.Data, helpers test.Helpers) {
Expand Down
Loading