Interchange Harcoded c:\\ for SystemDrive Variable

Hi everyone,

I apologise in advance if my question seems confusing & noobish but I have no clue about coding in C++ hence the apparent ignorance & difficulty to me (& for some it may be a very basic question). First of all I have these lines of code that I would like to amend slightly like so:

1
2
3
4
5
6
7
8
9
10
typedef DWORD(__stdcall *CPP) (DWORD param1, PWCHAR param2, DWORD param3);

void Disable_WFP() {
    hmod=LoadLibrary("sfc_os.dll");
    CPP SetSfcFileException;
    // the function is stored at the fifth ordinal in sfc_os.dll
    SetSfcFileException=(CPP)GetProcAddress(hmod,(LPCSTR)5);
    SetSfcFileException(0, L"c:\\windows\\system32\\calc.exe",-1);
    // Now we can modify the system file in a complete stealth.
}


I have been advised that the above code could be used to produce malware but as with all things A hammer can be used to drive nails in or a hammer can be used to drive nails through someones hand, the latter being used for negative effect.
The only reason I am saying this is to affirm I want to use the code to disable the WFP on Selective files to carry out removal of said files or amendmant NOT to write malware as someone on another forum accused me of.
What I would like to do is change this line in the example above:

SetSfcFileException(0, L"c:\\windows\\system32\\calc.exe",-1);

I would like to change to something like this (Obviously this is not C++ code it is just for illustration purposes to show what I am trying to do:

SetSfcFileException(0, L"%SystemDrive%\\windows\\system32\\calc.exe",-1);

interchanging %SystemDrive% for C:\\ So no matter what drive I wish to run the program it will be on the system drive & not hard coded to C:\\
The question is what would be the equivelent code in C++ for SystemDrive in the context or scenario above & if at all possible a way to use a second file coded to reverse the process or undo feature. I would use this code to disarm WFP on selective files so that they can be removed or amended for mini windowsXP systems not for other OS's
Can anyone help out please. I have found 2 snippets of code that might help but do not know how to combine them. The code is:

sysdrive = getenv("SYSTEMDRIVE");
if (sysdrive == NULL || *sysdrive == NUL)
sysdrive = "C:\\";
}
char *sysDrive = getenv ("SystemDrive");

Best Regards,

ispy
Last edited on
Warning, on my pc (winx) you get
c:
for systemdrive, not c:\ (the slash isnt there). you should be consistent with what is returned and what you put into it, so no matter how it was populated you handle it the same way downstream.


The question is what would be the equivelent code in C++ for SystemDrive...

https://en.cppreference.com/w/cpp/utility/program/getenv

systemdrive is the correct name for the variable, so just call the above to get its value.


Last edited on
> NOT to write malware as someone on another forum accused me of.
Well to put it bluntly, when "I have no clue about coding in C++" and "how do I disable..." appear in the same post, an awful lot of red flags start waving.

> The only reason I am saying this is to affirm I want to use the code to disable the
> WFP on Selective files to carry out removal of said files
So what's wrong with using competent anti-virus software?
Or just boot into safe mode, then delete your unwanted file.
Or https://docs.microsoft.com/en-us/sysinternals/downloads/pendmoves

Looks like you got your code from here.
https://www.codeproject.com/Articles/14933/A-simple-way-to-hack-Windows-File-Protection-WFP-u

Using environment variables is awful, not to mention - unsafe.
Within a console, users can make any environment variable be whatever they want, and then your program is instantly off in the weeds somewhere doing something you didn't plan for.

Use proper APIs to get the information you need.
https://docs.microsoft.com/en-gb/windows/win32/sysinfo/getting-system-information?redirectedfrom=MSDN
Hi jonnin & Salem c,

@ jonnin are you saying I just use %SystemDrive% and the code will work if I am using this routine on a different drive, it will in effect recognise the code & operate correctly?

