host_certificate_info.go 6.3 KB

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