文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

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

2024-04-04 23:42

关注

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《将自签名证书作为受信任的根证书添加到 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()

    

    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 钥匙串》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注编程网公众号吧!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