util.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. // SetupCertificateAuthority is a utility function for kubeadm testing that creates a
  26. // CertificateAuthority cert/key pair
  27. func SetupCertificateAuthority(t *testing.T) (*x509.Certificate, crypto.Signer) {
  28. caCert, caKey, err := pkiutil.NewCertificateAuthority(&pkiutil.CertConfig{
  29. Config: certutil.Config{CommonName: "kubernetes"},
  30. })
  31. if err != nil {
  32. t.Fatalf("failure while generating CA certificate and key: %v", err)
  33. }
  34. return caCert, caKey
  35. }
  36. // AssertCertificateIsSignedByCa is a utility function for kubeadm testing that asserts if a given certificate is signed
  37. // by the expected CA
  38. func AssertCertificateIsSignedByCa(t *testing.T, cert *x509.Certificate, signingCa *x509.Certificate) {
  39. if err := cert.CheckSignatureFrom(signingCa); err != nil {
  40. t.Error("cert is not signed by signing CA as expected")
  41. }
  42. }
  43. // AssertCertificateHasCommonName is a utility function for kubeadm testing that asserts if a given certificate has
  44. // the expected SubjectCommonName
  45. func AssertCertificateHasCommonName(t *testing.T, cert *x509.Certificate, commonName string) {
  46. if cert.Subject.CommonName != commonName {
  47. t.Errorf("cert has Subject.CommonName %s, expected %s", cert.Subject.CommonName, commonName)
  48. }
  49. }
  50. // AssertCertificateHasOrganizations is a utility function for kubeadm testing that asserts if a given certificate has
  51. // the expected Subject.Organization
  52. func AssertCertificateHasOrganizations(t *testing.T, cert *x509.Certificate, organizations ...string) {
  53. for _, organization := range organizations {
  54. found := false
  55. for i := range cert.Subject.Organization {
  56. if cert.Subject.Organization[i] == organization {
  57. found = true
  58. }
  59. }
  60. if !found {
  61. t.Errorf("cert does not contain Subject.Organization %s as expected", organization)
  62. }
  63. }
  64. }
  65. // AssertCertificateHasClientAuthUsage is a utility function for kubeadm testing that asserts if a given certificate has
  66. // the expected ExtKeyUsageClientAuth
  67. func AssertCertificateHasClientAuthUsage(t *testing.T, cert *x509.Certificate) {
  68. for i := range cert.ExtKeyUsage {
  69. if cert.ExtKeyUsage[i] == x509.ExtKeyUsageClientAuth {
  70. return
  71. }
  72. }
  73. t.Error("cert has not ClientAuth usage as expected")
  74. }
  75. // AssertCertificateHasServerAuthUsage is a utility function for kubeadm testing that asserts if a given certificate has
  76. // the expected ExtKeyUsageServerAuth
  77. func AssertCertificateHasServerAuthUsage(t *testing.T, cert *x509.Certificate) {
  78. for i := range cert.ExtKeyUsage {
  79. if cert.ExtKeyUsage[i] == x509.ExtKeyUsageServerAuth {
  80. return
  81. }
  82. }
  83. t.Error("cert is not a ServerAuth")
  84. }
  85. // AssertCertificateHasDNSNames is a utility function for kubeadm testing that asserts if a given certificate has
  86. // the expected DNSNames
  87. func AssertCertificateHasDNSNames(t *testing.T, cert *x509.Certificate, DNSNames ...string) {
  88. for _, DNSName := range DNSNames {
  89. found := false
  90. for _, val := range cert.DNSNames {
  91. if val == DNSName {
  92. found = true
  93. break
  94. }
  95. }
  96. if !found {
  97. t.Errorf("cert does not contain DNSName %s", DNSName)
  98. }
  99. }
  100. }
  101. // AssertCertificateHasIPAddresses is a utility function for kubeadm testing that asserts if a given certificate has
  102. // the expected IPAddresses
  103. func AssertCertificateHasIPAddresses(t *testing.T, cert *x509.Certificate, IPAddresses ...net.IP) {
  104. for _, IPAddress := range IPAddresses {
  105. found := false
  106. for _, val := range cert.IPAddresses {
  107. if val.Equal(IPAddress) {
  108. found = true
  109. break
  110. }
  111. }
  112. if !found {
  113. t.Errorf("cert does not contain IPAddress %s", IPAddress)
  114. }
  115. }
  116. }
  117. // CreateCACert creates a generic CA cert.
  118. func CreateCACert(t *testing.T) (*x509.Certificate, crypto.Signer) {
  119. certCfg := &pkiutil.CertConfig{Config: certutil.Config{CommonName: "kubernetes"}}
  120. cert, key, err := pkiutil.NewCertificateAuthority(certCfg)
  121. if err != nil {
  122. t.Fatalf("couldn't create CA: %v", err)
  123. }
  124. return cert, key
  125. }
  126. // CreateTestCert makes a generic certificate with the given CA and alternative names.
  127. func CreateTestCert(t *testing.T, caCert *x509.Certificate, caKey crypto.Signer, altNames certutil.AltNames) (*x509.Certificate, crypto.Signer, *pkiutil.CertConfig) {
  128. config := &pkiutil.CertConfig{
  129. Config: certutil.Config{
  130. CommonName: "testCert",
  131. Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  132. AltNames: altNames,
  133. },
  134. }
  135. cert, key, err := pkiutil.NewCertAndKey(caCert, caKey, config)
  136. if err != nil {
  137. t.Fatalf("couldn't create test cert: %v", err)
  138. }
  139. return cert, key, config
  140. }
  141. // CertTestCase is a configuration of certificates and whether it's expected to work.
  142. type CertTestCase struct {
  143. Name string
  144. Files PKIFiles
  145. ExpectError bool
  146. }
  147. // GetSparseCertTestCases produces a series of cert configurations and their intended outcomes.
  148. func GetSparseCertTestCases(t *testing.T) []CertTestCase {
  149. caCert, caKey := CreateCACert(t)
  150. fpCACert, fpCAKey := CreateCACert(t)
  151. etcdCACert, etcdCAKey := CreateCACert(t)
  152. fpCert, fpKey, _ := CreateTestCert(t, fpCACert, fpCAKey, certutil.AltNames{})
  153. return []CertTestCase{
  154. {
  155. Name: "nothing present",
  156. },
  157. {
  158. Name: "CAs already exist",
  159. Files: PKIFiles{
  160. "ca.crt": caCert,
  161. "ca.key": caKey,
  162. "front-proxy-ca.crt": fpCACert,
  163. "front-proxy-ca.key": fpCAKey,
  164. "etcd/ca.crt": etcdCACert,
  165. "etcd/ca.key": etcdCAKey,
  166. },
  167. },
  168. {
  169. Name: "CA certs only",
  170. Files: PKIFiles{
  171. "ca.crt": caCert,
  172. "front-proxy-ca.crt": fpCACert,
  173. "etcd/ca.crt": etcdCACert,
  174. },
  175. ExpectError: true,
  176. },
  177. {
  178. Name: "FrontProxyCA with certs",
  179. Files: PKIFiles{
  180. "ca.crt": caCert,
  181. "ca.key": caKey,
  182. "front-proxy-ca.crt": fpCACert,
  183. "front-proxy-client.crt": fpCert,
  184. "front-proxy-client.key": fpKey,
  185. "etcd/ca.crt": etcdCACert,
  186. "etcd/ca.key": etcdCAKey,
  187. },
  188. },
  189. {
  190. Name: "FrontProxy certs missing CA",
  191. Files: PKIFiles{
  192. "front-proxy-client.crt": fpCert,
  193. "front-proxy-client.key": fpKey,
  194. },
  195. ExpectError: true,
  196. },
  197. }
  198. }
  199. // PKIFiles are a list of files that should be created for a test case
  200. type PKIFiles map[string]interface{}
  201. // WritePKIFiles writes the given files out to the given directory
  202. func WritePKIFiles(t *testing.T, dir string, files PKIFiles) {
  203. for filename, body := range files {
  204. switch body := body.(type) {
  205. case *x509.Certificate:
  206. if err := certutil.WriteCert(path.Join(dir, filename), pkiutil.EncodeCertPEM(body)); err != nil {
  207. t.Errorf("unable to write certificate to file %q: [%v]", dir, err)
  208. }
  209. case *rsa.PublicKey:
  210. publicKeyBytes, err := pkiutil.EncodePublicKeyPEM(body)
  211. if err != nil {
  212. t.Errorf("unable to write public key to file %q: [%v]", filename, err)
  213. }
  214. if err := keyutil.WriteKey(path.Join(dir, filename), publicKeyBytes); err != nil {
  215. t.Errorf("unable to write public key to file %q: [%v]", filename, err)
  216. }
  217. case *rsa.PrivateKey:
  218. privateKey, err := keyutil.MarshalPrivateKeyToPEM(body)
  219. if err != nil {
  220. t.Errorf("unable to write private key to file %q: [%v]", filename, err)
  221. }
  222. if err := keyutil.WriteKey(path.Join(dir, filename), privateKey); err != nil {
  223. t.Errorf("unable to write private key to file %q: [%v]", filename, err)
  224. }
  225. }
  226. }
  227. }