Hi, I'm trying to use LogonUser. I think I'm doing everything right, but I keep getting this error: 1326 (ERROR_LOGON_FAILURE). I know my user and pass are right.

#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <windows.h>

void GetPassword(char *pass, int maxlen, char hidechar)
{
   char ch;
   int len = 0;

   memset(pass, 0, maxlen);

   while (ch != 13)
   {
      ch = getch();

      switch (ch)
      {
         case '\b':
            memset(pass + len, 0, sizeof(char));

            if (len > 0)
            {
               len--;
               printf("%c%c%c", '\b', ' ', '\b');
            }
            break;

         default:
            if (len < maxlen && (isalnum(ch) || isspace(ch) || ispunct(ch)))
            {
               memset(pass + len, ch, sizeof(char));
               len++;
               printf("%c", hidechar);
            }
            break;
      }
   }

   memset(pass + maxlen, 0, sizeof(char));
}

int main(int argc, char *argv[])
{
   char *pass = (char*)calloc(128, sizeof(char));
   char *user = (char*)calloc(128, sizeof(char));
   PHANDLE h;
   
   printf("Enter your username: ");
   fgets(user, 128, stdin);
   
   printf("Enter your password: ");
   GetPassword(pass, 128, '*');
   
   printf("\nPassword: %s", pass);
   
   if (LogonUser(user, NULL, pass, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, h))
   {
      printf("\nWindows logon successful!");
   }
   else
   {
      printf("\nWindows logon failed! Error code: %d", GetLastError());
   }
   
   free(pass);
   free(user);
   getch();
}

im not quite sure, but it seems that your backspace thing doesnt work:

case '\b':
            memset(pass + len, 0, sizeof(char));

            if (len > 0)
            {
               len--;
               printf("%c%c%c", '\b', ' ', '\b');
            }
            break;

i think you should swap 'memset' with 'if', because this way you set a block of memory that is already NULL to NULL

It is ridiculous to use memset to set a single character! It is also odd to dynamically declare memory (for pass and user) when you could just use automatic variables.

As for LogonUser, you need to declare a HANDLE (not a PHANDLE) to recieve the user token. You pass it to LogonUser (last param) as &h. And you should close the handle (CloseHandle) when you no longer need it.

This article has been dead for over six months. Start a new discussion instead.