/lazywarden

Automatic Bitwarden Backup

Primary LanguagePythonMIT LicenseMIT

Secure, Automated, and Multi-Cloud Bitwarden Backup and Import System

Lazywarden is a Python automation tool designed to Backup and Restore data from your vault, including Bitwarden attachments. It allows you to upload backups to multiple cloud storage services and receive notifications across multiple platforms. It also offers AES encrypted backups and uses key derivation with Argon2, ensuring maximum security for your data.

Features

  • πŸ”’ Maximum Security: Data protection with AES-256 encryption and Argon2 key derivation.
  • πŸ”„ Automated Backups and Imports: Keep your Bitwarden vault up to date and secure.
  • βœ… Integrity Verification: SHA-256 hash to ensure data integrity on every backup.
  • ☁️ Multi-Cloud Support: Store backups to services such as Dropbox, Google Drive, pCloud, MEGA, NextCloud, Seafile, Filebase (IPFS) and via SMTP.
  • πŸ–₯️ Local Storage: Save backups to a local path for greater control.
  • πŸ”” Real-Time Alerts: Instant notifications on Discord, Telegram and Slack.
  • πŸ—“οΈ Schedule Management: Integration with Todoist and CalDAV to manage your schedule.
  • 🐳 Easy Deployment: Quick setup with Docker Compose.
  • πŸ€– Full Automation and Custom Scheduling: Automatic backups with flexible scheduling options (daily, weekly, monthly, yearly). Integration with CalDAV and Todoist for complete tracking and email notifications.
  • πŸ”‘ Bitwarden Export to KeePass: Export Bitwarden items to a KeePass database (kdbx), including TOTP-seeded logins, URI, custom fields, card, identity attachments and secure notes.

Platform Compatibility

Demo Backup

Demo Import

Demo Schedule

Demo Import Keepass

Demo Decrypting All Zip and JSON

SMTP Backup

SMTP Scheduled

CalDAV Backup

CalDAV Schedule

Todoist Backup

Todoist Schedule

Slack

Discord

Telegram

System Requirements

  • Operating System: Compatible with major Linux distributions

    • βœ… Ubuntu
    • βœ… Debian

Installation

Clone the repository

   git clone https://github.com/querylab/lazywarden.git
   cd lazywarden

Configure Environment Variables & Bitwarden Secrets Manager

  • Create a .env file based on the on this .env.sample example file and fill in the necessary variables.
GOOGLE_SERVICE_ACCOUNT_FILE=/root/lazywarden/config/bitwarden-drive-backup-google.json
GOOGLE_FOLDER_ID=1oWWis8QR3VTz5qRA3W4YTtO0LjvXFvoB
BACKUP_DIR=/root/lazywarden/backup-drive/
TELEGRAM_TOKEN=
TELEGRAM_CHAT_ID=
DISCORD_WEBHOOK_URL=
SLACK_WEBHOOK_URL=
SMTP_SERVER=mail.smtp2go.com
SMTP_PORT=8025
SMTP_USERNAME=
SMTP_PASSWORD=
EMAIL_RECIPIENT=
SENDER_EMAIL=
API_URL=https://vault.bitwarden.com/api   # No Modify No Touch
IDENTITY_URL=https://vault.bitwarden.com/identity   # No Modify No Touch
ORGANIZATION_ID=232c1123-78f9-4124-b769-b195122f78bf
ACCESS_TOKEN=0.3a22t111a-c111-1111-8fa2-b1c12341236a.1QTvdFZ12333ZEVSGM8azrOns7Wux:H+5prum123OQb28123KvUw==  # Access Token from Bitwarden Secrets Manager Ubuntu-Lazywarden Machine
CRON_SCHEDULE="0 0 23 * *" #Cron Every 24 hours for Docker 
TIMEZONE=America/New_York
TIMESTAMP=2024_09_18_19_45_40 # To decrypt all zip files in your backup or import them, just use the timestamp that was generated in the backup. For example, use the files that are generated in the backup like this: bw-backup_2024_09_18_19_45_40.zip.

Ubuntu Configuration

  • Run the script to install all system dependencies and requirements
cd lazywarden/scripts
chmod +x setup-ubuntu-env.sh
./setup-ubuntu-env.sh
  • Run this script to automatically install Docker & Docker-Compose:
