Compare commits

..

15 Commits

Author SHA1 Message Date
Калинин Сергей Валерьевич
c4ded33507 Добавлена работа с файлами. Добавлен показ изображений и загрузка файлов. Изменен дизайн 2025-07-21 13:10:19 +03:00
svk
10c9635894 Обновить vault.go 2024-10-28 16:09:39 +03:00
Калинин Сергей Валерьевич
7ecdf7a606 Добавлена возможность шифровать данные (wrap).
Добавлена установка времени жизни токена (TTL).
Добавлено соответствие ограничения длины пароля и длины текста для шифрования.
Добавлена подготовка токена к расшифровке (ограничение длины, удаление пробельных символов).
2024-10-28 16:03:45 +03:00
svk
41e1a553f6 Обновить README.md 2024-10-17 15:08:06 +03:00
Калинин Сергей Валерьевич
897bb3de01 Добавлена поддержка wrap 2024-10-17 15:04:35 +03:00
svkalinin
ee921f6ae3 Переезд на другой сервер 2024-07-17 13:01:33 +03:00
svkalinin
f4c2f619d2 vault-wrap: Закрыл порты в контейнере 2024-07-11 14:43:37 +03:00
svkalinin
7fd90ff2ab vault-wrap: Причесал код. 2024-07-11 12:06:57 +03:00
svkalinin
9da7132bf1 vault-wrap: Исправление показа данных из других сессий 2024-07-11 10:41:34 +03:00
svkalinin
cb4aa3e23c vault-wrap: исправление шаблона. 2024-07-11 10:22:30 +03:00
svkalinin
518c90fccb vault-wrap: исправление шаблона. 2024-07-11 10:07:23 +03:00
svkalinin
09b72f89bb vault-wrap: исправление шаблона. 2024-07-11 10:05:44 +03:00
svkalinin
de8dc18eff vault-wrap: fix 2024-07-11 10:01:31 +03:00
svkalinin
62678531f4 vault-wrap: Рабочий вариант. INF-1541 2024-07-11 09:54:16 +03:00
svkalinin
33f90e5e02 vault-wrap: мучения продолжаются 2024-07-11 09:36:37 +03:00
10 changed files with 682 additions and 313 deletions

View File

@@ -1,95 +0,0 @@
stages:
- build
- release
- deploy
variables:
DOCKER_DRIVER: overlay2
IMAGE_PATH: $CI_REGISTRY/$CI_PROJECT_PATH
# IMAGE_VERSION: $CI_COMMIT_SHORT_SHA
RELEASE_VERSION: $CI_COMMIT_SHORT_SHA
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
- mkdir -p .ci_status
.dedicated-builder: &dedicated-builder
tags:
- build1-shell
.dedicated-runner: &dedicated-runner
tags:
- runner1-prod-shell
vault_wrap_build:
<<: *dedicated-builder
stage: build
script:
- DOCKER_BUILDKIT=1 COMPOSE_DOCKER_CLI_BUILD=1 docker-compose -f docker-compose.yml build vault-wrap
- docker tag $IMAGE_PATH/vault-wrap:$RELEASE_VERSION $IMAGE_PATH/vault-wrap:dev
- docker push $IMAGE_PATH/vault-wrap:dev
- touch .ci_status/vault_wrap_build
only:
refs:
- main
changes:
- vault-wrap.go
- Dockerfile
- entrypoint.sh
- docker-compose.yml
- .gitlab-ci.yml
artifacts:
paths:
- .ci_status/
# --------------- RELEASE STAGE -------------#
vault_wrap_release:
<<: *dedicated-builder
stage: release
script:
- if [ -e .ci_status/vault_wrap_build ]; then docker pull $IMAGE_PATH/vault-wrap:dev; docker tag $IMAGE_PATH/vault-wrap:dev $IMAGE_PATH/vault-wrap:$RELEASE_VERSION; docker push $IMAGE_PATH/vault-wrap:$RELEASE_VERSION; touch .ci_status/vault_wrap_release; fi
artifacts:
paths:
- .ci_status/
only:
refs:
- main
#-------------- DEPLOY STAGE ------------------#
vault_wrap_deploy:
<<: *dedicated-runner
stage: deploy
script:
- docker volume create vault-wrap_vault-wrap-conf
- docker run --rm -v vault-wrap_vault-wrap-conf:/temporary -v /etc/ssl/certs/:/files alpine cp files/runner1-prod.corp.samsonopt.ru.crt /temporary
- docker run --rm -v vault-wrap_vault-wrap-conf:/temporary -v /etc/ssl/private/:/files alpine cp files/runner1-prod.corp.samsonopt.ru.key /temporary
- docker run --rm -v vault-wrap_vault-wrap-conf:/temporary -v ./html-template/index.html:/files alpine cp files/index.html /temporary
# -cp /etc/ssl/certs/runner1-prod.corp.samsonopt.ru.crt /srv/docker/volumes/vault-wrap_vault-wrap-conf/_data/
# - cp /etc/ssl/private/runner1-prod.corp.samsonopt.ru.key /srv/docker/volumes/vault-wrap_vault-wrap-conf/_data/
- export TLS_CERT_FILE=runner1-prod.corp.samsonopt.ru.crt
- export TLS_KEY_FILE=runner1-prod.corp.samsonopt.ru.key
- if [ -e .ci_status/vault_wrap_release ]; then docker-compose -f docker-compose.yml up -d vault-wrap; fi
only:
refs:
- main
# traefik_deploy:
# <<: *dedicated-runner
# stage: deploy
# script:
# - mkdir -p /home/gitlab-runner/traefik
# - docker volume create vault-wrap_traefik-ssl
# - docker volume create vault-wrap_traefik-dynamic-conf
# - docker run --rm -v vault-wrap_traefik-ssl:/temporary -v /etc/ssl/certs/:/files alpine cp files/runner1-prod.corp.samsonopt.ru.crt /temporary
# - docker run --rm -v vault-wrap_traefik-ssl:/temporary -v /etc/ssl/private/:/files alpine cp files/runner1-prod.corp.samsonopt.ru.key /temporary
# - docker run --rm -v vault-wrap_traefik-dynamic-conf:/temporary -v ./traefik-files:/files alpine cp files/certificates.yml /temporary
# - cp traefik-files/traefik.yml /home/gitlab-runner/traefik/traefik.yml
# - export TLS_CERT_FILE=runner1-prod.corp.samsonopt.ru.crt
# - export TLS_KEY_FILE=runner1-prod.corp.samsonopt.ru.key
# - if [ -e .ci_status/vault_wrap_release ]; then docker-compose -f docker-compose.yml up -d traefik; fi
# only:
# refs:
# - main

