Skip to content

Instantly share code, notes, and snippets.

@YukiSakamoto
Created September 24, 2012 14:22
Show Gist options
  • Save YukiSakamoto/3776193 to your computer and use it in GitHub Desktop.
Save YukiSakamoto/3776193 to your computer and use it in GitHub Desktop.
Disable ASLR on MacOSX
#include <stdio.h>
/*
This source is testing for address layout randomization.
If ASLR is enabled, output of this program will be variable.
*/
int main(void)
{
printf("%p\n", main);
here:
printf("%p\n", &&here);
return 0;
}
#include <spawn.h>
#include <stdio.h>
int main(void)
{
int ret;
short ps_flags = 0;
pid_t pid;
posix_spawn_file_actions_t actions;
posix_spawnattr_t attrs;
/*
char *args[] = {"/bin/ls", "-l", NULL};
*/
char *args[] = {"./random", NULL};
posix_spawn_file_actions_init(&actions);
posix_spawnattr_init(&attrs);
#ifndef _POSIX_SPAWN_DISABLE_ASLR
# define _POSIX_SPAWN_DISABLE_ASLR 0x0100
#endif
ps_flags |= POSIX_SPAWN_SETEXEC;
ps_flags |= _POSIX_SPAWN_DISABLE_ASLR;
ret = posix_spawnattr_setflags(&attrs, ps_flags);
if (ret != 0) {
printf("cannot set posix_spawn flags\n");
}
posix_spawn(&pid, args[0], &actions, &attrs, args, NULL);
printf("pid: %d\n", pid);
printf("========================\n");
return 0;
}
@mstange
Copy link

mstange commented Apr 27, 2022

Here's an improved version of spawn.c which passes along the command name and arguments, and environment variables.

#include <spawn.h>
#include <stdio.h>

extern char **environ;

int main(int argc, char *argv[])
{
	if (!argv[0] || !argv[1]) {
		printf("Usage: spawn <command> <args>\n");
		return -1;
	}

	int ret;
	short ps_flags = 0;
	pid_t pid;
	posix_spawn_file_actions_t actions;
	posix_spawnattr_t attrs;

	posix_spawn_file_actions_init(&actions);
	posix_spawnattr_init(&attrs);
#ifndef _POSIX_SPAWN_DISABLE_ASLR
#	define _POSIX_SPAWN_DISABLE_ASLR 0x0100
#endif

	ps_flags |= POSIX_SPAWN_SETEXEC;
	ps_flags |= _POSIX_SPAWN_DISABLE_ASLR;
	ret = posix_spawnattr_setflags(&attrs, ps_flags);

	if (ret != 0) {
		printf("cannot set posix_spawn flags\n");
	}

	ret = posix_spawn(&pid, argv[1], &actions, &attrs, &argv[1], environ);
	if (ret != 0) {
		printf("failed to spawn %s\n", argv[1]);
		return ret;
	}

	printf("pid: %d\n", pid);
	printf("========================\n");
	return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment