main.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. package main
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "encoding/json"
  6. "encoding/hex"
  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. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. corev1 "k8s.io/api/core/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. // 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. PatchOperation {
  233. Op: "add",
  234. Path: path,
  235. Value: new,
  236. },
  237. }
  238. } else {
  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. }
  249. func addVolumes(existing, new []corev1.Volume, path string) (ops []PatchOperation) {
  250. if len(existing) == 0 {
  251. return []PatchOperation{
  252. PatchOperation {
  253. Op: "add",
  254. Path: path,
  255. Value: new,
  256. },
  257. }
  258. } else {
  259. for _, add := range new {
  260. ops = append(ops, PatchOperation {
  261. Op: "add",
  262. Path: path + "/-",
  263. Value: add,
  264. })
  265. }
  266. return ops
  267. }
  268. }
  269. func addCertsVolumeMount(volumeName string, containers []corev1.Container) (ops []PatchOperation) {
  270. volumeMount := corev1.VolumeMount {
  271. Name: volumeName,
  272. MountPath: volumeMountPath,
  273. ReadOnly: true,
  274. }
  275. for i, container := range containers {
  276. if len(container.VolumeMounts) == 0 {
  277. ops = append(ops, PatchOperation {
  278. Op: "add",
  279. Path: fmt.Sprintf("/spec/containers/%v/volumeMounts", i),
  280. Value: []corev1.VolumeMount{volumeMount},
  281. })
  282. } else {
  283. ops = append(ops, PatchOperation {
  284. Op: "add",
  285. Path: fmt.Sprintf("/spec/containers/%v/volumeMounts/-", i),
  286. Value: volumeMount,
  287. })
  288. }
  289. }
  290. return ops
  291. }
  292. func addAnnotations(existing, new map[string]string) (ops []PatchOperation) {
  293. if len(existing) == 0 {
  294. return []PatchOperation{
  295. PatchOperation {
  296. Op: "add",
  297. Path: "/metadata/annotations",
  298. Value: new,
  299. },
  300. }
  301. }
  302. for k, v := range new {
  303. if existing[k] == "" {
  304. ops = append(ops, PatchOperation {
  305. Op: "add",
  306. Path: "/metadata/annotations/" + escapeJsonPath(k),
  307. Value: v,
  308. })
  309. } else {
  310. ops = append(ops, PatchOperation {
  311. Op: "replace",
  312. Path: "/metadata/annotations/" + escapeJsonPath(k),
  313. Value: v,
  314. })
  315. }
  316. }
  317. return ops
  318. }
  319. // patch produces a list of patches to apply to a pod to inject a certificate. In particular,
  320. // we patch the pod in order to:
  321. // - Mount the `certs` volume in existing containers defined in the pod
  322. // - Add the autocert-renewer as a container (a sidecar)
  323. // - Add the autocert-bootstrapper as an initContainer
  324. // - Add the `certs` volume definition
  325. // - Annotate the pod to indicate that it's been processed by this controller
  326. // The result is a list of serialized JSONPatch objects (or an error).
  327. func patch(pod *corev1.Pod, namespace string, config *Config, provisioner Provisioner) ([]byte, error) {
  328. var ops[] PatchOperation
  329. commonName := pod.ObjectMeta.GetAnnotations()[admissionWebhookAnnotationKey]
  330. renewer := mkRenewer(config)
  331. bootstrapper, err := mkBootstrapper(config, commonName, namespace, provisioner)
  332. if err != nil {
  333. return nil, err
  334. }
  335. ops = append(ops, addCertsVolumeMount(config.CertsVolume.Name, pod.Spec.Containers)...)
  336. ops = append(ops, addContainers(pod.Spec.Containers, []corev1.Container{renewer}, "/spec/containers")...)
  337. ops = append(ops, addContainers(pod.Spec.InitContainers, []corev1.Container{bootstrapper}, "/spec/initContainers")...)
  338. ops = append(ops, addVolumes(pod.Spec.Volumes, []corev1.Volume{config.CertsVolume}, "/spec/volumes")...)
  339. ops = append(ops, addAnnotations(pod.Annotations, map[string]string{admissionWebhookStatusKey: "injected"})...)
  340. return json.Marshal(ops)
  341. }
  342. // shouldMutate checks whether a pod is subject to mutation by this admission controller. A pod
  343. // is subject to mutation if it's annotated with the `admissionWebhookAnnotationKey` and if it
  344. // has not already been processed (indicated by `admissionWebhookStatusKey` set to `injected`).
  345. func shouldMutate(metadata *metav1.ObjectMeta) bool {
  346. annotations := metadata.GetAnnotations()
  347. if annotations == nil {
  348. annotations = map[string]string{}
  349. }
  350. // Only mutate if the object is annotated appropriately (annotation key set) and we haven't
  351. // mutated already (status key isn't set).
  352. if annotations[admissionWebhookAnnotationKey] == "" || annotations[admissionWebhookStatusKey] == "injected" {
  353. return false
  354. } else {
  355. return true
  356. }
  357. }
  358. // mutate takes an `AdmissionReview`, determines whether it is subject to mutation, and returns
  359. // an appropriate `AdmissionResponse` including patches or any errors that occurred.
  360. func mutate(review *v1beta1.AdmissionReview, config *Config, provisioner Provisioner) *v1beta1.AdmissionResponse {
  361. ctxLog := log.WithField("uid", review.Request.UID)
  362. request := review.Request
  363. var pod corev1.Pod
  364. if err := json.Unmarshal(request.Object.Raw, &pod); err != nil {
  365. ctxLog.WithField("error", err).Error("Error unmarshalling pod")
  366. return &v1beta1.AdmissionResponse {
  367. Allowed: false,
  368. UID: request.UID,
  369. Result: &metav1.Status {
  370. Message: err.Error(),
  371. },
  372. }
  373. }
  374. ctxLog = ctxLog.WithFields(log.Fields{
  375. "kind": request.Kind,
  376. "operation": request.Operation,
  377. "name": pod.Name,
  378. "generateName": pod.GenerateName,
  379. "namespace": request.Namespace,
  380. "user": request.UserInfo,
  381. })
  382. if !shouldMutate(&pod.ObjectMeta) {
  383. ctxLog.WithField("annotations", pod.Annotations).Info("Skipping mutation")
  384. return &v1beta1.AdmissionResponse {
  385. Allowed: true,
  386. UID: request.UID,
  387. }
  388. }
  389. patchBytes, err := patch(&pod, request.Namespace, config, provisioner)
  390. if err != nil {
  391. ctxLog.WithField("error", err).Error("Error generating patch")
  392. return &v1beta1.AdmissionResponse {
  393. Allowed: false,
  394. UID: request.UID,
  395. Result: &metav1.Status {
  396. Message: err.Error(),
  397. },
  398. }
  399. }
  400. ctxLog.WithField("patch", string(patchBytes)).Info("Generated patch")
  401. return &v1beta1.AdmissionResponse {
  402. Allowed: true,
  403. Patch: patchBytes,
  404. UID: request.UID,
  405. PatchType: func() *v1beta1.PatchType {
  406. pt := v1beta1.PatchTypeJSONPatch
  407. return &pt
  408. }(),
  409. }
  410. }
  411. func main() {
  412. if len(os.Args) != 2 {
  413. log.Errorf("Usage: %s <config>\n", os.Args[0])
  414. os.Exit(1)
  415. }
  416. config, err := loadConfig(os.Args[1])
  417. if err != nil {
  418. panic(err)
  419. }
  420. log.SetOutput(os.Stdout)
  421. if config.LogFormat == "json" {
  422. log.SetFormatter(&log.JSONFormatter{})
  423. }
  424. if config.LogFormat == "text" {
  425. log.SetFormatter(&log.TextFormatter{})
  426. }
  427. log.WithFields(log.Fields{
  428. "config": config,
  429. }).Info("Loaded config")
  430. provisionerName := os.Getenv("PROVISIONER_NAME")
  431. provisionerKid := os.Getenv("PROVISIONER_KID")
  432. log.WithFields(log.Fields{
  433. "provisionerName": provisionerName,
  434. "provisionerKid": provisionerKid,
  435. }).Info("Loaded provisioner configuration")
  436. provisioner, err := NewProvisioner(provisionerName, provisionerKid, config.CaUrl, rootCAPath, provisionerPasswordFile)
  437. if err != nil {
  438. log.Errorf("Error loading provisioner: %v", err)
  439. os.Exit(1)
  440. }
  441. log.WithFields(log.Fields{
  442. "name": provisioner.Name(),
  443. "kid": provisioner.Kid(),
  444. }).Info("Loaded provisioner")
  445. namespace := os.Getenv("NAMESPACE")
  446. if namespace == "" {
  447. log.Errorf("$NAMESPACE not set")
  448. os.Exit(1)
  449. }
  450. name := fmt.Sprintf("autocert.%s.svc", namespace)
  451. token, err := provisioner.Token(name)
  452. if err != nil {
  453. log.WithField("error", err).Errorf("Error generating bootstrap token during controller startup")
  454. os.Exit(1)
  455. }
  456. log.WithField("name", name).Infof("Generated bootstrap token for controller")
  457. // make sure to cancel the renew goroutine
  458. ctx, cancel := context.WithCancel(context.Background())
  459. defer cancel()
  460. srv, err := ca.BootstrapServer(ctx, token, &http.Server{
  461. Addr: ":4443",
  462. Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  463. if r.URL.Path == "/healthz" {
  464. log.Info("/healthz")
  465. fmt.Fprintf(w, "ok")
  466. w.WriteHeader(http.StatusOK)
  467. return
  468. }
  469. /*
  470. var name string
  471. if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
  472. name = r.TLS.PeerCertificates[0].Subject.CommonName
  473. }
  474. */
  475. if r.URL.Path != "/mutate" {
  476. log.WithField("path", r.URL.Path).Error("Bad Request: 404 Not Found")
  477. http.NotFound(w, r)
  478. return
  479. }
  480. var body []byte
  481. if r.Body != nil {
  482. if data, err := ioutil.ReadAll(r.Body); err == nil {
  483. body = data
  484. }
  485. }
  486. if len(body) == 0 {
  487. log.Error("Bad Request: 400 (Empty Body)")
  488. http.Error(w, "Bad Request (Empty Body)", http.StatusBadRequest)
  489. return
  490. }
  491. contentType := r.Header.Get("Content-Type")
  492. if contentType != "application/json" {
  493. log.WithField("Content-Type", contentType).Error("Bad Request: 415 (Unsupported Media Type)")
  494. http.Error(w, fmt.Sprintf("Bad Request: 415 Unsupported Media Type (Expected Content-Type 'application/json' but got '%s')", contentType), http.StatusUnsupportedMediaType)
  495. return
  496. }
  497. var response *v1beta1.AdmissionResponse
  498. review := v1beta1.AdmissionReview{}
  499. if _, _, err := deserializer.Decode(body, nil, &review); err != nil {
  500. log.WithFields(log.Fields{
  501. "body": body,
  502. "error": err,
  503. }).Error("Can't decode body")
  504. response = &v1beta1.AdmissionResponse {
  505. Allowed: false,
  506. Result: &metav1.Status {
  507. Message: err.Error(),
  508. },
  509. }
  510. } else {
  511. response = mutate(&review, config, provisioner)
  512. }
  513. resp, err := json.Marshal(v1beta1.AdmissionReview {
  514. Response: response,
  515. })
  516. if err != nil {
  517. log.WithFields(log.Fields{
  518. "uid": review.Request.UID,
  519. "error": err,
  520. }).Info("Marshal error")
  521. http.Error(w, fmt.Sprintf("Marshal Error: %v", err), http.StatusInternalServerError)
  522. } else {
  523. log.WithFields(log.Fields{
  524. "uid": review.Request.UID,
  525. "response": string(resp),
  526. }).Info("Returning review")
  527. if _, err := w.Write(resp); err != nil {
  528. log.WithFields(log.Fields{
  529. "uid": review.Request.UID,
  530. "error": err,
  531. }).Info("Write error")
  532. }
  533. }
  534. }),
  535. }, ca.VerifyClientCertIfGiven())
  536. if err != nil {
  537. panic(err)
  538. }
  539. log.Info("Listening on :4443 ...")
  540. if err := srv.ListenAndServeTLS("", ""); err != nil {
  541. panic(err)
  542. }
  543. }