@@ -17,16 +17,24 @@ limitations under the License.
1717package vcsim
1818
1919import (
20+ "crypto/rand"
2021 "crypto/tls"
22+ "crypto/x509"
23+ "crypto/x509/pkix"
2124 "fmt"
25+ "math/big"
26+ "net"
2227 "net/url"
2328 "os"
2429 "os/exec"
2530 "strings"
31+ "time"
2632
2733 "github.com/onsi/gomega/gbytes"
34+ "github.com/pkg/errors"
2835 "github.com/vmware/govmomi/simulator"
2936 _ "github.com/vmware/govmomi/vapi/cluster/simulator" // import this to register cluster module service test endpoint
37+ "sigs.k8s.io/cluster-api/util/certs"
3038)
3139
3240// Builder helps in creating a vcsim simulator.
@@ -81,6 +89,12 @@ func (b *Builder) Build() (*Simulator, error) {
8189 }
8290
8391 b .model .Service .TLS = new (tls.Config )
92+ keyPair , err := generateTLSKeyPair ()
93+ if err != nil {
94+ return nil , err
95+ }
96+
97+ b .model .Service .TLS .Certificates = append (b .model .Service .TLS .Certificates , keyPair )
8498 b .model .Service .RegisterEndpoints = true
8599 server := b .model .Service .NewServer ()
86100 simr := & Simulator {
@@ -119,3 +133,47 @@ func govcCommand(govcURL, commandStr string, buffers ...*gbytes.Buffer) *exec.Cm
119133 }
120134 return cmd
121135}
136+
137+ // generateTLSKeyPair generates a self-signed certificatge keypair similar to the
138+ // hardcoded values in github.com/vmware/govmomi/simulator/internal but adds the
139+ // POD_IP to the IP Addresses of the certificate.
140+ func generateTLSKeyPair () (tls.Certificate , error ) {
141+ privateKey , err := certs .NewPrivateKey ()
142+ if err != nil {
143+ return tls.Certificate {}, err
144+ }
145+
146+ template := x509.Certificate {
147+ SerialNumber : new (big.Int ).SetInt64 (0 ),
148+ Subject : pkix.Name {
149+ Organization : []string {"CAPV vcsim" },
150+ },
151+ NotBefore : time .Now ().Add (time .Minute * - 5 ),
152+ NotAfter : time .Now ().Add (time .Hour * 24 * 365 ),
153+
154+ KeyUsage : x509 .KeyUsageDigitalSignature | x509 .KeyUsageKeyEncipherment | x509 .KeyUsageCertSign ,
155+ ExtKeyUsage : []x509.ExtKeyUsage {x509 .ExtKeyUsageServerAuth },
156+ BasicConstraintsValid : true ,
157+ IsCA : true ,
158+ IPAddresses : []net.IP {
159+ net .ParseIP ("127.0.0.1" ),
160+ net .ParseIP ("::1" ),
161+ },
162+ }
163+
164+ if ip := os .Getenv ("POD_IP" ); ip != "" {
165+ template .IPAddresses = append (template .IPAddresses , net .ParseIP (ip ))
166+ }
167+
168+ b , err := x509 .CreateCertificate (rand .Reader , & template , & template , & privateKey .PublicKey , privateKey )
169+ if err != nil {
170+ return tls.Certificate {}, errors .Wrap (err , "failed to create certificate" )
171+ }
172+
173+ cert , err := x509 .ParseCertificate (b )
174+ if err != nil {
175+ return tls.Certificate {}, errors .Wrap (err , "failed to parse certificate" )
176+ }
177+
178+ return tls .X509KeyPair (certs .EncodeCertPEM (cert ), certs .EncodePrivateKeyPEM (privateKey ))
179+ }
0 commit comments