About

PinkTrace is a ptrace() wrapper library.

C99 library which is a lightweight wrapper for ptrace hiding away architectural details.

Description

Using PinkTrace, it is easily possible to read/change system calls or system call arguments. This means you can deny a specific system call from executing altogether or only if a system call argument matches a certain value. You can also change the system call to execute a different system call or change the arguments of the system call so it takes a different integer or a different string as argument.

Background

The ptrace() system call provides a means by which one process (the “tracer”) may observe and control the execution of another process (the “tracee”), and examine and change the tracee’s memory and registers. It is primarily used to implement breakpoint debugging and system call tracing.

  • See ptrace manual page on more information regarding ptrace.
  • See strace which is a diagnostic, debugging and instructional userspace utility for Linux which also uses ptrace().
  • See gdb for the GNU Debugger which allows you to see what is going on inside another program while it executes using ptrace().

Installation Instructions

  • PinkTrace uses autotools. To build, simply do ./configure, make and sudo make install.
  • See Download to learn how to acquire PinkTrace sources.
  • See GIT to learn how to build PinkTrace using the GIT version.

Download

Building

This package is made with the GNU autotools, you should run ./configure inside the distribution directory for configuring the source tree. Some notable options you may pass to ./configure are:

  • –enable-doxygen Build API documentation using Doxygen
  • –enable-python Build Python bindings
  • –enable-python-doc Build API documentation of Python bindings using PyDoctor

After that you should run make for compilation and make install (as root) for installation of pinktrace. Optionally you may run make check to run the unit tests.

The source of this web site is also included in the distribution. To view them offline you should generate them using Hugo. After ./configure change directory to doc/ and run make site. The web site will be built under the public directory. You may then run make site-check and point your browser to http://localhost:1313/pinktrace` and view this web site offline.

Building from the Git repository

If you use a GIT version of PinkTrace source code, there will be some files missing that are needed to build PinkTrace. Some of these files are generated by tools from the GNU Autoconf and GNU Automake packages.

Note: rather than running autoreconf directly, please invoke ./autogen.sh script and follow the instructions given in INSTALL file for further building and installation.

Compiling C Code

You will need to specify various compiler flags when compiling C code. The usual way to do this is via pkg-config:

1
2
gcc -c $(pkg-config --cflags pinktrace) -o example.o example.c
gcc $(pkg-config --libs pinktrace) -o example example.o

Portability

PinkTrace runs on Linux only. Version 5.0.0 or later is recommended. Enabling the CONFIG_CROSS_MEMORY_ATTACH kernel option allows PinkTrace to make use of the process_vm_readv, and process_vm_writev system calls to transfer data to and from tracee’s address space which is much faster and more reliable than using ptrace to do the same.

Architectures

PinkTrace is supported on the following architectures:

YAMA

Note: Make sure you run PinkTrace on a system with ptrace() enabled. One of the most common ways to restrict ptrace() usage is Yama. Use the command sysctl kernel.yama.ptrace_scope to check if ptrace() usage is restricted. The sysctl settings (writable only with CAP_SYS_PTRACE) are:

0 - classic ptrace permissions: a process can PTRACE_ATTACH to any other process running under the same uid, as long as it is dumpable (i.e. did not transition uids, start privileged, or have called prctl(PR_SET_DUMPABLE...) already). Similarly, PTRACE_TRACEME is unchanged.

1 - restricted ptrace: a process must have a predefined relationship with the inferior it wants to call PTRACE_ATTACH on. By default, this relationship is that of only its descendants when the above classic criteria is also met. To change the relationship, an inferior can call prctl(PR_SET_PTRACER, debugger, ...) to declare an allowed debugger PID to call PTRACE_ATTACH on the inferior. Using **PTRACE_TRACEME is unchanged.

2 - admin-only attach: only processes with CAP_SYS_PTRACE may use ptrace with PTRACE_ATTACH, or through children calling PTRACE_TRACEME.

3 - no attach: no processes may use ptrace with PTRACE_ATTACH nor via PTRACE_TRACEME. Once set, this sysctl value cannot be changed.

Support

Hey you, out there beyond the wall,
Breaking bottles in the hall,
Can you help me?

You may use the PinkTrace GitHub page to submit issues or pull requests. Attaching poems encourages consideration tremendously.

Author

You may also contact the primary author Alï Polatel directly for any questions. Mail is preferred. Attaching poems encourages consideration tremendously.

Copying

PinkTrace is released under the terms of the GNU Lesser General Public License version 2.1 or later; see the file COPYING for details. PinkTrace Python bindings is released under the terms of the CNRI Python Open Source GPL Compatible License Agreement; see the file python/COPYING for details.

