Skip to content

Commit

Permalink
initial import
Browse files Browse the repository at this point in the history
  • Loading branch information
Arik Kfir committed Oct 3, 2017
1 parent 0807db7 commit b22d680
Show file tree
Hide file tree
Showing 10 changed files with 245 additions and 1 deletion.
3 changes: 3 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.python2.7
*.iml
*.md
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.python2.7
*.iml
16 changes: 16 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
language: generic
sudo: required
services:
- docker
before_script:
- docker login -u "${DOCKERHUB_USERNAME}" -p "${DOCKERHUB_PASSWORD}"
script:
- .travis/build.sh
after_script:
- |
if [[ "${TRAVIS_BRANCH}" == "master" ]]; then
docker run infolinks/github-release \
--token="${GITHUB_ACCESS_TOKEN}" \
--repo="${TRAVIS_REPO_SLUG}" \
--commit="${TRAVIS_COMMIT}"
fi
12 changes: 12 additions & 0 deletions .travis/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env bash

set -e

docker build -t infolinks/k8s-ingress-networks:${TRAVIS_COMMIT} .

if [[ ${TRAVIS_TAG} =~ ^v[0-9]+$ ]]; then
docker tag infolinks/k8s-ingress-networks:${TRAVIS_COMMIT} infolinks/k8s-ingress-networks:${TRAVIS_TAG}
docker push infolinks/k8s-ingress-networks:${TRAVIS_TAG}
docker tag infolinks/k8s-ingress-networks:${TRAVIS_COMMIT} infolinks/k8s-ingress-networks:latest
docker push infolinks/k8s-ingress-networks:latest
fi
47 changes: 47 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at dev@infolinks.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]

[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

11 changes: 11 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Contributing

When contributing to this repository, please first discuss the change you wish to make via issue, email, or any other method with the owners of this repository before making a change.

Please note we have a code of conduct, please follow it in all your interactions with the project.

## Pull Request Process

1. Include updates to README.md with details of the change, including new environment variables or mounts, preferably with examples.
2. Undocumented code will be rejected, as well as over-documented code :)

7 changes: 7 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
FROM google/cloud-sdk:171.0.0-alpine
MAINTAINER Arik Kfir <arik@infolinks.com>
RUN apk --no-cache --update add jq && \
gcloud components install --quiet kubectl
COPY update_ingresses.py scan-ingress-networks.sh /usr/local/bin/
RUN chmod a+x /usr/local/bin/scan-ingress-networks.sh /usr/local/bin/update_ingresses.py
ENTRYPOINT ["/usr/local/bin/scan-ingress-networks.sh"]
29 changes: 28 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,29 @@
# k8s-ingress-networks
Annotates Ingress resources with whitelisted CIDR ranges from configuration

