util.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package certs
  14. import (
  15. "crypto"
  16. "crypto/rsa"
  17. "crypto/x509"
  18. "net"
  19. "path"
  20. "testing"
  21. certutil "k8s.io/client-go/util/cert"
  22. "k8s.io/client-go/util/keyutil"
  23. pkiutil "k8s.io/kubernetes/cmd/kubeadm/app/util/pkiutil"
  24. )
  25. // SetupCertificateAuthorithy is a utility function for kubeadm testing that creates a
  26. // CertificateAuthorithy cert/key pair
  27. func SetupCertificateAuthorithy(t *testing.T) (*x509.Certificate, crypto.Signer) {
  28. caCert, caKey, err := pkiutil.NewCertificateAuthority(&certutil.Config{CommonName: "kubernetes"})
  29. if err != nil {
  30. t.Fatalf("failure while generating CA certificate and key: %v", err)
  31. }
  32. return caCert, caKey
  33. }
  34. // AssertCertificateIsSignedByCa is a utility function for kubeadm testing that asserts if a given certificate is signed
  35. // by the expected CA
  36. func AssertCertificateIsSignedByCa(t *testing.T, cert *x509.Certificate, signingCa *x509.Certificate) {
  37. if err := cert.CheckSignatureFrom(signingCa); err != nil {
  38. t.Error("cert is not signed by signing CA as expected")
  39. }
  40. }
  41. // AssertCertificateHasCommonName is a utility function for kubeadm testing that asserts if a given certificate has
  42. // the expected SubjectCommonName
  43. func AssertCertificateHasCommonName(t *testing.T, cert *x509.Certificate, commonName string) {
  44. if cert.Subject.CommonName != commonName {
  45. t.Errorf("cert has Subject.CommonName %s, expected %s", cert.Subject.CommonName, commonName)
  46. }
  47. }
  48. // AssertCertificateHasOrganizations is a utility function for kubeadm testing that asserts if a given certificate has
  49. // the expected Subject.Organization
  50. func AssertCertificateHasOrganizations(t *testing.T, cert *x509.Certificate, organizations ...string) {
  51. for _, organization := range organizations {
  52. found := false
  53. for i := range cert.Subject.Organization {
  54. if cert.Subject.Organization[i] == organization {
  55. found = true
  56. }
  57. }
  58. if !found {
  59. t.Errorf("cert does not contain Subject.Organization %s as expected", organization)
  60. }
  61. }
  62. }
  63. // AssertCertificateHasClientAuthUsage is a utility function for kubeadm testing that asserts if a given certificate has
  64. // the expected ExtKeyUsageClientAuth
  65. func AssertCertificateHasClientAuthUsage(t *testing.T, cert *x509.Certificate) {
  66. for i := range cert.ExtKeyUsage {
  67. if cert.ExtKeyUsage[i] == x509.ExtKeyUsageClientAuth {
  68. return
  69. }
  70. }
  71. t.Error("cert has not ClientAuth usage as expected")
  72. }
  73. // AssertCertificateHasServerAuthUsage is a utility function for kubeadm testing that asserts if a given certificate has
  74. // the expected ExtKeyUsageServerAuth
  75. func AssertCertificateHasServerAuthUsage(t *testing.T, cert *x509.Certificate) {
  76. for i := range cert.ExtKeyUsage {
  77. if cert.ExtKeyUsage[i] == x509.ExtKeyUsageServerAuth {
  78. return
  79. }
  80. }
  81. t.Error("cert is not a ServerAuth")
  82. }
  83. // AssertCertificateHasDNSNames is a utility function for kubeadm testing that asserts if a given certificate has
  84. // the expected DNSNames
  85. func AssertCertificateHasDNSNames(t *testing.T, cert *x509.Certificate, DNSNames ...string) {
  86. for _, DNSName := range DNSNames {
  87. found := false
  88. for _, val := range cert.DNSNames {
  89. if val == DNSName {
  90. found = true
  91. break
  92. }
  93. }
  94. if !found {
  95. t.Errorf("cert does not contain DNSName %s", DNSName)
  96. }
  97. }
  98. }
  99. // AssertCertificateHasIPAddresses is a utility function for kubeadm testing that asserts if a given certificate has
  100. // the expected IPAddresses
  101. func AssertCertificateHasIPAddresses(t *testing.T, cert *x509.Certificate, IPAddresses ...net.IP) {
  102. for _, IPAddress := range IPAddresses {
  103. found := false
  104. for _, val := range cert.IPAddresses {
  105. if val.Equal(IPAddress) {
  106. found = true
  107. break
  108. }
  109. }
  110. if !found {
  111. t.Errorf("cert does not contain IPAddress %s", IPAddress)
  112. }
  113. }
  114. }
  115. // CreateCACert creates a generic CA cert.
  116. func CreateCACert(t *testing.T) (*x509.Certificate, crypto.Signer) {
  117. certCfg := &certutil.Config{CommonName: "kubernetes"}
  118. cert, key, err := pkiutil.NewCertificateAuthority(certCfg)
  119. if err != nil {
  120. t.Fatalf("couldn't create CA: %v", err)
  121. }
  122. return cert, key
  123. }
  124. // CreateTestCert makes a generic certificate with the given CA and alternative names.
  125. func CreateTestCert(t *testing.T, caCert *x509.Certificate, caKey crypto.Signer, altNames certutil.AltNames) (*x509.Certificate, crypto.Signer, *certutil.Config) {
  126. config := &certutil.Config{
  127. CommonName: "testCert",
  128. Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  129. AltNames: altNames,
  130. }
  131. cert, key, err := pkiutil.NewCertAndKey(caCert, caKey, config)
  132. if err != nil {
  133. t.Fatalf("couldn't create test cert: %v", err)
  134. }
  135. return cert, key, config
  136. }
  137. // CertTestCase is a configuration of certificates and whether it's expected to work.
  138. type CertTestCase struct {
  139. Name string
  140. Files PKIFiles
  141. ExpectError bool
  142. }
  143. // GetSparseCertTestCases produces a series of cert configurations and their intended outcomes.
  144. func GetSparseCertTestCases(t *testing.T) []CertTestCase {
  145. caCert, caKey := CreateCACert(t)
  146. fpCACert, fpCAKey := CreateCACert(t)
  147. etcdCACert, etcdCAKey := CreateCACert(t)
  148. fpCert, fpKey, _ := CreateTestCert(t, fpCACert, fpCAKey, certutil.AltNames{})
  149. return []CertTestCase{
  150. {
  151. Name: "nothing present",
  152. },
  153. {
  154. Name: "CAs already exist",
  155. Files: PKIFiles{
  156. "ca.crt": caCert,
  157. "ca.key": caKey,
  158. "front-proxy-ca.crt": fpCACert,
  159. "front-proxy-ca.key": fpCAKey,
  160. "etcd/ca.crt": etcdCACert,
  161. "etcd/ca.key": etcdCAKey,
  162. },
  163. },
  164. {
  165. Name: "CA certs only",
  166. Files: PKIFiles{
  167. "ca.crt": caCert,
  168. "front-proxy-ca.crt": fpCACert,
  169. "etcd/ca.crt": etcdCACert,
  170. },
  171. ExpectError: true,
  172. },
  173. {
  174. Name: "FrontProxyCA with certs",
  175. Files: PKIFiles{
  176. "ca.crt": caCert,
  177. "ca.key": caKey,
  178. "front-proxy-ca.crt": fpCACert,
  179. "front-proxy-client.crt": fpCert,
  180. "front-proxy-client.key": fpKey,
  181. "etcd/ca.crt": etcdCACert,
  182. "etcd/ca.key": etcdCAKey,
  183. },
  184. },
  185. {
  186. Name: "FrontProxy certs missing CA",
  187. Files: PKIFiles{
  188. "front-proxy-client.crt": fpCert,
  189. "front-proxy-client.key": fpKey,
  190. },
  191. ExpectError: true,
  192. },
  193. }
  194. }
  195. // PKIFiles are a list of files that should be created for a test case
  196. type PKIFiles map[string]interface{}
  197. // WritePKIFiles writes the given files out to the given directory
  198. func WritePKIFiles(t *testing.T, dir string, files PKIFiles) {
  199. for filename, body := range files {
  200. switch body := body.(type) {
  201. case *x509.Certificate:
  202. if err := certutil.WriteCert(path.Join(dir, filename), pkiutil.EncodeCertPEM(body)); err != nil {
  203. t.Errorf("unable to write certificate to file %q: [%v]", dir, err)
  204. }
  205. case *rsa.PublicKey:
  206. publicKeyBytes, err := pkiutil.EncodePublicKeyPEM(body)
  207. if err != nil {
  208. t.Errorf("unable to write public key to file %q: [%v]", filename, err)
  209. }
  210. if err := keyutil.WriteKey(path.Join(dir, filename), publicKeyBytes); err != nil {
  211. t.Errorf("unable to write public key to file %q: [%v]", filename, err)
  212. }
  213. case *rsa.PrivateKey:
  214. privateKey, err := keyutil.MarshalPrivateKeyToPEM(body)
  215. if err != nil {
  216. t.Errorf("unable to write private key to file %q: [%v]", filename, err)
  217. }
  218. if err := keyutil.WriteKey(path.Join(dir, filename), privateKey); err != nil {
  219. t.Errorf("unable to write private key to file %q: [%v]", filename, err)
  220. }
  221. }
  222. }
  223. }