search
HomeBackend DevelopmentGolangWhen signing a certificate, the authorization key identifier is copied to the SKID

签署证书时,授权密钥标识符被复制到 SKID

php editor Strawberry pointed out when introducing the signing certificate that the authorization key identifier (SKID) plays an important role in the signing process. When a certificate is signed, the SKID is copied into the certificate and identifies the certificate's authorized key. The existence of this identifier can help ensure the authenticity and legality of the certificate, and also facilitate subsequent certificate verification and management. Copying the SKID is a necessary step when signing a certificate, and it plays an important role in the use and maintenance of the certificate.

Question content

I am trying to sign a certificate using csr and the spacemonkeygo/openssl wrapper.

The console openssl command for signing the certificate works as expected and I get a valid certificate.

openssl x509 -req -days 365 -in cert_client.csr -ca ca/root.crt -cakey ca/root.key -set_serial 10101 -out cert_client.crt -extfile ca/extensions.cnf

As can be seen from the screenshot, the keyid of skid and issuer are different.

However, my code in go provides the wrong certificate, where skid contains the exact value of the keyid that issued the certificate. This causes an invalid value for "Issuer" to be copied in "Authority Key Identifier": since the skid is the same as the issuer's keyid, it "thinks" the certificate is self-issued.

package main

import (
    "github.com/spacemonkeygo/openssl"
    "math/big"
    "os"
    "time"
)

func main() {

    crtfilepath := filepath("ca/root.crt")
    keyfilepath := filepath("ca/root.key")

    certca, privatekeyca, err := getrootca(pathcert(crtfilepath), pathkey(keyfilepath))
    if err != nil {
        panic(err)
    }

    serialnumber := big.newint(10101)

    country := "ru"
    organization := "some organization"
    commonname := "commonname"
    expirationdate := time.now().adddate(1, 0, 0)

    certinfo := &openssl.certificateinfo{
        serial:     serialnumber,
        expires:    expirationdate.sub(time.now()),
        commonname: commonname,

        // will fail if these are empty or not initialized
        country:      country,
        organization: organization,
    }

    // just for example. publickey is received from csr
    privatekeycert, err := openssl.generatersakey(2048)
    if err != nil {
        panic(err)
    }

    newcert, err := openssl.newcertificate(certinfo, openssl.publickey(privatekeycert))
    if err != nil {
        panic(err)
    }

    err = newcert.setversion(openssl.x509_v3)
    if err != nil {
        panic(err)
    }

    // (?) must be called before adding extensions
    err = newcert.setissuer(certca)
    if err != nil {
        panic(err)
    }

    err = newcert.addextension(openssl.nid_basic_constraints,
        "critical,ca:false")
    if err != nil {
        panic(err)
    }

    err = newcert.addextension(openssl.nid_subject_key_identifier,
        "hash")
    if err != nil {
        panic(err)
    }

    err = newcert.addextension(openssl.nid_authority_key_identifier,
        "keyid:always,issuer:always")
    if err != nil {
        panic(err)
    }

    err = newcert.sign(privatekeyca, openssl.evp_sha256)
    if err != nil {
        panic(err)
    }

    pembytes, err := newcert.marshalpem()
    if err != nil {
        panic(err)
    }

    err = os.writefile("generated.crt", pembytes, os.filemode(0644))
    if err != nil {
        panic(err)
    }

    print("done")
}

type filepath string
type pathcert string
type pathkey string

func getrootca(pathcert pathcert, pathkey pathkey) (*openssl.certificate, openssl.privatekey, error) {

    capublickeyfile, err := os.readfile(string(pathcert))
    if err != nil {
        return nil, nil, err
    }

    certca, err := openssl.loadcertificatefrompem(capublickeyfile)
    if err != nil {
        return nil, nil, err
    }

    caprivatekeyfile, err := os.readfile(string(pathkey))
    if err != nil {
        return nil, nil, err
    }

    privatekeyca, err := openssl.loadprivatekeyfrompem(caprivatekeyfile)
    if err != nil {
        return nil, nil, err
    }

    return certca, privatekeyca, nil
}