chmod +x docker-ubuntu.sh
./docker-ubuntu.sh
  • First, ensure you are in the root directory of the project lazywarden/:
cd .. 
source venv/bin/activate
  • Now Install Bitwarden CLI using the bitwarden-cli-install.py script, which will install all CLI dependencies:
python3 scripts/bitwarden-cli-install.py
  • Change the system timezone using the following command. Replace Region/City with the desired timezone (e.g., America/New_York):
timedatectl set-timezone Region/City
  • For example, to set the timezone to America/New_York, you would run:
timedatectl set-timezone America/New_York
  • Run the Lazywarden program. Navigate to the app/ folder and execute main.py:
cd app
python3 main.py

Debian Configuration

  • Run the script to install all system dependencies and requirements:
cd lazywarden/scripts
chmod +x setup-debian-env.sh
./setup-debian-env.sh
  • Run this script to automatically install Docker & Docker-Compose:
chmod +x docker-debian.sh
./docker-debian.sh
  • First, ensure you are in the root directory of the project lazywarden/:
cd .. 
source venv/bin/activate
  • Install Bitwarden CLI using the bitwarden-cli-install.py script, which will install all CLI dependencies:
python3 scripts/bitwarden-cli-install.py
  • Change the system timezone using the following command. Replace Region/City with the desired timezone (e.g., America/New_York):
timedatectl set-timezone Region/City
  • For example, to set the timezone to America/New_York, you would run:
timedatectl set-timezone America/New_York
  • Run the Lazywarden program. Navigate to the app/ folder and execute main.py:
cd app
python3 main.py
  • In Debian, if you encounter an error when running main.py, it may be related to missing or outdated libraries. To fix this, I recommend running the following command to install all the necessary dependencies:
 pip install -r requirements.txt

Steps to Configure Bitwarden Secrets Manager

To set up Secret Management in Bitwarden, first create a new organization in your account to serve as a container for shared secrets. Next, subscribe to the Secret Manager service, which allows you to securely store an unlimited number of secrets, such as API keys, passwords and certificates. This service provides end-to-end encryption, centralized management and access control.

  • After creating your Organization, go to Secret Manager in the tab at the top right.

  • Then create your lazywarden Project.

  • After creating your lazywarden Project, you need to create the secrets that will be in the lazywarden project. Here are some examples:

  • If you have TOTP enabled on your Bitwarden account, put the seeds of your TOTP in the BW_TOTP_SECRET variable.

  • If you do not have TOTP enabled on your Bitwarden account, just put random characters as shown in the image below.

  • Continue filling in the other variables one by one. If you do not have an account, for example for pCloud, MEGA, Filebase, Seafile, NextCloud or Dropbox fill in the variables with some random characters. For example, if you don't have a MEGA account, put the following:

  • As you can see in the images above, I don't have a MEGA account, so I used random strings. You always have to have something in the Secret Variables for the program to work. Now, the backup will only be stored locally in the chosen directory and in Google Drive, Dropbox, pCloud, NextCloud, Seafile and Filebase but not in MEGA as my account is not configured

  • After creating all your secrets, create a Machine Account that will hold our ACCESS_TOKEN.

  • Add and save the lazywarden project to your Machine Account.

  • Finally, go to Access Tokens and create one to use in our lazywarden project.

  • With these secrets added, we can now modify our secrets_manager.py file to contain our secrets.
	
    "BW_URL": "00000000-0000-0000-0000-000000000000",
    "BW_USERNAME": "00000000-0000-0000-0000-000000000000",
    "BW_PASSWORD": "00000000-0000-0000-0000-000000000000",
    "BW_TOTP_SECRET": "00000000-0000-0000-0000-000000000000",
    "ENCRYPTION_PASSWORD": "00000000-0000-0000-0000-000000000000",
    "ZIP_PASSWORD": "00000000-0000-0000-0000-000000000000",
    "ZIP_ATTACHMENT_PASSWORD": "00000000-0000-0000-0000-000000000000",
    "PCLOUD_USERNAME": "00000000-0000-0000-0000-000000000000",
    "PCLOUD_PASSWORD": "00000000-0000-0000-0000-000000000000",
    "MEGA_EMAIL": "00000000-0000-0000-0000-000000000000",
    "MEGA_PASSWORD": "00000000-0000-0000-0000-000000000000",
    "DROPBOX_ACCESS_TOKEN": "00000000-0000-0000-0000-000000000000",
    "DROPBOX_REFRESH_TOKEN": "00000000-0000-0000-0000-000000000000",
    "DROPBOX_APP_KEY": "00000000-0000-0000-0000-000000000000",
    "DROPBOX_APP_SECRET": "00000000-0000-0000-0000-000000000000",
    "TODOIST_TOKEN": "00000000-0000-0000-0000-000000000000",
    "CALDAV_URL": "00000000-0000-0000-0000-000000000000",
    "CALDAV_USERNAME": "00000000-0000-0000-0000-000000000000",
    "CALDAV_PASSWORD": "00000000-0000-0000-0000-000000000000",
    "NEXTCLOUD_URL": "00000000-0000-0000-0000-000000000000",
    "NEXTCLOUD_USERNAME": "00000000-0000-0000-0000-000000000000",
    "NEXTCLOUD_PASSWORD": "00000000-0000-0000-0000-000000000000",
    "SEAFILE_SERVER_URL": "00000000-0000-0000-0000-000000000000",
    "SEAFILE_USERNAME": "00000000-0000-0000-0000-000000000000",
    "SEAFILE_PASSWORD": "00000000-0000-0000-0000-000000000000",
    "FILEBASE_ACCESS_KEY": "00000000-0000-0000-0000-000000000000",
    "FILEBASE_SECRET_KEY": "00000000-0000-0000-0000-000000000000",
    "KEEPASS_PASSWORD": "00000000-0000-0000-0000-000000000000"
    
  • To find the ORGANIZATION_ID variable for our .env you can get it by visiting the URL when you are in your organization or by running the following command:
