在C中使用printf是不安全的 [英] Is printf unsafe to use in C

查看:479
本文介绍了在C中使用printf是不安全的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言的新手,所以我开始尝试一些代码。我的代码中有一个错误,因为我相信使用 printf(pass)是不安全的,因为它会覆盖值,因此对用户不安全。我想知道 printf(pass)在我的代码中不安全吗?另外,我如何仍可以让用户在不更改我的代码的情况下打印最终登录的消息。有什么办法做到?

I am new to C so I started playing around with some code. I have a bug in my code as I believe using printf(pass) is not safe to use because it can overwrite the value and hence not safe for the user. I was wondering am I right about it that printf(pass) is not safe in my code? Also, how can I still let user print the message finally logged in without changing my code. Is there any way to do that?

我的代码:

#include <stdio.h>

char pass[100];

char getPass() {
  int value = 'G';
  int * j = & value;
  fgets(pass, sizeof(pass), stdin);
  printf("your entered pass is ");
  printf(pass);
  return (char)( * j);
}

void main() {
  printf("enter the pass here ");
  if (getPass() == 'K') {
    printf("finally logged in\n");
    exit(0);
  } else {
    printf("Wrong password\n");
    exit(1);
  }
}


推荐答案

是这是不安全的,但并非出于您建议的原因。如果在 man 页中查看 printf()函数,您将看到它具有以下原型: / p>

Yes it's unsafe, but not for the reason you suggested. If you check the man page for the printf() function, you'll see it has the following prototype:

int printf(const char * restrict format, ...);

应用于第一个参数的 const 修饰符指定该值

The const modifier applied to the first argument specifies that the value of this parameter will not be changed when you call this function.

但是,您还会注意到此参数称为 format 。那是因为它应该指定格式字符串。在您的程序中,没有什么可以阻止用户输入格式说明符,例如%p ,在这种情况下,您对 printf()将开始打印堆栈中的内容。有 Wikipedia文章,其中详细介绍了此漏洞。

However, you'll also notice that this parameter is called format. That's because it's supposed to specify a format string. In your program, there's nothing to stop a user entering a format specifier like %p, in which case your call to printf() will start printing out the contents of the stack. There's a Wikipedia article that describes this vulnerability in more detail.

这篇关于在C中使用printf是不安全的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