-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcert.go
234 lines (200 loc) · 6.4 KB
/
cert.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package cert
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"log"
"math/big"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"time"
)
const (
certValidityDays = 365
rsaKeySize = 2048
orgName = "Yandex SDK Development Certificate"
)
type CertificateManager struct {
certPath string
keyPath string
}
func NewCertificateManager() *CertificateManager {
// Save certificates in a more permanent directory, such as the user's home directory.
homeDir, err := os.UserHomeDir()
if err != nil {
homeDir = "." // Fallback to current directory
}
certDir := filepath.Join(homeDir, ".yandex_sdk")
os.MkdirAll(certDir, 0755) // Ensure the directory exists.
return &CertificateManager{
certPath: filepath.Join(certDir, "yandex_sdk_cert.pem"),
keyPath: filepath.Join(certDir, "yandex_sdk_key.pem"),
}
}
func (cm *CertificateManager) GetOrCreateCertificate() (tls.Certificate, error) {
// Check if certificate exists and is valid
if cm.isValidCertificate() {
return tls.LoadX509KeyPair(cm.certPath, cm.keyPath)
}
// Generate new certificate
certPEM, keyPEM, err := cm.generateCertificate()
if err != nil {
return tls.Certificate{}, fmt.Errorf("failed to generate certificate: %v", err)
}
// Save certificate and key
if err := cm.saveCertificateAndKey(certPEM, keyPEM); err != nil {
return tls.Certificate{}, fmt.Errorf("failed to save certificate: %v", err)
}
// Attempt to add the certificate to the system's trust store
err = cm.addCertToTrustStore()
if err != nil {
log.Printf("Warning: Failed to add certificate to the system's trust store: %v", err)
log.Printf("You may need to manually trust the certificate located at %s", cm.certPath)
} else {
log.Printf("Certificate successfully added to the system's trust store.")
}
// Load and return the new certificate
cert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
return tls.Certificate{}, fmt.Errorf("failed to load generated certificate: %v", err)
}
return cert, nil
}
func (cm *CertificateManager) isValidCertificate() bool {
if !fileExists(cm.certPath) || !fileExists(cm.keyPath) {
return false
}
// Check if the certificate is valid and has required SANs
certPEM, err := os.ReadFile(cm.certPath)
if err != nil {
return false
}
block, _ := pem.Decode(certPEM)
if block == nil {
return false
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return false
}
now := time.Now()
return now.After(cert.NotBefore) && now.Before(cert.NotAfter) && cm.validateSANs(cert)
}
func (cm *CertificateManager) validateSANs(cert *x509.Certificate) bool {
hasLocalhost := false
hasLoopback := false
for _, name := range cert.DNSNames {
if name == "localhost" {
hasLocalhost = true
break
}
}
for _, ip := range cert.IPAddresses {
if ip.Equal(net.ParseIP("127.0.0.1")) || ip.Equal(net.ParseIP("::1")) {
hasLoopback = true
}
}
return hasLocalhost && hasLoopback
}
func (cm *CertificateManager) generateCertificate() ([]byte, []byte, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, rsaKeySize)
if err != nil {
return nil, nil, fmt.Errorf("failed to generate private key: %v", err)
}
serialNumber, err := generateSerialNumber()
if err != nil {
return nil, nil, fmt.Errorf("failed to generate serial number: %v", err)
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
CommonName: "localhost",
Organization: []string{orgName},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(certValidityDays * 24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")},
DNSNames: []string{"localhost"},
}
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
if err != nil {
return nil, nil, fmt.Errorf("failed to create certificate: %v", err)
}
certPEM := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: certDER,
})
keyPEM := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
})
return certPEM, keyPEM, nil
}
func (cm *CertificateManager) saveCertificateAndKey(certPEM, keyPEM []byte) error {
// Save the certificate and key to permanent files
if err := os.WriteFile(cm.certPath, certPEM, 0644); err != nil {
return fmt.Errorf("failed to save certificate: %v", err)
}
if err := os.WriteFile(cm.keyPath, keyPEM, 0600); err != nil {
os.Remove(cm.certPath) // Clean up certificate if key write fails
return fmt.Errorf("failed to save private key: %v", err)
}
return nil
}
// addCertToTrustStore attempts to add the generated certificate to the system's trust store.
// If administrative privileges are required and not available, it logs a warning.
func (cm *CertificateManager) addCertToTrustStore() error {
switch runtime.GOOS {
case "darwin":
return addCertToMacOSTrustStore(cm.certPath)
case "windows":
return addCertToWindowsTrustStore(cm.certPath)
default:
return fmt.Errorf("unsupported operating system")
}
}
func addCertToMacOSTrustStore(certPath string) error {
// Use the 'security' command to add the certificate to the login keychain
// Dynamically get the user's login keychain path
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get user home directory: %v", err)
}
keychainPath := filepath.Join(homeDir, "Library", "Keychains", "login.keychain-db")
cmd := exec.Command("security", "add-trusted-cert", "-p", "ssl", "-k", keychainPath, certPath)
cmd.Stdin = nil
cmd.Stdout = nil
cmd.Stderr = nil
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to add certificate to macOS trust store: %v", err)
}
return nil
}
func addCertToWindowsTrustStore(certPath string) error {
// Use 'certutil' to add the certificate to the Root store
cmd := exec.Command("certutil", "-addstore", "-user", "Root", certPath)
cmd.Stdin = nil
cmd.Stdout = nil
cmd.Stderr = nil
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to add certificate to Windows trust store: %v", err)
}
return nil
}
func generateSerialNumber() (*big.Int, error) {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
return rand.Int(rand.Reader, serialNumberLimit)
}
func fileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}