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 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
|
package local
import (
"bytes"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/hex"
"encoding/pem"
"io/ioutil"
"net/http"
"net/http/httptest"
"reflect"
"regexp"
"sort"
"strings"
"testing"
"time"
"github.com/cloudflare/cfssl/config"
"github.com/cloudflare/cfssl/csr"
cferr "github.com/cloudflare/cfssl/errors"
"github.com/cloudflare/cfssl/helpers"
"github.com/cloudflare/cfssl/log"
"github.com/cloudflare/cfssl/signer"
)
const (
fullSubjectCSR = "../../../../../../../signer/local/testdata/test.csr"
testCSR = "../../../../../../../signer/local/testdata/ecdsa256.csr"
testSANCSR = "../../../../../../../signer/local/testdata/san_domain.csr"
testCaFile = "../../../../../../../signer/local/testdata/ca.pem"
testCaKeyFile = "../../../../../../../signer/local/testdata/ca_key.pem"
testECDSACaFile = "../../../../../../../signer/local/testdata/ecdsa256_ca.pem"
testECDSACaKeyFile = "../../../../../../../signer/local/testdata/ecdsa256_ca_key.pem"
)
var expiry = 1 * time.Minute
// Start a signer with the testing RSA CA cert and key.
func newTestSigner(t *testing.T) (s *Signer) {
s, err := NewSignerFromFile(testCaFile, testCaKeyFile, nil)
if err != nil {
t.Fatal(err)
}
return
}
func TestNewSignerFromFilePolicy(t *testing.T) {
var CAConfig = &config.Config{
Signing: &config.Signing{
Profiles: map[string]*config.SigningProfile{
"signature": {
Usage: []string{"digital signature"},
Expiry: expiry,
},
},
Default: &config.SigningProfile{
Usage: []string{"cert sign", "crl sign"},
ExpiryString: "43800h",
Expiry: expiry,
CAConstraint: config.CAConstraint{IsCA: true},
},
},
}
_, err := NewSignerFromFile(testCaFile, testCaKeyFile, CAConfig.Signing)
if err != nil {
t.Fatal(err)
}
}
func TestNewSignerFromFileInvalidPolicy(t *testing.T) {
var invalidConfig = &config.Config{
Signing: &config.Signing{
Profiles: map[string]*config.SigningProfile{
"invalid": {
Usage: []string{"wiretapping"},
Expiry: expiry,
},
"empty": {},
},
Default: &config.SigningProfile{
Usage: []string{"digital signature"},
Expiry: expiry,
},
},
}
_, err := NewSignerFromFile(testCaFile, testCaKeyFile, invalidConfig.Signing)
if err == nil {
t.Fatal(err)
}
if !strings.Contains(err.Error(), `"code":5200`) {
t.Fatal(err)
}
}
func TestNewSignerFromFileNoUsageInPolicy(t *testing.T) {
var invalidConfig = &config.Config{
Signing: &config.Signing{
Profiles: map[string]*config.SigningProfile{
"invalid": {
Usage: []string{},
Expiry: expiry,
},
"empty": {},
},
Default: &config.SigningProfile{
Usage: []string{"digital signature"},
Expiry: expiry,
},
},
}
_, err := NewSignerFromFile(testCaFile, testCaKeyFile, invalidConfig.Signing)
if err == nil {
t.Fatal("expect InvalidPolicy error")
}
if !strings.Contains(err.Error(), `"code":5200`) {
t.Fatal(err)
}
}
func TestNewSignerFromFileEdgeCases(t *testing.T) {
res, err := NewSignerFromFile("nil", "nil", nil)
if res != nil && err == nil {
t.Fatal("Incorrect inputs failed to produce correct results")
}
res, err = NewSignerFromFile(testCaFile, "nil", nil)
if res != nil && err == nil {
t.Fatal("Incorrect inputs failed to produce correct results")
}
res, err = NewSignerFromFile("../../../../../helpers/testdata/messedupcert.pem", "local.go", nil)
if res != nil && err == nil {
t.Fatal("Incorrect inputs failed to produce correct results")
}
res, err = NewSignerFromFile("../../../../../helpers/testdata/cert.pem", "../../../../../helpers/testdata/messed_up_priv_key.pem", nil)
if res != nil && err == nil {
t.Fatal("Incorrect inputs failed to produce correct results")
}
}
// test the private method
func testSign(t *testing.T) {
signer, err := NewSignerFromFile("../../../../../../../signer/local/testdata/ca.pem", "../../../../../../../signer/local/testdata/ca_key.pem", nil)
if signer == nil || err != nil {
t.Fatal("Failed to produce signer")
}
pem, _ := ioutil.ReadFile("../../../../../../../helpers/testdata/cert.pem")
cert, _ := helpers.ParseCertificatePEM(pem)
badcert := *cert
badcert.PublicKey = nil
profl := config.SigningProfile{Usage: []string{"Certificates", "Rule"}}
_, err = signer.sign(&badcert, &profl)
if err == nil {
t.Fatal("Improper input failed to raise an error")
}
// nil profile
_, err = signer.sign(cert, &profl)
if err == nil {
t.Fatal("Nil profile failed to raise an error")
}
// empty profile
_, err = signer.sign(cert, &config.SigningProfile{})
if err == nil {
t.Fatal("Empty profile failed to raise an error")
}
// empty expiry
prof := signer.policy.Default
prof.Expiry = 0
_, err = signer.sign(cert, prof)
if err != nil {
t.Fatal("nil expiry raised an error")
}
// non empty urls
prof = signer.policy.Default
prof.CRL = "stuff"
prof.OCSP = "stuff"
prof.IssuerURL = []string{"stuff"}
_, err = signer.sign(cert, prof)
if err != nil {
t.Fatal("non nil urls raised an error")
}
// nil ca
nilca := *signer
prof = signer.policy.Default
prof.CAConstraint.IsCA = false
nilca.ca = nil
_, err = nilca.sign(cert, prof)
if err == nil {
t.Fatal("nil ca with isca false raised an error")
}
prof.CAConstraint.IsCA = true
_, err = nilca.sign(cert, prof)
if err != nil {
t.Fatal("nil ca with CA true raised an error")
}
}
func TestSign(t *testing.T) {
testSign(t)
s, err := NewSignerFromFile("../../../../../../../signer/local/testdata/ca.pem", "../../../../../../../signer/local/testdata/ca_key.pem", nil)
if err != nil {
t.Fatal("Failed to produce signer")
}
// test the empty request
_, err = s.Sign(signer.SignRequest{})
if err == nil {
t.Fatalf("Empty request failed to produce an error")
}
// not a csr
certPem, err := ioutil.ReadFile("../../../../../helpers/testdata/cert.pem")
if err != nil {
t.Fatal(err)
}
// csr with ip as hostname
pem, err := ioutil.ReadFile("../../../../../../../signer/local/testdata/ip.csr")
if err != nil {
t.Fatal(err)
}
// improper request
validReq := signer.SignRequest{Hosts: signer.SplitHosts(testHostName), Request: string(certPem)}
_, err = s.Sign(validReq)
if err == nil {
t.Fatal("A bad case failed to raise an error")
}
validReq = signer.SignRequest{Hosts: signer.SplitHosts("128.84.126.213"), Request: string(pem)}
_, err = s.Sign(validReq)
if err != nil {
t.Fatal("A bad case failed to raise an error")
}
pem, err = ioutil.ReadFile("../../../../../../../signer/local/testdata/ex.csr")
validReq = signer.SignRequest{
Request: string(pem),
Hosts: []string{"example.com"},
}
s.Sign(validReq)
if err != nil {
t.Fatal("Failed to sign")
}
}
func TestCertificate(t *testing.T) {
s, err := NewSignerFromFile("../../../../../../../signer/local/testdata/ca.pem", "../../../../../../../signer/local/testdata/ca_key.pem", nil)
if err != nil {
t.Fatal(err)
}
c, err := s.Certificate("", "")
if !reflect.DeepEqual(*c, *s.ca) || err != nil {
t.Fatal("Certificate() producing incorrect results")
}
}
func TestPolicy(t *testing.T) {
s, err := NewSignerFromFile("../../../../../../../signer/local/testdata/ca.pem", "../../../../../../../signer/local/testdata/ca_key.pem", nil)
if err != nil {
t.Fatal(err)
}
sgn := config.Signing{}
s.SetPolicy(&sgn)
if s.Policy() != &sgn {
t.Fatal("Policy is malfunctioning")
}
}
func newCustomSigner(t *testing.T, testCaFile, testCaKeyFile string) (s *Signer) {
s, err := NewSignerFromFile(testCaFile, testCaKeyFile, nil)
if err != nil {
t.Fatal(err)
}
return
}
func TestNewSignerFromFile(t *testing.T) {
newTestSigner(t)
}
const (
testHostName = "localhost"
)
func testSignFile(t *testing.T, certFile string) ([]byte, error) {
s := newTestSigner(t)
pem, err := ioutil.ReadFile(certFile)
if err != nil {
t.Fatal(err)
}
return s.Sign(signer.SignRequest{Hosts: signer.SplitHosts(testHostName), Request: string(pem)})
}
type csrTest struct {
file string
keyAlgo string
keyLen int
// Error checking function
errorCallback func(*testing.T, error)
}
// A helper function that returns a errorCallback function which expects an error.
func ExpectError() func(*testing.T, error) {
return func(t *testing.T, err error) {
if err == nil {
t.Fatal("Expected error. Got nothing.")
}
}
}
var csrTests = []csrTest{
{
file: "../../../../../../../signer/local/testdata/rsa2048.csr",
keyAlgo: "rsa",
keyLen: 2048,
errorCallback: nil,
},
{
file: "../../../../../../../signer/local/testdata/rsa3072.csr",
keyAlgo: "rsa",
keyLen: 3072,
errorCallback: nil,
},
{
file: "../../../../../../../signer/local/testdata/rsa4096.csr",
keyAlgo: "rsa",
keyLen: 4096,
errorCallback: nil,
},
{
file: "../../../../../../../signer/local/testdata/ecdsa256.csr",
keyAlgo: "ecdsa",
keyLen: 256,
errorCallback: nil,
},
{
file: "../../../../../../../signer/local/testdata/ecdsa384.csr",
keyAlgo: "ecdsa",
keyLen: 384,
errorCallback: nil,
},
{
file: "../../../../../../../signer/local/testdata/ecdsa521.csr",
keyAlgo: "ecdsa",
keyLen: 521,
errorCallback: nil,
},
{
file: "../../../../../../../signer/local/testdata/rsa-old.csr",
keyAlgo: "rsa",
keyLen: 2048,
errorCallback: nil,
},
}
func TestSignCSRs(t *testing.T) {
s := newTestSigner(t)
hostname := "cloudflare.com"
for _, test := range csrTests {
csr, err := ioutil.ReadFile(test.file)
if err != nil {
t.Fatal("CSR loading error:", err)
}
// It is possible to use different SHA2 algorithm with RSA CA key.
rsaSigAlgos := []x509.SignatureAlgorithm{x509.SHA1WithRSA, x509.SHA256WithRSA, x509.SHA384WithRSA, x509.SHA512WithRSA}
for _, sigAlgo := range rsaSigAlgos {
s.sigAlgo = sigAlgo
certBytes, err := s.Sign(signer.SignRequest{Hosts: signer.SplitHosts(hostname), Request: string(csr)})
if test.errorCallback != nil {
test.errorCallback(t, err)
} else {
if err != nil {
t.Fatalf("Expected no error. Got %s. Param %s %d", err.Error(), test.keyAlgo, test.keyLen)
}
cert, _ := helpers.ParseCertificatePEM(certBytes)
if cert.SignatureAlgorithm != s.SigAlgo() {
t.Fatal("Cert Signature Algorithm does not match the issuer.")
}
}
}
}
}
func TestECDSASigner(t *testing.T) {
s := newCustomSigner(t, testECDSACaFile, testECDSACaKeyFile)
hostname := "cloudflare.com"
for _, test := range csrTests {
csr, err := ioutil.ReadFile(test.file)
if err != nil {
t.Fatal("CSR loading error:", err)
}
// Try all ECDSA SignatureAlgorithm
SigAlgos := []x509.SignatureAlgorithm{x509.ECDSAWithSHA1, x509.ECDSAWithSHA256, x509.ECDSAWithSHA384, x509.ECDSAWithSHA512}
for _, sigAlgo := range SigAlgos {
s.sigAlgo = sigAlgo
certBytes, err := s.Sign(signer.SignRequest{Hosts: signer.SplitHosts(hostname), Request: string(csr)})
if test.errorCallback != nil {
test.errorCallback(t, err)
} else {
if err != nil {
t.Fatalf("Expected no error. Got %s. Param %s %d", err.Error(), test.keyAlgo, test.keyLen)
}
cert, _ := helpers.ParseCertificatePEM(certBytes)
if cert.SignatureAlgorithm != s.SigAlgo() {
t.Fatal("Cert Signature Algorithm does not match the issuer.")
}
}
}
}
}
const (
ecdsaInterCSR = "../../../../../../../signer/local/testdata/ecdsa256-inter.csr"
ecdsaInterKey = "../../../../../../../signer/local/testdata/ecdsa256-inter.key"
rsaInterCSR = "../../../../../../../signer/local/testdata/rsa2048-inter.csr"
rsaInterKey = "../../../../../../../signer/local/testdata/rsa2048-inter.key"
)
func TestCAIssuing(t *testing.T) {
var caCerts = []string{testCaFile, testECDSACaFile}
var caKeys = []string{testCaKeyFile, testECDSACaKeyFile}
var interCSRs = []string{ecdsaInterCSR, rsaInterCSR}
var interKeys = []string{ecdsaInterKey, rsaInterKey}
var CAPolicy = &config.Signing{
Default: &config.SigningProfile{
Usage: []string{"cert sign", "crl sign"},
ExpiryString: "1h",
Expiry: 1 * time.Hour,
CAConstraint: config.CAConstraint{IsCA: true, MaxPathLenZero: true},
},
}
var hostname = "cloudflare-inter.com"
// Each RSA or ECDSA root CA issues two intermediate CAs (one ECDSA and one RSA).
// For each intermediate CA, use it to issue additional RSA and ECDSA intermediate CSRs.
for i, caFile := range caCerts {
caKeyFile := caKeys[i]
s := newCustomSigner(t, caFile, caKeyFile)
s.policy = CAPolicy
for j, csr := range interCSRs {
csrBytes, _ := ioutil.ReadFile(csr)
certBytes, err := s.Sign(signer.SignRequest{Hosts: signer.SplitHosts(hostname), Request: string(csrBytes)})
if err != nil {
t.Fatal(err)
}
interCert, err := helpers.ParseCertificatePEM(certBytes)
if err != nil {
t.Fatal(err)
}
keyBytes, _ := ioutil.ReadFile(interKeys[j])
interKey, _ := helpers.ParsePrivateKeyPEM(keyBytes)
interSigner := &Signer{
ca: interCert,
priv: interKey,
policy: CAPolicy,
sigAlgo: signer.DefaultSigAlgo(interKey),
}
for _, anotherCSR := range interCSRs {
anotherCSRBytes, _ := ioutil.ReadFile(anotherCSR)
bytes, err := interSigner.Sign(
signer.SignRequest{
Hosts: signer.SplitHosts(hostname),
Request: string(anotherCSRBytes),
})
if err != nil {
t.Fatal(err)
}
cert, err := helpers.ParseCertificatePEM(bytes)
if err != nil {
t.Fatal(err)
}
if cert.SignatureAlgorithm != interSigner.SigAlgo() {
t.Fatal("Cert Signature Algorithm does not match the issuer.")
}
if cert.MaxPathLen != 0 {
t.Fatal("CA Cert Max Path is not zero.")
}
if cert.MaxPathLenZero != true {
t.Fatal("CA Cert Max Path is not zero.")
}
}
}
}
}
func TestPopulateSubjectFromCSR(t *testing.T) {
// a subject with all its fields full.
fullSubject := &signer.Subject{
CN: "CN",
Names: []csr.Name{
{
C: "C",
ST: "ST",
L: "L",
O: "O",
OU: "OU",
},
},
SerialNumber: "deadbeef",
}
fullName := pkix.Name{
CommonName: "CommonName",
Country: []string{"Country"},
Province: []string{"Province"},
Organization: []string{"Organization"},
OrganizationalUnit: []string{"OrganizationalUnit"},
SerialNumber: "SerialNumber",
}
noCN := *fullSubject
noCN.CN = ""
name := PopulateSubjectFromCSR(&noCN, fullName)
if name.CommonName != "CommonName" {
t.Fatal("Failed to replace empty common name")
}
noC := *fullSubject
noC.Names[0].C = ""
name = PopulateSubjectFromCSR(&noC, fullName)
if !reflect.DeepEqual(name.Country, fullName.Country) {
t.Fatal("Failed to replace empty country")
}
noL := *fullSubject
noL.Names[0].L = ""
name = PopulateSubjectFromCSR(&noL, fullName)
if !reflect.DeepEqual(name.Locality, fullName.Locality) {
t.Fatal("Failed to replace empty locality")
}
noO := *fullSubject
noO.Names[0].O = ""
name = PopulateSubjectFromCSR(&noO, fullName)
if !reflect.DeepEqual(name.Organization, fullName.Organization) {
t.Fatal("Failed to replace empty organization")
}
noOU := *fullSubject
noOU.Names[0].OU = ""
name = PopulateSubjectFromCSR(&noOU, fullName)
if !reflect.DeepEqual(name.OrganizationalUnit, fullName.OrganizationalUnit) {
t.Fatal("Failed to replace empty organizational unit")
}
noSerial := *fullSubject
noSerial.SerialNumber = ""
name = PopulateSubjectFromCSR(&noSerial, fullName)
if name.SerialNumber != fullName.SerialNumber {
t.Fatalf("Failed to replace empty serial number: want %#v, got %#v", fullName.SerialNumber, name.SerialNumber)
}
}
func TestOverrideSubject(t *testing.T) {
csrPEM, err := ioutil.ReadFile(fullSubjectCSR)
if err != nil {
t.Fatalf("%v", err)
}
req := &signer.Subject{
Names: []csr.Name{
{O: "example.net"},
},
}
s := newCustomSigner(t, testECDSACaFile, testECDSACaKeyFile)
request := signer.SignRequest{
Hosts: []string{"127.0.0.1", "localhost", "xyz@example.com"},
Request: string(csrPEM),
Subject: req,
}
certPEM, err := s.Sign(request)
if err != nil {
t.Fatalf("%v", err)
}
cert, err := helpers.ParseCertificatePEM(certPEM)
if err != nil {
t.Fatalf("%v", err)
}
block, _ := pem.Decode(csrPEM)
template, err := x509.ParseCertificateRequest(block.Bytes)
if err != nil {
t.Fatal(err.Error())
}
if cert.Subject.Organization[0] != "example.net" {
t.Fatalf("Failed to override subject: want example.net but have %s", cert.Subject.Organization[0])
}
if cert.Subject.Country[0] != template.Subject.Country[0] {
t.Fatal("Failed to override Country")
}
if cert.Subject.Locality[0] != template.Subject.Locality[0] {
t.Fatal("Failed to override Locality")
}
if cert.Subject.Organization[0] == template.Subject.Organization[0] {
t.Fatal("Shouldn't have overrode Organization")
}
if cert.Subject.OrganizationalUnit[0] != template.Subject.OrganizationalUnit[0] {
t.Fatal("Failed to override OrganizationalUnit")
}
log.Info("Overrode subject info")
}
func TestOverwriteHosts(t *testing.T) {
for _, csrFile := range []string{testCSR, testSANCSR} {
csrPEM, err := ioutil.ReadFile(csrFile)
if err != nil {
t.Fatal(err)
}
csrDER, _ := pem.Decode([]byte(csrPEM))
if err != nil {
t.Fatal(err)
}
csr, err := x509.ParseCertificateRequest(csrDER.Bytes)
if err != nil {
t.Fatal(err)
}
csrHosts := csr.DNSNames
for _, ip := range csr.IPAddresses {
csrHosts = append(csrHosts, ip.String())
}
sort.Strings(csrHosts)
s := newCustomSigner(t, testECDSACaFile, testECDSACaKeyFile)
for _, hosts := range [][]string{
nil,
{},
{"127.0.0.1", "localhost", "xyz@example.com"},
} {
request := signer.SignRequest{
Hosts: hosts,
Request: string(csrPEM),
Subject: nil,
}
certPEM, err := s.Sign(request)
if err != nil {
t.Fatalf("%v", err)
}
cert, err := helpers.ParseCertificatePEM(certPEM)
if err != nil {
t.Fatalf("%v", err)
}
// get the hosts, and add the ips and email addresses
certHosts := cert.DNSNames
for _, ip := range cert.IPAddresses {
certHosts = append(certHosts, ip.String())
}
for _, email := range cert.EmailAddresses {
certHosts = append(certHosts, email)
}
// compare the sorted host lists
sort.Strings(certHosts)
sort.Strings(request.Hosts)
if len(request.Hosts) > 0 && !reflect.DeepEqual(certHosts, request.Hosts) {
t.Fatalf("Hosts not the same. cert hosts: %v, expected: %v", certHosts, request.Hosts)
}
if request.Hosts == nil && !reflect.DeepEqual(certHosts, csrHosts) {
t.Fatalf("Hosts not the same. cert hosts: %v, expected csr hosts: %v", certHosts, csrHosts)
}
if request.Hosts != nil && len(request.Hosts) == 0 && len(certHosts) != 0 {
t.Fatalf("Hosts not the same. cert hosts: %v, expected: %v", certHosts, request.Hosts)
}
}
}
}
func expectOneValueOf(t *testing.T, s []string, e, n string) {
if len(s) != 1 {
t.Fatalf("Expected %s to have a single value, but it has %d values", n, len(s))
}
if s[0] != e {
t.Fatalf("Expected %s to be '%s', but it is '%s'", n, e, s[0])
}
}
func expectEmpty(t *testing.T, s []string, n string) {
if len(s) != 0 {
t.Fatalf("Expected no values in %s, but have %d values: %v", n, len(s), s)
}
}
func TestCASignPathlen(t *testing.T) {
var csrPathlenTests = []struct {
name string
caCertFile string
caKeyFile string
caProfile bool
csrFile string
err error
pathlen int
isZero bool
isCA bool
}{
{
name: "pathlen 1 signing pathlen 0",
caCertFile: testECDSACaFile,
caKeyFile: testECDSACaKeyFile,
caProfile: true,
csrFile: "../../../../../../../signer/local/testdata/inter_pathlen_0.csr",
err: nil,
pathlen: 0,
isZero: true,
isCA: true,
},
{
name: "pathlen 1 signing pathlen 1",
caCertFile: testECDSACaFile,
caKeyFile: testECDSACaKeyFile,
caProfile: true,
csrFile: "../../../../../../../signer/local/testdata/inter_pathlen_1.csr",
err: cferr.New(cferr.PolicyError, cferr.InvalidRequest),
},
{
name: "pathlen 0 signing pathlen 0",
caCertFile: testCaFile,
caKeyFile: testCaKeyFile,
caProfile: true,
csrFile: "../../../../../../../signer/local/testdata/inter_pathlen_0.csr",
err: cferr.New(cferr.PolicyError, cferr.InvalidRequest),
},
{
name: "pathlen 0 signing pathlen 1",
caCertFile: testCaFile,
caKeyFile: testCaKeyFile,
caProfile: true,
csrFile: "../../../../../../../signer/local/testdata/inter_pathlen_1.csr",
err: cferr.New(cferr.PolicyError, cferr.InvalidRequest),
},
{
name: "pathlen 0 signing pathlen unspecified",
caCertFile: testCaFile,
caKeyFile: testCaKeyFile,
caProfile: true,
csrFile: "../../../../../../../signer/local/testdata/inter_pathlen_unspecified.csr",
err: cferr.New(cferr.PolicyError, cferr.InvalidRequest),
},
{
name: "pathlen 1 signing unspecified pathlen",
caCertFile: testECDSACaFile,
caKeyFile: testECDSACaKeyFile,
caProfile: true,
csrFile: "../../../../../../../signer/local/testdata/inter_pathlen_unspecified.csr",
err: nil,
// golang x509 parses unspecified pathlen as MaxPathLen == -1 and
// MaxPathLenZero == false
pathlen: -1,
isZero: false,
isCA: true,
},
{
name: "non-ca singing profile signing pathlen 0",
caCertFile: testECDSACaFile,
caKeyFile: testECDSACaKeyFile,
caProfile: false,
csrFile: "../../../../../../../signer/local/testdata/inter_pathlen_0.csr",
err: cferr.New(cferr.PolicyError, cferr.InvalidRequest),
},
{
name: "non-ca singing profile signing pathlen 1",
caCertFile: testECDSACaFile,
caKeyFile: testECDSACaKeyFile,
caProfile: false,
csrFile: "../../../../../../../signer/local/testdata/inter_pathlen_1.csr",
err: cferr.New(cferr.PolicyError, cferr.InvalidRequest),
},
{
name: "non-ca singing profile signing pathlen 0",
caCertFile: testECDSACaFile,
caKeyFile: testECDSACaKeyFile,
caProfile: false,
csrFile: "../../../../../../../signer/local/testdata/inter_pathlen_unspecified.csr",
err: cferr.New(cferr.PolicyError, cferr.InvalidRequest),
},
}
for _, testCase := range csrPathlenTests {
csrPEM, err := ioutil.ReadFile(testCase.csrFile)
if err != nil {
t.Fatalf("%v", err)
}
req := &signer.Subject{
Names: []csr.Name{
{O: "sam certificate authority"},
},
CN: "localhost",
}
s := newCustomSigner(t, testCase.caCertFile, testCase.caKeyFile)
// No policy CSR whitelist: the normal set of CSR fields get passed through to
// certificate.
s.policy = &config.Signing{
Default: &config.SigningProfile{
Usage: []string{"cert sign", "crl sign"},
ExpiryString: "1h",
Expiry: 1 * time.Hour,
CAConstraint: config.CAConstraint{IsCA: testCase.caProfile,
MaxPathLen: testCase.pathlen,
MaxPathLenZero: testCase.isZero,
},
},
}
request := signer.SignRequest{
Hosts: []string{"127.0.0.1", "localhost"},
Request: string(csrPEM),
Subject: req,
}
certPEM, err := s.Sign(request)
if !reflect.DeepEqual(err, testCase.err) {
t.Fatalf("%s: expected: %v, actual: %v", testCase.name, testCase.err, err)
}
if err == nil {
cert, err := helpers.ParseCertificatePEM(certPEM)
if err != nil {
t.Fatalf("%s: %v", testCase.name, err)
}
if cert.IsCA != testCase.isCA {
t.Fatalf("%s: unexpected IsCA value: %v", testCase.name, cert.IsCA)
}
if cert.MaxPathLen != testCase.pathlen {
t.Fatalf("%s: unexpected pathlen value: %v", testCase.name, cert.MaxPathLen)
}
if cert.MaxPathLenZero != testCase.isZero {
t.Fatalf("%s: unexpected pathlen value: %v", testCase.name, cert.MaxPathLenZero)
}
}
}
}
func TestNoWhitelistSign(t *testing.T) {
csrPEM, err := ioutil.ReadFile(fullSubjectCSR)
if err != nil {
t.Fatalf("%v", err)
}
req := &signer.Subject{
Names: []csr.Name{
{O: "sam certificate authority"},
},
CN: "localhost",
}
s := newCustomSigner(t, testECDSACaFile, testECDSACaKeyFile)
// No policy CSR whitelist: the normal set of CSR fields get passed through to
// certificate.
s.policy = &config.Signing{
Default: &config.SigningProfile{
Usage: []string{"cert sign", "crl sign"},
ExpiryString: "1h",
Expiry: 1 * time.Hour,
CAConstraint: config.CAConstraint{IsCA: true},
},
}
request := signer.SignRequest{
Hosts: []string{"127.0.0.1", "localhost"},
Request: string(csrPEM),
Subject: req,
}
certPEM, err := s.Sign(request)
if err != nil {
t.Fatalf("%v", err)
}
cert, err := helpers.ParseCertificatePEM(certPEM)
if err != nil {
t.Fatalf("%v", err)
}
name := cert.Subject
if name.CommonName != "localhost" {
t.Fatalf("Expected certificate common name to be 'localhost' but have '%v'", name.CommonName)
}
// CSR has: Subject: C=US, O=CloudFlare, OU=WWW, L=Ithaca, ST=New York
// Expect all to be passed through.
expectOneValueOf(t, name.Organization, "sam certificate authority", "O")
expectOneValueOf(t, name.OrganizationalUnit, "WWW", "OU")
expectOneValueOf(t, name.Province, "New York", "ST")
expectOneValueOf(t, name.Locality, "Ithaca", "L")
expectOneValueOf(t, name.Country, "US", "C")
}
func TestWhitelistSign(t *testing.T) {
csrPEM, err := ioutil.ReadFile(fullSubjectCSR)
if err != nil {
t.Fatalf("%v", err)
}
req := &signer.Subject{
Names: []csr.Name{
{O: "sam certificate authority"},
},
}
s := newCustomSigner(t, testECDSACaFile, testECDSACaKeyFile)
// Whitelist only key-related fields. Subject, DNSNames, etc shouldn't get
// passed through from CSR.
s.policy = &config.Signing{
Default: &config.SigningProfile{
Usage: []string{"cert sign", "crl sign"},
ExpiryString: "1h",
Expiry: 1 * time.Hour,
CAConstraint: config.CAConstraint{IsCA: true},
CSRWhitelist: &config.CSRWhitelist{
PublicKey: true,
PublicKeyAlgorithm: true,
SignatureAlgorithm: true,
},
},
}
request := signer.SignRequest{
Hosts: []string{"127.0.0.1", "localhost"},
Request: string(csrPEM),
Subject: req,
}
certPEM, err := s.Sign(request)
if err != nil {
t.Fatalf("%v", err)
}
cert, err := helpers.ParseCertificatePEM(certPEM)
if err != nil {
t.Fatalf("%v", err)
}
name := cert.Subject
if name.CommonName != "" {
t.Fatalf("Expected empty certificate common name under policy without "+
"Subject whitelist, got %v", name.CommonName)
}
// O is provided by the signing API request, not the CSR, so it's allowed to
// be copied into the certificate.
expectOneValueOf(t, name.Organization, "sam certificate authority", "O")
expectEmpty(t, name.OrganizationalUnit, "OU")
expectEmpty(t, name.Province, "ST")
expectEmpty(t, name.Locality, "L")
expectEmpty(t, name.Country, "C")
if cert.PublicKeyAlgorithm != x509.RSA {
t.Fatalf("Expected public key algorithm to be RSA")
}
// Signature algorithm is allowed to be copied from CSR, but is overridden by
// DefaultSigAlgo.
if cert.SignatureAlgorithm != x509.ECDSAWithSHA256 {
t.Fatalf("Expected public key algorithm to be ECDSAWithSHA256, got %v",
cert.SignatureAlgorithm)
}
}
func TestNameWhitelistSign(t *testing.T) {
csrPEM, err := ioutil.ReadFile(fullSubjectCSR)
if err != nil {
t.Fatalf("%v", err)
}
subInvalid := &signer.Subject{
CN: "localhost.com",
}
subValid := &signer.Subject{
CN: "1lab41.cf",
}
wl := regexp.MustCompile("^1[a-z]*[0-9]*\\.cf$")
s := newCustomSigner(t, testECDSACaFile, testECDSACaKeyFile)
// Whitelist only key-related fields. Subject, DNSNames, etc shouldn't get
// passed through from CSR.
s.policy = &config.Signing{
Default: &config.SigningProfile{
Usage: []string{"cert sign", "crl sign"},
ExpiryString: "1h",
Expiry: 1 * time.Hour,
CAConstraint: config.CAConstraint{IsCA: true},
NameWhitelist: wl,
},
}
request := signer.SignRequest{
Hosts: []string{"127.0.0.1", "1machine23.cf"},
Request: string(csrPEM),
}
_, err = s.Sign(request)
if err != nil {
t.Fatalf("%v", err)
}
request = signer.SignRequest{
Hosts: []string{"invalid.cf", "1machine23.cf"},
Request: string(csrPEM),
}
_, err = s.Sign(request)
if err == nil {
t.Fatalf("expected a policy error")
}
request = signer.SignRequest{
Hosts: []string{"1machine23.cf"},
Request: string(csrPEM),
Subject: subInvalid,
}
_, err = s.Sign(request)
if err == nil {
t.Fatalf("expected a policy error")
}
request = signer.SignRequest{
Hosts: []string{"1machine23.cf"},
Request: string(csrPEM),
Subject: subValid,
}
_, err = s.Sign(request)
if err != nil {
t.Fatalf("%v", err)
}
}
func TestExtensionSign(t *testing.T) {
csrPEM, err := ioutil.ReadFile(testCSR)
if err != nil {
t.Fatalf("%v", err)
}
s := newCustomSigner(t, testECDSACaFile, testECDSACaKeyFile)
// By default, no extensions should be allowed
request := signer.SignRequest{
Request: string(csrPEM),
Extensions: []signer.Extension{
{ID: config.OID(asn1.ObjectIdentifier{1, 2, 3, 4})},
},
}
_, err = s.Sign(request)
if err == nil {
t.Fatalf("expected a policy error")
}
// Whitelist a specific extension. The extension with OID 1.2.3.4 should be
// allowed through, but the one with OID 1.2.3.5 should not.
s.policy = &config.Signing{
Default: &config.SigningProfile{
Usage: []string{"cert sign", "crl sign"},
ExpiryString: "1h",
Expiry: 1 * time.Hour,
CAConstraint: config.CAConstraint{IsCA: true},
ExtensionWhitelist: map[string]bool{"1.2.3.4": true},
},
}
// Test that a forbidden extension triggers a sign error
request = signer.SignRequest{
Request: string(csrPEM),
Extensions: []signer.Extension{
{ID: config.OID(asn1.ObjectIdentifier{1, 2, 3, 5})},
},
}
_, err = s.Sign(request)
if err == nil {
t.Fatalf("expected a policy error")
}
extValue := []byte{0x05, 0x00}
extValueHex := hex.EncodeToString(extValue)
// Test that an allowed extension makes it through
request = signer.SignRequest{
Request: string(csrPEM),
Extensions: []signer.Extension{
{
ID: config.OID(asn1.ObjectIdentifier{1, 2, 3, 4}),
Critical: false,
Value: extValueHex,
},
},
}
certPEM, err := s.Sign(request)
if err != nil {
t.Fatalf("%v", err)
}
cert, err := helpers.ParseCertificatePEM(certPEM)
if err != nil {
t.Fatalf("%v", err)
}
foundAllowed := false
for _, ext := range cert.Extensions {
if ext.Id.String() == "1.2.3.4" {
foundAllowed = true
if ext.Critical {
t.Fatalf("Extensions should not be marked critical")
}
if !bytes.Equal(extValue, ext.Value) {
t.Fatalf("Extension has wrong value: %s != %s", hex.EncodeToString(ext.Value), extValueHex)
}
}
}
if !foundAllowed {
t.Fatalf("Custom extension not included in the certificate")
}
}
func TestCTFailure(t *testing.T) {
// start a fake CT server that returns bad request
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(400)
}))
defer ts.Close()
var config = &config.Signing{
Default: &config.SigningProfile{
Expiry: helpers.OneYear,
CAConstraint: config.CAConstraint{IsCA: true},
Usage: []string{"signing", "key encipherment", "server auth", "client auth"},
ExpiryString: "8760h",
CTLogServers: []string{ts.URL},
},
}
testSigner, err := NewSignerFromFile(testCaFile, testCaKeyFile, config)
if err != nil {
t.Fatalf("%v", err)
}
var pem []byte
pem, err = ioutil.ReadFile("../../../../../../../signer/local/testdata/ex.csr")
if err != nil {
t.Fatalf("%v", err)
}
validReq := signer.SignRequest{
Request: string(pem),
Hosts: []string{"example.com"},
}
_, err = testSigner.Sign(validReq)
if err == nil {
t.Fatal("Expected CT log submission failure")
}
}
func TestCTSuccess(t *testing.T) {
// start a fake CT server that will accept the submission
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"sct_version":0,"id":"KHYaGJAn++880NYaAY12sFBXKcenQRvMvfYE9F1CYVM=","timestamp":1337,"extensions":"","signature":"BAMARjBEAiAIc21J5ZbdKZHw5wLxCP+MhBEsV5+nfvGyakOIv6FOvAIgWYMZb6Pw///uiNM7QTg2Of1OqmK1GbeGuEl9VJN8v8c="}`))
w.WriteHeader(200)
}))
defer ts.Close()
var config = &config.Signing{
Default: &config.SigningProfile{
Expiry: helpers.OneYear,
CAConstraint: config.CAConstraint{IsCA: true},
Usage: []string{"signing", "key encipherment", "server auth", "client auth"},
ExpiryString: "8760h",
CTLogServers: []string{ts.URL},
},
}
testSigner, err := NewSignerFromFile(testCaFile, testCaKeyFile, config)
if err != nil {
t.Fatalf("%v", err)
}
var pem []byte
pem, err = ioutil.ReadFile("../../../../../../../signer/local/testdata/ex.csr")
if err != nil {
t.Fatalf("%v", err)
}
validReq := signer.SignRequest{
Request: string(pem),
Hosts: []string{"example.com"},
}
_, err = testSigner.Sign(validReq)
if err != nil {
t.Fatal("Expected CT log submission success")
}
}
|