main.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. package main
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "encoding/hex"
  6. "encoding/json"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "strings"
  12. "time"
  13. "github.com/ghodss/yaml"
  14. "github.com/pkg/errors"
  15. log "github.com/sirupsen/logrus"
  16. "github.com/smallstep/certificates/ca"
  17. "github.com/smallstep/cli/crypto/pemutil"
  18. "k8s.io/api/admission/v1beta1"
  19. corev1 "k8s.io/api/core/v1"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/runtime"
  22. "k8s.io/apimachinery/pkg/runtime/serializer"
  23. )
  24. var (
  25. runtimeScheme = runtime.NewScheme()
  26. codecs = serializer.NewCodecFactory(runtimeScheme)
  27. deserializer = codecs.UniversalDeserializer()
  28. // GetRootCAPath() is broken; points to secrets not certs. So
  29. // we'll hard code instead for now.
  30. //rootCAPath = pki.GetRootCAPath()
  31. rootCAPath = "/home/step/.step/certs/root_ca.crt"
  32. )
  33. const (
  34. admissionWebhookAnnotationKey = "autocert.step.sm/name"
  35. admissionWebhookStatusKey = "autocert.step.sm/status"
  36. provisionerPasswordFile = "/home/step/password/password"
  37. volumeMountPath = "/var/run/autocert.step.sm"
  38. tokenSecretKey = "token"
  39. tokenSecretLabel = "autocert.step.sm/token"
  40. )
  41. // Config options for the autocert admission controller.
  42. type Config struct {
  43. LogFormat string `yaml:"logFormat"`
  44. CaURL string `yaml:"caUrl"`
  45. CertLifetime string `yaml:"certLifetime"`
  46. Bootstrapper corev1.Container `yaml:"bootstrapper"`
  47. Renewer corev1.Container `yaml:"renewer"`
  48. CertsVolume corev1.Volume `yaml:"certsVolume"`
  49. }
  50. // PatchOperation represents a RFC6902 JSONPatch Operation
  51. type PatchOperation struct {
  52. Op string `json:"op"`
  53. Path string `json:"path"`
  54. Value interface{} `json:"value,omitempty"`
  55. }
  56. // RFC6901 JSONPath Escaping -- https://tools.ietf.org/html/rfc6901
  57. func escapeJSONPath(path string) string {
  58. // Replace`~` with `~0` then `/` with `~1`. Note that the order
  59. // matters otherwise we'll turn a `/` into a `~/`.
  60. path = strings.Replace(path, "~", "~0", -1)
  61. path = strings.Replace(path, "/", "~1", -1)
  62. return path
  63. }
  64. func loadConfig(file string) (*Config, error) {
  65. data, err := ioutil.ReadFile(file)
  66. if err != nil {
  67. return nil, err
  68. }
  69. var cfg Config
  70. if err := yaml.Unmarshal(data, &cfg); err != nil {
  71. return nil, err
  72. }
  73. return &cfg, nil
  74. }
  75. // createTokenSecret generates a kubernetes Secret object containing a bootstrap token
  76. // in the specified namespce. The secret name is randomly generated with a given prefix.
  77. // A goroutine is scheduled to cleanup the secret after the token expires. The secret
  78. // is also labelled for easy identification and manual cleanup.
  79. func createTokenSecret(prefix, namespace, token string) (string, error) {
  80. secret := corev1.Secret{
  81. TypeMeta: metav1.TypeMeta{
  82. Kind: "Secret",
  83. APIVersion: "v1",
  84. },
  85. ObjectMeta: metav1.ObjectMeta{
  86. GenerateName: prefix,
  87. Namespace: namespace,
  88. Labels: map[string]string{
  89. tokenSecretLabel: "true",
  90. },
  91. },
  92. StringData: map[string]string{
  93. tokenSecretKey: token,
  94. },
  95. Type: corev1.SecretTypeOpaque,
  96. }
  97. client, err := NewInClusterK8sClient()
  98. if err != nil {
  99. return "", err
  100. }
  101. body, err := json.Marshal(secret)
  102. if err != nil {
  103. return "", err
  104. }
  105. log.WithField("secret", string(body)).Debug("Creating secret")
  106. req, err := client.PostRequest(fmt.Sprintf("api/v1/namespaces/%s/secrets", namespace), string(body), "application/json")
  107. if err != nil {
  108. return "", err
  109. }
  110. resp, err := client.Do(req)
  111. if err != nil {
  112. log.Errorf("Secret creation error. Response: %v", resp)
  113. return "", errors.Wrap(err, "secret creation")
  114. }
  115. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  116. log.Errorf("Secret creation error (!2XX). Response: %v", resp)
  117. var rbody []byte
  118. if resp.Body != nil {
  119. if data, err := ioutil.ReadAll(resp.Body); err == nil {
  120. rbody = data
  121. }
  122. }
  123. log.Error("Error body: ", string(rbody))
  124. return "", errors.New("Not 200")
  125. }
  126. var rbody []byte
  127. if resp.Body != nil {
  128. if data, err := ioutil.ReadAll(resp.Body); err == nil {
  129. rbody = data
  130. }
  131. }
  132. if len(rbody) == 0 {
  133. return "", errors.New("Empty response body")
  134. }
  135. var created *corev1.Secret
  136. if err := json.Unmarshal(rbody, &created); err != nil {
  137. return "", errors.Wrap(err, "Error unmarshalling secret response")
  138. }
  139. // Clean up after ourselves by deleting the Secret after the bootstrap
  140. // token expires. This is best effort -- obviously we'll miss some stuff
  141. // if this process goes away -- but the secrets are also labelled so
  142. // it's also easy to clean them up in bulk using kubectl if we miss any.
  143. go func() {
  144. time.Sleep(tokenLifetime)
  145. req, err := client.DeleteRequest(fmt.Sprintf("api/v1/namespaces/%s/secrets/%s", namespace, created.Name))
  146. ctxLog := log.WithFields(log.Fields{
  147. "name": created.Name,
  148. "namespace": namespace,
  149. })
  150. if err != nil {
  151. ctxLog.WithField("error", err).Error("Error deleting expired boostrap token secret")
  152. return
  153. }
  154. resp, err := client.Do(req)
  155. if err != nil {
  156. ctxLog.WithField("error", err).Error("Error deleting expired boostrap token secret")
  157. return
  158. }
  159. if resp.StatusCode < 200 || resp.StatusCode >= 300 {
  160. ctxLog.WithFields(log.Fields{
  161. "status": resp.Status,
  162. "statusCode": resp.StatusCode,
  163. }).Error("Error deleting expired boostrap token secret")
  164. return
  165. }
  166. ctxLog.Info("Deleted expired bootstrap token secret")
  167. }()
  168. return created.Name, err
  169. }
  170. // mkBootstrapper generates a bootstrap container based on the template defined in Config. It
  171. // generates a new bootstrap token and mounts it, along with other required coniguration, as
  172. // environment variables in the returned bootstrap container.
  173. func mkBootstrapper(config *Config, commonName string, namespace string, provisioner Provisioner) (corev1.Container, error) {
  174. b := config.Bootstrapper
  175. token, err := provisioner.Token(commonName)
  176. if err != nil {
  177. return b, errors.Wrap(err, "token generation")
  178. }
  179. // Generate CA fingerprint
  180. crt, err := pemutil.ReadCertificate(rootCAPath)
  181. if err != nil {
  182. return b, errors.Wrap(err, "CA fingerprint")
  183. }
  184. sum := sha256.Sum256(crt.Raw)
  185. fingerprint := strings.ToLower(hex.EncodeToString(sum[:]))
  186. secretName, err := createTokenSecret(commonName+"-", namespace, token)
  187. if err != nil {
  188. return b, errors.Wrap(err, "create token secret")
  189. }
  190. log.Infof("Secret name is: %s", secretName)
  191. b.Env = append(b.Env, corev1.EnvVar{
  192. Name: "COMMON_NAME",
  193. Value: commonName,
  194. })
  195. b.Env = append(b.Env, corev1.EnvVar{
  196. Name: "STEP_TOKEN",
  197. ValueFrom: &corev1.EnvVarSource{
  198. SecretKeyRef: &corev1.SecretKeySelector{
  199. LocalObjectReference: corev1.LocalObjectReference{
  200. Name: secretName,
  201. },
  202. Key: tokenSecretKey,
  203. },
  204. },
  205. })
  206. b.Env = append(b.Env, corev1.EnvVar{
  207. Name: "STEP_CA_URL",
  208. Value: config.CaURL,
  209. })
  210. b.Env = append(b.Env, corev1.EnvVar{
  211. Name: "STEP_FINGERPRINT",
  212. Value: fingerprint,
  213. })
  214. b.Env = append(b.Env, corev1.EnvVar{
  215. Name: "STEP_NOT_AFTER",
  216. Value: config.CertLifetime,
  217. })
  218. return b, nil
  219. }
  220. // mkRenewer generates a new renewer based on the template provided in Config.
  221. func mkRenewer(config *Config) corev1.Container {
  222. r := config.Renewer
  223. r.Env = append(r.Env, corev1.EnvVar{
  224. Name: "STEP_CA_URL",
  225. Value: config.CaURL,
  226. })
  227. return r
  228. }
  229. func addContainers(existing, new []corev1.Container, path string) (ops []PatchOperation) {
  230. if len(existing) == 0 {
  231. return []PatchOperation{
  232. {
  233. Op: "add",
  234. Path: path,
  235. Value: new,
  236. },
  237. }
  238. }
  239. for _, add := range new {
  240. ops = append(ops, PatchOperation{
  241. Op: "add",
  242. Path: path + "/-",
  243. Value: add,
  244. })
  245. }
  246. return ops
  247. }
  248. func addVolumes(existing, new []corev1.Volume, path string) (ops []PatchOperation) {
  249. if len(existing) == 0 {
  250. return []PatchOperation{
  251. {
  252. Op: "add",
  253. Path: path,
  254. Value: new,
  255. },
  256. }
  257. }
  258. for _, add := range new {
  259. ops = append(ops, PatchOperation{
  260. Op: "add",
  261. Path: path + "/-",
  262. Value: add,
  263. })
  264. }
  265. return ops
  266. }
  267. func addCertsVolumeMount(volumeName string, containers []corev1.Container) (ops []PatchOperation) {
  268. volumeMount := corev1.VolumeMount{
  269. Name: volumeName,
  270. MountPath: volumeMountPath,
  271. ReadOnly: true,
  272. }
  273. for i, container := range containers {
  274. if len(container.VolumeMounts) == 0 {
  275. ops = append(ops, PatchOperation{
  276. Op: "add",
  277. Path: fmt.Sprintf("/spec/containers/%v/volumeMounts", i),
  278. Value: []corev1.VolumeMount{volumeMount},
  279. })
  280. } else {
  281. ops = append(ops, PatchOperation{
  282. Op: "add",
  283. Path: fmt.Sprintf("/spec/containers/%v/volumeMounts/-", i),
  284. Value: volumeMount,
  285. })
  286. }
  287. }
  288. return ops
  289. }
  290. func addAnnotations(existing, new map[string]string) (ops []PatchOperation) {
  291. if len(existing) == 0 {
  292. return []PatchOperation{
  293. {
  294. Op: "add",
  295. Path: "/metadata/annotations",
  296. Value: new,
  297. },
  298. }
  299. }
  300. for k, v := range new {
  301. if existing[k] == "" {
  302. ops = append(ops, PatchOperation{
  303. Op: "add",
  304. Path: "/metadata/annotations/" + escapeJSONPath(k),
  305. Value: v,
  306. })
  307. } else {
  308. ops = append(ops, PatchOperation{
  309. Op: "replace",
  310. Path: "/metadata/annotations/" + escapeJSONPath(k),
  311. Value: v,
  312. })
  313. }
  314. }
  315. return ops
  316. }
  317. // patch produces a list of patches to apply to a pod to inject a certificate. In particular,
  318. // we patch the pod in order to:
  319. // - Mount the `certs` volume in existing containers defined in the pod
  320. // - Add the autocert-renewer as a container (a sidecar)
  321. // - Add the autocert-bootstrapper as an initContainer
  322. // - Add the `certs` volume definition
  323. // - Annotate the pod to indicate that it's been processed by this controller
  324. // The result is a list of serialized JSONPatch objects (or an error).
  325. func patch(pod *corev1.Pod, namespace string, config *Config, provisioner Provisioner) ([]byte, error) {
  326. var ops []PatchOperation
  327. commonName := pod.ObjectMeta.GetAnnotations()[admissionWebhookAnnotationKey]
  328. renewer := mkRenewer(config)
  329. bootstrapper, err := mkBootstrapper(config, commonName, namespace, provisioner)
  330. if err != nil {
  331. return nil, err
  332. }
  333. ops = append(ops, addCertsVolumeMount(config.CertsVolume.Name, pod.Spec.Containers)...)
  334. ops = append(ops, addContainers(pod.Spec.Containers, []corev1.Container{renewer}, "/spec/containers")...)
  335. ops = append(ops, addContainers(pod.Spec.InitContainers, []corev1.Container{bootstrapper}, "/spec/initContainers")...)
  336. ops = append(ops, addVolumes(pod.Spec.Volumes, []corev1.Volume{config.CertsVolume}, "/spec/volumes")...)
  337. ops = append(ops, addAnnotations(pod.Annotations, map[string]string{admissionWebhookStatusKey: "injected"})...)
  338. return json.Marshal(ops)
  339. }
  340. // shouldMutate checks whether a pod is subject to mutation by this admission controller. A pod
  341. // is subject to mutation if it's annotated with the `admissionWebhookAnnotationKey` and if it
  342. // has not already been processed (indicated by `admissionWebhookStatusKey` set to `injected`).
  343. func shouldMutate(metadata *metav1.ObjectMeta) bool {
  344. annotations := metadata.GetAnnotations()
  345. if annotations == nil {
  346. annotations = map[string]string{}
  347. }
  348. // Only mutate if the object is annotated appropriately (annotation key set) and we haven't
  349. // mutated already (status key isn't set).
  350. if annotations[admissionWebhookAnnotationKey] == "" || annotations[admissionWebhookStatusKey] == "injected" {
  351. return false
  352. }
  353. return true
  354. }
  355. // mutate takes an `AdmissionReview`, determines whether it is subject to mutation, and returns
  356. // an appropriate `AdmissionResponse` including patches or any errors that occurred.
  357. func mutate(review *v1beta1.AdmissionReview, config *Config, provisioner Provisioner) *v1beta1.AdmissionResponse {
  358. ctxLog := log.WithField("uid", review.Request.UID)
  359. request := review.Request
  360. var pod corev1.Pod
  361. if err := json.Unmarshal(request.Object.Raw, &pod); err != nil {
  362. ctxLog.WithField("error", err).Error("Error unmarshalling pod")
  363. return &v1beta1.AdmissionResponse{
  364. Allowed: false,
  365. UID: request.UID,
  366. Result: &metav1.Status{
  367. Message: err.Error(),
  368. },
  369. }
  370. }
  371. ctxLog = ctxLog.WithFields(log.Fields{
  372. "kind": request.Kind,
  373. "operation": request.Operation,
  374. "name": pod.Name,
  375. "generateName": pod.GenerateName,
  376. "namespace": request.Namespace,
  377. "user": request.UserInfo,
  378. })
  379. if !shouldMutate(&pod.ObjectMeta) {
  380. ctxLog.WithField("annotations", pod.Annotations).Info("Skipping mutation")
  381. return &v1beta1.AdmissionResponse{
  382. Allowed: true,
  383. UID: request.UID,
  384. }
  385. }
  386. patchBytes, err := patch(&pod, request.Namespace, config, provisioner)
  387. if err != nil {
  388. ctxLog.WithField("error", err).Error("Error generating patch")
  389. return &v1beta1.AdmissionResponse{
  390. Allowed: false,
  391. UID: request.UID,
  392. Result: &metav1.Status{
  393. Message: err.Error(),
  394. },
  395. }
  396. }
  397. ctxLog.WithField("patch", string(patchBytes)).Info("Generated patch")
  398. return &v1beta1.AdmissionResponse{
  399. Allowed: true,
  400. Patch: patchBytes,
  401. UID: request.UID,
  402. PatchType: func() *v1beta1.PatchType {
  403. pt := v1beta1.PatchTypeJSONPatch
  404. return &pt
  405. }(),
  406. }
  407. }
  408. func main() {
  409. if len(os.Args) != 2 {
  410. log.Errorf("Usage: %s <config>\n", os.Args[0])
  411. os.Exit(1)
  412. }
  413. config, err := loadConfig(os.Args[1])
  414. if err != nil {
  415. panic(err)
  416. }
  417. log.SetOutput(os.Stdout)
  418. if config.LogFormat == "json" {
  419. log.SetFormatter(&log.JSONFormatter{})
  420. }
  421. if config.LogFormat == "text" {
  422. log.SetFormatter(&log.TextFormatter{})
  423. }
  424. log.WithFields(log.Fields{
  425. "config": config,
  426. }).Info("Loaded config")
  427. provisionerName := os.Getenv("PROVISIONER_NAME")
  428. provisionerKid := os.Getenv("PROVISIONER_KID")
  429. log.WithFields(log.Fields{
  430. "provisionerName": provisionerName,
  431. "provisionerKid": provisionerKid,
  432. }).Info("Loaded provisioner configuration")
  433. provisioner, err := NewProvisioner(provisionerName, provisionerKid, config.CaURL, rootCAPath, provisionerPasswordFile)
  434. if err != nil {
  435. log.Errorf("Error loading provisioner: %v", err)
  436. os.Exit(1)
  437. }
  438. log.WithFields(log.Fields{
  439. "name": provisioner.Name(),
  440. "kid": provisioner.Kid(),
  441. }).Info("Loaded provisioner")
  442. namespace := os.Getenv("NAMESPACE")
  443. if namespace == "" {
  444. log.Errorf("$NAMESPACE not set")
  445. os.Exit(1)
  446. }
  447. name := fmt.Sprintf("autocert.%s.svc", namespace)
  448. token, err := provisioner.Token(name)
  449. if err != nil {
  450. log.WithField("error", err).Errorf("Error generating bootstrap token during controller startup")
  451. os.Exit(1)
  452. }
  453. log.WithField("name", name).Infof("Generated bootstrap token for controller")
  454. // make sure to cancel the renew goroutine
  455. ctx, cancel := context.WithCancel(context.Background())
  456. defer cancel()
  457. srv, err := ca.BootstrapServer(ctx, token, &http.Server{
  458. Addr: ":4443",
  459. Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  460. if r.URL.Path == "/healthz" {
  461. log.Info("/healthz")
  462. fmt.Fprintf(w, "ok")
  463. w.WriteHeader(http.StatusOK)
  464. return
  465. }
  466. /*
  467. var name string
  468. if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
  469. name = r.TLS.PeerCertificates[0].Subject.CommonName
  470. }
  471. */
  472. if r.URL.Path != "/mutate" {
  473. log.WithField("path", r.URL.Path).Error("Bad Request: 404 Not Found")
  474. http.NotFound(w, r)
  475. return
  476. }
  477. var body []byte
  478. if r.Body != nil {
  479. if data, err := ioutil.ReadAll(r.Body); err == nil {
  480. body = data
  481. }
  482. }
  483. if len(body) == 0 {
  484. log.Error("Bad Request: 400 (Empty Body)")
  485. http.Error(w, "Bad Request (Empty Body)", http.StatusBadRequest)
  486. return
  487. }
  488. contentType := r.Header.Get("Content-Type")
  489. if contentType != "application/json" {
  490. log.WithField("Content-Type", contentType).Error("Bad Request: 415 (Unsupported Media Type)")
  491. http.Error(w, fmt.Sprintf("Bad Request: 415 Unsupported Media Type (Expected Content-Type 'application/json' but got '%s')", contentType), http.StatusUnsupportedMediaType)
  492. return
  493. }
  494. var response *v1beta1.AdmissionResponse
  495. review := v1beta1.AdmissionReview{}
  496. if _, _, err := deserializer.Decode(body, nil, &review); err != nil {
  497. log.WithFields(log.Fields{
  498. "body": body,
  499. "error": err,
  500. }).Error("Can't decode body")
  501. response = &v1beta1.AdmissionResponse{
  502. Allowed: false,
  503. Result: &metav1.Status{
  504. Message: err.Error(),
  505. },
  506. }
  507. } else {
  508. response = mutate(&review, config, provisioner)
  509. }
  510. resp, err := json.Marshal(v1beta1.AdmissionReview{
  511. Response: response,
  512. })
  513. if err != nil {
  514. log.WithFields(log.Fields{
  515. "uid": review.Request.UID,
  516. "error": err,
  517. }).Info("Marshal error")
  518. http.Error(w, fmt.Sprintf("Marshal Error: %v", err), http.StatusInternalServerError)
  519. } else {
  520. log.WithFields(log.Fields{
  521. "uid": review.Request.UID,
  522. "response": string(resp),
  523. }).Info("Returning review")
  524. if _, err := w.Write(resp); err != nil {
  525. log.WithFields(log.Fields{
  526. "uid": review.Request.UID,
  527. "error": err,
  528. }).Info("Write error")
  529. }
  530. }
  531. }),
  532. }, ca.VerifyClientCertIfGiven())
  533. if err != nil {
  534. panic(err)
  535. }
  536. log.Info("Listening on :4443 ...")
  537. if err := srv.ListenAndServeTLS("", ""); err != nil {
  538. panic(err)
  539. }
  540. }