- Backup with restic
- restic
- Initialize Repository
- Backup
- Restore
- Manage Snapshots
- Check Integrity
- Cleanup
- Rest Server
- Install
- Backup
- Restic: backup для современного мира
- Теоретическая часть
- Предыстория
- Ненадежные медиа
- Сложная процедура бэкапа
- Restic: новый подход
- Как хранятся данные
- Практическая часть
- Установка и инициализация repository
- Типовые операции
- Бэкап
Backup with restic
Published: April 02, 2020 • linux, windows
There are various ways to backup data on a computer, and there are various tools that help you with this task. In this blog post, we are going to take a look at a command-line backup tool called restic.
restic
restic is an easy, fast, efficient, and secure backup utility. It is free and licensed under the BSD 2-Clause License.
It is actively developed on GitHub: https://github.com/restic/restic
restic is written in Go, and it runs on Linux, Windows, macOS, FreeBSD, and OpenBSD.
You can download the binary from the release page: https://github.com/restic/restic/releases
Or you install the application with a package manager. Visit the installation documentation page to find the installation steps for your operating system.
For this blog post, I worked on Windows 10 with restic 0.9.6. I downloaded the zip file from the release page, unzipped it, and copied the exe file it into an arbitrary folder. On Windows, you could copy the exe into the %SystemRoot%\System32 folder, and then it’s available in the path automatically. Or you add the path to your restic folder to the %PATH% environment variable.
restic supports out of the box many different backends:
- Local directory
- SFTP
- HTTP REST server
- AWS S3 (or self hosted Minio Server)
- OpenStack Swift
- BackBlaze B2
- Microsoft Azure Blob Storage
- Google Cloud Storage
If your preferred backend is not listed here, you can couple restic with rclone and use all the supported service of this tool. Visit the restic documentation to learn more about rclone support. And visit the rclone homepage to see a list of all supported backends.
restic is not a trivial file copy program. It works a little bit differently. It is based around the concept of repositories and snapshots. When you backup something, it is stored in a snapshot, which is stored in a repository.
The data in such a repository is always encrypted with AES. This is especially important when you back up sensitive data, and you send the backups to a server which is not under your control, for example to one of the cloud providers.
Initialize Repository
Before we can backup something, we have to initialize the repository. For this example, I connected an external hard disk (z:), and there I created an empty folder backup .
Run the following command to initialize the repository.
restic now asks you for the password. You have to remember this password. If you lose it, you can no longer access the backup!
Backup
The repository is created, and we can start backing up data. Each time you run a backup, restic creates a snapshot in the repository. To back up one or multiple folders or files, enter this command
-r is the short form of —repo and tells restic which repository to use. At the end of the command, you list files and directories you want to backup. In this example I backup two folders, which are located on two different local disks.
restic asks for your password and backs up the data. For demo purposes, I created one text file in each folder so restic had to transfer two files, which it tells me in the summary output.
Rerun the same command and see one of the benefits of restic. It created another snapshot, but it did not copy any files because there were no changes. This saves space on the backup drive, and it saves time and bandwidth when you back up over a network.
The backup command also supports command-line options to exclude and include files based on patterns. See the official documentation to dig deeper into this topic.
A tool like this is ideal for an automated backup script. The problem is that restic always requires a password to access the repository and to encrypt the data. The secure way would be that you always enter the password manually, which is not an option when you want to install a scheduled job that runs unattended.
There are different ways to specify the password and pass it to restic. You can set the environment variable RESTIC_PASSWORD , or you can store the password in a file and then specify the path to that file with the option —password-file or the environment variable RESTIC_PASSWORD_FILE . The third option is to call a program when a password is needed with the option —password-command or the environment variable RESTIC_PASSWORD_COMMAND .
Different backends require different environment variables. On this page you find all supported environment variables, and this page tells you how to configure the supported backends.
Restore
The restore command restores files and folders. restic does not restore the files into the original path. You have to specify a target location where restic restores the files.
Instead of specifying the snapshot ID, you can also use the keyword latest to restore the latest backup.
Like the backup command, restore supports filter options, if you want to restore just a host or a path or just a couple of files. The following example restore just the file workfile.txt
On supported operating systems, you can mount the repositories with FUSE and then browse them like a regular folder. This is not supported on Windows.
If you want to learn more about the restore command, visit the documentation page.
Manage Snapshots
We called the backup command twice, so there are now two snapshots in our backup repository. To list them, we use the snapshots command.
If you have many snapshots, you can filter them by path and host, and you can group them. See the documentation page for more information.
The diff command compares two snapshots with each other
Check Integrity
From time to time, you should check the integrity of the repository. The data in the repository is encrypted but the whole repository is just a collection of files and folders, and somebody could overwrite or delete a file. The check command verifies the repository and tells you if everything is okay or not.
Cleanup
To remove a snapshot restic provides two commands forget and prune . The forget command only deletes the snapshot from the index. The snapshot is no longer visible when you run the snapshots command, but the data is still there. To actually remove the data, you have to call the prune command.
Because you often use these two commands in tandem, you can also add the —prune option to the forget command. This command has the same effect as the two commands above
The documentation recommends to run a check after prune .
Deleting snapshots manually is cumbersome, and it’s easy to delete the wrong snapshot accidentally. For these reasons, restic provides a way to delete snapshots based on a policy. A policy could be to keep the last 3 snapshots or to keep snapshots of the last 20 days.
The forget command supports various keep-* parameters. For example to delete all but the last snapshot you can execute this command
If you want to keep the snapshots of the last 7 days, you issue this command. If there are multiple snapshots in a day, restic removes all but the last one for that day.
For example, you backup 6 times a day for 10 days. You now have 60 snapshots. After you run this command, there are 7 snapshots left in the repository. One snapshot for each of the last 7 days.
You can even combine multiple policies.
With this command forget keeps one snapshot for each of the last 7 days, always the last snapshot of a month for the last 12 months and always the last snapshot of a year for the last 3 years.
See the documentation for more example and a more in-depth description of the options.
Rest Server
Backup and restore works, but there is one issue we have to keep in mind. restic always requires a password to access the repository and to encrypt the backup. When you install a scheduled job, you have to store this password somewhere, as mentioned before, you can store it in an environment variable or a file. The problem is that when an attacker gains control over your computer, he could also figure out this password. He then could not only delete the data on your computer but also all the snapshots in the restic repository.
If that is a concern, you should consider installing a restic REST server. This server has a unique feature called append-only mode. When the server runs in this mode, you can backup your data normally but the server refuses to execute the forget command, even when an attacker has access to your restic password. Your backups are secure and can’t be deleted, as long as your backup server is secure.
In this section, I’m showing you how to install this REST server on a virtual private server. I rented a Debian 10 VPS from Hetzner, using the smallest configuration for €2.68 / per month with a 20 GB SSD for this example installation.
Install
First, we download the server application from the GitHub release page. The server, like the client, is written in Go and consists of just one binary.
Next, we create a password. This step is optional, and you can run the server without authentication. The password we create here is just for authenticating to the rest server. This password has nothing to do with the repository password. The repository password is still required but will always be set from the backup client.
For creating the password, we need the htpasswd program, which is part of the Apache utils package.
Then we create a password and encrypt it with bcrypt. Choose an arbitrary username. The password file needs to be located in the data directory. In our installation this is /opt/restic/data
I don’t want to run the rest-server with the root user, so I create a new user here, and change ownership of the program directory.
Now we install the service in systemd so that the rest-server will be started when the server starts.
Paste the following code into the file, save and close it.
The important flag here is —append-only . This is the flag we talked about before to prevent somebody from executing the forget command.
Check if the service runs properly
The rest-server runs by default on port 8000. Make sure that you open this port in the firewall, or change the port with the —listen option
Backup
As with any backend, we first have to initialize the repository. Instead of a path, we now have to specify the URL to the rest-server. Because we also configured username and password, we have to pass this information as well to the tool.
If that command is successful, you can now backup to your own restic rest-server
Now let’s see what happens when we try to delete the snapshot.
Although the password is correct, you get a bunch of error messages, thanks to the —append-only flag of the server. Even when an attacker gains access to your restic password, he can’t delete the backups.
The question now is what if you want to delete old snapshots because you only have limited disk space on your VPS. The repository the rest-server creates is a regular repository, and you can access it with the restic command-line tool locally.
Open an SSH connection to your VPS, and install the restic command-line tool.
Now you can run the forget command. Enter the correct password, and your snapshot is gone.
So far we used HTTP for the transfer, this is not a problem for the backup because that is already encrypted on the client-side, but we sent our HTTP username and password in plaintext over the Internet.
We can solve that by installing a TLS certificate. We are going to create a Let’s Encrypt certificate, and for that, you need to have a domain name. Add an A record with the IP address of your server. For this example I use the domain backup.rasc.ch
Install certbot and request a TLS certificate
When successful, cerbot should have created the key and certificate in the /etc/letsencrypt folder. In my example, the TLS certificate is stored in /etc/letsencrypt/live/backup.rasc.ch/fullchain.pem and the private key is located here /etc/letsencrypt/live/backup.rasc.ch/privkey.pem .
Open the service file.
Add the required TLS options
Restart the rest-server
With this configuration in place, you now have to use HTTPS from the client-side
Restic: backup для современного мира
Restic — это простой, надежный, быстрый и эффективный способ резервного копирования. Простой в установке и настройке, с поддержкой большого количества бэкендов хранения, надежным шифрованием и дедупликацией. Это прекрасный инструмент для резервного копирования в современном ИТ-ландшафте. Тут я расскажу, зачем он нужен, как его поставить и начать им пользоваться.
Теоретическая часть
Предыстория
Исторически сложилось, что системы резервного копирования устроены очень сложно. Их сложно устанавливать, настраивать и сопровождать. Руководство к Veritas NetBackup (в дальнейшем — Symantec) имеет размеры приличной книги, по этой системе можно сдать экзамен и получить сертификат. Конфиг Amanda или Bacula весит под сотню килобайт, а официальное руководство занимает больше 500 страниц. Разумеется — у этой поражающей сложности есть простая, понятная, логичная причина, даже две:
- ненадежность медиа
- сложность процедуры бэкапа
Ненадежные медиа
Резервные копии надо где-то хранить. Традиционно используются цифровые кассеты (DAT/DLT), CD (в дальнейшем — DVD и BD) ROM/RW и жесткие диски. Проблема физических медиа в их не абсолютной надежности: кассеты размагничиваются и осыпаются, диски — царапаются и страдают от деградаций красочного слоя, про жесткие диски и говорить нечего. Из-за этого “классические” системы резервного копирования имеют сложные структуры расписаний и управление медиа-пулом. Медианосители надо постоянно перетасовывать, чтобы нагрузка на чтение и запись была равномерной и чтобы не оказалось, что весь огромный многотеррабайтный бэкап зависит от одного-единственного диска, который только что рассыпался в дисководе. Сложное расписание умножается на сложную структуру бэкапов (полный, инкрементальный, дифференциальный) где каждый слой зависит от другого. Это делается для экономия места и времени бэкапа. Кроме этого медиа ограничены в размере, а потому — нужно иметь возможность точно отфильтровать файлы и писать только то, что реально необходимо.
Сложная процедура бэкапа
В классическом традиционном ИТ-подходе бэкап — это очень сложная процедура. Бэкапим мы файлы, но данные нельзя воспринимать как файлы — они меняются. Бэкап файлов “в лоб” провоцирует инконсистентные данные, когда что-то поменялось на ходу и часть файлов находится в состоянии “до”, а часть — уже “после”. В том же Veritas NetBackup львиную долю цены лицензий состовляла цена агентов — сущностей, которые помогали бэкапить конкретные базы (Oracle, MSSQL) или состояния конкретных продуктов (SAP, BAAN). Агент знал, как “заморозить” состояние системы и получить консистентный бэкап, без него резервное копирование превращалось в лотерею. В opensource решениях агентов обычно нет, но родовые травмы в виде PreTask/PostTask остались — нужно подготовить данные к резервному копированию, а потом — вывести систему из этого состояния.
Restic: новый подход
Restic задуман как резервное копирование для современного ИТ-мира. Он имеет простой (предельно простой) интерфейс и минимум настроек. Одно из главных нововведений Restic — отказ от сложных медиа-операций. В современном ИТ в качестве системы хранения используется внешний сервис хранения, доступный обычно по S3 (Amazon S3, Azure BlobStorage, DigitalOcean Spaces, Minio на собственном оборудовании) или через прослойку в виде rclone (dropbox, Yandex.Disk). Restic предполагает такой бэкенд небезопасным, но надежным. Разумеется, данные внутри Amazon S3 хранятся на медиа, и медиа эти ненадежны. Однако между пользователем и медиа — несколько слоев абстракции, которые защищают данные, следят за их целостностью и верификацией. RAID-контроллеры, Erasure Codes, репликация между серверами-стойками-датацентрами, media scrubbing, check-суммы блоков — технологий десятки, если не сотни. По словам Dropbox — 80% трафика внутри их датацентров составляет служебный трафик, верификация, репликация и проверки данных, и только 20% — это собственно пользовательские данные. Restic исходит из идеи, что данные во внешнем хранилище содержатся вполне надежно и шансы получить битый или потеряный блок — минимальны. Именно по этому в Restic нет разделения на типы бэкапов — полные, инкрементальные и дифференциальные. Вместо этого предложен механизм snapshot-тов. Это просто снимок состояния системы в момент времени.
Как хранятся данные
Так как restic предполагает, что медиа — небезопасно — все данные шифруются AES256-CTR. Ключ AES шифруется паролем. Содержимое файлов нарезается на блоки (blobs) переменной длины (от 512кб до 8Мб), при этом каждый blob имеет контрольную сумму (CDC). Блоки упаковываются в пачки (pack). Пачка хранит в себе содержимое файла с метаданными или дерево (то есть — хранит в себе ссылки на другие пачки — файлы). Разные пачки могут ссылаться на один и тот же blob, что позволяет значительно экономить место. На самом верху этой пирамиды восседает snapshot, который хранит метаданные о, собственно, бэкапе (кто, когда, где) и ссылку на пачку с деревом верхнего уровня. При этом разные snapshot-ы могут ссылаться на одни и те же пачки деревьев, а пачки деревьев — на одни и те же пачки файлов (если файлы не менялись). Restic имеет удобную команду restic cat blob , которая позволяет посмотреть в содержимое конкретного блоба и выяснить, что там лежит.
Практическая часть
Установка и инициализация repository
Restic написан на go и потому распространяется в виде единственно бинарного файла, который содержит все необходимое. В Debian и Ubuntu он есть в виде пакета, так что поставить можно традиционно:
Ну или просто скачать готовый binary отсюда.
После установки нужно инициализировать repo. При этом restic сгенерирует ключ для шифрования и создаст структуру каталогов для хранения blob-ов, паков и snapshot-ов. Тут нужно сделать небольшое отступление: в рамках одного repo можно хранить бэкапы разных каталогов и даже разных хостов. Структура repo restic-а позволяет это делать и бэкапы не будут пересекаться друг с другом (hostname и path бэкапа — обязательный атрибут snapshot-а, так что можно легко отфильтровать нужный). Блобы общие в рамках repo, по этому если три разных хоста хранят одинаковый файл — в repo он будет хранится в одном блобе, что позволит сэкономить место.
Инициализация выполняется командой init
Главное — не забыть пароль, про который спросит restic. Именно этим паролем шифруется ключ и если пароль посеять — шансов на распаковку будет примерно ноль.
Типовые операции
Бэкап
Бэкап — основная операция, которая выполняется (по-хорошему), чаще всего: