如何解决copy_from_user不起作用?

时间:2019-05-15 13:24:08

标签: c linux linux-kernel linux-device-driver kmalloc

我正在尝试在Linux中编写一个加密驱动程序,但是当我对字符串进行加密并使用copy_from_user()将其复制到缓冲区中时,它不起作用,并且k值是字符串

如果我将temp中的copy_from_user更改为buf,就可以正常使用

ssize_t encdec_write_caesar(struct file *filp, const char *buf, size_t count, loff_t *f_pos)
{
    char *temp ;
    temp = kmalloc(memory_size * sizeof(char),GFP_USER);
    memset(temp, 0, memory_size);

    int i , k ;

    k = ((encdec_private_date *)(filp->private_data))->key;
    for(i = 0; i < count; i++)
    {
        temp[i] = (buf[i] + k) % 128;
    }

    k = copy_from_user ( caesar_Buf , temp , count);
    printk("write-> %d\n"  ,k);

    kfree(temp);
    return 0;
 }

这是代码的一部分

#include <linux/ctype.h>
#include <linux/config.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/proc_fs.h>
#include <linux/fcntl.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include <linux/string.h>

#include "encdec.h"

#define MODULE_NAME "encdec"

MODULE_LICENSE("GPL");
MODULE_AUTHOR("YOUR NAME");

int     encdec_open(struct inode *inode, struct file *filp);
int     encdec_release(struct inode *inode, struct file *filp);
int     encdec_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg);

ssize_t encdec_read_caesar( struct file *filp, char *buf, size_t count, loff_t *f_pos );
ssize_t encdec_write_caesar(struct file *filp, const char *buf, size_t count, loff_t *f_pos);



int memory_size = 0;

MODULE_PARM(memory_size, "i");

int major = 0;
char *caesar_Buf = NULL;


struct file_operations fops_caesar = {
    .open    =  encdec_open,
    .release =  encdec_release,
    .read    =  encdec_read_caesar,
    .write   =  encdec_write_caesar,
    .llseek  =  NULL,
    .ioctl   =  encdec_ioctl,
    .owner   =  THIS_MODULE
};


// Implemetation suggestion:
// -------------------------
// Use this structure as your file-object's private data structure
typedef struct {
    unsigned char key;
    int read_state;
} encdec_private_date;

int init_module(void)
{
    major = register_chrdev(major, MODULE_NAME, &fops_caesar);
    if(major < 0)
    {
        return major;
    }



    caesar_Buf = (char *)kmalloc(memory_size * sizeof(char),GFP_KERNEL);



    return 0;
}

1 个答案:

答案 0 :(得分:1)

您应该使用copy_from_user而不是直接访问buf(在循环内部,而不是访问temp(位于内核空间内存中)时)

copy_from_user旨在确保在用户上下文中进行的访问仅访问用户空间数据-即,有人不会在syscall中传递指向内核内存的指针并以某种方式从内核泄漏数据