3

How to override connect() system call called from within PHP script, in an Apache request, when PHP is enabled via mod_php?

I have my custom connect() version defined in custom-connect.c:

#define _GNU_SOURCE 1
#include <stdio.h>
#include <arpa/inet.h>
#include <dlfcn.h>

int (*real_connect)(int, const struct sockaddr *, socklen_t);
FILE *f;

void _init (void) {
    const char *err;

    f = fopen("/tmp/connect.log", "a");

    real_connect = dlsym (RTLD_NEXT, "connect");
    if ((err = dlerror()) != NULL) {
        fprintf (f, "dlsym (connect): %s\n", err);
    }
}

int connect(int fd, const struct sockaddr *sk, socklen_t sl) {
    static struct sockaddr_in *sk_in;
    sk_in = (struct sockaddr_in *)sk;

    fprintf(f, "Custom connect: %d %s:%d\n", fd, inet_ntoa(sk_in->sin_addr), ntohs(sk_in->sin_port));

    return real_connect(fd, sk, sl);
}

I compile it with:

gcc -nostartfiles -fpic -shared custom-connect.c -o custom-connect.so -ldl

I have a simple script curl-test.php, that internally makes calls to the connect():

<?php
$ch = curl_init("http://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
echo 'Received length: ' . strlen($data) . "\n";

When I run my script with LD_PRELOAD from command line:

LD_PRELOAD=./custom-connect.so php curl-test.php

Then it looks fine, i can see that my custom connect() logged something to /tmp/connect.log:

Custom connect: 4 192.168.178.1:53
Custom connect: 4 93.184.216.34:80

It looks like it works fine from the command line. But how can I override connect() with my own version, when I run my script from Apache with PHP enabled via mod_php? Should I also use LD_PRELOAD? If yes, then how to configure it?

Luke 10X
  • 1,071
  • 2
  • 14
  • 30

0 Answers0