(The generated one is correct)

If I don't call setissuer, the skid is newly generated, but the generated certificate still shows as "invalid".

What am I doing wrong in my code?

renew: I compared the implementation adding extensions for 2 wrappers: spacemonkey/go and pyopenssl.

go:

// add an extension to a certificate.
// extension constants are nid_* as found in openssl.
func (c *certificate) addextension(nid nid, value string) error {
    issuer := c
    if c.issuer != nil {
        issuer = c.issuer
    }
    var ctx c.x509v3_ctx
    c.x509v3_set_ctx(&ctx, c.x, issuer.x, nil, nil, 0)
    ex := c.x509v3_ext_conf_nid(nil, &ctx, c.int(nid), c.cstring(value))
    if ex == nil {
        return errors.new("failed to create x509v3 extension")
    }
    defer c.x509_extension_free(ex)
    if c.x509_add_ext(c.x, ex, -1) <= 0 {
        return errors.new("failed to add x509v3 extension")
    }
    return nil
}

python (omitting some comments):

# X509Extension::__init__
def __init__(
        self,
        type_name: bytes,
        critical: bool,
        value: bytes,
        subject: Optional["X509"] = None,
        issuer: Optional["X509"] = None,
    ) -> None:

        ctx = _ffi.new("X509V3_CTX*")

        # A context is necessary for any extension which uses the r2i
        # conversion method.  That is, X509V3_EXT_nconf may segfault if passed
        # a NULL ctx. Start off by initializing most of the fields to NULL.
        _lib.X509V3_set_ctx(ctx, _ffi.NULL, _ffi.NULL, _ffi.NULL, _ffi.NULL, 0)

        # We have no configuration database - but perhaps we should (some
        # extensions may require it).
        _lib.X509V3_set_ctx_nodb(ctx)

        # Initialize the subject and issuer, if appropriate.  ctx is a local,
        # and as far as I can tell none of the X509V3_* APIs invoked here steal
        # any references, so no need to mess with reference counts or
        # duplicates.
        if issuer is not None:
            if not isinstance(issuer, X509):
                raise TypeError("issuer must be an X509 instance")
            ctx.issuer_cert = issuer._x509
        if subject is not None:
            if not isinstance(subject, X509):
                raise TypeError("subject must be an X509 instance")
            ctx.subject_cert = subject._x509

        if critical:
            # There are other OpenSSL APIs which would let us pass in critical
            # separately, but they're harder to use, and since value is already
            # a pile of crappy junk smuggling a ton of utterly important
            # structured data, what's the point of trying to avoid nasty stuff
            # with strings? (However, X509V3_EXT_i2d in particular seems like
            # it would be a better API to invoke.  I do not know where to get
            # the ext_struc it desires for its last parameter, though.)
            value = b"critical," + value

        extension = _lib.X509V3_EXT_nconf(_ffi.NULL, ctx, type_name, value)
        if extension == _ffi.NULL:
            _raise_current_error()
        self._extension = _ffi.gc(extension, _lib.X509_EXTENSION_free)

The obvious difference is the API: the python version accepts subject and issuer as parameters for overloading. The go version does not.

The implementation differences are as follows:

  • Calling in pythonx509v3_ext_nconf
  • x509v3_ext_conf_nid Called in go Both functions can be found on github.

I think it is not possible to add the skid extension when using openspacemonkey/go-openssl with ca signing.

It seems the only way is to manually use the c bindings and "do it like python".

Workaround

I implemented a clever workaround to add skid and authoritykeyidentifier. The generated certificate is valid. However, since the x *c.x509 members of the certificate structure are not exported, the only way to access them is through unsafe pointers and casts.
This is not a recommended approach, but is a way to go until spacemonkey/go is updated (which I suspect will happen soon).

