登录
首页 >  Golang >  Go问答

将自签名证书作为受信任的根证书添加到 Apple 钥匙串

来源:stackoverflow

时间:2024-04-01 16:36:34 439浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《将自签名证书作为受信任的根证书添加到 Apple 钥匙串》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我正在尝试使用以下 go 脚本将自签名证书添加到 macos 设备上的系统钥匙串:

package main

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "crypto/x509/pkix"
    "encoding/pem"
    "math/big"
    "os"
    "os/exec"
    "time"

    "github.com/sirupsen/logrus"
)

func main() {
    keyfilename := "key.pem"
    certfilename := "cert.pem"

    // generate a self-signed certificate (adapted from https://golang.org/src/crypto/tls/generate_cert.go)
    key, err := rsa.generatekey(rand.reader, 4096)
    if err != nil {
        logrus.witherror(err).fatal("generate key")
    }

    keyfile, err := os.create(keyfilename)
    if err != nil {
        logrus.witherror(err).fatal("create key file")
    }
    if err = pem.encode(keyfile, &pem.block{
        type:  "rsa private key",
        bytes: x509.marshalpkcs1privatekey(key),
    }); err != nil {
        logrus.witherror(err).fatal("marshal private key")
    }
    keyfile.close()

    template := x509.certificate{
        serialnumber: big.newint(42),
        subject: pkix.name{
            country:            []string{"us"},
            organization:       []string{"awesomeness, inc."},
            organizationalunit: []string{"awesomeness dept."},
            commonname:         "awesomeness, inc.",
        },
        notbefore:             time.now(),
        notafter:              time.now().adddate(10, 0, 0),
        keyusage:              x509.keyusagekeyencipherment | x509.keyusagedigitalsignature | x509.keyusagecertsign,
        extkeyusage:           []x509.extkeyusage{x509.extkeyusageserverauth},
        isca:                  true,
        basicconstraintsvalid: true,
    }

    derbytes, err := x509.createcertificate(rand.reader, &template, &template, &key.publickey, key)
    if err != nil {
        logrus.witherror(err).fatal("failed to create certificate")
    }

    certfile, err := os.create(certfilename)
    if err != nil {
        logrus.witherror(err).fatal("create cert file")
    }
    if err = pem.encode(certfile, &pem.block{
        type:  "certificate",
        bytes: derbytes,
    }); err != nil {
        logrus.witherror(err).fatal("encode certificate")
    }
    certfile.close()

    /*
        add-trusted-cert [-d] [-r resulttype] [-p policy] [-a apppath] [-s policystring] [-e allowederror] [-u
        keyusage] [-k keychain] [-i settingsfilein] [-o settingsfileout] certfile
            add certificate (in der or pem format) from certfile to per-user or local admin trust settings. when
            modifying per-user trust settings, user authentication is required via an authentication dialog. when
            modifying admin trust settings, the process must be running as root, or admin authentication is
            required.

            options:
            -d              add to admin cert store; default is user.
            -r resulttype   resulttype = trustroot|trustasroot|deny|unspecified; default is trustroot.
            -p policy       specify policy constraint (ssl, smime, codesign, ipsec, basic, swupdate, pkgsign,
                            eap, macappstore, appleid, timestamping).
            -a apppath      specify application constraint.
            -s policystring
                            specify policy-specific string.
            -e allowederror
                            specify allowed error (an integer value, or one of: certexpired, hostnamemismatch)
            -u keyusage     specify key usage, an integer.
            -k keychain     specify keychain to which cert is added.
            -i settingsfilein
                            input trust settings file; default is user domain.
            -o settingsfileout
                            output trust settings file; default is user domain.

            key usage codes:
                            -1 - any
                            1 - sign
                            2 - encrypt/decrypt data
                            4 - encrypt/decrypt key
                            8 - sign certificate
                            16 - sign revocation
                            32 - key exchange
                            to specify more than one usage, add values together (except -1 - any).
    */

    args := []string{"add-trusted-cert", "-k", "/library/keychains/system.keychain", "-r", "trustasroot", certfilename}

    output, err := exec.command("/usr/bin/security", args...).combinedoutput()
    if err != nil {
        logrus.fatalf("add-trusted-cert: %v - %s", err, output)
    }
}

