-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrewerse-engineering.ps1
More file actions
341 lines (289 loc) · 11.7 KB
/
rewerse-engineering.ps1
File metadata and controls
341 lines (289 loc) · 11.7 KB
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
param (
[parameter(Mandatory=$false)]
$WorkingDirectory,
[parameter(Mandatory=$false)]
$ApkFile,
[parameter(Mandatory = $false, ParameterSetName = "DefaultPath")]
[switch]$Pfx,
[parameter(Mandatory = $true, ParameterSetName = "CustomPath")]
[string]$PfxPath,
[parameter(Mandatory = $false)]
[switch]$Dl
)
# ——————————————————————————————————————————————————————————————————————————————
# Functions
# ——————————————————————————————————————————————————————————————————————————————
# APK download target version; update if this version is no longer available on UpToDown
$targetVersion = "5.11.0"
function Get-ApkVersionUrl {
try {
$response = Invoke-WebRequest -UseBasicParsing -Uri "https://rewe.en.uptodown.com/android/versions"
$content = $response.Content
# Find div with data-url, data-version-id, data-extra-url that contains target version
# HTML: <div data-url="URL" data-version-id="ID" data-extra-url="download">...<span class="version">VERSION</span>
$escapedVersion = [regex]::Escape($targetVersion)
if ($content -match "<div[^>]*data-url=`"([^`"]+)`"[^>]*data-version-id=`"([^`"]+)`"[^>]*data-extra-url=`"([^`"]+)`"[^>]*>[\s\S]*?<span[^>]*class=`"version`"[^>]*>$escapedVersion</span>") {
$baseUrl = $Matches[1]
$versionId = $Matches[2]
$extraUrl = $Matches[3]
return "$baseUrl/$extraUrl/$versionId"
}
Write-Error "Target version $targetVersion not found on the page"
return $null
} catch {
Write-Error "Error extracting download URL: $_"
return $null
}
}
function Get-ApkDownloadUrl {
[CmdletBinding()]
param()
try {
# Get the initial URL for the app version page
$initialUrl = Get-ApkVersionUrl
if ($null -eq $initialUrl) {
Write-Error "Failed to get initial URL"
return $null
}
Write-Verbose "Initial URL: $initialUrl"
# Request the version page
$versionPageResponse = Invoke-WebRequest -UseBasicParsing -Uri $initialUrl
$content = $versionPageResponse.Content
# Extract data-version from button.variants
if ($content -notmatch 'class="button variants"[^>]*data-version="([^"]+)"') {
Write-Error "Could not find variants button"
return $null
}
$dataVersion = $Matches[1]
Write-Verbose "Data Version: $dataVersion"
# Extract data-code from #detail-app-name
if ($content -notmatch 'id="detail-app-name"[^>]*data-code="([^"]+)"') {
Write-Error "Could not find app name element"
return $null
}
$dataCode = $Matches[1]
Write-Verbose "Data Code: $dataCode"
# Construct and request the variants URL
$variantsUrl = "https://rewe.en.uptodown.com/app/$dataCode/version/$dataVersion/files"
Write-Verbose "Variants URL: $variantsUrl"
$variantsResponse = Invoke-WebRequest -UseBasicParsing -Uri $variantsUrl
$jsonResponse = $variantsResponse.Content | ConvertFrom-Json
$htmlContent = $jsonResponse.content
# Extract URL from onclick in v-version div
# HTML: <div class="v-version" onclick="...location.href='URL';">
if ($htmlContent -match 'class="v-version"[^>]*onclick="[^"]*location\.href=''([^'']+)''') {
$downloadUrl = $Matches[1]
Write-Verbose "Found download URL: $downloadUrl"
return $downloadUrl
}
Write-Error "Could not find download URL in variants"
return $null
} catch {
Write-Error "Error extracting download URL: $_"
return $null
}
}
function Export-PfxToPemKey {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$PfxPath,
[Parameter(Mandatory = $true)]
[string]$WorkingDirectory
)
try {
# Create X509Certificate2 object from the PFX file
$Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2(
$PfxPath,
"NC3hDTstMX9waPPV",
[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable
)
# Export certificate to PEM format
$PemPath = Join-Path -Path $WorkingDirectory -ChildPath "certificate.pem"
$CertBytes = $Cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
$Base64Cert = [Convert]::ToBase64String($CertBytes)
$PemContent = "-----BEGIN CERTIFICATE-----`r`n$Base64Cert`r`n-----END CERTIFICATE-----"
Set-Content -Path $PemPath -Value $PemContent
# Export private key
$KeyPath = Join-Path -Path $WorkingDirectory -ChildPath "private.key"
try {
if ($IsLinux) {
$RSA = [System.Security.Cryptography.RSA]::Create()
$KeyBytes = $Cert.PrivateKey.ExportPkcs8PrivateKey()
} else {
$RSACng = [Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($Cert)
$KeyBytes = $RSACng.Key.Export([Security.Cryptography.CngKeyBlobFormat]::Pkcs8PrivateBlob)
}
$KeyBase64 = [Convert]::ToBase64String($KeyBytes, [Base64FormattingOptions]::InsertLineBreaks)
Set-Content -Path $KeyPath -Value @"
-----BEGIN PRIVATE KEY-----
$KeyBase64
-----END PRIVATE KEY-----
"@
} finally {
if ($null -ne $RSA) {
$RSA.Dispose()
}
}
Write-Host "Keys exported successfully."
return @{
CertificatePath = $PemPath
PrivateKeyPath = $KeyPath
}
}
catch {
Write-Error "Error exporting PFX to PEM and key: $_"
throw
}
}
function Download-ReweApk {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$WorkingDirectory
)
# Ensure the working directory exists
if (-not (Test-Path -Path $WorkingDirectory -PathType Container)) {
New-Item -Path $WorkingDirectory -ItemType Directory -Force | Out-Null
Write-Host "Created working directory: $WorkingDirectory"
}
# Function to get the APK download base URL
$BaseUrl = Get-ApkDownloadUrl
try {
# Send a request to the URL, then extract the dynamic download link from the response
$Response = Invoke-WebRequest -Uri $BaseUrl -UseBasicParsing
if ($response.StatusCode -ne 200) {
throw "Issue getting data-url"
}
} catch {
Write-Error "Failed to fetch the APK. Download the apk manually from https://rewe.en.uptodown.com/android/"
return
}
# Match the download data-url (the one with data-download-version attribute)
if ($Response.Content -match 'data-url="([^"]+)"[^>]*data-download-version=') {
$DataUrl = $matches[1]
} else {
Write-Error "No data-url found in the response content."
return
}
# Downloading the file
Write-Host "Starting download. Please wait..."
$ApkUrl = "https://dw.uptodown.com/dwn/$DataUrl"
$ApkFile = Join-Path -Path $WorkingDirectory -ChildPath "rewe.apk"
Invoke-WebRequest -Uri $ApkUrl -OutFile $ApkFile -UseBasicParsing
Write-Host "Done"
return $ApkFile
}
# ——————————————————————————————————————————————————————————————————————————————
# Main
# ——————————————————————————————————————————————————————————————————————————————
# Handle working directory
# Make absolute and check it's existence
if (-not $WorkingDirectory) {
$WorkingDirectory = "."
}
$ResWD = (Resolve-Path -Path $WorkingDirectory -ErrorAction SilentlyContinue)
if (-not $ResWD) {
Write-Error "The specified directory '$WorkingDirectory' does not exist."
return
} else {
$WorkingDirectory = $ResWD.Path
}
Write-Host "Working Directory: $WorkingDirectory"
Write-Host "Starting..."
Write-Host "------------------"
if ($Pfx -or $PfxPath) {
$PfxFileToUse = if ($Pfx) {
Join-Path -Path $WorkingDirectory -ChildPath "mtls_prod.pfx"
} else {
$PfxPath
}
if (-not [System.IO.Path]::IsPathRooted($PfxFileToUse)) {
$PfxFileToUse = [System.IO.Path]::GetFullPath((Join-Path -Path (Get-Location) -ChildPath $PfxFileToUse))
}
# Validate that the PFX file exists
if (-not (Test-Path -Path $PfxFileToUse -PathType Leaf)) {
Write-Error "PFX file not found: $PfxFileToUse"
exit 1
}
# Call the Export-PfxToPemKey function
try {
Write-Host "Exporting PFX file: $PfxFileToUse"
$result = Export-PfxToPemKey -PfxPath $PfxFileToUse -WorkingDirectory $WorkingDirectory
Write-Host "Certificate: $($result.CertificatePath)"
Write-Host "Private Key: $($result.PrivateKeyPath)"
} catch {
Write-Error "Failed to export PFX file: $_"
exit 1
}
return
}
if ($Dl) {
Write-Host "Downloading APK from UpToDown.com"
$ApkFile = Download-ReweApk $WorkingDirectory
Write-Host "Downloaded to $ApkFile"
return
}
# Apk files was not provided via cmdline
if (-not $ApkFile) {
Write-Host "No APK file specified. Looking in working directory..."
$ApkFiles = Get-ChildItem -Path $WorkingDirectory -File | Where-Object { $_.Extension -in ".apk",".xapk" }
# No apkfiles in working directory. download it.
if ($ApkFiles.Count -eq 0) {
Write-Host "No APK files found in the directory '$WorkingDirectory'"
Write-Host "Downloading from UpToDown.com"
$ApkFile = Download-ReweApk $WorkingDirectory
} elseif ($ApkFiles.Count -gt 1) {
Write-Host "Multiple APK files found in the directory"
$ApkFile = ($ApkFiles[0]).FullName
} else {
$ApkFile = ($ApkFiles[0]).FullName
}
}
# Check if the file exists
if (-not (Test-Path -Path $ApkFile -PathType Leaf)) {
Write-Error "APK file '$ApkFile' does not exist."
return
} else {
Write-Host "Using APK file: $($ApkFile)"
}
Write-Host "------------------"
$ErrorActionPreference = "Stop"
# Open the APK file as a zip archive
Add-Type -AssemblyName System.IO.Compression.FileSystem
$Zip = [System.IO.Compression.ZipFile]::OpenRead($ApkFile)
try {
# Check for nested APK (apkx packing)
$NestedApk = $Zip.GetEntry("de.rewe.app.mobile.apk")
if ($NestedApk) {
# Read nested APK into memory stream
$NestedStream = New-Object System.IO.MemoryStream
$NestedApk.Open().CopyTo($NestedStream)
$Zip.Dispose()
# Reset stream position and create new zip archive
$NestedStream.Position = 0
$Zip = [System.IO.Compression.ZipArchive]::new($NestedStream)
}
# Find the pfx and copy it out of the zip
$ExpectedCertName = "mtls_prod.pfx"
$Entry = $Zip.GetEntry("res/raw/$ExpectedCertName")
if($Entry) {
$Dest = Join-Path -Path $WorkingDirectory -ChildPath $ExpectedCertName
$EntrStr = $Entry.Open()
$FileStr = [System.IO.File]::Create($Dest)
$EntrStr.CopyTo($FileStr)
$FileStr.Close()
$EntrStr.Close()
Write-Host "Extracted $ExpectedCertName to $Dest"
$Zip.Dispose()
} else {
Write-Error "Certificate $ExpectedCertName not found in the APK."
$Zip.Dispose()
return
}
} finally {
$Zip.Dispose()
}
Write-Host "------------------"
Export-PfxToPemKey -PfxPath $Dest -WorkingDirectory $WorkingDirectory
Write-Host "Done :)"