certificate.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package http
  2. import (
  3. "crypto/x509"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "strings"
  8. "github.com/ethereum/go-ethereum/log"
  9. )
  10. // Load Root CA certificate(s).
  11. // Path can be a single certificate file, or a comma separated list containing a combination of
  12. // certificate files or directories containing certificate files.
  13. func loadRootCaCerts(rootCAPath string) (*x509.CertPool, error) {
  14. rootCAPool, err := x509.SystemCertPool()
  15. if err != nil {
  16. rootCAPool = x509.NewCertPool()
  17. }
  18. if len(rootCAPath) == 0 {
  19. return rootCAPool, nil
  20. }
  21. list := strings.Split(rootCAPath, ",")
  22. for _, thisFileOrDirEntry := range list {
  23. info, err := os.Lstat(thisFileOrDirEntry)
  24. if err != nil {
  25. return nil, fmt.Errorf("unable to check whether RootCA entry '%v' is a file or directory, due to: %s", thisFileOrDirEntry, err)
  26. }
  27. if info.Mode()&os.ModeDir != 0 {
  28. fileList, err := ioutil.ReadDir(thisFileOrDirEntry)
  29. if err != nil {
  30. return nil, fmt.Errorf("unable to read contents of RootCA directory '%v', due to: %s", thisFileOrDirEntry, err)
  31. }
  32. for _, fileinfo := range fileList {
  33. if err := loadRootCAFromFile(thisFileOrDirEntry+"/"+fileinfo.Name(), rootCAPool); err != nil {
  34. return nil, err
  35. }
  36. }
  37. } else if err := loadRootCAFromFile(thisFileOrDirEntry, rootCAPool); err != nil {
  38. return nil, err
  39. }
  40. }
  41. return rootCAPool, nil
  42. }
  43. func loadRootCAFromFile(file string, roots *x509.CertPool) error {
  44. log.Debug("loading RootCA certificate for connection to private transaction manager", "file", file)
  45. data, err := ioutil.ReadFile(file)
  46. if err != nil {
  47. return fmt.Errorf("unable to read contents of RootCA certificate file '%v', due to: %s", file, err)
  48. }
  49. if !roots.AppendCertsFromPEM(data) {
  50. return fmt.Errorf("failed to add TlsRootCA certificate to pool, check that '%v' contains a valid RootCA certificate", file)
  51. }
  52. return nil
  53. }