Alternative TLS implementation in Go
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

90 行
2.3 KiB

  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tls
  5. import (
  6. "crypto/x509"
  7. "encoding/pem"
  8. "strings"
  9. )
  10. // A CASet is a set of certificates.
  11. type CASet struct {
  12. bySubjectKeyId map[string][]*x509.Certificate
  13. byName map[string][]*x509.Certificate
  14. }
  15. // NewCASet returns a new, empty CASet.
  16. func NewCASet() *CASet {
  17. return &CASet{
  18. make(map[string][]*x509.Certificate),
  19. make(map[string][]*x509.Certificate),
  20. }
  21. }
  22. func nameToKey(name *x509.Name) string {
  23. return strings.Join(name.Country, ",") + "/" + strings.Join(name.Organization, ",") + "/" + strings.Join(name.OrganizationalUnit, ",") + "/" + name.CommonName
  24. }
  25. // FindVerifiedParent attempts to find the certificate in s which has signed
  26. // the given certificate. If no such certificate can be found or the signature
  27. // doesn't match, it returns nil.
  28. func (s *CASet) FindVerifiedParent(cert *x509.Certificate) (parent *x509.Certificate) {
  29. var candidates []*x509.Certificate
  30. if len(cert.AuthorityKeyId) > 0 {
  31. candidates = s.bySubjectKeyId[string(cert.AuthorityKeyId)]
  32. }
  33. if len(candidates) == 0 {
  34. candidates = s.byName[nameToKey(&cert.Issuer)]
  35. }
  36. for _, c := range candidates {
  37. if cert.CheckSignatureFrom(c) == nil {
  38. return c
  39. }
  40. }
  41. return nil
  42. }
  43. // AddCert adds a certificate to the set
  44. func (s *CASet) AddCert(cert *x509.Certificate) {
  45. if len(cert.SubjectKeyId) > 0 {
  46. keyId := string(cert.SubjectKeyId)
  47. s.bySubjectKeyId[keyId] = append(s.bySubjectKeyId[keyId], cert)
  48. }
  49. name := nameToKey(&cert.Subject)
  50. s.byName[name] = append(s.byName[name], cert)
  51. }
  52. // SetFromPEM attempts to parse a series of PEM encoded root certificates. It
  53. // appends any certificates found to s and returns true if any certificates
  54. // were successfully parsed. On many Linux systems, /etc/ssl/cert.pem will
  55. // contains the system wide set of root CAs in a format suitable for this
  56. // function.
  57. func (s *CASet) SetFromPEM(pemCerts []byte) (ok bool) {
  58. for len(pemCerts) > 0 {
  59. var block *pem.Block
  60. block, pemCerts = pem.Decode(pemCerts)
  61. if block == nil {
  62. break
  63. }
  64. if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
  65. continue
  66. }
  67. cert, err := x509.ParseCertificate(block.Bytes)
  68. if err != nil {
  69. continue
  70. }
  71. s.AddCert(cert)
  72. ok = true
  73. }
  74. return
  75. }