host_certificate_info.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. /*
  2. Copyright (c) 2016-2023 VMware, Inc. All Rights Reserved.
  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 object
  14. import (
  15. "crypto/tls"
  16. "crypto/x509"
  17. "crypto/x509/pkix"
  18. "encoding/asn1"
  19. "fmt"
  20. "io"
  21. "net/url"
  22. "strings"
  23. "text/tabwriter"
  24. "github.com/vmware/govmomi/vim25/soap"
  25. "github.com/vmware/govmomi/vim25/types"
  26. )
  27. // HostCertificateInfo provides helpers for types.HostCertificateManagerCertificateInfo
  28. type HostCertificateInfo struct {
  29. types.HostCertificateManagerCertificateInfo
  30. ThumbprintSHA1 string `json:"thumbprintSHA1"`
  31. ThumbprintSHA256 string `json:"thumbprintSHA256"`
  32. Err error `json:"err"`
  33. Certificate *x509.Certificate `json:"-"`
  34. subjectName *pkix.Name
  35. issuerName *pkix.Name
  36. }
  37. // FromCertificate converts x509.Certificate to HostCertificateInfo
  38. func (info *HostCertificateInfo) FromCertificate(cert *x509.Certificate) *HostCertificateInfo {
  39. info.Certificate = cert
  40. info.subjectName = &cert.Subject
  41. info.issuerName = &cert.Issuer
  42. info.Issuer = info.fromName(info.issuerName)
  43. info.NotBefore = &cert.NotBefore
  44. info.NotAfter = &cert.NotAfter
  45. info.Subject = info.fromName(info.subjectName)
  46. info.ThumbprintSHA1 = soap.ThumbprintSHA1(cert)
  47. info.ThumbprintSHA256 = soap.ThumbprintSHA256(cert)
  48. if info.Status == "" {
  49. info.Status = string(types.HostCertificateManagerCertificateInfoCertificateStatusUnknown)
  50. }
  51. return info
  52. }
  53. // FromURL connects to the given URL.Host via tls.Dial with the given tls.Config and populates the HostCertificateInfo
  54. // via tls.ConnectionState. If the certificate was verified with the given tls.Config, the Err field will be nil.
  55. // Otherwise, Err will be set to the x509.UnknownAuthorityError or x509.HostnameError.
  56. // If tls.Dial returns an error of any other type, that error is returned.
  57. func (info *HostCertificateInfo) FromURL(u *url.URL, config *tls.Config) error {
  58. addr := u.Host
  59. if !(strings.LastIndex(addr, ":") > strings.LastIndex(addr, "]")) {
  60. addr += ":443"
  61. }
  62. conn, err := tls.Dial("tcp", addr, config)
  63. if err != nil {
  64. if !soap.IsCertificateUntrusted(err) {
  65. return err
  66. }
  67. info.Err = err
  68. conn, err = tls.Dial("tcp", addr, &tls.Config{InsecureSkipVerify: true})
  69. if err != nil {
  70. return err
  71. }
  72. } else {
  73. info.Status = string(types.HostCertificateManagerCertificateInfoCertificateStatusGood)
  74. }
  75. state := conn.ConnectionState()
  76. _ = conn.Close()
  77. info.FromCertificate(state.PeerCertificates[0])
  78. return nil
  79. }
  80. var emailAddressOID = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1}
  81. func (info *HostCertificateInfo) fromName(name *pkix.Name) string {
  82. var attrs []string
  83. oids := map[string]string{
  84. emailAddressOID.String(): "emailAddress",
  85. }
  86. for _, attr := range name.Names {
  87. if key, ok := oids[attr.Type.String()]; ok {
  88. attrs = append(attrs, fmt.Sprintf("%s=%s", key, attr.Value))
  89. }
  90. }
  91. attrs = append(attrs, fmt.Sprintf("CN=%s", name.CommonName))
  92. add := func(key string, vals []string) {
  93. for _, val := range vals {
  94. attrs = append(attrs, fmt.Sprintf("%s=%s", key, val))
  95. }
  96. }
  97. elts := []struct {
  98. key string
  99. val []string
  100. }{
  101. {"OU", name.OrganizationalUnit},
  102. {"O", name.Organization},
  103. {"L", name.Locality},
  104. {"ST", name.Province},
  105. {"C", name.Country},
  106. }
  107. for _, elt := range elts {
  108. add(elt.key, elt.val)
  109. }
  110. return strings.Join(attrs, ",")
  111. }
  112. func (info *HostCertificateInfo) toName(s string) *pkix.Name {
  113. var name pkix.Name
  114. for _, pair := range strings.Split(s, ",") {
  115. attr := strings.SplitN(pair, "=", 2)
  116. if len(attr) != 2 {
  117. continue
  118. }
  119. v := attr[1]
  120. switch strings.ToLower(attr[0]) {
  121. case "cn":
  122. name.CommonName = v
  123. case "ou":
  124. name.OrganizationalUnit = append(name.OrganizationalUnit, v)
  125. case "o":
  126. name.Organization = append(name.Organization, v)
  127. case "l":
  128. name.Locality = append(name.Locality, v)
  129. case "st":
  130. name.Province = append(name.Province, v)
  131. case "c":
  132. name.Country = append(name.Country, v)
  133. case "emailaddress":
  134. name.Names = append(name.Names, pkix.AttributeTypeAndValue{Type: emailAddressOID, Value: v})
  135. }
  136. }
  137. return &name
  138. }
  139. // SubjectName parses Subject into a pkix.Name
  140. func (info *HostCertificateInfo) SubjectName() *pkix.Name {
  141. if info.subjectName != nil {
  142. return info.subjectName
  143. }
  144. return info.toName(info.Subject)
  145. }
  146. // IssuerName parses Issuer into a pkix.Name
  147. func (info *HostCertificateInfo) IssuerName() *pkix.Name {
  148. if info.issuerName != nil {
  149. return info.issuerName
  150. }
  151. return info.toName(info.Issuer)
  152. }
  153. // Write outputs info similar to the Chrome Certificate Viewer.
  154. func (info *HostCertificateInfo) Write(w io.Writer) error {
  155. tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0)
  156. s := func(val string) string {
  157. if val != "" {
  158. return val
  159. }
  160. return "<Not Part Of Certificate>"
  161. }
  162. ss := func(val []string) string {
  163. return s(strings.Join(val, ","))
  164. }
  165. name := func(n *pkix.Name) {
  166. fmt.Fprintf(tw, " Common Name (CN):\t%s\n", s(n.CommonName))
  167. fmt.Fprintf(tw, " Organization (O):\t%s\n", ss(n.Organization))
  168. fmt.Fprintf(tw, " Organizational Unit (OU):\t%s\n", ss(n.OrganizationalUnit))
  169. }
  170. status := info.Status
  171. if info.Err != nil {
  172. status = fmt.Sprintf("ERROR %s", info.Err)
  173. }
  174. fmt.Fprintf(tw, "Certificate Status:\t%s\n", status)
  175. fmt.Fprintln(tw, "Issued To:\t")
  176. name(info.SubjectName())
  177. fmt.Fprintln(tw, "Issued By:\t")
  178. name(info.IssuerName())
  179. fmt.Fprintln(tw, "Validity Period:\t")
  180. fmt.Fprintf(tw, " Issued On:\t%s\n", info.NotBefore)
  181. fmt.Fprintf(tw, " Expires On:\t%s\n", info.NotAfter)
  182. if info.ThumbprintSHA1 != "" {
  183. fmt.Fprintln(tw, "Thumbprints:\t")
  184. if info.ThumbprintSHA256 != "" {
  185. fmt.Fprintf(tw, " SHA-256 Thumbprint:\t%s\n", info.ThumbprintSHA256)
  186. }
  187. fmt.Fprintf(tw, " SHA-1 Thumbprint:\t%s\n", info.ThumbprintSHA1)
  188. }
  189. return tw.Flush()
  190. }