CreateDirectory vs fopen

Posted By: Scifi

CreateDirectory vs fopen - 04/11/15 15:01

So I did a little experiment with CreateDirectory() and fopen(). I wrote a small function to test if the application was run with Administrator rights, simply by creating a empty file/directory on the system drive. (I know there's the OpenProcessToken()/GetTokenInformation() pair which does the job better, but let's keep this simple).

This is my code
Code:
// Like str_clip (in fact it actually calls str_clip), but returns the cut string.
STRING *str_clip_a( STRING *s, int n ) {
	STRING *l = str_create(_chr(s));
	str_trunc(l, str_len(s)-n );
	str_clip(s, n);
	return l;
}

BOOL IsElevated () {
	const short len = 384;
	const short sublen = 3;
	char drivedir[384], cdir[3];
	GetSystemDirectory( drivedir, &len );
	strcpy(drivedir, _chr(str_clip_a(drivedir, 3))); // strlen("C:\") = 3
	strcat(drivedir, _chr ( str_for_num(NULL, rand()%256) ));
	//		if(0 == CreateDirectory(drivedir, 0))
	if(!fopen(drivedir,"w"))
	printf("Can't create file");
}




With fopen(), everything works fine. Compiled my script, run it normally, printf got executed, says it can't create the file. Right-click, chose "Run as administrator" and the file is created.

But if I substitute fopen() with CreateDirectory(), then the compiled script never creates any folder. I think creating a folder is as the same as creating a file? If so, why fopen() works but not CreateDirectory() ?

Thanks in advance.

Sorry for my bad English. laugh
Posted By: Scifi

Re: CreateDirectory vs fopen - 04/12/15 04:21

I recreated the code in C, compiled with tdm-gcc 4.8.1. Surprisingly, CreateDirectory() works even without Administrator rights, and fopen() only works with Administrator rights switched on, which is weird. The version of CreateDirectory() in A8's windows.h refuses to create any file in the system drive (but it works on some other drive which is not system drive, or in work_dir).

Here's the equivalent C code
Code:
#include <stdio.h>
#include <windows.h>

const char *token = "W\n";

bool IsElevated ();

int main() {
	printf("Administrator rights = %i",IsElevated());
	return 0;
}


bool IsElevated () {
	int dlen = 384, rlen = 3;
	char drivedir[384], cdir[3];
	GetSystemDirectory( drivedir, dlen );
	strcpy(drivedir, strtok(drivedir, token ));
	sprintf(cdir, "%i", rand()%1000 );
	strcat(drivedir,cdir);
	/*
	(0 != CreateDirectory(drivedir, 0)) // success
	return true;
	else return false;
	*/
	if(!fopen(drivedir,"w"))
	return false;
	else return true;
}



I'm confused... frown
© 2024 lite-C Forums