但是,当我使用 sudo 运行此脚本时,我得到一个相当不具体的“传递给函数的一个或多个参数无效”。错误:

> sudo go run add_to_keychain_trusted.go
Password:
FATA[0002] add-trusted-cert: exit status 1 - SecTrustSettingsSetTrustSettings: One or more parameters passed to a function were not valid. 
exit status 1

我注意到的一件事是,如果我使用 -r trustroot 选项而不是 -r trustasroot,则该命令有效。也许不再支持 -r trustasroot 选项(尽管它记录在 man security 页面中)?


解决方案


https://www.jamf.com/jamf-nation/discussions/13812/problems-importing-cert-via-terminal 之后,我通过编写包含证书的配置文件并使用 profiles 命令行工具安装该配置文件来解决此问题,而不是直接使用 security 工具。这是改编后的脚本:

package main

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "crypto/x509/pkix"
    "encoding/pem"
    "io/ioutil"
    "math/big"
    "os"
    "os/exec"
    "strings"
    "time"

    uuid "github.com/satori/go.uuid"
    "github.com/sirupsen/logrus"
    "howett.net/plist"
)

// Payload represents a configuration profile's payload. (Adapted from https://github.com/micromdm/micromdm/blob/master/mdm/enroll/profile.go).
type Payload struct {
    PayloadType         string      `json:"type"`
    PayloadVersion      int         `json:"version"`
    PayloadIdentifier   string      `json:"identifier"`
    PayloadUUID         string      `json:"uuid"`
    PayloadDisplayName  string      `json:"displayname" plist:",omitempty"`
    PayloadDescription  string      `json:"description,omitempty" plist:",omitempty"`
    PayloadOrganization string      `json:"organization,omitempty" plist:",omitempty"`
    PayloadScope        string      `json:"scope" plist:",omitempty"`
    PayloadContent      interface{} `json:"content,omitempty" plist:"PayloadContent,omitempty"`
}

// Profile represents a configuration profile (cf. https://developer.apple.com/business/documentation/Configuration-Profile-Reference.pdf)
type Profile struct {
    PayloadContent           []interface{}     `json:"content,omitempty"`
    PayloadDescription       string            `json:"description,omitempty" plist:",omitempty"`
    PayloadDisplayName       string            `json:"displayname,omitempty" plist:",omitempty"`
    PayloadExpirationDate    *time.Time        `json:"expiration_date,omitempty" plist:",omitempty"`
    PayloadIdentifier        string            `json:"identifier"`
    PayloadOrganization      string            `json:"organization,omitempty" plist:",omitempty"`
    PayloadUUID              string            `json:"uuid"`
    PayloadRemovalDisallowed bool              `json:"removal_disallowed" plist:",omitempty"`
    PayloadType              string            `json:"type"`
    PayloadVersion           int               `json:"version"`
    PayloadScope             string            `json:"scope" plist:",omitempty"`
    RemovalDate              *time.Time        `json:"removal_date" plist:"-" plist:",omitempty"`
    DurationUntilRemoval     float32           `json:"duration_until_removal" plist:",omitempty"`
    ConsentText              map[string]string `json:"consent_text" plist:",omitempty"`
}

type CertificatePayload struct {
    Payload
    PayloadContent             []byte
    PayloadCertificateFileName string `plist:",omitempty"`
    Password                   string `plist:",omitempty"`
    AllowAllAppsAccess         bool   `plist:",omitempty"`
}

// NewProfile creates a new configuration profile
func NewProfile() *Profile {
    payloadUUID := uuid.NewV4()

    return &Profile{
        PayloadVersion: 1,
        PayloadType:    "Configuration",
        PayloadUUID:    payloadUUID.String(),
    }
}

// NewPayload creates a new payload
func NewPayload(payloadType string) *Payload {
    payloadUUID := uuid.NewV4()

    return &Payload{
        PayloadVersion: 1,
        PayloadType:    payloadType,
        PayloadUUID:    payloadUUID.String(),
    }
}