106
README.md
View File

@@ -1,93 +1,39 @@
# Vault Wrap
# Vault Wrap/Unwrap
ВЭБ-интерфейс к сервису Hashicorp Vault wrap/unwrap для безопасной передачи секретов. Также генератор паролей.
## Запуск
## Getting started
Сервис можно запускать как с командной строки так и в docker-контейнере
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
Запуск с доступом по https (использование TLS/SSL):
```
cd existing_repo
git remote add origin https://gitlab.corp.samsonopt.ru/infosystems/vault-wrap.git
git branch -M main
git push -uf origin main
vault-wrap -action-address "https://secret.example.ru:8443" -vault-url "https://vault.example.ru:8200" -tls-cert cert.pem -tls-key privaty.key -listen-port 8443 -tls
```
## Integrate with your tools
Запуск с доступом по http:
```
vault-wrap -action-address "http://secret.example.ru:8080" -vault-url "https://vault.example.ru:8200" -tls-cert cert.pem -tls-key privaty.key -listen-port 8080
```
- [ ] [Set up project integrations](https://gitlab.corp.samsonopt.ru/infosystems/vault-wrap/-/settings/integrations)
Если сервис запущен за обратным прокси, то в качестве адреса сервиса -action-address требуется указать адрес прокси, т.е. адрес (FQDN) на который будут приходить запросы.
## Collaborate with your team
Для работы шифрования (wrap) нужен vault токен с доступом к vault wrap/unwrap. Токен задается через переменную окружения VAULT_TOKEN.
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Ключи командной строки
## Test and Deploy
- action-address string - Адрес данного сервиса (https://secret.example.ru). Адрес который будет подставляться в форму в html-шаблон
- debug - Вывод отладочных сообщений
- listen-port string - Номер порта сервиса (default "8080")
- log-file string - Путь до лог-файла (default "vault-unwrap.log")
- max-text-length - Максимальная длина текста для шифрования и длина пароля для генератора (default 100)
- template-dir string -Каталог с шаблонами (default "html-template")
- template-file string Файл-шаблон для ВЭБ-странцы (default "index.html")
- tls - Использовать SSL/TLS
- tls-cert string - TLS сертификат (полный путь к файлу)
- tls-key string - TLS ключ (полный путь к файлу)
- token-ttl - Время жизни wrap-токена в секундах (default "3600")
- vault-url string - Адрес сервера Hashicorp Vault (https://host.name:8200)
- help - Вывод справочной информации
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

View File

@@ -6,15 +6,18 @@ services:
image: $IMAGE_PATH/vault-wrap:$RELEASE_VERSION
container_name: vault-wrap
environment:
- ACTION_ADDRESS=${ACTION_ADDRESS:-secret.corp.samsonopt.ru}
- ACTION_ADDRESS=${ACTION_ADDRESS:-https://secret.example.ru}
- VAULT_ADDRESS=${VAULT_ADDRESS}
- LISTEN_PORT=1234
- VAULT_TOKEN=${WRAP_TOKEN}
- LISTEN_PORT=8080
- TLS_KEY_FILE=${TLS_KEY_FILE}
- TLS_CERT_FILE=${TLS_CERT_FILE}
- TZ=Europe/Moscow
- MAX_TEXT_LENGTH=${MAX_TEXT_LENGTH:-100}
- TOKEN_TTL=${TOKEN_TTL:-3600}
restart: always
ports:
- 1234:1234
# ports:
# - 1234:8080
build:
context: .
volumes:
@@ -27,8 +30,8 @@ services:
max-file: "5"
labels:
- "traefik.enable=true"
- "traefik.http.routers.secret.rule=Host(`secret.corp.samsonopt.ru`)"
- "traefik.http.services.secret.loadbalancer.server.port=1234"
- "traefik.http.routers.secret.rule=Host(`secret.example.ru`)"
- "traefik.http.services.secret.loadbalancer.server.port=8080"
- "traefik.docker.network=reverse-proxy"
- "traefik.http.routers.secret.tls=true"
- "traefik.http.services.secret.loadbalancer.server.scheme=http"
@@ -61,7 +64,7 @@ services:
labels:
- "traefik.enable=true"
- "traefik.http.routers.traefik.entrypoints=https"
- "traefik.http.routers.traefik.rule=Host(`runner1-prod.corp.samsonopt.ru`)"
- "traefik.http.routers.traefik.rule=Host(`example.ru`)"
- "traefik.http.routers.traefik.tls=true"
# - "traefik.http.routers.traefik.tls.certresolver=letsEncrypt"
- "traefik.http.routers.traefik.service=api@internal"

View File

@@ -3,6 +3,6 @@ set -u
while true ;do
# /go/bin/vault-wrap -action-address "${ACTION_ADDRESS}" -vault-url "${VAULT_ADDRESS}" -tls-cert "/usr/local/share/vault-wrap/${TLS_CERT_FILE}" -tls-key "/usr/local/share/vault-wrap/${TLS_KEY_FILE}" -template-dir /usr/local/share/vault-wrap -log-file /var/log/vault-wrap/vault-wrap.log -listen-port "${LISTEN_PORT}" -tls
/go/bin/vault-wrap -action-address "${ACTION_ADDRESS}" -template-dir /usr/local/share/vault-wrap -log-file /var/log/vault-wrap/vault-wrap.log
/go/bin/vault-wrap -action-address "${ACTION_ADDRESS}" -template-dir /usr/local/share/vault-wrap -log-file /var/log/vault-wrap/vault-wrap.log -token-ttl ${TOKEN_TTL}
sleep 120
done

View File

@@ -0,0 +1,78 @@
<!DOCTYPE html>
<html>
<head>
<title>{{.Title}}</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f9f9f9;
}
.file-container {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
margin-bottom: 20px;
}
img {
max-width: 100%;
height: auto;
margin: 20px 0;
}
.file-info {
margin-top: 20px;
padding: 15px;
background: #f5f5f5;
border-radius: 5px;
}
.download-btn {
display: inline-block;
padding: 10px 20px;
background: #4CAF50;
color: white;
text-decoration: none;
border-radius: 5px;
margin: 10px;
}
.action-btn {
display: inline-block;
padding: 10px 20px;
background: #f0f0f0;
color: #333;
text-decoration: none;
border-radius: 5px;
margin: 10px;
}
</style>
</head>
<body>
<div class="file-container">
<h1>{{.Title}}</h1>
{{if .IsImage}}
<img src="data:{{.MimeType}};base64,{{.Base64Data}}" alt="File preview">
{{else}}
<div class="file-info">
<p>Этот файл не может быть отображен в браузере</p>
</div>
{{end}}
<div class="file-info">
<p><strong>Тип файла:</strong> {{.MimeType}}</p>
<p><strong>Размер:</strong> {{.FileSize}} KB</p>
<p><strong>Имя файла:</strong> {{.FileName}}</p>
<a href="data:{{.MimeType}};base64,{{.Base64Data}}"
class="download-btn"
download="{{.FileName}}">
Скачать файл
</a>
<a href="/" class="action-btn">На главную</a>
<a href="javascript:history.back()" class="action-btn">Назад</a>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,57 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Unwrap Form</title>
<style>
textarea { width: 100%; max-width: 500px; }
table { border-collapse: collapse; }
hr { margin: 15px 0; }
</style>
</head>
<body>
<table>
<!-- Форма для wrap/unwrap текста -->
<tr><td>
<form method="post" action="{{.URL}}/wrap">
<table>
<tr><td>Введите текст или токен:</td></tr>
<tr><td>
<textarea name="input_token" cols="50" rows="10" maxlength="{{.MAXTEXTLENGTH}}">{{.TEXT}}</textarea>
</td></tr>
<tr><td align="right">
<button type="submit">Зашифровать</button>
<button type="submit" formaction="{{.URL}}/unwrap">Расшифровать</button>
</td></tr>
</table>
</form>
</td></tr>
<tr><td><hr></td></tr>
<!-- Отдельная форма для загрузки файла -->
<tr><td>
<form method="post" action="{{.URL}}/wrapfile" enctype="multipart/form-data">
<input type="file" name="file" id="file" required>
<button type="submit">Зашифровать файл</button>
</form>
</td></tr>
<tr><td><hr></td></tr>
<!-- Форма для генерации пароля -->
<tr><td>
<form method="post" action="{{.URL}}/genpassword">
<table>
<tr><td align="right">
Длина пароля (от 15 до {{.MAXTEXTLENGTH}}):
<input type="number" name="passlength" min="15" max="{{.MAXTEXTLENGTH}}" value="32">
<button type="submit">Сгенерировать пароль</button>
</td></tr>
</table>
</form>
</td></tr>
</table>
</body>
</html>

View File

@@ -1,35 +1,206 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Unwrap Form</title>
</head>
<body>
<table>
<tr><td>
<!-- <a href={{.URL}}/unwrap>Расшифровать</a> |
<a href={{.URL}}/genpassword>Сгенерировать пароль</a>-->
<tr><td><p></p></td></tr>
<tr><td>
<form method="post">
<table>
<tr><td>
<textarea id="wrapped_token" name="input_token" cols=50 rows=10>{{ .TEXT }}</textarea>
</td></tr>
<tr><td align=right>
<button type="submit" formaction="{{.URL}}/unwrap">Расшифровать</button>
<tr><td><hr></td></tr>
</td></tr>
<tr><td align=right>
Длина пароля (от 15 до 1024)
<input type="text" name="passlength"/ size=4 pattern="[0-9]{2,4}">
<button type="submit" formaction="{{.URL}}/genpassword">Сгенерировать пароль</button>
</td></tr>
</form>
</td></tr>
<tr><td>
</td></tr>
</table>
</body>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Wrap/Unwrap Form</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f9f9f9;
display: flex;
flex-direction: column;
min-height: 100vh;
box-sizing: border-box; /* Добавлено */
}
.content {
flex: 1;
padding-bottom: 20px; /* Добавлено */
}
.form-container {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
margin-bottom: 15px; /* Уменьшено */
}
h1 {
color: #333;
text-align: center;
margin-bottom: 25px; /* Уменьшено */
font-size: 1.8em; /* Добавлено */
}
textarea {
width: 100%;
max-width: 100%;
min-height: 120px; /* Уменьшено */
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-family: monospace;
resize: vertical;
box-sizing: border-box; /* Добавлено */
}
input[type="file"] {
margin: 8px 0; /* Уменьшено */
width: 100%; /* Добавлено */
}
input[type="number"] {
width: 60px;
padding: 5px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
padding: 8px 16px;
background: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin: 4px; /* Уменьшено */
transition: background 0.3s;
}
button:hover {
background: #45a049;
}
hr {
border: 0;
height: 1px;
background: #ddd;
margin: 15px 0; /* Уменьшено */
}
.form-title {
font-weight: bold;
margin-bottom: 8px; /* Уменьшено */
color: #555;
font-size: 0.95em; /* Добавлено */
}
.button-group {
text-align: right;
margin-top: 8px; /* Уменьшено */
}
footer {
text-align: center;
padding: 12px 0;
color: #777;
font-size: 0.85em; /* Уменьшено */
border-top: 1px solid #eee;
background: white;
margin-top: auto; /* Важно для прижатия */
position: sticky;
bottom: 0;
}
.footer-links {
margin-top: 6px; /* Уменьшено */
}
.footer-links a {
color: #4CAF50;
text-decoration: none;
margin: 0 6px; /* Уменьшено */
font-size: 0.85em; /* Уменьшено */
}
.footer-links a:hover {
text-decoration: underline;
}
@media (max-width: 600px) {
body {
padding: 15px;
}
.form-container {
padding: 15px;
}
h1 {
font-size: 1.5em;
margin-bottom: 20px;
}
button {
padding: 6px 12px;
font-size: 0.9em;
}
.btn-link {
background: #9C27B0;
}
.btn-link:hover {
background: #7B1FA2;
}
}
</style>
</head>
<body>
<div class="content">
<!-- <h1>Сервис передачи секретов</h1> -->
<div class="form-container">
<div class="form-title">Введите текст или токен:</div>
<form method="post" action="{{.URL}}/wrap">
<textarea id="tokenTextarea" name="input_token" maxlength="{{.MAXTEXTLENGTH}}" placeholder="Введите текст или токен...">{{.TEXT}}</textarea>
<div class="button-group">
<button type="submit">Зашифровать</button>
<button type="submit" formaction="{{.URL}}/unwrap">Расшифровать</button>
<button type="button" class="btn-copy" onclick="copyToken()">Скопировать</button>
</div>
</form>
</div>
<div class="form-container">
<div class="form-title">Выберите файл (до 100кб):</div>
<form method="post" action="{{.URL}}/wrapfile" enctype="multipart/form-data">
<input type="file" name="file" id="file" required>
<div class="button-group">
<button type="submit">Зашифровать файл</button>
</div>
</form>
</div>
<div class="form-container">
<div class="form-title">Генерация пароля:</div>
<form method="post" action="{{.URL}}/genpassword">
<div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap;">
<div style="margin-bottom: 8px;">
Длина пароля (от 15 до {{.MAXTEXTLENGTH}}):
<input type="number" name="passlength" min="15" max="{{.MAXTEXTLENGTH}}" value="32">
</div>
<button type="submit" style="margin-left: auto;">Сгенерировать пароль</button>
</div>
</form>
</div>
</div>
<footer>
<div>© <script>document.write(new Date().getFullYear())</script> SVK</div>
</footer>
<script>
function copyToken() {
const textarea = document.getElementById('tokenTextarea');
const fullText = textarea.value;
const token = fullText.split('\n')[0].trim();
copyToClipboard(token, '.btn-copy');
}
function copyToClipboard(text, buttonSelector) {
const tempInput = document.createElement('input');
tempInput.value = text;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand('copy');
document.body.removeChild(tempInput);
const copyBtn = document.querySelector(buttonSelector);
const originalText = copyBtn.textContent;
copyBtn.textContent = 'Скопировано!';
setTimeout(() => {
copyBtn.textContent = originalText;
}, 2000);
}
</script>
</body>
</html>

View File

@@ -1,12 +0,0 @@
# Dynamic configuration
# in configuration/certificates.yaml
tls:
certificates:
# first certificate
- certFile: /ssl/runner1-prod.corp.samsonopt.ru.crt
keyFile: /ssl/runner1-prod.corp.samsonopt.ru.key
# second certificate
#- certFile: /path/to/other.cert
# keyFile: /path/to/other.key

View File

@@ -1,30 +0,0 @@
api:
dashboard: true
insecure: true
accessLog: {}
log:
level: INFO
entryPoints:
http:
address: ":80"
https:
address: ":443"
dashboard:
address: ":888"
http:
routers:
host:
entryPoints:
- http
rule: Host(`corp.samsonopt.ru`)
providers:
docker:
endpoint: "unix:///var/run/docker.sock"
exposedByDefault: false
file:
filename: /configuration/certificates.yaml

363
vault.go
View File

@@ -1,16 +1,27 @@
// -------------------------------------------
// Hashicorp Vault wrap/unwrap web service
// Distributed under GNU Public License
// Author: Sergey Kalinin svk@nuk-svk.ru
// Home page: https://nuk-svk.ru https://git.nuk-svk.ru
// -------------------------------------------
package main
import (
// "context"
"log"
// "time"
"io"
"os"
"fmt"
"flag"
"regexp"
"bytes"
"strconv"
"strings"
"time"
"encoding/json"
"encoding/base64"
"crypto/tls"
"net/http"
"html/template"
@@ -41,15 +52,20 @@ var (
TemplateFile string
ActionAddress string
VaultAddress string
VaultToken string
Data string
ListenPort string
TlsEnable bool
TlsCertFile string
TlsKeyFile string
MaxTextLength int
TokenTTL string
)
type TemplateData struct {
URL string
TEXT string
MAXTEXTLENGTH int
TOKENTTL string
}
type UnwrappedData struct {
Rerquest_id string `json: "request_id"`
@@ -57,24 +73,71 @@ type UnwrappedData struct {
Renewable bool `json: "renewable"`
Lease_daration int `json:"lease_duration"`
Data map[string]string `json: "data"`
Wrap_info string `json: "wrap_info"`
Wrap_info *WrapInfo `json: "wrap_info"`
Warnings string `json: "warnings"`
Auth string `json: "auth"`
Mount_type string `json: "mount_type"`
Error string `json: "errors"`
Errors string `json: "errors"`
}
func vaultDataWrap(vaultAddr string, vaultToken string, vaultSecretName string) string {
type WrapInfo struct {
Token string `json:"token"`
Ttl int `json:"ttl"`
CreationTime time.Time `json:"creation_time"`
CreationPath string `json:"creation_path"`
}
type FileViewerData struct {
Title string
Base64Data string
MimeType string
FileSize string
FileName string
IsImage bool
}
// const MaxTextLength = 100
func vaultDataWrap(vaultAddr string, dataType string, content string) string {
secret := make(map[string]string)
// switch dataType {
// case "text":
// secret["wrapped_data"] = text
// case "file":
// secret["file"] = text
// default:
// secret["wrapped_data"] = text
// }
// Определяем ключ для данных
if Debug {
log.Println("Тип данныж:", dataType)
}
if dataType == "text" {
// Для текста используем ключ "text"
secret["text"] = content
} else {
// Для файла используем имя файла как ключ
// Если dataType не "text" и не пустое, считаем его именем файла
if dataType == "" {
dataType = "file" // fallback, если имя не указано
}
secret[dataType] = content
}
postBody, err := json.Marshal(secret)
if err != nil {
log.Println("Errored marshaling the text:", content)
}
customTransport := &(*http.DefaultTransport.(*http.Transport))
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client := &http.Client{Transport: customTransport}
// client := &http.Client{}
req, _ := http.NewRequest("POST", vaultAddr, nil)
req, _ := http.NewRequest("POST", vaultAddr, bytes.NewBuffer(postBody))
req.Header.Add("Accept", "application/json")
req.Header.Add("X-Vault-Token", vaultToken)
req.Header.Add("X-Vault-Token", VaultToken)
req.Header.Add("X-Vault-Wrap-TTL", TokenTTL)
resp, err := client.Do(req)
@@ -82,11 +145,16 @@ func vaultDataWrap(vaultAddr string, vaultToken string, vaultSecretName string)
log.Println("Errored when sending request to the Vault server")
}
var result map[string]interface{}
var result UnwrappedData
json.NewDecoder(resp.Body).Decode(&result)
secret := result["data"].(map[string]interface{})["data"].(map[string]interface{})[vaultSecretName]
log.Println(result)
return fmt.Sprint(secret)
// wrappedToken := result.Data
if Debug {
log.Println(resp)
log.Println("result", result)
log.Println("token", result.Wrap_info.Token)
}
return result.Wrap_info.Token
}
func vaultDataUnWrap(vaultAddr string, vaultWrapToken string) map[string]string {
@@ -107,20 +175,25 @@ func vaultDataUnWrap(vaultAddr string, vaultWrapToken string) map[string]string
if err != nil {
log.Println("Errored when sending request to the Vault server", err)
}
log.Println(resp)
if Debug {
log.Println(resp)
}
var result UnwrappedData
json.NewDecoder(resp.Body).Decode(&result)
secret := result.Data
if Debug {
log.Println(result)
log.Println(secret)
log.Println("result", result)
log.Println("secret", secret)
}
// log.Println("Length=", len(secret))
// if len(secret) == 0 {
// log.Println("Error:", result.Errors)
// }
// fmt.Sprint(secret)
for v, k := range secret {
log.Println(k, v)
}
// for v, k := range secret {
// log.Println(k, v)
// }
return secret
}
@@ -149,9 +222,10 @@ func getStaticPage(w http.ResponseWriter, r *http.Request) {
template := filepath.Join(TemplateDir, TemplateFile)
// templateData.UUID = uuid
templateData.URL = ActionAddress + ":" + ListenPort
templateData.URL = ActionAddress
templateData.TEXT = Data
templateData.MAXTEXTLENGTH = MaxTextLength
templateData.TOKENTTL = TokenTTL
// templateData.URL = FishingUrl + "/" + arrUsers[i].messageUUID
if body, err := ParseTemplate(template, templateData); err == nil {
@@ -159,46 +233,106 @@ func getStaticPage(w http.ResponseWriter, r *http.Request) {
}
}
func showFileViewer(w http.ResponseWriter, r *http.Request, fileData []byte, fileName string) {
// Определяем MIME-тип файла
mimeType := http.DetectContentType(fileData)
isImage := strings.HasPrefix(mimeType, "image/")
// Кодируем в base64
base64Data := base64.StdEncoding.EncodeToString(fileData)
// Подготавливаем данные для шаблона
data := FileViewerData{
Title: "Просмотр файла",
Base64Data: base64Data,
MimeType: mimeType,
FileSize: fmt.Sprintf("%.2f", float64(len(fileData))/1024),
FileName: fileName,
IsImage: isImage,
}
// Парсим шаблон
tmpl, err := template.ParseFiles(filepath.Join(TemplateDir, "file-viewer.html"))
if err != nil {
http.Error(w, "Error loading template", http.StatusInternalServerError)
return
}
// Отображаем шаблон
w.Header().Set("Content-Type", "text/html; charset=utf-8")
err = tmpl.Execute(w, data)
if err != nil {
http.Error(w, "Error rendering template", http.StatusInternalServerError)
}
}
// hvs.CAES - 95
// s.Dj7kZS - 26
func getDataFromHtmlForm(w http.ResponseWriter, r *http.Request) {
func unwrapDataFromHtmlForm(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
token := r.FormValue("input_token")
vaultPath := VaultAddress + "/v1/sys/wrapping/unwrap"
// fmt.Fprintln(w, r.URL.RawQuery)
// log.Println(w, r.URL.RawQuery)
if Debug {
log.Printf("Текст для расшифровки: %s ", token)
log.Printf("Адрес сервера Hashicorp Vault: %s ", vaultPath)
}
// Проверка текста на соответствие шаблону
Data = ""
// Нормализация токена
re := regexp.MustCompile(`^(hvs|s)\.[\w\-\_]+`)
if Debug {
fmt.Println(re.Match([]byte(token)))
}
if token != "" && re.Match([]byte(token)) {
b := new(bytes.Buffer)
for key, value := range vaultDataUnWrap(vaultPath, token) {
fmt.Fprintf(b, "%s: %s\n", key, value)
token = strings.TrimSpace(strings.ReplaceAll(token, "\r\n", ""))
if token != "" && re.MatchString(token) {
unwrappedData := vaultDataUnWrap(vaultPath, token)
// 1. Сначала проверяем наличие текстовых данных
if textData, exists := unwrappedData["text"]; exists {
Data = textData
} else {
// 2. Если текста нет, ищем файловые данные (любой ключ, кроме "text")
var fileData []byte
var fileName string
for key, value := range unwrappedData {
if key != "text" { // Пропускаем текстовые данные, если они есть
// Декодируем base64
decoded, err := base64.StdEncoding.DecodeString(value)
if err != nil {
log.Printf("Ошибка декодирования файла %s: %v", key, err)
continue
}
fileData = decoded
fileName = key
break
}
}
if fileData != nil {
// Если нашли файл - показываем просмотрщик
showFileViewer(w, r, fileData, fileName)
return
} else {
// Если не нашли ни текста, ни файла - выводим все данные как текст
b := new(bytes.Buffer)
for key, value := range unwrappedData {
fmt.Fprintf(b, "%s: %s\n", key, value)
}
Data = b.String()
}
}
Data = b.String()
if Debug {
log.Println(Data)
if Data == "" {
Data = "Ошибка! Токен не содержит данных."
}
} else {
Data = "Введите токен"
} else if token != "" {
Data = "Введенные данные не соответствуют формату. Введите корректный токен."
}
getStaticPage(w, r)
// http.Redirect(w, r, "http://"+r.Host, http.StatusMovedPermanently)
}
func genPassword(w http.ResponseWriter, r *http.Request) {
// params := mux.Vars(r)
// passLength := params["passLength"]
Data = ""
r.ParseForm()
passLength := r.FormValue("passlength")
if Debug {
@@ -209,7 +343,7 @@ func genPassword(w http.ResponseWriter, r *http.Request) {
}
// w.Write([]byte("Длина пароля " + passLength + "/n"))
passwordLength, err := strconv.Atoi(passLength)
if passwordLength > 1024 {
if passwordLength > MaxTextLength {
log.Printf("Oversized password length")
Data = "Превышена длина пароля"
getStaticPage(w, r)
@@ -218,7 +352,7 @@ func genPassword(w http.ResponseWriter, r *http.Request) {
if err != nil {
log.Println(err)
}
res, err := password.Generate(passwordLength, 10, 5, false, true)
res, err := password.Generate(passwordLength, 5, 5, false, true)
if err != nil {
log.Println(err)
}
@@ -242,6 +376,111 @@ func genPasswordDefault(w http.ResponseWriter, r *http.Request) {
getStaticPage(w, r)
}
func wrapDataFromHtmlForm(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
secret := r.FormValue("input_token")
if len([]rune(secret)) > MaxTextLength {
log.Println("Длина текста превышает заданные ограничения:", MaxTextLength)
Data = fmt.Sprintf("Длина текста превышает заданные ограничения: %s > %s", strconv.Itoa(len([]rune(secret))), strconv.Itoa(MaxTextLength))
} else {
vaultPath := VaultAddress + "/v1/sys/wrapping/wrap"
Data = ""
if Debug {
fmt.Println("Введен текст:", secret)
}
if secret != "" {
Data = vaultDataWrap(vaultPath, "text", secret)
if Data == "" {
Data = "Ошибка! Токен не найден."
}
if Debug {
log.Println(Data)
}
// Переводим секунды в часы и дабавляем к токену для информации.
ttl, _ := strconv.Atoi(TokenTTL)
ttl = ttl / 3600
Data = fmt.Sprintf("%s\n\n---\nВремя жизни токена %s ч.", Data, strconv.Itoa(ttl))
} else if secret != "" {
Data = "Введите текст для шифровки."
}
}
getStaticPage(w, r)
}
func wrapDataFromFile(w http.ResponseWriter, r *http.Request) {
MaxFileLength := 100000 // Максимальный размер файла (100KB)
// 1. Проверяем метод (должен быть POST)
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// 2. Проверяем Content-Type (должен быть multipart/form-data)
contentType := r.Header.Get("Content-Type")
if !strings.HasPrefix(contentType, "multipart/form-data") {
http.Error(w, "Expected multipart/form-data", http.StatusBadRequest)
return
}
// 3. Парсим форму с ограничением размера (10 МБ)
maxMemory := 10 << 20 // 10 MB
if err := r.ParseMultipartForm(int64(maxMemory)); err != nil {
log.Printf("Failed to parse multipart form: %v", err)
http.Error(w, "Unable to parse form (file too big?)", http.StatusBadRequest)
return
}
// 4. Получаем файл из формы (включая метаданные)
file, fileHeader, err := r.FormFile("file")
if err != nil {
log.Printf("Failed to get file from form: %v", err)
http.Error(w, "Error retrieving the file", http.StatusBadRequest)
return
}
defer file.Close()
// Получаем оригинальное имя файла
fileName := fileHeader.Filename
if fileName == "" {
fileName = "unnamed_file" // Запасной вариант, если имя не указано
}
if Debug {
log.Printf("Processing file: %s (size: %d bytes)", fileName, fileHeader.Size)
}
// 5. Читаем содержимое файла
fileBytes, err := io.ReadAll(file)
if err != nil {
log.Printf("Failed to read file: %v", err)
http.Error(w, "Error reading the file", http.StatusInternalServerError)
return
}
// 6. Проверяем размер файла
if len(fileBytes) > MaxFileLength {
errMsg := fmt.Sprintf("File too large (%d > %d)", len(fileBytes), MaxFileLength)
http.Error(w, errMsg, http.StatusBadRequest)
return
}
// 7. Кодируем в base64
encoded := base64.StdEncoding.EncodeToString(fileBytes)
// 8. Обёртываем данные в Vault с именем файла
vaultPath := VaultAddress + "/v1/sys/wrapping/wrap"
token := vaultDataWrap(vaultPath, fileName, encoded)
if token == "" {
http.Error(w, "Failed to wrap data in Vault", http.StatusInternalServerError)
return
}
ttl, _ := strconv.Atoi(TokenTTL)
ttl = ttl / 3600
Data = fmt.Sprintf("%s\n\n---\nВремя жизни токена %s ч.", token, strconv.Itoa(ttl))
getStaticPage(w, r)
}
func main() {
var (
logFile string
@@ -251,11 +490,13 @@ func main() {
flag.StringVar(&TemplateDir, "template-dir", "html-template", "Каталог с шаблонами")
flag.StringVar(&TemplateFile, "template-file", "index.html", "Файл-шаблон для ВЭБ-странцы")
flag.StringVar(&VaultAddress, "vault-url", "", "Адрес сервера Hashicorp Vault (https://host.name:8200)")
flag.StringVar(&ActionAddress, "action-address", "", "Адрес данного сервиса (host.name)")
flag.StringVar(&ActionAddress, "action-address", "", "Адрес данного сервиса (https://host.name)")
flag.StringVar(&ListenPort, "listen-port", "8080", "Номер порта сервиса")
flag.StringVar(&TlsCertFile, "tls-cert", "", "TLS сертификат (файл)")
flag.StringVar(&TlsKeyFile, "tls-key", "", "TLS ключ (файл)")
flag.BoolVar(&TlsEnable, "tls", false, "Использовать SSL/TLS")
flag.IntVar(&MaxTextLength, "max-text-length", 100 , "Максимальная длина текста для шифрования и длина пароля для генератора")
flag.StringVar(&TokenTTL, "token-ttl", "3600", "Время жизни wrap-токена в секундах")
flag.Parse()
@@ -281,17 +522,31 @@ func main() {
VaultAddress = os.Getenv("VAULT_ADDRESS")
}
if os.Getenv("VAULT_TOKEN") == "" && VaultToken == "" {
log.Println("Send error: make sure environment variables `VAULT_TOKEN` was set")
} else if os.Getenv("VAULT_TOKEN") != "" && VaultToken == "" {
VaultToken = os.Getenv("VAULT_TOKEN")
}
if os.Getenv("MAX_TEXT_LENGTH") != "" && MaxTextLength == 100 {
MaxTextLength, err = strconv.Atoi(os.Getenv("MAX_TEXT_LENGTH"))
if err != nil {
log.Printf("Ошибка преобразования значения ", os.Getenv("MAX_TEXT_LENGTH"))
}
}
if Debug {
log.Printf("Адрес сервера Hashicorp Vault: %s ", VaultAddress)
}
rtr := mux.NewRouter()
rtr.HandleFunc("/unwrap", getDataFromHtmlForm)
rtr.HandleFunc("/unwrap", unwrapDataFromHtmlForm)
rtr.HandleFunc("/wrap", wrapDataFromHtmlForm)
rtr.HandleFunc("/wrapfile", wrapDataFromFile).Methods("POST")
rtr.HandleFunc("/genpassword/{passLength:[0-9]+}", genPassword)
rtr.HandleFunc("/genpassword", genPassword)
rtr.HandleFunc("/", getDataFromHtmlForm)
rtr.HandleFunc("/", unwrapDataFromHtmlForm)
rtr.PathPrefix("/").Handler(http.FileServer(http.Dir("./static")))
http.Handle("/", rtr)
@@ -303,20 +558,16 @@ func main() {
}
}
listenAddr := ":" + ListenPort
// ActionAddress = "https://" + ActionAddress
if Debug {
log.Printf("Адрес сервиса: %s%s ", ActionAddress, listenAddr)
}
log.Println("Listening...")
if TlsEnable {
ActionAddress = "https://" + ActionAddress
if Debug {
log.Printf("Адрес сервиса: %s%s ", ActionAddress, listenAddr)
}
log.Fatal(http.ListenAndServeTLS(listenAddr, TlsCertFile, TlsKeyFile, nil))
} else {
ActionAddress = "http://" + ActionAddress
if Debug {
log.Printf("Адрес сервиса: %s%s ", ActionAddress, listenAddr)
}
http.ListenAndServe(listenAddr, nil)
}
}