Colota - Android GPS Location tracker
fix(network): improve endpoint validation and private IP handling
Max Dietrich86b2e5d284c0
diff --git a/android/app/src/main/java/com/locata/LocationsUtils.kt b/android/app/src/main/java/com/locata/LocationsUtils.ktindex 128dcab0..1ea6e107 100644--- a/android/app/src/main/java/com/locata/LocationsUtils.kt+++ b/android/app/src/main/java/com/locata/LocationsUtils.kt@@ -68,53 +68,53 @@ class LocationUtils(private val context: Context) {/*** Executes an asynchronous POST request to the server.- * Handles both HTTP (for localhost) and HTTPS connections.+ * Handles HTTP only for private IPs/localhost, HTTPS otherwise.*/suspend fun sendToEndpoint(- payload: JSONObject,+ payload: JSONObject,endpoint: String): Boolean = withContext(Dispatchers.IO) {- Log.d(TAG, "Reached sendToEndpoint")- // Validate endpoint+if (endpoint.isBlank()) {- Log.w(TAG, "Empty endpoint provided")+ // Endpoint empty, nothing to do+ if (BuildConfig.DEBUG) Log.d(TAG, "Empty endpoint provided")return@withContext false}-- // Determine if localhost/local network- val isLocalhost = endpoint.contains("localhost") ||- endpoint.contains("127.0.0.1") ||- endpoint.contains("192.168.") ||- endpoint.contains("10.0.")-- // Single validation check- val isValid = when {- endpoint.startsWith("https://", ignoreCase = true) -> true- endpoint.startsWith("http://", ignoreCase = true) && isLocalhost -> true- endpoint.startsWith("http://", ignoreCase = true) -> {- Log.e(TAG, "Insecure endpoint blocked: $endpoint (use HTTPS for non-localhost)")- false- }- else -> {- Log.e(TAG, "Invalid protocol: $endpoint (must start with http:// or https://)")- false- }++ // Parse URL safely+ val url = try {+ URL(endpoint)+ } catch (e: Exception) {+ Log.e(TAG, "Invalid URL: $endpoint")+ return@withContext false}-- if (!isValid) return@withContext false-++ val protocol = url.protocol.lowercase()+ val host = url.host ?: return@withContext false++ // Only allow http or https+ if (protocol != "http" && protocol != "https") {+ Log.e(TAG, "Invalid protocol: $endpoint")+ return@withContext false+ }++ // HTTP only allowed for private IPs / localhost+ if (protocol == "http" && !isPrivateHost(host)) {+ Log.e(TAG, "HTTP blocked for non-private host: $endpoint")+ return@withContext false+ }+// Check network availabilityif (!isNetworkAvailable()) {- Log.d(TAG, "Sync skipped: No internet")+ if (BuildConfig.DEBUG) Log.d(TAG, "Sync skipped: No internet")return@withContext false}-+var connection: java.net.HttpURLConnection? = null-+try {- val url = URL(endpoint)connection = url.openConnection() as java.net.HttpURLConnection-+connection.apply {requestMethod = "POST"setRequestProperty("Content-Type", "application/json; charset=UTF-8")@@ -124,34 +124,28 @@ class LocationUtils(private val context: Context) {readTimeout = READ_TIMEOUTuseCaches = false}-- // Write payload++ // Write payload to output streamval bodyBytes = payload.toString().toByteArray(Charsets.UTF_8)connection.setFixedLengthStreamingMode(bodyBytes.size)-- connection.outputStream.use { outputStream ->- outputStream.write(bodyBytes)- }-- // Read response++ connection.outputStream.use { it.write(bodyBytes) }+val responseCode = connection.responseCode-- if (responseCode in 200..299) {- if (BuildConfig.DEBUG) {- Log.d(TAG, "Location successfully sent")- }++ return@withContext if (responseCode in 200..299) {+ if (BuildConfig.DEBUG) Log.d(TAG, "Location successfully sent")true} else {- // Read error body for debuggingval errorBody = try {connection.errorStream?.bufferedReader()?.use { it.readText() } ?: "No error body"- } catch (e: Exception) {+ } catch (_: Exception) {"Could not read error body"}-Log.e(TAG, "POST failed: $responseCode - $errorBody")false}+} catch (e: Exception) {Log.e(TAG, "Network error: ${e.message}", e)false@@ -160,6 +154,34 @@ class LocationUtils(private val context: Context) {}}++ /**+ * Checks if the given host is private or local.+ * Returns true for:+ * - "localhost"+ * - Loopback addresses (127.x.x.x, ::1)+ * - Site-local addresses (RFC1918)+ * - Any local/unspecified addresses (0.0.0.0, ::)+ */+ private fun isPrivateHost(host: String): Boolean {+ if (host == "localhost") return true // explicit localhost check++ return try {+ val address = java.net.InetAddress.getByName(host)++ // isAnyLocalAddress: 0.0.0.0 / ::0+ // isLoopbackAddress: 127.x.x.x / ::1+ // isSiteLocalAddress: 10.x.x.x, 172.16-31.x.x, 192.168.x.x+ address.isAnyLocalAddress ||+ address.isLoopbackAddress ||+ address.isSiteLocalAddress+ } catch (e: Exception) {+ // Could not resolve host; treat as non-private+ if (BuildConfig.DEBUG) Log.d(TAG, "Host resolution failed for $host: ${e.message}")+ false+ }+ }+/*** Checks for an active, validated internet connection.* Cached to avoid excessive system calls.diff --git a/src/screens/SettingsScreen.tsx b/src/screens/SettingsScreen.tsxindex 17fc9c05..0dd6f4d1 100644--- a/src/screens/SettingsScreen.tsx+++ b/src/screens/SettingsScreen.tsx@@ -38,6 +38,39 @@ import { StatsCard, PresetOption, NumericInput } from "../components";const AUTOSAVE_DEBOUNCE_MS = 1500;+function isPrivateHost(url: string) {+ try {+ // Strip protocol+ const stripped = url.replace(/^https?:\/\//, "").split(/[/?#]/)[0];+ // Extract host (before any port)+ const host = stripped.split(":")[0];++ // Validate host: must be valid IP or hostname+ const ipRegex =+ /^(127\.0\.0\.1|10\.(\d{1,3}\.){2}\d{1,3}|192\.168\.(\d{1,3}\.)\d{1,3}|172\.(1[6-9]|2\d|3[0-1])\.(\d{1,3}\.)\d{1,3})$/;+ const hostnameRegex = /^localhost$/;++ return ipRegex.test(host) || hostnameRegex.test(host);+ } catch {+ return false;+ }+}++function isEndpointAllowed(url: string) {+ if (!url) return false;++ const match = url.match(/^(https?):\/\/([^\/:]+)(:\d+)?/);+ if (!match) return false;++ const protocol = match[1]; // http or https+ const host = match[2];++ if (protocol === "https") return true;+ if (protocol === "http" && isPrivateHost(host)) return true;++ return false;+}+/*** Settings screen for configuring location tracking.* Features auto-save, presets, and advanced customization.@@ -372,11 +405,12 @@ export function SettingsScreen({ navigation }: ScreenProps) {>{endpointInput.startsWith("https://")? "HTTPS"- : "⚠️ HTTP"}+ : "HTTP"}</Text></View>)}</View>+<TextInputstyle={[styles.input,@@ -394,6 +428,16 @@ export function SettingsScreen({ navigation }: ScreenProps) {autoCorrect={false}keyboardType="url"/>++ {/* Inline warning for non-private HTTP */}+ {endpointInput.startsWith("http://") &&+ !isPrivateHost(endpointInput) && (+ <Text+ style={[styles.httpWarning, { color: colors.warning }]}+ >+ HTTP only allowed for private IPs / localhost+ </Text>+ )}</View>{/* Test button with improved styling */}@@ -401,10 +445,14 @@ export function SettingsScreen({ navigation }: ScreenProps) {style={[styles.testButton,{ backgroundColor: colors.primary },- !endpointInput && styles.disabledButton,+ (!endpointInput || !isEndpointAllowed(endpointInput)) &&+ styles.disabledButton,]}- onPress={handleTestEndpoint}- disabled={!endpointInput || testing}+ onPress={() => {+ if (!endpointInput || !isEndpointAllowed(endpointInput))+ return; // prevent action+ handleTestEndpoint();+ }}title={testing ? "Testing..." : "Test Connection"}color="#f8f7f7"/>@@ -1090,4 +1138,9 @@ const styles = StyleSheet.create({fontWeight: "300",marginLeft: 12,},+ httpWarning: {+ marginTop: 6,+ fontSize: 12,+ fontWeight: "500",+ },});