*printf()格式化串安全漏洞分析(上)

How printf works——浅谈格式化串漏洞 本博客已经弃用,我的新博客地址:http://jujuba.me/ How printf works——浅谈格式化串漏洞 0x00 简介 格式化字符串漏洞由来已久,其主要原因是程序员在使用printf时未将格式化串的个数 和变量的个数相匹配,给了黑客们可乘之机。 我们可以先来看看printf函数的声明 int printf (const char *__format, ...... 阅读详情

*printf()格式化串安全漏洞分析(上)


     测试平台:RedHat 6.1, RedHat 6.2 (Intel i386)

前言:
=====
最近一段时间,一种新的安全漏洞正开始引起人们注意,就是诸多的*printf()函

数的格式
化串问题。其实这个问题应该说并不鲜见,只是一直没有人注意它,直到最近才

开始进行
一些深入的讨论。格式化串的问题实际上是由于程序员编程时的疏漏所导致的,

下面我们
就来看看具体是怎么回事。


关于格式化串
============
*printf()函数包括printf,  fprintf,  sprintf,  snprintf,  vprintf,

vfprintf,
vsprintf, vsnprintf等函数,它们可以将数据格式化后输出。以最简单的

printf()为例:
int printf(const char *format, arg1,arg2,...);

通过定制format的内容(%s,%d,%p,%x...),用户可以将数据按照某种格式输出。问

题是,
*printf()函数并不能确定数据参数arg1,arg2...究竟在什么地方结束,也就是说

,它不知
道参数的个数。它只会根据format中的打印格式的数目依次打印堆栈中参数

format后面地址
的内容。先来看一个简单的例子:

<- begin ->  fmt_test.c

#include <stdio.h>

int main(void)
{
   char string[]="Hello World!";
  
   printf("String: %s  , arg2: %#p , arg3: %#p/n", string);
   return 0;
}

<- end -> 

上面的例子中我们其实只提供了一个数据参数"string",但在格式串中有三个打印

格式,
我们看一下运行的结果:

[warning3@redhat-6 format]$ gcc -o fmt_test fmt_test.c
[warning3@redhat-6 format]$ ./fmt_test
String: Hello World!  , arg2: 0x6c6c6548 , arg3: 0x6f57206f

我们来看一下arg2,arg3显示的是哪里的内容:
[warning3@redhat-6 format]$ gdb ./fmt_test
<...>
(gdb) b printf
Breakpoint 1 at 0x8048308
(gdb) r
Starting program: /home/warning3/format/./fmt_test
Breakpoint 1 at 0x40064f5c: file printf.c, line 30.

Breakpoint 1, printf (
    format=0x80484c0 "String: %s  , arg2: %#p , arg3: %#p/n") at

printf.c:30
30      printf.c: No such file or directory.
(gdb) x/10x $ebp
0xbffffc88:     0xbffffca8      0x08048403      0x080484c0     

0xbffffc98
0xbffffc98:     0x6c6c6548      0x6f57206f      0x21646c72     

0x08049500
0xbffffca8:     0xbffffcc8      0x400301eb

我们看到printf()的第一个参数地址是$ebp+8,里面的内容是0x080484c0,
(gdb) x/s 0x080484c0
0x80484c0 <_IO_stdin_used+60>:   "String: %s  , arg2: %#p , arg3: %

#p/n"
这是我们的格式化串的地址

再来看我们要格式化输出的数据($ebp+12):
(gdb) x/s 0xbffffc98
0xbffffc98:      "Hello World!"

我们看到,紧接着下来的两个字的内容就是刚才的程序中显示的结果:
$ebp+16: 0x6c6c6548  "Hell"
$ebp+20: 0x6f57206f  "o Wo"

从下面的示意图上可以看得更清楚一些:

              栈顶
       +------------+
      |   ......   |   
      +------------+
0xbffffc88| 0xbffffca8 | --------> 保存的EBP  -- printf()
      +------------+
      | 0x08048403 | --------> 保存的EIP  -- printf()
      +------------+  format
format->  | 0x080484c0 | --------> "String: %s  , arg2: %#p , arg3: %

#p/n"的地址
      +------------+  arg1
      | 0xbffffc98 | --------> "Hello World!"的地址                    

    
      +------------+
      | 0x6c6c6548 | --------> string[] = "Hell   
      +------------+
      | 0x6f57206f | -------->             o Wo
      +------------+
      | 0x21646c72 | -------->             rld!"
      +------------+
      | 0x08049500 | -------->   '/0'xxx
      +------------+
0xbffffca8| 0xbffffcc8 | --------> 保存的EBP  -- main()
      +------------+
      | 0x400301eb | --------> 保存的EIP  -- main()
      +------------+
          |   ......   |   
      +------------+
              栈底

我们可以看到,arg2,arg3所显示的其实是main()中数组strings中前两个字的内

容。
从上面这个简单的例子我们可以看到, *printf()只根据format中打印格式(%)的

数目来依次
显示堆栈中format参数后面地址的内容,每次移动一个字(4个字节).
由于我们上面的例子中出现了三个(%)号,所以它会依次打印三个地址的内容:
format+4, format + 8, format + 12.

(注意:并不是所有的%格式都是移动4个字节,例如%f就每次移动8个字节。如果

要覆盖的地址
距离比较远(比如2048字节),而%的个数又有所限制的话,使用%f可以较快的到达

"目的地",
只需要256个%f就可以了,%E也是如此)

正常情况下,由于format串通常是程序员自己来定制,很少出现上面那种情况,

而且即使
出现了,也并不会有什么大的安全问题。然而,如果format串是由用户提供的话

,那么就
非常危险了!这种情况往往是由于程序员的疏忽导致的。最常见的情况是当需要

利用
vsprintf()等来构造自己的类printf()函数时,例如

mylog(LEVEL, "username = %s", username);

如果引用mylog时错误的使用了mylog(LEVEL,user_buf),而user_buf的内容又是用

户可以控
制的话,那么真正的危险就来了。

1. 问题一:格式化串导致的传统缓冲区溢出
==========================================
我们以不久前发现的QPOP 2.53的例子来做一下详细的说明。


QPOP 2.53中pop_uidl.c中有个函数pop_euidl (p),用来完成EUIDL命令的功能,

它错误的
使用了pop_msg()函数:

