将自签名证书作为受信任的根证书添加到 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语法

- 下一篇
- win10系统磁盘碎片整理的操作方法
查看更多
最新文章
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
查看更多
AI推荐
-
- 茅茅虫AIGC检测
- 茅茅虫AIGC检测,湖南茅茅虫科技有限公司倾力打造,运用NLP技术精准识别AI生成文本,提供论文、专著等学术文本的AIGC检测服务。支持多种格式,生成可视化报告,保障您的学术诚信和内容质量。
- 139次使用
-
- 赛林匹克平台(Challympics)
- 探索赛林匹克平台Challympics,一个聚焦人工智能、算力算法、量子计算等前沿技术的赛事聚合平台。连接产学研用,助力科技创新与产业升级。
- 161次使用
-
- 笔格AIPPT
- SEO 笔格AIPPT是135编辑器推出的AI智能PPT制作平台,依托DeepSeek大模型,实现智能大纲生成、一键PPT生成、AI文字优化、图像生成等功能。免费试用,提升PPT制作效率,适用于商务演示、教育培训等多种场景。
- 153次使用
-
- 稿定PPT
- 告别PPT制作难题!稿定PPT提供海量模板、AI智能生成、在线协作,助您轻松制作专业演示文稿。职场办公、教育学习、企业服务全覆盖,降本增效,释放创意!
- 138次使用
-
- Suno苏诺中文版
- 探索Suno苏诺中文版,一款颠覆传统音乐创作的AI平台。无需专业技能,轻松创作个性化音乐。智能词曲生成、风格迁移、海量音效,释放您的音乐灵感!
- 159次使用
查看更多
相关文章
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览