bw list organizations
ORGANIZATION_ID=212A4880-22f9-1114-b00e-12345234278ac

ACCESS_TOKEN=0.345f5e9c-8730-4a4c-917b-b100003312356.Oj4XzcyGFF222212345kwzV:e5mC4d1111111128/3EQ==

Attention: Security Critical Variables

### These variables contain the passwords for encrypting the backup.
### Change the passwords according to your preferences.

#Contains the encryption password for the JSON file
ENCRYPTION_PASSWORD=p3mTd5SqDqkXQqE!Tpwv27Ecx  


#Contains the encryption password for the first ZIP file
ZIP_PASSWORD=ZCGvq@gwS7QhV@&R3k*x*xN72anybyFHW2RWiBTr  


# Contains the encryption password for the attached ZIP file.
# Where our files will be stored if Bitwarden Premium is enabled.
# If Bitwarden Premium is not enabled, the attachment folder will be empty.
ZIP_ATTACHMENT_PASSWORD=HBLXL9!grer@Uay2edkwTXeZx!E9DxKphNxsNak1knb3dcfx2o   

Dropbox API Configuration

By following these steps, your Dropbox Token will remain active and will not expire every 4 hours.

  1. Go to https://www.dropbox.com/developers/apps/create
  • Create a new project.

  • Create Permissions

  1. Obtain the Authorization Code
  • Open a browser and navigate to the following URL, replacing <App key> with your App Key:
https://www.dropbox.com/oauth2/authorize?token_access_type=offline&response_type=code&client_id=<App key>

  1. Obtain the Authorization Token

Run the following command in the terminal, making sure to replace <received code>, <App key>, and <App secret> with the correct values:

curl https://api.dropbox.com/oauth2/token \
-d code=<received code> \
-d grant_type=authorization_code \
-u <App key>:<App secret>

#Example
curl https://api.dropbox.com/oauth2/token \
-d code=G4sTbrY9DMoAAAAAAAAAQTeLtVHACmv1tVaWYLYCGvA \
-d grant_type=authorization_code \
-u 7on1ofs1236ki:b6bl6jg123lm8iz
  • When you run the command, you will receive a response like this:
 "access_token": "sl.B3hxfHXr123459z8_TS230pcLcLNbJ1234Hj-ccZmG5XCcQrN-Wb6ESMs0PSzwOtROxLb6XRaj6mUzHU1g8G60canTvjkWBBaNzVY1234hH2FEOhlwseaNcnQ9RyPn6vh",
  "token_type": "bearer",
  "expires_in": 14400,
  "refresh_token": "WtG6MI5YdccAAAAAAAAAAcAvu1234nB6skR3BmpgH3x5Reb-ae7FsLuNQ5-mZkk",
  "scope": "account_info.read",
  "uid": "143786425",
  "account_id": "dbid:BBAnJyzGYtm3-WP9a2HkL1TL8FVgPl5s-VM"
  • Now use this new refresh_token, access_token along with the previous <App key>, and <App secret> to fill in the secret variables needed in Bitwarden Secret Manager:
