Compare commits

...

29 Commits

Author SHA1 Message Date
copilot-swe-agent[bot]
6ed071400a fix update script failure when image tag is missing 2026-07-14 13:06:43 +00:00
copilot-swe-agent[bot]
32f77c7054 Initial plan 2026-07-14 13:03:41 +00:00
vdmchkv
314e8e7fb6 Update URL with version information (#284)
* Update URL with version information

The previous URL is no longer working. Instead of the site redirect, switching directly to the official GitHub repository of Bitwarden to download the latest version information.

* Update update-bitwarden.sh

* Add prerequisite checks and switch JSON parsing to jq

The URL with the version of self-hosted Bitwarden is not working anymore. Now we're querying the official GitHub repository of Bitwarden and using jq to find the current released version. For simplification, we've moved to jq instead of sed/awk combinations and also added prerequisite checks for docker, openssl, and jq to avoid build failures.

* Add prerequisite checks and switch JSON parsing to jq

The URL with the version of self-hosted Bitwarden is not working anymore. Now we're querying the official GitHub repository of Bitwarden and using jq to find the current released version. For simplification, we've moved to jq instead of sed/awk combinations and also added prerequisite checks for docker, openssl, and jq to avoid build failures. The script was also changed to exit on failure (set -e).

* Update build.sh

Remove duplicate OpenSSL check

* Update update-bitwarden.sh

Remove duplicate OpenSSL check

* Apply suggestions from code review

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: captainhook <16797541+captainhook@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-06-18 18:51:04 +02:00
Pascal Pothmann
8def331bb6 Update to .NET 10.0 and fix certificate validation for Bitwarden server 2026.5.0 (#282)
* Update to .NET 10.0 for Bitwarden server 2026.5.0 compatibility

Bitwarden server 2026.5.0 ships with .NET 10.0 runtime only, breaking
the fast-patch build. This commit updates all .NET projects and build
pipelines to target net10.0 and the dotnet/sdk:10.0 image.

Additionally:
- Replace obsolete X509Certificate2(byte[]) constructors with
  X509CertificateLoader.LoadCertificate() / LoadPkcs12FromFile()
  to resolve SYSLIB0057 warnings introduced in .NET 9/10
- Add -certpbe AES-256-CBC -keypbe AES-256-CBC -macalg SHA256 to
  generate-keys.sh PKCS#12 export, fixing OpenSSL 3.x errors caused
  by the deprecated RC2-40-CBC legacy algorithm
- Update FixRuntimeConfig fallback framework version to 10.0.0

Fixes #281

Signed-off-by: Pascal Pothmann <19438422+p0thi@users.noreply.github.com>

* Fix certificate validation by replacing all thumbprint occurrences

Bitwarden's LicensingService performs two validation checks:
1. Validates _creationCertificate thumbprint
2. Validates all certificates in _verificationCertificates

The thumbprint constants are inlined at compile time, creating multiple
Ldstr instructions in the IL code. The patcher was only replacing the
first occurrence, causing the second validation to fail with:
'Invalid license verifying certificate.'

This fix replaces ALL occurrences of the old thumbprint to ensure both
validation checks pass.

Fixes runtime error: 'Invalid license verifying certificate'

---------

Signed-off-by: Pascal Pothmann <19438422+p0thi@users.noreply.github.com>
Co-authored-by: Pascal Pothmann <19438422+p0thi@users.noreply.github.com>
2026-06-03 21:57:45 +02:00
Lorenzo Moscati
9962717481 Fast patching via IL rewriting of Bitwarden images (#278)
* Fast patching via IL rewriting of Bitwarden images

Brings back the pre-047c4dd approach of patching pre-built Bitwarden
images instead of cloning and building from source. The fast patch mode
(now default) pulls ghcr.io/bitwarden/{api,identity} and rewrites
Core.dll in-place using Mono.Cecil, bypassing the full source build.

Updated to work with current Bitwarden:
- Uses SingleFileExtractor.Core to extract Core.dll from the
  PublishSingleFile bundle before patching; replaces the native
  launcher with a shell script wrapper (exec dotnet /app/Api.dll)
  so entrypoint.sh continues to work unchanged
- LicensingService search is now namespace-agnostic (handles the
  Bit.Core.Services → Bit.Core.Billing.Services rename)
- Thumbprint matching uses Contains() instead of Equals() to handle
  the hidden Unicode LRM character prepended to the production
  thumbprint string literal in the compiled IL

The original source-build path is preserved and accessible via
BITBETTER_BUILD_FROM_SOURCE=1.

Signed-off-by: Lorenzo Moscati <lorenzo@moscati.page>

* Address review: fix correctness and robustness

- dotnet publish -c Release with explicit -o to match Dockerfile expectation
- Add --platform "$TARGETPLATFORM" to fast-patch docker builds for parity with source-build mode
- mkdir -p for idempotent .keys directory creation
- Align namespace to BitwardenSelfLicensor (repo convention)
- Branch bundle extraction on .dll extension instead of bare catch; exit 1 with clear message on failure
- Replace First() with FirstOrDefault() + targeted error on missing licensing resource
- FixRuntimeConfig derives framework name/version from includedFrameworks; switch to LatestPatch rollForward

Signed-off-by: Lorenzo Moscati <lorenzo@moscati.page>

* Add BITBETTER_BUILD_FROM_SOURCE notes to README.md

Signed-off-by: Lorenzo Moscati <lorenzo@moscati.page>

---------

Signed-off-by: Lorenzo Moscati <lorenzo@moscati.page>
Co-authored-by: h44z <christoph.h@sprinternet.at>
2026-04-12 11:03:25 +01:00
Lorenzo Moscati
dbaaa8b45d Add missing licence options, bump licence version and add Token claim (#277)
* Add license options, bump version, add Token claim

Added the missing license options:
- `ExpirationWithoutGracePeriod`
- `UseAutomaticUserConfirmation`
- `UsePhisingBlocker`
- `UseDisableSmAdsForUsers`
- `UseMyItems`

Bumped the license version from 15 to 16 (`UseOrganizationDomains` is valid only with version 16).

Added `GenerateUserToken` and `GenerateOrgToken` helpers to create the expected `Token` claim that’s still missing in our licenses.

Signed-off-by: Lorenzo Moscati <lorenzo@moscati.page>

* Address Copilot review

- Capture `now = DateTime.UtcNow` once per license-generation call and pass it
  into GenerateUserToken/GenerateOrgToken, so all date fields in the JSON
  license and the embedded JWT derive from the same instant (fixes drift across
  separate DateTime.UtcNow calls)
- Move set("Token", ...) before ComputeHash/Sign in both GenerateUserLicense
  and GenerateOrgLicense so all fields are finalised before signing
- Add UseRiskInsights claim to the org JWT; confirmed present as a required
  claim in Bitwarden's OrganizationLicenseClaimsFactory

Version is intentionally excluded from both JWTs: neither UserLicenseClaimsFactory
nor OrganizationLicenseClaimsFactory generates it, and the claims-path VerifyData
never reads it.

Signed-off-by: Lorenzo Moscati <lorenzo@moscati.page>

---------

Signed-off-by: Lorenzo Moscati <lorenzo@moscati.page>
2026-04-12 07:04:48 +01:00
h44z
31a08b7e89 fix error message after build (#263), improve readme (#266) 2025-12-09 22:04:28 +01:00
Michiel Hazelhof
5387d1803d Add note for the new lite version (#268)
Not sure about the correct url
2025-12-09 21:14:00 +01:00
captainhook
2c9e4fd9fa Enhance build script to support multi-platform builds and improve Docker build experience (#262)
* Enhance build script to support multi-platform builds and improve Docker build experience

* Update build.sh

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Correct value for --platform argument

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-10-12 19:01:34 +02:00
h44z
0e2c9d42aa Fix path of OrganizationLicense object (#254)
* Fix path of OrganizationLicense object (see https://github.com/bitwarden/server/tree/main/src/Core/Billing/Organizations/Models)
2025-08-10 10:53:29 +02:00
Joseph Gigantino
063ab1d316 Test generating user and organization licenses during build check (#252)
Add commands to build check to build licensegen image as well and test if the created licensegen image can actually generate user and organization licenses. run.sh will print the generated license to stdout and return zero if successful. If an error occurs, a non zero error code is returned which should cause a build error.

Signed-off-by: Joseph Gigantino <128943406+Jgigantino31@users.noreply.github.com>
2025-07-30 19:15:45 +02:00
h44z
df9e74bb7a Fix license generator according to upstream changes (#245) (#249) 2025-07-29 21:08:44 +00:00
Joseph Gigantino
ac01b0c7ec Update build.sh (#246)
Match change in upstream location of LicensingService.cs

Signed-off-by: Joseph Gigantino <128943406+Jgigantino31@users.noreply.github.com>
2025-07-29 19:45:55 +02:00
Pablo
f3e36ab404 [Fix] TRUSTED CERTIFICATE (#238)
Fix for this error:

unable to load certificate
140067633099200:error:0909006C:PEM routines:get_name:no start line:../crypto/pem/pem_lib.c:745:Expecting: TRUSTED CERTIFICATE
2025-07-11 05:10:23 -07:00
Lorenzo Moscati
b9c46fffb2 Update Program.cs (#237)
Set three new license options to true: UseRiskInsights, UseOrganizationDomains, and UseAdminSponsoredFamilies.
2025-07-10 22:43:22 +00:00
Genva
047c4ddf6f Build image from source (#234)
* Build image from source

* Clone only current version tag

* remove obsolete project

* support loading Core.dll from single file application

* pass single file application to license gen

* remove loose file parameter

* fix executable parameter

* Remove unnecessary changes in LicensingService.cs

* Revert "Remove unnecessary changes in LicensingService.cs"

This reverts commit d8465e1aec.

* Changed comment
2025-07-09 01:04:58 +00:00
h44z
676dd7b85c Fix warning in Dockerfile (#230) 2025-05-17 14:22:29 +00:00
Lorenzo Moscati
0b33567820 Updated container repository (#225)
Updated the container image registries from Docker Hub to GitHub Container Registry. Fixes #224
2025-03-29 17:16:26 +00:00
Alessandro
180ad94838 Move Manually generating Certificate & Key section in README.md (#216)
Move `Manually generating Certificate & Key` section from `Building BitBetter` to `Setting up BitBetter` and mark it as `Optional` instead of `Note`.

Co-authored-by: h44z <christoph.h@sprinternet.at>
2024-11-24 19:10:11 +01:00
vdmchkv
38c43a43c9 Prevent docker compose from attempting to pull BitBetter images from the Docker repository (#219)
Co-authored-by: Vadim Iouchkov <vadim.iouchkov@d-gl.de>
2024-11-24 19:02:48 +01:00
Michiel Hazelhof
bfc821e918 Update documentation to reflect changes (#214) 2024-11-03 10:22:14 +01:00
Michiel Hazelhof
3ec7b3d843 Quick and dirty fix (#213)
* Quick and dirty fix

* Don't push obsolete code

* Improve code
2024-11-01 14:36:03 +00:00
Shuttleu
7f64e2cd4a Update license to version 15 (#211)
Co-authored-by: captainhook <16797541+captainhook@users.noreply.github.com>
2024-10-10 14:29:59 +01:00
Michiel Hazelhof
a65277198c Use new location (#202) 2024-06-30 01:33:01 +00:00
kasperk81
12da7d7249 use correct framework (#193)
* use correct framework

* use correct framework
2024-03-30 09:31:27 +00:00
Jan Schöppach
3c703f517d Update to .NET 8.0 to fix building with bitwarden v2024.2.2 (#187)
* Update to .NET 8.0 to fix building with bitwarden v2024.2.2

* Also update license gen to .NET 8.0
2024-02-22 23:16:34 +00:00
Rakesh
b93c9487eb Update License to use Secrets Manager fully (#182) 2024-01-19 18:02:14 +00:00
Ayitaka
e173c06320 Updated license version to 12, added SM options, increased max seats (short to int) (#172)
* - Updated license version to 12
- Added new SM license options

* Change seats, smseats, smserviceaccounts from short to int, like they are in the Bitwarden server code, to allow for the accurate maximum amount of seats
2023-11-29 12:07:21 +00:00
Ayitaka
80c0808e72 Update licenseGen with latest version and options (#165)
- Changed Version to 10
- Uncommented UseScim
- Added UseCustomPermissions
2023-04-21 14:24:41 +02:00
12 changed files with 528 additions and 224 deletions

View File

@@ -13,3 +13,12 @@ jobs:
- run: - run:
name: Build script name: Build script
command: ./build.sh command: ./build.sh
- run:
name: Build licenseGen
command: ./src/licenseGen/build.sh
- run:
name: Test generating user license
command: ./src/licenseGen/run.sh ./.keys/cert.pfx user TestName TestEmail@example.com 4a619d4a-522d-4c70-8596-affb5b607c23
- run:
name: Test generating organization license
command: ./src/licenseGen/run.sh ./.keys/cert.pfx org TestName TestEmail@example.com 4a619d4a-522d-4c70-8596-affb5b607c23

View File

@@ -15,6 +15,6 @@ DIR=`exec 2>/dev/null;(cd -- "$DIR") && cd -- "$DIR"|| cd "$DIR"; unset PWD; /us
# Generate new keys # Generate new keys
openssl req -x509 -newkey rsa:4096 -keyout "$DIR/key.pem" -out "$DIR/cert.cert" -days 36500 -subj '/CN=www.mydom.com/O=My Company Name LTD./C=US' -outform DER -passout pass:test openssl req -x509 -newkey rsa:4096 -keyout "$DIR/key.pem" -out "$DIR/cert.cert" -days 36500 -subj '/CN=www.mydom.com/O=My Company Name LTD./C=US' -outform DER -passout pass:test
openssl x509 -inform DER -in "$DIR/cert.cert" -out "$DIR/cert.pem" openssl x509 -inform DER -in "$DIR/cert.cert" -out "$DIR/cert.pem"
openssl pkcs12 -export -out "$DIR/cert.pfx" -inkey "$DIR/key.pem" -in "$DIR/cert.pem" -passin pass:test -passout pass:test openssl pkcs12 -export -out "$DIR/cert.pfx" -inkey "$DIR/key.pem" -in "$DIR/cert.pem" -passin pass:test -passout pass:test -certpbe AES-256-CBC -keypbe AES-256-CBC -macalg SHA256
ls ls

View File

@@ -4,6 +4,8 @@ BitBetter is is a tool to modify Bitwarden's core dll to allow you to generate y
Please see the FAQ below for details on why this software was created. Please see the FAQ below for details on why this software was created.
Looking for a solution to the Lite (formerly unified) version of bitwarden, [go to the Lite branch](../../tree/lite).
_Beware! BitBetter does janky stuff to rewrite the bitwarden core dll and allow the installation of a self signed certificate. Use at your own risk!_ _Beware! BitBetter does janky stuff to rewrite the bitwarden core dll and allow the installation of a self signed certificate. Use at your own risk!_
Credit to https://github.com/h44z/BitBetter and https://github.com/jakeswenson/BitBetter Credit to https://github.com/h44z/BitBetter and https://github.com/jakeswenson/BitBetter
@@ -14,8 +16,8 @@ Credit to https://github.com/h44z/BitBetter and https://github.com/jakeswenson/B
- [Getting Started](#getting-started) - [Getting Started](#getting-started)
- [Dependencies](#dependencies) - [Dependencies](#dependencies)
- [Setting up BitBetter](#setting-up-bitbetter) - [Setting up BitBetter](#setting-up-bitbetter)
- [Optional: Manually generating Certificate & Key](#optional-manually-generating-certificate--key)
- [Building BitBetter](#building-bitbetter) - [Building BitBetter](#building-bitbetter)
- [Note: Manually generating Certificate & Key](#note-manually-generating-certificate--key)
- [Updating Bitwarden and BitBetter](#updating-bitwarden-and-bitbetter) - [Updating Bitwarden and BitBetter](#updating-bitwarden-and-bitbetter)
- [Generating Signed Licenses](#generating-signed-licenses) - [Generating Signed Licenses](#generating-signed-licenses)
- [Note: Alternative Ways to Generate License](#note-alternative-ways-to-generate-license) - [Note: Alternative Ways to Generate License](#note-alternative-ways-to-generate-license)
@@ -40,6 +42,21 @@ With your dependencies installed, begin the installation of BitBetter by downloa
git clone https://github.com/jakeswenson/BitBetter.git git clone https://github.com/jakeswenson/BitBetter.git
``` ```
### Optional: Manually generating Certificate & Key
If you wish to generate your self-signed cert & key manually, you can run the following commands.
```bash
cd .keys
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.cert -days 36500 -outform DER -passout pass:test
openssl x509 -inform DER -in cert.cert -out cert.pem
openssl pkcs12 -export -out cert.pfx -inkey key.pem -in cert.pem -passin pass:test -passout pass:test
```
> Note that the password here must be `test`.<sup>[1](#f1)</sup>
---
## Building BitBetter ## Building BitBetter
Now that you've set up your build environment, you can **run the main build script** to generate a modified version of the `bitwarden/api` and `bitwarden/identity` docker images. Now that you've set up your build environment, you can **run the main build script** to generate a modified version of the `bitwarden/api` and `bitwarden/identity` docker images.
@@ -51,17 +68,27 @@ From the BitBetter directory, simply run:
This will create a new self-signed certificate in the `.keys` directory if one does not already exist and then create a modified version of the official `bitwarden/api` called `bitbetter/api` and a modified version of the `bitwarden/identity` called `bitbetter/identity`. This will create a new self-signed certificate in the `.keys` directory if one does not already exist and then create a modified version of the official `bitwarden/api` called `bitbetter/api` and a modified version of the `bitwarden/identity` called `bitbetter/identity`.
By default, the build script runs in **fast patch mode**: it pulls the official Bitwarden images from the GitHub Container Registry and patches the license certificate directly inside them — no local compilation required.
To instead **build from source**, set the `BITBETTER_BUILD_FROM_SOURCE` environment variable to `1` before running the script:
```bash
BITBETTER_BUILD_FROM_SOURCE=1 ./build.sh
```
In source build mode the script clones the Bitwarden server repository at the matching version tag, replaces the embedded license certificate, and compiles the `api` and `identity` images from scratch. This takes considerably longer but gives you full control over the build.
You may now simply create the file `/path/to/bwdata/docker/docker-compose.override.yml` with the following contents to utilize the modified images. You may now simply create the file `/path/to/bwdata/docker/docker-compose.override.yml` with the following contents to utilize the modified images.
```yaml ```yaml
version: '3'
services: services:
api: api:
image: bitbetter/api image: bitbetter/api
pull_policy: never
identity: identity:
image: bitbetter/identity image: bitbetter/identity
pull_policy: never
``` ```
You'll also want to edit the `/path/to/bwdata/scripts/run.sh` file. In the `function restart()` block, comment out the call to `dockerComposePull`. You'll also want to edit the `/path/to/bwdata/scripts/run.sh` file. In the `function restart()` block, comment out the call to `dockerComposePull`.
@@ -70,25 +97,22 @@ You'll also want to edit the `/path/to/bwdata/scripts/run.sh` file. In the `func
You can now start or restart Bitwarden as normal and the modified api will be used. **It is now ready to accept self-issued licenses.** You can now start or restart Bitwarden as normal and the modified api will be used. **It is now ready to accept self-issued licenses.**
---
### Note: Manually generating Certificate & Key
If you wish to generate your self-signed cert & key manually, you can run the following commands.
```bash
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.cert -days 36500 -outform DER -passout pass:test
openssl x509 -inform DER -in cert.cert -out cert.pem
openssl pkcs12 -export -out cert.pfx -inkey key.pem -in cert.pem -passin pass:test -passout pass:test
```
> Note that the password here must be `test`.<sup>[1](#f1)</sup>
--- ---
## Updating Bitwarden and BitBetter ## Updating Bitwarden and BitBetter
To update Bitwarden, the provided `update-bitwarden.sh` script can be used. It will rebuild the BitBetter images and automatically update Bitwarden afterwards. Docker pull errors can be ignored for api and identity images. To update Bitwarden, the provided `update-bitwarden.sh` script can be used. It will rebuild the BitBetter images and automatically update Bitwarden afterwards. Docker pull errors can be ignored for api and identity images.
By default, the images are built in **fast patch mode**: the official Bitwarden images are pulled from the GitHub Container Registry and the license certificate are directly patched inside them.
To instead **build from source**, set the `BITBETTER_BUILD_FROM_SOURCE` environment variable to `1` before running the script:
```bash
BITBETTER_BUILD_FROM_SOURCE=1 ./update-bitwarden.sh
```
In source build mode the script clones the Bitwarden server repository at the matching version tag, replaces the embedded license certificate, and compiles the `api` and `identity` images from scratch. This takes considerably longer but gives you full control over the build.
You can either run this script without providing any parameters in interactive mode (`./update-bitwarden.sh`) or by setting the parameters as follows, to run the script in non-interactive mode: You can either run this script without providing any parameters in interactive mode (`./update-bitwarden.sh`) or by setting the parameters as follows, to run the script in non-interactive mode:
```bash ```bash
./update-bitwarden.sh param1 param2 param3 ./update-bitwarden.sh param1 param2 param3

View File

@@ -1,22 +1,101 @@
#!/bin/sh #!/bin/sh
set -e
DIR=`dirname "$0"` DIR=`dirname "$0"`
DIR=`exec 2>/dev/null;(cd -- "$DIR") && cd -- "$DIR"|| cd "$DIR"; unset PWD; /usr/bin/pwd || /bin/pwd || pwd` DIR=`exec 2>/dev/null;(cd -- "$DIR") && cd -- "$DIR"|| cd "$DIR"; unset PWD; /usr/bin/pwd || /bin/pwd || pwd`
BW_VERSION=$(curl -sL https://go.btwrdn.co/bw-sh-versions | grep '^ *"'coreVersion'":' | awk -F\: '{ print $2 }' | sed -e 's/,$//' -e 's/^"//' -e 's/"$//')
# Check prerequisite libraries and executables
for cmd in docker curl openssl jq; do
command -v "$cmd" >/dev/null 2>&1 || { echo "Error: '$cmd' is required but not installed." >&2; exit 1; }
done
if [ "${BITBETTER_BUILD_FROM_SOURCE:-0}" = "1" ]; then
command -v git >/dev/null 2>&1 || { echo "Error: 'git' is required for BITBETTER_BUILD_FROM_SOURCE=1 but not installed." >&2; exit 1; }
fi
BW_VERSION=$(curl -fsSL https://raw.githubusercontent.com/bitwarden/self-host/refs/heads/main/version.json | jq -er '.versions.coreVersion')
echo "Building BitBetter for BitWarden version $BW_VERSION" echo "Building BitBetter for BitWarden version $BW_VERSION"
# Enable BuildKit for better build experience and to ensure platform args are populated
export DOCKER_BUILDKIT=1
export COMPOSE_DOCKER_CLI_BUILD=1
# Determine host architecture to use as default BUILDPLATFORM / TARGETPLATFORM if not supplied.
# Allow override via environment variables when invoking the script.
HOST_UNAME_ARCH=$(uname -m 2>/dev/null || echo unknown)
case "$HOST_UNAME_ARCH" in
x86_64|amd64) DEFAULT_ARCH=amd64 ;;
aarch64|arm64) DEFAULT_ARCH=arm64 ;;
armv7l|armv7) DEFAULT_ARCH=arm/v7 ;;
*) DEFAULT_ARCH=amd64 ;;
esac
: "${BUILDPLATFORM:=linux/${DEFAULT_ARCH}}"
: "${TARGETPLATFORM:=linux/${DEFAULT_ARCH}}"
echo "Using BUILDPLATFORM=$BUILDPLATFORM TARGETPLATFORM=$TARGETPLATFORM"
# If there aren't any keys, generate them first. # If there aren't any keys, generate them first.
[ -e "$DIR/.keys/cert.cert" ] || "$DIR/.keys/generate-keys.sh" [ -e "$DIR/.keys/cert.cert" ] || "$DIR/.keys/generate-keys.sh"
[ -e "$DIR/src/bitBetter/.keys" ] || mkdir "$DIR/src/bitBetter/.keys" if [ "${BITBETTER_BUILD_FROM_SOURCE:-0}" = "1" ]; then
echo "--- Source build mode ---"
cp "$DIR/.keys/cert.cert" "$DIR/src/bitBetter/.keys" # Prepare Bitwarden server repository
rm -rf $DIR/server
git clone --branch "v${BW_VERSION}" --depth 1 https://github.com/bitwarden/server.git $DIR/server
docker run --rm -v "$DIR/src/bitBetter:/bitBetter" -w=/bitBetter mcr.microsoft.com/dotnet/sdk:6.0 sh build.sh # Replace certificate file and thumbprint
old_thumbprint=$(openssl x509 -inform DER -fingerprint -noout -in $DIR/server/src/Core/licensing.cer | cut -d= -f2 | tr -d ':')
new_thumbprint=$(openssl x509 -inform DER -fingerprint -noout -in $DIR/.keys/cert.cert | cut -d= -f2 | tr -d ':')
sed -i -e "s/$old_thumbprint/$new_thumbprint/g" $DIR/server/src/Core/Billing/Services/Implementations/LicensingService.cs
cp $DIR/.keys/cert.cert $DIR/server/src/Core/licensing.cer
docker build --no-cache --build-arg BITWARDEN_TAG=bitwarden/api:$BW_VERSION --label com.bitwarden.product="bitbetter" -t bitbetter/api "$DIR/src/bitBetter" # --squash docker build \
docker build --no-cache --build-arg BITWARDEN_TAG=bitwarden/identity:$BW_VERSION --label com.bitwarden.product="bitbetter" -t bitbetter/identity "$DIR/src/bitBetter" # --squash --no-cache \
--platform "$TARGETPLATFORM" \
--build-arg BUILDPLATFORM="$BUILDPLATFORM" \
--build-arg TARGETPLATFORM="$TARGETPLATFORM" \
--label com.bitwarden.product="bitbetter" \
-f $DIR/server/src/Api/Dockerfile \
-t bitbetter/api \
$DIR/server
docker build \
--no-cache \
--platform "$TARGETPLATFORM" \
--build-arg BUILDPLATFORM="$BUILDPLATFORM" \
--build-arg TARGETPLATFORM="$TARGETPLATFORM" \
--label com.bitwarden.product="bitbetter" \
-f $DIR/server/src/Identity/Dockerfile \
-t bitbetter/identity \
$DIR/server
else
echo "--- Fast patch mode ---"
mkdir -p "$DIR/src/bitBetter/.keys"
cp "$DIR/.keys/cert.cert" "$DIR/src/bitBetter/.keys/cert.cert"
# Build the patcher tool inside the SDK container
docker run --rm \
-v "$DIR/src/bitBetter:/bitBetter" \
-w /bitBetter \
mcr.microsoft.com/dotnet/sdk:10.0 sh build.sh
docker build \
--no-cache \
--platform "$TARGETPLATFORM" \
--label com.bitwarden.product="bitbetter" \
--build-arg BITWARDEN_TAG="ghcr.io/bitwarden/api:$BW_VERSION" \
-t bitbetter/api \
"$DIR/src/bitBetter"
docker build \
--no-cache \
--platform "$TARGETPLATFORM" \
--label com.bitwarden.product="bitbetter" \
--build-arg BITWARDEN_TAG="ghcr.io/bitwarden/identity:$BW_VERSION" \
-t bitbetter/identity \
"$DIR/src/bitBetter"
fi
docker tag bitbetter/api bitbetter/api:latest docker tag bitbetter/api bitbetter/api:latest
docker tag bitbetter/identity bitbetter/identity:latest docker tag bitbetter/identity bitbetter/identity:latest
@@ -24,5 +103,5 @@ docker tag bitbetter/api bitbetter/api:$BW_VERSION
docker tag bitbetter/identity bitbetter/identity:$BW_VERSION docker tag bitbetter/identity bitbetter/identity:$BW_VERSION
# Remove old instances of the image after a successful build. # Remove old instances of the image after a successful build.
ids=$( docker images bitbetter/* | grep -E -v -- "CREATED|latest|${BW_VERSION}" | awk '{ print $3 }' ) ids=$( docker image ls --format="{{ .ID }} {{ .Tag }}" 'bitbetter/*' | grep -E -v -- "CREATED|latest|${BW_VERSION}" | awk '{ ids = (ids ? ids FS $1 : $1) } END { print ids }' )
[ -n "$ids" ] && docker rmi $ids || true [ -n "$ids" ] && docker rmi $ids || true

View File

@@ -1,11 +1,13 @@
ARG BITWARDEN_TAG ARG BITWARDEN_TAG
FROM ${BITWARDEN_TAG} FROM ${BITWARDEN_TAG}
COPY bin/Debug/netcoreapp6.0/publish/* /bitBetter/ COPY bin/Release/net10.0/publish/* /bitBetter/
COPY ./.keys/cert.cert /newLicensing.cer COPY ./.keys/cert.cert /newLicensing.cer
RUN set -e; set -x; \ RUN set -e; set -x; \
dotnet /bitBetter/bitBetter.dll && \ if [ -f /app/Api ]; then EXEC=Api; else EXEC=Identity; fi && \
mv /app/Core.dll /app/Core.orig.dll && \ dotnet /bitBetter/bitBetter.dll /newLicensing.cer /app/$EXEC && \
mv /app/modified.dll /app/Core.dll && \ rm -f /app/$EXEC && \
rm -rf /bitBetter && rm -rf /newLicensing.cer printf '#!/bin/sh\nexec dotnet /app/%s.dll "$@"\n' "$EXEC" > /app/$EXEC && \
chmod +x /app/$EXEC && \
rm -rf /bitBetter /newLicensing.cer

View File

@@ -1,93 +1,154 @@
using System; using System;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using Mono.Cecil; using System.Text.Json.Nodes;
using Mono.Cecil.Cil; using Mono.Cecil;
using Mono.Cecil.Rocks; using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
namespace bitwardenSelfLicensor using SingleFileExtractor.Core;
{
class Program namespace BitwardenSelfLicensor
{ {
static int Main(string[] args) class Program
{ {
string cerFile; static int Main(string[] args)
string corePath; {
string cerFile = args.Length >= 1 ? args[0] : "/newLicensing.cer";
if(args.Length >= 2) { string inputPath = args.Length >= 2 ? args[1] : "/app/Api";
cerFile = args[0];
corePath = args[1]; string coreDllPath;
} else if (args.Length == 1) { string extractDir = Path.GetDirectoryName(Path.GetFullPath(inputPath));
cerFile = args[0];
corePath = "/app/Core.dll"; if (string.Equals(Path.GetExtension(inputPath), ".dll", StringComparison.OrdinalIgnoreCase))
} {
else { // Input is already a direct Core.dll path — skip bundle extraction
cerFile = "/newLicensing.cer"; coreDllPath = inputPath;
corePath = "/app/Core.dll"; }
} else
{
try
var module = ModuleDefinition.ReadModule(new MemoryStream(File.ReadAllBytes(corePath))); {
var cert = File.ReadAllBytes(cerFile); var reader = new ExecutableReader(inputPath);
reader.ExtractToDirectory(extractDir);
var x = module.Resources.OfType<EmbeddedResource>() Console.WriteLine($"Extracted bundle to {extractDir}");
.Where(r => r.Name.Equals("Bit.Core.licensing.cer")) coreDllPath = Path.Combine(extractDir, "Core.dll");
.First();
// The extracted runtimeconfig.json is in self-contained format (no "framework" key).
Console.WriteLine(x.Name); // Running "dotnet App.dll" requires framework-dependent format; without it .NET looks
// for libhostpolicy.so in the app dir (which isn't there) and crashes.
var e = new EmbeddedResource("Bit.Core.licensing.cer", x.Attributes, cert); FixRuntimeConfig(extractDir, Path.GetFileNameWithoutExtension(inputPath));
}
module.Resources.Add(e); catch (Exception ex)
module.Resources.Remove(x); {
Console.Error.WriteLine($"ERROR: Failed to extract single-file bundle '{inputPath}': {ex.Message}");
var services = module.Types.Where(t => t.Namespace == "Bit.Core.Services"); return 1;
}
}
var type = services.First(t => t.Name == "LicensingService");
Console.WriteLine($"Patching: {coreDllPath}");
var licensingType = type.Resolve();
var certBytes = File.ReadAllBytes(cerFile);
var existingCert = new X509Certificate2(x.GetResourceData()); var module = ModuleDefinition.ReadModule(new MemoryStream(File.ReadAllBytes(coreDllPath)));
Console.WriteLine($"Existing Cert Thumbprint: {existingCert.Thumbprint}"); // Replace embedded certificate resource
X509Certificate2 certificate = new X509Certificate2(cert); var existingRes = module.Resources
.OfType<EmbeddedResource>()
Console.WriteLine($"New Cert Thumbprint: {certificate.Thumbprint}"); .FirstOrDefault(r => r.Name == "Bit.Core.licensing.cer");
var ctor = licensingType.GetConstructors().Single(); if (existingRes == null)
{
Console.Error.WriteLine("ERROR: Embedded resource 'Bit.Core.licensing.cer' not found in Core.dll");
var rewriter = ctor.Body.GetILProcessor(); return 1;
}
var instToReplace =
ctor.Body.Instructions.Where(i => i.OpCode == OpCodes.Ldstr Console.WriteLine($"Found resource: {existingRes.Name}");
&& string.Equals((string)i.Operand, existingCert.Thumbprint, StringComparison.InvariantCultureIgnoreCase)) module.Resources.Add(new EmbeddedResource("Bit.Core.licensing.cer", existingRes.Attributes, certBytes));
.FirstOrDefault(); module.Resources.Remove(existingRes);
if(instToReplace != null) { var existingCert = X509CertificateLoader.LoadCertificate(existingRes.GetResourceData());
rewriter.Replace(instToReplace, Instruction.Create(OpCodes.Ldstr, certificate.Thumbprint)); var newCert = X509CertificateLoader.LoadCertificate(certBytes);
} Console.WriteLine($"Old thumbprint: {existingCert.Thumbprint}");
else { Console.WriteLine($"New thumbprint: {newCert.Thumbprint}");
Console.WriteLine("Cant find inst");
} // Find LicensingService by class name (namespace-agnostic to handle renames)
var type = module.Types.FirstOrDefault(t => t.Name == "LicensingService");
// foreach (var inst in ctor.Body.Instructions) if (type == null)
// { {
// Console.Write(inst.OpCode.Name + " " + inst.Operand?.GetType() + " = "); Console.Error.WriteLine("ERROR: LicensingService not found in Core.dll");
// if(inst.OpCode.FlowControl == FlowControl.Call) { return 1;
// Console.WriteLine(inst.Operand); }
// } Console.WriteLine($"Found: {type.FullName}");
// else if(inst.OpCode == OpCodes.Ldstr) {
// Console.WriteLine(inst.Operand); var ctor = type.Resolve().GetConstructors().First();
// } var rewriter = ctor.Body.GetILProcessor();
// else {Console.WriteLine();}
// } // Use Contains() to handle the hidden Unicode LRM character (\u200E) that Bitwarden
// prepends to the production thumbprint string literal in LicensingService.cs
module.Write("modified.dll"); // Replace ALL occurrences since const fields are inlined at compile time and used in
// multiple validation checks (both _creationCertificate and _verificationCertificates)
return 0; var instructionsToReplace = ctor.Body.Instructions
} .Where(i => i.OpCode == OpCodes.Ldstr)
} .Where(i => ((string)i.Operand)
} .Contains(existingCert.Thumbprint, StringComparison.OrdinalIgnoreCase))
.ToList();
if (instructionsToReplace.Count > 0)
{
Console.WriteLine($"Found {instructionsToReplace.Count} thumbprint Ldstr instruction(s) to replace");
foreach (var inst in instructionsToReplace)
{
Console.WriteLine($" Replacing: '{inst.Operand}'");
rewriter.Replace(inst, Instruction.Create(OpCodes.Ldstr, newCert.Thumbprint));
}
}
else
{
Console.WriteLine("WARNING: Thumbprint Ldstr not found — cert resource replaced anyway");
}
module.Write(coreDllPath);
Console.WriteLine("Done.");
return 0;
}
// Converts a self-contained runtimeconfig.json to framework-dependent so the app can be
// launched with "dotnet App.dll" using the system-installed ASP.NET Core runtime.
static void FixRuntimeConfig(string dir, string appName)
{
var path = Path.Combine(dir, $"{appName}.runtimeconfig.json");
if (!File.Exists(path))
{
Console.WriteLine($"runtimeconfig not found at {path}, skipping");
return;
}
var root = JsonNode.Parse(File.ReadAllText(path))!;
var opts = root["runtimeOptions"]!.AsObject();
// Derive framework name/version from the self-contained includedFrameworks before removing it
string fwName = "Microsoft.AspNetCore.App";
string fwVersion = "10.0.0";
if (opts["includedFrameworks"] is JsonArray included && included.Count > 0)
{
var first = included[0]!.AsObject();
fwName = first["name"]?.GetValue<string>() ?? fwName;
fwVersion = first["version"]?.GetValue<string>() ?? fwVersion;
}
// Remove self-contained markers
opts.Remove("includedFrameworks");
// Add framework-dependent reference (LatestPatch allows compatibility across patch releases only)
opts["framework"] = new JsonObject
{
["name"] = fwName,
["version"] = fwVersion
};
opts["rollForward"] = "LatestPatch";
File.WriteAllText(path, root.ToJsonString(new System.Text.Json.JsonSerializerOptions { WriteIndented = true }));
Console.WriteLine($"Fixed runtimeconfig: {path}");
}
}
}

View File

@@ -2,11 +2,12 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>netcoreapp6.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Mono.Cecil" Version="0.11.2" /> <PackageReference Include="Mono.Cecil" Version="0.11.2" />
<PackageReference Include="SingleFileExtractor.Core" Version="2.3.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -4,4 +4,4 @@ set -e
set -x set -x
dotnet restore dotnet restore
dotnet publish dotnet publish -c Release -o bin/Release/net10.0/publish

View File

@@ -1,4 +1,4 @@
FROM mcr.microsoft.com/dotnet/sdk:6.0 as build FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /licenseGen WORKDIR /licenseGen
@@ -12,6 +12,6 @@ RUN set -e; set -x; \
FROM bitbetter/api FROM bitbetter/api
COPY --from=build /licenseGen/bin/Debug/netcoreapp6.0/publish/* /app/ COPY --from=build /licenseGen/bin/Release/net10.0/publish/* /app/
ENTRYPOINT [ "dotnet", "/app/licenseGen.dll", "--core", "/app/Core.dll", "--cert", "/cert.pfx" ] ENTRYPOINT [ "dotnet", "/app/licenseGen.dll", "--core", "/app/Core.dll", "--executable", "/app/Api", "--cert", "/cert.pfx" ]

View File

@@ -1,37 +1,43 @@
using System; namespace BitwardenSelfLicensor
using System.IO;
using System.Linq;
using System.Runtime.Loader;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.CommandLineUtils;
using Newtonsoft.Json;
namespace bitwardenSelfLicensor
{ {
class Program using Microsoft.Extensions.CommandLineUtils;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using SingleFileExtractor.Core;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Runtime.Loader;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
public static class Program
{ {
static int Main(string[] args) public static int Main(string[] args)
{ {
var app = new Microsoft.Extensions.CommandLineUtils.CommandLineApplication(); var app = new CommandLineApplication();
var cert = app.Option("--cert", "cert file", CommandOptionType.SingleValue); var cert = app.Option("--cert", "cert file", CommandOptionType.SingleValue);
var coreDll = app.Option("--core", "path to core dll", CommandOptionType.SingleValue); var coreDll = app.Option("--core", "path to core dll", CommandOptionType.SingleValue);
var exec = app.Option("--executable", "path to Bitwarden single file executable", CommandOptionType.SingleValue);
bool certExists() bool ExecExists() => File.Exists(exec.Value());
bool CertExists() => File.Exists(cert.Value());
bool CoreExists() => File.Exists(coreDll.Value());
bool VerifyTopOptions() =>
!string.IsNullOrWhiteSpace(cert.Value()) &&
(!string.IsNullOrWhiteSpace(coreDll.Value()) || !string.IsNullOrWhiteSpace(exec.Value())) &&
CertExists() &&
(CoreExists() || ExecExists());
string GetExtractedDll()
{ {
return File.Exists(cert.Value()); var coreDllPath = Path.Combine("extract", "Core.dll");
} var reader = new ExecutableReader(exec.Value());
reader.ExtractToDirectory("extract");
bool coreExists() var fileInfo = new FileInfo(coreDllPath);
{ return fileInfo.FullName;
return File.Exists(coreDll.Value());
}
bool verifyTopOptions()
{
return !string.IsNullOrWhiteSpace(cert.Value()) &&
!string.IsNullOrWhiteSpace(coreDll.Value()) &&
certExists() && coreExists();
} }
string GetCoreDllPath() => CoreExists() ? coreDll.Value() : GetExtractedDll();
app.Command("interactive", config => app.Command("interactive", config =>
{ {
@@ -43,11 +49,11 @@ namespace bitwardenSelfLicensor
config.OnExecute(() => config.OnExecute(() =>
{ {
if (!verifyTopOptions()) if (!VerifyTopOptions())
{ {
if (!coreExists()) config.Error.WriteLine($"Cant find core dll at: {coreDll.Value()}"); if (!ExecExists() && !string.IsNullOrWhiteSpace(exec.Value())) config.Error.WriteLine($"Cant find single file executable at: {exec.Value()}");
if (!certExists()) config.Error.WriteLine($"Cant find certificate at: {cert.Value()}"); if (!CoreExists() && !string.IsNullOrWhiteSpace(coreDll.Value())) config.Error.WriteLine($"Cant find core dll at: {coreDll.Value()}");
if (!CertExists()) config.Error.WriteLine($"Cant find certificate at: {cert.Value()}");
config.ShowHelp(); config.ShowHelp();
return 1; return 1;
} }
@@ -92,7 +98,7 @@ namespace bitwardenSelfLicensor
WriteLineOver("Please enter a business name, default is BitBetter. [Business Name]:"); WriteLineOver("Please enter a business name, default is BitBetter. [Business Name]:");
buff = Console.ReadLine(); buff = Console.ReadLine();
if (buff == "") businessname = "BitBetter"; if (buff == "") businessname = "BitBetter";
else if (checkBusinessName(buff)) businessname = buff; else if (CheckBusinessName(buff)) businessname = buff;
} }
} }
else else
@@ -105,14 +111,14 @@ namespace bitwardenSelfLicensor
{ {
WriteLineOver("Please provide the username this license will be registered to. [username]:"); WriteLineOver("Please provide the username this license will be registered to. [username]:");
buff = Console.ReadLine(); buff = Console.ReadLine();
if ( checkUsername(buff) ) name = buff; if ( CheckUsername(buff) ) name = buff;
} }
while (email == "") while (email == "")
{ {
WriteLineOver("Please provide the email address for the user " + name + ". [email]"); WriteLineOver("Please provide the email address for the user " + name + ". [email]");
buff = Console.ReadLine(); buff = Console.ReadLine();
if ( checkEmail(buff) ) email = buff; if ( CheckEmail(buff) ) email = buff;
} }
while (storage == 0) while (storage == 0)
@@ -125,7 +131,7 @@ namespace bitwardenSelfLicensor
} }
else else
{ {
if (checkStorage(buff)) storage = short.Parse(buff); if (CheckStorage(buff)) storage = short.Parse(buff);
} }
} }
@@ -135,7 +141,7 @@ namespace bitwardenSelfLicensor
buff = Console.ReadLine(); buff = Console.ReadLine();
if ( buff == "" || buff == "y" || buff == "Y" ) if ( buff == "" || buff == "y" || buff == "Y" )
{ {
GenerateUserLicense(new X509Certificate2(cert.Value(), "test"), coreDll.Value(), name, email, storage, guid, null); GenerateUserLicense(X509CertificateLoader.LoadPkcs12FromFile(cert.Value(), "test"), GetCoreDllPath(), name, email, storage, guid, null);
} }
else else
{ {
@@ -149,7 +155,7 @@ namespace bitwardenSelfLicensor
buff = Console.ReadLine(); buff = Console.ReadLine();
if ( buff == "" || buff == "y" || buff == "Y" ) if ( buff == "" || buff == "y" || buff == "Y" )
{ {
GenerateOrgLicense(new X509Certificate2(cert.Value(), "test"), coreDll.Value(), name, email, storage, installid, businessname, null); GenerateOrgLicense(X509CertificateLoader.LoadPkcs12FromFile(cert.Value(), "test"), GetCoreDllPath(), name, email, storage, installid, businessname, null);
} }
else else
{ {
@@ -173,17 +179,11 @@ namespace bitwardenSelfLicensor
config.OnExecute(() => config.OnExecute(() =>
{ {
if (!verifyTopOptions()) if (!VerifyTopOptions())
{ {
if (!coreExists()) if (!ExecExists() && !string.IsNullOrWhiteSpace(exec.Value())) config.Error.WriteLine($"Cant find single file executable at: {exec.Value()}");
{ if (!CoreExists() && !string.IsNullOrWhiteSpace(coreDll.Value())) config.Error.WriteLine($"Cant find core dll at: {coreDll.Value()}");
config.Error.WriteLine($"Cant find core dll at: {coreDll.Value()}"); if (!CertExists()) config.Error.WriteLine($"Cant find certificate at: {cert.Value()}");
}
if (!certExists())
{
config.Error.WriteLine($"Cant find certificate at: {cert.Value()}");
}
config.ShowHelp(); config.ShowHelp();
return 1; return 1;
} }
@@ -214,7 +214,7 @@ namespace bitwardenSelfLicensor
storageShort = (short) parsedStorage; storageShort = (short) parsedStorage;
} }
GenerateUserLicense(new X509Certificate2(cert.Value(), "test"), coreDll.Value(), name.Value, email.Value, storageShort, userId, key.Value); GenerateUserLicense(X509CertificateLoader.LoadPkcs12FromFile(cert.Value(), "test"), GetCoreDllPath(), name.Value, email.Value, storageShort, userId, key.Value);
return 0; return 0;
}); });
@@ -231,17 +231,11 @@ namespace bitwardenSelfLicensor
config.OnExecute(() => config.OnExecute(() =>
{ {
if (!verifyTopOptions()) if (!VerifyTopOptions())
{ {
if (!coreExists()) if (!ExecExists() && !string.IsNullOrWhiteSpace(exec.Value())) config.Error.WriteLine($"Cant find single file executable at: {exec.Value()}");
{ if (!CoreExists() && !string.IsNullOrWhiteSpace(coreDll.Value())) config.Error.WriteLine($"Cant find core dll at: {coreDll.Value()}");
config.Error.WriteLine($"Cant find core dll at: {coreDll.Value()}"); if (!CertExists()) config.Error.WriteLine($"Cant find certificate at: {cert.Value()}");
}
if (!certExists())
{
config.Error.WriteLine($"Cant find certificate at: {cert.Value()}");
}
config.ShowHelp(); config.ShowHelp();
return 1; return 1;
} }
@@ -275,7 +269,7 @@ namespace bitwardenSelfLicensor
storageShort = (short) parsedStorage; storageShort = (short) parsedStorage;
} }
GenerateOrgLicense(new X509Certificate2(cert.Value(), "test"), coreDll.Value(), name.Value, email.Value, storageShort, installationId, businessName.Value, key.Value); GenerateOrgLicense(X509CertificateLoader.LoadPkcs12FromFile(cert.Value(), "test"), GetCoreDllPath(), name.Value, email.Value, storageShort, installationId, businessName.Value, key.Value);
return 0; return 0;
}); });
@@ -301,7 +295,7 @@ namespace bitwardenSelfLicensor
} }
// checkUsername Checks that the username is a valid username // checkUsername Checks that the username is a valid username
static bool checkUsername(string s) private static bool CheckUsername(string s)
{ {
if ( string.IsNullOrWhiteSpace(s) ) { if ( string.IsNullOrWhiteSpace(s) ) {
WriteLineOver("The username provided doesn't appear to be valid.\n"); WriteLineOver("The username provided doesn't appear to be valid.\n");
@@ -311,7 +305,7 @@ namespace bitwardenSelfLicensor
} }
// checkBusinessName Checks that the Business Name is a valid username // checkBusinessName Checks that the Business Name is a valid username
static bool checkBusinessName(string s) private static bool CheckBusinessName(string s)
{ {
if ( string.IsNullOrWhiteSpace(s) ) { if ( string.IsNullOrWhiteSpace(s) ) {
WriteLineOver("The Business Name provided doesn't appear to be valid.\n"); WriteLineOver("The Business Name provided doesn't appear to be valid.\n");
@@ -321,7 +315,7 @@ namespace bitwardenSelfLicensor
} }
// checkEmail Checks that the email address is a valid email address // checkEmail Checks that the email address is a valid email address
static bool checkEmail(string s) private static bool CheckEmail(string s)
{ {
if ( string.IsNullOrWhiteSpace(s) ) { if ( string.IsNullOrWhiteSpace(s) ) {
WriteLineOver("The email provided doesn't appear to be valid.\n"); WriteLineOver("The email provided doesn't appear to be valid.\n");
@@ -331,7 +325,7 @@ namespace bitwardenSelfLicensor
} }
// checkStorage Checks that the storage is in a valid range // checkStorage Checks that the storage is in a valid range
static bool checkStorage(string s) private static bool CheckStorage(string s)
{ {
if (string.IsNullOrWhiteSpace(s)) if (string.IsNullOrWhiteSpace(s))
{ {
@@ -347,23 +341,20 @@ namespace bitwardenSelfLicensor
} }
// WriteLineOver Writes a new line to console over last line. // WriteLineOver Writes a new line to console over last line.
static void WriteLineOver(string s) private static void WriteLineOver(string s)
{ {
Console.SetCursorPosition(0, Console.CursorTop -1); Console.SetCursorPosition(0, Console.CursorTop -1);
Console.WriteLine(s); Console.WriteLine(s);
} }
// WriteLine This wrapper is just here so that console writes all look similar. // WriteLine This wrapper is just here so that console writes all look similar.
static void WriteLine(string s) private static void WriteLine(string s) => Console.WriteLine(s);
{
Console.WriteLine(s);
}
static void GenerateUserLicense(X509Certificate2 cert, string corePath, string userName, string email, short storage, Guid userId, string key) private static void GenerateUserLicense(X509Certificate2 cert, string corePath, string userName, string email, short storage, Guid userId, string key)
{ {
var core = AssemblyLoadContext.Default.LoadFromAssemblyPath(corePath); var core = AssemblyLoadContext.Default.LoadFromAssemblyPath(corePath);
var type = core.GetType("Bit.Core.Models.Business.UserLicense"); var type = core.GetType("Bit.Core.Billing.Models.Business.UserLicense");
var licenseTypeEnum = core.GetType("Bit.Core.Enums.LicenseType"); var licenseTypeEnum = core.GetType("Bit.Core.Enums.LicenseType");
var license = Activator.CreateInstance(type); var license = Activator.CreateInstance(type);
@@ -373,32 +364,36 @@ namespace bitwardenSelfLicensor
type.GetProperty(name).SetValue(license, value); type.GetProperty(name).SetValue(license, value);
} }
set("LicenseKey", string.IsNullOrWhiteSpace(key) ? Guid.NewGuid().ToString("n") : key); var licenseKey = string.IsNullOrWhiteSpace(key) ? Guid.NewGuid().ToString("n") : key;
set("LicenseKey", licenseKey);
set("Id", userId); set("Id", userId);
set("Name", userName); set("Name", userName);
set("Email", email); set("Email", email);
set("Premium", true); set("Premium", true);
set("MaxStorageGb", storage == 0 ? short.MaxValue : storage); set("MaxStorageGb", storage == 0 ? short.MaxValue : storage);
set("Version", 1); set("Version", 1);
set("Issued", DateTime.UtcNow); var now = DateTime.UtcNow;
set("Refresh", DateTime.UtcNow.AddYears(100).AddMonths(-1)); set("Issued", now);
set("Expires", DateTime.UtcNow.AddYears(100)); set("Refresh", now.AddYears(100).AddMonths(-1));
set("Expires", now.AddYears(100));
set("Trial", false); set("Trial", false);
set("LicenseType", Enum.Parse(licenseTypeEnum, "User")); set("LicenseType", Enum.Parse(licenseTypeEnum, "User"));
set("Token", GenerateUserToken(cert, userId, licenseKey, userName, email, storage, now));
set("Hash", Convert.ToBase64String((byte[])type.GetMethod("ComputeHash").Invoke(license, new object[0]))); set("Hash", Convert.ToBase64String((byte[])type.GetMethod("ComputeHash").Invoke(license, new object[0])));
set("Signature", Convert.ToBase64String((byte[])type.GetMethod("Sign").Invoke(license, new object[] { cert }))); set("Signature", Convert.ToBase64String((byte[])type.GetMethod("Sign").Invoke(license, new object[] { cert })));
Console.WriteLine(JsonConvert.SerializeObject(license, Formatting.Indented)); Console.WriteLine(JsonConvert.SerializeObject(license, Formatting.Indented));
} }
static void GenerateOrgLicense(X509Certificate2 cert, string corePath, string userName, string email, short storage, Guid instalId, string businessName, string key) private static void GenerateOrgLicense(X509Certificate2 cert, string corePath, string userName, string email, short storage, Guid instalId, string businessName, string key)
{ {
var core = AssemblyLoadContext.Default.LoadFromAssemblyPath(corePath); var core = AssemblyLoadContext.Default.LoadFromAssemblyPath(corePath);
var type = core.GetType("Bit.Core.Models.Business.OrganizationLicense"); var type = core.GetType("Bit.Core.Billing.Organizations.Models.OrganizationLicense");
var licenseTypeEnum = core.GetType("Bit.Core.Enums.LicenseType"); var licenseTypeEnum = core.GetType("Bit.Core.Enums.LicenseType");
var planTypeEnum = core.GetType("Bit.Core.Enums.PlanType"); var planTypeEnum = core.GetType("Bit.Core.Billing.Enums.PlanType");
var license = Activator.CreateInstance(type); var license = Activator.CreateInstance(type);
@@ -407,21 +402,24 @@ namespace bitwardenSelfLicensor
type.GetProperty(name).SetValue(license, value); type.GetProperty(name).SetValue(license, value);
} }
set("LicenseKey", string.IsNullOrWhiteSpace(key) ? Guid.NewGuid().ToString("n") : key); var licenseKey = string.IsNullOrWhiteSpace(key) ? Guid.NewGuid().ToString("n") : key;
var businessNameFinal = string.IsNullOrWhiteSpace(businessName) ? "BitBetter" : businessName;
set("LicenseKey", licenseKey);
set("InstallationId", instalId); set("InstallationId", instalId);
set("Id", Guid.NewGuid()); set("Id", Guid.NewGuid());
set("Name", userName); set("Name", userName);
set("BillingEmail", email); set("BillingEmail", email);
set("BusinessName", string.IsNullOrWhiteSpace(businessName) ? "BitBetter" : businessName); set("BusinessName", businessNameFinal);
set("Enabled", true); set("Enabled", true);
set("Plan", "Custom"); set("Plan", "Enterprise (Annually)");
set("PlanType", Enum.Parse(planTypeEnum, "Custom")); set("PlanType", Enum.Parse(planTypeEnum, "EnterpriseAnnually"));
set("Seats", (int)short.MaxValue); set("Seats", int.MaxValue);
set("MaxCollections", short.MaxValue); set("MaxCollections", short.MaxValue);
set("UsePolicies", true); set("UsePolicies", true);
set("UseSso", true); set("UseSso", true);
set("UseKeyConnector", true); set("UseKeyConnector", true);
//set("UseScim", true); // available in version 10, which is not released yet set("UseScim", true);
set("UseGroups", true); set("UseGroups", true);
set("UseEvents", true); set("UseEvents", true);
set("UseDirectory", true); set("UseDirectory", true);
@@ -429,20 +427,142 @@ namespace bitwardenSelfLicensor
set("Use2fa", true); set("Use2fa", true);
set("UseApi", true); set("UseApi", true);
set("UseResetPassword", true); set("UseResetPassword", true);
set("UseCustomPermissions", true);
set("MaxStorageGb", storage == 0 ? short.MaxValue : storage); set("MaxStorageGb", storage == 0 ? short.MaxValue : storage);
set("SelfHost", true); set("SelfHost", true);
set("UsersGetPremium", true); set("UsersGetPremium", true);
set("Version", 9); set("UsePasswordManager", true);
set("Issued", DateTime.UtcNow); set("UseSecretsManager", true);
set("Refresh", DateTime.UtcNow.AddYears(100).AddMonths(-1)); set("SmSeats", int.MaxValue);
set("Expires", DateTime.UtcNow.AddYears(100)); set("SmServiceAccounts", int.MaxValue);
set("Version", 16);
var now = DateTime.UtcNow;
set("Issued", now);
set("Refresh", now.AddYears(100).AddMonths(-1));
set("Expires", now.AddYears(100));
set("ExpirationWithoutGracePeriod", now.AddYears(100));
set("Trial", false); set("Trial", false);
set("LicenseType", Enum.Parse(licenseTypeEnum, "Organization")); set("LicenseType", Enum.Parse(licenseTypeEnum, "Organization"));
set("LimitCollectionCreationDeletion", true);
set("AllowAdminAccessToAllCollectionItems", true);
set("UseRiskInsights", true);
set("UseOrganizationDomains", true);
set("UseAdminSponsoredFamilies", true);
set("UseAutomaticUserConfirmation", true);
set("UsePhishingBlocker", true);
set("UseDisableSmAdsForUsers", true);
set("UseMyItems", true);
var orgId = (Guid)type.GetProperty("Id").GetValue(license);
set("Token", GenerateOrgToken(cert, orgId, instalId, licenseKey, email, businessNameFinal, userName, storage, planTypeEnum, now));
set("Hash", Convert.ToBase64String((byte[])type.GetMethod("ComputeHash").Invoke(license, new object[0]))); set("Hash", Convert.ToBase64String((byte[])type.GetMethod("ComputeHash").Invoke(license, new object[0])));
set("Signature", Convert.ToBase64String((byte[])type.GetMethod("Sign").Invoke(license, new object[] { cert }))); set("Signature", Convert.ToBase64String((byte[])type.GetMethod("Sign").Invoke(license, new object[] { cert })));
Console.WriteLine(JsonConvert.SerializeObject(license, Formatting.Indented)); Console.WriteLine(JsonConvert.SerializeObject(license, Formatting.Indented));
} }
private static string GenerateUserToken(X509Certificate2 cert, Guid userId, string licenseKey, string name, string email, short maxStorageGb, DateTime now)
{
var secKey = new X509SecurityKey(cert);
var creds = new SigningCredentials(secKey, SecurityAlgorithms.RsaSha256);
var expires = now.AddYears(100);
var claims = new List<Claim>
{
new Claim("LicenseType", "User"),
new Claim("LicenseKey", licenseKey),
new Claim("Id", userId.ToString()),
new Claim("Name", name),
new Claim("Email", email),
new Claim("Premium", "true"),
new Claim("MaxStorageGb", (maxStorageGb == 0 ? short.MaxValue : maxStorageGb).ToString()),
new Claim("Trial", "false"),
new Claim("Issued", now.ToString("o")),
new Claim("Expires", expires.ToString("o")),
new Claim("Refresh", now.AddYears(100).AddMonths(-1).ToString("o")),
};
var handler = new JwtSecurityTokenHandler();
var token = new JwtSecurityToken(
issuer: "bitwarden",
audience: $"user:{userId}",
claims: claims,
notBefore: now,
expires: expires,
signingCredentials: creds);
return handler.WriteToken(token);
}
private static string GenerateOrgToken(X509Certificate2 cert, Guid orgId, Guid installationId, string licenseKey, string billingEmail, string businessName, string name, short maxStorageGb, Type planTypeEnum, DateTime now)
{
var secKey = new X509SecurityKey(cert);
var creds = new SigningCredentials(secKey, SecurityAlgorithms.RsaSha256);
var expires = now.AddYears(100);
// Resolve the integer value of EnterpriseAnnually from the runtime enum
var planTypeInt = Convert.ToInt32(Enum.Parse(planTypeEnum, "EnterpriseAnnually"));
var claims = new List<Claim>
{
new Claim("LicenseType", "Organization"),
new Claim("LicenseKey", licenseKey),
new Claim("InstallationId", installationId.ToString()),
new Claim("Id", orgId.ToString()),
new Claim("Name", name),
new Claim("BillingEmail", billingEmail),
new Claim("BusinessName", businessName),
new Claim("Enabled", "true"),
new Claim("Plan", "Enterprise (Annually)"),
new Claim("PlanType", planTypeInt.ToString()),
new Claim("Seats", int.MaxValue.ToString()),
new Claim("MaxCollections", short.MaxValue.ToString()),
new Claim("MaxStorageGb", (maxStorageGb == 0 ? short.MaxValue : maxStorageGb).ToString()),
new Claim("SelfHost", "true"),
new Claim("UsersGetPremium", "true"),
new Claim("UseGroups", "true"),
new Claim("UseDirectory", "true"),
new Claim("UseEvents", "true"),
new Claim("UseTotp", "true"),
new Claim("Use2fa", "true"),
new Claim("UseApi", "true"),
new Claim("UsePolicies", "true"),
new Claim("UseSso", "true"),
new Claim("UseResetPassword", "true"),
new Claim("UseKeyConnector", "true"),
new Claim("UseScim", "true"),
new Claim("UseCustomPermissions", "true"),
new Claim("UsePasswordManager", "true"),
new Claim("UseSecretsManager", "true"),
new Claim("SmSeats", int.MaxValue.ToString()),
new Claim("SmServiceAccounts", int.MaxValue.ToString()),
new Claim("UseRiskInsights", "true"),
new Claim("UseAdminSponsoredFamilies", "true"),
new Claim("UseOrganizationDomains", "true"),
new Claim("UseAutomaticUserConfirmation", "true"),
new Claim("UseDisableSmAdsForUsers", "true"),
new Claim("UsePhishingBlocker", "true"),
new Claim("UseMyItems", "true"),
new Claim("LimitCollectionCreationDeletion", "true"),
new Claim("AllowAdminAccessToAllCollectionItems", "true"),
new Claim("Trial", "false"),
new Claim("Issued", now.ToString("o")),
new Claim("Expires", expires.ToString("o")),
new Claim("Refresh", now.AddYears(100).AddMonths(-1).ToString("o")),
new Claim("ExpirationWithoutGracePeriod", expires.ToString("o")),
};
var handler = new JwtSecurityTokenHandler();
var token = new JwtSecurityToken(
issuer: "bitwarden",
audience: $"organization:{orgId}",
claims: claims,
notBefore: now,
expires: expires,
signingCredentials: creds);
return handler.WriteToken(token);
}
} }
} }

View File

@@ -1,14 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>netcoreapp6.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.CommandLineUtils" Version="1.1.1" /> <PackageReference Include="Microsoft.Extensions.CommandLineUtils" Version="1.1.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="SingleFileExtractor.Core" Version="2.3.0" />
<PackageReference Include="System.Runtime.Loader" Version="4.3.0" /> <PackageReference Include="System.Runtime.Loader" Version="4.3.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.17.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -1,4 +1,6 @@
#!/bin/bash #!/bin/bash
set -e
ask () { ask () {
local __resultVar=$1 local __resultVar=$1
local __result="$2" local __result="$2"
@@ -9,7 +11,13 @@ ask () {
} }
SCRIPT_BASE="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" SCRIPT_BASE="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
BW_VERSION=$(curl -sL https://go.btwrdn.co/bw-sh-versions | grep '^ *"'coreVersion'":' | awk -F\: '{ print $2 }' | sed -e 's/,$//' -e 's/^"//' -e 's/"$//')
# Check prerequisite libraries and executables
for cmd in docker curl openssl jq; do
command -v "$cmd" >/dev/null 2>&1 || { echo "Error: '$cmd' is required but not installed." >&2; exit 1; }
done
BW_VERSION=$(curl -fsSL https://raw.githubusercontent.com/bitwarden/self-host/refs/heads/main/version.json | jq -er '.versions.coreVersion')
echo "Starting Bitwarden update, newest server version: $BW_VERSION" echo "Starting Bitwarden update, newest server version: $BW_VERSION"
@@ -32,14 +40,14 @@ RECREATE_OV=${tmprecreate:-$RECREATE_OV}
if [[ $RECREATE_OV =~ ^[Yy]$ ]] if [[ $RECREATE_OV =~ ^[Yy]$ ]]
then then
{ {
echo "version: '3'"
echo ""
echo "services:" echo "services:"
echo " api:" echo " api:"
echo " image: bitbetter/api:$BW_VERSION" echo " image: bitbetter/api:$BW_VERSION"
echo " pull_policy: never"
echo "" echo ""
echo " identity:" echo " identity:"
echo " image: bitbetter/identity:$BW_VERSION" echo " image: bitbetter/identity:$BW_VERSION"
echo " pull_policy: never"
echo "" echo ""
} > $BITWARDEN_BASE/bwdata/docker/docker-compose.override.yml } > $BITWARDEN_BASE/bwdata/docker/docker-compose.override.yml
echo "BitBetter docker-compose override created!" echo "BitBetter docker-compose override created!"
@@ -48,11 +56,9 @@ else
fi fi
# Check if user wants to rebuild the bitbetter images # Check if user wants to rebuild the bitbetter images
docker images bitbetter/api --format="{{ .Tag }}" | grep -F -- "${BW_VERSION}" > /dev/null
retval=$?
REBUILD_BB="n" REBUILD_BB="n"
REBUILD_BB_DESCR="[y/N]" REBUILD_BB_DESCR="[y/N]"
if [ $retval -ne 0 ]; then if ! docker images bitbetter/api --format="{{ .Tag }}" | grep -F -- "${BW_VERSION}" > /dev/null; then
REBUILD_BB="y" REBUILD_BB="y"
REBUILD_BB_DESCR="[Y/n]" REBUILD_BB_DESCR="[Y/n]"
fi fi
@@ -71,7 +77,7 @@ cd $BITWARDEN_BASE
./bitwarden.sh updateself ./bitwarden.sh updateself
# Update the bitwarden.sh: automatically patch run.sh to fix docker-compose pull errors for private images # Update the bitwarden.sh: automatically patch run.sh to fix docker-compose pull errors for private images
awk '1;/function downloadRunFile/{c=6}c&&!--c{print "sed -i '\''s/dccmd pull/dccmd pull --ignore-pull-failures || true/g'\'' $SCRIPTS_DIR/run.sh"}' $BITWARDEN_BASE/bitwarden.sh > tmp_bw.sh && mv tmp_bw.sh $BITWARDEN_BASE/bitwarden.sh sed -i 's/chmod u+x $SCRIPTS_DIR\/run.sh/chmod u+x $SCRIPTS_DIR\/run.sh\n sed -i \x27s\/dccmd pull\/dccmd pull --ignore-pull-failures || true\/g\x27 $SCRIPTS_DIR\/run.sh/g' -i $BITWARDEN_BASE/bitwarden.sh
chmod +x $BITWARDEN_BASE/bitwarden.sh chmod +x $BITWARDEN_BASE/bitwarden.sh
echo "Patching bitwarden.sh completed..." echo "Patching bitwarden.sh completed..."