Examples

There are examples on how to use the various parts of the library.

C

pink-about.c

Raw: https://git.exherbo.org/pinktrace-1.git/plain/examples/pink-about.c

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * \example pink-about.c
 *
 * A simple example demonstrating how to use Pink's version macros.
 **/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <pinktrace/pink.h>

int
main(void)
{
	printf("Built using %s %d.%d.%d%s",
		PINKTRACE_PACKAGE,
		PINKTRACE_VERSION_MAJOR,
		PINKTRACE_VERSION_MINOR,
		PINKTRACE_VERSION_MICRO,
		PINKTRACE_VERSION_SUFFIX);

	if (strncmp(PINKTRACE_GIT_HEAD, "", 1))
		printf(" %s", PINKTRACE_GIT_HEAD);

	fputc('\n', stdout);

	return EXIT_SUCCESS;
}

pink-fork.c

Raw: https://git.exherbo.org/pinktrace-1.git/plain/examples/pink-fork.c

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
 * \example pink-fork-linux.c
 *
 * Example demonstrating how to fork and start tracing a process on Linux.
 **/

#include <assert.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

#include <pinktrace/pink.h>

int
main(void)
{
	int r, status;
	pid_t pid;
	enum pink_event event;

	/* Fork and start tracing. */
	if ((pid = fork()) < 0) {
		perror("fork");
		return EXIT_FAILURE;
	}
	else if (!pid) {
		/* Set up for tracing. */
		if ((r = pink_trace_me()) < 0) {
			fprintf(stderr, "pink_trace_me: %d %s\n",
				-r, strerror(-r));
			_exit(EXIT_FAILURE);
		}
		/* Stop, so that the parent has the chance to set up options
		 * for tracing. */
		kill(getpid(), SIGSTOP);

		/* Here's the point where you can do whatever the traced child
		 * should do. */
		printf("hello world\n");

		_exit(EXIT_SUCCESS);
	}
	else {
		waitpid(pid, &status, 0);
		event = pink_event_decide(status);
		assert(event == PINK_EVENT_NONE);

		/* Set up the child for tracing */
		if ((r = pink_trace_setup(pid, PINK_TRACE_OPTION_SYSGOOD)) < 0) {
			perror("pink_trace_setup");
			pink_trace_kill(pid, -1, SIGKILL);
			return EXIT_FAILURE;
		}

		/* The child is ready for tracing, nothing interesting in this
		 * example, let the child resume its execution. */
		pink_trace_resume(pid, 0);

		/* Wait for the child to exit. */
		waitpid(pid, &status, 0);

		return EXIT_SUCCESS;
	}
}

pink-simple-strace.c

Raw: https://git.exherbo.org/pinktrace-1.git/plain/examples/pink-simple-strace.c

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/**
 * \example pink-simple-strace-linux.c
 *
 * Simple strace like program example written with pinktrace for Linux.
 **/

#include <assert.h>
#include <err.h>
#include <errno.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#include <pinktrace/pink.h>

struct process {
	pid_t pid;
	short abi;
	bool insyscall;
	struct pink_regset *regs;
};

/* Utility functions */
static void
process_update(struct process *proc)
{
	int r;

	/*
	 * Update process registers and system call ABI indicator, ie
	 * "personality".
	 */
	if ((r = pink_regset_fill(proc->pid, proc->regs)) < 0 ||
	    (r = pink_read_abi(proc->pid, proc->regs, &proc->abi)) < 0)
	{
		errno = -r;
		perror("pink_regset_fill");
	}
}

static void
print_ret(struct process *proc)
{
	int r;
	long ret;
	int err;

	if ((r = pink_read_retval(proc->pid, proc->regs, &ret, &err)) < 0) {
		errno = -r;
		perror("pink_read_retval");
		return;
	}

	if (err)
		printf("= %d (%s)", -err, strerror(-err));
	else
		printf("= %ld", ret);
}

static void
print_open_flags(long flags)
{
	long aflags;
	bool found;

	found = true;

	/* Check out access flags */
	aflags = flags & 3;
	switch (aflags) {
	case O_RDONLY:
		printf("O_RDONLY");
		break;
	case O_WRONLY:
		printf("O_WRONLY");
		break;
	case O_RDWR:
		printf("O_RDWR");
		break;
	default:
		/* Nothing found */
		found = false;
	}

	if (flags & O_CREAT) {
		printf("%s | O_CREAT", found ? "" : "0");
		found = true;
	}

	if (!found)
		printf("%#x", (unsigned)flags);
}

