-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
smtongsuo.go
482 lines (405 loc) · 13.8 KB
/
smtongsuo.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
package crypto
import (
"bytes"
"context"
"encoding/hex"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/Laisky/errors/v2"
"github.com/Laisky/zap"
gutils "github.com/Laisky/go-utils/v4"
glog "github.com/Laisky/go-utils/v4/log"
)
// Tongsuo is a wrapper of tongsuo executable binary
//
// https://github.com/Tongsuo-Project/Tongsuo
type Tongsuo struct {
exePath string
serialGenerator *DefaultX509CertSerialNumGenerator
}
// NewTongsuo new tongsuo wrapper
//
// #Args
// - exePath: path of tongsuo executable binary
func NewTongsuo(exePath string) (ins *Tongsuo, err error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
ins = &Tongsuo{exePath: exePath}
// check tongsuo executable binary
if out, err := ins.runCMD(ctx, []string{"version"}, nil); err != nil {
return nil, errors.Wrapf(err, "run `%s version` failed", exePath)
} else if !strings.Contains(string(out), "Tongsuo") {
return nil, errors.Errorf("only support Tongsuo")
}
// new serial number generator
if ins.serialGenerator, err = NewDefaultX509CertSerialNumGenerator(); err != nil {
return nil, errors.Wrap(err, "new serial number generator")
}
return ins, nil
}
func (t *Tongsuo) runCMD(ctx context.Context, args []string, stdin []byte) (output []byte, err error) {
if args, err = gutils.SanitizeCMDArgs(args); err != nil {
return nil, errors.Wrap(err, "sanitize cmd args")
}
//nolint: gosec
// G204: Subprocess launched with a potential tainted input or cmd arguments
cmd := exec.CommandContext(ctx, t.exePath, args...)
if len(stdin) != 0 {
var stdinBuf bytes.Buffer
stdinBuf.Write(stdin)
cmd.Stdin = &stdinBuf
}
if output, err = cmd.CombinedOutput(); err != nil {
return nil, errors.Wrapf(err, "run cmd failed, got %s", output)
}
return output, nil
}
// OpensslCertificateOutput output of `openssl x509 -inform DER -text`
type OpensslCertificateOutput struct {
Raw []byte
SerialNumber string
}
// ShowCertInfo show cert info
func (t *Tongsuo) ShowCertInfo(ctx context.Context, certDer []byte) (certInfo OpensslCertificateOutput, err error) {
certInfo.Raw, err = t.runCMD(ctx, []string{"x509", "-inform", "DER", "-text"}, certDer)
if err != nil {
return certInfo, errors.Wrap(err, "run cmd to show cert info")
}
matched := reX509CertSerialNo.FindAllSubmatch(certInfo.Raw, 1)
if len(matched) != 1 && len(matched[0]) != 2 {
return certInfo, errors.Errorf("invalid cert info")
}
certInfo.SerialNumber = strings.ReplaceAll(string(matched[0][1]), ":", "")
return certInfo, nil
}
// ShowCsrInfo show csr info
func (t *Tongsuo) ShowCsrInfo(ctx context.Context, csrDer []byte) (output string, err error) {
out, err := t.runCMD(ctx, []string{"req", "-inform", "DER", "-text"}, csrDer)
if err != nil {
return "", errors.Wrap(err, "run cmd to show csr info")
}
return string(out), nil
}
// NewPrikey generate new sm2 private key
func (t *Tongsuo) NewPrikey(ctx context.Context) (prikeyPem []byte, err error) {
prikeyPem, err = t.runCMD(ctx, []string{
"genpkey", "-outform", "PEM", "-algorithm", "SM2",
}, nil)
if err != nil {
return nil, errors.Wrap(err, "generate new private key")
}
return prikeyPem, nil
}
func (t *Tongsuo) removeAll(path string) {
if err := os.RemoveAll(path); err != nil {
glog.Shared.Error("remove dir", zap.String("path", path), zap.Error(err))
}
}
// NewPrikeyAndCert generate new private key and root ca
func (t *Tongsuo) NewPrikeyAndCert(ctx context.Context, opts ...X509CertOption) (prikeyPem, certDer []byte, err error) {
// new private key
if prikeyPem, err = t.NewPrikey(ctx); err != nil {
return nil, nil, errors.Wrap(err, "new private key")
}
certDer, err = t.NewX509Cert(ctx, prikeyPem, opts...)
if err != nil {
return nil, nil, errors.Wrap(err, "new root ca")
}
return prikeyPem, certDer, nil
}
// NewX509Cert generate new x509 cert
func (t *Tongsuo) NewX509Cert(ctx context.Context,
prikeyPem []byte, opts ...X509CertOption) (certDer []byte, err error) {
opt, tpl, err := x509CertOption2Template(opts...)
if err != nil {
return nil, errors.Wrap(err, "X509CertOption2Template")
}
opensslConf := X509Cert2OpensslConf(tpl)
dir, err := os.MkdirTemp("", "tongsuo*")
if err != nil {
return nil, errors.Wrap(err, "generate tem dir")
}
defer t.removeAll(dir)
// write conf
confPath := filepath.Join(dir, "rootca.cnf")
if err = os.WriteFile(confPath, opensslConf, 0600); err != nil {
return nil, errors.Wrap(err, "write openssl conf")
}
outCertPemPath := filepath.Join(dir, "rootca.pem")
// new root ca
if _, err = t.runCMD(ctx, []string{
"req", "-outform", "PEM", "-out", outCertPemPath,
"-key", "/dev/stdin",
"-set_serial", strconv.Itoa(int(t.serialGenerator.SerialNum())),
"-days", strconv.Itoa(int(time.Until(opt.notAfter) / time.Hour / 24)),
"-x509", "-new", "-nodes", "-utf8", "-batch",
"-sm3", "-sigopt", "sm2-za:no",
"-copy_extensions", "copyall",
"-extensions", "v3_ca",
"-config", confPath,
}, prikeyPem); err != nil {
return nil, errors.Wrap(err, "generate new root ca")
}
certPem, err := os.ReadFile(outCertPemPath)
if err != nil {
return nil, errors.Wrap(err, "read root ca")
}
if certDer, err = Pem2Der(certPem); err != nil {
return nil, errors.Wrap(err, "Pem2Der")
}
return certDer, nil
}
// NewX509CSR generate new x509 csr
func (t *Tongsuo) NewX509CSR(ctx context.Context, prikeyPem []byte, opts ...X509CSROption) (csrDer []byte, err error) {
dir, err := os.MkdirTemp("", "tongsuo*")
if err != nil {
return nil, errors.Wrap(err, "generate tem dir")
}
defer t.removeAll(dir)
tpl, err := X509CsrOption2Template(opts...)
if err != nil {
return nil, errors.Wrap(err, "X509CsrOption2Template")
}
opensslConf := X509Csr2OpensslConf(tpl)
confPath := filepath.Join(dir, "csr.cnf")
if err = os.WriteFile(confPath, opensslConf, 0600); err != nil {
return nil, errors.Wrap(err, "write openssl conf")
}
outCsrDerPath := filepath.Join(dir, "csr.der")
if _, err = t.runCMD(ctx, []string{
"req", "-new", "-outform", "DER", "-out", outCsrDerPath,
"-key", "/dev/stdin",
"-sm3", "-sigopt", "sm2-za:no",
"-config", confPath,
}, prikeyPem); err != nil {
return nil, errors.Wrap(err, "generate new csr")
}
if csrDer, err = os.ReadFile(outCsrDerPath); err != nil {
return nil, errors.Wrap(err, "read csr")
}
return csrDer, nil
}
// NewX509CertByCSR generate new x509 cert by csr
func (t *Tongsuo) NewX509CertByCSR(ctx context.Context,
parentCertDer []byte,
parentPrikeyPem []byte,
csrDer []byte,
opts ...SignCSROption) (certDer []byte, err error) {
opt, opensslConf, err := x509SignCsrOptions2OpensslConf(opts...)
if err != nil {
return nil, errors.Wrap(err, "X509SignCsrOptions2OpensslConf")
}
dir, err := os.MkdirTemp("", "tongsuo*")
if err != nil {
return nil, errors.Wrap(err, "generate tem dir")
}
defer t.removeAll(dir)
confPath := filepath.Join(dir, "csr.cnf")
if err = os.WriteFile(confPath, opensslConf, 0600); err != nil {
return nil, errors.Wrap(err, "write openssl conf")
}
parentCertDerPath := filepath.Join(dir, "ca.der")
if err = os.WriteFile(parentCertDerPath, parentCertDer, 0600); err != nil {
return nil, errors.Wrap(err, "write parent cert")
}
csrDerPath := filepath.Join(dir, "csr.der")
if err = os.WriteFile(csrDerPath, csrDer, 0600); err != nil {
return nil, errors.Wrap(err, "write csr")
}
outCertDerPath := filepath.Join(dir, "cert.der")
if _, err = t.runCMD(ctx, []string{
"x509", "-req", "-outform", "DER", "-out", outCertDerPath,
"-in", csrDerPath, "-inform", "DER",
"-CA", parentCertDerPath, "-CAkey", "/dev/stdin", "-CAcreateserial",
"-days", strconv.Itoa(int(time.Until(opt.notAfter) / time.Hour / 24)),
"-utf8", "-batch",
"-sm3", "-sigopt", "sm2-za:no", "-vfyopt", "sm2-za:no",
"-copy_extensions", "copyall",
"-extfile", confPath, "-extensions", "v3_ca",
}, parentPrikeyPem); err != nil {
return nil, errors.Wrap(err, "sign csr")
}
if certDer, err = os.ReadFile(outCertDerPath); err != nil {
return nil, errors.Wrap(err, "read signed cert")
}
return certDer, nil
}
// EncryptBySm4Baisc encrypt by sm4
//
// # Args
// - key: sm4 key, should be 16 bytes
// - plaintext: data to be encrypted
// - iv: sm4 iv, should be 16 bytes
//
// # Returns
// - ciphertext: sm4 encrypted data
// - hmac: hmac of ciphertext, 32 bytes
func (t *Tongsuo) EncryptBySm4Baisc(ctx context.Context,
key, plaintext, iv []byte) (ciphertext, hmac []byte, err error) {
if len(key) != 16 {
return nil, nil, errors.Errorf("key should be 16 bytes")
}
if len(iv) != 16 {
return nil, nil, errors.Errorf("iv should be 16 bytes")
}
if len(hmac) != 0 && len(hmac) != 32 {
return nil, nil, errors.Errorf("hmac should be 0 or 32 bytes")
}
dir, err := os.MkdirTemp("", "tongsuo*")
if err != nil {
return nil, nil, errors.Wrap(err, "generate tem dir")
}
defer t.removeAll(dir)
cipherPath := filepath.Join(dir, "cipher")
if _, err = t.runCMD(ctx, []string{
"enc", "-sm4-cbc", "-e",
"-in", "/dev/stdin", "-out", cipherPath,
"-K", hex.EncodeToString(key), "-iv", hex.EncodeToString(iv),
}, plaintext); err != nil {
return nil, nil, errors.Wrap(err, "encrypt")
}
if ciphertext, err = os.ReadFile(cipherPath); err != nil {
return nil, nil, errors.Wrap(err, "read cipher")
}
if hmac, err = HMACSha256(key, ciphertext); err != nil {
return nil, nil, errors.Wrap(err, "calculate hmac")
}
return ciphertext, hmac, nil
}
// DecryptBySm4Baisc decrypt by sm4
//
// # Args
// - key: sm4 key
// - ciphertext: sm4 encrypted data
// - iv: sm4 iv
// - hmac: if not nil, will check ciphertext's integrity by hmac
func (t *Tongsuo) DecryptBySm4Baisc(ctx context.Context,
key, ciphertext, iv, hmac []byte) (plaintext []byte, err error) {
if len(key) != 16 {
return nil, errors.Errorf("key should be 16 bytes")
}
if len(iv) != 16 {
return nil, errors.Errorf("iv should be 16 bytes")
}
if len(hmac) != 0 && len(hmac) != 32 {
return nil, errors.Errorf("hmac should be 0 or 32 bytes")
}
if len(hmac) != 0 { // check hmac
if expectedHmac, err := HMACSha256(key, ciphertext); err != nil {
return nil, errors.Wrap(err, "calculate hmac")
} else if !bytes.Equal(hmac, expectedHmac) {
return nil, errors.Errorf("hmac not match")
}
}
dir, err := os.MkdirTemp("", "tongsuo*")
if err != nil {
return nil, errors.Wrap(err, "generate tem dir")
}
defer t.removeAll(dir)
cipherPath := filepath.Join(dir, "cipher")
if err = os.WriteFile(cipherPath, ciphertext, 0600); err != nil {
return nil, errors.Wrap(err, "write cipher")
}
if plaintext, err = t.runCMD(ctx, []string{
"enc", "-sm4-cbc", "-d",
"-in", cipherPath, "-out", "/dev/stdout",
"-K", hex.EncodeToString(key), "-iv", hex.EncodeToString(iv),
}, ciphertext); err != nil {
return nil, errors.Wrap(err, "decrypt")
}
return plaintext, nil
}
// EncryptBySm4 encrypt by sm4, should be decrypted by `DecryptBySm4` only
func (t *Tongsuo) EncryptBySm4(ctx context.Context, key, plaintext []byte) (combinedCipher []byte, err error) {
iv, err := Salt(16)
if err != nil {
return nil, errors.Wrap(err, "generate iv")
}
cipher, hmac, err := t.EncryptBySm4Baisc(ctx, key, plaintext, iv)
if err != nil {
return nil, errors.Wrap(err, "encrypt by sm4 basic")
}
combinedCipher = make([]byte, 0, len(iv)+len(cipher)+len(hmac))
combinedCipher = append(combinedCipher, iv...)
combinedCipher = append(combinedCipher, cipher...)
combinedCipher = append(combinedCipher, hmac...)
return combinedCipher, nil
}
// DecryptBySm4 decrypt by sm4, should be encrypted by `EncryptBySm4` only
func (t *Tongsuo) DecryptBySm4(ctx context.Context, key, combinedCipher []byte) (plaintext []byte, err error) {
if len(combinedCipher) <= 48 {
return nil, errors.Errorf("invalid combined cipher")
}
iv := combinedCipher[:16]
cipher := combinedCipher[16 : len(combinedCipher)-32]
hmac := combinedCipher[len(combinedCipher)-32:]
return t.DecryptBySm4Baisc(ctx, key, cipher, iv, hmac)
}
var (
reX509Subject = regexp.MustCompile(`(?s)Subject: ([\S ]+)`)
reX509Sans = regexp.MustCompile(`(?m)X509v3 Subject Alternative Name: ?\n +(.+)\b`)
reX509CertSerialNo = regexp.MustCompile(`(?m)Serial Number: ?\n? +([^ ]+)\b`)
)
// CloneX509Csr generat a cloned csr with different private key
//
// # Args
// - prikeyPem: new private key for cloned csr
// - originCsrDer: origin csr
func (t *Tongsuo) CloneX509Csr(ctx context.Context,
prikeyPem []byte, originCsrDer []byte) (clonedCsrDer []byte, err error) {
csrinfo, err := t.ShowCsrInfo(ctx, originCsrDer)
if err != nil {
return nil, errors.Wrap(err, "show csr info")
}
var opts []X509CSROption
// extract subjects
// Subject: C = CN, ST = Shanghai, L = Shanghai, O = BBT, CN = Intermediate CA
matched := reX509Subject.FindStringSubmatch(csrinfo)
if len(matched) != 2 {
return nil, errors.Errorf("invalid csr info")
}
sbjs := strings.Split(matched[1], ", ")
for _, sbj := range sbjs {
kv := strings.Split(sbj, " = ")
if len(kv) != 2 {
return nil, errors.Errorf("invalid subject info %q", sbj)
}
switch kv[0] {
case "C":
opts = append(opts, WithX509CSRCountry(kv[1]))
case "ST":
opts = append(opts, WithX509CSRProvince(kv[1]))
case "L":
opts = append(opts, WithX509CSRLocality(kv[1]))
case "O":
opts = append(opts, WithX509CSROrganization(kv[1]))
case "CN":
opts = append(opts, WithX509CSRCommonName(kv[1]))
}
}
// extract SANs
// X509v3 Subject Alternative Name:
// DNS:www.example.com, DNS:www.example.net, DNS:www.example.origin
matched = reX509Sans.FindStringSubmatch(csrinfo)
if len(matched) == 2 {
sans := strings.Split(matched[1], ", ")
for _, san := range sans {
kv := strings.Split(san, ":")
if len(kv) != 2 {
return nil, errors.Errorf("invalid csr info %q", san)
}
opts = append(opts, WithX509CSRSANS(kv[1]))
}
}
// generate new csr
clonedCsrDer, err = t.NewX509CSR(ctx, prikeyPem, opts...)
if err != nil {
return nil, errors.Wrap(err, "generate cloned csr")
}
return clonedCsrDer, nil
}