server: check interface names in RPC arguments for validity

This patch introduces a method isIfaceName that checks interface
names from various RPCs for validity before e.g. using them as
part of iptables arguments or in filenames.

All of these RPC calls can only be called from applications
with at least the CONNECTIVITY_INTERNAL permission in recent
Android versions, so the impact of the missing checks luckily
isn't very high.

Orig-Author: Jann Horn <jann@thejh.net>

Change-Id: I80df8d745a3de99ad02d6649f0d10562c81f6b98
Signed-off-by: JP Abgrall <jpa@google.com>
diff --git a/server/NetdConstants.cpp b/server/NetdConstants.cpp
index c3c16eb..ea31410 100644
--- a/server/NetdConstants.cpp
+++ b/server/NetdConstants.cpp
@@ -17,6 +17,8 @@
 #include <fcntl.h>
 #include <string.h>
 #include <sys/wait.h>
+#include <ctype.h>
+#include <net/if.h>
 
 #define LOG_TAG "Netd"
 
@@ -143,3 +145,28 @@
     close(fd);
     return 0;
 }
+
+/*
+ * Check an interface name for plausibility. This should e.g. help against
+ * directory traversal.
+ */
+bool isIfaceName(const char *name) {
+    size_t i;
+    size_t name_len = strlen(name);
+    if ((name_len == 0) || (name_len > IFNAMSIZ)) {
+        return false;
+    }
+
+    /* First character must be alphanumeric */
+    if (!isalnum(name[0])) {
+        return false;
+    }
+
+    for (i = 1; i < name_len; i++) {
+        if (!isalnum(name[i]) && (name[i] != '_') && (name[i] != '-') && (name[i] != ':')) {
+            return false;
+        }
+    }
+
+    return true;
+}