#Example
      DROPBOX_ACCESS_TOKEN=sl.B3hxfHXrU12345z8_TS230pcLcLNbJj019MyrVHj-ccZmG5XCcQrN-Wb6ESMs0PSzwOtROxLb612345g8G60canTvjkWBBaNzVYP15cx5h12345NcnQ9RyPn6vh
      DROPBOX_REFRESH_TOKEN=WtG6MI5Yd1234AAAAAAcAvuFd9usnB6skR3BmpgH3x5Reb-ae7FsLuNQ5-mZkk
      DROPBOX_APP_KEY=1on14fs123456ki
      DROPBOX_APP_SECRET=b1bl12345m8iz

Google Drive API Configuration

  1. Go to this web page https://console.developers.google.com/iam-admin/serviceaccounts
  2. Create a New Project.

  1. Then go to "Service Accounts" and create a new service.

  1. Select the role "Actions Admin".

  1. Download the key in JSON format. This key will be used in our project to upload the Bitwarden backup to Google Drive. Once you obtain the JSON file, store it in the /config folder of the project. Name the JSON file bitwarden-drive-backup-google.json.
# Place the Google credentials file in the specified path /config

GOOGLE_SERVICE_ACCOUNT_FILE=/home/lazywarden/config/bitwarden-drive-backup-google.json

  1. Go to the following link and enable the Google Drive API:https://console.cloud.google.com/apis/library

  1. Now that you have enabled the API, go to your Google Drive and create a folder named "Bitwarden-Backup".

  1. Share the "Bitwarden-Backup" folder by clicking on "Share" and share it with the email address created in the Service Account when you set up the project.

  1. After sharing the folder, you need to get the ID of this folder to store it in your .env file. To find the ID of the β€œBitwarden-Backup” folder, open the folder and look at the URL in your browser.
GOOGLE_FOLDER_ID=1qtV4vfIjmXyhDdzIzJ6RiCc-b0M22vsF

Tree Structure

lazywarden/
β”œβ”€β”€ app/                           # This directory appears to contain the main application code
β”‚   β”œβ”€β”€ backup.py                  # Backup functions
β”‚   β”œβ”€β”€ bitwarden_client.py        # Client to interact with Bitwarden
β”‚   β”œβ”€β”€ config.py                  # General application configurations
β”‚   β”œβ”€β”€ imports.py                 # Handles common imports
β”‚   β”œβ”€β”€ main.py                    # Main entry point of the application
β”‚   β”œβ”€β”€ notifications.py           # Handles notifications
β”‚   β”œβ”€β”€ secrets_manager.py         # Manages secrets
β”‚   β”œβ”€β”€ import_to_bitwarden.py     # Import your bitwarden vault
β”‚   β”œβ”€β”€ import_to_keepass.py       # Create kdbx database 
β”‚   β”œβ”€β”€ schedule_backup.py         # For create Schedule Backup
β”œβ”€β”€ config/                        # Directory for configuration files
β”‚   β”œβ”€β”€ bitwarden-drive-backup-google.json # Configuration for Google Drive
β”œβ”€β”€ scripts/                       # Directory for installation and setup scripts
β”‚   β”œβ”€β”€ bitwarden-cli-install.py   # Script to install the Bitwarden CLI
β”‚   β”œβ”€β”€ docker-debian.sh           # Setup script for Debian with Docker
β”‚   β”œβ”€β”€ docker-ubuntu.sh           # Setup script for Ubuntu with Docker
β”‚   β”œβ”€β”€ setup-debian-env.sh        # Environment setup for Debian
β”‚   β”œβ”€β”€ setup-ubuntu-env.sh        # Environment setup for Ubuntu
β”‚   β”œβ”€β”€ alldecrypt-zip.py          # Decrypt all zip files 
β”‚   β”œβ”€β”€ json-only-decrypt.py       # Decrypt only json files (optional)
β”œβ”€β”€ backup-drive/
β”‚   β”œβ”€β”€ (This is where the generated backups will be stored local)
β”œβ”€β”€ .env                           # File for environment variables
β”œβ”€β”€ Dockerfile                     # Docker configuration file to create an application image
β”œβ”€β”€ docker-compose.yml             # Docker Compose Configuration
β”œβ”€β”€ entrypoint.sh                  # Entrypoint script for Docker
└── requirements.txt               # File that lists the project Python dependencies