[![Build Status](https://travis-ci.org/infolinks/k8s-ingress-networks.svg?branch=master)](https://travis-ci.org/infolinks/k8s-ingress-networks)

Container for continually ensuring that a Kubernetes Ingress resources is restricted only to a set of whitelisted
networks (CIDR ranges) based on a list of named networks.

This container will:

1. Search for a configuration map (whose name is provided as an environment variable) that will contain a mapping
between network names and CIDR ranges.
2. Watch Ingress resources with the annotation `ingress.infolinks.com/networks`
3. For each such Ingress resource:
1. Build a CIDR list from the combined CIDR ranges of all networks referenced in `ingress.infolinks.com/networks`
2. Add/update the Kubernetes annotation `ingress.kubernetes.io/whitelist-source-range` with the CIDR list

## Deployment

When running externally to a Kubernetes cluster, make sure that you configure `kubectl` to properly access your cluster.

If this container is running inside a Kubernetes cluster, you just need to make sure the `Pod` running this container
has the RBAC permissions to use `kubectl`.

## Contributions

Any contribution to the project will be appreciated! Whether it's bug
reports, feature requests, pull requests - all are welcome, as long as
you follow our [contribution guidelines for this project](CONTRIBUTING.md)
and our [code of conduct](CODE_OF_CONDUCT.md).
68 changes: 68 additions & 0 deletions scan-ingress-networks.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#!/usr/bin/env bash

CONFIG_MAP_NAMESPACE=${CONFIG_MAP_NAMESPACE}
if [[ -z "${CONFIG_MAP_NAMESPACE}" ]]; then
echo "Environment variable 'CONFIG_MAP_NAMESPACE' not defined" >&2
exit 1
fi

CONFIG_MAP_NAME=${CONFIG_MAP_NAME}
if [[ -z "${CONFIG_MAP_NAME}" ]]; then
echo "Environment variable 'CONFIG_MAP_NAME' not defined" >&2
exit 1
fi

while true; do
NETWORKS=$(kubectl get "configmap/${CONFIG_MAP_NAME}" -n "${CONFIG_MAP_NAMESPACE}" --output=json | jq '.data | map_values(. | split(","))')
if [[ $? != 0 ]]; then
exit 1
fi

RESTRICTED_INGRESSES=$(kubectl get ingress --all-namespaces --output=json | jq '
[
.items[] |
{
"namespace": .metadata.namespace,
"name": .metadata.name,
"networks": (.metadata.annotations["ingress.infolinks.com/networks"] // "") | split(","),
"whitelist": (.metadata.annotations["ingress.kubernetes.io/whitelist-source-range"] // "") | split(",")
}
]')
if [[ $? != 0 ]]; then
exit 1
fi

# example resulting context:
# {
# "networks": {
# "arik": [ "81.218.196.247/32", "31.168.217.84/32" ],
# "office": [ "212.143.214.138/32", "82.80.146.176/32" ]
# },
# "ingresses": [
# {
# "namespace": "app",
# "name": "echoserver",
# "networks": [ "arik", "office" ],
# "whitelist": [ "1.2.3.4/5", "6.7.8.9/0" ]
# },
# {
# "namespace": "app",
# "name": "echoserver",
# "networks": [],
# "whitelist": [ "0.0.0.0/0" ]
# }
# ]
# }
echo -nE "{ \"networks\": ${NETWORKS}, \"ingresses\": ${RESTRICTED_INGRESSES} }" | $(dirname $0)/update_ingresses.py
if [[ $? != 0 ]]; then
echo "Updating Ingress resources failed!" >&2
exit 1
fi

# rinse & repeat
sleep 10
if [[ $? != 0 ]]; then
echo "Interrupted" >&2
exit 0
fi
done
51 changes: 51 additions & 0 deletions update_ingresses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#!/usr/bin/env python2
import json
import subprocess

import sys

# URL constants
WHITELIST_ANN_NAME = 'ingress.kubernetes.io/whitelist-source-range'


def main():
# read JSON from stdin
try:
context = json.loads('\n'.join(sys.stdin.readlines()))
except:
sys.stderr.write("Failed reading JSON from stdin!\n")
sys.stderr.flush()
raise

# iterate ingresses, and for each one, construct the list of whitelisted CIDRs (from its whitelisted networks)
# then annotate the ingress to whitelist only the CIDRs collected from those whitelisted networks
networks = context['networks']
for ing in context['ingresses']:
ing_namespace = ing['namespace']
ing_name = ing['name']
ing_actual_whitelist = ing['whitelist']

# collect CIDRs from the ingress's whitelisted networks
if ing['networks']:
ing_desired_whitelist = []
for network_name in ing['networks']:
ing_desired_whitelist.extend(networks[network_name] if network_name in networks else [])
else:
ing_desired_whitelist = ["0.0.0.0/0"]

# if actual & desired whitelists are different, update ingress
if ing_actual_whitelist != ing_desired_whitelist:
print "Ingress '%s/%s' has differing actual & desired CIDR whitelist:" % (ing_namespace, ing_name)
print " Actual: %s" % ing_actual_whitelist
print " Desired: %s" % ing_desired_whitelist
whitelist_string = ','.join(ing_desired_whitelist)
subprocess.check_call(
"kubectl annotate --namespace=\"%s\" ingress/%s --overwrite %s=\"%s\"" % (ing_namespace,
ing_name,
WHITELIST_ANN_NAME,
whitelist_string),
shell=True)


if __name__ == "__main__":
main()

0 comments on commit b22d680

Please sign in to comment.