-
Notifications
You must be signed in to change notification settings - Fork 1
/
Export-Bitwarden.psm1
417 lines (340 loc) · 14.5 KB
/
Export-Bitwarden.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#!/usr/bin/pwsh
# Bitwarden Vault Export Script
# Author: David H (@dh024)
#
# This script will backup the following:
# - personal vault contents, password encrypted (or unencrypted)
# - organizational vault contents (passwd encrypted or unencrypted)
# - file attachments
# It will also report on whether there were items in the Trash that
# could not be exported.
#
# Converted to a PowerShell Script by Thomas Parkison.
function Export-Bitwarden { # Don't touch this line!
param (
[switch]$forcebwcliupdate,
[switch]$forcelogout
)
# This tells the script if it should automatically check for an update of the Bitwarden CLI executable that's actually responsible for backing up your Bitwarden vault.
# It does this by taking the version of your currently existing Bitwarden CLI and comparing it to the version that's contained in a small text file that's on my GitHub
# page. Now, if you don't want this to happen, you can disable this kind of functionality in the script by setting the value of the $checkForBWCliUpdate to $false.
# However, it's highly recommended that you do keep this setting enabled since keeping your Bitwarden CLI up to date is obviously a good thing to do.
$checkForBWCliUpdate = $true
if ($forcebwcliupdate) { $checkForBWCliUpdate = $true }
$currentLocation = Get-Location
try {
# ====================================================
# == WARNING!!! DO NOT TOUCH ANYTHING BELOW THIS!!! ==
# ====================================================
$ver = "1.48"
Write-Host -ForegroundColor Green "========================================================================================"
Write-Host -ForegroundColor Green "== Bitwarden Vault Export Script v$ver =="
Write-Host -ForegroundColor Green "== Originally created by David H, converted to a Powershell Script by Thomas Parkison =="
Write-Host -ForegroundColor Green "== https://github.com/trparky/Bitwarden-Vault-Export-Script =="
Write-Host -ForegroundColor Green "========================================================================================"
Write-Host ""
try {
$jsonData = (Invoke-WebRequest -Uri "https://api.github.com/repos/trparky/Bitwarden-Vault-Export-Script/releases/latest").Content | ConvertFrom-Json
$scriptVersionFromWeb = ($jsonData.tag_name) -replace "v", ""
}
catch { $scriptVersionFromWeb = $ver }
if ($scriptVersionFromWeb -ne $ver) {
Write-Host -ForegroundColor Green "Notice:" -NoNewline
if ($PSScriptRoot -Match "powershell/Modules" || $PSScriptRoot -Match "powershell\\Modules") {
Write-Host " There is an update to this script, please execute Update-Module at the Powershell prompt."
}
else {
Write-Host " There is an update to this script, please go to https://github.com/trparky/Bitwarden-Vault-Export-Script and download the new version."
}
Write-Host ""
}
function DownloadBWCli {
$zipFilePath = (Join-Path $PSScriptRoot "bw.zip")
$baseDownloadURL = "https://vault.bitwarden.com/download/?app=cli&platform="
if ($IsWindows) { Invoke-WebRequest -Uri ($baseDownloadURL + "windows") -OutFile $zipFilePath }
elseif ($IsLinux) { Invoke-WebRequest -Uri ($baseDownloadURL + "linux") -OutFile $zipFilePath }
elseif ($IsMacOS) { Invoke-WebRequest -Uri ($baseDownloadURL + "macos") -OutFile $zipFilePath }
Set-Location -Path $PSScriptRoot
Expand-Archive -Path $zipFilePath
if ($IsLinux || $IsMacOS) {
Move-Item -Path (Join-Path $PSScriptRoot "bw" "bw") -Destination (Join-Path $PSScriptRoot "bw.tmp")
Remove-Item -Force (Join-Path $PSScriptRoot "bw")
Move-Item -Path (Join-Path $PSScriptRoot "bw.tmp") -Destination (Join-Path $PSScriptRoot "bw")
chmod 755 (Join-Path $PSScriptRoot "bw")
}
elseif ($IsWindows) {
if (Test-Path -Path (Join-Path $PSScriptRoot "bw" "bw.exe")) {
Move-Item -Path (Join-Path $PSScriptRoot "bw" "bw.exe") -Destination (Join-Path $PSScriptRoot "bw.exe")
Remove-Item -Force (Join-Path $PSScriptRoot "bw")
}
}
Remove-Item -Path $zipFilePath
Write-Host " Done."
Write-Host ""
}
function ValidateEmailAddress {
param (
[string]$email
)
# Pattern comes from https://emailregex.com/index.html
$emailPattern = '\A(?:(?:[a-z0-9!#$%&''*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&''*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\]))\Z'
$regex = New-Object System.Text.RegularExpressions.Regex $emailPattern
return $regex.IsMatch($email)
}
function ShouldWeCheckForABWCLIUpdate {
$currentDate = Get-Date
$checkForLastUpdateFile = Join-Path $PSScriptRoot "lastcheckforupdate.txt"
if (!(Test-Path -Path $checkForLastUpdateFile)) {
$currentDate | Out-File -FilePath $checkForLastUpdateFile -NoNewline
return $true
}
else {
$storedDate = Get-Content -Path $checkForLastUpdateFile
try {
$storedDateTime = [DateTime]::Parse($storedDate)
$daysDifference = (Get-Date) - $storedDateTime
if ($daysDifference.Days -gt 10) {
$currentDate | Out-File -FilePath $checkForLastUpdateFile -NoNewline
return $true
}
else { return $false }
}
catch {
$currentDate | Out-File -FilePath $checkForLastUpdateFile
return $true
}
}
}
function ConvertSecureString {
param (
[System.Security.SecureString]$String
)
if ($String.Length -eq 0) { return "" }
else {
$output = ConvertFrom-SecureString -SecureString $String -AsPlainText
return $output.Trim()
}
}
function AskYesNoQuestion {
param (
[String]$prompt
)
$answer = ""
do {
$answer = (Read-Host $prompt).ToLower().Trim()
} while ($answer -ne 'y' -and $answer -ne 'n')
return $answer
}
function LockAndLogout {
& $bwCliBinName lock
Write-Host ""
& $bwCliBinName logout
Write-Host ""
}
if ($IsWindows) { $bwCliBinName = (Join-Path $PSScriptRoot "bw.exe") }
else { $bwCliBinName = (Join-Path $PSScriptRoot "bw") }
if (!(Test-Path -Path $bwCliBinName)) {
Write-Host "Bitwarden CLI application not found, downloading... Please Wait." -NoNewLine
DownloadBWCli
Get-Date | Out-File -FilePath (Join-Path $PSScriptRoot "lastcheckforupdate.txt") -NoNewline
}
else {
if (($checkForBWCliUpdate) -and (($forcebwcliupdate) -or (ShouldWeCheckForABWCLIUpdate))) {
if ($forcebwcliupdate) {
Write-Host -ForegroundColor Green "Notice:" -NoNewLine
Write-Host " Script executed with ForceBWCliUpdate flag." -NoNewLine
}
$localBWCliVersion = ((& $bwCliBinName --version) | Out-String).Trim()
$remoteBWCliVersion = (Invoke-WebRequest -Uri "https://trparky.github.io/bwcliversion.txt").Content.Trim()
if ($localBWCliVersion -ne $remoteBWCliVersion) {
Write-Host ""
Write-Host ""
Write-Host "Bitwarden CLI application update found, downloading... Please Wait." -NoNewLine
Remove-Item -Path $bwCliBinName
DownloadBWCli
}
else {
Write-Host " No update found."
Write-Host ""
}
}
}
if ((& $bwCliBinName status | ConvertFrom-Json).status -eq "unlocked") {
Write-Host -ForegroundColor Green "Notice:" -NoNewLine
Write-Host " Active Bitwarden CLI login session detected, using existing login session."
Write-Host "The next step will ask for your Bitwarden username but only for the sake of knowing where to save your exported data."
Write-Host ""
}
if ($forcelogout) {
LockAndLogout
Write-Host "Exiting script."
$env:BW_SESSION = ""
$bwPasswordEncrypted = ""
$bwPasswordPlainText = ""
$password1Encrypted = ""
$password1PlainText = ""
$password2Encrypted = ""
$password2PlainText = ""
return
}
# Prompt user for their Bitwarden username
$userEmail = Read-Host "Enter your Bitwarden Username"
if (!(ValidateEmailAddress -email $userEmail)) {
Write-Host -ForegroundColor Red "ERROR:" -NoNewline
Write-Host " Invalid email address. Script halted."
return
}
$saveFolder = Join-Path $currentLocation $userEmail
if ($IsWindows) { $saveFolder = $saveFolder + "\" }
else { $saveFolder = $saveFolder + "/" }
$saveFolderAttachments = Join-Path $saveFolder "attachments"
if (!(Test-Path -Path $saveFolder)) { New-Item -ItemType Directory -Path $saveFolder | Out-Null }
if ((& $bwCliBinName status | ConvertFrom-Json).status -ne "unlocked") {
# Prompt user for their Bitwarden password
$bwPasswordEncrypted = Read-Host "Enter your Bitwarden Password" -AsSecureString
Write-Host ""
# Login user if not already authenticated
if ((& $bwCliBinName status | ConvertFrom-Json).status -eq "unauthenticated") {
Write-Host "Performing login..."
$bwPasswordPlainText = ConvertSecureString -String $bwPasswordEncrypted
& $bwCliBinName login "$userEmail" "$bwPasswordPlainText" --quiet
}
if ((& $bwCliBinName status | ConvertFrom-Json).status -eq "unauthenticated") {
Write-Host -ForegroundColor Red "ERROR:" -NoNewLine
Write-Host " Failed to authenticate."
return
}
# Unlock the vault
$bwPasswordPlainText = ConvertSecureString -String $bwPasswordEncrypted
$sessionKey = (& $bwCliBinName unlock "$bwPasswordPlainText" --raw) | Out-String
# Verify that unlock succeeded
if ([String]::IsNullOrWhiteSpace($sessionKey)) {
Write-Host -ForegroundColor Red "ERROR:" -NoNewLine
Write-Host " Failed to authenticate."
return
}
else { Write-Host "Login successful." }
# Export the session key as an env variable (needed by bw.exe CLI)
$env:BW_SESSION = $sessionKey
}
$encryptedDataBackup = $false
Write-Host ""
if ((AskYesNoQuestion -prompt "Do you want to encrypt your backup? [y/n]") -eq "y") {
# Prompt the user for an encryption password
$password1Encrypted = Read-Host "Enter a password to encrypt your vault" -AsSecureString
$password1PlainText = ConvertSecureString -String $password1Encrypted
$password2Encrypted = Read-Host "Enter the same password for verification" -AsSecureString
$password2PlainText = ConvertSecureString -String $password2Encrypted
if ($password1PlainText -ne $password2PlainText) {
Write-Host -ForegroundColor Red "ERROR:" -NoNewLine
Write-Host " The passwords did not match."
LockAndLogout
$env:BW_SESSION = ""
$bwPasswordEncrypted = ""
$bwPasswordPlainText = ""
$password1Encrypted = ""
$password1PlainText = ""
$password2Encrypted = ""
$password2PlainText = ""
return
}
else {
Write-Host "Password verified. Be sure to save your password in a safe place!"
$encryptedDataBackup = $true
}
}
else {
Write-Host -ForegroundColor Yellow "WARNING!" -NoNewLine
Write-Host " Your vault contents will be saved to an unencrypted file."
if ((AskYesNoQuestion -prompt "Continue? [y/n]") -eq "n") {
LockAndLogout
Write-Host "Exiting script."
$env:BW_SESSION = ""
$bwPasswordEncrypted = ""
$bwPasswordPlainText = ""
$password1Encrypted = ""
$password1PlainText = ""
$password2Encrypted = ""
$password2PlainText = ""
return
}
}
Write-Host ""
Write-Host "Performing vault exports..."
Write-Host ""
if (!$encryptedDataBackup) {
Write-Host "Exporting personal vault to an unencrypted file..."
& $bwCliBinName export --format json --output $saveFolder
Write-Host ""
}
else {
Write-Host "Exporting personal vault to a password-encrypted file..."
& $bwCliBinName export --format encrypted_json --password "$password1PlainText" --output $saveFolder
Write-Host ""
}
$organizations = (& $bwCliBinName list organizations | ConvertFrom-Json)
if ($organizations.Count -gt 0) {
foreach ($organization in $organizations) {
$organizationID = $organization.id
$organizationName = $organization.name
if (!$encryptedDataBackup) {
Write-Host "Exporting organization vault for organization ""$organizationName"" to an unencrypted file..."
& $bwCliBinName export --organizationid $organizationID --format json --output $saveFolder
Write-Host ""
}
else {
Write-Host "Exporting organization vault for organization ""$organizationName"" to a password-encrypted file..."
& $bwCliBinName export --organizationid $organizationID --format encrypted_json --password "$password1PlainText" --output $saveFolder
Write-Host ""
}
}
}
else { Write-Host "No organizational vault exists, so nothing to export." }
# 3. Download all attachments (file backup)
# First download attachments in vault
$itemsWithAttachments = (& $bwCliBinName list items | ConvertFrom-Json | Where-Object { $null -ne $_.attachments })
if ($itemsWithAttachments.Count -gt 0) {
Write-Host "Saving attachments..."
foreach ($item in $itemsWithAttachments) {
foreach ($attachment in $item.attachments) {
$filePath = Join-Path $saveFolderAttachments $item.name
if ($IsWindows) { $filePath = $filePath + "\" }
else { $filePath = $filePath + "/" }
& $bwCliBinName get attachment "$($attachment.fileName)" --itemid $item.id --output $filePath
if ($IsWindows) { Write-Host "" }
}
}
}
else { Write-Host "No attachments exist, so nothing to export." }
Write-Host -ForegroundColor Green "Vault export complete."
# 4. Report items in the Trash (cannot be exported)
$trashCount = (& $bwCliBinName list items --trash | ConvertFrom-Json).Count
if ($trashCount -gt 0) {
Write-Host -ForegroundColor Yellow "Note:" -NoNewLine
Write-Host " You have $trashCount items in the trash that cannot be exported."
}
LockAndLogout
if ((AskYesNoQuestion -prompt "Compress? [y/n]") -eq "y") {
Write-Host "Compressing backup..." -NoNewLine
Set-Location -Path $saveFolder
$zipFileTestPath = Join-Path ".." "$userEmail.zip"
if (Test-Path $zipFileTestPath) { Remove-Item -Path $zipFileTestPath }
Compress-Archive -Path * -DestinationPath "$userEmail.zip" -Force
Move-Item -Path "$userEmail.zip" -Destination ..
Set-Location -Path ..
Remove-Item -Path $saveFolder -Recurse -Force
Write-Host " Done."
}
Write-Host -ForegroundColor Green "Script completed."
}
finally {
$env:BW_SESSION = ""
$bwPasswordEncrypted = ""
$bwPasswordPlainText = ""
$password1Encrypted = ""
$password1PlainText = ""
$password2Encrypted = ""
$password2PlainText = ""
Set-Location -Path $currentLocation
}
}