Cron Job for Python (optional)

To automatically run the backup script in the background using cron, every 24 hours follow these steps:

  1. Open the crontab for editing:
crontab -e
  1. Select an editor if you dont have one configured:
Select an editor.  To change later, run 'select-editor'.
  1. /bin/nano        <---- easiest
  2. /usr/bin/vim.basic
  3. /usr/bin/vim.tiny
  4. /bin/ed
Choose 1-4 [1]: 1
  1. Add the following line to schedule the lazywarden.py script to run at midnight every day:
0 0 23 * * /root/lazywarden/venv/bin/python3 /root/lazywarden/app/main.py >> /var/log/lazywarden-cron.log 2>&1
  1. Save & Close and reload the file. Verify that the cron job is set up correctly:
service cron reload

crontab -l

Docker Compose

The Docker container will run the main.py script every 24 hours to back up Bitwarden and upload it to the configured cloud services. Notifications will be sent to the specified services in case of success or failure. You can modify the backup frequency according to your needs, such as monthly, daily, or hourly.

services:
  lazywarden:
    container_name: lazywarden_backup
    hostname: lazywarden_backup
    build: .
    env_file:
      - .env
    environment:
      UNLOCK_VAULT: "true"
    volumes:
      - /root/lazywarden/config:/config
      - /root/lazywarden/backup-drive:/root/lazywarden/backup-drive
    restart: unless-stopped

Run Docker Compose

  • Run the Docker container
docker compose up -d

Dockerfile

  • The Dockerfile sets up the environment, installs dependencies, and copies necessary files into the container.

docker-compose.yml

  • The docker-compose.yml file defines the lazywarden service and sets up environment variables and volumes for persistent storage.

Security Recommendation: Run in Local Environment

  • For security, run this project only in a local environment within your personal network. This significantly reduces the risk of exposure to external attacks, ensuring that sensitive data and credentials remain protected within a controlled environment.

πŸ“’ Warning

Important Note
  • Large attachments in your Bitwarden account (e.g., MP4 videos, MP3 files, high-resolution photos) may cause the backup process to take longer. Uploading these larger backups to cloud services will also be slower. Local storage and importing data are much faster in comparison.
  • A high number of attachments can significantly extend the total backup time. Upload errors may occur when sending files to Dropbox, Google Drive, pCloud, MEGA, Seafile, Nextcloud, or Filebase. If an error occurs, retrying the backup often resolves the issue.
  • Configuring the Bitwarden Secret Manager is required for the program to function correctly. Even if you don't have an account, you must set a random variable to ensure proper operation.
  • This program is compatible with both self-hosted Bitwarden and Vaultwarden instances.
  • Import functionality for Vaultwarden and self-hosted Bitwarden is not yet implemented in the Bitwarden API.
  • CalDAV calendar integration has only been tested with the following providers: Baikal, Fruux, Memotoo, Posteo, and SOGo.
  • Rotate the secrets stored in Bitwarden Secret Manager regularly for enhanced security.
  • If you switch Bitwarden Accounts, make sure to run the bw logout command before logging into a new account.
  • I run the program using the root user.

Motivations

  • I created Lazywarden to Automate Bitwarden Backups without manual effort or exposing sensitive data. After struggling with complex tools, I leveraged Bitwarden Secret Manager to securely manage secrets. Lazywarden automates backups and uploads them to multiple cloud services (Google Drive, Dropbox, pCloud, MEGA, Seafile, Nextcloud, Filebase), and integrates with Telegram, Discord, Slack, Todoist, and CalDAV for notifications and tracking. Its standout feature is the ability to restore encrypted backups back into Bitwarden, making backup management simple, secure, and efficient.

  • If you like this project, please consider giving it a ⭐