├── .github └── workflows │ └── main.yml ├── .gitignore ├── .gitmodules ├── .make-release-support ├── .release ├── .vscode ├── launch.json └── settings.json ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── container ├── build.sh ├── environment │ └── default.yaml ├── service │ ├── gunicorn │ │ ├── install.sh │ │ ├── process.sh │ │ └── startup.sh │ ├── nginx │ │ ├── assets │ │ │ ├── certs │ │ │ │ ├── ca.crt │ │ │ │ └── dhparam.pem │ │ │ ├── etc │ │ │ │ └── conf.d │ │ │ │ │ └── default.conf │ │ │ └── scripts │ │ │ │ ├── auth.sh.txt │ │ │ │ └── authprinc.sh.txt │ │ ├── install.sh │ │ ├── process.sh │ │ └── startup.sh │ └── slapd │ │ ├── assets │ │ ├── ldif │ │ │ ├── auditlog.ldif │ │ │ └── ppolicy.ldif │ │ ├── schema │ │ │ ├── memberof.ldif │ │ │ ├── openssh-lpk.ldif │ │ │ └── sudo.ldif │ │ └── templates │ │ │ ├── config.ldif.tmpl │ │ │ └── data.ldif.tmpl │ │ ├── install.sh │ │ ├── process.sh │ │ └── startup.sh └── tools │ ├── add-multiple-process-stack │ ├── add-service-available │ ├── complex-bash-env │ ├── install-service │ ├── log-helper │ ├── run │ ├── setuser │ └── wait-process ├── contrib └── kp1-detach.sh └── modules └── build_builder.sh /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | # This is a basic workflow to help you get started with Actions 2 | 3 | name: CI 4 | 5 | # Controls when the action will run. Triggers the workflow on push or pull request 6 | # events but only for the master branch 7 | on: 8 | push: 9 | branches: [ master ] 10 | pull_request: 11 | branches: [ master ] 12 | 13 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 14 | jobs: 15 | # This workflow contains a single job called "build" 16 | build: 17 | # The type of runner that the job will run on 18 | runs-on: ubuntu-latest 19 | 20 | # Steps represent a sequence of tasks that will be executed as part of the job 21 | steps: 22 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it 23 | - 24 | name: Checkout 25 | uses: actions/checkout@v2 26 | with: 27 | submodules: recursive 28 | token: ${{ secrets.DBS_ACCESS_TOKEN }} 29 | - 30 | name: Set up QEMU 31 | uses: docker/setup-qemu-action@v1 32 | with: 33 | platforms: all 34 | - 35 | name: Set up Docker Buildx 36 | id: buildx 37 | uses: docker/setup-buildx-action@v1 38 | with: 39 | version: latest 40 | - 41 | name: Available platforms 42 | run: echo ${{ steps.buildx.outputs.platforms }} 43 | - 44 | name: Login to DockerHub 45 | uses: docker/login-action@v1 46 | with: 47 | username: ${{ secrets.DOCKERHUB_USERNAME }} 48 | password: ${{ secrets.DOCKERHUB_TOKEN }} 49 | - 50 | name: Login to Quay 51 | uses: docker/login-action@v1 52 | with: 53 | registry: quay.io 54 | username: ${{ secrets.QUAY_USERNAME }} 55 | password: ${{ secrets.QUAY_TOKEN }} 56 | - 57 | name: Get release env 58 | id: vars 59 | run: | 60 | rel=$(cat .release | awk -F= '/^release=/{print $2}') 61 | echo "::set-output name=tag::$rel" 62 | echo "$rel" 63 | - 64 | name: Build and push 65 | uses: docker/build-push-action@v2 66 | with: 67 | context: . 68 | file: ./Dockerfile 69 | platforms: linux/386,linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x 70 | push: true 71 | tags: | 72 | dbsentry/keyper:latest 73 | dbsentry/keyper:${{ steps.vars.outputs.tag }} 74 | quay.io/dbsentry/keyper:latest 75 | quay.io/dbsentry/keyper:${{ steps.vars.outputs.tag }} 76 | 77 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 98 | __pypackages__/ 99 | 100 | # Celery stuff 101 | celerybeat-schedule 102 | celerybeat.pid 103 | 104 | # SageMath parsed files 105 | *.sage.py 106 | 107 | # Environments 108 | .env 109 | .venv 110 | env/ 111 | venv/ 112 | ENV/ 113 | env.bak/ 114 | venv.bak/ 115 | 116 | # Spyder project settings 117 | .spyderproject 118 | .spyproject 119 | 120 | # Rope project settings 121 | .ropeproject 122 | 123 | # mkdocs documentation 124 | /site 125 | 126 | # mypy 127 | .mypy_cache/ 128 | .dmypy.json 129 | dmypy.json 130 | 131 | # Pyre type checker 132 | .pyre/ 133 | 134 | # pytype static type analyzer 135 | .pytype/ 136 | 137 | # Cython debug symbols 138 | cython_debug/ -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "modules/keyper-fe"] 2 | path = modules/keyper-fe 3 | url = https://github.com/dbsentry/keyper-fe.git 4 | [submodule "modules/keyper"] 5 | path = modules/keyper 6 | url = https://github.com/dbsentry/keyper.git 7 | -------------------------------------------------------------------------------- /.make-release-support: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright 2015 Xebia Nederland B.V. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | function hasChanges() { 18 | test -n "$(git status -s .)" 19 | } 20 | 21 | function getRelease() { 22 | awk -F= '/^release=/{print $2}' .release 23 | } 24 | 25 | function getBaseTag() { 26 | sed -n -e "s/^tag=\(.*\)$(getRelease)\$/\1/p" .release 27 | } 28 | 29 | function getTag() { 30 | if [ -z "$1" ] ; then 31 | awk -F= '/^tag/{print $2}' .release 32 | else 33 | echo "$(getBaseTag)$1" 34 | fi 35 | } 36 | 37 | function setRelease() { 38 | if [ -n "$1" ] ; then 39 | sed -i.x -e "s~^tag=.*~tag=$(getTag $1)~" .release 40 | sed -i.x -e "s~^release=.*~release=$1~g" .release 41 | rm -f .release.x 42 | runPreTagCommand "$1" 43 | else 44 | echo "ERROR: missing release version parameter " >&2 45 | return 1 46 | fi 47 | } 48 | 49 | function runPreTagCommand() { 50 | if [ -n "$1" ] ; then 51 | COMMAND=$(sed -n -e "s/@@RELEASE@@/$1/g" -e 's/^pre_tag_command=\(.*\)/\1/p' .release) 52 | if [ -n "$COMMAND" ] ; then 53 | if ! OUTPUT=$(bash -c "$COMMAND" 2>&1) ; then echo $OUTPUT >&2 && exit 1 ; fi 54 | fi 55 | else 56 | echo "ERROR: missing release version parameter " >&2 57 | return 1 58 | fi 59 | } 60 | 61 | function tagExists() { 62 | tag=${1:-$(getTag)} 63 | test -n "$tag" && test -n "$(git tag | grep "^$tag\$")" 64 | } 65 | 66 | function differsFromRelease() { 67 | tag=$(getTag) 68 | ! tagExists $tag || test -n "$(git diff --shortstat -r $tag .)" 69 | } 70 | 71 | function getVersion() { 72 | result=$(getRelease) 73 | 74 | # if differsFromRelease; then 75 | # result="$result-$(git log -n 1 --format=%h .)" 76 | # fi 77 | # 78 | # if hasChanges ; then 79 | # result="$result-dirty" 80 | # fi 81 | echo $result 82 | } 83 | 84 | function nextPatchLevel() { 85 | version=${1:-$(getRelease)} 86 | major_and_minor=$(echo $version | cut -d. -f1,2) 87 | patch=$(echo $version | cut -d. -f3) 88 | version=$(printf "%s.%d" $major_and_minor $(($patch + 1))) 89 | echo $version 90 | } 91 | 92 | function nextMinorLevel() { 93 | version=${1:-$(getRelease)} 94 | major=$(echo $version | cut -d. -f1); 95 | minor=$(echo $version | cut -d. -f2); 96 | version=$(printf "%d.%d.0" $major $(($minor + 1))) ; 97 | echo $version 98 | } 99 | 100 | function nextMajorLevel() { 101 | version=${1:-$(getRelease)} 102 | major=$(echo $version | cut -d. -f1); 103 | version=$(printf "%d.0.0" $(($major + 1))) 104 | echo $version 105 | } 106 | 107 | function getImageId() { 108 | echo "$(docker images $1 --format '{{.ID}}')" 109 | } 110 | -------------------------------------------------------------------------------- /.release: -------------------------------------------------------------------------------- 1 | release=0.3.2 2 | tag=0.3.2 -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | 8 | 9 | { 10 | "name": "Python: Flask", 11 | "type": "python", 12 | "request": "launch", 13 | "module": "flask", 14 | "env": { 15 | "FLASK_APP": "app.py", 16 | "FLASK_ENV": "development", 17 | "FLASK_DEBUG": "0" 18 | }, 19 | "args": [ 20 | "run", 21 | "--no-debugger", 22 | "--no-reload" 23 | ], 24 | "jinja": true 25 | } 26 | ] 27 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.pythonPath": "/Users/manish/python_projects/keyper/env/bin/python3.7" 3 | } -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:latest AS builder 2 | RUN apk add --no-cache python3 \ 3 | py3-yaml \ 4 | python3-dev \ 5 | bash \ 6 | gcc \ 7 | musl-dev \ 8 | npm \ 9 | openssl \ 10 | nginx \ 11 | openldap \ 12 | openldap-dev \ 13 | openldap-clients \ 14 | openldap-back-mdb \ 15 | openldap-overlay-memberof \ 16 | openldap-overlay-ppolicy \ 17 | openldap-overlay-refint \ 18 | openldap-overlay-auditlog \ 19 | openldap-back-monitor 20 | COPY modules /container 21 | RUN /container/build_builder.sh 22 | 23 | FROM alpine:latest 24 | RUN apk add --no-cache python3 \ 25 | py3-yaml \ 26 | runit \ 27 | bash \ 28 | shadow \ 29 | openssl \ 30 | nginx \ 31 | openssh-keygen \ 32 | openldap \ 33 | openldap-clients \ 34 | openldap-back-mdb \ 35 | openldap-overlay-memberof \ 36 | openldap-overlay-ppolicy \ 37 | openldap-overlay-refint \ 38 | openldap-overlay-auditlog \ 39 | openldap-back-monitor 40 | COPY container /container 41 | COPY --from=builder /container/out.tar.gz /container/out.tar.gz 42 | RUN /container/build.sh 43 | ENTRYPOINT ["/container/tools/run"] 44 | EXPOSE 80 443 389 636 45 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright 2015 Xebia Nederland B.V. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | REGISTRY_HOST=docker.io 17 | REGISTRY_HOST_QUAY=quay.io 18 | #USERNAME=$(USER) 19 | #NAME=$(shell basename $(CURDIR)) 20 | USERNAME=dbsentry 21 | NAME=keyper 22 | 23 | RELEASE_SUPPORT := $(shell dirname $(abspath $(lastword $(MAKEFILE_LIST))))/.make-release-support 24 | IMAGE=$(REGISTRY_HOST)/$(USERNAME)/$(NAME) 25 | IMAGE_QUAY=$(REGISTRY_HOST_QUAY)/$(USERNAME)/$(NAME) 26 | 27 | VERSION=$(shell . $(RELEASE_SUPPORT) ; getVersion) 28 | TAG=$(shell . $(RELEASE_SUPPORT); getTag) 29 | 30 | SHELL=/bin/bash 31 | 32 | DOCKER_BUILD_CONTEXT=. 33 | DOCKER_FILE_PATH=Dockerfile 34 | DOCKER_BUILD_ARGS=--squash 35 | 36 | .PHONY: pre-build docker-build post-build build release patch-release minor-release major-release tag check-status check-release showver \ 37 | push pre-push do-push post-push 38 | 39 | build: pre-build docker-build post-build 40 | 41 | build-quay: docker-build-quay 42 | 43 | pre-build: 44 | 45 | 46 | post-build: 47 | 48 | 49 | pre-push: 50 | 51 | 52 | post-push: 53 | 54 | pre-push-quay: 55 | 56 | 57 | post-push-quay: 58 | 59 | 60 | docker-build: .release 61 | docker build $(DOCKER_BUILD_ARGS) -t $(IMAGE):$(VERSION) $(DOCKER_BUILD_CONTEXT) -f $(DOCKER_FILE_PATH) 62 | @DOCKER_MAJOR=$(shell docker -v | sed -e 's/.*version //' -e 's/,.*//' | cut -d\. -f1) ; \ 63 | DOCKER_MINOR=$(shell docker -v | sed -e 's/.*version //' -e 's/,.*//' | cut -d\. -f2) ; \ 64 | if [ $$DOCKER_MAJOR -eq 1 ] && [ $$DOCKER_MINOR -lt 10 ] ; then \ 65 | echo docker tag -f $(IMAGE):$(VERSION) $(IMAGE):latest ;\ 66 | docker tag -f $(IMAGE):$(VERSION) $(IMAGE):latest ;\ 67 | else \ 68 | echo docker tag $(IMAGE):$(VERSION) $(IMAGE):latest ;\ 69 | docker tag $(IMAGE):$(VERSION) $(IMAGE):latest ; \ 70 | fi 71 | 72 | docker-build-quay: 73 | IMAGEID=$(shell . $(RELEASE_SUPPORT) ; getImageId "$(USERNAME)/$(NAME):$(VERSION)") ;\ 74 | docker tag $$IMAGEID $(IMAGE_QUAY):$(VERSION) ; \ 75 | docker tag $$IMAGEID $(IMAGE_QUAY):latest ; \ 76 | 77 | .release: 78 | @echo "release=0.0.0" > .release 79 | @echo "tag=$(NAME)-0.0.0" >> .release 80 | @echo INFO: .release created 81 | @cat .release 82 | 83 | 84 | release: check-status check-release build push 85 | 86 | push: pre-push do-push post-push 87 | 88 | push-quay: pre-push-quay do-push-quay post-push-quay 89 | 90 | do-push: 91 | docker push $(IMAGE):$(VERSION) 92 | docker push $(IMAGE):latest 93 | 94 | do-push-quay: 95 | docker push $(IMAGE_QUAY):$(VERSION) 96 | docker push $(IMAGE_QUAY):latest 97 | 98 | snapshot: build push 99 | 100 | showver: .release 101 | @. $(RELEASE_SUPPORT); getVersion 102 | 103 | tag-patch-release: VERSION := $(shell . $(RELEASE_SUPPORT); nextPatchLevel) 104 | tag-patch-release: .release tag 105 | 106 | tag-minor-release: VERSION := $(shell . $(RELEASE_SUPPORT); nextMinorLevel) 107 | tag-minor-release: .release tag 108 | 109 | tag-major-release: VERSION := $(shell . $(RELEASE_SUPPORT); nextMajorLevel) 110 | tag-major-release: .release tag 111 | 112 | patch-release: tag-patch-release release 113 | @echo $(VERSION) 114 | 115 | minor-release: tag-minor-release release 116 | @echo $(VERSION) 117 | 118 | major-release: tag-major-release release 119 | @echo $(VERSION) 120 | 121 | 122 | tag: TAG=$(shell . $(RELEASE_SUPPORT); getTag $(VERSION)) 123 | tag: check-status 124 | @. $(RELEASE_SUPPORT) ; ! tagExists $(TAG) || (echo "ERROR: tag $(TAG) for version $(VERSION) already tagged in git" >&2 && exit 1) ; 125 | @. $(RELEASE_SUPPORT) ; setRelease $(VERSION) 126 | git add . 127 | git commit -m "bumped to version $(VERSION)" ; 128 | git tag $(TAG) ; 129 | @ if [ -n "$(shell git remote -v)" ] ; then git push --tags ; else echo 'no remote to push tags to' ; fi 130 | 131 | check-status: 132 | @. $(RELEASE_SUPPORT) ; ! hasChanges || (echo "ERROR: there are still outstanding changes" >&2 && exit 1) ; 133 | 134 | check-release: .release 135 | @. $(RELEASE_SUPPORT) ; tagExists $(TAG) || (echo "ERROR: version not yet tagged in git. make [minor,major,patch]-release." >&2 && exit 1) ; 136 | @. $(RELEASE_SUPPORT) ; ! differsFromRelease $(TAG) || (echo "ERROR: current directory differs from tagged $(TAG). make [minor,major,patch]-release." ; exit 1) 137 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Docker Image Version (latest by date)](https://img.shields.io/docker/v/dbsentry/keyper) 2 | ![GitHub Workflow Status](https://img.shields.io/github/workflow/status/dbsentry/keyper-docker/CI) 3 | ![Docker Image Size (latest by date)](https://img.shields.io/docker/image-size/dbsentry/keyper) 4 | ![GitHub issues](https://img.shields.io/github/issues/mlgupta/keyper-docker) 5 | ![GitHub last commit](https://img.shields.io/github/last-commit/mlgupta/keyper-docker) 6 | ![GitHub](https://img.shields.io/github/license/mlgupta/keyper-docker) 7 | ![Docker Pulls](https://img.shields.io/docker/pulls/dbsentry/keyper) 8 | ![Keyper Architecture](https://keyper.dbsentry.com/media/keyper.png) 9 | 10 | Keyper is an SSH Key/Certificate Authentication Manager. It standardizes and centralizes the storage of SSH public keys and SSH Public Certificates for all Linux users within your organization saving significant time and effort it takes to manage SSH public keys and certificates. Keyper is a lightweight container taking less than 100MB. It is launched either using Docker or Podman. You can be up and running within minutes instead of days. 11 | 12 | Features include: 13 | - Public key storage 14 | - SSH CA 15 | - Certificate signing and storage 16 | - Public Key/Certificate Expiration 17 | - Forced Key rotation 18 | - Key Revocation List (KRL) 19 | - Streamlined provision or de-provisioning of users 20 | - Segmentation of Servers using groups 21 | - Policy definition to restrict user's access to server(s) 22 | - Centralized user account lockout 23 | - Docker container 24 | 25 | ## Installation/Build 26 | Follow the steps to build docker image using source code: 27 | 1. Clone this git repository 28 | ```console 29 | $ git clone https://github.com/dbsentry/keyper-docker.git 30 | ``` 31 | 2. Download keyper REST API submodule 32 | ```console 33 | $ cd keyper-docker 34 | $ git submodule init 35 | $ git submodule update modules/keyper 36 | $ git submodule update modules/keyper-fe 37 | ``` 38 | 3. By default Makefile creates image as dbsentry/keyper. To change, modify Makefile 39 | 4. Change .release to reflect correct tag on docker image 40 | 5. Run build 41 | ```console 42 | $ make build 43 | ``` 44 | The generated image when run would start a docker container with openldap and Keyper REST-API service. 45 | 46 | Refer to the [administration guide](https://keyper.dbsentry.com/docs/) for further information. 47 | 48 | ## Related Projects 49 | - [Keyper](https://github.com/dbsentry/keyper) 50 | - [Keyper-fe](https://github.com/dbsentry/keyper-fe) 51 | - [Keyper-docs](https://github.com/dbsentry/keyper-docs) 52 | 53 | ## License 54 | All assets and code are under the GNU GPL LICENSE and in the public domain unless specified otherwise. 55 | 56 | Some files were sourced from other open source projects and are under their terms and license. 57 | -------------------------------------------------------------------------------- /container/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -ex 2 | ############################################################################# 3 | # Confidentiality Information # 4 | # # 5 | # This module is the confidential and proprietary information of # 6 | # DBSentry Corp.; it is not to be copied, reproduced, or transmitted in any # 7 | # form, by any means, in whole or in part, nor is it to be used for any # 8 | # purpose other than that for which it is expressly provided without the # 9 | # written permission of DBSentry Corp. # 10 | # # 11 | # Copyright (c) 2020-2021 DBSentry Corp. All Rights Reserved. # 12 | # # 13 | ############################################################################# 14 | ln -s /container/tools/* /sbin/ 15 | 16 | mkdir /container/run 17 | [ -d /container/environment/startup ] || mkdir /container/environment/startup 18 | [ -d /container/service/gunicorn/assets ] || mkdir /container/service/gunicorn/assets 19 | [ -d /container/service/nginx/assets/docs ] || mkdir /container/service/nginx/assets/docs 20 | [ -d /container/service/gunicorn/assets/sshca ] || mkdir /container/service/gunicorn/assets/sshca 21 | [ -d /etc/sshca ] || mkdir /etc/sshca 22 | chown -R root:root /container/environment 23 | chmod 700 /container/environment /container/environment/startup 24 | 25 | cd /container 26 | tar -xzf out.tar.gz 27 | mv keyper /container/service/gunicorn/assets 28 | mv keyper-fe /container/service/nginx/assets 29 | 30 | apk upgrade --no-cache 31 | 32 | # Remove useless files 33 | rm -rf /tmp/* /var/tmp/* /container/build.sh /container/Dockerfile 34 | rm -f /container/out.tar.gz 35 | 36 | echo "Installing Services" 37 | /container/tools/install-service 38 | 39 | -------------------------------------------------------------------------------- /container/environment/default.yaml: -------------------------------------------------------------------------------- 1 | ############################################################################# 2 | # Confidentiality Information # 3 | # # 4 | # This module is the confidential and proprietary information of # 5 | # DBSentry Corp.; it is not to be copied, reproduced, or transmitted in any # 6 | # form, by any means, in whole or in part, nor is it to be used for any # 7 | # purpose other than that for which it is expressly provided without the # 8 | # written permission of DBSentry Corp. # 9 | # # 10 | # Copyright (c) 2020-2021 DBSentry Corp. All Rights Reserved. # 11 | # # 12 | ############################################################################# 13 | # All environment variables used after the container first start must be 14 | # defined here. 15 | ############################################################################# 16 | # 17 | LDAP_LOG_LEVEL: 256 18 | 19 | # Ulimit 20 | LDAP_NOFILE: 1024 21 | 22 | # Do not perform any chown to fix file ownership 23 | DISABLE_CHOWN: false 24 | 25 | # UID/GID for LDAP User 26 | LDAP_UID: 10100 27 | LDAP_GID: 10100 28 | 29 | # UID/GID for LDAP User 30 | NGINX_UID: 10080 31 | NGINX_GID: 10080 32 | 33 | 34 | # Default port to bind slapd 35 | LDAP_PORT: 389 36 | LDAPS_PORT: 636 37 | 38 | 39 | # Required and used for new ldap server only 40 | LDAP_ORGANIZATION_NAME: Example Inc. 41 | LDAP_DOMAIN: keyper.example.org 42 | 43 | LDAP_ADMIN_PASSWORD: superdupersecret 44 | 45 | LDAP_TLS_CA_CRT_FILENAME: ca.crt 46 | LDAP_TLS_CRT_FILENAME: server.crt 47 | LDAP_TLS_KEY_FILENAME: server.key 48 | LDAP_TLS_DH_PARAM_FILENAME: dhparam.pem 49 | 50 | LDAP_TLS_ENFORCE: false 51 | LDAP_TLS_CIPHER_SUITE: TLSv1.2:HIGH:!aNULL:!eNULL 52 | LDAP_TLS_PROTOCOL_MIN: 3.3 53 | LDAP_TLS_VERIFY_CLIENT: demand 54 | 55 | FLASK_CONFIG: prod 56 | 57 | SSH_CA_DIR: /etc/sshca 58 | SSH_CA_HOST_KEY: ca_host_key 59 | SSH_CA_USER_KEY: ca_user_key 60 | SSH_CA_KEY_TYPE: rsa 61 | SSH_CA_KRL_FILE: ca_krl 62 | SSH_CA_TMP_WORK_DIR: tmp 63 | SSH_CA_TMP_DELETE_FLAG: True 64 | -------------------------------------------------------------------------------- /container/service/gunicorn/install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | ############################################################################# 3 | # Confidentiality Information # 4 | # # 5 | # This module is the confidential and proprietary information of # 6 | # DBSentry Corp.; it is not to be copied, reproduced, or transmitted in any # 7 | # form, by any means, in whole or in part, nor is it to be used for any # 8 | # purpose other than that for which it is expressly provided without the # 9 | # written permission of DBSentry Corp. # 10 | # # 11 | # Copyright (c) 2020-2021 DBSentry Corp. All Rights Reserved. # 12 | # # 13 | ############################################################################# 14 | 15 | -------------------------------------------------------------------------------- /container/service/gunicorn/process.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | ############################################################################# 3 | # Confidentiality Information # 4 | # # 5 | # This module is the confidential and proprietary information of # 6 | # DBSentry Corp.; it is not to be copied, reproduced, or transmitted in any # 7 | # form, by any means, in whole or in part, nor is it to be used for any # 8 | # purpose other than that for which it is expressly provided without the # 9 | # written permission of DBSentry Corp. # 10 | # # 11 | # Copyright (c) 2020-2021 DBSentry Corp. All Rights Reserved. # 12 | # # 13 | ############################################################################# 14 | 15 | sv check /container/run/process/slapd 16 | log-helper info "gunicorn: Starting" 17 | exec su -s /bin/sh -c "cd /var/www/keyper; . env/bin/activate; gunicorn -w 4 'app:create_app()' --bind 127.0.0.1:8000 --user=nginx --group=nginx" nginx 18 | log-helper info "gunicorn: Started" 19 | -------------------------------------------------------------------------------- /container/service/gunicorn/startup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | ############################################################################# 3 | # Confidentiality Information # 4 | # # 5 | # This module is the confidential and proprietary information of # 6 | # DBSentry Corp.; it is not to be copied, reproduced, or transmitted in any # 7 | # form, by any means, in whole or in part, nor is it to be used for any # 8 | # purpose other than that for which it is expressly provided without the # 9 | # written permission of DBSentry Corp. # 10 | # # 11 | # Copyright (c) 2020-2021 DBSentry Corp. All Rights Reserved. # 12 | # # 13 | ############################################################################# 14 | 15 | FIRST_START_DONE="${CONTAINER_STATE_DIR}/gunicorn-first-start-done" 16 | 17 | if [ ! -e "$FIRST_START_DONE" ]; then 18 | touch $FIRST_START_DONE 19 | fi 20 | 21 | log-helper info "Setting UID/GID for nginx to ${NGINX_UID}/${NGINX_GID}" 22 | [ "$(id -g nginx)" -eq ${NGINX_GID} ] || groupmod -g ${NGINX_GID} nginx 23 | [ "$(id -u nginx)" -eq ${NGINX_UID} ] || usermod -u ${NGINX_UID} -g ${NGINX_GID} nginx 24 | 25 | cd /container/service/gunicorn/assets 26 | [ -d keyper ] && mv keyper /var/www 27 | cd /var/www 28 | 29 | [ -d ${SSH_CA_DIR} ] || mkdir ${SSH_CA_DIR} 30 | 31 | if [ "$(ls -A /container/service/gunicorn/assets/sshca | grep -v lost+found)" ]; then 32 | cp /container/service/gunicorn/assets/sshca/* ${SSH_CA_DIR} 33 | fi 34 | [ -d ${SSH_CA_DIR}/${SSH_CA_TMP_WORK_DIR} ] || mkdir ${SSH_CA_DIR}/${SSH_CA_TMP_WORK_DIR} 35 | 36 | [ -z ${SSH_CA_KEY_TYPE} ] && SSH_CA_KEY_TYPE=rsa 37 | log-helper info "CA KEY Type: ${SSH_CA_KEY_TYPE}." 38 | 39 | if [ ! -e "$SSH_CA_DIR/$SSH_CA_HOST_KEY" ]; then 40 | log-helper info "CA Host Key does not exist. Generating one ..." 41 | ssh-keygen -t ${SSH_CA_KEY_TYPE} -q -N "" -f ${SSH_CA_DIR}/${SSH_CA_HOST_KEY} 42 | fi 43 | 44 | if [ ! -e "$SSH_CA_DIR/$SSH_CA_USER_KEY" ]; then 45 | log-helper info "CA User Key does not exist. Generating one ..." 46 | ssh-keygen -t ${SSH_CA_KEY_TYPE} -q -N "" -f ${SSH_CA_DIR}/${SSH_CA_USER_KEY} 47 | fi 48 | 49 | if [ ! -e "$SSH_CA_DIR/$SSH_CA_KRL_FILE" ]; then 50 | log-helper info "CA KRL does not exist. Generating one ..." 51 | ssh-keygen -k -f ${SSH_CA_DIR}/${SSH_CA_KRL_FILE} 52 | fi 53 | 54 | [ -d /var/log/keyper ] || mkdir /var/log/keyper 55 | chown -R nginx:nginx /var/log/keyper /var/www/keyper ${SSH_CA_DIR} 56 | 57 | exit 0 58 | -------------------------------------------------------------------------------- /container/service/nginx/assets/certs/dhparam.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN DH PARAMETERS----- 2 | MIIBCAKCAQEAypdo28Heii/yBmwTCzMS9qV4w+9vvIAkaB+biaIvgCEgW1I06X9v 3 | cRpSS6VDrKONaBFZKUHizjGnj077YI1A3EQOpSNTueoKJDIvFITs9ZZ4HLjEk88q 4 | 5bIxgdBjplnCz75XnFHhv/wl8BVJR3qp65MFvLndjwSz9Tz9wOHLY6X+0eNJTdfW 5 | D2+JVS1ZvIgtNbSziT8Of9WU8YNXzhBGc63jVu1XkXlgLy7O3ghVOwZjLHWbRFKp 6 | StFzIun5+RCqXvVIQiIoWDPH6WogfBf7g002z4+uk+K+mJkMiMJWOucKrE3aSH6V 7 | pBOn4HcR9fxyz1bWVen7KvnIclzkYMJH0wIBAg== 8 | -----END DH PARAMETERS----- 9 | -------------------------------------------------------------------------------- /container/service/nginx/assets/etc/conf.d/default.conf: -------------------------------------------------------------------------------- 1 | # This is a default site configuration which will simply return 404, preventing 2 | # chance access to any other virtualhost. 3 | 4 | upstream flask-app { 5 | server localhost:8000; 6 | } 7 | 8 | server { 9 | listen 80 default_server; 10 | listen 443 ssl; 11 | 12 | ssl_certificate /etc/nginx/certs/server.crt; 13 | ssl_certificate_key /etc/nginx/certs/server.key; 14 | root /var/www/keyper-fe; 15 | 16 | location / { 17 | # root /var/www/keyper-fe; 18 | index index.html; 19 | try_files $uri $uri/ /index.html; 20 | } 21 | location /scripts/ { 22 | alias /var/www/scripts/; 23 | index index.html; 24 | try_files $uri $uri/ /index.html; 25 | autoindex on; 26 | } 27 | location /docs/ { 28 | alias /var/www/docs/; 29 | index index.html; 30 | try_files $uri $uri/ /index.html; 31 | } 32 | location /api/ { 33 | proxy_pass http://flask-app/; 34 | proxy_set_header Host "localhost"; 35 | proxy_set_header X-Real-IP $remote_addr; 36 | proxy_redirect off; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /container/service/nginx/assets/scripts/auth.sh.txt: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | ############################################################################# 3 | # Confidentiality Information # 4 | # # 5 | # This module is the confidential and proprietary information of # 6 | # DBSentry Corp.; it is not to be copied, reproduced, or transmitted in any # 7 | # form, by any means, in whole or in part, nor is it to be used for any # 8 | # purpose other than that for which it is expressly provided without the # 9 | # written permission of DBSentry Corp. # 10 | # # 11 | # Copyright (c) 2020-2021 DBSentry Corp. All Rights Reserved. # 12 | # # 13 | ############################################################################# 14 | # This scripts does the work of authorized_keys file by calling REST API # 15 | # and gets Public for the user attempting to login using SSH. # 16 | # # 17 | # The script accepts two parameters: # 18 | # 1. username: linux username of the user trying to login. It is a required # 19 | # parameter. It is set using %u on AuthorizedKeysCommand # 20 | # 2. fingerprint: SSH Key finger print. It is an optional parameter. It is # 21 | # set using %f on AuthorizedKeysCommand # 22 | # - Deploy this script under /etc/ssh (or corresponding location in your # 23 | # distro). # 24 | # - Rename it as auth.sh, and make sure it is owned by root and is # 25 | # executable. # 26 | # # chown root:root auth.sh # 27 | # # chmod +x auth.sh # 28 | # - Adjust KEYPER_HOST per the hostname and port. # 29 | # - Adjust HTTP protocol to http or https per your configuration of keyper. # 30 | # - Add following lines to sshd_config file (%f is optional) # 31 | # AuthorizedKeysCommand /bin/sh /etc/ssh/auth.sh %u %f # 32 | # AuthorizedKeysCommandUser root # 33 | # - Make sure that HOST is set to the hostname defined in keyper console. # 34 | # - Restart sshd  # 35 | # - Test script by invoking it on CLI # 36 | # # /etc/ssh/auth.sh # 37 | # - Above must return a SSH public key of the user # 38 | # # 39 | ############################################################################# 40 | USER="$1" 41 | FP="$2" 42 | HOST=`hostname` 43 | KEYPER_HOST={{HOSTNAME}} 44 | 45 | CURL_ARGS="-s -q -f -m 7" 46 | CURL_ARGS="${CURL_ARGS} --data-urlencode username=${USER}" 47 | CURL_ARGS="${CURL_ARGS} --data-urlencode host=${HOST}" 48 | 49 | [ -z ${FP} ] || CURL_ARGS="${CURL_ARGS} --data-urlencode fingerprint=${FP}" 50 | 51 | ## Use this if you want to get public keys using HTTP GET 52 | curl -G ${CURL_ARGS} http://${KEYPER_HOST}/api/authkeys 53 | 54 | ## Use this if you want get public keys using HTTP POST 55 | #curl ${CURL_ARGS} http://${KEYPER_HOST}/api/authkeys 56 | 57 | exit $? 58 | -------------------------------------------------------------------------------- /container/service/nginx/assets/scripts/authprinc.sh.txt: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | ############################################################################# 3 | # Confidentiality Information # 4 | # # 5 | # This module is the confidential and proprietary information of # 6 | # DBSentry Corp.; it is not to be copied, reproduced, or transmitted in any # 7 | # form, by any means, in whole or in part, nor is it to be used for any # 8 | # purpose other than that for which it is expressly provided without the # 9 | # written permission of DBSentry Corp. # 10 | # # 11 | # Copyright (c) 2020-2021 DBSentry Corp. All Rights Reserved. # 12 | # # 13 | ############################################################################# 14 | # This scripts does the work of AuthorizedPrinciaplsFile by calling REST # 15 | # API and gets Principal for the user attempting to login using SSH. # 16 | # # 17 | # The script accepts two parameters: # 18 | # 1. username: linux username of the user trying to login. It is a required # 19 | # parameter. It is set using %u on AuthorizedKeysCommand # 20 | # 2. fingerprint: SSH Key finger print. It is an optional parameter. It is # 21 | # set using %f on AuthorizedKeysCommand # 22 | # 3. serial: Certificate Serial No. It is set using %s on # 23 | # AuthorizedPrincipalsCommand # 24 | # - Deploy this script under /etc/ssh (or corresponding location in your # 25 | # distro). # 26 | # - Rename it as authprinc.sh, and make sure it is owned by root and is # 27 | # executable. # 28 | # # chown root:root authprinc.sh # 29 | # # chmod +x authprinc.sh # 30 | # - Adjust KEYPER_HOST per the hostname and port. # 31 | # - Adjust HTTP protocol to http or https per your configuration of keyper. # 32 | # - Add following lines to sshd_config file (%f is optional) # 33 | # AuthorizedPrincipalsCommand /bin/sh /etc/ssh/authprinc.sh %u %f %s # 34 | # AuthorizedPrincipalsCommandUser root # 35 | # - Make sure that HOST is set to the hostname defined in keyper console. # 36 | # - Restart sshd  # 37 | # - Test script by invoking it on CLI # 38 | # # /etc/ssh/authprinc.sh # 39 | # - Above must return a princiapl name for user # 40 | # # 41 | ############################################################################# 42 | USER="$1" 43 | FP="$2" 44 | HOST=`hostname` 45 | SERIAL="$3" 46 | KEYPER_HOST={{HOSTNAME}} 47 | 48 | CURL_ARGS="-s -q -f -m 7" 49 | CURL_ARGS="${CURL_ARGS} --data-urlencode username=${USER}" 50 | CURL_ARGS="${CURL_ARGS} --data-urlencode host=${HOST}" 51 | 52 | [ -z ${FP} ] || CURL_ARGS="${CURL_ARGS} --data-urlencode fingerprint=${FP}" 53 | [ -z ${SERIAL} ] || CURL_ARGS="${CURL_ARGS} --data-urlencode serial=${SERIAL}" 54 | 55 | ## Use this if you want to get public keys using HTTP GET 56 | curl -G ${CURL_ARGS} http://${KEYPER_HOST}/api/authprinc 57 | 58 | ## Use this if you want get public keys using HTTP POST 59 | #curl ${CURL_ARGS} http://${KEYPER_HOST}/api/authprinc 60 | 61 | exit $? 62 | -------------------------------------------------------------------------------- /container/service/nginx/install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | ############################################################################# 3 | # Confidentiality Information # 4 | # # 5 | # This module is the confidential and proprietary information of # 6 | # DBSentry Corp.; it is not to be copied, reproduced, or transmitted in any # 7 | # form, by any means, in whole or in part, nor is it to be used for any # 8 | # purpose other than that for which it is expressly provided without the # 9 | # written permission of DBSentry Corp. # 10 | # # 11 | # Copyright (c) 2020-2021 DBSentry Corp. All Rights Reserved. # 12 | # # 13 | ############################################################################# 14 | 15 | rm -rf /var/www/* 16 | -------------------------------------------------------------------------------- /container/service/nginx/process.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | ############################################################################# 3 | # Confidentiality Information # 4 | # # 5 | # This module is the confidential and proprietary information of # 6 | # DBSentry Corp.; it is not to be copied, reproduced, or transmitted in any # 7 | # form, by any means, in whole or in part, nor is it to be used for any # 8 | # purpose other than that for which it is expressly provided without the # 9 | # written permission of DBSentry Corp. # 10 | # # 11 | # Copyright (c) 2020-2021 DBSentry Corp. All Rights Reserved. # 12 | # # 13 | ############################################################################# 14 | 15 | sv check /container/run/process/gunicorn 16 | log-helper info "nginx: Starting" 17 | exec /usr/sbin/nginx -g "daemon off;" 18 | log-helper info "nginx: Started" 19 | -------------------------------------------------------------------------------- /container/service/nginx/startup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | ############################################################################# 3 | # Confidentiality Information # 4 | # # 5 | # This module is the confidential and proprietary information of # 6 | # DBSentry Corp.; it is not to be copied, reproduced, or transmitted in any # 7 | # form, by any means, in whole or in part, nor is it to be used for any # 8 | # purpose other than that for which it is expressly provided without the # 9 | # written permission of DBSentry Corp. # 10 | # # 11 | # Copyright (c) 2020-2021 DBSentry Corp. All Rights Reserved. # 12 | # # 13 | ############################################################################# 14 | 15 | FIRST_START_DONE="${CONTAINER_STATE_DIR}/nginx-first-start-done" 16 | 17 | if [ ! -e "$FIRST_START_DONE" ]; then 18 | touch $FIRST_START_DONE 19 | fi 20 | 21 | log-helper info "Setting UID/GID for nginx to ${NGINX_UID}/${NGINX_GID}" 22 | [ "$(id -g nginx)" -eq ${NGINX_GID} ] || groupmod -g ${NGINX_GID} nginx 23 | [ "$(id -u nginx)" -eq ${NGINX_UID} ] || usermod -u ${NGINX_UID} -g ${NGINX_GID} nginx 24 | 25 | cd /container/service/nginx/assets 26 | [ -d keyper-fe ] && mv keyper-fe /var/www 27 | [ -d scripts ] && mv scripts /var/www 28 | [ -d docs ] && mv docs /var/www 29 | cd /var/www 30 | chown -R nginx:nginx keyper-fe scripts docs 31 | 32 | cd /var/www/scripts 33 | sed -i "s/{{HOSTNAME}}/${HOSTNAME}/g" auth.sh.txt 34 | sed -i "s/{{HOSTNAME}}/${HOSTNAME}/g" authprinc.sh.txt 35 | 36 | cd /container/service/nginx/assets/etc/conf.d 37 | [ -f default.conf ] && mv default.conf /etc/nginx/conf.d 38 | 39 | [ -d /etc/nginx/certs ] || mkdir /etc/nginx/certs 40 | cp /container/service/nginx/assets/certs/* /etc/nginx/certs 41 | 42 | LDAP_TLS_CRT_PATH=/etc/nginx/certs/$LDAP_TLS_CRT_FILENAME 43 | LDAP_TLS_KEY_PATH=/etc/nginx/certs/$LDAP_TLS_KEY_FILENAME 44 | 45 | if [ ! -e "$LDAP_TLS_CRT_PATH" ]; then 46 | log-helper info "Certificate/key do not exist. Generating a self signed certificate ..." 47 | openssl req -newkey rsa:2048 -nodes -keyout $LDAP_TLS_KEY_PATH -x509 -days 3650 -out $LDAP_TLS_CRT_PATH -subj "/CN=${HOSTNAME}" 48 | fi 49 | 50 | chown -R nginx:nginx /etc/nginx/conf.d/default.conf /etc/nginx/certs /var/lib/nginx 51 | 52 | [ -d /run/nginx ] || mkdir /run/nginx 53 | 54 | exit 0 55 | -------------------------------------------------------------------------------- /container/service/slapd/assets/ldif/auditlog.ldif: -------------------------------------------------------------------------------- 1 | dn: olcOverlay=auditlog,olcDatabase={1}mdb,cn=config 2 | objectClass: olcOverlayConfig 3 | objectClass: olcAuditlogConfig 4 | objectClass: top 5 | olcOverlay: auditlog 6 | olcAuditlogFile: /var/log/openldap/auditlog.ldif 7 | 8 | -------------------------------------------------------------------------------- /container/service/slapd/assets/ldif/ppolicy.ldif: -------------------------------------------------------------------------------- 1 | dn: olcOverlay=ppolicy,olcDatabase={1}mdb,cn=config 2 | objectClass: olcOverlayConfig 3 | objectClass: olcPPolicyConfig 4 | objectClass: top 5 | olcOverlay: ppolicy 6 | olcPPolicyDefault: cn=default,ou=policies,dc=dbsentry,dc=com 7 | olcPPolicyHashCleartext: TRUE 8 | 9 | -------------------------------------------------------------------------------- /container/service/slapd/assets/schema/memberof.ldif: -------------------------------------------------------------------------------- 1 | dn: olcOverlay=memberof,olcDatabase={1}mdb,cn=config 2 | objectClass: olcConfig 3 | objectClass: olcMemberOf 4 | objectClass: olcOverlayConfig 5 | objectClass: top 6 | olcOverlay: memberof 7 | olcMemberOfRefint: TRUE 8 | olcMemberOfDangling: ignore 9 | olcMemberOfGroupOC: groupOfNames 10 | olcMemberOfMemberAD: member 11 | olcMemberOfMemberOfAD: memberOf 12 | 13 | -------------------------------------------------------------------------------- /container/service/slapd/assets/schema/openssh-lpk.ldif: -------------------------------------------------------------------------------- 1 | dn: cn=openssh-lpk,cn=schema,cn=config 2 | objectClass: olcSchemaConfig 3 | cn: openssh-lpk 4 | olcAttributeTypes: ( 1.3.6.1.4.1.24552.500.1.1.1.13 NAME 'sshPublicKey' 5 | DESC 'MANDATORY: OpenSSH Public key' 6 | EQUALITY octetStringMatch 7 | SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 ) 8 | olcObjectClasses: ( 1.3.6.1.4.1.24552.500.1.1.2.0 NAME 'ldapPublicKey' SUP top AUXILIARY 9 | DESC 'MANDATORY: OpenSSH LPK objectclass' 10 | MAY ( sshPublicKey $ uid ) 11 | ) 12 | 13 | -------------------------------------------------------------------------------- /container/service/slapd/assets/schema/sudo.ldif: -------------------------------------------------------------------------------- 1 | dn: cn=sudo,cn=schema,cn=config 2 | objectClass: olcSchemaConfig 3 | cn: sudo 4 | olcAttributeTypes: ( 1.3.6.1.4.1.15953.9.1.1 NAME 'sudoUser' DESC 'User(s) who may run sudo' EQUALITY caseExactIA5Match SUBSTR caseExactIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) 5 | olcAttributeTypes: ( 1.3.6.1.4.1.15953.9.1.2 NAME 'sudoHost' DESC 'Host(s) who may run sudo' EQUALITY caseExactIA5Match SUBSTR caseExactIA5SubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) 6 | olcAttributeTypes: ( 1.3.6.1.4.1.15953.9.1.3 NAME 'sudoCommand' DESC 'Command(s) to be executed by sudo' EQUALITY caseExactIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) 7 | olcAttributeTypes: ( 1.3.6.1.4.1.15953.9.1.4 NAME 'sudoRunAs' DESC 'User(s) impersonated by sudo (deprecated)' EQUALITY caseExactIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) 8 | olcAttributeTypes: ( 1.3.6.1.4.1.15953.9.1.5 NAME 'sudoOption' DESC 'Options(s) followed by sudo' EQUALITY caseExactIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) 9 | olcAttributeTypes: ( 1.3.6.1.4.1.15953.9.1.6 NAME 'sudoRunAsUser' DESC 'User(s) impersonated by sudo' EQUALITY caseExactIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) 10 | olcAttributeTypes: ( 1.3.6.1.4.1.15953.9.1.7 NAME 'sudoRunAsGroup' DESC 'Group(s) impersonated by sudo' EQUALITY caseExactIA5Match SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 ) 11 | olcObjectClasses: ( 1.3.6.1.4.1.15953.9.2.1 NAME 'sudoRole' SUP top STRUCTURAL DESC 'Sudoer Entries' MUST ( cn ) MAY ( sudoUser $ sudoHost $ sudoCommand $ sudoRunAs $ sudoRunAsUser $ sudoRunAsGroup $ sudoOption $ description ) ) 12 | 13 | -------------------------------------------------------------------------------- /container/service/slapd/assets/templates/config.ldif.tmpl: -------------------------------------------------------------------------------- 1 | dn: cn=config 2 | objectClass: olcGlobal 3 | cn: config 4 | olcArgsFile: /run/openldap/slapd.args 5 | olcPidFile: /run/openldap/slapd.pid 6 | olcDisallows: bind_anon 7 | olcRequires: authc 8 | structuralObjectClass: olcGlobal 9 | olcTLSCACertificateFile: {{LDAP_TLS_CA_CRT_PATH}} 10 | olcTLSCertificateFile: {{LDAP_TLS_CRT_PATH}} 11 | olcTLSCertificateKeyFile: {{LDAP_TLS_KEY_PATH}} 12 | olcTLSCipherSuite: {{LDAP_TLS_CIPHER_SUITE}} 13 | olcTLSDHParamFile: {{LDAP_TLS_DH_PARAM_PATH}} 14 | olcTLSProtocolMin: {{LDAP_TLS_PROTOCOL_MIN}} 15 | olcTLSVerifyClient: {{LDAP_TLS_VERIFY_CLIENT}} 16 | 17 | dn: cn=module{0},cn=config 18 | objectClass: olcModuleList 19 | cn: module{0} 20 | olcModulePath: /usr/lib/openldap 21 | olcModuleLoad: {0}back_mdb.so 22 | olcModuleLoad: {0}back_monitor.so 23 | olcModuleLoad: {0}ppolicy.so 24 | olcModuleLoad: {0}memberof.so 25 | olcModuleLoad: {0}refint.so 26 | olcModuleLoad: {0}auditlog.so 27 | structuralObjectClass: olcModuleList 28 | 29 | dn: cn=schema,cn=config 30 | objectClass: olcSchemaConfig 31 | cn: schema 32 | structuralObjectClass: olcSchemaConfig 33 | 34 | include: file:///etc/openldap/schema/core.ldif 35 | include: file:///etc/openldap/schema/cosine.ldif 36 | include: file:///etc/openldap/schema/inetorgperson.ldif 37 | include: file:///etc/openldap/schema/nis.ldif 38 | include: file:///etc/openldap/schema/openldap.ldif 39 | include: file:///etc/openldap/schema/ppolicy.ldif 40 | 41 | dn: olcDatabase={-1}frontend,cn=config 42 | objectClass: olcDatabaseConfig 43 | objectClass: olcFrontendConfig 44 | olcDatabase: {-1}frontend 45 | olcRequires: authc 46 | structuralObjectClass: olcDatabaseConfig 47 | 48 | dn: olcDatabase={0}config,cn=config 49 | objectClass: olcDatabaseConfig 50 | olcDatabase: {0}config 51 | olcAccess: {0}to * by * none 52 | olcAddContentAcl: TRUE 53 | olcLastMod: TRUE 54 | olcMaxDerefDepth: 15 55 | olcReadOnly: FALSE 56 | olcRootDN: cn=config 57 | olcRootPW: {{LDAP_ADMIN_PASSWORD}} 58 | olcSyncUseSubentry: FALSE 59 | olcMonitoring: FALSE 60 | structuralObjectClass: olcDatabaseConfig 61 | 62 | dn: olcDatabase={1}mdb,cn=config 63 | objectClass: olcDatabaseConfig 64 | objectClass: olcMdbConfig 65 | olcDatabase: {1}mdb 66 | olcDbDirectory: /var/lib/openldap/openldap-data 67 | olcSuffix: {{LDAP_BASEDN}} 68 | olcRootDN: cn=Manager,{{LDAP_BASEDN}} 69 | olcRootPW: {{LDAP_ADMIN_PASSWORD}} 70 | olcDbIndex: objectClass eq 71 | olcDbIndex: cn eq 72 | olcDbIndex: member eq 73 | olcDbIndex: pseudonym eq 74 | structuralObjectClass: olcMdbConfig 75 | 76 | dn: olcDatabase={2}monitor,cn=config 77 | objectClass: olcDatabaseConfig 78 | olcDatabase: {2}monitor 79 | olcAccess: {0}to dn.subtree=cn=monitor by users read 80 | structuralObjectClass: olcDatabaseConfig 81 | 82 | -------------------------------------------------------------------------------- /container/service/slapd/assets/templates/data.ldif.tmpl: -------------------------------------------------------------------------------- 1 | dn: {{LDAP_BASEDN}} 2 | objectClass: dcObject 3 | objectClass: organization 4 | o: {{LDAP_ORGANIZATION}} 5 | description: {"version": "0.1.8"} 6 | structuralObjectClass: organization 7 | 8 | dn: cn=Manager,{{LDAP_BASEDN}} 9 | objectClass: organizationalRole 10 | cn: Manager 11 | structuralObjectClass: organizationalRole 12 | 13 | dn: ou=groups,{{LDAP_BASEDN}} 14 | objectClass: organizationalUnit 15 | objectClass: top 16 | ou: groups 17 | description: OU where groups are defined 18 | structuralObjectClass: organizationalUnit 19 | 20 | dn: ou=people,{{LDAP_BASEDN}} 21 | objectClass: organizationalUnit 22 | objectClass: top 23 | ou: people 24 | structuralObjectClass: organizationalUnit 25 | 26 | dn: ou=Hosts,{{LDAP_BASEDN}} 27 | objectClass: organizationalUnit 28 | objectClass: top 29 | ou: Hosts 30 | structuralObjectClass: organizationalUnit 31 | 32 | dn: cn=admin,ou=people,{{LDAP_BASEDN}} 33 | objectClass: inetOrgPerson 34 | objectClass: top 35 | objectClass: ldapPublicKey 36 | objectClass: pwdPolicy 37 | objectClass: extensibleObject 38 | uid: admin 39 | cn: admin 40 | sn: admin 41 | givenName: admin 42 | displayName: admin 43 | userPassword: {{LDAP_ADMIN_PASSWORD}} 44 | memberOf: cn=KeyperAdmins,ou=groups,{{LDAP_BASEDN}} 45 | structuralObjectClass: inetOrgPerson 46 | pwdAttribute: userPassword 47 | 48 | dn: cn=KeyperAdmins,ou=groups,{{LDAP_BASEDN}} 49 | objectClass: groupOfNames 50 | objectClass: top 51 | description: Keyper Administrators 52 | member: cn=Manager,{{LDAP_BASEDN}} 53 | member: cn=admin,ou=people,{{LDAP_BASEDN}} 54 | structuralObjectClass: groupOfNames 55 | cn: KeyperAdmins 56 | 57 | dn: cn=AllHosts,ou=groups,{{LDAP_BASEDN}} 58 | objectClass: groupOfNames 59 | objectClass: top 60 | description: All Hosts Group 61 | member: cn=admin,ou=people,{{LDAP_BASEDN}} 62 | structuralObjectClass: groupOfNames 63 | cn: AllHosts 64 | 65 | dn: ou=policies,{{LDAP_BASEDN}} 66 | objectClass: organizationalUnit 67 | objectClass: top 68 | ou: policies 69 | description: Policy Definition OU 70 | structuralObjectClass: organizationalUnit 71 | 72 | dn: cn=default,ou=policies,{{LDAP_BASEDN}} 73 | objectClass: pwdPolicy 74 | objectClass: organizationalRole 75 | cn: default 76 | pwdAttribute: userPassword 77 | pwdMinLength: 3 78 | pwdCheckQuality: 2 79 | pwdLockout: TRUE 80 | structuralObjectClass: organizationalRole 81 | 82 | -------------------------------------------------------------------------------- /container/service/slapd/install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | ############################################################################# 3 | # Confidentiality Information # 4 | # # 5 | # This module is the confidential and proprietary information of # 6 | # DBSentry Corp.; it is not to be copied, reproduced, or transmitted in any # 7 | # form, by any means, in whole or in part, nor is it to be used for any # 8 | # purpose other than that for which it is expressly provided without the # 9 | # written permission of DBSentry Corp. # 10 | # # 11 | # Copyright (c) 2020-2021 DBSentry Corp. All Rights Reserved. # 12 | # # 13 | ############################################################################# 14 | 15 | rm -rf /var/lib/openldap/openldap-data/* /etc/openldap/slapd.d 16 | -------------------------------------------------------------------------------- /container/service/slapd/process.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | ############################################################################# 3 | # Confidentiality Information # 4 | # # 5 | # This module is the confidential and proprietary information of # 6 | # DBSentry Corp.; it is not to be copied, reproduced, or transmitted in any # 7 | # form, by any means, in whole or in part, nor is it to be used for any # 8 | # purpose other than that for which it is expressly provided without the # 9 | # written permission of DBSentry Corp. # 10 | # # 11 | # Copyright (c) 2020-2021 DBSentry Corp. All Rights Reserved. # 12 | # # 13 | ############################################################################# 14 | 15 | log-helper info "openldap: Starting" 16 | #exec /usr/sbin/slapd -F /etc/openldap/slapd.d -h "ldap:/// ldaps:///" -u ldap -g ldap -d "$LDAP_LOG_LEVEL" 17 | #exec /usr/sbin/slapd -h "ldap:/// ldaps:///" -u ldap -g ldap -d "$LDAP_LOG_LEVEL" 18 | exec /usr/sbin/slapd -h "ldap:/// ldaps:///" -u nginx -g nginx -d "$LDAP_LOG_LEVEL" 19 | log-helper info "openldap: Started" 20 | -------------------------------------------------------------------------------- /container/service/slapd/startup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | ############################################################################# 3 | # Confidentiality Information # 4 | # # 5 | # This module is the confidential and proprietary information of # 6 | # DBSentry Corp.; it is not to be copied, reproduced, or transmitted in any # 7 | # form, by any means, in whole or in part, nor is it to be used for any # 8 | # purpose other than that for which it is expressly provided without the # 9 | # written permission of DBSentry Corp. # 10 | # # 11 | # Copyright (c) 2020-2021 DBSentry Corp. All Rights Reserved. # 12 | # # 13 | ############################################################################# 14 | log-helper level eq trace && set -x 15 | 16 | ulimit ${LDAP_NOFILE} 17 | 18 | log-helper info "Setting UID/GID for nginx to ${NGINX_UID}/${NGINX_GID}" 19 | [ "$(id -g nginx)" -eq ${NGINX_GID} ] || groupmod -g ${NGINX_GID} ldap 20 | [ "$(id -u nginx)" -eq ${NGINX_UID} ] || usermod -u ${NGINX_UID} -g ${NGINX_GID} ldap 21 | 22 | [ -d /etc/openldap/slapd.d ] || mkdir /etc/openldap/slapd.d 23 | [ -d /etc/openldap/certs ] || mkdir /etc/openldap/certs 24 | [ -d /run/openldap ] || mkdir /run/openldap 25 | [ -d /var/log/openldap ] || mkdir /var/log/openldap 26 | 27 | ulimit ${LDAP_NOFILE} 28 | 29 | [ -z ${LDAP_ADMIN_PASSWORD} ] || PASS=${LDAP_ADMIN_PASSWORD} 30 | [ -z ${LDAP_DOMAIN} ] || DOMAIN=${LDAP_DOMAIN} 31 | [ -z "${LDAP_ORGANIZATION_NAME}" ] || ORG_NAME=${LDAP_ORGANIZATION_NAME} 32 | 33 | export BASEDN="dc=`echo ${DOMAIN} | sed 's/\./,dc=/g'`" 34 | 35 | log-helper info '--------------------------------------------------' 36 | log-helper info 'OpenLDAP database configuration' 37 | log-helper info '--------------------------------------------------' 38 | log-helper info "LDAP ORG: ${ORG_NAME}" 39 | log-helper info "LDAP DOMAIN: ${DOMAIN}" 40 | log-helper info "ADMIN PASSWD: ${PASS}" 41 | log-helper info "BASEDN: ${BASEDN}" 42 | log-helper info '--------------------------------------------------' 43 | 44 | cp /etc/nginx/certs/* /etc/openldap/certs 45 | 46 | LDAP_TLS_CA_CRT_PATH=/etc/openldap/certs/$LDAP_TLS_CA_CRT_FILENAME 47 | LDAP_TLS_CRT_PATH=/etc/openldap/certs/$LDAP_TLS_CRT_FILENAME 48 | LDAP_TLS_KEY_PATH=/etc/openldap/certs/$LDAP_TLS_KEY_FILENAME 49 | LDAP_TLS_DH_PARAM_PATH=/etc/openldap/certs/$LDAP_TLS_DH_PARAM_FILENAME 50 | 51 | FIRST_START_DONE="${CONTAINER_STATE_DIR}/openldap-first-start-done" 52 | 53 | if [ ! -e "$FIRST_START_DONE" ]; then 54 | BOOTSTRAP=false 55 | 56 | if [ -z "$(ls -A /var/lib/openldap/openldap-data | grep -v lost+found)" ] && \ 57 | [ -z "$(ls -A /etc/openldap/slapd.d | grep -v lost+found)" ]; then 58 | BOOTSTRAP=true 59 | 60 | log-helper info "Openldap DB and Config directories are empty..." 61 | log-helper info "Creating new LDAP Server" 62 | 63 | cd /container/service/slapd/assets/ldif 64 | cp ../templates/config.ldif.tmpl config.ldif 65 | cp ../templates/data.ldif.tmpl data.ldif 66 | sed -i "s/{{LDAP_BASEDN}}/${BASEDN}/g" config.ldif 67 | sed -i "s/{{LDAP_ADMIN_PASSWORD}}/${PASS}/g" config.ldif 68 | sed -i "s|{{LDAP_TLS_CA_CRT_PATH}}|${LDAP_TLS_CA_CRT_PATH}|g" config.ldif 69 | sed -i "s|{{LDAP_TLS_CRT_PATH}}|${LDAP_TLS_CRT_PATH}|g" config.ldif 70 | sed -i "s|{{LDAP_TLS_KEY_PATH}}|${LDAP_TLS_KEY_PATH}|g" config.ldif 71 | sed -i "s|{{LDAP_TLS_CIPHER_SUITE}}|${LDAP_TLS_CIPHER_SUITE}|g" config.ldif 72 | sed -i "s|{{LDAP_TLS_DH_PARAM_PATH}}|${LDAP_TLS_DH_PARAM_PATH}|g" config.ldif 73 | sed -i "s/{{LDAP_TLS_PROTOCOL_MIN}}/${LDAP_TLS_PROTOCOL_MIN}/g" config.ldif 74 | sed -i "s/{{LDAP_TLS_VERIFY_CLIENT}}/${LDAP_TLS_VERIFY_CLIENT}/g" config.ldif 75 | sed -i "s/{{LDAP_BASEDN}}/${BASEDN}/g" data.ldif 76 | sed -i "s/{{LDAP_ADMIN_PASSWORD}}/${PASS}/g" data.ldif 77 | sed -i "s/{{LDAP_ORGANIZATION}}/${ORG_NAME}/g" data.ldif 78 | 79 | log-helper info "Creating OpenLDAP Database: START" 80 | 81 | cd /container/service/slapd/assets 82 | slapadd -n 0 -F /etc/openldap/slapd.d -l ldif/config.ldif 83 | slapadd -n 0 -F /etc/openldap/slapd.d -l schema/memberof.ldif 84 | slapadd -n 0 -F /etc/openldap/slapd.d -l schema/sudo.ldif 85 | slapadd -n 0 -F /etc/openldap/slapd.d -l schema/openssh-lpk.ldif 86 | slapadd -n 0 -F /etc/openldap/slapd.d -l ldif/ppolicy.ldif 87 | slapadd -n 0 -F /etc/openldap/slapd.d -l ldif/auditlog.ldif 88 | 89 | slapadd -n 1 -F /etc/openldap/slapd.d -l ldif/data.ldif 90 | 91 | log-helper info "Creating OpenLDAP Database: END" 92 | elif [ ! -z "$(ls -A /var/lib/openldap/openldap-data | grep -v lost+found)" ] && \ 93 | [ -z "$(ls -A /etc/openldap/slapd.d | grep -v lost+found)" ]; then 94 | log-helper error "Error: The database directory /var/lib/openldap/openldap-data is empty but not the config directory /etc/openldap/slapd.d" 95 | exit 1 96 | elif [ -z "$(ls -A /var/lib/openldap/openldap-data | grep -v lost+found)" ] && \ 97 | [ ! -z "$(ls -A /etc/openldap/slapd.d | grep -v lost+found)" ]; then 98 | log-helper error "Error: The config directory /etc/openldap/slapd.d is empty but not the data directory /var/lib/openldap/openldap-data" 99 | exit 1 100 | fi 101 | 102 | touch $FIRST_START_DONE 103 | fi 104 | 105 | #chown -R ldap:ldap /etc/openldap/slapd.d /run/openldap /var/log/openldap /var/lib/openldap /etc/openldap/certs 106 | chown -R nginx:nginx /etc/openldap/slapd.d /run/openldap /var/log/openldap /var/lib/openldap /etc/openldap/certs 107 | 108 | exit 0 109 | -------------------------------------------------------------------------------- /container/tools/add-multiple-process-stack: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | echo "Install the multiple process stack: runit, syslog-ng-core, logrotate and cron" 3 | #/container/tools/add-service-available :runit :syslog-ng-core :logrotate :cron 4 | touch /container/multiple_process_stack_added 5 | -------------------------------------------------------------------------------- /container/tools/add-service-available: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | 3 | # Usage : 4 | # RUN /container/tools/add-service-available [service1] [service2] ... 5 | 6 | SERVICE_DIR="/container/service" 7 | SERVICE_AVAILABLE_DIR="/container/service-available" 8 | DOWNLOAD_FILENAME="download.sh" 9 | 10 | for i in "$@" 11 | do 12 | 13 | echo "add-service-available: ${i}" 14 | if [ -d "${SERVICE_AVAILABLE_DIR}/${i}" ]; then 15 | 16 | if [ -f "${SERVICE_AVAILABLE_DIR}/${i}/${DOWNLOAD_FILENAME}" ]; then 17 | echo "run ${SERVICE_AVAILABLE_DIR}/${i}/${DOWNLOAD_FILENAME}" 18 | ${SERVICE_AVAILABLE_DIR}/"${i}"/"${DOWNLOAD_FILENAME}" 19 | echo "remove ${SERVICE_AVAILABLE_DIR}/${i}/${DOWNLOAD_FILENAME}" 20 | rm -f "${SERVICE_AVAILABLE_DIR}/${i}/${DOWNLOAD_FILENAME}" 21 | fi 22 | 23 | echo "move ${SERVICE_AVAILABLE_DIR}/${i} to ${SERVICE_DIR}/${i}" 24 | mv "${SERVICE_AVAILABLE_DIR}/${i}" "${SERVICE_DIR}/${i}" 25 | 26 | else 27 | echo "service-available: ${i} not found in ${SERVICE_AVAILABLE_DIR}/${i}" 28 | exit 1 29 | fi 30 | done 31 | -------------------------------------------------------------------------------- /container/tools/complex-bash-env: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | call=$1 4 | 5 | function iterate() { 6 | local env_var_name=$1 7 | local env_var=${!env_var_name} 8 | 9 | if [ "$(complex-bash-env isTable "$env_var")" = true ]; then 10 | complex-bash-env stripTablePrefix "${env_var}" 11 | else 12 | echo "${env_var_name}" 13 | fi 14 | } 15 | 16 | function isTable() { 17 | local env_var=$1 18 | if [ "$(echo "${env_var}" | grep "#COMPLEX_BASH_ENV:TABLE:" -c )" -eq 1 ]; then 19 | echo true 20 | else 21 | echo false 22 | fi 23 | } 24 | 25 | function isRow() { 26 | local env_var=$1 27 | if [ "$(echo "${env_var}" | grep "#COMPLEX_BASH_ENV:ROW:" -c )" -eq 1 ]; then 28 | echo true 29 | else 30 | echo false 31 | fi 32 | } 33 | 34 | function getRowKey() { 35 | local env_var=$1 36 | local row_key_var_name 37 | row_key_var_name=$(complex-bash-env getRowKeyVarName "$env_var") 38 | echo "${!row_key_var_name}" 39 | } 40 | 41 | function getRowValue() { 42 | local env_var=$1 43 | local row_value_var_name 44 | row_value_var_name=$(complex-bash-env getRowValueVarName "$env_var") 45 | echo "${!row_value_var_name}" 46 | } 47 | 48 | function getRowKeyVarName() { 49 | local env_var=$1 50 | local row=($(complex-bash-env getRow "$env_var")) 51 | echo "${row[0]}" 52 | } 53 | 54 | function getRowValueVarName() { 55 | local env_var=$1 56 | local row=($(complex-bash-env getRow "$env_var")) 57 | echo "${row[1]}" 58 | } 59 | 60 | function getRow() { 61 | local env_var 62 | env_var=$1 63 | if [ "$(complex-bash-env isRow "$env_var")" = true ]; then 64 | local env_var 65 | env_var=$(complex-bash-env stripRowPrefix "$env_var") 66 | echo "${env_var}" 67 | else 68 | echo "$env_var is not a complex bash env row" 69 | exit 1 70 | fi 71 | } 72 | 73 | function stripTablePrefix() { 74 | local env_var=$1 75 | stripPrefix "$env_var" "#COMPLEX_BASH_ENV:TABLE:" 76 | } 77 | 78 | function stripRowPrefix() { 79 | local env_var=$1 80 | stripPrefix "$env_var" "#COMPLEX_BASH_ENV:ROW:" 81 | } 82 | 83 | function stripPrefix() { 84 | local env_var=$1 85 | local prefix=$2 86 | local r=${env_var#$prefix} 87 | echo "${r}" 88 | } 89 | 90 | shift 91 | $call "$@" 92 | -------------------------------------------------------------------------------- /container/tools/install-service: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 -u 2 | import os, os.path, subprocess 3 | 4 | SERVICE_DIR = "/container/service" 5 | INSTALL_FILENAME = "install.sh" 6 | PROCESS_FILENAME = "process.sh" 7 | nb_process = 0 8 | 9 | print("install-service") 10 | # Auto run global install script if available 11 | if os.path.isfile(SERVICE_DIR + os.sep + INSTALL_FILENAME): 12 | print(("run " + SERVICE_DIR + os.sep + INSTALL_FILENAME)) 13 | subprocess.call([SERVICE_DIR + os.sep + INSTALL_FILENAME],shell=True) 14 | 15 | print(("remove " + SERVICE_DIR + os.sep + INSTALL_FILENAME + "\n")) 16 | os.remove(SERVICE_DIR + os.sep + INSTALL_FILENAME) 17 | 18 | # Process install script of services in /container/service 19 | for service in sorted(os.listdir(SERVICE_DIR)): 20 | 21 | if os.path.isfile(SERVICE_DIR + os.sep + service + os.sep + INSTALL_FILENAME): 22 | print(("run " + SERVICE_DIR + os.sep + service + os.sep + INSTALL_FILENAME)) 23 | subprocess.call([SERVICE_DIR + os.sep + service + os.sep + INSTALL_FILENAME],shell=True) 24 | 25 | print(("remove " + SERVICE_DIR + os.sep + service + os.sep + INSTALL_FILENAME)) 26 | os.remove(SERVICE_DIR + os.sep + service + os.sep + INSTALL_FILENAME) 27 | 28 | if os.path.isfile(SERVICE_DIR + os.sep + service + os.sep + PROCESS_FILENAME): 29 | nb_process += 1 30 | 31 | 32 | print((str(nb_process) + " process found.")) 33 | 34 | # Multiple process image 35 | if nb_process > 1: 36 | if not os.path.exists("/container/multiple_process_stack_added"): 37 | print("This image has multiple process.") 38 | subprocess.call(["/container/tools/add-multiple-process-stack"],shell=True) 39 | print("For better image build process consider adding:") 40 | print("\"/container/tools/add-multiple-process-stack\" after an apk upgrade in your Dockerfile.") 41 | -------------------------------------------------------------------------------- /container/tools/log-helper: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | # log helper base on environment variable CONTAINER_LOG_LEVEL 4 | # CONTAINER_LOG_LEVEL environment variable is set by run tool based on --log-level argument (info by default) 5 | # or you can set it directly with docker --env argument 6 | 7 | # Usage example: log-helper info CONTAINER_LOG_LEVEL is info or more 8 | # the message "CONTAINER_LOG_LEVEL is info or more" will be printed only if log level is info, debug or trace 9 | 10 | LOG_LEVEL_NONE=0 11 | LOG_LEVEL_ERROR=1 12 | LOG_LEVEL_WARNING=2 13 | LOG_LEVEL_INFO=3 14 | LOG_LEVEL_DEBUG=4 15 | LOG_LEVEL_TRACE=5 16 | 17 | # default log level if CONTAINER_LOG_LEVEL is not set -> info 18 | log_level=${CONTAINER_LOG_LEVEL:-${LOG_LEVEL_INFO}} 19 | 20 | call=$1 # function to call (error, warning, info, debug, trace, level) 21 | if [[ ! "$call" =~ ^(error|warning|info|debug|trace|level)$ ]]; then 22 | echo "Error: Function $call not found" 23 | echo "Allowed functions are: error, warning, info, debug, trace, level" 24 | echo "usage example: log-helper info hello !" 25 | exit 1 26 | fi 27 | 28 | 29 | echo_msg="" # message to print if required log level is set 30 | echo_param="" # echo command parameters 31 | 32 | function error() { 33 | getEchoParams $@ 34 | 35 | if [ $log_level -ge 1 ]; then 36 | echo $echo_param "$echo_msg" 37 | fi 38 | } 39 | 40 | function warning() { 41 | getEchoParams $@ 42 | 43 | if [ $log_level -ge 2 ]; then 44 | echo $echo_param "$echo_msg" 45 | fi 46 | } 47 | 48 | function info() { 49 | getEchoParams $@ 50 | 51 | if [ $log_level -ge 3 ]; then 52 | echo $echo_param "$echo_msg" 53 | fi 54 | } 55 | 56 | function debug() { 57 | getEchoParams $@ 58 | 59 | if [ $log_level -ge 4 ]; then 60 | echo $echo_param "$echo_msg" 61 | fi 62 | } 63 | 64 | function trace() { 65 | getEchoParams $@ 66 | 67 | if [ $log_level -ge 5 ]; then 68 | echo $echo_param "$echo_msg" 69 | fi 70 | } 71 | 72 | function getMsgFromStdin() { 73 | if [ -z "$2" ]; then 74 | echo_msg=$(cat) 75 | fi 76 | } 77 | 78 | function getEchoParams() { 79 | 80 | echo_msg="$@" 81 | 82 | if [[ "$1" =~ ^(-e|-n|-E)$ ]]; then 83 | echo_param=$1 84 | echo_msg=${echo_msg#$1 } 85 | fi 86 | 87 | # read from pipe if echo_msg is empty 88 | [[ -n "$echo_msg" ]] || getMsgFromStdin 89 | } 90 | 91 | function level() { 92 | 93 | local operator=$1 94 | local loglevel_str=$2 95 | local loglevel_str=${loglevel_str^^} # uppercase 96 | 97 | if [[ ! "$operator" =~ ^(eq|ne|gt|ge|lt|le)$ ]]; then 98 | echo "Error: Operator $operator not allowed" 99 | echo "Allowed operators are: eq, ne, gt, ge, lt, le" 100 | echo "Help: http://www.tldp.org/LDP/abs/html/comparison-ops.html" 101 | exit 1 102 | fi 103 | 104 | if [ -z "$loglevel_str" ]; then 105 | echo "Error: No log level provided" 106 | echo "Allowed log level are: none, error, warning, info, debug, trace" 107 | echo "usage example: log-helper level eq info" 108 | exit 1 109 | fi 110 | 111 | local log_level_var=LOG_LEVEL_$loglevel_str 112 | 113 | if [ $log_level -$operator ${!log_level_var} ]; then 114 | exit 0 115 | else 116 | exit 1 117 | fi 118 | } 119 | 120 | shift 121 | $call "$@" 122 | -------------------------------------------------------------------------------- /container/tools/run: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 -u 2 | # -*- coding: utf-8 -*- 3 | 4 | import os, os.path, sys, stat, signal, errno, argparse, time, json, re, yaml, ast, socket, shutil, pwd, grp 5 | 6 | KILL_PROCESS_TIMEOUT = int(os.environ.get('KILL_PROCESS_TIMEOUT', 30)) 7 | KILL_ALL_PROCESSES_TIMEOUT = int(os.environ.get('KILL_ALL_PROCESSES_TIMEOUT', 30)) 8 | 9 | LOG_LEVEL_NONE = 0 10 | LOG_LEVEL_ERROR = 1 11 | LOG_LEVEL_WARNING = 2 12 | LOG_LEVEL_INFO = 3 13 | LOG_LEVEL_DEBUG = 4 14 | LOG_LEVEL_TRACE = 5 15 | 16 | SHENV_NAME_WHITELIST_REGEX = re.compile('\W') 17 | 18 | #log_level = None 19 | log_level = 5 20 | 21 | environ_backup = dict(os.environ) 22 | terminated_child_processes = {} 23 | 24 | IMPORT_STARTUP_FILENAME="startup.sh" 25 | IMPORT_PROCESS_FILENAME="process.sh" 26 | IMPORT_FINISH_FILENAME="finish.sh" 27 | 28 | IMPORT_ENVIRONMENT_DIR="/container/environment" 29 | IMPORT_FIRST_STARTUP_ENVIRONMENT_DIR="/container/environment/startup" 30 | 31 | ENV_FILES_YAML_EXTENSIONS = ('.yaml', '.startup.yaml') 32 | ENV_FILES_JSON_EXTENSIONS = ('.json', '.startup.json') 33 | ENV_FILES_STARTUP_EXTENSIONS = ('.startup.yaml', '.startup.json') 34 | 35 | IMPORT_SERVICE_DIR="/container/service" 36 | 37 | RUN_DIR="/container/run" 38 | RUN_STATE_DIR = RUN_DIR + "/state" 39 | RUN_ENVIRONMENT_DIR = RUN_DIR + "/environment" 40 | RUN_ENVIRONMENT_FILE_EXPORT = RUN_DIR + "/environment.sh" 41 | RUN_STARTUP_DIR = RUN_DIR + "/startup" 42 | RUN_STARTUP_FINAL_FILE = RUN_DIR + "/startup.sh" 43 | RUN_PROCESS_DIR = RUN_DIR + "/process" 44 | RUN_SERVICE_DIR = RUN_DIR + "/service" 45 | 46 | ENVIRONMENT_LOG_LEVEL_KEY = 'CONTAINER_LOG_LEVEL' 47 | ENVIRONMENT_SERVICE_DIR_KEY = 'CONTAINER_SERVICE_DIR' 48 | ENVIRONMENT_STATE_DIR_KEY = 'CONTAINER_STATE_DIR' 49 | 50 | class AlarmException(Exception): 51 | pass 52 | 53 | def error(message): 54 | if log_level >= LOG_LEVEL_ERROR: 55 | sys.stderr.write("*** %s\n" % message) 56 | 57 | def warning(message): 58 | if log_level >= LOG_LEVEL_WARNING: 59 | sys.stderr.write("*** %s\n" % message) 60 | 61 | def info(message): 62 | if log_level >= LOG_LEVEL_INFO: 63 | sys.stderr.write("*** %s\n" % message) 64 | 65 | def debug(message): 66 | if log_level >= LOG_LEVEL_DEBUG: 67 | sys.stderr.write("*** %s\n" % message) 68 | 69 | def trace(message): 70 | if log_level >= LOG_LEVEL_TRACE: 71 | sys.stderr.write("*** %s\n" % message) 72 | 73 | def debug_env_dump(): 74 | debug("------------ Environment dump ------------") 75 | for name, value in list(os.environ.items()): 76 | debug(name + " = " + value) 77 | debug("------------------------------------------") 78 | 79 | def ignore_signals_and_raise_keyboard_interrupt(signame): 80 | signal.signal(signal.SIGTERM, signal.SIG_IGN) 81 | signal.signal(signal.SIGINT, signal.SIG_IGN) 82 | raise KeyboardInterrupt(signame) 83 | 84 | def raise_alarm_exception(): 85 | raise AlarmException('Alarm') 86 | 87 | def listdir(path): 88 | try: 89 | result = os.stat(path) 90 | except OSError: 91 | return [] 92 | if stat.S_ISDIR(result.st_mode): 93 | return sorted(os.listdir(path)) 94 | else: 95 | return [] 96 | 97 | def is_exe(path): 98 | try: 99 | return os.path.isfile(path) and os.access(path, os.X_OK) 100 | except OSError: 101 | return False 102 | 103 | def xstr(s): 104 | if s is None: 105 | return '' 106 | return str(s) 107 | 108 | def set_env_hostname_to_etc_hosts(): 109 | try: 110 | if "HOSTNAME" in os.environ: 111 | socket_hostname = socket.gethostname() 112 | 113 | if os.environ["HOSTNAME"] != socket_hostname: 114 | ip_address = socket.gethostbyname(socket_hostname) 115 | with open("/etc/hosts", "a") as myfile: 116 | myfile.write(ip_address+" "+os.environ["HOSTNAME"]+"\n") 117 | except: 118 | trace("set_env_hostname_to_etc_hosts: failed at some point...") 119 | 120 | def python_dict_to_bash_envvar(name, python_dict): 121 | 122 | for value in python_dict: 123 | python_to_bash_envvar(name+"_KEY", value) 124 | python_to_bash_envvar(name+"_VALUE", python_dict.get(value)) 125 | 126 | values = "#COMPLEX_BASH_ENV:ROW: "+name+"_KEY "+name+"_VALUE" 127 | os.environ[name] = xstr(values) 128 | trace("python2bash : set : " + name + " = "+ os.environ[name]) 129 | 130 | def python_list_to_bash_envvar(name, python_list): 131 | 132 | values="#COMPLEX_BASH_ENV:TABLE:" 133 | 134 | i=1 135 | for value in python_list: 136 | child_name = name + "_ROW_" + str(i) 137 | values += " " + child_name 138 | python_to_bash_envvar(child_name, value) 139 | i = i +1 140 | 141 | os.environ[name] = xstr(values) 142 | trace("python2bash : set : " + name + " = "+ os.environ[name]) 143 | 144 | def python_to_bash_envvar(name, value): 145 | 146 | try: 147 | value = ast.literal_eval(value) 148 | except: 149 | pass 150 | 151 | if isinstance(value, list): 152 | python_list_to_bash_envvar(name,value) 153 | 154 | elif isinstance(value, dict): 155 | python_dict_to_bash_envvar(name,value) 156 | 157 | else: 158 | os.environ[name] = xstr(value) 159 | trace("python2bash : set : " + name + " = "+ os.environ[name]) 160 | 161 | def decode_python_envvars(): 162 | _environ = dict(os.environ) 163 | for name, value in list(_environ.items()): 164 | if value.startswith("#PYTHON2BASH:") : 165 | value = value.replace("#PYTHON2BASH:","",1) 166 | python_to_bash_envvar(name, value) 167 | 168 | def decode_json_envvars(): 169 | _environ = dict(os.environ) 170 | for name, value in list(_environ.items()): 171 | if value.startswith("#JSON2BASH:") : 172 | value = value.replace("#JSON2BASH:","",1) 173 | try: 174 | value = json.loads(value) 175 | python_to_bash_envvar(name,value) 176 | except: 177 | os.environ[name] = xstr(value) 178 | warning("failed to parse : " + xstr(value)) 179 | trace("set : " + name + " = "+ os.environ[name]) 180 | 181 | def decode_envvars(): 182 | decode_json_envvars() 183 | decode_python_envvars() 184 | 185 | def generic_import_envvars(path, override_existing_environment): 186 | if not os.path.exists(path): 187 | trace("generic_import_envvars "+ path+ " don't exists") 188 | return 189 | new_env = {} 190 | for envfile in listdir(path): 191 | filePath = path + os.sep + envfile 192 | if os.path.isfile(filePath) and "." not in envfile: 193 | name = os.path.basename(envfile) 194 | with open(filePath, "r") as f: 195 | # Text files often end with a trailing newline, which we 196 | # don't want to include in the env variable value. See 197 | # https://github.com/phusion/baseimage-docker/pull/49 198 | value = re.sub('\n\Z', '', f.read()) 199 | new_env[name] = value 200 | trace("import " + name + " from " + filePath + " --- ") 201 | 202 | for name, value in list(new_env.items()): 203 | if override_existing_environment or name not in os.environ: 204 | os.environ[name] = value 205 | trace("set : " + name + " = "+ os.environ[name]) 206 | else: 207 | debug("ignore : " + name + " = " + xstr(value) + " (keep " + name + " = " + os.environ[name] + " )") 208 | 209 | def import_run_envvars(): 210 | clear_environ() 211 | generic_import_envvars(RUN_ENVIRONMENT_DIR, True) 212 | 213 | def import_envvars(): 214 | generic_import_envvars(IMPORT_ENVIRONMENT_DIR, False) 215 | generic_import_envvars(IMPORT_FIRST_STARTUP_ENVIRONMENT_DIR, False) 216 | 217 | def export_run_envvars(to_dir = True): 218 | if to_dir and not os.path.exists(RUN_ENVIRONMENT_DIR): 219 | warning("export_run_envvars: "+RUN_ENVIRONMENT_DIR+" don't exists") 220 | return 221 | shell_dump = "" 222 | for name, value in list(os.environ.items()): 223 | if name in ['USER', 'GROUP', 'UID', 'GID', 'SHELL']: 224 | continue 225 | if to_dir: 226 | with open(RUN_ENVIRONMENT_DIR + os.sep + name, "w") as f: 227 | f.write(value) 228 | trace("export " + name + " to " + RUN_ENVIRONMENT_DIR + os.sep + name + " --- ") 229 | shell_dump += "export " + sanitize_shenvname(name) + "=" + shquote(value) + "\n" 230 | 231 | with open(RUN_ENVIRONMENT_FILE_EXPORT, "w") as f: 232 | f.write(shell_dump) 233 | trace("export "+RUN_ENVIRONMENT_FILE_EXPORT+" --- ") 234 | 235 | def create_run_envvars(): 236 | set_dir_env() 237 | set_log_level_env() 238 | import_envvars() 239 | import_env_files() 240 | decode_envvars() 241 | export_run_envvars() 242 | 243 | def clear_run_envvars(): 244 | try: 245 | shutil.rmtree(RUN_ENVIRONMENT_DIR) 246 | os.makedirs(RUN_ENVIRONMENT_DIR) 247 | os.chmod(RUN_ENVIRONMENT_DIR, 0o700) 248 | except: 249 | warning("clear_run_envvars: failed at some point...") 250 | 251 | def print_env_files_order(file_extensions): 252 | 253 | if not os.path.exists(IMPORT_ENVIRONMENT_DIR): 254 | warning("print_env_files_order "+IMPORT_ENVIRONMENT_DIR+" don't exists") 255 | return 256 | 257 | to_print = 'Caution: previously defined variables will not be overriden.\n' 258 | 259 | file_found = False 260 | for subdir, dirs, files in sorted(os.walk(IMPORT_ENVIRONMENT_DIR)): 261 | for file in files: 262 | filepath = subdir + os.sep + file 263 | if filepath.endswith(file_extensions): 264 | file_found = True 265 | filepath = subdir + os.sep + file 266 | to_print += filepath + '\n' 267 | 268 | if file_found: 269 | if log_level < LOG_LEVEL_DEBUG: 270 | to_print+='\nTo see how this files are processed and environment variables values,\n' 271 | to_print+='run this container with \'--loglevel debug\'' 272 | 273 | info('Environment files will be proccessed in this order : \n' + to_print) 274 | 275 | def import_env_files(): 276 | 277 | if not os.path.exists(IMPORT_ENVIRONMENT_DIR): 278 | warning("import_env_files: "+IMPORT_ENVIRONMENT_DIR+" don't exists") 279 | return 280 | 281 | file_extensions = ENV_FILES_YAML_EXTENSIONS + ENV_FILES_JSON_EXTENSIONS 282 | print_env_files_order(file_extensions) 283 | 284 | for subdir, dirs, files in sorted(os.walk(IMPORT_ENVIRONMENT_DIR)): 285 | for file in files: 286 | if file.endswith(file_extensions): 287 | filepath = subdir + os.sep + file 288 | 289 | try: 290 | with open(filepath, "r") as f: 291 | 292 | debug("--- process file : " + filepath+ " ---") 293 | 294 | if file.endswith(ENV_FILES_YAML_EXTENSIONS): 295 | env_vars = yaml.load(f) 296 | 297 | elif file.endswith(ENV_FILES_JSON_EXTENSIONS): 298 | env_vars = json.load(f) 299 | 300 | for name, value in list(env_vars.items()): 301 | if not name in os.environ: 302 | if isinstance(value, list) or isinstance(value, dict): 303 | os.environ[name] = '#PYTHON2BASH:' + xstr(value) 304 | else: 305 | os.environ[name] = xstr(value) 306 | trace("set : " + name + " = "+ os.environ[name]) 307 | else: 308 | debug("ignore : " + name + " = " + xstr(value) + " (keep " + name + " = " + os.environ[name] + " )") 309 | except: 310 | warning('failed to parse: ' + filepath) 311 | 312 | def remove_startup_env_files(): 313 | 314 | if os.path.isdir(IMPORT_FIRST_STARTUP_ENVIRONMENT_DIR): 315 | try: 316 | shutil.rmtree(IMPORT_FIRST_STARTUP_ENVIRONMENT_DIR) 317 | except: 318 | warning("remove_startup_env_files: failed to remove "+IMPORT_FIRST_STARTUP_ENVIRONMENT_DIR) 319 | 320 | if not os.path.exists(IMPORT_ENVIRONMENT_DIR): 321 | warning("remove_startup_env_files: "+IMPORT_ENVIRONMENT_DIR+" don't exists") 322 | return 323 | 324 | for subdir, dirs, files in sorted(os.walk(IMPORT_ENVIRONMENT_DIR)): 325 | for file in files: 326 | filepath = subdir + os.sep + file 327 | if filepath.endswith(ENV_FILES_STARTUP_EXTENSIONS): 328 | try: 329 | os.remove(filepath) 330 | info("Remove file "+filepath) 331 | except: 332 | warning("remove_startup_env_files: failed to remove "+filepath) 333 | 334 | def restore_environ(): 335 | clear_environ() 336 | trace("--- Restore initial environment ---") 337 | os.environ.update(environ_backup) 338 | 339 | def clear_environ(): 340 | trace("--- Clear existing environment ---") 341 | os.environ.clear() 342 | 343 | def set_startup_scripts_env(): 344 | info("Set environment for startup files") 345 | clear_run_envvars() # clear previous environment 346 | create_run_envvars() # create run envvars with all env files 347 | 348 | def set_process_env(keep_startup_env = False): 349 | info("Set environment for container process") 350 | if not keep_startup_env: 351 | remove_startup_env_files() 352 | clear_run_envvars() 353 | 354 | restore_environ() 355 | create_run_envvars() # recreate env var without startup env files 356 | 357 | def setup_run_directories(args): 358 | 359 | directories = (RUN_PROCESS_DIR, RUN_STARTUP_DIR, RUN_STATE_DIR, RUN_ENVIRONMENT_DIR) 360 | for directory in directories: 361 | if not os.path.exists(directory): 362 | os.makedirs(directory) 363 | 364 | if directory == RUN_ENVIRONMENT_DIR: 365 | os.chmod(directory, 0o700) 366 | 367 | if not os.path.exists(RUN_ENVIRONMENT_FILE_EXPORT): 368 | open(RUN_ENVIRONMENT_FILE_EXPORT, 'a').close() 369 | os.chmod(RUN_ENVIRONMENT_FILE_EXPORT, 0o640) 370 | uid = pwd.getpwnam("root").pw_uid 371 | gid = grp.getgrnam("root").gr_gid 372 | os.chown(RUN_ENVIRONMENT_FILE_EXPORT, uid, gid) 373 | 374 | if state_is_first_start(): 375 | 376 | if args.copy_service: 377 | copy_service_to_run_dir() 378 | 379 | set_dir_env() 380 | 381 | base_path = os.environ[ENVIRONMENT_SERVICE_DIR_KEY] 382 | nb_service = len(os.listdir(base_path)) 383 | 384 | if nb_service > 0 : 385 | info("Search service in " + ENVIRONMENT_SERVICE_DIR_KEY + " = "+base_path+" :") 386 | for d in listdir(base_path): 387 | d_path = base_path + os.sep + d 388 | if os.path.isdir(d_path): 389 | if is_exe(d_path + os.sep + IMPORT_STARTUP_FILENAME): 390 | info('link ' + d_path + os.sep + IMPORT_STARTUP_FILENAME + ' to ' + RUN_STARTUP_DIR + os.sep + d) 391 | try: 392 | os.symlink(d_path + os.sep + IMPORT_STARTUP_FILENAME, RUN_STARTUP_DIR + os.sep + d) 393 | except OSError as detail: 394 | warning('failed to link ' + d_path + os.sep + IMPORT_STARTUP_FILENAME + ' to ' + RUN_STARTUP_DIR + os.sep + d + ': ' + xstr(detail)) 395 | 396 | if is_exe(d_path + os.sep + IMPORT_PROCESS_FILENAME): 397 | info('link ' + d_path + os.sep + IMPORT_PROCESS_FILENAME + ' to ' + RUN_PROCESS_DIR + os.sep + d + os.sep + 'run') 398 | 399 | if not os.path.exists(RUN_PROCESS_DIR + os.sep + d): 400 | os.makedirs(RUN_PROCESS_DIR + os.sep + d) 401 | else: 402 | warning('directory ' + RUN_PROCESS_DIR + os.sep + d + ' already exists') 403 | 404 | try: 405 | os.symlink(d_path + os.sep + IMPORT_PROCESS_FILENAME, RUN_PROCESS_DIR + os.sep + d + os.sep + 'run') 406 | except OSError as detail: 407 | warning('failed to link ' + d_path + os.sep + IMPORT_PROCESS_FILENAME + ' to ' + RUN_PROCESS_DIR + os.sep + d + os.sep + 'run : ' + xstr(detail)) 408 | 409 | if not args.skip_finish_files and is_exe(d_path + os.sep + IMPORT_FINISH_FILENAME): 410 | info('link ' + d_path + os.sep + IMPORT_FINISH_FILENAME + ' to ' + RUN_PROCESS_DIR + os.sep + d + os.sep + 'finish') 411 | 412 | if not os.path.exists(RUN_PROCESS_DIR + os.sep + d): 413 | os.makedirs(RUN_PROCESS_DIR + os.sep + d) 414 | 415 | try: 416 | os.symlink(d_path + os.sep + IMPORT_FINISH_FILENAME, RUN_PROCESS_DIR + os.sep + d + os.sep + 'finish') 417 | except OSError as detail: 418 | warning('failed to link ' + d_path + os.sep + IMPORT_FINISH_FILENAME + ' to ' + RUN_PROCESS_DIR + os.sep + d + os.sep + 'finish : ' + xstr(detail)) 419 | 420 | def set_dir_env(): 421 | if state_is_service_copied_to_run_dir(): 422 | os.environ[ENVIRONMENT_SERVICE_DIR_KEY] = RUN_SERVICE_DIR 423 | else: 424 | os.environ[ENVIRONMENT_SERVICE_DIR_KEY] = IMPORT_SERVICE_DIR 425 | trace("set : " + ENVIRONMENT_SERVICE_DIR_KEY + " = " + os.environ[ENVIRONMENT_SERVICE_DIR_KEY]) 426 | 427 | os.environ[ENVIRONMENT_STATE_DIR_KEY] = RUN_STATE_DIR 428 | trace("set : " + ENVIRONMENT_STATE_DIR_KEY + " = " + os.environ[ENVIRONMENT_STATE_DIR_KEY]) 429 | 430 | def set_log_level_env(): 431 | os.environ[ENVIRONMENT_LOG_LEVEL_KEY] = xstr(log_level) 432 | trace("set : "+ENVIRONMENT_LOG_LEVEL_KEY+" = " + os.environ[ENVIRONMENT_LOG_LEVEL_KEY]) 433 | 434 | def copy_service_to_run_dir(): 435 | 436 | if os.path.exists(RUN_SERVICE_DIR): 437 | warning("Copy "+IMPORT_SERVICE_DIR+" to "+RUN_SERVICE_DIR + " ignored") 438 | warning(RUN_SERVICE_DIR + " already exists") 439 | return 440 | 441 | info("Copy "+IMPORT_SERVICE_DIR+" to "+RUN_SERVICE_DIR) 442 | 443 | try: 444 | shutil.copytree(IMPORT_SERVICE_DIR, RUN_SERVICE_DIR) 445 | except shutil.Error as e: 446 | warning(e) 447 | 448 | state_set_service_copied_to_run_dir() 449 | 450 | def state_set_service_copied_to_run_dir(): 451 | open(RUN_STATE_DIR+"/service-copied-to-run-dir", 'a').close() 452 | 453 | def state_is_service_copied_to_run_dir(): 454 | return os.path.exists(RUN_STATE_DIR+'/service-copied-to-run-dir') 455 | 456 | def state_set_first_startup_done(): 457 | open(RUN_STATE_DIR+"/first-startup-done", 'a').close() 458 | 459 | def state_is_first_start(): 460 | return os.path.exists(RUN_STATE_DIR+'/first-startup-done') == False 461 | 462 | def state_set_startup_done(): 463 | open(RUN_STATE_DIR+"/startup-done", 'a').close() 464 | 465 | def state_reset_startup_done(): 466 | try: 467 | os.remove(RUN_STATE_DIR+"/startup-done") 468 | except OSError: 469 | pass 470 | 471 | def is_multiple_process_container(): 472 | return len(listdir(RUN_PROCESS_DIR)) > 1 473 | 474 | def is_single_process_container(): 475 | return len(listdir(RUN_PROCESS_DIR)) == 1 476 | 477 | def get_container_process(): 478 | for p in listdir(RUN_PROCESS_DIR): 479 | return RUN_PROCESS_DIR + os.sep + p + os.sep + 'run' 480 | 481 | def is_runit_installed(): 482 | return os.path.exists('/sbin/sv') 483 | 484 | _find_unsafe = re.compile(r'[^\w@%+=:,./-]').search 485 | 486 | def shquote(s): 487 | """Return a shell-escaped version of the string *s*.""" 488 | if not s: 489 | return "''" 490 | if _find_unsafe(s) is None: 491 | return s 492 | 493 | # use single quotes, and put single quotes into double quotes 494 | # the string $'b is then quoted as '$'"'"'b' 495 | return "'" + s.replace("'", "'\"'\"'") + "'" 496 | 497 | def sanitize_shenvname(s): 498 | return re.sub(SHENV_NAME_WHITELIST_REGEX, "_", s) 499 | 500 | # Waits for the child process with the given PID, while at the same time 501 | # reaping any other child processes that have exited (e.g. adopted child 502 | # processes that have terminated). 503 | def waitpid_reap_other_children(pid): 504 | global terminated_child_processes 505 | 506 | status = terminated_child_processes.get(pid) 507 | if status: 508 | # A previous call to waitpid_reap_other_children(), 509 | # with an argument not equal to the current argument, 510 | # already waited for this process. Return the status 511 | # that was obtained back then. 512 | del terminated_child_processes[pid] 513 | return status 514 | 515 | done = False 516 | status = None 517 | while not done: 518 | try: 519 | # https://github.com/phusion/baseimage-docker/issues/151#issuecomment-92660569 520 | this_pid, status = os.waitpid(pid, os.WNOHANG) 521 | if this_pid == 0: 522 | this_pid, status = os.waitpid(-1, 0) 523 | if this_pid == pid: 524 | done = True 525 | else: 526 | # Save status for later. 527 | terminated_child_processes[this_pid] = status 528 | except OSError as e: 529 | if e.errno == errno.ECHILD or e.errno == errno.ESRCH: 530 | return None 531 | else: 532 | raise 533 | return status 534 | 535 | def stop_child_process(name, pid, signo = signal.SIGTERM, time_limit = KILL_PROCESS_TIMEOUT): 536 | info("Shutting down %s (PID %d)..." % (name, pid)) 537 | try: 538 | os.kill(pid, signo) 539 | except OSError: 540 | pass 541 | signal.alarm(time_limit) 542 | try: 543 | try: 544 | waitpid_reap_other_children(pid) 545 | except OSError: 546 | pass 547 | except AlarmException: 548 | warning("%s (PID %d) did not shut down in time. Forcing it to exit." % (name, pid)) 549 | try: 550 | os.kill(pid, signal.SIGKILL) 551 | except OSError: 552 | pass 553 | try: 554 | waitpid_reap_other_children(pid) 555 | except OSError: 556 | pass 557 | finally: 558 | signal.alarm(0) 559 | 560 | def run_command_killable(command): 561 | status = None 562 | debug_env_dump() 563 | pid = os.spawnvp(os.P_NOWAIT, command[0], command) 564 | try: 565 | status = waitpid_reap_other_children(pid) 566 | except BaseException: 567 | warning("An error occurred. Aborting.") 568 | stop_child_process(command[0], pid) 569 | raise 570 | if status != 0: 571 | if status is None: 572 | error("%s exited with unknown status\n" % command[0]) 573 | else: 574 | error("%s failed with status %d\n" % (command[0], os.WEXITSTATUS(status))) 575 | sys.exit(1) 576 | 577 | def run_command_killable_and_import_run_envvars(command): 578 | run_command_killable(command) 579 | import_run_envvars() 580 | export_run_envvars(False) 581 | 582 | def kill_all_processes(time_limit): 583 | info("Killing all processes...") 584 | try: 585 | os.kill(-1, signal.SIGTERM) 586 | except OSError: 587 | pass 588 | signal.alarm(time_limit) 589 | try: 590 | # Wait until no more child processes exist. 591 | done = False 592 | while not done: 593 | try: 594 | os.waitpid(-1, 0) 595 | except OSError as e: 596 | if e.errno == errno.ECHILD: 597 | done = True 598 | else: 599 | raise 600 | except AlarmException: 601 | warning("Not all processes have exited in time. Forcing them to exit.") 602 | try: 603 | os.kill(-1, signal.SIGKILL) 604 | except OSError: 605 | pass 606 | finally: 607 | signal.alarm(0) 608 | 609 | def container_had_startup_script(): 610 | return (len(listdir(RUN_STARTUP_DIR)) > 0 or is_exe(RUN_STARTUP_FINAL_FILE)) 611 | 612 | def run_startup_files(args): 613 | 614 | # Run /container/run/startup/* 615 | for name in listdir(RUN_STARTUP_DIR): 616 | filename = RUN_STARTUP_DIR + os.sep + name 617 | if is_exe(filename): 618 | info("Running %s..." % filename) 619 | run_command_killable_and_import_run_envvars([filename]) 620 | 621 | # Run /container/run/startup.sh. 622 | if is_exe(RUN_STARTUP_FINAL_FILE): 623 | info("Running "+RUN_STARTUP_FINAL_FILE+"...") 624 | run_command_killable_and_import_run_envvars([RUN_STARTUP_FINAL_FILE]) 625 | 626 | def wait_for_process_or_interrupt(pid): 627 | status = waitpid_reap_other_children(pid) 628 | return (True, status) 629 | 630 | def run_process(args, background_process_name, background_process_command): 631 | background_process_pid = run_background_process(background_process_name,background_process_command) 632 | background_process_exited = False 633 | exit_status = None 634 | 635 | if len(args.main_command) == 0: 636 | background_process_exited, exit_status = wait_background_process(background_process_name, background_process_pid) 637 | else: 638 | exit_status = run_foreground_process(args.main_command) 639 | 640 | return background_process_pid, background_process_exited, exit_status 641 | 642 | def run_background_process(name, command): 643 | info("Running "+ name +"...") 644 | pid = os.spawnvp(os.P_NOWAIT, command[0], command) 645 | debug("%s started as PID %d" % (name, pid)) 646 | return pid 647 | 648 | def wait_background_process(name, pid): 649 | exit_code = None 650 | exit_status = None 651 | process_exited = False 652 | 653 | process_exited, exit_code = wait_for_process_or_interrupt(pid) 654 | if process_exited: 655 | if exit_code is None: 656 | info(name + " exited with unknown status") 657 | exit_status = 1 658 | else: 659 | exit_status = os.WEXITSTATUS(exit_code) 660 | info("%s exited with status %d" % (name, exit_status)) 661 | return (process_exited, exit_status) 662 | 663 | def run_foreground_process(command): 664 | exit_code = None 665 | exit_status = None 666 | 667 | info("Running %s..." % " ".join(command)) 668 | pid = os.spawnvp(os.P_NOWAIT, command[0], command) 669 | try: 670 | exit_code = waitpid_reap_other_children(pid) 671 | if exit_code is None: 672 | info("%s exited with unknown status." % command[0]) 673 | exit_status = 1 674 | else: 675 | exit_status = os.WEXITSTATUS(exit_code) 676 | info("%s exited with status %d." % (command[0], exit_status)) 677 | except KeyboardInterrupt: 678 | stop_child_process(command[0], pid) 679 | raise 680 | except BaseException: 681 | warning("An error occurred. Aborting.") 682 | stop_child_process(command[0], pid) 683 | raise 684 | 685 | return exit_status 686 | 687 | def shutdown_runit_services(): 688 | debug("Begin shutting down runit services...") 689 | os.system("/sbin/sv -w %d force-stop %s/* > /dev/null" % (KILL_PROCESS_TIMEOUT, RUN_PROCESS_DIR)) 690 | 691 | def wait_for_runit_services(): 692 | debug("Waiting for runit services to exit...") 693 | done = False 694 | while not done: 695 | done = os.system("/sbin/sv status "+RUN_PROCESS_DIR+"/* | grep -q '^run:'") != 0 696 | if not done: 697 | time.sleep(0.1) 698 | shutdown_runit_services() 699 | 700 | def run_multiple_process_container(args): 701 | if not is_runit_installed(): 702 | error("Error: runit is not installed and this is a multiple process container.") 703 | return 704 | 705 | background_process_exited=False 706 | background_process_pid=None 707 | 708 | try: 709 | runit_command=["/sbin/runsvdir", "-P", RUN_PROCESS_DIR] 710 | background_process_pid, background_process_exited, exit_status = run_process(args, "runit daemon", runit_command) 711 | 712 | sys.exit(exit_status) 713 | finally: 714 | shutdown_runit_services() 715 | if not background_process_exited: 716 | stop_child_process("runit daemon", background_process_pid) 717 | wait_for_runit_services() 718 | 719 | def run_single_process_container(args): 720 | background_process_exited=False 721 | background_process_pid=None 722 | 723 | try: 724 | container_process=get_container_process(); 725 | background_process_pid, background_process_exited, exit_status = run_process(args, container_process, [container_process]) 726 | 727 | sys.exit(exit_status) 728 | finally: 729 | if not background_process_exited: 730 | stop_child_process(container_process, background_process_pid) 731 | 732 | def run_no_process_container(args): 733 | if len(args.main_command) == 0: 734 | args.main_command=['bash'] # run bash by default 735 | 736 | exit_status = run_foreground_process(args.main_command) 737 | sys.exit(exit_status) 738 | 739 | def run_finish_files(): 740 | 741 | # iterate process dir to find finish files 742 | for name in listdir(RUN_PROCESS_DIR): 743 | filename = RUN_PROCESS_DIR + os.sep + name + os.sep + "finish" 744 | if is_exe(filename): 745 | info("Running %s..." % filename) 746 | run_command_killable_and_import_run_envvars([filename]) 747 | 748 | def wait_states(states): 749 | for state in states: 750 | filename = RUN_STATE_DIR + os.sep + state 751 | info("Wait state: " + state) 752 | 753 | while not os.path.exists(filename): 754 | time.sleep(0.1) 755 | debug("Check file " + filename) 756 | pass 757 | debug("Check file " + filename + " [Ok]") 758 | 759 | def run_cmds(args, when): 760 | debug("Run commands before " + when + "...") 761 | if len(args.cmds) > 0: 762 | 763 | for cmd in args.cmds: 764 | if (len(cmd) > 1 and cmd[1] == when) or (len(cmd) == 1 and when == "startup"): 765 | info("Running '"+cmd[0]+"'...") 766 | run_command_killable_and_import_run_envvars(cmd[0].split()) 767 | 768 | def main(args): 769 | 770 | info(ENVIRONMENT_LOG_LEVEL_KEY + " = " + xstr(log_level) + " (" + log_level_switcher_inv.get(log_level) + ")") 771 | state_reset_startup_done() 772 | 773 | if args.set_env_hostname_to_etc_hosts: 774 | set_env_hostname_to_etc_hosts() 775 | 776 | wait_states(args.wait_states) 777 | setup_run_directories(args) 778 | 779 | if not args.skip_env_files: 780 | set_startup_scripts_env() 781 | 782 | run_cmds(args,"startup") 783 | 784 | if not args.skip_startup_files and container_had_startup_script(): 785 | run_startup_files(args) 786 | 787 | state_set_startup_done() 788 | state_set_first_startup_done() 789 | 790 | if not args.skip_env_files: 791 | set_process_env(args.keep_startup_env) 792 | 793 | run_cmds(args,"process") 794 | 795 | debug_env_dump() 796 | 797 | if is_single_process_container() and not args.skip_process_files: 798 | run_single_process_container(args) 799 | 800 | elif is_multiple_process_container() and not args.skip_process_files: 801 | run_multiple_process_container(args) 802 | 803 | else: 804 | run_no_process_container(args) 805 | 806 | # Parse options. 807 | parser = argparse.ArgumentParser(description = 'Initialize the system.', epilog='') 808 | parser.add_argument('main_command', metavar = 'MAIN_COMMAND', type = str, nargs = '*', 809 | help = 'The main command to run, leave empty to only run container process.') 810 | parser.add_argument('-e', '--skip-env-files', dest = 'skip_env_files', 811 | action = 'store_const', const = True, default = False, 812 | help = 'Skip getting environment values from environment file(s).') 813 | parser.add_argument('-s', '--skip-startup-files', dest = 'skip_startup_files', 814 | action = 'store_const', const = True, default = False, 815 | help = 'Skip running '+RUN_STARTUP_DIR+'/* and '+RUN_STARTUP_FINAL_FILE + ' file(s).') 816 | parser.add_argument('-p', '--skip-process-files', dest = 'skip_process_files', 817 | action = 'store_const', const = True, default = False, 818 | help = 'Skip running container process file(s).') 819 | parser.add_argument('-f', '--skip-finish-files', dest = 'skip_finish_files', 820 | action = 'store_const', const = True, default = False, 821 | help = 'Skip running container finish file(s).') 822 | parser.add_argument('-o', '--run-only', type=str, choices=["startup","process","finish"], dest = 'run_only', default = None, 823 | help = 'Run only this file type and ignore others.') 824 | parser.add_argument('-c', '--cmd', metavar=('COMMAND', 'WHEN={startup,process,finish}'), dest = 'cmds', type = str, 825 | action = 'append', default = [], nargs = "+", 826 | help = 'Run this command before WHEN file(s). Default before startup file(s).') 827 | parser.add_argument('-k', '--no-kill-all-on-exit', dest = 'kill_all_on_exit', 828 | action = 'store_const', const = False, default = True, 829 | help = 'Don\'t kill all processes on the system upon exiting.') 830 | parser.add_argument('--wait-state', metavar = 'FILENAME', dest = 'wait_states', type = str, 831 | action = 'append', default=[], 832 | help = 'Wait until the container state file exists in '+RUN_STATE_DIR+' directory before starting. Usefull when 2 containers share '+RUN_DIR+' directory via volume.') 833 | parser.add_argument('--wait-first-startup', dest = 'wait_first_startup', 834 | action = 'store_const', const = True, default = False, 835 | help = 'Wait until the first startup is done before starting. Usefull when 2 containers share '+RUN_DIR+' directory via volume.') 836 | parser.add_argument('--keep-startup-env', dest = 'keep_startup_env', 837 | action = 'store_const', const = True, default = False, 838 | help = 'Don\'t remove ' + xstr(ENV_FILES_STARTUP_EXTENSIONS) + ' environment files after startup scripts.') 839 | parser.add_argument('--copy-service', dest = 'copy_service', 840 | action = 'store_const', const = True, default = False, 841 | help = 'Copy '+IMPORT_SERVICE_DIR+' to '+RUN_SERVICE_DIR+'. Help to fix docker mounted files problems.') 842 | parser.add_argument('--dont-touch-etc-hosts', dest = 'set_env_hostname_to_etc_hosts', 843 | action = 'store_const', const = False, default = True, 844 | help = 'Don\'t add in /etc/hosts a line with the container ip and $HOSTNAME environment variable value.') 845 | parser.add_argument('--keepalive', dest = 'keepalive', 846 | action = 'store_const', const = True, default = False, 847 | help = 'Keep alive container if all startup files and process exited without error.') 848 | parser.add_argument('--keepalive-force', dest = 'keepalive_force', 849 | action = 'store_const', const = True, default = False, 850 | help = 'Keep alive container in all circonstancies.') 851 | parser.add_argument('-l', '--loglevel', type=str, choices=["none","error","warning","info","debug","trace"], dest = 'log_level', default = "info", 852 | help = 'Log level (default: info)') 853 | 854 | args = parser.parse_args() 855 | 856 | log_level_switcher = {"none": LOG_LEVEL_NONE,"error": LOG_LEVEL_ERROR,"warning": LOG_LEVEL_WARNING,"info": LOG_LEVEL_INFO,"debug": LOG_LEVEL_DEBUG, "trace": LOG_LEVEL_TRACE} 857 | log_level_switcher_inv = {LOG_LEVEL_NONE: "none",LOG_LEVEL_ERROR:"error",LOG_LEVEL_WARNING:"warning",LOG_LEVEL_INFO:"info",LOG_LEVEL_DEBUG:"debug",LOG_LEVEL_TRACE:"trace"} 858 | log_level = log_level_switcher.get(args.log_level) 859 | 860 | # Run only arg 861 | if args.run_only != None: 862 | if args.run_only == "startup" and args.skip_startup_files: 863 | error("Error: When '--run-only startup' is set '--skip-startup-files' can't be set.") 864 | sys.exit(1) 865 | elif args.run_only == "process" and args.skip_startup_files: 866 | error("Error: When '--run-only process' is set '--skip-process-files' can't be set.") 867 | sys.exit(1) 868 | elif args.run_only == "finish" and args.skip_startup_files: 869 | error("Error: When '--run-only finish' is set '--skip-finish-files' can't be set.") 870 | sys.exit(1) 871 | 872 | if args.run_only == "startup": 873 | args.skip_process_files = True 874 | args.skip_finish_files = True 875 | elif args.run_only == "process": 876 | args.skip_startup_files = True 877 | args.skip_finish_files = True 878 | elif args.run_only == "finish": 879 | args.skip_startup_files = True 880 | args.skip_process_files = True 881 | 882 | # wait for startup args 883 | if args.wait_first_startup: 884 | args.wait_states.insert(0, 'first-startup-done') 885 | 886 | # Run main function. 887 | signal.signal(signal.SIGTERM, lambda signum, frame: ignore_signals_and_raise_keyboard_interrupt('SIGTERM')) 888 | signal.signal(signal.SIGINT, lambda signum, frame: ignore_signals_and_raise_keyboard_interrupt('SIGINT')) 889 | signal.signal(signal.SIGALRM, lambda signum, frame: raise_alarm_exception()) 890 | 891 | exit_code = 0 892 | 893 | try: 894 | main(args) 895 | 896 | except SystemExit as err: 897 | info("In SystemExit") 898 | exit_code = err.code 899 | if args.keepalive and err.code == 0: 900 | try: 901 | info("All process have exited without error, keep container alive...") 902 | while True: 903 | time.sleep(60) 904 | pass 905 | except: 906 | info("Keep alive process ended.") 907 | 908 | except KeyboardInterrupt: 909 | warning("Init system aborted.") 910 | exit(2) 911 | 912 | finally: 913 | info("In finally") 914 | run_cmds(args,"finish") 915 | 916 | # for multiple process images finish script are run by runit 917 | if not args.skip_finish_files and not is_multiple_process_container(): 918 | run_finish_files() 919 | 920 | if args.keepalive_force: 921 | try: 922 | info("All process have exited, keep container alive...") 923 | while True: 924 | time.sleep(60) 925 | pass 926 | except: 927 | info("Keep alive process ended.") 928 | 929 | if args.kill_all_on_exit: 930 | kill_all_processes(KILL_ALL_PROCESSES_TIMEOUT) 931 | 932 | exit(exit_code) 933 | -------------------------------------------------------------------------------- /container/tools/setuser: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ''' 4 | Copyright (c) 2013-2015 Phusion Holding B.V. 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in 14 | all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | THE SOFTWARE. 23 | ''' 24 | 25 | import sys 26 | import os 27 | import pwd 28 | 29 | 30 | def abort(message): 31 | sys.stderr.write("setuser: %s\n" % message) 32 | sys.exit(1) 33 | 34 | 35 | def main(): 36 | ''' 37 | A simple alternative to sudo that executes a command as a user by setting 38 | the user ID and user parameters to those described by the system and then 39 | using execvp(3) to execute the command without the necessity of a TTY 40 | ''' 41 | 42 | username = sys.argv[1] 43 | try: 44 | user = pwd.getpwnam(username) 45 | except KeyError: 46 | abort("user %s not found" % username) 47 | os.initgroups(username, user.pw_gid) 48 | os.setgid(user.pw_gid) 49 | os.setuid(user.pw_uid) 50 | os.environ['USER'] = username 51 | os.environ['HOME'] = user.pw_dir 52 | os.environ['UID'] = str(user.pw_uid) 53 | try: 54 | os.execvp(sys.argv[2], sys.argv[2:]) 55 | except OSError as e: 56 | abort("cannot execute %s: %s" % (sys.argv[2], str(e))) 57 | 58 | if __name__ == '__main__': 59 | 60 | if len(sys.argv) < 3: 61 | sys.stderr.write("Usage: /sbin/setuser USERNAME COMMAND [args..]\n") 62 | sys.exit(1) 63 | 64 | main() 65 | -------------------------------------------------------------------------------- /container/tools/wait-process: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | 3 | # wait startup to finish 4 | while ! test -f /container/run/state/startup-done 5 | do 6 | sleep 0.5 7 | done 8 | 9 | for process in "$@" 10 | do 11 | # wait service 12 | while ! pgrep -c "${process}" > /dev/null 13 | do 14 | sleep 0.5 15 | done 16 | done 17 | -------------------------------------------------------------------------------- /contrib/kp1-detach.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ############################################################################# 3 | # Contributed by Philip Ingram # 4 | ############################################################################# 5 | 6 | # readlink works if script invoked by symbolic link 7 | this_script=$(readlink -f "$0") 8 | this_dir="$(dirname "${this_script}")" 9 | 10 | # initiate logging and check sudo capable 11 | log_sudo () { 12 | # checks user can use sudo 13 | # sets up log file 14 | # shows start time 15 | 16 | set +x #echo off. Use set -x to turn echo on 17 | 18 | local start_secs 19 | local runid 20 | local r0 21 | local r1 22 | 23 | # check being run with sudo 24 | # note that 'root' is not a member of the sudo group 25 | # must therefore test for id 0 before texting group membership 26 | 27 | if [[ $(id -u) -eq 0 ]] 28 | then 29 | echo "this script will run as root when required" 30 | echo "please rerun from an account with 'sudo' privileges" 31 | echo "_without_ using 'sudo' to ensure correct file ownership" 32 | exit 98 33 | else # not running as root 34 | # there are blanks on each side of $(groups) and of sudo 35 | # this simplifies the test 36 | if ! [[ " $(groups) " == *' sudo '* ]] 37 | then 38 | echo "This account is not a member of the 'sudo' group" 39 | echo 'Please rerun from a suitable account' 40 | exit 99 41 | fi # member of 'sudo' group, not running as root, OK 42 | fi 43 | 44 | start_secs=$(date +"%s") 45 | runid=$(date +"%y%m%d%H%M%S") 46 | r0=$(echo "$0" | sed 's:^.*/\(.*\):\1:' ) 47 | r1="$r0-"$runid".log" 48 | echo "log file is $PWD/logs/$r1" 49 | 50 | # Create log directory if needed 51 | mkdir -p "$PWD/logs" 52 | # route all output to log file 53 | exec &> >(tee -a "$PWD/logs/$r1") 54 | 55 | # report script name 56 | echo "bash source is <${BASH_SOURCE[0]}>" 57 | script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 58 | echo "script_dir is <$script_dir>" 59 | script_full_name="$(realpath "$0")" 60 | echo "script_full_name is <$script_full_name>" 61 | echo "script starts at: $runid" 62 | } 63 | 64 | log_sudo 65 | 66 | LDAP_ORGANIZATION_NAME='keyper test' 67 | LDAP_DOMAIN='lan' 68 | sudo docker volume create slapd.d 69 | sudo docker volume create openldap-data 70 | sudo docker volume create ssh-keys 71 | sudo docker volume create certs 72 | 73 | sudo docker run -p 8080:80 -p 8443:443 -p 2389:389 -p 2636:636 \ 74 | --hostname octopod21.lan \ 75 | --mount source=slapd.d,target=/etc/openldap/slapd.d \ 76 | --mount source=openldap-data,target=/var/lib/openldap/openldap-data \ 77 | --mount source=ssh-keys,target=/etc/sshca \ 78 | --mount source=certs,target=/etc/nginx/certs \ 79 | --detach \ 80 | -it dbsentry/keyper 81 | 82 | -------------------------------------------------------------------------------- /modules/build_builder.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -ex 2 | ############################################################################# 3 | # Confidentiality Information # 4 | # # 5 | # This module is the confidential and proprietary information of # 6 | # DBSentry Corp.; it is not to be copied, reproduced, or transmitted in any # 7 | # form, by any means, in whole or in part, nor is it to be used for any # 8 | # purpose other than that for which it is expressly provided without the # 9 | # written permission of DBSentry Corp. # 10 | # # 11 | # Copyright (c) 2020-2021 DBSentry Corp. All Rights Reserved. # 12 | # # 13 | ############################################################################# 14 | # Build Vue frontend app 15 | if [ -f /container/keyper-fe/package.json ]; then 16 | cd /container/keyper-fe 17 | rm -rf .git .gitignore 18 | npm install 19 | npm run build 20 | 21 | status=$? 22 | 23 | if [ $status -eq 0 ]; then 24 | mv dist /var/www/keyper-fe 25 | else 26 | echo "##########################################################" 27 | echo "Error building keyper-fe" 28 | echo "##########################################################" 29 | fi 30 | else 31 | mkdir /var/www/keyper-fe 32 | fi 33 | 34 | # Build and install flask modules/libraries 35 | mv /container/keyper /var/www 36 | cd /var/www/keyper 37 | rm -rf env/* .git .gitignore 38 | python3 -m venv env 39 | . env/bin/activate 40 | pip install -r requirements.txt 41 | 42 | status=$? 43 | 44 | if [ $status -eq 0 ]; then 45 | cd /var/www 46 | tar -czf /container/out.tar.gz . 47 | else 48 | echo "##########################################################" 49 | echo "Error building keyper" 50 | echo "##########################################################" 51 | fi 52 | --------------------------------------------------------------------------------