AeroToss v1.0.0: аудит безопасности, багфиксы, подпись APK
Безопасность: - Сервер bind на loopback (127.0.0.1) вместо 0.0.0.0 - Лимит соединений: Semaphore(10) для защиты от DoS - Валидация fileSize: max 10 ГБ, reject при превышении - Валидация пути файла: canonicalPath must startWith downloadsDir - FileUtils.resolveUniqueFile: max counter 1000 - FileUtils.deleteIfExists: исправлен TOCTOU race - Скрытие путей в ошибках (не泄漏 internal paths) - Трансфер-история ограничена 50 записями - Таймаут сокета увеличен до 60 сек - compareAndSet для защиты от double-bind - require(file.exists()) в sendFile Сборка: - Android: APK подписан debug keystore (self-signed) - Android: конвертирован из library в application - macOS: AeroToss.app (113 МБ) + JAR (28 МБ) - LICENSE: GPLv3 Тесты: все 71+ проходят
This commit is contained in:
@@ -11,11 +11,13 @@ import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.flow.*
|
||||
import kotlinx.serialization.json.Json
|
||||
import java.io.*
|
||||
import java.net.InetAddress
|
||||
import java.net.ServerSocket
|
||||
import java.net.Socket
|
||||
import java.security.MessageDigest
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.Semaphore
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
@@ -36,6 +38,7 @@ class AndroidFileTransferManager(private val context: Context) : TransferManager
|
||||
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
private val activeJobs = ConcurrentHashMap<String, Job>()
|
||||
private val running = AtomicBoolean(false)
|
||||
private val connectionLimiter = Semaphore(10)
|
||||
|
||||
private val downloadsDir: File = run {
|
||||
val dir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
|
||||
@@ -46,12 +49,11 @@ class AndroidFileTransferManager(private val context: Context) : TransferManager
|
||||
override fun getServerPort(): Int = serverSocket?.localPort ?: 0
|
||||
|
||||
fun startServer(port: Int = 0): Int {
|
||||
if (running.get()) return serverSocket?.localPort ?: 0
|
||||
if (!running.compareAndSet(false, true)) return serverSocket?.localPort ?: 0
|
||||
|
||||
try {
|
||||
val socket = ServerSocket(port)
|
||||
val socket = ServerSocket(port, 50, InetAddress.getLoopbackAddress())
|
||||
serverSocket = socket
|
||||
running.set(true)
|
||||
|
||||
serverThread = Thread {
|
||||
while (running.get() && !socket.isClosed) {
|
||||
@@ -76,20 +78,33 @@ class AndroidFileTransferManager(private val context: Context) : TransferManager
|
||||
}
|
||||
|
||||
private suspend fun handleIncomingConnection(socket: Socket) {
|
||||
if (!connectionLimiter.tryAcquire()) {
|
||||
try { socket.close() } catch (_: Exception) {}
|
||||
return
|
||||
}
|
||||
withContext(Dispatchers.IO) {
|
||||
val progressId = UUID.randomUUID().toString()
|
||||
var actualFile: File? = null
|
||||
var requestFileName: String = ""
|
||||
try {
|
||||
socket.use { sock ->
|
||||
sock.soTimeout = 30_000
|
||||
sock.soTimeout = 60_000
|
||||
val input = DataInputStream(sock.getInputStream())
|
||||
val output = DataOutputStream(sock.getOutputStream())
|
||||
|
||||
val requestJson = input.readUTF()
|
||||
val request = Json.decodeFromString<TransferRequest>(requestJson)
|
||||
val request = try {
|
||||
Json.decodeFromString<TransferRequest>(requestJson)
|
||||
} catch (_: Exception) {
|
||||
return@withContext
|
||||
}
|
||||
requestFileName = request.fileName
|
||||
|
||||
if (request.fileSize <= 0 || request.fileSize > FileUtils.MAX_FILE_SIZE) {
|
||||
output.writeBoolean(false)
|
||||
return@withContext
|
||||
}
|
||||
|
||||
val progress = TransferProgress(
|
||||
id = progressId,
|
||||
request = request,
|
||||
@@ -108,6 +123,10 @@ class AndroidFileTransferManager(private val context: Context) : TransferManager
|
||||
}
|
||||
|
||||
val file = FileUtils.resolveUniqueFile(downloadsDir, request.fileName)
|
||||
if (!FileUtils.validateFilePath(file, downloadsDir)) {
|
||||
output.writeBoolean(false)
|
||||
return@withContext
|
||||
}
|
||||
actualFile = file
|
||||
val sha256 = MessageDigest.getInstance("SHA-256")
|
||||
var bytesWritten = 0L
|
||||
@@ -159,8 +178,7 @@ class AndroidFileTransferManager(private val context: Context) : TransferManager
|
||||
))
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
} catch (_: Exception) {
|
||||
actualFile?.let { FileUtils.deleteIfExists(it) }
|
||||
val current = _incomingTransfers.value.find { it.id == progressId }
|
||||
if (current != null && current.state != TransferState.COMPLETED &&
|
||||
@@ -168,14 +186,19 @@ class AndroidFileTransferManager(private val context: Context) : TransferManager
|
||||
) {
|
||||
updateIncomingById(progressId, current.copy(
|
||||
state = TransferState.FAILED,
|
||||
error = e.message ?: "Unknown error"
|
||||
error = "Transfer failed"
|
||||
))
|
||||
}
|
||||
} finally {
|
||||
connectionLimiter.release()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun sendFile(file: File, targetHost: String, targetPort: Int): Flow<TransferProgress> {
|
||||
require(file.exists() && file.isFile) { "File does not exist or is not a regular file" }
|
||||
require(file.length() <= FileUtils.MAX_FILE_SIZE) { "File exceeds maximum size" }
|
||||
|
||||
val requestId = UUID.randomUUID().toString()
|
||||
val request = TransferRequest(
|
||||
fileName = file.name,
|
||||
@@ -260,11 +283,10 @@ class AndroidFileTransferManager(private val context: Context) : TransferManager
|
||||
))
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
} catch (_: Exception) {
|
||||
updateOutgoingById(requestId, initialProgress.copy(
|
||||
state = TransferState.FAILED,
|
||||
error = e.message ?: "Unknown error"
|
||||
error = "Transfer failed"
|
||||
))
|
||||
} finally {
|
||||
activeJobs.remove(requestId)
|
||||
@@ -294,19 +316,19 @@ class AndroidFileTransferManager(private val context: Context) : TransferManager
|
||||
|
||||
private fun updateIncoming(progress: TransferProgress) {
|
||||
_incomingTransfers.update { list ->
|
||||
list.filter { it.id != progress.id }.plus(progress)
|
||||
list.filter { it.id != progress.id }.plus(progress).takeLast(50)
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateIncomingById(id: String, progress: TransferProgress) {
|
||||
_incomingTransfers.update { list ->
|
||||
list.filter { it.id != id }.plus(progress)
|
||||
list.filter { it.id != id }.plus(progress).takeLast(50)
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateOutgoing(progress: TransferProgress) {
|
||||
_outgoingTransfers.update { list ->
|
||||
list.filter { it.id != progress.id }.plus(progress)
|
||||
list.filter { it.id != progress.id }.plus(progress).takeLast(50)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user