/* A very basic decoder for open(2) system call. */
static void
decode_open(struct process *proc)
{
	int r;
	long addr, flags;
	char buf[PATH_MAX];

	if ((r = pink_read_argument(proc->pid, proc->regs, 0, &addr)) < 0) {
		errno = -r;
		perror("pink_read_argument");
		return;
	}
	if ((r = pink_read_string(proc->pid, proc->regs, addr, buf, PATH_MAX)) < 0) {
		errno = -r;
		perror("pink_read_string");
		return;
	}
	if (!pink_read_argument(proc->pid, proc->regs, 1, &flags)) {
		errno = -r;
		perror("pink_read_argument");
		return;
	}

	printf("open(\"%s\", ", buf);
	print_open_flags(flags);
	fputc(')', stdout);
}

/* A very basic decoder for execve(2) system call. */
static void
decode_execve(struct process *proc)
{
	bool nil;
	unsigned i;
	int r;
	long arg;
	char buf[PATH_MAX];
	const char *sep;

	if ((r = pink_read_argument(proc->pid, proc->regs, 0, &arg)) < 0) {
		errno = -r;
		perror("pink_read_argument");
		return;
	}
	if ((r = pink_read_string(proc->pid, proc->regs, 0, buf, PATH_MAX)) < 0) {
		errno = -r;
		perror("pink_read_string");
		return;
	}
	if ((r = pink_read_argument(proc->pid, proc->regs, 1, &arg)) < 0) {
		errno = -r;
		perror("pink_read_argument");
		return;
	}

	printf("execve(\"%s\", [", buf);

	for (i = 0, nil = false, sep = "";;sep = ", ") {
		if ((r = pink_read_string_array(proc->pid, proc->regs,
						arg, ++i,
						buf, PATH_MAX, &nil)) < 0)
		{
			errno = -r;
			perror("pink_read_string_array");
			return;
		}
		printf("%s", sep);
		fputc('"', stdout);
		printf("%s", buf);
		fputc('"', stdout);

		if (nil) {
			printf("], envp[])");
			break;
		}
	}
}

/* A very basic decoder for bind() and connect() calls */
static void
decode_socketcall(struct process *proc, const char *scname)
{
	int fd, r;
	long addr, subcall;
	const char *path, *subname;
	char ip[100];
	struct pink_sockaddr sockaddr;

	subcall = -1;
	if (!strcmp(scname, "socketcall") &&
	    (r = pink_read_socket_subcall(proc->pid, proc->regs, true, &subcall)) < 0)
	{
		errno = -r;
		perror("pink_read_socket_subcall");
		return;
	}

	switch (subcall) {
	case -1:
	case PINK_SOCKET_SUBCALL_BIND:
	case PINK_SOCKET_SUBCALL_CONNECT:
		break;
	default:
		subname = pink_name_socket_subcall(subcall);
		if (!(!strcmp(subname, "bind") || !strcmp(subname, "connect"))) {
			/* Print the name only */
			printf("%s()", subname);
		}
		return;
	}

	if ((r = pink_read_socket_address(proc->pid, proc->regs, false, 1,
					  &fd, &sockaddr)) < 0)
	{
		errno = -r;
		perror("pink_read_socket_address");
		return;
	}

	printf("%s(%d, ", (subcall > 0) ? subname : scname, fd);

	switch (sockaddr.family) {
	case -1: /* NULL */
		printf("NULL");
		break;
	case AF_UNIX:
		printf("{sa_family=AF_UNIX, path=");
		path = sockaddr.u.sa_un.sun_path;
		if (path[0] == '\0' && path[1] != '\0') /* Abstract UNIX socket */
			printf("\"@%s\"}", ++path);
		else
			printf("\"%s\"}", path);
		break;
	case AF_INET:
		inet_ntop(AF_INET, &sockaddr.u.sa_in.sin_addr, ip, sizeof(ip));
		printf("{sa_family=AF_INET, sin_port=htons(%d), sin_sockaddr=inet_addr(\"%s\")}",
		       ntohs(sockaddr.u.sa_in.sin_port), ip);
		break;
	case AF_INET6:
		inet_ntop(AF_INET6, &sockaddr.u.sa6.sin6_addr, ip, sizeof(ip));
		printf("{sa_family=AF_INET6, sin_port=htons(%d), sin6_sockaddr=inet_addr(\"%s\")}",
		       ntohs(sockaddr.u.sa6.sin6_port), ip);
		break;
#if PINK_HAVE_NETLINK
	case AF_NETLINK:
		printf("{sa_family=AF_NETLINK, nl_pid=%d, nl_groups=%08x}",
		       sockaddr.u.nl.nl_pid, sockaddr.u.nl.nl_groups);
		break;
#endif /* PINKTRACE_HAVE_NETLINK */
	default: /* Unknown family */
		printf("{sa_family=???}");
		break;
	}

	printf(", %u)", sockaddr.length);
}

