Skip to content

Instantly share code, notes, and snippets.

@Dantee296
Forked from andrew-d/main.c
Created December 1, 2023 12:29
Show Gist options
  • Save Dantee296/632be013bedb7323b7190ba9cba33ce5 to your computer and use it in GitHub Desktop.
Save Dantee296/632be013bedb7323b7190ba9cba33ce5 to your computer and use it in GitHub Desktop.
Example of how to get current binary's path using Apple's Code Signing Services
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <Security/Security.h>
// Compile with:
// gcc -o ourpath -framework CoreFoundation -framework Security main.c
char* getPathForPid(pid_t pid) {
CFNumberRef value = NULL;
CFDictionaryRef attributes = NULL;
SecCodeRef code = NULL;
CFURLRef path = NULL;
CFStringRef posixPath = NULL;
OSStatus status;
char* ret = NULL;
value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pid);
if (value == NULL)
goto done;
attributes = CFDictionaryCreate(kCFAllocatorDefault, (const void **)&kSecGuestAttributePid, (const void **)&value, 1, NULL, NULL);
if (attributes == NULL)
goto done;
status = SecCodeCopyGuestWithAttributes(NULL, attributes, kSecCSDefaultFlags, &code);
if (status)
goto done;
status = SecCodeCopyPath(code, kSecCSDefaultFlags, &path);
if (status)
goto done;
posixPath = CFURLCopyFileSystemPath(path, kCFURLPOSIXPathStyle);
if (path == NULL)
goto done;
ret = strdup(CFStringGetCStringPtr(posixPath, kCFStringEncodingUTF8));
done:
if (posixPath) CFRelease(posixPath);
if (path) CFRelease(path);
if (code) CFRelease(code);
if (attributes) CFRelease(attributes);
if (value) CFRelease(value);
return ret;
}
int main(int argc, char* argv[]) {
pid_t pid = getpid();
printf("[-] started, our pid = %d\n", pid);
printf("[*] our argv[0] = %s\n", argv[0]);
char* ourPath = getPathForPid(pid);
if (ourPath) {
printf("[*] our path = %s\n", ourPath);
free(ourPath);
} else {
printf("[!] could not get our path\n");
}
printf("[-] done\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment