mirror of
https://github.com/amnezia-vpn/amnezia-client.git
synced 2026-05-08 14:33:23 +00:00
feat: enhance OpenVPN configuration handling and logging for iOS plat… (#1910)
* feat: enhance OpenVPN configuration handling and logging for iOS platform * refactor: remove $OPENVPN_TA_KEY_SANITIZED and use $OPENVPN_TA_KEY instead
This commit is contained in:
@@ -136,10 +136,21 @@ set_property(TARGET ${PROJECT} APPEND PROPERTY RESOURCE
|
||||
add_subdirectory(ios/networkextension)
|
||||
add_dependencies(${PROJECT} networkextension)
|
||||
|
||||
set_property(TARGET ${PROJECT} PROPERTY XCODE_EMBED_FRAMEWORKS
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/3rd-prebuilt/3rd-prebuilt/openvpn/apple/OpenVPNAdapter-ios/OpenVPNAdapter.framework"
|
||||
set(OPENVPN_FRAMEWORK_DIR "${CMAKE_CURRENT_SOURCE_DIR}/3rd-prebuilt/3rd-prebuilt/openvpn/apple/OpenVPNAdapter-ios")
|
||||
set(OPENVPN_EMBEDDED_FRAMEWORKS
|
||||
"${OPENVPN_FRAMEWORK_DIR}/OpenVPNAdapter.framework"
|
||||
"${OPENVPN_FRAMEWORK_DIR}/OpenVPNClient.framework"
|
||||
"${OPENVPN_FRAMEWORK_DIR}/mbedTLS.framework"
|
||||
"${OPENVPN_FRAMEWORK_DIR}/LZ4.framework"
|
||||
)
|
||||
|
||||
set(CMAKE_XCODE_ATTRIBUTE_FRAMEWORK_SEARCH_PATHS ${CMAKE_CURRENT_SOURCE_DIR}/3rd-prebuilt/3rd-prebuilt/openvpn/apple/OpenVPNAdapter-ios/)
|
||||
target_link_libraries("networkextension" PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/3rd-prebuilt/3rd-prebuilt/openvpn/apple/OpenVPNAdapter-ios/OpenVPNAdapter.framework")
|
||||
set_property(TARGET ${PROJECT} PROPERTY XCODE_EMBED_FRAMEWORKS "${OPENVPN_EMBEDDED_FRAMEWORKS}")
|
||||
set(CMAKE_XCODE_ATTRIBUTE_FRAMEWORK_SEARCH_PATHS "$(inherited) ${OPENVPN_FRAMEWORK_DIR}")
|
||||
|
||||
foreach(_framework ${OPENVPN_EMBEDDED_FRAMEWORKS})
|
||||
target_link_libraries(networkextension PRIVATE "${_framework}")
|
||||
endforeach()
|
||||
|
||||
set_property(TARGET networkextension PROPERTY XCODE_EMBED_FRAMEWORKS "${OPENVPN_EMBEDDED_FRAMEWORKS}")
|
||||
set_property(TARGET networkextension PROPERTY XCODE_EMBED_FRAMEWORKS_CODE_SIGN_ON_COPY ON)
|
||||
set_property(TARGET networkextension PROPERTY XCODE_ATTRIBUTE_FRAMEWORK_SEARCH_PATHS "$(inherited) ${OPENVPN_FRAMEWORK_DIR}")
|
||||
|
||||
@@ -83,12 +83,30 @@ QString OpenVpnConfigurator::createConfig(const ServerCredentials &credentials,
|
||||
return "";
|
||||
}
|
||||
|
||||
auto sanitizeStaticKey = [](const QString &key) {
|
||||
QStringList lines = key.split('\n');
|
||||
QStringList filtered;
|
||||
filtered.reserve(lines.size());
|
||||
for (const QString &line : lines) {
|
||||
const QString trimmed = line.trimmed();
|
||||
if (trimmed.startsWith('#')) {
|
||||
continue;
|
||||
}
|
||||
filtered.append(line);
|
||||
}
|
||||
QString result = filtered.join('\n');
|
||||
if (!result.endsWith('\n')) {
|
||||
result.append('\n');
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
config.replace("$OPENVPN_CA_CERT", connData.caCert);
|
||||
config.replace("$OPENVPN_CLIENT_CERT", connData.clientCert);
|
||||
config.replace("$OPENVPN_PRIV_KEY", connData.privKey);
|
||||
|
||||
if (config.contains("$OPENVPN_TA_KEY")) {
|
||||
config.replace("$OPENVPN_TA_KEY", connData.taKey);
|
||||
config.replace("$OPENVPN_TA_KEY", sanitizeStaticKey(connData.taKey));
|
||||
} else {
|
||||
config.replace("<tls-auth>", "");
|
||||
config.replace("</tls-auth>", "");
|
||||
@@ -117,7 +135,7 @@ QString OpenVpnConfigurator::processConfigWithLocalSettings(const QPair<QString,
|
||||
if (!isApiConfig) {
|
||||
QRegularExpression regex("redirect-gateway.*");
|
||||
config.replace(regex, "");
|
||||
|
||||
|
||||
// We don't use secondary DNS if primary DNS is AmneziaDNS
|
||||
if (dns.first.contains(protocols::dns::amneziaDnsIp)) {
|
||||
QRegularExpression dnsRegex("dhcp-option DNS " + dns.second);
|
||||
|
||||
@@ -2,7 +2,8 @@ import Foundation
|
||||
import os.log
|
||||
|
||||
struct Log {
|
||||
static let osLog = Logger()
|
||||
private static let subsystemIdentifier = Bundle.main.bundleIdentifier ?? "org.amnezia.AmneziaVPN"
|
||||
static let osLog = Logger(subsystem: subsystemIdentifier, category: "App")
|
||||
|
||||
private static let IsLoggingEnabledKey = "IsLoggingEnabled"
|
||||
static var isLoggingEnabled: Bool {
|
||||
@@ -77,9 +78,40 @@ struct Log {
|
||||
static func log(_ type: OSLogType, title: String = "", message: String, url: URL = neLogURL) {
|
||||
NSLog("\(title) \(message)")
|
||||
|
||||
guard isLoggingEnabled else { return }
|
||||
switch type {
|
||||
case .debug:
|
||||
if title.isEmpty {
|
||||
osLog.debug("\(message, privacy: .public)")
|
||||
} else {
|
||||
osLog.debug("\(title, privacy: .public) \(message, privacy: .public)")
|
||||
}
|
||||
case .info:
|
||||
if title.isEmpty {
|
||||
osLog.info("\(message, privacy: .public)")
|
||||
} else {
|
||||
osLog.info("\(title, privacy: .public) \(message, privacy: .public)")
|
||||
}
|
||||
case .error:
|
||||
if title.isEmpty {
|
||||
osLog.error("\(message, privacy: .public)")
|
||||
} else {
|
||||
osLog.error("\(title, privacy: .public) \(message, privacy: .public)")
|
||||
}
|
||||
case .fault:
|
||||
if title.isEmpty {
|
||||
osLog.fault("\(message, privacy: .public)")
|
||||
} else {
|
||||
osLog.fault("\(title, privacy: .public) \(message, privacy: .public)")
|
||||
}
|
||||
default:
|
||||
if title.isEmpty {
|
||||
osLog.log("\(message, privacy: .public)")
|
||||
} else {
|
||||
osLog.log("\(title, privacy: .public) \(message, privacy: .public)")
|
||||
}
|
||||
}
|
||||
|
||||
osLog.log(level: type, "\(title) \(message)")
|
||||
guard isLoggingEnabled else { return }
|
||||
|
||||
let date = Date()
|
||||
let level = Record.Level(from: type)
|
||||
|
||||
@@ -1,22 +1,76 @@
|
||||
import Foundation
|
||||
import os.log
|
||||
|
||||
private let subsystemIdentifier = Bundle.main.bundleIdentifier ?? "org.amnezia.AmneziaVPN"
|
||||
private let wireGuardSystemLogger = Logger(subsystem: subsystemIdentifier, category: "WireGuard")
|
||||
private let openVPNSystemLogger = Logger(subsystem: subsystemIdentifier, category: "OpenVPN")
|
||||
private let xraySystemLogger = Logger(subsystem: subsystemIdentifier, category: "Xray")
|
||||
private let networkExtensionLogger = Logger(subsystem: subsystemIdentifier, category: "NetworkExtension")
|
||||
|
||||
private func logToSystem(_ logger: Logger, type: OSLogType, prefix: String, title: String, message: String) {
|
||||
let combinedTitle: String
|
||||
if title.isEmpty {
|
||||
combinedTitle = prefix
|
||||
} else {
|
||||
combinedTitle = "\(prefix): \(title)"
|
||||
}
|
||||
|
||||
switch type {
|
||||
case .debug:
|
||||
if combinedTitle.isEmpty {
|
||||
logger.debug("\(message, privacy: .public)")
|
||||
} else {
|
||||
logger.debug("\(combinedTitle, privacy: .public) \(message, privacy: .public)")
|
||||
}
|
||||
case .info:
|
||||
if combinedTitle.isEmpty {
|
||||
logger.info("\(message, privacy: .public)")
|
||||
} else {
|
||||
logger.info("\(combinedTitle, privacy: .public) \(message, privacy: .public)")
|
||||
}
|
||||
case .error:
|
||||
if combinedTitle.isEmpty {
|
||||
logger.error("\(message, privacy: .public)")
|
||||
} else {
|
||||
logger.error("\(combinedTitle, privacy: .public) \(message, privacy: .public)")
|
||||
}
|
||||
case .fault:
|
||||
if combinedTitle.isEmpty {
|
||||
logger.fault("\(message, privacy: .public)")
|
||||
} else {
|
||||
logger.fault("\(combinedTitle, privacy: .public) \(message, privacy: .public)")
|
||||
}
|
||||
default:
|
||||
if combinedTitle.isEmpty {
|
||||
logger.log("\(message, privacy: .public)")
|
||||
} else {
|
||||
logger.log("\(combinedTitle, privacy: .public) \(message, privacy: .public)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func wg_log(_ type: OSLogType, title: String = "", staticMessage: StaticString) {
|
||||
neLog(type, title: "WG: \(title)", message: "\(staticMessage)")
|
||||
let stringMessage = String(describing: staticMessage)
|
||||
logToSystem(wireGuardSystemLogger, type: type, prefix: "WG", title: title, message: stringMessage)
|
||||
neLog(type, title: "WG: \(title)", message: stringMessage)
|
||||
}
|
||||
|
||||
public func wg_log(_ type: OSLogType, title: String = "", message: String) {
|
||||
logToSystem(wireGuardSystemLogger, type: type, prefix: "WG", title: title, message: message)
|
||||
neLog(type, title: "WG: \(title)", message: message)
|
||||
}
|
||||
|
||||
public func ovpnLog(_ type: OSLogType, title: String = "", message: String) {
|
||||
logToSystem(openVPNSystemLogger, type: type, prefix: "OVPN", title: title, message: message)
|
||||
neLog(type, title: "OVPN: \(title)", message: message)
|
||||
}
|
||||
|
||||
public func xrayLog(_ type: OSLogType, title: String = "", message: String) {
|
||||
logToSystem(xraySystemLogger, type: type, prefix: "XRAY", title: title, message: message)
|
||||
neLog(type, title: "XRAY: \(title)", message: message)
|
||||
}
|
||||
|
||||
public func neLog(_ type: OSLogType, title: String = "", message: String) {
|
||||
logToSystem(networkExtensionLogger, type: type, prefix: "NE", title: title, message: message)
|
||||
Log.log(type, title: "NE: \(title)", message: message)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import Foundation
|
||||
import NetworkExtension
|
||||
import OpenVPNAdapter
|
||||
import CryptoKit
|
||||
|
||||
struct OpenVPNConfig: Decodable {
|
||||
let config: String
|
||||
@@ -27,26 +28,83 @@ extension PacketTunnelProvider {
|
||||
let ovpnConfiguration = Data(openVPNConfig.config.utf8)
|
||||
setupAndlaunchOpenVPN(withConfig: ovpnConfiguration, completionHandler: completionHandler)
|
||||
} catch {
|
||||
ovpnLog(.error, message: "Can't parse config: \(error.localizedDescription)")
|
||||
|
||||
if let underlyingError = (error as NSError).userInfo[NSUnderlyingErrorKey] as? NSError {
|
||||
ovpnLog(.error, message: "Can't parse config: \(underlyingError.localizedDescription)")
|
||||
}
|
||||
|
||||
ovpnLog(.error, message: "Can't parse OpenVPN config: \(error.localizedDescription)")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
private func logOpenVPNError(_ error: NSError) {
|
||||
let fatalFlag = (error.userInfo[OpenVPNAdapterErrorFatalKey] as? Bool) ?? false
|
||||
var lines: [String] = []
|
||||
lines.append("domain=\(error.domain) code=\(error.code) fatal=\(fatalFlag)")
|
||||
|
||||
if let adapterMessage = error.userInfo[OpenVPNAdapterErrorMessageKey] as? String, !adapterMessage.isEmpty {
|
||||
lines.append("message=\(adapterMessage)")
|
||||
}
|
||||
|
||||
let userInfoKeys = error.userInfo.keys.map { String(describing: $0) }.sorted()
|
||||
if !userInfoKeys.isEmpty {
|
||||
lines.append("userInfoKeys=[\(userInfoKeys.joined(separator: ","))]")
|
||||
}
|
||||
|
||||
if let underlying = error.userInfo[NSUnderlyingErrorKey] as? NSError {
|
||||
lines.append("underlying=\(underlying.domain)#\(underlying.code) fatal=\((underlying.userInfo[OpenVPNAdapterErrorFatalKey] as? Bool) ?? false)")
|
||||
if let underlyingMessage = underlying.userInfo[OpenVPNAdapterErrorMessageKey] as? String, !underlyingMessage.isEmpty {
|
||||
lines.append("underlyingMessage=\(underlyingMessage)")
|
||||
} else if !underlying.localizedDescription.isEmpty {
|
||||
lines.append("underlyingLocalized=\(underlying.localizedDescription)")
|
||||
}
|
||||
} else if let underlying = error.userInfo[NSUnderlyingErrorKey] {
|
||||
lines.append("underlyingRaw=\(underlying)")
|
||||
}
|
||||
|
||||
let formatted = lines.joined(separator: "\n ")
|
||||
ovpnLog(.error, title: "Error", message: formatted)
|
||||
}
|
||||
|
||||
private func setupAndlaunchOpenVPN(withConfig ovpnConfiguration: Data,
|
||||
withShadowSocks viaSS: Bool = false,
|
||||
completionHandler: @escaping (Error?) -> Void) {
|
||||
ovpnLog(.info, message: "Setup and launch")
|
||||
|
||||
let str = String(decoding: ovpnConfiguration, as: UTF8.self)
|
||||
var configString = String(decoding: ovpnConfiguration, as: UTF8.self)
|
||||
|
||||
let digest = SHA256.hash(data: ovpnConfiguration)
|
||||
let digestString = digest.map { String(format: "%02x", $0) }.joined()
|
||||
ovpnLog(.info, title: "ConfigDigest", message: digestString)
|
||||
|
||||
let hasTlsAuthOpen = configString.contains("<tls-auth>")
|
||||
let hasTlsAuthClose = configString.contains("</tls-auth>")
|
||||
ovpnLog(.info, title: "ConfigFlags", message: "tls-auth open=\(hasTlsAuthOpen) close=\(hasTlsAuthClose)")
|
||||
|
||||
let lines = configString.split(separator: "\n")
|
||||
let head = lines.prefix(10).joined(separator: "\n")
|
||||
let tail = lines.suffix(10).joined(separator: "\n")
|
||||
ovpnLog(.debug, title: "ConfigHead", message: head)
|
||||
ovpnLog(.debug, title: "ConfigTail", message: tail)
|
||||
|
||||
if let start = configString.range(of: "<tls-auth>"),
|
||||
let end = configString.range(of: "</tls-auth>", range: start.upperBound..<configString.endIndex) {
|
||||
let keyBody = String(configString[start.upperBound..<end.lowerBound])
|
||||
ovpnLog(.debug, title: "TLSAuthInline", message: keyBody)
|
||||
let sanitizedLines = keyBody
|
||||
.split(whereSeparator: { $0.isNewline })
|
||||
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
|
||||
.filter { !$0.isEmpty }
|
||||
.filter { !$0.hasPrefix("#") }
|
||||
|
||||
let sanitizedKey = sanitizedLines.joined(separator: "\n")
|
||||
ovpnLog(.debug, title: "TLSAuthSanitized", message: sanitizedKey)
|
||||
let sanitizedBlock = "<tls-auth>\n\(sanitizedKey)\n</tls-auth>"
|
||||
configString.replaceSubrange(start.lowerBound..<end.upperBound, with: sanitizedBlock)
|
||||
}
|
||||
|
||||
let normalizedConfig = configString.replacingOccurrences(of: "\r\n", with: "\n")
|
||||
let sanitizedData = Data(normalizedConfig.utf8)
|
||||
|
||||
let configuration = OpenVPNConfiguration()
|
||||
configuration.fileContent = ovpnConfiguration
|
||||
if str.contains("cloak") {
|
||||
configuration.fileContent = sanitizedData
|
||||
if configString.contains("cloak") {
|
||||
configuration.setPTCloak()
|
||||
}
|
||||
|
||||
@@ -57,6 +115,8 @@ extension PacketTunnelProvider {
|
||||
evaluation = try ovpnAdapter?.apply(configuration: configuration)
|
||||
|
||||
} catch {
|
||||
let nsError = error as NSError
|
||||
ovpnLog(.error, title: "ApplyConfig", message: "domain=\(nsError.domain) code=\(nsError.code) info=\(nsError.userInfo)")
|
||||
completionHandler(error)
|
||||
return
|
||||
}
|
||||
@@ -208,8 +268,11 @@ extension PacketTunnelProvider: OpenVPNAdapterDelegate {
|
||||
|
||||
// Handle errors thrown by the OpenVPN library
|
||||
func openVPNAdapter(_ openVPNAdapter: OpenVPNAdapter, handleError error: Error) {
|
||||
let nsError = error as NSError
|
||||
logOpenVPNError(nsError)
|
||||
|
||||
// Handle only fatal errors
|
||||
guard let fatal = (error as NSError).userInfo[OpenVPNAdapterErrorFatalKey] as? Bool,
|
||||
guard let fatal = nsError.userInfo[OpenVPNAdapterErrorFatalKey] as? Bool,
|
||||
fatal == true else { return }
|
||||
|
||||
if vpnReachability.isTracking {
|
||||
|
||||
Reference in New Issue
Block a user