func NewCertificateProfile(certPEM []byte) *Profile {
    profile := NewProfile()
    profile.PayloadDescription = "Awesome Payload"
    profile.PayloadDisplayName = "Awesome Certificate"
    profile.PayloadIdentifier = "com.awesomeness.certificate"
    profile.PayloadScope = "System"
    profile.PayloadOrganization = "Awesomeness, Inc."

    payload := NewPayload("com.apple.security.pem")
    payload.PayloadDescription = "Awesome Certificate"
    payload.PayloadDisplayName = "Awesome Certificate"
    payload.PayloadOrganization = "Awesomeness, Inc."
    payload.PayloadIdentifier = profile.PayloadIdentifier + "." + payload.PayloadUUID

    certificatePayload := CertificatePayload{
        Payload:        *payload,
        PayloadContent: certPEM,
    }

    profile.PayloadContent = []interface{}{certificatePayload}

    return profile
}

func generateSelfSignedCertificate(keyFileName, certFileName string) {
    // Generate a self-signed certificate (adapted from https://golang.org/src/crypto/tls/generate_cert.go)
    key, err := rsa.GenerateKey(rand.Reader, 4096)
    if err != nil {
        logrus.WithError(err).Fatal("generate key")
    }

    keyFile, err := os.Create(keyFileName)
    if err != nil {
        logrus.WithError(err).Fatal("create key file")
    }
    if err = pem.Encode(keyFile, &pem.Block{
        Type:  "RSA PRIVATE KEY",
        Bytes: x509.MarshalPKCS1PrivateKey(key),
    }); err != nil {
        logrus.WithError(err).Fatal("marshal private key")
    }
    keyFile.Close()

    template := x509.Certificate{
        SerialNumber: big.NewInt(42),
        Subject: pkix.Name{
            Country:            []string{"US"},
            Organization:       []string{"Awesomeness, Inc."},
            OrganizationalUnit: []string{"Awesomeness Dept."},
            CommonName:         "Awesomeness 4, Inc.",
        },
        NotBefore:             time.Now(),
        NotAfter:              time.Now().AddDate(10, 0, 0),
        KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
        ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
        IsCA:                  true,
        BasicConstraintsValid: true,
    }

    derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
    if err != nil {
        logrus.WithError(err).Fatal("failed to create certificate")
    }

    certFile, err := os.Create(certFileName)
    if err != nil {
        logrus.WithError(err).Fatal("create cert file")
    }
    if err = pem.Encode(certFile, &pem.Block{
        Type:  "CERTIFICATE",
        Bytes: derBytes,
    }); err != nil {
        logrus.WithError(err).Fatal("encode certificate")
    }
    certFile.Close()
}

func main() {
    keyFileName := "key.pem"
    certFileName := "cert.pem"
    profileFileName := "certificate.mobileconfig"

    generateSelfSignedCertificate(keyFileName, certFileName)

    certPEM, err := ioutil.ReadFile(certFileName)
    if err != nil {
        logrus.WithError(err).Fatal("read certificate file")
    }

    certificateProfile := NewCertificateProfile(certPEM)

    mobileconfig, err := plist.MarshalIndent(certificateProfile, plist.XMLFormat, "\t")
    if err != nil {
        logrus.WithError(err).Fatal("marshal plist")
    }

    if err := ioutil.WriteFile(profileFileName, mobileconfig, 0755); err != nil {
        logrus.WithError(err).Fatal("write mobileconfig to file")
    }

    args := []string{"install", "-path", profileFileName}

    output, err := exec.Command("/usr/bin/profiles", args...).CombinedOutput()
    if err != nil {
        logrus.Fatalf("%s: %v - %s", "/usr/bin/profiles"+strings.Join(args, " "), err, output)
    }
}

使用 sudo -e go run add_certificate.go 运行此命令后,通用名为 awesomeness 4, inc. 的证书在我的钥匙串中显示为受信任的证书:

理论要掌握,实操不能落!以上关于《将自签名证书作为受信任的根证书添加到 Apple 钥匙串》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>