PadLock AES Core Test module

Source: Internet
Author: User

First, brief

A verification module for testing the padlock AES kernel interface is written. encrypted decryption is implemented using the PadLock AES kernel interface. This paper provides the method, procedure, principle and source code for applying the module.

Second, the operating environment

Operating system

mint17

Kernel

3.8.0

Compiler

gcc4.7.3

Cpu

VIA Nano X2 L4530 @ 1.6+ GHz

Memory

4G

Multi-core

2 x

Three, the main principle

The Linux kernel has interfaces for cryptographic functions, primarily in the cryto folder directory. There are many algorithms such as AES,SHA , etc. to implement the interface. There are many articles on the web that introduce the Linux kernel's framework of cryptographic algorithms, and by reading the Linux kernel source code, you write an AES Kernel module of the core function library.

There are 4 main functions using the AES encryption Algorithm :

Crypto_blkcipher_setkey

Crypto_blkcipher_set_iv

Crypto_blkcipher_encrypt

Crypto_blkcipher_decrypt

Only these functions are properly configured, so you can use the AES Encryption Library of the Linux kernel properly . The usage of these functions is described below.

static inline int Crypto_blkcipher_setkey (struct crypto_blkcipher *tfm,

Const U8 *key, unsigned int keylen)

This function is primarily used to set the encryption keywordKey. Here you need to explain theAESHow to apply the algorithm, for the algorithm level,AESthroughKey (Key Words),IV (initialization Vector), encryption Mode (CBC/ECB/CFB/OFB, etc.),key-length (128/192/256)to determine the mode of encryption, according to different modes of the same plaintext encryption of ciphertext is not the same. Crypto_blkcipher_setkey ()function is to set itsKey. *keyis the secret key,Keylenis the secret key length (unit bytes can be selected -, -, +)

Here is the Crypto_blkcipher *tfm, struct This is the encryption context, it is always through the encryption,Crypto_blkcipher_setkey,crypto_blkcipher _set_iv are used to set the structure of TFM, which is the carrier of the encryption configuration.