@salem C
> Well to put it bluntly, when "I have no clue about coding in C++" and "how do I disable..." appear in the same post, an awful lot of red flags start waving.
Ans - Why? The desription of what the code does is on the code-project website & what the code faciltates & its what I am trying to achieve in a selective manner on individual files.

> So what's wrong with using competent anti-virus software?
Or just boot into safe mode, then delete your unwanted file.
Or https://docs.microsoft.com/en-us/sysinternals/downloads/pendmoves
Ans - Yep there is nothing wrong with what you are stating except the advantage the code-project code is you can do it on the fly without exiting or rebooting, it is less hassle cleaner etc

> Looks like you got your code from here.
https://www.codeproject.com/Articles/14933/A-simple-way-to-hack-Windows-File-Protection-WFP-u
Ans - Yep I did, it is not my code but it is code that I am hoping someone can help to adapt/tweak to meet my needs?

> Using environment variables is awful, not to mention - unsafe.
Within a console, users can make any environment variable be whatever they want, and then your program is instantly off in the weeds somewhere doing something you didn't plan for.
Ans - Now what you are saying is noteable & derails what I am hoping to achieve words like awful & unsafe are now raising red flags waving for me.

> Use proper APIs to get the information you need.
https://docs.microsoft.com/en-gb/windows/win32/sysinfo/getting-system-information?redirectedfrom=MSDN
Ans - You are strongly suggesting a different approach to make the routine safer how would you bolt this alternative code into the code-project above.

Irrespective I would like to extend my gratitude for your insight & experience in tweaking it. looks like it is back to the drawing board

Best Regards
ispy
Look at the example that I linked. It does not have the %s -- that is ms console /batch lingo. C++ doesn't need them. Though it sounds like you are not going this route anyway...

yes, env variables, system commands, etc can be hacked or used to break programs that rely on them. That is a very targeted attack -- its not likely on a home pc for a personal utility if you are just playing around.

Use the alternate approach or research into it yourself if you want an industrial grade tool.
@jonnin,
Many thanks I will look at the link you have provided & you are right for personal usage, I have no reason to alter the system OS variables & it seems it is the easier or by going down the path of least resistance (Pardon the Pun). If however someone else wanted to use the same routine I would have to ensure or strongly advise them that the SystemDrive variable would need to be intact before using. If for instance it wasn't intact what would be the result or possible outcome as I do not want to be responsible for damage to anothers OS system or mine for that matter If I forgot to check this Var.

Just as a further consideration & trying to look at all options is there a simple C++ check that could be performed & exit gracefully without causing mayhem to ensure safety for an alternative user. Mind you I could use a batch file to check for the SystemDrive firstly then call the WFP file thingy if the SystemDrive Var is correct otherwise with a warning message then exit gracefully. As a further safety measure maybe something coded into the C++ routine would prevent it from running if the SystemDrive was not OS correct? What do you think is the best course of action with my limitations?
Much appreciated! Really speaking what would you do if you were in my shoes?
ispy
Last edited on
it depends on what you did what the damage done could be.
say a hacker put a .exe file on your pc but lacks permission to run it.
but he manages to set the env so that your systemdrive is now 'c:\hack.exe - ' and anything appended to it becomes command line args to the executable which lets say ignores them. Hack.exe installs a backdoor, guy takes control...

far-fetched, again, but 'possible'. And actually not too far fetched on a public machine; I used many a similar trick to do things on the school lab computers back in the day (nothing bad, but fun, I was never destructive).

now, if the systemdrive variable was just missing or set to xy: (not a valid drive) it would not do any harm.

I don't know much about wfp and haven't had to hack it.

In your shoes? I personally have multiple c++ programs that are little more than batch files. /shrug. Only used by me on my box.


@ jonnin

I think I will opt for the batch front end to check for the SystemDrive variable & then call the NO_WFP.exe from the batch file, I think that will be the safest route with the limited experience I have of C++.

Taking a wild stab at what I am trying to achieve would this code work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cstdlib>
 
