总贴 在这里。
网络隔离,透明代理
透明代理我之前有写过,博客在这里
原理是类似的,过程也是类似的,不过不是用iptable
,是用的 ip netns
不是用redsock,而是强哥自己写的一个socks5 proxy。是这样做的:
- 修改启动脚本,在开机的时候配置基本的网络
- 在zygote中为每个App设置独立的网络
- 在新的实例创建起来的时候,调用sh脚本,动态创建网络
细节代码是这样的,开机脚本在这里device/generic/common/init.sh
function init_xd_netns()
{
tmpfs_dir="/var/run/netns"
mkdir -m 777 -p $tmpfs_dir && chmod 0777 /var/run && mount -t tmpfs -o size=10M,mode=0777 tmpfs $tmpfs_dir
}
zygote中是这样设置的(也是在fork之后,在前一篇博客中mount文件系统的同一个地方)
/* Lionfore for ML: change to my own network world. Oct 25th, 2017 */
static void __enter_my_network_world (JNIEnv *env, int android_flags, int inst_no)
{
/* Lionfore for ML: mounting the intercepted dirs and files. Sep 14th, 2017 */
if (android_flags_is_user_app (android_flags)) {
char ns_node_path [32];
sprintf (ns_node_path, "/var/run/netns/.%d", inst_no);
if (__check_netns_node (ns_node_path) < 0) {
if (__notify_xd_daemon_app_to_be_started (inst_no, getpid ()) < 0) {
ALOGE ("Zg: Failed to talk to XD daemon for netns for process inst %d: error: %d, aborted!", inst_no, errno);
RuntimeAbort (env);
}
}
while (__check_netns_node (ns_node_path) < 0)
usleep (2000); /* Sleep 2ms */
if (unshare (CLONE_NEWNET) < 0) {
ALOGW ("Zg: Failed to unshare (NET) for process inst %d: error: %d, aborted!", inst_no, errno);
RuntimeAbort (env);
}
int fd = open (ns_node_path, O_RDONLY);
if (fd < 0) {
ALOGE ("Zg: Could not open netns node for process inst %d: error: %d, aborted!", inst_no, errno);
RuntimeAbort (env);
}
if (setns (fd, CLONE_NEWNET) < 0) {
ALOGE ("Zg: Could not change netns for process inst %d: error: %d, aborted!", inst_no, errno);
close (fd);
RuntimeAbort (env);
}
close (fd);
/* Lionfore for ML: We need to mount a version of /sys that describes the network namespace. Oct 26th, 2017 */
if (umount2 ("/sys", MNT_DETACH) < 0) {
ALOGW ("umount of /sys failed: %d\n", errno);
RuntimeAbort (env);
}
/* Lionfore for ML. Oct 26th, 2017 */
if (mount ("sys", "/sys", "sysfs", 0, NULL) < 0) {
ALOGW ("mount of /sys failed: %d\n", errno);
RuntimeAbort (env);
}
/* Lionfore for ML. Oct 26th, 2017 */
__mount_sys_subdirs (env);
}
}
#endif
配置网络的脚本大概是这样的
ip netns …
ps:这部分我参与得不深,所以只能描述下大概又大概的思路