Меню Закрыть

Создание шифрованного удаленного репозитория git

Иногда, например, личные пароли или настройки доступа удобно синхронизировать между устройствами с помощью git. И такие данные лучше хранить зашифрованными. С помощью помощника git-remote-gcrypt это сделать довольно легко и в заметке рассмотрим как его установить и использовать для шифрования удаленного репозитория

Для шифрования необходимо установить GnuPG, но по-умолчанию он уже идет в большинстве linux дистрибутивов

sudo apt install gnupg

Установим git-remote-gcrypt

sudo apt install git-remote-gcrypt

Далее для шифрования необходимо создать ключи, например, с именем GitKey (для имени необходимо минимум 5 символов) и E-Mail git@example.com

gpg --full-generate-key

Выбираем варианты по-умолчанию, вводим имя и e-mail и, при необходимости, пароль

gpg (GnuPG) 2.2.27; Copyright (C) 2021 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Please select what kind of key you want:
   (1) RSA and RSA (default)
   (2) DSA and Elgamal
   (3) DSA (sign only)
   (4) RSA (sign only)
  (14) Existing key from card
Your selection? 1
RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (3072) 
Requested keysize is 3072 bits
Please specify how long the key should be valid.
         0 = key does not expire
      <n>  = key expires in n days
      <n>w = key expires in n weeks
      <n>m = key expires in n months
      <n>y = key expires in n years
Key is valid for? (0) 
Key does not expire at all
Is this correct? (y/N) y

GnuPG needs to construct a user ID to identify your key.

Real name: GitKey
Email address: git@example.com
Comment: 
You selected this USER-ID:
    "GitKey <git@example.com>"

Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
gpg: key 0A982DB7B92FEF2B marked as ultimately trusted
gpg: directory '/home/imaroz/.gnupg/openpgp-revocs.d' created
gpg: revocation certificate stored as '/home/imaroz/.gnupg/openpgp-revocs.d/E990B6B159A450313DE773C50A982DB7B92FEF2B.rev'
public and secret key created and signed.

pub   rsa3072 2024-07-01 [SC]
      E990B6B159A450313DE773C50A982DB7B92FEF2B
uid                      GitKey <git@example.com>
sub   rsa3072 2024-07-01 [E]

Произведем классические манипуляции для создания пустышки локального репозитория

git init && \
echo "Hello world" > readme.md && \
git add . && \
git commit -m "Initial commit"   

Далее необходимо подключить удаленный репозиторий

git remote add origin gcrypt::git@example.com:encrypted

Далее необходимо указать какие ключи использовать, если у вас создано несколько ключей. Для этого выведем список ключей, возьмем его отпечаток пропишем в настройках удаленного репозитория

gpg --list-keys
gpg: checking the trustdb
gpg: marginals needed: 3  completes needed: 1  trust model: pgp
gpg: depth: 0  valid:   1  signed:   0  trust: 0-, 0q, 0n, 0m, 0f, 1u
/home/imaroz/.gnupg/pubring.kbx
-------------------------------
pub   rsa3072 2024-07-01 [SC]
      E990B6B159A450313DE773C50A982DB7B92FEF2B
uid           [ultimate] GitKey <git@example.com>
sub   rsa3072 2024-07-01 [E]
git config remote.origin.gcrypt-participants "E990B6B159A450313DE773C50A982DB7B92FEF2B"
git config remote.origin.gcrypt-signingkey "E990B6B159A450313DE773C50A982DB7B92FEF2B"

Теперь можно сделать push нашего кода

git push origin master -u
gcrypt: Repository not found: git@vbox:encrypted
gcrypt: Setting up new repository
gcrypt: Remote ID is :id:CdzW392tDV0q4NNmtTMj
gcrypt: Due to a longstanding bug, this push implicitly has --force.
gcrypt: Consider explicitly passing --force, and setting
gcrypt: gcrypt's require-explicit-force-push git config key.
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
gcrypt: Encrypting to:  -R 0A982DB7B92FEF2B
gcrypt: Requesting manifest signature
To vbox:encrypted
 * [new branch]      master -> master
Branch 'master' set up to track remote branch 'master' from 'origin'.