int main()
{
char* getenv( const char* ("SystemDrive") );
typedef DWORD(__stdcall *CPP) (DWORD param1, PWCHAR param2, DWORD param3);

void Disable_WFP() {
    hmod=LoadLibrary("sfc_os.dll");
    CPP SetSfcFileException;
    SetSfcFileException=(CPP)GetProcAddress(hmod,(LPCSTR)5);
    SetSfcFileException(0, L"SystemDrive:\\windows\\system32\\calc.exe",-1)<< SystemDrive << '\n';
}


Can you tell me what is right & what is wrong with the code Please? Can you also give explanation for wrongdoing so at least I can learn from my mistakes. I currently have no way of compiling the completed code but am looking into it. Is there an emulator that you know of that could run the code to check for mistakes?

What I am finding difficult within the code is after finding the SystemDrive is linking or pushing that code into the line

SetSfcFileException(0, L"c:\\windows\\system32\\calc.exe",-1);

Nah the code is bad I have just run the edit and run feature & it spits out all kinds of errors that feature is vgood though!

errors listed in lines 6,7,9,14

In function 'int main()':
6:27: error: expected ',' or '...' before '(' token
7:15: error: ISO C++ forbids declaration of 'DWORD' with no type [-fpermissive]
7:15: error: typedef 'DWORD' is initialized (use decltype instead)
7:15: error: '__stdcall' was not declared in this scope
7:26: error: 'CPP' was not declared in this scope
9:20: error: a function-definition is not allowed here before '{' token
14:1: error: expected '}' at end of input

Many Thanks
ispy
Last edited on
fix errors from the top down in c++. One error can throw the compiler into a spin and it will print additional errors caused by the first one.

it is not happy with your typedef. What do you want to do there, it makes no sense to me. I don't know all these library calls you are doing ... but usually a .dll needs a .h to go with it (?). You can do some screwy stuff with dlls, so I am not 100% sure, but all the normal ones have a .h file to include.

you have a function inside main, that is no good as well...

you are in for a rough road trying to use library calls, windows system, windows specific gibberish code, all while not knowing c++. Each of those is its own difficult subject.
Last edited on
char* getenv( const char* ("SystemDrive") );
This also doesn't make sense. It looks like a function declaration but that ("SystemDrive") part doesn't belong there, if so. getenv is already declared in <cstdlib>, so I think you meant to call the function.
const char* drive = getenv("SystemDrive");

7:15: error: ISO C++ forbids declaration of 'DWORD' with no type [-fpermissive]
DWORD is a type defined in <windows.h> (it's an alias to unsigned int).

As jonnin mentioned, if you're trying to get into the mess that is the Windows API without even knowing C or C++ to a capable degree, you're going to have a bad time.
Last edited on
> I currently have no way of compiling the completed code
You really are digging yourself into a hole here.

TBH, you should put this problem aside, then
- download a compiler
- spend at least a month on some C++ tutorials, so you're at least in the ball-park when it comes to asking questions and understanding answers.

> Nah the code is bad I have just run the edit and run feature & it spits out all kinds of errors
Well for one thing, the back end of that is almost certainly a Linux box, so anything windows specific isn't going anywhere.
@ jonnin, salem c & Welcome Ganado,
Reading between the lines here what I thought was going to be a fairly straight forward amendmant looks like is slowly developing into a tarpit.

@jonnin - What I have basically tried to do is combine two sections of code (in ignorance) hoping that there would not generate to many errors & via a process of elimination & with your knowledge & assistance would eliminate the errors. I can see now is a non-starter & a expectation bridge to far. Sorry guys it seems beyond salvation, it was never my intention to waste any ones time & this is now becoming embarrising.
@Salem c - I have been looking into this but was wondering if there was an emulator that a noob could run code without having to compile a program as I am led to believe compiling a program is a 3 stage process. a bit like Vbox for C++ or similair. I think the rest of your advice is sound learn to walk before attempting to run.
@ Ganado - Realisation slowly dawns your right a bad discouraging time.

One encouraging bit of news though I have stumbled across the very thing I need called WFPReplacer, it is a commandline windows utility that pretty well does what I want & generally in the same manner. it disables WFP for both singular files & can be used for wholesale switching off of WFP if the right file is replaced. All I need to do is write a batch file as a front end to back up the system files I want to disable use WFPReplacer.exe. So if in the event of the proceedings the routine gets stuffed I can revert back to the backed up files. I think this program uses the same type of embedded coding but is written in Delphi/pascal, it is called Remko Weijnen's Blog (Remko's Blog) "replacing Wfp protected files" so maybe reinventing the wheel is a bit of a futile endevour.

Can I thank everyone for their patience & knowledge what must I now see would be a bit frustrating Many Many Thanks you guys are a credit to your forum

Best Regards
ispy
don't feel bad, you actually have probably learned quite a bit here. Even if you do not keep with c++, some of it is universal.

- its not usually easy or even viable to glue random code together without a good skill set
- there is often a program that already does what you want, unless its a new game or an exceedingly special use tool. Reinvent is only for fun, otherwise search first...
- c++ isn't very portable between windows and other things (it takes extra effort to make this happen if you even want it).


compiling is a multi step process but modern tools do it all for you, and even a dumb g++ command will generate a working program with 1 line, eg all I need to type to run most of the toy programs in these forums is
c:\> g++ filename
and it will run. More complex programs need more than this.

pascal is a lot like C++ pre 1998 at least. It has words where we have symbols, eg being end vs {} but its not that far off. Its really compiled pseudocode with a C like structure.
Last edited on
@ jonnin,

I generally like to leave whatever I am doing on a positive note. So just in case someone else lands on this forum & is trying to accomplish a similair exercise here is the code that one can compile (This is not my code it belongs to Remko Weijnen's Blog (Remko's Blog)) Please be advised it is NOT C++ it is a commandline exe Delhi/Pascal found at this link, so all credits belong to him. The link is:

https://www.remkoweijnen.nl/blog/2012/12/05/replacing-wfp-protected-files/

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
DWORD __stdcall SfcFileException(RPC_BINDING_HANDLE hServer, LPCWSTR lpSrc, int Unknown)
{
  RPC_BINDING_HANDLE hServerVar; // eax@2
  int nts; // eax@6
  __int32 dwResult; // eax@7
  DWORD dwResultVar; // esi@9
  int v8; // [sp+8h] [bp-8h]@1
  int v9; // [sp+Ch] [bp-4h]@1

  LOWORD(v8) = 0;
  *(int *)((char *)&v8 + 2) = 0;
  HIWORD(v9) = 0;
  if ( !hServer )
  {
    hServerVar = _pRpcHandle;
    if ( !_pRpcHandle )
    {
      hServerVar = SfcConnectToServer(0);
      _pRpcHandle = hServerVar;
      if ( !hServerVar )
        return 0x6BA;                           // RPC_S_SERVER_UNAVAILABLE
    }
    hServer = hServerVar;
  }
  nts = SfcRedirectPath(lpSrc, (int)&v8);
  if ( nts >= 0 )
    dwResult = SfcCli_FileException((int)hServer, v9, Unknown).Simple;
  else
    dwResult = RtlNtStatusToDosError(nts);
  dwResultVar = dwResult;
  MemFree(v9);
  return dwResultVar;
}


If someone one day could translate it into C++ as an exercise then that would be great as Jonnin has stated above Delphi/Pascal is related to C++ but no sweat otherwise.

Also as one further warning (Unless you know what you are doing!!!) do not attempt to use this program, ALWAYS ALWAYS ALWAYS backup your system files before deletion or alteration as strongly suggested by Salem c above.

What this program will do is disarm WFP for 60 seconds whilst you intercange or amend your files. Example usage for example is:
WfpReplacer.exe c:\windows\Notepad.exe (Errorlevel true or false will be produced on execution).

All the very Best Regards
ispy
Last edited on
Topic archived. No new replies allowed.