4
0

main.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "time"
  8. "github.com/smallstep/certificates/ca"
  9. )
  10. func main() {
  11. if len(os.Args) != 2 {
  12. fmt.Fprintf(os.Stderr, "Usage: %s <token>\n", os.Args[0])
  13. os.Exit(1)
  14. }
  15. token := os.Args[1]
  16. // make sure to cancel the renew goroutine
  17. ctx, cancel := context.WithCancel(context.Background())
  18. defer cancel()
  19. srv, err := ca.BootstrapServer(ctx, token, &http.Server{
  20. Addr: ":8443",
  21. Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  22. name := "nobody"
  23. issuer := "none"
  24. if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
  25. name = r.TLS.PeerCertificates[0].Subject.CommonName
  26. issuer = r.TLS.PeerCertificates[len(r.TLS.PeerCertificates)-1].Issuer.CommonName
  27. }
  28. fmt.Fprintf(w, "Hello %s (cert issued by '%s') at %s", name, issuer, time.Now().UTC())
  29. }),
  30. ReadHeaderTimeout: 30 * time.Second,
  31. }, ca.AddFederationToClientCAs(), ListTrustedRoots())
  32. if err != nil {
  33. panic(err)
  34. }
  35. fmt.Println("Listening on :8443 ...")
  36. if err := srv.ListenAndServeTLS("", ""); err != nil {
  37. panic(err)
  38. }
  39. }
  40. // ListTrustedRoots prints list of trusted roots for illustration purposes
  41. func ListTrustedRoots() ca.TLSOption {
  42. fn := func(ctx *ca.TLSOptionCtx) error {
  43. certs, err := ctx.Client.Federation()
  44. if err != nil {
  45. return err
  46. }
  47. roots, err := ctx.Client.Roots()
  48. if err != nil {
  49. return err
  50. }
  51. if len(certs.Certificates) > len(roots.Certificates) {
  52. fmt.Println("Server is using federated root certificates")
  53. }
  54. for _, cert := range certs.Certificates {
  55. fmt.Printf("Accepting certs anchored in %s\n", cert.Certificate.Subject)
  56. }
  57. return nil
  58. }
  59. return func(ctx *ca.TLSOptionCtx) error {
  60. ctx.OnRenewFunc = append(ctx.OnRenewFunc, fn)
  61. return fn(ctx)
  62. }
  63. }