簡體   English   中英

新到 C 代碼不完全明白什么問題

[英]New to C code don't fully understand what's wrong

我使用的代碼應該只允許訪問密碼字節,但它也可以訪問字節字節。 我把它從原來的gets改成了fgets,解決了stacksmashing問題。 我需要做什么來解決字節字節被排除的新問題。

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
  
int main(void) {
// Use a struct to force local variable memory ordering
  struct {
    char buff[5];
    char pass;
  } localinfo;
  localinfo.pass = 0;
  
  printf("\n Enter the password:\n");
  fgets(localinfo.buff, 5, stdin); // Get the password from the user
  // Check the password with string matching
  if(strcmp(localinfo.buff, "byte") !=0 ){
    printf ("\n Wrong Password \n");
  }
  else {
    printf ("\n Correct Password\n");
  localinfo.pass = 1; // Set a flag denoting correct password
  }
//IF password matches
// GIVE root or admin rights to user by checking for flag
  if(localinfo.pass){ 
    printf ("\n Congratulations! Root privileges given to the user!\n");
  }
  return 0;
}

fgets()將僅讀取您在 size 參數中指定的字節數,對於 null 終止符,減去 1。 所以fgets(localinfo.buff, 5, stdin); 只會讀取輸入的前 4 個字節。 如果用戶輸入bytebyte ,則只會將byte讀入字符串,並且比較成功。

您應該將輸入讀入緩沖區的時間長於要與之比較的任何密碼。 只有在確定密碼有效后才復制到localinfo.buff

另外,不要忘記fgets()如果合適的話,會在輸入中留下換行符; 您應該在使用輸入之前刪除它。 請參閱從 fgets() 輸入中刪除尾隨換行符

你這樣聲明localinfo.buff

char buff[5];

這意味着該數組只有 4 個字符加上終止 null 字符的空間。

使用輸入bytebyte ,該行

fgets(localinfo.buff, 5, stdin);

只會將前 4 個字符讀入localinfo.buff並將所有其他字符留在輸入 stream 上。 這不是你想要的。

我建議您使用一個可能大小為 200 的輸入緩沖區,並通過驗證是否找到換行符來驗證是否已讀入整行。 之后,您應該刪除換行符,因為如果輸入包含換行符,它將永遠不會匹配所需的密碼。

這是一個例子:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
  
int main(void)
{
    char line[200], *p;

    //prompt user for input  
    printf("Enter the password: ");

    //attempt to read one line of user input
    if ( fgets( line, sizeof line, stdin ) == NULL )
    {
        printf( "Input error!\n" );
        exit( EXIT_FAILURE );
    }

    //attempt to find newline character
    p = strchr( line, '\n' );

    //verify that entire line was read in
    if ( p == NULL )
    {
        printf( "Line too long for input buffer!\n" );
        exit( EXIT_FAILURE );
    }

    //remove newline character by overwriting it with null character
    *p = '\0';

    //check the password
    if( strcmp( line, "byte" ) != 0 )
    {
        printf( "Wrong Password.\n" );
        exit( EXIT_FAILURE );
    }

    //print success message
    printf( "Correct Password.\n" );
    printf( "Congratulations! Root privileges given to the user!\n" );

    return 0;
}

該程序具有以下行為:

Enter the password: byte
Correct Password.
Congratulations! Root privileges given to the user!
Enter the password: bytebyte
Wrong Password.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM