Skip to content

Commit

Permalink
version 0.0.1
Browse files Browse the repository at this point in the history
  • Loading branch information
foxdalas authored and Maxim Pogozhiy committed Oct 30, 2017
1 parent 4da40b0 commit df538a4
Show file tree
Hide file tree
Showing 1,334 changed files with 495,689 additions and 102 deletions.
46 changes: 46 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
version: 2
defaults: &defaults
working_directory: /go/src/github.com/foxdalas/cfssl-kube
docker:
- image: circleci/golang:1.9.1
environment:
DOCKER_IMAGE_NAME: foxdalas/cfssl-kube
QUAY_IMAGE_NAME: quay.io/foxdalas/cfssl-kube
REPO_PATH: cfssl-kube

jobs:
build:
<<: *defaults
steps:
- checkout
- setup_remote_docker
- run:
name: Build Project
command: |
make build
docker login -u $DOCKER_LOGIN -p $DOCKER_PASSWORD
BUILD_TAG="build"
GIT_COMMIT=`git rev-parse HEAD`
GIT_TAGS=`git tag --contains $GIT_COMMIT`
DOCKER_IMAGE="$CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME"
if [[ $GIT_TAGS = "" ]]
then
IMAGE_TAGS="canary"
else
IMAGE_TAGS=`echo -e "$GIT_TAGS\nlatest"`
fi
make image
for tag in $IMAGE_TAGS; do
echo $tag
docker tag $DOCKER_IMAGE:$BUILD_TAG $DOCKER_IMAGE:$tag
docker push $DOCKER_IMAGE:$tag
done
cp Dockerfile _build/
cp Makefile _build/
docker images
- store_artifacts:
path: /go/src/github.com/foxdalas/cfssl-kube/_build
destination: cfssl-kube
- persist_to_workspace:
root: /go/src/github.com/foxdalas
paths: cfssl-kube
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff:
cfssl-kube
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
Expand Down
16 changes: 16 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
FROM alpine:3.5
MAINTAINER Maxim Pogozhiy <[email protected]>

RUN addgroup -g 1000 app && \
adduser -G app -h /home/app -u 1000 -D app

USER app
WORKDIR /home/app

COPY _build/cfssl-kube-linux-amd64 /cfssl-kube
ENTRYPOINT ["/cfssl-kube"]

ARG VCS_REF
LABEL org.label-schema.vcs-ref=$VCS_REF \
org.label-schema.vcs-url="https://github.com/foxdalas/cfssl-kube" \
org.label-schema.license="Apache-2.0"
62 changes: 62 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
ACCOUNT=foxdalas
APP_NAME=cfssl-kube

PACKAGE_NAME=github.com/${ACCOUNT}/${APP_NAME}
GO_VERSION=1.9.1

GOOS := linux
GOARCH := amd64

DOCKER_IMAGE=${ACCOUNT}/${APP_NAME}

BUILD_DIR=_build
TEST_DIR=_test

CONTAINER_DIR=/go/src/${PACKAGE_NAME}

BUILD_TAG := build
IMAGE_TAGS := canary

PACKAGES=$(shell find . -name "*_test.go" | xargs -n1 dirname | grep -v 'vendor/' | sort -u | xargs -n1 printf "%s.test_pkg ")

.PHONY: version

all: test build

depend:
rm -rf $(TEST_DIR)/
rm -rf ${BUILD_DIR}/
mkdir $(TEST_DIR)/
mkdir $(BUILD_DIR)/

version:
$(eval GIT_STATE := $(shell if test -z "`git status --porcelain 2> /dev/null`"; then echo "clean"; else echo "dirty"; fi))
$(eval GIT_COMMIT := $(shell git rev-parse HEAD))
$(eval APP_VERSION ?= $(shell cat VERSION))
@echo $(APP_VERSION)

%.test_pkg: test_prepare
$(eval PKG := ./$*)
$(eval PKG_CLEAN := $(shell echo "$*" | sed "s#^p#.p#" | sed "s#/#-#g"))
@echo "test $(PKG_CLEAN) ($(PKG))"
bash -o pipefail -c "go test -v -coverprofile=$(TEST_DIR)/coverage$(PKG_CLEAN).txt -covermode count $(PKG) | tee $(TEST_DIR)/test$(PKG_CLEAN).out"
cat $(TEST_DIR)/test$(PKG_CLEAN).out | go2xunit > $(TEST_DIR)/test$(PKG_CLEAN).xml
gocover-cobertura < $(TEST_DIR)/coverage$(PKG_CLEAN).txt > $(TEST_DIR)/coverage$(PKG_CLEAN).xml

build: depend version
CGO_ENABLED=0 GOOS=$(GOOS) GOARCH=$(GOARCH) go build \
-a -tags netgo \
-o ${BUILD_DIR}/${APP_NAME}-$(GOOS)-$(GOARCH) \
-ldflags "-X main.AppGitState=${GIT_STATE} -X main.AppGitCommit=${GIT_COMMIT} -X main.AppVersion=${APP_VERSION}"

docker:

image: version
docker build --build-arg VCS_REF=$(GIT_COMMIT) -t $(DOCKER_IMAGE):$(BUILD_TAG) .

push: image
set -e; \
for tag in $(IMAGE_TAGS); do \
docker tag $(DOCKER_IMAGE):$(BUILD_TAG) $(DOCKER_IMAGE):$${tag} ; \
docker push $(DOCKER_IMAGE):$${tag}; \
done
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# cfssl-kube
CFSSL Certificates generator for Kubernetes

[![Docker Repository on Quay](https://quay.io/repository/foxdalas/cfssl-kube/status "Docker Repository on Quay")](https://quay.io/repository/foxdalas/cfssl-kube)
[![Docker Pulls](https://img.shields.io/docker/pulls/foxdalas/cfssl-kube.svg?maxAge=604800)](https://hub.docker.com/r/foxdalas/cfssl-kube/)
[![CircleCI](https://circleci.com/gh/foxdalas/cfssl-kube.svg?style=svg)](https://circleci.com/gh/foxdalas/cfssl-kube)
1 change: 1 addition & 0 deletions VERSION
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0.0.1-dev
5 changes: 2 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package main

import (
"cfssl-kube/pkg/cfkube"
"github.com/foxdalas/cfssl-kube/pkg/cfkube"
)

var AppVersion = "unknown"
Expand All @@ -21,8 +21,7 @@ func Version() string {
return version
}


func main() {
cf := cfkube.New(Version())
cf.Init()
}
}
60 changes: 26 additions & 34 deletions pkg/cfkube/cfkube.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
package cfkube

import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
"sync"
cfkube "cfssl-kube/pkg/cfkube_const"
"cfssl-kube/pkg/secret"
"github.com/foxdalas/cfssl-kube/pkg/cfkube_const"
"github.com/foxdalas/cfssl-kube/pkg/cfssl"
"github.com/foxdalas/cfssl-kube/pkg/secret"
log "github.com/sirupsen/logrus"
"strings"
"k8s.io/client-go/kubernetes"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"cfssl-kube/pkg/cfssl"
"k8s.io/client-go/kubernetes"
"encoding/pem"
"crypto/x509"
"crypto/tls"
)

var _ cfkube.CFKube = &CFKube{}
Expand Down Expand Up @@ -52,25 +52,21 @@ func (cf *CFKube) Init() {
cf.Log().Fatal(err)
}



err = cf.InitKube()
if err != nil {
cf.Log().Fatal(err)
}


cf.Log().Infoln("Periodically check start")
ticker := time.NewTicker(cf.cfCheckInterval)
cs := cfssl.New(cf)
go func() {
for timestamp := range ticker.C {
timestamp := time.Now()
cf.Log().Infof("Periodically check certificates at %s", timestamp)
for _, namespace := range cf.cfKubeNamespaces {
cf.cfNamespace = namespace
cf.cfSecretName = "cfssl-tls-secret"
cf.Log().Infoln("Checking namespace: ", cf.cfNamespace)

cf.Log().Infoln("Checking namespace:", cf.cfNamespace)

s := secret.New(cf, namespace, "cfssl-tls-secret")

Expand All @@ -84,11 +80,12 @@ func (cf *CFKube) Init() {
cf.Log().Printf("Secret for namespace %s already exist", cf.cfNamespace)
validate := cf.ValidateTLS(s.SecretApi.Data["ca.pem"], s.SecretApi.Data["crt.pem"], s.SecretApi.Data["crt.key"])
if !validate {
cf.SaveSecret(cs.GetCertificate(cf.cfAddress, cf.cfAuthKey, cf.cfCSRConfig, cs.CreateKey()))
//cf.SaveSecret(cs.GetCertificate(cf.cfAddress, cf.cfAuthKey, cf.cfCSRConfig, cs.CreateKey()))
cf.Log().Println("Certificate validation problem.")
}
}
}
}
<- ticker.C
}()

<-cf.stopCh
Expand Down Expand Up @@ -130,7 +127,6 @@ func makeLog() *log.Entry {
return log.WithField("context", "cfkube")
}


func (cf *CFKube) Version() string {
return cf.version
}
Expand Down Expand Up @@ -160,7 +156,6 @@ func (cf *CFKube) cfsslSecret() *secret.Secret {
return secret.New(cf, cf.cfNamespace, cf.cfSecretName)
}


func (cf *CFKube) paramsCF() error {

cf.cfAddress = os.Getenv("CFKUBE_CFSSL_ADDRESS")
Expand All @@ -187,7 +182,7 @@ func (cf *CFKube) paramsCF() error {
cf.cfKubeApiURL = "http://127.0.0.1:8080"
}

cf.cfKubeNamespaces = strings.Split(os.Getenv("CFKUBE_NAMESPACES"),",")
cf.cfKubeNamespaces = strings.Split(os.Getenv("CFKUBE_NAMESPACES"), ",")
if len(cf.cfKubeNamespaces) == 0 {
return errors.New("Please provide the namespaces via environment variable CFKUBE_NAMESPACES (default,test,production)")
}
Expand All @@ -202,27 +197,29 @@ func (cf *CFKube) SaveSecret(data map[string][]byte) error {
}

func (c *CFKube) ValidateTLS(caByte []byte, certByte []byte, keyByte []byte) bool {
check := true

block, _ := pem.Decode(certByte)

if block == nil {
c.Log().Errorln("Failed to parse certificate PEM")
return false
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
c.Log().Printf("Failed to parse certificate: " + err.Error())
c.Log().Printf("Failed to parse certificate: %s", err)
return false
}
if (cert.NotAfter.Unix() - time.Now().Unix()) < int64(cfkube.ExpireThreshold) {
c.Log().Warningf("Certificate expire date > Threshold ")
check = false
return false
} else {
c.Log().Infoln("Certificate expire date is OK")
}

_, err = tls.X509KeyPair(certByte, keyByte)
if err != nil {
c.Log().Warningln("Certificate cert/key is mismatch")
check = false
return false
} else {
c.Log().Infoln("Certificate cert/key is OK")
}
Expand All @@ -231,27 +228,22 @@ func (c *CFKube) ValidateTLS(caByte []byte, certByte []byte, keyByte []byte) boo
ok := roots.AppendCertsFromPEM(caByte)
if !ok {
log.Warnln("Failed to parse root certificate")
check = false
return false
}

for _, dnsName := range cert.DNSNames {
opts := x509.VerifyOptions{
DNSName: dnsName,
Roots: roots,
}
c.Log().Infof("Validating certificate for DNS name: %s",dnsName )
c.Log().Infof("Validating certificate for DNS name: %s", dnsName)
if _, err := cert.Verify(opts); err != nil {
c.Log().Warnf("failed to verify certificate: " + err.Error())
check = false
return false
} else {
c.Log().Infof("Certificate is valid for %s", dnsName)
}
}

if check {
//Information about certificate
c.Log().Infof("Certificate is valid. Expire Date %s", cert.NotAfter)
}

return check
}
return true
}
2 changes: 1 addition & 1 deletion pkg/cfkube/kube.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,4 @@ func (cf *CFKube) InitKube() error {

func (cf *CFKube) Namespace() string {
return cf.cfNamespace
}
}
28 changes: 14 additions & 14 deletions pkg/cfkube/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,31 @@ package cfkube

import (
log "github.com/sirupsen/logrus"
"sync"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/util/workqueue"
"sync"
"time"
"k8s.io/client-go/kubernetes"
)

type CFKube struct {
version string
log *log.Entry
log *log.Entry

cfAddress string
cfAuthKey string
cfCSRConfig []byte
cfNamespace string
cfSecretName string
cfAddress string
cfAuthKey string
cfCSRConfig []byte
cfNamespace string
cfSecretName string

cfCheckInterval time.Duration
//cfsslClient cfkubeCfssl

kubeClient *kubernetes.Clientset
kubeClient *kubernetes.Clientset

cfKubeApiURL string
cfKubeApiURL string
cfKubeNamespaces []string

stopCh chan struct{}
waitGroup sync.WaitGroup
workQueue *workqueue.Type
}
stopCh chan struct{}
waitGroup sync.WaitGroup
workQueue *workqueue.Type
}
2 changes: 1 addition & 1 deletion pkg/cfkube/watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,4 @@ func (cf *CFKube) WatchReconfigure() {
cf.workQueue.Done(item)
}
}()
}
}
2 changes: 1 addition & 1 deletion pkg/cfkube_const/const.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ const TLSPrivateKeyKey = k8sApi.TLSPrivateKeyKey

const ExpireThreshold = 604800

const PKIUri = "/api/v1/cfssl/"
const PKIUri = "/api/v1/cfssl/"
Loading

0 comments on commit df538a4

Please sign in to comment.