static void
handle_syscall(struct process *proc)
{
	int r;
	long scno;
	const char *scname;

	/* We get this event twice, one at entering a
	 * system call and one at exiting a system
	 * call. */
	if (proc->insyscall) {
		/* Exiting the system call, print the
		 * return value. */
		proc->insyscall = false;
		fputc(' ', stdout);
		print_ret(proc);
		fputc('\n', stdout);
	}
	else {
		/* Get the system call number and call
		 * the appropriate decoder. */
		proc->insyscall = true;
		if ((r = pink_read_syscall(proc->pid, proc->regs, &scno)) < 0) {
			errno = -r;
			perror("pink_read_syscall");
			return;
		}
		scname = pink_name_syscall(scno, proc->abi);
		if (!scname)
			printf("%ld()", scno);
		else if (!strcmp(scname, "open"))
			decode_open(proc);
		else if (!strcmp(scname, "execve"))
			decode_execve(proc);
		else if (!strcmp(scname, "socketcall") || !strcmp(scname, "bind") || !strcmp(scname, "connect"))
			decode_socketcall(proc, scname);
		else
			printf("%s()", scname);
	}
}

int
main(int argc, char **argv)
{
	int r, sig, status, exit_code;
	enum pink_event event;
	struct process proc;

	/* Parse arguments */
	if (argc < 2) {
		fprintf(stderr, "Usage: %s program [argument...]\n", argv[0]);
		return EXIT_FAILURE;
	}

	/* Initialize */
	if ((r = pink_regset_alloc(&proc.regs)) < 0) {
		errno = -r;
		perror("pink_regset_alloc");
		return EXIT_FAILURE;
	}

	/* Fork */
	if ((proc.pid = fork()) < 0) {
		perror("fork");
		return EXIT_FAILURE;
	}
	else if (!proc.pid) { /* child */
		/* Set up for tracing */
		if ((r = pink_trace_me()) < 0) {
			errno = -r;
			perror("pink_trace_me");
			_exit(EXIT_FAILURE);
		}
		/* Stop and let the parent continue the execution. */
		kill(getpid(), SIGSTOP);

		++argv;
		execvp(argv[0], argv);
		perror("execvp");
		_exit(-1);
	}
	else {
		waitpid(proc.pid, &status, 0);
		event = pink_event_decide(status);
		assert(event == 0);

		/* Set up the tracing options. */
		if ((r = pink_trace_setup(proc.pid, PINK_TRACE_OPTION_SYSGOOD |
					  PINK_TRACE_OPTION_EXEC)) < 0) {
			errno = -r;
			perror("pink_trace_setup");
			pink_trace_kill(proc.pid, -1, SIGKILL);
			return EXIT_FAILURE;
		}

		/* Figure out the abi of the traced child. */
		process_update(&proc);
		printf("Child %d runs in ABI:%d\n", proc.pid, proc.abi);

		proc.insyscall = false;
		sig = exit_code = 0;
		for (;;) {
			/* At this point the traced child is stopped and needs
			 * to be resumed.
			 */
			if ((r = pink_trace_syscall(proc.pid, sig)) < 0) {
				perror("pink_trace_syscall");
				return (r == -ESRCH) ? 0 : 1;
			}
			sig = 0;

			/* Wait for the child */
			if ((proc.pid = waitpid(proc.pid, &status, 0)) < 0) {
				perror("waitpid");
				return (errno == ECHILD) ? 0 : 1;
			}

			if (WIFEXITED(status)) {
				exit_code = WEXITSTATUS(status);
				printf("Child %d exited normally with return code %d\n",
				       proc.pid, exit_code);
				break;
			} else if (WIFSIGNALED(status)) {
				exit_code = 128 + WTERMSIG(status);
				printf("Child %d exited with signal %d\n",
				       proc.pid, WTERMSIG(status));
				break;
			}

			/* Check the event. */
			event = pink_event_decide(status);
			switch (event) {
			case 0:
				process_update(&proc);
				handle_syscall(&proc);
				break;
			case PINK_EVENT_EXEC:
				/* Update abi */
				process_update(&proc);
				break;
			default:
				; /* Nothing */
			}
		}

		return exit_code;
	}
}