Create auditd formula

According to linked prod's we need to create fully functional
auditd formula. This formula allows install and configure auditd, as
well as generate auditd rules and install/configure audisp
plugins if necessary.

Change-Id: Ieb6c889c7fceec7281e1ad019b1f07daf689c3f7
Related-PROD: https://mirantis.jira.com/browse/PROD-20233
Related-PROD: https://mirantis.jira.com/browse/PROD-20138
diff --git a/.gitreview b/.gitreview
index fed844a..def1ba9 100644
--- a/.gitreview
+++ b/.gitreview
@@ -1,4 +1,3 @@
 [gerrit]
-host=172.16.48.254
-port=29418
+host=gerrit.mcp.mirantis.net
 project=salt-formulas/auditd.git
diff --git a/.kitchen.yml b/.kitchen.yml
new file mode 100644
index 0000000..0e39595
--- /dev/null
+++ b/.kitchen.yml
@@ -0,0 +1,46 @@
+# vim: ft=yaml
+---
+driver:
+  name: docker
+  vm_hostname: auditd.ci.local
+
+provisioner:
+  name: salt_solo
+  salt_install: bootstrap
+  salt_bootstrap_url: https://bootstrap.saltstack.com
+  salt_version: latest
+  require_chef: false
+  log_level: error
+  formula: auditd
+  state_top:
+    base:
+      "*":
+        - auditd
+  pillars:
+    top.sls:
+      base:
+        "*":
+          - server
+          - rules
+          - audisp
+
+verifier:
+  name: inspec
+  sudo: true
+
+platforms:
+  - name: <%=ENV['PLATFORM'] || 'saltstack-ubuntu-xenial-salt-stable' %>
+    driver_config:
+      image: <%=ENV['PLATFORM'] || 'epcim/salt:saltstack-ubuntu-xenial-salt-stable'%>
+      platform: ubuntu
+
+suites:
+
+  - name: server
+    provisioner:
+      pillars-from-files:
+        server.sls: tests/pillar/server.sls
+        rules.sls: tests/pillar/rules.sls
+        audisp.sls: tests/pillar/audisp.sls
+    driver:
+      hostname: auditd.ci.local
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..480f9f9
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,30 @@
+sudo: required
+services:
+  - docker
+
+install:
+  - pip install PyYAML
+  - pip install virtualenv
+  - |
+    test -e Gemfile || cat <<EOF > Gemfile
+    source 'https://rubygems.org'
+    gem 'rake'
+    gem 'test-kitchen'
+    gem 'kitchen-docker'
+    gem 'kitchen-inspec'
+    gem 'inspec'
+    gem 'kitchen-salt', :git => 'https://github.com/salt-formulas/kitchen-salt.git'
+  - bundle install
+
+env:
+  - PLATFORM=epcim/salt:saltstack-ubuntu-xenial-salt-2016.3 SUITE=server
+  - PLATFORM=epcim/salt:saltstack-ubuntu-xenial-salt-2017.7 SUITE=server
+  - PLATFORM=epcim/salt:saltstack-ubuntu-xenial-salt-2018.3 SUITE=server
+
+before_script:
+  - set -o pipefail
+  - make test | tail
+
+script:
+  - test ! -e .kitchen.yml || bundle exec kitchen converge ${SUITE} || true
+  - test ! -e .kitchen.yml || bundle exec kitchen verify ${SUITE} -t tests/integration
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
new file mode 100644
index 0000000..84a31b5
--- /dev/null
+++ b/CHANGELOG.rst
@@ -0,0 +1,6 @@
+auditd formula
+=====================================
+
+0.1 (2018-06-07)
+
+- Initial formula setup
diff --git a/INTEGRATION.rst b/INTEGRATION.rst
new file mode 100644
index 0000000..6555079
--- /dev/null
+++ b/INTEGRATION.rst
@@ -0,0 +1,114 @@
+
+Continuous Integration
+======================
+
+We are using Jenkins to spin a kitchen instances in Docker or OpenStack environment.
+
+If you would like to repeat, then you may use ``.kitchen.<backend>.yml`` configuration yaml in the main directory
+to override ``.kitchen.yml`` at some points.
+Usage: ``KITCHEN_LOCAL_YAML=.kitchen.<driver>.yml kitchen verify server-ubuntu-1404 -t tests/integration``.
+Example: ``KITCHEN_LOCAL_YAML=.kitchen.docker.yml kitchen verify server-ubuntu-1404 -t tests/integration``.
+
+Be aware of fundamental differences of backends. The formula verification scripts are primarily tested with
+Vagrant driver.
+
+CI uses a tuned `make kitchen` target defined in `Makefile` to perform following (Kitchen Test) actions:
+
+1. *create*, provision an test instance (VM, container)
+2. *converge*, run a provisioner (shell script, kitchen-salt)
+3. *verify*, run a verification (inspec, other may be added)
+4. *destroy*
+
+
+Test Kitchen
+------------
+
+
+To install Test Kitchen is as simple as:
+
+.. code-block:: shell
+
+  # install kitchen
+  gem install test-kitchen
+
+  # install required plugins
+  gem install kitchen-vagrant kitchen-docker kitchen-salt
+
+  # install additional plugins & tools
+  gem install kitchen-openstack kitchen-inspec busser-serverspec
+
+  kitchen list
+  kitchen test
+
+of course you have to have installed Ruby and it's package manager `gem <https://rubygems.org/>`_ first.
+
+One may be satisfied installing it system-wide right from OS package manager which is preferred installation method.
+For advanced users or the sake of complex environments you may use `rbenv <https://github.com/rbenv/rbenv>`_ for user side ruby installation.
+
+ * https://github.com/rbenv/rbenv
+ * http://kitchen.ci/docs/getting-started/installing
+
+An example steps then might be:
+
+.. code-block:: shell
+
+  # get rbenv
+  git clone https://github.com/rbenv/rbenv.git ~/.rbenv
+
+  # configure
+  cd ~/.rbenv && src/configure && make -C src     # don't worry if it fails
+  echo 'export PATH="$HOME/.rbenv/bin:$PATH"'>> ~/.bash_profile
+  # Ubuntu Desktop note: Modify your ~/.bashrc instead of ~/.bash_profile.
+  cd ~/.rbenv; git fetch
+
+  # install ruby-build, which provides the rbenv install command
+  git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
+
+  # list all available versions:
+  rbenv install -l
+
+  # install a Ruby version
+  # maybe you will need additional packages: libssl-dev, libreadline-dev, zlib1g-dev
+  rbenv install 2.0.0-p648
+
+  # activate
+  rbenv local 2.0.0-p648
+
+  # install test kitchen
+  gem install test-kitchen
+
+
+An optional ``Gemfile`` in the main directory may contain Ruby dependencies to be required for Test Kitchen workflow.
+To install them you have to install first ``gem install bundler`` and then run ``bundler install``.
+
+
+
+Verifier
+--------
+
+The `Busser <https://github.com/test-kitchen/busser>`_ *Verifier* goes with test-kitchen by default.
+It is used to setup and run tests implemented in `<repo>/test/integration`. It guess and installs the particular driver to tested instance.
+By default `InSpec <https://github.com/chef/kitchen-inspec>`_ is expected.
+
+You may avoid to install busser framework if you configure specific verifier in `.kitchen.yml` and install it kitchen plugin locally:
+
+	verifier:
+		name: serverspec
+
+If you would to write another verification scripts than InSpec store them in ``<repo>/tests/integration/<suite>/<busser>/*``.
+``Busser <https://github.com/test-kitchen/busser>`` is a test setup and execution framework under test kitchen.
+
+
+
+InSpec
+~~~~~~
+
+Implement integration tests under ``<repo>/tests/integration/<suite>/<busser>/*`` directory with ``_spec.rb`` filename
+suffix.
+
+Docs:
+
+* https://github.com/chef/inspec
+* https://github.com/chef/kitchen-inspec
+
+
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..55a70df
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,13 @@
+Copyright (c) 2018 Mirantis Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
\ No newline at end of file
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..1043fbe
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,118 @@
+DESTDIR=/
+SALTENVDIR=/usr/share/salt-formulas/env
+RECLASSDIR=/usr/share/salt-formulas/reclass
+FORMULANAME=$(shell grep name: metadata.yml|head -1|cut -d : -f 2|grep -Eo '[a-z0-9\-\_]*')
+VERSION=$(shell grep version: metadata.yml|head -1|cut -d : -f 2|grep -Eo '[a-z0-9\.\-\_]*')
+VERSION_MAJOR := $(shell echo $(VERSION)|cut -d . -f 1-2)
+VERSION_MINOR := $(shell echo $(VERSION)|cut -d . -f 3)
+
+NEW_MAJOR_VERSION ?= $(shell date +%Y.%m|sed 's,\.0,\.,g')
+NEW_MINOR_VERSION ?= $(shell /bin/bash -c 'echo $$[ $(VERSION_MINOR) + 1 ]')
+
+MAKE_PID := $(shell echo $$PPID)
+JOB_FLAG := $(filter -j%, $(subst -j ,-j,$(shell ps T | grep "^\s*$(MAKE_PID).*$(MAKE)")))
+
+ifneq ($(subst -j,,$(JOB_FLAG)),)
+JOBS := $(subst -j,,$(JOB_FLAG))
+else
+JOBS := 1
+endif
+
+KITCHEN_LOCAL_YAML?=.kitchen.yml
+KITCHEN_OPTS?="--concurrency=$(JOBS)"
+KITCHEN_OPTS_CREATE?=""
+KITCHEN_OPTS_CONVERGE?=""
+KITCHEN_OPTS_VERIFY?=""
+KITCHEN_OPTS_TEST?=""
+
+all:
+	@echo "make install - Install into DESTDIR"
+	@echo "make test    - Run tests"
+	@echo "make kitchen - Run Kitchen CI tests (create, converge, verify)"
+	@echo "make clean   - Cleanup after tests run"
+	@echo "make release-major  - Generate new major release"
+	@echo "make release-minor  - Generate new minor release"
+	@echo "make changelog      - Show changes since last release"
+
+install:
+	# Formula
+	[ -d $(DESTDIR)/$(SALTENVDIR) ] || mkdir -p $(DESTDIR)/$(SALTENVDIR)
+	cp -a $(FORMULANAME) $(DESTDIR)/$(SALTENVDIR)/
+	[ ! -d _modules ] || cp -a _modules $(DESTDIR)/$(SALTENVDIR)/
+	[ ! -d _states ] || cp -a _states $(DESTDIR)/$(SALTENVDIR)/ || true
+	[ ! -d _grains ] || cp -a _grains $(DESTDIR)/$(SALTENVDIR)/ || true
+	# Metadata
+	[ -d $(DESTDIR)/$(RECLASSDIR)/service/$(FORMULANAME) ] || mkdir -p $(DESTDIR)/$(RECLASSDIR)/service/$(FORMULANAME)
+	cp -a metadata/service/* $(DESTDIR)/$(RECLASSDIR)/service/$(FORMULANAME)
+
+test:
+	[ ! -d tests ] || (cd tests; ./run_tests.sh)
+
+release-major: check-changes
+	@echo "Current version is $(VERSION), new version is $(NEW_MAJOR_VERSION)"
+	@[ $(VERSION_MAJOR) != $(NEW_MAJOR_VERSION) ] || (echo "Major version $(NEW_MAJOR_VERSION) already released, nothing to do. Do you want release-minor?" && exit 1)
+	echo "$(NEW_MAJOR_VERSION)" > VERSION
+	sed -i 's,version: .*,version: "$(NEW_MAJOR_VERSION)",g' metadata.yml
+	[ ! -f debian/changelog ] || dch -v $(NEW_MAJOR_VERSION) -m --force-distribution -D `dpkg-parsechangelog -S Distribution` "New version"
+	make genchangelog-$(NEW_MAJOR_VERSION)
+	(git add -u; git commit -m "Version $(NEW_MAJOR_VERSION)")
+	git tag -s -m $(NEW_MAJOR_VERSION) $(NEW_MAJOR_VERSION)
+
+release-minor: check-changes
+	@echo "Current version is $(VERSION), new version is $(VERSION_MAJOR).$(NEW_MINOR_VERSION)"
+	echo "$(VERSION_MAJOR).$(NEW_MINOR_VERSION)" > VERSION
+	sed -i 's,version: .*,version: "$(VERSION_MAJOR).$(NEW_MINOR_VERSION)",g' metadata.yml
+	[ ! -f debian/changelog ] || dch -v $(VERSION_MAJOR).$(NEW_MINOR_VERSION) -m --force-distribution -D `dpkg-parsechangelog -S Distribution` "New version"
+	make genchangelog-$(VERSION_MAJOR).$(NEW_MINOR_VERSION)
+	(git add -u; git commit -m "Version $(VERSION_MAJOR).$(NEW_MINOR_VERSION)")
+	git tag -s -m $(NEW_MAJOR_VERSION) $(VERSION_MAJOR).$(NEW_MINOR_VERSION)
+
+check-changes:
+	@git log --pretty=oneline --decorate $(VERSION)..HEAD | grep -Eqc '.*' || (echo "No new changes since version $(VERSION)"; exit 1)
+
+changelog:
+	git log --pretty=short --invert-grep --grep="Merge pull request" --decorate $(VERSION)..HEAD
+
+genchangelog: genchangelog-$(VERSION_MAJOR).$(NEW_MINOR_VERSION)
+
+genchangelog-%:
+	$(eval NEW_VERSION := $(patsubst genchangelog-%,%,$@))
+	(echo "=========\nChangelog\n=========\n"; \
+	(echo $(NEW_VERSION);git tag) | sort -r | grep -E '^[0-9\.]+' | while read i; do \
+	    cur=$$i; \
+	    test $$i = $(NEW_VERSION) && i=HEAD; \
+	    prev=`(echo $(NEW_VERSION);git tag)|sort|grep -E '^[0-9\.]+'|grep -B1 "$$cur\$$"|head -1`; \
+	    echo "Version $$cur\n=============================\n"; \
+	    git log --pretty=short --invert-grep --grep="Merge pull request" --decorate $$prev..$$i; \
+	    echo; \
+	done) > CHANGELOG.rst
+
+kitchen-check:
+	@[ -e $(KITCHEN_LOCAL_YAML) ] || (echo "Kitchen tests not available, there's no $(KITCHEN_LOCAL_YAML)." && exit 1)
+
+kitchen: kitchen-check kitchen-create kitchen-converge kitchen-verify kitchen-list
+
+kitchen-create: kitchen-check
+	kitchen create ${KITCHEN_OPTS} ${KITCHEN_OPTS_CREATE}
+	[ "$(shell echo $(KITCHEN_LOCAL_YAML)|grep -Eo docker)" = "docker" ] || sleep 120
+
+kitchen-converge: kitchen-check
+	kitchen converge ${KITCHEN_OPTS} ${KITCHEN_OPTS_CONVERGE} &&\
+	kitchen converge ${KITCHEN_OPTS} ${KITCHEN_OPTS_CONVERGE}
+
+kitchen-verify: kitchen-check
+	[ ! -d tests/integration ] || kitchen verify -t tests/integration ${KITCHEN_OPTS} ${KITCHEN_OPTS_VERIFY}
+	[ -d tests/integration ]   || kitchen verify ${KITCHEN_OPTS} ${KITCHEN_OPTS_VERIFY}
+
+kitchen-test: kitchen-check
+	[ ! -d tests/integration ] || kitchen test -t tests/integration ${KITCHEN_OPTS} ${KITCHEN_OPTS_TEST}
+	[ -d tests/integration ]   || kitchen test ${KITCHEN_OPTS} ${KITCHEN_OPTS_TEST}
+
+kitchen-list: kitchen-check
+	kitchen list
+
+clean:
+	[ ! -x "$(shell which kitchen)" ] || kitchen destroy
+	[ ! -d .kitchen ] || rm -rf .kitchen
+	[ ! -d tests/build ] || rm -rf tests/build
+	[ ! -d build ] || rm -rf build
diff --git a/README.rst b/README.rst
new file mode 100644
index 0000000..2057ec5
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,100 @@
+
+==================================
+Auditd Formula
+==================================
+
+The Linux Audit system provides a way to track security-relevant information on
+your system. Based on pre-configured rules, Audit generates log entries to
+record as much information about the events that are happening on your system
+as possible. This information is crucial for mission-critical environments to
+determine the violator of the security policy and the actions they performed.
+Audit does not provide additional security to your system; rather, it can be
+used to discover violations of security policies used on your system.
+These violations can further be prevented by additional security
+measures such as SELinux.
+
+
+
+Sample Metadata
+===============
+
+Single auditd service
+
+.. code-block:: yaml
+  auditd:
+    service:
+      enabled: true
+      log_file: /var/log/audit/audit.log
+      log_format: NOLOG
+      log_group: root
+      priority_boost: 4
+      flush: INCREMENTAL
+      freq: 20
+      num_logs: 5
+      disp_qos: lossy
+      dispatcher: /sbin/audispd
+      name_format: HOSTNAME
+      max_log_file: 6
+      max_log_file_action: ROTATE
+      space_left: 75
+      space_left_action: SYSLOG
+      action_mail_acct: root
+      admin_space_left: 50
+      admin_space_left_action: SUSPEND
+      disk_full_action: SUSPEND
+      disk_error_action: SUSPEND
+      tcp_listen_queue: 5
+      tcp_max_per_addr: 1
+      tcp_client_max_idle: 0
+      enable_krb5: 'no'
+      krb5_principal: auditd
+    audisp:
+      enabled: true
+    rules:
+      options:
+        enabled: 0
+        bufsize: 8192
+      rules:
+        some_rule_key:
+          enabled: true
+          rule_list:
+            - '-w /etc/passwd -p wa'
+            - '-a always,exit -F arch=b64 -S mount'
+
+
+References
+=========
+https://github.com/linux-audit/audit-documentation/wiki
+https://linux-audit.com
+https://github.com/linux-audit/audit-userspace
+
+Documentation and Bugs
+======================
+
+To learn how to install and update salt-formulas, consult the documentation
+available online at:
+
+    http://salt-formulas.readthedocs.io/
+
+In the unfortunate event that bugs are discovered, they should be reported to
+the appropriate issue tracker. Use GitHub issue tracker for specific salt
+formula:
+
+    https://github.com/salt-formulas/salt-formula-auditd/issues
+
+For feature requests, bug reports or blueprints affecting entire ecosystem,
+use Launchpad salt-formulas project:
+
+    https://launchpad.net/salt-formulas
+
+Developers wishing to work on the salt-formulas projects should always base
+their work on master branch and submit pull request against specific formula.
+
+You should also subscribe to mailing list (salt-formulas@freelists.org):
+
+    https://www.freelists.org/list/salt-formulas
+
+Any questions or feedback is always welcome so feel free to join our IRC
+channel:
+
+    #salt-formulas @ irc.freenode.net
diff --git a/VERSION b/VERSION
new file mode 100644
index 0000000..49d5957
--- /dev/null
+++ b/VERSION
@@ -0,0 +1 @@
+0.1
diff --git a/auditd/audisp.sls b/auditd/audisp.sls
new file mode 100644
index 0000000..e735641
--- /dev/null
+++ b/auditd/audisp.sls
@@ -0,0 +1,27 @@
+{%- from "auditd/map.jinja" import audisp with context %}
+
+{%- if audisp.get('enabled', False) %}
+
+include:
+  - auditd.service
+
+audisp_packages:
+  pkg.installed:
+    - names: {{ audisp.pkgs }}
+
+{%- for plugin, plugin_params in audisp.plugins.items() %}
+{{ audisp.config_path }}/{{ plugin }}.conf:
+  file.managed:
+    - source: salt://auditd/files/audisp.plugin.conf
+    - template: jinja
+    - context:
+      params: {{ plugin_params }}
+    - user: root
+    - group: root
+    - mode: 0640
+    - require:
+      - pkg: audisp_packages
+    - watch_in:
+      - service: auditd_service
+{%- endfor %}
+{%- endif %}
diff --git a/auditd/files/audisp.plugin.conf b/auditd/files/audisp.plugin.conf
new file mode 100644
index 0000000..a9d73e3
--- /dev/null
+++ b/auditd/files/audisp.plugin.conf
@@ -0,0 +1,10 @@
+# This file managed by Salt.
+# All local modifications will be overwritten.
+active = {{ params.active }}
+direction = {{ params.direction }}
+path = {{ params.path }}
+type = {{ params.type }}
+{%- if 'args' in params %}
+args = {{ params.args }}
+{%- endif %}
+format = {{ params.format }}
diff --git a/auditd/files/auditd.conf b/auditd/files/auditd.conf
new file mode 100644
index 0000000..8b0d3f7
--- /dev/null
+++ b/auditd/files/auditd.conf
@@ -0,0 +1,101 @@
+{%- from "auditd/map.jinja" import service with context %}
+
+{%- if service.log_file is defined %}
+log_file = {{ service.log_file }}
+{%- endif %}
+
+{%- if service.log_format is defined %}
+log_format = {{ service.log_format }}
+{%- endif %}
+
+{%- if service.log_group is defined %}
+log_group = {{ service.log_group }}
+{%- endif %}
+
+{%- if service.priority_boost is defined %}
+priority_boost = {{ service.priority_boost }}
+{%- endif %}
+
+{%- if service.flush is defined %}
+flush = {{ service.flush }}
+{%- endif %}
+
+{%- if service.freq is defined %}
+freq = {{ service.freq }}
+{%- endif %}
+
+{%- if service.num_logs is defined %}
+num_logs = {{ service.num_logs }}
+{%- endif %}
+
+{%- if service.disp_qos is defined %}
+disp_qos = {{ service.disp_qos }}
+{%- endif %}
+
+{%- if service.dispatcher is defined %}
+dispatcher = {{ service.dispatcher }}
+{%- endif %}
+
+{%- if service.name_format is defined %}
+name_format = {{ service.name_format }}
+{%- endif %}
+
+{%- if service.max_log_file is defined %}
+max_log_file = {{ service.max_log_file }}
+{%- endif %}
+
+{%- if service.max_log_file_action is defined %}
+max_log_file_action = {{ service.max_log_file_action }}
+{%- endif %}
+
+{%- if service.space_left is defined %}
+space_left = {{ service.space_left }}
+{%- endif %}
+
+{%- if service.space_left_action is defined %}
+space_left_action = {{ service.space_left_action }}
+{%- endif %}
+
+{%- if service.action_mail_acct is defined %}
+action_mail_acct = {{ service.action_mail_acct }}
+{%- endif %}
+
+{%- if service.admin_space_left is defined %}
+admin_space_left = {{ service.admin_space_left }}
+{%- endif %}
+
+{%- if service.admin_space_left_action is defined %}
+admin_space_left_action = {{ service.admin_space_left_action }}
+{%- endif %}
+
+{%- if service.disk_full_action is defined %}
+disk_full_action = {{ service.disk_full_action }}
+{%- endif %}
+
+{%- if service.disk_error_action is defined %}
+disk_error_action = {{ service.disk_error_action }}
+{%- endif %}
+
+{%- if service.tcp_listen_port is defined %}
+tcp_listen_port = {{ service.tcp_listen_port }}
+{%- endif %}
+
+{%- if service.tcp_listen_queue is defined %}
+tcp_listen_queue = {{ service.tcp_listen_queue }}
+{%- endif %}
+
+{%- if service.tcp_max_per_addr is defined %}
+tcp_max_per_addr = {{ service.tcp_max_per_addr }}
+{%- endif %}
+
+{%- if service.tcp_client_max_idle is defined %}
+tcp_client_max_idle = {{ service.tcp_client_max_idle }}
+{%- endif %}
+
+{%- if service.enable_krb5 is defined %}
+enable_krb5 = {{ service.enable_krb5 }}
+{%- endif %}
+
+{%- if service.krb5_principal is defined %}
+krb5_principal = {{ service.krb5_principal }}
+{%- endif %}
diff --git a/auditd/files/auditd.rules.conf b/auditd/files/auditd.rules.conf
new file mode 100644
index 0000000..e218cfc
--- /dev/null
+++ b/auditd/files/auditd.rules.conf
@@ -0,0 +1,21 @@
+{%- from "auditd/map.jinja" import rules with context %}
+-D
+{%- set bufsize = rules.get('options', {}).get('bufsize', 8192) %}
+-b {{ bufsize }}
+
+{%- set ruledict = rules.get('rules', {}) %}
+{%- if ruledict|length > 0 %}
+# Rules
+{%- for rulegroup, options in ruledict.items() %}
+# {{ rulegroup }} section
+{%- if options.get('enabled', false) -%}
+{%- for rule in options.get('rule_list', []) %}
+{{ rule }} -k {{ rulegroup }}
+{%- endfor %}
+{%- endif %}
+{%- endfor %}
+{%- endif %}
+
+# Enabled
+{%- set enabled = rules.get('options', {}).get('enabled', 0) %}
+-e {{ enabled }}
diff --git a/auditd/init.sls b/auditd/init.sls
new file mode 100644
index 0000000..5e8d37b
--- /dev/null
+++ b/auditd/init.sls
@@ -0,0 +1,10 @@
+include:
+{%- if pillar.auditd.service is defined %}
+  - auditd.service
+{% endif %}
+{%- if pillar.auditd.audisp is defined %}
+  - auditd.audisp
+{%- endif %}
+{%- if pillar.auditd.rules is defined %}
+  - auditd.rules
+{%- endif %}
diff --git a/auditd/map.jinja b/auditd/map.jinja
new file mode 100644
index 0000000..bf32308
--- /dev/null
+++ b/auditd/map.jinja
@@ -0,0 +1,25 @@
+{%- set service = salt['grains.filter_by']({
+    'Debian': {
+        'pkgs': ['auditd'],
+        'enabled': false,
+        'name': 'auditd',
+    },
+}, grain='os_family', merge=salt['pillar.get']('auditd:service')) %}
+
+{%- set audisp = salt['grains.filter_by']({
+    'Debian': {
+        'pkgs': ['audispd-plugins'],
+        'enabled': false,
+        'config_path': '/etc/audisp/plugins.d',
+    },
+}, grain='os_family', merge=salt['pillar.get']('auditd:audisp')) %}
+
+{%- set rules = salt['grains.filter_by']({
+    'default': {
+        'options': {
+            'bufsize': 8192,
+            'enabed': 0,
+        },
+        'rules': {},
+    },
+}, grain='os_family', merge=salt['pillar.get']('auditd:rules')) %}
diff --git a/auditd/rules.sls b/auditd/rules.sls
new file mode 100644
index 0000000..79202b4
--- /dev/null
+++ b/auditd/rules.sls
@@ -0,0 +1,26 @@
+{%- from "auditd/map.jinja" import rules with context %}
+
+include:
+  - auditd.service
+
+/etc/audit/audit.rules:
+  file.managed:
+    - source: salt://auditd/files/auditd.rules.conf
+    - template: jinja
+    - user: root
+    - group: root
+    - mode: 0640
+    - require:
+      - pkg: auditd_packages
+    - watch_in:
+      - service: auditd_service
+
+{%- if grains.get('virtual_subtype', None) not in ['Docker', 'LXC'] %}
+reload_rules:
+  cmd.run:
+    - name: /sbin/auditctl -R /etc/audit/audit.rules
+    - onchanges:
+      - file: /etc/audit/audit.rules
+    - require:
+      - service: auditd_service
+{%- endif %}
diff --git a/auditd/service.sls b/auditd/service.sls
new file mode 100644
index 0000000..f568d4e
--- /dev/null
+++ b/auditd/service.sls
@@ -0,0 +1,28 @@
+{%- from "auditd/map.jinja" import service with context %}
+
+{%- if service.get('enabled', false) %}
+auditd_packages:
+  pkg.installed:
+    - names: {{ service.pkgs }}
+
+auditd_service:
+  service.running:
+    - enable: true
+    - running: true
+    - name: {{ service.name }}
+    - require:
+      - pkg: auditd_packages
+
+/etc/audit/auditd.conf:
+  file.managed:
+    - source: salt://auditd/files/auditd.conf
+    - template: jinja
+    - user: root
+    - group: root
+    - mode: 0640
+    - require:
+      - pkg: auditd_packages
+    - watch_in:
+      - service: auditd_service
+
+{%- endif %}
diff --git a/debian/changelog b/debian/changelog
new file mode 100644
index 0000000..cc1d8ba
--- /dev/null
+++ b/debian/changelog
@@ -0,0 +1,6 @@
+salt-formula-auditd (0.1) xenial; urgency=low
+
+  * Initial release
+
+ -- Ivan Suzdal <mos-linux@mirantis.com>  Mon, 05 Feb 2018 18:00:17 +0300
+
diff --git a/debian/compat b/debian/compat
new file mode 100644
index 0000000..ec63514
--- /dev/null
+++ b/debian/compat
@@ -0,0 +1 @@
+9
diff --git a/debian/control b/debian/control
new file mode 100644
index 0000000..28416e2
--- /dev/null
+++ b/debian/control
@@ -0,0 +1,15 @@
+Source: salt-formula-auditd
+Maintainer: MOS Linux Team <mos-linux@mirantis.com>
+Section: admin
+Priority: optional
+Build-Depends: debhelper (>= 9), python, python-yaml
+Standards-Version: 3.9.6
+Homepage: https://github.com/salt-formulas/salt-formula-auditd
+Vcs-Browser: https://github.com/salt-formulas/salt-formula-auditd
+Vcs-Git: https://github.com/salt-formulas/salt-formula-auditd.git
+
+Package: salt-formula-auditd
+Architecture: all
+Depends: ${misc:Depends}
+Description: auditd salt formula
+ Install and configure auditd.
diff --git a/debian/copyright b/debian/copyright
new file mode 100644
index 0000000..7ea3bea
--- /dev/null
+++ b/debian/copyright
@@ -0,0 +1,28 @@
+Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
+Upstream-Name: salt-formula-auditd
+Source: https://github.com/salt-formulas/salt-formula-auditd
+
+Files: debian/*
+Copyright:  2017, MOS Linux Team <mos-linux@mirantis.com>
+License: Apache-2
+
+Files: *
+Copyright: Ivan Suzdal <isuzdal@mirantis.com>
+  MOS Linux Team <mos-linux@mirantis.com>
+License: Apache-2
+
+License: Apache-2
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+ .
+    http://www.apache.org/licenses/LICENSE-2.0
+ .
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ .
+ On Debian-based systems the full text of the Apache version 2.0 license
+ can be found in `/usr/share/common-licenses/Apache-2.0'.
diff --git a/debian/docs b/debian/docs
new file mode 100644
index 0000000..d585829
--- /dev/null
+++ b/debian/docs
@@ -0,0 +1,3 @@
+README.rst
+CHANGELOG.rst
+VERSION
diff --git a/debian/rules b/debian/rules
new file mode 100644
index 0000000..2d33f6a
--- /dev/null
+++ b/debian/rules
@@ -0,0 +1,4 @@
+#!/usr/bin/make -f
+
+%:
+	dh $@
diff --git a/debian/source/format b/debian/source/format
new file mode 100644
index 0000000..89ae9db
--- /dev/null
+++ b/debian/source/format
@@ -0,0 +1 @@
+3.0 (native)
diff --git a/doc/source/conf.py b/doc/source/conf.py
new file mode 100644
index 0000000..82a1d0d
--- /dev/null
+++ b/doc/source/conf.py
@@ -0,0 +1,73 @@
+# -*- coding: utf-8 -*-
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import sys
+
+sys.path.insert(0, os.path.abspath('../..'))
+# -- General configuration ----------------------------------------------------
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = [
+    'sphinx.ext.autodoc',
+]
+
+# autodoc generation is a bit aggressive and a nuisance when doing heavy
+# text edit cycles.
+# execute "export SPHINX_DEBUG=1" in your terminal to disable
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = u'salt-formula-auditd'
+copyright = u'2016, Mirantis Inc.'
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+add_module_names = True
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+# -- Options for HTML output --------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages.  Major themes that come with
+# Sphinx are currently 'default' and 'sphinxdoc'.
+# html_theme_path = ["."]
+# html_theme = '_theme'
+# html_static_path = ['static']
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = '%sdoc' % project
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, documentclass
+# [howto/manual]).
+latex_documents = [
+    ('index',
+     '%s.tex' % project,
+     u'%s Documentation' % project,
+     u'OpenStack Foundation', 'manual'),
+]
+
+# Example configuration for intersphinx: refer to the Python standard library.
+# intersphinx_mapping = {'http://docs.python.org/': None}
diff --git a/doc/source/index.rst b/doc/source/index.rst
new file mode 100644
index 0000000..a6210d3
--- /dev/null
+++ b/doc/source/index.rst
@@ -0,0 +1 @@
+.. include:: ../../README.rst
diff --git a/metadata.yml b/metadata.yml
new file mode 100644
index 0000000..a250c76
--- /dev/null
+++ b/metadata.yml
@@ -0,0 +1,3 @@
+name: auditd
+version: "0.1"
+source: https://github.com/salt-formulas/salt-formula-auditd.git
diff --git a/metadata/service/audisp/init.yml b/metadata/service/audisp/init.yml
new file mode 100644
index 0000000..432e5dc
--- /dev/null
+++ b/metadata/service/audisp/init.yml
@@ -0,0 +1,15 @@
+applications:
+- auditd
+classes:
+- service.auditd.support
+parameters:
+  auditd:
+    audisp:
+      plugins:
+        syslog:
+          active: 'yes'
+          direction: out
+          path: builtin_syslog
+          type: builtin
+          args: LOG_INFO
+          format: string
diff --git a/metadata/service/rules/ciscat.yml b/metadata/service/rules/ciscat.yml
new file mode 100644
index 0000000..8482c09
--- /dev/null
+++ b/metadata/service/rules/ciscat.yml
@@ -0,0 +1,115 @@
+applications:
+- auditd
+classes:
+- service.auditd.support
+parameters:
+  auditd:
+    rules:
+      options:
+        enabled: 1
+        bufsize: 8192
+      rules:
+        MAC_policy:
+          enabled: true
+          rule_list:
+            - '-w /etc/apparmor/ -p wa'
+            - '-w /etc/apparmor.d/ -p wa'
+        access:
+          enabled: true
+          rule_list:
+            - '-a always,exit -F arch=b64 -S creat -S open -S openat -S truncate -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F arch=b32 -S creat -S open -S openat -S truncate -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F arch=b64 -S creat -S open -S openat -S truncate -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F arch=b32 -S creat -S open -S openat -S truncate -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=4294967295'
+        actions:
+          enabled: true
+          rule_list:
+            - '-w /var/log/sudo.log -p wa'
+        delete:
+          enabled: true
+          rule_list:
+            - '-a always,exit -F arch=b64 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F arch=b32 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -F auid!=4294967295'
+        identity:
+          enabled: true
+          rule_list:
+            - '-w /etc/group -p wa'
+            - '-w /etc/passwd -p wa'
+            - '-w /etc/gshadow -p wa'
+            - '-w /etc/shadow -p wa'
+            - '-w /etc/security/opasswd -p wa'
+        logins:
+          enabled: true
+          rule_list:
+            - '-w /var/log/faillog -p wa'
+            - '-w /var/log/lastlog -p wa'
+            - '-w /var/log/tallylog -p wa'
+        modules:
+          enabled: true
+          rule_list:
+            - '-w /sbin/insmod -p x'
+            - '-w /sbin/rmmod -p x'
+            - '-w /sbin/modprobe -p x'
+            - '-a always,exit -F arch=b64 -S init_module -S delete_module'
+        mounts:
+          enabled: true
+          rule_list:
+            - '-a always,exit -F arch=b64 -S mount -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F arch=b32 -S mount -F auid>=1000 -F auid!=4294967295'
+        perm_mod:
+          enabled: true
+          rule_list:
+            - '-a always,exit -F arch=b64 -S chmod -S fchmod -S fchmodat -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F arch=b32 -S chmod -S fchmod -S fchmodat -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F arch=b64 -S chown -S fchown -S fchownat -S lchown -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F arch=b32 -S chown -S fchown -S fchownat -S lchown -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F arch=b64 -S setxattr -S lsetxattr -S fsetxattr -S removexattr -S lremovexattr -S fremovexattr -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F arch=b32 -S setxattr -S lsetxattr -S fsetxattr -S removexattr -S lremovexattr -S fremovexattr -F auid>=1000 -F auid!=4294967295'
+        privileged:
+          enabled: true
+          rule_list:
+            - '-a always,exit -F path=/usr/bin/chage -F perm=x -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F path=/usr/bin/chsh -F perm=x -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F path=/usr/bin/crontab -F perm=x -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F path=/usr/bin/gpasswd -F perm=x -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F path=/usr/bin/newgrp -F perm=x -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F path=/usr/sbin/pam_timestamp_check -F perm=x -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F path=/usr/bin/passwd -F perm=x -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F path=/usr/sbin/postdrop -F perm=x -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F path=/usr/sbin/postqueue -F perm=x -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F path=/usr/lib/openssh/ssh-keysign -F perm=x -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F path=/usr/bin/su -F perm=x -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F path=/usr/bin/sudo -F perm=x -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F path=/usr/bin/sudoedit -F perm=x -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F path=/usr/bin/umount -F perm=x -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F path=/usr/sbin/unix_chkpwd -F perm=x -F auid>=1000 -F auid!=4294967295'
+            - '-a always,exit -F path=/usr/sbin/userhelper -F perm=x -F auid>=1000 -F auid!=4294967295'
+        scope:
+          enabled: true
+          rule_list:
+            - '-w /etc/sudoers -p wa'
+            - '-w /etc/sudoers.d -p wa'
+        session:
+          enabled: true
+          rule_list:
+            - '-w /var/run/utmp -p wa'
+            - '-w /var/log/wtmp -p wa'
+            - '-w /var/log/btmp -p wa'
+        system_locale:
+          enabled: true
+          rule_list:
+            - '-a always,exit -F arch=b64 -S sethostname -S setdomainname'
+            - '-a always,exit -F arch=b32 -S sethostname -S setdomainname'
+            - '-w /etc/issue -p wa'
+            - '-w /etc/issue.net -p wa'
+            - '-w /etc/hosts -p wa'
+            - '-w /etc/network -p wa'
+            - '-w /etc/networks -p wa'
+        time_change:
+          enabled: true
+          rule_list:
+            - '-a always,exit -F arch=b64 -S adjtimex -S settimeofday'
+            - '-a always,exit -F arch=b32 -S adjtimex -S settimeofday -S stime'
+            - '-a always,exit -F arch=b64 -S clock_settime'
+            - '-a always,exit -F arch=b32 -S clock_settime'
+            - '-w /etc/localtime -p wa'
diff --git a/metadata/service/server/init.yml b/metadata/service/server/init.yml
new file mode 100644
index 0000000..4632e12
--- /dev/null
+++ b/metadata/service/server/init.yml
@@ -0,0 +1,32 @@
+applications:
+- auditd
+classes:
+- service.auditd.support
+parameters:
+  auditd:
+    service:
+      enabled: true
+      log_file: /var/log/audit/audit.log
+      log_format: RAW
+      log_group: root
+      priority_boost: 4
+      flush: INCREMENTAL
+      freq: 20
+      num_logs: 5
+      disp_qos: lossy
+      dispatcher: /sbin/audispd
+      name_format: NONE
+      max_log_file: 6
+      max_log_file_action: ROTATE
+      space_left: 75
+      space_left_action: SYSLOG
+      action_mail_acct: root
+      admin_space_left: 50
+      admin_space_left_action: SUSPEND
+      disk_full_action: SUSPEND
+      disk_error_action: SUSPEND
+      tcp_listen_queue: 5
+      tcp_max_per_addr: 1
+      tcp_client_max_idle: 0
+      enable_krb5: 'no'
+      krb5_principal: auditd
diff --git a/metadata/service/support.yml b/metadata/service/support.yml
new file mode 100644
index 0000000..099b032
--- /dev/null
+++ b/metadata/service/support.yml
@@ -0,0 +1,18 @@
+parameters:
+  auditd:
+    _support:
+      collectd:
+        enabled: true
+      heka:
+        enabled: true
+      sensu:
+        enabled: false
+      sphinx:
+        enabled: false
+      grafana:
+        enabled: true
+      telegraf:
+        enabled: true
+      prometheus:
+        enabled: true
+
diff --git a/tests/pillar/audisp.sls b/tests/pillar/audisp.sls
new file mode 100644
index 0000000..4706f34
--- /dev/null
+++ b/tests/pillar/audisp.sls
@@ -0,0 +1,36 @@
+auditd:
+  service:
+    enabled: true
+    log_file: /var/log/audit/audit.log
+    log_format: RAW
+    log_group: root
+    priority_boost: 4
+    flush: INCREMENTAL
+    freq: 20
+    num_logs: 5
+    disp_qos: lossy
+    dispatcher: /sbin/audispd
+    name_format: NONE
+    max_log_file: 6
+    max_log_file_action: ROTATE
+    space_left: 75
+    space_left_action: SYSLOG
+    action_mail_acct: root
+    admin_space_left: 50
+    admin_space_left_action: SUSPEND
+    disk_full_action: SUSPEND
+    disk_error_action: SUSPEND
+    tcp_listen_queue: 5
+    tcp_max_per_addr: 1
+    tcp_client_max_idle: 0
+    enable_krb5: no
+  audisp:
+    enabled: true
+    plugins:
+      syslog:
+        active: 'yes'
+        direction: out
+        path: builtin_syslog
+        type: builtin
+        args: LOG_INFO
+        format: string
diff --git a/tests/pillar/rules.sls b/tests/pillar/rules.sls
new file mode 100644
index 0000000..2e4bb0d
--- /dev/null
+++ b/tests/pillar/rules.sls
@@ -0,0 +1,35 @@
+auditd:
+  service:
+    enabled: true
+    log_file: /var/log/audit/audit.log
+    log_format: RAW
+    log_group: root
+    priority_boost: 4
+    flush: INCREMENTAL
+    freq: 20
+    num_logs: 5
+    disp_qos: lossy
+    dispatcher: /sbin/audispd
+    name_format: NONE
+    max_log_file: 6
+    max_log_file_action: ROTATE
+    space_left: 75
+    space_left_action: SYSLOG
+    action_mail_acct: root
+    admin_space_left: 50
+    admin_space_left_action: SUSPEND
+    disk_full_action: SUSPEND
+    disk_error_action: SUSPEND
+    tcp_listen_queue: 5
+    tcp_max_per_addr: 1
+    tcp_client_max_idle: 0
+    enable_krb5: no
+  rules:
+    options:
+      enabled: 0
+      bufzise: 4096
+    rules:
+      host_conf:
+        enabled: true
+        rule_list:
+          - '-w /etc/host.conf -p wa'
diff --git a/tests/pillar/server.sls b/tests/pillar/server.sls
new file mode 100644
index 0000000..119811e
--- /dev/null
+++ b/tests/pillar/server.sls
@@ -0,0 +1,27 @@
+auditd:
+  service:
+    enabled: true
+    log_file: /var/log/audit/audit.log
+    log_format: RAW
+    log_group: root
+    priority_boost: 4
+    flush: INCREMENTAL
+    freq: 20
+    num_logs: 5
+    disp_qos: lossy
+    dispatcher: /sbin/audispd
+    name_format: NONE
+    max_log_file: 6
+    max_log_file_action: ROTATE
+    space_left: 75
+    space_left_action: SYSLOG
+    action_mail_acct: root
+    admin_space_left: 50
+    admin_space_left_action: SUSPEND
+    disk_full_action: SUSPEND
+    disk_error_action: SUSPEND
+    tcp_listen_queue: 5
+    tcp_max_per_addr: 1
+    tcp_client_max_idle: 0
+    enable_krb5: no
+    krb5_principal: auditd
diff --git a/tests/run_tests.sh b/tests/run_tests.sh
new file mode 100755
index 0000000..29fb975
--- /dev/null
+++ b/tests/run_tests.sh
@@ -0,0 +1,200 @@
+#!/usr/bin/env bash
+
+set -e
+[ -n "$DEBUG" ] && set -x
+
+CURDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+METADATA=${CURDIR}/../metadata.yml
+FORMULA_NAME=$(cat $METADATA | python -c "import sys,yaml; print yaml.load(sys.stdin)['name']")
+FORMULA_META_DIR=${CURDIR}/../${FORMULA_NAME}/meta
+
+## Overrideable parameters
+PILLARDIR=${PILLARDIR:-${CURDIR}/pillar}
+BUILDDIR=${BUILDDIR:-${CURDIR}/build}
+VENV_DIR=${VENV_DIR:-${BUILDDIR}/virtualenv}
+MOCK_BIN_DIR=${MOCK_BIN_DIR:-${CURDIR}/mock_bin}
+DEPSDIR=${BUILDDIR}/deps
+
+SALT_FILE_DIR=${SALT_FILE_DIR:-${BUILDDIR}/file_root}
+SALT_PILLAR_DIR=${SALT_PILLAR_DIR:-${BUILDDIR}/pillar_root}
+SALT_CONFIG_DIR=${SALT_CONFIG_DIR:-${BUILDDIR}/salt}
+SALT_CACHE_DIR=${SALT_CACHE_DIR:-${SALT_CONFIG_DIR}/cache}
+
+SALT_OPTS="${SALT_OPTS} --retcode-passthrough --local -c ${SALT_CONFIG_DIR} --log-file=/dev/null"
+
+if [ "x${SALT_VERSION}" != "x" ]; then
+    PIP_SALT_VERSION="==${SALT_VERSION}"
+fi
+
+## Functions
+log_info() {
+    echo "[INFO] $*"
+}
+
+log_err() {
+    echo "[ERROR] $*" >&2
+}
+
+setup_virtualenv() {
+    log_info "Setting up Python virtualenv"
+    virtualenv $VENV_DIR
+    source ${VENV_DIR}/bin/activate
+    pip install salt${PIP_SALT_VERSION}
+}
+
+setup_mock_bin() {
+    # If some state requires a binary, a lightweight replacement for
+    # such binary can be put into MOCK_BIN_DIR for test purposes
+    if [ -d "${MOCK_BIN_DIR}" ]; then
+        PATH="${MOCK_BIN_DIR}:$PATH"
+        export PATH
+    fi
+}
+
+setup_pillar() {
+    [ ! -d ${SALT_PILLAR_DIR} ] && mkdir -p ${SALT_PILLAR_DIR}
+    echo "base:" > ${SALT_PILLAR_DIR}/top.sls
+    for pillar in ${PILLARDIR}/*; do
+        grep ${FORMULA_NAME}: ${pillar} &>/dev/null || continue
+        state_name=$(basename ${pillar%.sls})
+        echo -e "  ${state_name}:\n    - ${state_name}" >> ${SALT_PILLAR_DIR}/top.sls
+    done
+}
+
+setup_salt() {
+    [ ! -d ${SALT_FILE_DIR} ] && mkdir -p ${SALT_FILE_DIR}
+    [ ! -d ${SALT_CONFIG_DIR} ] && mkdir -p ${SALT_CONFIG_DIR}
+    [ ! -d ${SALT_CACHE_DIR} ] && mkdir -p ${SALT_CACHE_DIR}
+
+    echo "base:" > ${SALT_FILE_DIR}/top.sls
+    for pillar in ${PILLARDIR}/*.sls; do
+        grep ${FORMULA_NAME}: ${pillar} &>/dev/null || continue
+        state_name=$(basename ${pillar%.sls})
+        echo -e "  ${state_name}:\n    - ${FORMULA_NAME}" >> ${SALT_FILE_DIR}/top.sls
+    done
+
+    cat << EOF > ${SALT_CONFIG_DIR}/minion
+file_client: local
+cachedir: ${SALT_CACHE_DIR}
+verify_env: False
+minion_id_caching: False
+
+file_roots:
+  base:
+  - ${SALT_FILE_DIR}
+  - ${CURDIR}/..
+  - /usr/share/salt-formulas/env
+
+pillar_roots:
+  base:
+  - ${SALT_PILLAR_DIR}
+  - ${PILLARDIR}
+EOF
+}
+
+fetch_dependency() {
+    dep_name="$(echo $1|cut -d : -f 1)"
+    dep_source="$(echo $1|cut -d : -f 2-)"
+    dep_root="${DEPSDIR}/$(basename $dep_source .git)"
+    dep_metadata="${dep_root}/metadata.yml"
+
+    [ -d /usr/share/salt-formulas/env/${dep_name} ] && log_info "Dependency $dep_name already present in system-wide salt env" && return 0
+    [ -d $dep_root ] && log_info "Dependency $dep_name already fetched" && return 0
+
+    log_info "Fetching dependency $dep_name"
+    [ ! -d ${DEPSDIR} ] && mkdir -p ${DEPSDIR}
+    git clone $dep_source ${DEPSDIR}/$(basename $dep_source .git)
+    ln -s ${dep_root}/${dep_name} ${SALT_FILE_DIR}/${dep_name}
+
+    METADATA="${dep_metadata}" install_dependencies
+}
+
+install_dependencies() {
+    grep -E "^dependencies:" ${METADATA} >/dev/null || return 0
+    (python - | while read dep; do fetch_dependency "$dep"; done) << EOF
+import sys,yaml
+for dep in yaml.load(open('${METADATA}', 'ro'))['dependencies']:
+    print '%s:%s' % (dep["name"], dep["source"])
+EOF
+}
+
+clean() {
+    log_info "Cleaning up ${BUILDDIR}"
+    [ -d ${BUILDDIR} ] && rm -rf ${BUILDDIR} || exit 0
+}
+
+salt_run() {
+    [ -e ${VEN_DIR}/bin/activate ] && source ${VENV_DIR}/bin/activate
+    salt-call ${SALT_OPTS} $*
+}
+
+prepare() {
+    [ -d ${BUILDDIR} ] && mkdir -p ${BUILDDIR}
+
+    which salt-call || setup_virtualenv
+    setup_mock_bin
+    setup_pillar
+    setup_salt
+    install_dependencies
+}
+
+run() {
+    for pillar in ${PILLARDIR}/*.sls; do
+        grep ${FORMULA_NAME}: ${pillar} &>/dev/null || continue
+        state_name=$(basename ${pillar%.sls})
+        salt_run grains.set 'noservices' False force=True
+
+        echo "Checking state ${FORMULA_NAME}.${state_name} ..."
+        salt_run --id=${state_name} state.show_sls ${FORMULA_NAME} || (log_err "Execution of ${FORMULA_NAME}.${state_name} failed"; exit 1)
+
+        # Check that all files in 'meta' folder can be rendered using any valid pillar
+        for meta in `find ${FORMULA_META_DIR} -type f`; do
+            meta_name=$(basename ${meta})
+            echo "Checking meta ${meta_name} ..."
+            salt_run --out=quiet --id=${state_name} cp.get_template ${meta} ${SALT_CACHE_DIR}/${meta_name} \
+              || (log_err "Failed to render meta ${meta} using pillar ${FORMULA_NAME}.${state_name}"; exit 1)
+            cat ${SALT_CACHE_DIR}/${meta_name}
+        done
+    done
+}
+
+real_run() {
+    for pillar in ${PILLARDIR}/*.sls; do
+        state_name=$(basename ${pillar%.sls})
+        salt_run --id=${state_name} state.sls ${FORMULA_NAME} || (log_err "Execution of ${FORMULA_NAME}.${state_name} failed"; exit 1)
+    done
+}
+
+_atexit() {
+    RETVAL=$?
+    trap true INT TERM EXIT
+
+    if [ $RETVAL -ne 0 ]; then
+        log_err "Execution failed"
+    else
+        log_info "Execution successful"
+    fi
+    return $RETVAL
+}
+
+## Main
+trap _atexit INT TERM EXIT
+
+case $1 in
+    clean)
+        clean
+        ;;
+    prepare)
+        prepare
+        ;;
+    run)
+        run
+        ;;
+    real-run)
+        real_run
+        ;;
+    *)
+        prepare
+        run
+        ;;
+esac
diff --git a/tests/test-requirements.txt b/tests/test-requirements.txt
new file mode 100644
index 0000000..a0f561a
--- /dev/null
+++ b/tests/test-requirements.txt
@@ -0,0 +1,2 @@
+jsonschema
+reno