Skip to content

Instantly share code, notes, and snippets.

@burke
Created September 13, 2021 18:41
Show Gist options
  • Save burke/1c32689b9bf173d310b0d81c47f7d513 to your computer and use it in GitHub Desktop.
Save burke/1c32689b9bf173d310b0d81c47f7d513 to your computer and use it in GitHub Desktop.

First, compile the shim:

gcc -Wall -O2 -fpic -shared -ldl bind.c -o bind.so

Now, run the demo and notice that it does what it looks like it does:

$ LD_PRELOAD=./bind.so ruby demo.rb
#<TCPServer:fd 5, AF_INET, 0.0.0.0, 8888>

Then, set ISOSPIN_NAMESPACE_IP and try again:

export ISOSPIN_NAMESPACE_IP=127.0.0.1
$ LD_PRELOAD=./bind.so ruby demo.rb
#<TCPServer:fd 5, AF_INET, 127.0.0.1, 8888>
// For RTLD_NEXT
#define _GNU_SOURCE
#include <stdio.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define ENVVARNAME "ISOSPIN_NAMESPACE_IP"
static int (*real_bind)(int sockfd, const struct sockaddr *addr, socklen_t addrlen) = NULL;
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {
char * target_ip = getenv(ENVVARNAME);
if (target_ip == NULL) {
return real_bind(sockfd, addr, addrlen);
}
if (addr->sa_family != AF_INET) {
return real_bind(sockfd, addr, addrlen);
}
char *ip = inet_ntoa(((struct sockaddr_in*)addr)->sin_addr);
if (strcmp(ip, "0.0.0.0") != 0) {
return real_bind(sockfd, addr, addrlen);
}
struct sockaddr shadowed_addr;
shadowed_addr.sa_family = addr->sa_family;
if (inet_aton(target_ip, &((struct sockaddr_in*)&shadowed_addr)->sin_addr) == 0) {
printf("failed to shadow INADDR_ANY bind: address invalid\n");
exit(255);
}
return real_bind(sockfd, &shadowed_addr, addrlen);
}
void __attribute__((constructor)) initialize(void) {
real_bind = dlsym(RTLD_NEXT, "bind");
if (real_bind == NULL) {
printf("dynamic linker failed to find bind(2)\n");
exit(255);
}
}
require('socket')
s = TCPServer.new('0.0.0.0', 8888)
puts s.inspect
s.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment