当前位置:首页 > 文章列表 > Golang > Go问答 > 将自签名证书作为受信任的根证书添加到 Apple 钥匙串

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

来源:stackoverflow 2024-04-01 16:36:34 0浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《将自签名证书作为受信任的根证书添加到 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删除
怎么在vue3中使用jsx语法怎么在vue3中使用jsx语法
上一篇
怎么在vue3中使用jsx语法
win10系统磁盘碎片整理的操作方法
下一篇
win10系统磁盘碎片整理的操作方法
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    508次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    497次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • 毕业宝AIGC检测:AI生成内容检测工具,助力学术诚信
    毕业宝AIGC检测
    毕业宝AIGC检测是“毕业宝”平台的AI生成内容检测工具,专为学术场景设计,帮助用户初步判断文本的原创性和AI参与度。通过与知网、维普数据库联动,提供全面检测结果,适用于学生、研究者、教育工作者及内容创作者。
    16次使用
  • AI Make Song:零门槛AI音乐创作平台,助你轻松制作个性化音乐
    AI Make Song
    AI Make Song是一款革命性的AI音乐生成平台,提供文本和歌词转音乐的双模式输入,支持多语言及商业友好版权体系。无论你是音乐爱好者、内容创作者还是广告从业者,都能在这里实现“用文字创造音乐”的梦想。平台已生成超百万首原创音乐,覆盖全球20个国家,用户满意度高达95%。
    26次使用
  • SongGenerator.io:零门槛AI音乐生成器,快速创作高质量音乐
    SongGenerator
    探索SongGenerator.io,零门槛、全免费的AI音乐生成器。无需注册,通过简单文本输入即可生成多风格音乐,适用于内容创作者、音乐爱好者和教育工作者。日均生成量超10万次,全球50国家用户信赖。
    24次使用
  •  BeArt AI换脸:免费在线工具,轻松实现照片、视频、GIF换脸
    BeArt AI换脸
    探索BeArt AI换脸工具,免费在线使用,无需下载软件,即可对照片、视频和GIF进行高质量换脸。体验快速、流畅、无水印的换脸效果,适用于娱乐创作、影视制作、广告营销等多种场景。
    26次使用
  • SEO标题协启动:AI驱动的智能对话与内容生成平台 - 提升创作效率
    协启动
    SEO摘要协启动(XieQiDong Chatbot)是由深圳协启动传媒有限公司运营的AI智能服务平台,提供多模型支持的对话服务、文档处理和图像生成工具,旨在提升用户内容创作与信息处理效率。平台支持订阅制付费,适合个人及企业用户,满足日常聊天、文案生成、学习辅助等需求。
    28次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码