.......
pop_euidl (p)
POP     *   p;
{
    char                    buffer[MAXLINELEN];     /*  Read buffer */
    char            *nl, *bp;
    MsgInfoList         *   mp;         /*  Pointer to message info

list */
......
      if (mp->del_flag) {
     
      /* 注意: 这里使用pop_msg()的做法是正确的! 注意和下面那个

pop_msg()的用法
                做一下比较。
       */
        return (pop_msg (p,POP_FAILURE,
     

C语言printf动态格式化:%*s、%.*s与%-.*s的深度解析与应用 格式化输出是编程中处理数据呈现的基础技术,其核心原理是通过格式说明符控制数据的显示方式。在C语言中,printf函数是实现格式化输出的关键工具,它通过解析格式字符串中的占位符,将内存中的数据转换为可读文本。这项技术的工程价值在于提升代码的灵活性与安全性,特别是在处理动态数据或不确定长度的内容时。在实际应用场景中,如日志系统、报表生成或命令行工具开发,经常需要根据运行时数据动态调整输出宽度、精度和对齐方式。本文聚焦于printf中带星号(*)的格式化说明符,深入探讨%*s、%.*s和%-.*s的用法与区别,帮 阅读详情

相关推荐

C语言printf格式化字符串漏洞解析与防御

格式化字符串是C语言中处理文本输出的核心机制,通过%转换符实现数据类型动态匹配。其安全风险源于参数读取时直接从栈获取数据的底层原理,当用户可控输入被直接作为格式字符串时,攻击者可利用%n等特殊转换符实现内存读写。这种漏洞常出现在日志记录、错误处理等场景,属于高危内存安全漏洞。以printf系列函数为例,防御需遵循‘永远验证用户输入’原则,结合编译器防护选项(-Wformat-security)和运行时检查(ASLR)。现代静态分析工具如Flawfinder能有效检测此类漏洞,而安全编码规范要求强制使用pri

weixin_26642481的博客 285

Android AI Agent集成实战:架构设计与自动化技能开发

AI Agent(人工智能代理)是一种能够感知环境、自主规划并执行任务以达成目标的软件实体。其核心原理在于结合大语言模型的推理能力与工具调用(Tool Calling)技术,使应用从被动响应转向主动服务。在移动开发领域,这项技术的价值在于为应用注入“智能大脑”,实现跨应用自动化与个性化交互,从而显著提升用户体验和操作效率。具体到Android平台,其应用场景广泛,例如自动填写表单、智能聊天辅助、个性化工作流优化等。本文聚焦于Android AI Agent的工程化落地,深入探讨了如何利用Accessibil

weixin_42636895的博客 666

Frida实战:如何用adb快速连接网易mumu模拟器进行参数Hook(附常见CPU架构问题排查)

本文详细介绍了如何使用Frida和adb快速连接网易MuMu模拟器进行参数Hook,包括环境配置、架构适配、Frida-server部署及常见问题排查。特别针对CPU架构兼容性问题提供了实用解决方案,帮助开发者高效完成逆向调试任务。

weixin_29274969的博客 291

C++和蓝图1:Unreal Engine 中 C++ 与蓝图的桥梁

摘要: 本文介绍了Unreal Engine(UE)中C++与蓝图可视化脚本的结合机制,重点解析了宏系统(UCLASS、UPROPERTY、UFUNCTION)如何实现代码与蓝图的交互。相比Unity的纯C#脚本模式,UE的双轨制开发允许程序员用C++处理核心逻辑,同时通过蓝图让非程序员快速迭代。文章对比了两大引擎的编程范式差异,指出UE的反射系统和宏标记提供了更精细的控制,并给出了从Unity迁移到UE的具体思路。核心在于理解UE的混合编程优势:C++保证性能,蓝图提升开发效率,二者通过宏系统无缝协作。

qq_46348216的博客 1409

CST实战:5分钟搞定圆极化天线轴比分析(含远场设置技巧)

本文提供了一份CST Studio Suite圆极化天线轴比分析的实战指南。文章详细讲解了轴比的概念与工程标准,并重点演示了如何正确设置远场监视器以获取Axial Ratio数据,包括关键步骤与后处理技巧。最后,通过植入式天线在生物组织环境中的案例,分析了复杂环境对轴比性能的影响及优化思路。

nokia的博客 999

mos管结电容等效模型_MOS管的防冲击防反接电路

MOS管的反接和抑制冲击一:原理分析MOS管由于生产工艺等因素,会产生相应的寄生电容,体二极管等。Mos管的寄生电容如图1所示,可以看到其具有三个寄生电容:G和S的电容Cgs;G和D的电容:Cgd,也称为反向传输电容、米勒电容、Crss;D和S的电容Cds。D和S之间的体二极管D1.图 1:MOS管等效模型寄生电容的数值可以从元器件的datasheet中得到,如图2,图3:Ciss(输入电容)=C...

weixin_29179583的博客 1859

基于Hadoop生态的大数据异常检测平台搭建

批处理:用Spark MLlib的LOF(局部异常因子,适合高密度数据)、(单类支持向量机,适合高维数据);流处理:用Flink ML的(实时聚类,检测离群点)、ADWIN(自适应滑动窗口,处理概念漂移)。数据层:用Flume/Kafka采集数据,HDFS存储,Hive管理元数据;计算层:用Spark处理离线批数据,Flink处理实时流数据;算法层:用孤立森林(批)、3σ原则(流)检测异常;可视化层:用Grafana做仪表盘,Prometheus+Alertmanager报警。这个平台能处理。

软件工程实践的博客 934

【光子AI / Photon.AI】manus 通用 Agent 的实现核心技术原理与应用

摘要 Manus是一款由国内团队开发的通用AI Agent,其核心技术原理基于多智能体协作架构、云端全能沙箱、规划-执行-反思循环等系统工程方法。与传统的对话式AI不同,Manus能够在独立的Linux虚拟机环境中自主规划并执行复杂任务,通过编写和运行代码来解决问题,具备强大的纠错能力和工具使用能力。 核心应用场景包括深度行业研究、自动化办公、生活助理、辅助编程和跨平台信息整合等。Manus的工程化落地优势体现在沙箱环境、多智能体调度和容错机制等方面,使其能够完成需要多步骤操作和多种工具调用的复杂任务,将A

AI天才研究院 675

【x265编码器】章节1——x265的lookahead模块分析

目录一、模块功能二、lookahead模块分析1.调用流程2.代码分析Lookahead::addPicture()Lookahead::checkLookaheadQueue()Lookahead::getDecidedPicture()Lookahead::findJob()Lookahead::slicetypeDecide()PreLookaheadGroup::processTasksLookaheadTLD::lowresIntraEstimate()Lookahead::slicetypeAn

vcvdv123的博客 4万+

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

上一篇: 如何修改动态库符号表
下一篇: *printf()格式化串安全漏洞分析(下)
普通网友
博客等级 码龄22年 1万+粉丝 3156原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值