Важно! Удаленный репозиторий должен быть чистым, т.е. без залитого ранее кода без шифрования

Теперь данные на удаленном репозитории хранятся в зашифрованном виде. Можем убедиться склонировав без дешифрования

git clone git@example.com:encrypted
Cloning into 'encrypted'...
remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (4/4), done.
Receiving objects: 100% (4/4), 1.77 KiB | 1.77 MiB/s, done.
remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0
cd encrypted/ && \
ls -l
total 8
-rw-rw-r-- 1 imaroz imaroz 1172 июл  1 18:07 91bd0c092128cf2e60e1a608c31e92caf1f9c1595f83f2890ef17c0e4881aa0a
-rw-rw-r-- 1 imaroz imaroz  288 июл  1 18:07 dc75a14dfc37d50e650a2e1d4c7f4bd700e40dc34006ffe92ae8b7ed9ecfdb7a

Как видим, в директории какие-то два файла, вместо одного readme.md с бинарным содержимым

Для того что получить расшифрованный необходимо добавить gcrypt:: в начале URI. При этом модуль будет перебирать ключи, пока не найдет подходящий для расшифровки

git clone gcrypt::git@example.com:encrypted
Cloning into 'encrypted'...
gcrypt: Decrypting manifest
gpg: error getting version from 'scdaemon': No SmartCard daemon
gpg: Signature made Пн 01 июл 2024 18:00:45 UTC
gpg:                using RSA key E990B6B159A450313DE773C50A982DB7B92FEF2B
gpg: Good signature from "GitKey <git@example.com>" [ultimate]
gcrypt: Remote ID is :id:CdzW392tDV0q4NNmtTMj
Receiving objects: 100% (3/3), done.

Теперь расшифровать данные можно только на рабочем месте с этим ключом. Чтоб можно было работать не нескольких местах, необходимо перенести ключ. Для этого создадим бэкап ключей и восстановим на другом рабочем месте

Экспортируем наш ключ в файл с именем git.example.com.gpg

gpg -o git.example.com.gpg --armor --export-options backup --export-secret-keys E990B6B159A450313DE773C50A982DB7B92FEF2B

Далее скопировав git.example.com.gpg на другую машину нужно его импортировать

gpg --import-options restore --import git.example.com.gpg

и подтвердить доверие к этому ключу, введя команды для редактирования

gpg --edit-key E990B6B159A450313DE773C50A982DB7B92FEF2B

Появится диалоговое окно с вводом команды, в которое надо ввести trust и указать уровень доверия (полное доверия, цифра 5)

gpg (GnuPG) 2.2.27; Copyright (C) 2021 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Secret key is available.

sec  rsa3072/0A982DB7B92FEF2B
     created: 2024-07-01  expires: never       usage: SC  
     trust: unknown       validity: unknown
ssb  rsa3072/220BA49FB23F9BE7
     created: 2024-07-01  expires: never       usage: E   
[ unknown] (1). GitKey <git@example.com>

gpg> trust
sec  rsa3072/0A982DB7B92FEF2B
     created: 2024-07-01  expires: never       usage: SC  
     trust: unknown       validity: unknown
ssb  rsa3072/220BA49FB23F9BE7
     created: 2024-07-01  expires: never       usage: E   
[ unknown] (1). GitKey <git@example.com>

Please decide how far you trust this user to correctly verify other users' keys
(by looking at passports, checking fingerprints from different sources, etc.)

  1 = I don't know or won't say
  2 = I do NOT trust
  3 = I trust marginally
  4 = I trust fully
  5 = I trust ultimately
  m = back to the main menu

Your decision? 5
Do you really want to set this key to ultimate trust? (y/N) y

sec  rsa3072/0A982DB7B92FEF2B
     created: 2024-07-01  expires: never       usage: SC  
     trust: ultimate      validity: unknown
ssb  rsa3072/220BA49FB23F9BE7
     created: 2024-07-01  expires: never       usage: E   
[ unknown] (1). GitKey <git@example.com>
Please note that the shown key validity is not necessarily correct
unless you restart the program.

Теперь можно работать на другой машине с шифрованным репозиторием


При подготовке заметки использовались статьи

Подписаться
Уведомить о
guest
0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии