cryptodev-linux-1.6/0000755000175100017510000000000012122420415013213 5ustar nmavnmavcryptodev-linux-1.6/README0000644000175100017510000000136012112103240014064 0ustar nmavnmavThis is a /dev/crypto device driver, equivalent to those in OpenBSD or FreeBSD. The main idea is to access of existing ciphers in kernel space from userspace, thus enabling re-use of a hardware implementation of a cipher. For questions and suggestions please use the mailing lists at: http://cryptodev-linux.org/lists.html === How to combine with cryptographic libraries === * GnuTLS: GnuTLS needs to be compiled with --enable-cryptodev in order to take advantage of /dev/crypto. GnuTLS 3.0.14 or later is recommended. * OpenSSL: The current releases of openssl support /dev/crypto by replacing eng_cryptodev.c with the version available in the extras subdirectory. In order to compile use the -DHAVE_CRYPTODEV -DUSE_CRYPTODEV_DIGESTS flags. cryptodev-linux-1.6/cryptodev_int.h0000644000175100017510000000673512102243276016276 0ustar nmavnmav/* cipher stuff */ #ifndef CRYPTODEV_INT_H # define CRYPTODEV_INT_H #include #include #include #include #include #include #include #include #include #include #include #define PFX "cryptodev: " #define dprintk(level, severity, format, a...) \ do { \ if (level <= cryptodev_verbosity) \ printk(severity PFX "%s[%u] (%s:%u): " format, \ current->comm, current->pid, \ __func__, __LINE__, \ ##a); \ } while (0) extern int cryptodev_verbosity; struct fcrypt { struct list_head list; struct mutex sem; }; /* compatibility stuff */ #ifdef CONFIG_COMPAT #include /* input of CIOCGSESSION */ struct compat_session_op { /* Specify either cipher or mac */ uint32_t cipher; /* cryptodev_crypto_op_t */ uint32_t mac; /* cryptodev_crypto_op_t */ uint32_t keylen; compat_uptr_t key; /* pointer to key data */ uint32_t mackeylen; compat_uptr_t mackey; /* pointer to mac key data */ uint32_t ses; /* session identifier */ }; /* input of CIOCCRYPT */ struct compat_crypt_op { uint32_t ses; /* session identifier */ uint16_t op; /* COP_ENCRYPT or COP_DECRYPT */ uint16_t flags; /* see COP_FLAG_* */ uint32_t len; /* length of source data */ compat_uptr_t src; /* source data */ compat_uptr_t dst; /* pointer to output data */ compat_uptr_t mac;/* pointer to output data for hash/MAC operations */ compat_uptr_t iv;/* initialization vector for encryption operations */ }; /* compat ioctls, defined for the above structs */ #define COMPAT_CIOCGSESSION _IOWR('c', 102, struct compat_session_op) #define COMPAT_CIOCCRYPT _IOWR('c', 104, struct compat_crypt_op) #define COMPAT_CIOCASYNCCRYPT _IOW('c', 107, struct compat_crypt_op) #define COMPAT_CIOCASYNCFETCH _IOR('c', 108, struct compat_crypt_op) #endif /* CONFIG_COMPAT */ /* kernel-internal extension to struct crypt_op */ struct kernel_crypt_op { struct crypt_op cop; int ivlen; __u8 iv[EALG_MAX_BLOCK_LEN]; int digestsize; uint8_t hash_output[AALG_MAX_RESULT_LEN]; struct task_struct *task; struct mm_struct *mm; }; struct kernel_crypt_auth_op { struct crypt_auth_op caop; int dst_len; /* based on src_len + pad + tag */ int ivlen; __u8 iv[EALG_MAX_BLOCK_LEN]; struct task_struct *task; struct mm_struct *mm; }; /* auth */ int kcaop_from_user(struct kernel_crypt_auth_op *kcop, struct fcrypt *fcr, void __user *arg); int kcaop_to_user(struct kernel_crypt_auth_op *kcaop, struct fcrypt *fcr, void __user *arg); int crypto_auth_run(struct fcrypt *fcr, struct kernel_crypt_auth_op *kcaop); int crypto_run(struct fcrypt *fcr, struct kernel_crypt_op *kcop); #include /* other internal structs */ struct csession { struct list_head entry; struct mutex sem; struct cipher_data cdata; struct hash_data hdata; uint32_t sid; uint32_t alignmask; unsigned int array_size; unsigned int used_pages; /* the number of pages that are used */ /* the number of pages marked as NOT-writable; they preceed writeables */ unsigned int readonly_pages; struct page **pages; struct scatterlist *sg; }; struct csession *crypto_get_session_by_sid(struct fcrypt *fcr, uint32_t sid); inline static void crypto_put_session(struct csession * ses_ptr) { mutex_unlock(&ses_ptr->sem); } int adjust_sg_array(struct csession * ses, int pagecount); #endif /* CRYPTODEV_INT_H */ cryptodev-linux-1.6/AUTHORS0000644000175100017510000000076412102243276014300 0ustar nmavnmavMichal Ludvig: Initial implementation for linux 2.6.8 Nikos Mavrogiannopoulos: Port to 2.6.27 and later, better compatibility with OpenBSD (and FreeBSD) cryptodev and maintanance. Michael Weiser: Porting to blkcipher async API. Several hardware drivers only implemented this API. Phil Sutter: Implemented a zero copy version of the internal engine. Dmitry Kasatkin: Multi-update support for hash calculation. Maintained by Nikos Mavrogiannopoulos (nmav [at] gnutls [dot] org) cryptodev-linux-1.6/version.h0000644000175100017510000000002612115015535015054 0ustar nmavnmav#define VERSION "1.6" cryptodev-linux-1.6/examples/0000755000175100017510000000000012102243276015037 5ustar nmavnmavcryptodev-linux-1.6/examples/sha.c0000644000175100017510000000547312102243276015767 0ustar nmavnmav/* * Demo on how to use /dev/crypto device for ciphering. * * Placed under public domain. * */ #include #include #include #include #include #include #include "sha.h" int sha_ctx_init(struct cryptodev_ctx* ctx, int cfd, const uint8_t *key, unsigned int key_size) { #ifdef CIOCGSESSINFO struct session_info_op siop; #endif memset(ctx, 0, sizeof(*ctx)); ctx->cfd = cfd; if (key == NULL) ctx->sess.mac = CRYPTO_SHA1; else { ctx->sess.mac = CRYPTO_SHA1_HMAC; ctx->sess.mackeylen = key_size; ctx->sess.mackey = (void*)key; } if (ioctl(ctx->cfd, CIOCGSESSION, &ctx->sess)) { perror("ioctl(CIOCGSESSION)"); return -1; } #ifdef CIOCGSESSINFO siop.ses = ctx->sess.ses; if (ioctl(ctx->cfd, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return -1; } printf("Got %s with driver %s\n", siop.hash_info.cra_name, siop.hash_info.cra_driver_name); if (!(siop.flags & SIOP_FLAG_KERNEL_DRIVER_ONLY)) { printf("Note: This is not an accelerated cipher\n"); } /*printf("Alignmask is %x\n", (unsigned int)siop.alignmask);*/ ctx->alignmask = siop.alignmask; #endif return 0; } void sha_ctx_deinit(struct cryptodev_ctx* ctx) { if (ioctl(ctx->cfd, CIOCFSESSION, &ctx->sess.ses)) { perror("ioctl(CIOCFSESSION)"); } } int sha_hash(struct cryptodev_ctx* ctx, const void* text, size_t size, void* digest) { struct crypt_op cryp; void* p; /* check text and ciphertext alignment */ if (ctx->alignmask) { p = (void*)(((unsigned long)text + ctx->alignmask) & ~ctx->alignmask); if (text != p) { fprintf(stderr, "text is not aligned\n"); return -1; } } memset(&cryp, 0, sizeof(cryp)); /* Encrypt data.in to data.encrypted */ cryp.ses = ctx->sess.ses; cryp.len = size; cryp.src = (void*)text; cryp.mac = digest; if (ioctl(ctx->cfd, CIOCCRYPT, &cryp)) { perror("ioctl(CIOCCRYPT)"); return -1; } return 0; } int main() { int cfd = -1, i; struct cryptodev_ctx ctx; uint8_t digest[20]; char text[] = "The quick brown fox jumps over the lazy dog"; uint8_t expected[] = "\x2f\xd4\xe1\xc6\x7a\x2d\x28\xfc\xed\x84\x9e\xe1\xbb\x76\xe7\x39\x1b\x93\xeb\x12"; /* Open the crypto device */ cfd = open("/dev/crypto", O_RDWR, 0); if (cfd < 0) { perror("open(/dev/crypto)"); return 1; } /* Set close-on-exec (not really neede here) */ if (fcntl(cfd, F_SETFD, 1) == -1) { perror("fcntl(F_SETFD)"); return 1; } sha_ctx_init(&ctx, cfd, NULL, 0); sha_hash(&ctx, text, strlen(text), digest); sha_ctx_deinit(&ctx); printf("digest: "); for (i = 0; i < 20; i++) { printf("%02x:", digest[i]); } printf("\n"); if (memcmp(digest, expected, 20) != 0) { fprintf(stderr, "SHA1 hashing failed\n"); return 1; } /* Close the original descriptor */ if (close(cfd)) { perror("close(cfd)"); return 1; } return 0; } cryptodev-linux-1.6/examples/aes-gcm.c0000644000175100017510000000633412102243276016525 0ustar nmavnmav/* * Demo on how to use /dev/crypto device for ciphering. * * Placed under public domain. * */ #include #include #include #include #include #include #include "aes-gcm.h" int aes_gcm_ctx_init(struct cryptodev_ctx* ctx, int cfd, const uint8_t *key, unsigned int key_size) { #ifdef CIOCGSESSINFO struct session_info_op siop; #endif memset(ctx, 0, sizeof(*ctx)); ctx->cfd = cfd; ctx->sess.cipher = CRYPTO_AES_GCM; ctx->sess.keylen = key_size; ctx->sess.key = (void*)key; if (ioctl(ctx->cfd, CIOCGSESSION, &ctx->sess)) { perror("ioctl(CIOCGSESSION)"); return -1; } #ifdef CIOCGSESSINFO siop.ses = ctx->sess.ses; if (ioctl(ctx->cfd, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return -1; } printf("Got %s with driver %s\n", siop.cipher_info.cra_name, siop.cipher_info.cra_driver_name); if (!(siop.flags & SIOP_FLAG_KERNEL_DRIVER_ONLY)) { printf("Note: This is not an accelerated cipher\n"); } /*printf("Alignmask is %x\n", (unsigned int)siop.alignmask); */ ctx->alignmask = siop.alignmask; #endif return 0; } void aes_gcm_ctx_deinit(struct cryptodev_ctx* ctx) { if (ioctl(ctx->cfd, CIOCFSESSION, &ctx->sess.ses)) { perror("ioctl(CIOCFSESSION)"); } } int aes_gcm_encrypt(struct cryptodev_ctx* ctx, const void* iv, const void* auth, size_t auth_size, const void* plaintext, void* ciphertext, size_t size) { struct crypt_auth_op cryp; void* p; /* check plaintext and ciphertext alignment */ if (ctx->alignmask) { p = (void*)(((unsigned long)plaintext + ctx->alignmask) & ~ctx->alignmask); if (plaintext != p) { fprintf(stderr, "plaintext is not aligned\n"); return -1; } p = (void*)(((unsigned long)ciphertext + ctx->alignmask) & ~ctx->alignmask); if (ciphertext != p) { fprintf(stderr, "ciphertext is not aligned\n"); return -1; } } memset(&cryp, 0, sizeof(cryp)); /* Encrypt data.in to data.encrypted */ cryp.ses = ctx->sess.ses; cryp.iv = (void*)iv; cryp.op = COP_ENCRYPT; cryp.auth_len = auth_size; cryp.auth_src = (void*)auth; cryp.len = size; cryp.src = (void*)plaintext; cryp.dst = ciphertext; if (ioctl(ctx->cfd, CIOCAUTHCRYPT, &cryp)) { perror("ioctl(CIOCAUTHCRYPT)"); return -1; } return 0; } int aes_gcm_decrypt(struct cryptodev_ctx* ctx, const void* iv, const void* auth, size_t auth_size, const void* ciphertext, void* plaintext, size_t size) { struct crypt_auth_op cryp; void* p; /* check plaintext and ciphertext alignment */ if (ctx->alignmask) { p = (void*)(((unsigned long)plaintext + ctx->alignmask) & ~ctx->alignmask); if (plaintext != p) { fprintf(stderr, "plaintext is not aligned\n"); return -1; } p = (void*)(((unsigned long)ciphertext + ctx->alignmask) & ~ctx->alignmask); if (ciphertext != p) { fprintf(stderr, "ciphertext is not aligned\n"); return -1; } } memset(&cryp, 0, sizeof(cryp)); /* Encrypt data.in to data.encrypted */ cryp.ses = ctx->sess.ses; cryp.iv = (void*)iv; cryp.op = COP_DECRYPT; cryp.auth_len = auth_size; cryp.auth_src = (void*)auth; cryp.len = size; cryp.src = (void*)ciphertext; cryp.dst = plaintext; if (ioctl(ctx->cfd, CIOCAUTHCRYPT, &cryp)) { perror("ioctl(CIOCAUTHCRYPT)"); return -1; } return 0; } cryptodev-linux-1.6/examples/aes.h0000644000175100017510000000100512102243276015754 0ustar nmavnmav#ifndef AES_H # define AES_H #include struct cryptodev_ctx { int cfd; struct session_op sess; uint16_t alignmask; }; #define AES_BLOCK_SIZE 16 int aes_ctx_init(struct cryptodev_ctx* ctx, int cfd, const uint8_t *key, unsigned int key_size); void aes_ctx_deinit(); int aes_encrypt(struct cryptodev_ctx* ctx, const void* iv, const void* plaintext, void* ciphertext, size_t size); int aes_decrypt(struct cryptodev_ctx* ctx, const void* iv, const void* ciphertext, void* plaintext, size_t size); #endif cryptodev-linux-1.6/examples/aes-sha1.h0000644000175100017510000000143412102243276016614 0ustar nmavnmav#ifndef AES_H # define AES_H #include struct cryptodev_ctx { int cfd; struct session_op sess; uint16_t alignmask; }; #define AES_BLOCK_SIZE 16 int aes_sha1_ctx_init(struct cryptodev_ctx* ctx, int cfd, const uint8_t *key, unsigned int key_size, const uint8_t *mac_key, unsigned int mac_key_size); void aes_sha1_ctx_deinit(); /* Note that encryption assumes that ciphertext has enough size * for the tag and padding to be appended. * * Only in-place encryption and decryption are supported. */ int aes_sha1_encrypt(struct cryptodev_ctx* ctx, const void* iv, const void* auth, size_t auth_size, void* plaintext, size_t size); int aes_sha1_decrypt(struct cryptodev_ctx* ctx, const void* iv, const void* auth, size_t auth_size, void* ciphertext, size_t size); #endif cryptodev-linux-1.6/examples/sha.h0000644000175100017510000000053412102243276015765 0ustar nmavnmav#ifndef SHA_H # define SHA_H #include struct cryptodev_ctx { int cfd; struct session_op sess; uint16_t alignmask; }; int sha_ctx_init(struct cryptodev_ctx* ctx, int cfd, const uint8_t *key, unsigned int key_size); void sha_ctx_deinit(); int sha_hash(struct cryptodev_ctx* ctx, const void* text, size_t size, void* digest); #endif cryptodev-linux-1.6/examples/aes-sha1.c0000644000175100017510000000620512102243276016610 0ustar nmavnmav/* * Demo on how to use /dev/crypto device for ciphering. * * Placed under public domain. * */ #include #include #include #include #include #include #include "aes-sha1.h" /* This is the TLS version of AES-CBC with HMAC-SHA1. */ int aes_sha1_ctx_init(struct cryptodev_ctx* ctx, int cfd, const uint8_t *key, unsigned int key_size, const uint8_t *mac_key, unsigned int mac_key_size) { #ifdef CIOCGSESSINFO struct session_info_op siop; #endif memset(ctx, 0, sizeof(*ctx)); ctx->cfd = cfd; ctx->sess.cipher = CRYPTO_AES_CBC; ctx->sess.keylen = key_size; ctx->sess.key = (void*)key; ctx->sess.mac = CRYPTO_SHA1_HMAC; ctx->sess.mackeylen = mac_key_size; ctx->sess.mackey = (void*)mac_key; if (ioctl(ctx->cfd, CIOCGSESSION, &ctx->sess)) { perror("ioctl(CIOCGSESSION)"); return -1; } #ifdef CIOCGSESSINFO siop.ses = ctx->sess.ses; if (ioctl(ctx->cfd, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return -1; } printf("Got %s with driver %s\n", siop.cipher_info.cra_name, siop.cipher_info.cra_driver_name); if (!(siop.flags & SIOP_FLAG_KERNEL_DRIVER_ONLY)) { printf("Note: This is not an accelerated cipher\n"); } /*printf("Alignmask is %x\n", (unsigned int)siop.alignmask); */ ctx->alignmask = siop.alignmask; #endif return 0; } void aes_sha1_ctx_deinit(struct cryptodev_ctx* ctx) { if (ioctl(ctx->cfd, CIOCFSESSION, &ctx->sess.ses)) { perror("ioctl(CIOCFSESSION)"); } } int aes_sha1_encrypt(struct cryptodev_ctx* ctx, const void* iv, const void* auth, size_t auth_size, void* plaintext, size_t size) { struct crypt_auth_op cryp; void* p; /* check plaintext and ciphertext alignment */ if (ctx->alignmask) { p = (void*)(((unsigned long)plaintext + ctx->alignmask) & ~ctx->alignmask); if (plaintext != p) { fprintf(stderr, "plaintext is not aligned\n"); return -1; } } memset(&cryp, 0, sizeof(cryp)); /* Encrypt data.in to data.encrypted */ cryp.ses = ctx->sess.ses; cryp.iv = (void*)iv; cryp.op = COP_ENCRYPT; cryp.auth_len = auth_size; cryp.auth_src = (void*)auth; cryp.len = size; cryp.src = (void*)plaintext; cryp.dst = plaintext; cryp.flags = COP_FLAG_AEAD_TLS_TYPE; if (ioctl(ctx->cfd, CIOCAUTHCRYPT, &cryp)) { perror("ioctl(CIOCAUTHCRYPT)"); return -1; } return 0; } int aes_sha1_decrypt(struct cryptodev_ctx* ctx, const void* iv, const void* auth, size_t auth_size, void* ciphertext, size_t size) { struct crypt_auth_op cryp; void* p; /* check plaintext and ciphertext alignment */ if (ctx->alignmask) { p = (void*)(((unsigned long)ciphertext + ctx->alignmask) & ~ctx->alignmask); if (ciphertext != p) { fprintf(stderr, "ciphertext is not aligned\n"); return -1; } } memset(&cryp, 0, sizeof(cryp)); /* Encrypt data.in to data.encrypted */ cryp.ses = ctx->sess.ses; cryp.iv = (void*)iv; cryp.op = COP_DECRYPT; cryp.auth_len = auth_size; cryp.auth_src = (void*)auth; cryp.len = size; cryp.src = (void*)ciphertext; cryp.dst = ciphertext; cryp.flags = COP_FLAG_AEAD_TLS_TYPE; if (ioctl(ctx->cfd, CIOCAUTHCRYPT, &cryp)) { perror("ioctl(CIOCAUTHCRYPT)"); return -1; } return 0; } cryptodev-linux-1.6/examples/aes.c0000644000175100017510000001332312102243276015755 0ustar nmavnmav/* * Demo on how to use /dev/crypto device for ciphering. * * Placed under public domain. * */ #include #include #include #include #include #include #include "aes.h" #define KEY_SIZE 16 int aes_ctx_init(struct cryptodev_ctx* ctx, int cfd, const uint8_t *key, unsigned int key_size) { #ifdef CIOCGSESSINFO struct session_info_op siop; #endif memset(ctx, 0, sizeof(*ctx)); ctx->cfd = cfd; ctx->sess.cipher = CRYPTO_AES_CBC; ctx->sess.keylen = key_size; ctx->sess.key = (void*)key; if (ioctl(ctx->cfd, CIOCGSESSION, &ctx->sess)) { perror("ioctl(CIOCGSESSION)"); return -1; } #ifdef CIOCGSESSINFO memset(&siop, 0, sizeof(siop)); siop.ses = ctx->sess.ses; if (ioctl(ctx->cfd, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return -1; } printf("Got %s with driver %s\n", siop.cipher_info.cra_name, siop.cipher_info.cra_driver_name); if (!(siop.flags & SIOP_FLAG_KERNEL_DRIVER_ONLY)) { printf("Note: This is not an accelerated cipher\n"); } /*printf("Alignmask is %x\n", (unsigned int)siop.alignmask); */ ctx->alignmask = siop.alignmask; #endif return 0; } void aes_ctx_deinit(struct cryptodev_ctx* ctx) { if (ioctl(ctx->cfd, CIOCFSESSION, &ctx->sess.ses)) { perror("ioctl(CIOCFSESSION)"); } } int aes_encrypt(struct cryptodev_ctx* ctx, const void* iv, const void* plaintext, void* ciphertext, size_t size) { struct crypt_op cryp; void* p; /* check plaintext and ciphertext alignment */ if (ctx->alignmask) { p = (void*)(((unsigned long)plaintext + ctx->alignmask) & ~ctx->alignmask); if (plaintext != p) { fprintf(stderr, "plaintext is not aligned\n"); return -1; } p = (void*)(((unsigned long)ciphertext + ctx->alignmask) & ~ctx->alignmask); if (ciphertext != p) { fprintf(stderr, "ciphertext is not aligned\n"); return -1; } } memset(&cryp, 0, sizeof(cryp)); /* Encrypt data.in to data.encrypted */ cryp.ses = ctx->sess.ses; cryp.len = size; cryp.src = (void*)plaintext; cryp.dst = ciphertext; cryp.iv = (void*)iv; cryp.op = COP_ENCRYPT; if (ioctl(ctx->cfd, CIOCCRYPT, &cryp)) { perror("ioctl(CIOCCRYPT)"); return -1; } return 0; } int aes_decrypt(struct cryptodev_ctx* ctx, const void* iv, const void* ciphertext, void* plaintext, size_t size) { struct crypt_op cryp; void* p; /* check plaintext and ciphertext alignment */ if (ctx->alignmask) { p = (void*)(((unsigned long)plaintext + ctx->alignmask) & ~ctx->alignmask); if (plaintext != p) { fprintf(stderr, "plaintext is not aligned\n"); return -1; } p = (void*)(((unsigned long)ciphertext + ctx->alignmask) & ~ctx->alignmask); if (ciphertext != p) { fprintf(stderr, "ciphertext is not aligned\n"); return -1; } } memset(&cryp, 0, sizeof(cryp)); /* Encrypt data.in to data.encrypted */ cryp.ses = ctx->sess.ses; cryp.len = size; cryp.src = (void*)ciphertext; cryp.dst = plaintext; cryp.iv = (void*)iv; cryp.op = COP_DECRYPT; if (ioctl(ctx->cfd, CIOCCRYPT, &cryp)) { perror("ioctl(CIOCCRYPT)"); return -1; } return 0; } static int test_aes(int cfd) { char plaintext1_raw[AES_BLOCK_SIZE + 63], *plaintext1; char ciphertext1[AES_BLOCK_SIZE] = { 0xdf, 0x55, 0x6a, 0x33, 0x43, 0x8d, 0xb8, 0x7b, 0xc4, 0x1b, 0x17, 0x52, 0xc5, 0x5e, 0x5e, 0x49 }; char iv1[AES_BLOCK_SIZE]; uint8_t key1[KEY_SIZE] = { 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; char plaintext2_data[AES_BLOCK_SIZE] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00 }; char plaintext2_raw[AES_BLOCK_SIZE + 63], *plaintext2; char ciphertext2[AES_BLOCK_SIZE] = { 0xb7, 0x97, 0x2b, 0x39, 0x41, 0xc4, 0x4b, 0x90, 0xaf, 0xa7, 0xb2, 0x64, 0xbf, 0xba, 0x73, 0x87 }; char iv2[AES_BLOCK_SIZE]; uint8_t key2[KEY_SIZE]; struct cryptodev_ctx ctx; aes_ctx_init(&ctx, cfd, key1, sizeof(key1)); if (ctx.alignmask) plaintext1 = (char *)(((unsigned long)plaintext1_raw + ctx.alignmask) & ~ctx.alignmask); else plaintext1 = plaintext1_raw; memset(plaintext1, 0x0, AES_BLOCK_SIZE); memset(iv1, 0x0, sizeof(iv1)); aes_encrypt(&ctx, iv1, plaintext1, plaintext1, AES_BLOCK_SIZE); /* Verify the result */ if (memcmp(plaintext1, ciphertext1, AES_BLOCK_SIZE) != 0) { fprintf(stderr, "FAIL: Decrypted data are different from the input data.\n"); return -1; } aes_ctx_deinit(&ctx); /* Test 2 */ memset(key2, 0x0, sizeof(key2)); memset(iv2, 0x0, sizeof(iv2)); aes_ctx_init(&ctx, cfd, key2, sizeof(key2)); if (ctx.alignmask) { plaintext2 = (char *)(((unsigned long)plaintext2_raw + ctx.alignmask) & ~ctx.alignmask); } else { plaintext2 = plaintext2_raw; } memcpy(plaintext2, plaintext2_data, AES_BLOCK_SIZE); /* Encrypt data.in to data.encrypted */ aes_encrypt(&ctx, iv2, plaintext2, plaintext2, AES_BLOCK_SIZE); /* Verify the result */ if (memcmp(plaintext2, ciphertext2, AES_BLOCK_SIZE) != 0) { int i; fprintf(stderr, "FAIL: Decrypted data are different from the input data.\n"); printf("plaintext:"); for (i = 0; i < AES_BLOCK_SIZE; i++) { printf("%02x ", plaintext2[i]); } printf("ciphertext:"); for (i = 0; i < AES_BLOCK_SIZE; i++) { printf("%02x ", ciphertext2[i]); } printf("\n"); return 1; } aes_ctx_deinit(&ctx); printf("AES Test passed\n"); return 0; } int main() { int cfd = -1; /* Open the crypto device */ cfd = open("/dev/crypto", O_RDWR, 0); if (cfd < 0) { perror("open(/dev/crypto)"); return 1; } /* Set close-on-exec (not really neede here) */ if (fcntl(cfd, F_SETFD, 1) == -1) { perror("fcntl(F_SETFD)"); return 1; } /* Run the test itself */ if (test_aes(cfd)) return 1; /* Close the original descriptor */ if (close(cfd)) { perror("close(cfd)"); return 1; } return 0; } cryptodev-linux-1.6/examples/aes-gcm.h0000644000175100017510000000141712102243276016527 0ustar nmavnmav#ifndef AES_H # define AES_H #include struct cryptodev_ctx { int cfd; struct session_op sess; uint16_t alignmask; }; #define AES_BLOCK_SIZE 16 int aes_gcm_ctx_init(struct cryptodev_ctx* ctx, int cfd, const uint8_t *key, unsigned int key_size); void aes_gcm_ctx_deinit(); /* Note that encryption assumes that ciphertext has enough size * for the tag to be appended. In decryption the tag is assumed * to be the last bytes of ciphertext. */ int aes_gcm_encrypt(struct cryptodev_ctx* ctx, const void* iv, const void* auth, size_t auth_size, const void* plaintext, void* ciphertext, size_t size); int aes_gcm_decrypt(struct cryptodev_ctx* ctx, const void* iv, const void* auth, size_t auth_size, const void* ciphertext, void* plaintext, size_t size); #endif cryptodev-linux-1.6/NEWS0000644000175100017510000000662512122420354013725 0ustar nmavnmavVersion 1.6 (released 2013-03-20) * Added modules_install target in Makefile * Added SHA224. Patch by Yashpal Dutta. * Asynchronous operations will not be scheduled if zero copy is disabled. * Asynchronous operations are disabled by default, unless -DENABLE_ASYNC is enabled on Makefile. Version 1.5 (released 2012-08-04) * Fixes in AEAD support. Patches by Jaren Johnston. * Simplifications in memory locking. Patch by Phil Sutter. * Allow empty plaintext and authenticated data in AEAD ciphers. Patch by Jaren Johnston. Version 1.4 (released 2012-03-15) * Correctly report hw accelerated ciphers. Version 1.3 (released 2012-02-29) * Return EBADMSG instead of ECANCELED on tag verification failure in authenc modes. * COP_FLAG_RESET can be combined with COP_FLAG_UPDATE for efficiency. * Added more test cases. * Automatically set public permissions for the device Version 1.2 (released 2012-02-24) * In kernels that do not distinguish between hw accelerated ciphers or not set the SIOP_FLAG_KERNEL_DRIVER_ONLY flag based on driver name. * camelia was renamed to camellia. * Added COP_FLAG_RESET to allow resetting the state in multi-update. * Corrected issue in ARM processors with mv_cesa. Version 1.1 (released 2012-02-20) * Fixed alignment issue in speed.c * Defined HASH_MAX_LEN in cryptodev.h * CIOCGSESSINFO ioctl() sets the SIOP_FLAG_KERNEL_DRIVER_ONLY flag if the driver is only available through kernel driver (and is not just software cipher). * Added new encryption ioctl, CIOCAUTHCRYPT, which combines authentication and encryption. Operates in AEAD, TLS and SRTP modes (the API might change in later versions). Version 1.0 (released 2011-04-12) * Several fixes in the included examples. Based on patches by Vladimir Zapolskiy. Version 0.9 (released 2011-02-11) * Added additional test tools: - sha_speed does performance testing of SHA1 and SHA256 - hashcrypt_speed additionally encrypts with AES128 and AES256 * Allow updating the IV in userspace via the COP_FLAG_WRITE_IV flag. * Export the alignmask in an OCF compatible way. * Fix for kernel crash on passing incorrect session ID. * Added CIOCGSESSINFO to export additional information for each session. Version 0.8 (released 2010-11-06) * Made cryptodev aware of alignment constraints. * Added support for CRYPTO_AES_ECB. * Added asynchronous operation support using CIOCASYNCCRYPT, CIOCASYNCFETCH ioctls and poll(). Version 0.7 (released 2010-10-08) * Added COP_FLAG_FINAL to make multi-update more efficient. * Added CRIOGET_NOT_NEEDED definition to allow users of the API to distinguish from the bare OpenBSD API that requires the CRIOGET. Version 0.6 (released 2010-09-16) * multi-update support for hash calculation using the new flag COP_FLAG_UPDATE. * Relicensed under GPLv2. * Added AES-CTR. * Corrected fallback to non-zero copy when referenced pages were not writable. Version 0.5 (released 2010-07-06) * Corrected issue with zero copy on multiple pages. * Fallback to normal operation if user pages cannot be mapped. Version 0.4 (released 2010-07-03) * Internal engine supports operations with zero copy from user space. Version 0.3 (released 2010-06-19) * Corrected bug when initializing unsupported algorithms. Version 0.2 (released 2010-06-18) * Added compat_ioctl() to allow working on systems where userspace is 32bits and kernel is operating in 64bit mode (Phil Sutter) * Added several sanity checks to input. cryptodev-linux-1.6/zc.c0000644000175100017510000001410012102243276013775 0ustar nmavnmav/* * Driver for /dev/crypto device (aka CryptoDev) * * Copyright (c) 2009-2011 Nikos Mavrogiannopoulos * Copyright (c) 2010 Phil Sutter * Copyright (c) 2011, 2012 OpenSSL Software Foundation, Inc. * * This file is part of linux cryptodev. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include "cryptodev_int.h" #include "zc.h" #include "version.h" /* Helper functions to assist zero copy. * This needs to be redesigned and moved out of the session. --nmav */ /* offset of buf in it's first page */ #define PAGEOFFSET(buf) ((unsigned long)buf & ~PAGE_MASK) /* fetch the pages addr resides in into pg and initialise sg with them */ int __get_userbuf(uint8_t __user *addr, uint32_t len, int write, unsigned int pgcount, struct page **pg, struct scatterlist *sg, struct task_struct *task, struct mm_struct *mm) { int ret, pglen, i = 0; struct scatterlist *sgp; if (unlikely(!pgcount || !len || !addr)) { sg_mark_end(sg); return 0; } down_read(&mm->mmap_sem); ret = get_user_pages(task, mm, (unsigned long)addr, pgcount, write, 0, pg, NULL); up_read(&mm->mmap_sem); if (ret != pgcount) return -EINVAL; sg_init_table(sg, pgcount); pglen = min((ptrdiff_t)(PAGE_SIZE - PAGEOFFSET(addr)), (ptrdiff_t)len); sg_set_page(sg, pg[i++], pglen, PAGEOFFSET(addr)); len -= pglen; for (sgp = sg_next(sg); len; sgp = sg_next(sgp)) { pglen = min((uint32_t)PAGE_SIZE, len); sg_set_page(sgp, pg[i++], pglen, 0); len -= pglen; } sg_mark_end(sg_last(sg, pgcount)); return 0; } int adjust_sg_array(struct csession * ses, int pagecount) { struct scatterlist *sg; struct page **pages; int array_size; for (array_size = ses->array_size; array_size < pagecount; array_size *= 2) ; dprintk(0, KERN_DEBUG, "reallocating from %d to %d pages\n", ses->array_size, array_size); pages = krealloc(ses->pages, array_size * sizeof(struct page *), GFP_KERNEL); if (unlikely(!pages)) return -ENOMEM; ses->pages = pages; sg = krealloc(ses->sg, array_size * sizeof(struct scatterlist), GFP_KERNEL); if (unlikely(!sg)) return -ENOMEM; ses->sg = sg; ses->array_size = array_size; return 0; } void release_user_pages(struct csession *ses) { unsigned int i; for (i=0;iused_pages;i++) { if (!PageReserved(ses->pages[i])) SetPageDirty(ses->pages[i]); if (ses->readonly_pages == 0) flush_dcache_page(ses->pages[i]); else ses->readonly_pages--; page_cache_release(ses->pages[i]); } ses->used_pages = 0; } /* make src and dst available in scatterlists. * dst might be the same as src. */ int get_userbuf(struct csession *ses, void* __user src, unsigned int src_len, void* __user dst, unsigned int dst_len, struct task_struct *task, struct mm_struct *mm, struct scatterlist **src_sg, struct scatterlist **dst_sg) { int src_pagecount, dst_pagecount; int rc; /* Empty input is a valid option to many algorithms & is tested by NIST/FIPS */ /* Make sure NULL input has 0 length */ if (!src && src_len) src_len = 0; /* I don't know that null output is ever useful, but we can handle it gracefully */ /* Make sure NULL output has 0 length */ if (!dst && dst_len) dst_len = 0; if (ses->alignmask && !IS_ALIGNED((unsigned long)src, ses->alignmask)) { dprintk(2, KERN_WARNING, "careful - source address %lx is not %d byte aligned\n", (unsigned long)src, ses->alignmask + 1); } if (ses->alignmask && !IS_ALIGNED((unsigned long)dst, ses->alignmask)) { dprintk(2, KERN_WARNING, "careful - destination address %lx is not %d byte aligned\n", (unsigned long)dst, ses->alignmask + 1); } src_pagecount = PAGECOUNT(src, src_len); dst_pagecount = PAGECOUNT(dst, dst_len); ses->used_pages = (src == dst) ? max(src_pagecount, dst_pagecount) : src_pagecount + dst_pagecount; ses->readonly_pages = (src == dst) ? 0 : src_pagecount; if (ses->used_pages > ses->array_size) { rc = adjust_sg_array(ses, ses->used_pages); if (rc) return rc; } if (src == dst) { /* inplace operation */ rc = __get_userbuf(src, src_len, 1, ses->used_pages, ses->pages, ses->sg, task, mm); if (unlikely(rc)) { dprintk(1, KERN_ERR, "failed to get user pages for data IO\n"); return rc; } (*src_sg) = (*dst_sg) = ses->sg; return 0; } *src_sg = NULL; // default to no input *dst_sg = NULL; // default to ignore output if(likely(src)) { rc = __get_userbuf(src, src_len, 0, ses->readonly_pages, ses->pages, ses->sg, task, mm); if (unlikely(rc)) { dprintk(1, KERN_ERR, "failed to get user pages for data input\n"); return rc; } *src_sg = ses->sg; } if(likely(dst)) { const unsigned int writable_pages = ses->used_pages - ses->readonly_pages; struct page **dst_pages = ses->pages + ses->readonly_pages; *dst_sg = ses->sg + ses->readonly_pages; rc = __get_userbuf(dst, dst_len, 1, writable_pages, dst_pages, *dst_sg, task, mm); if (unlikely(rc)) { dprintk(1, KERN_ERR, "failed to get user pages for data output\n"); release_user_pages(ses); /* FIXME: use __release_userbuf(src, ...) */ return rc; } } return 0; } cryptodev-linux-1.6/COPYING0000644000175100017510000004325412102243276014264 0ustar nmavnmav GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. cryptodev-linux-1.6/main.c0000644000175100017510000001477212102243276014324 0ustar nmavnmav/* * Driver for /dev/crypto device (aka CryptoDev) * * Copyright (c) 2004 Michal Ludvig , SuSE Labs * Copyright (c) 2009,2010 Nikos Mavrogiannopoulos * * This file is part of linux cryptodev. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * Device /dev/crypto provides an interface for * accessing kernel CryptoAPI algorithms (ciphers, * hashes) from userspace programs. * * /dev/crypto interface was originally introduced in * OpenBSD and this module attempts to keep the API. * */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "cryptodev_int.h" #include "zc.h" #include "cryptlib.h" #include "version.h" /* This file contains the traditional operations of encryption * and hashing of /dev/crypto. */ static int hash_n_crypt(struct csession *ses_ptr, struct crypt_op *cop, struct scatterlist *src_sg, struct scatterlist *dst_sg, uint32_t len) { int ret; /* Always hash before encryption and after decryption. Maybe * we should introduce a flag to switch... TBD later on. */ if (cop->op == COP_ENCRYPT) { if (ses_ptr->hdata.init != 0) { ret = cryptodev_hash_update(&ses_ptr->hdata, src_sg, len); if (unlikely(ret)) goto out_err; } if (ses_ptr->cdata.init != 0) { ret = cryptodev_cipher_encrypt(&ses_ptr->cdata, src_sg, dst_sg, len); if (unlikely(ret)) goto out_err; } } else { if (ses_ptr->cdata.init != 0) { ret = cryptodev_cipher_decrypt(&ses_ptr->cdata, src_sg, dst_sg, len); if (unlikely(ret)) goto out_err; } if (ses_ptr->hdata.init != 0) { ret = cryptodev_hash_update(&ses_ptr->hdata, dst_sg, len); if (unlikely(ret)) goto out_err; } } return 0; out_err: dprintk(0, KERN_ERR, "CryptoAPI failure: %d\n", ret); return ret; } /* This is the main crypto function - feed it with plaintext and get a ciphertext (or vice versa :-) */ static int __crypto_run_std(struct csession *ses_ptr, struct crypt_op *cop) { char *data; char __user *src, *dst; struct scatterlist sg; size_t nbytes, bufsize; int ret = 0; nbytes = cop->len; data = (char *)__get_free_page(GFP_KERNEL); if (unlikely(!data)) { dprintk(1, KERN_ERR, "Error getting free page.\n"); return -ENOMEM; } bufsize = PAGE_SIZE < nbytes ? PAGE_SIZE : nbytes; src = cop->src; dst = cop->dst; while (nbytes > 0) { size_t current_len = nbytes > bufsize ? bufsize : nbytes; if (unlikely(copy_from_user(data, src, current_len))) { dprintk(1, KERN_ERR, "Error copying %d bytes from user address %p.\n", (int)current_len, src); ret = -EFAULT; break; } sg_init_one(&sg, data, current_len); ret = hash_n_crypt(ses_ptr, cop, &sg, &sg, current_len); if (unlikely(ret)) { dprintk(1, KERN_ERR, "hash_n_crypt failed.\n"); break; } if (ses_ptr->cdata.init != 0) { if (unlikely(copy_to_user(dst, data, current_len))) { dprintk(1, KERN_ERR, "could not copy to user.\n"); ret = -EFAULT; break; } } dst += current_len; nbytes -= current_len; src += current_len; } free_page((unsigned long)data); return ret; } /* This is the main crypto function - zero-copy edition */ static int __crypto_run_zc(struct csession *ses_ptr, struct kernel_crypt_op *kcop) { struct scatterlist *src_sg, *dst_sg; struct crypt_op *cop = &kcop->cop; int ret = 0; ret = get_userbuf(ses_ptr, cop->src, cop->len, cop->dst, cop->len, kcop->task, kcop->mm, &src_sg, &dst_sg); if (unlikely(ret)) { dprintk(1, KERN_ERR, "Error getting user pages. " "Falling back to non zero copy.\n"); return __crypto_run_std(ses_ptr, cop); } ret = hash_n_crypt(ses_ptr, cop, src_sg, dst_sg, cop->len); release_user_pages(ses_ptr); return ret; } int crypto_run(struct fcrypt *fcr, struct kernel_crypt_op *kcop) { struct csession *ses_ptr; struct crypt_op *cop = &kcop->cop; int ret; if (unlikely(cop->op != COP_ENCRYPT && cop->op != COP_DECRYPT)) { dprintk(1, KERN_DEBUG, "invalid operation op=%u\n", cop->op); return -EINVAL; } /* this also enters ses_ptr->sem */ ses_ptr = crypto_get_session_by_sid(fcr, cop->ses); if (unlikely(!ses_ptr)) { dprintk(1, KERN_ERR, "invalid session ID=0x%08X\n", cop->ses); return -EINVAL; } if (ses_ptr->hdata.init != 0 && (cop->flags == 0 || cop->flags & COP_FLAG_RESET)) { ret = cryptodev_hash_reset(&ses_ptr->hdata); if (unlikely(ret)) { dprintk(1, KERN_ERR, "error in cryptodev_hash_reset()\n"); goto out_unlock; } } if (ses_ptr->cdata.init != 0) { int blocksize = ses_ptr->cdata.blocksize; if (unlikely(cop->len % blocksize)) { dprintk(1, KERN_ERR, "data size (%u) isn't a multiple " "of block size (%u)\n", cop->len, blocksize); ret = -EINVAL; goto out_unlock; } cryptodev_cipher_set_iv(&ses_ptr->cdata, kcop->iv, min(ses_ptr->cdata.ivsize, kcop->ivlen)); } if (likely(cop->len)) { if (cop->flags & COP_FLAG_NO_ZC) ret = __crypto_run_std(ses_ptr, &kcop->cop); else ret = __crypto_run_zc(ses_ptr, kcop); if (unlikely(ret)) goto out_unlock; } if (ses_ptr->cdata.init != 0) { cryptodev_cipher_get_iv(&ses_ptr->cdata, kcop->iv, min(ses_ptr->cdata.ivsize, kcop->ivlen)); } if (ses_ptr->hdata.init != 0 && ((cop->flags & COP_FLAG_FINAL) || (!(cop->flags & COP_FLAG_UPDATE) || cop->len == 0))) { ret = cryptodev_hash_final(&ses_ptr->hdata, kcop->hash_output); if (unlikely(ret)) { dprintk(0, KERN_ERR, "CryptoAPI failure: %d\n", ret); goto out_unlock; } kcop->digestsize = ses_ptr->hdata.digestsize; } out_unlock: crypto_put_session(ses_ptr); return ret; } cryptodev-linux-1.6/extras/0000755000175100017510000000000012114365576014542 5ustar nmavnmavcryptodev-linux-1.6/extras/eng_cryptodev.c0000644000175100017510000011127412114365576017564 0ustar nmavnmav/* * Copyright (c) 2002 Bob Beck * Copyright (c) 2002 Theo de Raadt * Copyright (c) 2002 Markus Friedl * Copyright (c) 2012 Nikos Mavrogiannopoulos * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include #include #include #include #if (defined(__unix__) || defined(unix)) && !defined(USG) && \ (defined(OpenBSD) || defined(__FreeBSD__)) #include # if (OpenBSD >= 200112) || ((__FreeBSD_version >= 470101 && __FreeBSD_version < 500000) || __FreeBSD_version >= 500041) # define HAVE_CRYPTODEV # endif # if (OpenBSD >= 200110) # define HAVE_SYSLOG_R # endif #endif #ifndef HAVE_CRYPTODEV void ENGINE_load_cryptodev(void) { /* This is a NOP on platforms without /dev/crypto */ return; } #else #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include struct dev_crypto_state { struct session_op d_sess; int d_fd; #ifdef USE_CRYPTODEV_DIGESTS unsigned char digest_res[HASH_MAX_LEN]; char *mac_data; int mac_len; #endif }; static u_int32_t cryptodev_asymfeat = 0; static int get_asym_dev_crypto(void); static int open_dev_crypto(void); static int get_dev_crypto(void); static int get_cryptodev_ciphers(const int **cnids); #ifdef USE_CRYPTODEV_DIGESTS static int get_cryptodev_digests(const int **cnids); #endif static int cryptodev_usable_ciphers(const int **nids); static int cryptodev_usable_digests(const int **nids); static int cryptodev_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl); static int cryptodev_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); static int cryptodev_cleanup(EVP_CIPHER_CTX *ctx); static int cryptodev_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid); static int cryptodev_engine_digests(ENGINE *e, const EVP_MD **digest, const int **nids, int nid); static int bn2crparam(const BIGNUM *a, struct crparam *crp); static int crparam2bn(struct crparam *crp, BIGNUM *a); static void zapparams(struct crypt_kop *kop); static int cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r, int slen, BIGNUM *s); static int cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); static int cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx); static int cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx); static int cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); static int cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g, BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2, BIGNUM *p, BN_CTX *ctx, BN_MONT_CTX *mont); static DSA_SIG *cryptodev_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa); static int cryptodev_dsa_verify(const unsigned char *dgst, int dgst_len, DSA_SIG *sig, DSA *dsa); static int cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx); static int cryptodev_dh_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh); static int cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)); void ENGINE_load_cryptodev(void); static const ENGINE_CMD_DEFN cryptodev_defns[] = { { 0, NULL, NULL, 0 } }; static struct { int id; int nid; int ivmax; int keylen; } ciphers[] = { { CRYPTO_ARC4, NID_rc4, 0, 16, }, { CRYPTO_DES_CBC, NID_des_cbc, 8, 8, }, { CRYPTO_3DES_CBC, NID_des_ede3_cbc, 8, 24, }, { CRYPTO_AES_CBC, NID_aes_128_cbc, 16, 16, }, { CRYPTO_AES_CBC, NID_aes_192_cbc, 16, 24, }, { CRYPTO_AES_CBC, NID_aes_256_cbc, 16, 32, }, { CRYPTO_BLF_CBC, NID_bf_cbc, 8, 16, }, { CRYPTO_CAST_CBC, NID_cast5_cbc, 8, 16, }, { CRYPTO_SKIPJACK_CBC, NID_undef, 0, 0, }, { 0, NID_undef, 0, 0, }, }; #ifdef USE_CRYPTODEV_DIGESTS static struct { int id; int nid; int digestlen; } digests[] = { #if 0 /* HMAC is not supported */ { CRYPTO_MD5_HMAC, NID_hmacWithMD5, 16}, { CRYPTO_SHA1_HMAC, NID_hmacWithSHA1, 20}, { CRYPTO_SHA2_256_HMAC, NID_hmacWithSHA256, 32}, { CRYPTO_SHA2_384_HMAC, NID_hmacWithSHA384, 48}, { CRYPTO_SHA2_512_HMAC, NID_hmacWithSHA512, 64}, #endif { CRYPTO_MD5, NID_md5, 16}, { CRYPTO_SHA1, NID_sha1, 20}, { CRYPTO_SHA2_256, NID_sha256, 32}, { CRYPTO_SHA2_384, NID_sha384, 48}, { CRYPTO_SHA2_512, NID_sha512, 64}, { 0, NID_undef, 0}, }; #endif /* * Return a fd if /dev/crypto seems usable, 0 otherwise. */ static int open_dev_crypto(void) { static int fd = -1; if (fd == -1) { if ((fd = open("/dev/crypto", O_RDWR, 0)) == -1) return (-1); /* close on exec */ if (fcntl(fd, F_SETFD, 1) == -1) { close(fd); fd = -1; return (-1); } } return (fd); } static int get_dev_crypto(void) { int fd, retfd; if ((fd = open_dev_crypto()) == -1) return (-1); #ifndef CRIOGET_NOT_NEEDED if (ioctl(fd, CRIOGET, &retfd) == -1) return (-1); /* close on exec */ if (fcntl(retfd, F_SETFD, 1) == -1) { close(retfd); return (-1); } #else retfd = fd; #endif return (retfd); } static void put_dev_crypto(int fd) { #ifndef CRIOGET_NOT_NEEDED close(fd); #endif } /* Caching version for asym operations */ static int get_asym_dev_crypto(void) { static int fd = -1; if (fd == -1) fd = get_dev_crypto(); return fd; } /* * Find out what ciphers /dev/crypto will let us have a session for. * XXX note, that some of these openssl doesn't deal with yet! * returning them here is harmless, as long as we return NULL * when asked for a handler in the cryptodev_engine_ciphers routine */ static int get_cryptodev_ciphers(const int **cnids) { static int nids[CRYPTO_ALGORITHM_MAX]; struct session_op sess; int fd, i, count = 0; unsigned char fake_key[CRYPTO_CIPHER_MAX_KEY_LEN]; if ((fd = get_dev_crypto()) < 0) { *cnids = NULL; return (0); } memset(&sess, 0, sizeof(sess)); sess.key = (void*)fake_key; for (i = 0; ciphers[i].id && count < CRYPTO_ALGORITHM_MAX; i++) { if (ciphers[i].nid == NID_undef) continue; sess.cipher = ciphers[i].id; sess.keylen = ciphers[i].keylen; sess.mac = 0; if (ioctl(fd, CIOCGSESSION, &sess) != -1 && ioctl(fd, CIOCFSESSION, &sess.ses) != -1) nids[count++] = ciphers[i].nid; } put_dev_crypto(fd); if (count > 0) *cnids = nids; else *cnids = NULL; return (count); } #ifdef USE_CRYPTODEV_DIGESTS /* * Find out what digests /dev/crypto will let us have a session for. * XXX note, that some of these openssl doesn't deal with yet! * returning them here is harmless, as long as we return NULL * when asked for a handler in the cryptodev_engine_digests routine */ static int get_cryptodev_digests(const int **cnids) { static int nids[CRYPTO_ALGORITHM_MAX]; unsigned char fake_key[CRYPTO_CIPHER_MAX_KEY_LEN]; struct session_op sess; int fd, i, count = 0; if ((fd = get_dev_crypto()) < 0) { *cnids = NULL; return (0); } memset(&sess, 0, sizeof(sess)); sess.mackey = fake_key; for (i = 0; digests[i].id && count < CRYPTO_ALGORITHM_MAX; i++) { if (digests[i].nid == NID_undef) continue; sess.mac = digests[i].id; sess.mackeylen = 8; sess.cipher = 0; if (ioctl(fd, CIOCGSESSION, &sess) != -1 && ioctl(fd, CIOCFSESSION, &sess.ses) != -1) nids[count++] = digests[i].nid; } put_dev_crypto(fd); if (count > 0) *cnids = nids; else *cnids = NULL; return (count); } #endif /* 0 */ /* * Find the useable ciphers|digests from dev/crypto - this is the first * thing called by the engine init crud which determines what it * can use for ciphers from this engine. We want to return * only what we can do, anythine else is handled by software. * * If we can't initialize the device to do anything useful for * any reason, we want to return a NULL array, and 0 length, * which forces everything to be done is software. By putting * the initalization of the device in here, we ensure we can * use this engine as the default, and if for whatever reason * /dev/crypto won't do what we want it will just be done in * software * * This can (should) be greatly expanded to perhaps take into * account speed of the device, and what we want to do. * (although the disabling of particular alg's could be controlled * by the device driver with sysctl's.) - this is where we * want most of the decisions made about what we actually want * to use from /dev/crypto. */ static int cryptodev_usable_ciphers(const int **nids) { return (get_cryptodev_ciphers(nids)); } static int cryptodev_usable_digests(const int **nids) { #ifdef USE_CRYPTODEV_DIGESTS return (get_cryptodev_digests(nids)); #else /* * XXXX just disable all digests for now, because it sucks. * we need a better way to decide this - i.e. I may not * want digests on slow cards like hifn on fast machines, * but might want them on slow or loaded machines, etc. * will also want them when using crypto cards that don't * suck moose gonads - would be nice to be able to decide something * as reasonable default without having hackery that's card dependent. * of course, the default should probably be just do everything, * with perhaps a sysctl to turn algoritms off (or have them off * by default) on cards that generally suck like the hifn. */ *nids = NULL; return (0); #endif } static int cryptodev_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { struct crypt_op cryp; struct dev_crypto_state *state = ctx->cipher_data; struct session_op *sess = &state->d_sess; const void *iiv; unsigned char save_iv[EVP_MAX_IV_LENGTH]; if (state->d_fd < 0) return (0); if (!inl) return (1); if ((inl % ctx->cipher->block_size) != 0) return (0); memset(&cryp, 0, sizeof(cryp)); cryp.ses = sess->ses; cryp.flags = 0; cryp.len = inl; cryp.src = (void*) in; cryp.dst = (void*) out; cryp.mac = 0; cryp.op = ctx->encrypt ? COP_ENCRYPT : COP_DECRYPT; if (ctx->cipher->iv_len) { cryp.iv = (void*) ctx->iv; if (!ctx->encrypt) { iiv = in + inl - ctx->cipher->iv_len; memcpy(save_iv, iiv, ctx->cipher->iv_len); } } else cryp.iv = NULL; if (ioctl(state->d_fd, CIOCCRYPT, &cryp) == -1) { /* XXX need better errror handling * this can fail for a number of different reasons. */ return (0); } if (ctx->cipher->iv_len) { if (ctx->encrypt) iiv = out + inl - ctx->cipher->iv_len; else iiv = save_iv; memcpy(ctx->iv, iiv, ctx->cipher->iv_len); } return (1); } static int cryptodev_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { struct dev_crypto_state *state = ctx->cipher_data; struct session_op *sess = &state->d_sess; int cipher = -1, i; for (i = 0; ciphers[i].id; i++) if (ctx->cipher->nid == ciphers[i].nid && ctx->cipher->iv_len <= ciphers[i].ivmax && ctx->key_len == ciphers[i].keylen) { cipher = ciphers[i].id; break; } if (!ciphers[i].id) { state->d_fd = -1; return (0); } memset(sess, 0, sizeof(struct session_op)); if ((state->d_fd = get_dev_crypto()) < 0) return (0); sess->key = (void*)key; sess->keylen = ctx->key_len; sess->cipher = cipher; if (ioctl(state->d_fd, CIOCGSESSION, sess) == -1) { put_dev_crypto(state->d_fd); state->d_fd = -1; return (0); } return (1); } /* * free anything we allocated earlier when initting a * session, and close the session. */ static int cryptodev_cleanup(EVP_CIPHER_CTX *ctx) { int ret = 0; struct dev_crypto_state *state = ctx->cipher_data; struct session_op *sess = &state->d_sess; if (state->d_fd < 0) return (0); /* XXX if this ioctl fails, someting's wrong. the invoker * may have called us with a bogus ctx, or we could * have a device that for whatever reason just doesn't * want to play ball - it's not clear what's right * here - should this be an error? should it just * increase a counter, hmm. For right now, we return * 0 - I don't believe that to be "right". we could * call the gorpy openssl lib error handlers that * print messages to users of the library. hmm.. */ if (ioctl(state->d_fd, CIOCFSESSION, &sess->ses) == -1) { ret = 0; } else { ret = 1; } put_dev_crypto(state->d_fd); state->d_fd = -1; return (ret); } /* * libcrypto EVP stuff - this is how we get wired to EVP so the engine * gets called when libcrypto requests a cipher NID. */ /* RC4 */ const EVP_CIPHER cryptodev_rc4 = { NID_rc4, 1, 16, 0, EVP_CIPH_VARIABLE_LENGTH, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), NULL, NULL, NULL }; /* DES CBC EVP */ const EVP_CIPHER cryptodev_des_cbc = { NID_des_cbc, 8, 8, 8, EVP_CIPH_CBC_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; /* 3DES CBC EVP */ const EVP_CIPHER cryptodev_3des_cbc = { NID_des_ede3_cbc, 8, 24, 8, EVP_CIPH_CBC_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; const EVP_CIPHER cryptodev_bf_cbc = { NID_bf_cbc, 8, 16, 8, EVP_CIPH_CBC_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; const EVP_CIPHER cryptodev_cast_cbc = { NID_cast5_cbc, 8, 16, 8, EVP_CIPH_CBC_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; const EVP_CIPHER cryptodev_aes_cbc = { NID_aes_128_cbc, 16, 16, 16, EVP_CIPH_CBC_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; const EVP_CIPHER cryptodev_aes_192_cbc = { NID_aes_192_cbc, 16, 24, 16, EVP_CIPH_CBC_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; const EVP_CIPHER cryptodev_aes_256_cbc = { NID_aes_256_cbc, 16, 32, 16, EVP_CIPH_CBC_MODE, cryptodev_init_key, cryptodev_cipher, cryptodev_cleanup, sizeof(struct dev_crypto_state), EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL }; /* * Registered by the ENGINE when used to find out how to deal with * a particular NID in the ENGINE. this says what we'll do at the * top level - note, that list is restricted by what we answer with */ static int cryptodev_engine_ciphers(ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid) { if (!cipher) return (cryptodev_usable_ciphers(nids)); switch (nid) { case NID_rc4: *cipher = &cryptodev_rc4; break; case NID_des_ede3_cbc: *cipher = &cryptodev_3des_cbc; break; case NID_des_cbc: *cipher = &cryptodev_des_cbc; break; case NID_bf_cbc: *cipher = &cryptodev_bf_cbc; break; case NID_cast5_cbc: *cipher = &cryptodev_cast_cbc; break; case NID_aes_128_cbc: *cipher = &cryptodev_aes_cbc; break; case NID_aes_192_cbc: *cipher = &cryptodev_aes_192_cbc; break; case NID_aes_256_cbc: *cipher = &cryptodev_aes_256_cbc; break; default: *cipher = NULL; break; } return (*cipher != NULL); } #ifdef USE_CRYPTODEV_DIGESTS /* convert digest type to cryptodev */ static int digest_nid_to_cryptodev(int nid) { int i; for (i = 0; digests[i].id; i++) if (digests[i].nid == nid) return (digests[i].id); return (0); } static int cryptodev_digest_init(EVP_MD_CTX *ctx) { struct dev_crypto_state *state = ctx->md_data; struct session_op *sess = &state->d_sess; int digest; if ((digest = digest_nid_to_cryptodev(ctx->digest->type)) == NID_undef){ printf("cryptodev_digest_init: Can't get digest \n"); return (0); } memset(state, 0, sizeof(struct dev_crypto_state)); if ((state->d_fd = get_dev_crypto()) < 0) { printf("cryptodev_digest_init: Can't get Dev \n"); return (0); } sess->mackey = NULL; sess->mackeylen = 0; sess->mac = digest; if (ioctl(state->d_fd, CIOCGSESSION, sess) < 0) { put_dev_crypto(state->d_fd); state->d_fd = -1; printf("cryptodev_digest_init: Open session failed\n"); return (0); } return (1); } static int cryptodev_digest_update(EVP_MD_CTX *ctx, const void *data, size_t count) { struct dev_crypto_state *state = ctx->md_data; struct crypt_op cryp; struct session_op *sess = &state->d_sess; if (!data || state->d_fd < 0) { printf("cryptodev_digest_update: illegal inputs \n"); return (0); } if (!count) { return (1); } if (!(ctx->flags & EVP_MD_CTX_FLAG_ONESHOT)) { /* if application doesn't support one buffer */ state->mac_data = OPENSSL_realloc(state->mac_data, state->mac_len + count); if (!state->mac_data) { printf("cryptodev_digest_update: realloc failed\n"); return (0); } memcpy(state->mac_data + state->mac_len, data, count); state->mac_len += count; return (1); } memset(&cryp, 0, sizeof(cryp)); cryp.ses = sess->ses; cryp.flags = 0; cryp.len = count; cryp.src = (void*) data; cryp.dst = NULL; cryp.mac = (void*) state->digest_res; if (ioctl(state->d_fd, CIOCCRYPT, &cryp) < 0) { printf("cryptodev_digest_update: digest failed\n"); return (0); } return (1); } static int cryptodev_digest_final(EVP_MD_CTX *ctx, unsigned char *md) { struct crypt_op cryp; struct dev_crypto_state *state = ctx->md_data; struct session_op *sess = &state->d_sess; if (!md || state->d_fd < 0) { printf("cryptodev_digest_final: illegal input\n"); return(0); } if (! (ctx->flags & EVP_MD_CTX_FLAG_ONESHOT) ) { /* if application doesn't support one buffer */ memset(&cryp, 0, sizeof(cryp)); cryp.ses = sess->ses; cryp.flags = 0; cryp.len = state->mac_len; cryp.src = state->mac_data; cryp.dst = NULL; cryp.mac = (void*)md; if (ioctl(state->d_fd, CIOCCRYPT, &cryp) < 0) { printf("cryptodev_digest_final: digest failed\n"); return (0); } return 1; } memcpy(md, state->digest_res, ctx->digest->md_size); return 1; } static int cryptodev_digest_cleanup(EVP_MD_CTX *ctx) { int ret = 1; struct dev_crypto_state *state = ctx->md_data; struct session_op *sess = &state->d_sess; if (state == NULL) return 0; if (state->d_fd < 0) { printf("cryptodev_digest_cleanup: illegal input\n"); return (0); } if (state->mac_data) { OPENSSL_free(state->mac_data); state->mac_data = NULL; state->mac_len = 0; } if (ioctl(state->d_fd, CIOCFSESSION, &sess->ses) < 0) { printf("cryptodev_digest_cleanup: failed to close session\n"); ret = 0; } else { ret = 1; } put_dev_crypto(state->d_fd); state->d_fd = -1; return (ret); } static int cryptodev_digest_copy(EVP_MD_CTX *to,const EVP_MD_CTX *from) { struct dev_crypto_state *fstate = from->md_data; struct dev_crypto_state *dstate = to->md_data; struct session_op *sess; int digest; if (dstate == NULL || fstate == NULL) return 1; memcpy(dstate, fstate, sizeof(struct dev_crypto_state)); sess = &dstate->d_sess; digest = digest_nid_to_cryptodev(to->digest->type); sess->mackey = NULL; sess->mackeylen = 0; sess->mac = digest; dstate->d_fd = get_dev_crypto(); if (ioctl(dstate->d_fd, CIOCGSESSION, sess) < 0) { put_dev_crypto(dstate->d_fd); dstate->d_fd = -1; printf("cryptodev_digest_init: Open session failed\n"); return (0); } if (fstate->mac_len != 0) { if (fstate->mac_data != NULL) { dstate->mac_data = OPENSSL_malloc(fstate->mac_len); memcpy(dstate->mac_data, fstate->mac_data, fstate->mac_len); dstate->mac_len = fstate->mac_len; } } return 1; } static const EVP_MD cryptodev_sha1 = { NID_sha1, NID_sha1WithRSAEncryption, SHA_DIGEST_LENGTH, #if defined(EVP_MD_FLAG_PKEY_METHOD_SIGNATURE) && defined(EVP_MD_FLAG_DIGALGID_ABSENT) EVP_MD_FLAG_PKEY_METHOD_SIGNATURE| EVP_MD_FLAG_DIGALGID_ABSENT| #endif EVP_MD_FLAG_ONESHOT, cryptodev_digest_init, cryptodev_digest_update, cryptodev_digest_final, cryptodev_digest_copy, cryptodev_digest_cleanup, EVP_PKEY_RSA_method, SHA_CBLOCK, sizeof(EVP_MD *)+sizeof(struct dev_crypto_state), }; static const EVP_MD cryptodev_sha256 = { NID_sha256, NID_sha256WithRSAEncryption, SHA256_DIGEST_LENGTH, #if defined(EVP_MD_FLAG_PKEY_METHOD_SIGNATURE) && defined(EVP_MD_FLAG_DIGALGID_ABSENT) EVP_MD_FLAG_PKEY_METHOD_SIGNATURE| EVP_MD_FLAG_DIGALGID_ABSENT| #endif EVP_MD_FLAG_ONESHOT, cryptodev_digest_init, cryptodev_digest_update, cryptodev_digest_final, cryptodev_digest_copy, cryptodev_digest_cleanup, EVP_PKEY_RSA_method, SHA256_CBLOCK, sizeof(EVP_MD *)+sizeof(struct dev_crypto_state), }; static const EVP_MD cryptodev_sha224 = { NID_sha224, NID_sha224WithRSAEncryption, SHA224_DIGEST_LENGTH, #if defined(EVP_MD_FLAG_PKEY_METHOD_SIGNATURE) && defined(EVP_MD_FLAG_DIGALGID_ABSENT) EVP_MD_FLAG_PKEY_METHOD_SIGNATURE| EVP_MD_FLAG_DIGALGID_ABSENT| #endif EVP_MD_FLAG_ONESHOT, cryptodev_digest_init, cryptodev_digest_update, cryptodev_digest_final, cryptodev_digest_copy, cryptodev_digest_cleanup, EVP_PKEY_RSA_method, SHA256_CBLOCK, sizeof(EVP_MD *)+sizeof(struct dev_crypto_state), }; static const EVP_MD cryptodev_sha384 = { NID_sha384, NID_sha384WithRSAEncryption, SHA384_DIGEST_LENGTH, #if defined(EVP_MD_FLAG_PKEY_METHOD_SIGNATURE) && defined(EVP_MD_FLAG_DIGALGID_ABSENT) EVP_MD_FLAG_PKEY_METHOD_SIGNATURE| EVP_MD_FLAG_DIGALGID_ABSENT| #endif EVP_MD_FLAG_ONESHOT, cryptodev_digest_init, cryptodev_digest_update, cryptodev_digest_final, cryptodev_digest_copy, cryptodev_digest_cleanup, EVP_PKEY_RSA_method, SHA512_CBLOCK, sizeof(EVP_MD *)+sizeof(struct dev_crypto_state), }; static const EVP_MD cryptodev_sha512 = { NID_sha512, NID_sha512WithRSAEncryption, SHA512_DIGEST_LENGTH, #if defined(EVP_MD_FLAG_PKEY_METHOD_SIGNATURE) && defined(EVP_MD_FLAG_DIGALGID_ABSENT) EVP_MD_FLAG_PKEY_METHOD_SIGNATURE| EVP_MD_FLAG_DIGALGID_ABSENT| #endif EVP_MD_FLAG_ONESHOT, cryptodev_digest_init, cryptodev_digest_update, cryptodev_digest_final, cryptodev_digest_copy, cryptodev_digest_cleanup, EVP_PKEY_RSA_method, SHA512_CBLOCK, sizeof(EVP_MD *)+sizeof(struct dev_crypto_state), }; static const EVP_MD cryptodev_md5 = { NID_md5, NID_md5WithRSAEncryption, 16 /* MD5_DIGEST_LENGTH */, #if defined(EVP_MD_FLAG_PKEY_METHOD_SIGNATURE) && defined(EVP_MD_FLAG_DIGALGID_ABSENT) EVP_MD_FLAG_PKEY_METHOD_SIGNATURE| EVP_MD_FLAG_DIGALGID_ABSENT| #endif EVP_MD_FLAG_ONESHOT, cryptodev_digest_init, cryptodev_digest_update, cryptodev_digest_final, cryptodev_digest_copy, cryptodev_digest_cleanup, EVP_PKEY_RSA_method, 64 /* MD5_CBLOCK */, sizeof(EVP_MD *)+sizeof(struct dev_crypto_state), }; #endif /* USE_CRYPTODEV_DIGESTS */ static int cryptodev_engine_digests(ENGINE *e, const EVP_MD **digest, const int **nids, int nid) { if (!digest) return (cryptodev_usable_digests(nids)); switch (nid) { #ifdef USE_CRYPTODEV_DIGESTS case NID_md5: *digest = &cryptodev_md5; break; case NID_sha1: *digest = &cryptodev_sha1; break; case NID_sha224: *digest = &cryptodev_sha224; break; case NID_sha256: *digest = &cryptodev_sha256; break; case NID_sha384: *digest = &cryptodev_sha384; break; case NID_sha512: *digest = &cryptodev_sha512; break; default: #endif /* USE_CRYPTODEV_DIGESTS */ *digest = NULL; break; } return (*digest != NULL); } /* * Convert a BIGNUM to the representation that /dev/crypto needs. * Upon completion of use, the caller is responsible for freeing * crp->crp_p. */ static int bn2crparam(const BIGNUM *a, struct crparam *crp) { int i, j, k; ssize_t bytes, bits; u_char *b; crp->crp_p = NULL; crp->crp_nbits = 0; bits = BN_num_bits(a); bytes = (bits + 7) / 8; b = malloc(bytes); if (b == NULL) return (1); memset(b, 0, bytes); crp->crp_p = (void*) b; crp->crp_nbits = bits; for (i = 0, j = 0; i < a->top; i++) { for (k = 0; k < BN_BITS2 / 8; k++) { if ((j + k) >= bytes) return (0); b[j + k] = a->d[i] >> (k * 8); } j += BN_BITS2 / 8; } return (0); } /* Convert a /dev/crypto parameter to a BIGNUM */ static int crparam2bn(struct crparam *crp, BIGNUM *a) { u_int8_t *pd; int i, bytes; bytes = (crp->crp_nbits + 7) / 8; if (bytes == 0) return (-1); if ((pd = (u_int8_t *) malloc(bytes)) == NULL) return (-1); for (i = 0; i < bytes; i++) pd[i] = crp->crp_p[bytes - i - 1]; BN_bin2bn(pd, bytes, a); free(pd); return (0); } static void zapparams(struct crypt_kop *kop) { int i; for (i = 0; i < kop->crk_iparams + kop->crk_oparams; i++) { if (kop->crk_param[i].crp_p) free(kop->crk_param[i].crp_p); kop->crk_param[i].crp_p = NULL; kop->crk_param[i].crp_nbits = 0; } } static int cryptodev_asym(struct crypt_kop *kop, int rlen, BIGNUM *r, int slen, BIGNUM *s) { int fd, ret = -1; if ((fd = get_asym_dev_crypto()) < 0) return (ret); if (r) { kop->crk_param[kop->crk_iparams].crp_p = calloc(rlen, sizeof(char)); kop->crk_param[kop->crk_iparams].crp_nbits = rlen * 8; kop->crk_oparams++; } if (s) { kop->crk_param[kop->crk_iparams+1].crp_p = calloc(slen, sizeof(char)); kop->crk_param[kop->crk_iparams+1].crp_nbits = slen * 8; kop->crk_oparams++; } if (ioctl(fd, CIOCKEY, kop) == 0) { if (r) crparam2bn(&kop->crk_param[kop->crk_iparams], r); if (s) crparam2bn(&kop->crk_param[kop->crk_iparams+1], s); ret = 0; } return (ret); } static int cryptodev_bn_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont) { struct crypt_kop kop; int ret = 1; /* Currently, we know we can do mod exp iff we can do any * asymmetric operations at all. */ if (cryptodev_asymfeat == 0) { ret = BN_mod_exp(r, a, p, m, ctx); return (ret); } memset(&kop, 0, sizeof kop); kop.crk_op = CRK_MOD_EXP; /* inputs: a^p % m */ if (bn2crparam(a, &kop.crk_param[0])) goto err; if (bn2crparam(p, &kop.crk_param[1])) goto err; if (bn2crparam(m, &kop.crk_param[2])) goto err; kop.crk_iparams = 3; if (cryptodev_asym(&kop, BN_num_bytes(m), r, 0, NULL)) { const RSA_METHOD *meth = RSA_PKCS1_SSLeay(); printf("OCF asym process failed, Running in software\n"); ret = meth->bn_mod_exp(r, a, p, m, ctx, in_mont); } else if (ECANCELED == kop.crk_status) { const RSA_METHOD *meth = RSA_PKCS1_SSLeay(); printf("OCF hardware operation cancelled. Running in Software\n"); ret = meth->bn_mod_exp(r, a, p, m, ctx, in_mont); } /* else cryptodev operation worked ok ==> ret = 1*/ err: zapparams(&kop); return (ret); } static int cryptodev_rsa_nocrt_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) { int r; ctx = BN_CTX_new(); r = cryptodev_bn_mod_exp(r0, I, rsa->d, rsa->n, ctx, NULL); BN_CTX_free(ctx); return (r); } static int cryptodev_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx) { struct crypt_kop kop; int ret = 1; if (!rsa->p || !rsa->q || !rsa->dmp1 || !rsa->dmq1 || !rsa->iqmp) { /* XXX 0 means failure?? */ return (0); } memset(&kop, 0, sizeof kop); kop.crk_op = CRK_MOD_EXP_CRT; /* inputs: rsa->p rsa->q I rsa->dmp1 rsa->dmq1 rsa->iqmp */ if (bn2crparam(rsa->p, &kop.crk_param[0])) goto err; if (bn2crparam(rsa->q, &kop.crk_param[1])) goto err; if (bn2crparam(I, &kop.crk_param[2])) goto err; if (bn2crparam(rsa->dmp1, &kop.crk_param[3])) goto err; if (bn2crparam(rsa->dmq1, &kop.crk_param[4])) goto err; if (bn2crparam(rsa->iqmp, &kop.crk_param[5])) goto err; kop.crk_iparams = 6; if (cryptodev_asym(&kop, BN_num_bytes(rsa->n), r0, 0, NULL)) { const RSA_METHOD *meth = RSA_PKCS1_SSLeay(); printf("OCF asym process failed, running in Software\n"); ret = (*meth->rsa_mod_exp)(r0, I, rsa, ctx); } else if (ECANCELED == kop.crk_status) { const RSA_METHOD *meth = RSA_PKCS1_SSLeay(); printf("OCF hardware operation cancelled. Running in Software\n"); ret = (*meth->rsa_mod_exp)(r0, I, rsa, ctx); } /* else cryptodev operation worked ok ==> ret = 1*/ err: zapparams(&kop); return (ret); } static RSA_METHOD cryptodev_rsa = { "cryptodev RSA method", NULL, /* rsa_pub_enc */ NULL, /* rsa_pub_dec */ NULL, /* rsa_priv_enc */ NULL, /* rsa_priv_dec */ NULL, NULL, NULL, /* init */ NULL, /* finish */ 0, /* flags */ NULL, /* app_data */ NULL, /* rsa_sign */ NULL /* rsa_verify */ }; static int cryptodev_dsa_bn_mod_exp(DSA *dsa, BIGNUM *r, BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) { return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx)); } static int cryptodev_dsa_dsa_mod_exp(DSA *dsa, BIGNUM *t1, BIGNUM *g, BIGNUM *u1, BIGNUM *pub_key, BIGNUM *u2, BIGNUM *p, BN_CTX *ctx, BN_MONT_CTX *mont) { BIGNUM t2; int ret = 0; BN_init(&t2); /* v = ( g^u1 * y^u2 mod p ) mod q */ /* let t1 = g ^ u1 mod p */ ret = 0; if (!dsa->meth->bn_mod_exp(dsa,t1,dsa->g,u1,dsa->p,ctx,mont)) goto err; /* let t2 = y ^ u2 mod p */ if (!dsa->meth->bn_mod_exp(dsa,&t2,dsa->pub_key,u2,dsa->p,ctx,mont)) goto err; /* let u1 = t1 * t2 mod p */ if (!BN_mod_mul(u1,t1,&t2,dsa->p,ctx)) goto err; BN_copy(t1,u1); ret = 1; err: BN_free(&t2); return(ret); } static DSA_SIG * cryptodev_dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa) { struct crypt_kop kop; BIGNUM *r = NULL, *s = NULL; DSA_SIG *dsaret = NULL; if ((r = BN_new()) == NULL) goto err; if ((s = BN_new()) == NULL) { BN_free(r); goto err; } memset(&kop, 0, sizeof kop); kop.crk_op = CRK_DSA_SIGN; /* inputs: dgst dsa->p dsa->q dsa->g dsa->priv_key */ kop.crk_param[0].crp_p = (void*)dgst; kop.crk_param[0].crp_nbits = dlen * 8; if (bn2crparam(dsa->p, &kop.crk_param[1])) goto err; if (bn2crparam(dsa->q, &kop.crk_param[2])) goto err; if (bn2crparam(dsa->g, &kop.crk_param[3])) goto err; if (bn2crparam(dsa->priv_key, &kop.crk_param[4])) goto err; kop.crk_iparams = 5; if (cryptodev_asym(&kop, BN_num_bytes(dsa->q), r, BN_num_bytes(dsa->q), s) == 0) { dsaret = DSA_SIG_new(); dsaret->r = r; dsaret->s = s; } else { const DSA_METHOD *meth = DSA_OpenSSL(); BN_free(r); BN_free(s); dsaret = (meth->dsa_do_sign)(dgst, dlen, dsa); } err: kop.crk_param[0].crp_p = NULL; zapparams(&kop); return (dsaret); } static int cryptodev_dsa_verify(const unsigned char *dgst, int dlen, DSA_SIG *sig, DSA *dsa) { struct crypt_kop kop; int dsaret = 1; memset(&kop, 0, sizeof kop); kop.crk_op = CRK_DSA_VERIFY; /* inputs: dgst dsa->p dsa->q dsa->g dsa->pub_key sig->r sig->s */ kop.crk_param[0].crp_p = (void*)dgst; kop.crk_param[0].crp_nbits = dlen * 8; if (bn2crparam(dsa->p, &kop.crk_param[1])) goto err; if (bn2crparam(dsa->q, &kop.crk_param[2])) goto err; if (bn2crparam(dsa->g, &kop.crk_param[3])) goto err; if (bn2crparam(dsa->pub_key, &kop.crk_param[4])) goto err; if (bn2crparam(sig->r, &kop.crk_param[5])) goto err; if (bn2crparam(sig->s, &kop.crk_param[6])) goto err; kop.crk_iparams = 7; if (cryptodev_asym(&kop, 0, NULL, 0, NULL) == 0) { /*OCF success value is 0, if not zero, change dsaret to fail*/ if(0 != kop.crk_status) dsaret = 0; } else { const DSA_METHOD *meth = DSA_OpenSSL(); dsaret = (meth->dsa_do_verify)(dgst, dlen, sig, dsa); } err: kop.crk_param[0].crp_p = NULL; zapparams(&kop); return (dsaret); } static DSA_METHOD cryptodev_dsa = { "cryptodev DSA method", NULL, NULL, /* dsa_sign_setup */ NULL, NULL, /* dsa_mod_exp */ NULL, NULL, /* init */ NULL, /* finish */ 0, /* flags */ NULL /* app_data */ }; static int cryptodev_mod_exp_dh(const DH *dh, BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx) { return (cryptodev_bn_mod_exp(r, a, p, m, ctx, m_ctx)); } static int cryptodev_dh_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh) { struct crypt_kop kop; int dhret = 1; int fd, keylen; if ((fd = get_asym_dev_crypto()) < 0) { const DH_METHOD *meth = DH_OpenSSL(); return ((meth->compute_key)(key, pub_key, dh)); } keylen = BN_num_bits(dh->p); memset(&kop, 0, sizeof kop); kop.crk_op = CRK_DH_COMPUTE_KEY; /* inputs: dh->priv_key pub_key dh->p key */ if (bn2crparam(dh->priv_key, &kop.crk_param[0])) goto err; if (bn2crparam(pub_key, &kop.crk_param[1])) goto err; if (bn2crparam(dh->p, &kop.crk_param[2])) goto err; kop.crk_iparams = 3; kop.crk_param[3].crp_p = (void*) key; kop.crk_param[3].crp_nbits = keylen; kop.crk_oparams = 1; dhret = keylen/8; if (ioctl(fd, CIOCKEY, &kop) == -1) { const DH_METHOD *meth = DH_OpenSSL(); dhret = (meth->compute_key)(key, pub_key, dh); } err: kop.crk_param[3].crp_p = NULL; zapparams(&kop); return (dhret); } static DH_METHOD cryptodev_dh = { "cryptodev DH method", NULL, /* cryptodev_dh_generate_key */ NULL, NULL, NULL, NULL, 0, /* flags */ NULL /* app_data */ }; /* * ctrl right now is just a wrapper that doesn't do much * but I expect we'll want some options soon. */ static int cryptodev_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)) { #ifdef HAVE_SYSLOG_R struct syslog_data sd = SYSLOG_DATA_INIT; #endif switch (cmd) { default: #ifdef HAVE_SYSLOG_R syslog_r(LOG_ERR, &sd, "cryptodev_ctrl: unknown command %d", cmd); #else syslog(LOG_ERR, "cryptodev_ctrl: unknown command %d", cmd); #endif break; } return (1); } void ENGINE_load_cryptodev(void) { ENGINE *engine = ENGINE_new(); int fd; if (engine == NULL) return; if ((fd = get_dev_crypto()) < 0) { ENGINE_free(engine); return; } /* * find out what asymmetric crypto algorithms we support */ if (ioctl(fd, CIOCASYMFEAT, &cryptodev_asymfeat) == -1) { put_dev_crypto(fd); ENGINE_free(engine); return; } put_dev_crypto(fd); if (!ENGINE_set_id(engine, "cryptodev") || !ENGINE_set_name(engine, "cryptodev engine") || !ENGINE_set_ciphers(engine, cryptodev_engine_ciphers) || !ENGINE_set_digests(engine, cryptodev_engine_digests) || !ENGINE_set_ctrl_function(engine, cryptodev_ctrl) || !ENGINE_set_cmd_defns(engine, cryptodev_defns)) { ENGINE_free(engine); return; } if (ENGINE_set_RSA(engine, &cryptodev_rsa)) { const RSA_METHOD *rsa_meth = RSA_PKCS1_SSLeay(); cryptodev_rsa.bn_mod_exp = rsa_meth->bn_mod_exp; cryptodev_rsa.rsa_mod_exp = rsa_meth->rsa_mod_exp; cryptodev_rsa.rsa_pub_enc = rsa_meth->rsa_pub_enc; cryptodev_rsa.rsa_pub_dec = rsa_meth->rsa_pub_dec; cryptodev_rsa.rsa_priv_enc = rsa_meth->rsa_priv_enc; cryptodev_rsa.rsa_priv_dec = rsa_meth->rsa_priv_dec; if (cryptodev_asymfeat & CRF_MOD_EXP) { cryptodev_rsa.bn_mod_exp = cryptodev_bn_mod_exp; if (cryptodev_asymfeat & CRF_MOD_EXP_CRT) cryptodev_rsa.rsa_mod_exp = cryptodev_rsa_mod_exp; else cryptodev_rsa.rsa_mod_exp = cryptodev_rsa_nocrt_mod_exp; } } if (ENGINE_set_DSA(engine, &cryptodev_dsa)) { const DSA_METHOD *meth = DSA_OpenSSL(); memcpy(&cryptodev_dsa, meth, sizeof(DSA_METHOD)); if (cryptodev_asymfeat & CRF_DSA_SIGN) cryptodev_dsa.dsa_do_sign = cryptodev_dsa_do_sign; if (cryptodev_asymfeat & CRF_MOD_EXP) { cryptodev_dsa.bn_mod_exp = cryptodev_dsa_bn_mod_exp; cryptodev_dsa.dsa_mod_exp = cryptodev_dsa_dsa_mod_exp; } if (cryptodev_asymfeat & CRF_DSA_VERIFY) cryptodev_dsa.dsa_do_verify = cryptodev_dsa_verify; } if (ENGINE_set_DH(engine, &cryptodev_dh)){ const DH_METHOD *dh_meth = DH_OpenSSL(); cryptodev_dh.generate_key = dh_meth->generate_key; cryptodev_dh.compute_key = dh_meth->compute_key; cryptodev_dh.bn_mod_exp = dh_meth->bn_mod_exp; if (cryptodev_asymfeat & CRF_MOD_EXP) { cryptodev_dh.bn_mod_exp = cryptodev_mod_exp_dh; if (cryptodev_asymfeat & CRF_DH_COMPUTE_KEY) cryptodev_dh.compute_key = cryptodev_dh_compute_key; } } ENGINE_add(engine); ENGINE_free(engine); ERR_clear_error(); } #endif /* HAVE_CRYPTODEV */ cryptodev-linux-1.6/authenc.c0000644000175100017510000004656012102243276015027 0ustar nmavnmav/* * Driver for /dev/crypto device (aka CryptoDev) * * Copyright (c) 2011, 2012 OpenSSL Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of linux cryptodev. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * This file handles the AEAD part of /dev/crypto. * */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "cryptodev_int.h" #include "zc.h" #include "util.h" #include "cryptlib.h" #include "version.h" /* make caop->dst available in scatterlist. * (caop->src is assumed to be equal to caop->dst) */ static int get_userbuf_tls(struct csession *ses, struct kernel_crypt_auth_op *kcaop, struct scatterlist **dst_sg) { int pagecount = 0; struct crypt_auth_op *caop = &kcaop->caop; int rc; if (caop->dst == NULL) return -EINVAL; if (ses->alignmask) { if (!IS_ALIGNED((unsigned long)caop->dst, ses->alignmask)) dprintk(2, KERN_WARNING, "careful - source address %lx is not %d byte aligned\n", (unsigned long)caop->dst, ses->alignmask + 1); } if (kcaop->dst_len == 0) { dprintk(1, KERN_WARNING, "Destination length cannot be zero\n"); return -EINVAL; } pagecount = PAGECOUNT(caop->dst, kcaop->dst_len); ses->used_pages = pagecount; ses->readonly_pages = 0; rc = adjust_sg_array(ses, pagecount); if (rc) return rc; rc = __get_userbuf(caop->dst, kcaop->dst_len, 1, pagecount, ses->pages, ses->sg, kcaop->task, kcaop->mm); if (unlikely(rc)) { dprintk(1, KERN_ERR, "failed to get user pages for data input\n"); return -EINVAL; } (*dst_sg) = ses->sg; return 0; } #define MAX_SRTP_AUTH_DATA_DIFF 256 /* Makes caop->auth_src available as scatterlist. * It also provides a pointer to caop->dst, which however, * is assumed to be within the caop->auth_src buffer. If not * (if their difference exceeds MAX_SRTP_AUTH_DATA_DIFF) it * returns error. */ static int get_userbuf_srtp(struct csession *ses, struct kernel_crypt_auth_op *kcaop, struct scatterlist **auth_sg, struct scatterlist **dst_sg) { int pagecount, diff; int auth_pagecount = 0; struct crypt_auth_op *caop = &kcaop->caop; int rc; if (caop->dst == NULL && caop->auth_src == NULL) { dprintk(1, KERN_ERR, "dst and auth_src cannot be both null\n"); return -EINVAL; } if (ses->alignmask) { if (!IS_ALIGNED((unsigned long)caop->dst, ses->alignmask)) dprintk(2, KERN_WARNING, "careful - source address %lx is not %d byte aligned\n", (unsigned long)caop->dst, ses->alignmask + 1); if (!IS_ALIGNED((unsigned long)caop->auth_src, ses->alignmask)) dprintk(2, KERN_WARNING, "careful - source address %lx is not %d byte aligned\n", (unsigned long)caop->auth_src, ses->alignmask + 1); } if (unlikely(kcaop->dst_len == 0 || caop->auth_len == 0)) { dprintk(1, KERN_WARNING, "Destination length cannot be zero\n"); return -EINVAL; } /* Note that in SRTP auth data overlap with data to be encrypted (dst) */ auth_pagecount = PAGECOUNT(caop->auth_src, caop->auth_len); diff = (int)(caop->src - caop->auth_src); if (diff > MAX_SRTP_AUTH_DATA_DIFF || diff < 0) { dprintk(1, KERN_WARNING, "auth_src must overlap with src (diff: %d).\n", diff); return -EINVAL; } pagecount = auth_pagecount; rc = adjust_sg_array(ses, pagecount*2); /* double pages to have pages for dst(=auth_src) */ if (rc) { dprintk(1, KERN_ERR, "cannot adjust sg array\n"); return rc; } rc = __get_userbuf(caop->auth_src, caop->auth_len, 1, auth_pagecount, ses->pages, ses->sg, kcaop->task, kcaop->mm); if (unlikely(rc)) { dprintk(1, KERN_ERR, "failed to get user pages for data input\n"); return -EINVAL; } ses->used_pages = pagecount; ses->readonly_pages = 0; (*auth_sg) = ses->sg; (*dst_sg) = ses->sg + auth_pagecount; sg_init_table(*dst_sg, auth_pagecount); sg_copy(ses->sg, (*dst_sg), caop->auth_len); (*dst_sg) = sg_advance(*dst_sg, diff); if (*dst_sg == NULL) { release_user_pages(ses); dprintk(1, KERN_ERR, "failed to get enough pages for auth data\n"); return -EINVAL; } return 0; } static int fill_kcaop_from_caop(struct kernel_crypt_auth_op *kcaop, struct fcrypt *fcr) { struct crypt_auth_op *caop = &kcaop->caop; struct csession *ses_ptr; int ret; /* this also enters ses_ptr->sem */ ses_ptr = crypto_get_session_by_sid(fcr, caop->ses); if (unlikely(!ses_ptr)) { dprintk(1, KERN_ERR, "invalid session ID=0x%08X\n", caop->ses); return -EINVAL; } if (caop->flags & COP_FLAG_AEAD_TLS_TYPE || caop->flags & COP_FLAG_AEAD_SRTP_TYPE) { if (caop->src != caop->dst) { dprintk(1, KERN_ERR, "Non-inplace encryption and decryption is not efficient and not implemented\n"); ret = -EINVAL; goto out_unlock; } } if (caop->tag_len == 0) caop->tag_len = ses_ptr->hdata.digestsize; kcaop->ivlen = caop->iv ? ses_ptr->cdata.ivsize : 0; if (caop->flags & COP_FLAG_AEAD_TLS_TYPE) kcaop->dst_len = caop->len + ses_ptr->cdata.blocksize /* pad */ + caop->tag_len; else kcaop->dst_len = caop->len; kcaop->task = current; kcaop->mm = current->mm; if (caop->iv) { ret = copy_from_user(kcaop->iv, caop->iv, kcaop->ivlen); if (unlikely(ret)) { dprintk(1, KERN_ERR, "error copying IV (%d bytes), copy_from_user returned %d for address %lx\n", kcaop->ivlen, ret, (unsigned long)caop->iv); ret = -EFAULT; goto out_unlock; } } ret = 0; out_unlock: crypto_put_session(ses_ptr); return ret; } static int fill_caop_from_kcaop(struct kernel_crypt_auth_op *kcaop, struct fcrypt *fcr) { int ret; kcaop->caop.len = kcaop->dst_len; if (kcaop->ivlen && kcaop->caop.flags & COP_FLAG_WRITE_IV) { ret = copy_to_user(kcaop->caop.iv, kcaop->iv, kcaop->ivlen); if (unlikely(ret)) { dprintk(1, KERN_ERR, "Error in copying to userspace\n"); return -EFAULT; } } return 0; } int kcaop_from_user(struct kernel_crypt_auth_op *kcaop, struct fcrypt *fcr, void __user *arg) { if (unlikely(copy_from_user(&kcaop->caop, arg, sizeof(kcaop->caop)))) { dprintk(1, KERN_ERR, "Error in copying from userspace\n"); return -EFAULT; } return fill_kcaop_from_caop(kcaop, fcr); } int kcaop_to_user(struct kernel_crypt_auth_op *kcaop, struct fcrypt *fcr, void __user *arg) { int ret; ret = fill_caop_from_kcaop(kcaop, fcr); if (unlikely(ret)) { dprintk(1, KERN_ERR, "fill_caop_from_kcaop\n"); return ret; } if (unlikely(copy_to_user(arg, &kcaop->caop, sizeof(kcaop->caop)))) { dprintk(1, KERN_ERR, "Error in copying to userspace\n"); return -EFAULT; } return 0; } static void copy_tls_hash( struct scatterlist *dst_sg, int len, void* hash, int hash_len) { scatterwalk_map_and_copy(hash, dst_sg, len, hash_len, 1); } static void read_tls_hash( struct scatterlist *dst_sg, int len, void* hash, int hash_len) { scatterwalk_map_and_copy(hash, dst_sg, len-hash_len, hash_len, 0); } static int pad_record( struct scatterlist *dst_sg, int len, int block_size) { uint8_t pad[block_size]; int pad_size = block_size - (len % block_size); memset(pad, pad_size-1, pad_size); scatterwalk_map_and_copy(pad, dst_sg, len, pad_size, 1); return pad_size; } static int verify_tls_record_pad( struct scatterlist *dst_sg, int len, int block_size) { uint8_t pad[256]; /* the maximum allowed */ uint8_t pad_size; int i; scatterwalk_map_and_copy(&pad_size, dst_sg, len-1, 1, 0); if (pad_size+1 > len) { dprintk(1, KERN_ERR, "Pad size: %d\n", pad_size); return -EBADMSG; } scatterwalk_map_and_copy(pad, dst_sg, len-pad_size-1, pad_size+1, 0); for (i=0;icaop; uint8_t vhash[AALG_MAX_RESULT_LEN]; uint8_t hash_output[AALG_MAX_RESULT_LEN]; /* TLS authenticates the plaintext except for the padding. */ if (caop->op == COP_ENCRYPT) { if (ses_ptr->hdata.init != 0) { if (auth_len > 0) { ret = cryptodev_hash_update(&ses_ptr->hdata, auth_sg, auth_len); if (unlikely(ret)) { dprintk(0, KERN_ERR, "cryptodev_hash_update: %d\n", ret); return ret; } } if (len > 0) { ret = cryptodev_hash_update(&ses_ptr->hdata, dst_sg, len); if (unlikely(ret)) { dprintk(0, KERN_ERR, "cryptodev_hash_update: %d\n", ret); return ret; } } ret = cryptodev_hash_final(&ses_ptr->hdata, hash_output); if (unlikely(ret)) { dprintk(0, KERN_ERR, "cryptodev_hash_final: %d\n", ret); return ret; } copy_tls_hash( dst_sg, len, hash_output, caop->tag_len); len += caop->tag_len; } if (ses_ptr->cdata.init != 0) { if (ses_ptr->cdata.blocksize > 1) { ret = pad_record(dst_sg, len, ses_ptr->cdata.blocksize); len += ret; } ret = cryptodev_cipher_encrypt(&ses_ptr->cdata, dst_sg, dst_sg, len); if (unlikely(ret)) { dprintk(0, KERN_ERR, "cryptodev_cipher_encrypt: %d\n", ret); return ret; } } } else { if (ses_ptr->cdata.init != 0) { ret = cryptodev_cipher_decrypt(&ses_ptr->cdata, dst_sg, dst_sg, len); if (unlikely(ret)) { dprintk(0, KERN_ERR, "cryptodev_cipher_decrypt: %d\n", ret); return ret; } if (ses_ptr->cdata.blocksize > 1) { ret = verify_tls_record_pad(dst_sg, len, ses_ptr->cdata.blocksize); if (unlikely(ret < 0)) { dprintk(2, KERN_ERR, "verify_record_pad: %d\n", ret); fail = 1; } else { len -= ret; } } } if (ses_ptr->hdata.init != 0) { if (unlikely(caop->tag_len > sizeof(vhash) || caop->tag_len > len)) { dprintk(1, KERN_ERR, "Illegal tag len size\n"); return -EINVAL; } read_tls_hash( dst_sg, len, vhash, caop->tag_len); len -= caop->tag_len; if (auth_len > 0) { ret = cryptodev_hash_update(&ses_ptr->hdata, auth_sg, auth_len); if (unlikely(ret)) { dprintk(0, KERN_ERR, "cryptodev_hash_update: %d\n", ret); return ret; } } if (len > 0) { ret = cryptodev_hash_update(&ses_ptr->hdata, dst_sg, len); if (unlikely(ret)) { dprintk(0, KERN_ERR, "cryptodev_hash_update: %d\n", ret); return ret; } } ret = cryptodev_hash_final(&ses_ptr->hdata, hash_output); if (unlikely(ret)) { dprintk(0, KERN_ERR, "cryptodev_hash_final: %d\n", ret); return ret; } if (memcmp(vhash, hash_output, caop->tag_len) != 0 || fail != 0) { dprintk(2, KERN_ERR, "MAC verification failed (tag_len: %d)\n", caop->tag_len); return -EBADMSG; } } } kcaop->dst_len = len; return 0; } /* Authenticate and encrypt the SRTP way. During decryption * it verifies the tag and returns -EBADMSG on error. */ static int srtp_auth_n_crypt(struct csession *ses_ptr, struct kernel_crypt_auth_op *kcaop, struct scatterlist *auth_sg, uint32_t auth_len, struct scatterlist *dst_sg, uint32_t len) { int ret, fail = 0; struct crypt_auth_op *caop = &kcaop->caop; uint8_t vhash[AALG_MAX_RESULT_LEN]; uint8_t hash_output[AALG_MAX_RESULT_LEN]; /* SRTP authenticates the encrypted data. */ if (caop->op == COP_ENCRYPT) { if (ses_ptr->cdata.init != 0) { ret = cryptodev_cipher_encrypt(&ses_ptr->cdata, dst_sg, dst_sg, len); if (unlikely(ret)) { dprintk(0, KERN_ERR, "cryptodev_cipher_encrypt: %d\n", ret); return ret; } } if (ses_ptr->hdata.init != 0) { if (auth_len > 0) { ret = cryptodev_hash_update(&ses_ptr->hdata, auth_sg, auth_len); if (unlikely(ret)) { dprintk(0, KERN_ERR, "cryptodev_hash_update: %d\n", ret); return ret; } } ret = cryptodev_hash_final(&ses_ptr->hdata, hash_output); if (unlikely(ret)) { dprintk(0, KERN_ERR, "cryptodev_hash_final: %d\n", ret); return ret; } if (unlikely(copy_to_user(caop->tag, hash_output, caop->tag_len))) { return -EFAULT; } } } else { if (ses_ptr->hdata.init != 0) { if (unlikely(caop->tag_len > sizeof(vhash) || caop->tag_len > len)) { dprintk(1, KERN_ERR, "Illegal tag len size\n"); return -EINVAL; } if (unlikely(copy_from_user(vhash, caop->tag, caop->tag_len))) { return -EFAULT; } ret = cryptodev_hash_update(&ses_ptr->hdata, auth_sg, auth_len); if (unlikely(ret)) { dprintk(0, KERN_ERR, "cryptodev_hash_update: %d\n", ret); return ret; } ret = cryptodev_hash_final(&ses_ptr->hdata, hash_output); if (unlikely(ret)) { dprintk(0, KERN_ERR, "cryptodev_hash_final: %d\n", ret); return ret; } if (memcmp(vhash, hash_output, caop->tag_len) != 0 || fail != 0) { dprintk(2, KERN_ERR, "MAC verification failed\n"); return -EBADMSG; } } if (ses_ptr->cdata.init != 0) { ret = cryptodev_cipher_decrypt(&ses_ptr->cdata, dst_sg, dst_sg, len); if (unlikely(ret)) { dprintk(0, KERN_ERR, "cryptodev_cipher_decrypt: %d\n", ret); return ret; } } } kcaop->dst_len = len; return 0; } /* Typical AEAD (i.e. GCM) encryption/decryption. * During decryption the tag is verified. */ static int auth_n_crypt(struct csession *ses_ptr, struct kernel_crypt_auth_op *kcaop, struct scatterlist *auth_sg, uint32_t auth_len, struct scatterlist *src_sg, struct scatterlist *dst_sg, uint32_t len) { int ret; struct crypt_auth_op *caop = &kcaop->caop; int max_tag_len; max_tag_len = cryptodev_cipher_get_tag_size(&ses_ptr->cdata); if (unlikely(caop->tag_len > max_tag_len)) { dprintk(0, KERN_ERR, "Illegal tag length: %d\n", caop->tag_len); return -EINVAL; } if (caop->tag_len) cryptodev_cipher_set_tag_size(&ses_ptr->cdata, caop->tag_len); else caop->tag_len = max_tag_len; cryptodev_cipher_auth(&ses_ptr->cdata, auth_sg, auth_len); if (caop->op == COP_ENCRYPT) { ret = cryptodev_cipher_encrypt(&ses_ptr->cdata, src_sg, dst_sg, len); if (unlikely(ret)) { dprintk(0, KERN_ERR, "cryptodev_cipher_encrypt: %d\n", ret); return ret; } kcaop->dst_len = len + caop->tag_len; caop->tag = caop->dst + len; } else { ret = cryptodev_cipher_decrypt(&ses_ptr->cdata, src_sg, dst_sg, len); if (unlikely(ret)) { dprintk(0, KERN_ERR, "cryptodev_cipher_decrypt: %d\n", ret); return ret; } kcaop->dst_len = len - caop->tag_len; caop->tag = caop->dst + len - caop->tag_len; } return 0; } /* This is the main crypto function - zero-copy edition */ static int __crypto_auth_run_zc(struct csession *ses_ptr, struct kernel_crypt_auth_op *kcaop) { struct scatterlist *dst_sg, *auth_sg, *src_sg; struct crypt_auth_op *caop = &kcaop->caop; int ret = 0; if (caop->flags & COP_FLAG_AEAD_SRTP_TYPE) { if (unlikely(ses_ptr->cdata.init != 0 && (ses_ptr->cdata.stream == 0 || ses_ptr->cdata.aead != 0))) { dprintk(0, KERN_ERR, "Only stream modes are allowed in SRTP mode (but not AEAD)\n"); return -EINVAL; } ret = get_userbuf_srtp(ses_ptr, kcaop, &auth_sg, &dst_sg); if (unlikely(ret)) { dprintk(1, KERN_ERR, "get_userbuf_srtp(): Error getting user pages.\n"); return ret; } ret = srtp_auth_n_crypt(ses_ptr, kcaop, auth_sg, caop->auth_len, dst_sg, caop->len); release_user_pages(ses_ptr); } else { /* TLS and normal cases. Here auth data are usually small * so we just copy them to a free page, instead of trying * to map them. */ unsigned char* auth_buf = NULL; struct scatterlist tmp; if (unlikely(caop->auth_len > PAGE_SIZE)) { dprintk(1, KERN_ERR, "auth data len is excessive.\n"); return -EINVAL; } auth_buf = (char *)__get_free_page(GFP_KERNEL); if (unlikely(!auth_buf)) { dprintk(1, KERN_ERR, "unable to get a free page.\n"); return -ENOMEM; } if (caop->auth_src && caop->auth_len > 0) { if (unlikely(copy_from_user(auth_buf, caop->auth_src, caop->auth_len))) { dprintk(1, KERN_ERR, "unable to copy auth data from userspace.\n"); ret = -EFAULT; goto free_auth_buf; } sg_init_one(&tmp, auth_buf, caop->auth_len); auth_sg = &tmp; } else { auth_sg = NULL; } if (caop->flags & COP_FLAG_AEAD_TLS_TYPE && ses_ptr->cdata.aead == 0) { ret = get_userbuf_tls(ses_ptr, kcaop, &dst_sg); if (unlikely(ret)) { dprintk(1, KERN_ERR, "get_userbuf_tls(): Error getting user pages.\n"); goto free_auth_buf; } ret = tls_auth_n_crypt(ses_ptr, kcaop, auth_sg, caop->auth_len, dst_sg, caop->len); } else { int dst_len; if (unlikely(ses_ptr->cdata.init == 0 || ses_ptr->cdata.stream == 0 || ses_ptr->cdata.aead == 0)) { dprintk(0, KERN_ERR, "Only stream and AEAD ciphers are allowed for authenc\n"); ret = -EINVAL; goto free_auth_buf; } if (caop->op == COP_ENCRYPT) dst_len = caop->len + cryptodev_cipher_get_tag_size(&ses_ptr->cdata); else dst_len = caop->len; ret = get_userbuf(ses_ptr, caop->src, caop->len, caop->dst, dst_len, kcaop->task, kcaop->mm, &src_sg, &dst_sg); if (unlikely(ret)) { dprintk(1, KERN_ERR, "get_userbuf(): Error getting user pages.\n"); goto free_auth_buf; } ret = auth_n_crypt(ses_ptr, kcaop, auth_sg, caop->auth_len, src_sg, dst_sg, caop->len); } release_user_pages(ses_ptr); free_auth_buf: free_page((unsigned long)auth_buf); } return ret; } int crypto_auth_run(struct fcrypt *fcr, struct kernel_crypt_auth_op *kcaop) { struct csession *ses_ptr; struct crypt_auth_op *caop = &kcaop->caop; int ret; if (unlikely(caop->op != COP_ENCRYPT && caop->op != COP_DECRYPT)) { dprintk(1, KERN_DEBUG, "invalid operation op=%u\n", caop->op); return -EINVAL; } /* this also enters ses_ptr->sem */ ses_ptr = crypto_get_session_by_sid(fcr, caop->ses); if (unlikely(!ses_ptr)) { dprintk(1, KERN_ERR, "invalid session ID=0x%08X\n", caop->ses); return -EINVAL; } if (unlikely(ses_ptr->cdata.init == 0)) { dprintk(1, KERN_ERR, "cipher context not initialized\n"); ret = -EINVAL; goto out_unlock; } /* If we have a hash/mac handle reset its state */ if (ses_ptr->hdata.init != 0) { ret = cryptodev_hash_reset(&ses_ptr->hdata); if (unlikely(ret)) { dprintk(1, KERN_ERR, "error in cryptodev_hash_reset()\n"); goto out_unlock; } } cryptodev_cipher_set_iv(&ses_ptr->cdata, kcaop->iv, min(ses_ptr->cdata.ivsize, kcaop->ivlen)); ret = __crypto_auth_run_zc(ses_ptr, kcaop); if (unlikely(ret)) { dprintk(1, KERN_ERR, "error in __crypto_auth_run_zc()\n"); goto out_unlock; } ret = 0; cryptodev_cipher_get_iv(&ses_ptr->cdata, kcaop->iv, min(ses_ptr->cdata.ivsize, kcaop->ivlen)); out_unlock: crypto_put_session(ses_ptr); return ret; } cryptodev-linux-1.6/Makefile0000644000175100017510000000303012115016400014644 0ustar nmavnmav# # Since version 1.6 the asynchronous mode has been # disabled by default. To re-enable it uncomment the # corresponding CFLAG. # CRYPTODEV_CFLAGS ?= #-DENABLE_ASYNC KBUILD_CFLAGS += -I$(src) $(CRYPTODEV_CFLAGS) KERNEL_DIR = /lib/modules/$(shell uname -r)/build VERSION = 1.6 PREFIX = cryptodev-objs = ioctl.o main.o cryptlib.o authenc.o zc.o util.o obj-m += cryptodev.o build: version.h make -C $(KERNEL_DIR) SUBDIRS=`pwd` modules version.h: Makefile @echo "#define VERSION \"$(VERSION)\"" > version.h install: modules_install modules_install: make -C $(KERNEL_DIR) SUBDIRS=`pwd` modules_install @echo "Installing cryptodev.h in $(PREFIX)/usr/include/crypto ..." @install -D crypto/cryptodev.h $(PREFIX)/usr/include/crypto/cryptodev.h clean: make -C $(KERNEL_DIR) SUBDIRS=`pwd` clean rm -f $(hostprogs) *~ CFLAGS=$(CRYPTODEV_CFLAGS) KERNEL_DIR=$(KERNEL_DIR) make -C tests clean check: CFLAGS=$(CRYPTODEV_CFLAGS) KERNEL_DIR=$(KERNEL_DIR) make -C tests check FILEBASE = cryptodev-linux-$(VERSION) TMPDIR ?= /tmp OUTPUT = $(FILEBASE).tar.gz dist: clean @echo Packing @rm -f *.tar.gz @mkdir $(TMPDIR)/$(FILEBASE) @cp -ar crypto extras tests examples Makefile *.c *.h README NEWS \ AUTHORS COPYING $(TMPDIR)/$(FILEBASE) @rm -rf $(TMPDIR)/$(FILEBASE)/.git* $(TMPDIR)/$(FILEBASE)/releases $(TMPDIR)/$(FILEBASE)/scripts @tar -C /tmp -czf ./$(OUTPUT) $(FILEBASE) @rm -rf $(TMPDIR)/$(FILEBASE) @echo Signing $(OUTPUT) @gpg --output $(OUTPUT).sig -sb $(OUTPUT) @gpg --verify $(OUTPUT).sig $(OUTPUT) @mv $(OUTPUT) $(OUTPUT).sig releases/ cryptodev-linux-1.6/cryptlib.h0000644000175100017510000000465712102243276015236 0ustar nmavnmav#ifndef CRYPTLIB_H # define CRYPTLIB_H struct cipher_data { int init; /* 0 uninitialized */ int blocksize; int aead; int stream; int ivsize; int alignmask; struct { /* block ciphers */ struct crypto_ablkcipher *s; struct ablkcipher_request *request; /* AEAD ciphers */ struct crypto_aead *as; struct aead_request *arequest; struct cryptodev_result *result; uint8_t iv[EALG_MAX_BLOCK_LEN]; } async; }; int cryptodev_cipher_init(struct cipher_data *out, const char *alg_name, uint8_t *key, size_t keylen, int stream, int aead); void cryptodev_cipher_deinit(struct cipher_data *cdata); ssize_t cryptodev_cipher_decrypt(struct cipher_data *cdata, const struct scatterlist *sg1, struct scatterlist *sg2, size_t len); ssize_t cryptodev_cipher_encrypt(struct cipher_data *cdata, const struct scatterlist *sg1, struct scatterlist *sg2, size_t len); /* AEAD */ inline static void cryptodev_cipher_auth(struct cipher_data *cdata, struct scatterlist *sg1, size_t len) { /* for some reason we _have_ to call that even for zero length sgs */ aead_request_set_assoc(cdata->async.arequest, len ? sg1 : NULL, len); } inline static void cryptodev_cipher_set_tag_size(struct cipher_data *cdata, int size) { if (likely(cdata->aead != 0)) crypto_aead_setauthsize(cdata->async.as, size); } inline static int cryptodev_cipher_get_tag_size(struct cipher_data *cdata) { if (likely(cdata->init && cdata->aead != 0)) return crypto_aead_authsize(cdata->async.as); else return 0; } inline static void cryptodev_cipher_set_iv(struct cipher_data *cdata, void *iv, size_t iv_size) { memcpy(cdata->async.iv, iv, min(iv_size, sizeof(cdata->async.iv))); } inline static void cryptodev_cipher_get_iv(struct cipher_data *cdata, void *iv, size_t iv_size) { memcpy(iv, cdata->async.iv, min(iv_size, sizeof(cdata->async.iv))); } /* Hash */ struct hash_data { int init; /* 0 uninitialized */ int digestsize; int alignmask; struct { struct crypto_ahash *s; struct cryptodev_result *result; struct ahash_request *request; } async; }; int cryptodev_hash_final(struct hash_data *hdata, void *output); ssize_t cryptodev_hash_update(struct hash_data *hdata, struct scatterlist *sg, size_t len); int cryptodev_hash_reset(struct hash_data *hdata); void cryptodev_hash_deinit(struct hash_data *hdata); int cryptodev_hash_init(struct hash_data *hdata, const char *alg_name, int hmac_mode, void *mackey, size_t mackeylen); #endif cryptodev-linux-1.6/crypto/0000755000175100017510000000000012115015315014534 5ustar nmavnmavcryptodev-linux-1.6/crypto/cryptodev.h~0000644000175100017510000002153612102243276017136 0ustar nmavnmav/* This is a source compatible implementation with the original API of * cryptodev by Angelos D. Keromytis, found at openbsd cryptodev.h. * Placed under public domain */ #ifndef L_CRYPTODEV_H #define L_CRYPTODEV_H #include #ifndef __KERNEL__ #define __user #endif /* API extensions for linux */ #define CRYPTO_HMAC_MAX_KEY_LEN 512 #define CRYPTO_CIPHER_MAX_KEY_LEN 64 /* All the supported algorithms */ enum cryptodev_crypto_op_t { CRYPTO_DES_CBC = 1, CRYPTO_3DES_CBC = 2, CRYPTO_BLF_CBC = 3, CRYPTO_CAST_CBC = 4, CRYPTO_SKIPJACK_CBC = 5, CRYPTO_MD5_HMAC = 6, CRYPTO_SHA1_HMAC = 7, CRYPTO_RIPEMD160_HMAC = 8, CRYPTO_MD5_KPDK = 9, CRYPTO_SHA1_KPDK = 10, CRYPTO_RIJNDAEL128_CBC = 11, CRYPTO_AES_CBC = CRYPTO_RIJNDAEL128_CBC, CRYPTO_ARC4 = 12, CRYPTO_MD5 = 13, CRYPTO_SHA1 = 14, CRYPTO_DEFLATE_COMP = 15, CRYPTO_NULL = 16, CRYPTO_LZS_COMP = 17, CRYPTO_SHA2_256_HMAC = 18, CRYPTO_SHA2_384_HMAC = 19, CRYPTO_SHA2_512_HMAC = 20, CRYPTO_AES_CTR = 21, CRYPTO_AES_XTS = 22, CRYPTO_AES_ECB = 23, CRYPTO_AES_GCM = 50, CRYPTO_CAMELLIA_CBC = 101, CRYPTO_RIPEMD160, CRYPTO_SHA2_224, CRYPTO_SHA2_256, CRYPTO_SHA2_384, CRYPTO_SHA2_512, CRYPTO_SHA2_224_HMAC, CRYPTO_ALGORITHM_ALL, /* Keep updated - see below */ }; #define CRYPTO_ALGORITHM_MAX (CRYPTO_ALGORITHM_ALL - 1) /* Values for ciphers */ #define DES_BLOCK_LEN 8 #define DES3_BLOCK_LEN 8 #define RIJNDAEL128_BLOCK_LEN 16 #define AES_BLOCK_LEN RIJNDAEL128_BLOCK_LEN #define CAMELLIA_BLOCK_LEN 16 #define BLOWFISH_BLOCK_LEN 8 #define SKIPJACK_BLOCK_LEN 8 #define CAST128_BLOCK_LEN 8 /* the maximum of the above */ #define EALG_MAX_BLOCK_LEN 16 /* Values for hashes/MAC */ #define AALG_MAX_RESULT_LEN 64 /* maximum length of verbose alg names (depends on CRYPTO_MAX_ALG_NAME) */ #define CRYPTODEV_MAX_ALG_NAME 64 #define HASH_MAX_LEN 64 /* input of CIOCGSESSION */ struct session_op { /* Specify either cipher or mac */ __u32 cipher; /* cryptodev_crypto_op_t */ __u32 mac; /* cryptodev_crypto_op_t */ __u32 keylen; __u8 __user *key; __u32 mackeylen; __u8 __user *mackey; __u32 ses; /* session identifier */ }; struct session_info_op { __u32 ses; /* session identifier */ /* verbose names for the requested ciphers */ struct alg_info { char cra_name[CRYPTODEV_MAX_ALG_NAME]; char cra_driver_name[CRYPTODEV_MAX_ALG_NAME]; } cipher_info, hash_info; __u16 alignmask; /* alignment constraints */ __u32 flags; /* SIOP_FLAGS_* */ }; /* If this flag is set then this algorithm uses * a driver only available in kernel (software drivers, * or drivers based on instruction sets do not set this flag). * * If multiple algorithms are involved (as in AEAD case), then * if one of them is kernel-driver-only this flag will be set. */ #define SIOP_FLAG_KERNEL_DRIVER_ONLY 1 #define COP_ENCRYPT 0 #define COP_DECRYPT 1 /* input of CIOCCRYPT */ struct crypt_op { __u32 ses; /* session identifier */ __u16 op; /* COP_ENCRYPT or COP_DECRYPT */ __u16 flags; /* see COP_FLAG_* */ __u32 len; /* length of source data */ __u8 __user *src; /* source data */ __u8 __user *dst; /* pointer to output data */ /* pointer to output data for hash/MAC operations */ __u8 __user *mac; /* initialization vector for encryption operations */ __u8 __user *iv; }; /* input of CIOCAUTHCRYPT */ struct crypt_auth_op { __u32 ses; /* session identifier */ __u16 op; /* COP_ENCRYPT or COP_DECRYPT */ __u16 flags; /* see COP_FLAG_AEAD_* */ __u32 len; /* length of source data */ __u32 auth_len; /* length of auth data */ __u8 __user *auth_src; /* authenticated-only data */ /* The current implementation is more efficient if data are * encrypted in-place (src==dst). */ __u8 __user *src; /* data to be encrypted and authenticated */ __u8 __user *dst; /* pointer to output data. Must have * space for tag. For TLS this should be at least * len + tag_size + block_size for padding */ __u8 __user *tag; /* where the tag will be copied to. TLS mode * doesn't use that as tag is copied to dst. * SRTP mode copies tag there. */ __u32 tag_len; /* the length of the tag. Use zero for digest size or max tag. */ /* initialization vector for encryption operations */ __u8 __user *iv; __u32 iv_len; }; /* In plain AEAD mode the following are required: * flags : 0 * iv : the initialization vector (12 bytes) * auth_len: the length of the data to be authenticated * auth_src: the data to be authenticated * len : length of data to be encrypted * src : the data to be encrypted * dst : space to hold encrypted data. It must have * at least a size of len + tag_size. * tag_size: the size of the desired authentication tag or zero to use * the maximum tag output. * * Note tag isn't being used because the Linux AEAD interface * copies the tag just after data. */ /* In TLS mode (used for CBC ciphers that required padding) * the following are required: * flags : COP_FLAG_AEAD_TLS_TYPE * iv : the initialization vector * auth_len: the length of the data to be authenticated only * len : length of data to be encrypted * auth_src: the data to be authenticated * src : the data to be encrypted * dst : space to hold encrypted data (preferably in-place). It must have * at least a size of len + tag_size + blocksize. * tag_size: the size of the desired authentication tag or zero to use * the default mac output. * * Note that the padding used is the minimum padding. */ /* In SRTP mode the following are required: * flags : COP_FLAG_AEAD_SRTP_TYPE * iv : the initialization vector * auth_len: the length of the data to be authenticated. This must * include the SRTP header + SRTP payload (data to be encrypted) + rest * * len : length of data to be encrypted * auth_src: pointer the data to be authenticated. Should point at the same buffer as src. * src : pointer to the data to be encrypted. * dst : This is mandatory to be the same as src (in-place only). * tag_size: the size of the desired authentication tag or zero to use * the default mac output. * tag : Pointer to an address where the authentication tag will be copied. */ /* struct crypt_op flags */ #define COP_FLAG_NONE (0 << 0) /* totally no flag */ #define COP_FLAG_UPDATE (1 << 0) /* multi-update hash mode */ #define COP_FLAG_FINAL (1 << 1) /* multi-update final hash mode */ #define COP_FLAG_WRITE_IV (1 << 2) /* update the IV during operation */ #define COP_FLAG_NO_ZC (1 << 3) /* do not zero-copy */ #define COP_FLAG_AEAD_TLS_TYPE (1 << 4) /* authenticate and encrypt using the * TLS protocol rules */ #define COP_FLAG_AEAD_SRTP_TYPE (1 << 5) /* authenticate and encrypt using the * SRTP protocol rules */ #define COP_FLAG_RESET (1 << 6) /* multi-update reset the state. * should be used in combination * with COP_FLAG_UPDATE */ /* Stuff for bignum arithmetic and public key * cryptography - not supported yet by linux * cryptodev. */ #define CRYPTO_ALG_FLAG_SUPPORTED 1 #define CRYPTO_ALG_FLAG_RNG_ENABLE 2 #define CRYPTO_ALG_FLAG_DSA_SHA 4 struct crparam { __u8 *crp_p; __u32 crp_nbits; }; #define CRK_MAXPARAM 8 /* input of CIOCKEY */ struct crypt_kop { __u32 crk_op; /* cryptodev_crk_ot_t */ __u32 crk_status; __u16 crk_iparams; __u16 crk_oparams; __u32 crk_pad1; struct crparam crk_param[CRK_MAXPARAM]; }; enum cryptodev_crk_op_t { CRK_MOD_EXP = 0, CRK_MOD_EXP_CRT = 1, CRK_DSA_SIGN = 2, CRK_DSA_VERIFY = 3, CRK_DH_COMPUTE_KEY = 4, CRK_ALGORITHM_ALL }; #define CRK_ALGORITHM_MAX (CRK_ALGORITHM_ALL-1) /* features to be queried with CIOCASYMFEAT ioctl */ #define CRF_MOD_EXP (1 << CRK_MOD_EXP) #define CRF_MOD_EXP_CRT (1 << CRK_MOD_EXP_CRT) #define CRF_DSA_SIGN (1 << CRK_DSA_SIGN) #define CRF_DSA_VERIFY (1 << CRK_DSA_VERIFY) #define CRF_DH_COMPUTE_KEY (1 << CRK_DH_COMPUTE_KEY) /* ioctl's. Compatible with old linux cryptodev.h */ #define CRIOGET _IOWR('c', 101, __u32) #define CIOCGSESSION _IOWR('c', 102, struct session_op) #define CIOCFSESSION _IOW('c', 103, __u32) #define CIOCCRYPT _IOWR('c', 104, struct crypt_op) #define CIOCKEY _IOWR('c', 105, struct crypt_kop) #define CIOCASYMFEAT _IOR('c', 106, __u32) #define CIOCGSESSINFO _IOWR('c', 107, struct session_info_op) /* to indicate that CRIOGET is not required in linux */ #define CRIOGET_NOT_NEEDED 1 /* additional ioctls for asynchronous operation */ #define CIOCASYNCCRYPT _IOW('c', 107, struct crypt_op) #define CIOCASYNCFETCH _IOR('c', 108, struct crypt_op) /* additional ioctls for AEAD */ #define CIOCAUTHCRYPT _IOWR('c', 109, struct crypt_auth_op) #endif /* L_CRYPTODEV_H */ cryptodev-linux-1.6/crypto/cryptodev.h0000644000175100017510000002162512115015315016732 0ustar nmavnmav/* This is a source compatible implementation with the original API of * cryptodev by Angelos D. Keromytis, found at openbsd cryptodev.h. * Placed under public domain */ #ifndef L_CRYPTODEV_H #define L_CRYPTODEV_H #include #ifndef __KERNEL__ #define __user #endif /* API extensions for linux */ #define CRYPTO_HMAC_MAX_KEY_LEN 512 #define CRYPTO_CIPHER_MAX_KEY_LEN 64 /* All the supported algorithms */ enum cryptodev_crypto_op_t { CRYPTO_DES_CBC = 1, CRYPTO_3DES_CBC = 2, CRYPTO_BLF_CBC = 3, CRYPTO_CAST_CBC = 4, CRYPTO_SKIPJACK_CBC = 5, CRYPTO_MD5_HMAC = 6, CRYPTO_SHA1_HMAC = 7, CRYPTO_RIPEMD160_HMAC = 8, CRYPTO_MD5_KPDK = 9, CRYPTO_SHA1_KPDK = 10, CRYPTO_RIJNDAEL128_CBC = 11, CRYPTO_AES_CBC = CRYPTO_RIJNDAEL128_CBC, CRYPTO_ARC4 = 12, CRYPTO_MD5 = 13, CRYPTO_SHA1 = 14, CRYPTO_DEFLATE_COMP = 15, CRYPTO_NULL = 16, CRYPTO_LZS_COMP = 17, CRYPTO_SHA2_256_HMAC = 18, CRYPTO_SHA2_384_HMAC = 19, CRYPTO_SHA2_512_HMAC = 20, CRYPTO_AES_CTR = 21, CRYPTO_AES_XTS = 22, CRYPTO_AES_ECB = 23, CRYPTO_AES_GCM = 50, CRYPTO_CAMELLIA_CBC = 101, CRYPTO_RIPEMD160, CRYPTO_SHA2_224, CRYPTO_SHA2_256, CRYPTO_SHA2_384, CRYPTO_SHA2_512, CRYPTO_SHA2_224_HMAC, CRYPTO_ALGORITHM_ALL, /* Keep updated - see below */ }; #define CRYPTO_ALGORITHM_MAX (CRYPTO_ALGORITHM_ALL - 1) /* Values for ciphers */ #define DES_BLOCK_LEN 8 #define DES3_BLOCK_LEN 8 #define RIJNDAEL128_BLOCK_LEN 16 #define AES_BLOCK_LEN RIJNDAEL128_BLOCK_LEN #define CAMELLIA_BLOCK_LEN 16 #define BLOWFISH_BLOCK_LEN 8 #define SKIPJACK_BLOCK_LEN 8 #define CAST128_BLOCK_LEN 8 /* the maximum of the above */ #define EALG_MAX_BLOCK_LEN 16 /* Values for hashes/MAC */ #define AALG_MAX_RESULT_LEN 64 /* maximum length of verbose alg names (depends on CRYPTO_MAX_ALG_NAME) */ #define CRYPTODEV_MAX_ALG_NAME 64 #define HASH_MAX_LEN 64 /* input of CIOCGSESSION */ struct session_op { /* Specify either cipher or mac */ __u32 cipher; /* cryptodev_crypto_op_t */ __u32 mac; /* cryptodev_crypto_op_t */ __u32 keylen; __u8 __user *key; __u32 mackeylen; __u8 __user *mackey; __u32 ses; /* session identifier */ }; struct session_info_op { __u32 ses; /* session identifier */ /* verbose names for the requested ciphers */ struct alg_info { char cra_name[CRYPTODEV_MAX_ALG_NAME]; char cra_driver_name[CRYPTODEV_MAX_ALG_NAME]; } cipher_info, hash_info; __u16 alignmask; /* alignment constraints */ __u32 flags; /* SIOP_FLAGS_* */ }; /* If this flag is set then this algorithm uses * a driver only available in kernel (software drivers, * or drivers based on instruction sets do not set this flag). * * If multiple algorithms are involved (as in AEAD case), then * if one of them is kernel-driver-only this flag will be set. */ #define SIOP_FLAG_KERNEL_DRIVER_ONLY 1 #define COP_ENCRYPT 0 #define COP_DECRYPT 1 /* input of CIOCCRYPT */ struct crypt_op { __u32 ses; /* session identifier */ __u16 op; /* COP_ENCRYPT or COP_DECRYPT */ __u16 flags; /* see COP_FLAG_* */ __u32 len; /* length of source data */ __u8 __user *src; /* source data */ __u8 __user *dst; /* pointer to output data */ /* pointer to output data for hash/MAC operations */ __u8 __user *mac; /* initialization vector for encryption operations */ __u8 __user *iv; }; /* input of CIOCAUTHCRYPT */ struct crypt_auth_op { __u32 ses; /* session identifier */ __u16 op; /* COP_ENCRYPT or COP_DECRYPT */ __u16 flags; /* see COP_FLAG_AEAD_* */ __u32 len; /* length of source data */ __u32 auth_len; /* length of auth data */ __u8 __user *auth_src; /* authenticated-only data */ /* The current implementation is more efficient if data are * encrypted in-place (src==dst). */ __u8 __user *src; /* data to be encrypted and authenticated */ __u8 __user *dst; /* pointer to output data. Must have * space for tag. For TLS this should be at least * len + tag_size + block_size for padding */ __u8 __user *tag; /* where the tag will be copied to. TLS mode * doesn't use that as tag is copied to dst. * SRTP mode copies tag there. */ __u32 tag_len; /* the length of the tag. Use zero for digest size or max tag. */ /* initialization vector for encryption operations */ __u8 __user *iv; __u32 iv_len; }; /* In plain AEAD mode the following are required: * flags : 0 * iv : the initialization vector (12 bytes) * auth_len: the length of the data to be authenticated * auth_src: the data to be authenticated * len : length of data to be encrypted * src : the data to be encrypted * dst : space to hold encrypted data. It must have * at least a size of len + tag_size. * tag_size: the size of the desired authentication tag or zero to use * the maximum tag output. * * Note tag isn't being used because the Linux AEAD interface * copies the tag just after data. */ /* In TLS mode (used for CBC ciphers that required padding) * the following are required: * flags : COP_FLAG_AEAD_TLS_TYPE * iv : the initialization vector * auth_len: the length of the data to be authenticated only * len : length of data to be encrypted * auth_src: the data to be authenticated * src : the data to be encrypted * dst : space to hold encrypted data (preferably in-place). It must have * at least a size of len + tag_size + blocksize. * tag_size: the size of the desired authentication tag or zero to use * the default mac output. * * Note that the padding used is the minimum padding. */ /* In SRTP mode the following are required: * flags : COP_FLAG_AEAD_SRTP_TYPE * iv : the initialization vector * auth_len: the length of the data to be authenticated. This must * include the SRTP header + SRTP payload (data to be encrypted) + rest * * len : length of data to be encrypted * auth_src: pointer the data to be authenticated. Should point at the same buffer as src. * src : pointer to the data to be encrypted. * dst : This is mandatory to be the same as src (in-place only). * tag_size: the size of the desired authentication tag or zero to use * the default mac output. * tag : Pointer to an address where the authentication tag will be copied. */ /* struct crypt_op flags */ #define COP_FLAG_NONE (0 << 0) /* totally no flag */ #define COP_FLAG_UPDATE (1 << 0) /* multi-update hash mode */ #define COP_FLAG_FINAL (1 << 1) /* multi-update final hash mode */ #define COP_FLAG_WRITE_IV (1 << 2) /* update the IV during operation */ #define COP_FLAG_NO_ZC (1 << 3) /* do not zero-copy */ #define COP_FLAG_AEAD_TLS_TYPE (1 << 4) /* authenticate and encrypt using the * TLS protocol rules */ #define COP_FLAG_AEAD_SRTP_TYPE (1 << 5) /* authenticate and encrypt using the * SRTP protocol rules */ #define COP_FLAG_RESET (1 << 6) /* multi-update reset the state. * should be used in combination * with COP_FLAG_UPDATE */ /* Stuff for bignum arithmetic and public key * cryptography - not supported yet by linux * cryptodev. */ #define CRYPTO_ALG_FLAG_SUPPORTED 1 #define CRYPTO_ALG_FLAG_RNG_ENABLE 2 #define CRYPTO_ALG_FLAG_DSA_SHA 4 struct crparam { __u8 *crp_p; __u32 crp_nbits; }; #define CRK_MAXPARAM 8 /* input of CIOCKEY */ struct crypt_kop { __u32 crk_op; /* cryptodev_crk_ot_t */ __u32 crk_status; __u16 crk_iparams; __u16 crk_oparams; __u32 crk_pad1; struct crparam crk_param[CRK_MAXPARAM]; }; enum cryptodev_crk_op_t { CRK_MOD_EXP = 0, CRK_MOD_EXP_CRT = 1, CRK_DSA_SIGN = 2, CRK_DSA_VERIFY = 3, CRK_DH_COMPUTE_KEY = 4, CRK_ALGORITHM_ALL }; #define CRK_ALGORITHM_MAX (CRK_ALGORITHM_ALL-1) /* features to be queried with CIOCASYMFEAT ioctl */ #define CRF_MOD_EXP (1 << CRK_MOD_EXP) #define CRF_MOD_EXP_CRT (1 << CRK_MOD_EXP_CRT) #define CRF_DSA_SIGN (1 << CRK_DSA_SIGN) #define CRF_DSA_VERIFY (1 << CRK_DSA_VERIFY) #define CRF_DH_COMPUTE_KEY (1 << CRK_DH_COMPUTE_KEY) /* ioctl's. Compatible with old linux cryptodev.h */ #define CRIOGET _IOWR('c', 101, __u32) #define CIOCGSESSION _IOWR('c', 102, struct session_op) #define CIOCFSESSION _IOW('c', 103, __u32) #define CIOCCRYPT _IOWR('c', 104, struct crypt_op) #define CIOCKEY _IOWR('c', 105, struct crypt_kop) #define CIOCASYMFEAT _IOR('c', 106, __u32) #define CIOCGSESSINFO _IOWR('c', 107, struct session_info_op) /* to indicate that CRIOGET is not required in linux */ #define CRIOGET_NOT_NEEDED 1 /* additional ioctls for AEAD */ #define CIOCAUTHCRYPT _IOWR('c', 109, struct crypt_auth_op) /* additional ioctls for asynchronous operation. * These are conditionally enabled since version 1.6. */ #define CIOCASYNCCRYPT _IOW('c', 110, struct crypt_op) #define CIOCASYNCFETCH _IOR('c', 111, struct crypt_op) #endif /* L_CRYPTODEV_H */ cryptodev-linux-1.6/util.c0000644000175100017510000000370112102243276014343 0ustar nmavnmav/* * Copyright (c) 2011 Maxim Levitsky * * This file is part of linux cryptodev. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include "util.h" /* These were taken from Maxim Levitsky's patch to lkml. */ struct scatterlist *sg_advance(struct scatterlist *sg, int consumed) { while (consumed >= sg->length) { consumed -= sg->length; sg = sg_next(sg); if (!sg) break; } WARN_ON(!sg && consumed); if (!sg) return NULL; sg->offset += consumed; sg->length -= consumed; if (sg->offset >= PAGE_SIZE) { struct page *page = nth_page(sg_page(sg), sg->offset / PAGE_SIZE); sg_set_page(sg, page, sg->length, sg->offset % PAGE_SIZE); } return sg; } /** * sg_copy - copies sg entries from sg_from to sg_to, such * as sg_to covers first 'len' bytes from sg_from. */ int sg_copy(struct scatterlist *sg_from, struct scatterlist *sg_to, int len) { while (len > sg_from->length) { len -= sg_from->length; sg_set_page(sg_to, sg_page(sg_from), sg_from->length, sg_from->offset); sg_to = sg_next(sg_to); sg_from = sg_next(sg_from); if (len && (!sg_from || !sg_to)) return -ENOMEM; } if (len) sg_set_page(sg_to, sg_page(sg_from), len, sg_from->offset); sg_mark_end(sg_to); return 0; } cryptodev-linux-1.6/zc.h0000644000175100017510000000155312102243276014012 0ustar nmavnmav#ifndef ZC_H # define ZC_H #include "cryptodev_int.h" /* For zero copy */ int __get_userbuf(uint8_t __user *addr, uint32_t len, int write, unsigned int pgcount, struct page **pg, struct scatterlist *sg, struct task_struct *task, struct mm_struct *mm); void release_user_pages(struct csession* ses); int get_userbuf(struct csession *ses, void* __user src, unsigned int src_len, void* __user dst, unsigned int dst_len, struct task_struct *task, struct mm_struct *mm, struct scatterlist **src_sg, struct scatterlist **dst_sg); /* buflen ? (last page - first page + 1) : 0 */ #define PAGECOUNT(buf, buflen) ((buflen) \ ? ((((unsigned long)(buf + buflen - 1)) >> PAGE_SHIFT) - \ (((unsigned long)(buf )) >> PAGE_SHIFT) + 1) \ : 0) #define DEFAULT_PREALLOC_PAGES 32 #endif cryptodev-linux-1.6/cryptlib.c0000644000175100017510000002301712102243276015220 0ustar nmavnmav/* * Driver for /dev/crypto device (aka CryptoDev) * * Copyright (c) 2010,2011 Nikos Mavrogiannopoulos * Portions Copyright (c) 2010 Michael Weiser * Portions Copyright (c) 2010 Phil Sutter * * This file is part of linux cryptodev. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include "cryptodev_int.h" struct cryptodev_result { struct completion completion; int err; }; static void cryptodev_complete(struct crypto_async_request *req, int err) { struct cryptodev_result *res = req->data; if (err == -EINPROGRESS) return; res->err = err; complete(&res->completion); } int cryptodev_cipher_init(struct cipher_data *out, const char *alg_name, uint8_t *keyp, size_t keylen, int stream, int aead) { int ret; memset(out, 0, sizeof(*out)); if (aead == 0) { struct ablkcipher_alg *alg; out->async.s = crypto_alloc_ablkcipher(alg_name, 0, 0); if (unlikely(IS_ERR(out->async.s))) { dprintk(1, KERN_DEBUG, "Failed to load cipher %s\n", alg_name); return -EINVAL; } alg = crypto_ablkcipher_alg(out->async.s); if (alg != NULL) { /* Was correct key length supplied? */ if (alg->max_keysize > 0 && unlikely((keylen < alg->min_keysize) || (keylen > alg->max_keysize))) { dprintk(1, KERN_DEBUG, "Wrong keylen '%zu' for algorithm '%s'. \ Use %u to %u.\n", keylen, alg_name, alg->min_keysize, alg->max_keysize); ret = -EINVAL; goto error; } } out->blocksize = crypto_ablkcipher_blocksize(out->async.s); out->ivsize = crypto_ablkcipher_ivsize(out->async.s); out->alignmask = crypto_ablkcipher_alignmask(out->async.s); ret = crypto_ablkcipher_setkey(out->async.s, keyp, keylen); } else { out->async.as = crypto_alloc_aead(alg_name, 0, 0); if (unlikely(IS_ERR(out->async.as))) { dprintk(1, KERN_DEBUG, "Failed to load cipher %s\n", alg_name); return -EINVAL; } out->blocksize = crypto_aead_blocksize(out->async.as); out->ivsize = crypto_aead_ivsize(out->async.as); out->alignmask = crypto_aead_alignmask(out->async.as); ret = crypto_aead_setkey(out->async.as, keyp, keylen); } if (unlikely(ret)) { dprintk(1, KERN_DEBUG, "Setting key failed for %s-%zu.\n", alg_name, keylen*8); ret = -EINVAL; goto error; } out->stream = stream; out->aead = aead; out->async.result = kmalloc(sizeof(*out->async.result), GFP_KERNEL); if (unlikely(!out->async.result)) { ret = -ENOMEM; goto error; } memset(out->async.result, 0, sizeof(*out->async.result)); init_completion(&out->async.result->completion); if (aead == 0) { out->async.request = ablkcipher_request_alloc(out->async.s, GFP_KERNEL); if (unlikely(!out->async.request)) { dprintk(1, KERN_ERR, "error allocating async crypto request\n"); ret = -ENOMEM; goto error; } ablkcipher_request_set_callback(out->async.request, CRYPTO_TFM_REQ_MAY_BACKLOG, cryptodev_complete, out->async.result); } else { out->async.arequest = aead_request_alloc(out->async.as, GFP_KERNEL); if (unlikely(!out->async.arequest)) { dprintk(1, KERN_ERR, "error allocating async crypto request\n"); ret = -ENOMEM; goto error; } aead_request_set_callback(out->async.arequest, CRYPTO_TFM_REQ_MAY_BACKLOG, cryptodev_complete, out->async.result); } out->init = 1; return 0; error: if (aead == 0) { if (out->async.request) ablkcipher_request_free(out->async.request); if (out->async.s) crypto_free_ablkcipher(out->async.s); } else { if (out->async.arequest) aead_request_free(out->async.arequest); if (out->async.s) crypto_free_aead(out->async.as); } kfree(out->async.result); return ret; } void cryptodev_cipher_deinit(struct cipher_data *cdata) { if (cdata->init) { if (cdata->aead == 0) { if (cdata->async.request) ablkcipher_request_free(cdata->async.request); if (cdata->async.s) crypto_free_ablkcipher(cdata->async.s); } else { if (cdata->async.arequest) aead_request_free(cdata->async.arequest); if (cdata->async.as) crypto_free_aead(cdata->async.as); } kfree(cdata->async.result); cdata->init = 0; } } static inline int waitfor(struct cryptodev_result *cr, ssize_t ret) { switch (ret) { case 0: break; case -EINPROGRESS: case -EBUSY: wait_for_completion(&cr->completion); /* At this point we known for sure the request has finished, * because wait_for_completion above was not interruptible. * This is important because otherwise hardware or driver * might try to access memory which will be freed or reused for * another request. */ if (unlikely(cr->err)) { dprintk(0, KERN_ERR, "error from async request: %d\n", cr->err); return cr->err; } break; default: return ret; } return 0; } ssize_t cryptodev_cipher_encrypt(struct cipher_data *cdata, const struct scatterlist *src, struct scatterlist *dst, size_t len) { int ret; INIT_COMPLETION(cdata->async.result->completion); if (cdata->aead == 0) { ablkcipher_request_set_crypt(cdata->async.request, (struct scatterlist *)src, dst, len, cdata->async.iv); ret = crypto_ablkcipher_encrypt(cdata->async.request); } else { aead_request_set_crypt(cdata->async.arequest, (struct scatterlist *)src, dst, len, cdata->async.iv); ret = crypto_aead_encrypt(cdata->async.arequest); } return waitfor(cdata->async.result, ret); } ssize_t cryptodev_cipher_decrypt(struct cipher_data *cdata, const struct scatterlist *src, struct scatterlist *dst, size_t len) { int ret; INIT_COMPLETION(cdata->async.result->completion); if (cdata->aead == 0) { ablkcipher_request_set_crypt(cdata->async.request, (struct scatterlist *)src, dst, len, cdata->async.iv); ret = crypto_ablkcipher_decrypt(cdata->async.request); } else { aead_request_set_crypt(cdata->async.arequest, (struct scatterlist *)src, dst, len, cdata->async.iv); ret = crypto_aead_decrypt(cdata->async.arequest); } return waitfor(cdata->async.result, ret); } /* Hash functions */ int cryptodev_hash_init(struct hash_data *hdata, const char *alg_name, int hmac_mode, void *mackey, size_t mackeylen) { int ret; hdata->async.s = crypto_alloc_ahash(alg_name, 0, 0); if (unlikely(IS_ERR(hdata->async.s))) { dprintk(1, KERN_DEBUG, "Failed to load transform for %s\n", alg_name); return -EINVAL; } /* Copy the key from user and set to TFM. */ if (hmac_mode != 0) { ret = crypto_ahash_setkey(hdata->async.s, mackey, mackeylen); if (unlikely(ret)) { dprintk(1, KERN_DEBUG, "Setting hmac key failed for %s-%zu.\n", alg_name, mackeylen*8); ret = -EINVAL; goto error; } } hdata->digestsize = crypto_ahash_digestsize(hdata->async.s); hdata->alignmask = crypto_ahash_alignmask(hdata->async.s); hdata->async.result = kmalloc(sizeof(*hdata->async.result), GFP_KERNEL); if (unlikely(!hdata->async.result)) { ret = -ENOMEM; goto error; } memset(hdata->async.result, 0, sizeof(*hdata->async.result)); init_completion(&hdata->async.result->completion); hdata->async.request = ahash_request_alloc(hdata->async.s, GFP_KERNEL); if (unlikely(!hdata->async.request)) { dprintk(0, KERN_ERR, "error allocating async crypto request\n"); ret = -ENOMEM; goto error; } ahash_request_set_callback(hdata->async.request, CRYPTO_TFM_REQ_MAY_BACKLOG, cryptodev_complete, hdata->async.result); ret = crypto_ahash_init(hdata->async.request); if (unlikely(ret)) { dprintk(0, KERN_ERR, "error in crypto_hash_init()\n"); goto error_request; } hdata->init = 1; return 0; error_request: ahash_request_free(hdata->async.request); error: kfree(hdata->async.result); crypto_free_ahash(hdata->async.s); return ret; } void cryptodev_hash_deinit(struct hash_data *hdata) { if (hdata->init) { if (hdata->async.request) ahash_request_free(hdata->async.request); kfree(hdata->async.result); if (hdata->async.s) crypto_free_ahash(hdata->async.s); hdata->init = 0; } } int cryptodev_hash_reset(struct hash_data *hdata) { int ret; ret = crypto_ahash_init(hdata->async.request); if (unlikely(ret)) { dprintk(0, KERN_ERR, "error in crypto_hash_init()\n"); return ret; } return 0; } ssize_t cryptodev_hash_update(struct hash_data *hdata, struct scatterlist *sg, size_t len) { int ret; INIT_COMPLETION(hdata->async.result->completion); ahash_request_set_crypt(hdata->async.request, sg, NULL, len); ret = crypto_ahash_update(hdata->async.request); return waitfor(hdata->async.result, ret); } int cryptodev_hash_final(struct hash_data *hdata, void* output) { int ret; INIT_COMPLETION(hdata->async.result->completion); ahash_request_set_crypt(hdata->async.request, NULL, output, 0); ret = crypto_ahash_final(hdata->async.request); return waitfor(hdata->async.result, ret); } cryptodev-linux-1.6/ioctl.c0000644000175100017510000006535012115015535014507 0ustar nmavnmav/* * Driver for /dev/crypto device (aka CryptoDev) * * Copyright (c) 2004 Michal Ludvig , SuSE Labs * Copyright (c) 2009,2010,2011 Nikos Mavrogiannopoulos * Copyright (c) 2010 Phil Sutter * * This file is part of linux cryptodev. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * Device /dev/crypto provides an interface for * accessing kernel CryptoAPI algorithms (ciphers, * hashes) from userspace programs. * * /dev/crypto interface was originally introduced in * OpenBSD and this module attempts to keep the API. * */ #include #include #include #include #include #include #include #include #include #include #include #include #include "cryptodev_int.h" #include "zc.h" #include "version.h" MODULE_AUTHOR("Nikos Mavrogiannopoulos "); MODULE_DESCRIPTION("CryptoDev driver"); MODULE_LICENSE("GPL"); /* ====== Compile-time config ====== */ /* Default (pre-allocated) and maximum size of the job queue. * These are free, pending and done items all together. */ #define DEF_COP_RINGSIZE 16 #define MAX_COP_RINGSIZE 64 /* ====== Module parameters ====== */ int cryptodev_verbosity; module_param(cryptodev_verbosity, int, 0644); MODULE_PARM_DESC(cryptodev_verbosity, "0: normal, 1: verbose, 2: debug"); /* ====== CryptoAPI ====== */ struct todo_list_item { struct list_head __hook; struct kernel_crypt_op kcop; int result; }; struct locked_list { struct list_head list; struct mutex lock; }; struct crypt_priv { struct fcrypt fcrypt; struct locked_list free, todo, done; int itemcount; struct work_struct cryptask; wait_queue_head_t user_waiter; }; #define FILL_SG(sg, ptr, len) \ do { \ (sg)->page = virt_to_page(ptr); \ (sg)->offset = offset_in_page(ptr); \ (sg)->length = len; \ (sg)->dma_address = 0; \ } while (0) /* cryptodev's own workqueue, keeps crypto tasks from disturbing the force */ static struct workqueue_struct *cryptodev_wq; /* Prepare session for future use. */ static int crypto_create_session(struct fcrypt *fcr, struct session_op *sop) { struct csession *ses_new = NULL, *ses_ptr; int ret = 0; const char *alg_name = NULL; const char *hash_name = NULL; int hmac_mode = 1, stream = 0, aead = 0; /* Does the request make sense? */ if (unlikely(!sop->cipher && !sop->mac)) { dprintk(1, KERN_DEBUG, "Both 'cipher' and 'mac' unset.\n"); return -EINVAL; } switch (sop->cipher) { case 0: break; case CRYPTO_DES_CBC: alg_name = "cbc(des)"; break; case CRYPTO_3DES_CBC: alg_name = "cbc(des3_ede)"; break; case CRYPTO_BLF_CBC: alg_name = "cbc(blowfish)"; break; case CRYPTO_AES_CBC: alg_name = "cbc(aes)"; break; case CRYPTO_AES_ECB: alg_name = "ecb(aes)"; break; case CRYPTO_CAMELLIA_CBC: alg_name = "cbc(camellia)"; break; case CRYPTO_AES_CTR: alg_name = "ctr(aes)"; stream = 1; break; case CRYPTO_AES_GCM: alg_name = "gcm(aes)"; stream = 1; aead = 1; break; case CRYPTO_NULL: alg_name = "ecb(cipher_null)"; stream = 1; break; default: dprintk(1, KERN_DEBUG, "bad cipher: %d\n", sop->cipher); return -EINVAL; } switch (sop->mac) { case 0: break; case CRYPTO_MD5_HMAC: hash_name = "hmac(md5)"; break; case CRYPTO_RIPEMD160_HMAC: hash_name = "hmac(rmd160)"; break; case CRYPTO_SHA1_HMAC: hash_name = "hmac(sha1)"; break; case CRYPTO_SHA2_224_HMAC: hash_name = "hmac(sha224)"; break; case CRYPTO_SHA2_256_HMAC: hash_name = "hmac(sha256)"; break; case CRYPTO_SHA2_384_HMAC: hash_name = "hmac(sha384)"; break; case CRYPTO_SHA2_512_HMAC: hash_name = "hmac(sha512)"; break; /* non-hmac cases */ case CRYPTO_MD5: hash_name = "md5"; hmac_mode = 0; break; case CRYPTO_RIPEMD160: hash_name = "rmd160"; hmac_mode = 0; break; case CRYPTO_SHA1: hash_name = "sha1"; hmac_mode = 0; break; case CRYPTO_SHA2_224: hash_name = "sha224"; hmac_mode = 0; break; case CRYPTO_SHA2_256: hash_name = "sha256"; hmac_mode = 0; break; case CRYPTO_SHA2_384: hash_name = "sha384"; hmac_mode = 0; break; case CRYPTO_SHA2_512: hash_name = "sha512"; hmac_mode = 0; break; default: dprintk(1, KERN_DEBUG, "bad mac: %d\n", sop->mac); return -EINVAL; } /* Create a session and put it to the list. */ ses_new = kzalloc(sizeof(*ses_new), GFP_KERNEL); if (!ses_new) return -ENOMEM; /* Set-up crypto transform. */ if (alg_name) { uint8_t keyp[CRYPTO_CIPHER_MAX_KEY_LEN]; if (unlikely(sop->keylen > CRYPTO_CIPHER_MAX_KEY_LEN)) { dprintk(1, KERN_DEBUG, "Setting key failed for %s-%zu.\n", alg_name, (size_t)sop->keylen*8); ret = -EINVAL; goto error_cipher; } if (unlikely(copy_from_user(keyp, sop->key, sop->keylen))) { ret = -EFAULT; goto error_cipher; } ret = cryptodev_cipher_init(&ses_new->cdata, alg_name, keyp, sop->keylen, stream, aead); if (ret < 0) { dprintk(1, KERN_DEBUG, "Failed to load cipher for %s\n", alg_name); ret = -EINVAL; goto error_cipher; } } if (hash_name && aead == 0) { uint8_t keyp[CRYPTO_HMAC_MAX_KEY_LEN]; if (unlikely(sop->mackeylen > CRYPTO_HMAC_MAX_KEY_LEN)) { dprintk(1, KERN_DEBUG, "Setting key failed for %s-%zu.\n", alg_name, (size_t)sop->mackeylen*8); ret = -EINVAL; goto error_hash; } if (sop->mackey && unlikely(copy_from_user(keyp, sop->mackey, sop->mackeylen))) { ret = -EFAULT; goto error_hash; } ret = cryptodev_hash_init(&ses_new->hdata, hash_name, hmac_mode, keyp, sop->mackeylen); if (ret != 0) { dprintk(1, KERN_DEBUG, "Failed to load hash for %s\n", hash_name); ret = -EINVAL; goto error_hash; } } ses_new->alignmask = max(ses_new->cdata.alignmask, ses_new->hdata.alignmask); dprintk(2, KERN_DEBUG, "got alignmask %d\n", ses_new->alignmask); ses_new->array_size = DEFAULT_PREALLOC_PAGES; dprintk(2, KERN_DEBUG, "preallocating for %d user pages\n", ses_new->array_size); ses_new->pages = kzalloc(ses_new->array_size * sizeof(struct page *), GFP_KERNEL); ses_new->sg = kzalloc(ses_new->array_size * sizeof(struct scatterlist), GFP_KERNEL); if (ses_new->sg == NULL || ses_new->pages == NULL) { dprintk(0, KERN_DEBUG, "Memory error\n"); ret = -ENOMEM; goto error_hash; } /* put the new session to the list */ get_random_bytes(&ses_new->sid, sizeof(ses_new->sid)); mutex_init(&ses_new->sem); mutex_lock(&fcr->sem); restart: list_for_each_entry(ses_ptr, &fcr->list, entry) { /* Check for duplicate SID */ if (unlikely(ses_new->sid == ses_ptr->sid)) { get_random_bytes(&ses_new->sid, sizeof(ses_new->sid)); /* Unless we have a broken RNG this shouldn't loop forever... ;-) */ goto restart; } } list_add(&ses_new->entry, &fcr->list); mutex_unlock(&fcr->sem); /* Fill in some values for the user. */ sop->ses = ses_new->sid; return 0; error_hash: cryptodev_cipher_deinit(&ses_new->cdata); kfree(ses_new->sg); kfree(ses_new->pages); error_cipher: kfree(ses_new); return ret; } /* Everything that needs to be done when remowing a session. */ static inline void crypto_destroy_session(struct csession *ses_ptr) { if (!mutex_trylock(&ses_ptr->sem)) { dprintk(2, KERN_DEBUG, "Waiting for semaphore of sid=0x%08X\n", ses_ptr->sid); mutex_lock(&ses_ptr->sem); } dprintk(2, KERN_DEBUG, "Removed session 0x%08X\n", ses_ptr->sid); cryptodev_cipher_deinit(&ses_ptr->cdata); cryptodev_hash_deinit(&ses_ptr->hdata); dprintk(2, KERN_DEBUG, "freeing space for %d user pages\n", ses_ptr->array_size); kfree(ses_ptr->pages); kfree(ses_ptr->sg); mutex_unlock(&ses_ptr->sem); kfree(ses_ptr); } /* Look up a session by ID and remove. */ static int crypto_finish_session(struct fcrypt *fcr, uint32_t sid) { struct csession *tmp, *ses_ptr; struct list_head *head; int ret = 0; mutex_lock(&fcr->sem); head = &fcr->list; list_for_each_entry_safe(ses_ptr, tmp, head, entry) { if (ses_ptr->sid == sid) { list_del(&ses_ptr->entry); crypto_destroy_session(ses_ptr); break; } } if (unlikely(!ses_ptr)) { dprintk(1, KERN_ERR, "Session with sid=0x%08X not found!\n", sid); ret = -ENOENT; } mutex_unlock(&fcr->sem); return ret; } /* Remove all sessions when closing the file */ static int crypto_finish_all_sessions(struct fcrypt *fcr) { struct csession *tmp, *ses_ptr; struct list_head *head; mutex_lock(&fcr->sem); head = &fcr->list; list_for_each_entry_safe(ses_ptr, tmp, head, entry) { list_del(&ses_ptr->entry); crypto_destroy_session(ses_ptr); } mutex_unlock(&fcr->sem); return 0; } /* Look up session by session ID. The returned session is locked. */ struct csession * crypto_get_session_by_sid(struct fcrypt *fcr, uint32_t sid) { struct csession *ses_ptr, *retval = NULL; if (unlikely(fcr == NULL)) return NULL; mutex_lock(&fcr->sem); list_for_each_entry(ses_ptr, &fcr->list, entry) { if (ses_ptr->sid == sid) { mutex_lock(&ses_ptr->sem); retval = ses_ptr; break; } } mutex_unlock(&fcr->sem); return retval; } static void cryptask_routine(struct work_struct *work) { struct crypt_priv *pcr = container_of(work, struct crypt_priv, cryptask); struct todo_list_item *item; LIST_HEAD(tmp); /* fetch all pending jobs into the temporary list */ mutex_lock(&pcr->todo.lock); list_cut_position(&tmp, &pcr->todo.list, pcr->todo.list.prev); mutex_unlock(&pcr->todo.lock); /* handle each job locklessly */ list_for_each_entry(item, &tmp, __hook) { item->result = crypto_run(&pcr->fcrypt, &item->kcop); if (unlikely(item->result)) dprintk(0, KERN_ERR, "crypto_run() failed: %d\n", item->result); } /* push all handled jobs to the done list at once */ mutex_lock(&pcr->done.lock); list_splice_tail(&tmp, &pcr->done.list); mutex_unlock(&pcr->done.lock); /* wake for POLLIN */ wake_up_interruptible(&pcr->user_waiter); } /* ====== /dev/crypto ====== */ static int cryptodev_open(struct inode *inode, struct file *filp) { struct todo_list_item *tmp; struct crypt_priv *pcr; int i; pcr = kmalloc(sizeof(*pcr), GFP_KERNEL); if (!pcr) return -ENOMEM; memset(pcr, 0, sizeof(*pcr)); mutex_init(&pcr->fcrypt.sem); INIT_LIST_HEAD(&pcr->fcrypt.list); INIT_LIST_HEAD(&pcr->free.list); INIT_LIST_HEAD(&pcr->todo.list); INIT_LIST_HEAD(&pcr->done.list); INIT_WORK(&pcr->cryptask, cryptask_routine); mutex_init(&pcr->free.lock); mutex_init(&pcr->todo.lock); mutex_init(&pcr->done.lock); init_waitqueue_head(&pcr->user_waiter); for (i = 0; i < DEF_COP_RINGSIZE; i++) { tmp = kzalloc(sizeof(struct todo_list_item), GFP_KERNEL); if (!tmp) return -ENOMEM; pcr->itemcount++; dprintk(2, KERN_DEBUG, "allocated new item at %lx\n", (unsigned long)tmp); list_add(&tmp->__hook, &pcr->free.list); } filp->private_data = pcr; dprintk(2, KERN_DEBUG, "Cryptodev handle initialised, %d elements in queue\n", DEF_COP_RINGSIZE); return 0; } static int cryptodev_release(struct inode *inode, struct file *filp) { struct crypt_priv *pcr = filp->private_data; struct todo_list_item *item, *item_safe; int items_freed = 0; if (!pcr) return 0; cancel_work_sync(&pcr->cryptask); mutex_destroy(&pcr->todo.lock); mutex_destroy(&pcr->done.lock); mutex_destroy(&pcr->free.lock); list_splice_tail(&pcr->todo.list, &pcr->free.list); list_splice_tail(&pcr->done.list, &pcr->free.list); list_for_each_entry_safe(item, item_safe, &pcr->free.list, __hook) { dprintk(2, KERN_DEBUG, "freeing item at %lx\n", (unsigned long)item); list_del(&item->__hook); kfree(item); items_freed++; } if (items_freed != pcr->itemcount) { dprintk(0, KERN_ERR, "freed %d items, but %d should exist!\n", items_freed, pcr->itemcount); } crypto_finish_all_sessions(&pcr->fcrypt); kfree(pcr); filp->private_data = NULL; dprintk(2, KERN_DEBUG, "Cryptodev handle deinitialised, %d elements freed\n", items_freed); return 0; } static int clonefd(struct file *filp) { int ret; ret = get_unused_fd(); if (ret >= 0) { get_file(filp); fd_install(ret, filp); } return ret; } #ifdef ENABLE_ASYNC /* enqueue a job for asynchronous completion * * returns: * -EBUSY when there are no free queue slots left * (and the number of slots has reached it MAX_COP_RINGSIZE) * -EFAULT when there was a memory allocation error * 0 on success */ static int crypto_async_run(struct crypt_priv *pcr, struct kernel_crypt_op *kcop) { struct todo_list_item *item = NULL; if (unlikely(kcop->cop.flags & COP_FLAG_NO_ZC)) return -EINVAL; mutex_lock(&pcr->free.lock); if (likely(!list_empty(&pcr->free.list))) { item = list_first_entry(&pcr->free.list, struct todo_list_item, __hook); list_del(&item->__hook); } else if (pcr->itemcount < MAX_COP_RINGSIZE) { pcr->itemcount++; } else { mutex_unlock(&pcr->free.lock); return -EBUSY; } mutex_unlock(&pcr->free.lock); if (unlikely(!item)) { item = kzalloc(sizeof(struct todo_list_item), GFP_KERNEL); if (unlikely(!item)) return -EFAULT; dprintk(1, KERN_INFO, "increased item count to %d\n", pcr->itemcount); } memcpy(&item->kcop, kcop, sizeof(struct kernel_crypt_op)); mutex_lock(&pcr->todo.lock); list_add_tail(&item->__hook, &pcr->todo.list); mutex_unlock(&pcr->todo.lock); queue_work(cryptodev_wq, &pcr->cryptask); return 0; } /* get the first completed job from the "done" queue * * returns: * -EBUSY if no completed jobs are ready (yet) * the return value of crypto_run() otherwise */ static int crypto_async_fetch(struct crypt_priv *pcr, struct kernel_crypt_op *kcop) { struct todo_list_item *item; int retval; mutex_lock(&pcr->done.lock); if (list_empty(&pcr->done.list)) { mutex_unlock(&pcr->done.lock); return -EBUSY; } item = list_first_entry(&pcr->done.list, struct todo_list_item, __hook); list_del(&item->__hook); mutex_unlock(&pcr->done.lock); memcpy(kcop, &item->kcop, sizeof(struct kernel_crypt_op)); retval = item->result; mutex_lock(&pcr->free.lock); list_add_tail(&item->__hook, &pcr->free.list); mutex_unlock(&pcr->free.lock); /* wake for POLLOUT */ wake_up_interruptible(&pcr->user_waiter); return retval; } #endif /* this function has to be called from process context */ static int fill_kcop_from_cop(struct kernel_crypt_op *kcop, struct fcrypt *fcr) { struct crypt_op *cop = &kcop->cop; struct csession *ses_ptr; int rc; /* this also enters ses_ptr->sem */ ses_ptr = crypto_get_session_by_sid(fcr, cop->ses); if (unlikely(!ses_ptr)) { dprintk(1, KERN_ERR, "invalid session ID=0x%08X\n", cop->ses); return -EINVAL; } kcop->ivlen = cop->iv ? ses_ptr->cdata.ivsize : 0; kcop->digestsize = 0; /* will be updated during operation */ crypto_put_session(ses_ptr); kcop->task = current; kcop->mm = current->mm; if (cop->iv) { rc = copy_from_user(kcop->iv, cop->iv, kcop->ivlen); if (unlikely(rc)) { dprintk(1, KERN_ERR, "error copying IV (%d bytes), copy_from_user returned %d for address %lx\n", kcop->ivlen, rc, (unsigned long)cop->iv); return -EFAULT; } } return 0; } /* this function has to be called from process context */ static int fill_cop_from_kcop(struct kernel_crypt_op *kcop, struct fcrypt *fcr) { int ret; if (kcop->digestsize) { ret = copy_to_user(kcop->cop.mac, kcop->hash_output, kcop->digestsize); if (unlikely(ret)) return -EFAULT; } if (kcop->ivlen && kcop->cop.flags & COP_FLAG_WRITE_IV) { ret = copy_to_user(kcop->cop.iv, kcop->iv, kcop->ivlen); if (unlikely(ret)) return -EFAULT; } return 0; } static int kcop_from_user(struct kernel_crypt_op *kcop, struct fcrypt *fcr, void __user *arg) { if (unlikely(copy_from_user(&kcop->cop, arg, sizeof(kcop->cop)))) return -EFAULT; return fill_kcop_from_cop(kcop, fcr); } static int kcop_to_user(struct kernel_crypt_op *kcop, struct fcrypt *fcr, void __user *arg) { int ret; ret = fill_cop_from_kcop(kcop, fcr); if (unlikely(ret)) { dprintk(1, KERN_ERR, "Error in fill_cop_from_kcop\n"); return ret; } if (unlikely(copy_to_user(arg, &kcop->cop, sizeof(kcop->cop)))) { dprintk(1, KERN_ERR, "Cannot copy to userspace\n"); return -EFAULT; } return 0; } static inline void tfm_info_to_alg_info(struct alg_info *dst, struct crypto_tfm *tfm) { snprintf(dst->cra_name, CRYPTODEV_MAX_ALG_NAME, "%s", crypto_tfm_alg_name(tfm)); snprintf(dst->cra_driver_name, CRYPTODEV_MAX_ALG_NAME, "%s", crypto_tfm_alg_driver_name(tfm)); } static unsigned int is_known_accelerated(struct crypto_tfm *tfm) { const char* name = crypto_tfm_alg_driver_name(tfm); if (name == NULL) return 1; /* assume accelerated */ if (strstr(name, "-talitos")) return 1; else if (strncmp(name, "mv-", 3) == 0) return 1; else if (strstr(name, "geode")) return 1; else if (strstr(name, "hifn")) return 1; else if (strstr(name, "-ixp4xx")) return 1; else if (strstr(name, "-omap")) return 1; else if (strstr(name, "-picoxcell")) return 1; else if (strstr(name, "-s5p")) return 1; else if (strstr(name, "-ppc4xx")) return 1; else if (strstr(name, "-caam")) return 1; else if (strstr(name, "-n2")) return 1; return 0; } static int get_session_info(struct fcrypt *fcr, struct session_info_op *siop) { struct csession *ses_ptr; struct crypto_tfm *tfm; /* this also enters ses_ptr->sem */ ses_ptr = crypto_get_session_by_sid(fcr, siop->ses); if (unlikely(!ses_ptr)) { dprintk(1, KERN_ERR, "invalid session ID=0x%08X\n", siop->ses); return -EINVAL; } siop->flags = 0; if (ses_ptr->cdata.init) { if (ses_ptr->cdata.aead == 0) { tfm = crypto_ablkcipher_tfm(ses_ptr->cdata.async.s); } else { tfm = crypto_aead_tfm(ses_ptr->cdata.async.as); } tfm_info_to_alg_info(&siop->cipher_info, tfm); #ifdef CRYPTO_ALG_KERN_DRIVER_ONLY if (tfm->__crt_alg->cra_flags & CRYPTO_ALG_KERN_DRIVER_ONLY) siop->flags |= SIOP_FLAG_KERNEL_DRIVER_ONLY; #else if (is_known_accelerated(tfm)) siop->flags |= SIOP_FLAG_KERNEL_DRIVER_ONLY; #endif } if (ses_ptr->hdata.init) { tfm = crypto_ahash_tfm(ses_ptr->hdata.async.s); tfm_info_to_alg_info(&siop->hash_info, tfm); #ifdef CRYPTO_ALG_KERN_DRIVER_ONLY if (tfm->__crt_alg->cra_flags & CRYPTO_ALG_KERN_DRIVER_ONLY) siop->flags |= SIOP_FLAG_KERNEL_DRIVER_ONLY; #else if (is_known_accelerated(tfm)) siop->flags |= SIOP_FLAG_KERNEL_DRIVER_ONLY; #endif } siop->alignmask = ses_ptr->alignmask; crypto_put_session(ses_ptr); return 0; } static long cryptodev_ioctl(struct file *filp, unsigned int cmd, unsigned long arg_) { void __user *arg = (void __user *)arg_; int __user *p = arg; struct session_op sop; struct kernel_crypt_op kcop; struct kernel_crypt_auth_op kcaop; struct crypt_priv *pcr = filp->private_data; struct fcrypt *fcr; struct session_info_op siop; uint32_t ses; int ret, fd; if (unlikely(!pcr)) BUG(); fcr = &pcr->fcrypt; switch (cmd) { case CIOCASYMFEAT: return put_user(0, p); case CRIOGET: fd = clonefd(filp); ret = put_user(fd, p); if (unlikely(ret)) { sys_close(fd); return ret; } return ret; case CIOCGSESSION: if (unlikely(copy_from_user(&sop, arg, sizeof(sop)))) return -EFAULT; ret = crypto_create_session(fcr, &sop); if (unlikely(ret)) return ret; ret = copy_to_user(arg, &sop, sizeof(sop)); if (unlikely(ret)) { crypto_finish_session(fcr, sop.ses); return -EFAULT; } return ret; case CIOCFSESSION: ret = get_user(ses, (uint32_t __user *)arg); if (unlikely(ret)) return ret; ret = crypto_finish_session(fcr, ses); return ret; case CIOCGSESSINFO: if (unlikely(copy_from_user(&siop, arg, sizeof(siop)))) return -EFAULT; ret = get_session_info(fcr, &siop); if (unlikely(ret)) return ret; return copy_to_user(arg, &siop, sizeof(siop)); case CIOCCRYPT: if (unlikely(ret = kcop_from_user(&kcop, fcr, arg))) { dprintk(1, KERN_WARNING, "Error copying from user\n"); return ret; } ret = crypto_run(fcr, &kcop); if (unlikely(ret)) { dprintk(1, KERN_WARNING, "Error in crypto_run\n"); return ret; } return kcop_to_user(&kcop, fcr, arg); case CIOCAUTHCRYPT: if (unlikely(ret = kcaop_from_user(&kcaop, fcr, arg))) { dprintk(1, KERN_WARNING, "Error copying from user\n"); return ret; } ret = crypto_auth_run(fcr, &kcaop); if (unlikely(ret)) { dprintk(1, KERN_WARNING, "Error in crypto_auth_run\n"); return ret; } return kcaop_to_user(&kcaop, fcr, arg); #ifdef ENABLE_ASYNC case CIOCASYNCCRYPT: if (unlikely(ret = kcop_from_user(&kcop, fcr, arg))) return ret; return crypto_async_run(pcr, &kcop); case CIOCASYNCFETCH: ret = crypto_async_fetch(pcr, &kcop); if (unlikely(ret)) return ret; return kcop_to_user(&kcop, fcr, arg); #endif default: return -EINVAL; } } /* compatibility code for 32bit userlands */ #ifdef CONFIG_COMPAT static inline void compat_to_session_op(struct compat_session_op *compat, struct session_op *sop) { sop->cipher = compat->cipher; sop->mac = compat->mac; sop->keylen = compat->keylen; sop->key = compat_ptr(compat->key); sop->mackeylen = compat->mackeylen; sop->mackey = compat_ptr(compat->mackey); sop->ses = compat->ses; } static inline void session_op_to_compat(struct session_op *sop, struct compat_session_op *compat) { compat->cipher = sop->cipher; compat->mac = sop->mac; compat->keylen = sop->keylen; compat->key = ptr_to_compat(sop->key); compat->mackeylen = sop->mackeylen; compat->mackey = ptr_to_compat(sop->mackey); compat->ses = sop->ses; } static inline void compat_to_crypt_op(struct compat_crypt_op *compat, struct crypt_op *cop) { cop->ses = compat->ses; cop->op = compat->op; cop->flags = compat->flags; cop->len = compat->len; cop->src = compat_ptr(compat->src); cop->dst = compat_ptr(compat->dst); cop->mac = compat_ptr(compat->mac); cop->iv = compat_ptr(compat->iv); } static inline void crypt_op_to_compat(struct crypt_op *cop, struct compat_crypt_op *compat) { compat->ses = cop->ses; compat->op = cop->op; compat->flags = cop->flags; compat->len = cop->len; compat->src = ptr_to_compat(cop->src); compat->dst = ptr_to_compat(cop->dst); compat->mac = ptr_to_compat(cop->mac); compat->iv = ptr_to_compat(cop->iv); } static int compat_kcop_from_user(struct kernel_crypt_op *kcop, struct fcrypt *fcr, void __user *arg) { struct compat_crypt_op compat_cop; if (unlikely(copy_from_user(&compat_cop, arg, sizeof(compat_cop)))) return -EFAULT; compat_to_crypt_op(&compat_cop, &kcop->cop); return fill_kcop_from_cop(kcop, fcr); } static int compat_kcop_to_user(struct kernel_crypt_op *kcop, struct fcrypt *fcr, void __user *arg) { int ret; struct compat_crypt_op compat_cop; ret = fill_cop_from_kcop(kcop, fcr); if (unlikely(ret)) { dprintk(1, KERN_WARNING, "Error in fill_cop_from_kcop\n"); return ret; } crypt_op_to_compat(&kcop->cop, &compat_cop); if (unlikely(copy_to_user(arg, &compat_cop, sizeof(compat_cop)))) { dprintk(1, KERN_WARNING, "Error copying to user\n"); return -EFAULT; } return 0; } static long cryptodev_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg_) { void __user *arg = (void __user *)arg_; struct crypt_priv *pcr = file->private_data; struct fcrypt *fcr; struct session_op sop; struct compat_session_op compat_sop; struct kernel_crypt_op kcop; int ret; if (unlikely(!pcr)) BUG(); fcr = &pcr->fcrypt; switch (cmd) { case CIOCASYMFEAT: case CRIOGET: case CIOCFSESSION: case CIOCGSESSINFO: return cryptodev_ioctl(file, cmd, arg_); case COMPAT_CIOCGSESSION: if (unlikely(copy_from_user(&compat_sop, arg, sizeof(compat_sop)))) return -EFAULT; compat_to_session_op(&compat_sop, &sop); ret = crypto_create_session(fcr, &sop); if (unlikely(ret)) return ret; session_op_to_compat(&sop, &compat_sop); ret = copy_to_user(arg, &compat_sop, sizeof(compat_sop)); if (unlikely(ret)) { crypto_finish_session(fcr, sop.ses); return -EFAULT; } return ret; case COMPAT_CIOCCRYPT: ret = compat_kcop_from_user(&kcop, fcr, arg); if (unlikely(ret)) return ret; ret = crypto_run(fcr, &kcop); if (unlikely(ret)) return ret; return compat_kcop_to_user(&kcop, fcr, arg); #ifdef ENABLE_ASYNC case COMPAT_CIOCASYNCCRYPT: if (unlikely(ret = compat_kcop_from_user(&kcop, fcr, arg))) return ret; return crypto_async_run(pcr, &kcop); case COMPAT_CIOCASYNCFETCH: ret = crypto_async_fetch(pcr, &kcop); if (unlikely(ret)) return ret; return compat_kcop_to_user(&kcop, fcr, arg); #endif default: return -EINVAL; } } #endif /* CONFIG_COMPAT */ static unsigned int cryptodev_poll(struct file *file, poll_table *wait) { struct crypt_priv *pcr = file->private_data; int ret = 0; poll_wait(file, &pcr->user_waiter, wait); if (!list_empty_careful(&pcr->done.list)) ret |= POLLIN | POLLRDNORM; if (!list_empty_careful(&pcr->free.list) || pcr->itemcount < MAX_COP_RINGSIZE) ret |= POLLOUT | POLLWRNORM; return ret; } static const struct file_operations cryptodev_fops = { .owner = THIS_MODULE, .open = cryptodev_open, .release = cryptodev_release, .unlocked_ioctl = cryptodev_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = cryptodev_compat_ioctl, #endif /* CONFIG_COMPAT */ .poll = cryptodev_poll, }; static struct miscdevice cryptodev = { .minor = MISC_DYNAMIC_MINOR, .name = "crypto", .fops = &cryptodev_fops, .mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH, }; static int __init cryptodev_register(void) { int rc; rc = misc_register(&cryptodev); if (unlikely(rc)) { printk(KERN_ERR PFX "registration of /dev/crypto failed\n"); return rc; } return 0; } static void __exit cryptodev_deregister(void) { misc_deregister(&cryptodev); } /* ====== Module init/exit ====== */ static int __init init_cryptodev(void) { int rc; cryptodev_wq = create_workqueue("cryptodev_queue"); if (unlikely(!cryptodev_wq)) { printk(KERN_ERR PFX "failed to allocate the cryptodev workqueue\n"); return -EFAULT; } rc = cryptodev_register(); if (unlikely(rc)) { destroy_workqueue(cryptodev_wq); return rc; } printk(KERN_INFO PFX "driver %s loaded.\n", VERSION); return 0; } static void __exit exit_cryptodev(void) { flush_workqueue(cryptodev_wq); destroy_workqueue(cryptodev_wq); cryptodev_deregister(); printk(KERN_INFO PFX "driver unloaded.\n"); } module_init(init_cryptodev); module_exit(exit_cryptodev); cryptodev-linux-1.6/util.h0000644000175100017510000000022412102243276014345 0ustar nmavnmavint sg_copy(struct scatterlist *sg_from, struct scatterlist *sg_to, int len); struct scatterlist *sg_advance(struct scatterlist *sg, int consumed); cryptodev-linux-1.6/tests/0000755000175100017510000000000012122420356014361 5ustar nmavnmavcryptodev-linux-1.6/tests/fullspeed.c0000644000175100017510000001031312102243276016510 0ustar nmavnmav/* cryptodev_test - simple benchmark tool for cryptodev * * Copyright (C) 2010 by Phil Sutter * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include #include #include #include #include #include #include #include static int si = 1; /* SI by default */ static double udifftimeval(struct timeval start, struct timeval end) { return (double)(end.tv_usec - start.tv_usec) + (double)(end.tv_sec - start.tv_sec) * 1000 * 1000; } static int must_finish = 0; static void alarm_handler(int signo) { must_finish = 1; } static char *units[] = { "", "Ki", "Mi", "Gi", "Ti", 0}; static char *si_units[] = { "", "K", "M", "G", "T", 0}; static void value2human(int si, double bytes, double time, double* data, double* speed,char* metric) { int unit = 0; *data = bytes; if (si) { while (*data > 1000 && si_units[unit + 1]) { *data /= 1000; unit++; } *speed = *data / time; sprintf(metric, "%sB", si_units[unit]); } else { while (*data > 1024 && units[unit + 1]) { *data /= 1024; unit++; } *speed = *data / time; sprintf(metric, "%sB", units[unit]); } } #define MAX(x,y) ((x)>(y)?(x):(y)) int encrypt_data(int algo, void* keybuf, int key_size, int fdc, int chunksize) { struct crypt_op cop; char *buffer, iv[32]; static int val = 23; struct timeval start, end; double total = 0; double secs, ddata, dspeed; char metric[16]; struct session_op sess; if (posix_memalign((void **)&buffer, 16, chunksize)) { printf("posix_memalign() failed! (mask %x, size: %d)\n", 16, chunksize); return 1; } memset(iv, 0x23, 32); printf("\tEncrypting in chunks of %d bytes: ", chunksize); fflush(stdout); memset(buffer, val++, chunksize); must_finish = 0; alarm(5); gettimeofday(&start, NULL); do { memset(&sess, 0, sizeof(sess)); sess.cipher = algo; sess.keylen = key_size; sess.key = keybuf; if (ioctl(fdc, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } memset(&cop, 0, sizeof(cop)); cop.ses = sess.ses; cop.len = chunksize; cop.iv = (unsigned char *)iv; cop.op = COP_ENCRYPT; cop.src = (unsigned char *)buffer; cop.dst = buffer; if (ioctl(fdc, CIOCCRYPT, &cop)) { perror("ioctl(CIOCCRYPT)"); return 1; } ioctl(fdc, CIOCFSESSION, &sess.ses); total+=chunksize; } while(must_finish==0); gettimeofday(&end, NULL); secs = udifftimeval(start, end)/ 1000000.0; value2human(si, total, secs, &ddata, &dspeed, metric); printf ("done. %.2f %s in %.2f secs: ", ddata, metric, secs); printf ("%.2f %s/sec\n", dspeed, metric); free(buffer); return 0; } int main(int argc, char** argv) { int fd, i, fdc = -1; char keybuf[32]; signal(SIGALRM, alarm_handler); if (argc > 1) { if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) { printf("Usage: speed [--kib]\n"); exit(0); } if (strcmp(argv[1], "--kib") == 0) { si = 0; } } if ((fd = open("/dev/crypto", O_RDWR, 0)) < 0) { perror("open()"); return 1; } if (ioctl(fd, CRIOGET, &fdc)) { perror("ioctl(CRIOGET)"); return 1; } fprintf(stderr, "Testing NULL cipher: \n"); for (i = 512; i <= (64 * 1024); i *= 2) { if (encrypt_data(CRYPTO_NULL, keybuf, 0, fdc, i)) break; } fprintf(stderr, "\nTesting AES-128-CBC cipher: \n"); memset(keybuf, 0x42, 16); for (i = 512; i <= (64 * 1024); i *= 2) { if (encrypt_data(CRYPTO_AES_CBC, keybuf, 16, fdc, i)) break; } close(fdc); close(fd); return 0; } cryptodev-linux-1.6/tests/openssl_wrapper.c0000644000175100017510000001335512102243276017761 0ustar nmavnmav#include #include #include #include #include #include //#define DEBUG #ifdef DEBUG # define dbgp(...) { \ fprintf(stderr, "%s:%d: ", __FILE__, __LINE__); \ fprintf(stderr, __VA_ARGS__); \ fprintf(stderr, "\n"); \ } #else # define dbgp(...) /* nothing */ #endif enum ctx_type { ctx_type_none = 0, ctx_type_hmac, ctx_type_md, }; union openssl_ctx { HMAC_CTX hmac; EVP_MD_CTX md; }; struct ctx_mapping { __u32 ses; enum ctx_type type; union openssl_ctx ctx; }; static struct ctx_mapping ctx_map[512]; static struct ctx_mapping *find_mapping(__u32 ses) { int i; for (i = 0; i < 512; i++) { if (ctx_map[i].ses == ses) return &ctx_map[i]; } return NULL; } static struct ctx_mapping *new_mapping(void) { return find_mapping(0); } static void remove_mapping(__u32 ses) { struct ctx_mapping *mapping; if (!(mapping = find_mapping(ses))) { printf("%s: failed to find mapping for session %d\n", __func__, ses); return; } switch (mapping->type) { case ctx_type_none: break; case ctx_type_hmac: dbgp("%s: calling HMAC_CTX_cleanup\n", __func__); HMAC_CTX_cleanup(&mapping->ctx.hmac); break; case ctx_type_md: dbgp("%s: calling EVP_MD_CTX_cleanup\n", __func__); EVP_MD_CTX_cleanup(&mapping->ctx.md); break; } memset(mapping, 0, sizeof(*mapping)); } static union openssl_ctx *__ses_to_ctx(__u32 ses) { struct ctx_mapping *mapping; if (!(mapping = find_mapping(ses))) return NULL; return &mapping->ctx; } static HMAC_CTX *ses_to_hmac(__u32 ses) { return (HMAC_CTX *)__ses_to_ctx(ses); } static EVP_MD_CTX *ses_to_md(__u32 ses) { return (EVP_MD_CTX *)__ses_to_ctx(ses); } static const EVP_MD *sess_to_evp_md(struct session_op *sess) { switch (sess->mac) { #ifndef OPENSSL_NO_MD5 case CRYPTO_MD5_HMAC: return EVP_md5(); #endif #ifndef OPENSSL_NO_SHA case CRYPTO_SHA1_HMAC: case CRYPTO_SHA1: return EVP_sha1(); #endif #ifndef OPENSSL_NO_RIPEMD case CRYPTO_RIPEMD160_HMAC: return EVP_ripemd160(); #endif #ifndef OPENSSL_NO_SHA256 case CRYPTO_SHA2_256_HMAC: return EVP_sha256(); #endif #ifndef OPENSSL_NO_SHA512 case CRYPTO_SHA2_384_HMAC: return EVP_sha384(); case CRYPTO_SHA2_512_HMAC: return EVP_sha512(); #endif default: printf("%s: failed to get an EVP, things will be broken!\n", __func__); return NULL; } } static int openssl_hmac(struct session_op *sess, struct crypt_op *cop) { HMAC_CTX *ctx = ses_to_hmac(sess->ses); if (!ctx) { struct ctx_mapping *mapping = new_mapping(); if (!mapping) { printf("%s: failed to get new mapping\n", __func__); return 1; } mapping->ses = sess->ses; mapping->type = ctx_type_hmac; ctx = &mapping->ctx.hmac; dbgp("calling HMAC_CTX_init"); HMAC_CTX_init(ctx); dbgp("calling HMAC_Init_ex"); if (!HMAC_Init_ex(ctx, sess->mackey, sess->mackeylen, sess_to_evp_md(sess), NULL)) { printf("%s: HMAC_Init_ex failed\n", __func__); return 1; } } if (cop->len) { dbgp("calling HMAC_Update"); if (!HMAC_Update(ctx, cop->src, cop->len)) { printf("%s: HMAC_Update failed\n", __func__); return 1; } } if (cop->flags & COP_FLAG_FINAL || (cop->len && !(cop->flags & COP_FLAG_UPDATE))) { dbgp("calling HMAC_Final"); if (!HMAC_Final(ctx, cop->mac, 0)) { printf("%s: HMAC_Final failed\n", __func__); remove_mapping(sess->ses); return 1; } remove_mapping(sess->ses); } return 0; } static int openssl_md(struct session_op *sess, struct crypt_op *cop) { EVP_MD_CTX *ctx = ses_to_md(sess->ses); if (!ctx) { struct ctx_mapping *mapping = new_mapping(); if (!mapping) { printf("%s: failed to get new mapping\n", __func__); return 1; } mapping->ses = sess->ses; mapping->type = ctx_type_md; ctx = &mapping->ctx.md; dbgp("calling EVP_MD_CTX_init"); EVP_MD_CTX_init(ctx); dbgp("calling EVP_DigestInit"); EVP_DigestInit(ctx, sess_to_evp_md(sess)); } if (cop->len) { dbgp("calling EVP_DigestUpdate"); EVP_DigestUpdate(ctx, cop->src, cop->len); } if (cop->flags & COP_FLAG_FINAL || (cop->len && !(cop->flags & COP_FLAG_UPDATE))) { dbgp("calling EVP_DigestFinal"); EVP_DigestFinal(ctx, cop->mac, 0); remove_mapping(sess->ses); } return 0; } static int openssl_aes(struct session_op *sess, struct crypt_op *cop) { AES_KEY key; int i, enc; unsigned char ivec[AES_BLOCK_SIZE]; if (cop->len % AES_BLOCK_SIZE) { printf("%s: illegal length passed, " "not a multiple of AES_BLOCK_SIZE\n", __func__); return 1; } switch (cop->op) { case COP_ENCRYPT: AES_set_encrypt_key(sess->key, sess->keylen * 8, &key); enc = 1; break; case COP_DECRYPT: AES_set_decrypt_key(sess->key, sess->keylen * 8, &key); enc = 0; break; default: printf("%s: unknown cop->op received!\n", __func__); return 1; } switch (sess->cipher) { case CRYPTO_AES_CBC: memcpy(ivec, cop->iv, AES_BLOCK_SIZE); AES_cbc_encrypt(cop->src, cop->dst, cop->len, &key, ivec, enc); if (cop->flags & COP_FLAG_WRITE_IV) memcpy(cop->iv, ivec, AES_BLOCK_SIZE); break; #if 0 /* XXX: TODO: implement this stuff */ case CRYPTO_AES_CTR: AES_ctr128_encrypt(cop->src, cop->dst, &key, cop->iv, case CRYPTO_AES_XTS: #endif case CRYPTO_AES_ECB: for (i = 0; i < cop->len; i += AES_BLOCK_SIZE) AES_ecb_encrypt(cop->src + i, cop->dst + i, &key, enc); break; } return 0; } int openssl_cioccrypt(struct session_op *sess, struct crypt_op *cop) { if (sess->mac && sess->mackey && sess->mackeylen) openssl_hmac(sess, cop); else if (sess->mac) openssl_md(sess, cop); switch (sess->cipher) { case CRYPTO_AES_CBC: case CRYPTO_AES_CTR: case CRYPTO_AES_XTS: case CRYPTO_AES_ECB: openssl_aes(sess, cop); break; case 0: /* no encryption wanted, everythings fine */ break; default: printf("%s: unknown cipher passed!\n", __func__); break; } return 0; } cryptodev-linux-1.6/tests/hash_comp.c0000644000175100017510000000553012102243276016473 0ustar nmavnmav/* * Compare digest results with ones from openssl. * * Placed under public domain. * */ #include #include #include #include #include #include #include #include #include "openssl_wrapper.h" #define BLOCK_SIZE 16 #define MAX_DATALEN (64 * 1024) static void printhex(unsigned char *buf, int buflen) { while (buflen-- > 0) { printf("\\x%.2x", *(buf++)); } printf("\n"); } static int test_crypto(int cfd, struct session_op *sess, int datalen) { unsigned char *data; unsigned char mac[AALG_MAX_RESULT_LEN]; unsigned char mac_comp[AALG_MAX_RESULT_LEN]; struct crypt_op cryp; int ret = 0, fail = 0; data = malloc(datalen); memset(data, datalen & 0xff, datalen); memset(mac, 0, sizeof(mac)); memset(mac_comp, 0, sizeof(mac_comp)); memset(&cryp, 0, sizeof(cryp)); /* Encrypt data.in to data.encrypted */ cryp.ses = sess->ses; cryp.len = datalen; cryp.src = data; cryp.mac = mac; cryp.op = COP_ENCRYPT; if ((ret = ioctl(cfd, CIOCCRYPT, &cryp))) { perror("ioctl(CIOCCRYPT)"); goto out; } cryp.mac = mac_comp; if ((ret = openssl_cioccrypt(sess, &cryp))) { fprintf(stderr, "openssl_cioccrypt() failed!\n"); goto out; } if (memcmp(mac, mac_comp, AALG_MAX_RESULT_LEN)) { printf("fail for datalen %d, MACs do not match!\n", datalen); fail = 1; printf("wrong mac: "); printhex(mac, 20); printf("right mac: "); printhex(mac_comp, 20); } out: free(data); return ret; } #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) int main(int argc, char **argv) { int fd; struct session_op sess; int datalen = BLOCK_SIZE; int datalen_end = MAX_DATALEN; int i; if (argc > 1) { datalen = min(max(atoi(argv[1]), BLOCK_SIZE), MAX_DATALEN); datalen_end = datalen; } if (argc > 2) { datalen_end = min(atoi(argv[2]), MAX_DATALEN); if (datalen_end < datalen) datalen_end = datalen; } /* Open the crypto device */ fd = open("/dev/crypto", O_RDWR, 0); if (fd < 0) { perror("open(/dev/crypto)"); return 1; } memset(&sess, 0, sizeof(sess)); /* Hash test */ sess.mac = CRYPTO_SHA1; if (ioctl(fd, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO { struct session_info_op siop = { .ses = sess.ses, }; if (ioctl(fd, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); } else { printf("requested mac CRYPTO_SHA1, got hash %s with driver %s\n", siop.hash_info.cra_name, siop.hash_info.cra_driver_name); } } #endif for (; datalen <= datalen_end; datalen += BLOCK_SIZE) { if (test_crypto(fd, &sess, datalen)) { printf("test_crypto() failed for datalen of %d\n", datalen); return 1; } } /* Finish crypto session */ if (ioctl(fd, CIOCFSESSION, &sess.ses)) { perror("ioctl(CIOCFSESSION)"); } close(fd); return 0; } cryptodev-linux-1.6/tests/hmac_comp.c0000644000175100017510000000745412102243276016467 0ustar nmavnmav/* * Compare HMAC results with ones from openssl. * * Placed under public domain. * */ #include #include #include #include #include #include #include #include #include "openssl_wrapper.h" #define BLOCK_SIZE 16 #define KEY_SIZE 16 #define MACKEY_SIZE 20 #define MAX_DATALEN (64 * 1024) static void printhex(unsigned char *buf, int buflen) { while (buflen-- > 0) { printf("\\x%.2x", *(buf++)); } printf("\n"); } static int test_crypto(int cfd, struct session_op *sess, int datalen) { unsigned char *data, *encrypted; unsigned char *encrypted_comp; unsigned char iv[BLOCK_SIZE]; unsigned char mac[AALG_MAX_RESULT_LEN]; unsigned char mac_comp[AALG_MAX_RESULT_LEN]; struct crypt_op cryp; int ret = 0; data = malloc(datalen); encrypted = malloc(datalen); encrypted_comp = malloc(datalen); memset(data, datalen & 0xff, datalen); memset(encrypted, 0x27, datalen); memset(encrypted_comp, 0x27, datalen); memset(iv, 0x23, sizeof(iv)); memset(mac, 0, sizeof(mac)); memset(mac_comp, 0, sizeof(mac_comp)); memset(&cryp, 0, sizeof(cryp)); /* Encrypt data.in to data.encrypted */ cryp.ses = sess->ses; cryp.len = datalen; cryp.src = data; cryp.dst = encrypted; cryp.iv = iv; cryp.mac = mac; cryp.op = COP_ENCRYPT; if ((ret = ioctl(cfd, CIOCCRYPT, &cryp))) { perror("ioctl(CIOCCRYPT)"); goto out; } cryp.dst = encrypted_comp; cryp.mac = mac_comp; if ((ret = openssl_cioccrypt(sess, &cryp))) { fprintf(stderr, "openssl_cioccrypt() failed!\n"); goto out; } if ((ret = memcmp(encrypted, encrypted_comp, cryp.len))) { printf("fail for datalen %d, cipher texts do not match!\n", datalen); } if ((ret = memcmp(mac, mac_comp, AALG_MAX_RESULT_LEN))) { printf("fail for datalen 0x%x, MACs do not match!\n", datalen); printf("wrong mac: "); printhex(mac, 20); printf("right mac: "); printhex(mac_comp, 20); } out: free(data); free(encrypted); free(encrypted_comp); return ret; } #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) int main(int argc, char **argv) { int fd; struct session_op sess; unsigned char key[KEY_SIZE], mackey[MACKEY_SIZE]; int datalen = BLOCK_SIZE; int datalen_end = MAX_DATALEN; int i; if (argc > 1) { datalen = min(max(atoi(argv[1]), BLOCK_SIZE), MAX_DATALEN); datalen_end = datalen; } if (argc > 2) { datalen_end = min(atoi(argv[2]), MAX_DATALEN); if (datalen_end < datalen) datalen_end = datalen; } /* Open the crypto device */ fd = open("/dev/crypto", O_RDWR, 0); if (fd < 0) { perror("open(/dev/crypto)"); return 1; } for (i = 0; i < KEY_SIZE; i++) key[i] = i & 0xff; for (i = 0; i < MACKEY_SIZE; i++) mackey[i] = i & 0xff; memset(&sess, 0, sizeof(sess)); /* Hash and encryption in one step test */ sess.cipher = CRYPTO_AES_CBC; sess.mac = CRYPTO_SHA1_HMAC; sess.keylen = KEY_SIZE; sess.key = key; sess.mackeylen = MACKEY_SIZE; sess.mackey = mackey; if (ioctl(fd, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO { struct session_info_op siop = { .ses = sess.ses, }; if (ioctl(fd, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); } else { printf("requested cipher CRYPTO_AES_CBC and mac CRYPTO_SHA1_HMAC," " got cipher %s with driver %s and hash %s with driver %s\n", siop.cipher_info.cra_name, siop.cipher_info.cra_driver_name, siop.hash_info.cra_name, siop.hash_info.cra_driver_name); } } #endif for (; datalen <= datalen_end; datalen += BLOCK_SIZE) { if (test_crypto(fd, &sess, datalen)) { printf("test_crypto() failed for datalen of %d\n", datalen); return 1; } } /* Finish crypto session */ if (ioctl(fd, CIOCFSESSION, &sess.ses)) { perror("ioctl(CIOCFSESSION)"); } close(fd); return 0; } cryptodev-linux-1.6/tests/cipher_comp.c0000644000175100017510000000652112102243276017023 0ustar nmavnmav/* * Compare encryption results with ones from openssl. * * Placed under public domain. * */ #include #include #include #include #include #include #include #include #include "openssl_wrapper.h" #define BLOCK_SIZE 16 #define KEY_SIZE 16 #define MAX_DATALEN (64 * 1024) static int test_crypto(int cfd, struct session_op *sess, int datalen) { char *data, *encrypted; char *encrypted_comp; char iv_in[BLOCK_SIZE]; char iv[BLOCK_SIZE]; char iv_comp[BLOCK_SIZE]; struct crypt_op cryp; int ret = 0, fail = 0; data = malloc(datalen); encrypted = malloc(datalen); encrypted_comp = malloc(datalen); memset(data, datalen & 0xff, datalen); memset(encrypted, 0x27, datalen); memset(encrypted_comp, 0x41, datalen); memset(iv_in, 0x23, sizeof(iv_in)); memcpy(iv, iv_in, sizeof(iv)); memcpy(iv_comp, iv_in, sizeof(iv_comp)); memset(&cryp, 0, sizeof(cryp)); /* Encrypt data.in to data.encrypted */ cryp.ses = sess->ses; cryp.len = datalen; cryp.src = data; cryp.dst = encrypted; cryp.iv = iv; cryp.op = COP_ENCRYPT; cryp.flags = COP_FLAG_WRITE_IV; if ((ret = ioctl(cfd, CIOCCRYPT, &cryp))) { perror("ioctl(CIOCCRYPT)"); goto out; } cryp.dst = encrypted_comp; cryp.iv = iv_comp; if ((ret = openssl_cioccrypt(sess, &cryp))) { fprintf(stderr, "openssl_cioccrypt() failed!\n"); goto out; } if ((ret = memcmp(encrypted, encrypted_comp, cryp.len))) { printf("fail for datalen %d, cipher texts do not match!\n", datalen); } if ((ret = memcmp(iv, iv_comp, BLOCK_SIZE))) { printf("fail for datalen %d, IVs do not match!\n", datalen); } out: free(data); free(encrypted); free(encrypted_comp); return ret; } #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) int main(int argc, char **argv) { int fd; struct session_op sess; unsigned char key[KEY_SIZE]; int datalen = BLOCK_SIZE; int datalen_end = MAX_DATALEN; int i; if (argc > 1) { datalen = min(max(atoi(argv[1]), BLOCK_SIZE), MAX_DATALEN); datalen_end = datalen; } if (argc > 2) { datalen_end = min(atoi(argv[2]), MAX_DATALEN); if (datalen_end < datalen) datalen_end = datalen; } /* Open the crypto device */ fd = open("/dev/crypto", O_RDWR, 0); if (fd < 0) { perror("open(/dev/crypto)"); return 1; } for (i = 0; i < KEY_SIZE; i++) key[i] = i & 0xff; memset(&sess, 0, sizeof(sess)); /* encryption test */ sess.cipher = CRYPTO_AES_CBC; sess.keylen = KEY_SIZE; sess.key = key; if (ioctl(fd, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO { struct session_info_op siop = { .ses = sess.ses, }; if (ioctl(fd, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); } else { printf("requested cipher CRYPTO_AES_CBC and mac CRYPTO_SHA1_HMAC," " got cipher %s with driver %s and hash %s with driver %s\n", siop.cipher_info.cra_name, siop.cipher_info.cra_driver_name, siop.hash_info.cra_name, siop.hash_info.cra_driver_name); } } #endif for (; datalen <= datalen_end; datalen += BLOCK_SIZE) { if (test_crypto(fd, &sess, datalen)) { printf("test_crypto() failed for datalen of %d\n", datalen); return 1; } } /* Finish crypto session */ if (ioctl(fd, CIOCFSESSION, &sess.ses)) { perror("ioctl(CIOCFSESSION)"); } close(fd); return 0; } cryptodev-linux-1.6/tests/cipher-gcm.c0000644000175100017510000003056512102243276016556 0ustar nmavnmav/* * Demo on how to use /dev/crypto device for ciphering. * * Placed under public domain. * */ #include #include #include #include #include #include #include #define DATA_SIZE (8*1024) #define AUTH_SIZE 31 #define BLOCK_SIZE 16 #define KEY_SIZE 16 #define my_perror(x) {fprintf(stderr, "%s: %d\n", __func__, __LINE__); perror(x); } static int debug = 0; static void print_buf(char *desc, const unsigned char *buf, int size) { int i; fputs(desc, stdout); for (i = 0; i < size; i++) { printf("%.2x", (uint8_t) buf[i]); } fputs("\n", stdout); } struct aes_gcm_vectors_st { const uint8_t *key; const uint8_t *auth; int auth_size; const uint8_t *plaintext; int plaintext_size; const uint8_t *iv; const uint8_t *ciphertext; const uint8_t *tag; }; struct aes_gcm_vectors_st aes_gcm_vectors[] = { { .key = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", .auth = NULL, .auth_size = 0, .plaintext = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", .plaintext_size = 16, .ciphertext = "\x03\x88\xda\xce\x60\xb6\xa3\x92\xf3\x28\xc2\xb9\x71\xb2\xfe\x78", .iv = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", .tag = "\xab\x6e\x47\xd4\x2c\xec\x13\xbd\xf5\x3a\x67\xb2\x12\x57\xbd\xdf" }, { .key = "\xfe\xff\xe9\x92\x86\x65\x73\x1c\x6d\x6a\x8f\x94\x67\x30\x83\x08", .auth = NULL, .auth_size = 0, .plaintext = "\xd9\x31\x32\x25\xf8\x84\x06\xe5\xa5\x59\x09\xc5\xaf\xf5\x26\x9a\x86\xa7\xa9\x53\x15\x34\xf7\xda\x2e\x4c\x30\x3d\x8a\x31\x8a\x72\x1c\x3c\x0c\x95\x95\x68\x09\x53\x2f\xcf\x0e\x24\x49\xa6\xb5\x25\xb1\x6a\xed\xf5\xaa\x0d\xe6\x57\xba\x63\x7b\x39\x1a\xaf\xd2\x55", .plaintext_size = 64, .ciphertext = "\x42\x83\x1e\xc2\x21\x77\x74\x24\x4b\x72\x21\xb7\x84\xd0\xd4\x9c\xe3\xaa\x21\x2f\x2c\x02\xa4\xe0\x35\xc1\x7e\x23\x29\xac\xa1\x2e\x21\xd5\x14\xb2\x54\x66\x93\x1c\x7d\x8f\x6a\x5a\xac\x84\xaa\x05\x1b\xa3\x0b\x39\x6a\x0a\xac\x97\x3d\x58\xe0\x91\x47\x3f\x59\x85", .iv = "\xca\xfe\xba\xbe\xfa\xce\xdb\xad\xde\xca\xf8\x88", .tag = "\x4d\x5c\x2a\xf3\x27\xcd\x64\xa6\x2c\xf3\x5a\xbd\x2b\xa6\xfa\xb4" }, { .key = "\xfe\xff\xe9\x92\x86\x65\x73\x1c\x6d\x6a\x8f\x94\x67\x30\x83\x08", .auth = "\xfe\xed\xfa\xce\xde\xad\xbe\xef\xfe\xed\xfa\xce\xde\xad\xbe\xef\xab\xad\xda\xd2", .auth_size = 20, .plaintext = "\xd9\x31\x32\x25\xf8\x84\x06\xe5\xa5\x59\x09\xc5\xaf\xf5\x26\x9a\x86\xa7\xa9\x53\x15\x34\xf7\xda\x2e\x4c\x30\x3d\x8a\x31\x8a\x72\x1c\x3c\x0c\x95\x95\x68\x09\x53\x2f\xcf\x0e\x24\x49\xa6\xb5\x25\xb1\x6a\xed\xf5\xaa\x0d\xe6\x57\xba\x63\x7b\x39", .plaintext_size = 60, .ciphertext = "\x42\x83\x1e\xc2\x21\x77\x74\x24\x4b\x72\x21\xb7\x84\xd0\xd4\x9c\xe3\xaa\x21\x2f\x2c\x02\xa4\xe0\x35\xc1\x7e\x23\x29\xac\xa1\x2e\x21\xd5\x14\xb2\x54\x66\x93\x1c\x7d\x8f\x6a\x5a\xac\x84\xaa\x05\x1b\xa3\x0b\x39\x6a\x0a\xac\x97\x3d\x58\xe0\x91", .iv = "\xca\xfe\xba\xbe\xfa\xce\xdb\xad\xde\xca\xf8\x88", .tag = "\x5b\xc9\x4f\xbc\x32\x21\xa5\xdb\x94\xfa\xe9\x5a\xe7\x12\x1a\x47" } }; /* Test against AES-GCM test vectors. */ static int test_crypto(int cfd) { int i; int8_t tmp[128]; struct session_op sess; struct crypt_auth_op cao; /* Get crypto session for AES128 */ if (debug) { fprintf(stdout, "Tests on AES-GCM vectors: "); fflush(stdout); } for (i = 0; i < sizeof(aes_gcm_vectors) / sizeof(aes_gcm_vectors[0]); i++) { memset(&sess, 0, sizeof(sess)); memset(tmp, 0, sizeof(tmp)); sess.cipher = CRYPTO_AES_GCM; sess.keylen = 16; sess.key = (void *) aes_gcm_vectors[i].key; if (ioctl(cfd, CIOCGSESSION, &sess)) { my_perror("ioctl(CIOCGSESSION)"); return 1; } memset(&cao, 0, sizeof(cao)); cao.ses = sess.ses; cao.dst = tmp; cao.iv = (void *) aes_gcm_vectors[i].iv; cao.iv_len = 12; cao.op = COP_ENCRYPT; cao.flags = 0; if (aes_gcm_vectors[i].auth_size > 0) { cao.auth_src = (void *) aes_gcm_vectors[i].auth; cao.auth_len = aes_gcm_vectors[i].auth_size; } if (aes_gcm_vectors[i].plaintext_size > 0) { cao.src = (void *) aes_gcm_vectors[i].plaintext; cao.len = aes_gcm_vectors[i].plaintext_size; } if (ioctl(cfd, CIOCAUTHCRYPT, &cao)) { my_perror("ioctl(CIOCAUTHCRYPT)"); return 1; } if (aes_gcm_vectors[i].plaintext_size > 0) if (memcmp (tmp, aes_gcm_vectors[i].ciphertext, aes_gcm_vectors[i].plaintext_size) != 0) { fprintf(stderr, "AES-GCM test vector %d failed!\n", i); print_buf("Cipher: ", tmp, aes_gcm_vectors[i].plaintext_size); print_buf("Expected: ", aes_gcm_vectors[i].ciphertext, aes_gcm_vectors[i].plaintext_size); return 1; } if (memcmp (&tmp[cao.len - cao.tag_len], aes_gcm_vectors[i].tag, 16) != 0) { fprintf(stderr, "AES-GCM test vector %d failed (tag)!\n", i); print_buf("Tag: ", tmp, cao.tag_len); print_buf("Expected tag: ", aes_gcm_vectors[i].tag, 16); return 1; } } if (debug) { fprintf(stdout, "ok\n"); fprintf(stdout, "\n"); } /* Finish crypto session */ if (ioctl(cfd, CIOCFSESSION, &sess.ses)) { my_perror("ioctl(CIOCFSESSION)"); return 1; } return 0; } /* Checks if encryption and subsequent decryption * produces the same data. */ static int test_encrypt_decrypt(int cfd) { char plaintext_raw[DATA_SIZE + 63], *plaintext; char ciphertext_raw[DATA_SIZE + 63], *ciphertext; char iv[BLOCK_SIZE]; char key[KEY_SIZE]; char auth[AUTH_SIZE]; int enc_len; struct session_op sess; struct crypt_auth_op cao; struct session_info_op siop; if (debug) { fprintf(stdout, "Tests on AES-GCM encryption/decryption: "); fflush(stdout); } memset(&sess, 0, sizeof(sess)); memset(&cao, 0, sizeof(cao)); memset(key, 0x33, sizeof(key)); memset(iv, 0x03, sizeof(iv)); memset(auth, 0xf1, sizeof(auth)); /* Get crypto session for AES128 */ sess.cipher = CRYPTO_AES_GCM; sess.keylen = KEY_SIZE; sess.key = key; if (ioctl(cfd, CIOCGSESSION, &sess)) { my_perror("ioctl(CIOCGSESSION)"); return 1; } siop.ses = sess.ses; if (ioctl(cfd, CIOCGSESSINFO, &siop)) { my_perror("ioctl(CIOCGSESSINFO)"); return 1; } // printf("requested cipher CRYPTO_AES_CBC/HMAC-SHA1, got %s with driver %s\n", // siop.cipher_info.cra_name, siop.cipher_info.cra_driver_name); plaintext = (char *) (((unsigned long) plaintext_raw + siop.alignmask) & ~siop.alignmask); ciphertext = (char *) (((unsigned long) ciphertext_raw + siop.alignmask) & ~siop.alignmask); memset(plaintext, 0x15, DATA_SIZE); /* Encrypt data.in to data.encrypted */ cao.ses = sess.ses; cao.auth_src = auth; cao.auth_len = sizeof(auth); cao.len = DATA_SIZE; cao.src = plaintext; cao.dst = ciphertext; cao.iv = iv; cao.iv_len = 12; cao.op = COP_ENCRYPT; cao.flags = 0; if (ioctl(cfd, CIOCAUTHCRYPT, &cao)) { my_perror("ioctl(CIOCAUTHCRYPT)"); return 1; } enc_len = cao.len; //printf("Original plaintext size: %d, ciphertext: %d\n", DATA_SIZE, enc_len); if (ioctl(cfd, CIOCFSESSION, &sess.ses)) { my_perror("ioctl(CIOCFSESSION)"); return 1; } /* Get crypto session for AES128 */ memset(&sess, 0, sizeof(sess)); sess.cipher = CRYPTO_AES_GCM; sess.keylen = KEY_SIZE; sess.key = key; if (ioctl(cfd, CIOCGSESSION, &sess)) { my_perror("ioctl(CIOCGSESSION)"); return 1; } /* Decrypt data.encrypted to data.decrypted */ cao.ses = sess.ses; cao.auth_src = auth; cao.auth_len = sizeof(auth); cao.len = enc_len; cao.src = ciphertext; cao.dst = ciphertext; cao.iv = iv; cao.iv_len = 12; cao.op = COP_DECRYPT; cao.flags = 0; if (ioctl(cfd, CIOCAUTHCRYPT, &cao)) { my_perror("ioctl(CIOCAUTHCRYPT)"); return 1; } if (cao.len != DATA_SIZE) { fprintf(stderr, "decrypted data size incorrect!\n"); return 1; } /* Verify the result */ if (memcmp(plaintext, ciphertext, DATA_SIZE) != 0) { int i; fprintf(stderr, "FAIL: Decrypted data are different from the input data.\n"); printf("plaintext:"); for (i = 0; i < DATA_SIZE; i++) { if ((i % 30) == 0) printf("\n"); printf("%02x ", plaintext[i]); } printf("ciphertext:"); for (i = 0; i < DATA_SIZE; i++) { if ((i % 30) == 0) printf("\n"); printf("%02x ", ciphertext[i]); } printf("\n"); return 1; } /* Finish crypto session */ if (ioctl(cfd, CIOCFSESSION, &sess.ses)) { my_perror("ioctl(CIOCFSESSION)"); return 1; } if (debug) { fprintf(stdout, "ok\n"); fprintf(stdout, "\n"); } return 0; } static int test_encrypt_decrypt_error(int cfd, int err) { char plaintext_raw[DATA_SIZE + 63], *plaintext; char ciphertext_raw[DATA_SIZE + 63], *ciphertext; char iv[BLOCK_SIZE]; char key[KEY_SIZE]; char auth[AUTH_SIZE]; int enc_len; struct session_op sess; struct crypt_op co; struct crypt_auth_op cao; struct session_info_op siop; if (debug) { fprintf(stdout, "Tests on AES-GCM tag verification: "); fflush(stdout); } memset(&sess, 0, sizeof(sess)); memset(&cao, 0, sizeof(cao)); memset(&co, 0, sizeof(co)); memset(key, 0x33, sizeof(key)); memset(iv, 0x03, sizeof(iv)); memset(auth, 0xf1, sizeof(auth)); /* Get crypto session for AES128 */ sess.cipher = CRYPTO_AES_CBC; sess.keylen = KEY_SIZE; sess.key = key; sess.mac = CRYPTO_SHA1_HMAC; sess.mackeylen = 16; sess.mackey = (uint8_t *) "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b"; if (ioctl(cfd, CIOCGSESSION, &sess)) { my_perror("ioctl(CIOCGSESSION)"); return 1; } siop.ses = sess.ses; if (ioctl(cfd, CIOCGSESSINFO, &siop)) { my_perror("ioctl(CIOCGSESSINFO)"); return 1; } // printf("requested cipher CRYPTO_AES_CBC/HMAC-SHA1, got %s with driver %s\n", // siop.cipher_info.cra_name, siop.cipher_info.cra_driver_name); plaintext = (char *) (((unsigned long) plaintext_raw + siop.alignmask) & ~siop.alignmask); ciphertext = (char *) (((unsigned long) ciphertext_raw + siop.alignmask) & ~siop.alignmask); memset(plaintext, 0x15, DATA_SIZE); memcpy(ciphertext, plaintext, DATA_SIZE); /* Encrypt data.in to data.encrypted */ cao.ses = sess.ses; cao.auth_src = auth; cao.auth_len = sizeof(auth); cao.len = DATA_SIZE; cao.src = ciphertext; cao.dst = ciphertext; cao.iv = iv; cao.op = COP_ENCRYPT; cao.flags = COP_FLAG_AEAD_TLS_TYPE; if (ioctl(cfd, CIOCAUTHCRYPT, &cao)) { my_perror("ioctl(CIOCAUTHCRYPT)"); return 1; } enc_len = cao.len; //printf("Original plaintext size: %d, ciphertext: %d\n", DATA_SIZE, enc_len); if (ioctl(cfd, CIOCFSESSION, &sess.ses)) { my_perror("ioctl(CIOCFSESSION)"); return 1; } /* Get crypto session for AES128 */ memset(&sess, 0, sizeof(sess)); sess.cipher = CRYPTO_AES_CBC; sess.keylen = KEY_SIZE; sess.key = key; sess.mac = CRYPTO_SHA1_HMAC; sess.mackeylen = 16; sess.mackey = (uint8_t *) "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b"; if (ioctl(cfd, CIOCGSESSION, &sess)) { my_perror("ioctl(CIOCGSESSION)"); return 1; } if (err == 0) auth[2]++; else ciphertext[4]++; /* Decrypt data.encrypted to data.decrypted */ cao.ses = sess.ses; cao.auth_src = auth; cao.auth_len = sizeof(auth); cao.len = enc_len; cao.src = ciphertext; cao.dst = ciphertext; cao.iv = iv; cao.op = COP_DECRYPT; cao.flags = COP_FLAG_AEAD_TLS_TYPE; if (ioctl(cfd, CIOCAUTHCRYPT, &cao)) { if (ioctl(cfd, CIOCFSESSION, &sess.ses)) { my_perror("ioctl(CIOCFSESSION)"); return 1; } if (debug) { fprintf(stdout, "ok\n"); fprintf(stdout, "\n"); } return 0; } /* Finish crypto session */ if (ioctl(cfd, CIOCFSESSION, &sess.ses)) { my_perror("ioctl(CIOCFSESSION)"); return 1; } fprintf(stderr, "Modification to ciphertext was not detected\n"); return 1; } int main(int argc, char** argv) { int fd = -1, cfd = -1; if (argc > 1) debug = 1; /* Open the crypto device */ fd = open("/dev/crypto", O_RDWR, 0); if (fd < 0) { my_perror("open(/dev/crypto)"); return 1; } /* Clone file descriptor */ if (ioctl(fd, CRIOGET, &cfd)) { my_perror("ioctl(CRIOGET)"); return 1; } /* Set close-on-exec (not really neede here) */ if (fcntl(cfd, F_SETFD, 1) == -1) { my_perror("fcntl(F_SETFD)"); return 1; } /* Run the test itself */ if (test_crypto(cfd)) return 1; if (test_encrypt_decrypt(cfd)) return 1; if (test_encrypt_decrypt_error(cfd, 0)) return 1; if (test_encrypt_decrypt_error(cfd, 1)) return 1; /* Close cloned descriptor */ if (close(cfd)) { my_perror("close(cfd)"); return 1; } /* Close the original descriptor */ if (close(fd)) { my_perror("close(fd)"); return 1; } return 0; } cryptodev-linux-1.6/tests/cipher.c0000644000175100017510000001644012102243276016006 0ustar nmavnmav/* * Demo on how to use /dev/crypto device for ciphering. * * Placed under public domain. * */ #include #include #include #include #include #include static int debug = 0; #define DATA_SIZE 8*1024 #define BLOCK_SIZE 16 #define KEY_SIZE 16 static int test_crypto(int cfd) { char plaintext_raw[DATA_SIZE + 63], *plaintext; char ciphertext_raw[DATA_SIZE + 63], *ciphertext; char iv[BLOCK_SIZE]; char key[KEY_SIZE]; struct session_op sess; #ifdef CIOCGSESSINFO struct session_info_op siop; #endif struct crypt_op cryp; memset(&sess, 0, sizeof(sess)); memset(&cryp, 0, sizeof(cryp)); memset(key, 0x33, sizeof(key)); memset(iv, 0x03, sizeof(iv)); /* Get crypto session for AES128 */ sess.cipher = CRYPTO_AES_CBC; sess.keylen = KEY_SIZE; sess.key = key; if (ioctl(cfd, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop.ses = sess.ses; if (ioctl(cfd, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } if (debug) printf("requested cipher CRYPTO_AES_CBC, got %s with driver %s\n", siop.cipher_info.cra_name, siop.cipher_info.cra_driver_name); plaintext = (char *)(((unsigned long)plaintext_raw + siop.alignmask) & ~siop.alignmask); ciphertext = (char *)(((unsigned long)ciphertext_raw + siop.alignmask) & ~siop.alignmask); #else plaintext = plaintext_raw; ciphertext = ciphertext_raw; #endif memset(plaintext, 0x15, DATA_SIZE); /* Encrypt data.in to data.encrypted */ cryp.ses = sess.ses; cryp.len = DATA_SIZE; cryp.src = plaintext; cryp.dst = ciphertext; cryp.iv = iv; cryp.op = COP_ENCRYPT; if (ioctl(cfd, CIOCCRYPT, &cryp)) { perror("ioctl(CIOCCRYPT)"); return 1; } if (ioctl(cfd, CIOCFSESSION, &sess.ses)) { perror("ioctl(CIOCFSESSION)"); return 1; } if (ioctl(cfd, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop.ses = sess.ses; if (ioctl(cfd, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } if (debug) printf("requested cipher CRYPTO_AES_CBC, got %s with driver %s\n", siop.cipher_info.cra_name, siop.cipher_info.cra_driver_name); #endif /* Decrypt data.encrypted to data.decrypted */ cryp.ses = sess.ses; cryp.len = DATA_SIZE; cryp.src = ciphertext; cryp.dst = ciphertext; cryp.iv = iv; cryp.op = COP_DECRYPT; if (ioctl(cfd, CIOCCRYPT, &cryp)) { perror("ioctl(CIOCCRYPT)"); return 1; } /* Verify the result */ if (memcmp(plaintext, ciphertext, DATA_SIZE) != 0) { int i; fprintf(stderr, "FAIL: Decrypted data are different from the input data.\n"); printf("plaintext:"); for (i = 0; i < DATA_SIZE; i++) { if ((i % 30) == 0) printf("\n"); printf("%02x ", plaintext[i]); } printf("ciphertext:"); for (i = 0; i < DATA_SIZE; i++) { if ((i % 30) == 0) printf("\n"); printf("%02x ", ciphertext[i]); } printf("\n"); return 1; } else if (debug) printf("Test passed\n"); /* Finish crypto session */ if (ioctl(cfd, CIOCFSESSION, &sess.ses)) { perror("ioctl(CIOCFSESSION)"); return 1; } return 0; } static int test_aes(int cfd) { char plaintext1_raw[BLOCK_SIZE + 63], *plaintext1; char ciphertext1[BLOCK_SIZE] = { 0xdf, 0x55, 0x6a, 0x33, 0x43, 0x8d, 0xb8, 0x7b, 0xc4, 0x1b, 0x17, 0x52, 0xc5, 0x5e, 0x5e, 0x49 }; char iv1[BLOCK_SIZE]; char key1[KEY_SIZE] = { 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; char plaintext2_data[BLOCK_SIZE] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00 }; char plaintext2_raw[BLOCK_SIZE + 63], *plaintext2; char ciphertext2[BLOCK_SIZE] = { 0xb7, 0x97, 0x2b, 0x39, 0x41, 0xc4, 0x4b, 0x90, 0xaf, 0xa7, 0xb2, 0x64, 0xbf, 0xba, 0x73, 0x87 }; char iv2[BLOCK_SIZE]; char key2[KEY_SIZE]; struct session_op sess; #ifdef CIOCGSESSINFO struct session_info_op siop; #endif struct crypt_op cryp; memset(&sess, 0, sizeof(sess)); memset(&cryp, 0, sizeof(cryp)); /* Get crypto session for AES128 */ sess.cipher = CRYPTO_AES_CBC; sess.keylen = KEY_SIZE; sess.key = key1; if (ioctl(cfd, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop.ses = sess.ses; if (ioctl(cfd, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } plaintext1 = (char *)(((unsigned long)plaintext1_raw + siop.alignmask) & ~siop.alignmask); #else plaintext1 = plaintext1_raw; #endif memset(plaintext1, 0x0, BLOCK_SIZE); memset(iv1, 0x0, sizeof(iv1)); /* Encrypt data.in to data.encrypted */ cryp.ses = sess.ses; cryp.len = BLOCK_SIZE; cryp.src = plaintext1; cryp.dst = plaintext1; cryp.iv = iv1; cryp.op = COP_ENCRYPT; if (ioctl(cfd, CIOCCRYPT, &cryp)) { perror("ioctl(CIOCCRYPT)"); return 1; } /* Verify the result */ if (memcmp(plaintext1, ciphertext1, BLOCK_SIZE) != 0) { fprintf(stderr, "FAIL: Decrypted data are different from the input data.\n"); return 1; } /* Test 2 */ memset(key2, 0x0, sizeof(key2)); memset(iv2, 0x0, sizeof(iv2)); /* Get crypto session for AES128 */ sess.cipher = CRYPTO_AES_CBC; sess.keylen = KEY_SIZE; sess.key = key2; if (ioctl(cfd, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop.ses = sess.ses; if (ioctl(cfd, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } if (debug) printf("requested cipher CRYPTO_AES_CBC, got %s with driver %s\n", siop.cipher_info.cra_name, siop.cipher_info.cra_driver_name); plaintext2 = (char *)(((unsigned long)plaintext2_raw + siop.alignmask) & ~siop.alignmask); #else plaintext2 = plaintext2_raw; #endif memcpy(plaintext2, plaintext2_data, BLOCK_SIZE); /* Encrypt data.in to data.encrypted */ cryp.ses = sess.ses; cryp.len = BLOCK_SIZE; cryp.src = plaintext2; cryp.dst = plaintext2; cryp.iv = iv2; cryp.op = COP_ENCRYPT; if (ioctl(cfd, CIOCCRYPT, &cryp)) { perror("ioctl(CIOCCRYPT)"); return 1; } /* Verify the result */ if (memcmp(plaintext2, ciphertext2, BLOCK_SIZE) != 0) { int i; fprintf(stderr, "FAIL: Decrypted data are different from the input data.\n"); printf("plaintext:"); for (i = 0; i < BLOCK_SIZE; i++) { if ((i % 30) == 0) printf("\n"); printf("%02x ", plaintext2[i]); } printf("ciphertext:"); for (i = 0; i < BLOCK_SIZE; i++) { if ((i % 30) == 0) printf("\n"); printf("%02x ", ciphertext2[i]); } printf("\n"); return 1; } if (debug) printf("AES Test passed\n"); /* Finish crypto session */ if (ioctl(cfd, CIOCFSESSION, &sess.ses)) { perror("ioctl(CIOCFSESSION)"); return 1; } return 0; } int main(int argc, char** argv) { int fd = -1, cfd = -1; if (argc > 1) debug = 1; /* Open the crypto device */ fd = open("/dev/crypto", O_RDWR, 0); if (fd < 0) { perror("open(/dev/crypto)"); return 1; } /* Clone file descriptor */ if (ioctl(fd, CRIOGET, &cfd)) { perror("ioctl(CRIOGET)"); return 1; } /* Set close-on-exec (not really neede here) */ if (fcntl(cfd, F_SETFD, 1) == -1) { perror("fcntl(F_SETFD)"); return 1; } /* Run the test itself */ if (test_aes(cfd)) return 1; if (test_crypto(cfd)) return 1; /* Close cloned descriptor */ if (close(cfd)) { perror("close(cfd)"); return 1; } /* Close the original descriptor */ if (close(fd)) { perror("close(fd)"); return 1; } return 0; } cryptodev-linux-1.6/tests/async_hmac.c0000644000175100017510000001466112115016263016642 0ustar nmavnmav/* * Demo on how to use /dev/crypto device for HMAC. * * Placed under public domain. * */ #include #include #include #include #include #include #include #include #include "testhelper.h" #ifdef ENABLE_ASYNC static int debug = 0; #define DATA_SIZE 4096 #define BLOCK_SIZE 16 #define KEY_SIZE 16 #define SHA1_HASH_LEN 20 static int test_crypto(int cfd) { struct { uint8_t in[DATA_SIZE], encrypted[DATA_SIZE], decrypted[DATA_SIZE], iv[BLOCK_SIZE], key[KEY_SIZE]; } data; struct session_op sess; struct crypt_op cryp; uint8_t mac[AALG_MAX_RESULT_LEN]; uint8_t oldmac[AALG_MAX_RESULT_LEN]; uint8_t md5_hmac_out[] = "\x75\x0c\x78\x3e\x6a\xb0\xb5\x03\xea\xa8\x6e\x31\x0a\x5d\xb7\x38"; uint8_t sha1_out[] = "\x8f\x82\x03\x94\xf9\x53\x35\x18\x20\x45\xda\x24\xf3\x4d\xe5\x2b\xf8\xbc\x34\x32"; int i; memset(&sess, 0, sizeof(sess)); memset(&cryp, 0, sizeof(cryp)); /* Use the garbage that is on the stack :-) */ /* memset(&data, 0, sizeof(data)); */ /* SHA1 plain test */ memset(mac, 0, sizeof(mac)); sess.cipher = 0; sess.mac = CRYPTO_SHA1; if (ioctl(cfd, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } cryp.ses = sess.ses; cryp.len = sizeof("what do ya want for nothing?")-1; cryp.src = "what do ya want for nothing?"; cryp.mac = mac; cryp.op = COP_ENCRYPT; DO_OR_DIE(do_async_crypt(cfd, &cryp), 0); DO_OR_DIE(do_async_fetch(cfd, &cryp), 0); if (memcmp(mac, sha1_out, 20)!=0) { printf("mac: "); for (i=0;i * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include #include #include #include #include #include #include #include #define MAX(x,y) ((x)>(y)?(x):(y)) static double udifftimeval(struct timeval start, struct timeval end) { return (double)(end.tv_usec - start.tv_usec) + (double)(end.tv_sec - start.tv_sec) * 1000 * 1000; } static int must_finish = 0; static void alarm_handler(int signo) { must_finish = 1; } static char *units[] = { "", "Ki", "Mi", "Gi", "Ti", 0}; static char *si_units[] = { "", "K", "M", "G", "T", 0}; static void value2human(int si, double bytes, double time, double* data, double* speed,char* metric) { int unit = 0; *data = bytes; if (si) { while (*data > 1000 && si_units[unit + 1]) { *data /= 1000; unit++; } *speed = *data / time; sprintf(metric, "%sB", si_units[unit]); } else { while (*data > 1024 && units[unit + 1]) { *data /= 1024; unit++; } *speed = *data / time; sprintf(metric, "%sB", units[unit]); } } int hash_data(struct session_op *sess, int fdc, int chunksize, int align) { struct crypt_op cop; char *buffer; static int val = 23; struct timeval start, end; double total = 0; double secs, ddata, dspeed; char metric[16]; uint8_t mac[AALG_MAX_RESULT_LEN]; if (align) { if (posix_memalign((void **)&buffer, align, chunksize)) { printf("posix_memalign() failed, align: %d, size: %d!\n", align, chunksize); return 1; } } else { if (!(buffer = malloc(chunksize))) { perror("malloc()"); return 1; } } printf("\tEncrypting in chunks of %d bytes: ", chunksize); fflush(stdout); memset(buffer, val++, chunksize); must_finish = 0; alarm(5); gettimeofday(&start, NULL); do { memset(&cop, 0, sizeof(cop)); cop.ses = sess->ses; cop.len = chunksize; cop.op = COP_ENCRYPT; cop.src = cop.dst = (unsigned char *)buffer; cop.mac = mac; if (ioctl(fdc, CIOCCRYPT, &cop)) { perror("ioctl(CIOCCRYPT)"); return 1; } total+=chunksize; } while(must_finish==0); gettimeofday(&end, NULL); secs = udifftimeval(start, end)/ 1000000.0; value2human(1, total, secs, &ddata, &dspeed, metric); printf ("done. %.2f %s in %.2f secs: ", ddata, metric, secs); printf ("%.2f %s/sec\n", dspeed, metric); free(buffer); return 0; } int main(void) { int fd, i, fdc = -1, align = 0; struct session_op sess; char keybuf[32]; #ifdef CIOCGSESSINFO struct session_info_op siop; #endif signal(SIGALRM, alarm_handler); if ((fd = open("/dev/crypto", O_RDWR, 0)) < 0) { perror("open()"); return 1; } if (ioctl(fd, CRIOGET, &fdc)) { perror("ioctl(CRIOGET)"); return 1; } fprintf(stderr, "Testing AES128 with SHA1 Hash: \n"); memset(&sess, 0, sizeof(sess)); sess.cipher = CRYPTO_AES_CBC; sess.keylen = 16; memset(keybuf, 0x42, 32); sess.key = (unsigned char *)keybuf; sess.mac = CRYPTO_SHA1; if (ioctl(fdc, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop.ses = sess.ses; if (ioctl(fdc, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } printf("requested hash CRYPTO_SHA1, got %s with driver %s\n", siop.hash_info.cra_name, siop.hash_info.cra_driver_name); align = MAX(sizeof(void*), siop.alignmask+1); #endif for (i = 256; i <= (64 * 1024); i *= 4) { if (hash_data(&sess, fdc, i, align)) break; } fprintf(stderr, "\nTesting AES256 with SHA256 Hash: \n"); memset(&sess, 0, sizeof(sess)); sess.cipher = CRYPTO_AES_CBC; sess.keylen = 32; sess.key = (unsigned char *)keybuf; sess.mac = CRYPTO_SHA2_256; if (ioctl(fdc, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop.ses = sess.ses; if (ioctl(fdc, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } printf("requested hash CRYPTO_SHA2_256, got %s with driver %s\n", siop.hash_info.cra_name, siop.hash_info.cra_driver_name); align = MAX(sizeof(void*), siop.alignmask+1); #endif for (i = 256; i <= (64 * 1024); i *= 4) { if (hash_data(&sess, fdc, i, align)) break; } close(fdc); close(fd); return 0; } cryptodev-linux-1.6/tests/testhelper.h0000644000175100017510000000235412102243276016717 0ustar nmavnmav/* * Some helper stuff shared between the sample programs. */ #ifndef _TESTHELPER_H #define _TESTHELPER_H /* poll until POLLOUT, then call CIOCASYNCCRYPT */ inline int do_async_crypt(int cfd, struct crypt_op *cryp) { struct pollfd pfd; pfd.fd = cfd; pfd.events = POLLOUT; if (poll(&pfd, 1, -1) < 1) { perror("poll()"); return 1; } if (ioctl(cfd, CIOCASYNCCRYPT, cryp)) { perror("ioctl(CIOCCRYPT)"); return 1; } return 0; } /* poll until POLLIN, then call CIOCASYNCFETCH */ inline int do_async_fetch(int cfd, struct crypt_op *cryp) { struct pollfd pfd; pfd.fd = cfd; pfd.events = POLLIN; if (poll(&pfd, 1, -1) < 1) { perror("poll()"); return 1; } if (ioctl(cfd, CIOCASYNCFETCH, cryp)) { perror("ioctl(CIOCCRYPT)"); return 1; } return 0; } /* Check return value of stmt for identity with goodval. If they * don't match, call return with the value of stmt. */ #define DO_OR_DIE(stmt, goodval) { \ int __rc_val; \ if ((__rc_val = stmt) != goodval) { \ perror("DO_OR_DIE(" #stmt "," #goodval ")"); \ return __rc_val; \ } \ } #endif /* _TESTHELPER_H */ cryptodev-linux-1.6/tests/sha_speed.c0000644000175100017510000001116512102243276016466 0ustar nmavnmav/* sha_speed - simple SHA benchmark tool for cryptodev * * Copyright (C) 2011 by Phil Sutter * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include #include #include #include #include #include #include #include static double udifftimeval(struct timeval start, struct timeval end) { return (double)(end.tv_usec - start.tv_usec) + (double)(end.tv_sec - start.tv_sec) * 1000 * 1000; } static int must_finish = 0; static void alarm_handler(int signo) { must_finish = 1; } static char *units[] = { "", "Ki", "Mi", "Gi", "Ti", 0}; static char *si_units[] = { "", "K", "M", "G", "T", 0}; static void value2human(int si, double bytes, double time, double* data, double* speed,char* metric) { int unit = 0; *data = bytes; if (si) { while (*data > 1000 && si_units[unit + 1]) { *data /= 1000; unit++; } *speed = *data / time; sprintf(metric, "%sB", si_units[unit]); } else { while (*data > 1024 && units[unit + 1]) { *data /= 1024; unit++; } *speed = *data / time; sprintf(metric, "%sB", units[unit]); } } int hash_data(struct session_op *sess, int fdc, int chunksize, int alignmask) { struct crypt_op cop; char *buffer; static int val = 23; struct timeval start, end; double total = 0; double secs, ddata, dspeed; char metric[16]; uint8_t mac[AALG_MAX_RESULT_LEN]; if (alignmask) { if (posix_memalign((void **)&buffer, alignmask + 1, chunksize)) { printf("posix_memalign() failed!\n"); return 1; } } else { if (!(buffer = malloc(chunksize))) { perror("malloc()"); return 1; } } printf("\tEncrypting in chunks of %d bytes: ", chunksize); fflush(stdout); memset(buffer, val++, chunksize); must_finish = 0; alarm(5); gettimeofday(&start, NULL); do { memset(&cop, 0, sizeof(cop)); cop.ses = sess->ses; cop.len = chunksize; cop.op = COP_ENCRYPT; cop.src = (unsigned char *)buffer; cop.mac = mac; if (ioctl(fdc, CIOCCRYPT, &cop)) { perror("ioctl(CIOCCRYPT)"); return 1; } total+=chunksize; } while(must_finish==0); gettimeofday(&end, NULL); secs = udifftimeval(start, end)/ 1000000.0; value2human(1, total, secs, &ddata, &dspeed, metric); printf ("done. %.2f %s in %.2f secs: ", ddata, metric, secs); printf ("%.2f %s/sec\n", dspeed, metric); free(buffer); return 0; } int main(void) { int fd, i, fdc = -1, alignmask = 0; struct session_op sess; char keybuf[32]; #ifdef CIOCGSESSINFO struct session_info_op siop; #endif signal(SIGALRM, alarm_handler); if ((fd = open("/dev/crypto", O_RDWR, 0)) < 0) { perror("open()"); return 1; } if (ioctl(fd, CRIOGET, &fdc)) { perror("ioctl(CRIOGET)"); return 1; } fprintf(stderr, "Testing SHA1 Hash: \n"); memset(&sess, 0, sizeof(sess)); sess.mac = CRYPTO_SHA1; if (ioctl(fdc, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop.ses = sess.ses; if (ioctl(fdc, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } printf("requested hash CRYPTO_SHA1, got %s with driver %s\n", siop.hash_info.cra_name, siop.hash_info.cra_driver_name); alignmask = siop.alignmask; #endif for (i = 256; i <= (64 * 1024); i *= 4) { if (hash_data(&sess, fdc, i, alignmask)) break; } fprintf(stderr, "\nTesting SHA256 Hash: \n"); memset(&sess, 0, sizeof(sess)); sess.mac = CRYPTO_SHA2_256; if (ioctl(fdc, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop.ses = sess.ses; if (ioctl(fdc, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } printf("requested hash CRYPTO_SHA2_256, got %s with driver %s\n", siop.hash_info.cra_name, siop.hash_info.cra_driver_name); alignmask = siop.alignmask; #endif for (i = 256; i <= (64 * 1024); i *= 4) { if (hash_data(&sess, fdc, i, alignmask)) break; } close(fdc); close(fd); return 0; } cryptodev-linux-1.6/tests/cipher-aead.c0000644000175100017510000003151312102243276016674 0ustar nmavnmav/* * Demo on how to use /dev/crypto device for ciphering. * * Placed under public domain. * */ #include #include #include #include #include #include #include #define DATA_SIZE (8*1024) #define AUTH_SIZE 31 #define BLOCK_SIZE 16 #define KEY_SIZE 16 #define MAC_SIZE 20 /* SHA1 */ static int debug = 0; static int get_sha1_hmac(int cfd, void* key, int key_size, void* data1, int data1_size, void* data2, int data2_size, void* mac) { struct session_op sess; struct crypt_op cryp; memset(&sess, 0, sizeof(sess)); memset(&cryp, 0, sizeof(cryp)); sess.cipher = 0; sess.mac = CRYPTO_SHA1_HMAC; sess.mackeylen = key_size; sess.mackey = key; if (ioctl(cfd, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } /* Encrypt data.in to data.encrypted */ cryp.ses = sess.ses; cryp.len = data1_size; cryp.src = data1; cryp.dst = NULL; cryp.iv = NULL; cryp.mac = mac; cryp.op = COP_ENCRYPT; cryp.flags = COP_FLAG_UPDATE; if (ioctl(cfd, CIOCCRYPT, &cryp)) { perror("ioctl(CIOCCRYPT)"); return 1; } cryp.ses = sess.ses; cryp.len = data2_size; cryp.src = data2; cryp.dst = NULL; cryp.iv = NULL; cryp.mac = mac; cryp.op = COP_ENCRYPT; cryp.flags = COP_FLAG_FINAL; if (ioctl(cfd, CIOCCRYPT, &cryp)) { perror("ioctl(CIOCCRYPT)"); return 1; } /* Finish crypto session */ if (ioctl(cfd, CIOCFSESSION, &sess.ses)) { perror("ioctl(CIOCFSESSION)"); return 1; } return 0; } static void print_buf(char* desc, unsigned char* buf, int size) { int i; fputs(desc, stdout); for (i=0;i * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include #include #include #include #include #include #include #include #include #ifdef ENABLE_ASYNC static double udifftimeval(struct timeval start, struct timeval end) { return (double)(end.tv_usec - start.tv_usec) + (double)(end.tv_sec - start.tv_sec) * 1000 * 1000; } static int must_finish = 0; static struct pollfd pfd; static void alarm_handler(int signo) { must_finish = 1; pfd.events = POLLIN; } static char *units[] = { "", "Ki", "Mi", "Gi", "Ti", 0}; static void value2human(double bytes, double time, double* data, double* speed,char* metric) { int unit = 0; *data = bytes; while (*data > 1024 && units[unit + 1]) { *data /= 1024; unit++; } *speed = *data / time; sprintf(metric, "%sB", units[unit]); } int encrypt_data(struct session_op *sess, int fdc, int chunksize, int alignmask) { struct crypt_op cop; char *buffer[64], iv[32]; static int val = 23; struct timeval start, end; double total = 0; double secs, ddata, dspeed; char metric[16]; int rc, wqueue = 0, bufidx = 0; memset(iv, 0x23, 32); printf("\tEncrypting in chunks of %d bytes: ", chunksize); fflush(stdout); for (rc = 0; rc < 64; rc++) { if (alignmask) { if (posix_memalign((void **)(buffer + rc), alignmask + 1, chunksize)) { printf("posix_memalign() failed!\n"); return 1; } } else { if (!(buffer[rc] = malloc(chunksize))) { perror("malloc()"); return 1; } } memset(buffer[rc], val++, chunksize); } pfd.fd = fdc; pfd.events = POLLOUT | POLLIN; must_finish = 0; alarm(5); gettimeofday(&start, NULL); do { if ((rc = poll(&pfd, 1, 100)) < 0) { if (errno & (ERESTART | EINTR)) continue; fprintf(stderr, "errno = %d ", errno); perror("poll()"); return 1; } if (pfd.revents & POLLOUT) { memset(&cop, 0, sizeof(cop)); cop.ses = sess->ses; cop.len = chunksize; cop.iv = (unsigned char *)iv; cop.op = COP_ENCRYPT; cop.src = cop.dst = (unsigned char *)buffer[bufidx]; bufidx = (bufidx + 1) % 64; if (ioctl(fdc, CIOCASYNCCRYPT, &cop)) { perror("ioctl(CIOCASYNCCRYPT)"); return 1; } wqueue++; } if (pfd.revents & POLLIN) { if (ioctl(fdc, CIOCASYNCFETCH, &cop)) { perror("ioctl(CIOCASYNCFETCH)"); return 1; } wqueue--; total += cop.len; } } while(!must_finish || wqueue); gettimeofday(&end, NULL); secs = udifftimeval(start, end)/ 1000000.0; value2human(total, secs, &ddata, &dspeed, metric); printf ("done. %.2f %s in %.2f secs: ", ddata, metric, secs); printf ("%.2f %s/sec\n", dspeed, metric); for (rc = 0; rc < 64; rc++) free(buffer[rc]); return 0; } int main(void) { int fd, i, fdc = -1, alignmask = 0; struct session_op sess; #ifdef CIOCGSESSINFO struct session_info_op siop; #endif char keybuf[32]; signal(SIGALRM, alarm_handler); if ((fd = open("/dev/crypto", O_RDWR, 0)) < 0) { perror("open()"); return 1; } if (ioctl(fd, CRIOGET, &fdc)) { perror("ioctl(CRIOGET)"); return 1; } fprintf(stderr, "Testing NULL cipher: \n"); memset(&sess, 0, sizeof(sess)); sess.cipher = CRYPTO_NULL; sess.keylen = 0; sess.key = (unsigned char *)keybuf; if (ioctl(fdc, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop.ses = sess.ses; if (ioctl(fdc, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } alignmask = siop.alignmask; #endif for (i = 256; i <= (64 * 4096); i *= 2) { if (encrypt_data(&sess, fdc, i, alignmask)) break; } fprintf(stderr, "\nTesting AES-128-CBC cipher: \n"); memset(&sess, 0, sizeof(sess)); sess.cipher = CRYPTO_AES_CBC; sess.keylen = 16; memset(keybuf, 0x42, 16); sess.key = (unsigned char *)keybuf; if (ioctl(fdc, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop.ses = sess.ses; if (ioctl(fdc, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } alignmask = siop.alignmask; #endif for (i = 256; i <= (64 * 1024); i *= 2) { if (encrypt_data(&sess, fdc, i, alignmask)) break; } close(fdc); close(fd); return 0; } #else int main(int argc, char** argv) { return (0); } #endif cryptodev-linux-1.6/tests/Makefile0000644000175100017510000000167712115016041016026 0ustar nmavnmavKERNEL_DIR ?= /lib/modules/$(shell uname -r)/build KBUILD_CFLAGS += -I.. $(CRYPTODEV_CFLAGS) CFLAGS += -I.. $(CRYPTODEV_CFLAGS) comp_progs := cipher_comp hash_comp hmac_comp hostprogs := cipher cipher-aead hmac speed async_cipher async_hmac \ async_speed sha_speed hashcrypt_speed fullspeed cipher-gcm \ cipher-aead-srtp ${comp_progs} example-cipher-objs := cipher.o example-cipher-aead-objs := cipher-aead.o example-hmac-objs := hmac.o example-speed-objs := speed.c example-fullspeed-objs := fullspeed.c example-sha-speed-objs := sha_speed.c example-async-cipher-objs := async_cipher.o example-async-hmac-objs := async_hmac.o example-async-speed-objs := async_speed.o example-hashcrypt-speed-objs := hashcrypt_speed.c check: $(hostprogs) ./cipher ./hmac ./async_cipher ./async_hmac ./cipher-aead-srtp ./cipher-gcm ./cipher-aead clean: rm -f *.o *~ $(hostprogs) ${comp_progs}: LDFLAGS += -lssl -lcrypto ${comp_progs}: %: %.o openssl_wrapper.o cryptodev-linux-1.6/tests/cipher-aead-srtp.c0000644000175100017510000003166512102243276017672 0ustar nmavnmav/* * Demo on how to use /dev/crypto device for ciphering. * * Placed under public domain. * */ #include #include #include #include #include #include #include #define DATA_SIZE (8*1024) #define HEADER_SIZE 193 #define PLAINTEXT_SIZE 1021 #define FOOTER_SIZE 15 #define BLOCK_SIZE 16 #define KEY_SIZE 16 #define MAC_SIZE 20 /* SHA1 */ static int debug = 0; static int get_sha1_hmac(int cfd, void* key, int key_size, void* data, int data_size, void* mac) { struct session_op sess; struct crypt_op cryp; memset(&sess, 0, sizeof(sess)); memset(&cryp, 0, sizeof(cryp)); sess.cipher = 0; sess.mac = CRYPTO_SHA1_HMAC; sess.mackeylen = key_size; sess.mackey = key; if (ioctl(cfd, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } /* Encrypt data.in to data.encrypted */ cryp.ses = sess.ses; cryp.len = data_size; cryp.src = data; cryp.dst = NULL; cryp.iv = NULL; cryp.mac = mac; cryp.op = COP_ENCRYPT; if (ioctl(cfd, CIOCCRYPT, &cryp)) { perror("ioctl(CIOCCRYPT)"); return 1; } /* Finish crypto session */ if (ioctl(cfd, CIOCFSESSION, &sess.ses)) { perror("ioctl(CIOCFSESSION)"); return 1; } return 0; } static void print_buf(char* desc, unsigned char* buf, int size) { int i; fputs(desc, stderr); for (i=0;i 1) debug = 1; /* Open the crypto device */ fd = open("/dev/crypto", O_RDWR, 0); if (fd < 0) { perror("open(/dev/crypto)"); return 1; } /* Clone file descriptor */ if (ioctl(fd, CRIOGET, &cfd)) { perror("ioctl(CRIOGET)"); return 1; } /* Set close-on-exec (not really neede here) */ if (fcntl(cfd, F_SETFD, 1) == -1) { perror("fcntl(F_SETFD)"); return 1; } /* Run the test itself */ if (test_crypto(cfd)) return 1; if (test_encrypt_decrypt(cfd)) return 1; if (test_encrypt_decrypt_error(cfd,0)) return 1; if (test_encrypt_decrypt_error(cfd,1)) return 1; /* Close cloned descriptor */ if (close(cfd)) { perror("close(cfd)"); return 1; } /* Close the original descriptor */ if (close(fd)) { perror("close(fd)"); return 1; } return 0; } cryptodev-linux-1.6/tests/hmac.c0000644000175100017510000001673512102243276015453 0ustar nmavnmav/* * Demo on how to use /dev/crypto device for HMAC. * * Placed under public domain. * */ #include #include #include #include #include #include #include static int debug = 0; #define DATA_SIZE 4096 #define BLOCK_SIZE 16 #define KEY_SIZE 16 #define SHA1_HASH_LEN 20 static int test_crypto(int cfd) { struct { uint8_t in[DATA_SIZE], encrypted[DATA_SIZE], decrypted[DATA_SIZE], iv[BLOCK_SIZE], key[KEY_SIZE]; } data; struct session_op sess; #ifdef CIOCGSESSINFO struct session_info_op siop; #endif struct crypt_op cryp; uint8_t mac[AALG_MAX_RESULT_LEN]; uint8_t oldmac[AALG_MAX_RESULT_LEN]; uint8_t md5_hmac_out[] = "\x75\x0c\x78\x3e\x6a\xb0\xb5\x03\xea\xa8\x6e\x31\x0a\x5d\xb7\x38"; uint8_t sha1_out[] = "\x8f\x82\x03\x94\xf9\x53\x35\x18\x20\x45\xda\x24\xf3\x4d\xe5\x2b\xf8\xbc\x34\x32"; int i; memset(&sess, 0, sizeof(sess)); memset(&cryp, 0, sizeof(cryp)); /* Use the garbage that is on the stack :-) */ /* memset(&data, 0, sizeof(data)); */ /* SHA1 plain test */ memset(mac, 0, sizeof(mac)); sess.cipher = 0; sess.mac = CRYPTO_SHA1; if (ioctl(cfd, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop.ses = sess.ses; if (ioctl(cfd, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } if (debug) printf("requested mac CRYPTO_SHA1, got %s with driver %s\n", siop.hash_info.cra_name, siop.hash_info.cra_driver_name); #endif cryp.ses = sess.ses; cryp.len = sizeof("what do ya want for nothing?")-1; cryp.src = "what do ya want for nothing?"; cryp.mac = mac; cryp.op = COP_ENCRYPT; if (ioctl(cfd, CIOCCRYPT, &cryp)) { perror("ioctl(CIOCCRYPT)"); return 1; } if (memcmp(mac, sha1_out, 20)!=0) { printf("mac: "); for (i=0;i 1) debug = 1; /* Open the crypto device */ fd = open("/dev/crypto", O_RDWR, 0); if (fd < 0) { perror("open(/dev/crypto)"); return 1; } /* Clone file descriptor */ if (ioctl(fd, CRIOGET, &cfd)) { perror("ioctl(CRIOGET)"); return 1; } /* Set close-on-exec (not really neede here) */ if (fcntl(cfd, F_SETFD, 1) == -1) { perror("fcntl(F_SETFD)"); return 1; } /* Run the test itself */ if (test_crypto(cfd)) return 1; if (test_extras(cfd)) return 1; /* Close cloned descriptor */ if (close(cfd)) { perror("close(cfd)"); return 1; } /* Close the original descriptor */ if (close(fd)) { perror("close(fd)"); return 1; } return 0; } cryptodev-linux-1.6/tests/async_cipher.c0000644000175100017510000001723012115016255017200 0ustar nmavnmav/* * Demo on how to use /dev/crypto device for ciphering. * * Placed under public domain. * */ #include #include #include #include #include #include #include #include "testhelper.h" #ifdef ENABLE_ASYNC static int debug = 0; #define DATA_SIZE 8*1024 #define BLOCK_SIZE 16 #define KEY_SIZE 16 static int test_crypto(int cfd) { char plaintext_raw[DATA_SIZE + 63], *plaintext; char ciphertext_raw[DATA_SIZE + 63], *ciphertext; char iv[BLOCK_SIZE]; char key[KEY_SIZE]; struct session_op sess; #ifdef CIOCGSESSINFO struct session_info_op siop; #endif struct crypt_op cryp; if (debug) printf("running %s\n", __func__); memset(&sess, 0, sizeof(sess)); memset(&cryp, 0, sizeof(cryp)); memset(key, 0x33, sizeof(key)); memset(iv, 0x03, sizeof(iv)); /* Get crypto session for AES128 */ sess.cipher = CRYPTO_AES_CBC; sess.keylen = KEY_SIZE; sess.key = key; if (ioctl(cfd, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } if (debug) printf("%s: got the session\n", __func__); #ifdef CIOCGSESSINFO siop.ses = sess.ses; if (ioctl(cfd, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } plaintext = (char *)(((unsigned long)plaintext_raw + siop.alignmask) & ~siop.alignmask); ciphertext = (char *)(((unsigned long)ciphertext_raw + siop.alignmask) & ~siop.alignmask); #else plaintext = plaintext_raw; ciphertext = ciphertext_raw; #endif memset(plaintext, 0x15, DATA_SIZE); /* Encrypt data.in to data.encrypted */ cryp.ses = sess.ses; cryp.len = DATA_SIZE; cryp.src = plaintext; cryp.dst = ciphertext; cryp.iv = iv; cryp.op = COP_ENCRYPT; DO_OR_DIE(do_async_crypt(cfd, &cryp), 0); DO_OR_DIE(do_async_fetch(cfd, &cryp), 0); if (debug) printf("%s: data encrypted\n", __func__); if (ioctl(cfd, CIOCFSESSION, &sess.ses)) { perror("ioctl(CIOCFSESSION)"); return 1; } if (debug) printf("%s: session finished\n", __func__); if (ioctl(cfd, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } if (debug) printf("%s: got new session\n", __func__); /* Decrypt data.encrypted to data.decrypted */ cryp.ses = sess.ses; cryp.len = DATA_SIZE; cryp.src = ciphertext; cryp.dst = ciphertext; cryp.iv = iv; cryp.op = COP_DECRYPT; DO_OR_DIE(do_async_crypt(cfd, &cryp), 0); DO_OR_DIE(do_async_fetch(cfd, &cryp), 0); if (debug) printf("%s: data encrypted\n", __func__); /* Verify the result */ if (memcmp(plaintext, ciphertext, DATA_SIZE) != 0) { fprintf(stderr, "FAIL: Decrypted data are different from the input data.\n"); return 1; } else if (debug) printf("Test passed\n"); /* Finish crypto session */ if (ioctl(cfd, CIOCFSESSION, &sess.ses)) { perror("ioctl(CIOCFSESSION)"); return 1; } return 0; } static int test_aes(int cfd) { char plaintext1_raw[BLOCK_SIZE + 63], *plaintext1; char ciphertext1[BLOCK_SIZE] = { 0xdf, 0x55, 0x6a, 0x33, 0x43, 0x8d, 0xb8, 0x7b, 0xc4, 0x1b, 0x17, 0x52, 0xc5, 0x5e, 0x5e, 0x49 }; char iv1[BLOCK_SIZE]; char key1[KEY_SIZE] = { 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; char plaintext2_data[BLOCK_SIZE] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00 }; char plaintext2_raw[BLOCK_SIZE + 63], *plaintext2; char ciphertext2[BLOCK_SIZE] = { 0xb7, 0x97, 0x2b, 0x39, 0x41, 0xc4, 0x4b, 0x90, 0xaf, 0xa7, 0xb2, 0x64, 0xbf, 0xba, 0x73, 0x87 }; char iv2[BLOCK_SIZE]; char key2[KEY_SIZE]; struct session_op sess1, sess2; #ifdef CIOCGSESSINFO struct session_info_op siop1, siop2; #endif struct crypt_op cryp1, cryp2; memset(&sess1, 0, sizeof(sess1)); memset(&sess2, 0, sizeof(sess2)); memset(&cryp1, 0, sizeof(cryp1)); memset(&cryp2, 0, sizeof(cryp2)); /* Get crypto session for AES128 */ sess1.cipher = CRYPTO_AES_CBC; sess1.keylen = KEY_SIZE; sess1.key = key1; if (ioctl(cfd, CIOCGSESSION, &sess1)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop1.ses = sess1.ses; if (ioctl(cfd, CIOCGSESSINFO, &siop1)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } plaintext1 = (char *)(((unsigned long)plaintext1_raw + siop1.alignmask) & ~siop1.alignmask); #else plaintext1 = plaintext1_raw; #endif memset(plaintext1, 0x0, BLOCK_SIZE); memset(iv1, 0x0, sizeof(iv1)); memset(key2, 0x0, sizeof(key2)); /* Get second crypto session for AES128 */ sess2.cipher = CRYPTO_AES_CBC; sess2.keylen = KEY_SIZE; sess2.key = key2; if (ioctl(cfd, CIOCGSESSION, &sess2)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop2.ses = sess2.ses; if (ioctl(cfd, CIOCGSESSINFO, &siop2)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } plaintext2 = (char *)(((unsigned long)plaintext2_raw + siop2.alignmask) & ~siop2.alignmask); #else plaintext2 = plaintext2_raw; #endif memcpy(plaintext2, plaintext2_data, BLOCK_SIZE); /* Encrypt data.in to data.encrypted */ cryp1.ses = sess1.ses; cryp1.len = BLOCK_SIZE; cryp1.src = plaintext1; cryp1.dst = plaintext1; cryp1.iv = iv1; cryp1.op = COP_ENCRYPT; DO_OR_DIE(do_async_crypt(cfd, &cryp1), 0); if (debug) printf("cryp1 written out\n"); memset(iv2, 0x0, sizeof(iv2)); /* Encrypt data.in to data.encrypted */ cryp2.ses = sess2.ses; cryp2.len = BLOCK_SIZE; cryp2.src = plaintext2; cryp2.dst = plaintext2; cryp2.iv = iv2; cryp2.op = COP_ENCRYPT; DO_OR_DIE(do_async_crypt(cfd, &cryp2), 0); if (debug) printf("cryp2 written out\n"); DO_OR_DIE(do_async_fetch(cfd, &cryp1), 0); DO_OR_DIE(do_async_fetch(cfd, &cryp2), 0); if (debug) printf("cryp1 + cryp2 successfully read\n"); /* Verify the result */ if (memcmp(plaintext1, ciphertext1, BLOCK_SIZE) != 0) { int i; fprintf(stderr, "FAIL: Decrypted data are different from the input data.\n"); printf("plaintext:"); for (i = 0; i < BLOCK_SIZE; i++) { if ((i % 30) == 0) printf("\n"); printf("%02x ", plaintext1[i]); } printf("ciphertext:"); for (i = 0; i < BLOCK_SIZE; i++) { if ((i % 30) == 0) printf("\n"); printf("%02x ", ciphertext1[i]); } printf("\n"); return 1; } else { if (debug) printf("result 1 passed\n"); } /* Test 2 */ /* Verify the result */ if (memcmp(plaintext2, ciphertext2, BLOCK_SIZE) != 0) { int i; fprintf(stderr, "FAIL: Decrypted data are different from the input data.\n"); printf("plaintext:"); for (i = 0; i < BLOCK_SIZE; i++) { if ((i % 30) == 0) printf("\n"); printf("%02x ", plaintext2[i]); } printf("ciphertext:"); for (i = 0; i < BLOCK_SIZE; i++) { if ((i % 30) == 0) printf("\n"); printf("%02x ", ciphertext2[i]); } printf("\n"); return 1; } else { if (debug) printf("result 2 passed\n"); } if (debug) printf("AES Test passed\n"); /* Finish crypto session */ if (ioctl(cfd, CIOCFSESSION, &sess1.ses)) { perror("ioctl(CIOCFSESSION)"); return 1; } if (ioctl(cfd, CIOCFSESSION, &sess2.ses)) { perror("ioctl(CIOCFSESSION)"); return 1; } return 0; } int main(int argc, char** argv) { int fd = -1, cfd = -1; if (argc > 1) debug = 1; /* Open the crypto device */ fd = open("/dev/crypto", O_RDWR, 0); if (fd < 0) { perror("open(/dev/crypto)"); return 1; } /* Clone file descriptor */ if (ioctl(fd, CRIOGET, &cfd)) { perror("ioctl(CRIOGET)"); return 1; } /* Set close-on-exec (not really neede here) */ if (fcntl(cfd, F_SETFD, 1) == -1) { perror("fcntl(F_SETFD)"); return 1; } /* Run the test itself */ if (test_aes(cfd)) return 1; if (test_crypto(cfd)) return 1; /* Close cloned descriptor */ if (close(cfd)) { perror("close(cfd)"); return 1; } /* Close the original descriptor */ if (close(fd)) { perror("close(fd)"); return 1; } return 0; } #else int main(int argc, char** argv) { return (0); } #endif cryptodev-linux-1.6/tests/speed.c0000644000175100017510000001160212102243276015627 0ustar nmavnmav/* cryptodev_test - simple benchmark tool for cryptodev * * Copyright (C) 2010 by Phil Sutter * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include #include #include #include #include #include #include static int si = 1; /* SI by default */ static double udifftimeval(struct timeval start, struct timeval end) { return (double)(end.tv_usec - start.tv_usec) + (double)(end.tv_sec - start.tv_sec) * 1000 * 1000; } static int must_finish = 0; static void alarm_handler(int signo) { must_finish = 1; } static char *units[] = { "", "Ki", "Mi", "Gi", "Ti", 0}; static char *si_units[] = { "", "K", "M", "G", "T", 0}; static void value2human(int si, double bytes, double time, double* data, double* speed,char* metric) { int unit = 0; *data = bytes; if (si) { while (*data > 1000 && si_units[unit + 1]) { *data /= 1000; unit++; } *speed = *data / time; sprintf(metric, "%sB", si_units[unit]); } else { while (*data > 1024 && units[unit + 1]) { *data /= 1024; unit++; } *speed = *data / time; sprintf(metric, "%sB", units[unit]); } } #define MAX(x,y) ((x)>(y)?(x):(y)) int encrypt_data(struct session_op *sess, int fdc, int chunksize, int alignmask) { struct crypt_op cop; char *buffer, iv[32]; static int val = 23; struct timeval start, end; double total = 0; double secs, ddata, dspeed; char metric[16]; if (alignmask) { if (posix_memalign((void **)&buffer, MAX(alignmask + 1, sizeof(void*)), chunksize)) { printf("posix_memalign() failed! (mask %x, size: %d)\n", alignmask+1, chunksize); return 1; } } else { if (!(buffer = malloc(chunksize))) { perror("malloc()"); return 1; } } memset(iv, 0x23, 32); printf("\tEncrypting in chunks of %d bytes: ", chunksize); fflush(stdout); memset(buffer, val++, chunksize); must_finish = 0; alarm(5); gettimeofday(&start, NULL); do { memset(&cop, 0, sizeof(cop)); cop.ses = sess->ses; cop.len = chunksize; cop.iv = (unsigned char *)iv; cop.op = COP_ENCRYPT; cop.src = cop.dst = (unsigned char *)buffer; if (ioctl(fdc, CIOCCRYPT, &cop)) { perror("ioctl(CIOCCRYPT)"); return 1; } total+=chunksize; } while(must_finish==0); gettimeofday(&end, NULL); secs = udifftimeval(start, end)/ 1000000.0; value2human(si, total, secs, &ddata, &dspeed, metric); printf ("done. %.2f %s in %.2f secs: ", ddata, metric, secs); printf ("%.2f %s/sec\n", dspeed, metric); free(buffer); return 0; } int main(int argc, char** argv) { int fd, i, fdc = -1, alignmask = 0; struct session_op sess; #ifdef CIOCGSESSINFO struct session_info_op siop; #endif char keybuf[32]; signal(SIGALRM, alarm_handler); if (argc > 1) { if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) { printf("Usage: speed [--kib]\n"); exit(0); } if (strcmp(argv[1], "--kib") == 0) { si = 0; } } if ((fd = open("/dev/crypto", O_RDWR, 0)) < 0) { perror("open()"); return 1; } if (ioctl(fd, CRIOGET, &fdc)) { perror("ioctl(CRIOGET)"); return 1; } fprintf(stderr, "Testing NULL cipher: \n"); memset(&sess, 0, sizeof(sess)); sess.cipher = CRYPTO_NULL; sess.keylen = 0; sess.key = (unsigned char *)keybuf; if (ioctl(fdc, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop.ses = sess.ses; if (ioctl(fdc, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } alignmask = siop.alignmask; #endif for (i = 512; i <= (64 * 1024); i *= 2) { if (encrypt_data(&sess, fdc, i, alignmask)) break; } fprintf(stderr, "\nTesting AES-128-CBC cipher: \n"); memset(&sess, 0, sizeof(sess)); sess.cipher = CRYPTO_AES_CBC; sess.keylen = 16; memset(keybuf, 0x42, 16); sess.key = (unsigned char *)keybuf; if (ioctl(fdc, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } #ifdef CIOCGSESSINFO siop.ses = sess.ses; if (ioctl(fdc, CIOCGSESSINFO, &siop)) { perror("ioctl(CIOCGSESSINFO)"); return 1; } alignmask = siop.alignmask; #endif for (i = 512; i <= (64 * 1024); i *= 2) { if (encrypt_data(&sess, fdc, i, alignmask)) break; } close(fdc); close(fd); return 0; }