allow source IP binding

This commit is contained in:
Çağrı 2023-10-15 20:08:13 +00:00 committed by GitHub
parent 785b646713
commit 28b0b08cf8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -9,12 +9,23 @@
#include <arpa/inet.h> #include <arpa/inet.h>
#include <stdbool.h> #include <stdbool.h>
#include <stdint.h> #include <stdint.h>
#include <unistd.h>
//#define DEBUG //#define DEBUG
//compile with gcc -nostartfiles -fpic -shared bindToInterface.c -o bindToInterface.so -ldl -D_GNU_SOURCE //compile with gcc -nostartfiles -fpic -shared bindToInterface.c -o bindToInterface.so -ldl -D_GNU_SOURCE
//Use with BIND_INTERFACE=<network interface> LD_PRELOAD=./bindInterface.so <your program> like curl ifconfig.me //Use with BIND_INTERFACE=<network interface> LD_PRELOAD=./bindInterface.so <your program> like curl ifconfig.me
int bind_to_source_ip(int sockfd, const char *source_ip)
{
struct sockaddr_in source_addr;
memset(&source_addr, 0, sizeof(source_addr));
source_addr.sin_family = AF_INET;
source_addr.sin_addr.s_addr = inet_addr(source_ip);
return bind(sockfd, (struct sockaddr *)&source_addr, sizeof(source_addr));
}
int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
{ {
int *(*original_connect)(int, const struct sockaddr *, socklen_t); int *(*original_connect)(int, const struct sockaddr *, socklen_t);
@ -80,6 +91,8 @@ int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
{ {
char *bind_addr_env; char *bind_addr_env;
bind_addr_env = getenv("BIND_INTERFACE"); bind_addr_env = getenv("BIND_INTERFACE");
char *source_ip_env;
source_ip_env = getenv("BIND_SOURCE_IP");
struct ifreq interface; struct ifreq interface;
int errorCode; int errorCode;
@ -118,8 +131,15 @@ int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
}; };
} }
} }
else
{ if(source_ip_env != NULL && strlen(source_ip_env) > 0){
if (bind_to_source_ip(sockfd, source_ip_env) < 0){
perror("bind_to_source_ip failed");
return -1;
}
}
if(!(source_ip_env != NULL && strlen(source_ip_env) > 0) && !(bind_addr_env != NULL && strlen(bind_addr_env) > 0)){
printf("Warning: Programm with LD_PRELOAD startet, but BIND_INTERFACE environment variable not set\n"); printf("Warning: Programm with LD_PRELOAD startet, but BIND_INTERFACE environment variable not set\n");
fprintf(stderr, "Warning: Programm with LD_PRELOAD startet, but BIND_INTERFACE environment variable not set\n"); fprintf(stderr, "Warning: Programm with LD_PRELOAD startet, but BIND_INTERFACE environment variable not set\n");
} }