export.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. package authority
  2. import (
  3. "encoding/json"
  4. "net/url"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "github.com/pkg/errors"
  9. "github.com/smallstep/certificates/authority/provisioner"
  10. "go.step.sm/cli-utils/step"
  11. "go.step.sm/linkedca"
  12. "google.golang.org/protobuf/types/known/structpb"
  13. )
  14. // Export creates a linkedca configuration form the current ca.json and loaded
  15. // authorities.
  16. //
  17. // Note that export will not export neither the pki password nor the certificate
  18. // issuer password.
  19. func (a *Authority) Export() (c *linkedca.Configuration, err error) {
  20. // Recover from panics
  21. defer func() {
  22. if r := recover(); r != nil {
  23. err = r.(error)
  24. }
  25. }()
  26. files := make(map[string][]byte)
  27. // The exported configuration should not include the password in it.
  28. c = &linkedca.Configuration{
  29. Version: "1.0",
  30. Root: mustReadFilesOrURIs(a.config.Root, files),
  31. FederatedRoots: mustReadFilesOrURIs(a.config.FederatedRoots, files),
  32. Intermediate: mustReadFileOrURI(a.config.IntermediateCert, files),
  33. IntermediateKey: mustReadFileOrURI(a.config.IntermediateKey, files),
  34. Address: a.config.Address,
  35. InsecureAddress: a.config.InsecureAddress,
  36. DnsNames: a.config.DNSNames,
  37. Db: mustMarshalToStruct(a.config.DB),
  38. Logger: mustMarshalToStruct(a.config.Logger),
  39. Monitoring: mustMarshalToStruct(a.config.Monitoring),
  40. Authority: &linkedca.Authority{
  41. Id: a.config.AuthorityConfig.AuthorityID,
  42. EnableAdmin: a.config.AuthorityConfig.EnableAdmin,
  43. DisableIssuedAtCheck: a.config.AuthorityConfig.DisableIssuedAtCheck,
  44. Backdate: mustDuration(a.config.AuthorityConfig.Backdate),
  45. DeploymentType: a.config.AuthorityConfig.DeploymentType,
  46. },
  47. Files: files,
  48. }
  49. // SSH
  50. if v := a.config.SSH; v != nil {
  51. c.Ssh = &linkedca.SSH{
  52. HostKey: mustReadFileOrURI(v.HostKey, files),
  53. UserKey: mustReadFileOrURI(v.UserKey, files),
  54. AddUserPrincipal: v.AddUserPrincipal,
  55. AddUserCommand: v.AddUserCommand,
  56. }
  57. for _, k := range v.Keys {
  58. typ, ok := linkedca.SSHPublicKey_Type_value[strings.ToUpper(k.Type)]
  59. if !ok {
  60. return nil, errors.Errorf("unsupported ssh key type %s", k.Type)
  61. }
  62. c.Ssh.Keys = append(c.Ssh.Keys, &linkedca.SSHPublicKey{
  63. Type: linkedca.SSHPublicKey_Type(typ),
  64. Federated: k.Federated,
  65. Key: mustMarshalToStruct(k),
  66. })
  67. }
  68. if b := v.Bastion; b != nil {
  69. c.Ssh.Bastion = &linkedca.Bastion{
  70. Hostname: b.Hostname,
  71. User: b.User,
  72. Port: b.Port,
  73. Command: b.Command,
  74. Flags: b.Flags,
  75. }
  76. }
  77. }
  78. // KMS
  79. if v := a.config.KMS; v != nil {
  80. var typ int32
  81. var ok bool
  82. if v.Type == "" {
  83. typ = int32(linkedca.KMS_SOFTKMS)
  84. } else {
  85. typ, ok = linkedca.KMS_Type_value[strings.ToUpper(v.Type)]
  86. if !ok {
  87. return nil, errors.Errorf("unsupported kms type %s", v.Type)
  88. }
  89. }
  90. c.Kms = &linkedca.KMS{
  91. Type: linkedca.KMS_Type(typ),
  92. CredentialsFile: v.CredentialsFile,
  93. Uri: v.URI,
  94. Pin: v.Pin,
  95. ManagementKey: v.ManagementKey,
  96. Region: v.Region,
  97. Profile: v.Profile,
  98. }
  99. }
  100. // Authority
  101. // cas options
  102. if v := a.config.AuthorityConfig.Options; v != nil {
  103. c.Authority.Type = 0
  104. c.Authority.CertificateAuthority = v.CertificateAuthority
  105. c.Authority.CertificateAuthorityFingerprint = v.CertificateAuthorityFingerprint
  106. c.Authority.CredentialsFile = v.CredentialsFile
  107. if iss := v.CertificateIssuer; iss != nil {
  108. typ, ok := linkedca.CertificateIssuer_Type_value[strings.ToUpper(iss.Type)]
  109. if !ok {
  110. return nil, errors.Errorf("unknown certificate issuer type %s", iss.Type)
  111. }
  112. // The exported certificate issuer should not include the password.
  113. c.Authority.CertificateIssuer = &linkedca.CertificateIssuer{
  114. Type: linkedca.CertificateIssuer_Type(typ),
  115. Provisioner: iss.Provisioner,
  116. Certificate: mustReadFileOrURI(iss.Certificate, files),
  117. Key: mustReadFileOrURI(iss.Key, files),
  118. }
  119. }
  120. }
  121. // admins
  122. for {
  123. list, cursor := a.admins.Find("", 100)
  124. c.Authority.Admins = append(c.Authority.Admins, list...)
  125. if cursor == "" {
  126. break
  127. }
  128. }
  129. // provisioners
  130. for {
  131. list, cursor := a.provisioners.Find("", 100)
  132. for _, p := range list {
  133. lp, err := ProvisionerToLinkedca(p)
  134. if err != nil {
  135. return nil, err
  136. }
  137. c.Authority.Provisioners = append(c.Authority.Provisioners, lp)
  138. }
  139. if cursor == "" {
  140. break
  141. }
  142. }
  143. // global claims
  144. c.Authority.Claims = claimsToLinkedca(a.config.AuthorityConfig.Claims)
  145. // Distinguished names template
  146. if v := a.config.AuthorityConfig.Template; v != nil {
  147. c.Authority.Template = &linkedca.DistinguishedName{
  148. Country: v.Country,
  149. Organization: v.Organization,
  150. OrganizationalUnit: v.OrganizationalUnit,
  151. Locality: v.Locality,
  152. Province: v.Province,
  153. StreetAddress: v.StreetAddress,
  154. SerialNumber: v.SerialNumber,
  155. CommonName: v.CommonName,
  156. }
  157. }
  158. // TLS
  159. if v := a.config.TLS; v != nil {
  160. c.Tls = &linkedca.TLS{
  161. MinVersion: v.MinVersion.String(),
  162. MaxVersion: v.MaxVersion.String(),
  163. Renegotiation: v.Renegotiation,
  164. }
  165. for _, cs := range v.CipherSuites.Value() {
  166. c.Tls.CipherSuites = append(c.Tls.CipherSuites, linkedca.TLS_CiperSuite(cs))
  167. }
  168. }
  169. // Templates
  170. if v := a.config.Templates; v != nil {
  171. c.Templates = &linkedca.ConfigTemplates{
  172. Ssh: &linkedca.SSHConfigTemplate{},
  173. Data: mustMarshalToStruct(v.Data),
  174. }
  175. // Remove automatically loaded vars
  176. if c.Templates.Data != nil && c.Templates.Data.Fields != nil {
  177. delete(c.Templates.Data.Fields, "Step")
  178. }
  179. for _, t := range v.SSH.Host {
  180. typ, ok := linkedca.ConfigTemplate_Type_value[strings.ToUpper(string(t.Type))]
  181. if !ok {
  182. return nil, errors.Errorf("unsupported template type %s", t.Type)
  183. }
  184. c.Templates.Ssh.Hosts = append(c.Templates.Ssh.Hosts, &linkedca.ConfigTemplate{
  185. Type: linkedca.ConfigTemplate_Type(typ),
  186. Name: t.Name,
  187. Template: mustReadFileOrURI(t.TemplatePath, files),
  188. Path: t.Path,
  189. Comment: t.Comment,
  190. Requires: t.RequiredData,
  191. Content: t.Content,
  192. })
  193. }
  194. for _, t := range v.SSH.User {
  195. typ, ok := linkedca.ConfigTemplate_Type_value[strings.ToUpper(string(t.Type))]
  196. if !ok {
  197. return nil, errors.Errorf("unsupported template type %s", t.Type)
  198. }
  199. c.Templates.Ssh.Users = append(c.Templates.Ssh.Users, &linkedca.ConfigTemplate{
  200. Type: linkedca.ConfigTemplate_Type(typ),
  201. Name: t.Name,
  202. Template: mustReadFileOrURI(t.TemplatePath, files),
  203. Path: t.Path,
  204. Comment: t.Comment,
  205. Requires: t.RequiredData,
  206. Content: t.Content,
  207. })
  208. }
  209. }
  210. return c, nil
  211. }
  212. func mustDuration(d *provisioner.Duration) string {
  213. if d == nil || d.Duration == 0 {
  214. return ""
  215. }
  216. return d.String()
  217. }
  218. func mustMarshalToStruct(v interface{}) *structpb.Struct {
  219. b, err := json.Marshal(v)
  220. if err != nil {
  221. panic(errors.Wrapf(err, "error marshaling %T", v))
  222. }
  223. var r *structpb.Struct
  224. if err := json.Unmarshal(b, &r); err != nil {
  225. panic(errors.Wrapf(err, "error unmarshaling %T", v))
  226. }
  227. return r
  228. }
  229. func mustReadFileOrURI(fn string, m map[string][]byte) string {
  230. if fn == "" {
  231. return ""
  232. }
  233. stepPath := filepath.ToSlash(step.Path())
  234. if !strings.HasSuffix(stepPath, "/") {
  235. stepPath += "/"
  236. }
  237. fn = strings.TrimPrefix(filepath.ToSlash(fn), stepPath)
  238. ok, err := isFilename(fn)
  239. if err != nil {
  240. panic(err)
  241. }
  242. if ok {
  243. b, err := os.ReadFile(step.Abs(fn))
  244. if err != nil {
  245. panic(errors.Wrapf(err, "error reading %s", fn))
  246. }
  247. m[fn] = b
  248. return fn
  249. }
  250. return fn
  251. }
  252. func mustReadFilesOrURIs(fns []string, m map[string][]byte) []string {
  253. var result []string
  254. for _, fn := range fns {
  255. result = append(result, mustReadFileOrURI(fn, m))
  256. }
  257. return result
  258. }
  259. func isFilename(fn string) (bool, error) {
  260. u, err := url.Parse(fn)
  261. if err != nil {
  262. return false, errors.Wrapf(err, "error parsing %s", fn)
  263. }
  264. return u.Scheme == "" || u.Scheme == "file", nil
  265. }