Compare commits

..

3 Commits

Author SHA1 Message Date
NickVs2015
041cdf39b4 fix: suppress linux firewall errors and add missing 400.allowPIA anchor 2026-07-21 19:06:33 +03:00
NickVs2015
35acbadd43 fix: extend IPC security validation to macOS firewall 2026-07-20 22:34:20 +03:00
NickVs2015
5d774e6c38 fix: resolve critical IPC security vulnerabilities
- Validate IP/CIDR values from IPC before passing to Linux firewall
- Replace shell interpolation with direct execve in firewall update functions
- Block dangerous OpenVPN/WireGuard arguments in sanitizeArguments()
- Add programId bounds check in IpcServerProcess::setProgram()
- Add SO_PEERCRED peer authentication for IPC connections on Linux
2026-07-20 22:34:20 +03:00
65 changed files with 352 additions and 929 deletions

View File

@@ -531,8 +531,6 @@ jobs:
QT_INSTALL_DIR: ${{ runner.temp }}
CODESIGN_SIGNATURE: ${{ secrets.MAC_SIGNER_ID }}
CODESIGN_INSTALLER_SIGNATURE: ${{ secrets.MAC_INSTALLER_SIGNER_ID }}
CODESIGN_KEYCHAIN: ${{ steps.setup-keychain.outputs.keychain-path }}
CODESIGN_INSTALLER_KEYCHAIN: ${{ steps.setup-keychain.outputs.keychain-path }}
NOTARYTOOL_TEAM_ID: ${{ secrets.MAC_TEAM_ID }}
NOTARYTOOL_EMAIL: ${{ secrets.APPLE_DEV_EMAIL }}
NOTARYTOOL_PASSWORD: ${{ secrets.APPLE_DEV_PASSWORD }}

View File

@@ -4,7 +4,7 @@ set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(PROJECT AmneziaVPN)
set(AMNEZIAVPN_VERSION 5.0.0.2)
set(AMNEZIAVPN_VERSION 4.9.0.4)
set(QT_CREATOR_SKIP_PACKAGE_MANAGER_SETUP ON CACHE BOOL "" FORCE)
set(CMAKE_PROJECT_TOP_LEVEL_INCLUDES
@@ -28,7 +28,7 @@ string(TIMESTAMP CURRENT_DATE "%Y-%m-%d")
set(RELEASE_DATE "${CURRENT_DATE}")
set(APP_MAJOR_VERSION ${CMAKE_PROJECT_VERSION_MAJOR}.${CMAKE_PROJECT_VERSION_MINOR}.${CMAKE_PROJECT_VERSION_PATCH})
set(APP_ANDROID_VERSION_CODE 2135)
set(APP_ANDROID_VERSION_CODE 2133)
if(${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
set(MZ_PLATFORM_NAME "linux")

View File

@@ -38,14 +38,14 @@
## Links
- [https://amnezia.org](https://amnezia.org/?utm_source=github&utm_campaign=amnezia_website-read) - Project website | [Alternative link (mirror)](https://storage.googleapis.com/amnezia/amnezia.org?utm_source=github&utm_campaign=amnezia_website-read)
- [https://docs.amnezia.org](https://docs.amnezia.org/?utm_source=github&utm_campaign=amnezia_website-read) - Documentation | [Alternative link (mirror)](https://storage.googleapis.com/amnezia/docs?utm_source=github&utm_campaign=amnezia_website-read)
- [https://amnezia.org](https://amnezia.org) - Project website | [Alternative link (mirror)](https://storage.googleapis.com/kldscp/amnezia.org)
- [https://docs.amnezia.org](https://docs.amnezia.org) - Documentation
- [https://www.reddit.com/r/AmneziaVPN](https://www.reddit.com/r/AmneziaVPN) - Reddit
- [https://telegram.me/amnezia_vpn_en](https://telegram.me/amnezia_vpn_en) - Telegram support channel (English)
- [https://telegram.me/amnezia_vpn_ir](https://telegram.me/amnezia_vpn_ir) - Telegram support channel (Farsi)
- [https://telegram.me/amnezia_vpn_mm](https://telegram.me/amnezia_vpn_mm) - Telegram support channel (Myanmar)
- [https://telegram.me/amnezia_vpn](https://telegram.me/amnezia_vpn) - Telegram support channel (Russian)
- [Get Premium for 6 or 12 months](https://storage.googleapis.com/amnezia/pay?utm_source=github&utm_campaign=ampay-read)
- [https://t.me/amnezia_vpn_en](https://t.me/amnezia_vpn_en) - Telegram support channel (English)
- [https://t.me/amnezia_vpn_ir](https://t.me/amnezia_vpn_ir) - Telegram support channel (Farsi)
- [https://t.me/amnezia_vpn_mm](https://t.me/amnezia_vpn_mm) - Telegram support channel (Myanmar)
- [https://t.me/amnezia_vpn](https://t.me/amnezia_vpn) - Telegram support channel (Russian)
- [https://vpnpay.io/en/amnezia-premium/](https://vpnpay.io/en/amnezia-premium/) - Amnezia Premium
## Tech

View File

@@ -35,14 +35,14 @@
## Ссылки
- [https://amnezia.org](https://amnezia.org/?utm_source=github&utm_campaign=amnezia_website-read) - Веб-сайт проекта | [Альтернативная ссылка (зеркало)](https://storage.googleapis.com/amnezia/amnezia.org?utm_source=github&utm_campaign=amnezia_website-read)
- [https://docs.amnezia.org](https://docs.amnezia.org/?utm_source=github&utm_campaign=amnezia_website-read) - Документация | [Альтернативная ссылка (зеркало)](https://storage.googleapis.com/amnezia/docs?utm_source=github&utm_campaign=amnezia_website-read)
- [https://amnezia.org](https://amnezia.org) - Веб-сайт проекта | [Альтернативная ссылка (зеркало)](https://storage.googleapis.com/kldscp/amnezia.org)
- [https://docs.amnezia.org](https://docs.amnezia.org) - Документация
- [https://www.reddit.com/r/AmneziaVPN](https://www.reddit.com/r/AmneziaVPN) - Reddit
- [https://telegram.me/amnezia_vpn_en](https://telegram.me/amnezia_vpn_en) - Канал поддержки в Telegram (Английский)
- [https://telegram.me/amnezia_vpn_ir](https://telegram.me/amnezia_vpn_ir) - Канал поддержки в Telegram (Фарси)
- [https://telegram.me/amnezia_vpn_mm](https://telegram.me/amnezia_vpn_mm) - Канал поддержки в Telegram (Мьянма)
- [https://telegram.me/amnezia_vpn](https://telegram.me/amnezia_vpn) - Канал поддержки в Telegram (Русский)
- [Оформите Premium на 6 или 12 месяцев](https://storage.googleapis.com/amnezia/pay?utm_source=github&utm_campaign=ampay-read)
- [https://t.me/amnezia_vpn_en](https://t.me/amnezia_vpn_en) - Канал поддержки в Telegram (Английский)
- [https://t.me/amnezia_vpn_ir](https://t.me/amnezia_vpn_ir) - Канал поддержки в Telegram (Фарси)
- [https://t.me/amnezia_vpn_mm](https://t.me/amnezia_vpn_mm) - Канал поддержки в Telegram (Мьянма)
- [https://t.me/amnezia_vpn](https://t.me/amnezia_vpn) - Канал поддержки в Telegram (Русский)
- [https://vpnpay.io/en/amnezia-premium/](https://vpnpay.io/en/amnezia-premium/) - Amnezia Premium | [Зеркало](https://storage.googleapis.com/kldscp/vpnpay.io/ru/amnezia-premium\)
## Технологии

View File

@@ -145,9 +145,6 @@ void AmneziaApplication::init()
m_coreController.reset(new CoreController(m_vpnConnection, m_settings, m_engine));
m_marketplaceUpdateController.reset(new MarketplaceUpdateController());
m_marketplaceUpdateController->start();
m_engine->addImportPath("qrc:/ui/qml/Modules/");
if (m_parser.isSet(m_optImport)) {

View File

@@ -15,7 +15,6 @@
#include "core/controllers/coreController.h"
#include "secureQSettings.h"
#include "ui/controllers/marketplaceUpdateController.h"
#include "vpnConnection.h"
#include "ui/models/containerProps.h"
#include "ui/models/protocolProps.h"
@@ -57,7 +56,6 @@ private:
SecureQSettings* m_settings;
QScopedPointer<CoreController> m_coreController;
QScopedPointer<MarketplaceUpdateController> m_marketplaceUpdateController;
QSharedPointer<ContainerProps> m_containerProps;
QSharedPointer<ProtocolProps> m_protocolProps;

View File

@@ -84,5 +84,4 @@ dependencies {
implementation(libs.google.mlkit)
implementation(libs.androidx.datastore)
implementation(libs.androidx.biometric)
implementation(libs.google.play.app.update)
}

View File

@@ -12,7 +12,6 @@ androidx-datastore = "1.1.1"
kotlinx-coroutines = "1.8.1"
kotlinx-serialization = "1.6.3"
google-mlkit = "17.3.0"
google-play-app-update = "2.1.0"
[libraries]
androidx-core = { module = "androidx.core:core-ktx", version.ref = "androidx-core" }
@@ -29,7 +28,6 @@ androidx-datastore = { module = "androidx.datastore:datastore-preferences", vers
kotlinx-coroutines = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kotlinx-coroutines" }
kotlinx-serialization-protobuf = { module = "org.jetbrains.kotlinx:kotlinx-serialization-protobuf", version.ref = "kotlinx-serialization" }
google-mlkit = { module = "com.google.mlkit:barcode-scanning", version.ref = "google-mlkit" }
google-play-app-update = { module = "com.google.android.play:app-update-ktx", version.ref = "google-play-app-update" }
[bundles]
androidx-camera = [

View File

@@ -48,15 +48,6 @@ import kotlin.LazyThreadSafetyMode.NONE
import kotlin.coroutines.CoroutineContext
import kotlin.text.RegexOption.IGNORE_CASE
import AppListProvider
import com.google.android.play.core.appupdate.AppUpdateInfo
import com.google.android.play.core.appupdate.AppUpdateManager
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import com.google.android.play.core.appupdate.AppUpdateOptions
import com.google.android.play.core.install.InstallState
import com.google.android.play.core.install.InstallStateUpdatedListener
import com.google.android.play.core.install.model.AppUpdateType
import com.google.android.play.core.install.model.InstallStatus
import com.google.android.play.core.install.model.UpdateAvailability
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -83,9 +74,6 @@ private const val CHECK_VPN_PERMISSION_ACTION_CODE = 1
private const val CREATE_FILE_ACTION_CODE = 2
private const val OPEN_FILE_ACTION_CODE = 3
private const val CHECK_NOTIFICATION_PERMISSION_ACTION_CODE = 4
private const val UPDATE_APP_ACTION_CODE = 5
private const val PLAY_UPDATE_UNAVAILABLE = 1
private const val PREFS_NOTIFICATION_PERMISSION_ASKED = "NOTIFICATION_PERMISSION_ASKED"
private const val OPEN_FILE_AFTER_RESUME_DELAY_MS = 400L
@@ -112,24 +100,6 @@ class AmneziaActivity : QtActivity() {
private var pendingOpenFileUri: String? = null
private var openFileDeliveryScheduled = false
private var appUpdateManager: AppUpdateManager? = null
private var restartTitle = ""
private var restartMessage = ""
private var restartAction = ""
private var restartLater = ""
private var restartPromptShown = false
private val installStateListener = InstallStateUpdatedListener(::onInstallStateUpdated)
private fun onInstallStateUpdated(state: InstallState) {
when (state.installStatus()) {
InstallStatus.DOWNLOADED -> promptCompleteUpdate()
InstallStatus.INSTALLED, InstallStatus.FAILED, InstallStatus.CANCELED ->
appUpdateManager?.unregisterListener(installStateListener)
else -> {}
}
}
private val vpnServiceEventHandler: Handler by lazy(NONE) {
object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
@@ -404,12 +374,6 @@ class AmneziaActivity : QtActivity() {
QtAndroidController.onActivityResumed()
}
appUpdateManager?.appUpdateInfo?.addOnSuccessListener { info ->
if (info.installStatus() == InstallStatus.DOWNLOADED) {
promptCompleteUpdate()
}
}
if (pendingOpenFileUri != null && !openFileDeliveryScheduled) {
val uri = pendingOpenFileUri!!
openFileDeliveryScheduled = true
@@ -523,92 +487,9 @@ class AmneziaActivity : QtActivity() {
super.onDestroy()
}
fun checkPlayUpdate(restartTitle: String, restartMessage: String, restartAction: String, restartLater: String) {
this.restartTitle = restartTitle
this.restartMessage = restartMessage
this.restartAction = restartAction
this.restartLater = restartLater
runOnUiThread {
val manager = appUpdateManager
?: AppUpdateManagerFactory.create(applicationContext).also { appUpdateManager = it }
manager.appUpdateInfo
.addOnSuccessListener { info ->
val available = info.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE &&
info.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)
if (available) {
startPlayFlexibleFlow(info)
} else {
Log.d(TAG, "Play update not available, using fallback")
QtAndroidController.onPlayUpdateResult(PLAY_UPDATE_UNAVAILABLE)
}
}
.addOnFailureListener { e ->
Log.w(TAG, "checkPlayUpdate failed: ${e.message}")
QtAndroidController.onPlayUpdateResult(PLAY_UPDATE_UNAVAILABLE)
}
}
}
private fun startPlayFlexibleFlow(info: AppUpdateInfo) {
val manager = appUpdateManager ?: run {
QtAndroidController.onPlayUpdateResult(PLAY_UPDATE_UNAVAILABLE)
return
}
try {
manager.registerListener(installStateListener)
manager.startUpdateFlowForResult(
info, this, AppUpdateOptions.newBuilder(AppUpdateType.FLEXIBLE).build(), UPDATE_APP_ACTION_CODE
)
} catch (e: Exception) {
Log.w(TAG, "startPlayUpdateFlow failed: ${e.message}")
manager.unregisterListener(installStateListener)
QtAndroidController.onPlayUpdateResult(PLAY_UPDATE_UNAVAILABLE)
}
}
private fun promptCompleteUpdate() {
if (isFinishing || isDestroyed || restartPromptShown) return
restartPromptShown = true
AlertDialog.Builder(this)
.setTitle(restartTitle)
.setMessage(restartMessage)
.setCancelable(false)
.setPositiveButton(restartAction) { _, _ -> appUpdateManager?.completeUpdate() }
.setNegativeButton(restartLater) { d, _ ->
restartPromptShown = false
d.dismiss()
}
.show()
}
fun showUpdatePrompt(title: String, message: String, updateTitle: String, skipTitle: String, storeUrl: String) {
runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread
AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setCancelable(true)
.setPositiveButton(updateTitle) { _, _ ->
try {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(storeUrl)))
} catch (e: ActivityNotFoundException) {
Log.w(TAG, "open store failed: ${e.message}")
}
}
.setNegativeButton(skipTitle) { d, _ -> d.dismiss() }
.show()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
Log.d(TAG, "Process activity result, code: ${actionCodeToString(requestCode)}, " +
"resultCode: $resultCode, data: $data")
if (requestCode == UPDATE_APP_ACTION_CODE) {
if (resultCode != RESULT_OK) {
appUpdateManager?.unregisterListener(installStateListener)
}
return
}
actionResultHandlers[requestCode]?.let { handler ->
when (resultCode) {
RESULT_OK -> handler.onSuccess(data)
@@ -1312,7 +1193,6 @@ class AmneziaActivity : QtActivity() {
CREATE_FILE_ACTION_CODE -> "CREATE_FILE"
OPEN_FILE_ACTION_CODE -> "OPEN_FILE"
CHECK_NOTIFICATION_PERMISSION_ACTION_CODE -> "CHECK_NOTIFICATION_PERMISSION"
UPDATE_APP_ACTION_CODE -> "UPDATE_APP"
else -> actionCode.toString()
}
}

View File

@@ -34,6 +34,4 @@ object QtAndroidController {
external fun onActivityPaused()
external fun onActivityResumed()
external fun onPlayUpdateResult(status: Int)
}

View File

@@ -111,7 +111,7 @@ open class Wireguard : Protocol() {
configExtensionParameters(configData)
}
configData.optStringOrNull("persistent_keep_alive")?.let { setPersistentKeepalive(it) }
configData.optStringOrNull("persistent_keep_alive")?.let { setPersistentKeepalive(it.toInt()) }
configData.getString("client_priv_key").let { setPrivateKeyHex(it.base64ToHex()) }
configData.getString("server_pub_key").let { setPublicKeyHex(it.base64ToHex()) }
configData.optStringOrNull("psk_key")?.let { setPreSharedKeyHex(it.base64ToHex()) }
@@ -134,20 +134,6 @@ open class Wireguard : Protocol() {
configData.optStringOrNull("I3")?.let { setI3(it) }
configData.optStringOrNull("I4")?.let { setI4(it) }
configData.optStringOrNull("I5")?.let { setI5(it) }
configData.optStringOrNull("HeaderProtectionKey")?.trim()?.takeIf { it.isNotEmpty() }
?.let { setHeaderProtectionKey(it.base64ToHex()) }
configData.optStringOrNull("ContentPaddingAddition")?.trim()?.takeIf { it.isNotEmpty() }
?.let { setContentPaddingAddition(it) }
configData.optStringOrNull("RekeyAfterTime")?.trim()?.takeIf { it.isNotEmpty() }
?.let { setRekeyAfterTime(it) }
configData.optStringOrNull("RekeyTimeout")?.trim()?.takeIf { it.isNotEmpty() }
?.let { setRekeyTimeout(it) }
configData.optStringOrNull("RejectAfterTime")?.trim()?.takeIf { it.isNotEmpty() }
?.let { setRejectAfterTime(it) }
configData.optStringOrNull("KeepaliveTimeout")?.trim()?.takeIf { it.isNotEmpty() }
?.let { setKeepaliveTimeout(it) }
configData.optStringOrNull("MaxHandshakeAttempts")?.trim()?.takeIf { it.isNotEmpty() }
?.let { setMaxHandshakeAttempts(it) }
}
private fun start(

View File

@@ -10,7 +10,7 @@ private const val WIREGUARD_DEFAULT_MTU = 1280
open class WireguardConfig protected constructor(
protocolConfigBuilder: ProtocolConfig.Builder,
val endpoint: InetEndpoint,
val persistentKeepalive: String?,
val persistentKeepalive: Int,
val publicKeyHex: String,
val preSharedKeyHex: String?,
val privateKeyHex: String,
@@ -31,13 +31,6 @@ open class WireguardConfig protected constructor(
var i3: String?,
var i4: String?,
var i5: String?,
val headerProtectionKeyHex: String?,
val contentPaddingAddition: String?,
val rekeyAfterTime: String?,
val rekeyTimeout: String?,
val rejectAfterTime: String?,
val keepaliveTimeout: String?,
val maxHandshakeAttempts: String?,
) : ProtocolConfig(protocolConfigBuilder) {
protected constructor(builder: Builder) : this(
@@ -64,13 +57,6 @@ open class WireguardConfig protected constructor(
builder.i3,
builder.i4,
builder.i5,
builder.headerProtectionKeyHex,
builder.contentPaddingAddition,
builder.rekeyAfterTime,
builder.rekeyTimeout,
builder.rejectAfterTime,
builder.keepaliveTimeout,
builder.maxHandshakeAttempts,
)
fun toWgUserspaceString(): String = with(StringBuilder()) {
@@ -101,13 +87,6 @@ open class WireguardConfig protected constructor(
i4?.let { appendLine("i4=$it") }
i5?.let { appendLine("i5=$it") }
}
headerProtectionKeyHex?.takeIf { it.isNotEmpty() }?.let { appendLine("header_protection_key=$it") }
contentPaddingAddition?.takeIf { it.isNotEmpty() }?.let { appendLine("content_padding_addition=$it") }
rekeyAfterTime?.takeIf { it.isNotEmpty() }?.let { appendLine("rekey_after_time=$it") }
rekeyTimeout?.takeIf { it.isNotEmpty() }?.let { appendLine("rekey_timeout=$it") }
rejectAfterTime?.takeIf { it.isNotEmpty() }?.let { appendLine("reject_after_time=$it") }
keepaliveTimeout?.takeIf { it.isNotEmpty() }?.let { appendLine("keepalive_timeout=$it") }
maxHandshakeAttempts?.takeIf { it.isNotEmpty() }?.let { appendLine("max_handshake_attempts=$it") }
}
private fun validateProtocolExtensionParameters() {
@@ -128,7 +107,7 @@ open class WireguardConfig protected constructor(
appendLine("allowed_ip=${route.inetNetwork}")
}
appendLine("endpoint=$endpoint")
if (!persistentKeepalive.isNullOrEmpty() && persistentKeepalive != "0")
if (persistentKeepalive != 0)
appendLine("persistent_keepalive_interval=$persistentKeepalive")
if (preSharedKeyHex != null)
appendLine("preshared_key=$preSharedKeyHex")
@@ -138,7 +117,7 @@ open class WireguardConfig protected constructor(
internal lateinit var endpoint: InetEndpoint
private set
internal var persistentKeepalive: String? = null
internal var persistentKeepalive: Int = 0
private set
internal lateinit var publicKeyHex: String
@@ -170,17 +149,10 @@ open class WireguardConfig protected constructor(
internal var i3: String? = null
internal var i4: String? = null
internal var i5: String? = null
internal var headerProtectionKeyHex: String? = null
internal var contentPaddingAddition: String? = null
internal var rekeyAfterTime: String? = null
internal var rekeyTimeout: String? = null
internal var rejectAfterTime: String? = null
internal var keepaliveTimeout: String? = null
internal var maxHandshakeAttempts: String? = null
fun setEndpoint(endpoint: InetEndpoint) = apply { this.endpoint = endpoint }
fun setPersistentKeepalive(persistentKeepalive: String) = apply { this.persistentKeepalive = persistentKeepalive }
fun setPersistentKeepalive(persistentKeepalive: Int) = apply { this.persistentKeepalive = persistentKeepalive }
fun setPublicKeyHex(publicKeyHex: String) = apply { this.publicKeyHex = publicKeyHex }
@@ -206,13 +178,6 @@ open class WireguardConfig protected constructor(
fun setI3(i3: String) = apply { this.i3 = i3 }
fun setI4(i4: String) = apply { this.i4 = i4 }
fun setI5(i5: String) = apply { this.i5 = i5 }
fun setHeaderProtectionKey(headerProtectionKeyHex: String) = apply { this.headerProtectionKeyHex = headerProtectionKeyHex }
fun setContentPaddingAddition(contentPaddingAddition: String) = apply { this.contentPaddingAddition = contentPaddingAddition }
fun setRekeyAfterTime(rekeyAfterTime: String) = apply { this.rekeyAfterTime = rekeyAfterTime }
fun setRekeyTimeout(rekeyTimeout: String) = apply { this.rekeyTimeout = rekeyTimeout }
fun setRejectAfterTime(rejectAfterTime: String) = apply { this.rejectAfterTime = rejectAfterTime }
fun setKeepaliveTimeout(keepaliveTimeout: String) = apply { this.keepaliveTimeout = keepaliveTimeout }
fun setMaxHandshakeAttempts(maxHandshakeAttempts: String) = apply { this.maxHandshakeAttempts = maxHandshakeAttempts }
override fun build(): WireguardConfig = configBuild().run { WireguardConfig(this@Builder) }
}

View File

@@ -133,11 +133,6 @@ target_sources(${PROJECT} PRIVATE
${CLIENT_ROOT_DIR}/platforms/ios/StoreKit2Helper.swift
)
set_source_files_properties(
${CMAKE_CURRENT_SOURCE_DIR}/macos/app/Images.xcassets
PROPERTIES MACOSX_PACKAGE_LOCATION Resources
)
target_sources(${PROJECT} PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/macos/app/Images.xcassets
${CMAKE_CURRENT_SOURCE_DIR}/ios/app/PrivacyInfo.xcprivacy

View File

@@ -266,7 +266,7 @@ ProtocolConfig WireguardConfigurator::createConfig(const ServerCredentials &cred
clientConfig.presharedKey = connData.pskKey;
clientConfig.clientId = connData.clientPubKey;
clientConfig.allowedIps = QStringList { "0.0.0.0/0", "::/0" };
clientConfig.persistentKeepAlive = protocols::wireguard::defaultPersistentKeepAlive;
clientConfig.persistentKeepAlive = "25";
clientConfig.mtu = mtu;
clientConfig.isObfuscationEnabled = false;

View File

@@ -205,7 +205,6 @@ ErrorCode SubscriptionController::extractServerConfigJsonFromResponse(const QByt
serverProtocolConfig[configKey::specialJunk3] = clientProtocolConfig.value(configKey::specialJunk3);
serverProtocolConfig[configKey::specialJunk4] = clientProtocolConfig.value(configKey::specialJunk4);
serverProtocolConfig[configKey::specialJunk5] = clientProtocolConfig.value(configKey::specialJunk5);
serverProtocolConfig[configKey::headerProtectionKey] = clientProtocolConfig.value(configKey::headerProtectionKey);
//

View File

@@ -31,6 +31,7 @@ ConnectionController::ConnectionController(SecureServersRepository* serversRepos
connect(m_vpnConnection, &VpnConnection::connectionStateChanged, this, &ConnectionController::connectionStateChanged);
connect(this, &ConnectionController::openConnectionRequested, m_vpnConnection, &VpnConnection::connectToVpn, Qt::QueuedConnection);
connect(this, &ConnectionController::closeConnectionRequested, m_vpnConnection, &VpnConnection::disconnectFromVpn, Qt::QueuedConnection);
connect(this, &ConnectionController::setConnectionStateRequested, m_vpnConnection, &VpnConnection::setConnectionState, Qt::QueuedConnection);
connect(this, &ConnectionController::killSwitchModeChangedRequested, m_vpnConnection, &VpnConnection::onKillSwitchModeChanged, Qt::QueuedConnection);
#ifdef Q_OS_ANDROID
connect(this, &ConnectionController::restoreConnectionRequested, m_vpnConnection, &VpnConnection::restoreConnection, Qt::QueuedConnection);
@@ -44,7 +45,9 @@ bool ConnectionController::isConnected() const
void ConnectionController::setConnectionState(Vpn::ConnectionState state)
{
emit connectionStateChanged(state);
if (m_vpnConnection) {
emit setConnectionStateRequested(state);
}
}
ErrorCode ConnectionController::defaultContainerForServer(const QString &serverId, DockerContainer &container) const

View File

@@ -67,6 +67,7 @@ signals:
void connectionStateChanged(Vpn::ConnectionState state);
void openConnectionRequested(const QString &serverId, DockerContainer container, const QJsonObject &vpnConfiguration);
void closeConnectionRequested();
void setConnectionStateRequested(Vpn::ConnectionState state);
void killSwitchModeChangedRequested(bool enabled);
#ifdef Q_OS_ANDROID

View File

@@ -285,10 +285,6 @@ void CoreController::initSignalHandlers()
if (m_serversUiController->hasServersFromGatewayApi()) {
m_apiNewsUiController->fetchNews(false);
}
#if !defined(Q_OS_ANDROID) && !defined(Q_OS_IOS)
m_updateController->checkForUpdates();
#endif
}
void CoreController::updateTranslator(const QLocale &locale)

View File

@@ -440,6 +440,9 @@ void CoreSignalHandlers::initNotificationHandler()
void CoreSignalHandlers::initUpdateFoundHandler()
{
#if !defined(Q_OS_ANDROID) && !defined(Q_OS_IOS)
connect(m_coreController->m_apiNewsUiController, &ApiNewsUiController::fetchNewsFinished, m_coreController->m_updateUiController,
&UpdateUiController::checkForUpdates);
connect(m_coreController->m_updateUiController, &UpdateUiController::updateFound, this, [this]() {
const QString version = m_coreController->m_updateUiController->getVersion();
const QString updateId = version.isEmpty() ? QStringLiteral("update") : QStringLiteral("update-%1").arg(version);

View File

@@ -74,28 +74,6 @@ QJsonObject AwgServerConfig::toJson() const
obj[configKey::specialJunk4] = specialJunk4;
obj[configKey::specialJunk5] = specialJunk5;
if (!headerProtectionKey.isEmpty()) {
obj[configKey::headerProtectionKey] = headerProtectionKey;
}
if (!contentPaddingAddition.isEmpty()) {
obj[configKey::contentPaddingAddition] = contentPaddingAddition;
}
if (!rekeyAfterTime.isEmpty()) {
obj[configKey::rekeyAfterTime] = rekeyAfterTime;
}
if (!rekeyTimeout.isEmpty()) {
obj[configKey::rekeyTimeout] = rekeyTimeout;
}
if (!rejectAfterTime.isEmpty()) {
obj[configKey::rejectAfterTime] = rejectAfterTime;
}
if (!keepaliveTimeout.isEmpty()) {
obj[configKey::keepaliveTimeout] = keepaliveTimeout;
}
if (!maxHandshakeAttempts.isEmpty()) {
obj[configKey::maxHandshakeAttempts] = maxHandshakeAttempts;
}
if (isThirdPartyConfig) {
obj[configKey::isThirdPartyConfig] = isThirdPartyConfig;
}
@@ -131,14 +109,6 @@ AwgServerConfig AwgServerConfig::fromJson(const QJsonObject& json)
config.specialJunk3 = json.value(configKey::specialJunk3).toString();
config.specialJunk4 = json.value(configKey::specialJunk4).toString();
config.specialJunk5 = json.value(configKey::specialJunk5).toString();
config.headerProtectionKey = json.value(configKey::headerProtectionKey).toString();
config.contentPaddingAddition = json.value(configKey::contentPaddingAddition).toString();
config.rekeyAfterTime = json.value(configKey::rekeyAfterTime).toString();
config.rekeyTimeout = json.value(configKey::rekeyTimeout).toString();
config.rejectAfterTime = json.value(configKey::rejectAfterTime).toString();
config.keepaliveTimeout = json.value(configKey::keepaliveTimeout).toString();
config.maxHandshakeAttempts = json.value(configKey::maxHandshakeAttempts).toString();
config.isThirdPartyConfig = json.value(configKey::isThirdPartyConfig).toBool(false);
@@ -241,28 +211,6 @@ QJsonObject AwgClientConfig::toJson() const
if (!specialJunk5.isEmpty()) {
obj[configKey::specialJunk5] = specialJunk5;
}
if (!headerProtectionKey.isEmpty()) {
obj[configKey::headerProtectionKey] = headerProtectionKey;
}
if (!contentPaddingAddition.isEmpty()) {
obj[configKey::contentPaddingAddition] = contentPaddingAddition;
}
if (!rekeyAfterTime.isEmpty()) {
obj[configKey::rekeyAfterTime] = rekeyAfterTime;
}
if (!rekeyTimeout.isEmpty()) {
obj[configKey::rekeyTimeout] = rekeyTimeout;
}
if (!rejectAfterTime.isEmpty()) {
obj[configKey::rejectAfterTime] = rejectAfterTime;
}
if (!keepaliveTimeout.isEmpty()) {
obj[configKey::keepaliveTimeout] = keepaliveTimeout;
}
if (!maxHandshakeAttempts.isEmpty()) {
obj[configKey::maxHandshakeAttempts] = maxHandshakeAttempts;
}
if (isObfuscationEnabled) {
obj[configKey::isObfuscationEnabled] = isObfuscationEnabled;
@@ -310,14 +258,6 @@ AwgClientConfig AwgClientConfig::fromJson(const QJsonObject& json)
config.specialJunk3 = json.value(configKey::specialJunk3).toString();
config.specialJunk4 = json.value(configKey::specialJunk4).toString();
config.specialJunk5 = json.value(configKey::specialJunk5).toString();
config.headerProtectionKey = json.value(configKey::headerProtectionKey).toString();
config.contentPaddingAddition = json.value(configKey::contentPaddingAddition).toString();
config.rekeyAfterTime = json.value(configKey::rekeyAfterTime).toString();
config.rekeyTimeout = json.value(configKey::rekeyTimeout).toString();
config.rejectAfterTime = json.value(configKey::rejectAfterTime).toString();
config.keepaliveTimeout = json.value(configKey::keepaliveTimeout).toString();
config.maxHandshakeAttempts = json.value(configKey::maxHandshakeAttempts).toString();
config.isObfuscationEnabled = json.value(configKey::isObfuscationEnabled).toBool(false);
@@ -380,8 +320,7 @@ bool AwgServerConfig::hasEqualServerSettings(const AwgServerConfig& other) const
transportPacketMagicHeader != other.transportPacketMagicHeader ||
specialJunk1 != other.specialJunk1 || specialJunk2 != other.specialJunk2 ||
specialJunk3 != other.specialJunk3 || specialJunk4 != other.specialJunk4 ||
specialJunk5 != other.specialJunk5 ||
headerProtectionKey != other.headerProtectionKey) {
specialJunk5 != other.specialJunk5) {
return false;
}

View File

@@ -39,13 +39,6 @@ struct AwgServerConfig {
QString specialJunk3;
QString specialJunk4;
QString specialJunk5;
QString headerProtectionKey;
QString contentPaddingAddition;
QString rekeyAfterTime;
QString rekeyTimeout;
QString rejectAfterTime;
QString keepaliveTimeout;
QString maxHandshakeAttempts;
bool isThirdPartyConfig = false;
QJsonObject toJson() const;
@@ -83,13 +76,6 @@ struct AwgClientConfig {
QString specialJunk3;
QString specialJunk4;
QString specialJunk5;
QString headerProtectionKey;
QString contentPaddingAddition;
QString rekeyAfterTime;
QString rekeyTimeout;
QString rejectAfterTime;
QString keepaliveTimeout;
QString maxHandshakeAttempts;
bool isObfuscationEnabled = false;
QJsonObject toJson() const;

View File

@@ -90,14 +90,6 @@ namespace amnezia
constexpr QLatin1String specialJunk4("I4");
constexpr QLatin1String specialJunk5("I5");
constexpr QLatin1String headerProtectionKey("HeaderProtectionKey");
constexpr QLatin1String contentPaddingAddition("ContentPaddingAddition");
constexpr QLatin1String rekeyAfterTime("RekeyAfterTime");
constexpr QLatin1String rekeyTimeout("RekeyTimeout");
constexpr QLatin1String rejectAfterTime("RejectAfterTime");
constexpr QLatin1String keepaliveTimeout("KeepaliveTimeout");
constexpr QLatin1String maxHandshakeAttempts("MaxHandshakeAttempts");
constexpr QLatin1String protocolVersion("protocol_version");
constexpr QLatin1String openvpn("openvpn");

View File

@@ -64,7 +64,7 @@ namespace amnezia
constexpr char defaultFlow[] = "xtls-rprx-vision";
constexpr char defaultTransport[] = "raw";
constexpr char defaultFingerprint[] = "chrome";
constexpr char defaultSni[] = "www.googletagmanager.com";
constexpr char defaultSni[] = "cdn.example.com";
constexpr char defaultAlpn[] = "HTTP/2";
constexpr char defaultXhttpMode[] = "Auto";
@@ -147,7 +147,6 @@ namespace amnezia
constexpr char defaultSubnetCidr[] = "24";
constexpr char defaultPort[] = "51820";
constexpr char defaultPersistentKeepAlive[] = "25";
#if defined(Q_OS_ANDROID) || defined(Q_OS_IOS) || defined(MACOS_NE)
constexpr char defaultMtu[] = "1280";

View File

@@ -286,7 +286,7 @@ QPair<QString, QNetworkInterface> NetworkUtilities::getGatewayAndIface()
return { resGateway, QNetworkInterface::interfaceFromIndex(resIndex) };
#endif
#ifdef Q_OS_LINUX
constexpr int BUFFER_SIZE = 8192;
constexpr int BUFFER_SIZE = 100;
int received_bytes = 0, msg_len = 0, route_attribute_len = 0;
int sock = -1, msgseq = 0;
struct nlmsghdr *nlh, *nlmsg;
@@ -294,7 +294,7 @@ QPair<QString, QNetworkInterface> NetworkUtilities::getGatewayAndIface()
// This struct contain route attributes (route type)
struct rtattr *route_attribute;
char gateway_address[INET_ADDRSTRLEN], interface[IF_NAMESIZE];
char msgbuf[100], buffer[BUFFER_SIZE];
char msgbuf[BUFFER_SIZE], buffer[BUFFER_SIZE];
char *ptr = buffer;
struct timeval tv;
@@ -339,8 +339,8 @@ QPair<QString, QNetworkInterface> NetworkUtilities::getGatewayAndIface()
nlh = (struct nlmsghdr *) ptr;
/* Check if the header is valid */
if((NLMSG_OK(nlh, received_bytes) == 0) ||
(nlh->nlmsg_type == NLMSG_ERROR))
if((NLMSG_OK(nlmsg, received_bytes) == 0) ||
(nlmsg->nlmsg_type == NLMSG_ERROR))
{
perror("Error in received packet");
return {};
@@ -355,15 +355,13 @@ QPair<QString, QNetworkInterface> NetworkUtilities::getGatewayAndIface()
}
/* Break if its not a multi part message */
if ((nlh->nlmsg_flags & NLM_F_MULTI) == 0)
if ((nlmsg->nlmsg_flags & NLM_F_MULTI) == 0)
break;
}
while ((nlh->nlmsg_seq != msgseq) || (nlh->nlmsg_pid != getpid()));
while ((nlmsg->nlmsg_seq != msgseq) || (nlmsg->nlmsg_pid != getpid()));
/* parse response */
int remaining = msg_len + received_bytes;
nlh = (struct nlmsghdr *) buffer;
for ( ; NLMSG_OK(nlh, remaining); nlh = NLMSG_NEXT(nlh, remaining))
for ( ; NLMSG_OK(nlh, received_bytes); nlh = NLMSG_NEXT(nlh, received_bytes))
{
/* Get the route data */
route_entry = (struct rtmsg *) NLMSG_DATA(nlh);
@@ -372,10 +370,6 @@ QPair<QString, QNetworkInterface> NetworkUtilities::getGatewayAndIface()
if (route_entry->rtm_table != RT_TABLE_MAIN)
continue;
/* Reset per-route to avoid cross-route state pollution */
memset(gateway_address, 0, sizeof(gateway_address));
memset(interface, 0, sizeof(interface));
route_attribute = (struct rtattr *) RTM_RTA(route_entry);
route_attribute_len = RTM_PAYLOAD(nlh);
@@ -401,8 +395,6 @@ QPair<QString, QNetworkInterface> NetworkUtilities::getGatewayAndIface()
break;
}
}
if (!(*gateway_address) || !(*interface))
qDebug() << "getGatewayAndIface: no gateway found";
close(sock);
return { gateway_address, QNetworkInterface::interfaceFromName(interface) };
#endif

View File

@@ -265,8 +265,6 @@ bool Daemon::parseConfig(const QJsonObject& obj, InterfaceConfig& config) {
#endif
}
config.m_persistentKeepalive = obj.value("persistentKeepalive").toString();
config.m_deviceIpv4Address = obj.value("deviceIpv4Address").toString();
config.m_deviceIpv6Address = obj.value("deviceIpv6Address").toString();
if (config.m_deviceIpv4Address.isNull() &&
@@ -443,28 +441,6 @@ bool Daemon::parseConfig(const QJsonObject& obj, InterfaceConfig& config) {
config.m_specialJunk["I5"] = i5.toString();
}
if (const auto headerProtectionKey = obj.value("HeaderProtectionKey"); !headerProtectionKey.isUndefined()) {
config.m_headerProtectionKey = headerProtectionKey.toString();
}
if (const auto contentPaddingAddition = obj.value("ContentPaddingAddition"); !contentPaddingAddition.isUndefined()) {
config.m_contentPaddingAddition = contentPaddingAddition.toString();
}
if (const auto rekeyAfterTime = obj.value("RekeyAfterTime"); !rekeyAfterTime.isUndefined()) {
config.m_rekeyAfterTime = rekeyAfterTime.toString();
}
if (const auto rekeyTimeout = obj.value("RekeyTimeout"); !rekeyTimeout.isUndefined()) {
config.m_rekeyTimeout = rekeyTimeout.toString();
}
if (const auto rejectAfterTime = obj.value("RejectAfterTime"); !rejectAfterTime.isUndefined()) {
config.m_rejectAfterTime = rejectAfterTime.toString();
}
if (const auto keepaliveTimeout = obj.value("KeepaliveTimeout"); !keepaliveTimeout.isUndefined()) {
config.m_keepaliveTimeout = keepaliveTimeout.toString();
}
if (const auto maxHandshakeAttempts = obj.value("MaxHandshakeAttempts"); !maxHandshakeAttempts.isUndefined()) {
config.m_maxHandshakeAttempts = maxHandshakeAttempts.toString();
}
return true;
}

View File

@@ -24,9 +24,6 @@ QJsonObject InterfaceConfig::toJson() const {
json.insert("serverIpv6AddrIn", QJsonValue(m_serverIpv6AddrIn));
json.insert("serverPort", QJsonValue((double)m_serverPort));
json.insert("deviceMTU", QJsonValue(m_deviceMTU));
if (!m_persistentKeepalive.isEmpty()) {
json.insert("persistentKeepalive", QJsonValue(m_persistentKeepalive));
}
if ((m_hopType == InterfaceConfig::MultiHopExit) ||
(m_hopType == InterfaceConfig::SingleHop)) {
json.insert("serverIpv4Gateway", QJsonValue(m_serverIpv4Gateway));
@@ -156,28 +153,6 @@ QString InterfaceConfig::toWgConf(const QMap<QString, QString>& extra) const {
out << key << " = " << m_specialJunk[key] << "\n";
}
if (!m_headerProtectionKey.isEmpty()) {
out << "HeaderProtectionKey = " << m_headerProtectionKey << "\n";
}
if (!m_contentPaddingAddition.isEmpty()) {
out << "ContentPaddingAddition = " << m_contentPaddingAddition << "\n";
}
if (!m_rekeyAfterTime.isEmpty()) {
out << "RekeyAfterTime = " << m_rekeyAfterTime << "\n";
}
if (!m_rekeyTimeout.isEmpty()) {
out << "RekeyTimeout = " << m_rekeyTimeout << "\n";
}
if (!m_rejectAfterTime.isEmpty()) {
out << "RejectAfterTime = " << m_rejectAfterTime << "\n";
}
if (!m_keepaliveTimeout.isEmpty()) {
out << "KeepaliveTimeout = " << m_keepaliveTimeout << "\n";
}
if (!m_maxHandshakeAttempts.isEmpty()) {
out << "MaxHandshakeAttempts = " << m_maxHandshakeAttempts << "\n";
}
// If any extra config was provided, append it now.
for (const QString& key : extra.keys()) {
out << key << " = " << extra[key] << "\n";
@@ -198,9 +173,6 @@ QString InterfaceConfig::toWgConf(const QMap<QString, QString>& extra) const {
ranges.append(ip.toString());
}
out << "AllowedIPs = " << ranges.join(", ") << "\n";
if (!m_persistentKeepalive.isEmpty()) {
out << "PersistentKeepalive = " << m_persistentKeepalive << "\n";
}
return content;
}

View File

@@ -36,7 +36,6 @@ class InterfaceConfig {
QString m_secondaryDnsServer;
int m_serverPort = 0;
int m_deviceMTU = 1420;
QString m_persistentKeepalive;
QList<IPAddress> m_allowedIPAddressRanges;
QStringList m_excludedAddresses;
QStringList m_vpnDisabledApps;
@@ -59,14 +58,6 @@ class InterfaceConfig {
QString m_transportPacketMagicHeader;
QMap<QString, QString> m_specialJunk;
QString m_headerProtectionKey;
QString m_contentPaddingAddition;
QString m_rekeyAfterTime;
QString m_rekeyTimeout;
QString m_rejectAfterTime;
QString m_keepaliveTimeout;
QString m_maxHandshakeAttempts;
QJsonObject toJson() const;
QString toWgConf(
const QMap<QString, QString>& extra = QMap<QString, QString>()) const;

View File

@@ -16,6 +16,8 @@
constexpr const char* WG_INTERFACE = "amn0";
constexpr uint16_t WG_KEEPALIVE_PERIOD = 60;
class WireguardUtils : public QObject {
Q_OBJECT

View File

@@ -44,20 +44,8 @@
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
<key>CFBundleIconName</key>
<string>AppIcon</string>
<key>CFBundleIcons</key>
<dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon</string>
</array>
<key>CFBundleIconName</key>
<string>AppIcon</string>
</dict>
</dict>
<dict/>
<key>UTImportedTypeDeclarations</key>
<array>
<dict>

View File

@@ -159,11 +159,6 @@ void LocalSocketController::activate(const QJsonObject &rawConfig) {
json.insert("serverIpv4Gateway", wgConfig.value(amnezia::configKey::hostName));
// json.insert("serverIpv6Gateway", QJsonValue(hop.m_server.ipv6Gateway()));
if (wgConfig.contains(amnezia::configKey::persistentKeepAlive)) {
json.insert("persistentKeepalive",
wgConfig.value(amnezia::configKey::persistentKeepAlive).toString());
}
json.insert("primaryDnsServer", rawConfig.value(amnezia::configKey::dns1));
// We don't use secondary DNS if primary DNS is AmneziaDNS
@@ -268,13 +263,6 @@ void LocalSocketController::activate(const QJsonObject &rawConfig) {
json.insert(amnezia::configKey::specialJunk3, wgConfig.value(amnezia::configKey::specialJunk3));
json.insert(amnezia::configKey::specialJunk4, wgConfig.value(amnezia::configKey::specialJunk4));
json.insert(amnezia::configKey::specialJunk5, wgConfig.value(amnezia::configKey::specialJunk5));
json.insert(amnezia::configKey::headerProtectionKey, wgConfig.value(amnezia::configKey::headerProtectionKey));
json.insert(amnezia::configKey::contentPaddingAddition, wgConfig.value(amnezia::configKey::contentPaddingAddition));
json.insert(amnezia::configKey::rekeyAfterTime, wgConfig.value(amnezia::configKey::rekeyAfterTime));
json.insert(amnezia::configKey::rekeyTimeout, wgConfig.value(amnezia::configKey::rekeyTimeout));
json.insert(amnezia::configKey::rejectAfterTime, wgConfig.value(amnezia::configKey::rejectAfterTime));
json.insert(amnezia::configKey::keepaliveTimeout, wgConfig.value(amnezia::configKey::keepaliveTimeout));
json.insert(amnezia::configKey::maxHandshakeAttempts, wgConfig.value(amnezia::configKey::maxHandshakeAttempts));
} else if (!wgConfig.value(amnezia::configKey::junkPacketCount).isUndefined()
&& !wgConfig.value(amnezia::configKey::junkPacketMinSize).isUndefined()
&& !wgConfig.value(amnezia::configKey::junkPacketMaxSize).isUndefined()
@@ -302,13 +290,6 @@ void LocalSocketController::activate(const QJsonObject &rawConfig) {
json.insert(amnezia::configKey::specialJunk3, wgConfig.value(amnezia::configKey::specialJunk3));
json.insert(amnezia::configKey::specialJunk4, wgConfig.value(amnezia::configKey::specialJunk4));
json.insert(amnezia::configKey::specialJunk5, wgConfig.value(amnezia::configKey::specialJunk5));
json.insert(amnezia::configKey::headerProtectionKey, wgConfig.value(amnezia::configKey::headerProtectionKey));
json.insert(amnezia::configKey::contentPaddingAddition, wgConfig.value(amnezia::configKey::contentPaddingAddition));
json.insert(amnezia::configKey::rekeyAfterTime, wgConfig.value(amnezia::configKey::rekeyAfterTime));
json.insert(amnezia::configKey::rekeyTimeout, wgConfig.value(amnezia::configKey::rekeyTimeout));
json.insert(amnezia::configKey::rejectAfterTime, wgConfig.value(amnezia::configKey::rejectAfterTime));
json.insert(amnezia::configKey::keepaliveTimeout, wgConfig.value(amnezia::configKey::keepaliveTimeout));
json.insert(amnezia::configKey::maxHandshakeAttempts, wgConfig.value(amnezia::configKey::maxHandshakeAttempts));
}
write(json);

View File

@@ -103,8 +103,7 @@ bool AndroidController::initialize()
{"onImeInsetsChanged", "(I)V", reinterpret_cast<void *>(onImeInsetsChanged)},
{"onSystemBarsInsetsChanged", "(II)V", reinterpret_cast<void *>(onSystemBarsInsetsChanged)},
{"onActivityPaused", "()V", reinterpret_cast<void *>(onActivityPaused)},
{"onActivityResumed", "()V", reinterpret_cast<void *>(onActivityResumed)},
{"onPlayUpdateResult", "(I)V", reinterpret_cast<void *>(onPlayUpdateResult)}
{"onActivityResumed", "()V", reinterpret_cast<void *>(onActivityResumed)}
};
QJniEnvironment env;
@@ -155,29 +154,6 @@ void AndroidController::resetLastServer(int serverIndex)
callActivityMethod("resetLastServer", "(I)V", serverIndex);
}
void AndroidController::checkPlayUpdate(const QString &restartTitle, const QString &restartMessage,
const QString &restartAction, const QString &restartLater)
{
callActivityMethod("checkPlayUpdate",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
QJniObject::fromString(restartTitle).object<jstring>(),
QJniObject::fromString(restartMessage).object<jstring>(),
QJniObject::fromString(restartAction).object<jstring>(),
QJniObject::fromString(restartLater).object<jstring>());
}
void AndroidController::showUpdatePrompt(const QString &title, const QString &message, const QString &updateTitle,
const QString &skipTitle, const QString &storeUrl)
{
callActivityMethod("showUpdatePrompt",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
QJniObject::fromString(title).object<jstring>(),
QJniObject::fromString(message).object<jstring>(),
QJniObject::fromString(updateTitle).object<jstring>(),
QJniObject::fromString(skipTitle).object<jstring>(),
QJniObject::fromString(storeUrl).object<jstring>());
}
void AndroidController::saveFile(const QString &fileName, const QString &data)
{
callActivityMethod("saveFile", "(Ljava/lang/String;Ljava/lang/String;)V",
@@ -602,13 +578,4 @@ void AndroidController::onActivityResumed(JNIEnv *env, jobject thiz)
emit AndroidController::instance()->activityResumed();
}
// static
void AndroidController::onPlayUpdateResult(JNIEnv *env, jobject thiz, jint status)
{
Q_UNUSED(env);
Q_UNUSED(thiz);
emit AndroidController::instance()->playUpdateResult(static_cast<int>(status));
}

View File

@@ -56,11 +56,6 @@ public:
bool requestAuthentication();
void sendTouch(float x, float y);
void checkPlayUpdate(const QString &restartTitle, const QString &restartMessage, const QString &restartAction,
const QString &restartLater);
void showUpdatePrompt(const QString &title, const QString &message, const QString &updateTitle,
const QString &skipTitle, const QString &storeUrl);
static bool initLogging();
static void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message);
@@ -82,7 +77,6 @@ signals:
void systemBarsInsetsChanged(int navBarHeightDp, int statusBarHeightDp);
void activityPaused();
void activityResumed();
void playUpdateResult(int status);
private:
bool isWaitingStatus = true;
@@ -115,7 +109,6 @@ private:
static void onSystemBarsInsetsChanged(JNIEnv *env, jobject thiz, jint navBarHeightDp, jint statusBarHeightDp);
static void onActivityPaused(JNIEnv *env, jobject thiz);
static void onActivityResumed(JNIEnv *env, jobject thiz);
static void onPlayUpdateResult(JNIEnv *env, jobject thiz, jint status);
template <typename Ret, typename ...Args>
static auto callActivityMethod(const char *methodName, const char *signature, Args &&...args);

View File

@@ -6,8 +6,6 @@ struct WGConfig: Decodable {
let junkPacketCount, junkPacketMinSize, junkPacketMaxSize: String?
let initPacketJunkSize, responsePacketJunkSize, cookieReplyPacketJunkSize, transportPacketJunkSize: String?
let specialJunk1, specialJunk2, specialJunk3, specialJunk4, specialJunk5: String?
let headerProtectionKey: String?
let contentPaddingAddition, rekeyAfterTime, rekeyTimeout, rejectAfterTime, keepaliveTimeout, maxHandshakeAttempts: String?
let dns1: String
let dns2: String
let mtu: String
@@ -18,7 +16,7 @@ struct WGConfig: Decodable {
let serverPublicKey: String
let presharedKey: String?
var allowedIPs: [String]
var persistentKeepAlive: String?
var persistentKeepAlive: String
let splitTunnelType: Int
let splitTunnelSites: [String]
@@ -28,11 +26,6 @@ struct WGConfig: Decodable {
case junkPacketCount = "Jc", junkPacketMinSize = "Jmin", junkPacketMaxSize = "Jmax"
case initPacketJunkSize = "S1", responsePacketJunkSize = "S2", cookieReplyPacketJunkSize = "S3", transportPacketJunkSize = "S4"
case specialJunk1 = "I1", specialJunk2 = "I2", specialJunk3 = "I3", specialJunk4 = "I4", specialJunk5 = "I5"
case headerProtectionKey = "HeaderProtectionKey"
case contentPaddingAddition = "ContentPaddingAddition"
case rekeyAfterTime = "RekeyAfterTime", rekeyTimeout = "RekeyTimeout"
case rejectAfterTime = "RejectAfterTime", keepaliveTimeout = "KeepaliveTimeout"
case maxHandshakeAttempts = "MaxHandshakeAttempts"
case dns1
case dns2
case mtu
@@ -107,28 +100,6 @@ struct WGConfig: Decodable {
settingsLines.append("I5 = \(i5)")
}
if let headerProtectionKey = trimmed(headerProtectionKey) {
settingsLines.append("HeaderProtectionKey = \(headerProtectionKey)")
}
if let contentPaddingAddition = trimmed(contentPaddingAddition) {
settingsLines.append("ContentPaddingAddition = \(contentPaddingAddition)")
}
if let rekeyAfterTime = trimmed(rekeyAfterTime) {
settingsLines.append("RekeyAfterTime = \(rekeyAfterTime)")
}
if let rekeyTimeout = trimmed(rekeyTimeout) {
settingsLines.append("RekeyTimeout = \(rekeyTimeout)")
}
if let rejectAfterTime = trimmed(rejectAfterTime) {
settingsLines.append("RejectAfterTime = \(rejectAfterTime)")
}
if let keepaliveTimeout = trimmed(keepaliveTimeout) {
settingsLines.append("KeepaliveTimeout = \(keepaliveTimeout)")
}
if let maxHandshakeAttempts = trimmed(maxHandshakeAttempts) {
settingsLines.append("MaxHandshakeAttempts = \(maxHandshakeAttempts)")
}
return settingsLines.joined(separator: "\n")
}
@@ -145,7 +116,7 @@ struct WGConfig: Decodable {
\(presharedKey == nil ? "" : "PresharedKey = \(presharedKey!)")
AllowedIPs = \(allowedIPs.joined(separator: ", "))
Endpoint = \(hostName):\(port)
\(persistentKeepAlive == nil ? "" : "PersistentKeepalive = \(persistentKeepAlive!)")
PersistentKeepalive = \(persistentKeepAlive)
"""
}
@@ -162,7 +133,7 @@ struct WGConfig: Decodable {
PresharedKey = ***
AllowedIPs = \(allowedIPs.joined(separator: ", "))
Endpoint = \(hostName):\(port)
\(persistentKeepAlive == nil ? "" : "PersistentKeepalive = \(persistentKeepAlive!)")
PersistentKeepalive = \(persistentKeepAlive)
SplitTunnelType = \(splitTunnelType)
SplitTunnelSites = \(splitTunnelSites.joined(separator: ", "))

View File

@@ -80,9 +80,6 @@ public:
void requestInetAccess();
bool isTestFlight();
void showUpdatePrompt(const QString &title, const QString &message, const QString &updateTitle,
const QString &skipTitle, const QString &storeUrl);
signals:
void connectionStateChanged(Vpn::ConnectionState state);
void bytesChanged(quint64 receivedBytes, quint64 sentBytes);

View File

@@ -591,6 +591,8 @@ bool IosController::setupWireGuard()
if (config.contains(configKey::persistentKeepAlive)) {
wgConfig.insert(configKey::persistentKeepAlive, config[configKey::persistentKeepAlive]);
} else {
wgConfig.insert(configKey::persistentKeepAlive, "25");
}
if (config.contains(configKey::isObfuscationEnabled) && config.value(configKey::isObfuscationEnabled).toBool()) {
@@ -607,14 +609,6 @@ bool IosController::setupWireGuard()
wgConfig.insert(configKey::junkPacketCount, config[configKey::junkPacketCount]);
wgConfig.insert(configKey::junkPacketMinSize, config[configKey::junkPacketMinSize]);
wgConfig.insert(configKey::junkPacketMaxSize, config[configKey::junkPacketMaxSize]);
wgConfig.insert(configKey::headerProtectionKey, config[configKey::headerProtectionKey]);
wgConfig.insert(configKey::contentPaddingAddition, config[configKey::contentPaddingAddition]);
wgConfig.insert(configKey::rekeyAfterTime, config[configKey::rekeyAfterTime]);
wgConfig.insert(configKey::rekeyTimeout, config[configKey::rekeyTimeout]);
wgConfig.insert(configKey::rejectAfterTime, config[configKey::rejectAfterTime]);
wgConfig.insert(configKey::keepaliveTimeout, config[configKey::keepaliveTimeout]);
wgConfig.insert(configKey::maxHandshakeAttempts, config[configKey::maxHandshakeAttempts]);
}
QJsonDocument wgConfigDoc(wgConfig);
@@ -703,6 +697,8 @@ bool IosController::setupAwg()
if (config.contains(configKey::persistentKeepAlive)) {
wgConfig.insert(configKey::persistentKeepAlive, config[configKey::persistentKeepAlive]);
} else {
wgConfig.insert(configKey::persistentKeepAlive, "25");
}
wgConfig.insert(configKey::initPacketMagicHeader, config[configKey::initPacketMagicHeader]);
@@ -725,14 +721,6 @@ bool IosController::setupAwg()
wgConfig.insert(configKey::specialJunk4, config[configKey::specialJunk4]);
wgConfig.insert(configKey::specialJunk5, config[configKey::specialJunk5]);
wgConfig.insert(configKey::headerProtectionKey, config[configKey::headerProtectionKey]);
wgConfig.insert(configKey::contentPaddingAddition, config[configKey::contentPaddingAddition]);
wgConfig.insert(configKey::rekeyAfterTime, config[configKey::rekeyAfterTime]);
wgConfig.insert(configKey::rekeyTimeout, config[configKey::rekeyTimeout]);
wgConfig.insert(configKey::rejectAfterTime, config[configKey::rejectAfterTime]);
wgConfig.insert(configKey::keepaliveTimeout, config[configKey::keepaliveTimeout]);
wgConfig.insert(configKey::maxHandshakeAttempts, config[configKey::maxHandshakeAttempts]);
QJsonDocument wgConfigDoc(wgConfig);
QString wgConfigDocStr(wgConfigDoc.toJson(QJsonDocument::Compact));
@@ -1212,85 +1200,3 @@ bool IosController::isTestFlight() {
NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
return receiptURL && [[receiptURL lastPathComponent] isEqualToString:@"sandboxReceipt"];
}
#if !MACOS_NE
static UIWindow *s_updateAlertWindow = nil;
static UIWindowScene *activeWindowScene() {
UIWindowScene *fallback = nil;
for (UIScene *scene in [UIApplication sharedApplication].connectedScenes) {
if (![scene isKindOfClass:[UIWindowScene class]]) {
continue;
}
fallback = (UIWindowScene *)scene;
if (scene.activationState == UISceneActivationStateForegroundActive) {
return (UIWindowScene *)scene;
}
}
return fallback;
}
#endif
void IosController::showUpdatePrompt(const QString &title, const QString &message, const QString &updateTitle,
const QString &skipTitle, const QString &storeUrl) {
#if !MACOS_NE
NSString *nsTitle = title.toNSString();
NSString *nsMessage = message.toNSString();
NSString *nsUpdate = updateTitle.toNSString();
NSString *nsSkip = skipTitle.toNSString();
NSString *nsUrl = storeUrl.toNSString();
dispatch_async(dispatch_get_main_queue(), ^{
if (s_updateAlertWindow) {
return;
}
UIWindowScene *scene = activeWindowScene();
if (!scene) {
return;
}
UIWindow *win = [[UIWindow alloc] initWithWindowScene:scene];
win.windowLevel = UIWindowLevelAlert + 1;
win.backgroundColor = [UIColor clearColor];
UIViewController *vc = [[[UIViewController alloc] init] autorelease];
vc.view.backgroundColor = [UIColor clearColor];
win.rootViewController = vc;
[win makeKeyAndVisible];
s_updateAlertWindow = win;
void (^dismiss)(void) = ^{
s_updateAlertWindow.hidden = YES;
[s_updateAlertWindow release];
s_updateAlertWindow = nil;
};
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nsTitle
message:nsMessage
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *updateAction = [UIAlertAction actionWithTitle:nsUpdate
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
NSURL *url = [NSURL URLWithString:nsUrl];
if (url) {
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
}
dismiss();
}];
UIAlertAction *skipAction = [UIAlertAction actionWithTitle:nsSkip
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action) {
dismiss();
}];
[alert addAction:updateAction];
[alert addAction:skipAction];
alert.preferredAction = updateAction;
[vc presentViewController:alert animated:YES completion:nil];
});
#else
Q_UNUSED(title) Q_UNUSED(message) Q_UNUSED(updateTitle) Q_UNUSED(skipTitle) Q_UNUSED(storeUrl)
#endif
}

View File

@@ -33,6 +33,7 @@
#include "linuxfirewall.h"
#include "logger.h"
#include "xray_defs.h"
#include <QFileInfo>
#include <QProcess>
#define BRAND_CODE "amn"
@@ -109,7 +110,7 @@ int LinuxFirewall::linkChain(LinuxFirewall::IPVersion ip, const QString& chain,
// (we can't safely delete all rules at once since rule numbers change)
// TODO: occasionally this script results in warnings in logs "Bad rule (does a matching rule exist in the chain?)" - this happens when
// the e.g OUTPUT chain is empty but this script attempts to delete things from it anyway. It doesn't cause any problems, but we should still fix at some point..
return execute(QStringLiteral("if ! %1 -L %2 -n --line-numbers -t %4 2> /dev/null | awk 'int($1) == 1 && $2 == \"%3\" { found=1 } END { if(found==1) { exit 0 } else { exit 1 } }' ; then %1 -I %2 -j %3 -t %4 && %1 -L %2 -n --line-numbers -t %4 2> /dev/null | awk 'int($1) > 1 && $2 == \"%3\" { print $1; exit }' | xargs %1 -t %4 -D %2 ; fi").arg(cmd, parent, chain, tableName));
return execute(QStringLiteral("if ! %1 -L %2 -n --line-numbers -t %4 2> /dev/null | awk 'int($1) == 1 && $2 == \"%3\" { found=1 } END { if(found==1) { exit 0 } else { exit 1 } }' ; then %1 -I %2 -j %3 -t %4 && %1 -L %2 -n --line-numbers -t %4 2> /dev/null | awk 'int($1) > 1 && $2 == \"%3\" { print $1; exit }' | xargs -r %1 -t %4 -D %2 ; fi").arg(cmd, parent, chain, tableName));
}
else
return execute(QStringLiteral("if ! %1 -C %2 -j %3 -t %4 2> /dev/null ; then %1 -A %2 -j %3 -t %4; fi").arg(cmd, parent, chain, tableName));
@@ -291,6 +292,8 @@ void LinuxFirewall::install()
installAnchor(IPv4, QStringLiteral("110.allowNets"), {});
installAnchor(Both, QStringLiteral("400.allowPIA"), {});
installAnchor(Both, QStringLiteral("100.blockAll"), {
QStringLiteral("-j REJECT"),
});
@@ -454,16 +457,33 @@ void LinuxFirewall::updateDNSServers(const QStringList& servers)
static QStringList existingServers {};
existingServers = servers;
execute(QStringLiteral("iptables -F %1.320.allowDNS").arg(kAnchorName));
for (const QString& rule : getDNSRules(servers))
execute(QStringLiteral("iptables -A %1.320.allowDNS %2").arg(kAnchorName, rule));
const QString chain = QStringLiteral("%1.320.allowDNS").arg(kAnchorName);
executeIptables(QStringLiteral("iptables"), {QStringLiteral("-F"), chain});
const QStringList ifaces = {
QStringLiteral("amn0+"), QStringLiteral("tun0+"), QStringLiteral("tun2+")
};
for (const QString& server : servers) {
for (const QString& iface : ifaces) {
executeIptables(QStringLiteral("iptables"),
{QStringLiteral("-A"), chain, QStringLiteral("-o"), iface,
QStringLiteral("-d"), server, QStringLiteral("-p"), QStringLiteral("udp"),
QStringLiteral("--dport"), QStringLiteral("53"), QStringLiteral("-j"), QStringLiteral("ACCEPT")});
executeIptables(QStringLiteral("iptables"),
{QStringLiteral("-A"), chain, QStringLiteral("-o"), iface,
QStringLiteral("-d"), server, QStringLiteral("-p"), QStringLiteral("tcp"),
QStringLiteral("--dport"), QStringLiteral("53"), QStringLiteral("-j"), QStringLiteral("ACCEPT")});
}
}
}
void LinuxFirewall::updateAllowNets(const QStringList& servers)
{
execute(QStringLiteral("iptables -F %1.110.allowNets").arg(kAnchorName));
for (const QString& rule : getAllowRule(servers))
execute(QStringLiteral("iptables -A %1.110.allowNets %2").arg(kAnchorName, rule));
const QString chain = QStringLiteral("%1.110.allowNets").arg(kAnchorName);
executeIptables(QStringLiteral("iptables"), {QStringLiteral("-F"), chain});
for (const QString& server : servers)
executeIptables(QStringLiteral("iptables"),
{QStringLiteral("-A"), chain, QStringLiteral("-d"), server,
QStringLiteral("-j"), QStringLiteral("ACCEPT")});
}
void LinuxFirewall::updateBlockNets(const QStringList& servers)
@@ -471,9 +491,12 @@ void LinuxFirewall::updateBlockNets(const QStringList& servers)
static QStringList existingServers {};
existingServers = servers;
execute(QStringLiteral("iptables -F %1.120.blockNets").arg(kAnchorName));
for (const QString& rule : getBlockRule(servers))
execute(QStringLiteral("iptables -A %1.120.blockNets %2").arg(kAnchorName, rule));
const QString chain = QStringLiteral("%1.120.blockNets").arg(kAnchorName);
executeIptables(QStringLiteral("iptables"), {QStringLiteral("-F"), chain});
for (const QString& server : servers)
executeIptables(QStringLiteral("iptables"),
{QStringLiteral("-A"), chain, QStringLiteral("-d"), server,
QStringLiteral("-j"), QStringLiteral("REJECT")});
}
int waitForExitCode(QProcess& process)
@@ -506,10 +529,39 @@ int LinuxFirewall::execute(const QString &command, bool ignoreErrors)
return exitCode;
}
int LinuxFirewall::executeIptables(const QString &program, const QStringList &args, bool ignoreErrors)
{
QProcess p;
p.start(program, args, QProcess::ReadOnly);
p.closeWriteChannel();
int exitCode = waitForExitCode(p);
auto out = p.readAllStandardOutput().trimmed();
auto err = p.readAllStandardError().trimmed();
if ((exitCode != 0 || !err.isEmpty()) && !ignoreErrors)
logger.warning() << "(" << exitCode << ") $ " << program << args.join(QLatin1Char(' '));
if (!out.isEmpty())
logger.info() << out;
if (!err.isEmpty())
logger.warning() << err;
return exitCode;
}
void LinuxFirewall::setupTrafficSplitting()
{
const QString cgroupBase = QStringLiteral("/sys/fs/cgroup/net_cls");
if (!QFileInfo::exists(cgroupBase)) {
logger.warning() << "net_cls cgroup v1 not available, traffic splitting disabled";
return;
}
execute(QStringLiteral(
"if ! grep -qE '^[0-9]+[[:space:]]+%1$' /etc/iproute2/rt_tables 2>/dev/null ; then "
"echo '200 %1' >> /etc/iproute2/rt_tables ; fi"
).arg(kRtableName));
auto cGroupDir = "/sys/fs/cgroup/net_cls/" BRAND_CODE "vpnexclusions/";
logger.info() << "Should be setting up cgroup in" << cGroupDir << "for traffic splitting";
logger.info() << "Setting up cgroup in" << cGroupDir << "for traffic splitting";
execute(QStringLiteral("if [ ! -d %1 ] ; then mkdir %1 ; sleep 0.1 ; echo %2 > %1/net_cls.classid ; fi").arg(cGroupDir).arg(kCGroupId));
// Set a rule with priority 100 (lower priority than local but higher than main/default, 0 is highest priority)
execute(QStringLiteral("if ! ip rule list | grep -q %1 ; then ip rule add from all fwmark %1 lookup %2 pri 100 ; fi").arg(kPacketTag, kRtableName));
@@ -518,7 +570,7 @@ void LinuxFirewall::setupTrafficSplitting()
void LinuxFirewall::teardownTrafficSplitting()
{
logger.info() << "Tearing down cgroup and routing rules";
execute(QStringLiteral("if ip rule list | grep -q %1; then ip rule del from all fwmark %1 lookup %2 2> /dev/null ; fi").arg(kPacketTag, kRtableName));
execute(QStringLiteral("ip route flush table %1").arg(kRtableName));
execute(QStringLiteral("if ip rule list | grep -q %1; then ip rule del from all fwmark %1 lookup %2 2>/dev/null ; fi").arg(kPacketTag, kRtableName));
execute(QStringLiteral("ip route flush table %1 2>/dev/null || true").arg(kRtableName));
execute(QStringLiteral("ip route flush cache"));
}

View File

@@ -85,6 +85,7 @@ private:
static void setupTrafficSplitting();
static void teardownTrafficSplitting();
static int execute(const QString& command, bool ignoreErrors = false);
static int executeIptables(const QString& program, const QStringList& args, bool ignoreErrors = false);
private:
// Chain names
static QString kOutputChain, kRootChain, kPostRoutingChain, kPreRoutingChain;

View File

@@ -144,30 +144,6 @@ bool WireguardUtilsLinux::addInterface(const InterfaceConfig& config) {
out << key.toLower() << "=" << config.m_specialJunk.value(key) << "\n";
}
if (!config.m_headerProtectionKey.isEmpty()) {
QByteArray headerProtectionKey =
QByteArray::fromBase64(config.m_headerProtectionKey.toUtf8());
out << "header_protection_key=" << QString(headerProtectionKey.toHex()) << "\n";
}
if (!config.m_contentPaddingAddition.isEmpty()) {
out << "content_padding_addition=" << config.m_contentPaddingAddition << "\n";
}
if (!config.m_rekeyAfterTime.isEmpty()) {
out << "rekey_after_time=" << config.m_rekeyAfterTime << "\n";
}
if (!config.m_rekeyTimeout.isEmpty()) {
out << "rekey_timeout=" << config.m_rekeyTimeout << "\n";
}
if (!config.m_rejectAfterTime.isEmpty()) {
out << "reject_after_time=" << config.m_rejectAfterTime << "\n";
}
if (!config.m_keepaliveTimeout.isEmpty()) {
out << "keepalive_timeout=" << config.m_keepaliveTimeout << "\n";
}
if (!config.m_maxHandshakeAttempts.isEmpty()) {
out << "max_handshake_attempts=" << config.m_maxHandshakeAttempts << "\n";
}
int err = uapiErrno(uapiCommand(message));
if (err != 0) {
logger.error() << "Interface configuration failed:" << strerror(err);
@@ -253,9 +229,7 @@ bool WireguardUtilsLinux::updatePeer(const InterfaceConfig& config) {
out << config.m_serverPort << "\n";
out << "replace_allowed_ips=true\n";
if (!config.m_persistentKeepalive.isEmpty()) {
out << "persistent_keepalive_interval=" << config.m_persistentKeepalive << "\n";
}
out << "persistent_keepalive_interval=" << WG_KEEPALIVE_PERIOD << "\n";
for (const IPAddress& ip : config.m_allowedIPAddressRanges) {
out << "allowed_ip=" << ip.toString() << "\n";
}

View File

@@ -142,30 +142,6 @@ bool WireguardUtilsMacos::addInterface(const InterfaceConfig& config) {
out << key.toLower() << "=" << config.m_specialJunk.value(key) << "\n";
}
if (!config.m_headerProtectionKey.isEmpty()) {
QByteArray headerProtectionKey =
QByteArray::fromBase64(config.m_headerProtectionKey.toUtf8());
out << "header_protection_key=" << QString(headerProtectionKey.toHex()) << "\n";
}
if (!config.m_contentPaddingAddition.isEmpty()) {
out << "content_padding_addition=" << config.m_contentPaddingAddition << "\n";
}
if (!config.m_rekeyAfterTime.isEmpty()) {
out << "rekey_after_time=" << config.m_rekeyAfterTime << "\n";
}
if (!config.m_rekeyTimeout.isEmpty()) {
out << "rekey_timeout=" << config.m_rekeyTimeout << "\n";
}
if (!config.m_rejectAfterTime.isEmpty()) {
out << "reject_after_time=" << config.m_rejectAfterTime << "\n";
}
if (!config.m_keepaliveTimeout.isEmpty()) {
out << "keepalive_timeout=" << config.m_keepaliveTimeout << "\n";
}
if (!config.m_maxHandshakeAttempts.isEmpty()) {
out << "max_handshake_attempts=" << config.m_maxHandshakeAttempts << "\n";
}
int err = uapiErrno(uapiCommand(message));
if (err != 0) {
logger.error() << "Interface configuration failed:" << strerror(err);
@@ -253,9 +229,7 @@ bool WireguardUtilsMacos::updatePeer(const InterfaceConfig& config) {
out << config.m_serverPort << "\n";
out << "replace_allowed_ips=true\n";
if (!config.m_persistentKeepalive.isEmpty()) {
out << "persistent_keepalive_interval=" << config.m_persistentKeepalive << "\n";
}
out << "persistent_keepalive_interval=" << WG_KEEPALIVE_PERIOD << "\n";
for (const IPAddress& ip : config.m_allowedIPAddressRanges) {
out << "allowed_ip=" << ip.toString() << "\n";
}

View File

@@ -180,9 +180,7 @@ bool WireguardUtilsWindows::updatePeer(const InterfaceConfig& config) {
out << config.m_serverPort << "\n";
out << "replace_allowed_ips=true\n";
if (!config.m_persistentKeepalive.isEmpty()) {
out << "persistent_keepalive_interval=" << config.m_persistentKeepalive << "\n";
}
out << "persistent_keepalive_interval=" << WG_KEEPALIVE_PERIOD << "\n";
for (const IPAddress& ip : config.m_allowedIPAddressRanges) {
out << "allowed_ip=" << ip.toString() << "\n";
}

View File

@@ -29,7 +29,6 @@ void ConnectionUiController::openConnection()
{
const QString serverId = m_serversController->getDefaultServerId();
if (serverId.isEmpty()) {
m_connectionController->setConnectionState(Vpn::ConnectionState::Disconnected);
return;
}

View File

@@ -1,163 +0,0 @@
#include "marketplaceUpdateController.h"
#include <QDebug>
#include "version.h"
#if defined(Q_OS_IOS) || defined(Q_OS_ANDROID)
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLocale>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QRegularExpression>
#include <QVersionNumber>
#include "amneziaApplication.h"
#endif
#if defined(Q_OS_IOS)
#include "platforms/ios/ios_controller.h"
#endif
#if defined(Q_OS_ANDROID)
#include "platforms/android/android_controller.h"
#endif
#if defined(Q_OS_IOS) || defined(Q_OS_ANDROID)
namespace
{
#if defined(Q_OS_IOS)
constexpr auto kIosBundleId = "org.amnezia.AmneziaVPN";
constexpr auto kIosStoreUrlFallback = "itms-apps://itunes.apple.com/app/id1600529900";
#else
constexpr auto kAndroidPackage = "org.amnezia.vpn";
constexpr auto kGithubReleasesUrl = "https://github.com/amnezia-vpn/amnezia-client/releases/latest";
#endif
} // namespace
#endif
MarketplaceUpdateController::MarketplaceUpdateController(QObject *parent) : QObject(parent)
{
}
void MarketplaceUpdateController::start()
{
#if defined(Q_OS_IOS)
startNetworkCheck();
#elif defined(Q_OS_ANDROID)
connect(AndroidController::instance(), &AndroidController::playUpdateResult, this,
&MarketplaceUpdateController::onPlayUpdateResult, Qt::UniqueConnection);
const QString restartTitle = tr("Update downloaded");
const QString restartMessage = tr("An update to AmneziaVPN has been downloaded. Restart to install it.");
const QString restartAction = tr("Restart");
const QString restartLater = tr("Later");
AndroidController::instance()->checkPlayUpdate(restartTitle, restartMessage, restartAction, restartLater);
#endif
}
#if defined(Q_OS_ANDROID)
void MarketplaceUpdateController::onPlayUpdateResult(int status)
{
if (status == 1) {
qInfo() << "[MarketplaceUpdate] Play unavailable, falling back to GitHub";
startNetworkCheck();
}
}
#endif
#if defined(Q_OS_IOS) || defined(Q_OS_ANDROID)
void MarketplaceUpdateController::startNetworkCheck()
{
const QUrl url = versionSourceUrl();
if (!url.isValid()) {
return;
}
QNetworkRequest request(url);
request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::AlwaysNetwork);
request.setHeader(QNetworkRequest::UserAgentHeader, QByteArrayLiteral("AmneziaVPN"));
request.setTransferTimeout(7000);
QNetworkReply *reply = amnApp->networkManager()->get(request);
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
reply->deleteLater();
if (reply->error() != QNetworkReply::NoError) {
qWarning() << "[MarketplaceUpdate] network error:" << reply->errorString();
return;
}
QString version;
QString storeUrl;
if (!parseStoreVersion(reply->readAll(), version, storeUrl) || version.isEmpty()) {
qWarning() << "[MarketplaceUpdate] could not determine store version";
return;
}
const auto current = QVersionNumber::fromString(QString(APP_VERSION)).normalized();
const auto store = QVersionNumber::fromString(version).normalized();
qInfo() << "[MarketplaceUpdate] current:" << current.toString() << "store:" << store.toString();
if (store > current) {
showUpdatePrompt(storeUrl);
}
});
}
QUrl MarketplaceUpdateController::versionSourceUrl() const
{
#if defined(Q_OS_IOS)
const QString country = QLocale::system().name().section('_', 1, 1).toLower();
QString url = QStringLiteral("https://itunes.apple.com/lookup?bundleId=%1").arg(kIosBundleId);
if (!country.isEmpty()) {
url += QStringLiteral("&country=%1").arg(country);
}
return QUrl(url);
#else
return QUrl(QStringLiteral("https://play.google.com/store/apps/details?id=%1&hl=en&gl=US").arg(kAndroidPackage));
#endif
}
bool MarketplaceUpdateController::parseStoreVersion(const QByteArray &body, QString &version, QString &storeUrl)
{
#if defined(Q_OS_IOS)
const auto results = QJsonDocument::fromJson(body).object().value("results").toArray();
if (results.isEmpty()) {
return false;
}
const auto first = results.first().toObject();
version = first.value("version").toString();
storeUrl = first.value("trackViewUrl").toString();
if (storeUrl.isEmpty()) {
storeUrl = QString::fromLatin1(kIosStoreUrlFallback);
}
return !version.isEmpty();
#else
const QString html = QString::fromUtf8(body);
static const QRegularExpression re(QStringLiteral("\\[\\[\\[\"(\\d+\\.\\d+(?:\\.\\d+){0,2})\"\\]\\]"));
const auto match = re.match(html);
if (match.hasMatch()) {
version = match.captured(1);
}
storeUrl = QString::fromLatin1(kGithubReleasesUrl);
return !version.isEmpty();
#endif
}
void MarketplaceUpdateController::showUpdatePrompt(const QString &storeUrl)
{
const QString title = tr("Update available");
const QString message = tr("A new version of AmneziaVPN is available.");
const QString updateTitle = tr("Update");
const QString skipTitle = tr("Skip");
#if defined(Q_OS_IOS)
IosController::Instance()->showUpdatePrompt(title, message, updateTitle, skipTitle, storeUrl);
#else
AndroidController::instance()->showUpdatePrompt(title, message, updateTitle, skipTitle, storeUrl);
#endif
}
#endif

View File

@@ -1,31 +0,0 @@
#ifndef MARKETPLACEUPDATECONTROLLER_H
#define MARKETPLACEUPDATECONTROLLER_H
#include <QObject>
#include <QUrl>
class MarketplaceUpdateController : public QObject
{
Q_OBJECT
public:
explicit MarketplaceUpdateController(QObject *parent = nullptr);
public slots:
void start();
private:
#if defined(Q_OS_IOS) || defined(Q_OS_ANDROID)
void startNetworkCheck();
QUrl versionSourceUrl() const;
bool parseStoreVersion(const QByteArray &body, QString &version, QString &storeUrl);
void showUpdatePrompt(const QString &storeUrl);
#endif
#if defined(Q_OS_ANDROID)
private slots:
void onPlayUpdateResult(int status);
#endif
};
#endif // MARKETPLACEUPDATECONTROLLER_H

View File

@@ -635,7 +635,6 @@ void InstallUiController::validateConfig()
{
const QString serverId = m_serversController->getDefaultServerId();
if (serverId.isEmpty()) {
emit configValidated(false);
return;
}
m_installController->validateConfig(serverId);

View File

@@ -4,7 +4,7 @@ import QtQuick.Controls
Menu {
property var textObj
popupType: Popup.Native
popupType: Qt.platform.os === "ios" ? Popup.Item : Popup.Native
property Item inputBlocker: null

View File

@@ -93,7 +93,7 @@ Rectangle {
wrapMode: Text.Wrap
ContextMenu.menu: contextMenu
ContextMenu.menu: Qt.platform.os === "ios" ? null : contextMenu
ContextMenuType {
id: contextMenu

View File

@@ -79,7 +79,7 @@ Rectangle {
wrapMode: Text.Wrap
ContextMenu.menu: contextMenu
ContextMenu.menu: Qt.platform.os === "ios" ? null : contextMenu
ContextMenuType {
id: contextMenu

View File

@@ -144,7 +144,7 @@ Item {
}
}
ContextMenu.menu: contextMenu
ContextMenu.menu: Qt.platform.os === "ios" ? null : contextMenu
ContextMenuType {
id: contextMenu

View File

@@ -69,7 +69,9 @@ PageType {
rightImageSource: "qrc:/images/controls/chevron-right.svg"
clickedFunction: function() {
NewsModel.markAsRead(index)
if (!isUpdate) {
NewsModel.markAsRead(index)
}
NewsModel.processedIndex = index
PageController.goToPage(PageEnum.PageSettingsNewsDetail)
}

View File

@@ -408,10 +408,11 @@ void VpnConnection::appendSplitTunnelingConfig()
for (auto &line : nativeConfigLines) {
if (line.contains("PersistentKeepalive")) {
auto persistentKeepaliveString = line.split(" = ");
if (persistentKeepaliveString.size() > 1) {
configData.insert(configKey::persistentKeepAlive, persistentKeepaliveString.at(1));
m_vpnConfiguration.insert(protocolName + "_config_data", configData);
if (persistentKeepaliveString.size() < 1) {
break;
}
configData.insert(configKey::persistentKeepAlive, persistentKeepaliveString.at(1));
m_vpnConfiguration.insert(protocolName + "_config_data", configData);
break;
}
}

View File

@@ -19,26 +19,26 @@ class AmneziaVPN(ConanFile):
if has_service:
if os == "Windows":
self.requires("awg-windows/3.0.2")
self.requires("awg-windows/0.2.0")
self.requires("tap-windows6/9.27.0")
self.requires("win-split-tunnel/1.2.5.0")
self.requires("wintun/0.14.1")
else:
self.requires("awg-go/3.0.1")
self.requires("awg-go/0.2.19")
self.requires("amnezia-xray-bindings/1.3.0")
self.requires("amnezia-xray-bindings/1.2.0")
self.requires("tun2socks/2.6.0")
self.requires("openvpn/2.7.0")
self.requires("v2ray-rules-dat/202603162227")
if has_ne:
self.requires("awg-apple/3.0.1")
self.requires("awg-apple/2.0.3")
self.requires("hev-socks5-tunnel/2.15.0", options={"as_framework": True})
self.requires("openvpnadapter/1.0.0")
if os == "Android":
self.requires("amnezia-libxray/1.0.2")
self.requires("awg-android/3.0.1")
self.requires("amnezia-libxray/1.0.1")
self.requires("awg-android/2.0.2")
self.requires("openvpn-pt-android/1.0.0")
# expicitly use libssh@amnezia to prevent it from being downloaded from conan-center

View File

@@ -3,6 +3,8 @@
#include <QObject>
#include <QString>
#include <QRegularExpression>
#include <QSet>
#include "../client/core/utils/utilities.h"
@@ -15,7 +17,8 @@ enum PermittedProcess {
OpenVPN,
Wireguard,
Tun2Socks,
CertUtil
CertUtil,
_Count
};
inline QString permittedProcessPath(PermittedProcess pid)
@@ -57,16 +60,56 @@ inline QStringList sanitizeArguments(PermittedProcess proc, const QStringList &a
QList<Validator> positionalArgs;
switch (proc) {
case OpenVPN: {
static const QSet<QString> blocked = {
QStringLiteral("--script-security"),
QStringLiteral("--up"),
QStringLiteral("--down"),
QStringLiteral("--route-up"),
QStringLiteral("--ipchange"),
QStringLiteral("--tls-verify"),
QStringLiteral("--plugin"),
QStringLiteral("--auth-user-pass-verify"),
QStringLiteral("--learn-address"),
QStringLiteral("--client-connect"),
QStringLiteral("--client-disconnect"),
QStringLiteral("--management"),
QStringLiteral("--management-external-key")
};
QStringList out;
for (int i = 0; i < args.size(); ++i) {
if (blocked.contains(args[i])) {
qWarning() << "IPC: blocked OpenVPN argument:" << args[i];
++i; // skip following value
continue;
}
out << args[i];
}
return out;
}
case Wireguard: {
static const QRegularExpression hookRe(
QStringLiteral(R"((?i)(PostUp|PreUp|PostDown|PreDown)\s*=)"));
QStringList out;
for (const QString& a : args) {
if (hookRe.match(a).hasMatch()) {
qWarning() << "IPC: blocked WireGuard hook argument:" << a;
continue;
}
out << a;
}
return out;
}
case Tun2Socks:
namedArgs["-device"] = [](const QString& v) { return v.startsWith("tun://"); };
namedArgs["-proxy"] = [](const QString& v) { return v.startsWith("socks5://"); };
break;
default:
//FIXME
case CertUtil:
return args;
default:
return {};
}
QStringList sanitized;
for (int i = 0, pos = 0; i < args.size(); i++) {

View File

@@ -22,6 +22,27 @@
#include "tapcontroller_win.h"
#endif
#ifdef Q_OS_LINUX
#include <sys/socket.h>
#include <sys/types.h>
extern uid_t g_allowedUid;
extern bool g_allowedUidSet;
static bool checkPrivPeerCredentials(QLocalSocket *socket) {
struct ucred cred{};
socklen_t len = sizeof(cred);
if (getsockopt(socket->socketDescriptor(), SOL_SOCKET, SO_PEERCRED, &cred, &len) != 0) {
qWarning() << "IpcServer: SO_PEERCRED failed, rejecting privileged process connection";
return false;
}
if (cred.uid == 0) return true;
if (g_allowedUidSet && cred.uid == g_allowedUid) return true;
qWarning() << "IpcServer: rejected privileged process connection from unauthorized UID" << cred.uid;
return false;
}
#endif
IpcServer::IpcServer(QObject *parent) : IpcInterfaceSource(parent)
{
@@ -48,8 +69,16 @@ int IpcServer::createPrivilegedProcess()
// Make sure any connections are handed to QtRO
QObject::connect(pd.localServer.data(), &QLocalServer::newConnection, this, [pd]() {
qDebug() << "IpcServer new connection";
QLocalSocket *conn = pd.localServer->nextPendingConnection();
#ifdef Q_OS_LINUX
if (!checkPrivPeerCredentials(conn)) {
conn->close();
conn->deleteLater();
return;
}
#endif
if (pd.serverNode) {
pd.serverNode->addHostSideConnection(pd.localServer->nextPendingConnection());
pd.serverNode->addHostSideConnection(conn);
pd.serverNode->enableRemoting(pd.ipcProcess.data());
}
});

View File

@@ -77,6 +77,11 @@ void IpcServerProcess::setProcessChannelMode(QProcess::ProcessChannelMode mode)
void IpcServerProcess::setProgram(int programId)
{
if (programId <= static_cast<int>(amnezia::PermittedProcess::Invalid) ||
programId >= static_cast<int>(amnezia::PermittedProcess::_Count)) {
qWarning() << "IPC: invalid programId" << programId << ", ignoring";
return;
}
m_program = static_cast<amnezia::PermittedProcess>(programId);
m_process->setProgram(amnezia::permittedProcessPath(m_program));
m_process->setArguments({});

View File

@@ -1,3 +0,0 @@
patches:
"1.0.1":
- patch_file: "patches/0001-add-16kb-page-support-amnezia-libxray.patch"

View File

@@ -1,5 +1,5 @@
from conan import ConanFile
from conan.tools.files import get, copy, apply_conandata_patches, export_conandata_patches
from conan.tools.files import get, copy
from conan.tools.layout import basic_layout
from conan.errors import ConanInvalidConfiguration
from conan.tools.env import Environment
@@ -11,12 +11,9 @@ from pathlib import Path
class AmneziaLibxray(ConanFile):
name = "amnezia-libxray"
version = "1.0.2"
version = "1.0.1"
settings = "os", "arch", "compiler"
def export_sources(self):
export_conandata_patches(self)
def configure(self):
self.settings.rm_safe("compiler.libcxx")
self.settings.rm_safe("compiler.cppstd")
@@ -33,7 +30,7 @@ class AmneziaLibxray(ConanFile):
def source(self):
get(self, f"https://github.com/amnezia-vpn/amnezia-libxray/archive/refs/tags/v{self.version}.zip",
sha256="a434a84574b021c4bcd52d9edc906e5ec03eaaab98c192f683f84294b3e4e79c", strip_root=True
sha256="f17bca781d4a2fad4dfda9e8b1c0f6960a3f75f6218b906b1b0e2458652ffa5a", strip_root=True
)
def generate(self):
@@ -47,7 +44,6 @@ class AmneziaLibxray(ConanFile):
env.vars(self).save_script("conan_provide_androidhome")
def _patch_sources(self):
apply_conandata_patches(self)
build_path = os.path.join(self.build_folder, "build.sh")
build_stat = os.stat(build_path)
os.chmod(build_path, build_stat.st_mode | stat.S_IEXEC)

View File

@@ -1,24 +0,0 @@
From 0531cd00cd580524ec21a663442264136dbd368f Mon Sep 17 00:00:00 2001
From: NickVs2015 <nv@amnezia.org>
Date: Thu, 23 Jul 2026 11:23:07 +0300
Subject: [PATCH] fix: add 16kb page size support for android build
---
build.sh | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/build.sh b/build.sh
index 7969505..02c5b73 100755
--- a/build.sh
+++ b/build.sh
@@ -28,7 +28,7 @@ build_android() {
rm -fr assets
mkdir -p assets/geo
mv dat/* assets/geo
- gomobile bind -target android -androidapi 24 -javapkg=org.amnezia.vpn.protocol.xray -o libxray.aar -ldflags="-w -s -buildid= -checklinkname=0" -trimpath
+ gomobile bind -target android -androidapi 24 -javapkg=org.amnezia.vpn.protocol.xray -o libxray.aar -ldflags="-w -s -buildid= -checklinkname=0 -extldflags=-Wl,-z,max-page-size=16384" -trimpath
}
download_geo() {
--
2.50.1 (Apple Git-155)

View File

@@ -13,7 +13,7 @@ import shlex
class AmneziaXrayBindings(ConanFile):
name = "amnezia-xray-bindings"
version = "1.3.0"
version = "1.2.0"
settings = "os", "arch", "compiler"
_arch_map = {
@@ -76,8 +76,8 @@ class AmneziaXrayBindings(ConanFile):
)
def source(self):
get(self, f"https://github.com/amnezia-vpn/amnezia-xray-bindings/archive/refs/tags/v{self.version}.zip",
sha256="97233926c91e0bed61603fddb9909607b97a65f8ff0841a628f96268637ade5c", strip_root=True)
get(self, f"https://github.com/amnezia-vpn/amnezia-xray-bindings/archive/v{self.version}.zip",
sha256="45b687dcd90cf1d953ece9c9f42d0b02785b2bbb33a97f5bad229f048da34d7c", strip_root=True)
def generate(self):
tc = AutotoolsToolchain(self)

View File

@@ -9,7 +9,7 @@ import platform
class AwgAndroid(ConanFile):
name = "awg-android"
version = "3.0.1"
version = "2.0.2"
settings = "os", "arch", "build_type", "compiler"
def configure(self):

View File

@@ -9,7 +9,7 @@ import os
class AwgApple(ConanFile):
name = "awg-apple"
version = "3.0.1"
version = "2.0.3"
settings = "os", "arch", "compiler"
@property
@@ -39,7 +39,7 @@ class AwgApple(ConanFile):
def source(self):
get(self, f"https://github.com/amnezia-vpn/amneziawg-apple/archive/refs/tags/v{self.version}.zip",
sha256="8efd086e3c51637270be105336692ca89b396b2ea9b71ea30ce28292c61c76e8", strip_root=True
sha256="a868f0dfbded869b6c08b7a7a0e8c1a5485e649a179f4d1715b1b93664ea4fd4", strip_root=True
)
def generate(self):

View File

@@ -14,7 +14,7 @@ import shlex
class AwgGo(ConanFile):
name = "awg-go"
version = "3.0.1"
version = "0.2.19"
package_type = "application"
settings = "os", "arch"
@@ -61,7 +61,7 @@ class AwgGo(ConanFile):
def source(self):
get(self, f"https://github.com/amnezia-vpn/amneziawg-go/archive/refs/tags/v{self.version}.zip",
sha256="3ab9655b894c6fe43dfcba6d1e3cbfff20ca1f1928eae6242875541e82488247", strip_root=True
sha256="430396f9f2d4f6559ac69f178b707f955f7f847723b78e9de748b73d7e718798", strip_root=True
)
def generate(self):

View File

@@ -8,7 +8,7 @@ import os
class AwgWindows(ConanFile):
name = "awg-windows"
version = "3.0.2"
version = "0.2.0"
settings = "os", "arch"
@property
@@ -63,7 +63,7 @@ class AwgWindows(ConanFile):
def source(self):
get(self, f"https://github.com/amnezia-vpn/amneziawg-windows/archive/refs/tags/v{self.version}.zip",
sha256="e5755ef1e19fd8408881cab49684d37ee4a0822d706960bbabe89770f7c436f1", strip_root=True)
sha256="9e74240b9bae2f9c8a9381bdf6e5a43ad37653de186e01e0f5a92935e4310252", strip_root=True)
def generate(self):
tc = AutotoolsToolchain(self)

View File

@@ -3,6 +3,7 @@
#include <QApplication>
#include <QHostAddress>
#include <QRegularExpression>
#include "../client/core/utils/protocolEnum.h"
#include "../client/core/protocols/protocolUtils.h"
@@ -11,6 +12,37 @@
#include "qjsonarray.h"
#include "version.h"
#if defined(Q_OS_LINUX) || defined(Q_OS_MACOS)
static bool isValidIpOrCidr(const QString &value) {
static const QRegularExpression re(
QStringLiteral(R"(^(\d{1,3}\.){3}\d{1,3}(/\d{1,2})?$)"));
if (!re.match(value).hasMatch()) return false;
const QStringList ipParts = value.split(QLatin1Char('/'))[0].split(QLatin1Char('.'));
for (const QString &part : ipParts) {
bool ok;
int octet = part.toInt(&ok);
if (!ok || octet < 0 || octet > 255) return false;
}
if (value.contains(QLatin1Char('/'))) {
bool ok;
int prefix = value.split(QLatin1Char('/'))[1].toInt(&ok);
if (!ok || prefix < 0 || prefix > 32) return false;
}
return true;
}
static QStringList filterIpList(const QStringList &values) {
QStringList safe;
for (const QString &v : values) {
if (isValidIpOrCidr(v))
safe << v;
else
qWarning() << "IPC: rejected invalid IP/CIDR value:" << v;
}
return safe;
}
#endif
#ifdef Q_OS_WIN
#include "../client/platforms/windows/daemon/windowsfirewall.h"
#include "../client/platforms/windows/daemon/windowsdaemon.h"
@@ -166,7 +198,11 @@ bool KillSwitch::disableAllTraffic() {
bool KillSwitch::resetAllowedRange(const QStringList &ranges) {
#ifdef Q_OS_LINUX
m_allowedRanges = filterIpList(ranges);
#else
m_allowedRanges = ranges;
#endif
#ifdef Q_OS_LINUX
LinuxFirewall::setAnchorEnabled(LinuxFirewall::IPv4, QStringLiteral("110.allowNets"), true);
@@ -189,7 +225,12 @@ bool KillSwitch::resetAllowedRange(const QStringList &ranges) {
}
bool KillSwitch::addAllowedRange(const QStringList &ranges) {
for (const QString &range : ranges) {
#ifdef Q_OS_LINUX
const QStringList safeRanges = filterIpList(ranges);
#else
const QStringList &safeRanges = ranges;
#endif
for (const QString &range : safeRanges) {
if (!range.isEmpty() && !m_allowedRanges.contains(range)) {
m_allowedRanges.append(range);
}
@@ -317,9 +358,9 @@ bool KillSwitch::enableKillSwitch(const QJsonObject &configStr, int vpnAdapterIn
LinuxFirewall::setAnchorEnabled(LinuxFirewall::Both, QStringLiteral("000.allowLoopback"), true);
LinuxFirewall::setAnchorEnabled(LinuxFirewall::Both, QStringLiteral("100.blockAll"), blockAll);
LinuxFirewall::setAnchorEnabled(LinuxFirewall::IPv4, QStringLiteral("110.allowNets"), allowNets);
LinuxFirewall::updateAllowNets(allownets);
LinuxFirewall::updateAllowNets(filterIpList(allownets));
LinuxFirewall::setAnchorEnabled(LinuxFirewall::IPv4, QStringLiteral("120.blockNets"), blockAll);
LinuxFirewall::updateBlockNets(blocknets);
LinuxFirewall::updateBlockNets(filterIpList(blocknets));
LinuxFirewall::setAnchorEnabled(LinuxFirewall::Both, QStringLiteral("130.allowMarkedXray"), true);
LinuxFirewall::setAnchorEnabled(LinuxFirewall::IPv4, QStringLiteral("200.allowVPN"), true);
LinuxFirewall::setAnchorEnabled(LinuxFirewall::IPv6, QStringLiteral("250.blockIPv6"), true);
@@ -328,23 +369,36 @@ bool KillSwitch::enableKillSwitch(const QJsonObject &configStr, int vpnAdapterIn
LinuxFirewall::setAnchorEnabled(LinuxFirewall::IPv4, QStringLiteral("310.blockDNS"), true);
QStringList dnsServers;
dnsServers.append(configStr.value(amnezia::configKey::dns1).toString());
const QString dns1 = configStr.value(amnezia::configKey::dns1).toString();
if (isValidIpOrCidr(dns1))
dnsServers.append(dns1);
else if (!dns1.isEmpty())
qWarning() << "IPC: rejected invalid dns1:" << dns1;
// We don't use secondary DNS if primary DNS is AmneziaDNS
if (!configStr.value(amnezia::configKey::dns1).toString().contains(amnezia::protocols::dns::amneziaDnsIp)) {
dnsServers.append(configStr.value(amnezia::configKey::dns2).toString());
if (!dns1.contains(amnezia::protocols::dns::amneziaDnsIp)) {
const QString dns2 = configStr.value(amnezia::configKey::dns2).toString();
if (isValidIpOrCidr(dns2))
dnsServers.append(dns2);
else if (!dns2.isEmpty())
qWarning() << "IPC: rejected invalid dns2:" << dns2;
}
dnsServers.append("127.0.0.1");
dnsServers.append("127.0.0.53");
for (auto dns : configStr.value(amnezia::configKey::allowedDnsServers).toArray()) {
if (!dns.isString()) {
break;
}
dnsServers.append(dns.toString());
const QString dnsStr = dns.toString();
if (isValidIpOrCidr(dnsStr))
dnsServers.append(dnsStr);
else if (!dnsStr.isEmpty())
qWarning() << "IPC: rejected invalid allowedDnsServer:" << dnsStr;
}
LinuxFirewall::updateDNSServers(dnsServers);
LinuxFirewall::setAnchorEnabled(LinuxFirewall::IPv4, QStringLiteral("320.allowDNS"), true);
LinuxFirewall::setAnchorEnabled(LinuxFirewall::Both, QStringLiteral("400.allowPIA"), true);
@@ -360,28 +414,40 @@ bool KillSwitch::enableKillSwitch(const QJsonObject &configStr, int vpnAdapterIn
MacOSFirewall::setAnchorEnabled(QStringLiteral("000.allowLoopback"), true);
MacOSFirewall::setAnchorEnabled(QStringLiteral("100.blockAll"), blockAll);
MacOSFirewall::setAnchorEnabled(QStringLiteral("110.allowNets"), allowNets);
MacOSFirewall::setAnchorTable(QStringLiteral("110.allowNets"), allowNets, QStringLiteral("allownets"), allownets);
MacOSFirewall::setAnchorTable(QStringLiteral("110.allowNets"), allowNets, QStringLiteral("allownets"), filterIpList(allownets));
MacOSFirewall::setAnchorEnabled(QStringLiteral("120.blockNets"), blockNets);
MacOSFirewall::setAnchorTable(QStringLiteral("120.blockNets"), blockNets, QStringLiteral("blocknets"), blocknets);
MacOSFirewall::setAnchorTable(QStringLiteral("120.blockNets"), blockNets, QStringLiteral("blocknets"), filterIpList(blocknets));
MacOSFirewall::setAnchorEnabled(QStringLiteral("200.allowVPN"), true);
MacOSFirewall::setAnchorEnabled(QStringLiteral("250.blockIPv6"), true);
MacOSFirewall::setAnchorEnabled(QStringLiteral("290.allowDHCP"), true);
MacOSFirewall::setAnchorEnabled(QStringLiteral("300.allowLAN"), true);
QStringList dnsServers;
dnsServers.append(configStr.value(amnezia::configKey::dns1).toString());
const QString dns1 = configStr.value(amnezia::configKey::dns1).toString();
if (isValidIpOrCidr(dns1))
dnsServers.append(dns1);
else if (!dns1.isEmpty())
qWarning() << "IPC: rejected invalid dns1:" << dns1;
// We don't use secondary DNS if primary DNS is AmneziaDNS
if (!configStr.value(amnezia::configKey::dns1).toString().contains(amnezia::protocols::dns::amneziaDnsIp)) {
dnsServers.append(configStr.value(amnezia::configKey::dns2).toString());
if (!dns1.contains(amnezia::protocols::dns::amneziaDnsIp)) {
const QString dns2 = configStr.value(amnezia::configKey::dns2).toString();
if (isValidIpOrCidr(dns2))
dnsServers.append(dns2);
else if (!dns2.isEmpty())
qWarning() << "IPC: rejected invalid dns2:" << dns2;
}
for (auto dns : configStr.value(amnezia::configKey::allowedDnsServers).toArray()) {
if (!dns.isString()) {
break;
}
dnsServers.append(dns.toString());
const QString dnsStr = dns.toString();
if (isValidIpOrCidr(dnsStr))
dnsServers.append(dnsStr);
else if (!dnsStr.isEmpty())
qWarning() << "IPC: rejected invalid allowedDnsServer:" << dnsStr;
}
MacOSFirewall::setAnchorEnabled(QStringLiteral("310.blockDNS"), true);

View File

@@ -17,6 +17,35 @@
#include "tapcontroller_win.h"
#endif
#ifdef Q_OS_LINUX
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
uid_t g_allowedUid = static_cast<uid_t>(-1);
bool g_allowedUidSet = false;
static bool checkPeerCredentials(QLocalSocket *socket) {
struct ucred cred{};
socklen_t len = sizeof(cred);
if (getsockopt(socket->socketDescriptor(), SOL_SOCKET, SO_PEERCRED, &cred, &len) != 0) {
qWarning() << "LocalServer: SO_PEERCRED failed, rejecting connection";
return false;
}
if (cred.uid == 0) return true;
if (!g_allowedUidSet) {
g_allowedUid = cred.uid;
g_allowedUidSet = true;
qDebug() << "LocalServer: registered session UID" << g_allowedUid;
}
if (cred.uid != g_allowedUid) {
qWarning() << "LocalServer: rejected connection from unauthorized UID" << cred.uid;
return false;
}
return true;
}
#endif
namespace {
Logger logger("WgDaemonServer");
}
@@ -35,7 +64,15 @@ LocalServer::LocalServer(QObject *parent) : QObject(parent),
QObject::connect(m_server.data(), &QLocalServer::newConnection, this, [this]() {
qDebug() << "LocalServer new connection";
m_serverNode.addHostSideConnection(m_server->nextPendingConnection());
QLocalSocket *conn = m_server->nextPendingConnection();
#ifdef Q_OS_LINUX
if (!checkPeerCredentials(conn)) {
conn->close();
conn->deleteLater();
return;
}
#endif
m_serverNode.addHostSideConnection(conn);
if (!m_isRemotingEnabled) {
m_isRemotingEnabled = true;