为什么C有%n格式说明符,尽管有明显的缺点?(复制)

时间:2022-09-07 07:38:43

This question already has an answer here:

这个问题已经有了答案:

I've been learning about format string vulnerabilities, and it's the first time I've ever heard of %n. And I don't understand why it exists.

我一直在学习格式化字符串漏洞,这是我第一次听说%n。我不明白它为什么存在。

Okay, sure, I can imagine cases where you'd like to know how many characters you've written so far. But there are a lot of other ways to find the length of a string, and %n seems like a bizarre approach. It's unlike all the other format specifiers, because it doesn't write to the string, it writes to some other manually-specified location in memory. And because it's so unintuitive - who would expect printf to write to arbitrary memory? - it seems to have an obvious potential for creating security holes. Unless someone warns you about format string vulnerabilities, you might never think about it.

好的,当然,我可以想象一些情况,你想知道到目前为止你写了多少字符。但是有很多其他的方法来求字符串的长度,%n看起来是一种奇怪的方法。它不同于所有其他格式说明符,因为它不写入字符串,而是写入内存中的其他手动指定位置。因为它是如此的不直观-谁会期望printf写到任意的内存中呢?-它似乎有很明显的可能产生安全漏洞。除非有人警告您格式化字符串漏洞,否则您可能永远不会考虑它。

There must have been a reason for doing things this way. But what was it? Or were the problems described above just not considered to be serious at the time?

这样做一定是有原因的。但是它是什么呢?或者是上面描述的问题在当时不被认为是严重的?

1 个解决方案

#1


2  

As show in This question It doesn't actually store it's value in random memory.

正如在这个问题中所显示的它并没有将它的值存储在随机存储器中。


Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.

没有打印出来。参数必须是指向有符号整型的指针,其中存储迄今为止写入的字符数。

#include <stdio.h>

int main()
{
  int val;

  printf("blah %n blah\n", &val);

  printf("val = %d\n", val);

  return 0;

}

This argument is useful if you want to know when to wrap lines on consoles, want to align your values and for other formatting processes you may wish to do to your output.

如果您想知道何时在控制台上换行,想要对齐您的值,以及想要对输出执行的其他格式化过程,那么这个参数是非常有用的。

#1


2  

As show in This question It doesn't actually store it's value in random memory.

正如在这个问题中所显示的它并没有将它的值存储在随机存储器中。


Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.

没有打印出来。参数必须是指向有符号整型的指针,其中存储迄今为止写入的字符数。

#include <stdio.h>

int main()
{
  int val;

  printf("blah %n blah\n", &val);

  printf("val = %d\n", val);

  return 0;

}

This argument is useful if you want to know when to wrap lines on consoles, want to align your values and for other formatting processes you may wish to do to your output.

如果您想知道何时在控制台上换行,想要对齐您的值,以及想要对输出执行的其他格式化过程,那么这个参数是非常有用的。