struct Crypto_blkcipher {struct CRYPTO_TFM base;}; struct CRYPTO_TFM {u32 crt_flags;union {struct ABLKCIPHER_TFM ablkcipher;struct aead_tfm aead;struct blkcipher_tfm blkci Pher;struct cipher_tfm cipher;struct hash_tfm hash;struct compress_tfm compress;struct RNG_TFM rng; Crt_u;   Determine the algorithm pattern void (*exit) (struct CRYPTO_TFM *tfm); Exit Function struct Crypto_alg *__crt_alg;void *__crt_ctx[] crypto_minalign_attr;};

From the middle one.Unionand a bunch of them up there.#defineit can be seen from this structure can be scattered out of a groupXXX_TFM. Crypto_algcorrespondingCIPHER_TFM. The last parameter__crt_ctx[]is the algorithm context mentioned above. In other words, the algorithm context is followedTFMassigned together. FromTFM, we can getCTX. Linuxprovides a functioninline void *crypto_tfm_ctx (struct CRYPTO_TFM *tfm);to perform the conversion, the function is also<srcdir>/include/linux/crypto.hthe.

The crypto_blkcipher_set_iv function is described below

static inline void Crypto_blkcipher_set_iv (struct crypto_blkcipher *tfm,

Const U8 *SRC, unsigned int len)

Its function is to set IV(initialization vector). src is the IV value,len is the length of IV,TFM is the same as the one described earlier.

The following describes the core cryptographic function Crypto_blkcipher_encrypt_iv:

static inline int crypto_blkcipher_encrypt (struct blkcipher_desc *desc,      struct scatterlist *dst,      struct Scatterlist *src,      unsigned int nbytes)

Its function is to implement encryption. Return 0 is correct and1 indicates an error. *desc is a cryptographic context structure, above Set_iv and set_key is used to set this Blkcipher_desc structure of the body,

The prototypes are:

struct BLKCIPHER_DESC {

struct Crypto_blkcipher *tfm;

void *info;

U32 flags;

};

where TFM is what we call the encryption context,info is typically used to store IV, because the block-encrypted hash sequence tool ( Scatterwalk) uses info as an IV directly at initialization time .

What is a hash sequence (scatterlist)? "1"

InLinuxin the kernel, there are three ways of dealing with peripherals:IO, ports, andDMA, this textbook is all about. WhichDMAWay is byDMAcontroller to control the data transfer between memory and peripherals. We know thatLinuxThere are three types of address space: virtual address, Physical address, and bus address. DMAa whole chunk of data is required to be distributed over a continuous bus address space for each transmission. andDMAis designed for transmitting large chunks of data, but large chunks of contiguous bus address space are often scarce. So when there is not that much contiguous space, you can only spread large chunks of data to as few small contiguous addresses as possible, and then letDMAthe controller passes all the data in one piece. SoLinuxThe kernel is designed specifically for a sequence called a hash set (scatterlist), the data structure of the small block of continuous bus address string up, giveDMAThe drive transmits automatically one after the other.

Plainly,scatterlist is a linear table (scatterlist can be a list or an array), each element contains a pointer to a contiguous block of memory for a bus address, which is DMA -tailored data structure.

Scatterlist structure struct Scatterlist {#ifdef config_debug_sgunsigned longsg_magic;     #endifunsigned Longpage_link;     which page unsigned intoffset;            The offset of the page unsigned intlength;           The length of the data is dma_addr_tdma_address; #ifdef config_need_sg_dma_lengthunsigned intdma_length; #endif};

Allocate space for Scatterwalk and set data utilization function in this article:

Sg_init_one().

Scatterwalk is the operation of physical memory, which facilitates the transmission of DMA. But much of what we do in the Linux kernel is the processing of virtual memory (which shows the data PRINTK), so we also need to apply Scatterwalk and it needs to be mapped to virtual memory to take advantage ( Kmap ), which is described in the following implementation program.

DST is the destination address,src is the original data,nbytes is the byte processed.

the prototype of the Crypto_blkcipher_decrypt function is:

static inline int crypto_blkcipher_decrypt (struct blkcipher_desc *desc,   struct scatterlist *dst,   struct Scatterlist *src,   unsigned int nbytes)

This function is decrypted, similar to cryptographic algorithm parameters, and is no longer described.

Iv. implementation of the source code

The main key functions are finished, the following combination of specific source code further analysis:

I implemented the Linux kernel module by compiling two files:tcrypt.c and Makefile. It can be done directly via make,doinstall .

TCRYPT.C: #include <linux/module.h> #include <linux/crypto.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/scatterlist.h> #include <linux/slab.h> #include <linux/highmem.h >static void My_test_cipher (void)///implement function {unsigned int ret;int i;/* must use an array, if you use *code this way will output incorrect data, also ask the gods to help answer */char CODE[17] = "1234567887654321"; char *key = "0123456789abcdef";//Key Keychar *iv = "1234567887654321";//set IV value struct Scatterlist sgd;//hash sequence, output struct scatterlist sgs;//hash sequence, input struct scatterlist sgl;//hash sequence, decrypt output char last_mem[ 17];char Dst_mem[17];char *out = Null;char *result = Null;char *src = null;struct crypto_blkcipher *tfm;struct blkcipher_d ESC Desc;memset (last_mem,0,17); memset (dst_mem,0,17);/* Allocates block encryption context CBC (AES) representation mode, or OFB (AES), usually the first parameter is 0, the third parameter represents the encryption mode, * /TFM = Crypto_alloc_blkcipher ("CBC (AES)", 0, Crypto_alg_async);d ESC.TFM = Tfm;desc.flags = 0;/* Sets the hash sequence, The data from the virtual memory in the Linux kernel is transferred to the hash sequence for the DMA application, where Dst_mem,code,last_mem is the value we set ourselves, followed by 16 for the length of the data */Sg_iniT_one (&sgd,dst_mem,16);        Sg_init_one (&sgs,code,16); Sg_init_one (&sgl,last_mem,16); Crypto_blkcipher_setkey (tfm,key,16);//Set Key Crypto_blkcipher_set_iv (tfm,iv,16 )///set iv/* to map the SGS (hash sequence, physical memory) to the virtual memory of the Linux kernel, in order that we can display its data */SRC = Kmap (Sg_page (&AMP;SGS)) +SGS.OFFSET;PRINTK ("the Orgin is\n "); for (i = 0; i < sgs.length;i++) {PRINTK ("%c\n ", Src[i]);} cryptographic ret = Crypto_blkcipher_encrypt (&desc,&sgd,&sgs,sgs.length), if (!ret) {PRINTK ("AES encrypt success***        \ n "); out = Kmap (Sg_page (&AMP;SGD)) +sgd.offset;        PRINTK ("The Encrypt is:\n");        for (i = 0;i<sgd.length;i++) {PRINTK ("%c\n", Out[i]);       }}ELSE{PRINTK ("The Encrypt is wrong\n"); return;}       Crypto_blkcipher_setkey (tfm,key,16);       Crypto_blkcipher_set_iv (tfm,iv,16);//decryption ret = Crypto_blkcipher_decrypt (&desc,&sgl,&sgd,sgd.length);                 if (!ret) {PRINTK (kern_info "HW Aes Decrypt is success\n"); result = KMAP (Sg_page (&AMP;SGL)) +sgl.offset;        for (i = 0; i < sgl.length;i++) {PRINTK ("%c\n", Result[i]);} }ELSE{PRINTK ("The Decrypt is wrong\n"); return;} Crypto_free_blkcipher (TFM); }static int __init tcrypt_mod_init (void) {my_test_cipher (); return 0;} /* * If an init function is provided, a exit function must also be provided * to allow module unload. */static void __exit Tcrypt_mod_fini (void) {}module_init (tcrypt_mod_init); Module_exit (Tcrypt_mod_fini);//MODULE_ Parm_desc (sec, "Length in seconds of the speed tests"//"(defaults to zero which uses CPU cycles instead)"); Module_license ("GPL"); Module_description ("Quick & Dirty Crypto Testing module"); Module_author ("Dachuan"); Makefile:koname = tcrypt.oiftest=$ (Shell lsmod | grep tcrypt | wc-l) Kerneldir: =/lib/modules/$ (Shell uname-r)/buildpwd : =$ (shell pwd) obj-m:=$ (koname) module:make-c $ (kerneldir) m=$ (PWD) test_install:ifeq ($ (iftest), 1) rmmod Tcryptinsmod Tcrypt.koelseinsmod Tcrypt.koendifinstaLl:test_install. Phony:install clean:rm *.o *.mod.c modules.order module.symvers. *.cmd *.korm-rf. tmp_versions

Five, the experiment

First enter the folder with tcrypt.c makefile :

Enter the command:

Make


Make install

View Linux kernel information using DMESG :


Reference documents

[1]http://blog.csdn.net/sonicling/article/details/6275898 Linux kernel block device encryption analysis


PadLock AES Core Test module

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.