From 9f729dbb52e735d0fb312c73fadbff6537edf420 Mon Sep 17 00:00:00 2001 From: Tigran Muradyan Date: Thu, 5 Oct 2023 15:05:58 +0400 Subject: [PATCH] feat(DMVP-2721): have wireguard setup in aws --- .github/dependabot.yml | 8 + .github/workflows/checkov.yaml | 23 ++ .github/workflows/pre-commit.yaml | 22 ++ .github/workflows/semantic.yaml | 21 ++ .github/workflows/terraform-test.yaml | 26 +++ .github/workflows/tflint.yaml | 27 +++ .github/workflows/tfsec.yaml | 18 ++ .gitignore | 39 ++++ .pre-commit-config.yaml | 36 ++++ LICENSE | 201 ++++++++++++++++++ commitlint.config.js | 5 + git-conventional-commits.json | 41 ++++ githooks/commit-msg | 86 ++++++++ githooks/pre-commit | 5 + modules/aws/README.md | 87 ++++++++ modules/aws/data.tf | 26 +++ modules/aws/main.tf | 62 ++++++ modules/aws/output.tf | 21 ++ .../aws/templates/wireguard-client.conf.tpl | 13 ++ .../templates/wireguard-server-init.sh.tpl | 36 ++++ modules/aws/tests/basic/0-setup.tf | 24 +++ modules/aws/tests/basic/1-example.tf | 20 ++ modules/aws/tests/basic/2-assert.tf | 9 + modules/aws/tests/basic/README.md | 36 ++++ modules/aws/variables.tf | 90 ++++++++ modules/aws/versions.tf | 10 + package.json | 22 ++ 27 files changed, 1014 insertions(+) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/checkov.yaml create mode 100644 .github/workflows/pre-commit.yaml create mode 100644 .github/workflows/semantic.yaml create mode 100644 .github/workflows/terraform-test.yaml create mode 100644 .github/workflows/tflint.yaml create mode 100644 .github/workflows/tfsec.yaml create mode 100644 .gitignore create mode 100644 .pre-commit-config.yaml create mode 100644 LICENSE create mode 100644 commitlint.config.js create mode 100644 git-conventional-commits.json create mode 100755 githooks/commit-msg create mode 100755 githooks/pre-commit create mode 100644 modules/aws/README.md create mode 100644 modules/aws/data.tf create mode 100644 modules/aws/main.tf create mode 100644 modules/aws/output.tf create mode 100644 modules/aws/templates/wireguard-client.conf.tpl create mode 100644 modules/aws/templates/wireguard-server-init.sh.tpl create mode 100644 modules/aws/tests/basic/0-setup.tf create mode 100644 modules/aws/tests/basic/1-example.tf create mode 100644 modules/aws/tests/basic/2-assert.tf create mode 100644 modules/aws/tests/basic/README.md create mode 100644 modules/aws/variables.tf create mode 100644 modules/aws/versions.tf create mode 100644 package.json diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..b9723f9 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,8 @@ +version: 2 +updates: + - package-ecosystem: "terraform" + directory: + - ./ + - modules/aws + schedule: + interval: "daily" diff --git a/.github/workflows/checkov.yaml b/.github/workflows/checkov.yaml new file mode 100644 index 0000000..b2200a2 --- /dev/null +++ b/.github/workflows/checkov.yaml @@ -0,0 +1,23 @@ +name: Checkov +on: + pull_request: + push: + branches: [main, master] +jobs: + terraform-validate: + runs-on: ubuntu-latest + strategy: + matrix: + path: + - aws + permissions: + actions: write + contents: write + discussions: write + pull-requests: write + steps: + - uses: dasmeta/reusable-actions-workflows/checkov@main + with: + fetch-depth: 0 + directory: modules/${{ matrix.path }} + continue-on-error: true diff --git a/.github/workflows/pre-commit.yaml b/.github/workflows/pre-commit.yaml new file mode 100644 index 0000000..bfe0a54 --- /dev/null +++ b/.github/workflows/pre-commit.yaml @@ -0,0 +1,22 @@ +name: Pre-Commit +on: + pull_request: + push: + branches: [main, master] +jobs: + terraform-validate: + runs-on: ubuntu-latest + permissions: + actions: write + contents: write + discussions: write + pull-requests: write + steps: + - name: Pre-Commit + uses: dasmeta/reusable-actions-workflows/pre-commit@main + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + path: modules/${{ matrix.path }} + continue-on-error: true diff --git a/.github/workflows/semantic.yaml b/.github/workflows/semantic.yaml new file mode 100644 index 0000000..dc1f956 --- /dev/null +++ b/.github/workflows/semantic.yaml @@ -0,0 +1,21 @@ +name: Semantic-Release +on: [pull_request, push] +jobs: + publish: + runs-on: ubuntu-latest + permissions: + actions: write + contents: write + discussions: write + pull-requests: write + steps: + - uses: actions/checkout@v2 + - name: Setup Node.js + uses: actions/setup-node@v1 + with: + node-version: 16 + - name: Semantic Release + uses: cycjimmy/semantic-release-action@v3 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.github/workflows/terraform-test.yaml b/.github/workflows/terraform-test.yaml new file mode 100644 index 0000000..1e3dfbe --- /dev/null +++ b/.github/workflows/terraform-test.yaml @@ -0,0 +1,26 @@ +name: Terraform Test +on: + pull_request: + push: + branches: [main, master] +jobs: + terraform-validate: + runs-on: ubuntu-latest + strategy: + matrix: + path: + - ./ + - modules/aws + permissions: + actions: write + contents: write + discussions: write + pull-requests: write + steps: + - uses: dasmeta/reusable-actions-workflows/terraform-test@main + with: + aws-region: ${{ secrets.AWS_REGION}} + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + path: ${{ matrix.path }} + continue-on-error: true diff --git a/.github/workflows/tflint.yaml b/.github/workflows/tflint.yaml new file mode 100644 index 0000000..6a023fb --- /dev/null +++ b/.github/workflows/tflint.yaml @@ -0,0 +1,27 @@ +name: Tflint +on: + pull_request: + push: + branches: [main, master] +jobs: + terraform-validate: + runs-on: ubuntu-latest + strategy: + matrix: + path: + - ./ + - modules/aws + permissions: + actions: write + contents: write + discussions: write + pull-requests: write + steps: + - uses: dasmeta/reusable-actions-workflows/tflint@main + with: + aws-region: ${{ secrets.AWS_REGION}} + aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} + aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + path: ${{ matrix.path }} + repo-token: ${{ secrets.GITHUB_TOKEN }} + continue-on-error: true diff --git a/.github/workflows/tfsec.yaml b/.github/workflows/tfsec.yaml new file mode 100644 index 0000000..bb21ea0 --- /dev/null +++ b/.github/workflows/tfsec.yaml @@ -0,0 +1,18 @@ +name: TFSEC +on: + pull_request: + push: + branches: [main, master] +jobs: + terraform-tfsec: + runs-on: ubuntu-latest + permissions: + actions: write + contents: write + discussions: write + pull-requests: write + steps: + - uses: dasmeta/reusable-actions-workflows/tfsec@main + with: + fetch-depth: 0 + continue-on-error: true diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..424d0c1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,39 @@ +# Local .terraform directories +**/.terraform/* + +# .tfstate files +*.tfstate +*.tfstate.* + +# terraform lock files +*.lock.hcl + +# Crash log files +crash.log + +# Ignore any .tfvars files that are generated automatically for each Terraform run. Most +# .tfvars files are managed as part of configuration and so should be included in +# version control. +# +# example.tfvars + +# Ignore override files as they are usually used to override resources locally and so +# are not checked in +override.tf +override.tf.json +*_override.tf +*_override.tf.json + +# Include override files you do wish to add to version control using negated pattern +# +# !example_override.tf + +# Include tfplan files to ignore the plan output of command: terraform plan -out=tfplan +# example: *tfplan* + +.DS_Store +_tfc +.terraform +**/*.tfbackend +**/terraform.tfvars +**/_terraform diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..a4ff632 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,36 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.3.0 + hooks: + - id: check-added-large-files + - id: check-merge-conflict + - id: check-vcs-permalinks + - id: end-of-file-fixer + - id: trailing-whitespace + args: [--markdown-linebreak-ext=md] + exclude: CHANGELOG.md + - id: check-yaml + - id: check-merge-conflict + - id: check-case-conflict + - id: mixed-line-ending + args: [--fix=lf] + - id: detect-aws-credentials + args: ["--allow-missing-credentials"] + - id: detect-private-key + - repo: https://github.com/antonbabenko/pre-commit-terraform + rev: v1.75.0 + hooks: + - id: terraform_fmt + - id: terraform_docs + args: + - --hook-config=--path-to-file=README.md + - --hook-config=--add-to-existing-file=true + - --hook-config=--create-file-if-not-exist=true + - repo: https://github.com/qoomon/git-conventional-commits + rev: v2.4.0 + hooks: + - id: conventional-commits + - repo: https://github.com/zricethezav/gitleaks + rev: v8.12.0 + hooks: + - id: gitleaks diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/commitlint.config.js b/commitlint.config.js new file mode 100644 index 0000000..81c4b92 --- /dev/null +++ b/commitlint.config.js @@ -0,0 +1,5 @@ +module.exports = { + extends: [ + "@commitlint/config-conventional" + ] +} diff --git a/git-conventional-commits.json b/git-conventional-commits.json new file mode 100644 index 0000000..009fca5 --- /dev/null +++ b/git-conventional-commits.json @@ -0,0 +1,41 @@ +{ + "convention" : { + "commitTypes": [ + "feat", + "fix", + "perf", + "refactor", + "style", + "test", + "build", + "ops", + "docs", + "merge", + "chore" + ], + "commitScopes": [], + "releaseTagGlobPattern": "v[0-9]*.[0-9]*.[0-9]*", + "issueRegexPattern": "(^|\\s)#\\d+(\\s|$)" + }, + "changelog" : { + "commitTypes": [ + "feat", + "fix", + "perf", + "merge" + ], + "includeInvalidCommits": true, + "commitScopes": [], + "commitIgnoreRegexPattern": "^WIP ", + "headlines": { + "feat": "Features", + "fix": "Bug Fixes", + "perf": "Performance Improvements", + "merge": "Merged Branches", + "breakingChange": "BREAKING CHANGES" + }, + "commitUrl": "https://github.com/ACCOUNT/REPOSITORY/commit/%commit%", + "commitRangeUrl": "https://github.com/ACCOUNT/REPOSITORY/compare/%from%...%to%?diff=split", + "issueUrl": "https://github.com/ACCOUNT/REPOSITORY/issues/%issue%" + } +} diff --git a/githooks/commit-msg b/githooks/commit-msg new file mode 100755 index 0000000..beaf311 --- /dev/null +++ b/githooks/commit-msg @@ -0,0 +1,86 @@ +#!/bin/bash + +RED='\033[1;31m' +YELLOW='\033[1;33m' +GREEN='\033[1;32m' +NC='\033[0m' + +isNvmOk=false +isYarnOk=false +isNodeOk=false +isGccOk=false + +source ~/.nvm/nvm.sh > /dev/null 2>&1 +nvm -v > /dev/null 2>&1 +if [ ! $? -eq 0 ]; then + mkdir ~/.nvm > /dev/null 2>&1 + (curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash) > /dev/null 2>&1 + + source ~/.nvm/nvm.sh + + if [ `command -v nvm` ]; then + isNvmOk=true + #echo -e "$${GREEN}[ OK ]$${NC} nvm installed successfully" + else + isNvmOk=false + #echo -e "$${RED}[ FAIL ]$${NC} Error during nvm installation" + fi +fi + + +if [ `command -v node` ]; then + isNodeOk=true + #echo -e "$${GREEN}[ OK ]$${NC} npm and node is already installed" +else + #echo -e "$${YELLOW}[ WAIT ]$${NC} npm is not installed.. installing" + nvm install node > /dev/null 2>&1 + if [ `command -v node` ] && [ `command -v npm` ]; then + isNodeOk=true + #echo -e "$${GREEN}[ OK ]$${NC} npm installed successfully" + fi + +# mkdir ~/.npm-global > /dev/null 2>&1 +# npm config set prefix '~/.npm-global' > /dev/null 2>&1 +# export PATH=~/.npm-global/bin:$PATH > /dev/null 2>&1 +# source ~/.profile > /dev/null 2>&1 + +fi + + +if [ `command -v yarn` ]; then + isYarnOk=true + #echo -e "$${GREEN}[ OK ]$${NC} Yarn already installed" + +else + rm -rf ~/.yarn + (curl -o- -L https://yarnpkg.com/install.sh | bash) > /dev/null 2>&1 + export PATH="$HOME/.yarn/bin:$PATH" + yarn config set prefix ~/.yarn -g > /dev/null 2>&1 + + if [ `command -v yarn` ]; then + isYarnOk=true + # echo $yarn_result + # echo -e "$${GREEN}[ OK ]$${NC} Yarn installed successfully" + fi +fi + +#echo -e "$${GREEN}[ OK ]$${NC}" nvm cache clear --force + +PATH="/c/Program Files/nodejs:$HOME/AppData/Roaming/npm/:$PATH" + +npm install --global git-conventional-commits > /dev/null 2>&1 +if [ $? -eq 0 ]; then + isGccOk=true + # echo -e "$${GREEN}[ OK ]$${NC} git-conventional-commit successfully installed" + else + isGccOk=false + # echo -e "$${RED}[ FAIL ]$${NC} Error during installation of git-conventional-commit" +fi + +git-conventional-commits commit-msg-hook "$1" + +if [[ $isNodeOk && $isYarnOk && $isNvmOk && $isNodeOk ]]; then + echo -e "$${GREEN}[ OK ]$${NC} Dependencies installed successfully" +else + echo -e "$${RED}[ FAIL ]$${NC} Error during dependency installation" +fi diff --git a/githooks/pre-commit b/githooks/pre-commit new file mode 100755 index 0000000..06baba8 --- /dev/null +++ b/githooks/pre-commit @@ -0,0 +1,5 @@ +#!/bin/bash + +set -e + +pre-commit run --show-diff-on-failure --color=always --all-files diff --git a/modules/aws/README.md b/modules/aws/README.md new file mode 100644 index 0000000..3aad88e --- /dev/null +++ b/modules/aws/README.md @@ -0,0 +1,87 @@ +# aws ec2 wireguard setup + +The module allows to create/configure wireguard VPN server and clients. To install wireguard check here: https://www.wireguard.com/install/ + +Examples can found in [tests](tests) folder, + + +NOTES: + +1. server and client public/private keys generation (please generate separate public/private key pairs for server and each client) + + a. for linux and cli use wg cli tool: + ```sh + # for server key fi + wg genkey > privatekey-server + wg pubkey < privatekey-server > publickey-server + + wg genkey > privatekey-client1 + wg pubkey < privatekey-client1 > publickey-client1 + ``` + you need only key values to pass to module so that you can remove generated private/public keys as soon as you copy keys to module params + + b. for macOS and windows you can also use gui, check GUI app corresponding docs + +2. get and usa clients configs + +There is module output named client_config and it contains each client wireguard config file which needs to be set in clients laptop/machine + + a. for linux cli: `/etc/wireguard/wg0.conf` path(the filename can be custom, but should be with extension .conf) if you use wg-quick cli, create this path and file if not exist, the file should be owned by root and you will probably need to switch to root (sudo su). in order to start/stop connection switch to root user and run `wg-quick up wg0` and `wg-quick down wg0` + + b. for mac os and windows gui: you can import it from wireguard program GUI, there should be option to set name and start/stop connection + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.3.0 | +| [aws](#requirement\_aws) | >= 4.16 | + +## Providers + +| Name | Version | +|------|---------| +| [aws](#provider\_aws) | >= 4.16 | + +## Modules + +No modules. + +## Resources + +| Name | Type | +|------|------| +| [aws_eip.this](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/eip) | resource | +| [aws_eip_association.this](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/eip_association) | resource | +| [aws_instance.this](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance) | resource | +| [aws_security_group.wireguard](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/security_group) | resource | +| [aws_ami.ubuntu](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/ami) | data source | +| [aws_subnets.public_subnets](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/subnets) | data source | + +## Inputs + +| Name | Description | Type | Default | Required | +|------|-------------|------|---------|:--------:| +| [clients](#input\_clients) | Wireguard clients/peers list with configs |
list(object({
name = string # should be unique in list
ip = string # client uniq IP form var.network_cidr range in cidr format, TODO: we maybe can automate this IP creation inside module
route_ip_ranges = string # comma separated IP ranges that the client should route via the VPN in format "1.2.3.4/32,1.1.1.1/16", set "0.0.0.0/0" to route all traffic through VPN
public_key = string # public key of client/peer, both private and public keys can be generated by using wg cli and client private key: `wg pubkey < privatekey-client1 > publickey-client1`, # TODO: we probably need to have this set as sensitive
private_key = optional(string, "{client-private-key}") # client private key, pass in case you want to get fully prepared to use client_configs output, can be generated using wg cli: `wg genkey > privatekey-client1`
}))
| `[]` | no | +| [dns](#input\_dns) | Custom DNS server | `string` | `null` | no | +| [ingress](#input\_ingress) | The IPs/CIDRs from where the instance wireguard and ssh port are open to connect | `list(any)` |
[
"0.0.0.0/0"
]
| no | +| [instance\_type](#input\_instance\_type) | The wireguard server machine instance type | `string` | `"t2.micro"` | no | +| [keep\_alive](#input\_keep\_alive) | CLients peer connection persistance keep alive config | `number` | `25` | no | +| [name](#input\_name) | The name to use of instance/machine | `string` | n/a | yes | +| [network\_cidr](#input\_network\_cidr) | Wireguard network CIDR which should not overlap with local/server networks | `string` | `"10.11.11.0/24"` | no | +| [server\_port](#input\_server\_port) | Wireguard server port number | `number` | `51820` | no | +| [server\_private\_key](#input\_server\_private\_key) | Wireguard server private key, which can be generated using wg cli tool: `wg genkey > privatekey-server` | `string` | n/a | yes | +| [server\_public\_key](#input\_server\_public\_key) | Wireguard server public key, which can be generated using wg cli tool and server private key: `wg pubkey < privatekey-server > publickey-server` | `string` | n/a | yes | +| [ssh\_key\_name](#input\_ssh\_key\_name) | The ssh key to attach to instances | `string` | `null` | no | +| [ubuntu\_version](#input\_ubuntu\_version) | The version of ubuntu to use | `string` | `"ubuntu-focal-20.04"` | no | +| [vpc\_id](#input\_vpc\_id) | The vpc id | `string` | n/a | yes | +| [vpc\_subnet\_additional\_filter](#input\_vpc\_subnet\_additional\_filter) | Additional filters to get subnet under vpc, where instance will be created | `list(any)` |
[
{
"name": "map-public-ip-on-launch",
"values": [
true
]
}
]
| no | + +## Outputs + +| Name | Description | +|------|-------------| +| [client\_configs](#output\_client\_configs) | The client configs to copy/set in their laptops/machines /etc/wireguard/wg0.conf file | +| [debug](#output\_debug) | n/a | +| [public\_ip](#output\_public\_ip) | n/a | + diff --git a/modules/aws/data.tf b/modules/aws/data.tf new file mode 100644 index 0000000..df808c3 --- /dev/null +++ b/modules/aws/data.tf @@ -0,0 +1,26 @@ +# get vpc public subnets by vpc id and additional filtration +data "aws_subnets" "public_subnets" { + filter { + name = "vpc-id" + values = [var.vpc_id] + } + + dynamic "filter" { + for_each = var.vpc_subnet_additional_filter + + content { + name = filter.value.name + values = filter.value.values + } + } +} + +# Lookup the AMI instance that corresponds to a Ubuntu server +data "aws_ami" "ubuntu" { + most_recent = true + filter { + name = "name" + values = ["ubuntu/images/hvm-ssd/${var.ubuntu_version}-amd64-server-*"] + } + owners = ["099720109477"] # Canonical +} diff --git a/modules/aws/main.tf b/modules/aws/main.tf new file mode 100644 index 0000000..3726310 --- /dev/null +++ b/modules/aws/main.tf @@ -0,0 +1,62 @@ +# Create a security group that allows access to the EC2 instance +resource "aws_security_group" "wireguard" { + name = "${var.name}-vpn" + description = "Wireguard security group Communication to and from VPC endpoint" + vpc_id = var.vpc_id + + ingress { + from_port = var.server_port + to_port = var.server_port + protocol = "udp" + cidr_blocks = var.ingress + } + + dynamic "ingress" { + for_each = var.ssh_key_name != null ? [1] : [] + + content { + from_port = 22 + to_port = 22 + protocol = "tcp" + cidr_blocks = var.ingress + } + } + + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } +} + +# Provision wireguard server instance +resource "aws_instance" "this" { + ami = data.aws_ami.ubuntu.id + instance_type = var.instance_type + subnet_id = data.aws_subnets.public_subnets.ids[0] # if no subnet found to use for instance and it fails here, check if you have public subnet in passed vpc and/or check var.vpc_subnet_additional_filter to alter additional filtration + vpc_security_group_ids = [aws_security_group.wireguard.id] + key_name = var.ssh_key_name + user_data_replace_on_change = true + + user_data = templatefile("${path.module}/templates/wireguard-server-init.sh.tpl", { + network_cidr = var.network_cidr + server_port = var.server_port + server_private_key = var.server_private_key + server_public_key = var.server_public_key + clients = var.clients + }) + + tags = { + Name = var.name + } +} + +# create static/elastic IP and attach to wireguard server instance +resource "aws_eip" "this" { + vpc = true +} +resource "aws_eip_association" "this" { + instance_id = aws_instance.this.id + allocation_id = aws_eip.this.id +} diff --git a/modules/aws/output.tf b/modules/aws/output.tf new file mode 100644 index 0000000..fdf3e31 --- /dev/null +++ b/modules/aws/output.tf @@ -0,0 +1,21 @@ +output "public_ip" { + value = aws_eip.this.public_ip +} + +output "client_configs" { + value = { for client in var.clients : client.name => templatefile("${path.module}/templates/wireguard-client.conf.tpl", { + client_private_key = client.private_key + client_ip = client.ip + route_ip_ranges = client.route_ip_ranges + dns = var.dns + server_public_ip = aws_eip.this.public_ip + server_port = var.server_port + server_public_key = var.server_public_key + keep_alive = var.keep_alive + }) } + description = "The client configs to copy/set in their laptops/machines /etc/wireguard/wg0.conf file" +} + +output "debug" { + value = data.aws_subnets.public_subnets +} diff --git a/modules/aws/templates/wireguard-client.conf.tpl b/modules/aws/templates/wireguard-client.conf.tpl new file mode 100644 index 0000000..812609d --- /dev/null +++ b/modules/aws/templates/wireguard-client.conf.tpl @@ -0,0 +1,13 @@ +[Interface] +PrivateKey = ${client_private_key} +%{ if dns != null ~} +DNS = ${dns} +%{ endif ~} + +Address = ${client_ip} + +[Peer] +Endpoint = ${server_public_ip}:${server_port} +PublicKey = ${server_public_key} +PersistentKeepalive = ${keep_alive} +AllowedIPs = ${route_ip_ranges} diff --git a/modules/aws/templates/wireguard-server-init.sh.tpl b/modules/aws/templates/wireguard-server-init.sh.tpl new file mode 100644 index 0000000..6d60210 --- /dev/null +++ b/modules/aws/templates/wireguard-server-init.sh.tpl @@ -0,0 +1,36 @@ +#!/bin/bash -v + +echo "Wireguard setup started!" > /note.txt + +# install wireguard and neded tools +apt update && apt -y install net-tools wireguard + +# create wireguard server configuration file +mkdir -p /etc/wireguard +cat > /etc/wireguard/wg0.conf <<- EOF +[Interface] +Address = ${network_cidr} +ListenPort = ${server_port} +PrivateKey = ${server_private_key} +PostUp = sysctl -w -q net.ipv4.ip_forward=1 +PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o ENI -j MASQUERADE +PostDown = sysctl -w -q net.ipv4.ip_forward=0 +PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o ENI -j MASQUERADE + +%{ for client in clients } +[Peer] +# ${client.name} +PublicKey = ${client.public_key} +AllowedIPs = ${client.ip} +%{ endfor ~} + +EOF + +# Make sure we replace the "ENI" placeholder with the actual network interface name +export ENI=$(ip route get 8.8.8.8 | grep 8.8.8.8 | awk '{print $5}') +sed -i "s/ENI/$ENI/g" /etc/wireguard/wg0.conf + +# Launch the WireGuard server +wg-quick up wg0 +systemctl enable wg-quick@wg0 +echo "Wireguard setup finished!" >> /note.txt diff --git a/modules/aws/tests/basic/0-setup.tf b/modules/aws/tests/basic/0-setup.tf new file mode 100644 index 0000000..9c76587 --- /dev/null +++ b/modules/aws/tests/basic/0-setup.tf @@ -0,0 +1,24 @@ +terraform { + required_providers { + test = { + source = "terraform.io/builtin/test" + } + + aws = { + source = "hashicorp/aws" + version = ">= 3.41" + } + } + + required_version = ">= 1.3.0" +} + +/** + * set the following env vars so that aws provider will get authenticated before apply: + + export AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxxxxxxxxxxx + export AWS_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxxxxxxxxxxx +*/ +provider "aws" { + region = "eu-central-1" +} diff --git a/modules/aws/tests/basic/1-example.tf b/modules/aws/tests/basic/1-example.tf new file mode 100644 index 0000000..d8b8a31 --- /dev/null +++ b/modules/aws/tests/basic/1-example.tf @@ -0,0 +1,20 @@ +module "this" { + source = "../../" + + name = "wireguard-test-2" + vpc_id = "vpc-046effd7e14742653" + ssh_key_name = "wireguard-test-2" + + server_private_key = "CEXfZgx+G/rzVOawGWaMhFYKkMeTqI0BSr99Shbeb28=" + server_public_key = "6sPQH8RvnPmS8vGUpF050/S+PZu4yYQFowF1WAga7xg=" + + clients = [ + { + name = "client1" + public_key = "lJd5CessDQ9eay8sUEA15/rNl+6eNcbaTT/jnQ2qhig=" + private_key = "eDWDX79XqXxK0nHwuvxq/yrp0tntk5ASKW8FeRTgBnQ=" + ip = "10.11.11.1/32" + route_ip_ranges = "34.160.111.145/32" # this is ifconfig.me website/service ip with show requester IP, check things after apply by using command `curl ifconfig.me` + } + ] +} diff --git a/modules/aws/tests/basic/2-assert.tf b/modules/aws/tests/basic/2-assert.tf new file mode 100644 index 0000000..99458ca --- /dev/null +++ b/modules/aws/tests/basic/2-assert.tf @@ -0,0 +1,9 @@ +resource "test_assertions" "dummy" { + component = "this" + + equal "scheme" { + description = "As module does not have any output and data just make sure the case runs. Probably can be thrown away." + got = "all good" + want = "all good" + } +} diff --git a/modules/aws/tests/basic/README.md b/modules/aws/tests/basic/README.md new file mode 100644 index 0000000..08dd597 --- /dev/null +++ b/modules/aws/tests/basic/README.md @@ -0,0 +1,36 @@ +# basic + + +## Requirements + +| Name | Version | +|------|---------| +| [terraform](#requirement\_terraform) | >= 1.3.0 | +| [aws](#requirement\_aws) | >= 3.41 | + +## Providers + +| Name | Version | +|------|---------| +| [test](#provider\_test) | n/a | + +## Modules + +| Name | Source | Version | +|------|--------|---------| +| [this](#module\_this) | ../../ | n/a | + +## Resources + +| Name | Type | +|------|------| +| test_assertions.dummy | resource | + +## Inputs + +No inputs. + +## Outputs + +No outputs. + diff --git a/modules/aws/variables.tf b/modules/aws/variables.tf new file mode 100644 index 0000000..f00b874 --- /dev/null +++ b/modules/aws/variables.tf @@ -0,0 +1,90 @@ +variable "name" { + type = string + description = "The name to use of instance/machine" +} + +variable "vpc_id" { + type = string + description = "The vpc id" +} + +variable "server_private_key" { # TODO: we probably need to have this set as sensitive + type = string + description = "Wireguard server private key, which can be generated using wg cli tool: `wg genkey > privatekey-server`" +} + +variable "server_public_key" { + type = string + description = "Wireguard server public key, which can be generated using wg cli tool and server private key: `wg pubkey < privatekey-server > publickey-server`" +} + +variable "network_cidr" { + type = string + default = "10.11.11.0/24" # client/peer valid IPs for this default value are in range 10.11.11.1 - 10.11.11.255 + description = "Wireguard network CIDR which should not overlap with local/server networks" +} + +variable "clients" { + type = list(object({ + name = string # should be unique in list + ip = string # client uniq IP form var.network_cidr range in cidr format, TODO: we maybe can automate this IP creation inside module + route_ip_ranges = string # comma separated IP ranges that the client should route via the VPN in format "1.2.3.4/32,1.1.1.1/16", set "0.0.0.0/0" to route all traffic through VPN + public_key = string # public key of client/peer, both private and public keys can be generated by using wg cli and client private key: `wg pubkey < privatekey-client1 > publickey-client1`, # TODO: we probably need to have this set as sensitive + private_key = optional(string, "{client-private-key}") # client private key, pass in case you want to get fully prepared to use client_configs output, can be generated using wg cli: `wg genkey > privatekey-client1` + })) + default = [] + description = "Wireguard clients/peers list with configs" +} + +variable "ubuntu_version" { + type = string + description = "The version of ubuntu to use" + default = "ubuntu-focal-20.04" +} + +variable "instance_type" { + type = string + default = "t2.micro" + description = "The wireguard server machine instance type" +} + +variable "server_port" { + type = number + default = 51820 + description = "Wireguard server port number" +} + +variable "dns" { + type = string + default = null + description = "Custom DNS server" +} + +variable "keep_alive" { + type = number + default = 25 + description = "CLients peer connection persistance keep alive config" +} + +variable "ssh_key_name" { + type = string + default = null + description = "The ssh key to attach to instances" +} + +variable "ingress" { + type = list(any) + default = ["0.0.0.0/0"] # default to all + description = "The IPs/CIDRs from where the instance wireguard and ssh port are open to connect" +} + +variable "vpc_subnet_additional_filter" { + type = list(any) + default = [ + { + name = "map-public-ip-on-launch" # to filter public subnets + values = [true] + } + ] + description = "Additional filters to get subnet under vpc, where instance will be created" +} diff --git a/modules/aws/versions.tf b/modules/aws/versions.tf new file mode 100644 index 0000000..0f4be67 --- /dev/null +++ b/modules/aws/versions.tf @@ -0,0 +1,10 @@ +terraform { + required_version = ">= 1.3.0" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 4.16" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..1782661 --- /dev/null +++ b/package.json @@ -0,0 +1,22 @@ +{ + "name": "app", + "devDependencies": { + "@commitlint/cli": "^17.0.3", + "@commitlint/config-conventional": "^17.0.3", + "husky": "^8.0.1", + "@semantic-release/github": "^8.0.4", + "semantic-release": "^19.0.3" + }, + "release": { + "branches": [ + "main", "master", "next" + ] + }, + "private": true, + "plugins": [ + "@semantic-release/commit-analyzer", + "@semantic-release/release-notes-generator", + "@semantic-release/github", + "@semantic-release/npm" + ] +}