func addAuthorityKeyIdentifier(c *openssl.Certificate) error {
    var ctx C.X509V3_CTX
    C.X509V3_set_ctx(&ctx, nil, nil, nil, nil, 0)

    // this is ugly and very unsafe!
    cx509 := *(**C.X509)(unsafe.Pointer(c))

    cx509Issuer := cx509
    if c.Issuer != nil {
        cx509Issuer = *(**C.X509)(unsafe.Pointer(c.Issuer))
    }
    ctx.issuer_cert = cx509Issuer

    cExtName := C.CString("authorityKeyIdentifier")
    defer C.free(unsafe.Pointer(cExtName))
    cExtValue := C.CString("keyid:always,issuer:always")
    defer C.free(unsafe.Pointer(cExtValue))

    extension := C.X509V3_EXT_nconf(nil, &ctx, cExtName, cExtValue)
    if extension == nil {
        return errors.New("failed to set 'authorityKeyIdentifier' extension")
    }
    defer C.X509_EXTENSION_free(extension)

    addResult := C.X509_add_ext(cx509, extension, -1)
    if addResult == 0 {
        return errors.New("failed to set 'authorityKeyIdentifier' extension")
    }

    return nil
}

func addSKIDExtension(c *openssl.Certificate) error {
    var ctx C.X509V3_CTX
    C.X509V3_set_ctx(&ctx, nil, nil, nil, nil, 0)
    
    // this is ugly and very unsafe!
    cx509 := *(**C.X509)(unsafe.Pointer(c))
    _ = cx509

    ctx.subject_cert = cx509
    _ = ctx

    cExtName := C.CString("subjectKeyIdentifier")
    defer C.free(unsafe.Pointer(cExtName))
    cExtValue := C.CString("hash")
    defer C.free(unsafe.Pointer(cExtValue))

    extension := C.X509V3_EXT_nconf(nil, &ctx, cExtName, cExtValue)
    if extension == nil {
        return errors.New("failed to set 'subjectKeyIdentifier' extension")
    }
    defer C.X509_EXTENSION_free(extension)

    // adding itself as a subject
    addResult := C.X509_add_ext(cx509, extension, -1)
    if addResult == 0 {
        return errors.New("failed to set 'subjectKeyIdentifier' extension")
    }

    return nil
}

The above is the detailed content of When signing a certificate, the authorization key identifier is copied to the SKID. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
How do you use the pprof tool to analyze Go performance?How do you use the pprof tool to analyze Go performance?Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

What are the vulnerabilities of Debian OpenSSLWhat are the vulnerabilities of Debian OpenSSLApr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

How do you write unit tests in Go?How do you write unit tests in Go?Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

How do I write mock objects and stubs for testing in Go?How do I write mock objects and stubs for testing in Go?Mar 10, 2025 pm 05:38 PM

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

How can I define custom type constraints for generics in Go?How can I define custom type constraints for generics in Go?Mar 10, 2025 pm 03:20 PM

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

Explain the purpose of Go's reflect package. When would you use reflection? What are the performance implications?Explain the purpose of Go's reflect package. When would you use reflection? What are the performance implications?Mar 25, 2025 am 11:17 AM

The article discusses Go's reflect package, used for runtime manipulation of code, beneficial for serialization, generic programming, and more. It warns of performance costs like slower execution and higher memory use, advising judicious use and best

How can I use tracing tools to understand the execution flow of my Go applications?How can I use tracing tools to understand the execution flow of my Go applications?Mar 10, 2025 pm 05:36 PM

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization

How do you use table-driven tests in Go?How do you use table-driven tests in Go?Mar 21, 2025 pm 06:35 PM

The article discusses using table-driven tests in Go, a method that uses a table of test cases to test functions with multiple inputs and outcomes. It highlights benefits like improved readability, reduced duplication, scalability, consistency, and a

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.