将自签名证书作为受信任的根证书添加到 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语法
- 下一篇
- win10系统磁盘碎片整理的操作方法
查看更多
最新文章
-
- Golang · Go问答 | 17小时前 | 标准库 · 性能优化 · Go问答 · io.CopyBuffer WriterTo ReaderFrom Go io.Copy Go手写复制循环
- Copy、CopyBuffer 与手写循环的差别主要在哪里
- 243浏览 收藏
-
- Golang · Go问答 | 17小时前 | error · api设计 · database/sql · Go问答 · database/sql errors.Is 错误封装 Go错误处理 错误转换 领域错误
- 业务层是否应该暴露底层数据库错误,怎样转换才不丢信息
- 409浏览 收藏
-
- Golang · Go问答 | 18小时前 |
- 什么时候应该定义哨兵错误,什么时候使用自定义类型
- 145浏览 收藏
-
- Golang · Go问答 | 18小时前 |
- 敏感字段已经写入日志,怎样从源头建立不可绕过的脱敏层
- 341浏览 收藏
-
- Golang · Go问答 | 19小时前 |
- 日志量过大时先调级别还是做采样,取舍依据是什么
- 354浏览 收藏
-
- Golang · Go问答 | 19小时前 | go · slog · 可观测性 · Go问答 · log/slog Logger.With LogAttrs Go结构化日志 slog Handler
- 结构化日志字段应该在调用处还是 Handler 中补齐
- 406浏览 收藏
-
- Golang · Go问答 | 19小时前 | go · Go问答 · replace go.work 本地联调 Go Modules Go多模块工作区
- 多模块联调时 replace 与 go.work 的职责有什么区别
- 195浏览 收藏
-
- Golang · Go问答 | 21小时前 |
- 项目应使用 replace 还是发布预览版本来联调依赖
- 479浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 375次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 445次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 451次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 397次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 223次使用
查看更多
相关文章
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go crypto/rand.Text 的长度为什么不是固定字符数
- 2026-10-04 501浏览
-
- Go strings.ToValidUTF8 清洗日志内容的边界
- 2026-10-03 501浏览
-
- Go tls.GetCertificate 为什么收不到空 ServerName 请求
- 2026-09-27 501浏览

