language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
C | aircrack-ng/lib/ce-wep/uniqueiv.c | /*
* IV uniqueness detection method.
*
* Copyright (C) 2004-2008 Stanislaw Pusep:
*
* 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
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
/*
* Each IV byte is stored in corresponding "level". We have 3 levels with
* IV[2] as root index (level 0), IV[1] and IV[2] as level 2 and level 1
* indices respectively. Space required to allocate all data is at maximum
* 2^24/8 (2 MB) and space required by filled index structures is 257 KB.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/ce-wep/uniqueiv.h"
/* allocate root structure */
unsigned char ** uniqueiv_init(void)
{
int i;
/* allocate root bucket (level 0) as vector of pointers */
unsigned char ** uiv_root
= (unsigned char **) malloc(256 * sizeof(unsigned char *));
if (uiv_root == NULL) return (NULL);
/* setup initial state as empty */
for (i = 0; i < 256; ++i) uiv_root[i] = NULL;
return (uiv_root);
}
/* update records with new IV */
int uniqueiv_mark(unsigned char ** uiv_root, unsigned char IV[3])
{
unsigned char ** uiv_lvl1;
unsigned char * uiv_lvl2;
short i;
if (uiv_root == NULL) return (0);
/* select bucket from level 1 */
uiv_lvl1 = (unsigned char **) uiv_root[IV[2]];
/* create if it doesn't exist */
if (uiv_lvl1 == NULL)
{
/* allocate level 2 bucket being a vector of bits */
uiv_lvl1 = (unsigned char **) malloc(256 * sizeof(unsigned char *));
if (uiv_lvl1 == NULL) return (1);
/* setup initial state as empty */
for (i = 0; i < 256; i++) uiv_lvl1[i] = NULL;
/* link to parent bucket */
uiv_root[IV[2]] = (unsigned char *) uiv_lvl1;
}
/* select bucket from level 2 */
uiv_lvl2 = (unsigned char *) uiv_lvl1[IV[1]];
/* create if it doesn't exist */
if (uiv_lvl2 == NULL)
{
/* allocate level 2 bucket as a vector of pointers */
uiv_lvl2 = (unsigned char *) malloc(32 * sizeof(unsigned char));
if (uiv_lvl2 == NULL) return (1);
/* setup initial state as empty */
for (i = 0; i < 32; i++) uiv_lvl2[i] = 0;
/* link to parent bucket */
uiv_lvl1[IV[1]] = uiv_lvl2;
}
/* place single bit into level 2 bucket */
uiv_lvl2[BITWISE_OFFT(IV[0])] |= BITWISE_MASK(IV[0]);
return (0);
}
/* check if already seen IV */
int uniqueiv_check(unsigned char ** uiv_root, unsigned char IV[3])
{
unsigned char ** uiv_lvl1;
unsigned char * uiv_lvl2;
if (uiv_root == NULL) return (IV_NOTHERE);
/* select bucket from level 1 */
uiv_lvl1 = (unsigned char **) uiv_root[IV[2]];
/* stop here if not even allocated */
if (uiv_lvl1 == NULL) return (IV_NOTHERE);
/* select bucket from level 2 */
uiv_lvl2 = (unsigned char *) uiv_lvl1[IV[1]];
/* stop here if not even allocated */
if (uiv_lvl2 == NULL) return (IV_NOTHERE);
/* check single bit from level 2 bucket */
if ((uiv_lvl2[BITWISE_OFFT(IV[0])] & BITWISE_MASK(IV[0])) == 0)
return (IV_NOTHERE);
else
return (IV_PRESENT);
}
/* unallocate everything */
void uniqueiv_wipe(unsigned char ** uiv_root)
{
int i, j;
unsigned char ** uiv_lvl1;
unsigned char * uiv_lvl2;
if (uiv_root == NULL) return;
/* recursively wipe out allocated buckets */
for (i = 0; i < 256; ++i)
{
uiv_lvl1 = (unsigned char **) uiv_root[i];
if (uiv_lvl1 != NULL)
{
for (j = 0; j < 256; ++j)
{
uiv_lvl2 = (unsigned char *) uiv_lvl1[j];
if (uiv_lvl2 != NULL)
{
free(uiv_lvl2);
uiv_lvl2 = NULL;
}
}
free(uiv_lvl1);
uiv_lvl1 = NULL;
}
}
free(uiv_root);
uiv_root = NULL;
return;
}
unsigned char * data_init(void)
{
// It could eat up to (256*256*256) * 3 bytes = 48Mb :/
unsigned char * IVs
= (unsigned char *) calloc(256 * 256 * 256 * 3, sizeof(unsigned char));
ALLEGE(IVs != NULL);
return (IVs);
}
/* Checking WEP packet:
* The 2 first bytes of 2 different data packets having the same IV (for the
* same AP)
* should be exactly the same due to the fact that unencrypted, they are always
* the same:
* AA AA
*/
int data_check(unsigned char * data_root,
unsigned char IV[3],
unsigned char data[2])
{
int IV_position, cloaking;
// Init vars
cloaking = NO_CLOAKING;
// Make sure it is allocated
if (data_root != NULL)
{
// Try to find IV
IV_position = (((IV[0] * 256) + IV[1]) * 256) + IV[2];
IV_position *= 3;
// Check if existing
if (*(data_root + IV_position) == 0)
{
// Not existing
*(data_root + IV_position) = 1;
// Add it
*(data_root + IV_position + 1) = data[0];
*(data_root + IV_position + 2) = data[1];
}
else
{
// Good, we found it, so check it now
if (*(data_root + IV_position + 1) != data[0]
|| *(data_root + IV_position + 2) != data[1])
{
cloaking = CLOAKING;
}
}
}
// else, cannot detect since it is not started
return (cloaking);
}
void data_wipe(unsigned char * data)
{
if (data) free(data);
} |
C | aircrack-ng/lib/ce-wpa/crypto_engine.c | /*
* Copyright (C) 2018-2022 Joseph Benden <[email protected]>
*
* 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
* is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
* NON-INFRINGEMENT. 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.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <err.h>
#include <limits.h>
#define _GNU_SOURCE
#include <string.h>
#include <stdint.h>
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/ce-wpa/simd-intrinsics.h"
#include "aircrack-ng/ce-wpa/wpapsk.h"
#include "aircrack-ng/cpu/trampoline.h"
#include "aircrack-ng/ce-wpa/crypto_engine.h"
// #define XDEBUG
EXPORT int ac_crypto_engine_supported_features(void)
{
#if defined(JOHN_AVX512F)
return SIMD_SUPPORTS_AVX512F;
#elif defined(JOHN_AVX2)
return SIMD_SUPPORTS_AVX2;
#elif defined(JOHN_AVX)
return SIMD_SUPPORTS_AVX;
#elif defined(JOHN_SSE2)
return SIMD_SUPPORTS_SSE2;
#elif defined(JOHN_NEON)
return SIMD_SUPPORTS_NEON;
#elif defined(JOHN_ASIMD)
return SIMD_SUPPORTS_ASIMD;
#elif defined(JOHN_POWER8)
return SIMD_SUPPORTS_POWER8;
#elif defined(JOHN_ALTIVEC)
return SIMD_SUPPORTS_ALTIVEC;
#else
return SIMD_SUPPORTS_NONE;
#endif
}
EXPORT int ac_crypto_engine_simd_width(void)
{
#ifdef SIMD_COEF_32
return SIMD_COEF_32;
#else
return 1;
#endif
}
EXPORT int ac_crypto_engine_init(ac_crypto_engine_t * engine)
{
assert(engine != NULL);
#ifdef XDEBUG
fprintf(stderr, "ac_crypto_engine_init(%p)\n", engine);
#endif
init_atoi();
engine->essid = mem_calloc_align(1, ESSID_LENGTH + 1, MEM_ALIGN_SIMD);
engine->essid_length = 0;
for (int i = 0; i < MAX_THREADS; ++i) engine->thread_data[i] = NULL;
return 0;
}
EXPORT void ac_crypto_engine_destroy(ac_crypto_engine_t * engine)
{
assert(engine != NULL);
#ifdef XDEBUG
fprintf(stderr, "ac_crypto_engine_destroy(%p)\n", engine);
#endif
MEM_FREE(engine->essid);
}
EXPORT void ac_crypto_engine_set_essid(ac_crypto_engine_t * engine,
const uint8_t * essid)
{
assert(engine != NULL);
#ifdef XDEBUG
fprintf(stderr, "ac_crypto_engine_set_essid(%p, %s)\n", engine, essid);
#endif
memccpy(engine->essid, essid, 0, ESSID_LENGTH);
engine->essid_length = (uint32_t) strlen((char *) essid);
}
EXPORT int ac_crypto_engine_thread_init(ac_crypto_engine_t * engine,
int threadid)
{
assert(engine != NULL);
#ifdef XDEBUG
fprintf(stderr, "ac_crypto_engine_thread_init(%p, %d)\n", engine, threadid);
#endif
// allocate per-thread data.
engine->thread_data[threadid] = mem_calloc_align(
1, sizeof(struct ac_crypto_engine_perthread), MEM_ALIGN_SIMD);
return 0;
}
EXPORT void ac_crypto_engine_thread_destroy(ac_crypto_engine_t * engine,
int threadid)
{
assert(engine != NULL);
#ifdef XDEBUG
fprintf(
stderr, "ac_crypto_engine_thread_destroy(%p, %d)\n", engine, threadid);
#endif
if (engine->thread_data[threadid] != NULL)
{
MEM_FREE(engine->thread_data[threadid]);
}
}
EXPORT uint8_t *
ac_crypto_engine_get_pmk(ac_crypto_engine_t * engine, int threadid, int index)
{
return (uint8_t *) engine->thread_data[threadid]->pmk
+ (sizeof(wpapsk_hash) * index);
}
EXPORT uint8_t *
ac_crypto_engine_get_ptk(ac_crypto_engine_t * engine, int threadid, int index)
{
return (uint8_t *) engine->thread_data[threadid]->ptk + (20 * index);
}
EXPORT void ac_crypto_engine_calc_pke(ac_crypto_engine_t * engine,
const uint8_t bssid[6],
const uint8_t stmac[6],
const uint8_t anonce[32],
const uint8_t snonce[32],
int threadid)
{
uint8_t * pke = engine->thread_data[threadid]->pke;
assert(pke != NULL); //-V547
/* pre-compute the key expansion buffer */
memcpy(pke, "Pairwise key expansion", 23);
if (memcmp(stmac, bssid, 6) < 0)
{
memcpy(pke + 23, stmac, 6);
memcpy(pke + 29, bssid, 6);
}
else
{
memcpy(pke + 23, bssid, 6);
memcpy(pke + 29, stmac, 6);
}
if (memcmp(snonce, anonce, 32) < 0)
{
memcpy(pke + 35, snonce, 32);
memcpy(pke + 67, anonce, 32);
}
else
{
memcpy(pke + 35, anonce, 32);
memcpy(pke + 67, snonce, 32);
}
}
/* derive the PMK from the passphrase and the essid */
EXPORT void ac_crypto_engine_calc_one_pmk(const uint8_t * key,
const uint8_t * essid_pre,
uint32_t essid_pre_len,
uint8_t pmk[static PMK_LEN])
{
if (KDF_PBKDF2_SHA1(key, essid_pre, essid_pre_len, 4096, pmk, PMK_LEN) != 0)
errx(1, "Failed to compute PBKDF2 HMAC-SHA1");
}
EXPORT void ac_crypto_engine_calc_pmk(
ac_crypto_engine_t * engine,
const wpapsk_password key[MAX_KEYS_PER_CRYPT_SUPPORTED],
const int nparallel,
const int threadid)
{
wpapsk_hash * pmk = engine->thread_data[threadid]->pmk;
// PMK calculation
#ifdef SIMD_CORE
if (nparallel >= 4)
{
init_wpapsk(engine, key, nparallel, threadid);
}
else
#endif
for (int j = 0; j < nparallel; ++j)
{
#ifdef XDEBUG
printf("%lu: Trying: %s\n", pthread_self(), (char *) key[j].v);
#endif
ac_crypto_engine_calc_one_pmk(key[j].v,
(uint8_t *) engine->essid,
engine->essid_length,
(uint8_t *) (&pmk[j]));
}
}
EXPORT void ac_crypto_engine_calc_ptk(ac_crypto_engine_t * engine,
const uint8_t keyver,
int vectorIdx,
int threadid)
{
uint8_t data[64 + 12];
uint8_t * ptk = engine->thread_data[threadid]->ptk;
wpapsk_hash * pmk = engine->thread_data[threadid]->pmk;
uint8_t * pke = &engine->thread_data[threadid]->pke[23];
memset(data, 0, sizeof(data));
memcpy(data, pke, ETH_ALEN);
memcpy(data + ETH_ALEN, pke + ETH_ALEN, ETH_ALEN);
memcpy(data + 2 * ETH_ALEN, pke + 35 - 23, 64); //-V512
if (keyver < 3)
{
SHA1_PRF((const uint8_t *) (&pmk[vectorIdx]),
32,
(const uint8_t *) "Pairwise key expansion",
data,
76,
&ptk[vectorIdx],
4 * DIGEST_SHA1_MAC_LEN);
}
else
{
Digest_SHA256_PRF_Bits((const uint8_t *) (&pmk[vectorIdx]),
32,
(const uint8_t *) "Pairwise key expansion",
data,
76,
ptk,
48 * CHAR_BIT);
}
}
EXPORT void ac_crypto_engine_calc_mic(ac_crypto_engine_t * engine,
const uint8_t eapol[256],
const uint32_t eapol_size,
uint8_t mic[MAX_KEYS_PER_CRYPT_SUPPORTED]
[20],
const uint8_t keyver,
const int vectorIdx,
const int threadid)
{
uint8_t * ptk = engine->thread_data[threadid]->ptk;
if (keyver == 1)
MAC_HMAC_MD5(16, &ptk[vectorIdx], eapol_size, eapol, mic[vectorIdx]);
else if (keyver == 2)
MAC_HMAC_SHA1(16, &ptk[vectorIdx], eapol_size, eapol, mic[vectorIdx]);
else if (keyver == 3)
{
const uint8_t * addr[4];
size_t len[4];
addr[0] = eapol;
len[0] = eapol_size;
MAC_OMAC1_AES_Vector(
16, ptk, 1, addr, len, (uint8_t *) &mic[vectorIdx]);
}
else
{
fprintf(stderr, "Unsupported key version %d encountered.\n", keyver);
if (keyver == 0) fprintf(stderr, "May be WPA3 - not yet supported.\n");
abort();
}
}
EXPORT int ac_crypto_engine_wpa_crack(
ac_crypto_engine_t * engine,
const wpapsk_password key[MAX_KEYS_PER_CRYPT_SUPPORTED],
const uint8_t eapol[256],
const uint32_t eapol_size,
uint8_t mic[MAX_KEYS_PER_CRYPT_SUPPORTED][20],
const uint8_t keyver,
const uint8_t cmpmic[20],
const int nparallel,
const int threadid)
{
ac_crypto_engine_calc_pmk(engine, key, nparallel, threadid);
for (int j = 0; j < nparallel; ++j)
{
/* compute the pairwise transient key and the frame MIC */
ac_crypto_engine_calc_ptk(engine, keyver, j, threadid);
ac_crypto_engine_calc_mic(
engine, eapol, eapol_size, mic, keyver, j, threadid);
/* did we successfully crack it? */
if (memcmp(mic[j], cmpmic, 16) == 0) //-V512
{
return j;
}
}
return -1;
}
EXPORT void ac_crypto_engine_set_pmkid_salt(ac_crypto_engine_t * engine,
const uint8_t bssid[6],
const uint8_t stmac[6],
int threadid)
{
uint8_t * pke = engine->thread_data[threadid]->pke;
assert(pke != NULL); //-V547
/* pre-compute the PMKID salt buffer */
memcpy(pke, "PMK Name", 8);
memcpy(pke + 8, bssid, 6);
memcpy(pke + 14, stmac, 6);
}
EXPORT int ac_crypto_engine_wpa_pmkid_crack(
ac_crypto_engine_t * engine,
const wpapsk_password key[MAX_KEYS_PER_CRYPT_SUPPORTED],
const uint8_t pmkid[32],
const int nparallel,
const int threadid)
{
ac_crypto_engine_calc_pmk(engine, key, nparallel, threadid);
uint8_t * pke = engine->thread_data[threadid]->pke;
wpapsk_hash * pmk = engine->thread_data[threadid]->pmk;
uint8_t l_pmkid[DIGEST_SHA1_MAC_LEN];
for (int j = 0; j < nparallel; ++j)
{
MAC_HMAC_SHA1(32, (const uint8_t *) &pmk[j], 20, pke, l_pmkid);
/* did we successfully crack it? */
if (memcmp(l_pmkid, pmkid, 16) == 0) //-V512
{
return j;
}
}
return -1;
} |
C | aircrack-ng/lib/ce-wpa/memory.c | /*
* Based on John the Ripper and modified to integrate with aircrack
*
* John the Ripper copyright and license.
*
* John the Ripper password cracker,
* Copyright (c) 1996-2013 by Solar Designer.
*
* 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.
*
* As a special exception to the GNU General Public License terms,
* permission is hereby granted to link the code of this program, with or
* without modification, with any version of the OpenSSL library and/or any
* version of unRAR, and to distribute such linked combinations. You must
* obey the GNU GPL in all respects for all of the code used other than
* OpenSSL and unRAR. If you modify this program, you may extend this
* exception to your version of the program, but you are not obligated to
* do so. (In other words, you may release your derived work under pure
* GNU GPL version 2 or later as published by the FSF.)
*
* (This exception from the GNU GPL is not required for the core tree of
* John the Ripper, but arguably it is required for -jumbo.)
*
* Relaxed terms for certain components.
*
* In addition or alternatively to the license above, many components are
* available to you under more relaxed terms (most commonly under cut-down
* BSD license) as specified in the corresponding source files.
*
* For more information on John the Ripper licensing please visit:
*
* http://www.openwall.com/john/doc/LICENSE.shtml
*
* This file is part of John the Ripper password cracker,
* Copyright (c) 1996-98,2010,2012 by Solar Designer
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* There's ABSOLUTELY NO WARRANTY, express or implied.
*/
#define _POSIX_C_SOURCE 200112L
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <ctype.h> /* for isprint() */
#if HAVE_MEMALIGN && HAVE_MALLOC_H
#include <malloc.h>
#endif
#include "aircrack-ng/ce-wpa/arch.h"
#include "aircrack-ng/ce-wpa/misc.h"
#include "aircrack-ng/ce-wpa/memory.h"
#include "aircrack-ng/ce-wpa/jcommon.h"
#include "aircrack-ng/ce-wpa/johnswap.h"
unsigned int mem_saving_level = 0;
// Add 'cleanup' methods for the mem_alloc_tiny. VERY little cost, but
// allows us to check for mem leaks easier.
struct rm_list
{
void * mem;
struct rm_list * next;
};
static struct rm_list * mem_alloc_tiny_memory;
static void add_memory_link(void * v)
{
struct rm_list * p = (struct rm_list *) mem_alloc(sizeof(struct rm_list));
if (p)
{
p->next = mem_alloc_tiny_memory;
p->mem = v;
mem_alloc_tiny_memory = p;
}
}
// call at program exit.
void cleanup_tiny_memory(void)
{
struct rm_list *p = mem_alloc_tiny_memory, *p2;
for (;;)
{
if (!p) return;
free(p->mem);
p2 = p->next;
free(p);
p = p2;
}
}
void * mem_alloc_func(size_t size)
{
void * res;
if (!size) return NULL;
res = malloc(size);
if (!res)
{
fprintf(stderr,
"mem_alloc(): %s trying to allocate " Zu " bytes\n",
strerror(ENOMEM),
size);
perror("mem_alloc");
}
return res;
}
void * mem_calloc_func(size_t count, size_t size)
{
void * res;
if (!count || !size) return NULL;
res = calloc(count, size);
if (!res)
{
fprintf(stderr,
"mem_calloc(): %s trying to allocate " Zu " bytes\n",
strerror(ENOMEM),
count * size);
perror("mem_calloc");
}
return res;
}
/*
* if -DDEBUG we turn mem_alloc_tiny() to essentially be just a malloc()
* with additional alignment. The reason for this is it's way easier to
* trace bugs that way.
* Also, with -DDEBUG we always return exactly the requested
* alignment, in order to trigger bugs!
*/
#ifdef DEBUG
#undef MEM_ALLOC_SIZE
#define MEM_ALLOC_SIZE 0
#endif
void * mem_alloc_tiny_func(size_t size, size_t align)
{
static char * buffer = NULL;
static size_t bufree = 0;
size_t mask;
char * p;
#ifdef DEBUG
/*
* We may be called with size zero, for example from ldr_load_pw_line()
* that calls mem_alloc_copy() with format->params.salt_size as size.
* This causes problems with -DDEBUG without this fix because we never
* get out of the while loop when MEM_ALLOC_SIZE is zero too. The
* previous fix for this was returning NULL but that lead to other
* problems that I did not bother digging into. This fix should be
* 100% safe.
*/
if (size == 0) size = 1;
#endif
#if ARCH_ALLOWS_UNALIGNED
if (mem_saving_level > 2 && align < MEM_ALIGN_SIMD) align = MEM_ALIGN_NONE;
#endif
mask = align - 1;
do
{
if (buffer)
{
size_t need = size + mask - (((size_t) buffer + mask) & mask);
if (bufree >= need)
{
p = buffer;
p += mask;
p -= (size_t) p & mask;
bufree -= need;
buffer = p + size;
#if defined(DEBUG)
/* Ensure alignment is no better than requested */
if (((size_t) p & ((mask << 1) + 1)) == 0) p += align;
#endif
return p;
}
}
if (size + mask > MEM_ALLOC_SIZE || bufree > MEM_ALLOC_MAX_WASTE) break;
buffer = (char *) mem_alloc(MEM_ALLOC_SIZE);
add_memory_link((void *) buffer);
bufree = MEM_ALLOC_SIZE;
} while (1);
p = (char *) mem_alloc(size + mask);
if (p == NULL) abort();
add_memory_link((void *) p);
p += mask;
p -= (size_t) p & mask;
#if defined(DEBUG)
/* Ensure alignment is no better than requested */
if (((size_t) p & ((mask << 1) + 1)) == 0) p += align;
#endif
return p;
}
void * mem_calloc_tiny_func(size_t size, size_t align)
{
char * cp = (char *) mem_alloc_tiny(size, align);
memset(cp, 0, size);
return cp;
}
void * mem_alloc_copy_func(void * src, size_t size, size_t align)
{
return memcpy(mem_alloc_tiny(size, align), src, size);
}
void * mem_alloc_align_func(size_t size, size_t align)
{
void * ptr = NULL;
#if HAVE_POSIX_MEMALIGN
if (posix_memalign(&ptr, align, size)) pexit("posix_memalign");
#elif HAVE_ALIGNED_ALLOC
/* According to the Linux man page, "size should be a multiple of
alignment", whatever they mean with "should"... This does not
make any sense whatsoever but we round it up to comply. */
size = ((size + (align - 1)) / align) * align;
if (!(ptr = aligned_alloc(align, size))) pexit("aligned_alloc");
#elif HAVE_MEMALIGN
/* Let's just pray this implementation can actually free it */
#if defined(__sparc__) || defined(__sparc) || defined(sparc) \
|| defined(__sparcv9)
if (!(ptr = memalign(align, size)))
#else
if (!(ptr = memalign(&ptr, align, size)))
#endif
perror("memalign");
#elif HAVE___MINGW_ALIGNED_MALLOC
if (!(ptr = __mingw_aligned_malloc(size, align)))
perror("__mingw_aligned_malloc");
#elif HAVE__ALIGNED_MALLOC
if (!(ptr = _aligned_malloc(size, align))) perror("aligned_malloc");
#elif AC_BUILT
#error No suitable aligned alloc found, please report to john-dev mailing list (state your OS details).
/* we need an aligned alloc function for legacy builds */
#elif _ISOC11_SOURCE
size = ((size + (align - 1)) / align) * align;
if (!(ptr = aligned_alloc(align, size))) perror("aligned_alloc");
#else
if (posix_memalign(&ptr, align, size)) perror("posix_memalign");
#endif
return ptr;
}
void * mem_calloc_align_func(size_t count, size_t size, size_t align)
{
void * ptr = mem_alloc_align_func(size * count, align);
memset(ptr, 0, size * count);
return ptr;
}
char * str_alloc_copy_func(char * src)
{
size_t size;
if (!src) return "";
if (!*src) return "";
size = strlen(src) + 1;
return (char *) memcpy(mem_alloc_tiny(size, MEM_ALIGN_NONE), src, size);
}
void dump_text(void * in, int len)
{
unsigned char * p = (unsigned char *) in;
while (len--)
{
fputc(isprint(*p) ? *p : '.', stdout);
p++;
}
fputc('\n', stdout);
}
void dump_stuff_noeol(void * x, unsigned int size)
{
unsigned int i;
for (i = 0; i < size; i++)
{
printf("%.2x", ((unsigned char *) x)[i]);
if ((i % 4) == 3) printf(" ");
}
}
void dump_stuff(void * x, unsigned int size)
{
dump_stuff_noeol(x, size);
printf("\n");
}
void dump_stuff_msg(const void * msg, void * x, unsigned int size)
{
printf("%s : ", (char *) msg);
dump_stuff(x, size);
}
void dump_stuff_msg_sepline(const void * msg, void * x, unsigned int size)
{
printf("%s :\n", (char *) msg);
dump_stuff(x, size);
}
void dump_stuff_be_noeol(void * x, unsigned int size)
{
unsigned int i;
for (i = 0; i < size; i++)
{
printf("%.2x", ((unsigned char *) x)[i ^ 3]);
if ((i % 4) == 3) printf(" ");
}
}
void dump_stuff_be(void * x, unsigned int size)
{
dump_stuff_be_noeol(x, size);
printf("\n");
}
void dump_stuff_be_msg(const void * msg, void * x, unsigned int size)
{
printf("%s : ", (char *) msg);
dump_stuff_be(x, size);
}
void dump_stuff_be_msg_sepline(const void * msg, void * x, unsigned int size)
{
printf("%s :\n", (char *) msg);
dump_stuff_be(x, size);
}
void alter_endianity(void * _x, unsigned int size)
{
ARCH_WORD_32 * x = (ARCH_WORD_32 *) _x;
// size is in octets
size >>= 2;
#if !ARCH_ALLOWS_UNALIGNED
if (is_aligned(x, sizeof(ARCH_WORD_32)))
{
#endif
while (size--)
{
*x = JOHNSWAP(*x);
x++;
}
#if !ARCH_ALLOWS_UNALIGNED
}
else
{
unsigned char *cpX, c;
cpX = (unsigned char *) x;
while (size--)
{
c = *cpX;
*cpX = cpX[3];
cpX[3] = c;
c = cpX[1];
cpX[1] = cpX[2];
cpX[2] = c;
cpX += 4;
}
}
#endif
}
#if defined(SIMD_COEF_32) || defined(NT_X86_64) || defined(SIMD_PARA_MD5) \
|| defined(SIMD_PARA_MD4) || defined(SIMD_PARA_SHA1)
#ifndef SIMD_COEF_32
#define SIMD_COEF_32 4
#endif
#ifndef SIMD_COEF_64
#define SIMD_COEF_64 2
#endif
#ifndef SIMD_COEF_32
#define SIMD_COEF_32 4
#endif
// These work for standard SIMD_COEF_32 buffers, AND for SSEi MMX_PARA multiple
// SIMD_COEF_32 blocks, where index will be mod(X * SIMD_COEF_32) and not simply
// mod(SIMD_COEF_32)
#define SHAGETPOS(i, index) \
((index & (SIMD_COEF_32 - 1)) * 4 \
+ ((i) & (0xffffffff - 3)) * SIMD_COEF_32 \
+ (3 - ((i) &3)) \
+ (unsigned int) index / SIMD_COEF_32 * SHA_BUF_SIZ * 4 \
* SIMD_COEF_32) // for endianity conversion
#define SHAGETOUTPOS(i, index) \
((index & (SIMD_COEF_32 - 1)) * 4 \
+ ((i) & (0xffffffff - 3)) * SIMD_COEF_32 \
+ (3 - ((i) &3)) \
+ (unsigned int) index / SIMD_COEF_32 * 20 \
* SIMD_COEF_32) // for endianity conversion
// for MD4/MD5 or any 64 byte LE SSE interleaved hash
#define GETPOS(i, index) \
((index & (SIMD_COEF_32 - 1)) * 4 \
+ ((i) & (0xffffffff - 3)) * SIMD_COEF_32 \
+ ((i) &3) \
+ (unsigned int) index / SIMD_COEF_32 * 64 * SIMD_COEF_32)
#define GETOUTPOS(i, index) \
((index & (SIMD_COEF_32 - 1)) * 4 \
+ ((i) & (0xffffffff - 3)) * SIMD_COEF_32 \
+ ((i) &3) \
+ (unsigned int) index / SIMD_COEF_32 * 16 * SIMD_COEF_32)
// for SHA384/SHA512 128 byte BE interleaved hash (arrays of 16 8 byte ints)
#define SHA64GETPOS(i, index) \
((index & (SIMD_COEF_64 - 1)) * 8 \
+ ((i) & (0xffffffff - 7)) * SIMD_COEF_64 \
+ (7 - ((i) &7)) \
+ (unsigned int) index / SIMD_COEF_64 * SHA_BUF_SIZ * 8 * SIMD_COEF_64)
#define SHA64GETOUTPOS(i, index) \
((index & (SIMD_COEF_64 - 1)) * 8 \
+ ((i) & (0xffffffff - 7)) * SIMD_COEF_64 \
+ (7 - ((i) &7)) \
+ (unsigned int) index / SIMD_COEF_64 * 64 * SIMD_COEF_64)
// for SHA384/SHA512 128 byte FLAT interleaved hash (arrays of 16 8 byte ints),
// but we do not BE interleave.
#define SHA64GETPOSne(i, index) \
((index & (SIMD_COEF_64 - 1)) * 8 \
+ ((i) & (0xffffffff - 7)) * SIMD_COEF_64 \
+ ((i) &7) \
+ (unsigned int) index / SIMD_COEF_64 * SHA_BUF_SIZ * 8 * SIMD_COEF_64)
void dump_stuff_mmx_noeol(void * buf, unsigned int size, unsigned int index)
{
unsigned int i;
for (i = 0; i < size; i++)
{
printf("%.2x", ((unsigned char *) buf)[GETPOS(i, index)]);
if ((i % 4) == 3) printf(" ");
}
}
void dump_stuff_mmx(void * buf, unsigned int size, unsigned int index)
{
dump_stuff_mmx_noeol(buf, size, index);
printf("\n");
}
void dump_stuff_mmx_msg(const void * msg,
void * buf,
unsigned int size,
unsigned int index)
{
printf("%s : ", (char *) msg);
dump_stuff_mmx(buf, size, index);
}
void dump_stuff_mmx_msg_sepline(const void * msg,
void * buf,
unsigned int size,
unsigned int index)
{
printf("%s :\n", (char *) msg);
dump_stuff_mmx(buf, size, index);
}
void dump_out_mmx_noeol(void * buf, unsigned int size, unsigned int index)
{
unsigned int i;
for (i = 0; i < size; i++)
{
printf("%.2x", ((unsigned char *) buf)[GETOUTPOS(i, index)]);
if ((i % 4) == 3) printf(" ");
}
}
void dump_out_mmx(void * buf, unsigned int size, unsigned int index)
{
dump_out_mmx_noeol(buf, size, index);
printf("\n");
}
void dump_out_mmx_msg(const void * msg,
void * buf,
unsigned int size,
unsigned int index)
{
printf("%s : ", (char *) msg);
dump_out_mmx(buf, size, index);
}
void dump_out_mmx_msg_sepline(const void * msg,
void * buf,
unsigned int size,
unsigned int index)
{
printf("%s :\n", (char *) msg);
dump_out_mmx(buf, size, index);
}
#if defined(SIMD_PARA_MD5)
#define GETPOSMPARA(i, index) \
((index & (SIMD_COEF_32 - 1)) * 4 \
+ (((i) & (0xffffffff - 3)) % 64) * SIMD_COEF_32 \
+ (i / 64) * SIMD_COEF_32 * SIMD_PARA_MD5 * 64 \
+ ((i) &3) \
+ (unsigned int) index / SIMD_COEF_32 * 64 * SIMD_COEF_32)
// multiple para blocks
void dump_stuff_mpara_mmx_noeol(void * buf,
unsigned int size,
unsigned int index)
{
unsigned int i;
for (i = 0; i < size; i++)
{
printf("%.2x", ((unsigned char *) buf)[GETPOSMPARA(i, index)]);
if ((i % 4) == 3) printf(" ");
}
}
void dump_stuff_mpara_mmx(void * buf, unsigned int size, unsigned int index)
{
dump_stuff_mpara_mmx_noeol(buf, size, index);
printf("\n");
}
// obuf has to be at lease size long. This function will unwind the SSE-para
// buffers into a flat.
void getbuf_stuff_mpara_mmx(unsigned char * oBuf,
void * buf,
unsigned int size,
unsigned int index)
{
unsigned int i;
for (i = 0; i < size; i++)
*oBuf++ = ((unsigned char *) buf)[GETPOSMPARA(i, index)];
}
void dump_stuff_mpara_mmx_msg(const void * msg,
void * buf,
unsigned int size,
unsigned int index)
{
printf("%s : ", (char *) msg);
dump_stuff_mpara_mmx(buf, size, index);
}
void dump_stuff_mpara_mmx_msg_sepline(const void * msg,
void * buf,
unsigned int size,
unsigned int index)
{
printf("%s :\n", (char *) msg);
dump_stuff_mpara_mmx(buf, size, index);
}
#endif
void dump_stuff_shammx(void * buf, unsigned int size, unsigned int index)
{
unsigned int i;
for (i = 0; i < size; i++)
{
printf("%.2x", ((unsigned char *) buf)[SHAGETPOS(i, index)]);
if ((i % 4) == 3) printf(" ");
}
printf("\n");
}
void dump_stuff_shammx_msg(const void * msg,
void * buf,
unsigned int size,
unsigned int index)
{
printf("%s : ", (char *) msg);
dump_stuff_shammx(buf, size, index);
}
void dump_out_shammx(void * buf, unsigned int size, unsigned int index)
{
unsigned int i;
for (i = 0; i < size; i++)
{
printf("%.2x", ((unsigned char *) buf)[SHAGETOUTPOS(i, index)]);
if ((i % 4) == 3) printf(" ");
}
printf("\n");
}
void dump_out_shammx_msg(const void * msg,
void * buf,
unsigned int size,
unsigned int index)
{
printf("%s : ", (char *) msg);
dump_out_shammx(buf, size, index);
}
void dump_stuff_shammx64(void * buf, unsigned int size, unsigned int index)
{
unsigned int i;
for (i = 0; i < size; i++)
{
printf("%.2x", ((unsigned char *) buf)[SHA64GETPOS(i, index)]);
if ((i % 4) == 3) printf(" ");
}
printf("\n");
}
void dump_stuff_shammx64_msg(const void * msg,
void * buf,
unsigned int size,
unsigned int index)
{
printf("%s : ", (char *) msg);
dump_stuff_shammx64(buf, size, index);
}
void dump_stuff_mmx64(void * buf, unsigned int size, unsigned int index)
{
unsigned int i;
for (i = 0; i < size; i++)
{
printf("%.2x", ((unsigned char *) buf)[SHA64GETPOSne(i, index)]);
if ((i % 4) == 3) printf(" ");
}
printf("\n");
}
void dump_stuff_mmx64_msg(const void * msg,
void * buf,
unsigned int size,
unsigned int index)
{
printf("%s : ", (char *) msg);
dump_stuff_mmx64(buf, size, index);
}
void dump_out_shammx64(void * buf, unsigned int size, unsigned int index)
{
unsigned int i;
for (i = 0; i < size; i++)
{
printf("%.2x", ((unsigned char *) buf)[SHA64GETOUTPOS(i, index)]);
if ((i % 4) == 3) printf(" ");
}
printf("\n");
}
void dump_out_shammx64_msg(const void * msg,
void * buf,
unsigned int size,
unsigned int index)
{
printf("%s : ", (char *) msg);
dump_out_shammx64(buf, size, index);
}
#endif
void alter_endianity_w(void * _x, unsigned int count)
{
int i = -1;
ARCH_WORD_32 * x = (ARCH_WORD_32 *) _x;
#if ARCH_ALLOWS_UNALIGNED
while (++i < (int) count)
{
x[i] = JOHNSWAP(x[i]);
}
#else
unsigned char *cpX, c;
if (is_aligned(x, sizeof(ARCH_WORD_32)))
{
// we are in alignment.
while (++i < (int) count)
{
x[i] = JOHNSWAP(x[i]);
}
return;
}
// non-aligned data :(
cpX = (unsigned char *) x;
while (++i < (int) count)
{
c = *cpX;
*cpX = cpX[3];
cpX[3] = c;
c = cpX[1];
cpX[1] = cpX[2];
cpX[2] = c;
cpX += 4;
}
#endif
}
void alter_endianity_w64(void * _x, unsigned int count)
{
int i = -1;
ARCH_WORD_64 * x = (ARCH_WORD_64 *) _x;
#if ARCH_ALLOWS_UNALIGNED
while (++i < (int) count)
{
x[i] = JOHNSWAP64(x[i]);
}
#else
unsigned char *cpX, c;
if (is_aligned(x, sizeof(ARCH_WORD_64)))
{
// we are in alignment.
while (++i < (int) count)
{
x[i] = JOHNSWAP64(x[i]);
}
return;
}
// non-aligned data :(
cpX = (unsigned char *) x;
while (++i < (int) count)
{
c = *cpX;
*cpX = cpX[7];
cpX[7] = c;
c = cpX[1];
cpX[1] = cpX[6];
cpX[6] = c;
c = cpX[2];
cpX[2] = cpX[5];
cpX[5] = c;
c = cpX[3];
cpX[3] = cpX[4];
cpX[4] = c;
cpX += 8;
}
#endif
} |
C | aircrack-ng/lib/ce-wpa/simd-intrinsics.c | /*
* Based on John the Ripper and modified to integrate with aircrack
*
* John the Ripper copyright and license.
*
* John the Ripper password cracker,
* Copyright (c) 1996-2013 by Solar Designer.
*
* 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.
*
* As a special exception to the GNU General Public License terms,
* permission is hereby granted to link the code of this program, with or
* without modification, with any version of the OpenSSL library and/or any
* version of unRAR, and to distribute such linked combinations. You must
* obey the GNU GPL in all respects for all of the code used other than
* OpenSSL and unRAR. If you modify this program, you may extend this
* exception to your version of the program, but you are not obligated to
* do so. (In other words, you may release your derived work under pure
* GNU GPL version 2 or later as published by the FSF.)
*
* (This exception from the GNU GPL is not required for the core tree of
* John the Ripper, but arguably it is required for -jumbo.)
*
* Relaxed terms for certain components.
*
* In addition or alternatively to the license above, many components are
* available to you under more relaxed terms (most commonly under cut-down
* BSD license) as specified in the corresponding source files.
*
* For more information on John the Ripper licensing please visit:
*
* http://www.openwall.com/john/doc/LICENSE.shtml
*
* This software is
* Copyright (c) 2010 bartavelle, <bartavelle at bandecon.com>,
* Copyright (c) 2012 Solar Designer,
* Copyright (c) 2011-2015 JimF,
* Copyright (c) 2011-2015 magnum,
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* SHA-2 Copyright 2013, epixoip. Redistribution and use in source and binary
* forms, with or without modification, are permitted provided that
* redistribution of source retains the above copyright.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <assert.h>
#include <string.h>
#include <stdint.h>
#include "aircrack-ng/ce-wpa/arch.h"
#include "aircrack-ng/ce-wpa/pseudo_intrinsics.h"
#include "aircrack-ng/ce-wpa/memory.h"
#include "aircrack-ng/ce-wpa/johnswap.h"
#include "aircrack-ng/ce-wpa/simd-intrinsics-load-flags.h"
#include "aircrack-ng/ce-wpa/aligned.h"
#include "aircrack-ng/ce-wpa/misc.h"
/* Shorter names for use in index calculations */
#define VS32 SIMD_COEF_32
#define VS64 SIMD_COEF_64
#if SIMD_PARA_MD5
#define MD5_SSE_NUM_KEYS (SIMD_COEF_32 * SIMD_PARA_MD5)
#define MD5_PARA_DO(x) for ((x) = 0; (x) < SIMD_PARA_MD5; (x)++)
#define MD5_F(x, y, z) tmp[i] = vcmov((y[i]), (z[i]), (x[i]));
#define MD5_G(x, y, z) tmp[i] = vcmov((x[i]), (y[i]), (z[i]));
#if __AVX512F__
#define MD5_H(x, y, z) tmp[i] = vternarylogic(x[i], y[i], z[i], 0x96);
#define MD5_H2(x, y, z) tmp[i] = vternarylogic(x[i], y[i], z[i], 0x96);
#elif 1
#define MD5_H(x, y, z) \
tmp2[i] = vxor((x[i]), (y[i])); \
tmp[i] = vxor(tmp2[i], (z[i]));
#define MD5_H2(x, y, z) tmp[i] = vxor((x[i]), tmp2[i]);
#else
#define MD5_H(x, y, z) \
tmp[i] = vxor((x[i]), (y[i])); \
tmp[i] = vxor((tmp[i]), (z[i]));
#define MD5_H2(x, y, z) \
tmp[i] = vxor((y[i]), (z[i])); \
tmp[i] = vxor((tmp[i]), (x[i]));
#endif
#if __AVX512F__
#define MD5_I(x, y, z) tmp[i] = vternarylogic(x[i], y[i], z[i], 0x39);
#elif __ARM_NEON__
#define MD5_I(x, y, z) \
tmp[i] = vorn((x[i]), (z[i])); \
tmp[i] = vxor((tmp[i]), (y[i]));
#elif !VCMOV_EMULATED
#define MD5_I(x, y, z) \
tmp[i] = vcmov((x[i]), mask, (z[i])); \
tmp[i] = vxor((tmp[i]), (y[i]));
#else
#define MD5_I(x, y, z) \
tmp[i] = vandnot((z[i]), mask); \
tmp[i] = vor((tmp[i]), (x[i])); \
tmp[i] = vxor((tmp[i]), (y[i]));
#endif
#define MD5_STEP(f, a, b, c, d, x, t, s) \
MD5_PARA_DO(i) \
{ \
a[i] = vadd_epi32(a[i], vset1_epi32(t)); \
a[i] = vadd_epi32(a[i], data[i * 16 + x]); \
f((b), (c), (d)) a[i] = vadd_epi32(a[i], tmp[i]); \
a[i] = vroti_epi32(a[i], (s)); \
a[i] = vadd_epi32(a[i], b[i]); \
}
#define MD5_STEP_r16(f, a, b, c, d, x, t, s) \
MD5_PARA_DO(i) \
{ \
a[i] = vadd_epi32(a[i], vset1_epi32(t)); \
a[i] = vadd_epi32(a[i], data[i * 16 + x]); \
f((b), (c), (d)) a[i] = vadd_epi32(a[i], tmp[i]); \
a[i] = vroti16_epi32(a[i], (s)); \
a[i] = vadd_epi32(a[i], b[i]); \
}
#define INIT_A 0x67452301
void md5_reverse(uint32_t * hash) { hash[0] -= INIT_A; }
void md5_unreverse(uint32_t * hash) { hash[0] += INIT_A; }
#undef INIT_A
void SIMDmd5body(vtype * _data,
unsigned int * out,
ARCH_WORD_32 * reload_state,
unsigned SSEi_flags)
{
vtype w[16 * SIMD_PARA_MD5];
vtype a[SIMD_PARA_MD5];
vtype b[SIMD_PARA_MD5];
vtype c[SIMD_PARA_MD5];
vtype d[SIMD_PARA_MD5];
vtype tmp[SIMD_PARA_MD5];
#if !__AVX512F__
vtype tmp2[SIMD_PARA_MD5];
#endif
unsigned int i;
vtype * data;
#if !__AVX512F__ && !__ARM_NEON__
vtype mask;
mask = vset1_epi32(0xffffffff);
#endif
if (SSEi_flags & SSEi_FLAT_IN)
{
// Move _data to __data, mixing it SIMD_COEF_32 wise.
#if __SSE4_1__ || __MIC__
unsigned k;
vtype * W = w;
ARCH_WORD_32 * saved_key = (ARCH_WORD_32 *) _data;
MD5_PARA_DO(k)
{
if (SSEi_flags & SSEi_4BUF_INPUT)
{
for (i = 0; i < 16; ++i)
{
GATHER_4x(W[i], saved_key, i);
}
saved_key += (VS32 << 6);
}
else if (SSEi_flags & SSEi_2BUF_INPUT)
{
for (i = 0; i < 16; ++i)
{
GATHER_2x(W[i], saved_key, i);
}
saved_key += (VS32 << 5);
}
else
{
for (i = 0; i < 16; ++i)
{
GATHER(W[i], saved_key, i);
}
saved_key += (VS32 << 4);
}
W += 16;
}
#else
unsigned j, k;
ARCH_WORD_32 * p = (ARCH_WORD_32 *) w;
vtype * W = w;
ARCH_WORD_32 * saved_key = (ARCH_WORD_32 *) _data;
MD5_PARA_DO(k)
{
if (SSEi_flags & SSEi_4BUF_INPUT)
{
for (j = 0; j < 16; j++)
for (i = 0; i < VS32; i++) *p++ = saved_key[(i << 6) + j];
saved_key += (VS32 << 6);
}
else if (SSEi_flags & SSEi_2BUF_INPUT)
{
for (j = 0; j < 16; j++)
for (i = 0; i < VS32; i++) *p++ = saved_key[(i << 5) + j];
saved_key += (VS32 << 5);
}
else
{
for (j = 0; j < 16; j++)
for (i = 0; i < VS32; i++) *p++ = saved_key[(i << 4) + j];
saved_key += (VS32 << 4);
}
W += 16;
}
#endif
// now set our data pointer to point to this 'mixed' data.
data = w;
}
else
data = _data;
if ((SSEi_flags & SSEi_RELOAD) == 0)
{
MD5_PARA_DO(i)
{
a[i] = vset1_epi32(0x67452301);
b[i] = vset1_epi32(0xefcdab89);
c[i] = vset1_epi32(0x98badcfe);
d[i] = vset1_epi32(0x10325476);
}
}
else
{
if ((SSEi_flags & SSEi_RELOAD_INP_FMT) == SSEi_RELOAD_INP_FMT)
{
MD5_PARA_DO(i)
{
a[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 0 * VS32]);
b[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 1 * VS32]);
c[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 2 * VS32]);
d[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 3 * VS32]);
}
}
else
{
MD5_PARA_DO(i)
{
a[i] = vload((vtype *) &reload_state[i * 4 * VS32 + 0 * VS32]);
b[i] = vload((vtype *) &reload_state[i * 4 * VS32 + 1 * VS32]);
c[i] = vload((vtype *) &reload_state[i * 4 * VS32 + 2 * VS32]);
d[i] = vload((vtype *) &reload_state[i * 4 * VS32 + 3 * VS32]);
}
}
}
/* Round 1 */
MD5_STEP(MD5_F, a, b, c, d, 0, 0xd76aa478, 7)
MD5_STEP(MD5_F, d, a, b, c, 1, 0xe8c7b756, 12)
MD5_STEP(MD5_F, c, d, a, b, 2, 0x242070db, 17)
MD5_STEP(MD5_F, b, c, d, a, 3, 0xc1bdceee, 22)
MD5_STEP(MD5_F, a, b, c, d, 4, 0xf57c0faf, 7)
MD5_STEP(MD5_F, d, a, b, c, 5, 0x4787c62a, 12)
MD5_STEP(MD5_F, c, d, a, b, 6, 0xa8304613, 17)
MD5_STEP(MD5_F, b, c, d, a, 7, 0xfd469501, 22)
MD5_STEP(MD5_F, a, b, c, d, 8, 0x698098d8, 7)
MD5_STEP(MD5_F, d, a, b, c, 9, 0x8b44f7af, 12)
MD5_STEP(MD5_F, c, d, a, b, 10, 0xffff5bb1, 17)
MD5_STEP(MD5_F, b, c, d, a, 11, 0x895cd7be, 22)
MD5_STEP(MD5_F, a, b, c, d, 12, 0x6b901122, 7)
MD5_STEP(MD5_F, d, a, b, c, 13, 0xfd987193, 12)
MD5_STEP(MD5_F, c, d, a, b, 14, 0xa679438e, 17)
MD5_STEP(MD5_F, b, c, d, a, 15, 0x49b40821, 22)
/* Round 2 */
MD5_STEP(MD5_G, a, b, c, d, 1, 0xf61e2562, 5)
MD5_STEP(MD5_G, d, a, b, c, 6, 0xc040b340, 9)
MD5_STEP(MD5_G, c, d, a, b, 11, 0x265e5a51, 14)
MD5_STEP(MD5_G, b, c, d, a, 0, 0xe9b6c7aa, 20)
MD5_STEP(MD5_G, a, b, c, d, 5, 0xd62f105d, 5)
MD5_STEP(MD5_G, d, a, b, c, 10, 0x02441453, 9)
MD5_STEP(MD5_G, c, d, a, b, 15, 0xd8a1e681, 14)
MD5_STEP(MD5_G, b, c, d, a, 4, 0xe7d3fbc8, 20)
MD5_STEP(MD5_G, a, b, c, d, 9, 0x21e1cde6, 5)
MD5_STEP(MD5_G, d, a, b, c, 14, 0xc33707d6, 9)
MD5_STEP(MD5_G, c, d, a, b, 3, 0xf4d50d87, 14)
MD5_STEP(MD5_G, b, c, d, a, 8, 0x455a14ed, 20)
MD5_STEP(MD5_G, a, b, c, d, 13, 0xa9e3e905, 5)
MD5_STEP(MD5_G, d, a, b, c, 2, 0xfcefa3f8, 9)
MD5_STEP(MD5_G, c, d, a, b, 7, 0x676f02d9, 14)
MD5_STEP(MD5_G, b, c, d, a, 12, 0x8d2a4c8a, 20)
/* Round 3 */
MD5_STEP(MD5_H, a, b, c, d, 5, 0xfffa3942, 4)
MD5_STEP(MD5_H2, d, a, b, c, 8, 0x8771f681, 11)
MD5_STEP_r16(MD5_H, c, d, a, b, 11, 0x6d9d6122, 16) MD5_STEP(
MD5_H2, b, c, d, a, 14, 0xfde5380c, 23)
MD5_STEP(MD5_H, a, b, c, d, 1, 0xa4beea44, 4) MD5_STEP(
MD5_H2, d, a, b, c, 4, 0x4bdecfa9, 11)
MD5_STEP_r16(MD5_H, c, d, a, b, 7, 0xf6bb4b60, 16) MD5_STEP(
MD5_H2, b, c, d, a, 10, 0xbebfbc70, 23)
MD5_STEP(MD5_H, a, b, c, d, 13, 0x289b7ec6, 4) MD5_STEP(
MD5_H2, d, a, b, c, 0, 0xeaa127fa, 11)
MD5_STEP_r16(MD5_H, c, d, a, b, 3, 0xd4ef3085, 16) MD5_STEP(
MD5_H2, b, c, d, a, 6, 0x04881d05, 23)
MD5_STEP(MD5_H, a, b, c, d, 9, 0xd9d4d039, 4) MD5_STEP(
MD5_H2, d, a, b, c, 12, 0xe6db99e5, 11)
MD5_STEP_r16(MD5_H, c, d, a, b, 15, 0x1fa27cf8, 16)
MD5_STEP(MD5_H2, b, c, d, a, 2, 0xc4ac5665, 23)
/* Round 4 */
MD5_STEP(MD5_I, a, b, c, d, 0, 0xf4292244, 6) MD5_STEP(
MD5_I, d, a, b, c, 7, 0x432aff97, 10)
MD5_STEP(MD5_I, c, d, a, b, 14, 0xab9423a7, 15) MD5_STEP(
MD5_I, b, c, d, a, 5, 0xfc93a039, 21)
MD5_STEP(MD5_I, a, b, c, d, 12, 0x655b59c3, 6) MD5_STEP(
MD5_I, d, a, b, c, 3, 0x8f0ccc92, 10)
MD5_STEP(MD5_I, c, d, a, b, 10, 0xffeff47d, 15) MD5_STEP(
MD5_I, b, c, d, a, 1, 0x85845dd1, 21)
MD5_STEP(MD5_I, a, b, c, d, 8, 0x6fa87e4f, 6) MD5_STEP(
MD5_I, d, a, b, c, 15, 0xfe2ce6e0, 10)
MD5_STEP(MD5_I, c, d, a, b, 6, 0xa3014314, 15)
MD5_STEP(MD5_I, b, c, d, a, 13, 0x4e0811a1, 21)
MD5_STEP(
MD5_I, a, b, c, d, 4, 0xf7537e82, 6)
if (SSEi_flags & SSEi_REVERSE_STEPS)
{
MD5_PARA_DO(i)
{
vstore((vtype *) &out[i * 4 * VS32 + 0 * VS32], a[i]);
}
return;
}
MD5_STEP(MD5_I, d, a, b, c, 11, 0xbd3af235, 10)
MD5_STEP(MD5_I, c, d, a, b, 2, 0x2ad7d2bb, 15)
MD5_STEP(MD5_I, b, c, d, a, 9, 0xeb86d391, 21)
if ((SSEi_flags & SSEi_RELOAD) == 0)
{
MD5_PARA_DO(i)
{
a[i] = vadd_epi32(a[i], vset1_epi32(0x67452301));
b[i] = vadd_epi32(b[i], vset1_epi32(0xefcdab89));
c[i] = vadd_epi32(c[i], vset1_epi32(0x98badcfe));
d[i] = vadd_epi32(d[i], vset1_epi32(0x10325476));
}
}
else
{
if ((SSEi_flags & SSEi_RELOAD_INP_FMT) == SSEi_RELOAD_INP_FMT)
{
MD5_PARA_DO(i)
{
a[i] = vadd_epi32(
a[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 0 * VS32]));
b[i] = vadd_epi32(
b[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 1 * VS32]));
c[i] = vadd_epi32(
c[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 2 * VS32]));
d[i] = vadd_epi32(
d[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 3 * VS32]));
}
}
else
{
MD5_PARA_DO(i)
{
a[i] = vadd_epi32(
a[i],
vload((vtype *) &reload_state[i * 4 * VS32 + 0 * VS32]));
b[i] = vadd_epi32(
b[i],
vload((vtype *) &reload_state[i * 4 * VS32 + 1 * VS32]));
c[i] = vadd_epi32(
c[i],
vload((vtype *) &reload_state[i * 4 * VS32 + 2 * VS32]));
d[i] = vadd_epi32(
d[i],
vload((vtype *) &reload_state[i * 4 * VS32 + 3 * VS32]));
}
}
}
#if USE_EXPERIMENTAL
/*
* This is currently not used for MD5, and was observed to result
* in a significant performance regression (at least on XOP) just by sitting
* here. http://www.openwall.com/lists/john-dev/2015/09/05/5
* NOTE the regression might be gone now anyway since we went from -O3 to -O2.
*/
if (SSEi_flags & SSEi_FLAT_OUT)
{
MD5_PARA_DO(i)
{
uint32_t * o = (uint32_t *) &out[i * 4 * VS32];
#if __AVX512F__ || __MIC__
vtype idxs = vset_epi32(15 * 4,
14 * 4,
13 * 4,
12 * 4,
11 * 4,
10 * 4,
9 * 4,
8 * 4,
7 * 4,
6 * 4,
5 * 4,
4 * 4,
3 * 4,
2 * 4,
1 * 4,
0 * 4);
vscatter_epi32(o + 0, idxs, a[i], 4);
vscatter_epi32(o + 1, idxs, b[i], 4);
vscatter_epi32(o + 2, idxs, c[i], 4);
vscatter_epi32(o + 3, idxs, d[i], 4);
#else
uint32_t j, k;
union {
vtype v[4];
uint32_t s[4 * VS32];
} tmp;
tmp.v[0] = a[i];
tmp.v[1] = b[i];
tmp.v[2] = c[i];
tmp.v[3] = d[i];
for (j = 0; j < VS32; j++)
for (k = 0; k < 4; k++) o[j * 4 + k] = tmp.s[k * VS32 + j];
#endif
}
}
else
#endif
if (SSEi_flags & SSEi_OUTPUT_AS_INP_FMT)
{
if ((SSEi_flags & SSEi_OUTPUT_AS_2BUF_INP_FMT)
== SSEi_OUTPUT_AS_2BUF_INP_FMT)
{
MD5_PARA_DO(i)
{
vstore((vtype *) &out[i * 32 * VS32 + 0 * VS32], a[i]);
vstore((vtype *) &out[i * 32 * VS32 + 1 * VS32], b[i]);
vstore((vtype *) &out[i * 32 * VS32 + 2 * VS32], c[i]);
vstore((vtype *) &out[i * 32 * VS32 + 3 * VS32], d[i]);
}
}
else
{
MD5_PARA_DO(i)
{
vstore((vtype *) &out[i * 16 * VS32 + 0 * VS32], a[i]);
vstore((vtype *) &out[i * 16 * VS32 + 1 * VS32], b[i]);
vstore((vtype *) &out[i * 16 * VS32 + 2 * VS32], c[i]);
vstore((vtype *) &out[i * 16 * VS32 + 3 * VS32], d[i]);
}
}
}
else
{
MD5_PARA_DO(i)
{
vstore((vtype *) &out[i * 4 * VS32 + 0 * VS32], a[i]);
vstore((vtype *) &out[i * 4 * VS32 + 1 * VS32], b[i]);
vstore((vtype *) &out[i * 4 * VS32 + 2 * VS32], c[i]);
vstore((vtype *) &out[i * 4 * VS32 + 3 * VS32], d[i]);
}
}
}
#define GETPOS(i, index) \
((index & (VS32 - 1)) * 4 + (i & (0xffffffff - 3)) * VS32 + ((i) &3))
static MAYBE_INLINE void mmxput(void * buf,
unsigned int index,
unsigned int bid,
unsigned int offset,
unsigned char * src,
unsigned int len)
{
unsigned char * nbuf;
unsigned int i;
nbuf = ((unsigned char *) buf) + index / VS32 * 64 * VS32
+ bid * 64 * MD5_SSE_NUM_KEYS;
for (i = 0; i < len; i++) nbuf[GETPOS((offset + i), index)] = src[i];
}
static MAYBE_INLINE void mmxput2(void * buf, unsigned int bid, void * src)
{
unsigned char * nbuf;
unsigned int i;
nbuf = ((unsigned char *) buf) + bid * 64 * MD5_SSE_NUM_KEYS;
MD5_PARA_DO(i)
memcpy(nbuf + i * 64 * VS32,
((unsigned char *) src) + i * 16 * VS32,
16 * VS32);
}
#if (ARCH_SIZE >= 8) || defined(__i386__) || defined(__ARM_NEON__)
#define BITALIGN(hi, lo, s) ((((uint64_t)(hi) << 32) | (lo)) >> (s))
#else
#define BITALIGN(hi, lo, s) (((hi) << (32 - (s))) | ((lo) >> (s)))
#endif
static MAYBE_INLINE void mmxput3(void * buf,
unsigned int bid,
unsigned int * offset,
unsigned int mult,
unsigned int saltlen,
void * src)
{
unsigned int j;
MD5_PARA_DO(j)
{
unsigned int i;
unsigned int jm = j * VS32 * 4;
unsigned char * nbuf
= ((unsigned char *) buf) + bid * (64 * MD5_SSE_NUM_KEYS) + jm * 16;
unsigned int * s = (unsigned int *) src + jm;
for (i = 0; i < VS32; i++, s++)
{
unsigned int n = offset[i + jm / 4] * mult + saltlen;
unsigned int * d = (unsigned int *) (nbuf + (n & ~3U) * VS32) + i;
switch (n &= 3)
{
case 0:
d[0] = s[0];
d[1 * VS32] = s[1 * VS32];
d[2 * VS32] = s[2 * VS32];
d[3 * VS32] = s[3 * VS32];
break;
#if 0
default:
n <<= 3;
{
unsigned int m = 32 - n;
d[0] = (d[0] & (0xffffffffU >> m)) | (s[0] << n);
d[1 * VS32] = BITALIGN(s[1 * VS32], s[0], m);
d[2 * VS32] = BITALIGN(s[2 * VS32], s[1 * VS32], m);
d[3 * VS32] = BITALIGN(s[3 * VS32], s[2 * VS32], m);
d[4 * VS32] = (d[4 * VS32] & (0xffffffffU << n)) | (s[3 * VS32] >> m);
}
#else
case 1:
d[0] = (d[0] & 0xffU) | (s[0] << 8);
d[1 * VS32] = BITALIGN(s[1 * VS32], s[0], 24);
d[2 * VS32] = BITALIGN(s[2 * VS32], s[1 * VS32], 24);
d[3 * VS32] = BITALIGN(s[3 * VS32], s[2 * VS32], 24);
d[4 * VS32]
= (d[4 * VS32] & 0xffffff00U) | (s[3 * VS32] >> 24);
break;
case 2:
d[0] = (d[0] & 0xffffU) | (s[0] << 16);
d[1 * VS32] = BITALIGN(s[1 * VS32], s[0], 16);
d[2 * VS32] = BITALIGN(s[2 * VS32], s[1 * VS32], 16);
d[3 * VS32] = BITALIGN(s[3 * VS32], s[2 * VS32], 16);
d[4 * VS32]
= (d[4 * VS32] & 0xffff0000U) | (s[3 * VS32] >> 16);
break;
case 3:
d[0] = (d[0] & 0xffffffU) | (s[0] << 24);
d[1 * VS32] = BITALIGN(s[1 * VS32], s[0], 8);
d[2 * VS32] = BITALIGN(s[2 * VS32], s[1 * VS32], 8);
d[3 * VS32] = BITALIGN(s[3 * VS32], s[2 * VS32], 8);
d[4 * VS32]
= (d[4 * VS32] & 0xff000000U) | (s[3 * VS32] >> 8);
#endif
}
}
}
}
static MAYBE_INLINE void dispatch(unsigned char buffers[8]
[64 * MD5_SSE_NUM_KEYS],
unsigned int f[4 * MD5_SSE_NUM_KEYS],
unsigned int length[MD5_SSE_NUM_KEYS],
unsigned int saltlen)
{
unsigned int i, j;
unsigned int bufferid;
i = 1000 / 42;
j = 0;
do
{
switch (j)
{
case 0:
bufferid = 0;
mmxput2(buffers, bufferid, f);
break;
case 21:
bufferid = 1;
mmxput3(buffers, bufferid, length, 1, 0, f);
break;
case 3:
case 9:
case 15:
case 27:
case 33:
case 39:
bufferid = 2;
mmxput3(buffers, bufferid, length, 2, 0, f);
break;
case 6:
case 12:
case 18:
case 24:
case 30:
case 36:
bufferid = 3;
mmxput2(buffers, bufferid, f);
break;
case 7:
case 35:
bufferid = 4;
mmxput3(buffers, bufferid, length, 1, saltlen, f);
break;
case 14:
case 28:
bufferid = 5;
mmxput2(buffers, bufferid, f);
break;
case 2:
case 4:
case 8:
case 10:
case 16:
case 20:
case 22:
case 26:
case 32:
case 34:
case 38:
case 40:
bufferid = 6;
mmxput2(buffers, bufferid, f);
break;
default:
bufferid = 7;
mmxput3(buffers, bufferid, length, 2, saltlen, f);
break;
}
SIMDmd5body((vtype *) &buffers[bufferid], f, NULL, SSEi_MIXED_IN);
if (j++ < 1000 % 42 - 1) continue;
if (j == 1000 % 42)
{
if (!i) break;
i--;
continue;
}
if (j >= 42) j = 0;
} while (1);
}
void md5cryptsse(unsigned char pwd[MD5_SSE_NUM_KEYS][16],
unsigned char * salt,
char * out,
unsigned int md5_type)
{
unsigned int length[MD5_SSE_NUM_KEYS];
unsigned int saltlen;
unsigned int i, j;
MD5_CTX ctx;
MD5_CTX tctx;
JTR_ALIGN(MEM_ALIGN_SIMD)
unsigned char buffers[8][64 * MD5_SSE_NUM_KEYS] = {{0}};
JTR_ALIGN(MEM_ALIGN_SIMD) unsigned int F[4 * MD5_SSE_NUM_KEYS];
saltlen = strlen((char *) salt);
for (i = 0; i < MD5_SSE_NUM_KEYS; i++)
{
unsigned int length_i = strlen((char *) pwd[i]);
unsigned int * bt;
unsigned int tf[4];
/* cas 0 fs */
mmxput(buffers, i, 0, 16, pwd[i], length_i);
mmxput(buffers, i, 0, length_i + 16, (unsigned char *) "\x80", 1);
/* cas 1 sf */
mmxput(buffers, i, 1, 0, pwd[i], length_i);
mmxput(buffers, i, 1, length_i + 16, (unsigned char *) "\x80", 1);
/* cas 2 ssf */
mmxput(buffers, i, 2, 0, pwd[i], length_i);
mmxput(buffers, i, 2, length_i, pwd[i], length_i);
mmxput(buffers, i, 2, length_i * 2 + 16, (unsigned char *) "\x80", 1);
/* cas 3 fss */
mmxput(buffers, i, 3, 16, pwd[i], length_i);
mmxput(buffers, i, 3, 16 + length_i, pwd[i], length_i);
mmxput(buffers, i, 3, length_i * 2 + 16, (unsigned char *) "\x80", 1);
/* cas 4 scf */
mmxput(buffers, i, 4, 0, pwd[i], length_i);
mmxput(buffers, i, 4, length_i, salt, saltlen);
mmxput(buffers,
i,
4,
saltlen + length_i + 16,
(unsigned char *) "\x80",
1);
/* cas 5 fcs */
mmxput(buffers, i, 5, 16, salt, saltlen);
mmxput(buffers, i, 5, 16 + saltlen, pwd[i], length_i);
mmxput(buffers,
i,
5,
saltlen + length_i + 16,
(unsigned char *) "\x80",
1);
/* cas 6 fcss */
mmxput(buffers, i, 6, 16, salt, saltlen);
mmxput(buffers, i, 6, 16 + saltlen, pwd[i], length_i);
mmxput(buffers, i, 6, 16 + saltlen + length_i, pwd[i], length_i);
mmxput(buffers,
i,
6,
saltlen + 2 * length_i + 16,
(unsigned char *) "\x80",
1);
/* cas 7 scsf */
mmxput(buffers, i, 7, 0, pwd[i], length_i);
mmxput(buffers, i, 7, length_i, salt, saltlen);
mmxput(buffers, i, 7, length_i + saltlen, pwd[i], length_i);
mmxput(buffers,
i,
7,
saltlen + 2 * length_i + 16,
(unsigned char *) "\x80",
1);
bt = (unsigned int *) &buffers[0];
bt[14 * VS32 + (i & (VS32 - 1)) + i / VS32 * 16 * VS32]
= (length_i + 16) << 3;
bt = (unsigned int *) &buffers[1];
bt[14 * VS32 + (i & (VS32 - 1)) + i / VS32 * 16 * VS32]
= (length_i + 16) << 3;
bt = (unsigned int *) &buffers[2];
bt[14 * VS32 + (i & (VS32 - 1)) + i / VS32 * 16 * VS32]
= (length_i * 2 + 16) << 3;
bt = (unsigned int *) &buffers[3];
bt[14 * VS32 + (i & (VS32 - 1)) + i / VS32 * 16 * VS32]
= (length_i * 2 + 16) << 3;
bt = (unsigned int *) &buffers[4];
bt[14 * VS32 + (i & (VS32 - 1)) + i / VS32 * 16 * VS32]
= (length_i + saltlen + 16) << 3;
bt = (unsigned int *) &buffers[5];
bt[14 * VS32 + (i & (VS32 - 1)) + i / VS32 * 16 * VS32]
= (length_i + saltlen + 16) << 3;
bt = (unsigned int *) &buffers[6];
bt[14 * VS32 + (i & (VS32 - 1)) + i / VS32 * 16 * VS32]
= (length_i * 2 + saltlen + 16) << 3;
bt = (unsigned int *) &buffers[7];
bt[14 * VS32 + (i & (VS32 - 1)) + i / VS32 * 16 * VS32]
= (length_i * 2 + saltlen + 16) << 3;
MD5_Init(&ctx);
MD5_Update(&ctx, pwd[i], length_i);
if (md5_type == MD5_TYPE_STD)
MD5_Update(&ctx, "$1$", 3);
else if (md5_type == MD5_TYPE_APACHE)
MD5_Update(&ctx, "$apr1$", 6);
// else it's AIX and no prefix included
MD5_Update(&ctx, salt, saltlen);
MD5_Init(&tctx);
MD5_Update(&tctx, pwd[i], length_i);
MD5_Update(&tctx, salt, saltlen);
MD5_Update(&tctx, pwd[i], length_i);
MD5_Final((unsigned char *) tf, &tctx);
MD5_Update(&ctx, tf, length_i);
length[i] = length_i;
for (j = length_i; j; j >>= 1)
if (j & 1)
MD5_Update(&ctx, "\0", 1);
else
MD5_Update(&ctx, pwd[i], 1);
MD5_Final((unsigned char *) tf, &ctx);
F[i / VS32 * 4 * VS32 + (i & (VS32 - 1)) + 0 * VS32] = tf[0];
F[i / VS32 * 4 * VS32 + (i & (VS32 - 1)) + 1 * VS32] = tf[1];
F[i / VS32 * 4 * VS32 + (i & (VS32 - 1)) + 2 * VS32] = tf[2];
F[i / VS32 * 4 * VS32 + (i & (VS32 - 1)) + 3 * VS32] = tf[3];
}
dispatch(buffers, F, length, saltlen);
memcpy(out, F, MD5_SSE_NUM_KEYS * 16);
}
#endif /* SIMD_PARA_MD5 */
#if SIMD_PARA_MD4
#define MD4_SSE_NUM_KEYS (SIMD_COEF_32 * SIMD_PARA_MD4)
#define MD4_PARA_DO(x) for ((x) = 0; (x) < SIMD_PARA_MD4; (x)++)
#define MD4_F(x, y, z) tmp[i] = vcmov((y[i]), (z[i]), (x[i]));
#if __AVX512F__
#define MD4_G(x, y, z) tmp[i] = vternarylogic(x[i], y[i], z[i], 0xE8);
#elif !VCMOV_EMULATED
#define MD4_G(x, y, z) \
tmp[i] = vxor((y[i]), (z[i])); \
tmp[i] = vcmov((x[i]), (z[i]), (tmp[i]));
#else
#define MD4_G(x, y, z) \
tmp[i] = vor((y[i]), (z[i])); \
tmp2[i] = vand((y[i]), (z[i])); \
tmp[i] = vand((tmp[i]), (x[i])); \
tmp[i] = vor((tmp[i]), (tmp2[i]));
#endif
#if __AVX512F__
#define MD4_H(x, y, z) tmp[i] = vternarylogic(x[i], y[i], z[i], 0x96);
#define MD4_H2(x, y, z) tmp[i] = vternarylogic(x[i], y[i], z[i], 0x96);
#elif SIMD_PARA_MD4 < 3
#define MD4_H(x, y, z) \
tmp2[i] = vxor((x[i]), (y[i])); \
tmp[i] = vxor(tmp2[i], (z[i]));
#define MD4_H2(x, y, z) tmp[i] = vxor((x[i]), tmp2[i]);
#else
#define MD4_H(x, y, z) \
tmp[i] = vxor((x[i]), (y[i])); \
tmp[i] = vxor((tmp[i]), (z[i]));
#define MD4_H2(x, y, z) \
tmp[i] = vxor((y[i]), (z[i])); \
tmp[i] = vxor((tmp[i]), (x[i]));
#endif
#define MD4_STEP(f, a, b, c, d, x, t, s) \
MD4_PARA_DO(i) \
{ \
a[i] = vadd_epi32(a[i], t); \
f((b), (c), (d)) a[i] = vadd_epi32(a[i], tmp[i]); \
a[i] = vadd_epi32(a[i], data[i * 16 + x]); \
a[i] = vroti_epi32(a[i], (s)); \
}
#define MD4_REV_STEP(f, a, b, c, d, x, t, s) \
MD4_PARA_DO(i) \
{ \
f((b), (c), (d)) a[i] = vadd_epi32(a[i], tmp[i]); \
a[i] = vadd_epi32(a[i], data[i * 16 + x]); \
}
#define INIT_A 0x67452301
#define INIT_B 0xefcdab89
#define INIT_C 0x98badcfe
#define INIT_D 0x10325476
#define SQRT_3 0x6ed9eba1
void md4_reverse(uint32_t * hash)
{
hash[0] -= INIT_A;
hash[1] -= INIT_B;
hash[2] -= INIT_C;
hash[3] -= INIT_D;
hash[1] = (hash[1] >> 15) | (hash[1] << 17);
hash[1] -= SQRT_3 + (hash[2] ^ hash[3] ^ hash[0]);
hash[1] = (hash[1] >> 15) | (hash[1] << 17);
hash[1] -= SQRT_3;
}
void md4_unreverse(uint32_t * hash)
{
hash[1] += SQRT_3;
hash[1] = (hash[1] >> 17) | (hash[1] << 15);
hash[1] += SQRT_3 + (hash[2] ^ hash[3] ^ hash[0]);
hash[1] = (hash[1] >> 17) | (hash[1] << 15);
hash[3] += INIT_D;
hash[2] += INIT_C;
hash[1] += INIT_B;
hash[0] += INIT_A;
}
#undef SQRT_3
#undef INIT_D
#undef INIT_C
#undef INIT_B
#undef INIT_A
void SIMDmd4body(vtype * _data,
unsigned int * out,
ARCH_WORD_32 * reload_state,
unsigned SSEi_flags)
{
vtype w[16 * SIMD_PARA_MD4];
vtype a[SIMD_PARA_MD4];
vtype b[SIMD_PARA_MD4];
vtype c[SIMD_PARA_MD4];
vtype d[SIMD_PARA_MD4];
vtype tmp[SIMD_PARA_MD4];
#if (SIMD_PARA_MD4 < 3 || VCMOV_EMULATED) && !__AVX512F__
vtype tmp2[SIMD_PARA_MD4];
#endif
vtype cst;
unsigned int i;
vtype * data;
if (SSEi_flags & SSEi_FLAT_IN)
{
// Move _data to __data, mixing it SIMD_COEF_32 wise.
#if __SSE4_1__ || __MIC__
unsigned k;
vtype * W = w;
ARCH_WORD_32 * saved_key = (ARCH_WORD_32 *) _data;
MD4_PARA_DO(k)
{
if (SSEi_flags & SSEi_4BUF_INPUT)
{
for (i = 0; i < 16; ++i)
{
GATHER_4x(W[i], saved_key, i);
}
saved_key += (VS32 << 6);
}
else if (SSEi_flags & SSEi_2BUF_INPUT)
{
for (i = 0; i < 16; ++i)
{
GATHER_2x(W[i], saved_key, i);
}
saved_key += (VS32 << 5);
}
else
{
for (i = 0; i < 16; ++i)
{
GATHER(W[i], saved_key, i);
}
saved_key += (VS32 << 4);
}
W += 16;
}
#else
unsigned j, k;
ARCH_WORD_32 * p = (ARCH_WORD_32 *) w;
vtype * W = w;
ARCH_WORD_32 * saved_key = (ARCH_WORD_32 *) _data;
MD4_PARA_DO(k)
{
if (SSEi_flags & SSEi_4BUF_INPUT)
{
for (j = 0; j < 16; j++)
for (i = 0; i < VS32; i++) *p++ = saved_key[(i << 6) + j];
saved_key += (VS32 << 6);
}
else if (SSEi_flags & SSEi_2BUF_INPUT)
{
for (j = 0; j < 16; j++)
for (i = 0; i < VS32; i++) *p++ = saved_key[(i << 5) + j];
saved_key += (VS32 << 5);
}
else
{
for (j = 0; j < 16; j++)
for (i = 0; i < VS32; i++) *p++ = saved_key[(i << 4) + j];
saved_key += (VS32 << 4);
}
W += 16;
}
#endif
// now set our data pointer to point to this 'mixed' data.
data = w;
}
else
data = _data;
if ((SSEi_flags & SSEi_RELOAD) == 0)
{
MD4_PARA_DO(i)
{
a[i] = vset1_epi32(0x67452301);
b[i] = vset1_epi32(0xefcdab89);
c[i] = vset1_epi32(0x98badcfe);
d[i] = vset1_epi32(0x10325476);
}
}
else
{
if ((SSEi_flags & SSEi_RELOAD_INP_FMT) == SSEi_RELOAD_INP_FMT)
{
MD4_PARA_DO(i)
{
a[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 0 * VS32]);
b[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 1 * VS32]);
c[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 2 * VS32]);
d[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 3 * VS32]);
}
}
else
{
MD4_PARA_DO(i)
{
a[i] = vload((vtype *) &reload_state[i * 4 * VS32 + 0 * VS32]);
b[i] = vload((vtype *) &reload_state[i * 4 * VS32 + 1 * VS32]);
c[i] = vload((vtype *) &reload_state[i * 4 * VS32 + 2 * VS32]);
d[i] = vload((vtype *) &reload_state[i * 4 * VS32 + 3 * VS32]);
}
}
}
/* Round 1 */
cst = vsetzero();
MD4_STEP(MD4_F, a, b, c, d, 0, cst, 3)
MD4_STEP(MD4_F, d, a, b, c, 1, cst, 7)
MD4_STEP(MD4_F, c, d, a, b, 2, cst, 11)
MD4_STEP(MD4_F, b, c, d, a, 3, cst, 19)
MD4_STEP(MD4_F, a, b, c, d, 4, cst, 3)
MD4_STEP(MD4_F, d, a, b, c, 5, cst, 7)
MD4_STEP(MD4_F, c, d, a, b, 6, cst, 11)
MD4_STEP(MD4_F, b, c, d, a, 7, cst, 19)
MD4_STEP(MD4_F, a, b, c, d, 8, cst, 3)
MD4_STEP(MD4_F, d, a, b, c, 9, cst, 7)
MD4_STEP(MD4_F, c, d, a, b, 10, cst, 11)
MD4_STEP(MD4_F, b, c, d, a, 11, cst, 19)
MD4_STEP(MD4_F, a, b, c, d, 12, cst, 3)
MD4_STEP(MD4_F, d, a, b, c, 13, cst, 7)
MD4_STEP(MD4_F, c, d, a, b, 14, cst, 11)
MD4_STEP(MD4_F, b, c, d, a, 15, cst, 19)
/* Round 2 */
cst = vset1_epi32(0x5A827999L);
MD4_STEP(MD4_G, a, b, c, d, 0, cst, 3)
MD4_STEP(MD4_G, d, a, b, c, 4, cst, 5)
MD4_STEP(MD4_G, c, d, a, b, 8, cst, 9)
MD4_STEP(MD4_G, b, c, d, a, 12, cst, 13)
MD4_STEP(MD4_G, a, b, c, d, 1, cst, 3)
MD4_STEP(MD4_G, d, a, b, c, 5, cst, 5)
MD4_STEP(MD4_G, c, d, a, b, 9, cst, 9)
MD4_STEP(MD4_G, b, c, d, a, 13, cst, 13)
MD4_STEP(MD4_G, a, b, c, d, 2, cst, 3)
MD4_STEP(MD4_G, d, a, b, c, 6, cst, 5)
MD4_STEP(MD4_G, c, d, a, b, 10, cst, 9)
MD4_STEP(MD4_G, b, c, d, a, 14, cst, 13)
MD4_STEP(MD4_G, a, b, c, d, 3, cst, 3)
MD4_STEP(MD4_G, d, a, b, c, 7, cst, 5)
MD4_STEP(MD4_G, c, d, a, b, 11, cst, 9)
MD4_STEP(MD4_G, b, c, d, a, 15, cst, 13)
/* Round 3 */
cst = vset1_epi32(0x6ED9EBA1L);
MD4_STEP(MD4_H, a, b, c, d, 0, cst, 3)
MD4_STEP(MD4_H2, d, a, b, c, 8, cst, 9)
MD4_STEP(MD4_H, c, d, a, b, 4, cst, 11)
MD4_STEP(MD4_H2, b, c, d, a, 12, cst, 15)
MD4_STEP(MD4_H, a, b, c, d, 2, cst, 3)
MD4_STEP(MD4_H2, d, a, b, c, 10, cst, 9)
MD4_STEP(MD4_H, c, d, a, b, 6, cst, 11)
MD4_STEP(MD4_H2, b, c, d, a, 14, cst, 15)
MD4_STEP(MD4_H, a, b, c, d, 1, cst, 3)
MD4_STEP(MD4_H2, d, a, b, c, 9, cst, 9)
MD4_STEP(MD4_H, c, d, a, b, 5, cst, 11)
if (SSEi_flags & SSEi_REVERSE_STEPS)
{
MD4_REV_STEP(MD4_H2, b, c, d, a, 13, cst, 15)
MD4_PARA_DO(i)
{
vstore((vtype *) &out[i * 4 * VS32 + 1 * VS32], b[i]);
}
return;
}
MD4_STEP(MD4_H2, b, c, d, a, 13, cst, 15)
MD4_STEP(MD4_H, a, b, c, d, 3, cst, 3)
MD4_STEP(MD4_H2, d, a, b, c, 11, cst, 9)
MD4_STEP(MD4_H, c, d, a, b, 7, cst, 11)
MD4_STEP(MD4_H2, b, c, d, a, 15, cst, 15)
if ((SSEi_flags & SSEi_RELOAD) == 0)
{
MD4_PARA_DO(i)
{
a[i] = vadd_epi32(a[i], vset1_epi32(0x67452301));
b[i] = vadd_epi32(b[i], vset1_epi32(0xefcdab89));
c[i] = vadd_epi32(c[i], vset1_epi32(0x98badcfe));
d[i] = vadd_epi32(d[i], vset1_epi32(0x10325476));
}
}
else
{
if ((SSEi_flags & SSEi_RELOAD_INP_FMT) == SSEi_RELOAD_INP_FMT)
{
MD4_PARA_DO(i)
{
a[i] = vadd_epi32(
a[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 0 * VS32]));
b[i] = vadd_epi32(
b[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 1 * VS32]));
c[i] = vadd_epi32(
c[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 2 * VS32]));
d[i] = vadd_epi32(
d[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 3 * VS32]));
}
}
else
{
MD4_PARA_DO(i)
{
a[i] = vadd_epi32(
a[i],
vload((vtype *) &reload_state[i * 4 * VS32 + 0 * VS32]));
b[i] = vadd_epi32(
b[i],
vload((vtype *) &reload_state[i * 4 * VS32 + 1 * VS32]));
c[i] = vadd_epi32(
c[i],
vload((vtype *) &reload_state[i * 4 * VS32 + 2 * VS32]));
d[i] = vadd_epi32(
d[i],
vload((vtype *) &reload_state[i * 4 * VS32 + 3 * VS32]));
}
}
}
#if USE_EXPERIMENTAL
/*
* This is currently not used for MD4, and was observed to result
* in a significant performance regression (at least on XOP) just by sitting
* here. http://www.openwall.com/lists/john-dev/2015/09/05/5
* NOTE the regression might be gone now anyway since we went from -O3 to -O2.
*/
if (SSEi_flags & SSEi_FLAT_OUT)
{
MD4_PARA_DO(i)
{
uint32_t * o = (uint32_t *) &out[i * 4 * VS32];
#if __AVX512F__ || __MIC__
vtype idxs = vset_epi32(15 * 4,
14 * 4,
13 * 4,
12 * 4,
11 * 4,
10 * 4,
9 * 4,
8 * 4,
7 * 4,
6 * 4,
5 * 4,
4 * 4,
3 * 4,
2 * 4,
1 * 4,
0 * 4);
vscatter_epi32(o + 0, idxs, a[i], 4);
vscatter_epi32(o + 1, idxs, b[i], 4);
vscatter_epi32(o + 2, idxs, c[i], 4);
vscatter_epi32(o + 3, idxs, d[i], 4);
#else
uint32_t j, k;
union {
vtype v[4];
uint32_t s[4 * VS32];
} tmp;
tmp.v[0] = a[i];
tmp.v[1] = b[i];
tmp.v[2] = c[i];
tmp.v[3] = d[i];
for (j = 0; j < VS32; j++)
for (k = 0; k < 4; k++) o[j * 4 + k] = tmp.s[k * VS32 + j];
#endif
}
}
else
#endif
if (SSEi_flags & SSEi_OUTPUT_AS_INP_FMT)
{
if ((SSEi_flags & SSEi_OUTPUT_AS_2BUF_INP_FMT)
== SSEi_OUTPUT_AS_2BUF_INP_FMT)
{
MD4_PARA_DO(i)
{
vstore((vtype *) &out[i * 32 * VS32 + 0 * VS32], a[i]);
vstore((vtype *) &out[i * 32 * VS32 + 1 * VS32], b[i]);
vstore((vtype *) &out[i * 32 * VS32 + 2 * VS32], c[i]);
vstore((vtype *) &out[i * 32 * VS32 + 3 * VS32], d[i]);
}
}
else
{
MD4_PARA_DO(i)
{
vstore((vtype *) &out[i * 16 * VS32 + 0 * VS32], a[i]);
vstore((vtype *) &out[i * 16 * VS32 + 1 * VS32], b[i]);
vstore((vtype *) &out[i * 16 * VS32 + 2 * VS32], c[i]);
vstore((vtype *) &out[i * 16 * VS32 + 3 * VS32], d[i]);
}
}
}
else
{
MD4_PARA_DO(i)
{
vstore((vtype *) &out[i * 4 * VS32 + 0 * VS32], a[i]);
vstore((vtype *) &out[i * 4 * VS32 + 1 * VS32], b[i]);
vstore((vtype *) &out[i * 4 * VS32 + 2 * VS32], c[i]);
vstore((vtype *) &out[i * 4 * VS32 + 3 * VS32], d[i]);
}
}
}
#endif /* SIMD_PARA_MD4 */
#if SIMD_PARA_SHA1
#define SHA1_SSE_NUM_KEYS (SIMD_COEF_32 * SIMD_PARA_SHA1)
#define SHA1_PARA_DO(x) for ((x) = 0; (x) < SIMD_PARA_SHA1; (x)++)
#define SHA1_F(x, y, z) tmp[i] = vcmov((y[i]), (z[i]), (x[i]));
#if __AVX512F__
#define SHA1_G(x, y, z) tmp[i] = vternarylogic(x[i], y[i], z[i], 0x96);
#else
#define SHA1_G(x, y, z) \
tmp[i] = vxor((y[i]), (z[i])); \
tmp[i] = vxor((tmp[i]), (x[i]));
#endif
#if __AVX512F__
#define SHA1_H(x, y, z) tmp[i] = vternarylogic(x[i], y[i], z[i], 0xE8);
#elif !VCMOV_EMULATED
#define SHA1_H(x, y, z) \
tmp[i] = vxor((z[i]), (y[i])); \
tmp[i] = vcmov((x[i]), (y[i]), tmp[i]);
#else
#define SHA1_H(x, y, z) \
tmp[i] = vand((x[i]), (y[i])); \
tmp[i] = vor((tmp[i]), vand(vor((x[i]), (y[i])), (z[i])));
#endif
#define SHA1_I(x, y, z) SHA1_G(x, y, z)
#define SHA1_EXPAND2a(t) \
tmp[i] = vxor(data[i * 16 + t - 3], data[i * 16 + t - 8]); \
tmp[i] = vxor(tmp[i], data[i * 16 + t - 14]); \
tmp[i] = vxor(tmp[i], data[i * 16 + t - 16]); \
w[i * 16 + ((t) &0xF)] = vroti_epi32(tmp[i], 1);
#define SHA1_EXPAND2b(t) \
tmp[i] = vxor(w[i * 16 + ((t - 3) & 0xF)], data[i * 16 + t - 8]); \
tmp[i] = vxor(tmp[i], data[i * 16 + t - 14]); \
tmp[i] = vxor(tmp[i], data[i * 16 + t - 16]); \
w[i * 16 + ((t) &0xF)] = vroti_epi32(tmp[i], 1);
#define SHA1_EXPAND2c(t) \
tmp[i] = vxor(w[i * 16 + ((t - 3) & 0xF)], w[i * 16 + ((t - 8) & 0xF)]); \
tmp[i] = vxor(tmp[i], data[i * 16 + t - 14]); \
tmp[i] = vxor(tmp[i], data[i * 16 + t - 16]); \
w[i * 16 + ((t) &0xF)] = vroti_epi32(tmp[i], 1);
#define SHA1_EXPAND2d(t) \
tmp[i] = vxor(w[i * 16 + ((t - 3) & 0xF)], w[i * 16 + ((t - 8) & 0xF)]); \
tmp[i] = vxor(tmp[i], w[i * 16 + ((t - 14) & 0xF)]); \
tmp[i] = vxor(tmp[i], data[i * 16 + t - 16]); \
w[i * 16 + ((t) &0xF)] = vroti_epi32(tmp[i], 1);
#define SHA1_EXPAND2(t) \
tmp[i] = vxor(w[i * 16 + ((t - 3) & 0xF)], w[i * 16 + ((t - 8) & 0xF)]); \
tmp[i] = vxor(tmp[i], w[i * 16 + ((t - 14) & 0xF)]); \
tmp[i] = vxor(tmp[i], w[i * 16 + ((t - 16) & 0xF)]); \
w[i * 16 + ((t) &0xF)] = vroti_epi32(tmp[i], 1);
#define SHA1_ROUND2a(a, b, c, d, e, F, t) \
SHA1_PARA_DO(i) \
{ \
F(b, c, d) \
e[i] = vadd_epi32(e[i], tmp[i]); \
tmp[i] = vroti_epi32(a[i], 5); \
e[i] = vadd_epi32(e[i], tmp[i]); \
e[i] = vadd_epi32(e[i], cst); \
e[i] = vadd_epi32(e[i], data[i * 16 + t]); \
b[i] = vroti_epi32(b[i], 30); \
SHA1_EXPAND2a(t + 16) \
}
#define SHA1_ROUND2b(a, b, c, d, e, F, t) \
SHA1_PARA_DO(i) \
{ \
F(b, c, d) \
e[i] = vadd_epi32(e[i], tmp[i]); \
tmp[i] = vroti_epi32(a[i], 5); \
e[i] = vadd_epi32(e[i], tmp[i]); \
e[i] = vadd_epi32(e[i], cst); \
e[i] = vadd_epi32(e[i], data[i * 16 + t]); \
b[i] = vroti_epi32(b[i], 30); \
SHA1_EXPAND2b(t + 16) \
}
#define SHA1_ROUND2c(a, b, c, d, e, F, t) \
SHA1_PARA_DO(i) \
{ \
F(b, c, d) \
e[i] = vadd_epi32(e[i], tmp[i]); \
tmp[i] = vroti_epi32(a[i], 5); \
e[i] = vadd_epi32(e[i], tmp[i]); \
e[i] = vadd_epi32(e[i], cst); \
e[i] = vadd_epi32(e[i], data[i * 16 + t]); \
b[i] = vroti_epi32(b[i], 30); \
SHA1_EXPAND2c(t + 16) \
}
#define SHA1_ROUND2d(a, b, c, d, e, F, t) \
SHA1_PARA_DO(i) \
{ \
F(b, c, d) \
e[i] = vadd_epi32(e[i], tmp[i]); \
tmp[i] = vroti_epi32(a[i], 5); \
e[i] = vadd_epi32(e[i], tmp[i]); \
e[i] = vadd_epi32(e[i], cst); \
e[i] = vadd_epi32(e[i], data[i * 16 + t]); \
b[i] = vroti_epi32(b[i], 30); \
SHA1_EXPAND2d(t + 16) \
}
#define SHA1_ROUND2(a, b, c, d, e, F, t) \
SHA1_PARA_DO(i) \
{ \
F(b, c, d) \
e[i] = vadd_epi32(e[i], tmp[i]); \
tmp[i] = vroti_epi32(a[i], 5); \
e[i] = vadd_epi32(e[i], tmp[i]); \
e[i] = vadd_epi32(e[i], cst); \
e[i] = vadd_epi32(e[i], w[i * 16 + (t & 0xF)]); \
b[i] = vroti_epi32(b[i], 30); \
SHA1_EXPAND2(t + 16) \
}
#define SHA1_ROUND2x(a, b, c, d, e, F, t) \
SHA1_PARA_DO(i) \
{ \
F(b, c, d) \
e[i] = vadd_epi32(e[i], tmp[i]); \
tmp[i] = vroti_epi32(a[i], 5); \
e[i] = vadd_epi32(e[i], tmp[i]); \
e[i] = vadd_epi32(e[i], cst); \
e[i] = vadd_epi32(e[i], w[i * 16 + (t & 0xF)]); \
b[i] = vroti_epi32(b[i], 30); \
}
#define INIT_E 0xC3D2E1F0
void sha1_reverse(uint32_t * hash)
{
hash[4] -= INIT_E;
hash[4] = (hash[4] << 2) | (hash[4] >> 30);
}
void sha1_unreverse(uint32_t * hash)
{
hash[4] = (hash[4] << 30) | (hash[4] >> 2);
hash[4] += INIT_E;
}
#undef INIT_E
// SSEi_MIXED_IN | SSEi_RELOAD | SSEi_OUTPUT_AS_INP_FMT
void SIMDSHA1body(vtype * _data,
ARCH_WORD_32 * out,
ARCH_WORD_32 * reload_state,
unsigned SSEi_flags)
{
#if __ALTIVEC__
vtype w[16 * SIMD_PARA_SHA1] = {{{0}}};
vtype a[SIMD_PARA_SHA1] = {{{0}}};
vtype b[SIMD_PARA_SHA1] = {{{0}}};
vtype c[SIMD_PARA_SHA1] = {{{0}}};
vtype d[SIMD_PARA_SHA1] = {{{0}}};
vtype e[SIMD_PARA_SHA1] = {{{0}}};
#else
vtype w[16 * SIMD_PARA_SHA1] = {(vtype){0}};
vtype a[SIMD_PARA_SHA1] = {(vtype){0}};
vtype b[SIMD_PARA_SHA1] = {(vtype){0}};
vtype c[SIMD_PARA_SHA1] = {(vtype){0}};
vtype d[SIMD_PARA_SHA1] = {(vtype){0}};
vtype e[SIMD_PARA_SHA1] = {(vtype){0}};
#endif
vtype tmp[SIMD_PARA_SHA1];
vtype cst;
unsigned int i;
vtype * data;
#ifdef NDEBUG
(void) SSEi_flags;
#endif
#if 0
if (SSEi_flags & SSEi_FLAT_IN)
{
// Move _data to __data, mixing it SIMD_COEF_32 wise.
#if __SSE4_1__ || __MIC__
unsigned k;
vtype * W = w;
ARCH_WORD_32 * saved_key = (ARCH_WORD_32 *) _data;
SHA1_PARA_DO(k)
{
if (SSEi_flags & SSEi_4BUF_INPUT)
{
for (i = 0; i < 14; ++i)
{
GATHER_4x(W[i], saved_key, i);
vswap32(W[i]);
}
GATHER_4x(W[14], saved_key, 14);
GATHER_4x(W[15], saved_key, 15);
saved_key += (VS32 << 6);
}
else if (SSEi_flags & SSEi_2BUF_INPUT)
{
for (i = 0; i < 14; ++i)
{
GATHER_2x(W[i], saved_key, i);
vswap32(W[i]);
}
GATHER_2x(W[14], saved_key, 14);
GATHER_2x(W[15], saved_key, 15);
saved_key += (VS32 << 5);
}
else
{
for (i = 0; i < 14; ++i)
{
GATHER(W[i], saved_key, i);
vswap32(W[i]);
}
GATHER(W[14], saved_key, 14);
GATHER(W[15], saved_key, 15);
saved_key += (VS32 << 4);
}
if (((SSEi_flags & SSEi_2BUF_INPUT_FIRST_BLK)
== SSEi_2BUF_INPUT_FIRST_BLK)
|| ((SSEi_flags & SSEi_4BUF_INPUT_FIRST_BLK)
== SSEi_4BUF_INPUT_FIRST_BLK)
|| ((SSEi_flags & SSEi_FLAT_RELOAD_SWAPLAST)
== SSEi_FLAT_RELOAD_SWAPLAST))
{
vswap32(W[14]);
vswap32(W[15]);
}
W += 16;
}
#else
unsigned j, k;
ARCH_WORD_32 * p = (ARCH_WORD_32 *) w;
vtype * W = w;
ARCH_WORD_32 * saved_key = (ARCH_WORD_32 *) _data;
SHA1_PARA_DO(k)
{
if (SSEi_flags & SSEi_4BUF_INPUT)
{
for (j = 0; j < 16; j++)
for (i = 0; i < VS32; i++) *p++ = saved_key[(i << 6) + j];
saved_key += (VS32 << 6);
}
else if (SSEi_flags & SSEi_2BUF_INPUT)
{
for (j = 0; j < 16; j++)
for (i = 0; i < VS32; i++) *p++ = saved_key[(i << 5) + j];
saved_key += (VS32 << 5);
}
else
{
for (j = 0; j < 16; j++)
for (i = 0; i < VS32; i++) *p++ = saved_key[(i << 4) + j];
saved_key += (VS32 << 4);
}
for (i = 0; i < 14; i++) vswap32(W[i]);
if (((SSEi_flags & SSEi_2BUF_INPUT_FIRST_BLK)
== SSEi_2BUF_INPUT_FIRST_BLK)
|| ((SSEi_flags & SSEi_4BUF_INPUT_FIRST_BLK)
== SSEi_4BUF_INPUT_FIRST_BLK)
|| ((SSEi_flags & SSEi_FLAT_RELOAD_SWAPLAST)
== SSEi_FLAT_RELOAD_SWAPLAST))
{
vswap32(W[14]);
vswap32(W[15]);
}
W += 16;
}
#endif
// now set our data pointer to point to this 'mixed' data.
data = w;
}
else
#else
assert((SSEi_flags & SSEi_FLAT_IN) == 0);
#endif
data = _data;
#if 0
if ((SSEi_flags & SSEi_RELOAD) == 0)
{
SHA1_PARA_DO(i)
{
a[i] = vset1_epi32(0x67452301);
b[i] = vset1_epi32(0xefcdab89);
c[i] = vset1_epi32(0x98badcfe);
d[i] = vset1_epi32(0x10325476);
e[i] = vset1_epi32(0xC3D2E1F0);
}
}
else
{
#endif
assert((SSEi_flags & SSEi_RELOAD) != 0);
#if 0
if ((SSEi_flags & SSEi_RELOAD_INP_FMT) == SSEi_RELOAD_INP_FMT)
{
SHA1_PARA_DO(i)
{
a[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 0 * VS32]);
b[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 1 * VS32]);
c[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 2 * VS32]);
d[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 3 * VS32]);
e[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 4 * VS32]);
}
}
else
{
#endif
SHA1_PARA_DO(i)
{
a[i] = vload((vtype *) &reload_state[i * 5 * VS32 + 0 * VS32]);
b[i] = vload((vtype *) &reload_state[i * 5 * VS32 + 1 * VS32]);
c[i] = vload((vtype *) &reload_state[i * 5 * VS32 + 2 * VS32]);
d[i] = vload((vtype *) &reload_state[i * 5 * VS32 + 3 * VS32]);
e[i] = vload((vtype *) &reload_state[i * 5 * VS32 + 4 * VS32]);
}
#if 0
}
#endif
#if 0
}
#endif
cst = vset1_epi32(0x5A827999);
SHA1_ROUND2a(a, b, c, d, e, SHA1_F, 0);
SHA1_ROUND2a(e, a, b, c, d, SHA1_F, 1);
SHA1_ROUND2a(d, e, a, b, c, SHA1_F, 2);
SHA1_ROUND2b(c, d, e, a, b, SHA1_F, 3);
SHA1_ROUND2b(b, c, d, e, a, SHA1_F, 4);
SHA1_ROUND2b(a, b, c, d, e, SHA1_F, 5);
SHA1_ROUND2b(e, a, b, c, d, SHA1_F, 6);
SHA1_ROUND2b(d, e, a, b, c, SHA1_F, 7);
SHA1_ROUND2c(c, d, e, a, b, SHA1_F, 8);
SHA1_ROUND2c(b, c, d, e, a, SHA1_F, 9);
SHA1_ROUND2c(a, b, c, d, e, SHA1_F, 10);
SHA1_ROUND2c(e, a, b, c, d, SHA1_F, 11);
SHA1_ROUND2c(d, e, a, b, c, SHA1_F, 12);
SHA1_ROUND2c(c, d, e, a, b, SHA1_F, 13);
SHA1_ROUND2d(b, c, d, e, a, SHA1_F, 14);
SHA1_ROUND2d(a, b, c, d, e, SHA1_F, 15);
SHA1_ROUND2(e, a, b, c, d, SHA1_F, 16);
SHA1_ROUND2(d, e, a, b, c, SHA1_F, 17);
SHA1_ROUND2(c, d, e, a, b, SHA1_F, 18);
SHA1_ROUND2(b, c, d, e, a, SHA1_F, 19);
cst = vset1_epi32(0x6ED9EBA1);
SHA1_ROUND2(a, b, c, d, e, SHA1_G, 20);
SHA1_ROUND2(e, a, b, c, d, SHA1_G, 21);
SHA1_ROUND2(d, e, a, b, c, SHA1_G, 22);
SHA1_ROUND2(c, d, e, a, b, SHA1_G, 23);
SHA1_ROUND2(b, c, d, e, a, SHA1_G, 24);
SHA1_ROUND2(a, b, c, d, e, SHA1_G, 25);
SHA1_ROUND2(e, a, b, c, d, SHA1_G, 26);
SHA1_ROUND2(d, e, a, b, c, SHA1_G, 27);
SHA1_ROUND2(c, d, e, a, b, SHA1_G, 28);
SHA1_ROUND2(b, c, d, e, a, SHA1_G, 29);
SHA1_ROUND2(a, b, c, d, e, SHA1_G, 30);
SHA1_ROUND2(e, a, b, c, d, SHA1_G, 31);
SHA1_ROUND2(d, e, a, b, c, SHA1_G, 32);
SHA1_ROUND2(c, d, e, a, b, SHA1_G, 33);
SHA1_ROUND2(b, c, d, e, a, SHA1_G, 34);
SHA1_ROUND2(a, b, c, d, e, SHA1_G, 35);
SHA1_ROUND2(e, a, b, c, d, SHA1_G, 36);
SHA1_ROUND2(d, e, a, b, c, SHA1_G, 37);
SHA1_ROUND2(c, d, e, a, b, SHA1_G, 38);
SHA1_ROUND2(b, c, d, e, a, SHA1_G, 39);
cst = vset1_epi32(0x8F1BBCDC);
SHA1_ROUND2(a, b, c, d, e, SHA1_H, 40);
SHA1_ROUND2(e, a, b, c, d, SHA1_H, 41);
SHA1_ROUND2(d, e, a, b, c, SHA1_H, 42);
SHA1_ROUND2(c, d, e, a, b, SHA1_H, 43);
SHA1_ROUND2(b, c, d, e, a, SHA1_H, 44);
SHA1_ROUND2(a, b, c, d, e, SHA1_H, 45);
SHA1_ROUND2(e, a, b, c, d, SHA1_H, 46);
SHA1_ROUND2(d, e, a, b, c, SHA1_H, 47);
SHA1_ROUND2(c, d, e, a, b, SHA1_H, 48);
SHA1_ROUND2(b, c, d, e, a, SHA1_H, 49);
SHA1_ROUND2(a, b, c, d, e, SHA1_H, 50);
SHA1_ROUND2(e, a, b, c, d, SHA1_H, 51);
SHA1_ROUND2(d, e, a, b, c, SHA1_H, 52);
SHA1_ROUND2(c, d, e, a, b, SHA1_H, 53);
SHA1_ROUND2(b, c, d, e, a, SHA1_H, 54);
SHA1_ROUND2(a, b, c, d, e, SHA1_H, 55);
SHA1_ROUND2(e, a, b, c, d, SHA1_H, 56);
SHA1_ROUND2(d, e, a, b, c, SHA1_H, 57);
SHA1_ROUND2(c, d, e, a, b, SHA1_H, 58);
SHA1_ROUND2(b, c, d, e, a, SHA1_H, 59);
cst = vset1_epi32(0xCA62C1D6);
SHA1_ROUND2(a, b, c, d, e, SHA1_I, 60);
SHA1_ROUND2(e, a, b, c, d, SHA1_I, 61);
SHA1_ROUND2(d, e, a, b, c, SHA1_I, 62);
SHA1_ROUND2(c, d, e, a, b, SHA1_I, 63);
SHA1_ROUND2x(b, c, d, e, a, SHA1_I, 64);
SHA1_ROUND2x(a, b, c, d, e, SHA1_I, 65);
SHA1_ROUND2x(e, a, b, c, d, SHA1_I, 66);
SHA1_ROUND2x(d, e, a, b, c, SHA1_I, 67);
SHA1_ROUND2x(c, d, e, a, b, SHA1_I, 68);
SHA1_ROUND2x(b, c, d, e, a, SHA1_I, 69);
SHA1_ROUND2x(a, b, c, d, e, SHA1_I, 70);
SHA1_ROUND2x(e, a, b, c, d, SHA1_I, 71);
SHA1_ROUND2x(d, e, a, b, c, SHA1_I, 72);
SHA1_ROUND2x(c, d, e, a, b, SHA1_I, 73);
SHA1_ROUND2x(b, c, d, e, a, SHA1_I, 74);
SHA1_ROUND2x(a, b, c, d, e, SHA1_I, 75);
#if 0
if (SSEi_flags & SSEi_REVERSE_STEPS)
{
SHA1_PARA_DO(i)
{
vstore((vtype *) &out[i * 5 * VS32 + 4 * VS32], e[i]);
}
return;
}
#endif
SHA1_ROUND2x(e, a, b, c, d, SHA1_I, 76);
SHA1_ROUND2x(d, e, a, b, c, SHA1_I, 77);
SHA1_ROUND2x(c, d, e, a, b, SHA1_I, 78);
SHA1_ROUND2x(b, c, d, e, a, SHA1_I, 79);
#if 0
if ((SSEi_flags & SSEi_RELOAD) == 0)
{
SHA1_PARA_DO(i)
{
a[i] = vadd_epi32(a[i], vset1_epi32(0x67452301));
b[i] = vadd_epi32(b[i], vset1_epi32(0xefcdab89));
c[i] = vadd_epi32(c[i], vset1_epi32(0x98badcfe));
d[i] = vadd_epi32(d[i], vset1_epi32(0x10325476));
e[i] = vadd_epi32(e[i], vset1_epi32(0xC3D2E1F0));
}
}
else
{
if ((SSEi_flags & SSEi_RELOAD_INP_FMT) == SSEi_RELOAD_INP_FMT)
{
SHA1_PARA_DO(i)
{
a[i] = vadd_epi32(
a[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 0 * VS32]));
b[i] = vadd_epi32(
b[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 1 * VS32]));
c[i] = vadd_epi32(
c[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 2 * VS32]));
d[i] = vadd_epi32(
d[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 3 * VS32]));
e[i] = vadd_epi32(
e[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 4 * VS32]));
}
}
else
{
#endif
SHA1_PARA_DO(i)
{
a[i] = vadd_epi32(
a[i], vload((vtype *) &reload_state[i * 5 * VS32 + 0 * VS32]));
b[i] = vadd_epi32(
b[i], vload((vtype *) &reload_state[i * 5 * VS32 + 1 * VS32]));
c[i] = vadd_epi32(
c[i], vload((vtype *) &reload_state[i * 5 * VS32 + 2 * VS32]));
d[i] = vadd_epi32(
d[i], vload((vtype *) &reload_state[i * 5 * VS32 + 3 * VS32]));
e[i] = vadd_epi32(
e[i], vload((vtype *) &reload_state[i * 5 * VS32 + 4 * VS32]));
}
#if 0
}
}
#endif
#if 0
if (SSEi_flags & SSEi_FLAT_OUT)
{
SHA1_PARA_DO(i)
{
uint32_t * o = (uint32_t *) &out[i * 5 * VS32];
#if __AVX512F__ || __MIC__
vtype idxs = vset_epi32(15 * 5,
14 * 5,
13 * 5,
12 * 5,
11 * 5,
10 * 5,
9 * 5,
8 * 5,
7 * 5,
6 * 5,
5 * 5,
4 * 5,
3 * 5,
2 * 5,
1 * 5,
0 * 5);
vscatter_epi32((((uint32_t *) o) + 0), idxs, vswap32(a[i]), 4);
vscatter_epi32((((uint32_t *) o) + 1), idxs, vswap32(b[i]), 4);
vscatter_epi32((((uint32_t *) o) + 2), idxs, vswap32(c[i]), 4);
vscatter_epi32((((uint32_t *) o) + 3), idxs, vswap32(d[i]), 4);
vscatter_epi32((((uint32_t *) o) + 4), idxs, vswap32(e[i]), 4);
#else
uint32_t j, k;
union {
vtype v[5];
uint32_t s[5 * VS32];
} tmp;
tmp.v[0] = vswap32(a[i]);
tmp.v[1] = vswap32(b[i]);
tmp.v[2] = vswap32(c[i]);
tmp.v[3] = vswap32(d[i]);
tmp.v[4] = vswap32(e[i]);
for (j = 0; j < VS32; j++)
for (k = 0; k < 5; k++) o[j * 5 + k] = tmp.s[k * VS32 + j];
#endif
}
}
else if (SSEi_flags & SSEi_OUTPUT_AS_INP_FMT)
{
if ((SSEi_flags & SSEi_OUTPUT_AS_2BUF_INP_FMT)
== SSEi_OUTPUT_AS_2BUF_INP_FMT)
{
SHA1_PARA_DO(i)
{
vstore((vtype *) &out[i * 32 * VS32 + 0 * VS32], a[i]);
vstore((vtype *) &out[i * 32 * VS32 + 1 * VS32], b[i]);
vstore((vtype *) &out[i * 32 * VS32 + 2 * VS32], c[i]);
vstore((vtype *) &out[i * 32 * VS32 + 3 * VS32], d[i]);
vstore((vtype *) &out[i * 32 * VS32 + 4 * VS32], e[i]);
}
}
else
{
#endif
assert((SSEi_flags & SSEi_OUTPUT_AS_INP_FMT) != 0
&& (SSEi_flags & SSEi_OUTPUT_AS_2BUF_INP_FMT)
!= SSEi_OUTPUT_AS_2BUF_INP_FMT);
SHA1_PARA_DO(i)
{
vstore((vtype *) &out[i * 16 * VS32 + 0 * VS32], a[i]);
vstore((vtype *) &out[i * 16 * VS32 + 1 * VS32], b[i]);
vstore((vtype *) &out[i * 16 * VS32 + 2 * VS32], c[i]);
vstore((vtype *) &out[i * 16 * VS32 + 3 * VS32], d[i]);
vstore((vtype *) &out[i * 16 * VS32 + 4 * VS32], e[i]);
}
#if 0
}
}
else
{
SHA1_PARA_DO(i)
{
vstore((vtype *) &out[i * 5 * VS32 + 0 * VS32], a[i]);
vstore((vtype *) &out[i * 5 * VS32 + 1 * VS32], b[i]);
vstore((vtype *) &out[i * 5 * VS32 + 2 * VS32], c[i]);
vstore((vtype *) &out[i * 5 * VS32 + 3 * VS32], d[i]);
vstore((vtype *) &out[i * 5 * VS32 + 4 * VS32], e[i]);
}
}
#endif
#if defined(__AVX2__) || defined(__AVX512F__)
/* The fix for known issues with mixing AVX2+ and SSE. */
_mm256_zeroupper();
#endif
}
#endif /* SIMD_PARA_SHA1 */
#if SIMD_PARA_SHA256
/*
* These optimized Sigma alternatives are from "Fast SHA-256 Implementations
* on Intel Architecture Processors" whitepaper by Intel. They should result
* in less register copy operations but in our case they definitely cause a
* regression. Not sure why.
*/
#if 0
#define S0(x) \
vroti_epi32(vxor(vroti_epi32(vxor(vroti_epi32(x, -9), x), -11), x), -2)
#define S1(x) \
vroti_epi32(vxor(vroti_epi32(vxor(vroti_epi32(x, -14), x), -5), x), -6)
#else
#define S0(x) \
(vxor(vroti_epi32(x, -22), vxor(vroti_epi32(x, -2), vroti_epi32(x, -13))))
#define S1(x) \
(vxor(vroti_epi32(x, -25), vxor(vroti_epi32(x, -6), vroti_epi32(x, -11))))
#endif
#define s0(x) \
(vxor(vsrli_epi32(x, 3), vxor(vroti_epi32(x, -7), vroti_epi32(x, -18))))
#define s1(x) \
(vxor(vsrli_epi32(x, 10), vxor(vroti_epi32(x, -17), vroti_epi32(x, -19))))
#if __AVX512F__
#define Maj(x, y, z) vternarylogic(x, y, z, 0xE8)
#elif !VCMOV_EMULATED
#define Maj(x, y, z) vcmov(x, y, vxor(z, y))
#else
#define Maj(x, y, z) vor(vand(x, y), vand(vor(x, y), z))
#endif
#define Ch(x, y, z) vcmov(y, z, x)
#undef R
#define R(t) \
{ \
tmp1[i] = vadd_epi32(s1(w[(t - 2) & 0xf]), w[(t - 7) & 0xf]); \
tmp2[i] = vadd_epi32(s0(w[(t - 15) & 0xf]), w[(t - 16) & 0xf]); \
w[(t) &0xf] = vadd_epi32(tmp1[i], tmp2[i]); \
}
#define SHA256_PARA_DO(x) for (x = 0; x < SIMD_PARA_SHA256; ++x)
#define SHA256_STEP(a, b, c, d, e, f, g, h, x, K) \
{ \
SHA256_PARA_DO(i) \
{ \
w = _w[i].w; \
tmp1[i] = vadd_epi32(h[i], S1(e[i])); \
tmp1[i] = vadd_epi32(tmp1[i], Ch(e[i], f[i], g[i])); \
tmp1[i] = vadd_epi32(tmp1[i], vset1_epi32(K)); \
tmp1[i] = vadd_epi32(tmp1[i], w[(x) &0xf]); \
tmp2[i] = vadd_epi32(S0(a[i]), Maj(a[i], b[i], c[i])); \
d[i] = vadd_epi32(tmp1[i], d[i]); \
h[i] = vadd_epi32(tmp1[i], tmp2[i]); \
if (x < 48) R(x); \
} \
}
#define INIT_A 0x6a09e667
#define INIT_B 0xbb67ae85
#define INIT_C 0x3c6ef372
#define INIT_D 0xa54ff53a
#define INIT_E 0x510e527f
#define INIT_F 0x9b05688c
#define INIT_G 0x1f83d9ab
#define INIT_H 0x5be0cd19
#define ror(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
void sha256_reverse(uint32_t * hash)
{
uint32_t a, b, c, d, e, f, g, h, s0, maj, tmp;
a = hash[0] - INIT_A;
b = hash[1] - INIT_B;
c = hash[2] - INIT_C;
d = hash[3] - INIT_D;
e = hash[4] - INIT_E;
f = hash[5] - INIT_F;
g = hash[6] - INIT_G;
h = hash[7] - INIT_H;
s0 = ror(b, 2) ^ ror(b, 13) ^ ror(b, 22);
maj = (b & c) ^ (b & d) ^ (c & d);
tmp = d;
d = e - (a - (s0 + maj));
e = f;
f = g;
g = h;
a = b;
b = c;
c = tmp;
s0 = ror(b, 2) ^ ror(b, 13) ^ ror(b, 22);
maj = (b & c) ^ (b & d) ^ (c & d);
tmp = d;
d = e - (a - (s0 + maj));
e = f;
f = g;
a = b;
b = c;
c = tmp;
s0 = ror(b, 2) ^ ror(b, 13) ^ ror(b, 22);
maj = (b & c) ^ (b & d) ^ (c & d);
tmp = d;
d = e - (a - (s0 + maj));
e = f;
a = b;
b = c;
c = tmp;
s0 = ror(b, 2) ^ ror(b, 13) ^ ror(b, 22);
maj = (b & c) ^ (b & d) ^ (c & d);
hash[0] = e - (a - (s0 + maj));
}
void sha256_unreverse(void)
{
fprintf(stderr, "sha256_unreverse() not implemented\n");
perror("sha256_unreverse");
}
#undef ror
#undef INIT_H
#undef INIT_G
#undef INIT_F
#undef INIT_E
#undef INIT_D
#undef INIT_C
#undef INIT_B
#undef INIT_A
#define INIT_D 0xf70e5939
void sha224_reverse(uint32_t * hash) { hash[3] -= INIT_D; }
void sha224_unreverse(uint32_t * hash) { hash[3] += INIT_D; }
#undef INIT_D
void SIMDSHA256body(vtype * data,
ARCH_WORD_32 * out,
ARCH_WORD_32 * reload_state,
unsigned SSEi_flags)
{
vtype a[SIMD_PARA_SHA256], b[SIMD_PARA_SHA256], c[SIMD_PARA_SHA256],
d[SIMD_PARA_SHA256], e[SIMD_PARA_SHA256], f[SIMD_PARA_SHA256],
g[SIMD_PARA_SHA256], h[SIMD_PARA_SHA256];
union {
vtype w[16];
ARCH_WORD_32 p[16 * sizeof(vtype) / sizeof(ARCH_WORD_32)];
} _w[SIMD_PARA_SHA256];
vtype tmp1[SIMD_PARA_SHA256], tmp2[SIMD_PARA_SHA256], *w = NULL;
ARCH_WORD_32 * saved_key = 0;
unsigned int i, k;
if (SSEi_flags & SSEi_FLAT_IN)
{
#if __SSE4_1__ || __MIC__
saved_key = (ARCH_WORD_32 *) data;
SHA256_PARA_DO(k)
{
w = _w[k].w;
if (SSEi_flags & SSEi_4BUF_INPUT)
{
for (i = 0; i < 14; ++i)
{
GATHER_4x(w[i], saved_key, i);
vswap32(w[i]);
}
GATHER_4x(w[14], saved_key, 14);
GATHER_4x(w[15], saved_key, 15);
saved_key += (VS32 << 6);
}
else if (SSEi_flags & SSEi_2BUF_INPUT)
{
for (i = 0; i < 14; ++i)
{
GATHER_2x(w[i], saved_key, i);
vswap32(w[i]);
}
GATHER_2x(w[14], saved_key, 14);
GATHER_2x(w[15], saved_key, 15);
saved_key += (VS32 << 5);
}
else
{
for (i = 0; i < 14; ++i)
{
GATHER(w[i], saved_key, i);
vswap32(w[i]);
}
GATHER(w[14], saved_key, 14);
GATHER(w[15], saved_key, 15);
saved_key += (VS32 << 4);
}
if (((SSEi_flags & SSEi_2BUF_INPUT_FIRST_BLK)
== SSEi_2BUF_INPUT_FIRST_BLK)
|| ((SSEi_flags & SSEi_4BUF_INPUT_FIRST_BLK)
== SSEi_4BUF_INPUT_FIRST_BLK)
|| ((SSEi_flags & SSEi_FLAT_RELOAD_SWAPLAST)
== SSEi_FLAT_RELOAD_SWAPLAST))
{
vswap32(w[14]);
vswap32(w[15]);
}
}
#else
unsigned int j;
saved_key = (ARCH_WORD_32 *) data;
SHA256_PARA_DO(k)
{
ARCH_WORD_32 * p = _w[k].p;
w = _w[k].w;
if (SSEi_flags & SSEi_4BUF_INPUT)
{
for (j = 0; j < 16; j++)
for (i = 0; i < VS32; i++) *p++ = saved_key[(i << 6) + j];
saved_key += (VS32 << 6);
}
else if (SSEi_flags & SSEi_2BUF_INPUT)
{
for (j = 0; j < 16; j++)
for (i = 0; i < VS32; i++) *p++ = saved_key[(i << 5) + j];
saved_key += (VS32 << 5);
}
else
{
for (j = 0; j < 16; j++)
for (i = 0; i < VS32; i++) *p++ = saved_key[(i << 4) + j];
saved_key += (VS32 << 4);
}
for (i = 0; i < 14; i++) vswap32(w[i]);
if (((SSEi_flags & SSEi_2BUF_INPUT_FIRST_BLK)
== SSEi_2BUF_INPUT_FIRST_BLK)
|| ((SSEi_flags & SSEi_4BUF_INPUT_FIRST_BLK)
== SSEi_4BUF_INPUT_FIRST_BLK)
|| ((SSEi_flags & SSEi_FLAT_RELOAD_SWAPLAST)
== SSEi_FLAT_RELOAD_SWAPLAST))
{
vswap32(w[14]);
vswap32(w[15]);
}
}
#endif
}
else
memcpy(_w, data, 16 * sizeof(vtype) * SIMD_PARA_SHA256);
// dump_stuff_shammx(w, 64, 0);
if (SSEi_flags & SSEi_RELOAD)
{
if ((SSEi_flags & SSEi_RELOAD_INP_FMT) == SSEi_RELOAD_INP_FMT)
{
SHA256_PARA_DO(i)
{
a[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 0 * VS32]);
b[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 1 * VS32]);
c[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 2 * VS32]);
d[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 3 * VS32]);
e[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 4 * VS32]);
f[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 5 * VS32]);
g[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 6 * VS32]);
h[i] = vload((vtype *) &reload_state[i * 16 * VS32 + 7 * VS32]);
}
}
else
{
SHA256_PARA_DO(i)
{
a[i] = vload((vtype *) &reload_state[i * 8 * VS32 + 0 * VS32]);
b[i] = vload((vtype *) &reload_state[i * 8 * VS32 + 1 * VS32]);
c[i] = vload((vtype *) &reload_state[i * 8 * VS32 + 2 * VS32]);
d[i] = vload((vtype *) &reload_state[i * 8 * VS32 + 3 * VS32]);
e[i] = vload((vtype *) &reload_state[i * 8 * VS32 + 4 * VS32]);
f[i] = vload((vtype *) &reload_state[i * 8 * VS32 + 5 * VS32]);
g[i] = vload((vtype *) &reload_state[i * 8 * VS32 + 6 * VS32]);
h[i] = vload((vtype *) &reload_state[i * 8 * VS32 + 7 * VS32]);
}
}
}
else
{
if (SSEi_flags & SSEi_CRYPT_SHA224)
{
SHA256_PARA_DO(i)
{
/* SHA-224 IV */
a[i] = vset1_epi32(0xc1059ed8);
b[i] = vset1_epi32(0x367cd507);
c[i] = vset1_epi32(0x3070dd17);
d[i] = vset1_epi32(0xf70e5939);
e[i] = vset1_epi32(0xffc00b31);
f[i] = vset1_epi32(0x68581511);
g[i] = vset1_epi32(0x64f98fa7);
h[i] = vset1_epi32(0xbefa4fa4);
}
}
else
{
SHA256_PARA_DO(i)
{
// SHA-256 IV */
a[i] = vset1_epi32(0x6a09e667);
b[i] = vset1_epi32(0xbb67ae85);
c[i] = vset1_epi32(0x3c6ef372);
d[i] = vset1_epi32(0xa54ff53a);
e[i] = vset1_epi32(0x510e527f);
f[i] = vset1_epi32(0x9b05688c);
g[i] = vset1_epi32(0x1f83d9ab);
h[i] = vset1_epi32(0x5be0cd19);
}
}
}
SHA256_STEP(a, b, c, d, e, f, g, h, 0, 0x428a2f98);
SHA256_STEP(h, a, b, c, d, e, f, g, 1, 0x71374491);
SHA256_STEP(g, h, a, b, c, d, e, f, 2, 0xb5c0fbcf);
SHA256_STEP(f, g, h, a, b, c, d, e, 3, 0xe9b5dba5);
SHA256_STEP(e, f, g, h, a, b, c, d, 4, 0x3956c25b);
SHA256_STEP(d, e, f, g, h, a, b, c, 5, 0x59f111f1);
SHA256_STEP(c, d, e, f, g, h, a, b, 6, 0x923f82a4);
SHA256_STEP(b, c, d, e, f, g, h, a, 7, 0xab1c5ed5);
SHA256_STEP(a, b, c, d, e, f, g, h, 8, 0xd807aa98);
SHA256_STEP(h, a, b, c, d, e, f, g, 9, 0x12835b01);
SHA256_STEP(g, h, a, b, c, d, e, f, 10, 0x243185be);
SHA256_STEP(f, g, h, a, b, c, d, e, 11, 0x550c7dc3);
SHA256_STEP(e, f, g, h, a, b, c, d, 12, 0x72be5d74);
SHA256_STEP(d, e, f, g, h, a, b, c, 13, 0x80deb1fe);
SHA256_STEP(c, d, e, f, g, h, a, b, 14, 0x9bdc06a7);
SHA256_STEP(b, c, d, e, f, g, h, a, 15, 0xc19bf174);
SHA256_STEP(a, b, c, d, e, f, g, h, 16, 0xe49b69c1);
SHA256_STEP(h, a, b, c, d, e, f, g, 17, 0xefbe4786);
SHA256_STEP(g, h, a, b, c, d, e, f, 18, 0x0fc19dc6);
SHA256_STEP(f, g, h, a, b, c, d, e, 19, 0x240ca1cc);
SHA256_STEP(e, f, g, h, a, b, c, d, 20, 0x2de92c6f);
SHA256_STEP(d, e, f, g, h, a, b, c, 21, 0x4a7484aa);
SHA256_STEP(c, d, e, f, g, h, a, b, 22, 0x5cb0a9dc);
SHA256_STEP(b, c, d, e, f, g, h, a, 23, 0x76f988da);
SHA256_STEP(a, b, c, d, e, f, g, h, 24, 0x983e5152);
SHA256_STEP(h, a, b, c, d, e, f, g, 25, 0xa831c66d);
SHA256_STEP(g, h, a, b, c, d, e, f, 26, 0xb00327c8);
SHA256_STEP(f, g, h, a, b, c, d, e, 27, 0xbf597fc7);
SHA256_STEP(e, f, g, h, a, b, c, d, 28, 0xc6e00bf3);
SHA256_STEP(d, e, f, g, h, a, b, c, 29, 0xd5a79147);
SHA256_STEP(c, d, e, f, g, h, a, b, 30, 0x06ca6351);
SHA256_STEP(b, c, d, e, f, g, h, a, 31, 0x14292967);
SHA256_STEP(a, b, c, d, e, f, g, h, 32, 0x27b70a85);
SHA256_STEP(h, a, b, c, d, e, f, g, 33, 0x2e1b2138);
SHA256_STEP(g, h, a, b, c, d, e, f, 34, 0x4d2c6dfc);
SHA256_STEP(f, g, h, a, b, c, d, e, 35, 0x53380d13);
SHA256_STEP(e, f, g, h, a, b, c, d, 36, 0x650a7354);
SHA256_STEP(d, e, f, g, h, a, b, c, 37, 0x766a0abb);
SHA256_STEP(c, d, e, f, g, h, a, b, 38, 0x81c2c92e);
SHA256_STEP(b, c, d, e, f, g, h, a, 39, 0x92722c85);
SHA256_STEP(a, b, c, d, e, f, g, h, 40, 0xa2bfe8a1);
SHA256_STEP(h, a, b, c, d, e, f, g, 41, 0xa81a664b);
SHA256_STEP(g, h, a, b, c, d, e, f, 42, 0xc24b8b70);
SHA256_STEP(f, g, h, a, b, c, d, e, 43, 0xc76c51a3);
SHA256_STEP(e, f, g, h, a, b, c, d, 44, 0xd192e819);
SHA256_STEP(d, e, f, g, h, a, b, c, 45, 0xd6990624);
SHA256_STEP(c, d, e, f, g, h, a, b, 46, 0xf40e3585);
SHA256_STEP(b, c, d, e, f, g, h, a, 47, 0x106aa070);
SHA256_STEP(a, b, c, d, e, f, g, h, 48, 0x19a4c116);
SHA256_STEP(h, a, b, c, d, e, f, g, 49, 0x1e376c08);
SHA256_STEP(g, h, a, b, c, d, e, f, 50, 0x2748774c);
SHA256_STEP(f, g, h, a, b, c, d, e, 51, 0x34b0bcb5);
SHA256_STEP(e, f, g, h, a, b, c, d, 52, 0x391c0cb3);
SHA256_STEP(d, e, f, g, h, a, b, c, 53, 0x4ed8aa4a);
SHA256_STEP(c, d, e, f, g, h, a, b, 54, 0x5b9cca4f);
SHA256_STEP(b, c, d, e, f, g, h, a, 55, 0x682e6ff3);
SHA256_STEP(a, b, c, d, e, f, g, h, 56, 0x748f82ee);
if (SSEi_flags & SSEi_REVERSE_STEPS && !(SSEi_flags & SSEi_CRYPT_SHA224))
{
SHA256_PARA_DO(i)
{
vstore((vtype *) &(out[i * 8 * VS32 + 0 * VS32]), h[i]);
}
return;
}
SHA256_STEP(h, a, b, c, d, e, f, g, 57, 0x78a5636f);
SHA256_STEP(g, h, a, b, c, d, e, f, 58, 0x84c87814);
SHA256_STEP(f, g, h, a, b, c, d, e, 59, 0x8cc70208);
SHA256_STEP(e, f, g, h, a, b, c, d, 60, 0x90befffa);
if (SSEi_flags & SSEi_REVERSE_STEPS)
{
SHA256_PARA_DO(i)
{
vstore((vtype *) &(out[i * 8 * VS32 + 3 * VS32]), d[i]);
}
return;
}
SHA256_STEP(d, e, f, g, h, a, b, c, 61, 0xa4506ceb);
SHA256_STEP(c, d, e, f, g, h, a, b, 62, 0xbef9a3f7);
SHA256_STEP(b, c, d, e, f, g, h, a, 63, 0xc67178f2);
if (SSEi_flags & SSEi_RELOAD)
{
if ((SSEi_flags & SSEi_RELOAD_INP_FMT) == SSEi_RELOAD_INP_FMT)
{
SHA256_PARA_DO(i)
{
a[i] = vadd_epi32(
a[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 0 * VS32]));
b[i] = vadd_epi32(
b[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 1 * VS32]));
c[i] = vadd_epi32(
c[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 2 * VS32]));
d[i] = vadd_epi32(
d[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 3 * VS32]));
e[i] = vadd_epi32(
e[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 4 * VS32]));
f[i] = vadd_epi32(
f[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 5 * VS32]));
g[i] = vadd_epi32(
g[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 6 * VS32]));
h[i] = vadd_epi32(
h[i],
vload((vtype *) &reload_state[i * 16 * VS32 + 7 * VS32]));
}
}
else
{
SHA256_PARA_DO(i)
{
a[i] = vadd_epi32(
a[i],
vload((vtype *) &reload_state[i * 8 * VS32 + 0 * VS32]));
b[i] = vadd_epi32(
b[i],
vload((vtype *) &reload_state[i * 8 * VS32 + 1 * VS32]));
c[i] = vadd_epi32(
c[i],
vload((vtype *) &reload_state[i * 8 * VS32 + 2 * VS32]));
d[i] = vadd_epi32(
d[i],
vload((vtype *) &reload_state[i * 8 * VS32 + 3 * VS32]));
e[i] = vadd_epi32(
e[i],
vload((vtype *) &reload_state[i * 8 * VS32 + 4 * VS32]));
f[i] = vadd_epi32(
f[i],
vload((vtype *) &reload_state[i * 8 * VS32 + 5 * VS32]));
g[i] = vadd_epi32(
g[i],
vload((vtype *) &reload_state[i * 8 * VS32 + 6 * VS32]));
h[i] = vadd_epi32(
h[i],
vload((vtype *) &reload_state[i * 8 * VS32 + 7 * VS32]));
}
}
}
else
{
if (SSEi_flags & SSEi_CRYPT_SHA224)
{
SHA256_PARA_DO(i)
{
/* SHA-224 IV */
a[i] = vadd_epi32(a[i], vset1_epi32(0xc1059ed8));
b[i] = vadd_epi32(b[i], vset1_epi32(0x367cd507));
c[i] = vadd_epi32(c[i], vset1_epi32(0x3070dd17));
d[i] = vadd_epi32(d[i], vset1_epi32(0xf70e5939));
e[i] = vadd_epi32(e[i], vset1_epi32(0xffc00b31));
f[i] = vadd_epi32(f[i], vset1_epi32(0x68581511));
g[i] = vadd_epi32(g[i], vset1_epi32(0x64f98fa7));
h[i] = vadd_epi32(h[i], vset1_epi32(0xbefa4fa4));
}
}
else
{
SHA256_PARA_DO(i)
{
/* SHA-256 IV */
a[i] = vadd_epi32(a[i], vset1_epi32(0x6a09e667));
b[i] = vadd_epi32(b[i], vset1_epi32(0xbb67ae85));
c[i] = vadd_epi32(c[i], vset1_epi32(0x3c6ef372));
d[i] = vadd_epi32(d[i], vset1_epi32(0xa54ff53a));
e[i] = vadd_epi32(e[i], vset1_epi32(0x510e527f));
f[i] = vadd_epi32(f[i], vset1_epi32(0x9b05688c));
g[i] = vadd_epi32(g[i], vset1_epi32(0x1f83d9ab));
h[i] = vadd_epi32(h[i], vset1_epi32(0x5be0cd19));
}
}
}
if (SSEi_flags & SSEi_FLAT_OUT)
{
SHA256_PARA_DO(i)
{
uint32_t * o = (uint32_t *) &out[i * 8 * VS32];
#if __AVX512F__ || __MIC__
vtype idxs = vset_epi32(15 << 3,
14 << 3,
13 << 3,
12 << 3,
11 << 3,
10 << 3,
9 << 3,
8 << 3,
7 << 3,
6 << 3,
5 << 3,
4 << 3,
3 << 3,
2 << 3,
1 << 3,
0 << 3);
vscatter_epi32((((uint32_t *) o) + 0), idxs, vswap32(a[i]), 4);
vscatter_epi32((((uint32_t *) o) + 1), idxs, vswap32(b[i]), 4);
vscatter_epi32((((uint32_t *) o) + 2), idxs, vswap32(c[i]), 4);
vscatter_epi32((((uint32_t *) o) + 3), idxs, vswap32(d[i]), 4);
vscatter_epi32((((uint32_t *) o) + 4), idxs, vswap32(e[i]), 4);
vscatter_epi32((((uint32_t *) o) + 5), idxs, vswap32(f[i]), 4);
vscatter_epi32((((uint32_t *) o) + 6), idxs, vswap32(g[i]), 4);
vscatter_epi32((((uint32_t *) o) + 7), idxs, vswap32(h[i]), 4);
#else
uint32_t j, k;
union {
vtype v[8];
uint32_t s[8 * VS32];
} tmp;
tmp.v[0] = vswap32(a[i]);
tmp.v[1] = vswap32(b[i]);
tmp.v[2] = vswap32(c[i]);
tmp.v[3] = vswap32(d[i]);
tmp.v[4] = vswap32(e[i]);
tmp.v[5] = vswap32(f[i]);
tmp.v[6] = vswap32(g[i]);
tmp.v[7] = vswap32(h[i]);
for (j = 0; j < VS32; j++)
for (k = 0; k < 8; k++) o[j * 8 + k] = tmp.s[k * VS32 + j];
#endif
}
}
else if (SSEi_flags & SSEi_OUTPUT_AS_INP_FMT)
{
if ((SSEi_flags & SSEi_OUTPUT_AS_2BUF_INP_FMT)
== SSEi_OUTPUT_AS_2BUF_INP_FMT)
{
SHA256_PARA_DO(i)
{
vstore((vtype *) &out[i * 32 * VS32 + 0 * VS32], a[i]);
vstore((vtype *) &out[i * 32 * VS32 + 1 * VS32], b[i]);
vstore((vtype *) &out[i * 32 * VS32 + 2 * VS32], c[i]);
vstore((vtype *) &out[i * 32 * VS32 + 3 * VS32], d[i]);
vstore((vtype *) &out[i * 32 * VS32 + 4 * VS32], e[i]);
vstore((vtype *) &out[i * 32 * VS32 + 5 * VS32], f[i]);
vstore((vtype *) &out[i * 32 * VS32 + 6 * VS32], g[i]);
vstore((vtype *) &out[i * 32 * VS32 + 7 * VS32], h[i]);
}
}
else
{
SHA256_PARA_DO(i)
{
vstore((vtype *) &out[i * 16 * VS32 + 0 * VS32], a[i]);
vstore((vtype *) &out[i * 16 * VS32 + 1 * VS32], b[i]);
vstore((vtype *) &out[i * 16 * VS32 + 2 * VS32], c[i]);
vstore((vtype *) &out[i * 16 * VS32 + 3 * VS32], d[i]);
vstore((vtype *) &out[i * 16 * VS32 + 4 * VS32], e[i]);
vstore((vtype *) &out[i * 16 * VS32 + 5 * VS32], f[i]);
vstore((vtype *) &out[i * 16 * VS32 + 6 * VS32], g[i]);
vstore((vtype *) &out[i * 16 * VS32 + 7 * VS32], h[i]);
}
}
}
else
{
SHA256_PARA_DO(i)
{
vstore((vtype *) &(out[i * 8 * VS32 + 0 * VS32]), a[i]);
vstore((vtype *) &(out[i * 8 * VS32 + 1 * VS32]), b[i]);
vstore((vtype *) &(out[i * 8 * VS32 + 2 * VS32]), c[i]);
vstore((vtype *) &(out[i * 8 * VS32 + 3 * VS32]), d[i]);
vstore((vtype *) &(out[i * 8 * VS32 + 4 * VS32]), e[i]);
vstore((vtype *) &(out[i * 8 * VS32 + 5 * VS32]), f[i]);
vstore((vtype *) &(out[i * 8 * VS32 + 6 * VS32]), g[i]);
vstore((vtype *) &(out[i * 8 * VS32 + 7 * VS32]), h[i]);
}
}
}
#endif /* SIMD_PARA_SHA256 */
#if SIMD_PARA_SHA512
#undef S0
#define S0(x) \
(vxor(vroti_epi64(x, -39), vxor(vroti_epi64(x, -28), vroti_epi64(x, -34))))
#undef S1
#define S1(x) \
(vxor(vroti_epi64(x, -41), vxor(vroti_epi64(x, -14), vroti_epi64(x, -18))))
/*
* These optimized sigma alternatives are from "Fast SHA-512 Implementations
* on Intel Architecture Processors" whitepaper by Intel. They result in less
* register copy operations so is faster despite using more ops. Slight boost
* indeed seen on intel core i7.
*/
#if 1
#undef s0
#define s0(x) \
(vxor(vsrli_epi64(vxor(vsrli_epi64(vxor(vsrli_epi64(x, 1), x), 6), x), 1), \
vslli_epi64(vxor(vslli_epi64(x, 7), x), 56)))
#undef s1
#define s1(x) \
(vxor( \
vsrli_epi64(vxor(vsrli_epi64(vxor(vsrli_epi64(x, 42), x), 13), x), 6), \
vslli_epi64(vxor(vslli_epi64(x, 42), x), 3)))
#else
#undef s0
#define s0(x) \
(vxor(vsrli_epi64(x, 7), vxor(vroti_epi64(x, -1), vroti_epi64(x, -8))))
#undef s1
#define s1(x) \
(vxor(vsrli_epi64(x, 6), vxor(vroti_epi64(x, -19), vroti_epi64(x, -61))))
#endif
#if __AVX512F__
#define Maj(x, y, z) vternarylogic(x, y, z, 0xE8)
#elif !VCMOV_EMULATED
#define Maj(x, y, z) vcmov(x, y, vxor(z, y))
#else
#define Maj(x, y, z) vor(vand(x, y), vand(vor(x, y), z))
#endif
#define Ch(x, y, z) vcmov(y, z, x)
#define SHA512_PARA_DO(x) for (x = 0; x < SIMD_PARA_SHA512; ++x)
#undef R
#define R(t) \
{ \
tmp1[i] = vadd_epi64(s1(w[i][(t - 2) & 0xf]), w[i][(t - 7) & 0xf]); \
tmp2[i] = vadd_epi64(s0(w[i][(t - 15) & 0xf]), w[i][(t - 16) & 0xf]); \
w[i][(t) &0xf] = vadd_epi64(tmp1[i], tmp2[i]); \
}
#define SHA512_STEP(a, b, c, d, e, f, g, h, x, K) \
{ \
SHA512_PARA_DO(i) \
{ \
tmp1[i] = vadd_epi64(h[i], w[i][(x) &0xf]); \
tmp2[i] = vadd_epi64(S1(e[i]), vset1_epi64(K)); \
tmp1[i] = vadd_epi64(tmp1[i], Ch(e[i], f[i], g[i])); \
tmp1[i] = vadd_epi64(tmp1[i], tmp2[i]); \
tmp2[i] = vadd_epi64(S0(a[i]), Maj(a[i], b[i], c[i])); \
d[i] = vadd_epi64(tmp1[i], d[i]); \
h[i] = vadd_epi64(tmp1[i], tmp2[i]); \
if (x < 64) R(x); \
} \
}
#define INIT_A 0x6a09e667f3bcc908ULL
#define INIT_B 0xbb67ae8584caa73bULL
#define INIT_C 0x3c6ef372fe94f82bULL
#define INIT_D 0xa54ff53a5f1d36f1ULL
#define INIT_E 0x510e527fade682d1ULL
#define INIT_F 0x9b05688c2b3e6c1fULL
#define INIT_G 0x1f83d9abfb41bd6bULL
#define INIT_H 0x5be0cd19137e2179ULL
#define ror(x, n) (((x) >> (n)) | ((x) << (64 - (n))))
void sha512_reverse(uint64_t * hash)
{
uint64_t a, b, c, d, e, f, g, h, s0, maj, tmp;
a = hash[0] - INIT_A;
b = hash[1] - INIT_B;
c = hash[2] - INIT_C;
d = hash[3] - INIT_D;
e = hash[4] - INIT_E;
f = hash[5] - INIT_F;
g = hash[6] - INIT_G;
h = hash[7] - INIT_H;
s0 = ror(b, 28) ^ ror(b, 34) ^ ror(b, 39);
maj = (b & c) ^ (b & d) ^ (c & d);
tmp = d;
d = e - (a - (s0 + maj));
e = f;
f = g;
g = h;
a = b;
b = c;
c = tmp;
s0 = ror(b, 28) ^ ror(b, 34) ^ ror(b, 39);
maj = (b & c) ^ (b & d) ^ (c & d);
tmp = d;
d = e - (a - (s0 + maj));
e = f;
f = g;
a = b;
b = c;
c = tmp;
s0 = ror(b, 28) ^ ror(b, 34) ^ ror(b, 39);
maj = (b & c) ^ (b & d) ^ (c & d);
tmp = d;
d = e - (a - (s0 + maj));
e = f;
a = b;
b = c;
c = tmp;
s0 = ror(b, 28) ^ ror(b, 34) ^ ror(b, 39);
maj = (b & c) ^ (b & d) ^ (c & d);
hash[0] = e - (a - (s0 + maj));
}
void sha512_unreverse(void)
{
fprintf(stderr, "sha512_unreverse() not implemented\n");
perror("sha512");
}
#undef ror
#undef INIT_H
#undef INIT_G
#undef INIT_F
#undef INIT_E
#undef INIT_D
#undef INIT_C
#undef INIT_B
#undef INIT_A
#define INIT_D 0x152fecd8f70e5939ULL
void sha384_reverse(ARCH_WORD_64 * hash) { hash[3] -= INIT_D; }
void sha384_unreverse(ARCH_WORD_64 * hash) { hash[3] += INIT_D; }
#undef INIT_D
void SIMDSHA512body(vtype * data,
ARCH_WORD_64 * out,
ARCH_WORD_64 * reload_state,
unsigned SSEi_flags)
{
unsigned int i, k;
vtype a[SIMD_PARA_SHA512], b[SIMD_PARA_SHA512], c[SIMD_PARA_SHA512],
d[SIMD_PARA_SHA512], e[SIMD_PARA_SHA512], f[SIMD_PARA_SHA512],
g[SIMD_PARA_SHA512], h[SIMD_PARA_SHA512];
vtype w[SIMD_PARA_SHA512][16];
vtype tmp1[SIMD_PARA_SHA512], tmp2[SIMD_PARA_SHA512];
if (SSEi_flags & SSEi_FLAT_IN)
{
ARCH_WORD_64 * _data = (ARCH_WORD_64 *) data;
SHA512_PARA_DO(k)
{
if (SSEi_flags & SSEi_2BUF_INPUT)
{
ARCH_WORD_64(*saved_key)[32] = (ARCH_WORD_64(*)[32]) _data;
for (i = 0; i < 14; i += 2)
{
GATHER64(tmp1[k], saved_key, i);
GATHER64(tmp2[k], saved_key, i + 1);
vswap64(tmp1[k]);
vswap64(tmp2[k]);
w[k][i] = tmp1[k];
w[k][i + 1] = tmp2[k];
}
GATHER64(tmp1[k], saved_key, 14);
GATHER64(tmp2[k], saved_key, 15);
_data += (VS64 << 5);
}
else
{
ARCH_WORD_64(*saved_key)[16] = (ARCH_WORD_64(*)[16]) _data;
for (i = 0; i < 14; i += 2)
{
GATHER64(tmp1[k], saved_key, i);
GATHER64(tmp2[k], saved_key, i + 1);
vswap64(tmp1[k]);
vswap64(tmp2[k]);
w[k][i] = tmp1[k];
w[k][i + 1] = tmp2[k];
}
GATHER64(tmp1[k], saved_key, 14);
GATHER64(tmp2[k], saved_key, 15);
_data += (VS64 << 4);
}
if (((SSEi_flags & SSEi_2BUF_INPUT_FIRST_BLK)
== SSEi_2BUF_INPUT_FIRST_BLK)
|| ((SSEi_flags & SSEi_FLAT_RELOAD_SWAPLAST)
== SSEi_FLAT_RELOAD_SWAPLAST))
{
vswap64(tmp1[k]);
vswap64(tmp2[k]);
}
w[k][14] = tmp1[k];
w[k][15] = tmp2[k];
}
}
else
memcpy(w, data, 16 * sizeof(vtype) * SIMD_PARA_SHA512);
// dump_stuff_shammx64_msg("\nindex 2", w, 128, 2);
if (SSEi_flags & SSEi_RELOAD)
{
if ((SSEi_flags & SSEi_RELOAD_INP_FMT) == SSEi_RELOAD_INP_FMT)
{
SHA512_PARA_DO(i)
{
a[i] = vload((vtype *) &reload_state[i * 16 * VS64 + 0 * VS64]);
b[i] = vload((vtype *) &reload_state[i * 16 * VS64 + 1 * VS64]);
c[i] = vload((vtype *) &reload_state[i * 16 * VS64 + 2 * VS64]);
d[i] = vload((vtype *) &reload_state[i * 16 * VS64 + 3 * VS64]);
e[i] = vload((vtype *) &reload_state[i * 16 * VS64 + 4 * VS64]);
f[i] = vload((vtype *) &reload_state[i * 16 * VS64 + 5 * VS64]);
g[i] = vload((vtype *) &reload_state[i * 16 * VS64 + 6 * VS64]);
h[i] = vload((vtype *) &reload_state[i * 16 * VS64 + 7 * VS64]);
}
}
else
{
SHA512_PARA_DO(i)
{
a[i] = vload((vtype *) &reload_state[i * 8 * VS64 + 0 * VS64]);
b[i] = vload((vtype *) &reload_state[i * 8 * VS64 + 1 * VS64]);
c[i] = vload((vtype *) &reload_state[i * 8 * VS64 + 2 * VS64]);
d[i] = vload((vtype *) &reload_state[i * 8 * VS64 + 3 * VS64]);
e[i] = vload((vtype *) &reload_state[i * 8 * VS64 + 4 * VS64]);
f[i] = vload((vtype *) &reload_state[i * 8 * VS64 + 5 * VS64]);
g[i] = vload((vtype *) &reload_state[i * 8 * VS64 + 6 * VS64]);
h[i] = vload((vtype *) &reload_state[i * 8 * VS64 + 7 * VS64]);
}
}
}
else
{
if (SSEi_flags & SSEi_CRYPT_SHA384)
{
SHA512_PARA_DO(i)
{
/* SHA-384 IV */
a[i] = vset1_epi64(0xcbbb9d5dc1059ed8ULL);
b[i] = vset1_epi64(0x629a292a367cd507ULL);
c[i] = vset1_epi64(0x9159015a3070dd17ULL);
d[i] = vset1_epi64(0x152fecd8f70e5939ULL);
e[i] = vset1_epi64(0x67332667ffc00b31ULL);
f[i] = vset1_epi64(0x8eb44a8768581511ULL);
g[i] = vset1_epi64(0xdb0c2e0d64f98fa7ULL);
h[i] = vset1_epi64(0x47b5481dbefa4fa4ULL);
}
}
else
{
SHA512_PARA_DO(i)
{
/* SHA-512 IV */
a[i] = vset1_epi64(0x6a09e667f3bcc908ULL);
b[i] = vset1_epi64(0xbb67ae8584caa73bULL);
c[i] = vset1_epi64(0x3c6ef372fe94f82bULL);
d[i] = vset1_epi64(0xa54ff53a5f1d36f1ULL);
e[i] = vset1_epi64(0x510e527fade682d1ULL);
f[i] = vset1_epi64(0x9b05688c2b3e6c1fULL);
g[i] = vset1_epi64(0x1f83d9abfb41bd6bULL);
h[i] = vset1_epi64(0x5be0cd19137e2179ULL);
}
}
}
SHA512_STEP(a, b, c, d, e, f, g, h, 0, 0x428a2f98d728ae22ULL);
SHA512_STEP(h, a, b, c, d, e, f, g, 1, 0x7137449123ef65cdULL);
SHA512_STEP(g, h, a, b, c, d, e, f, 2, 0xb5c0fbcfec4d3b2fULL);
SHA512_STEP(f, g, h, a, b, c, d, e, 3, 0xe9b5dba58189dbbcULL);
SHA512_STEP(e, f, g, h, a, b, c, d, 4, 0x3956c25bf348b538ULL);
SHA512_STEP(d, e, f, g, h, a, b, c, 5, 0x59f111f1b605d019ULL);
SHA512_STEP(c, d, e, f, g, h, a, b, 6, 0x923f82a4af194f9bULL);
SHA512_STEP(b, c, d, e, f, g, h, a, 7, 0xab1c5ed5da6d8118ULL);
SHA512_STEP(a, b, c, d, e, f, g, h, 8, 0xd807aa98a3030242ULL);
SHA512_STEP(h, a, b, c, d, e, f, g, 9, 0x12835b0145706fbeULL);
SHA512_STEP(g, h, a, b, c, d, e, f, 10, 0x243185be4ee4b28cULL);
SHA512_STEP(f, g, h, a, b, c, d, e, 11, 0x550c7dc3d5ffb4e2ULL);
SHA512_STEP(e, f, g, h, a, b, c, d, 12, 0x72be5d74f27b896fULL);
SHA512_STEP(d, e, f, g, h, a, b, c, 13, 0x80deb1fe3b1696b1ULL);
SHA512_STEP(c, d, e, f, g, h, a, b, 14, 0x9bdc06a725c71235ULL);
SHA512_STEP(b, c, d, e, f, g, h, a, 15, 0xc19bf174cf692694ULL);
SHA512_STEP(a, b, c, d, e, f, g, h, 16, 0xe49b69c19ef14ad2ULL);
SHA512_STEP(h, a, b, c, d, e, f, g, 17, 0xefbe4786384f25e3ULL);
SHA512_STEP(g, h, a, b, c, d, e, f, 18, 0x0fc19dc68b8cd5b5ULL);
SHA512_STEP(f, g, h, a, b, c, d, e, 19, 0x240ca1cc77ac9c65ULL);
SHA512_STEP(e, f, g, h, a, b, c, d, 20, 0x2de92c6f592b0275ULL);
SHA512_STEP(d, e, f, g, h, a, b, c, 21, 0x4a7484aa6ea6e483ULL);
SHA512_STEP(c, d, e, f, g, h, a, b, 22, 0x5cb0a9dcbd41fbd4ULL);
SHA512_STEP(b, c, d, e, f, g, h, a, 23, 0x76f988da831153b5ULL);
SHA512_STEP(a, b, c, d, e, f, g, h, 24, 0x983e5152ee66dfabULL);
SHA512_STEP(h, a, b, c, d, e, f, g, 25, 0xa831c66d2db43210ULL);
SHA512_STEP(g, h, a, b, c, d, e, f, 26, 0xb00327c898fb213fULL);
SHA512_STEP(f, g, h, a, b, c, d, e, 27, 0xbf597fc7beef0ee4ULL);
SHA512_STEP(e, f, g, h, a, b, c, d, 28, 0xc6e00bf33da88fc2ULL);
SHA512_STEP(d, e, f, g, h, a, b, c, 29, 0xd5a79147930aa725ULL);
SHA512_STEP(c, d, e, f, g, h, a, b, 30, 0x06ca6351e003826fULL);
SHA512_STEP(b, c, d, e, f, g, h, a, 31, 0x142929670a0e6e70ULL);
SHA512_STEP(a, b, c, d, e, f, g, h, 32, 0x27b70a8546d22ffcULL);
SHA512_STEP(h, a, b, c, d, e, f, g, 33, 0x2e1b21385c26c926ULL);
SHA512_STEP(g, h, a, b, c, d, e, f, 34, 0x4d2c6dfc5ac42aedULL);
SHA512_STEP(f, g, h, a, b, c, d, e, 35, 0x53380d139d95b3dfULL);
SHA512_STEP(e, f, g, h, a, b, c, d, 36, 0x650a73548baf63deULL);
SHA512_STEP(d, e, f, g, h, a, b, c, 37, 0x766a0abb3c77b2a8ULL);
SHA512_STEP(c, d, e, f, g, h, a, b, 38, 0x81c2c92e47edaee6ULL);
SHA512_STEP(b, c, d, e, f, g, h, a, 39, 0x92722c851482353bULL);
SHA512_STEP(a, b, c, d, e, f, g, h, 40, 0xa2bfe8a14cf10364ULL);
SHA512_STEP(h, a, b, c, d, e, f, g, 41, 0xa81a664bbc423001ULL);
SHA512_STEP(g, h, a, b, c, d, e, f, 42, 0xc24b8b70d0f89791ULL);
SHA512_STEP(f, g, h, a, b, c, d, e, 43, 0xc76c51a30654be30ULL);
SHA512_STEP(e, f, g, h, a, b, c, d, 44, 0xd192e819d6ef5218ULL);
SHA512_STEP(d, e, f, g, h, a, b, c, 45, 0xd69906245565a910ULL);
SHA512_STEP(c, d, e, f, g, h, a, b, 46, 0xf40e35855771202aULL);
SHA512_STEP(b, c, d, e, f, g, h, a, 47, 0x106aa07032bbd1b8ULL);
SHA512_STEP(a, b, c, d, e, f, g, h, 48, 0x19a4c116b8d2d0c8ULL);
SHA512_STEP(h, a, b, c, d, e, f, g, 49, 0x1e376c085141ab53ULL);
SHA512_STEP(g, h, a, b, c, d, e, f, 50, 0x2748774cdf8eeb99ULL);
SHA512_STEP(f, g, h, a, b, c, d, e, 51, 0x34b0bcb5e19b48a8ULL);
SHA512_STEP(e, f, g, h, a, b, c, d, 52, 0x391c0cb3c5c95a63ULL);
SHA512_STEP(d, e, f, g, h, a, b, c, 53, 0x4ed8aa4ae3418acbULL);
SHA512_STEP(c, d, e, f, g, h, a, b, 54, 0x5b9cca4f7763e373ULL);
SHA512_STEP(b, c, d, e, f, g, h, a, 55, 0x682e6ff3d6b2b8a3ULL);
SHA512_STEP(a, b, c, d, e, f, g, h, 56, 0x748f82ee5defb2fcULL);
SHA512_STEP(h, a, b, c, d, e, f, g, 57, 0x78a5636f43172f60ULL);
SHA512_STEP(g, h, a, b, c, d, e, f, 58, 0x84c87814a1f0ab72ULL);
SHA512_STEP(f, g, h, a, b, c, d, e, 59, 0x8cc702081a6439ecULL);
SHA512_STEP(e, f, g, h, a, b, c, d, 60, 0x90befffa23631e28ULL);
SHA512_STEP(d, e, f, g, h, a, b, c, 61, 0xa4506cebde82bde9ULL);
SHA512_STEP(c, d, e, f, g, h, a, b, 62, 0xbef9a3f7b2c67915ULL);
SHA512_STEP(b, c, d, e, f, g, h, a, 63, 0xc67178f2e372532bULL);
SHA512_STEP(a, b, c, d, e, f, g, h, 64, 0xca273eceea26619cULL);
SHA512_STEP(h, a, b, c, d, e, f, g, 65, 0xd186b8c721c0c207ULL);
SHA512_STEP(g, h, a, b, c, d, e, f, 66, 0xeada7dd6cde0eb1eULL);
SHA512_STEP(f, g, h, a, b, c, d, e, 67, 0xf57d4f7fee6ed178ULL);
SHA512_STEP(e, f, g, h, a, b, c, d, 68, 0x06f067aa72176fbaULL);
SHA512_STEP(d, e, f, g, h, a, b, c, 69, 0x0a637dc5a2c898a6ULL);
SHA512_STEP(c, d, e, f, g, h, a, b, 70, 0x113f9804bef90daeULL);
SHA512_STEP(b, c, d, e, f, g, h, a, 71, 0x1b710b35131c471bULL);
SHA512_STEP(a, b, c, d, e, f, g, h, 72, 0x28db77f523047d84ULL);
if (SSEi_flags & SSEi_REVERSE_STEPS && !(SSEi_flags & SSEi_CRYPT_SHA384))
{
SHA512_PARA_DO(i)
{
vstore((vtype *) &(out[i * 8 * VS64 + 0 * VS64]), h[i]);
}
return;
}
SHA512_STEP(h, a, b, c, d, e, f, g, 73, 0x32caab7b40c72493ULL);
SHA512_STEP(g, h, a, b, c, d, e, f, 74, 0x3c9ebe0a15c9bebcULL);
SHA512_STEP(f, g, h, a, b, c, d, e, 75, 0x431d67c49c100d4cULL);
SHA512_STEP(e, f, g, h, a, b, c, d, 76, 0x4cc5d4becb3e42b6ULL);
if (SSEi_flags & SSEi_REVERSE_STEPS)
{
SHA512_PARA_DO(i)
{
vstore((vtype *) &(out[i * 8 * VS64 + 3 * VS64]), d[i]);
}
return;
}
SHA512_STEP(d, e, f, g, h, a, b, c, 77, 0x597f299cfc657e2aULL);
SHA512_STEP(c, d, e, f, g, h, a, b, 78, 0x5fcb6fab3ad6faecULL);
SHA512_STEP(b, c, d, e, f, g, h, a, 79, 0x6c44198c4a475817ULL);
if (SSEi_flags & SSEi_RELOAD)
{
if ((SSEi_flags & SSEi_RELOAD_INP_FMT) == SSEi_RELOAD_INP_FMT)
{
SHA512_PARA_DO(i)
{
a[i] = vadd_epi64(
a[i],
vload((vtype *) &reload_state[i * 16 * VS64 + 0 * VS64]));
b[i] = vadd_epi64(
b[i],
vload((vtype *) &reload_state[i * 16 * VS64 + 1 * VS64]));
c[i] = vadd_epi64(
c[i],
vload((vtype *) &reload_state[i * 16 * VS64 + 2 * VS64]));
d[i] = vadd_epi64(
d[i],
vload((vtype *) &reload_state[i * 16 * VS64 + 3 * VS64]));
e[i] = vadd_epi64(
e[i],
vload((vtype *) &reload_state[i * 16 * VS64 + 4 * VS64]));
f[i] = vadd_epi64(
f[i],
vload((vtype *) &reload_state[i * 16 * VS64 + 5 * VS64]));
g[i] = vadd_epi64(
g[i],
vload((vtype *) &reload_state[i * 16 * VS64 + 6 * VS64]));
h[i] = vadd_epi64(
h[i],
vload((vtype *) &reload_state[i * 16 * VS64 + 7 * VS64]));
}
}
else
{
SHA512_PARA_DO(i)
{
a[i] = vadd_epi64(
a[i],
vload((vtype *) &reload_state[i * 8 * VS64 + 0 * VS64]));
b[i] = vadd_epi64(
b[i],
vload((vtype *) &reload_state[i * 8 * VS64 + 1 * VS64]));
c[i] = vadd_epi64(
c[i],
vload((vtype *) &reload_state[i * 8 * VS64 + 2 * VS64]));
d[i] = vadd_epi64(
d[i],
vload((vtype *) &reload_state[i * 8 * VS64 + 3 * VS64]));
e[i] = vadd_epi64(
e[i],
vload((vtype *) &reload_state[i * 8 * VS64 + 4 * VS64]));
f[i] = vadd_epi64(
f[i],
vload((vtype *) &reload_state[i * 8 * VS64 + 5 * VS64]));
g[i] = vadd_epi64(
g[i],
vload((vtype *) &reload_state[i * 8 * VS64 + 6 * VS64]));
h[i] = vadd_epi64(
h[i],
vload((vtype *) &reload_state[i * 8 * VS64 + 7 * VS64]));
}
}
}
else
{
if (SSEi_flags & SSEi_CRYPT_SHA384)
{
SHA512_PARA_DO(i)
{
/* SHA-384 IV */
a[i] = vadd_epi64(a[i], vset1_epi64(0xcbbb9d5dc1059ed8ULL));
b[i] = vadd_epi64(b[i], vset1_epi64(0x629a292a367cd507ULL));
c[i] = vadd_epi64(c[i], vset1_epi64(0x9159015a3070dd17ULL));
d[i] = vadd_epi64(d[i], vset1_epi64(0x152fecd8f70e5939ULL));
e[i] = vadd_epi64(e[i], vset1_epi64(0x67332667ffc00b31ULL));
f[i] = vadd_epi64(f[i], vset1_epi64(0x8eb44a8768581511ULL));
g[i] = vadd_epi64(g[i], vset1_epi64(0xdb0c2e0d64f98fa7ULL));
h[i] = vadd_epi64(h[i], vset1_epi64(0x47b5481dbefa4fa4ULL));
}
}
else
{
SHA512_PARA_DO(i)
{
/* SHA-512 IV */
a[i] = vadd_epi64(a[i], vset1_epi64(0x6a09e667f3bcc908ULL));
b[i] = vadd_epi64(b[i], vset1_epi64(0xbb67ae8584caa73bULL));
c[i] = vadd_epi64(c[i], vset1_epi64(0x3c6ef372fe94f82bULL));
d[i] = vadd_epi64(d[i], vset1_epi64(0xa54ff53a5f1d36f1ULL));
e[i] = vadd_epi64(e[i], vset1_epi64(0x510e527fade682d1ULL));
f[i] = vadd_epi64(f[i], vset1_epi64(0x9b05688c2b3e6c1fULL));
g[i] = vadd_epi64(g[i], vset1_epi64(0x1f83d9abfb41bd6bULL));
h[i] = vadd_epi64(h[i], vset1_epi64(0x5be0cd19137e2179ULL));
}
}
}
if (SSEi_flags & SSEi_FLAT_OUT)
{
SHA512_PARA_DO(i)
{
uint64_t * o = (uint64_t *) &out[i * 8 * VS64];
#if __AVX512F__ || __MIC__
vtype idxs = vset_epi64(
7 << 3, 6 << 3, 5 << 3, 4 << 3, 3 << 3, 2 << 3, 1 << 3, 0 << 3);
vscatter_epi64((((uint64_t *) o) + 0), idxs, vswap64(a[i]), 8);
vscatter_epi64((((uint64_t *) o) + 1), idxs, vswap64(b[i]), 8);
vscatter_epi64((((uint64_t *) o) + 2), idxs, vswap64(c[i]), 8);
vscatter_epi64((((uint64_t *) o) + 3), idxs, vswap64(d[i]), 8);
vscatter_epi64((((uint64_t *) o) + 4), idxs, vswap64(e[i]), 8);
vscatter_epi64((((uint64_t *) o) + 5), idxs, vswap64(f[i]), 8);
vscatter_epi64((((uint64_t *) o) + 6), idxs, vswap64(g[i]), 8);
vscatter_epi64((((uint64_t *) o) + 7), idxs, vswap64(h[i]), 8);
#else
uint64_t j, k;
union {
vtype v[8];
uint64_t s[8 * VS64];
} tmp;
tmp.v[0] = vswap64(a[i]);
tmp.v[1] = vswap64(b[i]);
tmp.v[2] = vswap64(c[i]);
tmp.v[3] = vswap64(d[i]);
tmp.v[4] = vswap64(e[i]);
tmp.v[5] = vswap64(f[i]);
tmp.v[6] = vswap64(g[i]);
tmp.v[7] = vswap64(h[i]);
for (j = 0; j < VS64; j++)
for (k = 0; k < 8; k++) o[j * 8 + k] = tmp.s[k * VS64 + j];
#endif
}
}
else if (SSEi_flags & SSEi_OUTPUT_AS_INP_FMT)
{
if ((SSEi_flags & SSEi_OUTPUT_AS_2BUF_INP_FMT)
== SSEi_OUTPUT_AS_2BUF_INP_FMT)
{
SHA512_PARA_DO(i)
{
vstore((vtype *) &out[i * 32 * VS64 + 0 * VS64], a[i]);
vstore((vtype *) &out[i * 32 * VS64 + 1 * VS64], b[i]);
vstore((vtype *) &out[i * 32 * VS64 + 2 * VS64], c[i]);
vstore((vtype *) &out[i * 32 * VS64 + 3 * VS64], d[i]);
vstore((vtype *) &out[i * 32 * VS64 + 4 * VS64], e[i]);
vstore((vtype *) &out[i * 32 * VS64 + 5 * VS64], f[i]);
vstore((vtype *) &out[i * 32 * VS64 + 6 * VS64], g[i]);
vstore((vtype *) &out[i * 32 * VS64 + 7 * VS64], h[i]);
}
}
else
{
SHA512_PARA_DO(i)
{
vstore((vtype *) &out[i * 16 * VS64 + 0 * VS64], a[i]);
vstore((vtype *) &out[i * 16 * VS64 + 1 * VS64], b[i]);
vstore((vtype *) &out[i * 16 * VS64 + 2 * VS64], c[i]);
vstore((vtype *) &out[i * 16 * VS64 + 3 * VS64], d[i]);
vstore((vtype *) &out[i * 16 * VS64 + 4 * VS64], e[i]);
vstore((vtype *) &out[i * 16 * VS64 + 5 * VS64], f[i]);
vstore((vtype *) &out[i * 16 * VS64 + 6 * VS64], g[i]);
vstore((vtype *) &out[i * 16 * VS64 + 7 * VS64], h[i]);
}
}
}
else
{
SHA512_PARA_DO(i)
{
vstore((vtype *) &(out[i * 8 * VS64 + 0 * VS64]), a[i]);
vstore((vtype *) &(out[i * 8 * VS64 + 1 * VS64]), b[i]);
vstore((vtype *) &(out[i * 8 * VS64 + 2 * VS64]), c[i]);
vstore((vtype *) &(out[i * 8 * VS64 + 3 * VS64]), d[i]);
vstore((vtype *) &(out[i * 8 * VS64 + 4 * VS64]), e[i]);
vstore((vtype *) &(out[i * 8 * VS64 + 5 * VS64]), f[i]);
vstore((vtype *) &(out[i * 8 * VS64 + 6 * VS64]), g[i]);
vstore((vtype *) &(out[i * 8 * VS64 + 7 * VS64]), h[i]);
}
}
}
#endif /* SIMD_PARA_SHA512 */ |
C | aircrack-ng/lib/ce-wpa/wpapsk.c | /*
* Based on John the Ripper and modified to integrate with aircrack
*
* John the Ripper copyright and license.
*
* John the Ripper password cracker,
* Copyright (c) 1996-2013 by Solar Designer.
*
* 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.
*
* As a special exception to the GNU General Public License terms,
* permission is hereby granted to link the code of this program, with or
* without modification, with any version of the OpenSSL library and/or any
* version of unRAR, and to distribute such linked combinations. You must
* obey the GNU GPL in all respects for all of the code used other than
* OpenSSL and unRAR. If you modify this program, you may extend this
* exception to your version of the program, but you are not obligated to
* do so. (In other words, you may release your derived work under pure
* GNU GPL version 2 or later as published by the FSF.)
*
* (This exception from the GNU GPL is not required for the core tree of
* John the Ripper, but arguably it is required for -jumbo.)
*
* Relaxed terms for certain components.
*
* In addition or alternatively to the license above, many components are
* available to you under more relaxed terms (most commonly under cut-down
* BSD license) as specified in the corresponding source files.
*
* For more information on John the Ripper licensing please visit:
*
* http://www.openwall.com/john/doc/LICENSE.shtml
*
* This software is Copyright (c) 2012 Lukas Odzioba <ukasz at openwall dot net>
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* Code is based on Aircrack-ng source
*
* SSE2 code enhancement, Jim Fougeron, Jan, 2013.
* Also removed oSSL code: HMAC(EVP_sha1(), ....), and coded what it does
* (which is simple), inline.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <string.h>
#include <stdint.h>
#include <aircrack-ng/crypto/crypto.h>
#include "aircrack-ng/ce-wpa/simd-intrinsics.h"
#include "aircrack-ng/aircrack-ng.h"
#include "aircrack-ng/ce-wpa/arch.h"
#include "aircrack-ng/ce-wpa/wpapsk.h"
#include "aircrack-ng/ce-wpa/johnswap.h"
#include "aircrack-ng/ce-wpa/memory.h"
#include "aircrack-ng/cpu/simd_cpuid.h"
// #define XDEBUG
#if defined(__INTEL_COMPILER)
#define SIMD_PARA_SHA1 1
#elif defined(__clang__)
#define SIMD_PARA_SHA1 1
#elif defined(__llvm__)
#define SIMD_PARA_SHA1 1
#elif defined(__GNUC__) && GCC_VERSION < 40504 // 4.5.4
#define SIMD_PARA_SHA1 1
#elif !defined(__AVX__) && defined(__GNUC__) && GCC_VERSION > 40700 // 4.7.0
#define SIMD_PARA_SHA1 1
#else
#define SIMD_PARA_SHA1 1
#endif
#ifdef SIMD_CORE
#ifdef SIMD_COEF_32
#define NBKEYS (SIMD_COEF_32 * SIMD_PARA_SHA1)
#ifdef _OPENMP
#include <omp.h>
#endif
#else
#define NBKEYS 1
#ifdef _OPENMP
#include <omp.h>
#endif
#endif
#else
#ifdef MMX_COEF
#define NBKEYS (MMX_COEF * SHA1_SSE_PARA)
#ifdef _OPENMP
#include <omp.h>
#endif
#else
#define NBKEYS 1
#ifdef _OPENMP
#include <omp.h>
#endif
#endif
#endif
static char itoa64[64]
= "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char atoi64[0x100];
/* for endianity conversion */
#ifdef SIMD_CORE
#define GETPOS(i, index) \
((index & (SIMD_COEF_32 - 1)) * 4 \
+ ((i) & (0xffffffff - 3)) * SIMD_COEF_32 \
+ (3 - ((i) &3)) \
+ (unsigned int) index / SIMD_COEF_32 * SHA_BUF_SIZ * SIMD_COEF_32 * 4)
#endif
#define BUF_BASE_OFFSET_OF(co, width, index) \
(((index) / (co)) * (co) * (width) + ((index) & ((co) -1)))
#define BUF_OFFSET_OF(co, width, index, offset) \
(BUF_BASE_OFFSET_OF((co), (width), (index)) + (offset) * (co))
#define SSE_HASH1_PTR_OF(j) \
&((uint32_t *) \
t_sse_hash1)[((((j) / SIMD_COEF_32) * SHA_BUF_SIZ) * SIMD_COEF_32) \
+ ((j) & (SIMD_COEF_32 - 1))]
#ifdef SIMD_CORE
static MAYBE_INLINE void wpapsk_sse(ac_crypto_engine_t * engine,
int threadid,
int count,
const wpapsk_password * in)
{
int t; // thread count
int salt_length = engine->essid_length;
int slen = salt_length + 4;
int loops = (count + NBKEYS - 1) / NBKEYS;
unsigned char * sse_hash1 = NULL;
unsigned char * sse_crypt1 = NULL;
unsigned char * sse_crypt2 = NULL;
unsigned char essid[ESSID_LENGTH + 4];
sse_hash1 = engine->thread_data[threadid]->hash1;
sse_crypt1 = engine->thread_data[threadid]->crypt1;
sse_crypt2 = engine->thread_data[threadid]->crypt2;
memset(essid, 0, sizeof(essid));
strncpy((char *) essid,
(const char *) engine->essid,
(size_t) engine->essid_length);
for (t = 0; t < loops; t++)
{
unsigned int i, k, j;
union {
unsigned char c[64];
uint32_t i[16];
} buffer[NBKEYS];
char __dummy[CACHELINE_SIZE];
union {
unsigned char c[40]; // only 40 are used
uint32_t i[10]; // only 8 are used
} outbuf[NBKEYS];
char __dummy2[CACHELINE_SIZE];
wpapsk_SHA1_CTX ctx_ipad[NBKEYS];
char __dummy3[CACHELINE_SIZE];
wpapsk_SHA1_CTX ctx_opad[NBKEYS];
char __dummy4[CACHELINE_SIZE];
wpapsk_SHA1_CTX sha1_ctx;
unsigned int *i1, *i2, *o1;
unsigned char *t_sse_crypt1, *t_sse_crypt2, *t_sse_hash1;
// All pointers get their offset for this thread here. No further
// offsetting below.
t_sse_crypt1 = &sse_crypt1[t * NBKEYS * DIGEST_SHA1_MAC_LEN];
t_sse_crypt2 = &sse_crypt2[t * NBKEYS * DIGEST_SHA1_MAC_LEN];
t_sse_hash1 = &sse_hash1[t * NBKEYS * SHA_BUF_SIZ * 4];
i1 = (unsigned int *) t_sse_crypt1;
i2 = (unsigned int *) t_sse_crypt2;
o1 = (unsigned int *) t_sse_hash1;
(void) __dummy;
(void) __dummy2;
(void) __dummy3;
(void) __dummy4;
for (j = 0; j < NBKEYS; ++j)
{
memcpy(
buffer[j].c, in[t * NBKEYS + j].v, in[t * NBKEYS + j].length);
memset(&buffer[j].c[in[t * NBKEYS + j].length],
0,
64 - in[t * NBKEYS + j].length);
wpapsk_SHA1_Init(&ctx_ipad[j]);
wpapsk_SHA1_Init(&ctx_opad[j]);
for (i = 0; i < 16; i++) buffer[j].i[i] ^= 0x36363636;
wpapsk_SHA1_Update(&ctx_ipad[j], buffer[j].c, 64);
for (i = 0; i < 16; i++) buffer[j].i[i] ^= 0x6a6a6a6a;
wpapsk_SHA1_Update(&ctx_opad[j], buffer[j].c, 64);
i1[BUF_OFFSET_OF(SIMD_COEF_32, 5, j, 0)] = ctx_ipad[j].h0;
i1[BUF_OFFSET_OF(SIMD_COEF_32, 5, j, 1)] = ctx_ipad[j].h1;
i1[BUF_OFFSET_OF(SIMD_COEF_32, 5, j, 2)] = ctx_ipad[j].h2;
i1[BUF_OFFSET_OF(SIMD_COEF_32, 5, j, 3)] = ctx_ipad[j].h3;
i1[BUF_OFFSET_OF(SIMD_COEF_32, 5, j, 4)] = ctx_ipad[j].h4;
i2[BUF_OFFSET_OF(SIMD_COEF_32, 5, j, 0)] = ctx_opad[j].h0;
i2[BUF_OFFSET_OF(SIMD_COEF_32, 5, j, 1)] = ctx_opad[j].h1;
i2[BUF_OFFSET_OF(SIMD_COEF_32, 5, j, 2)] = ctx_opad[j].h2;
i2[BUF_OFFSET_OF(SIMD_COEF_32, 5, j, 3)] = ctx_opad[j].h3;
i2[BUF_OFFSET_OF(SIMD_COEF_32, 5, j, 4)] = ctx_opad[j].h4;
essid[slen - 1] = 1;
// This code does the HMAC(EVP_....) call. We already
// have essid appended with BE((int)1) so we simply
// call a single SHA1_Update
wpapsk_SHA1_Clone(&sha1_ctx, &ctx_ipad[j]);
wpapsk_SHA1_Update(&sha1_ctx, essid, slen);
wpapsk_SHA1_Final(outbuf[j].c, &sha1_ctx);
wpapsk_SHA1_Clone(&sha1_ctx, &ctx_opad[j]);
wpapsk_SHA1_Update(&sha1_ctx, outbuf[j].c, DIGEST_SHA1_MAC_LEN);
wpapsk_SHA1_Final(outbuf[j].c, &sha1_ctx);
// now convert this from flat into COEF buffers. Also,
// perform the 'first' ^= into the crypt buffer. We
// are doing that in BE format so we will need to
// 'undo' that in the end.
o1[BUF_OFFSET_OF(SIMD_COEF_32, SHA_BUF_SIZ, j, 0)] = outbuf[j].i[0]
= sha1_ctx.h0;
o1[BUF_OFFSET_OF(SIMD_COEF_32, SHA_BUF_SIZ, j, 1)] = outbuf[j].i[1]
= sha1_ctx.h1;
o1[BUF_OFFSET_OF(SIMD_COEF_32, SHA_BUF_SIZ, j, 2)] = outbuf[j].i[2]
= sha1_ctx.h2;
o1[BUF_OFFSET_OF(SIMD_COEF_32, SHA_BUF_SIZ, j, 3)] = outbuf[j].i[3]
= sha1_ctx.h3;
o1[BUF_OFFSET_OF(SIMD_COEF_32, SHA_BUF_SIZ, j, 4)] = outbuf[j].i[4]
= sha1_ctx.h4;
}
for (i = 1; i < 4096; i++)
{
SIMDSHA1body((unsigned int *) t_sse_hash1,
(unsigned int *) t_sse_hash1,
(unsigned int *) t_sse_crypt1,
SSEi_MIXED_IN | SSEi_RELOAD | SSEi_OUTPUT_AS_INP_FMT);
SIMDSHA1body((unsigned int *) t_sse_hash1,
(unsigned int *) t_sse_hash1,
(unsigned int *) t_sse_crypt2,
SSEi_MIXED_IN | SSEi_RELOAD | SSEi_OUTPUT_AS_INP_FMT);
for (j = 0; j < NBKEYS; j++)
{
uint32_t * p = SSE_HASH1_PTR_OF(j);
for (k = 0; k < 5; k++) outbuf[j].i[k] ^= p[(k * SIMD_COEF_32)];
}
}
essid[slen - 1] = 2;
for (j = 0; j < NBKEYS; ++j)
{
// This code does the HMAC(EVP_....) call. We already
// have essid appended with BE((int)1) so we simply
// call a single SHA1_Update
wpapsk_SHA1_Clone(&sha1_ctx, &ctx_ipad[j]);
wpapsk_SHA1_Update(&sha1_ctx, essid, slen);
wpapsk_SHA1_Final(&outbuf[j].c[DIGEST_SHA1_MAC_LEN], &sha1_ctx);
wpapsk_SHA1_Clone(&sha1_ctx, &ctx_opad[j]);
wpapsk_SHA1_Update(&sha1_ctx,
&outbuf[j].c[DIGEST_SHA1_MAC_LEN],
DIGEST_SHA1_MAC_LEN);
wpapsk_SHA1_Final(&outbuf[j].c[DIGEST_SHA1_MAC_LEN], &sha1_ctx);
// now convert this from flat into COEF buffers. Also,
// perform the 'first' ^= into the crypt buffer. We
// are doing that in BE format so we will need to
// 'undo' that in the end. (only 3 dwords of the 2nd
// block outbuf are worked with).
o1[BUF_OFFSET_OF(SIMD_COEF_32, SHA_BUF_SIZ, j, 0)] = outbuf[j].i[5]
= sha1_ctx.h0;
o1[BUF_OFFSET_OF(SIMD_COEF_32, SHA_BUF_SIZ, j, 1)] = outbuf[j].i[6]
= sha1_ctx.h1;
o1[BUF_OFFSET_OF(SIMD_COEF_32, SHA_BUF_SIZ, j, 2)] = outbuf[j].i[7]
= sha1_ctx.h2;
o1[BUF_OFFSET_OF(SIMD_COEF_32, SHA_BUF_SIZ, j, 3)] = sha1_ctx.h3;
o1[BUF_OFFSET_OF(SIMD_COEF_32, SHA_BUF_SIZ, j, 4)] = sha1_ctx.h4;
}
for (i = 1; i < 4096; i++)
{
SIMDSHA1body((unsigned int *) t_sse_hash1,
(unsigned int *) t_sse_hash1,
(unsigned int *) t_sse_crypt1,
SSEi_MIXED_IN | SSEi_RELOAD | SSEi_OUTPUT_AS_INP_FMT);
SIMDSHA1body((unsigned int *) t_sse_hash1,
(unsigned int *) t_sse_hash1,
(unsigned int *) t_sse_crypt2,
SSEi_MIXED_IN | SSEi_RELOAD | SSEi_OUTPUT_AS_INP_FMT);
for (j = 0; j < NBKEYS; j++)
{
uint32_t * p = SSE_HASH1_PTR_OF(j);
for (k = 5; k < 8; k++)
outbuf[j].i[k] ^= p[((k - 5) * SIMD_COEF_32)];
}
}
for (j = 0; j < NBKEYS; ++j)
{
memcpy(&engine->thread_data[threadid]->pmk[j], //-V512
outbuf[j].c,
32);
alter_endianity_to_BE((&engine->thread_data[threadid]->pmk[j]), 8);
}
}
return;
}
#endif
void init_atoi(void)
{
memset(atoi64, 0x7F, sizeof(atoi64));
for (char const * pos = itoa64; pos != &itoa64[63]; pos++)
atoi64[ARCH_INDEX(*pos)] = pos - itoa64;
}
#ifdef SIMD_CORE
//#define XDEBUG 1
//#define ODEBUG 1
int init_wpapsk(ac_crypto_engine_t * engine,
const wpapsk_password key[MAX_KEYS_PER_CRYPT_SUPPORTED],
int nparallel,
int threadid)
{
int i = 0;
int count = 0;
// clear entire output table
memset(engine->thread_data[threadid]->pmk,
0,
(sizeof(wpapsk_hash) * (nparallel)));
{
unsigned char * sse_hash1 = engine->thread_data[threadid]->hash1;
int index;
for (index = 0; index < nparallel; ++index)
{
// set the length of all hash1 SSE buffer to
// 64+20 * 8 bits. The 64 is for the ipad/opad,
// the 20 is for the length of the SHA1 buffer that
// also gets into each crypt. Works for SSE2i and SSE2
((unsigned int *)
sse_hash1)[15 * SIMD_COEF_32 + (index & (SIMD_COEF_32 - 1))
+ (unsigned int) index / SIMD_COEF_32 * SHA_BUF_SIZ
* SIMD_COEF_32]
= (84 << 3); // all encrypts are 64+20 bytes.
sse_hash1[GETPOS(20, index)] = 0x80;
}
}
for (i = 0; i < nparallel; ++i)
{
char * tkey = (char *) key[i].v;
if (*tkey != 0)
{
// set_key(tkey, i, inbuffer);
#ifdef XDEBUG
printf(
"key%d (inbuffer) = (%p) %s VALID\n", i + 1, tkey, key[i].v);
#endif
count = i + 1;
}
}
wpapsk_sse(engine, threadid, count, key);
return 0;
}
#endif |
C | aircrack-ng/lib/cowpatty/cowpatty.c | /*
* coWPAtty hash DB file helper functions
*
* Copyright (C) 2018 Thomas d'Otreppe <[email protected]>
*
* 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
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/cowpatty/cowpatty.h"
void close_free_cowpatty_hashdb(struct cowpatty_file * cf)
{
if (cf != NULL)
{
if (cf->fp)
{
fclose(cf->fp);
}
free(cf);
}
}
struct cowpatty_file * open_cowpatty_hashdb(const char * filename,
const char * mode)
{
struct hashdb_head filehead;
// Initialize structure
struct cowpatty_file * ret
= (struct cowpatty_file *) malloc(sizeof(struct cowpatty_file));
ALLEGE(ret != NULL);
memset(ret->ssid, 0, sizeof(ret->ssid));
memset(ret->error, 0, sizeof(ret->error));
ret->fp = NULL;
if (filename == NULL || filename[0] == 0)
{
strcpy(ret->error, "No filename specified");
return (ret);
}
if (mode == NULL || strncmp(mode, "r", 1) == 0)
{
if (strcmp(filename, "-") == 0)
{
ret->fp = stdin;
}
else
{
ret->fp = fopen(filename, "r");
if (ret->fp == NULL)
{
snprintf(ret->error,
sizeof(ret->error),
"File <%s> cannot be opened",
filename);
return (ret);
}
}
// Check headers
if (fread(&filehead, sizeof(struct hashdb_head), 1, ret->fp) != 1)
{
strcpy(ret->error, "Failed reading hash DB header");
fclose(ret->fp);
ret->fp = NULL;
return (ret);
}
if (filehead.magic != GENPMKMAGIC)
{ // Verify header magic
strcpy(ret->error, "Header magic doesn't match");
fclose(ret->fp);
ret->fp = NULL;
return (ret);
}
if (filehead.ssid[0] == 0)
{
strcpy(ret->error, "SSID is NULL");
fclose(ret->fp);
ret->fp = NULL;
return (ret);
}
// Copy SSID
memcpy(ret->ssid, filehead.ssid, sizeof(filehead.ssid));
if (filehead.ssidlen > 32 || filehead.ssidlen == 0)
{
snprintf(ret->error,
sizeof(ret->error),
"Advertised SSID length is %u (Max length: 32)",
filehead.ssidlen);
fclose(ret->fp);
ret->fp = NULL;
}
}
else
{
// Write not supported yet
strcpy(ret->error, "Write and other modes not supported yet");
}
return (ret);
}
struct hashdb_rec * read_next_cowpatty_record(struct cowpatty_file * cf)
{
int rc, wordlength;
struct hashdb_rec * ret = NULL;
if (cf == NULL || cf->error[0])
{
return (NULL);
}
if (cf->fp == NULL)
{
strcpy(cf->error, "File pointer is NULL");
return (NULL);
}
// Allocate memory
ret = (struct hashdb_rec *) malloc(sizeof(struct hashdb_rec));
if (ret == NULL)
{
strcpy(cf->error, "Failed allocating memory for coWPAtty record");
return (NULL);
}
// Read record size
rc = fread(&(ret->rec_size), sizeof(ret->rec_size), 1, cf->fp);
// Close and exit if failed
if (rc != 1 && feof(cf->fp))
{
free(ret);
fclose(cf->fp);
cf->fp = NULL;
return (NULL);
}
// Get passphrase length
ret->word = NULL;
wordlength = ret->rec_size - (sizeof(ret->pmk) + sizeof(ret->rec_size));
if (wordlength > 0 && wordlength <= MAX_PASSPHRASE_LENGTH)
{
ret->word = (char *) calloc(wordlength + 1, sizeof(char));
ALLEGE(ret->word != NULL);
// Read passphrase
rc += fread(ret->word, wordlength, 1, cf->fp);
if (rc == 2)
{
// And the PMK
rc += fread(&ret->pmk, sizeof(ret->pmk), 1, cf->fp);
}
}
// Check if everything went well
if (rc != 3 || ret->word == NULL || ret->word[0] == 0)
{
if (rc == 1)
{
snprintf(cf->error,
sizeof(cf->error),
"Error while reading record, failed to read passphrase "
"invalid word length: %i",
wordlength);
}
else if (rc == 2)
{
strcpy(cf->error, "Error while reading record, failed reading PMK");
}
else
{
strcpy(cf->error, "NULL or empty passphrase");
}
// Cleanup and close file
fclose(cf->fp);
free(ret->word);
free(ret);
ret = NULL;
cf->fp = NULL;
}
return (ret);
} |
C | aircrack-ng/lib/crypto/aes-128-cbc-gcrypt.c | // clang-format off
/**
* \file aes-128-cbc-gcrypt.c
*
* \brief The Advanced Encryption Standard
*
* \author Joseph Benden <[email protected]>
* \author Jouni Malinen <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stddef.h> // size_t
#include <stdint.h> // [u]int{8,16,32,64}_t types
#include <err.h> // warn{,x} err{,x}
#include <gcrypt.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/aes.h"
// clang-format on
#ifdef USE_GCRYPT
API_EXPORT
Cipher_AES_CTX * Cipher_AES_Encrypt_Init(size_t len, const uint8_t key[static len])
{
gcry_cipher_hd_t * hd = malloc(sizeof(gcry_cipher_hd_t));
if (gcry_cipher_open(hd, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_ECB, 0)
!= GPG_ERR_NO_ERROR)
{
errx(1, "cipher AES-128-CBC open failed");
return NULL;
}
if (gcry_cipher_setkey(*hd, key, len) != GPG_ERR_NO_ERROR)
{
errx(1, "AES-128-cbc setkey failed");
gcry_cipher_close(*hd);
return NULL;
}
return hd;
}
API_EXPORT
int Cipher_AES_Encrypt(Cipher_AES_CTX * ctx,
const uint8_t * plain,
uint8_t * crypt)
{
if (gcry_cipher_encrypt(*ctx, crypt, 16, plain, 16) != GPG_ERR_NO_ERROR)
warnx("Failed to AES encrypt data");
return 0;
}
API_EXPORT
void Cipher_AES_Encrypt_Deinit(Cipher_AES_CTX * ctx)
{
gcry_cipher_close(*ctx);
free(ctx);
}
#endif /* USE_GCRYPT */ |
C | aircrack-ng/lib/crypto/aes-128-cbc-generic.c | // clang-format off
/**
* \file aes-128-cbc-generic.c
*
* \brief AES 128-bit with CBC encryption routines
*
* \author Joseph Benden <[email protected]>
* \author Jouni Malinen <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#include <config.h>
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include <err.h> // err{,x} warn{,x}
#include <aircrack-ng/defs.h>
#include <aircrack-ng/crypto/aes.h>
// clang-format on
API_EXPORT
Cipher_AES_CTX * Cipher_AES_Encrypt_Init(size_t len,
const uint8_t key[static len])
{
REQUIRE(len > 0);
(void) key;
return (NULL);
}
API_EXPORT
int Cipher_AES_Encrypt(Cipher_AES_CTX * ctx,
const uint8_t * plain,
uint8_t * crypt)
{
REQUIRE(ctx != NULL);
REQUIRE(plain != NULL);
REQUIRE(crypt != NULL);
return (0);
}
API_EXPORT
void Cipher_AES_Encrypt_Deinit(Cipher_AES_CTX * ctx)
{
REQUIRE(ctx != NULL);
} |
C | aircrack-ng/lib/crypto/aes-128-cbc-openssl.c | // clang-format off
/**
* \file aes-128-cbc-openssl.c
*
* \brief AES 128-bit with CBC encryption routines
*
* \author Joseph Benden <[email protected]>
* \author Jouni Malinen <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#include <config.h>
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include <err.h> // err{,x} warn{,x}
#include <openssl/evp.h> // OpenSSL high-level interface import
#include <openssl/err.h> // ... include error support
#include <aircrack-ng/defs.h>
#include <aircrack-ng/crypto/aes.h>
// clang-format on
#if OPENSSL_VERSION_NUMBER < 0x10100000L
#define EVP_MD_CTX_new EVP_MD_CTX_create
#define EVP_MD_CTX_free EVP_MD_CTX_destroy
#endif
static const EVP_CIPHER * aes_get_evp_cipher(size_t keylen)
{
switch (keylen)
{
case 16:
return (EVP_aes_128_ecb());
case 24:
return (EVP_aes_192_ecb());
case 32:
return (EVP_aes_256_ecb());
}
return (NULL);
}
API_EXPORT
Cipher_AES_CTX * Cipher_AES_Encrypt_Init(size_t len,
const uint8_t key[static len])
{
EVP_CIPHER_CTX * ctx;
const EVP_CIPHER * type;
type = aes_get_evp_cipher(len);
if (!type)
{
warnx("Could not find matching mode for key length %zd.", len);
return (NULL);
}
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
{
errx(1, "out of memory");
return (NULL);
}
if (EVP_EncryptInit_ex(ctx, type, NULL, key, NULL) != 1)
{
warnx("failed to AES encrypt data");
EVP_CIPHER_CTX_free(ctx);
return (NULL);
}
EVP_CIPHER_CTX_set_padding(ctx, 0);
return (ctx);
}
API_EXPORT
int Cipher_AES_Encrypt(Cipher_AES_CTX * ctx,
const uint8_t * plain,
uint8_t * crypt)
{
int clen = 16;
if (EVP_EncryptUpdate(ctx, crypt, &clen, plain, 16) != 1)
{
warnx("OpenSSL: EVP_EncryptUpdate failed: %s",
ERR_error_string(ERR_get_error(), NULL));
return (-1);
}
return (0);
}
API_EXPORT
void Cipher_AES_Encrypt_Deinit(Cipher_AES_CTX * ctx)
{
uint8_t buf[16];
int len = sizeof(buf);
if (EVP_EncryptFinal_ex(ctx, buf, &len) != 1)
{
warnx("OpenSSL: EVP_EncryptFinal_ex failed: "
"%s",
ERR_error_string(ERR_get_error(), NULL));
}
if (len != 0)
{
warnx("OpenSSL: Unexpected padding length %d "
"in AES encrypt",
len);
}
EVP_CIPHER_CTX_free(ctx);
} |
C | aircrack-ng/lib/crypto/arcfour-gcrypt.c | // clang-format off
/**
* \file arcfour-gcrypt.c
*
* \brief The ARCFOUR stream cipher
*
* \warning ARC4 is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers instead.
*
* \author Joseph Benden <[email protected]>
* \author Jouni Malinen <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#ifdef USE_GCRYPT
#include <err.h> // warn{,s} err{,x}
#include <gcrypt.h>
#include "aircrack-ng/crypto/arcfour.h"
// clang-format on
void Cipher_RC4_set_key(Cipher_RC4_KEY * h, size_t l, const uint8_t k[static l])
{
if (gcry_cipher_open(h, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0)
!= GPG_ERR_NO_ERROR)
errx(1, "missing ARCFOUR support");
if (gcry_cipher_setkey(*h, k, l) != GPG_ERR_NO_ERROR)
errx(1, "unable to set ARCFOUR key");
}
int Cipher_RC4(Cipher_RC4_KEY * h,
size_t l,
const uint8_t s[static l],
uint8_t d[static l])
{
if (gcry_cipher_encrypt(*h, d, l, s, l) != GPG_ERR_NO_ERROR)
errx(1, "failed ARCFOUR encryption");
gcry_cipher_close(*h);
return (0);
}
#endif |
C | aircrack-ng/lib/crypto/arcfour-generic.c | // clang-format off
/**
* \file arcfour-generic.c
*
* \brief The ARCFOUR stream cipher
*
* \warning ARC4 is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers instead.
*
* \author Joseph Benden <[email protected]>
* \author The Mbed TLS Contributors
*
* \license Apache-2.0
*
* \ingroup
* \cond
******************************************************************************
*
* Portitions are Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include "aircrack-ng/crypto/arcfour.h"
// clang-format on
#ifdef DEFINE_ARCFOUR_API
void Cipher_RC4_set_key(Cipher_RC4_KEY * ctx,
size_t keylen,
const uint8_t key[static keylen])
{
int i, j, a;
unsigned int k;
unsigned char * m;
ctx->x = 0;
ctx->y = 0;
m = ctx->m;
for (i = 0; i < 256; i++) m[i] = (unsigned char) i;
j = k = 0;
for (i = 0; i < 256; i++, k++)
{
if (k >= keylen) k = 0;
a = m[i];
j = (j + a + key[k]) & 0xFF;
m[i] = m[j];
m[j] = (unsigned char) a;
}
}
int Cipher_RC4(Cipher_RC4_KEY * ctx,
size_t length,
const uint8_t input[static length],
uint8_t output[static length])
{
int x, y, a, b;
size_t i;
unsigned char * m;
x = ctx->x;
y = ctx->y;
m = ctx->m;
for (i = 0; i < length; i++)
{
x = (x + 1) & 0xFF;
a = m[x];
y = (y + a) & 0xFF;
b = m[y];
m[x] = (unsigned char) b;
m[y] = (unsigned char) a;
output[i] = (unsigned char) (input[i] ^ m[(unsigned char) (a + b)]);
}
ctx->x = x;
ctx->y = y;
return (0);
}
#endif |
C | aircrack-ng/lib/crypto/arcfour-openssl.c | // clang-format off
/**
* \file arcfour-openssl.c
*
* \brief The ARCFOUR stream cipher
*
* \warning ARC4 is considered a weak cipher and its use constitutes a
* security risk. We recommend considering stronger ciphers instead.
*
* \author Joseph Benden <[email protected]>
* \author Jouni Malinen <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include <err.h> // warn{,s} err{,x}
#include "aircrack-ng/crypto/crypto.h"
// clang-format on
#ifdef OPENSSL_WITH_ARCFOUR
# if OPENSSL_VERSION_NUMBER >= 0x30000000L
void Cipher_RC4_set_key(Cipher_RC4_KEY * h, size_t l, const uint8_t k[static l])
{
EVP_CIPHER_CTX * ctx = EVP_CIPHER_CTX_new();
if ( !ctx
|| !EVP_CipherInit_ex(ctx, EVP_rc4(), NULL, NULL, NULL, 1)
|| !EVP_CIPHER_CTX_set_padding(ctx, 0)
|| !EVP_CIPHER_CTX_set_key_length(ctx, l)
|| !EVP_CipherInit_ex(ctx, NULL, NULL, k, NULL, 1))
errx(1, "An error occurred processing RC4_set_key");
h = (void *) ctx;
}
int Cipher_RC4(Cipher_RC4_KEY * h,
size_t l,
const uint8_t s[static l],
uint8_t d[static l])
{
int outlen = l;
EVP_CIPHER_CTX * ctx = (void *) h;
return (EVP_CipherUpdate(ctx, d, &outlen, s, l));
}
#endif
#endif |
C | aircrack-ng/lib/crypto/crypto.c | /*
* MD5, SHA-1, RC4 and AES implementations
*
* Copyright (C) 2001-2004 Christophe Devine
*
* 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
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <err.h>
#include <string.h>
#include <arpa/inet.h>
#include <assert.h>
#include <pthread.h>
#include <stdint.h>
#include <errno.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/crypto/crctable.h"
#include "aircrack-ng/aircrack-ng.h"
#include "aircrack-ng/support/common.h"
#define UBTOUL(b) ((unsigned long) (b))
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
# include <openssl/provider.h>
#endif /* OpenSSL version >= 3.0 */
// libgcrypt thread callback definition for libgcrypt < 1.6.0
#ifdef USE_GCRYPT
#if GCRYPT_VERSION_NUMBER < 0x010600
GCRY_THREAD_OPTION_PTHREAD_IMPL;
#endif
#endif
API_EXPORT
void ac_crypto_init(void)
{
#ifdef USE_GCRYPT
// Register callback functions to ensure proper locking in the sensitive parts
// of libgcrypt < 1.6.0
#if GCRYPT_VERSION_NUMBER < 0x010600
gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
#endif
// Disable secure memory.
gcry_control(GCRYCTL_DISABLE_SECMEM, 0);
// Tell Libgcrypt that initialization has completed.
gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
#else
# if OPENSSL_VERSION_NUMBER >= 0x30000000L
static bool loaded = false;
OSSL_PROVIDER *legacy;
if (loaded)
return;
legacy = OSSL_PROVIDER_load(NULL, "legacy");
if (legacy) {
OSSL_PROVIDER_load(NULL, "default");
loaded = true;
}
# endif /* OpenSSL version >= 3.0 */
#endif
}
/* RC4 encryption/ WEP decryption check */
/* SSL decryption */
int
encrypt_wep(unsigned char * data, int len, unsigned char * key, int keylen)
{
Cipher_RC4_KEY S;
memset(&S, 0, sizeof(S));
Cipher_RC4_set_key(&S, keylen, key);
Cipher_RC4(&S, (size_t) len, data, data);
return (0);
}
int
decrypt_wep(unsigned char * data, int len, unsigned char * key, int keylen)
{
encrypt_wep(data, len, key, keylen);
return (check_crc_buf(data, len - 4));
}
void calc_pmk(const uint8_t * key,
const uint8_t * essid_pre,
uint8_t pmk[static PMK_LEN])
{
REQUIRE(key != NULL);
REQUIRE(essid_pre != NULL);
if (KDF_PBKDF2_SHA1(key, essid_pre, ustrlen(essid_pre), 4096, pmk, PMK_LEN)
!= 0)
errx(1, "Failed to compute PBKDF2 HMAC-SHA1");
}
void calc_mic(struct AP_info * ap,
unsigned char pmk[static 32],
unsigned char ptk[static 80],
unsigned char mic[static 20])
{
REQUIRE(ap != NULL);
int i;
unsigned char pke[100];
memcpy(pke, "Pairwise key expansion", 23);
if (memcmp(ap->wpa.stmac, ap->bssid, 6) < 0)
{
memcpy(pke + 23, ap->wpa.stmac, 6);
memcpy(pke + 29, ap->bssid, 6);
}
else
{
memcpy(pke + 23, ap->bssid, 6);
memcpy(pke + 29, ap->wpa.stmac, 6);
}
if (memcmp(ap->wpa.snonce, ap->wpa.anonce, 32) < 0)
{
memcpy(pke + 35, ap->wpa.snonce, 32);
memcpy(pke + 67, ap->wpa.anonce, 32);
}
else
{
memcpy(pke + 35, ap->wpa.anonce, 32);
memcpy(pke + 67, ap->wpa.snonce, 32);
}
for (i = 0; i < 4; i++)
{
pke[99] = i;
MAC_HMAC_SHA1(32, pmk, 100, pke, ptk + i * DIGEST_SHA1_MAC_LEN);
}
if (ap->wpa.keyver == 1)
{
MAC_HMAC_MD5(16, ptk, ap->wpa.eapol_size, ap->wpa.eapol, mic);
}
else
{
MAC_HMAC_SHA1(16, ptk, ap->wpa.eapol_size, ap->wpa.eapol, mic);
}
}
static inline unsigned long calc_crc(const unsigned char * buf, int len)
{
REQUIRE(buf != NULL);
unsigned long crc = 0xFFFFFFFF;
for (; len > 0; len--, buf++)
crc = crc_tbl[(crc ^ *buf) & 0xFF] ^ (crc >> 8);
return (~crc);
}
// without inversion, must be used for bit flipping attacks
static inline unsigned long calc_crc_plain(unsigned char * buf, int len)
{
REQUIRE(buf != NULL);
unsigned long crc = 0x00000000;
for (; len > 0; len--, buf++)
crc = crc_tbl[(crc ^ *buf) & 0xFF] ^ (crc >> 8);
return (crc);
}
/* CRC checksum verification routine */
int check_crc_buf(const unsigned char * buf, int len)
{
REQUIRE(buf != NULL);
unsigned long crc;
crc = calc_crc(buf, len);
buf += len;
return (((crc) &0xFF) == buf[0] && ((crc >> 8) & 0xFF) == buf[1]
&& ((crc >> 16) & 0xFF) == buf[2]
&& ((crc >> 24) & 0xFF) == buf[3]);
}
/* Add CRC32 */
int add_crc32(unsigned char * data, int length)
{
REQUIRE(data != NULL);
unsigned long crc;
crc = calc_crc(data, length);
data[length] = (uint8_t)((crc) &0xFF);
data[length + 1] = (uint8_t)((crc >> 8) & 0xFF);
data[length + 2] = (uint8_t)((crc >> 16) & 0xFF);
data[length + 3] = (uint8_t)((crc >> 24) & 0xFF);
return (0);
}
int add_crc32_plain(unsigned char * data, int length)
{
REQUIRE(data != NULL);
unsigned long crc;
crc = calc_crc_plain(data, length);
data[length] = (uint8_t)((crc) &0xFF);
data[length + 1] = (uint8_t)((crc >> 8) & 0xFF);
data[length + 2] = (uint8_t)((crc >> 16) & 0xFF);
data[length + 3] = (uint8_t)((crc >> 24) & 0xFF);
return (0);
}
int calc_crc_buf(const unsigned char * buf, int len)
{
REQUIRE(buf != NULL);
return (int) (calc_crc(buf, len));
}
static void * get_da(unsigned char * wh)
{
REQUIRE(wh != NULL);
if (wh[1] & IEEE80211_FC1_DIR_FROMDS)
return (wh + 4);
else
return (wh + 4 + 6 * 2);
}
static void * get_sa(unsigned char * wh)
{
REQUIRE(wh != NULL);
if (wh[1] & IEEE80211_FC1_DIR_FROMDS)
return (wh + 4 + 6 * 2);
else
return (wh + 4 + 6);
}
int is_ipv6(void * wh)
{
REQUIRE(wh != NULL);
if (memcmp((char *) wh + 4, "\x33\x33", 2) == 0
|| memcmp((char *) wh + 16, "\x33\x33", 2) == 0)
return (1);
return (0);
}
int is_dhcp_discover(void * wh, size_t len)
{
REQUIRE(wh != NULL);
if ((memcmp((char *) wh + 4, BROADCAST, 6) == 0
|| memcmp((char *) wh + 16, BROADCAST, 6) == 0)
&& (len >= 360 - 24 - 4 - 4 && len <= 380 - 24 - 4 - 4))
return (1);
return (0);
}
static inline int is_arp(void * wh, size_t len)
{
UNUSED_PARAM(wh);
const size_t arpsize = 8 + 8 + 10 * 2;
/* remove non BROADCAST frames? could be anything, but
* chances are good that we got an arp response tho. */
if (len == arpsize || len == 54) return (1);
return (0);
}
static inline int is_wlccp(void * wh, size_t len)
{
UNUSED_PARAM(wh);
const size_t wlccpsize = 58;
if (len == wlccpsize) return (1);
return (0);
}
int is_qos_arp_tkip(void * wh, int len)
{
REQUIRE(wh != NULL);
unsigned char * packet = (unsigned char *) wh;
const int qosarpsize
= (24 + 2) + 8 + (8 + (8 + 10 * 2)) + 8 + 4; // 82 in total
if ((packet[1] & 3) == 1) // to ds
{
if (len == qosarpsize) // always wireless
return (1);
}
if ((packet[1] & 3) == 2) // from ds
{
if (len == qosarpsize
|| len == qosarpsize + 18) // wireless or padded wired
return (1);
}
return (0);
}
static int is_spantree(void * wh)
{
REQUIRE(wh != NULL);
if (memcmp((char *) wh + 4, SPANTREE, 6) == 0
|| memcmp((char *) wh + 16, SPANTREE, 6) == 0)
return (1);
return (0);
}
static int is_cdp_vtp(void * wh)
{
REQUIRE(wh != NULL);
if (memcmp((char *) wh + 4, CDP_VTP, 6) == 0
|| memcmp((char *) wh + 16, CDP_VTP, 6) == 0)
return (1);
return (0);
}
/* weight is used for guesswork in PTW. Can be null if known_clear is not for
* PTW, but just for getting known clear-text.
*/
int known_clear(
void * clear, int * clen, int * weight, unsigned char * wh, size_t len)
{
REQUIRE(clear != NULL);
REQUIRE(clen != NULL);
REQUIRE(wh != NULL);
unsigned char * ptr = clear;
int num;
if (is_arp(wh, len)) /*arp*/
{
len = sizeof(S_LLC_SNAP_ARP) - 1;
memcpy(ptr, S_LLC_SNAP_ARP, len);
ptr += len;
/* arp hdr */
len = 6;
memcpy(ptr, "\x00\x01\x08\x00\x06\x04", len);
ptr += len;
/* type of arp */
len = 2;
if (memcmp(get_da(wh), "\xff\xff\xff\xff\xff\xff", 6) == 0)
memcpy(ptr, "\x00\x01", len);
else
memcpy(ptr, "\x00\x02", len);
ptr += len;
/* src mac */
len = 6;
memcpy(ptr, get_sa(wh), len);
ptr += len;
len = ptr - ((unsigned char *) clear);
*clen = (int) len;
if (weight) weight[0] = 256;
return (1);
}
else if (is_wlccp(wh, len)) /*wlccp*/
{
len = sizeof(S_LLC_SNAP_WLCCP) - 1;
memcpy(ptr, S_LLC_SNAP_WLCCP, len);
ptr += len;
/* wlccp hdr */
len = 4;
memcpy(ptr, "\x00\x32\x40\x01", len);
ptr += len;
/* dst mac */
len = 6;
memcpy(ptr, get_da(wh), len);
ptr += len;
len = ptr - ((unsigned char *) clear);
*clen = (int) len;
if (weight) weight[0] = 256;
return (1);
}
else if (is_spantree(wh)) /*spantree*/
{
len = sizeof(S_LLC_SNAP_SPANTREE) - 1;
memcpy(ptr, S_LLC_SNAP_SPANTREE, len);
ptr += len;
len = ptr - ((unsigned char *) clear);
*clen = (int) len;
if (weight) weight[0] = 256;
return (1);
}
else if (is_cdp_vtp(wh)) /*spantree*/
{
len = sizeof(S_LLC_SNAP_CDP) - 1;
memcpy(ptr, S_LLC_SNAP_CDP, len);
ptr += len;
len = ptr - ((unsigned char *) clear);
*clen = (int) len;
if (weight) weight[0] = 256;
return (1);
}
else /* IP */
{
unsigned short iplen = htons((uint16_t)(len - 8));
len = sizeof(S_LLC_SNAP_IP) - 1;
memcpy(ptr, S_LLC_SNAP_IP, len);
ptr += len;
// version=4; header_length=20; services=0
len = 2;
memcpy(ptr, "\x45\x00", len);
ptr += len;
// ip total length
memcpy(ptr, &iplen, len);
ptr += len;
/* no guesswork */
if (!weight)
{
*clen = (int) (ptr - ((unsigned char *) clear));
return (1);
}
/* setting IP ID 0 is ok, as we
* bruteforce it later
*/
// ID=0
/* len = 2; */
memcpy(ptr, "\x00\x00", len);
ptr += len;
// ip flags=don't fragment
/* len = 2; */
memcpy(ptr, "\x40\x00", len);
ptr += len;
len = ptr - ((unsigned char *) clear);
*clen = (int) len;
memmove((char *) clear + 32, clear, len);
memcpy((char *) clear + 32 + 14, "\x00\x00", 2); // ip flags=none
num = 2;
ALLEGE(weight);
weight[0] = 220;
weight[1] = 36;
return (num);
}
}
/* derive the pairwise transcient keys from a bunch of stuff */
int calc_ptk(struct WPA_ST_info * wpa, unsigned char pmk[static 32])
{
REQUIRE(wpa != NULL);
int i;
unsigned char pke[100];
unsigned char mic[20];
memcpy(pke, "Pairwise key expansion", 23);
if (memcmp(wpa->stmac, wpa->bssid, 6) < 0)
{
memcpy(pke + 23, wpa->stmac, 6);
memcpy(pke + 29, wpa->bssid, 6);
}
else
{
memcpy(pke + 23, wpa->bssid, 6);
memcpy(pke + 29, wpa->stmac, 6);
}
if (memcmp(wpa->snonce, wpa->anonce, 32) < 0)
{
memcpy(pke + 35, wpa->snonce, 32);
memcpy(pke + 67, wpa->anonce, 32);
}
else
{
memcpy(pke + 35, wpa->anonce, 32);
memcpy(pke + 67, wpa->snonce, 32);
}
for (i = 0; i < 4; i++)
{
pke[99] = (uint8_t) i;
MAC_HMAC_SHA1(32, pmk, 100, pke, wpa->ptk + i * DIGEST_SHA1_MAC_LEN);
}
/* check the EAPOL frame MIC */
if ((wpa->keyver & 0x07) == 1)
MAC_HMAC_MD5(16, wpa->ptk, wpa->eapol_size, wpa->eapol, mic);
else
MAC_HMAC_SHA1(16, wpa->ptk, wpa->eapol_size, wpa->eapol, mic);
return (memcmp(mic, wpa->keymic, 16) == 0); //-V512
}
static int init_michael(struct Michael * mic, const unsigned char key[static 8])
{
REQUIRE(mic != NULL);
mic->key0 = UBTOUL(key[0]) << 0UL | UBTOUL(key[1]) << 8UL
| UBTOUL(key[2]) << 16UL | UBTOUL(key[3] << 24UL);
mic->key1 = UBTOUL(key[4]) << 0UL | UBTOUL(key[5]) << 8UL
| UBTOUL(key[6]) << 16UL | UBTOUL(key[7] << 24UL);
// and reset the message
mic->left = mic->key0;
mic->right = mic->key1;
mic->nBytesInM = 0UL;
mic->message = 0UL;
return (0);
}
static int michael_append_byte(struct Michael * mic, unsigned char byte)
{
REQUIRE(mic != NULL);
mic->message |= (UBTOUL(byte) << (8UL * mic->nBytesInM));
mic->nBytesInM++;
// Process the word if it is full.
if (mic->nBytesInM >= 4UL)
{
mic->left ^= mic->message;
mic->right ^= ROL32(mic->left, 17);
mic->left += mic->right;
mic->right ^= ((mic->left & 0xff00ff00) >> 8UL)
| ((mic->left & 0x00ff00ff) << 8UL);
mic->left += mic->right;
mic->right ^= ROL32(mic->left, 3);
mic->left += mic->right;
mic->right ^= ROR32(mic->left, 2);
mic->left += mic->right;
// Clear the buffer
mic->message = 0UL;
mic->nBytesInM = 0UL;
}
return (0);
}
static int michael_remove_byte(struct Michael * mic,
const unsigned char bytes[static 4])
{
REQUIRE(mic != NULL);
if (mic->nBytesInM == 0)
{
// Clear the buffer
mic->message = UBTOUL(bytes[0]) << 0UL | UBTOUL(bytes[1]) << 8UL
| UBTOUL(bytes[2]) << 16UL | UBTOUL(bytes[3]) << 24UL;
mic->nBytesInM = 4;
mic->left -= mic->right;
mic->right ^= ROR32(mic->left, 2);
mic->left -= mic->right;
mic->right ^= ROL32(mic->left, 3);
mic->left -= mic->right;
mic->right ^= ((mic->left & 0xff00ff00) >> 8UL)
| ((mic->left & 0x00ff00ff) << 8UL);
mic->left -= mic->right;
mic->right ^= ROL32(mic->left, 17);
mic->left ^= mic->message;
}
mic->nBytesInM--;
mic->message &= ~(0xFFUL << (8UL * mic->nBytesInM));
return (0);
}
static int
michael_append(struct Michael * mic, unsigned char * bytes, int length)
{
while (length > 0)
{
michael_append_byte(mic, *bytes++);
length--;
}
return (0);
}
static int
michael_remove(struct Michael * mic, unsigned char * bytes, int length)
{
while (length >= 4)
{
michael_remove_byte(mic, (bytes + length - 4));
length--;
}
return (0);
}
static int michael_finalize(struct Michael * mic)
{
REQUIRE(mic != NULL);
// Append the minimum padding
michael_append_byte(mic, 0x5a);
michael_append_byte(mic, 0);
michael_append_byte(mic, 0);
michael_append_byte(mic, 0);
michael_append_byte(mic, 0);
// and then zeroes until the length is a multiple of 4
while (mic->nBytesInM != 0)
{
michael_append_byte(mic, 0);
}
// The appendByte function has already computed the result.
mic->mic[0] = (uint8_t)((mic->left >> 0) & 0xff);
mic->mic[1] = (uint8_t)((mic->left >> 8) & 0xff);
mic->mic[2] = (uint8_t)((mic->left >> 16) & 0xff);
mic->mic[3] = (uint8_t)((mic->left >> 24) & 0xff);
mic->mic[4] = (uint8_t)((mic->right >> 0) & 0xff);
mic->mic[5] = (uint8_t)((mic->right >> 8) & 0xff);
mic->mic[6] = (uint8_t)((mic->right >> 16) & 0xff);
mic->mic[7] = (uint8_t)((mic->right >> 24) & 0xff);
return (0);
}
static int michael_finalize_zero(struct Michael * mic)
{
REQUIRE(mic != NULL);
// Append the minimum padding
michael_append_byte(mic, 0);
michael_append_byte(mic, 0);
michael_append_byte(mic, 0);
michael_append_byte(mic, 0);
michael_append_byte(mic, 0);
// and then zeroes until the length is a multiple of 4
while (mic->nBytesInM != 0)
{
michael_append_byte(mic, 0);
}
// The appendByte function has already computed the result.
mic->mic[0] = (uint8_t)((mic->left >> 0) & 0xff);
mic->mic[1] = (uint8_t)((mic->left >> 8) & 0xff);
mic->mic[2] = (uint8_t)((mic->left >> 16) & 0xff);
mic->mic[3] = (uint8_t)((mic->left >> 24) & 0xff);
mic->mic[4] = (uint8_t)((mic->right >> 0) & 0xff);
mic->mic[5] = (uint8_t)((mic->right >> 8) & 0xff);
mic->mic[6] = (uint8_t)((mic->right >> 16) & 0xff);
mic->mic[7] = (uint8_t)((mic->right >> 24) & 0xff);
return (0);
}
int michael_test(unsigned char key[static 8],
unsigned char * message,
int length,
unsigned char out[static 8])
{
int i = 0;
struct Michael mic0;
struct Michael mic1;
struct Michael mic2;
struct Michael mic;
init_michael(&mic0, (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00");
init_michael(&mic1, (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00");
init_michael(&mic2, (unsigned char *) "\x00\x00\x00\x00\x00\x00\x00\x00");
michael_append_byte(&mic0, 0x02);
michael_append_byte(&mic1, 0x01);
michael_append_byte(&mic2, 0x03);
michael_finalize(&mic0);
michael_finalize_zero(&mic1);
michael_finalize(&mic2);
printf("Blub 2:");
for (i = 0; i < 8; i++)
{
printf("%02X ", mic0.mic[i]);
}
printf("\n");
printf("Blub 1:");
for (i = 0; i < 8; i++)
{
printf("%02X ", mic1.mic[i]);
}
printf("\n");
printf("Blub 3:");
for (i = 0; i < 8; i++)
{
printf("%02X ", mic2.mic[i]);
}
printf("\n");
init_michael(&mic, key);
michael_append(&mic, message, length);
michael_finalize(&mic);
return (memcmp(mic.mic, out, 8) == 0);
}
int calc_tkip_mic_key(unsigned char * packet,
int length,
unsigned char key[static 8])
{
REQUIRE(packet != NULL);
int z, is_qos = 0;
unsigned char smac[6], dmac[6], bssid[6];
unsigned char prio[4];
unsigned char message[4096];
unsigned char * ptr;
struct Michael mic;
memset(message, 0, 4096);
z = ((packet[1] & 3) != 3) ? 24 : 30;
if (length < z) return (0);
/* Check if 802.11e (QoS) */
if ((packet[0] & 0x80) == 0x80)
{
z += 2;
is_qos = 1;
}
memset(prio, 0, 4);
if (is_qos)
{
prio[0] = (uint8_t)(packet[z - 2] & 0x0f);
}
switch (packet[1] & 3)
{
case 0:
memcpy(bssid, packet + 16, 6);
memcpy(dmac, packet + 4, 6);
memcpy(smac, packet + 10, 6);
break;
case 1:
memcpy(bssid, packet + 4, 6);
memcpy(dmac, packet + 16, 6);
memcpy(smac, packet + 10, 6);
break;
case 2:
memcpy(bssid, packet + 10, 6);
memcpy(dmac, packet + 4, 6);
memcpy(smac, packet + 16, 6);
break;
default:
memcpy(bssid, packet + 10, 6);
memcpy(dmac, packet + 16, 6);
memcpy(smac, packet + 24, 6);
break;
}
ptr = message;
memcpy(ptr, dmac, 6);
ptr += 6;
memcpy(ptr, smac, 6);
ptr += 6;
memcpy(ptr, prio, 4);
ptr += 4;
memcpy(ptr, packet + z, length - z - 8UL);
ptr += length - z - 8;
memcpy(ptr, "\x5a", 1);
ptr += 1;
memcpy(ptr, ZERO, 4);
ptr += 4;
if ((ptr - message) % 4 > 0)
{
memcpy(ptr, ZERO, 4 - ((ptr - message) % 4));
ptr += 4 - ((ptr - message) % 4);
}
init_michael(&mic, packet + length - 8);
michael_remove(&mic, message, (int) (ptr - message));
mic.mic[0] = (uint8_t)((mic.left >> 0) & 0xFF);
mic.mic[1] = (uint8_t)((mic.left >> 8) & 0xFF);
mic.mic[2] = (uint8_t)((mic.left >> 16) & 0xFF);
mic.mic[3] = (uint8_t)((mic.left >> 24) & 0xFF);
mic.mic[4] = (uint8_t)((mic.right >> 0) & 0xFF);
mic.mic[5] = (uint8_t)((mic.right >> 8) & 0xFF);
mic.mic[6] = (uint8_t)((mic.right >> 16) & 0xFF);
mic.mic[7] = (uint8_t)((mic.right >> 24) & 0xFF);
memcpy(key, mic.mic, 8);
return (0);
}
int calc_tkip_mic(unsigned char * packet,
int length,
unsigned char ptk[static 80],
unsigned char value[static 8])
{
REQUIRE(packet != NULL);
int z, koffset = 0, is_qos = 0;
unsigned char smac[6], dmac[6], bssid[6];
unsigned char prio[4];
struct Michael mic;
z = ((packet[1] & 3) != 3) ? 24 : 30;
if (length < z) return (0);
/* Check if 802.11e (QoS) */
if ((packet[0] & 0x80) == 0x80)
{
z += 2;
is_qos = 1;
}
switch (packet[1] & 3)
{
case 0:
memcpy(bssid, packet + 16, 6);
memcpy(dmac, packet + 4, 6);
memcpy(smac, packet + 10, 6);
break;
case 1:
memcpy(bssid, packet + 4, 6);
memcpy(dmac, packet + 16, 6);
memcpy(smac, packet + 10, 6);
koffset = 48 + 8;
break;
case 2:
memcpy(bssid, packet + 10, 6);
memcpy(dmac, packet + 4, 6);
memcpy(smac, packet + 16, 6);
koffset = 48;
break;
default:
memcpy(bssid, packet + 10, 6);
memcpy(dmac, packet + 16, 6);
memcpy(smac, packet + 24, 6);
break;
}
if (koffset != 48 && koffset != 48 + 8) return (1);
init_michael(&mic, ptk + koffset);
michael_append(&mic, dmac, 6);
michael_append(&mic, smac, 6);
memset(prio, 0, 4);
if (is_qos)
{
prio[0] = (uint8_t)(packet[z - 2] & 0x0f);
}
michael_append(&mic, prio, 4);
michael_append(&mic, packet + z, length - z);
michael_finalize(&mic);
memcpy(value, mic.mic, 8);
return (0);
}
static const unsigned short TkipSbox[2][256]
= {{0xC6A5, 0xF884, 0xEE99, 0xF68D, 0xFF0D, 0xD6BD, 0xDEB1, 0x9154, 0x6050,
0x0203, 0xCEA9, 0x567D, 0xE719, 0xB562, 0x4DE6, 0xEC9A, 0x8F45, 0x1F9D,
0x8940, 0xFA87, 0xEF15, 0xB2EB, 0x8EC9, 0xFB0B, 0x41EC, 0xB367, 0x5FFD,
0x45EA, 0x23BF, 0x53F7, 0xE496, 0x9B5B, 0x75C2, 0xE11C, 0x3DAE, 0x4C6A,
0x6C5A, 0x7E41, 0xF502, 0x834F, 0x685C, 0x51F4, 0xD134, 0xF908, 0xE293,
0xAB73, 0x6253, 0x2A3F, 0x080C, 0x9552, 0x4665, 0x9D5E, 0x3028, 0x37A1,
0x0A0F, 0x2FB5, 0x0E09, 0x2436, 0x1B9B, 0xDF3D, 0xCD26, 0x4E69, 0x7FCD,
0xEA9F, 0x121B, 0x1D9E, 0x5874, 0x342E, 0x362D, 0xDCB2, 0xB4EE, 0x5BFB,
0xA4F6, 0x764D, 0xB761, 0x7DCE, 0x527B, 0xDD3E, 0x5E71, 0x1397, 0xA6F5,
0xB968, 0x0000, 0xC12C, 0x4060, 0xE31F, 0x79C8, 0xB6ED, 0xD4BE, 0x8D46,
0x67D9, 0x724B, 0x94DE, 0x98D4, 0xB0E8, 0x854A, 0xBB6B, 0xC52A, 0x4FE5,
0xED16, 0x86C5, 0x9AD7, 0x6655, 0x1194, 0x8ACF, 0xE910, 0x0406, 0xFE81,
0xA0F0, 0x7844, 0x25BA, 0x4BE3, 0xA2F3, 0x5DFE, 0x80C0, 0x058A, 0x3FAD,
0x21BC, 0x7048, 0xF104, 0x63DF, 0x77C1, 0xAF75, 0x4263, 0x2030, 0xE51A,
0xFD0E, 0xBF6D, 0x814C, 0x1814, 0x2635, 0xC32F, 0xBEE1, 0x35A2, 0x88CC,
0x2E39, 0x9357, 0x55F2, 0xFC82, 0x7A47, 0xC8AC, 0xBAE7, 0x322B, 0xE695,
0xC0A0, 0x1998, 0x9ED1, 0xA37F, 0x4466, 0x547E, 0x3BAB, 0x0B83, 0x8CCA,
0xC729, 0x6BD3, 0x283C, 0xA779, 0xBCE2, 0x161D, 0xAD76, 0xDB3B, 0x6456,
0x744E, 0x141E, 0x92DB, 0x0C0A, 0x486C, 0xB8E4, 0x9F5D, 0xBD6E, 0x43EF,
0xC4A6, 0x39A8, 0x31A4, 0xD337, 0xF28B, 0xD532, 0x8B43, 0x6E59, 0xDAB7,
0x018C, 0xB164, 0x9CD2, 0x49E0, 0xD8B4, 0xACFA, 0xF307, 0xCF25, 0xCAAF,
0xF48E, 0x47E9, 0x1018, 0x6FD5, 0xF088, 0x4A6F, 0x5C72, 0x3824, 0x57F1,
0x73C7, 0x9751, 0xCB23, 0xA17C, 0xE89C, 0x3E21, 0x96DD, 0x61DC, 0x0D86,
0x0F85, 0xE090, 0x7C42, 0x71C4, 0xCCAA, 0x90D8, 0x0605, 0xF701, 0x1C12,
0xC2A3, 0x6A5F, 0xAEF9, 0x69D0, 0x1791, 0x9958, 0x3A27, 0x27B9, 0xD938,
0xEB13, 0x2BB3, 0x2233, 0xD2BB, 0xA970, 0x0789, 0x33A7, 0x2DB6, 0x3C22,
0x1592, 0xC920, 0x8749, 0xAAFF, 0x5078, 0xA57A, 0x038F, 0x59F8, 0x0980,
0x1A17, 0x65DA, 0xD731, 0x84C6, 0xD0B8, 0x82C3, 0x29B0, 0x5A77, 0x1E11,
0x7BCB, 0xA8FC, 0x6DD6, 0x2C3A},
{0xA5C6, 0x84F8, 0x99EE, 0x8DF6, 0x0DFF, 0xBDD6, 0xB1DE, 0x5491, 0x5060,
0x0302, 0xA9CE, 0x7D56, 0x19E7, 0x62B5, 0xE64D, 0x9AEC, 0x458F, 0x9D1F,
0x4089, 0x87FA, 0x15EF, 0xEBB2, 0xC98E, 0x0BFB, 0xEC41, 0x67B3, 0xFD5F,
0xEA45, 0xBF23, 0xF753, 0x96E4, 0x5B9B, 0xC275, 0x1CE1, 0xAE3D, 0x6A4C,
0x5A6C, 0x417E, 0x02F5, 0x4F83, 0x5C68, 0xF451, 0x34D1, 0x08F9, 0x93E2,
0x73AB, 0x5362, 0x3F2A, 0x0C08, 0x5295, 0x6546, 0x5E9D, 0x2830, 0xA137,
0x0F0A, 0xB52F, 0x090E, 0x3624, 0x9B1B, 0x3DDF, 0x26CD, 0x694E, 0xCD7F,
0x9FEA, 0x1B12, 0x9E1D, 0x7458, 0x2E34, 0x2D36, 0xB2DC, 0xEEB4, 0xFB5B,
0xF6A4, 0x4D76, 0x61B7, 0xCE7D, 0x7B52, 0x3EDD, 0x715E, 0x9713, 0xF5A6,
0x68B9, 0x0000, 0x2CC1, 0x6040, 0x1FE3, 0xC879, 0xEDB6, 0xBED4, 0x468D,
0xD967, 0x4B72, 0xDE94, 0xD498, 0xE8B0, 0x4A85, 0x6BBB, 0x2AC5, 0xE54F,
0x16ED, 0xC586, 0xD79A, 0x5566, 0x9411, 0xCF8A, 0x10E9, 0x0604, 0x81FE,
0xF0A0, 0x4478, 0xBA25, 0xE34B, 0xF3A2, 0xFE5D, 0xC080, 0x8A05, 0xAD3F,
0xBC21, 0x4870, 0x04F1, 0xDF63, 0xC177, 0x75AF, 0x6342, 0x3020, 0x1AE5,
0x0EFD, 0x6DBF, 0x4C81, 0x1418, 0x3526, 0x2FC3, 0xE1BE, 0xA235, 0xCC88,
0x392E, 0x5793, 0xF255, 0x82FC, 0x477A, 0xACC8, 0xE7BA, 0x2B32, 0x95E6,
0xA0C0, 0x9819, 0xD19E, 0x7FA3, 0x6644, 0x7E54, 0xAB3B, 0x830B, 0xCA8C,
0x29C7, 0xD36B, 0x3C28, 0x79A7, 0xE2BC, 0x1D16, 0x76AD, 0x3BDB, 0x5664,
0x4E74, 0x1E14, 0xDB92, 0x0A0C, 0x6C48, 0xE4B8, 0x5D9F, 0x6EBD, 0xEF43,
0xA6C4, 0xA839, 0xA431, 0x37D3, 0x8BF2, 0x32D5, 0x438B, 0x596E, 0xB7DA,
0x8C01, 0x64B1, 0xD29C, 0xE049, 0xB4D8, 0xFAAC, 0x07F3, 0x25CF, 0xAFCA,
0x8EF4, 0xE947, 0x1810, 0xD56F, 0x88F0, 0x6F4A, 0x725C, 0x2438, 0xF157,
0xC773, 0x5197, 0x23CB, 0x7CA1, 0x9CE8, 0x213E, 0xDD96, 0xDC61, 0x860D,
0x850F, 0x90E0, 0x427C, 0xC471, 0xAACC, 0xD890, 0x0506, 0x01F7, 0x121C,
0xA3C2, 0x5F6A, 0xF9AE, 0xD069, 0x9117, 0x5899, 0x273A, 0xB927, 0x38D9,
0x13EB, 0xB32B, 0x3322, 0xBBD2, 0x70A9, 0x8907, 0xA733, 0xB62D, 0x223C,
0x9215, 0x20C9, 0x4987, 0xFFAA, 0x7850, 0x7AA5, 0x8F03, 0xF859, 0x8009,
0x171A, 0xDA65, 0x31D7, 0xC684, 0xB8D0, 0xC382, 0xB029, 0x775A, 0x111E,
0xCB7B, 0xFCA8, 0xD66D, 0x3A2C}};
/* TKIP (RC4 + key mixing) decryption routine */
#define ROTR1(x) ((((x) >> 1) & 0x7FFF) ^ (((x) &1) << 15))
#define LO8(x) ((x) &0x00FF)
#define LO16(x) ((x) &0xFFFF)
#define HI8(x) (((x) >> 8) & 0x00FF)
#define HI16(x) (((x) >> 16) & 0xFFFF)
#define MK16(hi, lo) ((lo) ^ (LO8(hi) << 8))
#define TK16(N) MK16(TK1[2 * (N) + 1], TK1[2 * (N)])
#define _S_(x) (TkipSbox[0][LO8(x)] ^ TkipSbox[1][HI8(x)])
int calc_tkip_ppk(unsigned char * h80211,
int caplen,
unsigned char TK1[static 16],
unsigned char key[static 16])
{
UNUSED_PARAM(caplen);
REQUIRE(h80211 != NULL);
int i, z;
uint32_t IV32;
uint16_t IV16;
uint16_t PPK[6];
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if (GET_SUBTYPE(h80211[0]) == IEEE80211_FC0_SUBTYPE_QOS)
{
z += 2;
}
IV16 = (uint16_t) MK16(h80211[z], h80211[z + 2]);
IV32 = (h80211[z + 4]) | (h80211[z + 5] << 8) | (h80211[z + 6] << 16)
| (h80211[z + 7] << 24);
PPK[0] = (uint16_t) LO16(IV32);
PPK[1] = (uint16_t) HI16(IV32);
PPK[2] = (uint16_t) MK16(h80211[11], h80211[10]);
PPK[3] = (uint16_t) MK16(h80211[13], h80211[12]);
PPK[4] = (uint16_t) MK16(h80211[15], h80211[14]);
for (i = 0; i < 8; i++)
{
PPK[0] += _S_(PPK[4] ^ TK16((i & 1) + 0));
PPK[1] += _S_(PPK[0] ^ TK16((i & 1) + 2));
PPK[2] += _S_(PPK[1] ^ TK16((i & 1) + 4));
PPK[3] += _S_(PPK[2] ^ TK16((i & 1) + 6));
PPK[4] += _S_(PPK[3] ^ TK16((i & 1) + 0)) + i;
}
PPK[5] = PPK[4] + IV16;
PPK[0] += _S_(PPK[5] ^ TK16(0));
PPK[1] += _S_(PPK[0] ^ TK16(1));
PPK[2] += _S_(PPK[1] ^ TK16(2));
PPK[3] += _S_(PPK[2] ^ TK16(3));
PPK[4] += _S_(PPK[3] ^ TK16(4));
PPK[5] += _S_(PPK[4] ^ TK16(5));
PPK[0] += ROTR1(PPK[5] ^ TK16(6));
PPK[1] += ROTR1(PPK[0] ^ TK16(7));
PPK[2] += ROTR1(PPK[1]);
PPK[3] += ROTR1(PPK[2]);
PPK[4] += ROTR1(PPK[3]);
PPK[5] += ROTR1(PPK[4]);
key[0] = (uint8_t) HI8(IV16);
key[1] = (uint8_t)((HI8(IV16) | 0x20) & 0x7F);
key[2] = (uint8_t) LO8(IV16);
key[3] = (uint8_t) LO8((PPK[5] ^ TK16(0)) >> 1);
for (i = 0; i < 6; i++)
{
key[4 + (2 * i)] = (uint8_t) LO8(PPK[i]);
key[5 + (2 * i)] = (uint8_t) HI8(PPK[i]);
}
return (0);
}
static int calc_tkip_mic_skip_eiv(unsigned char * packet,
int length,
unsigned char ptk[static 80],
unsigned char value[static 8])
{
REQUIRE(packet != NULL);
int z, koffset = 0, is_qos = 0;
unsigned char smac[6], dmac[6], bssid[6];
unsigned char prio[4] = {0};
struct Michael mic;
z = ((packet[1] & 3) != 3) ? 24 : 30;
if (length < z) return (0);
/* Check if 802.11e (QoS) */
if ((packet[0] & 0x80) == 0x80)
{
z += 2;
is_qos = 1;
}
switch (packet[1] & 3)
{
case 0:
memcpy(bssid, packet + 16, 6);
memcpy(dmac, packet + 4, 6);
memcpy(smac, packet + 10, 6);
break;
case 1:
memcpy(bssid, packet + 4, 6);
memcpy(dmac, packet + 16, 6);
memcpy(smac, packet + 10, 6);
koffset = 48 + 8;
break;
case 2:
memcpy(bssid, packet + 10, 6);
memcpy(dmac, packet + 4, 6);
memcpy(smac, packet + 16, 6);
koffset = 48;
break;
default:
memcpy(bssid, packet + 10, 6);
memcpy(dmac, packet + 16, 6);
memcpy(smac, packet + 24, 6);
break;
}
if (koffset != 48 && koffset != 48 + 8) return (1);
init_michael(&mic, ptk + koffset);
michael_append(&mic, dmac, 6);
michael_append(&mic, smac, 6);
// memset(prio, 0, 4);
if (is_qos)
{
prio[0] = (uint8_t)(packet[z - 2] & 0x0f);
}
michael_append(&mic, prio, 4);
michael_append(&mic, packet + z + 8, length - z - 8);
michael_finalize(&mic);
memcpy(value, mic.mic, 8);
return (0);
}
void encrypt_tkip(unsigned char * h80211,
int caplen,
unsigned char ptk[static 80])
{
REQUIRE(h80211 != NULL);
unsigned char * TK1 = ptk + 32;
unsigned char K[16];
int z;
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if (GET_SUBTYPE(h80211[0]) == IEEE80211_FC0_SUBTYPE_QOS)
{
z += 2;
}
// Update the MIC in the frame...
// Had to mod calc_tkip_mic to skip extended IV to avoid memmoves
unsigned char micval[8] = {0};
calc_tkip_mic_skip_eiv(h80211, caplen - 12, ptk, micval);
unsigned char * mic_in_packet = h80211 + caplen - 12;
memcpy(mic_in_packet, micval, 8);
// Update the CRC in the frame before encrypting
uint32_t crc = (uint32_t) calc_crc(h80211 + z + 8, caplen - z - 8 - 4);
unsigned char * buf = h80211 + z + 8;
buf += caplen - z - 8 - 4;
buf[0] = (uint8_t)((crc) &0xFF);
buf[2] = (uint8_t)((crc >> 16) & 0xFF);
buf[1] = (uint8_t)((crc >> 8) & 0xFF);
buf[3] = (uint8_t)((crc >> 24) & 0xFF);
calc_tkip_ppk(h80211, caplen, TK1, K);
decrypt_wep(h80211 + z + 8, caplen - z - 8, K, 16);
}
int decrypt_tkip(unsigned char * h80211,
int caplen,
unsigned char TK1[static 16])
{
REQUIRE(h80211 != NULL);
unsigned char K[16];
int z;
z = ((h80211[1] & 3) != 3) ? 24 : 30;
if (GET_SUBTYPE(h80211[0]) == IEEE80211_FC0_SUBTYPE_QOS)
{
z += 2;
}
calc_tkip_ppk(h80211, caplen, TK1, K);
return (decrypt_wep(h80211 + z + 8, caplen - z - 8, K, 16));
}
/* CCMP (AES-CTR-MAC) decryption routine */
static inline void XOR(unsigned char * dst, unsigned char * src, int len)
{
REQUIRE(dst != NULL);
REQUIRE(src != NULL);
for (int i = 0; i < len; i++) dst[i] ^= src[i];
}
// Important documents for the implementation of encrypt_ccmp() and
// decrypt_ccmp():
//
// * RFC 3610 Counter with CBC-MAC (CCM)
// https://www.ietf.org/rfc/rfc3610.txt
//
// * IEEE 802.11(TM)-2012
// http://standards.ieee.org/about/get/802/802.11.html
//
// Note: RFC uses the abbreviation MAC (Message Authentication Code, or
// value U in the RFC). It is the same as IEEE's MIC (Message
// Integrity Code)
// encrypt_ccmp() takes an h80211 frame and encrypts it in-place using CCMP.
// This results in a frame that is 16 bytes longer than the original, take this
// into account when allocating h80211! encrypt() returns the new length (and
// thus the offset where the caller needs to write the FCS).
// caplen is the combined length of the 802.11 header and data, not the FCS!
int encrypt_ccmp(unsigned char * h80211,
int caplen,
unsigned char TK1[static 16],
unsigned char PN[static 6])
{
REQUIRE(h80211 != NULL);
int is_a4, i, z, blocks, is_qos;
int data_len, last, offset;
unsigned char B0[16], B[16], MIC[16];
unsigned char AAD[32];
Cipher_AES_CTX * aes_ctx;
is_a4 = (h80211[1] & 3) == 3;
is_qos = (h80211[0] & 0x8C) == 0x88;
z = 24 + 6 * is_a4;
z += 2 * is_qos;
// Insert CCMP header
memmove(h80211 + z + 8, h80211 + z, (size_t) caplen - z);
h80211[z + 0] = PN[5];
h80211[z + 1] = PN[4];
h80211[z + 2] = 0x00; // Reserved -> 0
h80211[z + 3] = 0x20; // ExtIV=1, KeyID=0
h80211[z + 4] = PN[3];
h80211[z + 5] = PN[2];
h80211[z + 6] = PN[1];
h80211[z + 7] = PN[0];
data_len = caplen - z;
// B_0 := B0
B0[0] = 0x59; // Flags
B0[1] = 0; // Nonce := CCM Nonce: - Nonce flags
memcpy(B0 + 2, h80211 + 10, 6); // - A2
memcpy(B0 + 8, PN, 6); // - PN
B0[14] = (uint8_t)((data_len >> 8) & 0xFF); // l(m)
B0[15] = (uint8_t)(data_len & 0xFF); // l(m)
// B_1 := AAD[ 0..15]
// B_2 := AAD[16..31]
// AAD[ 0.. 1] = l(a)
// AAD[ 2..31] = a
memset(AAD, 0, sizeof(AAD));
AAD[2] = (uint8_t)(h80211[0] & 0x8F); // AAD[2..3] = FC
AAD[3] = (uint8_t)(h80211[1] & 0xC7); //
memcpy(AAD + 4, h80211 + 4, 3 * 6); // AAD[4..21] = [A1,A2,A3]
AAD[22] = (uint8_t)(h80211[22] & 0x0F); // AAD[22] = SC
if (is_a4)
{
memcpy(AAD + 24, h80211 + 24, 6); // AAD[24..29] = A4
if (is_qos)
{
AAD[30] = (uint8_t)(h80211[z - 2] & 0x0F); // AAD[30..31] = QC
AAD[31] = 0; //
B0[1] = AAD[30]; // B0[ 1] = CCM Nonce flags
AAD[1] = 22 + 2 + 6; // AAD[ 0.. 1] = l(a)
}
else
{
memset(&AAD[30], 0, 2); // AAD[30..31] = QC
B0[1] = 0; // B0[ 1] = CCM Nonce flags
AAD[1] = 22 + 6; // AAD[ 0.. 1] = l(a)
}
}
else
{
if (is_qos)
{
AAD[24] = (uint8_t)(h80211[z - 2] & 0x0F); // AAD[24..25] = QC
AAD[25] = 0; //
B0[1] = AAD[24]; // B0[ 1] = CCM Nonce flags
AAD[1] = 22 + 2; // AAD[ 0.. 1] = l(a)
}
else
{
memset(&AAD[24], 0, 2); // AAD[24..25] = QC
B0[1] = 0; // B0[ 1] = CCM Nonce flags
AAD[1] = 22; // AAD[ 0.. 1] = l(a)
}
}
aes_ctx = Cipher_AES_Encrypt_Init(16, TK1);
REQUIRE(aes_ctx != NULL);
Cipher_AES_Encrypt(aes_ctx, B0, MIC); // X_1 := E( K, B_0 )
XOR(MIC, AAD, 16); // X_2 := E( K, X_1 XOR B_1 )
Cipher_AES_Encrypt(aes_ctx, MIC, MIC);
XOR(MIC, AAD + 16, 16); // X_3 := E( K, X_2 XOR B_2 )
Cipher_AES_Encrypt(aes_ctx, MIC, MIC);
// A_i := B0
// B0[ 0] = Flags
// B0[ 1..13] = Nonce := CCM Nonce
// B0[14..15] = i
B0[0] &= 0x07;
B0[14] = B0[15] = 0;
Cipher_AES_Encrypt(aes_ctx, B0, B); // S_0 := E( K, A_i )
memcpy(h80211 + z + 8 + data_len, B, 8); //-V512
// ^^^^^^^^^^^^^^^^^^^ ^
// S_0[0..7]/future U S_0
blocks = (data_len + 16 - 1) / 16;
last = data_len % 16;
offset = z + 8;
for (i = 1; i <= blocks; i++)
{
int n = (last > 0 && i == blocks) ? last : 16;
XOR(MIC, h80211 + offset, n); // X_i+3 := E( K, X_i+2 XOR B_i+2 )
Cipher_AES_Encrypt(aes_ctx, MIC, MIC);
// (X_i+2 ^^^)(^^^ X_i+3)
// The message is encrypted by XORing the octets of message m with the
// first l(m) octets of the concatenation of S_1, S_2, S_3, ... .
B0[14] = (uint8_t)((i >> 8) & 0xFF); // A_i[14..15] = i
B0[15] = (uint8_t)(i & 0xFF); //
Cipher_AES_Encrypt(aes_ctx, B0, B); // S_i := E( K, A_i )
XOR(h80211 + offset, B, n);
// [B_3, ..., B_n] := m
offset += n;
}
Cipher_AES_Encrypt_Deinit(aes_ctx);
aes_ctx = NULL;
// T := X_i+3[ 0.. 7]
// U := T XOR S_0[ 0.. 7]
XOR(h80211 + offset, MIC, 8);
return (z + 8 + data_len + 8);
}
int decrypt_ccmp(unsigned char * h80211,
int caplen,
unsigned char TK1[static 16])
{
REQUIRE(h80211 != NULL);
int is_a4, i, z, blocks, is_qos;
int data_len, last, offset;
unsigned char B0[16], B[16], MIC[16];
unsigned char PN[6], AAD[32];
Cipher_AES_CTX * aes_ctx;
is_a4 = (h80211[1] & 3) == 3;
is_qos = (h80211[0] & 0x8C) == 0x88;
z = 24 + 6 * is_a4;
z += 2 * is_qos;
PN[0] = h80211[z + 7];
PN[1] = h80211[z + 6];
PN[2] = h80211[z + 5];
PN[3] = h80211[z + 4];
PN[4] = h80211[z + 1];
PN[5] = h80211[z + 0];
data_len = caplen - z - 8 - 8;
// B_0 := B0
B0[0] = 0x59; // Flags
B0[1] = 0; // Nonce := CCM Nonce: - Nonce flags
memcpy(B0 + 2, h80211 + 10, 6); // - A2
memcpy(B0 + 8, PN, 6); // - PN
B0[14] = (uint8_t)((data_len >> 8) & 0xFF); // l(m)
B0[15] = (uint8_t)(data_len & 0xFF); // l(m)
// B_1 := AAD[ 0..15]
// B_2 := AAD[16..31]
// AAD[ 0.. 1] = l(a)
// AAD[ 2..31] = a
memset(AAD, 0, sizeof(AAD));
AAD[2] = (uint8_t)(h80211[0] & 0x8F); // AAD[2..3] = FC
AAD[3] = (uint8_t)(h80211[1] & 0xC7); //
memcpy(AAD + 4, h80211 + 4, 3 * 6); // AAD[4..21] = [A1,A2,A3]
AAD[22] = (uint8_t)(h80211[22] & 0x0F); // AAD[22] = SC
if (is_a4)
{
memcpy(AAD + 24, h80211 + 24, 6); // AAD[24..29] = A4
if (is_qos)
{
AAD[30] = (uint8_t)(h80211[z - 2] & 0x0F); // AAD[30..31] = QC
AAD[31] = 0; //
B0[1] = AAD[30]; // B0[ 1] = CCM Nonce flags
AAD[1] = 22 + 2 + 6; // AAD[ 0.. 1] = l(a)
}
else
{
memset(&AAD[30], 0, 2); // AAD[30..31] = QC
B0[1] = 0; // B0[ 1] = CCM Nonce flags
AAD[1] = 22 + 6; // AAD[ 0.. 1] = l(a)
}
}
else
{
if (is_qos)
{
AAD[24] = (uint8_t)(h80211[z - 2] & 0x0F); // AAD[24..25] = QC
AAD[25] = 0; //
B0[1] = AAD[24]; // B0[ 1] = CCM Nonce flags
AAD[1] = 22 + 2; // AAD[ 0.. 1] = l(a)
}
else
{
memset(&AAD[24], 0, 2); // AAD[24..25] = QC
B0[1] = 0; // B0[ 1] = CCM Nonce flags
AAD[1] = 22; // AAD[ 0.. 1] = l(a)
}
}
aes_ctx = Cipher_AES_Encrypt_Init(16, TK1);
REQUIRE(aes_ctx != NULL);
Cipher_AES_Encrypt(aes_ctx, B0, MIC); // X_1 := E( K, B_0 )
XOR(MIC, AAD, 16); // X_2 := E( K, X_1 XOR B_1 )
Cipher_AES_Encrypt(aes_ctx, MIC, MIC);
XOR(MIC, AAD + 16, 16); // X_3 := E( K, X_2 XOR B_2 )
Cipher_AES_Encrypt(aes_ctx, MIC, MIC);
// A_i := B0
// B0[ 0] = Flags
// B0[ 1..13] = Nonce := CCM Nonce
// B0[14..15] = i
B0[0] &= 0x07;
B0[14] = B0[15] = 0;
Cipher_AES_Encrypt(aes_ctx, B0, B); // S_0 := E( K, A_i )
XOR(h80211 + caplen - 8, B, 8); // T := U XOR S_0[0..7]
// ^^^^^^^^^^^^^^^ ^
// U:=MIC -> T S_0
blocks = (data_len + 16 - 1) / 16;
last = data_len % 16;
offset = z + 8;
for (i = 1; i <= blocks; i++)
{
int n = (last > 0 && i == blocks) ? last : 16;
B0[14] = (uint8_t)((i >> 8) & 0xFF); // A_i[14..15] = i
B0[15] = (uint8_t)(i & 0xFF); //
Cipher_AES_Encrypt(aes_ctx, B0, B); // S_i := E( K, A_i )
// The message is encrypted by XORing the octets of message m with the
// first l(m) octets of the concatenation of S_1, S_2, S_3, ... .
XOR(h80211 + offset, B, n);
// [B_3, ..., B_n] := m
XOR(MIC, h80211 + offset, n); // X_i+3 := E( K, X_i+2 XOR B_i+2 )
Cipher_AES_Encrypt(aes_ctx, MIC, MIC);
// (X_i+2 ^^^)(^^^ X_i+3)
offset += n;
}
Cipher_AES_Encrypt_Deinit(aes_ctx);
aes_ctx = NULL;
// T := X_n[ 0.. 7]
// Note: Decryption is successful if calculated T is the same as the one
// that was sent with the message.
return (memcmp(h80211 + offset, MIC, 8) == 0); //-V512
} |
C | aircrack-ng/lib/crypto/mac-hmac-md5-generic.c | // clang-format off
/**
* \file mac-hmac-md5-generic.c
*
* \author Joseph Benden <[email protected]>
* \author Jouni Malinen <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/crypto/md5.h"
// clang-format on
API_EXPORT
int MAC_HMAC_MD5_Vector(size_t key_len,
const uint8_t key[static key_len],
size_t count,
const uint8_t * addr[],
const size_t * len,
uint8_t mac[static DIGEST_MD5_MAC_LEN])
{
// clang-format off
uint8_t k_pad[64]; /* padding - key XORd with ipad/opad */
uint8_t tk[DIGEST_MD5_MAC_LEN];
const uint8_t *_addr[6];
size_t i, _len[6];
int res;
// clang-format on
if (count > 5)
{
/*
* Fixed limit on the number of fragments to avoid having to
* allocate memory (which could fail).
*/
return -1;
}
/* if key is longer than 64 bytes reset it to key = MD5(key) */
if (key_len > 64)
{
if (Digest_MD5_Vector(1, &key, &key_len, tk)) return -1;
key = tk;
key_len = DIGEST_MD5_MAC_LEN;
}
/* the HMAC_MD5 transform looks like:
*
* MD5(K XOR opad, MD5(K XOR ipad, text))
*
* where K is an n byte key
* ipad is the byte 0x36 repeated 64 times
* opad is the byte 0x5c repeated 64 times
* and text is the data being protected */
/* start out by storing key in ipad */
memset(k_pad, 0, sizeof(k_pad));
memcpy(k_pad, key, key_len);
/* XOR key with ipad values */
for (i = 0; i < 64; i++) k_pad[i] ^= 0x36;
/* perform inner MD5 */
_addr[0] = k_pad;
_len[0] = 64;
for (i = 0; i < count; i++)
{
_addr[i + 1] = addr[i];
_len[i + 1] = len[i];
}
if (Digest_MD5_Vector(1 + count, _addr, _len, mac)) return -1;
memset(k_pad, 0, sizeof(k_pad));
memcpy(k_pad, key, key_len);
/* XOR key with opad values */
for (i = 0; i < 64; i++) k_pad[i] ^= 0x5c;
/* perform outer MD5 */
// clang-format off
_addr[0] = k_pad;
_len[0] = 64;
_addr[1] = mac;
_len[1] = DIGEST_MD5_MAC_LEN;
// clang-format on
res = Digest_MD5_Vector(2, _addr, _len, mac);
return res;
}
API_EXPORT
int MAC_HMAC_MD5(size_t key_len,
const uint8_t key[static key_len],
size_t data_len,
const uint8_t data[static data_len],
uint8_t output[static DIGEST_MD5_MAC_LEN])
{
return MAC_HMAC_MD5_Vector(key_len, key, 1, &data, &data_len, output);
} |
C | aircrack-ng/lib/crypto/mac-hmac-sha1-generic.c | // clang-format off
/**
* \file mac-hmac-sha1-generic.c
*
* \author Joseph Benden <[email protected]>
* \author Jouni Malinen <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/crypto/sha1.h"
// clang-format on
API_EXPORT
int MAC_HMAC_SHA1_Vector(size_t key_len,
const uint8_t key[static key_len],
size_t count,
const uint8_t * addr[],
const size_t * len,
uint8_t mac[static DIGEST_SHA1_MAC_LEN])
{
// clang-format off
uint8_t k_pad[64]; /* padding - key XORd with ipad/opad */
uint8_t tk[DIGEST_SHA1_MAC_LEN];
const uint8_t *_addr[6];
size_t i, _len[6];
int res;
// clang-format on
if (count > 5)
{
/*
* Fixed limit on the number of fragments to avoid having to
* allocate memory (which could fail).
*/
return -1;
}
/* if key is longer than 64 bytes reset it to key = SHA-1(key) */
if (key_len > 64)
{
if (Digest_SHA1_Vector(1, &key, &key_len, tk)) return -1;
key = tk;
key_len = DIGEST_SHA1_MAC_LEN;
}
/* the HMAC-SHA-1 transform looks like:
*
* SHA-1(K XOR opad, SHA-1(K XOR ipad, text))
*
* where K is an n byte key
* ipad is the byte 0x36 repeated 64 times
* opad is the byte 0x5c repeated 64 times
* and text is the data being protected */
/* start out by storing key in ipad */
memset(k_pad, 0, sizeof(k_pad));
memcpy(k_pad, key, key_len);
/* XOR key with ipad values */
for (i = 0; i < 64; i++) k_pad[i] ^= 0x36;
/* perform inner SHA-1 */
_addr[0] = k_pad;
_len[0] = 64;
for (i = 0; i < count; i++)
{
_addr[i + 1] = addr[i];
_len[i + 1] = len[i];
}
if (Digest_SHA1_Vector(1 + count, _addr, _len, mac)) return -1;
memset(k_pad, 0, sizeof(k_pad));
memcpy(k_pad, key, key_len);
/* XOR key with opad values */
for (i = 0; i < 64; i++) k_pad[i] ^= 0x5c;
/* perform outer SHA-1 */
// clang-format off
_addr[0] = k_pad;
_len[0] = 64;
_addr[1] = mac;
_len[1] = DIGEST_SHA1_MAC_LEN;
// clang-format on
res = Digest_SHA1_Vector(2, _addr, _len, mac);
return res;
}
API_EXPORT
int MAC_HMAC_SHA1(size_t key_len,
const uint8_t key[static key_len],
size_t data_len,
const uint8_t data[static data_len],
uint8_t output[static DIGEST_SHA1_MAC_LEN])
{
return MAC_HMAC_SHA1_Vector(key_len, key, 1, &data, &data_len, output);
} |
C | aircrack-ng/lib/crypto/mac-hmac-sha256-generic.c | // clang-format off
/**
* \file mac-hmac-sha256-generic.c
*
* \author Joseph Benden <[email protected]>
* \author Jouni Malinen <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/crypto/sha256.h"
// clang-format on
API_EXPORT
int MAC_HMAC_SHA256_Vector(size_t key_len,
const uint8_t key[static key_len],
size_t count,
const uint8_t * addr[],
const size_t * len,
uint8_t mac[static DIGEST_SHA256_MAC_LEN])
{
// clang-format off
uint8_t k_pad[64]; /* padding - key XORd with ipad/opad */
uint8_t tk[DIGEST_SHA256_MAC_LEN];
const uint8_t *_addr[6];
size_t i, _len[6];
int res;
// clang-format on
if (count > 5)
{
/*
* Fixed limit on the number of fragments to avoid having to
* allocate memory (which could fail).
*/
return (-1);
}
/* if key is longer than 64 bytes reset it to key = SHA-2-256(key) */
if (key_len > 64)
{
if (Digest_SHA256_Vector(1, &key, &key_len, tk)) return -1;
key = tk;
key_len = DIGEST_SHA256_MAC_LEN;
}
/* the HMAC-SHA-2-256 transform looks like:
*
* SHA-2-256(K XOR opad, SHA-2-256(K XOR ipad, text))
*
* where K is an n byte key
* ipad is the byte 0x36 repeated 64 times
* opad is the byte 0x5c repeated 64 times
* and text is the data being protected */
/* start out by storing key in ipad */
memset(k_pad, 0, sizeof(k_pad));
memcpy(k_pad, key, key_len);
/* XOR key with ipad values */
for (i = 0; i < 64; i++) k_pad[i] ^= 0x36;
/* perform inner SHA-2-256 */
_addr[0] = k_pad;
_len[0] = 64;
for (i = 0; i < count; i++)
{
_addr[i + 1] = addr[i];
_len[i + 1] = len[i];
}
if (Digest_SHA256_Vector(1 + count, _addr, _len, mac)) return -1;
memset(k_pad, 0, sizeof(k_pad));
memcpy(k_pad, key, key_len);
/* XOR key with opad values */
for (i = 0; i < 64; i++) k_pad[i] ^= 0x5c;
/* perform outer SHA-2-256 */
// clang-format off
_addr[0] = k_pad;
_len[0] = 64;
_addr[1] = mac;
_len[1] = DIGEST_SHA256_MAC_LEN;
// clang-format on
res = Digest_SHA256_Vector(2, _addr, _len, mac);
return res;
}
API_EXPORT
int MAC_HMAC_SHA256(size_t key_len,
const uint8_t key[static key_len],
size_t data_len,
const uint8_t data[static data_len],
uint8_t output[static DIGEST_SHA256_MAC_LEN])
{
return MAC_HMAC_SHA256_Vector(key_len, key, 1, &data, &data_len, output);
} |
C | aircrack-ng/lib/crypto/mac-omac1-gcrypt.c | // clang-format off
/**
* \file mac-omac1-gcrypt.c
*
* \brief One-Key CBC MAC (OMAC1) hash with AES.
*
* \author Joseph Benden <[email protected]>
* \author Jouni Malinen <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include <err.h> // warn{,s} err{,x}
#include <gcrypt.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/crypto/mac.h"
API_EXPORT
int MAC_OMAC1_AES_Vector(size_t key_len,
const uint8_t key[static key_len],
size_t num_elem,
const uint8_t * addr[],
const size_t * len,
uint8_t * mac)
{
gcry_mac_hd_t ctx;
int ret = -1;
size_t outlen = 16, i;
if (gcry_mac_open(&ctx, GCRY_MAC_CMAC_AES, 0, NULL) != GPG_ERR_NO_ERROR)
{
errx(1, "Failed to open CMAC-AES-128-CBC");
goto fail;
}
if (gcry_mac_setkey(ctx, key, key_len) != GPG_ERR_NO_ERROR)
{
warnx("Failed to setkey for CMAC-AES-128-CBC");
goto fail;
}
for (i = 0; i < num_elem; i++)
{
if (gcry_mac_write(ctx, addr[i], len[i]) != GPG_ERR_NO_ERROR)
{
warnx("Failed to write CMAC-AES-128-CBC");
goto fail;
}
}
if (gcry_mac_read(ctx, mac, &outlen) != GPG_ERR_NO_ERROR || outlen != 16)
{
warnx("Failed to read CMAC-AES-128-CBC (got %zd)", outlen);
goto fail;
}
ret = 0;
fail:
gcry_mac_close(ctx);
return (ret);
} |
C | aircrack-ng/lib/crypto/mac-omac1-generic.c | // clang-format off
/**
* \file mac-omac1-generic.c
*
* \brief One-Key CBC MAC (OMAC1) hash with AES.
*
* \author Joseph Benden <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stddef.h> // size_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/crypto.h"
// clang-format on
API_EXPORT
int MAC_OMAC1_AES_Vector(size_t key_len,
const uint8_t key[static key_len],
size_t num_elem,
const uint8_t * addr[],
const size_t * len,
uint8_t * mac)
{
UNUSED_PARAM(key);
UNUSED_PARAM(num_elem);
UNUSED_PARAM(addr);
UNUSED_PARAM(len);
UNUSED_PARAM(mac);
fprintf(stderr,
"OMAC1 is only supported when OpenSSL (or similar) "
"supports CMAC.\n");
return (-1);
} |
C | aircrack-ng/lib/crypto/mac-omac1-openssl.c | // clang-format off
/**
* \file mac-omac1-openssl.c
*
* \brief One-Key CBC MAC (OMAC1) hash with AES.
*
* \author Joseph Benden <[email protected]>
* \author Jouni Malinen <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stddef.h> // size_t
#include <stdint.h> // [u]int{8,16,32,64}_t types
#include <aircrack-ng/defs.h>
#include <aircrack-ng/crypto/crypto.h>
// clang-format on
API_EXPORT
int MAC_OMAC1_AES_Vector(size_t key_len,
const uint8_t key[static key_len],
size_t num_elem,
const uint8_t * addr[],
const size_t * len,
uint8_t * mac)
{
int ret = -1;
size_t outlen, i;
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
EVP_MAC * cmac = EVP_MAC_fetch(NULL, "cmac", NULL);
OSSL_PARAM params[3];
size_t params_n = 0;
memset(params, 0, sizeof(params));
if (key_len == 16)
params[params_n++]
= OSSL_PARAM_construct_utf8_string("cipher", "aes-128-cbc", 0);
else if (key_len == 32)
params[params_n++]
= OSSL_PARAM_construct_utf8_string("cipher", "aes-256-cbc", 0);
else
return (-1);
EVP_MAC_CTX * c = EVP_MAC_CTX_new(cmac);
EVP_MAC_init(c, key, key_len, params);
for (i = 0; i < num_elem; i++)
{
EVP_MAC_update(c, addr[i], len[i]);
}
EVP_MAC_final(c, mac, &outlen, 20);
EVP_MAC_CTX_free(c);
ret = 0;
#else
CMAC_CTX * ctx;
ctx = CMAC_CTX_new();
if (ctx == NULL) return -1;
if (key_len == 32)
{
if (!CMAC_Init(ctx, key, 32, EVP_aes_256_cbc(), NULL)) goto fail;
}
else if (key_len == 16)
{
if (!CMAC_Init(ctx, key, 16, EVP_aes_128_cbc(), NULL)) goto fail;
}
else
{
goto fail;
}
for (i = 0; i < num_elem; i++)
{
if (!CMAC_Update(ctx, addr[i], len[i])) goto fail;
}
if (!CMAC_Final(ctx, mac, &outlen) || outlen != 16) goto fail;
ret = 0;
fail:
CMAC_CTX_free(ctx);
#endif
return ret;
} |
C | aircrack-ng/lib/crypto/md5-gcrypt.c | // clang-format off
/**
* \file md5-gcrypt.c
*
* \brief The MD5 message digest algorithm (hash function)
*
* \warning MD5 is considered a weak digest and its use constitutes a
* security risk. We recommend considering stronger digests instead.
*
* \author Joseph Benden <[email protected]>
* \author Jouni Malinen <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include <err.h> // warn{,s} err{,x}
#include <gcrypt.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/md5.h"
#ifndef GCRYPT_WITH_MD5
# error "Wrong module included for MD5 with Gcrypt."
#endif
// clang-format on
API_EXPORT
Digest_MD5_CTX * Digest_MD5_Create(void)
{
return calloc(1, sizeof(Digest_MD5_CTX));
}
API_EXPORT
void Digest_MD5_Destroy(Digest_MD5_CTX * ctx)
{
REQUIRE(ctx != NULL);
free(ctx);
}
API_EXPORT
int Digest_MD5_Init(Digest_MD5_CTX * ctx)
{
REQUIRE(ctx != NULL);
if (gcry_md_open(ctx, GCRY_MD_MD5, 0) != GPG_ERR_NO_ERROR)
errx(1, "Failed to open MD5");
return (0);
}
API_EXPORT
int Digest_MD5_Update(Digest_MD5_CTX * ctx, const uint8_t * input, size_t ilen)
{
gcry_md_write(*ctx, input, ilen);
return (0);
}
API_EXPORT
int Digest_MD5_Finish(Digest_MD5_CTX * ctx,
uint8_t output[static DIGEST_MD5_MAC_LEN])
{
unsigned int dlen = gcry_md_get_algo_dlen(gcry_md_get_algo(*ctx));
unsigned char * dgst = gcry_md_read(*ctx, GCRY_MD_MD5);
if (!dgst) return (-1);
memcpy(output, dgst, dlen);
gcry_md_close(*ctx);
return (0);
}
API_EXPORT
int Digest_MD5(const uint8_t * input,
size_t ilen,
uint8_t output[static DIGEST_MD5_MAC_LEN])
{
int ret = -1;
gcry_md_hd_t ctx;
memset(&ctx, 0, sizeof(ctx));
if ((ret = Digest_MD5_Init(&ctx)) != 0)
errx(1, "Digest_MD5_Init() failed");
else if ((ret = Digest_MD5_Update(&ctx, input, ilen)) != 0)
errx(1, "Digest_MD5_Update() failed");
else if ((ret = Digest_MD5_Finish(&ctx, output)) != 0)
errx(1, "Digest_MD5_Finish() failed");
return (ret);
} |
C | aircrack-ng/lib/crypto/md5-generic.c | // clang-format off
/**
* \file md5-generic.c
*
* \brief The MD5 message digest algorithm (hash function)
*
* \warning MD5 is considered a weak digest and its use constitutes a
* security risk. We recommend considering stronger digests instead.
*
* \author Joseph Benden <[email protected]>
* \author The Mbed TLS Contributors
*
* \license Apache-2.0
*
* \ingroup
* \cond
******************************************************************************
*
* Portitions are Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include <err.h> // warn{,s} err{,x}
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/md5.h"
// clang-format on
// clang-format off
/*
* 32-bit integer manipulation macros (little endian)
*/
#ifndef GET_UINT32_LE
#define GET_UINT32_LE(n,b,i) \
{ \
(n) = ( (uint32_t) (b)[(i) ] ) \
| ( (uint32_t) (b)[(i) + 1] << 8 ) \
| ( (uint32_t) (b)[(i) + 2] << 16 ) \
| ( (uint32_t) (b)[(i) + 3] << 24 ); \
}
#endif
#ifndef PUT_UINT32_LE
#define PUT_UINT32_LE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( ( (n) ) & 0xFF ); \
(b)[(i) + 1] = (unsigned char) ( ( (n) >> 8 ) & 0xFF ); \
(b)[(i) + 2] = (unsigned char) ( ( (n) >> 16 ) & 0xFF ); \
(b)[(i) + 3] = (unsigned char) ( ( (n) >> 24 ) & 0xFF ); \
}
#endif
// clang-format on
API_EXPORT
Digest_MD5_CTX * Digest_MD5_Create(void)
{
return calloc(1, sizeof(Digest_MD5_CTX));
}
API_EXPORT
void Digest_MD5_Destroy(Digest_MD5_CTX * ctx)
{
REQUIRE(ctx != NULL);
free(ctx);
}
API_EXPORT
int Digest_MD5_Init(Digest_MD5_CTX * ctx)
{
REQUIRE(ctx != NULL);
ctx->total[0] = 0;
ctx->total[1] = 0;
ctx->state[0] = 0x67452301;
ctx->state[1] = 0xEFCDAB89;
ctx->state[2] = 0x98BADCFE;
ctx->state[3] = 0x10325476;
return (0);
}
int Digest_Internal_MD5_Process(Digest_MD5_CTX * ctx,
const uint8_t data[static DIGEST_MD5_BLK_LEN])
{
struct
{
uint32_t X[16], A, B, C, D;
} local;
// clang-format off
GET_UINT32_LE( local.X[ 0], data, 0 );
GET_UINT32_LE( local.X[ 1], data, 4 );
GET_UINT32_LE( local.X[ 2], data, 8 );
GET_UINT32_LE( local.X[ 3], data, 12 );
GET_UINT32_LE( local.X[ 4], data, 16 );
GET_UINT32_LE( local.X[ 5], data, 20 );
GET_UINT32_LE( local.X[ 6], data, 24 );
GET_UINT32_LE( local.X[ 7], data, 28 );
GET_UINT32_LE( local.X[ 8], data, 32 );
GET_UINT32_LE( local.X[ 9], data, 36 );
GET_UINT32_LE( local.X[10], data, 40 );
GET_UINT32_LE( local.X[11], data, 44 );
GET_UINT32_LE( local.X[12], data, 48 );
GET_UINT32_LE( local.X[13], data, 52 );
GET_UINT32_LE( local.X[14], data, 56 );
GET_UINT32_LE( local.X[15], data, 60 );
#define S(x,n) \
( ( (x) << (n) ) | ( ( (x) & 0xFFFFFFFF) >> ( 32 - (n) ) ) )
#define P(a,b,c,d,k,s,t) \
do \
{ \
(a) += F((b),(c),(d)) + local.X[(k)] + (t); \
(a) = S((a),(s)) + (b); \
} while( 0 )
local.A = ctx->state[0];
local.B = ctx->state[1];
local.C = ctx->state[2];
local.D = ctx->state[3];
#define F(x,y,z) ((z) ^ ((x) & ((y) ^ (z))))
P( local.A, local.B, local.C, local.D, 0, 7, 0xD76AA478 );
P( local.D, local.A, local.B, local.C, 1, 12, 0xE8C7B756 );
P( local.C, local.D, local.A, local.B, 2, 17, 0x242070DB );
P( local.B, local.C, local.D, local.A, 3, 22, 0xC1BDCEEE );
P( local.A, local.B, local.C, local.D, 4, 7, 0xF57C0FAF );
P( local.D, local.A, local.B, local.C, 5, 12, 0x4787C62A );
P( local.C, local.D, local.A, local.B, 6, 17, 0xA8304613 );
P( local.B, local.C, local.D, local.A, 7, 22, 0xFD469501 );
P( local.A, local.B, local.C, local.D, 8, 7, 0x698098D8 );
P( local.D, local.A, local.B, local.C, 9, 12, 0x8B44F7AF );
P( local.C, local.D, local.A, local.B, 10, 17, 0xFFFF5BB1 );
P( local.B, local.C, local.D, local.A, 11, 22, 0x895CD7BE );
P( local.A, local.B, local.C, local.D, 12, 7, 0x6B901122 );
P( local.D, local.A, local.B, local.C, 13, 12, 0xFD987193 );
P( local.C, local.D, local.A, local.B, 14, 17, 0xA679438E );
P( local.B, local.C, local.D, local.A, 15, 22, 0x49B40821 );
#undef F
#define F(x,y,z) ((y) ^ ((z) & ((x) ^ (y))))
P( local.A, local.B, local.C, local.D, 1, 5, 0xF61E2562 );
P( local.D, local.A, local.B, local.C, 6, 9, 0xC040B340 );
P( local.C, local.D, local.A, local.B, 11, 14, 0x265E5A51 );
P( local.B, local.C, local.D, local.A, 0, 20, 0xE9B6C7AA );
P( local.A, local.B, local.C, local.D, 5, 5, 0xD62F105D );
P( local.D, local.A, local.B, local.C, 10, 9, 0x02441453 );
P( local.C, local.D, local.A, local.B, 15, 14, 0xD8A1E681 );
P( local.B, local.C, local.D, local.A, 4, 20, 0xE7D3FBC8 );
P( local.A, local.B, local.C, local.D, 9, 5, 0x21E1CDE6 );
P( local.D, local.A, local.B, local.C, 14, 9, 0xC33707D6 );
P( local.C, local.D, local.A, local.B, 3, 14, 0xF4D50D87 );
P( local.B, local.C, local.D, local.A, 8, 20, 0x455A14ED );
P( local.A, local.B, local.C, local.D, 13, 5, 0xA9E3E905 );
P( local.D, local.A, local.B, local.C, 2, 9, 0xFCEFA3F8 );
P( local.C, local.D, local.A, local.B, 7, 14, 0x676F02D9 );
P( local.B, local.C, local.D, local.A, 12, 20, 0x8D2A4C8A );
#undef F
#define F(x,y,z) ((x) ^ (y) ^ (z))
P( local.A, local.B, local.C, local.D, 5, 4, 0xFFFA3942 );
P( local.D, local.A, local.B, local.C, 8, 11, 0x8771F681 );
P( local.C, local.D, local.A, local.B, 11, 16, 0x6D9D6122 );
P( local.B, local.C, local.D, local.A, 14, 23, 0xFDE5380C );
P( local.A, local.B, local.C, local.D, 1, 4, 0xA4BEEA44 );
P( local.D, local.A, local.B, local.C, 4, 11, 0x4BDECFA9 );
P( local.C, local.D, local.A, local.B, 7, 16, 0xF6BB4B60 );
P( local.B, local.C, local.D, local.A, 10, 23, 0xBEBFBC70 );
P( local.A, local.B, local.C, local.D, 13, 4, 0x289B7EC6 );
P( local.D, local.A, local.B, local.C, 0, 11, 0xEAA127FA );
P( local.C, local.D, local.A, local.B, 3, 16, 0xD4EF3085 );
P( local.B, local.C, local.D, local.A, 6, 23, 0x04881D05 );
P( local.A, local.B, local.C, local.D, 9, 4, 0xD9D4D039 );
P( local.D, local.A, local.B, local.C, 12, 11, 0xE6DB99E5 );
P( local.C, local.D, local.A, local.B, 15, 16, 0x1FA27CF8 );
P( local.B, local.C, local.D, local.A, 2, 23, 0xC4AC5665 );
#undef F
#define F(x,y,z) ((y) ^ ((x) | ~(z)))
P( local.A, local.B, local.C, local.D, 0, 6, 0xF4292244 );
P( local.D, local.A, local.B, local.C, 7, 10, 0x432AFF97 );
P( local.C, local.D, local.A, local.B, 14, 15, 0xAB9423A7 );
P( local.B, local.C, local.D, local.A, 5, 21, 0xFC93A039 );
P( local.A, local.B, local.C, local.D, 12, 6, 0x655B59C3 );
P( local.D, local.A, local.B, local.C, 3, 10, 0x8F0CCC92 );
P( local.C, local.D, local.A, local.B, 10, 15, 0xFFEFF47D );
P( local.B, local.C, local.D, local.A, 1, 21, 0x85845DD1 );
P( local.A, local.B, local.C, local.D, 8, 6, 0x6FA87E4F );
P( local.D, local.A, local.B, local.C, 15, 10, 0xFE2CE6E0 );
P( local.C, local.D, local.A, local.B, 6, 15, 0xA3014314 );
P( local.B, local.C, local.D, local.A, 13, 21, 0x4E0811A1 );
P( local.A, local.B, local.C, local.D, 4, 6, 0xF7537E82 );
P( local.D, local.A, local.B, local.C, 11, 10, 0xBD3AF235 );
P( local.C, local.D, local.A, local.B, 2, 15, 0x2AD7D2BB );
P( local.B, local.C, local.D, local.A, 9, 21, 0xEB86D391 );
#undef F
// clang-format on
ctx->state[0] += local.A;
ctx->state[1] += local.B;
ctx->state[2] += local.C;
ctx->state[3] += local.D;
return (0);
}
API_EXPORT
int Digest_MD5_Update(Digest_MD5_CTX * ctx, const uint8_t * input, size_t ilen)
{
int ret = -1;
size_t fill;
uint32_t left;
if (ilen == 0) return (0);
left = ctx->total[0] & 0x3F;
fill = 64 - left;
ctx->total[0] += (uint32_t) ilen;
ctx->total[0] &= 0xFFFFFFFF;
if (ctx->total[0] < (uint32_t) ilen) ctx->total[1]++;
if (left && ilen >= fill)
{
memcpy((void *) (ctx->buffer + left), input, fill);
if ((ret = Digest_Internal_MD5_Process(ctx, ctx->buffer)) != 0)
return (ret);
input += fill;
ilen -= fill;
left = 0;
}
while (ilen >= 64)
{
if ((ret = Digest_Internal_MD5_Process(ctx, input)) != 0) return (ret);
input += 64;
ilen -= 64;
}
if (ilen > 0)
{
memcpy((void *) (ctx->buffer + left), input, ilen);
}
return (0);
}
API_EXPORT
int Digest_MD5_Finish(Digest_MD5_CTX * ctx,
uint8_t output[static DIGEST_MD5_MAC_LEN])
{
int ret = -1;
uint32_t used;
uint32_t high, low;
/* Add padding: 0x80 then 0x00 until 8 bytes remain for the length */
used = ctx->total[0] & 0x3F;
ctx->buffer[used++] = 0x80;
if (used <= 56)
{
/* Enough room for padding + length in current block */
memset(ctx->buffer + used, 0, 56 - used);
}
else
{
/* We'll need an extra block */
memset(ctx->buffer + used, 0, 64 - used);
if ((ret = Digest_Internal_MD5_Process(ctx, ctx->buffer)) != 0)
return (ret);
memset(ctx->buffer, 0, 56);
}
/* Add message length */
// clang-format off
high = ( ctx->total[0] >> 29 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
// clang-format on
PUT_UINT32_LE(low, ctx->buffer, 56);
PUT_UINT32_LE(high, ctx->buffer, 60);
if ((ret = Digest_Internal_MD5_Process(ctx, ctx->buffer)) != 0)
return (ret);
/* Output final state */
// clang-format off
PUT_UINT32_LE( ctx->state[0], output, 0 );
PUT_UINT32_LE( ctx->state[1], output, 4 );
PUT_UINT32_LE( ctx->state[2], output, 8 );
PUT_UINT32_LE( ctx->state[3], output, 12 );
// clang-format on
return (0);
}
API_EXPORT
int Digest_MD5(const uint8_t * input,
size_t ilen,
uint8_t output[static DIGEST_MD5_MAC_LEN])
{
int ret = -1;
Digest_MD5_CTX ctx;
memset(&ctx, 0, sizeof(ctx));
if ((ret = Digest_MD5_Init(&ctx)) != 0)
errx(1, "Digest_MD5_Init() failed");
else if ((ret = Digest_MD5_Update(&ctx, input, ilen)) != 0)
errx(1, "Digest_MD5_Update() failed");
else if ((ret = Digest_MD5_Finish(&ctx, output)) != 0)
errx(1, "Digest_MD5_Finish() failed");
return (ret);
} |
C | aircrack-ng/lib/crypto/md5-openssl.c | // clang-format off
/**
* \file md5-openssl.c
*
* \brief The MD5 message digest algorithm (hash function)
*
* This code uses the OpenSSL EVP high-level interfaces; which heap allocate!
* See: https://github.com/openssl/openssl/issues/7219
*
* \warning MD5 is considered a weak digest and its use constitutes a
* security risk. We recommend considering stronger digests instead.
*
* \author Joseph Benden <[email protected]>
* \author Jouni Malinen <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include <err.h> // warn{,s} err{,x}
#include <openssl/evp.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/md5.h"
#if OPENSSL_VERSION_NUMBER < 0x10100000L
# define EVP_MD_CTX_new EVP_MD_CTX_create
# define EVP_MD_CTX_free EVP_MD_CTX_destroy
#endif
// clang-format on
Digest_MD5_CTX * Digest_MD5_Create(void) { return EVP_MD_CTX_new(); }
void Digest_MD5_Destroy(Digest_MD5_CTX * ctx) { EVP_MD_CTX_free(ctx); }
int Digest_MD5_Init(Digest_MD5_CTX * ctx)
{
if (!EVP_DigestInit_ex(ctx, EVP_md5(), NULL))
return (-1);
else
return (0);
}
int Digest_MD5_Update(Digest_MD5_CTX * ctx, const uint8_t * input, size_t ilen)
{
if (!EVP_DigestUpdate(ctx, input, ilen))
return (-1);
else
return (0);
}
int Digest_MD5_Finish(Digest_MD5_CTX * ctx,
uint8_t output[static DIGEST_MD5_MAC_LEN])
{
unsigned int ilen;
if (!EVP_DigestFinal_ex(ctx, output, &ilen)) return (-1);
if (ilen != 16u)
return (-1);
else
return (0);
}
int Digest_MD5(const uint8_t * input,
size_t ilen,
uint8_t output[static DIGEST_MD5_MAC_LEN])
{
int ret;
Digest_MD5_CTX * ctx = NULL;
if ((ctx = Digest_MD5_Create()) == NULL)
errx(1, "Digest_MD5_Create() failed");
else if ((ret = Digest_MD5_Init(ctx)) != 0)
errx(1, "Digest_MD5_Init() failed");
else if ((ret = Digest_MD5_Update(ctx, input, ilen)) != 0)
errx(1, "Digest_MD5_Update() failed");
else if ((ret = Digest_MD5_Finish(ctx, output)) != 0)
errx(1, "Digest_MD5_Finish() failed");
Digest_MD5_Destroy(ctx);
return (ret);
} |
C | aircrack-ng/lib/crypto/md5.c | // clang-format off
/**
* \file md5.c
*
* \brief The MD5 message digest algorithm (hash function)
*
* \warning MD5 is considered a weak digest and its use constitutes a
* security risk. We recommend considering stronger digests instead.
*
* \author Joseph Benden <[email protected]>
* \author Jouni Malinen <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/crypto/md5.h"
// clang-format on
API_EXPORT
int Digest_MD5_Vector(size_t num_elem,
const uint8_t * addr[static num_elem],
const size_t len[static num_elem],
uint8_t mac[static DIGEST_MD5_MAC_LEN])
{
Digest_MD5_CTX * ctx = Digest_MD5_Create();
size_t i;
if (!ctx) return -1;
Digest_MD5_Init(ctx);
for (i = 0; i < num_elem; i++) Digest_MD5_Update(ctx, addr[i], len[i]);
Digest_MD5_Finish(ctx, mac);
Digest_MD5_Destroy(ctx);
return 0;
} |
C | aircrack-ng/lib/crypto/sha1-gcrypt.c | // clang-format off
/**
* \file sha1-gcrypt.c
*
* \brief The SHA-1 cryptographic hash function
*
* The Secure Hash Algorithm 1 (SHA-1) cryptographic hash function is defined
* in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
*
* \warning SHA-1 is considered a weak message digest and its use constitutes
* a security risk. We recommend considering stronger message
* digests instead.
*
* \author Joseph Benden <[email protected]>
* \author Jouni Malinen <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include <err.h> // warn{,s} err{,x}
#include <gcrypt.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/sha1.h"
// clang-format on
// clang-format off
#ifndef GCRYPT_WITH_SHA1
# error "Wrong module included for SHA-1 with Gcrypt."
#endif
// clang-format on
Digest_SHA1_CTX * Digest_SHA1_Create(void)
{
return calloc(1, sizeof(Digest_SHA1_CTX));
}
void Digest_SHA1_Destroy(Digest_SHA1_CTX * ctx)
{
REQUIRE(ctx != NULL);
free(ctx);
}
void Digest_SHA1_Clone(Digest_SHA1_CTX ** dst, const Digest_SHA1_CTX * src)
{
REQUIRE(src != NULL);
REQUIRE(dst != NULL);
if (gcry_md_copy(*dst, *src) != GPG_ERR_NO_ERROR)
errx(1, "Failed to copy SHA-1");
}
int Digest_SHA1_Init(Digest_SHA1_CTX * ctx)
{
REQUIRE(ctx != NULL);
if (gcry_md_open(ctx, GCRY_MD_SHA1, 0) != GPG_ERR_NO_ERROR)
errx(1, "Failed to open SHA-1");
return (0);
}
int Digest_SHA1_Update(Digest_SHA1_CTX * ctx,
const uint8_t * input,
size_t ilen)
{
gcry_md_write(*ctx, input, ilen);
return (0);
}
int Digest_SHA1_Finish(Digest_SHA1_CTX * ctx,
uint8_t output[static DIGEST_SHA1_MAC_LEN])
{
unsigned int dlen = gcry_md_get_algo_dlen(gcry_md_get_algo(*ctx));
unsigned char * dgst = gcry_md_read(*ctx, GCRY_MD_SHA1);
if (!dgst) return (-1);
memcpy(output, dgst, dlen);
gcry_md_close(*ctx);
return (0);
}
int Digest_SHA1(const uint8_t * input,
size_t ilen,
uint8_t output[static DIGEST_SHA1_MAC_LEN])
{
int ret = -1;
gcry_md_hd_t ctx;
memset(&ctx, 0, sizeof(ctx));
if ((ret = Digest_SHA1_Init(&ctx)) != 0)
errx(1, "Digest_SHA1_Init failed");
else if ((ret = Digest_SHA1_Update(&ctx, input, ilen)) != 0)
errx(1, "Digest_SHA1_Update failed");
else if ((ret = Digest_SHA1_Finish(&ctx, output)) != 0)
errx(1, "Digest_SHA1_Finish failed");
return (ret);
} |
C | aircrack-ng/lib/crypto/sha1-generic.c | // clang-format off
/**
* \file sha1-gcrypt.c
*
* \brief The SHA-1 cryptographic hash function
*
* The Secure Hash Algorithm 1 (SHA-1) cryptographic hash function is defined
* in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
*
* \warning SHA-1 is considered a weak message digest and its use constitutes
* a security risk. We recommend considering stronger message
* digests instead.
*
* \author Joseph Benden <[email protected]>
* \author The Mbed TLS Contributors
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portitions are Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include <err.h> // warn{,s} err{,x}
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/sha1.h"
// clang-format on
// clang-format off
/*
* 32-bit integer manipulation macros (big endian)
*/
#ifndef GET_UINT32_BE
#define GET_UINT32_BE(n,b,i) \
{ \
(n) = ( (uint32_t) (b)[(i) ] << 24 ) \
| ( (uint32_t) (b)[(i) + 1] << 16 ) \
| ( (uint32_t) (b)[(i) + 2] << 8 ) \
| ( (uint32_t) (b)[(i) + 3] ); \
}
#endif
#ifndef PUT_UINT32_BE
#define PUT_UINT32_BE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( (n) >> 24 ); \
(b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \
(b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \
(b)[(i) + 3] = (unsigned char) ( (n) ); \
}
#endif
// clang-format on
Digest_SHA1_CTX * Digest_SHA1_Create(void)
{
return calloc(1, sizeof(Digest_SHA1_CTX));
}
void Digest_SHA1_Destroy(Digest_SHA1_CTX * ctx)
{
REQUIRE(ctx != NULL);
free(ctx);
}
void Digest_SHA1_Clone(Digest_SHA1_CTX ** dst, const Digest_SHA1_CTX * src)
{
REQUIRE(src != NULL);
REQUIRE(dst != NULL);
**dst = *src;
}
int Digest_SHA1_Init(Digest_SHA1_CTX * ctx)
{
REQUIRE(ctx != NULL);
ctx->total[0] = 0;
ctx->total[1] = 0;
ctx->state[0] = 0x67452301;
ctx->state[1] = 0xEFCDAB89;
ctx->state[2] = 0x98BADCFE;
ctx->state[3] = 0x10325476;
ctx->state[4] = 0xC3D2E1F0;
return (0);
}
int Digest_Internal_SHA1_Process(Digest_SHA1_CTX * ctx,
const uint8_t data[static DIGEST_SHA1_BLK_LEN])
{
struct
{
uint32_t temp, W[16], A, B, C, D, E;
} local;
// clang-format off
GET_UINT32_BE( local.W[ 0], data, 0 );
GET_UINT32_BE( local.W[ 1], data, 4 );
GET_UINT32_BE( local.W[ 2], data, 8 );
GET_UINT32_BE( local.W[ 3], data, 12 );
GET_UINT32_BE( local.W[ 4], data, 16 );
GET_UINT32_BE( local.W[ 5], data, 20 );
GET_UINT32_BE( local.W[ 6], data, 24 );
GET_UINT32_BE( local.W[ 7], data, 28 );
GET_UINT32_BE( local.W[ 8], data, 32 );
GET_UINT32_BE( local.W[ 9], data, 36 );
GET_UINT32_BE( local.W[10], data, 40 );
GET_UINT32_BE( local.W[11], data, 44 );
GET_UINT32_BE( local.W[12], data, 48 );
GET_UINT32_BE( local.W[13], data, 52 );
GET_UINT32_BE( local.W[14], data, 56 );
GET_UINT32_BE( local.W[15], data, 60 );
#define S(x,n) (((x) << (n)) | (((x) & 0xFFFFFFFF) >> (32 - (n))))
#define R(t) \
( \
local.temp = local.W[( (t) - 3 ) & 0x0F] ^ \
local.W[( (t) - 8 ) & 0x0F] ^ \
local.W[( (t) - 14 ) & 0x0F] ^ \
local.W[ (t) & 0x0F], \
( local.W[(t) & 0x0F] = S(local.temp,1) ) \
)
#define P(a,b,c,d,e,x) \
do \
{ \
(e) += S((a),5) + F((b),(c),(d)) + K + (x); \
(b) = S((b),30); \
} while( 0 )
local.A = ctx->state[0];
local.B = ctx->state[1];
local.C = ctx->state[2];
local.D = ctx->state[3];
local.E = ctx->state[4];
#define F(x,y,z) ((z) ^ ((x) & ((y) ^ (z))))
#define K 0x5A827999
P( local.A, local.B, local.C, local.D, local.E, local.W[0] );
P( local.E, local.A, local.B, local.C, local.D, local.W[1] );
P( local.D, local.E, local.A, local.B, local.C, local.W[2] );
P( local.C, local.D, local.E, local.A, local.B, local.W[3] );
P( local.B, local.C, local.D, local.E, local.A, local.W[4] );
P( local.A, local.B, local.C, local.D, local.E, local.W[5] );
P( local.E, local.A, local.B, local.C, local.D, local.W[6] );
P( local.D, local.E, local.A, local.B, local.C, local.W[7] );
P( local.C, local.D, local.E, local.A, local.B, local.W[8] );
P( local.B, local.C, local.D, local.E, local.A, local.W[9] );
P( local.A, local.B, local.C, local.D, local.E, local.W[10] );
P( local.E, local.A, local.B, local.C, local.D, local.W[11] );
P( local.D, local.E, local.A, local.B, local.C, local.W[12] );
P( local.C, local.D, local.E, local.A, local.B, local.W[13] );
P( local.B, local.C, local.D, local.E, local.A, local.W[14] );
P( local.A, local.B, local.C, local.D, local.E, local.W[15] );
P( local.E, local.A, local.B, local.C, local.D, R(16) );
P( local.D, local.E, local.A, local.B, local.C, R(17) );
P( local.C, local.D, local.E, local.A, local.B, R(18) );
P( local.B, local.C, local.D, local.E, local.A, R(19) );
#undef K
#undef F
#define F(x,y,z) ((x) ^ (y) ^ (z))
#define K 0x6ED9EBA1
P( local.A, local.B, local.C, local.D, local.E, R(20) );
P( local.E, local.A, local.B, local.C, local.D, R(21) );
P( local.D, local.E, local.A, local.B, local.C, R(22) );
P( local.C, local.D, local.E, local.A, local.B, R(23) );
P( local.B, local.C, local.D, local.E, local.A, R(24) );
P( local.A, local.B, local.C, local.D, local.E, R(25) );
P( local.E, local.A, local.B, local.C, local.D, R(26) );
P( local.D, local.E, local.A, local.B, local.C, R(27) );
P( local.C, local.D, local.E, local.A, local.B, R(28) );
P( local.B, local.C, local.D, local.E, local.A, R(29) );
P( local.A, local.B, local.C, local.D, local.E, R(30) );
P( local.E, local.A, local.B, local.C, local.D, R(31) );
P( local.D, local.E, local.A, local.B, local.C, R(32) );
P( local.C, local.D, local.E, local.A, local.B, R(33) );
P( local.B, local.C, local.D, local.E, local.A, R(34) );
P( local.A, local.B, local.C, local.D, local.E, R(35) );
P( local.E, local.A, local.B, local.C, local.D, R(36) );
P( local.D, local.E, local.A, local.B, local.C, R(37) );
P( local.C, local.D, local.E, local.A, local.B, R(38) );
P( local.B, local.C, local.D, local.E, local.A, R(39) );
#undef K
#undef F
#define F(x,y,z) (((x) & (y)) | ((z) & ((x) | (y))))
#define K 0x8F1BBCDC
P( local.A, local.B, local.C, local.D, local.E, R(40) );
P( local.E, local.A, local.B, local.C, local.D, R(41) );
P( local.D, local.E, local.A, local.B, local.C, R(42) );
P( local.C, local.D, local.E, local.A, local.B, R(43) );
P( local.B, local.C, local.D, local.E, local.A, R(44) );
P( local.A, local.B, local.C, local.D, local.E, R(45) );
P( local.E, local.A, local.B, local.C, local.D, R(46) );
P( local.D, local.E, local.A, local.B, local.C, R(47) );
P( local.C, local.D, local.E, local.A, local.B, R(48) );
P( local.B, local.C, local.D, local.E, local.A, R(49) );
P( local.A, local.B, local.C, local.D, local.E, R(50) );
P( local.E, local.A, local.B, local.C, local.D, R(51) );
P( local.D, local.E, local.A, local.B, local.C, R(52) );
P( local.C, local.D, local.E, local.A, local.B, R(53) );
P( local.B, local.C, local.D, local.E, local.A, R(54) );
P( local.A, local.B, local.C, local.D, local.E, R(55) );
P( local.E, local.A, local.B, local.C, local.D, R(56) );
P( local.D, local.E, local.A, local.B, local.C, R(57) );
P( local.C, local.D, local.E, local.A, local.B, R(58) );
P( local.B, local.C, local.D, local.E, local.A, R(59) );
#undef K
#undef F
#define F(x,y,z) ((x) ^ (y) ^ (z))
#define K 0xCA62C1D6
P( local.A, local.B, local.C, local.D, local.E, R(60) );
P( local.E, local.A, local.B, local.C, local.D, R(61) );
P( local.D, local.E, local.A, local.B, local.C, R(62) );
P( local.C, local.D, local.E, local.A, local.B, R(63) );
P( local.B, local.C, local.D, local.E, local.A, R(64) );
P( local.A, local.B, local.C, local.D, local.E, R(65) );
P( local.E, local.A, local.B, local.C, local.D, R(66) );
P( local.D, local.E, local.A, local.B, local.C, R(67) );
P( local.C, local.D, local.E, local.A, local.B, R(68) );
P( local.B, local.C, local.D, local.E, local.A, R(69) );
P( local.A, local.B, local.C, local.D, local.E, R(70) );
P( local.E, local.A, local.B, local.C, local.D, R(71) );
P( local.D, local.E, local.A, local.B, local.C, R(72) );
P( local.C, local.D, local.E, local.A, local.B, R(73) );
P( local.B, local.C, local.D, local.E, local.A, R(74) );
P( local.A, local.B, local.C, local.D, local.E, R(75) );
P( local.E, local.A, local.B, local.C, local.D, R(76) );
P( local.D, local.E, local.A, local.B, local.C, R(77) );
P( local.C, local.D, local.E, local.A, local.B, R(78) );
P( local.B, local.C, local.D, local.E, local.A, R(79) );
#undef K
#undef F
// clang-format on
ctx->state[0] += local.A;
ctx->state[1] += local.B;
ctx->state[2] += local.C;
ctx->state[3] += local.D;
ctx->state[4] += local.E;
return (0);
}
int Digest_SHA1_Update(Digest_SHA1_CTX * ctx,
const uint8_t * input,
size_t ilen)
{
int ret = -1;
size_t fill;
uint32_t left;
if (ilen == 0) return (0);
left = ctx->total[0] & 0x3F;
fill = 64 - left;
ctx->total[0] += (uint32_t) ilen;
ctx->total[0] &= 0xFFFFFFFF;
if (ctx->total[0] < (uint32_t) ilen) ctx->total[1]++;
if (left && ilen >= fill)
{
memcpy((void *) (ctx->buffer + left), input, fill);
if ((ret = Digest_Internal_SHA1_Process(ctx, ctx->buffer)) != 0)
return (ret);
input += fill;
ilen -= fill;
left = 0;
}
while (ilen >= 64)
{
if ((ret = Digest_Internal_SHA1_Process(ctx, input)) != 0) return (ret);
input += 64;
ilen -= 64;
}
if (ilen > 0)
{
memcpy((void *) (ctx->buffer + left), input, ilen);
}
return (0);
}
int Digest_SHA1_Finish(Digest_SHA1_CTX * ctx, uint8_t output[static DIGEST_SHA1_MAC_LEN])
{
int ret = -1;
uint32_t used;
uint32_t high, low;
/* Add padding: 0x80 then 0x00 until 8 bytes remain for the length */
used = ctx->total[0] & 0x3F;
ctx->buffer[used++] = 0x80;
if (used <= 56)
{
/* Enough room for padding + length in current block */
memset(ctx->buffer + used, 0, 56 - used);
}
else
{
/* We'll need an extra block */
memset(ctx->buffer + used, 0, 64 - used);
if ((ret = Digest_Internal_SHA1_Process(ctx, ctx->buffer)) != 0)
return (ret);
memset(ctx->buffer, 0, 56);
}
/* Add message length */
// clang-format off
high = ( ctx->total[0] >> 29 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
// clang-format on
PUT_UINT32_BE(high, ctx->buffer, 56);
PUT_UINT32_BE(low, ctx->buffer, 60);
if ((ret = Digest_Internal_SHA1_Process(ctx, ctx->buffer)) != 0)
return (ret);
/* Output final state */
// clang-format off
PUT_UINT32_BE( ctx->state[0], output, 0 );
PUT_UINT32_BE( ctx->state[1], output, 4 );
PUT_UINT32_BE( ctx->state[2], output, 8 );
PUT_UINT32_BE( ctx->state[3], output, 12 );
PUT_UINT32_BE( ctx->state[4], output, 16 );
// clang-format on
return (0);
}
int Digest_SHA1(const uint8_t * input,
size_t ilen,
uint8_t output[static DIGEST_SHA1_MAC_LEN])
{
int ret = -1;
Digest_SHA1_CTX ctx;
memset(&ctx, 0, sizeof(ctx));
if ((ret = Digest_SHA1_Init(&ctx)) != 0)
errx(1, "Digest_SHA1_Init() failed");
else if ((ret = Digest_SHA1_Update(&ctx, input, ilen)) != 0)
errx(1, "Digest_SHA1_Update() failed");
else if ((ret = Digest_SHA1_Finish(&ctx, output)) != 0)
errx(1, "Digest_SHA1_Finish() failed");
return (ret);
} |
C | aircrack-ng/lib/crypto/sha1-git.c | #ifndef _SHA1_GIT
/*
* sha1-git.c
*
* This code is based on the GIT SHA1 Implementation.
*
* Copyright (C) 2009 Linus Torvalds <[email protected]>
* Copyright (C) 2009 Nicolas Pitre <[email protected]>
* Copyright (C) 2009 Junio C Hamano <[email protected]>
* Copyright (C) 2009 Brandon Casey <[email protected]>
* Copyright (C) 2010 Ramsay Jones <[email protected]>
* Copyright (C) 2012 Carlos Alberto Lopez Perez <[email protected]>
*
* 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.
*
*/
/*
* SHA1 routine optimized to do word accesses rather than byte accesses,
* and to avoid unnecessary copies into the context array.
*
* This was initially based on the Mozilla SHA1 implementation, although
* none of the original Mozilla code remains.
*/
/* this is only to get definitions for memcpy(), ntohl() and htonl() */
//#include "../git-compat-util.h"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <arpa/inet.h>
#include "aircrack-ng/crypto/sha1-git.h"
#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
/*
* Force usage of rol or ror by selecting the one with the smaller constant.
* It _can_ generate slightly smaller code (a constant of 1 is special), but
* perhaps more importantly it's possibly faster on any uarch that does a
* rotate with a loop.
*/
#define SHA_ASM(op, x, n) \
__extension__({ \
unsigned int __res; \
__asm__(op " %1,%0" : "=r"(__res) : "i"(n), "0"(x)); \
__res; \
})
#define SHA_ROL(x, n) SHA_ASM("rol", x, n)
#define SHA_ROR(x, n) SHA_ASM("ror", x, n)
#else
#define SHA_ROT(X, l, r) (((X) << (l)) | ((X) >> (r)))
#define SHA_ROL(X, n) SHA_ROT(X, n, 32 - (n))
#define SHA_ROR(X, n) SHA_ROT(X, 32 - (n), n)
#endif
/*
* If you have 32 registers or more, the compiler can (and should)
* try to change the array[] accesses into registers. However, on
* machines with less than ~25 registers, that won't really work,
* and at least gcc will make an unholy mess of it.
*
* So to avoid that mess which just slows things down, we force
* the stores to memory to actually happen (we might be better off
* with a 'W(t)=(val);asm("":"+m" (W(t))' there instead, as
* suggested by Artur Skawina - that will also make gcc unable to
* try to do the silly "optimize away loads" part because it won't
* see what the value will be).
*
* Ben Herrenschmidt reports that on PPC, the C version comes close
* to the optimized asm with this (ie on PPC you don't want that
* 'volatile', since there are lots of registers).
*
* On ARM we get the best code generation by forcing a full memory barrier
* between each SHA_ROUND, otherwise gcc happily get wild with spilling and
* the stack frame size simply explode and performance goes down the drain.
*/
#if defined(__i386__) || defined(__x86_64__)
#define setW(x, val) (*(volatile unsigned int *) &W(x) = (val))
#elif defined(__GNUC__) && defined(__arm__)
#define setW(x, val) \
do \
{ \
W(x) = (val); \
__asm__("" ::: "memory"); \
} while (0)
#else
#define setW(x, val) (W(x) = (val))
#endif
/*
* Performance might be improved if the CPU architecture is OK with
* unaligned 32-bit loads and a fast ntohl() is available.
* Otherwise fall back to byte loads and shifts which is portable,
* and is faster on architectures with memory alignment issues.
*/
#if defined(__i386__) || defined(__x86_64__) || defined(_M_IX86) \
|| defined(_M_X64) || defined(__ppc__) || defined(__ppc64__) \
|| defined(__powerpc__) || defined(__powerpc64__) || defined(__s390__) \
|| defined(__s390x__)
#define get_be32(p) ntohl(*(unsigned int *) (p))
#define put_be32(p, v) \
do \
{ \
*(unsigned int *) (p) = htonl(v); \
} while (0)
#else
#define get_be32(p) \
((*((unsigned char *) (p) + 0) << 24) \
| (*((unsigned char *) (p) + 1) << 16) \
| (*((unsigned char *) (p) + 2) << 8) \
| (*((unsigned char *) (p) + 3) << 0))
#define put_be32(p, v) \
do \
{ \
unsigned int __v = (v); \
*((unsigned char *) (p) + 0) = __v >> 24; \
*((unsigned char *) (p) + 1) = __v >> 16; \
*((unsigned char *) (p) + 2) = __v >> 8; \
*((unsigned char *) (p) + 3) = __v >> 0; \
} while (0)
#endif
/* This "rolls" over the 512-bit array */
#define W(x) (array[(x) &15])
/*
* Where do we get the source from? The first 16 iterations get it from
* the input data, the next mix it from the 512-bit array.
*/
#define SHA_SRC(t) get_be32(data + (t))
#define SHA_MIX(t) SHA_ROL(W((t) + 13) ^ W((t) + 8) ^ W((t) + 2) ^ W((t)), 1)
#define SHA_ROUND(t, input, fn, constant, A, B, C, D, E) \
do \
{ \
unsigned int TEMP = input((t)); \
setW((t), TEMP); \
E += TEMP + SHA_ROL((A), 5) + (fn) + (constant); \
B = SHA_ROR((B), 2); \
} while (0)
#define T_0_15(t, A, B, C, D, E) \
SHA_ROUND((t), \
SHA_SRC, \
((((C) ^ (D)) & (B)) ^ (D)), \
0x5a827999, \
(A), \
(B), \
(C), \
(D), \
(E))
#define T_16_19(t, A, B, C, D, E) \
SHA_ROUND((t), \
SHA_MIX, \
((((C) ^ (D)) & (B)) ^ (D)), \
0x5a827999, \
(A), \
(B), \
(C), \
(D), \
(E))
#define T_20_39(t, A, B, C, D, E) \
SHA_ROUND( \
(t), SHA_MIX, ((B) ^ (C) ^ (D)), 0x6ed9eba1, (A), (B), (C), (D), (E))
#define T_40_59(t, A, B, C, D, E) \
SHA_ROUND((t), \
SHA_MIX, \
(((B) & (C)) + ((D) & ((B) ^ (C)))), \
0x8f1bbcdc, \
(A), \
(B), \
(C), \
(D), \
(E))
#define T_60_79(t, A, B, C, D, E) \
SHA_ROUND( \
(t), SHA_MIX, ((B) ^ (C) ^ (D)), 0xca62c1d6, (A), (B), (C), (D), (E))
static void blk_SHA1_Block(blk_SHA_CTX * ctx, const unsigned int * data)
{
unsigned int A, B, C, D, E;
unsigned int array[16];
A = ctx->h0;
B = ctx->h1;
C = ctx->h2;
D = ctx->h3;
E = ctx->h4;
/* Round 1 - iterations 0-16 take their input from 'data' */
T_0_15(0, A, B, C, D, E);
T_0_15(1, E, A, B, C, D);
T_0_15(2, D, E, A, B, C);
T_0_15(3, C, D, E, A, B);
T_0_15(4, B, C, D, E, A);
T_0_15(5, A, B, C, D, E);
T_0_15(6, E, A, B, C, D);
T_0_15(7, D, E, A, B, C);
T_0_15(8, C, D, E, A, B);
T_0_15(9, B, C, D, E, A);
T_0_15(10, A, B, C, D, E);
T_0_15(11, E, A, B, C, D);
T_0_15(12, D, E, A, B, C);
T_0_15(13, C, D, E, A, B);
T_0_15(14, B, C, D, E, A);
T_0_15(15, A, B, C, D, E);
/* Round 1 - tail. Input from 512-bit mixing array */
T_16_19(16, E, A, B, C, D);
T_16_19(17, D, E, A, B, C);
T_16_19(18, C, D, E, A, B);
T_16_19(19, B, C, D, E, A);
/* Round 2 */
T_20_39(20, A, B, C, D, E);
T_20_39(21, E, A, B, C, D);
T_20_39(22, D, E, A, B, C);
T_20_39(23, C, D, E, A, B);
T_20_39(24, B, C, D, E, A);
T_20_39(25, A, B, C, D, E);
T_20_39(26, E, A, B, C, D);
T_20_39(27, D, E, A, B, C);
T_20_39(28, C, D, E, A, B);
T_20_39(29, B, C, D, E, A);
T_20_39(30, A, B, C, D, E);
T_20_39(31, E, A, B, C, D);
T_20_39(32, D, E, A, B, C);
T_20_39(33, C, D, E, A, B);
T_20_39(34, B, C, D, E, A);
T_20_39(35, A, B, C, D, E);
T_20_39(36, E, A, B, C, D);
T_20_39(37, D, E, A, B, C);
T_20_39(38, C, D, E, A, B);
T_20_39(39, B, C, D, E, A);
/* Round 3 */
T_40_59(40, A, B, C, D, E);
T_40_59(41, E, A, B, C, D);
T_40_59(42, D, E, A, B, C);
T_40_59(43, C, D, E, A, B);
T_40_59(44, B, C, D, E, A);
T_40_59(45, A, B, C, D, E);
T_40_59(46, E, A, B, C, D);
T_40_59(47, D, E, A, B, C);
T_40_59(48, C, D, E, A, B);
T_40_59(49, B, C, D, E, A);
T_40_59(50, A, B, C, D, E);
T_40_59(51, E, A, B, C, D);
T_40_59(52, D, E, A, B, C);
T_40_59(53, C, D, E, A, B);
T_40_59(54, B, C, D, E, A);
T_40_59(55, A, B, C, D, E);
T_40_59(56, E, A, B, C, D);
T_40_59(57, D, E, A, B, C);
T_40_59(58, C, D, E, A, B);
T_40_59(59, B, C, D, E, A);
/* Round 4 */
T_60_79(60, A, B, C, D, E);
T_60_79(61, E, A, B, C, D);
T_60_79(62, D, E, A, B, C);
T_60_79(63, C, D, E, A, B);
T_60_79(64, B, C, D, E, A);
T_60_79(65, A, B, C, D, E);
T_60_79(66, E, A, B, C, D);
T_60_79(67, D, E, A, B, C);
T_60_79(68, C, D, E, A, B);
T_60_79(69, B, C, D, E, A);
T_60_79(70, A, B, C, D, E);
T_60_79(71, E, A, B, C, D);
T_60_79(72, D, E, A, B, C);
T_60_79(73, C, D, E, A, B);
T_60_79(74, B, C, D, E, A);
T_60_79(75, A, B, C, D, E);
T_60_79(76, E, A, B, C, D);
T_60_79(77, D, E, A, B, C);
T_60_79(78, C, D, E, A, B);
T_60_79(79, B, C, D, E, A);
ctx->h0 += A;
ctx->h1 += B;
ctx->h2 += C;
ctx->h3 += D;
ctx->h4 += E;
}
void blk_SHA1_Init(blk_SHA_CTX * ctx)
{
ctx->size = 0;
/* Initialize H with the magic constants (see FIPS180 for constants) */
ctx->h0 = 0x67452301;
ctx->h1 = 0xefcdab89;
ctx->h2 = 0x98badcfe;
ctx->h3 = 0x10325476;
ctx->h4 = 0xc3d2e1f0;
}
void blk_SHA1_Update(blk_SHA_CTX * ctx, const void * data, unsigned long len)
{
unsigned int lenW = ctx->size & 63;
ctx->size += len;
/* Read the data into W and process blocks as they get full */
if (lenW)
{
unsigned int left = 64 - lenW;
if (len < left) left = len;
memcpy(lenW + (char *) ctx->W, data, left);
lenW = (lenW + left) & 63;
len -= left;
data = ((const char *) data + left);
if (lenW) return;
blk_SHA1_Block(ctx, ctx->W);
}
while (len >= 64)
{
blk_SHA1_Block(ctx, data);
data = ((const char *) data + 64);
len -= 64;
}
if (len) memcpy(ctx->W, data, len);
}
void blk_SHA1_Final(unsigned char hashout[20], blk_SHA_CTX * ctx)
{
static const unsigned char pad[64] = {0x80}; //-V1009
unsigned int padlen[2];
int i;
/* Pad with a binary 1 (ie 0x80), then zeroes, then length */
padlen[0] = htonl((uint32_t)(ctx->size >> 29));
padlen[1] = htonl((uint32_t)(ctx->size << 3));
i = ctx->size & 63;
blk_SHA1_Update(ctx, pad, 1 + (63 & (55 - i)));
blk_SHA1_Update(ctx, padlen, 8);
/* Output hash */
put_be32(&hashout[0], ctx->h0);
put_be32(&hashout[4], ctx->h1);
put_be32(&hashout[8], ctx->h2);
put_be32(&hashout[12], ctx->h3);
put_be32(&hashout[16], ctx->h4);
}
#define _SHA1_GIT
#endif |
C | aircrack-ng/lib/crypto/sha1-openssl.c | // clang-format off
/**
* \file sha1-openssl.c
*
* \brief The SHA-1 cryptographic hash function
*
* The Secure Hash Algorithm 1 (SHA-1) cryptographic hash function is defined
* in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
*
* This code uses the OpenSSL EVP high-level interfaces; which heap allocate!
* See: https://github.com/openssl/openssl/issues/7219
*
* \warning SHA-1 is considered a weak message digest and its use constitutes
* a security risk. We recommend considering stronger message
* digests instead.
*
* \author Joseph Benden <[email protected]>
* \author Jouni Malinen <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include <err.h> // warn{,s} err{,x}
#include <openssl/evp.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/sha1.h"
#if OPENSSL_VERSION_NUMBER < 0x10100000L
# define EVP_MD_CTX_new EVP_MD_CTX_create
# define EVP_MD_CTX_free EVP_MD_CTX_destroy
#endif
// clang-format on
Digest_SHA1_CTX * Digest_SHA1_Create(void) { return EVP_MD_CTX_new(); }
void Digest_SHA1_Destroy(Digest_SHA1_CTX * ctx)
{
if (ctx) EVP_MD_CTX_free(ctx);
}
void Digest_SHA1_Clone(Digest_SHA1_CTX ** dst, const Digest_SHA1_CTX * src)
{
REQUIRE(src != NULL);
REQUIRE(dst != NULL);
REQUIRE(*dst != NULL);
(void) EVP_MD_CTX_copy(*dst, src);
}
int Digest_SHA1_Init(Digest_SHA1_CTX * ctx)
{
if (!EVP_DigestInit_ex(ctx, EVP_sha1(), NULL))
return (-1);
else
return (0);
}
int Digest_SHA1_Update(Digest_SHA1_CTX * ctx,
const uint8_t * input,
size_t ilen)
{
if (!EVP_DigestUpdate(ctx, input, ilen))
return (-1);
else
return (0);
}
int Digest_SHA1_Finish(Digest_SHA1_CTX * ctx,
uint8_t output[static DIGEST_SHA1_MAC_LEN])
{
unsigned int ilen;
if (!EVP_DigestFinal_ex(ctx, output, &ilen)) return (-1);
if (ilen != (unsigned int) DIGEST_SHA1_MAC_LEN)
return (-1);
else
return (0);
}
int Digest_SHA1(const uint8_t * input,
size_t ilen,
uint8_t output[static DIGEST_SHA1_MAC_LEN])
{
int ret;
Digest_SHA1_CTX * ctx = NULL;
if ((ctx = Digest_SHA1_Create()) == NULL)
errx(1, "Digest_SHA1_Create() failed");
else if ((ret = Digest_SHA1_Init(ctx)) != 0)
errx(1, "Digest_SHA1_Init() failed");
else if ((ret = Digest_SHA1_Update(ctx, input, ilen)) != 0)
errx(1, "Digest_SHA1_Update() failed");
else if ((ret = Digest_SHA1_Finish(ctx, output)) != 0)
errx(1, "Digest_SHA1_Finish() failed");
Digest_SHA1_Destroy(ctx);
return (ret);
} |
C | aircrack-ng/lib/crypto/sha1.c | // clang-format off
/**
* \file sha1.c
*
* \brief The SHA-1 cryptographic hash function
*
* The Secure Hash Algorithm 1 (SHA-1) cryptographic hash function is defined
* in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
*
* \warning SHA-1 is considered a weak message digest and its use constitutes
* a security risk. We recommend considering stronger message
* digests instead.
*
* \author Joseph Benden <[email protected]>
* \author Jouni Malinen <[email protected]>
*
* \license BSD-3-CLAUSE
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/crypto/sha1.h"
// clang-format on
API_EXPORT
int Digest_SHA1_Vector(size_t num_elem,
const uint8_t * addr[static num_elem],
const size_t len[static num_elem],
uint8_t mac[static DIGEST_SHA1_MAC_LEN])
{
Digest_SHA1_CTX * ctx = Digest_SHA1_Create();
size_t i;
if (!ctx) return -1;
Digest_SHA1_Init(ctx);
for (i = 0; i < num_elem; i++) Digest_SHA1_Update(ctx, addr[i], len[i]);
Digest_SHA1_Finish(ctx, mac);
Digest_SHA1_Destroy(ctx);
return 0;
}
static int pbkdf2_sha1_f(const uint8_t * passphrase,
const uint8_t * ssid,
size_t ssid_len,
size_t iterations,
size_t count,
uint8_t digest[static DIGEST_SHA1_MAC_LEN])
{
unsigned char tmp[DIGEST_SHA1_MAC_LEN], tmp2[DIGEST_SHA1_MAC_LEN];
size_t i, j;
unsigned char count_buf[4];
const uint8_t * addr[2];
size_t len[2];
size_t passphrase_len = ustrlen(passphrase);
addr[0] = ssid;
len[0] = ssid_len;
addr[1] = count_buf;
len[1] = 4;
/* F(P, S, c, i) = U1 xor U2 xor ... Uc
* U1 = PRF(P, S || i)
* U2 = PRF(P, U1)
* Uc = PRF(P, Uc-1)
*/
count_buf[0] = (count >> 24) & 0xff;
count_buf[1] = (count >> 16) & 0xff;
count_buf[2] = (count >> 8) & 0xff;
count_buf[3] = count & 0xff;
if (MAC_HMAC_SHA1_Vector(passphrase_len, passphrase, 2, addr, len, tmp))
return -1;
memcpy(digest, tmp, DIGEST_SHA1_MAC_LEN);
for (i = 1; i < iterations; i++)
{
if (MAC_HMAC_SHA1(
passphrase_len, passphrase, DIGEST_SHA1_MAC_LEN, tmp, tmp2))
return -1;
memcpy(tmp, tmp2, DIGEST_SHA1_MAC_LEN);
for (j = 0; j < DIGEST_SHA1_MAC_LEN; j++) digest[j] ^= tmp2[j];
}
return 0;
}
API_EXPORT
int KDF_PBKDF2_SHA1(const uint8_t * passphrase,
const uint8_t * ssid,
size_t ssid_len,
size_t iterations,
uint8_t * buf,
size_t buflen)
{
unsigned int count = 0;
unsigned char * pos = buf;
size_t left = buflen, plen;
unsigned char digest[DIGEST_SHA1_MAC_LEN];
while (left > 0)
{
count++;
if (pbkdf2_sha1_f(
passphrase, ssid, ssid_len, iterations, count, digest))
return -1;
plen = left > DIGEST_SHA1_MAC_LEN ? DIGEST_SHA1_MAC_LEN : left;
memcpy(pos, digest, plen);
pos += plen;
left -= plen;
}
return 0;
}
API_EXPORT
int SHA1_PRF(const uint8_t * key,
size_t key_len,
const uint8_t * label,
const uint8_t * data,
size_t data_len,
uint8_t * buf,
size_t buf_len)
{
uint8_t counter = 0;
size_t pos, plen;
uint8_t hash[DIGEST_SHA1_MAC_LEN];
size_t label_len = ustrlen(label) + 1;
const uint8_t * addr[3];
size_t len[3];
// clang-format off
addr[0] = label;
len[0] = label_len;
addr[1] = data;
len[1] = data_len;
addr[2] = &counter;
len[2] = 1;
// clang-format on
pos = 0;
while (pos < buf_len)
{
plen = buf_len - pos;
if (plen >= DIGEST_SHA1_MAC_LEN)
{
if (MAC_HMAC_SHA1_Vector(key_len, key, 3, addr, len, &buf[pos]))
return -1;
pos += DIGEST_SHA1_MAC_LEN;
}
else
{
if (MAC_HMAC_SHA1_Vector(key_len, key, 3, addr, len, hash))
return -1;
memcpy(&buf[pos], hash, plen);
break;
}
counter++;
}
return 0;
} |
C | aircrack-ng/lib/crypto/sha256-gcrypt.c | // clang-format off
/**
* \file sha256-gcrypt.c
*
* \brief The SHA-256 cryptographic hash function and PRF (IEEE 802.11r)
*
* The Secure Hash Algorithm 2 (256-bit) cryptographic hash function is
* defined in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
*
* \ingroup
* \cond
******************************************************************************
*
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include <err.h> // warn{,s} err{,x}
#include <gcrypt.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/crypto.h"
// clang-format on
#ifdef USE_GCRYPT
// clang-format off
#ifndef GCRYPT_WITH_SHA256
# error "Wrong module included for SHA-2-256 with Gcrypt."
#endif
// clang-format on
Digest_SHA256_CTX * Digest_SHA256_Create(void)
{
return calloc(1, sizeof(Digest_SHA256_CTX));
}
void Digest_SHA256_Destroy(Digest_SHA256_CTX * ctx)
{
REQUIRE(ctx != NULL);
free(ctx);
}
void Digest_SHA256_Clone(Digest_SHA256_CTX ** dst,
const Digest_SHA256_CTX * src)
{
REQUIRE(src != NULL);
REQUIRE(dst != NULL);
if (gcry_md_copy(*dst, *src) != GPG_ERR_NO_ERROR)
errx(1, "Failed to copy SHA-1");
}
int Digest_SHA256_Init(Digest_SHA256_CTX * ctx)
{
REQUIRE(ctx != NULL);
if (gcry_md_open(ctx, GCRY_MD_SHA256, 0) != GPG_ERR_NO_ERROR)
errx(1, "Failed to open SHA-2-256");
return (0);
}
int Digest_SHA256_Update(Digest_SHA256_CTX * ctx,
const uint8_t * input,
size_t ilen)
{
gcry_md_write(*ctx, input, ilen);
return (0);
}
int Digest_SHA256_Finish(Digest_SHA256_CTX * ctx,
uint8_t output[static DIGEST_SHA256_MAC_LEN])
{
unsigned int dlen = gcry_md_get_algo_dlen(gcry_md_get_algo(*ctx));
unsigned char * dgst = gcry_md_read(*ctx, GCRY_MD_SHA256);
if (!dgst) return (-1);
memcpy(output, dgst, dlen);
gcry_md_close(*ctx);
return (0);
}
int Digest_SHA256(const uint8_t * input,
size_t ilen,
uint8_t output[static DIGEST_SHA256_MAC_LEN])
{
int ret = -1;
gcry_md_hd_t ctx;
memset(&ctx, 0, sizeof(ctx));
if ((ret = Digest_SHA256_Init(&ctx)) != 0)
errx(1, "Digest_SHA256_Init failed");
else if ((ret = Digest_SHA256_Update(&ctx, input, ilen)) != 0)
errx(1, "Digest_SHA256_Update failed");
else if ((ret = Digest_SHA256_Finish(&ctx, output)) != 0)
errx(1, "Digest_SHA256_Finish failed");
return (ret);
}
#endif |
C | aircrack-ng/lib/crypto/sha256-openssl.c | // clang-format off
/**
* \file sha256-openssl.c
*
* \brief The SHA-256 cryptographic hash function and PRF (IEEE 802.11r)
*
* The Secure Hash Algorithm 2 (256-bit) cryptographic hash function is
* defined in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
*
* This code uses the OpenSSL EVP high-level interfaces; which heap allocate!
*
* See: https://github.com/openssl/openssl/issues/7219
*
* \ingroup
* \cond
******************************************************************************
*
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include <err.h> // warn{,s} err{,x}
#include <openssl/evp.h>
#include <aircrack-ng/defs.h>
#include <aircrack-ng/crypto/sha256.h>
#if OPENSSL_VERSION_NUMBER < 0x10100000L
# define EVP_MD_CTX_new EVP_MD_CTX_create
# define EVP_MD_CTX_free EVP_MD_CTX_destroy
#endif
// clang-format on
Digest_SHA256_CTX * Digest_SHA256_Create(void) { return EVP_MD_CTX_new(); }
void Digest_SHA256_Destroy(Digest_SHA256_CTX * ctx)
{
if (ctx) EVP_MD_CTX_free(ctx);
}
void Digest_SHA256_Clone(Digest_SHA256_CTX ** dst,
const Digest_SHA256_CTX * src)
{
ENSURE(src != NULL);
ENSURE(dst != NULL);
(void) EVP_MD_CTX_copy(*dst, src);
}
int Digest_SHA256_Init(Digest_SHA256_CTX * ctx)
{
if (!EVP_DigestInit_ex(ctx, EVP_sha256(), NULL))
return (-1);
else
return (0);
}
int Digest_SHA256_Update(Digest_SHA256_CTX * ctx,
const uint8_t * input,
size_t ilen)
{
if (!EVP_DigestUpdate(ctx, input, ilen))
return (-1);
else
return (0);
}
int Digest_SHA256_Finish(Digest_SHA256_CTX * ctx,
uint8_t output[static DIGEST_SHA256_MAC_LEN])
{
unsigned int ilen;
if (!EVP_DigestFinal_ex(ctx, output, &ilen)) return (-1);
if (ilen != (unsigned int) DIGEST_SHA256_MAC_LEN)
return (-1);
else
return (0);
}
int Digest_SHA256(const uint8_t * input,
size_t ilen,
uint8_t output[static DIGEST_SHA256_MAC_LEN])
{
int ret;
Digest_SHA256_CTX * ctx = NULL;
if ((ctx = Digest_SHA256_Create()) == NULL)
errx(1, "Digest_SHA256_Create() failed");
else if ((ret = Digest_SHA256_Init(ctx)) != 0)
errx(1, "Digest_SHA256_Init() failed");
else if ((ret = Digest_SHA256_Update(ctx, input, ilen)) != 0)
errx(1, "Digest_SHA256_Update() failed");
else if ((ret = Digest_SHA256_Finish(ctx, output)) != 0)
errx(1, "Digest_SHA256_Finish() failed");
Digest_SHA256_Destroy(ctx);
return (ret);
} |
C | aircrack-ng/lib/crypto/sha256.c | // clang-format off
/**
* \file sha256.c
*
* \brief The SHA-2-256 cryptographic hash function and PRF (IEEE 802.11r)
*
* The Secure Hash Algorithm 2 (256-bit) cryptographic hash function is
* defined in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
*
* \ingroup
* \cond
******************************************************************************
*
* Portions Copyright (c) 2003-2016, Jouni Malinen <[email protected]>
* SPDX-License-Identifier: BSD-3-CLAUSE
*
******************************************************************************
* \endcond
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stddef.h> // {s,ss}ize_t
#include <stdint.h> // [u]int[8,16,32,64]_t
#include "aircrack-ng/defs.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/crypto/sha256.h"
API_EXPORT
int Digest_SHA256_Vector( size_t num_elem,
const uint8_t *addr[static num_elem],
const size_t len[static num_elem],
uint8_t mac[static DIGEST_SHA256_MAC_LEN] )
{
Digest_SHA256_CTX * ctx = Digest_SHA256_Create();
size_t i;
if (!ctx) return -1;
Digest_SHA256_Init(ctx);
for (i = 0; i < num_elem; i++)
Digest_SHA256_Update(ctx, addr[i], len[i]);
Digest_SHA256_Finish(ctx, mac);
Digest_SHA256_Destroy(ctx);
return 0;
}
#if defined(__i386__) || defined(__x86_64__) || defined(_M_IX86) \
|| defined(_M_X64) || defined(__ppc__) || defined(__ppc64__) \
|| defined(__powerpc__) || defined(__powerpc64__) || defined(__s390__) \
|| defined(__s390x__)
static inline
void WPA_PUT_LE16(uint8_t * a, uint_fast16_t val)
{
a[1] = (uint8_t)(val >> 8u);
a[0] = (uint8_t)(val & 0xff);
}
#else
void WPA_PUT_LE16(uint8_t * a, uint_fast16_t val)
{
a[0] = (uint8_t)(val >> 8u);
a[1] = (uint8_t)(val & 0xff);
}
#endif
void Digest_SHA256_PRF_Bits(const uint8_t *key,
size_t key_len,
const uint8_t *label,
const uint8_t *data,
size_t data_len,
uint8_t *buf,
size_t buf_len_bits)
{
uint16_t counter = 1;
size_t pos;
size_t plen;
uint8_t hash[DIGEST_SHA256_MAC_LEN];
const uint8_t *addr[4];
size_t len[4];
uint8_t counter_le[2];
uint8_t length_le[2];
size_t buf_len = (buf_len_bits + 7) / 8;
addr[0] = counter_le;
len[0] = 2;
addr[1] = label;
len[1] = ustrlen(label);
addr[2] = data;
len[2] = data_len;
addr[3] = length_le;
len[3] = sizeof(length_le);
WPA_PUT_LE16(length_le, (uint_fast16_t) buf_len_bits);
pos = 0;
while (pos < buf_len)
{
plen = buf_len - pos;
WPA_PUT_LE16(counter_le, counter);
if (plen >= DIGEST_SHA256_MAC_LEN)
{
MAC_HMAC_SHA256_Vector(key_len, key, 4, addr, len, &buf[pos]);
pos += DIGEST_SHA256_MAC_LEN;
}
else
{
MAC_HMAC_SHA256_Vector(key_len, key, 4, addr, len, hash);
memcpy(&buf[pos], hash, plen);
pos += plen;
break;
}
counter++;
}
/*
* Mask out unused bits in the last octet if it does not use all the
* bits.
*/
if (buf_len_bits % 8)
{
const uint8_t mask = (uint8_t)(0xff << (8u - buf_len_bits % 8));
buf[pos - 1] &= mask;
}
}
// clang-format on |
Visual Studio Solution | aircrack-ng/lib/csharp/Example1/Example1.sln | Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Example1", "Example1\Example1.csproj", "{C4AE481A-A896-4830-9202-6221890AB43B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WirelessPanda", "..\WirelessPanda\WirelessPanda.csproj", "{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|Mixed Platforms = Debug|Mixed Platforms
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|Mixed Platforms = Release|Mixed Platforms
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C4AE481A-A896-4830-9202-6221890AB43B}.Debug|Any CPU.ActiveCfg = Debug|x86
{C4AE481A-A896-4830-9202-6221890AB43B}.Debug|Mixed Platforms.ActiveCfg = Debug|x86
{C4AE481A-A896-4830-9202-6221890AB43B}.Debug|Mixed Platforms.Build.0 = Debug|x86
{C4AE481A-A896-4830-9202-6221890AB43B}.Debug|x86.ActiveCfg = Debug|x86
{C4AE481A-A896-4830-9202-6221890AB43B}.Debug|x86.Build.0 = Debug|x86
{C4AE481A-A896-4830-9202-6221890AB43B}.Release|Any CPU.ActiveCfg = Release|x86
{C4AE481A-A896-4830-9202-6221890AB43B}.Release|Mixed Platforms.ActiveCfg = Release|x86
{C4AE481A-A896-4830-9202-6221890AB43B}.Release|Mixed Platforms.Build.0 = Release|x86
{C4AE481A-A896-4830-9202-6221890AB43B}.Release|x86.ActiveCfg = Release|x86
{C4AE481A-A896-4830-9202-6221890AB43B}.Release|x86.Build.0 = Release|x86
{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}.Debug|x86.ActiveCfg = Debug|Any CPU
{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}.Release|Any CPU.Build.0 = Release|Any CPU
{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}.Release|x86.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal |
aircrack-ng/lib/csharp/Example1/Example1/app.config | <?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration> |
|
aircrack-ng/lib/csharp/Example1/Example1/Example1.csproj | <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{C4AE481A-A896-4830-9202-6221890AB43B}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Example1</RootNamespace>
<AssemblyName>Example1</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="app.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\WirelessPanda\WirelessPanda.csproj">
<Project>{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}</Project>
<Name>WirelessPanda</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> |
|
C# | aircrack-ng/lib/csharp/Example1/Example1/Form1.cs | // License: BSD
// Copyright (C) 2011-2018 Thomas d'Otreppe
using System;
using System.Windows.Forms;
using WirelessPanda.Readers;
namespace Example1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// Load file
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = false;
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Load file
Reader reader = new UniversalReader(ofd.FileName);
try
{
// and parse it
reader.Read();
// Add Datatables
this.dataGridView1.DataSource = reader.Dataset.Tables[Reader.ACCESSPOINTS_DATATABLE];
this.dataGridView2.DataSource = reader.Dataset.Tables[Reader.STATIONS_DATATABLE];
}
catch (Exception ex)
{
MessageBox.Show("Exception: " + ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
// Set file type
this.lblFiletype.Text = reader.ReaderType;
// Set filename
this.lblFilename.Text = reader.Filename;
// Indicate if parsing was successful
if (reader.ParseSuccess)
{
this.lblParsed.Text = "Yes";
}
else
{
this.lblParsed.Text = "No";
}
}
}
private void Form1_SizeChanged(object sender, EventArgs e)
{
Form f = sender as Form;
this.label1.Left = (f.Width - this.label1.Width) / 2;
this.label2.Left = (f.Width - this.label2.Width) / 2;
}
}
} |
C# | aircrack-ng/lib/csharp/Example1/Example1/Form1.Designer.cs | namespace Example1
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.dataGridView2 = new System.Windows.Forms.DataGridView();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.lblFiletype = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.lblFilename = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.lblParsed = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dataGridView2)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;
this.dataGridView1.AllowUserToOrderColumns = true;
this.dataGridView1.AllowUserToResizeRows = false;
this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.ColumnHeader;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(12, 106);
this.dataGridView1.MultiSelect = false;
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.ReadOnly = true;
this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.Size = new System.Drawing.Size(860, 128);
this.dataGridView1.TabIndex = 0;
//
// dataGridView2
//
this.dataGridView2.AllowUserToAddRows = false;
this.dataGridView2.AllowUserToDeleteRows = false;
this.dataGridView2.AllowUserToOrderColumns = true;
this.dataGridView2.AllowUserToResizeRows = false;
this.dataGridView2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGridView2.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dataGridView2.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView2.Location = new System.Drawing.Point(12, 268);
this.dataGridView2.MultiSelect = false;
this.dataGridView2.Name = "dataGridView2";
this.dataGridView2.ReadOnly = true;
this.dataGridView2.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView2.Size = new System.Drawing.Size(860, 128);
this.dataGridView2.TabIndex = 1;
//
// label1
//
this.label1.Anchor = System.Windows.Forms.AnchorStyles.Top;
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(388, 86);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(109, 17);
this.label1.TabIndex = 2;
this.label1.Text = "Access Points";
//
// label2
//
this.label2.Anchor = System.Windows.Forms.AnchorStyles.Top;
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(409, 248);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(67, 17);
this.label2.TabIndex = 3;
this.label2.Text = "Stations";
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button1.Location = new System.Drawing.Point(797, 12);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 4;
this.button1.Text = "Load...";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(12, 35);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(49, 13);
this.label3.TabIndex = 5;
this.label3.Text = "File type:";
//
// lblFiletype
//
this.lblFiletype.AutoSize = true;
this.lblFiletype.Location = new System.Drawing.Point(67, 35);
this.lblFiletype.Name = "lblFiletype";
this.lblFiletype.Size = new System.Drawing.Size(53, 13);
this.lblFiletype.TabIndex = 6;
this.lblFiletype.Text = "Unknown";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(12, 12);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(52, 13);
this.label4.TabIndex = 7;
this.label4.Text = "Filename:";
//
// lblFilename
//
this.lblFilename.AutoSize = true;
this.lblFilename.Location = new System.Drawing.Point(67, 12);
this.lblFilename.Name = "lblFilename";
this.lblFilename.Size = new System.Drawing.Size(53, 13);
this.lblFilename.TabIndex = 8;
this.lblFilename.Text = "Unknown";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(12, 57);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(43, 13);
this.label5.TabIndex = 9;
this.label5.Text = "Parsed:";
//
// lblParsed
//
this.lblParsed.AutoSize = true;
this.lblParsed.Location = new System.Drawing.Point(67, 57);
this.lblParsed.Name = "lblParsed";
this.lblParsed.Size = new System.Drawing.Size(53, 13);
this.lblParsed.TabIndex = 10;
this.lblParsed.Text = "Unknown";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(884, 411);
this.Controls.Add(this.lblParsed);
this.Controls.Add(this.label5);
this.Controls.Add(this.lblFilename);
this.Controls.Add(this.label4);
this.Controls.Add(this.lblFiletype);
this.Controls.Add(this.label3);
this.Controls.Add(this.button1);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.dataGridView2);
this.Controls.Add(this.dataGridView1);
this.MinimumSize = new System.Drawing.Size(200, 438);
this.Name = "Form1";
this.Text = "Example 1";
this.SizeChanged += new System.EventHandler(this.Form1_SizeChanged);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dataGridView2)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.DataGridView dataGridView2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label lblFiletype;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label lblFilename;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label lblParsed;
}
} |
aircrack-ng/lib/csharp/Example1/Example1/Form1.resx | <?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root> |
|
C# | aircrack-ng/lib/csharp/Example1/Example1/Program.cs | using System;
using System.Windows.Forms;
namespace Example1
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
} |
C# | aircrack-ng/lib/csharp/Example1/Example1/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Example1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Example1")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c8ca20fd-396d-461e-a240-3cb2214597d8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] |
C# | aircrack-ng/lib/csharp/Example1/Example1/Properties/Resources.Designer.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.225
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Example1.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Example1.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
} |
aircrack-ng/lib/csharp/Example1/Example1/Properties/Resources.resx | <?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root> |
|
C# | aircrack-ng/lib/csharp/Example1/Example1/Properties/Settings.Designer.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.225
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Example1.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
} |
aircrack-ng/lib/csharp/Example1/Example1/Properties/Settings.settings | <?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile> |
|
Visual Studio Solution | aircrack-ng/lib/csharp/MonoExample/NewStationNotify.sln | Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NewStationNotify", "NewStationNotify\NewStationNotify.csproj", "{82B5448F-10AA-4BE0-9C20-DEA6441C9146}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NDesk-dbus", "NDesk-dbus\NDesk-dbus.csproj", "{223B034E-A2F0-4BC7-875A-F9B5972C0670}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WirelessPanda", "..\WirelessPanda\WirelessPanda.csproj", "{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{223B034E-A2F0-4BC7-875A-F9B5972C0670}.Debug|x86.ActiveCfg = Debug|Any CPU
{223B034E-A2F0-4BC7-875A-F9B5972C0670}.Debug|x86.Build.0 = Debug|Any CPU
{223B034E-A2F0-4BC7-875A-F9B5972C0670}.Release|x86.ActiveCfg = Release|Any CPU
{223B034E-A2F0-4BC7-875A-F9B5972C0670}.Release|x86.Build.0 = Release|Any CPU
{82B5448F-10AA-4BE0-9C20-DEA6441C9146}.Debug|x86.ActiveCfg = Debug|x86
{82B5448F-10AA-4BE0-9C20-DEA6441C9146}.Debug|x86.Build.0 = Debug|x86
{82B5448F-10AA-4BE0-9C20-DEA6441C9146}.Release|x86.ActiveCfg = Release|x86
{82B5448F-10AA-4BE0-9C20-DEA6441C9146}.Release|x86.Build.0 = Release|x86
{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}.Debug|x86.ActiveCfg = Debug|Any CPU
{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}.Debug|x86.Build.0 = Debug|Any CPU
{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}.Release|x86.ActiveCfg = Release|Any CPU
{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
StartupItem = NewStationNotify\NewStationNotify.csproj
EndGlobalSection
EndGlobal |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/Address.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Text;
using System.Collections.Generic;
namespace NDesk.DBus
{
public class BadAddressException : Exception
{
public BadAddressException (string reason) : base (reason) {}
}
class AddressEntry
{
public string Method;
public IDictionary<string,string> Properties = new Dictionary<string,string> ();
public override string ToString ()
{
StringBuilder sb = new StringBuilder ();
sb.Append (Method);
sb.Append (':');
bool first = true;
foreach (KeyValuePair<string,string> prop in Properties) {
if (first)
first = false;
else
sb.Append (',');
sb.Append (prop.Key);
sb.Append ('=');
sb.Append (Escape (prop.Value));
}
return sb.ToString ();
}
static string Escape (string str)
{
if (str == null)
return String.Empty;
StringBuilder sb = new StringBuilder ();
int len = str.Length;
for (int i = 0 ; i != len ; i++) {
char c = str[i];
//everything other than the optionally escaped chars _must_ be escaped
if (Char.IsLetterOrDigit (c) || c == '-' || c == '_' || c == '/' || c == '\\' || c == '.')
sb.Append (c);
else
sb.Append (Uri.HexEscape (c));
}
return sb.ToString ();
}
static string Unescape (string str)
{
if (str == null)
return String.Empty;
StringBuilder sb = new StringBuilder ();
int len = str.Length;
int i = 0;
while (i != len) {
if (Uri.IsHexEncoding (str, i))
sb.Append (Uri.HexUnescape (str, ref i));
else
sb.Append (str[i++]);
}
return sb.ToString ();
}
public static AddressEntry Parse (string s)
{
AddressEntry entry = new AddressEntry ();
string[] parts = s.Split (':');
if (parts.Length < 2)
throw new BadAddressException ("No colon found");
if (parts.Length > 2)
throw new BadAddressException ("Too many colons found");
entry.Method = parts[0];
foreach (string propStr in parts[1].Split (',')) {
parts = propStr.Split ('=');
if (parts.Length < 2)
throw new BadAddressException ("No equals sign found");
if (parts.Length > 2)
throw new BadAddressException ("Too many equals signs found");
entry.Properties[parts[0]] = Unescape (parts[1]);
}
return entry;
}
}
static class Address
{
//(unix:(path|abstract)=.*,guid=.*|tcp:host=.*(,port=.*)?);? ...
public static AddressEntry[] Parse (string addresses)
{
if (addresses == null)
throw new ArgumentNullException (addresses);
List<AddressEntry> entries = new List<AddressEntry> ();
foreach (string entryStr in addresses.Split (';'))
entries.Add (AddressEntry.Parse (entryStr));
return entries.ToArray ();
}
const string SYSTEM_BUS_ADDRESS = "unix:path=/var/run/dbus/system_bus_socket";
public static string System
{
get {
string addr = Environment.GetEnvironmentVariable ("DBUS_SYSTEM_BUS_ADDRESS");
if (String.IsNullOrEmpty (addr))
addr = SYSTEM_BUS_ADDRESS;
return addr;
}
}
public static string Session
{
get {
return Environment.GetEnvironmentVariable ("DBUS_SESSION_BUS_ADDRESS");
}
}
public static string Starter
{
get {
return Environment.GetEnvironmentVariable ("DBUS_STARTER_ADDRESS");
}
}
public static string StarterBusType
{
get {
return Environment.GetEnvironmentVariable ("DBUS_STARTER_BUS_TYPE");
}
}
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/AssemblyInfo.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyFileVersion("0.6.0")]
[assembly: AssemblyInformationalVersion("0.6.0")]
[assembly: AssemblyVersion("0.6.0")]
[assembly: AssemblyTitle ("NDesk.DBus")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker")]
[assembly: AssemblyCompany ("NDesk")]
#if STRONG_NAME
[assembly: InternalsVisibleTo ("dbus-monitor, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("NDesk.DBus.GLib, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("NDesk.DBus.Proxies, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
#else
[assembly: InternalsVisibleTo ("dbus-monitor")]
[assembly: InternalsVisibleTo ("NDesk.DBus.GLib")]
[assembly: InternalsVisibleTo ("NDesk.DBus.Proxies")]
#endif |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/Authentication.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Globalization;
namespace NDesk.DBus.Authentication
{
enum ClientState
{
WaitingForData,
WaitingForOK,
WaitingForReject,
}
enum ServerState
{
WaitingForAuth,
WaitingForData,
WaitingForBegin,
}
class SaslClient
{
protected Connection conn;
protected SaslClient ()
{
}
public SaslClient (Connection conn)
{
this.conn = conn;
}
public void Run ()
{
StreamReader sr = new StreamReader (conn.Transport.Stream, Encoding.ASCII);
StreamWriter sw = new StreamWriter (conn.Transport.Stream, Encoding.ASCII);
sw.NewLine = "\r\n";
string str = conn.Transport.AuthString ();
byte[] bs = Encoding.ASCII.GetBytes (str);
string authStr = ToHex (bs);
sw.WriteLine ("AUTH EXTERNAL {0}", authStr);
sw.Flush ();
string ok_rep = sr.ReadLine ();
string[] parts;
parts = ok_rep.Split (' ');
if (parts.Length < 1 || parts[0] != "OK")
throw new Exception ("Authentication error: AUTH EXTERNAL was not OK: \"" + ok_rep + "\"");
/*
string guid = parts[1];
byte[] guidData = FromHex (guid);
uint unixTime = BitConverter.ToUInt32 (guidData, 0);
Console.Error.WriteLine ("guid: " + guid + ", " + "unixTime: " + unixTime + " (" + UnixToDateTime (unixTime) + ")");
*/
sw.WriteLine ("BEGIN");
sw.Flush ();
}
//From Mono.Unix.Native.NativeConvert
//should these methods use long or (u)int?
public static DateTime UnixToDateTime (long time)
{
DateTime LocalUnixEpoch = new DateTime (1970, 1, 1);
TimeSpan LocalUtcOffset = TimeZone.CurrentTimeZone.GetUtcOffset (DateTime.UtcNow);
return LocalUnixEpoch.AddSeconds ((double) time + LocalUtcOffset.TotalSeconds);
}
public static long DateTimeToUnix (DateTime time)
{
DateTime LocalUnixEpoch = new DateTime (1970, 1, 1);
TimeSpan LocalUtcOffset = TimeZone.CurrentTimeZone.GetUtcOffset (DateTime.UtcNow);
TimeSpan unixTime = time.Subtract (LocalUnixEpoch) - LocalUtcOffset;
return (long) unixTime.TotalSeconds;
}
//From Mono.Security.Cryptography
//Modified to output lowercase hex
static public string ToHex (byte[] input)
{
if (input == null)
return null;
StringBuilder sb = new StringBuilder (input.Length * 2);
foreach (byte b in input) {
sb.Append (b.ToString ("x2", CultureInfo.InvariantCulture));
}
return sb.ToString ();
}
//From Mono.Security.Cryptography
static private byte FromHexChar (char c)
{
if ((c >= 'a') && (c <= 'f'))
return (byte) (c - 'a' + 10);
if ((c >= 'A') && (c <= 'F'))
return (byte) (c - 'A' + 10);
if ((c >= '0') && (c <= '9'))
return (byte) (c - '0');
throw new ArgumentException ("Invalid hex char");
}
//From Mono.Security.Cryptography
static public byte[] FromHex (string hex)
{
if (hex == null)
return null;
if ((hex.Length & 0x1) == 0x1)
throw new ArgumentException ("Length must be a multiple of 2");
byte[] result = new byte [hex.Length >> 1];
int n = 0;
int i = 0;
while (n < result.Length) {
result [n] = (byte) (FromHexChar (hex [i++]) << 4);
result [n++] += FromHexChar (hex [i++]);
}
return result;
}
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/Bus.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using org.freedesktop.DBus;
namespace NDesk.DBus
{
public sealed class Bus : Connection
{
static Bus systemBus = null;
public static Bus System
{
get {
if (systemBus == null) {
try {
if (Address.StarterBusType == "system")
systemBus = Starter;
else
systemBus = Bus.Open (Address.System);
} catch (Exception e) {
throw new Exception ("Unable to open the system message bus.", e);
}
}
return systemBus;
}
}
static Bus sessionBus = null;
public static Bus Session
{
get {
if (sessionBus == null) {
try {
if (Address.StarterBusType == "session")
sessionBus = Starter;
else
sessionBus = Bus.Open (Address.Session);
} catch (Exception e) {
throw new Exception ("Unable to open the session message bus.", e);
}
}
return sessionBus;
}
}
//TODO: parsing of starter bus type, or maybe do this another way
static Bus starterBus = null;
public static Bus Starter
{
get {
if (starterBus == null) {
try {
starterBus = Bus.Open (Address.Starter);
} catch (Exception e) {
throw new Exception ("Unable to open the starter message bus.", e);
}
}
return starterBus;
}
}
//public static readonly Bus Session = null;
//TODO: use the guid, not the whole address string
//TODO: consider what happens when a connection has been closed
static Dictionary<string,Bus> buses = new Dictionary<string,Bus> ();
//public static Connection Open (string address)
public static new Bus Open (string address)
{
if (address == null)
throw new ArgumentNullException ("address");
if (buses.ContainsKey (address))
return buses[address];
Bus bus = new Bus (address);
buses[address] = bus;
return bus;
}
IBus bus;
static readonly string DBusName = "org.freedesktop.DBus";
static readonly ObjectPath DBusPath = new ObjectPath ("/org/freedesktop/DBus");
public Bus (string address) : base (address)
{
bus = GetObject<IBus> (DBusName, DBusPath);
/*
bus.NameAcquired += delegate (string acquired_name) {
Console.WriteLine ("NameAcquired: " + acquired_name);
};
*/
Register ();
}
//should this be public?
//as long as Bus subclasses Connection, having a Register with a completely different meaning is bad
void Register ()
{
if (unique_name != null)
throw new Exception ("Bus already has a unique name");
unique_name = bus.Hello ();
}
public ulong GetUnixUser (string name)
{
return bus.GetConnectionUnixUser (name);
}
public RequestNameReply RequestName (string name)
{
return RequestName (name, NameFlag.None);
}
public RequestNameReply RequestName (string name, NameFlag flags)
{
return bus.RequestName (name, flags);
}
public ReleaseNameReply ReleaseName (string name)
{
return bus.ReleaseName (name);
}
public bool NameHasOwner (string name)
{
return bus.NameHasOwner (name);
}
public StartReply StartServiceByName (string name)
{
return StartServiceByName (name, 0);
}
public StartReply StartServiceByName (string name, uint flags)
{
return bus.StartServiceByName (name, flags);
}
internal protected override void AddMatch (string rule)
{
bus.AddMatch (rule);
}
internal protected override void RemoveMatch (string rule)
{
bus.RemoveMatch (rule);
}
string unique_name = null;
public string UniqueName
{
get {
return unique_name;
} set {
if (unique_name != null)
throw new Exception ("Unique name can only be set once");
unique_name = value;
}
}
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/BusObject.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
namespace NDesk.DBus
{
class BusObject
{
protected Connection conn;
string bus_name;
ObjectPath object_path;
//protected BusObject ()
public BusObject ()
{
}
public BusObject (Connection conn, string bus_name, ObjectPath object_path)
{
this.conn = conn;
this.bus_name = bus_name;
this.object_path = object_path;
}
public Connection Connection
{
get {
return conn;
}
}
public string BusName
{
get {
return bus_name;
}
}
public ObjectPath Path
{
get {
return object_path;
}
}
public void ToggleSignal (string iface, string member, Delegate dlg, bool adding)
{
MatchRule rule = new MatchRule ();
rule.MessageType = MessageType.Signal;
rule.Interface = iface;
rule.Member = member;
rule.Path = object_path;
if (adding) {
if (conn.Handlers.ContainsKey (rule))
conn.Handlers[rule] = Delegate.Combine (conn.Handlers[rule], dlg);
else {
conn.Handlers[rule] = dlg;
conn.AddMatch (rule.ToString ());
}
} else {
conn.Handlers[rule] = Delegate.Remove (conn.Handlers[rule], dlg);
if (conn.Handlers[rule] == null) {
conn.RemoveMatch (rule.ToString ());
conn.Handlers.Remove (rule);
}
}
}
public void SendSignal (string iface, string member, string inSigStr, MessageWriter writer, Type retType, out Exception exception)
{
exception = null;
//TODO: don't ignore retVal, exception etc.
Signature outSig = String.IsNullOrEmpty (inSigStr) ? Signature.Empty : new Signature (inSigStr);
Signal signal = new Signal (object_path, iface, member);
signal.message.Signature = outSig;
Message signalMsg = signal.message;
signalMsg.Body = writer.ToArray ();
conn.Send (signalMsg);
}
public object SendMethodCall (string iface, string member, string inSigStr, MessageWriter writer, Type retType, out Exception exception)
{
exception = null;
//TODO: don't ignore retVal, exception etc.
Signature inSig = String.IsNullOrEmpty (inSigStr) ? Signature.Empty : new Signature (inSigStr);
MethodCall method_call = new MethodCall (object_path, iface, member, bus_name, inSig);
Message callMsg = method_call.message;
callMsg.Body = writer.ToArray ();
//Invoke Code::
//TODO: complete out parameter support
/*
Type[] outParmTypes = Mapper.GetTypes (ArgDirection.Out, mi.GetParameters ());
Signature outParmSig = Signature.GetSig (outParmTypes);
if (outParmSig != Signature.Empty)
throw new Exception ("Out parameters not yet supported: out_signature='" + outParmSig.Value + "'");
*/
Type[] outTypes = new Type[1];
outTypes[0] = retType;
//we default to always requiring replies for now, even though unnecessary
//this is to make sure errors are handled synchronously
//TODO: don't hard code this
bool needsReply = true;
//if (mi.ReturnType == typeof (void))
// needsReply = false;
callMsg.ReplyExpected = needsReply;
callMsg.Signature = inSig;
if (!needsReply) {
conn.Send (callMsg);
return null;
}
#if PROTO_REPLY_SIGNATURE
if (needsReply) {
Signature outSig = Signature.GetSig (outTypes);
callMsg.Header.Fields[FieldCode.ReplySignature] = outSig;
}
#endif
Message retMsg = conn.SendWithReplyAndBlock (callMsg);
object retVal = null;
//handle the reply message
switch (retMsg.Header.MessageType) {
case MessageType.MethodReturn:
object[] retVals = MessageHelper.GetDynamicValues (retMsg, outTypes);
if (retVals.Length != 0)
retVal = retVals[retVals.Length - 1];
break;
case MessageType.Error:
//TODO: typed exceptions
Error error = new Error (retMsg);
string errMsg = String.Empty;
if (retMsg.Signature.Value.StartsWith ("s")) {
MessageReader reader = new MessageReader (retMsg);
errMsg = reader.ReadString ();
}
exception = new Exception (error.ErrorName + ": " + errMsg);
break;
default:
throw new Exception ("Got unexpected message of type " + retMsg.Header.MessageType + " while waiting for a MethodReturn or Error");
}
return retVal;
}
public void Invoke (MethodBase methodBase, string methodName, object[] inArgs, out object[] outArgs, out object retVal, out Exception exception)
{
outArgs = new object[0];
retVal = null;
exception = null;
MethodInfo mi = methodBase as MethodInfo;
if (mi != null && mi.IsSpecialName && (methodName.StartsWith ("add_") || methodName.StartsWith ("remove_"))) {
string[] parts = methodName.Split (new char[]{'_'}, 2);
string ename = parts[1];
Delegate dlg = (Delegate)inArgs[0];
ToggleSignal (Mapper.GetInterfaceName (mi), ename, dlg, parts[0] == "add");
return;
}
Type[] inTypes = Mapper.GetTypes (ArgDirection.In, mi.GetParameters ());
Signature inSig = Signature.GetSig (inTypes);
MethodCall method_call;
Message callMsg;
//build the outbound method call message
{
//this bit is error-prone (no null checking) and will need rewriting when DProxy is replaced
string iface = null;
if (mi != null)
iface = Mapper.GetInterfaceName (mi);
//map property accessors
//TODO: this needs to be done properly, not with simple String.Replace
//note that IsSpecialName is also for event accessors, but we already handled those and returned
if (mi != null && mi.IsSpecialName) {
methodName = methodName.Replace ("get_", "Get");
methodName = methodName.Replace ("set_", "Set");
}
method_call = new MethodCall (object_path, iface, methodName, bus_name, inSig);
callMsg = method_call.message;
if (inArgs != null && inArgs.Length != 0) {
MessageWriter writer = new MessageWriter (Connection.NativeEndianness);
writer.connection = conn;
for (int i = 0 ; i != inTypes.Length ; i++)
writer.Write (inTypes[i], inArgs[i]);
callMsg.Body = writer.ToArray ();
}
}
//TODO: complete out parameter support
/*
Type[] outParmTypes = Mapper.GetTypes (ArgDirection.Out, mi.GetParameters ());
Signature outParmSig = Signature.GetSig (outParmTypes);
if (outParmSig != Signature.Empty)
throw new Exception ("Out parameters not yet supported: out_signature='" + outParmSig.Value + "'");
*/
Type[] outTypes = new Type[1];
outTypes[0] = mi.ReturnType;
//we default to always requiring replies for now, even though unnecessary
//this is to make sure errors are handled synchronously
//TODO: don't hard code this
bool needsReply = true;
//if (mi.ReturnType == typeof (void))
// needsReply = false;
callMsg.ReplyExpected = needsReply;
callMsg.Signature = inSig;
if (!needsReply) {
conn.Send (callMsg);
return;
}
#if PROTO_REPLY_SIGNATURE
if (needsReply) {
Signature outSig = Signature.GetSig (outTypes);
callMsg.Header.Fields[FieldCode.ReplySignature] = outSig;
}
#endif
Message retMsg = conn.SendWithReplyAndBlock (callMsg);
//handle the reply message
switch (retMsg.Header.MessageType) {
case MessageType.MethodReturn:
object[] retVals = MessageHelper.GetDynamicValues (retMsg, outTypes);
if (retVals.Length != 0)
retVal = retVals[retVals.Length - 1];
break;
case MessageType.Error:
//TODO: typed exceptions
Error error = new Error (retMsg);
string errMsg = String.Empty;
if (retMsg.Signature.Value.StartsWith ("s")) {
MessageReader reader = new MessageReader (retMsg);
errMsg = reader.ReadString ();
}
exception = new Exception (error.ErrorName + ": " + errMsg);
break;
default:
throw new Exception ("Got unexpected message of type " + retMsg.Header.MessageType + " while waiting for a MethodReturn or Error");
}
return;
}
public static object GetObject (Connection conn, string bus_name, ObjectPath object_path, Type declType)
{
Type proxyType = TypeImplementer.GetImplementation (declType);
BusObject inst = (BusObject)Activator.CreateInstance (proxyType);
inst.conn = conn;
inst.bus_name = bus_name;
inst.object_path = object_path;
return inst;
}
public Delegate GetHookupDelegate (EventInfo ei)
{
DynamicMethod hookupMethod = TypeImplementer.GetHookupMethod (ei);
Delegate d = hookupMethod.CreateDelegate (ei.EventHandlerType, this);
return d;
}
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/Connection.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Reflection;
namespace NDesk.DBus
{
using Authentication;
using Transports;
public partial class Connection
{
//TODO: reconsider this field
Stream ns = null;
Transport transport;
internal Transport Transport {
get {
return transport;
} set {
transport = value;
}
}
protected Connection () {}
internal Connection (Transport transport)
{
this.transport = transport;
transport.Connection = this;
//TODO: clean this bit up
ns = transport.Stream;
}
//should this be public?
internal Connection (string address)
{
OpenPrivate (address);
Authenticate ();
}
/*
bool isConnected = false;
public bool IsConnected
{
get {
return isConnected;
}
}
*/
//should we do connection sharing here?
public static Connection Open (string address)
{
Connection conn = new Connection ();
conn.OpenPrivate (address);
conn.Authenticate ();
return conn;
}
internal void OpenPrivate (string address)
{
if (address == null)
throw new ArgumentNullException ("address");
AddressEntry[] entries = Address.Parse (address);
if (entries.Length == 0)
throw new Exception ("No addresses were found");
//TODO: try alternative addresses if needed
AddressEntry entry = entries[0];
transport = Transport.Create (entry);
//TODO: clean this bit up
ns = transport.Stream;
}
void Authenticate ()
{
if (transport != null)
transport.WriteCred ();
SaslClient auth = new SaslClient (this);
auth.Run ();
isAuthenticated = true;
}
bool isAuthenticated = false;
internal bool IsAuthenticated
{
get {
return isAuthenticated;
}
}
//Interlocked.Increment() handles the overflow condition for uint correctly, so it's ok to store the value as an int but cast it to uint
int serial = 0;
uint GenerateSerial ()
{
//return ++serial;
return (uint)Interlocked.Increment (ref serial);
}
internal Message SendWithReplyAndBlock (Message msg)
{
PendingCall pending = SendWithReply (msg);
return pending.Reply;
}
internal PendingCall SendWithReply (Message msg)
{
msg.ReplyExpected = true;
msg.Header.Serial = GenerateSerial ();
//TODO: throttle the maximum number of concurrent PendingCalls
PendingCall pending = new PendingCall (this);
pendingCalls[msg.Header.Serial] = pending;
WriteMessage (msg);
return pending;
}
internal uint Send (Message msg)
{
msg.Header.Serial = GenerateSerial ();
WriteMessage (msg);
//Outbound.Enqueue (msg);
//temporary
//Flush ();
return msg.Header.Serial;
}
object writeLock = new object ();
internal void WriteMessage (Message msg)
{
byte[] HeaderData = msg.GetHeaderData ();
long msgLength = HeaderData.Length + (msg.Body != null ? msg.Body.Length : 0);
if (msgLength > Protocol.MaxMessageLength)
throw new Exception ("Message length " + msgLength + " exceeds maximum allowed " + Protocol.MaxMessageLength + " bytes");
lock (writeLock) {
ns.Write (HeaderData, 0, HeaderData.Length);
if (msg.Body != null && msg.Body.Length != 0)
ns.Write (msg.Body, 0, msg.Body.Length);
}
}
Queue<Message> Inbound = new Queue<Message> ();
/*
Queue<Message> Outbound = new Queue<Message> ();
public void Flush ()
{
//should just iterate the enumerator here
while (Outbound.Count != 0) {
Message msg = Outbound.Dequeue ();
WriteMessage (msg);
}
}
public bool ReadWrite (int timeout_milliseconds)
{
//TODO
return true;
}
public bool ReadWrite ()
{
return ReadWrite (-1);
}
public bool Dispatch ()
{
//TODO
Message msg = Inbound.Dequeue ();
//HandleMessage (msg);
return true;
}
public bool ReadWriteDispatch (int timeout_milliseconds)
{
//TODO
return Dispatch ();
}
public bool ReadWriteDispatch ()
{
return ReadWriteDispatch (-1);
}
*/
internal Message ReadMessage ()
{
byte[] header;
byte[] body = null;
int read;
//16 bytes is the size of the fixed part of the header
byte[] hbuf = new byte[16];
read = ns.Read (hbuf, 0, 16);
if (read == 0)
return null;
if (read != 16)
throw new Exception ("Header read length mismatch: " + read + " of expected " + "16");
EndianFlag endianness = (EndianFlag)hbuf[0];
MessageReader reader = new MessageReader (endianness, hbuf);
//discard the endian byte as we've already read it
reader.ReadByte ();
//discard message type and flags, which we don't care about here
reader.ReadByte ();
reader.ReadByte ();
byte version = reader.ReadByte ();
if (version < Protocol.MinVersion || version > Protocol.MaxVersion)
throw new NotSupportedException ("Protocol version '" + version.ToString () + "' is not supported");
if (Protocol.Verbose)
if (version != Protocol.Version)
Console.Error.WriteLine ("Warning: Protocol version '" + version.ToString () + "' is not explicitly supported but may be compatible");
uint bodyLength = reader.ReadUInt32 ();
//discard serial
reader.ReadUInt32 ();
uint headerLength = reader.ReadUInt32 ();
//this check may become relevant if a future version of the protocol allows larger messages
/*
if (bodyLength > Int32.MaxValue || headerLength > Int32.MaxValue)
throw new NotImplementedException ("Long messages are not yet supported");
*/
int bodyLen = (int)bodyLength;
int toRead = (int)headerLength;
//we fixup to include the padding following the header
toRead = Protocol.Padded (toRead, 8);
long msgLength = toRead + bodyLen;
if (msgLength > Protocol.MaxMessageLength)
throw new Exception ("Message length " + msgLength + " exceeds maximum allowed " + Protocol.MaxMessageLength + " bytes");
header = new byte[16 + toRead];
Array.Copy (hbuf, header, 16);
read = ns.Read (header, 16, toRead);
if (read != toRead)
throw new Exception ("Message header length mismatch: " + read + " of expected " + toRead);
//read the body
if (bodyLen != 0) {
body = new byte[bodyLen];
read = ns.Read (body, 0, bodyLen);
if (read != bodyLen)
throw new Exception ("Message body length mismatch: " + read + " of expected " + bodyLen);
}
Message msg = new Message ();
msg.Connection = this;
msg.Body = body;
msg.SetHeaderData (header);
return msg;
}
//temporary hack
internal void DispatchSignals ()
{
lock (Inbound) {
while (Inbound.Count != 0) {
Message msg = Inbound.Dequeue ();
HandleSignal (msg);
}
}
}
internal Thread mainThread = Thread.CurrentThread;
//temporary hack
public void Iterate ()
{
mainThread = Thread.CurrentThread;
//Message msg = Inbound.Dequeue ();
Message msg = ReadMessage ();
HandleMessage (msg);
DispatchSignals ();
}
internal void HandleMessage (Message msg)
{
//TODO: support disconnection situations properly and move this check elsewhere
if (msg == null)
throw new ArgumentNullException ("msg", "Cannot handle a null message; maybe the bus was disconnected");
{
object field_value;
if (msg.Header.Fields.TryGetValue (FieldCode.ReplySerial, out field_value)) {
uint reply_serial = (uint)field_value;
PendingCall pending;
if (pendingCalls.TryGetValue (reply_serial, out pending)) {
if (pendingCalls.Remove (reply_serial))
pending.Reply = msg;
return;
}
//we discard reply messages with no corresponding PendingCall
if (Protocol.Verbose)
Console.Error.WriteLine ("Unexpected reply message received: MessageType='" + msg.Header.MessageType + "', ReplySerial=" + reply_serial);
return;
}
}
switch (msg.Header.MessageType) {
case MessageType.MethodCall:
MethodCall method_call = new MethodCall (msg);
HandleMethodCall (method_call);
break;
case MessageType.Signal:
//HandleSignal (msg);
lock (Inbound)
Inbound.Enqueue (msg);
break;
case MessageType.Error:
//TODO: better exception handling
Error error = new Error (msg);
string errMsg = String.Empty;
if (msg.Signature.Value.StartsWith ("s")) {
MessageReader reader = new MessageReader (msg);
errMsg = reader.ReadString ();
}
//throw new Exception ("Remote Error: Signature='" + msg.Signature.Value + "' " + error.ErrorName + ": " + errMsg);
//if (Protocol.Verbose)
Console.Error.WriteLine ("Remote Error: Signature='" + msg.Signature.Value + "' " + error.ErrorName + ": " + errMsg);
break;
case MessageType.Invalid:
default:
throw new Exception ("Invalid message received: MessageType='" + msg.Header.MessageType + "'");
}
}
Dictionary<uint,PendingCall> pendingCalls = new Dictionary<uint,PendingCall> ();
//this might need reworking with MulticastDelegate
internal void HandleSignal (Message msg)
{
Signal signal = new Signal (msg);
//TODO: this is a hack, not necessary when MatchRule is complete
MatchRule rule = new MatchRule ();
rule.MessageType = MessageType.Signal;
rule.Interface = signal.Interface;
rule.Member = signal.Member;
rule.Path = signal.Path;
Delegate dlg;
if (Handlers.TryGetValue (rule, out dlg)) {
//dlg.DynamicInvoke (GetDynamicValues (msg));
MethodInfo mi = dlg.Method;
//signals have no return value
dlg.DynamicInvoke (MessageHelper.GetDynamicValues (msg, mi.GetParameters ()));
} else {
//TODO: how should we handle this condition? sending an Error may not be appropriate in this case
if (Protocol.Verbose)
Console.Error.WriteLine ("Warning: No signal handler for " + signal.Member);
}
}
internal Dictionary<MatchRule,Delegate> Handlers = new Dictionary<MatchRule,Delegate> ();
//very messy
internal void MaybeSendUnknownMethodError (MethodCall method_call)
{
Message msg = MessageHelper.CreateUnknownMethodError (method_call);
if (msg != null)
Send (msg);
}
//not particularly efficient and needs to be generalized
internal void HandleMethodCall (MethodCall method_call)
{
//TODO: Ping and Introspect need to be abstracted and moved somewhere more appropriate once message filter infrastructure is complete
//FIXME: these special cases are slightly broken for the case where the member but not the interface is specified in the message
if (method_call.Interface == "org.freedesktop.DBus.Peer" && method_call.Member == "Ping") {
Message reply = MessageHelper.ConstructReply (method_call);
Send (reply);
return;
}
if (method_call.Interface == "org.freedesktop.DBus.Introspectable" && method_call.Member == "Introspect") {
Introspector intro = new Introspector ();
intro.root_path = method_call.Path;
intro.WriteStart ();
//FIXME: do this properly
//this is messy and inefficient
List<string> linkNodes = new List<string> ();
int depth = method_call.Path.Decomposed.Length;
foreach (ObjectPath pth in RegisteredObjects.Keys) {
if (pth.Value == (method_call.Path.Value)) {
ExportObject exo = (ExportObject)RegisteredObjects[pth];
intro.WriteType (exo.obj.GetType ());
} else {
for (ObjectPath cur = pth ; cur != null ; cur = cur.Parent) {
if (cur.Value == method_call.Path.Value) {
string linkNode = pth.Decomposed[depth];
if (!linkNodes.Contains (linkNode)) {
intro.WriteNode (linkNode);
linkNodes.Add (linkNode);
}
}
}
}
}
intro.WriteEnd ();
Message reply = MessageHelper.ConstructReply (method_call, intro.xml);
Send (reply);
return;
}
BusObject bo;
if (RegisteredObjects.TryGetValue (method_call.Path, out bo)) {
ExportObject eo = (ExportObject)bo;
eo.HandleMethodCall (method_call);
} else {
MaybeSendUnknownMethodError (method_call);
}
}
Dictionary<ObjectPath,BusObject> RegisteredObjects = new Dictionary<ObjectPath,BusObject> ();
//FIXME: this shouldn't be part of the core API
//that also applies to much of the other object mapping code
public object GetObject (Type type, string bus_name, ObjectPath path)
{
//if (type == null)
// return GetObject (bus_name, path);
//if the requested type is an interface, we can implement it efficiently
//otherwise we fall back to using a transparent proxy
if (type.IsInterface) {
return BusObject.GetObject (this, bus_name, path, type);
} else {
if (Protocol.Verbose)
Console.Error.WriteLine ("Warning: Note that MarshalByRefObject use is not recommended; for best performance, define interfaces");
BusObject busObject = new BusObject (this, bus_name, path);
DProxy prox = new DProxy (busObject, type);
return prox.GetTransparentProxy ();
}
}
public T GetObject<T> (string bus_name, ObjectPath path)
{
return (T)GetObject (typeof (T), bus_name, path);
}
[Obsolete ("Use the overload of Register() which does not take a bus_name parameter")]
public void Register (string bus_name, ObjectPath path, object obj)
{
Register (path, obj);
}
[Obsolete ("Use the overload of Unregister() which does not take a bus_name parameter")]
public object Unregister (string bus_name, ObjectPath path)
{
return Unregister (path);
}
public void Register (ObjectPath path, object obj)
{
ExportObject eo = new ExportObject (this, path, obj);
eo.Registered = true;
//TODO: implement some kind of tree data structure or internal object hierarchy. right now we are ignoring the name and putting all object paths in one namespace, which is bad
RegisteredObjects[path] = eo;
}
public object Unregister (ObjectPath path)
{
BusObject bo;
if (!RegisteredObjects.TryGetValue (path, out bo))
throw new Exception ("Cannot unregister " + path + " as it isn't registered");
RegisteredObjects.Remove (path);
ExportObject eo = (ExportObject)bo;
eo.Registered = false;
return eo.obj;
}
//these look out of place, but are useful
internal protected virtual void AddMatch (string rule)
{
}
internal protected virtual void RemoveMatch (string rule)
{
}
static Connection ()
{
if (BitConverter.IsLittleEndian)
NativeEndianness = EndianFlag.Little;
else
NativeEndianness = EndianFlag.Big;
}
internal static readonly EndianFlag NativeEndianness;
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/DBus.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using NDesk.DBus;
namespace org.freedesktop.DBus
{
[Flags]
public enum NameFlag : uint
{
None = 0,
AllowReplacement = 0x1,
ReplaceExisting = 0x2,
DoNotQueue = 0x4,
}
public enum RequestNameReply : uint
{
PrimaryOwner = 1,
InQueue,
Exists,
AlreadyOwner,
}
public enum ReleaseNameReply : uint
{
Released = 1,
NonExistent,
NotOwner,
}
public enum StartReply : uint
{
//The service was successfully started.
Success = 1,
//A connection already owns the given name.
AlreadyRunning,
}
public delegate void NameOwnerChangedHandler (string name, string old_owner, string new_owner);
public delegate void NameAcquiredHandler (string name);
public delegate void NameLostHandler (string name);
[Interface ("org.freedesktop.DBus.Peer")]
public interface Peer
{
void Ping ();
[return: Argument ("machine_uuid")]
string GetMachineId ();
}
[Interface ("org.freedesktop.DBus.Introspectable")]
public interface Introspectable
{
[return: Argument ("data")]
string Introspect ();
}
[Interface ("org.freedesktop.DBus.Properties")]
public interface Properties
{
[return: Argument ("value")]
object Get (string @interface, string propname);
void Set (string @interface, string propname, object value);
[return: Argument ("props")]
IDictionary<string,object> GetAll(string @interface);
}
[Interface ("org.freedesktop.DBus")]
public interface IBus : Introspectable
{
RequestNameReply RequestName (string name, NameFlag flags);
ReleaseNameReply ReleaseName (string name);
string Hello ();
string[] ListNames ();
string[] ListActivatableNames ();
bool NameHasOwner (string name);
event NameOwnerChangedHandler NameOwnerChanged;
event NameLostHandler NameLost;
event NameAcquiredHandler NameAcquired;
StartReply StartServiceByName (string name, uint flags);
string GetNameOwner (string name);
uint GetConnectionUnixUser (string connection_name);
void AddMatch (string rule);
void RemoveMatch (string rule);
//undocumented in spec
string[] ListQueuedOwners (string name);
uint GetConnectionUnixProcessID (string connection_name);
byte[] GetConnectionSELinuxSecurityContext (string connection_name);
void ReloadConfig ();
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/DProxy.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Reflection;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Messaging;
namespace NDesk.DBus
{
//marked internal because this is really an implementation detail and needs to be replaced
internal class DProxy : RealProxy
{
protected BusObject busObject;
public DProxy (BusObject busObject, Type type) : base(type)
{
this.busObject = busObject;
}
static MethodInfo mi_GetHashCode = typeof (object).GetMethod ("GetHashCode");
static MethodInfo mi_Equals = typeof (object).GetMethod ("Equals", BindingFlags.Instance);
static MethodInfo mi_ToString = typeof (object).GetMethod ("ToString");
static MethodInfo mi_GetLifetimeService = typeof (MarshalByRefObject).GetMethod ("GetLifetimeService");
object GetDefaultReturn (MethodBase mi, object[] inArgs)
{
if (mi == mi_GetHashCode)
return busObject.Path.Value.GetHashCode ();
if (mi == mi_Equals)
return busObject.Path.Value == ((BusObject)((MarshalByRefObject)inArgs[0]).GetLifetimeService ()).Path.Value;
if (mi == mi_ToString)
return busObject.Path.Value;
if (mi == mi_GetLifetimeService)
return busObject;
return null;
}
public override IMessage Invoke (IMessage message)
{
IMethodCallMessage callMessage = (IMethodCallMessage) message;
object defaultRetVal = GetDefaultReturn (callMessage.MethodBase, callMessage.InArgs);
if (defaultRetVal != null) {
MethodReturnMessageWrapper defaultReturnMessage = new MethodReturnMessageWrapper ((IMethodReturnMessage) message);
defaultReturnMessage.ReturnValue = defaultRetVal;
return defaultReturnMessage;
}
object[] outArgs;
object retVal;
Exception exception;
busObject.Invoke (callMessage.MethodBase, callMessage.MethodName, callMessage.InArgs, out outArgs, out retVal, out exception);
MethodReturnMessageWrapper returnMessage = new MethodReturnMessageWrapper ((IMethodReturnMessage) message);
returnMessage.Exception = exception;
returnMessage.ReturnValue = retVal;
return returnMessage;
}
/*
public override ObjRef CreateObjRef (Type ServerType)
{
throw new System.NotImplementedException ();
}
*/
~DProxy ()
{
//FIXME: remove handlers/match rules here
if (Protocol.Verbose)
Console.Error.WriteLine ("Warning: Finalization of " + busObject.Path + " not yet supported");
}
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/ExportObject.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Reflection;
using System.Reflection.Emit;
using org.freedesktop.DBus;
namespace NDesk.DBus
{
//TODO: perhaps ExportObject should not derive from BusObject
internal class ExportObject : BusObject //, Peer
{
public readonly object obj;
public ExportObject (Connection conn, ObjectPath object_path, object obj) : base (conn, null, object_path)
{
this.obj = obj;
}
//maybe add checks to make sure this is not called more than once
//it's a bit silly as a property
public bool Registered
{
set {
Type type = obj.GetType ();
foreach (MemberInfo mi in Mapper.GetPublicMembers (type)) {
EventInfo ei = mi as EventInfo;
if (ei == null)
continue;
Delegate dlg = GetHookupDelegate (ei);
if (value)
ei.AddEventHandler (obj, dlg);
else
ei.RemoveEventHandler (obj, dlg);
}
}
}
public void HandleMethodCall (MethodCall method_call)
{
Type type = obj.GetType ();
//object retObj = type.InvokeMember (msg.Member, BindingFlags.InvokeMethod, null, obj, MessageHelper.GetDynamicValues (msg));
//TODO: there is no member name mapping for properties etc. yet
MethodInfo mi = Mapper.GetMethod (type, method_call);
if (mi == null) {
conn.MaybeSendUnknownMethodError (method_call);
return;
}
object retObj = null;
object[] parmValues = MessageHelper.GetDynamicValues (method_call.message, mi.GetParameters ());
try {
retObj = mi.Invoke (obj, parmValues);
} catch (TargetInvocationException e) {
if (!method_call.message.ReplyExpected)
return;
Exception ie = e.InnerException;
//TODO: complete exception sending support
Error error = new Error (Mapper.GetInterfaceName (ie.GetType ()), method_call.message.Header.Serial);
error.message.Signature = new Signature (DType.String);
MessageWriter writer = new MessageWriter (Connection.NativeEndianness);
writer.connection = conn;
writer.Write (ie.Message);
error.message.Body = writer.ToArray ();
//TODO: we should be more strict here, but this fallback was added as a quick fix for p2p
if (method_call.Sender != null)
error.message.Header.Fields[FieldCode.Destination] = method_call.Sender;
conn.Send (error.message);
return;
}
if (method_call.message.ReplyExpected) {
Message reply = MessageHelper.ConstructDynamicReply (method_call, mi, retObj, parmValues);
conn.Send (reply);
}
}
/*
public void Ping ()
{
}
public string GetMachineId ()
{
//TODO: implement this
return String.Empty;
}
*/
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/Introspection.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Text;
using System.Reflection;
namespace NDesk.DBus
{
//TODO: complete this class
class Introspector
{
const string NAMESPACE = "http://www.freedesktop.org/standards/dbus";
const string PUBLIC_IDENTIFIER = "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN";
const string SYSTEM_IDENTIFIER = "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd";
public StringBuilder sb;
public string xml;
public ObjectPath root_path = ObjectPath.Root;
protected XmlWriter writer;
public Introspector ()
{
XmlWriterSettings settings = new XmlWriterSettings ();
settings.Indent = true;
settings.IndentChars = (" ");
settings.OmitXmlDeclaration = true;
sb = new StringBuilder ();
writer = XmlWriter.Create (sb, settings);
}
static string GetProductDescription ()
{
String version;
Assembly assembly = Assembly.GetExecutingAssembly ();
AssemblyName aname = assembly.GetName ();
AssemblyInformationalVersionAttribute iversion = Attribute.GetCustomAttribute (assembly, typeof (AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute;
if (iversion != null)
version = iversion.InformationalVersion;
else
version = aname.Version.ToString ();
return aname.Name + " " + version;
}
public void WriteStart ()
{
writer.WriteDocType ("node", PUBLIC_IDENTIFIER, SYSTEM_IDENTIFIER, null);
writer.WriteComment (" " + GetProductDescription () + " ");
//the root node element
writer.WriteStartElement ("node");
}
public void WriteNode (string name)
{
writer.WriteStartElement ("node");
writer.WriteAttributeString ("name", name);
writer.WriteEndElement ();
}
public void WriteEnd ()
{
/*
WriteEnum (typeof (org.freedesktop.DBus.NameFlag));
WriteEnum (typeof (org.freedesktop.DBus.NameReply));
WriteEnum (typeof (org.freedesktop.DBus.ReleaseNameReply));
WriteEnum (typeof (org.freedesktop.DBus.StartReply));
WriteInterface (typeof (org.freedesktop.DBus.IBus));
*/
writer.WriteEndElement ();
writer.Flush ();
xml = sb.ToString ();
}
//public void WriteNode ()
public void WriteType (Type target_type)
{
//writer.WriteStartElement ("node");
//TODO: non-well-known introspection has paths as well, which we don't do yet. read the spec again
//hackishly just remove the root '/' to make the path relative for now
//writer.WriteAttributeString ("name", target_path.Value.Substring (1));
//writer.WriteAttributeString ("name", "test");
//reflect our own interface manually
WriteInterface (typeof (org.freedesktop.DBus.Introspectable));
//reflect the target interface
if (target_type != null) {
WriteInterface (target_type);
foreach (Type ifType in target_type.GetInterfaces ())
WriteInterface (ifType);
}
//TODO: review recursion of interfaces and inheritance hierarchy
//writer.WriteEndElement ();
}
public void WriteArg (ParameterInfo pi)
{
WriteArg (pi.ParameterType, Mapper.GetArgumentName (pi), pi.IsOut, false);
}
public void WriteArgReverse (ParameterInfo pi)
{
WriteArg (pi.ParameterType, Mapper.GetArgumentName (pi), pi.IsOut, true);
}
//TODO: clean up and get rid of reverse (or argIsOut) parm
public void WriteArg (Type argType, string argName, bool argIsOut, bool reverse)
{
argType = argIsOut ? argType.GetElementType () : argType;
if (argType == typeof (void))
return;
writer.WriteStartElement ("arg");
if (!String.IsNullOrEmpty (argName))
writer.WriteAttributeString ("name", argName);
//we can't rely on the default direction (qt-dbus requires a direction at time of writing), so we use a boolean to reverse the parameter direction and make it explicit
if (argIsOut)
writer.WriteAttributeString ("direction", !reverse ? "out" : "in");
else
writer.WriteAttributeString ("direction", !reverse ? "in" : "out");
Signature sig = Signature.GetSig (argType);
//TODO: avoid writing null (DType.Invalid) to the XML stream
writer.WriteAttributeString ("type", sig.Value);
//annotations aren't valid in an arg element, so this is disabled
//if (argType.IsEnum)
// WriteAnnotation ("org.ndesk.DBus.Enum", Mapper.GetInterfaceName (argType));
writer.WriteEndElement ();
}
public void WriteMethod (MethodInfo mi)
{
writer.WriteStartElement ("method");
writer.WriteAttributeString ("name", mi.Name);
foreach (ParameterInfo pi in mi.GetParameters ())
WriteArg (pi);
//Mono <= 1.1.13 doesn't support MethodInfo.ReturnParameter, so avoid it
//WriteArgReverse (mi.ReturnParameter);
WriteArg (mi.ReturnType, Mapper.GetArgumentName (mi.ReturnTypeCustomAttributes, "ret"), false, true);
WriteAnnotations (mi);
writer.WriteEndElement ();
}
public void WriteProperty (PropertyInfo pri)
{
//expose properties as dbus properties
writer.WriteStartElement ("property");
writer.WriteAttributeString ("name", pri.Name);
writer.WriteAttributeString ("type", Signature.GetSig (pri.PropertyType).Value);
string access = (pri.CanRead ? "read" : String.Empty) + (pri.CanWrite ? "write" : String.Empty);
writer.WriteAttributeString ("access", access);
WriteAnnotations (pri);
writer.WriteEndElement ();
//expose properties as methods also
//it may not be worth doing this in the long run
/*
if (pri.CanRead) {
writer.WriteStartElement ("method");
writer.WriteAttributeString ("name", "Get" + pri.Name);
WriteArgReverse (pri.GetGetMethod ().ReturnParameter);
writer.WriteEndElement ();
}
if (pri.CanWrite) {
writer.WriteStartElement ("method");
writer.WriteAttributeString ("name", "Set" + pri.Name);
foreach (ParameterInfo pi in pri.GetSetMethod ().GetParameters ())
WriteArg (pi);
writer.WriteEndElement ();
}
*/
}
public void WriteSignal (EventInfo ei)
{
writer.WriteStartElement ("signal");
writer.WriteAttributeString ("name", ei.Name);
foreach (ParameterInfo pi in ei.EventHandlerType.GetMethod ("Invoke").GetParameters ())
WriteArgReverse (pi);
WriteAnnotations (ei);
//no need to consider the delegate return value as dbus doesn't support it
writer.WriteEndElement ();
}
const BindingFlags relevantBindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;
public void WriteInterface (Type type)
{
if (type == null)
return;
//TODO: this is unreliable, fix it
if (!Mapper.IsPublic (type))
return;
writer.WriteStartElement ("interface");
writer.WriteAttributeString ("name", Mapper.GetInterfaceName (type));
/*
foreach (MemberInfo mbi in type.GetMembers (relevantBindingFlags)) {
switch (mbi.MemberType) {
case MemberTypes.Method:
if (!((MethodInfo)mbi).IsSpecialName)
WriteMethod ((MethodInfo)mbi);
break;
case MemberTypes.Event:
WriteSignal ((EventInfo)mbi);
break;
case MemberTypes.Property:
WriteProperty ((PropertyInfo)mbi);
break;
default:
Console.Error.WriteLine ("Warning: Unhandled MemberType '{0}' encountered while introspecting {1}", mbi.MemberType, type.FullName);
break;
}
}
*/
foreach (MethodInfo mi in type.GetMethods (relevantBindingFlags))
if (!mi.IsSpecialName)
WriteMethod (mi);
foreach (EventInfo ei in type.GetEvents (relevantBindingFlags))
WriteSignal (ei);
foreach (PropertyInfo pri in type.GetProperties (relevantBindingFlags))
WriteProperty (pri);
//TODO: indexers
//TODO: attributes as annotations?
writer.WriteEndElement ();
//this recursion seems somewhat inelegant
WriteInterface (type.BaseType);
}
public void WriteAnnotations (ICustomAttributeProvider attrProvider)
{
if (Mapper.IsDeprecated (attrProvider))
WriteAnnotation ("org.freedesktop.DBus.Deprecated", "true");
}
public void WriteAnnotation (string name, string value)
{
writer.WriteStartElement ("annotation");
writer.WriteAttributeString ("name", name);
writer.WriteAttributeString ("value", value);
writer.WriteEndElement ();
}
//this is not in the spec, and is not finalized
public void WriteEnum (Type type)
{
writer.WriteStartElement ("enum");
writer.WriteAttributeString ("name", Mapper.GetInterfaceName (type));
writer.WriteAttributeString ("type", Signature.GetSig (type.GetElementType ()).Value);
writer.WriteAttributeString ("flags", (type.IsDefined (typeof (FlagsAttribute), false)) ? "true" : "false");
string[] names = Enum.GetNames (type);
int i = 0;
foreach (Enum val in Enum.GetValues (type)) {
writer.WriteStartElement ("element");
writer.WriteAttributeString ("name", names[i++]);
writer.WriteAttributeString ("value", val.ToString ("d"));
writer.WriteEndElement ();
}
writer.WriteEndElement ();
}
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/Mapper.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using System.Reflection;
namespace NDesk.DBus
{
static class Mapper
{
//TODO: move these Get*Name helpers somewhere more appropriate
public static string GetArgumentName (ParameterInfo pi)
{
string argName = pi.Name;
if (pi.IsRetval && String.IsNullOrEmpty (argName))
argName = "ret";
return GetArgumentName ((ICustomAttributeProvider)pi, argName);
}
public static string GetArgumentName (ICustomAttributeProvider attrProvider, string defaultName)
{
string argName = defaultName;
//TODO: no need for foreach
foreach (ArgumentAttribute aa in attrProvider.GetCustomAttributes (typeof (ArgumentAttribute), true))
argName = aa.Name;
return argName;
}
//TODO: these two methods are quite messy and need review
public static IEnumerable<MemberInfo> GetPublicMembers (Type type)
{
//note that Type.GetInterfaces() returns all interfaces with flattened hierarchy
foreach (Type ifType in type.GetInterfaces ())
foreach (MemberInfo mi in GetDeclaredPublicMembers (ifType))
yield return mi;
if (IsPublic (type))
foreach (MemberInfo mi in GetDeclaredPublicMembers (type))
yield return mi;
}
static IEnumerable<MemberInfo> GetDeclaredPublicMembers (Type type)
{
if (IsPublic (type))
foreach (MemberInfo mi in type.GetMembers (BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
yield return mi;
}
//this method walks the interface tree in an undefined manner and returns the first match, or if no matches are found, null
//the logic needs review and cleanup
//TODO: unify member name mapping as is already done with interfaces and args
public static MethodInfo GetMethod (Type type, MethodCall method_call)
{
foreach (MemberInfo member in Mapper.GetPublicMembers (type)) {
//this could be made more efficient by using the given interface name earlier and avoiding walking through all public interfaces
if (method_call.Interface != null)
if (GetInterfaceName (member) != method_call.Interface)
continue;
MethodInfo meth = null;
Type[] inTypes = null;
if (member is PropertyInfo) {
PropertyInfo prop = member as PropertyInfo;
MethodInfo getter = prop.GetGetMethod (false);
MethodInfo setter = prop.GetSetMethod (false);
if (getter != null && "Get" + prop.Name == method_call.Member) {
meth = getter;
inTypes = Type.EmptyTypes;
} else if (setter != null && "Set" + prop.Name == method_call.Member) {
meth = setter;
inTypes = new Type[] {prop.PropertyType};
}
} else {
meth = member as MethodInfo;
if (meth == null)
continue;
if (meth.Name != method_call.Member)
continue;
inTypes = Mapper.GetTypes (ArgDirection.In, meth.GetParameters ());
}
if (meth == null || inTypes == null)
continue;
Signature inSig = Signature.GetSig (inTypes);
if (inSig != method_call.Signature)
continue;
return meth;
}
return null;
}
public static bool IsPublic (MemberInfo mi)
{
return IsPublic (mi.DeclaringType);
}
public static bool IsPublic (Type type)
{
//we need to have a proper look at what's really public at some point
//this will do for now
if (type.IsDefined (typeof (InterfaceAttribute), false))
return true;
if (type.IsSubclassOf (typeof (MarshalByRefObject)))
return true;
return false;
}
public static string GetInterfaceName (MemberInfo mi)
{
return GetInterfaceName (mi.DeclaringType);
}
public static string GetInterfaceName (Type type)
{
string interfaceName = type.FullName;
//TODO: better fallbacks and namespace mangling when no InterfaceAttribute is available
//TODO: no need for foreach
foreach (InterfaceAttribute ia in type.GetCustomAttributes (typeof (InterfaceAttribute), true))
interfaceName = ia.Name;
return interfaceName;
}
public static Type[] GetTypes (ArgDirection dir, ParameterInfo[] parms)
{
List<Type> types = new List<Type> ();
//TODO: consider InOut/Ref
for (int i = 0 ; i != parms.Length ; i++) {
switch (dir) {
case ArgDirection.In:
//docs say IsIn isn't reliable, and this is indeed true
//if (parms[i].IsIn)
if (!parms[i].IsOut)
types.Add (parms[i].ParameterType);
break;
case ArgDirection.Out:
if (parms[i].IsOut) {
//TODO: note that IsOut is optional to the compiler, we may want to use IsByRef instead
//eg: if (parms[i].ParameterType.IsByRef)
types.Add (parms[i].ParameterType.GetElementType ());
}
break;
}
}
return types.ToArray ();
}
public static bool IsDeprecated (ICustomAttributeProvider attrProvider)
{
return attrProvider.IsDefined (typeof (ObsoleteAttribute), true);
}
static bool AreEqual (Type[] a, Type[] b)
{
if (a.Length != b.Length)
return false;
for (int i = 0 ; i != a.Length ; i++)
if (a[i] != b[i])
return false;
return true;
}
//workaround for Mono bug #81035 (memory leak)
static List<Type> genTypes = new List<Type> ();
internal static Type GetGenericType (Type defType, Type[] parms)
{
foreach (Type genType in genTypes) {
if (genType.GetGenericTypeDefinition () != defType)
continue;
Type[] genParms = genType.GetGenericArguments ();
if (!AreEqual (genParms, parms))
continue;
return genType;
}
Type type = defType.MakeGenericType (parms);
genTypes.Add (type);
return type;
}
}
//TODO: this class is messy, move the methods somewhere more appropriate
static class MessageHelper
{
public static Message CreateUnknownMethodError (MethodCall method_call)
{
if (!method_call.message.ReplyExpected)
return null;
string errMsg = String.Format ("Method \"{0}\" with signature \"{1}\" on interface \"{2}\" doesn't exist", method_call.Member, method_call.Signature.Value, method_call.Interface);
Error error = new Error ("org.freedesktop.DBus.Error.UnknownMethod", method_call.message.Header.Serial);
error.message.Signature = new Signature (DType.String);
MessageWriter writer = new MessageWriter (Connection.NativeEndianness);
writer.Write (errMsg);
error.message.Body = writer.ToArray ();
//TODO: we should be more strict here, but this fallback was added as a quick fix for p2p
if (method_call.Sender != null)
error.message.Header.Fields[FieldCode.Destination] = method_call.Sender;
return error.message;
}
public static void WriteDynamicValues (MessageWriter mw, ParameterInfo[] parms, object[] vals)
{
foreach (ParameterInfo parm in parms) {
if (!parm.IsOut)
continue;
Type actualType = parm.ParameterType.GetElementType ();
mw.Write (actualType, vals[parm.Position]);
}
}
public static object[] GetDynamicValues (Message msg, ParameterInfo[] parms)
{
//TODO: this validation check should provide better information, eg. message dump or a stack trace, or at least the interface/member
/*
if (Protocol.Verbose) {
Signature expected = Signature.GetSig (types);
Signature actual = msg.Signature;
if (actual != expected)
Console.Error.WriteLine ("Warning: The signature of the message does not match that of the handler: " + "Expected '" + expected + "', got '" + actual + "'");
}
*/
object[] vals = new object[parms.Length];
if (msg.Body != null) {
MessageReader reader = new MessageReader (msg);
foreach (ParameterInfo parm in parms) {
if (parm.IsOut)
continue;
vals[parm.Position] = reader.ReadValue (parm.ParameterType);
}
}
return vals;
}
public static object[] GetDynamicValues (Message msg, Type[] types)
{
//TODO: this validation check should provide better information, eg. message dump or a stack trace, or at least the interface/member
if (Protocol.Verbose) {
Signature expected = Signature.GetSig (types);
Signature actual = msg.Signature;
if (actual != expected)
Console.Error.WriteLine ("Warning: The signature of the message does not match that of the handler: " + "Expected '" + expected + "', got '" + actual + "'");
}
object[] vals = new object[types.Length];
if (msg.Body != null) {
MessageReader reader = new MessageReader (msg);
for (int i = 0 ; i != types.Length ; i++)
vals[i] = reader.ReadValue (types[i]);
}
return vals;
}
public static Message ConstructReply (MethodCall method_call, params object[] vals)
{
MethodReturn method_return = new MethodReturn (method_call.message.Header.Serial);
Message replyMsg = method_return.message;
Signature inSig = Signature.GetSig (vals);
if (vals != null && vals.Length != 0) {
MessageWriter writer = new MessageWriter (Connection.NativeEndianness);
foreach (object arg in vals)
writer.Write (arg.GetType (), arg);
replyMsg.Body = writer.ToArray ();
}
//TODO: we should be more strict here, but this fallback was added as a quick fix for p2p
if (method_call.Sender != null)
replyMsg.Header.Fields[FieldCode.Destination] = method_call.Sender;
replyMsg.Signature = inSig;
//replyMsg.WriteHeader ();
return replyMsg;
}
public static Message ConstructDynamicReply (MethodCall method_call, MethodInfo mi, object retVal, object[] vals)
{
Type retType = mi.ReturnType;
MethodReturn method_return = new MethodReturn (method_call.message.Header.Serial);
Message replyMsg = method_return.message;
Signature outSig = Signature.GetSig (retType);
outSig += Signature.GetSig (Mapper.GetTypes (ArgDirection.Out, mi.GetParameters ()));
if (outSig != Signature.Empty) {
MessageWriter writer = new MessageWriter (Connection.NativeEndianness);
//first write the return value, if any
if (retType != null && retType != typeof (void))
writer.Write (retType, retVal);
//then write the out args
WriteDynamicValues (writer, mi.GetParameters (), vals);
replyMsg.Body = writer.ToArray ();
}
//TODO: we should be more strict here, but this fallback was added as a quick fix for p2p
if (method_call.Sender != null)
replyMsg.Header.Fields[FieldCode.Destination] = method_call.Sender;
replyMsg.Signature = outSig;
return replyMsg;
}
}
[AttributeUsage (AttributeTargets.Interface | AttributeTargets.Class, AllowMultiple=false, Inherited=true)]
public class InterfaceAttribute : Attribute
{
public string Name;
public InterfaceAttribute (string name)
{
this.Name = name;
}
}
[AttributeUsage (AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple=false, Inherited=true)]
public class ArgumentAttribute : Attribute
{
public string Name;
public ArgumentAttribute (string name)
{
this.Name = name;
}
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/MatchRule.cs | // Copyright 2007 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Text;
using System.Collections.Generic;
namespace NDesk.DBus
{
//delegate void MessageHandler (Message msg);
class MatchRule
{
public MessageType? MessageType;
public string Interface;
public string Member;
public ObjectPath Path;
public string Sender;
public string Destination;
public readonly SortedDictionary<int,string> Args = new SortedDictionary<int,string> ();
public MatchRule ()
{
}
void Append (StringBuilder sb, string key, string value)
{
if (sb.Length != 0)
sb.Append (",");
sb.Append (key + "='");
sb.Append (value);
sb.Append ("'");
}
void AppendArg (StringBuilder sb, int index, string value)
{
Append (sb, "arg" + index, value);
}
public override bool Equals (object o)
{
MatchRule r = o as MatchRule;
if (r == null)
return false;
if (r.MessageType != MessageType)
return false;
if (r.Interface != Interface)
return false;
if (r.Member != Member)
return false;
//TODO: see why path comparison doesn't work
if (r.Path.Value != Path.Value)
//if (r.Path != Path)
return false;
if (r.Sender != Sender)
return false;
if (r.Destination != Destination)
return false;
//FIXME: do args
return true;
}
public override int GetHashCode ()
{
//FIXME: not at all optimal
return ToString ().GetHashCode ();
}
public override string ToString ()
{
StringBuilder sb = new StringBuilder ();
if (MessageType != null)
Append (sb, "type", MessageFilter.MessageTypeToString ((MessageType)MessageType));
if (Interface != null)
Append (sb, "interface", Interface);
if (Member != null)
Append (sb, "member", Member);
if (Path != null)
//Append (sb, "path", Path.ToString ());
Append (sb, "path", Path.Value);
if (Sender != null)
Append (sb, "sender", Sender);
if (Destination != null)
Append (sb, "destination", Destination);
if (Args != null) {
foreach (KeyValuePair<int,string> pair in Args)
AppendArg (sb, pair.Key, pair.Value);
}
return sb.ToString ();
}
//this is useful as a Predicate<Message> delegate
public bool Matches (Message msg)
{
if (MessageType != null)
if (msg.Header.MessageType != MessageType)
return false;
object value;
if (Interface != null)
if (msg.Header.Fields.TryGetValue (FieldCode.Interface, out value))
if ((string)value != Interface)
return false;
if (Member != null)
if (msg.Header.Fields.TryGetValue (FieldCode.Member, out value))
if ((string)value != Member)
return false;
if (Path != null)
if (msg.Header.Fields.TryGetValue (FieldCode.Path, out value))
//if ((ObjectPath)value != Path)
if (((ObjectPath)value).Value != Path.Value)
return false;
if (Sender != null)
if (msg.Header.Fields.TryGetValue (FieldCode.Sender, out value))
if ((string)value != Sender)
return false;
if (Destination != null)
if (msg.Header.Fields.TryGetValue (FieldCode.Destination, out value))
if ((string)value != Destination)
return false;
//FIXME: do args
return true;
}
//this could be made more efficient
public static MatchRule Parse (string text)
{
MatchRule r = new MatchRule ();
foreach (string propStr in text.Split (',')) {
string[] parts = propStr.Split ('=');
if (parts.Length < 2)
throw new Exception ("No equals sign found");
if (parts.Length > 2)
throw new Exception ("Too many equals signs found");
string key = parts[0].Trim ();
string value = parts[1].Trim ();
if (!value.StartsWith ("'") || !value.EndsWith ("'"))
throw new Exception ("Too many equals signs found");
value = value.Substring (1, value.Length - 2);
if (key.StartsWith ("arg")) {
int argnum = Int32.Parse (key.Remove (0, "arg".Length));
if (argnum < 0 || argnum > 63)
throw new Exception ("arg match must be between 0 and 63 inclusive");
if (r.Args.ContainsKey (argnum))
return null;
r.Args[argnum] = value;
continue;
}
//TODO: more consistent error handling
switch (key) {
case "type":
if (r.MessageType != null)
return null;
r.MessageType = MessageFilter.StringToMessageType (value);
break;
case "interface":
if (r.Interface != null)
return null;
r.Interface = value;
break;
case "member":
if (r.Member != null)
return null;
r.Member = value;
break;
case "path":
if (r.Path != null)
return null;
r.Path = new ObjectPath (value);
break;
case "sender":
if (r.Sender != null)
return null;
r.Sender = value;
break;
case "destination":
if (r.Destination != null)
return null;
r.Destination = value;
break;
default:
if (Protocol.Verbose)
Console.Error.WriteLine ("Warning: Unrecognized match rule key: " + key);
break;
}
}
return r;
}
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/Message.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using System.IO;
namespace NDesk.DBus
{
class Message
{
public Message ()
{
Header.Endianness = Connection.NativeEndianness;
Header.MessageType = MessageType.MethodCall;
Header.Flags = HeaderFlag.NoReplyExpected; //TODO: is this the right place to do this?
Header.MajorVersion = Protocol.Version;
Header.Fields = new Dictionary<FieldCode,object> ();
}
public Header Header;
public Connection Connection;
public Signature Signature
{
get {
object o;
if (Header.Fields.TryGetValue (FieldCode.Signature, out o))
return (Signature)o;
else
return Signature.Empty;
} set {
if (value == Signature.Empty)
Header.Fields.Remove (FieldCode.Signature);
else
Header.Fields[FieldCode.Signature] = value;
}
}
public bool ReplyExpected
{
get {
return (Header.Flags & HeaderFlag.NoReplyExpected) == HeaderFlag.None;
} set {
if (value)
Header.Flags &= ~HeaderFlag.NoReplyExpected; //flag off
else
Header.Flags |= HeaderFlag.NoReplyExpected; //flag on
}
}
//public HeaderField[] HeaderFields;
//public Dictionary<FieldCode,object>;
public byte[] Body;
//TODO: make use of Locked
/*
protected bool locked = false;
public bool Locked
{
get {
return locked;
}
}
*/
public void SetHeaderData (byte[] data)
{
EndianFlag endianness = (EndianFlag)data[0];
MessageReader reader = new MessageReader (endianness, data);
Header = (Header)reader.ReadStruct (typeof (Header));
}
public byte[] GetHeaderData ()
{
if (Body != null)
Header.Length = (uint)Body.Length;
MessageWriter writer = new MessageWriter (Header.Endianness);
writer.WriteValueType (Header, typeof (Header));
writer.CloseWrite ();
return writer.ToArray ();
}
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/MessageFilter.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
namespace NDesk.DBus
{
class MessageFilter
{
//this should probably be made to use HeaderField or similar
//this class is not generalized yet
public static string MessageTypeToString (MessageType mtype)
{
switch (mtype)
{
case MessageType.MethodCall:
return "method_call";
case MessageType.MethodReturn:
return "method_return";
case MessageType.Error:
return "error";
case MessageType.Signal:
return "signal";
case MessageType.Invalid:
return "invalid";
default:
throw new Exception ("Bad MessageType: " + mtype);
}
}
public static MessageType StringToMessageType (string text)
{
switch (text)
{
case "method_call":
return MessageType.MethodCall;
case "method_return":
return MessageType.MethodReturn;
case "error":
return MessageType.Error;
case "signal":
return MessageType.Signal;
case "invalid":
return MessageType.Invalid;
default:
throw new Exception ("Bad MessageType: " + text);
}
}
//TODO: remove this -- left here for the benefit of the monitor tool for now
public static string CreateMatchRule (MessageType mtype)
{
return "type='" + MessageTypeToString (mtype) + "'";
}
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/MessageReader.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace NDesk.DBus
{
class MessageReader
{
protected EndianFlag endianness;
protected byte[] data;
//TODO: this should be uint or long to handle long messages
protected int pos = 0;
protected Message message;
public MessageReader (EndianFlag endianness, byte[] data)
{
if (data == null)
throw new ArgumentNullException ("data");
this.endianness = endianness;
this.data = data;
}
public MessageReader (Message message) : this (message.Header.Endianness, message.Body)
{
if (message == null)
throw new ArgumentNullException ("message");
this.message = message;
}
public object ReadValue (Type type)
{
if (type == typeof (void))
return null;
if (type.IsArray) {
return ReadArray (type.GetElementType ());
} else if (type == typeof (ObjectPath)) {
return ReadObjectPath ();
} else if (type == typeof (Signature)) {
return ReadSignature ();
} else if (type == typeof (object)) {
return ReadVariant ();
} else if (type == typeof (string)) {
return ReadString ();
} else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (IDictionary<,>)) {
Type[] genArgs = type.GetGenericArguments ();
//Type dictType = typeof (Dictionary<,>).MakeGenericType (genArgs);
//workaround for Mono bug #81035 (memory leak)
Type dictType = Mapper.GetGenericType (typeof (Dictionary<,>), genArgs);
System.Collections.IDictionary idict = (System.Collections.IDictionary)Activator.CreateInstance(dictType, new object[0]);
GetValueToDict (genArgs[0], genArgs[1], idict);
return idict;
} else if (Mapper.IsPublic (type)) {
return GetObject (type);
} else if (!type.IsPrimitive && !type.IsEnum) {
return ReadStruct (type);
} else {
object val;
DType dtype = Signature.TypeToDType (type);
val = ReadValue (dtype);
if (type.IsEnum)
val = Enum.ToObject (type, val);
return val;
}
}
//helper method, should not be used generally
public object ReadValue (DType dtype)
{
switch (dtype)
{
case DType.Byte:
return ReadByte ();
case DType.Boolean:
return ReadBoolean ();
case DType.Int16:
return ReadInt16 ();
case DType.UInt16:
return ReadUInt16 ();
case DType.Int32:
return ReadInt32 ();
case DType.UInt32:
return ReadUInt32 ();
case DType.Int64:
return ReadInt64 ();
case DType.UInt64:
return ReadUInt64 ();
#if !DISABLE_SINGLE
case DType.Single:
return ReadSingle ();
#endif
case DType.Double:
return ReadDouble ();
case DType.String:
return ReadString ();
case DType.ObjectPath:
return ReadObjectPath ();
case DType.Signature:
return ReadSignature ();
case DType.Variant:
return ReadVariant ();
default:
throw new Exception ("Unhandled D-Bus type: " + dtype);
}
}
public object GetObject (Type type)
{
ObjectPath path = ReadObjectPath ();
return message.Connection.GetObject (type, (string)message.Header.Fields[FieldCode.Sender], path);
}
public byte ReadByte ()
{
return data[pos++];
}
public bool ReadBoolean ()
{
uint intval = ReadUInt32 ();
switch (intval) {
case 0:
return false;
case 1:
return true;
default:
throw new Exception ("Read value " + intval + " at position " + pos + " while expecting boolean (0/1)");
}
}
unsafe protected void MarshalUShort (byte *dst)
{
ReadPad (2);
if (endianness == Connection.NativeEndianness) {
dst[0] = data[pos + 0];
dst[1] = data[pos + 1];
} else {
dst[0] = data[pos + 1];
dst[1] = data[pos + 0];
}
pos += 2;
}
unsafe public short ReadInt16 ()
{
short val;
MarshalUShort ((byte*)&val);
return val;
}
unsafe public ushort ReadUInt16 ()
{
ushort val;
MarshalUShort ((byte*)&val);
return val;
}
unsafe protected void MarshalUInt (byte *dst)
{
ReadPad (4);
if (endianness == Connection.NativeEndianness) {
dst[0] = data[pos + 0];
dst[1] = data[pos + 1];
dst[2] = data[pos + 2];
dst[3] = data[pos + 3];
} else {
dst[0] = data[pos + 3];
dst[1] = data[pos + 2];
dst[2] = data[pos + 1];
dst[3] = data[pos + 0];
}
pos += 4;
}
unsafe public int ReadInt32 ()
{
int val;
MarshalUInt ((byte*)&val);
return val;
}
unsafe public uint ReadUInt32 ()
{
uint val;
MarshalUInt ((byte*)&val);
return val;
}
unsafe protected void MarshalULong (byte *dst)
{
ReadPad (8);
if (endianness == Connection.NativeEndianness) {
for (int i = 0; i < 8; ++i)
dst[i] = data[pos + i];
} else {
for (int i = 0; i < 8; ++i)
dst[i] = data[pos + (7 - i)];
}
pos += 8;
}
unsafe public long ReadInt64 ()
{
long val;
MarshalULong ((byte*)&val);
return val;
}
unsafe public ulong ReadUInt64 ()
{
ulong val;
MarshalULong ((byte*)&val);
return val;
}
#if !DISABLE_SINGLE
unsafe public float ReadSingle ()
{
float val;
MarshalUInt ((byte*)&val);
return val;
}
#endif
unsafe public double ReadDouble ()
{
double val;
MarshalULong ((byte*)&val);
return val;
}
public string ReadString ()
{
uint ln = ReadUInt32 ();
string val = Encoding.UTF8.GetString (data, pos, (int)ln);
pos += (int)ln;
ReadNull ();
return val;
}
public ObjectPath ReadObjectPath ()
{
//exactly the same as string
return new ObjectPath (ReadString ());
}
public Signature ReadSignature ()
{
byte ln = ReadByte ();
if (ln > Protocol.MaxSignatureLength)
throw new Exception ("Signature length " + ln + " exceeds maximum allowed " + Protocol.MaxSignatureLength + " bytes");
byte[] sigData = new byte[ln];
Array.Copy (data, pos, sigData, 0, (int)ln);
pos += (int)ln;
ReadNull ();
return new Signature (sigData);
}
public object ReadVariant ()
{
return ReadVariant (ReadSignature ());
}
object ReadVariant (Signature sig)
{
return ReadValue (sig.ToType ());
}
//not pretty or efficient but works
public void GetValueToDict (Type keyType, Type valType, System.Collections.IDictionary val)
{
uint ln = ReadUInt32 ();
if (ln > Protocol.MaxArrayLength)
throw new Exception ("Dict length " + ln + " exceeds maximum allowed " + Protocol.MaxArrayLength + " bytes");
//advance to the alignment of the element
//ReadPad (Protocol.GetAlignment (Signature.TypeToDType (type)));
ReadPad (8);
int endPos = pos + (int)ln;
//while (stream.Position != endPos)
while (pos < endPos)
{
ReadPad (8);
val.Add (ReadValue (keyType), ReadValue (valType));
}
if (pos != endPos)
throw new Exception ("Read pos " + pos + " != ep " + endPos);
}
//this could be made generic to avoid boxing
public Array ReadArray (Type elemType)
{
uint ln = ReadUInt32 ();
if (ln > Protocol.MaxArrayLength)
throw new Exception ("Array length " + ln + " exceeds maximum allowed " + Protocol.MaxArrayLength + " bytes");
//TODO: more fast paths for primitive arrays
if (elemType == typeof (byte)) {
byte[] valb = new byte[ln];
Array.Copy (data, pos, valb, 0, (int)ln);
pos += (int)ln;
return valb;
}
//advance to the alignment of the element
ReadPad (Protocol.GetAlignment (Signature.TypeToDType (elemType)));
int endPos = pos + (int)ln;
//List<T> vals = new List<T> ();
System.Collections.ArrayList vals = new System.Collections.ArrayList ();
//while (stream.Position != endPos)
while (pos < endPos)
vals.Add (ReadValue (elemType));
if (pos != endPos)
throw new Exception ("Read pos " + pos + " != ep " + endPos);
return vals.ToArray (elemType);
}
//struct
//probably the wrong place for this
//there might be more elegant solutions
public object ReadStruct (Type type)
{
ReadPad (8);
object val = Activator.CreateInstance (type);
/*
if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (KeyValuePair<,>)) {
object elem;
System.Reflection.PropertyInfo key_prop = type.GetProperty ("Key");
GetValue (key_prop.PropertyType, out elem);
key_prop.SetValue (val, elem, null);
System.Reflection.PropertyInfo val_prop = type.GetProperty ("Value");
GetValue (val_prop.PropertyType, out elem);
val_prop.SetValue (val, elem, null);
return;
}
*/
FieldInfo[] fis = type.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (System.Reflection.FieldInfo fi in fis)
fi.SetValue (val, ReadValue (fi.FieldType));
return val;
}
public void ReadNull ()
{
if (data[pos] != 0)
throw new Exception ("Read non-zero byte at position " + pos + " while expecting null terminator");
pos++;
}
/*
public void ReadPad (int alignment)
{
pos = Protocol.Padded (pos, alignment);
}
*/
public void ReadPad (int alignment)
{
for (int endPos = Protocol.Padded (pos, alignment) ; pos != endPos ; pos++)
if (data[pos] != 0)
throw new Exception ("Read non-zero byte at position " + pos + " while expecting padding");
}
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/MessageWriter.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace NDesk.DBus
{
class MessageWriter
{
protected EndianFlag endianness;
protected MemoryStream stream;
public Connection connection;
//a default constructor is a bad idea for now as we want to make sure the header and content-type match
public MessageWriter () : this (Connection.NativeEndianness) {}
public MessageWriter (EndianFlag endianness)
{
this.endianness = endianness;
stream = new MemoryStream ();
}
public byte[] ToArray ()
{
//TODO: mark the writer locked or something here
return stream.ToArray ();
}
public void CloseWrite ()
{
int needed = Protocol.PadNeeded ((int)stream.Position, 8);
for (int i = 0 ; i != needed ; i++)
stream.WriteByte (0);
}
public void Write (byte val)
{
stream.WriteByte (val);
}
public void Write (bool val)
{
Write ((uint) (val ? 1 : 0));
}
unsafe protected void MarshalUShort (byte *data)
{
WritePad (2);
byte[] dst = new byte[2];
if (endianness == Connection.NativeEndianness) {
dst[0] = data[0];
dst[1] = data[1];
} else {
dst[0] = data[1];
dst[1] = data[0];
}
stream.Write (dst, 0, 2);
}
unsafe public void Write (short val)
{
MarshalUShort ((byte*)&val);
}
unsafe public void Write (ushort val)
{
MarshalUShort ((byte*)&val);
}
unsafe protected void MarshalUInt (byte *data)
{
WritePad (4);
byte[] dst = new byte[4];
if (endianness == Connection.NativeEndianness) {
dst[0] = data[0];
dst[1] = data[1];
dst[2] = data[2];
dst[3] = data[3];
} else {
dst[0] = data[3];
dst[1] = data[2];
dst[2] = data[1];
dst[3] = data[0];
}
stream.Write (dst, 0, 4);
}
unsafe public void Write (int val)
{
MarshalUInt ((byte*)&val);
}
unsafe public void Write (uint val)
{
MarshalUInt ((byte*)&val);
}
unsafe protected void MarshalULong (byte *data)
{
WritePad (8);
byte[] dst = new byte[8];
if (endianness == Connection.NativeEndianness) {
for (int i = 0; i < 8; ++i)
dst[i] = data[i];
} else {
for (int i = 0; i < 8; ++i)
dst[i] = data[7 - i];
}
stream.Write (dst, 0, 8);
}
unsafe public void Write (long val)
{
MarshalULong ((byte*)&val);
}
unsafe public void Write (ulong val)
{
MarshalULong ((byte*)&val);
}
#if !DISABLE_SINGLE
unsafe public void Write (float val)
{
MarshalUInt ((byte*)&val);
}
#endif
unsafe public void Write (double val)
{
MarshalULong ((byte*)&val);
}
public void Write (string val)
{
byte[] utf8_data = Encoding.UTF8.GetBytes (val);
Write ((uint)utf8_data.Length);
stream.Write (utf8_data, 0, utf8_data.Length);
WriteNull ();
}
public void Write (ObjectPath val)
{
Write (val.Value);
}
public void Write (Signature val)
{
byte[] ascii_data = val.GetBuffer ();
if (ascii_data.Length > Protocol.MaxSignatureLength)
throw new Exception ("Signature length " + ascii_data.Length + " exceeds maximum allowed " + Protocol.MaxSignatureLength + " bytes");
Write ((byte)ascii_data.Length);
stream.Write (ascii_data, 0, ascii_data.Length);
WriteNull ();
}
public void WriteComplex (object val, Type type)
{
if (type == typeof (void))
return;
if (type.IsArray) {
WriteArray (val, type.GetElementType ());
} else if (type.IsGenericType && (type.GetGenericTypeDefinition () == typeof (IDictionary<,>) || type.GetGenericTypeDefinition () == typeof (Dictionary<,>))) {
Type[] genArgs = type.GetGenericArguments ();
System.Collections.IDictionary idict = (System.Collections.IDictionary)val;
WriteFromDict (genArgs[0], genArgs[1], idict);
} else if (Mapper.IsPublic (type)) {
WriteObject (type, val);
} else if (!type.IsPrimitive && !type.IsEnum) {
WriteValueType (val, type);
/*
} else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (Nullable<>)) {
//is it possible to support nullable types?
Type[] genArgs = type.GetGenericArguments ();
WriteVariant (genArgs[0], val);
*/
} else {
throw new Exception ("Can't write");
}
}
public void Write (Type type, object val)
{
if (type == typeof (void))
return;
if (type.IsArray) {
WriteArray (val, type.GetElementType ());
} else if (type == typeof (ObjectPath)) {
Write ((ObjectPath)val);
} else if (type == typeof (Signature)) {
Write ((Signature)val);
} else if (type == typeof (object)) {
Write (val);
} else if (type == typeof (string)) {
Write ((string)val);
} else if (type.IsGenericType && (type.GetGenericTypeDefinition () == typeof (IDictionary<,>) || type.GetGenericTypeDefinition () == typeof (Dictionary<,>))) {
Type[] genArgs = type.GetGenericArguments ();
System.Collections.IDictionary idict = (System.Collections.IDictionary)val;
WriteFromDict (genArgs[0], genArgs[1], idict);
} else if (Mapper.IsPublic (type)) {
WriteObject (type, val);
} else if (!type.IsPrimitive && !type.IsEnum) {
WriteValueType (val, type);
} else {
Write (Signature.TypeToDType (type), val);
}
}
//helper method, should not be used as it boxes needlessly
public void Write (DType dtype, object val)
{
switch (dtype)
{
case DType.Byte:
{
Write ((byte)val);
}
break;
case DType.Boolean:
{
Write ((bool)val);
}
break;
case DType.Int16:
{
Write ((short)val);
}
break;
case DType.UInt16:
{
Write ((ushort)val);
}
break;
case DType.Int32:
{
Write ((int)val);
}
break;
case DType.UInt32:
{
Write ((uint)val);
}
break;
case DType.Int64:
{
Write ((long)val);
}
break;
case DType.UInt64:
{
Write ((ulong)val);
}
break;
#if !DISABLE_SINGLE
case DType.Single:
{
Write ((float)val);
}
break;
#endif
case DType.Double:
{
Write ((double)val);
}
break;
case DType.String:
{
Write ((string)val);
}
break;
case DType.ObjectPath:
{
Write ((ObjectPath)val);
}
break;
case DType.Signature:
{
Write ((Signature)val);
}
break;
case DType.Variant:
{
Write ((object)val);
}
break;
default:
throw new Exception ("Unhandled D-Bus type: " + dtype);
}
}
public void WriteObject (Type type, object val)
{
ObjectPath path;
BusObject bobj = val as BusObject;
if (bobj == null && val is MarshalByRefObject) {
bobj = ((MarshalByRefObject)val).GetLifetimeService () as BusObject;
}
if (bobj == null)
throw new Exception ("No object reference to write");
path = bobj.Path;
Write (path);
}
//variant
public void Write (object val)
{
//TODO: maybe support sending null variants
if (val == null)
throw new NotSupportedException ("Cannot send null variant");
Type type = val.GetType ();
WriteVariant (type, val);
}
public void WriteVariant (Type type, object val)
{
Signature sig = Signature.GetSig (type);
Write (sig);
Write (type, val);
}
//this requires a seekable stream for now
public void WriteArray (object obj, Type elemType)
{
Array val = (Array)obj;
//TODO: more fast paths for primitive arrays
if (elemType == typeof (byte)) {
if (val.Length > Protocol.MaxArrayLength)
throw new Exception ("Array length " + val.Length + " exceeds maximum allowed " + Protocol.MaxArrayLength + " bytes");
Write ((uint)val.Length);
stream.Write ((byte[])val, 0, val.Length);
return;
}
long origPos = stream.Position;
Write ((uint)0);
//advance to the alignment of the element
WritePad (Protocol.GetAlignment (Signature.TypeToDType (elemType)));
long startPos = stream.Position;
foreach (object elem in val)
Write (elemType, elem);
long endPos = stream.Position;
uint ln = (uint)(endPos - startPos);
stream.Position = origPos;
if (ln > Protocol.MaxArrayLength)
throw new Exception ("Array length " + ln + " exceeds maximum allowed " + Protocol.MaxArrayLength + " bytes");
Write (ln);
stream.Position = endPos;
}
public void WriteFromDict (Type keyType, Type valType, System.Collections.IDictionary val)
{
long origPos = stream.Position;
Write ((uint)0);
//advance to the alignment of the element
//WritePad (Protocol.GetAlignment (Signature.TypeToDType (type)));
WritePad (8);
long startPos = stream.Position;
foreach (System.Collections.DictionaryEntry entry in val)
{
WritePad (8);
Write (keyType, entry.Key);
Write (valType, entry.Value);
}
long endPos = stream.Position;
uint ln = (uint)(endPos - startPos);
stream.Position = origPos;
if (ln > Protocol.MaxArrayLength)
throw new Exception ("Dict length " + ln + " exceeds maximum allowed " + Protocol.MaxArrayLength + " bytes");
Write (ln);
stream.Position = endPos;
}
public void WriteValueType (object val, Type type)
{
MethodInfo mi = TypeImplementer.GetWriteMethod (type);
mi.Invoke (null, new object[] {this, val});
}
/*
public void WriteValueTypeOld (object val, Type type)
{
WritePad (8);
if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (KeyValuePair<,>)) {
System.Reflection.PropertyInfo key_prop = type.GetProperty ("Key");
Write (key_prop.PropertyType, key_prop.GetValue (val, null));
System.Reflection.PropertyInfo val_prop = type.GetProperty ("Value");
Write (val_prop.PropertyType, val_prop.GetValue (val, null));
return;
}
FieldInfo[] fis = type.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (System.Reflection.FieldInfo fi in fis) {
object elem;
elem = fi.GetValue (val);
Write (fi.FieldType, elem);
}
}
*/
public void WriteNull ()
{
stream.WriteByte (0);
}
public void WritePad (int alignment)
{
stream.Position = Protocol.Padded ((int)stream.Position, alignment);
}
}
} |
aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/NDesk-dbus.csproj | <?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>10.0.0</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{223B034E-A2F0-4BC7-875A-F9B5972C0670}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>NDeskdbus</RootNamespace>
<AssemblyName>NDesk-dbus</AssemblyName>
<SignAssembly>false</SignAssembly>
<AssemblyOriginatorKeyFile>ndesk.snk</AssemblyOriginatorKeyFile>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
<additionalargs>/unsafe</additionalargs>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
<additionalargs>/unsafe</additionalargs>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Xml" />
<Reference Include="Mono.Posix, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756" />
</ItemGroup>
<ItemGroup>
<Compile Include="AssemblyInfo.cs" />
<Compile Include="Authentication.cs" />
<Compile Include="Bus.cs" />
<Compile Include="BusObject.cs" />
<Compile Include="Connection.cs" />
<Compile Include="DBus.cs" />
<Compile Include="DProxy.cs" />
<Compile Include="ExportObject.cs" />
<Compile Include="Introspection.cs" />
<Compile Include="Mapper.cs" />
<Compile Include="MatchRule.cs" />
<Compile Include="Message.cs" />
<Compile Include="MessageFilter.cs" />
<Compile Include="MessageReader.cs" />
<Compile Include="MessageWriter.cs" />
<Compile Include="Address.cs" />
<Compile Include="PendingCall.cs" />
<Compile Include="Protocol.cs" />
<Compile Include="Signature.cs" />
<Compile Include="SocketTransport.cs" />
<Compile Include="Transport.cs" />
<Compile Include="TypeImplementer.cs" />
<Compile Include="UnixNativeTransport.cs" />
<Compile Include="UnixTransport.cs" />
<Compile Include="Wrapper.cs" />
<Compile Include="Notifications.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
</Project> |
|
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/Notifications.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop.DBus;
// Hand-written interfaces for bootstrapping
namespace org.freedesktop
{
public struct ServerInformation
{
public string Name;
public string Vendor;
public string Version;
public string SpecVersion;
}
[Interface ("org.freedesktop.Notifications")]
public interface Notifications : Introspectable, Properties
{
ServerInformation GetServerInformation ();
string[] GetCapabilities ();
void CloseNotification (uint id);
uint Notify (string app_name, uint id, string icon, string summary, string body, string[] actions, IDictionary<string,object> hints, int timeout);
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/PendingCall.cs | // Copyright 2007 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Threading;
namespace NDesk.DBus
{
class PendingCall
{
Connection conn;
Message reply = null;
object lockObj = new object ();
public PendingCall (Connection conn)
{
this.conn = conn;
}
int waiters = 0;
public Message Reply
{
get {
if (Thread.CurrentThread == conn.mainThread) {
/*
while (reply == null)
conn.Iterate ();
*/
while (reply == null)
conn.HandleMessage (conn.ReadMessage ());
conn.DispatchSignals ();
} else {
lock (lockObj) {
Interlocked.Increment (ref waiters);
while (reply == null)
Monitor.Wait (lockObj);
Interlocked.Decrement (ref waiters);
}
}
return reply;
} set {
lock (lockObj) {
reply = value;
if (waiters > 0)
Monitor.PulseAll (lockObj);
if (Completed != null)
Completed (reply);
}
}
}
public event Action<Message> Completed;
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/Protocol.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
namespace NDesk.DBus
{
//yyyyuua{yv}
struct Header
{
public EndianFlag Endianness;
public MessageType MessageType;
public HeaderFlag Flags;
public byte MajorVersion;
public uint Length;
public uint Serial;
//public HeaderField[] Fields;
public IDictionary<FieldCode,object> Fields;
/*
public static DType TypeForField (FieldCode f)
{
switch (f) {
case FieldCode.Invalid:
return DType.Invalid;
case FieldCode.Path:
return DType.ObjectPath;
case FieldCode.Interface:
return DType.String;
case FieldCode.Member:
return DType.String;
case FieldCode.ErrorName:
return DType.String;
case FieldCode.ReplySerial:
return DType.UInt32;
case FieldCode.Destination:
return DType.String;
case FieldCode.Sender:
return DType.String;
case FieldCode.Signature:
return DType.Signature;
#if PROTO_REPLY_SIGNATURE
case FieldCode.ReplySignature: //note: not supported in dbus
return DType.Signature;
#endif
default:
return DType.Invalid;
}
}
*/
}
/*
public struct HeaderField
{
//public HeaderField (FieldCode code, object value)
//{
// this.Code = code;
// this.Value = value;
//}
public static HeaderField Create (FieldCode code, object value)
{
HeaderField hf;
hf.Code = code;
hf.Value = value;
return hf;
}
public FieldCode Code;
public object Value;
}
*/
enum MessageType : byte
{
//This is an invalid type.
Invalid,
//Method call.
MethodCall,
//Method reply with returned data.
MethodReturn,
//Error reply. If the first argument exists and is a string, it is an error message.
Error,
//Signal emission.
Signal,
}
enum FieldCode : byte
{
Invalid,
Path,
Interface,
Member,
ErrorName,
ReplySerial,
Destination,
Sender,
Signature,
#if PROTO_REPLY_SIGNATURE
ReplySignature, //note: not supported in dbus
#endif
}
enum EndianFlag : byte
{
Little = (byte)'l',
Big = (byte)'B',
}
[Flags]
enum HeaderFlag : byte
{
None = 0,
NoReplyExpected = 0x1,
NoAutoStart = 0x2,
}
public sealed class ObjectPath //: IComparable, IComparable<ObjectPath>, IEquatable<ObjectPath>
{
public static readonly ObjectPath Root = new ObjectPath ("/");
internal readonly string Value;
public ObjectPath (string value)
{
if (value == null)
throw new ArgumentNullException ("value");
this.Value = value;
}
public override bool Equals (object o)
{
ObjectPath b = o as ObjectPath;
if (b == null)
return false;
return Value.Equals (b.Value);
}
public override int GetHashCode ()
{
return Value.GetHashCode ();
}
public override string ToString ()
{
return Value;
}
//this may or may not prove useful
internal string[] Decomposed
{
get {
return Value.Split (new char[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
/*
} set {
Value = String.Join ("/", value);
*/
}
}
internal ObjectPath Parent
{
get {
if (Value == Root.Value)
return null;
string par = Value.Substring (0, Value.LastIndexOf ('/'));
if (par == String.Empty)
par = "/";
return new ObjectPath (par);
}
}
/*
public int CompareTo (object value)
{
return 1;
}
public int CompareTo (ObjectPath value)
{
return 1;
}
public bool Equals (ObjectPath value)
{
return false;
}
*/
}
static class Protocol
{
//protocol versions that we support
public const byte MinVersion = 0;
public const byte Version = 1;
public const byte MaxVersion = Version;
public const uint MaxMessageLength = 134217728; //2 to the 27th power
public const uint MaxArrayLength = 67108864; //2 to the 26th power
public const uint MaxSignatureLength = 255;
public const uint MaxArrayDepth = 32;
public const uint MaxStructDepth = 32;
//this is not strictly related to Protocol since names are passed around as strings
internal const uint MaxNameLength = 255;
public static int PadNeeded (int pos, int alignment)
{
int pad = pos % alignment;
pad = pad == 0 ? 0 : alignment - pad;
return pad;
}
public static int Padded (int pos, int alignment)
{
int pad = pos % alignment;
if (pad != 0)
pos += alignment - pad;
return pos;
}
public static int GetAlignment (DType dtype)
{
switch (dtype) {
case DType.Byte:
return 1;
case DType.Boolean:
return 4;
case DType.Int16:
case DType.UInt16:
return 2;
case DType.Int32:
case DType.UInt32:
return 4;
case DType.Int64:
case DType.UInt64:
return 8;
#if !DISABLE_SINGLE
case DType.Single: //Not yet supported!
return 4;
#endif
case DType.Double:
return 8;
case DType.String:
return 4;
case DType.ObjectPath:
return 4;
case DType.Signature:
return 1;
case DType.Array:
return 4;
case DType.Struct:
return 8;
case DType.Variant:
return 1;
case DType.DictEntry:
return 8;
case DType.Invalid:
default:
throw new Exception ("Cannot determine alignment of " + dtype);
}
}
//this class may not be the best place for Verbose
public readonly static bool Verbose;
static Protocol ()
{
Verbose = !String.IsNullOrEmpty (Environment.GetEnvironmentVariable ("DBUS_VERBOSE"));
}
}
#if UNDOCUMENTED_IN_SPEC
/*
"org.freedesktop.DBus.Error.Failed"
"org.freedesktop.DBus.Error.NoMemory"
"org.freedesktop.DBus.Error.ServiceUnknown"
"org.freedesktop.DBus.Error.NameHasNoOwner"
"org.freedesktop.DBus.Error.NoReply"
"org.freedesktop.DBus.Error.IOError"
"org.freedesktop.DBus.Error.BadAddress"
"org.freedesktop.DBus.Error.NotSupported"
"org.freedesktop.DBus.Error.LimitsExceeded"
"org.freedesktop.DBus.Error.AccessDenied"
"org.freedesktop.DBus.Error.AuthFailed"
"org.freedesktop.DBus.Error.NoServer"
"org.freedesktop.DBus.Error.Timeout"
"org.freedesktop.DBus.Error.NoNetwork"
"org.freedesktop.DBus.Error.AddressInUse"
"org.freedesktop.DBus.Error.Disconnected"
"org.freedesktop.DBus.Error.InvalidArgs"
"org.freedesktop.DBus.Error.FileNotFound"
"org.freedesktop.DBus.Error.UnknownMethod"
"org.freedesktop.DBus.Error.TimedOut"
"org.freedesktop.DBus.Error.MatchRuleNotFound"
"org.freedesktop.DBus.Error.MatchRuleInvalid"
"org.freedesktop.DBus.Error.Spawn.ExecFailed"
"org.freedesktop.DBus.Error.Spawn.ForkFailed"
"org.freedesktop.DBus.Error.Spawn.ChildExited"
"org.freedesktop.DBus.Error.Spawn.ChildSignaled"
"org.freedesktop.DBus.Error.Spawn.Failed"
"org.freedesktop.DBus.Error.UnixProcessIdUnknown"
"org.freedesktop.DBus.Error.InvalidSignature"
"org.freedesktop.DBus.Error.SELinuxSecurityContextUnknown"
*/
#endif
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/Signature.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Text;
using System.Collections.Generic;
//TODO: Reflection should be done at a higher level than this class
using System.Reflection;
namespace NDesk.DBus
{
//maybe this should be nullable?
struct Signature
{
//TODO: this class needs some work
//Data should probably include the null terminator
public static readonly Signature Empty = new Signature (String.Empty);
public static bool operator == (Signature a, Signature b)
{
/*
//TODO: remove this hack to handle bad case when Data is null
if (a.data == null || b.data == null)
throw new Exception ("Encountered Signature with null buffer");
*/
/*
if (a.data == null && b.data == null)
return true;
if (a.data == null || b.data == null)
return false;
*/
if (a.data.Length != b.data.Length)
return false;
for (int i = 0 ; i != a.data.Length ; i++)
if (a.data[i] != b.data[i])
return false;
return true;
}
public static bool operator != (Signature a, Signature b)
{
return !(a == b);
}
public override bool Equals (object o)
{
if (o == null)
return false;
if (!(o is Signature))
return false;
return this == (Signature)o;
}
public override int GetHashCode ()
{
return data.GetHashCode ();
}
public static Signature operator + (Signature s1, Signature s2)
{
return Concat (s1, s2);
}
//these need to be optimized
public static Signature Concat (Signature s1, Signature s2)
{
return new Signature (s1.Value + s2.Value);
}
public static Signature Copy (Signature sig)
{
return new Signature (sig.data);
}
public Signature (string value)
{
this.data = Encoding.ASCII.GetBytes (value);
}
public Signature (byte[] value)
{
this.data = (byte[])value.Clone ();
}
//this will become obsolete soon
internal Signature (DType value)
{
this.data = new byte[] {(byte)value};
}
internal Signature (DType[] value)
{
this.data = new byte[value.Length];
/*
MemoryStream ms = new MemoryStream (this.data);
foreach (DType t in value)
ms.WriteByte ((byte)t);
*/
for (int i = 0 ; i != value.Length ; i++)
this.data[i] = (byte)value[i];
}
byte[] data;
//TODO: this should be private, but MessageWriter and Monitor still use it
//[Obsolete]
public byte[] GetBuffer ()
{
return data;
}
internal DType this[int index]
{
get {
return (DType)data[index];
}
}
public int Length
{
get {
return data.Length;
}
}
//[Obsolete]
public string Value
{
get {
/*
//FIXME: hack to handle bad case when Data is null
if (data == null)
return String.Empty;
*/
return Encoding.ASCII.GetString (data);
}
}
public override string ToString ()
{
return Value;
/*
StringBuilder sb = new StringBuilder ();
foreach (DType t in data) {
//we shouldn't rely on object mapping here, but it's an easy way to get string representations for now
Type type = DTypeToType (t);
if (type != null) {
sb.Append (type.Name);
} else {
char c = (char)t;
if (!Char.IsControl (c))
sb.Append (c);
else
sb.Append (@"\" + (int)c);
}
sb.Append (" ");
}
return sb.ToString ();
*/
}
public Signature MakeArraySignature ()
{
return new Signature (DType.Array) + this;
}
public static Signature MakeStruct (params Signature[] elems)
{
Signature sig = Signature.Empty;
sig += new Signature (DType.StructBegin);
foreach (Signature elem in elems)
sig += elem;
sig += new Signature (DType.StructEnd);
return sig;
}
public static Signature MakeDictEntry (Signature keyType, Signature valueType)
{
Signature sig = Signature.Empty;
sig += new Signature (DType.DictEntryBegin);
sig += keyType;
sig += valueType;
sig += new Signature (DType.DictEntryEnd);
return sig;
}
public static Signature MakeDict (Signature keyType, Signature valueType)
{
return MakeDictEntry (keyType, valueType).MakeArraySignature ();
}
/*
//TODO: complete this
public bool IsPrimitive
{
get {
if (this == Signature.Empty)
return true;
return false;
}
}
*/
public bool IsDict
{
get {
if (Length < 3)
return false;
if (!IsArray)
return false;
if (this[2] != DType.DictEntryBegin)
return false;
return true;
}
}
public bool IsArray
{
get {
if (Length < 2)
return false;
if (this[0] != DType.Array)
return false;
return true;
}
}
public Signature GetElementSignature ()
{
if (!IsArray)
throw new Exception ("Cannot get the element signature of a non-array (signature was '" + this + "')");
//TODO: improve this
if (Length != 2)
throw new NotSupportedException ("Parsing signatures with more than one primitive value is not supported (signature was '" + this + "')");
return new Signature (this[1]);
}
public Type[] ToTypes ()
{
List<Type> types = new List<Type> ();
for (int i = 0 ; i != data.Length ; types.Add (ToType (ref i)));
return types.ToArray ();
}
public Type ToType ()
{
int pos = 0;
Type ret = ToType (ref pos);
if (pos != data.Length)
throw new Exception ("Signature '" + Value + "' is not a single complete type");
return ret;
}
internal static DType TypeCodeToDType (TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.Empty:
return DType.Invalid;
case TypeCode.Object:
return DType.Invalid;
case TypeCode.DBNull:
return DType.Invalid;
case TypeCode.Boolean:
return DType.Boolean;
case TypeCode.Char:
return DType.UInt16;
case TypeCode.SByte:
return DType.Byte;
case TypeCode.Byte:
return DType.Byte;
case TypeCode.Int16:
return DType.Int16;
case TypeCode.UInt16:
return DType.UInt16;
case TypeCode.Int32:
return DType.Int32;
case TypeCode.UInt32:
return DType.UInt32;
case TypeCode.Int64:
return DType.Int64;
case TypeCode.UInt64:
return DType.UInt64;
case TypeCode.Single:
return DType.Single;
case TypeCode.Double:
return DType.Double;
case TypeCode.Decimal:
return DType.Invalid;
case TypeCode.DateTime:
return DType.Invalid;
case TypeCode.String:
return DType.String;
default:
return DType.Invalid;
}
}
//FIXME: this method is bad, get rid of it
internal static DType TypeToDType (Type type)
{
if (type == typeof (void))
return DType.Invalid;
if (type == typeof (string))
return DType.String;
if (type == typeof (ObjectPath))
return DType.ObjectPath;
if (type == typeof (Signature))
return DType.Signature;
if (type == typeof (object))
return DType.Variant;
if (type.IsPrimitive)
return TypeCodeToDType (Type.GetTypeCode (type));
if (type.IsEnum)
return TypeToDType (Enum.GetUnderlyingType (type));
//needs work
if (type.IsArray)
return DType.Array;
//if (type.UnderlyingSystemType != null)
// return TypeToDType (type.UnderlyingSystemType);
if (Mapper.IsPublic (type))
return DType.ObjectPath;
if (!type.IsPrimitive && !type.IsEnum)
return DType.Struct;
//TODO: maybe throw an exception here
return DType.Invalid;
}
/*
public static DType TypeToDType (Type type)
{
if (type == null)
return DType.Invalid;
else if (type == typeof (byte))
return DType.Byte;
else if (type == typeof (bool))
return DType.Boolean;
else if (type == typeof (short))
return DType.Int16;
else if (type == typeof (ushort))
return DType.UInt16;
else if (type == typeof (int))
return DType.Int32;
else if (type == typeof (uint))
return DType.UInt32;
else if (type == typeof (long))
return DType.Int64;
else if (type == typeof (ulong))
return DType.UInt64;
else if (type == typeof (float)) //not supported by libdbus at time of writing
return DType.Single;
else if (type == typeof (double))
return DType.Double;
else if (type == typeof (string))
return DType.String;
else if (type == typeof (ObjectPath))
return DType.ObjectPath;
else if (type == typeof (Signature))
return DType.Signature;
else
return DType.Invalid;
}
*/
public Type ToType (ref int pos)
{
DType dtype = (DType)data[pos++];
switch (dtype) {
case DType.Invalid:
return typeof (void);
case DType.Byte:
return typeof (byte);
case DType.Boolean:
return typeof (bool);
case DType.Int16:
return typeof (short);
case DType.UInt16:
return typeof (ushort);
case DType.Int32:
return typeof (int);
case DType.UInt32:
return typeof (uint);
case DType.Int64:
return typeof (long);
case DType.UInt64:
return typeof (ulong);
case DType.Single: ////not supported by libdbus at time of writing
return typeof (float);
case DType.Double:
return typeof (double);
case DType.String:
return typeof (string);
case DType.ObjectPath:
return typeof (ObjectPath);
case DType.Signature:
return typeof (Signature);
case DType.Array:
//peek to see if this is in fact a dictionary
if ((DType)data[pos] == DType.DictEntryBegin) {
//skip over the {
pos++;
Type keyType = ToType (ref pos);
Type valueType = ToType (ref pos);
//skip over the }
pos++;
//return typeof (IDictionary<,>).MakeGenericType (new Type[] {keyType, valueType});
//workaround for Mono bug #81035 (memory leak)
return Mapper.GetGenericType (typeof (IDictionary<,>), new Type[] {keyType, valueType});
} else {
return ToType (ref pos).MakeArrayType ();
}
case DType.Struct:
return typeof (ValueType);
case DType.DictEntry:
return typeof (System.Collections.Generic.KeyValuePair<,>);
case DType.Variant:
return typeof (object);
default:
throw new NotSupportedException ("Parsing or converting this signature is not yet supported (signature was '" + this + "'), at DType." + dtype);
}
}
public static Signature GetSig (object[] objs)
{
return GetSig (Type.GetTypeArray (objs));
}
public static Signature GetSig (Type[] types)
{
if (types == null)
throw new ArgumentNullException ("types");
Signature sig = Signature.Empty;
foreach (Type type in types)
sig += GetSig (type);
return sig;
}
public static Signature GetSig (Type type)
{
if (type == null)
throw new ArgumentNullException ("type");
//this is inelegant, but works for now
if (type == typeof (Signature))
return new Signature (DType.Signature);
if (type == typeof (ObjectPath))
return new Signature (DType.ObjectPath);
if (type == typeof (void))
return Signature.Empty;
if (type == typeof (string))
return new Signature (DType.String);
if (type == typeof (object))
return new Signature (DType.Variant);
if (type.IsArray)
return GetSig (type.GetElementType ()).MakeArraySignature ();
if (type.IsGenericType && (type.GetGenericTypeDefinition () == typeof (IDictionary<,>) || type.GetGenericTypeDefinition () == typeof (Dictionary<,>))) {
Type[] genArgs = type.GetGenericArguments ();
return Signature.MakeDict (GetSig (genArgs[0]), GetSig (genArgs[1]));
}
if (Mapper.IsPublic (type)) {
return new Signature (DType.ObjectPath);
}
if (!type.IsPrimitive && !type.IsEnum) {
Signature sig = Signature.Empty;
foreach (FieldInfo fi in type.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
sig += GetSig (fi.FieldType);
return Signature.MakeStruct (sig);
}
DType dtype = Signature.TypeToDType (type);
return new Signature (dtype);
}
}
enum ArgDirection
{
In,
Out,
}
enum DType : byte
{
Invalid = (byte)'\0',
Byte = (byte)'y',
Boolean = (byte)'b',
Int16 = (byte)'n',
UInt16 = (byte)'q',
Int32 = (byte)'i',
UInt32 = (byte)'u',
Int64 = (byte)'x',
UInt64 = (byte)'t',
Single = (byte)'f', //This is not yet supported!
Double = (byte)'d',
String = (byte)'s',
ObjectPath = (byte)'o',
Signature = (byte)'g',
Array = (byte)'a',
//TODO: remove Struct and DictEntry -- they are not relevant to wire protocol
Struct = (byte)'r',
DictEntry = (byte)'e',
Variant = (byte)'v',
StructBegin = (byte)'(',
StructEnd = (byte)')',
DictEntryBegin = (byte)'{',
DictEntryEnd = (byte)'}',
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/SocketTransport.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace NDesk.DBus.Transports
{
class SocketTransport : Transport
{
protected Socket socket;
public override void Open (AddressEntry entry)
{
string host, portStr;
int port;
if (!entry.Properties.TryGetValue ("host", out host))
throw new Exception ("No host specified");
if (!entry.Properties.TryGetValue ("port", out portStr))
throw new Exception ("No port specified");
if (!Int32.TryParse (portStr, out port))
throw new Exception ("Invalid port: \"" + port + "\"");
Open (host, port);
}
public void Open (string host, int port)
{
//TODO: use Socket directly
TcpClient client = new TcpClient (host, port);
Stream = client.GetStream ();
}
public void Open (Socket socket)
{
this.socket = socket;
socket.Blocking = true;
SocketHandle = (long)socket.Handle;
//Stream = new UnixStream ((int)socket.Handle);
Stream = new NetworkStream (socket);
}
public override void WriteCred ()
{
Stream.WriteByte (0);
}
public override string AuthString ()
{
return String.Empty;
}
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/Transport.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.IO;
namespace NDesk.DBus.Transports
{
abstract class Transport
{
public static Transport Create (AddressEntry entry)
{
switch (entry.Method) {
case "tcp":
{
Transport transport = new SocketTransport ();
transport.Open (entry);
return transport;
}
#if !PORTABLE
case "unix":
{
//Transport transport = new UnixMonoTransport ();
Transport transport = new UnixNativeTransport ();
transport.Open (entry);
return transport;
}
#endif
default:
throw new NotSupportedException ("Transport method \"" + entry.Method + "\" not supported");
}
}
protected Connection connection;
public Connection Connection
{
get {
return connection;
} set {
connection = value;
}
}
//TODO: design this properly
//this is just a temporary solution
public Stream Stream;
public long SocketHandle;
public abstract void Open (AddressEntry entry);
public abstract string AuthString ();
public abstract void WriteCred ();
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/TypeImplementer.cs | // Copyright 2007 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
namespace NDesk.DBus
{
static class TypeImplementer
{
static AssemblyBuilder asmB;
static ModuleBuilder modB;
static void InitHack ()
{
if (asmB != null)
return;
asmB = AppDomain.CurrentDomain.DefineDynamicAssembly (new AssemblyName ("NDesk.DBus.Proxies"), AssemblyBuilderAccess.Run);
modB = asmB.DefineDynamicModule ("ProxyModule");
}
static Dictionary<Type,Type> map = new Dictionary<Type,Type> ();
public static Type GetImplementation (Type declType)
{
Type retT;
if (map.TryGetValue (declType, out retT))
return retT;
InitHack ();
TypeBuilder typeB = modB.DefineType (declType.Name + "Proxy", TypeAttributes.Class | TypeAttributes.Public, typeof (BusObject));
Implement (typeB, declType);
foreach (Type iface in declType.GetInterfaces ())
Implement (typeB, iface);
retT = typeB.CreateType ();
map[declType] = retT;
return retT;
}
public static void Implement (TypeBuilder typeB, Type iface)
{
typeB.AddInterfaceImplementation (iface);
foreach (MethodInfo declMethod in iface.GetMethods ()) {
ParameterInfo[] parms = declMethod.GetParameters ();
Type[] parmTypes = new Type[parms.Length];
for (int i = 0 ; i < parms.Length ; i++)
parmTypes[i] = parms[i].ParameterType;
MethodAttributes attrs = declMethod.Attributes ^ MethodAttributes.Abstract;
MethodBuilder method_builder = typeB.DefineMethod (declMethod.Name, attrs, declMethod.ReturnType, parmTypes);
typeB.DefineMethodOverride (method_builder, declMethod);
//define in/out/ref/name for each of the parameters
for (int i = 0; i < parms.Length ; i++)
method_builder.DefineParameter (i, parms[i].Attributes, parms[i].Name);
ILGenerator ilg = method_builder.GetILGenerator ();
GenHookupMethod (ilg, declMethod, sendMethodCallMethod, Mapper.GetInterfaceName (iface), declMethod.Name);
}
}
static MethodInfo sendMethodCallMethod = typeof (BusObject).GetMethod ("SendMethodCall");
static MethodInfo sendSignalMethod = typeof (BusObject).GetMethod ("SendSignal");
static MethodInfo toggleSignalMethod = typeof (BusObject).GetMethod ("ToggleSignal");
static Dictionary<EventInfo,DynamicMethod> hookup_methods = new Dictionary<EventInfo,DynamicMethod> ();
public static DynamicMethod GetHookupMethod (EventInfo ei)
{
DynamicMethod hookupMethod;
if (hookup_methods.TryGetValue (ei, out hookupMethod))
return hookupMethod;
if (ei.EventHandlerType.IsAssignableFrom (typeof (System.EventHandler)))
Console.Error.WriteLine ("Warning: Cannot yet fully expose EventHandler and its subclasses: " + ei.EventHandlerType);
MethodInfo declMethod = ei.EventHandlerType.GetMethod ("Invoke");
hookupMethod = GetHookupMethod (declMethod, sendSignalMethod, Mapper.GetInterfaceName (ei), ei.Name);
hookup_methods[ei] = hookupMethod;
return hookupMethod;
}
public static DynamicMethod GetHookupMethod (MethodInfo declMethod, MethodInfo invokeMethod, string @interface, string member)
{
ParameterInfo[] delegateParms = declMethod.GetParameters ();
Type[] hookupParms = new Type[delegateParms.Length+1];
hookupParms[0] = typeof (BusObject);
for (int i = 0; i < delegateParms.Length ; i++)
hookupParms[i+1] = delegateParms[i].ParameterType;
DynamicMethod hookupMethod = new DynamicMethod ("Handle" + member, declMethod.ReturnType, hookupParms, typeof (MessageWriter));
ILGenerator ilg = hookupMethod.GetILGenerator ();
GenHookupMethod (ilg, declMethod, invokeMethod, @interface, member);
return hookupMethod;
}
//static MethodInfo getMethodFromHandleMethod = typeof (MethodBase).GetMethod ("GetMethodFromHandle", new Type[] {typeof (RuntimeMethodHandle)});
static MethodInfo getTypeFromHandleMethod = typeof (Type).GetMethod ("GetTypeFromHandle", new Type[] {typeof (RuntimeTypeHandle)});
static ConstructorInfo argumentNullExceptionConstructor = typeof (ArgumentNullException).GetConstructor (new Type[] {typeof (string)});
static ConstructorInfo messageWriterConstructor = typeof (MessageWriter).GetConstructor (Type.EmptyTypes);
static MethodInfo messageWriterWriteMethod = typeof (MessageWriter).GetMethod ("WriteComplex", new Type[] {typeof (object), typeof (Type)});
static MethodInfo messageWriterWritePad = typeof (MessageWriter).GetMethod ("WritePad", new Type[] {typeof (int)});
static Dictionary<Type,MethodInfo> writeMethods = new Dictionary<Type,MethodInfo> ();
public static MethodInfo GetWriteMethod (Type t)
{
MethodInfo meth;
if (writeMethods.TryGetValue (t, out meth))
return meth;
/*
Type tUnder = t;
if (t.IsEnum)
tUnder = Enum.GetUnderlyingType (t);
meth = typeof (MessageWriter).GetMethod ("Write", BindingFlags.ExactBinding | BindingFlags.Instance | BindingFlags.Public, null, new Type[] {tUnder}, null);
if (meth != null) {
writeMethods[t] = meth;
return meth;
}
*/
DynamicMethod method_builder = new DynamicMethod ("Write" + t.Name, typeof (void), new Type[] {typeof (MessageWriter), t}, typeof (MessageWriter));
ILGenerator ilg = method_builder.GetILGenerator ();
ilg.Emit (OpCodes.Ldarg_0);
ilg.Emit (OpCodes.Ldarg_1);
GenMarshalWrite (ilg, t);
ilg.Emit (OpCodes.Ret);
meth = method_builder;
writeMethods[t] = meth;
return meth;
}
//takes the Writer instance and the value of Type t off the stack, writes it
public static void GenWriter (ILGenerator ilg, Type t)
{
Type tUnder = t;
//bool imprecise = false;
if (t.IsEnum) {
tUnder = Enum.GetUnderlyingType (t);
//imprecise = true;
}
//MethodInfo exactWriteMethod = typeof (MessageWriter).GetMethod ("Write", new Type[] {tUnder});
MethodInfo exactWriteMethod = typeof (MessageWriter).GetMethod ("Write", BindingFlags.ExactBinding | BindingFlags.Instance | BindingFlags.Public, null, new Type[] {tUnder}, null);
//ExactBinding InvokeMethod
if (exactWriteMethod != null) {
//if (imprecise)
// ilg.Emit (OpCodes.Castclass, tUnder);
ilg.Emit (exactWriteMethod.IsFinal ? OpCodes.Call : OpCodes.Callvirt, exactWriteMethod);
} else {
//..boxed if necessary
if (t.IsValueType)
ilg.Emit (OpCodes.Box, t);
//the Type parameter
ilg.Emit (OpCodes.Ldtoken, t);
ilg.Emit (OpCodes.Call, getTypeFromHandleMethod);
ilg.Emit (messageWriterWriteMethod.IsFinal ? OpCodes.Call : OpCodes.Callvirt, messageWriterWriteMethod);
}
}
//takes a writer and a reference to an object off the stack
public static void GenMarshalWrite (ILGenerator ilg, Type type)
{
LocalBuilder val = ilg.DeclareLocal (type);
ilg.Emit (OpCodes.Stloc, val);
LocalBuilder writer = ilg.DeclareLocal (typeof (MessageWriter));
ilg.Emit (OpCodes.Stloc, writer);
FieldInfo[] fis = type.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
//align to 8 for structs
ilg.Emit (OpCodes.Ldloc, writer);
ilg.Emit (OpCodes.Ldc_I4, 8);
ilg.Emit (messageWriterWritePad.IsFinal ? OpCodes.Call : OpCodes.Callvirt, messageWriterWritePad);
foreach (FieldInfo fi in fis) {
Type t = fi.FieldType;
//the Writer to write to
ilg.Emit (OpCodes.Ldloc, writer);
//the object parameter
ilg.Emit (OpCodes.Ldloc, val);
ilg.Emit (OpCodes.Ldfld, fi);
GenWriter (ilg, t);
}
}
public static void GenHookupMethod (ILGenerator ilg, MethodInfo declMethod, MethodInfo invokeMethod, string @interface, string member)
{
ParameterInfo[] parms = declMethod.GetParameters ();
Type retType = declMethod.ReturnType;
//the BusObject instance
ilg.Emit (OpCodes.Ldarg_0);
//MethodInfo
/*
ilg.Emit (OpCodes.Ldtoken, declMethod);
ilg.Emit (OpCodes.Call, getMethodFromHandleMethod);
*/
//interface
ilg.Emit (OpCodes.Ldstr, @interface);
//special case event add/remove methods
if (declMethod.IsSpecialName && (declMethod.Name.StartsWith ("add_") || declMethod.Name.StartsWith ("remove_"))) {
string[] parts = declMethod.Name.Split (new char[]{'_'}, 2);
string ename = parts[1];
//Delegate dlg = (Delegate)inArgs[0];
bool adding = parts[0] == "add";
ilg.Emit (OpCodes.Ldstr, ename);
ilg.Emit (OpCodes.Ldarg_1);
ilg.Emit (OpCodes.Ldc_I4, adding ? 1 : 0);
ilg.Emit (OpCodes.Tailcall);
ilg.Emit (toggleSignalMethod.IsFinal ? OpCodes.Call : OpCodes.Callvirt, toggleSignalMethod);
ilg.Emit (OpCodes.Ret);
return;
}
//property accessor mapping
if (declMethod.IsSpecialName) {
if (member.StartsWith ("get_"))
member = "Get" + member.Substring (4);
else if (member.StartsWith ("set_"))
member = "Set" + member.Substring (4);
}
//member
ilg.Emit (OpCodes.Ldstr, member);
//signature
Signature inSig = Signature.Empty;
Signature outSig = Signature.Empty;
if (!declMethod.IsSpecialName)
foreach (ParameterInfo parm in parms)
{
if (parm.IsOut)
outSig += Signature.GetSig (parm.ParameterType.GetElementType ());
else
inSig += Signature.GetSig (parm.ParameterType);
}
ilg.Emit (OpCodes.Ldstr, inSig.Value);
LocalBuilder writer = ilg.DeclareLocal (typeof (MessageWriter));
ilg.Emit (OpCodes.Newobj, messageWriterConstructor);
ilg.Emit (OpCodes.Stloc, writer);
foreach (ParameterInfo parm in parms)
{
if (parm.IsOut)
continue;
Type t = parm.ParameterType;
//offset by one to account for "this"
int i = parm.Position + 1;
//null checking of parameters (but not their recursive contents)
if (!t.IsValueType) {
Label notNull = ilg.DefineLabel ();
//if the value is null...
ilg.Emit (OpCodes.Ldarg, i);
ilg.Emit (OpCodes.Brtrue_S, notNull);
//...throw Exception
string paramName = parm.Name;
ilg.Emit (OpCodes.Ldstr, paramName);
ilg.Emit (OpCodes.Newobj, argumentNullExceptionConstructor);
ilg.Emit (OpCodes.Throw);
//was not null, so all is well
ilg.MarkLabel (notNull);
}
ilg.Emit (OpCodes.Ldloc, writer);
//the parameter
ilg.Emit (OpCodes.Ldarg, i);
GenWriter (ilg, t);
}
ilg.Emit (OpCodes.Ldloc, writer);
//the expected return Type
ilg.Emit (OpCodes.Ldtoken, retType);
ilg.Emit (OpCodes.Call, getTypeFromHandleMethod);
LocalBuilder exc = ilg.DeclareLocal (typeof (Exception));
ilg.Emit (OpCodes.Ldloca_S, exc);
//make the call
ilg.Emit (invokeMethod.IsFinal ? OpCodes.Call : OpCodes.Callvirt, invokeMethod);
//define a label we'll use to deal with a non-null Exception
Label noErr = ilg.DefineLabel ();
//if the out Exception is not null...
ilg.Emit (OpCodes.Ldloc, exc);
ilg.Emit (OpCodes.Brfalse_S, noErr);
//...throw it.
ilg.Emit (OpCodes.Ldloc, exc);
ilg.Emit (OpCodes.Throw);
//Exception was null, so all is well
ilg.MarkLabel (noErr);
if (retType == typeof (void)) {
//we aren't expecting a return value, so throw away the (hopefully) null return
if (invokeMethod.ReturnType != typeof (void))
ilg.Emit (OpCodes.Pop);
} else {
if (retType.IsValueType)
ilg.Emit (OpCodes.Unbox_Any, retType);
else
ilg.Emit (OpCodes.Castclass, retType);
}
ilg.Emit (OpCodes.Ret);
}
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/UnixNativeTransport.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
//We send BSD-style credentials on all platforms
//Doesn't seem to break Linux (but is redundant there)
//This may turn out to be a bad idea
#define HAVE_CMSGCRED
using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using Mono.Unix;
using Mono.Unix.Native;
namespace NDesk.DBus.Transports
{
class UnixSocket
{
public const short AF_UNIX = 1;
//TODO: SOCK_STREAM is 2 on Solaris
public const short SOCK_STREAM = 1;
//TODO: some of these are provided by libsocket instead of libc on Solaris
[DllImport ("libc", SetLastError=true)]
protected static extern int socket (int domain, int type, int protocol);
[DllImport ("libc", SetLastError=true)]
protected static extern int connect (int sockfd, byte[] serv_addr, uint addrlen);
[DllImport ("libc", SetLastError=true)]
protected static extern int bind (int sockfd, byte[] my_addr, uint addrlen);
[DllImport ("libc", SetLastError=true)]
protected static extern int listen (int sockfd, int backlog);
//TODO: this prototype is probably wrong, fix it
[DllImport ("libc", SetLastError=true)]
protected static extern int accept (int sockfd, byte[] addr, ref uint addrlen);
//TODO: confirm and make use of these functions
[DllImport ("libc", SetLastError=true)]
protected static extern int getsockopt (int s, int optname, IntPtr optval, ref uint optlen);
[DllImport ("libc", SetLastError=true)]
protected static extern int setsockopt (int s, int optname, IntPtr optval, uint optlen);
[DllImport ("libc", SetLastError=true)]
public static extern int recvmsg (int s, IntPtr msg, int flags);
[DllImport ("libc", SetLastError=true)]
public static extern int sendmsg (int s, IntPtr msg, int flags);
public int Handle;
public UnixSocket (int handle)
{
this.Handle = handle;
}
public UnixSocket ()
{
//TODO: don't hard-code PF_UNIX and SOCK_STREAM or SocketType.Stream
//AddressFamily family, SocketType type, ProtocolType proto
int r = socket (AF_UNIX, SOCK_STREAM, 0);
//we should get the Exception from UnixMarshal and throw it here for a better stack trace, but the relevant API seems to be private
UnixMarshal.ThrowExceptionForLastErrorIf (r);
Handle = r;
}
protected bool connected = false;
//TODO: consider memory management
public void Connect (byte[] remote_end)
{
int r = connect (Handle, remote_end, (uint)remote_end.Length);
//we should get the Exception from UnixMarshal and throw it here for a better stack trace, but the relevant API seems to be private
UnixMarshal.ThrowExceptionForLastErrorIf (r);
connected = true;
}
//assigns a name to the socket
public void Bind (byte[] local_end)
{
int r = bind (Handle, local_end, (uint)local_end.Length);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
}
public void Listen (int backlog)
{
int r = listen (Handle, backlog);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
}
public UnixSocket Accept ()
{
byte[] addr = new byte[110];
uint addrlen = (uint)addr.Length;
int r = accept (Handle, addr, ref addrlen);
UnixMarshal.ThrowExceptionForLastErrorIf (r);
//TODO: use the returned addr
//TODO: fix probable memory leak here
//string str = Encoding.Default.GetString (addr, 0, (int)addrlen);
return new UnixSocket (r);
}
}
struct IOVector
{
public IntPtr Base;
public int Length;
}
class UnixNativeTransport : UnixTransport
{
protected UnixSocket socket;
public override void Open (string path, bool @abstract)
{
if (String.IsNullOrEmpty (path))
throw new ArgumentException ("path");
if (@abstract)
socket = OpenAbstractUnix (path);
else
socket = OpenUnix (path);
//socket.Blocking = true;
SocketHandle = (long)socket.Handle;
Stream = new UnixStream ((int)socket.Handle);
}
//send peer credentials null byte
//different platforms do this in different ways
#if HAVE_CMSGCRED
unsafe void WriteBsdCred ()
{
//null credentials byte
byte buf = 0;
IOVector iov = new IOVector ();
iov.Base = (IntPtr)(&buf);
iov.Length = 1;
msghdr msg = new msghdr ();
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
cmsg cm = new cmsg ();
msg.msg_control = (IntPtr)(&cm);
msg.msg_controllen = (uint)sizeof (cmsg);
cm.hdr.cmsg_len = (uint)sizeof (cmsg);
cm.hdr.cmsg_level = 0xffff; //SOL_SOCKET
cm.hdr.cmsg_type = 0x03; //SCM_CREDS
int written = UnixSocket.sendmsg (socket.Handle, (IntPtr)(&msg), 0);
UnixMarshal.ThrowExceptionForLastErrorIf (written);
if (written != 1)
throw new Exception ("Failed to write credentials");
}
#endif
public override void WriteCred ()
{
#if HAVE_CMSGCRED
try {
WriteBsdCred ();
} catch {
if (Protocol.Verbose)
Console.Error.WriteLine ("Warning: WriteBsdCred() failed; falling back to ordinary WriteCred()");
//null credentials byte
byte buf = 0;
Stream.WriteByte (buf);
}
#else
//null credentials byte
byte buf = 0;
Stream.WriteByte (buf);
#endif
}
protected UnixSocket OpenAbstractUnix (string path)
{
byte[] p = Encoding.Default.GetBytes (path);
byte[] sa = new byte[2 + 1 + p.Length];
//we use BitConverter to stay endian-safe
byte[] afData = BitConverter.GetBytes (UnixSocket.AF_UNIX);
sa[0] = afData[0];
sa[1] = afData[1];
sa[2] = 0; //null prefix for abstract domain socket addresses, see unix(7)
for (int i = 0 ; i != p.Length ; i++)
sa[3 + i] = p[i];
UnixSocket client = new UnixSocket ();
client.Connect (sa);
return client;
}
public UnixSocket OpenUnix (string path)
{
byte[] p = Encoding.Default.GetBytes (path);
byte[] sa = new byte[2 + p.Length + 1];
//we use BitConverter to stay endian-safe
byte[] afData = BitConverter.GetBytes (UnixSocket.AF_UNIX);
sa[0] = afData[0];
sa[1] = afData[1];
for (int i = 0 ; i != p.Length ; i++)
sa[2 + i] = p[i];
sa[2 + p.Length] = 0; //null suffix for domain socket addresses, see unix(7)
UnixSocket client = new UnixSocket ();
client.Connect (sa);
return client;
}
}
#if HAVE_CMSGCRED
/*
public struct msg
{
public IntPtr msg_next;
public long msg_type;
public ushort msg_ts;
short msg_spot;
IntPtr label;
}
*/
unsafe struct msghdr
{
public IntPtr msg_name; //optional address
public uint msg_namelen; //size of address
public IOVector *msg_iov; //scatter/gather array
public int msg_iovlen; //# elements in msg_iov
public IntPtr msg_control; //ancillary data, see below
public uint msg_controllen; //ancillary data buffer len
public int msg_flags; //flags on received message
}
struct cmsghdr
{
public uint cmsg_len; //data byte count, including header
public int cmsg_level; //originating protocol
public int cmsg_type; //protocol-specific type
}
unsafe struct cmsgcred
{
public int cmcred_pid; //PID of sending process
public uint cmcred_uid; //real UID of sending process
public uint cmcred_euid; //effective UID of sending process
public uint cmcred_gid; //real GID of sending process
public short cmcred_ngroups; //number or groups
public fixed uint cmcred_groups[16]; //groups, CMGROUP_MAX
}
struct cmsg
{
public cmsghdr hdr;
public cmsgcred cred;
}
#endif
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/UnixTransport.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.IO;
using Mono.Unix;
namespace NDesk.DBus.Transports
{
abstract class UnixTransport : Transport
{
public override void Open (AddressEntry entry)
{
string path;
bool abstr;
if (entry.Properties.TryGetValue ("path", out path))
abstr = false;
else if (entry.Properties.TryGetValue ("abstract", out path))
abstr = true;
else
throw new Exception ("No path specified for UNIX transport");
Open (path, abstr);
}
public override string AuthString ()
{
long uid = UnixUserInfo.GetRealUserId ();
return uid.ToString ();
}
public abstract void Open (string path, bool @abstract);
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NDesk-dbus/Wrapper.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using System.IO;
namespace NDesk.DBus
{
//TODO: complete and use these wrapper classes
//not sure exactly what I'm thinking but there seems to be sense here
//FIXME: signature sending/receiving is currently ambiguous in this code
//FIXME: in fact, these classes are totally broken and end up doing no-op, do not use without understanding the problem
class MethodCall
{
public Message message = new Message ();
public MethodCall (ObjectPath path, string @interface, string member, string destination, Signature signature)
{
message.Header.MessageType = MessageType.MethodCall;
message.ReplyExpected = true;
message.Header.Fields[FieldCode.Path] = path;
if (@interface != null)
message.Header.Fields[FieldCode.Interface] = @interface;
message.Header.Fields[FieldCode.Member] = member;
message.Header.Fields[FieldCode.Destination] = destination;
//TODO: consider setting Sender here for p2p situations
//this will allow us to remove the p2p hacks in MethodCall and Message
#if PROTO_REPLY_SIGNATURE
//TODO
#endif
//message.Header.Fields[FieldCode.Signature] = signature;
//use the wrapper in Message because it checks for emptiness
message.Signature = signature;
}
public MethodCall (Message message)
{
this.message = message;
Path = (ObjectPath)message.Header.Fields[FieldCode.Path];
if (message.Header.Fields.ContainsKey (FieldCode.Interface))
Interface = (string)message.Header.Fields[FieldCode.Interface];
Member = (string)message.Header.Fields[FieldCode.Member];
Destination = (string)message.Header.Fields[FieldCode.Destination];
//TODO: filled by the bus so reliable, but not the case for p2p
//so we make it optional here, but this needs some more thought
if (message.Header.Fields.ContainsKey (FieldCode.Sender))
Sender = (string)message.Header.Fields[FieldCode.Sender];
#if PROTO_REPLY_SIGNATURE
//TODO: note that an empty ReplySignature should really be treated differently to the field not existing!
if (message.Header.Fields.ContainsKey (FieldCode.ReplySignature))
ReplySignature = (Signature)message.Header.Fields[FieldCode.ReplySignature];
else
ReplySignature = Signature.Empty;
#endif
//Signature = (Signature)message.Header.Fields[FieldCode.Signature];
//use the wrapper in Message because it checks for emptiness
Signature = message.Signature;
}
public ObjectPath Path;
public string Interface;
public string Member;
public string Destination;
public string Sender;
#if PROTO_REPLY_SIGNATURE
public Signature ReplySignature;
#endif
public Signature Signature;
}
class MethodReturn
{
public Message message = new Message ();
public MethodReturn (uint reply_serial)
{
message.Header.MessageType = MessageType.MethodReturn;
message.Header.Flags = HeaderFlag.NoReplyExpected | HeaderFlag.NoAutoStart;
message.Header.Fields[FieldCode.ReplySerial] = reply_serial;
//signature optional?
//message.Header.Fields[FieldCode.Signature] = signature;
}
public MethodReturn (Message message)
{
this.message = message;
ReplySerial = (uint)message.Header.Fields[FieldCode.ReplySerial];
}
public uint ReplySerial;
}
class Error
{
public Message message = new Message ();
public Error (string error_name, uint reply_serial)
{
message.Header.MessageType = MessageType.Error;
message.Header.Flags = HeaderFlag.NoReplyExpected | HeaderFlag.NoAutoStart;
message.Header.Fields[FieldCode.ErrorName] = error_name;
message.Header.Fields[FieldCode.ReplySerial] = reply_serial;
}
public Error (Message message)
{
this.message = message;
ErrorName = (string)message.Header.Fields[FieldCode.ErrorName];
ReplySerial = (uint)message.Header.Fields[FieldCode.ReplySerial];
//Signature = (Signature)message.Header.Fields[FieldCode.Signature];
}
public string ErrorName;
public uint ReplySerial;
//public Signature Signature;
}
class Signal
{
public Message message = new Message ();
public Signal (ObjectPath path, string @interface, string member)
{
message.Header.MessageType = MessageType.Signal;
message.Header.Flags = HeaderFlag.NoReplyExpected | HeaderFlag.NoAutoStart;
message.Header.Fields[FieldCode.Path] = path;
message.Header.Fields[FieldCode.Interface] = @interface;
message.Header.Fields[FieldCode.Member] = member;
}
public Signal (Message message)
{
this.message = message;
Path = (ObjectPath)message.Header.Fields[FieldCode.Path];
Interface = (string)message.Header.Fields[FieldCode.Interface];
Member = (string)message.Header.Fields[FieldCode.Member];
if (message.Header.Fields.ContainsKey (FieldCode.Sender))
Sender = (string)message.Header.Fields[FieldCode.Sender];
}
public ObjectPath Path;
public string Interface;
public string Member;
public string Sender;
}
} |
C# | aircrack-ng/lib/csharp/MonoExample/NewStationNotify/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("NewStationNotify")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Thomas d'Otreppe")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")] |
C# | aircrack-ng/lib/csharp/MonoExample/NewStationNotify/Main.cs | // License: BSD/LGPL
// Copyright (C) 2011-2018 Thomas d'Otreppe
//
using System.Threading;
using WirelessPanda.Readers;
using WirelessPanda;
using System.Collections;
using System.Collections.Generic;
using System;
namespace NewStationNotify
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine(DateTime.Now + " - Program started");
Reader r = new UniversalReader("/home/user/dump-01.csv");
List<Station> stationList = new List<Station>();
// Read the file
r.Read();
// Add existing stations to the list
stationList.AddRange(r.Stations);
while (true) {
// Sleep 5 seconds
Thread.Sleep(5000);
Console.WriteLine(DateTime.Now + " - Checking for updates");
// Update file
r.Read();
// Get station list
foreach(Station sta in r.Stations) {
// If new station, update us
if (!stationList.Contains(sta)) {
stationList.Add(sta);
// Display it on the command line
Console.WriteLine(DateTime.Now + " - New station: " + sta.StationMAC);
// Display it as a notification
Notification.Notify(sta.BSSID, sta.StationMAC);
}
}
}
}
}
} |
aircrack-ng/lib/csharp/MonoExample/NewStationNotify/NewStationNotify.csproj | <?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{82B5448F-10AA-4BE0-9C20-DEA6441C9146}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>NewStationNotify</RootNamespace>
<AssemblyName>NewStationNotify</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
<Externalconsole>true</Externalconsole>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<DebugType>none</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
<Externalconsole>true</Externalconsole>
</PropertyGroup>
<ItemGroup>
<Reference Include="System">
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Main.cs" />
<Compile Include="AssemblyInfo.cs" />
<Compile Include="Notification.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
<ProjectReference Include="..\NDesk-dbus\NDesk-dbus.csproj">
<Project>{223B034E-A2F0-4BC7-875A-F9B5972C0670}</Project>
<Name>NDesk-dbus</Name>
</ProjectReference>
<ProjectReference Include="..\..\WirelessPanda\WirelessPanda.csproj">
<Project>{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}</Project>
<Name>WirelessPanda</Name>
</ProjectReference>
</ItemGroup>
</Project> |
|
C# | aircrack-ng/lib/csharp/MonoExample/NewStationNotify/Notification.cs | // License: BSD
// Copyright (C) 2011-2018 Thomas d'Otreppe
using System;
using System.Collections.Generic;
using NDesk.DBus;
using org.freedesktop;
namespace NewStationNotify
{
public class Notification
{
public Notification ()
{
}
/// <summary>
/// Shows a notification on the screen. This has been tested on a N900 and will probably not work with anything else but it can be used as a base.
/// </summary>
public static void Notify(String BSSID, String staMac) {
Bus bus = Bus.Session;
Notifications nf = bus.GetObject<Notifications> ("org.freedesktop.Notifications", new ObjectPath ("/org/freedesktop/Notifications"));
Dictionary<string,object> hints = new Dictionary<string,object> ();
if (string.IsNullOrEmpty(BSSID)) {
nf.Notify ("Notification", 0, "control_bluetooth_paired", "New unassociated station", staMac, new string[0], hints, 0);
} else {
nf.Notify ("Notification", 0, "control_bluetooth_paired", "New associated station", staMac + " (AP: " + BSSID + ")", new string[0], hints, 0);
}
/*
// Ugly hack for the N900 to notify the user since this can't be done with dbus-send
// because it does not support empty array.
StreamWriter sw = new StreamWriter("/home/user/notify.py");
if (string.IsNullOrEmpty(BSSID)) {
sw.WriteLine("import dbus\n" +
"bus = dbus.SessionBus()\n" +
"proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')\n" +
"interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')\n" +
"interface.Notify('Notification', 0, 'control_bluetooth_paired', 'New unassociated station', '{0}', [], {{}}, 0)", staMac);
} else {
sw.WriteLine("import dbus\n" +
"bus = dbus.SessionBus()\n" +
"proxy = bus.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications')\n" +
"interface = dbus.Interface(proxy,dbus_interface='org.freedesktop.Notifications')\n" +
"interface.Notify('Notification', 0, 'control_bluetooth_paired', 'New associated station', '{0} is associated to {1}', [], {{}}, 0)", staMac, BSSID);
}
sw.Close();
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "/usr/bin/python";
p.StartInfo.Arguments = "/home/user/notify.py";
p.Start();
p.WaitForExit();
FileInfo f = new FileInfo("/home/user/notify.py");
f.Delete();
*/
}
}
} |
C# | aircrack-ng/lib/csharp/WirelessPanda/AccessPoint.cs | // License: BSD/LGPL
// Copyright (C) 2011-2018 Thomas d'Otreppe
using System;
using System.Collections.Generic;
namespace WirelessPanda
{
public class AccessPoint : WirelessDevice, IEquatable<AccessPoint>
{
#region Properties
/// <summary>
/// Max Rate
/// </summary>
public double MaxRate
{
get
{
return (double)this.getDictValue("Max Rate");
}
set
{
this.setDictValue("Max Rate", value);
}
}
/// <summary>
/// Max Seen Rate
/// </summary>
public double MaxSeenRate
{
get
{
return (double)this.getDictValue("Max Seen Rate");
}
set
{
this.setDictValue("Max Seen Rate", value);
}
}
/// <summary>
/// Privacy
/// </summary>
public string Privacy
{
get
{
return (string)this.getDictValue("Privacy");
}
set
{
this.setDictValue("Privacy", value);
}
}
/// <summary>
/// Cipher
/// </summary>
public string Cipher
{
get
{
return (string)this.getDictValue("Cipher");
}
set
{
this.setDictValue("Cipher", value);
}
}
/// <summary>
/// Authentication
/// </summary>
public string Authentication
{
get
{
return (string)this.getDictValue("Authentication");
}
set
{
this.setDictValue("Authentication", value);
}
}
/// <summary>
/// # Data Frames
/// </summary>
public ulong DataFrames
{
get
{
return (ulong)this.getDictValue("Data");
}
set
{
this.setDictValue("Data", value);
}
}
/// <summary>
/// Beacons
/// </summary>
public long Beacons
{
get
{
return (long)this.getDictValue("Beacons");
}
set
{
this.setDictValue("Beacons", value);
}
}
/// <summary>
/// IP Address
/// </summary>
public string IP
{
get
{
return (string)this.getDictValue("IP");
}
set
{
this.setDictValue("IP", value);
}
}
/// <summary>
/// IP Type
/// </summary>
public int IPType
{
get
{
return (int)this.getDictValue("IP Type");
}
set
{
this.setDictValue("IP Type", value);
}
}
/// <summary>
/// ESSID
/// </summary>
public string ESSID
{
get
{
return (string)this.getDictValue("ESSID");
}
set
{
this.setDictValue("ESSID", value);
}
}
/// <summary>
/// ESSID Length
/// </summary>
public byte ESSIDLength
{
get
{
return (byte)this.getDictValue("ESSID Length");
}
set
{
this.setDictValue("ESSID Length", value);
}
}
/// <summary>
/// Key
/// </summary>
public string Key
{
get
{
return (string)this.getDictValue("Key");
}
set
{
this.setDictValue("Key", value);
}
}
/// <summary>
/// Network Type
/// </summary>
public string NetworkType
{
get
{
return (string)this.getDictValue("Network Type");
}
set
{
this.setDictValue("Network Type", value);
}
}
/// <summary>
/// Info
/// </summary>
public string Info
{
get
{
return (string)this.getDictValue("Info");
}
set
{
this.setDictValue("Info", value);
}
}
/// <summary>
/// Encoding
/// </summary>
public string Encoding
{
get
{
return (string)this.getDictValue("Encoding");
}
set
{
this.setDictValue("Encoding", value);
}
}
/// <summary>
/// Cloaked ?
/// </summary>
public bool Cloaked
{
get
{
return (bool)this.getDictValue("Cloaked");
}
set
{
this.setDictValue("Cloaked", value);
}
}
/// <summary>
/// Encryption
/// </summary>
public string Encryption
{
get
{
return (string)this.getDictValue("Encryption");
}
set
{
this.setDictValue("Encryption", value);
}
}
/// <summary>
/// Is the traffic decrypted?
/// </summary>
public bool Decrypted
{
get
{
return (bool)this.getDictValue("Decrypted");
}
set
{
this.setDictValue("Decrypted", value);
}
}
/// <summary>
/// # Beacon Frames
/// </summary>
public ulong Beacon
{
get
{
return (ulong)this.getDictValue("Beacon");
}
set
{
this.setDictValue("Beacon", value);
}
}
/// <summary>
/// # LLC Frames
/// </summary>
public ulong LLC
{
get
{
return (ulong)this.getDictValue("LLC");
}
set
{
this.setDictValue("LLC", value);
}
}
/// <summary>
/// # Crypt Frames
/// </summary>
public ulong Crypt
{
get
{
return (ulong)this.getDictValue("Crypt");
}
set
{
this.setDictValue("Crypt", value);
}
}
/// <summary>
/// # Weak Frames
/// </summary>
public ulong Weak
{
get
{
return (ulong)this.getDictValue("Weak");
}
set
{
this.setDictValue("Weak", value);
}
}
/// <summary>
/// Total Nb of Frames
/// </summary>
public ulong Total
{
get
{
return (ulong)this.getDictValue("Total");
}
set
{
this.setDictValue("Total", value);
}
}
/// <summary>
/// Carrier
/// </summary>
public string Carrier
{
get
{
return (string)this.getDictValue("Carrier");
}
set
{
this.setDictValue("Carrier", value);
}
}
/// <summary>
/// Best Quality
/// </summary>
public int BestQuality
{
get
{
return (int)this.getDictValue("BestQuality");
}
set
{
this.setDictValue("BestQuality", value);
}
}
/// <summary>
/// Best Signal
/// </summary>
public int BestSignal
{
get
{
return (int)this.getDictValue("Best Signal");
}
set
{
this.setDictValue("Best Signal", value);
}
}
/// <summary>
/// Best Noise
/// </summary>
public int BestNoise
{
get
{
return (int)this.getDictValue("Best Noise");
}
set
{
this.setDictValue("Best Noise", value);
}
}
/// <summary>
/// Min Location
/// </summary>
public Coordinates MinLocation
{
get
{
return (Coordinates)this.getDictValue("Min Location");
}
set
{
this.setDictValue("Min Location", value);
}
}
/// <summary>
/// Best Location
/// </summary>
public Coordinates BestLocation
{
get
{
return (Coordinates)this.getDictValue("Best Location");
}
set
{
this.setDictValue("Best Location", value);
}
}
/// <summary>
/// Max Location
/// </summary>
public Coordinates MaxLocation
{
get
{
return (Coordinates)this.getDictValue("Max Location");
}
set
{
this.setDictValue("Max Location", value);
}
}
/// <summary>
/// Data Size
/// </summary>
public ulong DataSize
{
get
{
return (ulong)this.getDictValue("Data Size");
}
set
{
this.setDictValue("Data Size", value);
}
}
#endregion
/// <summary>
/// Internal list of client
/// </summary>
private List<Station> _clientList = new List<Station>();
/// <summary>
/// Add a client to our list
/// </summary>
/// <param name="sta"></param>
public void addClient(Station sta)
{
this._clientList.Add(sta);
sta.AP = this;
}
/// <summary>
/// Returns the client list
/// </summary>
public List<Station> ClientList
{
get
{
return this._clientList;
}
}
/// <summary>
/// Implements IEquatable
/// </summary>
/// <param name="other">Other AccessPoint to compare to</param>
/// <returns>true if equals, false if not</returns>
public bool Equals(AccessPoint other)
{
try
{
if (this.BSSID == other.BSSID)
{
return true;
}
}
catch { }
return false;
}
}
} |
C# | aircrack-ng/lib/csharp/WirelessPanda/Coordinates.cs | // License: BSD/LGPL
// Copyright (C) 2011-2018 Thomas d'Otreppe
using System;
using System.Collections;
using System.Text;
namespace WirelessPanda
{
public class Coordinates
{
#region Dictionary stuff
private Hashtable _dictionary = new Hashtable();
private void setDictValue(string elem, double value)
{
if (this._dictionary.ContainsKey(elem))
{
this._dictionary.Remove(elem);
}
this._dictionary.Add(elem, value);
}
private double getDictValue(string elem)
{
if (this._dictionary.ContainsKey(elem))
{
return (double)this._dictionary[elem];
}
throw new MissingFieldException("Value <" + elem + "> is not set or does not exist");
}
#endregion
#region Properties
/// <summary>
/// Latitude
/// </summary>
public double Latitude
{
get
{
return this.getDictValue("Latitude");
}
set
{
this.setDictValue("Latitude", value);
}
}
/// <summary>
/// Longitude
/// </summary>
public double Longitude
{
get
{
return this.getDictValue("Longitude");
}
set
{
this.setDictValue("Longitude", value);
}
}
/// <summary>
/// Altitude (in meters)
/// </summary>
public double Altitude
{
get
{
return this.getDictValue("Altitude");
}
set
{
this.setDictValue("Altitude", value);
}
}
/// <summary>
/// Speed (UOM: probably knot but unsure)
/// </summary>
public double Speed
{
get
{
return this.getDictValue("Speed");
}
set
{
this.setDictValue("Speed", value);
}
}
#endregion
public Coordinates(string latitude = null, string longitude = null, string altitude = null, string speed = null)
{
if (!string.IsNullOrEmpty(latitude))
{
this.Latitude = double.Parse(latitude);
}
if (!string.IsNullOrEmpty(longitude))
{
this.Longitude = double.Parse(longitude);
}
if (!string.IsNullOrEmpty(altitude))
{
this.Altitude = double.Parse(altitude);
}
if (!string.IsNullOrEmpty(speed))
{
this.Speed = double.Parse(speed);
}
}
public Coordinates(double latitude, double longitude)
{
this.Latitude = latitude;
}
public Coordinates(double latitude, double longitude, double altitude) : this(latitude, longitude)
{
this.Altitude = latitude;
}
public Coordinates(double latitude, double longitude, double altitude, double speed) : this(latitude, longitude, altitude)
{
this.Speed = speed;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
try
{
sb.Append(this.Latitude);
sb.Append(", ");
sb.Append(this.Longitude);
if (this._dictionary.ContainsKey("Altitude"))
{
sb.Append(" - Altitude: ");
sb.Append(this.Altitude);
}
if (this._dictionary.ContainsKey("Speed"))
{
sb.Append(" - Speed: ");
sb.Append(this.Speed);
}
}
catch
{
if (sb.Length > 0)
{
sb.Remove(0, sb.Length);
}
}
return sb.ToString();
}
}
} |
C# | aircrack-ng/lib/csharp/WirelessPanda/Station.cs | // License: BSD/LGPL
// Copyright (C) 2011-2018 Thomas d'Otreppe
using System;
using System.Collections.Generic;
using System.Text;
namespace WirelessPanda
{
public class Station : WirelessDevice, IEquatable<Station>
{
private AccessPoint _ap = null;
/// <summary>
/// Access point
/// </summary>
public AccessPoint AP
{
get
{
return this._ap;
}
// Only allow to do it inside the lib
internal set
{
this._ap = value;
}
}
/// <summary>
/// Station MAC
/// </summary>
public string StationMAC
{
get
{
return (string)this.getDictValue("Station MAC");
}
set
{
if (value != null)
{
this.setDictValue("Station MAC", value.Trim());
}
else
{
this.setDictValue("Station MAC", value);
}
}
}
/// <summary>
/// # Packets
/// </summary>
public ulong NbPackets
{
get
{
return (ulong)this.getDictValue("# Packets");
}
set
{
this.setDictValue("# Packets", value);
}
}
/// <summary>
/// Probed ESSIDs (comma separated)
/// </summary>
public string ProbedESSIDs
{
get
{
return (string)this.getDictValue("Probed ESSIDs");
}
set
{
this.setDictValue("Probed ESSIDs", value);
// Update probe ESSID list
this._probedESSIDsList.Clear();
if (string.IsNullOrEmpty(value))
{
foreach (string s in value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
if (string.IsNullOrEmpty(s.Trim()))
{
continue;
}
// Add ESSID
this._probedESSIDsList.Add(s);
}
}
}
}
private List<string> _probedESSIDsList = new List<string>();
/// <summary>
/// Probed ESSIDs List
/// </summary>
public string[] ProbedESSIDsList
{
get
{
return _probedESSIDsList.ToArray().Clone() as string[];
}
set
{
this._probedESSIDsList.Clear();
this.setDictValue("Probed ESSIDs", string.Empty);
if (value != null && value.Length > 0)
{
this._probedESSIDsList.AddRange(value);
// Generate the string list of SSID
StringBuilder sb = new StringBuilder(string.Empty);
foreach (string s in value)
{
sb.AppendFormat("{0}, ", s);
}
string res = sb.ToString();
if (res.Length > 0)
{
res = res.Substring(0, res.Length - 2);
}
// And put it in the Probed ESSIDs dictionary item
this.setDictValue("Probed ESSIDs", res);
}
}
}
/// <summary>
/// Implements IEquatable
/// </summary>
/// <param name="other">Other Station to compare to</param>
/// <returns>true if equals, false if not</returns>
public bool Equals(Station other)
{
try
{
if (this.StationMAC == other.StationMAC)
{
return true;
}
}
catch { }
return false;
}
}
} |
C# | aircrack-ng/lib/csharp/WirelessPanda/WirelessDevice.cs | // License: BSD/LGPL
// Copyright (C) 2011-2018 Thomas d'Otreppe
using System;
using System.Collections;
namespace WirelessPanda
{
public abstract class WirelessDevice
{
#region Dictionary stuff
/// <summary>
/// Keep track of the last position for the column
/// </summary>
private int _lastPosition = 0;
/// <summary>
/// Dictionary containing all values
/// </summary>
protected Hashtable _fieldsDictionary = new Hashtable();
/// <summary>
/// Order of the columns
/// </summary>
protected Hashtable _fieldsOrder = new Hashtable();
/// <summary>
/// Sets a value in the dictionary
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
protected void setDictValue(string key, object value)
{
if (this._fieldsDictionary.ContainsKey(key))
{
this._fieldsDictionary.Remove(key);
}
else
{
// Save the position for the column (useful when creating the dataset)
this._fieldsOrder.Add(this._lastPosition++, key);
}
this._fieldsDictionary.Add(key, value);
}
/// <summary>
/// Return a value in the dictionary
/// </summary>
/// <param name="key">Key</param>
/// <returns>Object value</returns>
/// <exception cref="MissingFieldException"></exception>
protected object getDictValue(string key)
{
if (this._fieldsDictionary.ContainsKey(key))
{
return this._fieldsDictionary[key];
}
throw new MissingFieldException("Value for <" + key + "> is not set or does not exist");
}
/// <summary>
/// Returns a copy of the dictionary
/// </summary>
internal Hashtable FieldsDictionary
{
get
{
return this._fieldsDictionary as Hashtable;
}
}
/// <summary>
/// Returns a copy of the column order
/// </summary>
internal Hashtable FieldsOrder
{
get
{
return this._fieldsOrder as Hashtable;
}
}
#endregion
#region Properties
public string BSSID
{
get
{
return (string)this.getDictValue("BSSID");
}
set
{
this.setDictValue("BSSID", value);
if (value != null)
{
// Special case, not associated
if (value.Trim() == "(not associated)")
{
this.setDictValue("BSSID", string.Empty);
}
else
{
this.setDictValue("BSSID", value.Trim());
}
}
}
}
public DateTime FirstTimeSeen
{
get
{
return (DateTime)this.getDictValue("First Time Seen");
}
set
{
this.setDictValue("First Time Seen", value);
}
}
public DateTime LastTimeSeen
{
get
{
return (DateTime)this.getDictValue("Last Time Seen");
}
set
{
this.setDictValue("Last Time Seen", value);
}
}
public int Channel
{
get
{
return (int)this.getDictValue("Channel");
}
set
{
this.setDictValue("Channel", value);
}
}
public ulong TotalFrames
{
get
{
return (ulong)this.getDictValue("Total Frames");
}
set
{
this.setDictValue("Total Frames", value);
}
}
public Coordinates Location
{
get
{
return (Coordinates)this.getDictValue("Location");
}
set
{
this.setDictValue("Location", value);
}
}
public int Power
{
get
{
return (int)this.getDictValue("Power");
}
set
{
this.setDictValue("Power", value);
}
}
#endregion
}
} |
aircrack-ng/lib/csharp/WirelessPanda/WirelessPanda.csproj | <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>WirelessPanda</RootNamespace>
<AssemblyName>WirelessPanda</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AccessPoint.cs" />
<Compile Include="Coordinates.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Readers\csvReader.cs" />
<Compile Include="Readers\kismetCsvReader.cs" />
<Compile Include="Readers\NetXMLReader.cs" />
<Compile Include="Readers\Reader.cs" />
<Compile Include="Readers\UniversalReader.cs" />
<Compile Include="Station.cs" />
<Compile Include="WirelessDevice.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> |
|
aircrack-ng/lib/csharp/WirelessPanda/WirelessPanda.Mono.csproj | <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{F3A06E01-20E6-4CF8-AD62-1034A0B4EAE3}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>WirelessPanda</RootNamespace>
<AssemblyName>WirelessPanda</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System">
</Reference>
<Reference Include="System.Data">
</Reference>
<Reference Include="System.Xml">
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="AccessPoint.cs" />
<Compile Include="Coordinates.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Readers\csvReader.cs" />
<Compile Include="Readers\kismetCsvReader.cs" />
<Compile Include="Readers\NetXMLReader.cs" />
<Compile Include="Readers\Reader.cs" />
<Compile Include="Readers\UniversalReader.cs" />
<Compile Include="Station.cs" />
<Compile Include="WirelessDevice.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> |
|
C# | aircrack-ng/lib/csharp/WirelessPanda/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WirelessPanda")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Aircrack-ng")]
[assembly: AssemblyProduct("WirelessPanda")]
[assembly: AssemblyCopyright("Copyright © Aircrack-ng team 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("17562500-6dc8-4460-a427-440ea5f27f26")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] |
C# | aircrack-ng/lib/csharp/WirelessPanda/Readers/csvReader.cs | // License: BSD/LGPL
// Copyright (C) 2011-2018 Thomas d'Otreppe
using System;
using System.Collections.Generic;
namespace WirelessPanda.Readers
{
public class CsvReader : Reader
{
/// <summary>
/// Date format (Same format for 0.x and 1.x)
/// </summary>
protected override string DATE_FORMAT
{
get
{
return "yyyy-MM-dd HH:mm:ss";
}
}
public enum CSVFileFormat
{
v0X,
v1X,
Unknown
}
/// <summary>
/// Get the file format
/// </summary>
public CSVFileFormat FileFormat
{
get
{
return this._fileFormat;
}
}
private CSVFileFormat _fileFormat = CSVFileFormat.Unknown;
/// <summary>
/// Reader type
/// </summary>
public override string ReaderType
{
get
{
return "Airodump-ng CSV";
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="filename">Filename (doesn't need to exist now but MUST when using Read() )</param>
public CsvReader(string filename) : base(filename) { }
/// <summary>
/// Read/Update the content of the file
/// </summary>
/// <returns>true if successful</returns>
/// <exception cref="FormatException">Airodump-ng CSV format unknown</exception>
public override bool Read()
{
// Reset parsing status
this.ParseSuccess = false;
// Get the content of the file
string[] content = this.getStrippedFileContent();
// Get file format
this._fileFormat = this.getFormat(content);
if (this._fileFormat == CSVFileFormat.Unknown)
{
throw new FormatException("Airodump-ng CSV format unknown");
}
// Parse AP ...
int i = 2; // Start at line 3 (skipping header)
for (; i < content.Length && !string.IsNullOrEmpty(content[i]); i++)
{
string [] split = content[i].Split(',');
switch (this._fileFormat)
{
case CSVFileFormat.v0X:
if (split.Length < 11)
{
continue;
}
break;
case CSVFileFormat.v1X:
if (split.Length < 15)
{
continue;
}
break;
}
AccessPoint ap = new AccessPoint();
ap.BSSID = split[0].Trim();
ap.FirstTimeSeen = this.parseDateTime(split[1]);
ap.LastTimeSeen = this.parseDateTime(split[2]);
ap.Channel = int.Parse(split[3].Trim());
ap.MaxRate = double.Parse(split[4].Trim());
ap.Privacy = split[5].Trim();
switch (this._fileFormat)
{
case CSVFileFormat.v0X:
ap.Power = int.Parse(split[6].Trim());
ap.Beacons = long.Parse(split[7].Trim());
ap.DataFrames = ulong.Parse(split[8].Trim());
ap.IP = split[9].Replace(" ", "");
ap.ESSID = split[10].Substring(1); // TODO: Improve it because it may contain a ','
ap.ESSIDLength = (byte)ap.ESSID.Length;
break;
case CSVFileFormat.v1X:
ap.Cipher = split[6].Trim();
ap.Authentication = split[7].Trim();
ap.Power = int.Parse(split[8].Trim());
ap.Beacons = long.Parse(split[9].Trim());
ap.DataFrames = ulong.Parse(split[10].Trim());
ap.IP = split[11].Replace(" ", "");
ap.ESSIDLength = byte.Parse(split[12].Trim());
ap.ESSID = split[13].Substring(1); // TODO: Improve it because it may contain a ','
ap.Key = split[14];
break;
}
// Add AP to the list
this.addAccessPoint(ap);
}
// ... Parse stations
i += 2; // Skip station header
for (; i < content.Length && !string.IsNullOrEmpty(content[i]); i++)
{
string[] split = content[i].Split(',');
// Skip to the next if not long enough
if (split.Length < 6)
{
continue;
}
// Parse station information
Station sta = new Station();
sta.StationMAC = split[0].Trim();
sta.FirstTimeSeen = this.parseDateTime(split[1]);
sta.LastTimeSeen = this.parseDateTime(split[2]);
sta.Power = int.Parse(split[3].Trim());
sta.NbPackets = ulong.Parse(split[4].Trim());
sta.BSSID = split[5].Trim();
// Get probed ESSID list
if (split.Length > 6 && split[6] != "")
{
List<string> list = new List<string>();
for (int j = 6; j < split.Length; j++)
{
// There's always a whitespace character before
list.Add(split[j].Substring(1));
}
sta.ProbedESSIDsList = list.ToArray();
}
else
{
sta.ProbedESSIDs = string.Empty;
}
// Add station to the list
this.addStation(sta);
}
// Link them together
this.LinkAPClients();
// Parsing was successful
this.ParseSuccess = true;
return this.ParseSuccess;
}
/// <summary>
/// Returns the format of the file
/// </summary>
/// <param name="content">File content</param>
/// <returns>CSV File Format</returns>
/// <exception cref="ArgumentNullException">content is null</exception>
/// <exception cref="ArgumentException">content is empty</exception>
private CSVFileFormat getFormat(string[] content)
{
// Checks
if (content == null)
{
throw new ArgumentNullException("Cannot determine format without any content");
}
if (content.Length == 1 && string.IsNullOrEmpty(content[0]))
{
throw new ArgumentException("Cannot determine format without any content");
}
// First line is empty and the second line contains the header
if (content.Length > 2 && string.IsNullOrEmpty(content[0]))
{
// Version 1.x
if (content[1] == "BSSID, First time seen, Last time seen, channel, Speed, Privacy, Cipher, Authentication, Power, # beacons, # IV, LAN IP, ID-length, ESSID, Key")
{
return CSVFileFormat.v1X;
}
// Version 0.x
if (content[1] == "BSSID, First time seen, Last time seen, Channel, Speed, Privacy, Power, # beacons, # data, LAN IP, ESSID")
{
return CSVFileFormat.v0X;
}
}
return CSVFileFormat.Unknown;
}
}
} |
C# | aircrack-ng/lib/csharp/WirelessPanda/Readers/kismetCsvReader.cs | // License: BSD/LGPL
// Copyright (C) 2011-2018 Thomas d'Otreppe
using System;
namespace WirelessPanda.Readers
{
public class KismetCsvReader : Reader
{
/// <summary>
/// Date format (Same format for Kismet CSV and NetXML)
/// </summary>
protected override string DATE_FORMAT
{
get
{
return "ddd MMM dd HH:mm:ss yyyy";
}
}
/// <summary>
/// Date format (Same format for Kismet CSV and NetXML)
/// </summary>
protected override string ALT_DATE_FORMAT
{
get
{
return "ddd MMM d HH:mm:ss yyyy";
}
}
/// <summary>
/// Reader type
/// </summary>
public override string ReaderType
{
get
{
return "Kismet CSV";
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="filename">Filename (doesn't need to exist now but MUST when using Read() )</param>
public KismetCsvReader(string filename) : base(filename) { }
/// <summary>
/// Read/Update the content of the file
/// </summary>
/// <returns>true if successful</returns>
/// <exception cref="FormatException">Airodump-ng CSV format unknown</exception>
public override bool Read()
{
// Reset parsing status
this.ParseSuccess = false;
// Get the content of the file
string[] content = this.getStrippedFileContent();
// Check if this is really a kismet CSV file
if (content.Length == 0)
{
throw new FormatException("Empty file");
}
this.ParseSuccess = (content[0] == "Network;NetType;ESSID;BSSID;Info;Channel;Cloaked;Encryption;Decrypted;MaxRate;MaxSeenRate;Beacon;LLC;Data;Crypt;Weak;Total;Carrier;Encoding;FirstTime;LastTime;BestQuality;BestSignal;BestNoise;GPSMinLat;GPSMinLon;GPSMinAlt;GPSMinSpd;GPSMaxLat;GPSMaxLon;GPSMaxAlt;GPSMaxSpd;GPSBestLat;GPSBestLon;GPSBestAlt;DataSize;IPType;IP;");
if (!this.ParseSuccess)
{
throw new FormatException("Not a Kismet CSV file");
}
// Parse content
for (int i = 1; i < content.Length && !string.IsNullOrEmpty(content[i]); i++)
{
string [] split = content[i].Split(';');
// Check if there are enough elements
if (split.Length < 39)
{
continue;
}
AccessPoint ap = new AccessPoint();
// Skip first element which is the network number (if someone cares about it, email me)
ap.NetworkType = split[1].Trim();
ap.ESSID = split[2].Trim();
ap.ESSIDLength = (byte)split[2].Length;
ap.BSSID = split[3].Trim();
ap.Info = split[4].Trim();
ap.Channel = int.Parse(split[5]);
ap.Cloaked = (split[6].Trim().ToLower() == "yes");
ap.Encryption = split[7].Trim();
ap.Decrypted = (split[8].Trim().ToLower() == "yes");
ap.MaxRate = double.Parse(split[9]);
ap.MaxSeenRate = double.Parse(split[10]);
ap.Beacon = ulong.Parse(split[11]);
ap.LLC = ulong.Parse(split[12]);
ap.DataFrames = ulong.Parse(split[13]);
ap.Crypt = ulong.Parse(split[14]);
ap.Weak = ulong.Parse(split[15]);
ap.Total = ulong.Parse(split[16]);
ap.Carrier = split[17].Trim();
ap.Encoding = split[18].Trim();
ap.FirstTimeSeen = this.parseDateTime(split[19]);
ap.LastTimeSeen = this.parseDateTime(split[20]);
ap.BestQuality = int.Parse(split[21]);
ap.BestSignal = int.Parse(split[22]);
ap.BestNoise = int.Parse(split[23]);
ap.MinLocation = new Coordinates(split[24], split[25], split[26], split[27]);
ap.MaxLocation = new Coordinates(split[28], split[29], split[30], split[31]);
ap.BestLocation = new Coordinates(split[32], split[33], split[34], "");
ap.DataSize = ulong.Parse(split[35]);
ap.IPType = int.Parse(split[36]);
ap.IP = split[37].Replace(" ", "");
this.addAccessPoint(ap);
}
// No need to link stations and access points together since there are only access points.
return true;
}
}
} |
C# | aircrack-ng/lib/csharp/WirelessPanda/Readers/NetXMLReader.cs | using System;
namespace WirelessPanda.Readers
{
// See http://msdn.microsoft.com/en-us/library/cc189056(v=vs.95).aspx
public class NetXMLReader : Reader
{
/// <summary>
/// Date format (Same format for Kismet CSV and NetXML)
/// </summary>
protected override string DATE_FORMAT
{
get
{
return "ddd MMM dd HH:mm:ss yyyy";
}
}
/// <summary>
/// Date format (Same format for Kismet CSV and NetXML)
/// </summary>
protected override string ALT_DATE_FORMAT
{
get
{
return "ddd MMM d HH:mm:ss yyyy";
}
}
/// <summary>
/// Reader type
/// </summary>
public override string ReaderType
{
get
{
return "Kismet NetXML";
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="filename">Filename (doesn't need to exist now but MUST when using Read() )</param>
public NetXMLReader(string filename) : base(filename)
{
throw new NotImplementedException("NetXML parser not implemented yet");
}
}
} |
C# | aircrack-ng/lib/csharp/WirelessPanda/Readers/Reader.cs | // License: BSD/LGPL
// Copyright (C) 2011-2018 Thomas d'Otreppe
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
namespace WirelessPanda.Readers
{
public class Reader
{
public const string ACCESSPOINTS_DATATABLE = "Access Points";
public const string STATIONS_DATATABLE = "Stations";
#region Private members
private DataSet _dataset = new DataSet();
private List<AccessPoint> _accessPoints = new List<AccessPoint>();
private List<Station> _stations = new List<Station>();
private string _filename = string.Empty;
private bool _parseSuccess = false;
#endregion
#region Properties
/// <summary>
/// Returns true if the file exist
/// </summary>
public bool FileExist
{
get
{
return File.Exists(this._filename);
}
}
/// <summary>
/// DataSet containing 2 tables: "Access Points" and "Stations"
/// </summary>
public virtual DataSet Dataset
{
get
{
return this._dataset;
}
}
/// <summary>
/// Was the file parsed successfully?
/// </summary>
public bool ParseSuccess
{
get
{
return this._parseSuccess;
}
protected set
{
this._parseSuccess = value;
}
}
/// <summary>
/// Array of access points
/// </summary>
public virtual AccessPoint[] AccessPoints
{
get
{
return this._accessPoints.ToArray().Clone() as AccessPoint[];
}
}
/// <summary>
/// Array of stations
/// </summary>
public virtual Station[] Stations
{
get
{
return this._stations.ToArray().Clone() as Station[];
}
}
/// <summary>
/// Filename
/// </summary>
public string Filename
{
get
{
return this._filename;
}
}
/// <summary>
/// Reader type
/// </summary>
public virtual string ReaderType
{
get
{
return "Unknown";
}
}
/// <summary>
/// Reader type
/// </summary>
protected virtual string DATE_FORMAT
{
get
{
return null;
}
}
/// <summary>
/// Reader type
/// </summary>
protected virtual string ALT_DATE_FORMAT
{
get
{
return null;
}
}
#endregion
/// <summary>
/// Constructor
/// </summary>
/// <param name="filename">Filename (doesn't need to exist now but MUST when using Read() )</param>
public Reader(string filename)
{
if (string.IsNullOrEmpty(filename))
{
throw new FileNotFoundException("Filename cannot be null or empty");
}
this._filename = filename;
}
protected void Clear()
{
// Clear all the values and re-create datatables
this._dataset.Tables.Clear();
this._accessPoints.Clear();
this._stations.Clear();
this._parseSuccess = false;
}
/// <summary>
/// Open the file and returns its content
/// </summary>
/// <returns></returns>
/// <exception cref="FileNotFoundException">File does not exist</exception>
/// <exception cref="Exception">Fails to open file</exception>
protected string[] getStrippedFileContent()
{
if (string.IsNullOrEmpty(this.Filename))
{
throw new FileNotFoundException("Filename cannot be null or empty");
}
FileInfo f = new FileInfo(this.Filename);
if (!f.Exists)
{
throw new FileNotFoundException("File <" + this.Filename + "> does not exist");
}
// Returns an array with one empty string
if (f.Length == 0)
{
return new string[] { string.Empty };
}
StreamReader sr = null;
// Open the file
try
{
sr = f.OpenText();
}
catch (Exception e)
{
throw new Exception("Failed to open <" + this.Filename + ">", e);
}
List<string> lines = new List<string>();
// Read the file
try
{
while (!sr.EndOfStream)
{
lines.Add(sr.ReadLine().Trim());
}
}
catch { /* Done or failure so stop */}
// Close file
try
{
sr.Close();
}
catch { }
return lines.ToArray();
}
/// <summary>
/// Read/Update the content of the file
/// </summary>
/// <returns>true if successful</returns>
public virtual bool Read() { return this.ParseSuccess; }
/// <summary>
/// Generate the columns for the DataTable from the Hashtable (and in a specific order if needed)
/// </summary>
/// <param name="ht"></param>
/// <returns></returns>
private DataColumn[] getColumnsFromHashtable(Hashtable ht, Hashtable order)
{
List<DataColumn> columnList = new List<DataColumn>();
if (ht != null)
{
if (order == null)
{
// No specific order but that's not going to happen
foreach (string key in ht.Keys)
{
Type t = ht[key].GetType();
columnList.Add(new DataColumn(key, t));
}
}
else
{
for (int i = 0; i < order.Count; i++)
{
Type t = ht[(string)order[i]].GetType();
columnList.Add(new DataColumn((string)order[i], t));
}
}
}
return columnList.ToArray();
}
/// <summary>
/// Add a station to the list
/// </summary>
/// <param name="s">Station</param>
/// <returns></returns>
protected bool addStation(Station s)
{
if (s == null)
{
return false;
}
// Create DataTable if needed
if (!this._dataset.Tables.Contains(STATIONS_DATATABLE))
{
// Create Stations DataTable
DataTable dtStations = new DataTable(STATIONS_DATATABLE);
dtStations.CaseSensitive = true;
// Create columns
dtStations.Columns.AddRange(this.getColumnsFromHashtable(s.FieldsDictionary, s.FieldsOrder));
// And add it to the dataset
this._dataset.Tables.Add(dtStations);
}
// Add row
DataRow dr = this._dataset.Tables[STATIONS_DATATABLE].NewRow();
// Set value for each field
foreach (string key in s.FieldsDictionary.Keys)
{
dr[key] = s.FieldsDictionary[key];
}
// Add row
this._dataset.Tables[STATIONS_DATATABLE].Rows.Add(dr);
// Add station to the list
this._stations.Add(s);
return true;
}
/// <summary>
/// Link clients to their associated AP
/// </summary>
protected void LinkAPClients()
{
foreach (Station s in this._stations)
{
if (string.IsNullOrEmpty(s.BSSID))
{
continue;
}
foreach (AccessPoint ap in this._accessPoints)
{
if (ap.BSSID == s.BSSID)
{
ap.addClient(s);
break;
}
}
}
//this._dataset.Tables[ACCESSPOINTS_DATATABLE].ChildRelations.Add(new DataRelation("Cients", this._dataset.Tables[ACCESSPOINTS_DATATABLE].Columns["BSSID"], this._dataset.Tables[STATIONS_DATATABLE].Columns["BSSID"]));
//this._dataset.Tables[STATIONS_DATATABLE].ParentRelations.Add(new DataRelation("Associated AP", this._dataset.Tables[ACCESSPOINTS_DATATABLE].Columns["BSSID"], this._dataset.Tables[STATIONS_DATATABLE].Columns["BSSID"]));
}
/// <summary>
/// Add Access Point to the list
/// </summary>
/// <param name="ap">Access Point</param>
/// <returns></returns>
protected bool addAccessPoint(AccessPoint ap)
{
if (ap == null)
{
return false;
}
// Create DataTable if needed
if (!this._dataset.Tables.Contains(ACCESSPOINTS_DATATABLE))
{
// Create Access Points DataTable
DataTable dtAPs = new DataTable(ACCESSPOINTS_DATATABLE);
dtAPs.CaseSensitive = true;
// Create columns
dtAPs.Columns.AddRange(this.getColumnsFromHashtable(ap.FieldsDictionary, ap.FieldsOrder));
this._dataset.Tables.Add(dtAPs);
}
// Add row
DataRow dr = this._dataset.Tables[ACCESSPOINTS_DATATABLE].NewRow();
foreach (string key in ap.FieldsDictionary.Keys)
{
dr[key] = ap.FieldsDictionary[key];
}
// Add row
this._dataset.Tables[ACCESSPOINTS_DATATABLE].Rows.Add(dr);
// Add the Access Point to the list
this._accessPoints.Add(ap);
return true;
}
/// <summary>
/// Return the type of the file (and obviously, also the "name" of the reader to use
/// </summary>
/// <param name="path">Path to the file</param>
/// <returns>Null if type is unknown or a string with the type</returns>
public static string getFileType(string path)
{
Reader r = new CsvReader(path);
try
{
r.Read();
}
catch
{
r = new KismetCsvReader(path);
try
{
r.Read();
}
catch
{
r = new NetXMLReader(path);
try
{
r.Read();
}
catch { }
}
}
if (!r.ParseSuccess)
{
return null;
}
return r.ReaderType;
}
/// <summary>
/// Parse a string containing the date and time
/// </summary>
/// <param name="s">Date string</param>
/// <returns>DateTime value</returns>
/// <exception cref="ArgumentNullException">Date/Time string cannot be null or empty</exception>
/// <exception cref="FormatException">Date Format is not set</exception>
protected DateTime parseDateTime(string s)
{
if (string.IsNullOrEmpty(this.DATE_FORMAT))
{
throw new FormatException("Date Format is not set");
}
if (string.IsNullOrEmpty(s))
{
throw new ArgumentNullException("Date/Time string cannot be null or empty");
}
// Parse it
DateTime ret = new DateTime();
try
{
ret = DateTime.ParseExact(s.Trim(), DATE_FORMAT, null);
}
catch
{
ret = DateTime.ParseExact(s.Trim(), ALT_DATE_FORMAT, null);
}
return ret;
}
}
} |
C# | aircrack-ng/lib/csharp/WirelessPanda/Readers/UniversalReader.cs | // License: BSD/LGPL
// Copyright (C) 2011-2018 Thomas d'Otreppe
using System;
using System.Data;
namespace WirelessPanda.Readers
{
public class UniversalReader : Reader
{
/// <summary>
/// Reader
/// </summary>
private Reader _reader = null;
/// <summary>
/// File type
/// </summary>
/// <remarks>So that we have to check it only once</remarks>
private string _fileType = string.Empty;
#region Properties
/// <summary>
/// DataSet containing 2 tables: "Access Points" and "Stations"
/// </summary>
public override DataSet Dataset
{
get
{
return this._reader.Dataset;
}
}
/// <summary>
/// Array of access points
/// </summary>
public override AccessPoint[] AccessPoints
{
get
{
return this._reader.AccessPoints;
}
}
/// <summary>
/// Array of stations
/// </summary>
public override Station[] Stations
{
get
{
return this._reader.Stations;
}
}
/// <summary>
/// Reader type
/// </summary>
public override string ReaderType
{
get
{
return "Universal: Airodump-ng CSV, Kismet CSV, Kismet NetXML";
}
}
#endregion
/// <summary>
/// Constructor
/// </summary>
/// <param name="filename">Filename (doesn't need to exist now but MUST when using Read() )</param>
public UniversalReader(string filename) : base(filename) { }
/// <summary>
/// Read/Update the content of the file
/// </summary>
/// <returns>true if successful</returns>
public override bool Read()
{
this.ParseSuccess = false;
if (string.IsNullOrEmpty(this._fileType))
{
this._fileType = Reader.getFileType(this.Filename);
}
switch (this._fileType)
{
case "Airodump-ng CSV":
this._reader = new CsvReader(this.Filename);
break;
case "Kismet CSV":
this._reader = new KismetCsvReader(this.Filename);
break;
case "Kismet NetXML":
this._reader = new NetXMLReader(this.Filename);
break;
default:
throw new FormatException("Unknown file format, can't parse");
break;
}
this.ParseSuccess = this._reader.Read();
return this.ParseSuccess;
}
}
} |
C | aircrack-ng/lib/libac/adt/avl_tree.c | /**
* collectd - src/utils_avltree.c
* Copyright (C) 2006,2007 Florian octo Forster
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Authors:
* Florian octo Forster <octo at collectd.org>
**/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <assert.h>
#include <stdlib.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/adt/avl_tree.h"
#define BALANCE(n) \
(((n) == NULL) ? 0 \
: (((n)->left == NULL) ? 0 : (n)->left->height) \
- (((n)->right == NULL) ? 0 : (n)->right->height))
/*
* private data types
*/
struct c_avl_node_s
{
void * key;
void * value;
int height;
struct c_avl_node_s * left;
struct c_avl_node_s * right;
struct c_avl_node_s * parent;
};
typedef struct c_avl_node_s c_avl_node_t;
struct c_avl_tree_s
{
c_avl_node_t * root;
int (*compare)(const void *, const void *);
int size;
};
struct c_avl_iterator_s
{
c_avl_tree_t * tree;
c_avl_node_t * node;
};
/*
* private functions
*/
#if 0
static void verify_tree (c_avl_node_t *n)
{
if (n == NULL)
return;
verify_tree (n->left);
verify_tree (n->right);
assert ((BALANCE (n) >= -1) && (BALANCE (n) <= 1));
assert ((n->parent == NULL) || (n->parent->right == n) || (n->parent->left == n));
} /* void verify_tree */
#else
#define verify_tree(n) /**/
#endif
static void free_node(c_avl_node_t * n)
{
if (n == NULL) return;
if (n->left != NULL) free_node(n->left);
if (n->right != NULL) free_node(n->right);
free(n);
}
static int calc_height(c_avl_node_t * n)
{
int height_left;
int height_right;
if (n == NULL) return 0;
height_left = (n->left == NULL) ? 0 : n->left->height;
height_right = (n->right == NULL) ? 0 : n->right->height;
return ((height_left > height_right) ? height_left : height_right) + 1;
} /* int calc_height */
static c_avl_node_t * search(c_avl_tree_t * t, const void * key)
{
c_avl_node_t * n;
int cmp;
n = t->root;
while (n != NULL)
{
cmp = t->compare(key, n->key);
if (cmp == 0)
return n;
else if (cmp < 0)
n = n->left;
else
n = n->right;
}
return NULL;
}
/* (x) (y)
* / \ / \
* (y) /\ /\ (x)
* / \ /_c\ ==> / a\ / \
* /\ /\ /____\/\ /\
* / a\ /_b\ /_b\ /_c\
* /____\
*/
static c_avl_node_t * rotate_right(c_avl_tree_t * t, c_avl_node_t * x)
{
c_avl_node_t * p;
c_avl_node_t * y;
c_avl_node_t * b;
assert(x != NULL);
assert(x->left != NULL);
p = x->parent;
y = x->left;
b = y->right;
x->left = b;
if (b != NULL) b->parent = x;
x->parent = y;
y->right = x;
y->parent = p;
assert((p == NULL) || (p->left == x) || (p->right == x));
if (p == NULL)
t->root = y;
else if (p->left == x)
p->left = y;
else
p->right = y;
x->height = calc_height(x);
y->height = calc_height(y);
return y;
} /* void rotate_right */
/*
* (x) (y)
* / \ / \
* /\ (y) (x) /\
* /_a\ / \ ==> / \ / c\
* /\ /\ /\ /\/____\
* /_b\ / c\ /_a\ /_b\
* /____\
*/
static c_avl_node_t * rotate_left(c_avl_tree_t * t, c_avl_node_t * x)
{
c_avl_node_t * p;
c_avl_node_t * y;
c_avl_node_t * b;
assert(x != NULL);
assert(x->right != NULL);
p = x->parent;
y = x->right;
b = y->left;
x->right = b;
if (b != NULL) b->parent = x;
x->parent = y;
y->left = x;
y->parent = p;
assert((p == NULL) || (p->left == x) || (p->right == x));
if (p == NULL)
t->root = y;
else if (p->left == x)
p->left = y;
else
p->right = y;
x->height = calc_height(x);
y->height = calc_height(y);
return y;
} /* void rotate_left */
static c_avl_node_t * rotate_left_right(c_avl_tree_t * t, c_avl_node_t * x)
{
rotate_left(t, x->left);
return rotate_right(t, x);
} /* void rotate_left_right */
static c_avl_node_t * rotate_right_left(c_avl_tree_t * t, c_avl_node_t * x)
{
rotate_right(t, x->right);
return rotate_left(t, x);
} /* void rotate_right_left */
static void rebalance(c_avl_tree_t * t, c_avl_node_t * n)
{
int b_top;
int b_bottom;
while (n != NULL)
{
b_top = BALANCE(n);
assert((b_top >= -2) && (b_top <= 2));
if (b_top == -2)
{
assert(n->right != NULL);
b_bottom = BALANCE(n->right);
assert((b_bottom >= -1) && (b_bottom <= 1));
if (b_bottom == 1)
n = rotate_right_left(t, n);
else
n = rotate_left(t, n);
}
else if (b_top == 2)
{
assert(n->left != NULL);
b_bottom = BALANCE(n->left);
assert((b_bottom >= -1) && (b_bottom <= 1));
if (b_bottom == -1)
n = rotate_left_right(t, n);
else
n = rotate_right(t, n);
}
else
{
int height = calc_height(n);
if (height == n->height) break;
n->height = height;
}
assert(n->height == calc_height(n));
n = n->parent;
} /* while (n != NULL) */
} /* void rebalance */
static c_avl_node_t * c_avl_node_next(c_avl_node_t * n)
{
c_avl_node_t * r; /* return node */
if (n == NULL)
{
return NULL;
}
/* If we can't descent any further, we have to backtrack to the first
* parent that's bigger than we, i. e. who's _left_ child we are. */
if (n->right == NULL)
{
r = n->parent;
while ((r != NULL) && (r->parent != NULL))
{
if (r->left == n) break;
n = r;
r = n->parent;
}
/* n->right == NULL && r == NULL => t is root and has no next
* r->left != n => r->right = n => r->parent == NULL */
if ((r == NULL) || (r->left != n))
{
assert((r == NULL) || (r->parent == NULL));
return NULL;
}
else
{
assert(r->left == n);
return r;
}
}
else
{
r = n->right;
while (r->left != NULL) r = r->left;
}
return r;
} /* c_avl_node_t *c_avl_node_next */
static c_avl_node_t * c_avl_node_prev(c_avl_node_t * n)
{
c_avl_node_t * r; /* return node */
if (n == NULL)
{
return NULL;
}
/* If we can't descent any further, we have to backtrack to the first
* parent that's smaller than we, i. e. who's _right_ child we are. */
if (n->left == NULL)
{
r = n->parent;
while ((r != NULL) && (r->parent != NULL))
{
if (r->right == n) break;
n = r;
r = n->parent;
}
/* n->left == NULL && r == NULL => t is root and has no next
* r->right != n => r->left = n => r->parent == NULL */
if ((r == NULL) || (r->right != n))
{
assert((r == NULL) || (r->parent == NULL));
return NULL;
}
else
{
assert(r->right == n);
return r;
}
}
else
{
r = n->left;
while (r->right != NULL) r = r->right;
}
return r;
} /* c_avl_node_t *c_avl_node_prev */
static int _remove(c_avl_tree_t * t, c_avl_node_t * n)
{
assert((t != NULL) && (n != NULL));
if (n && (n->left != NULL) && (n->right != NULL))
{
c_avl_node_t * r; /* replacement node */
if (BALANCE(n) > 0) /* left subtree is higher */
{
assert(n->left != NULL); //-V547
r = c_avl_node_prev(n);
}
else /* right subtree is higher */
{
assert(n->right != NULL); //-V547
r = c_avl_node_next(n);
}
ALLEGE(r != NULL && ((r->left == NULL) || (r->right == NULL)));
/* copy content */
n->key = r->key;
n->value = r->value;
n = r;
}
ALLEGE(n != NULL && ((n->left == NULL) || (n->right == NULL)));
if ((n->left == NULL) && (n->right == NULL))
{
/* Deleting a leave is easy */
if (n->parent == NULL)
{
assert(t->root == n);
t->root = NULL;
}
else
{
assert((n->parent->left == n) || (n->parent->right == n));
if (n->parent->left == n)
n->parent->left = NULL;
else
n->parent->right = NULL;
rebalance(t, n->parent);
}
free_node(n);
}
else if (n->left == NULL)
{
assert(BALANCE(n) == -1); //-V547
assert((n->parent == NULL) || (n->parent->left == n)
|| (n->parent->right == n));
if (n->parent == NULL)
{
assert(t->root == n);
t->root = n->right;
}
else if (n->parent->left == n)
{
n->parent->left = n->right;
}
else
{
n->parent->right = n->right;
}
ALLEGE(n->right != NULL);
n->right->parent = n->parent;
if (n->parent != NULL) rebalance(t, n->parent);
n->right = NULL;
free_node(n);
}
else if (n->right == NULL)
{
assert(BALANCE(n) == 1); //-V547
assert((n->parent == NULL) || (n->parent->left == n)
|| (n->parent->right == n));
if (n->parent == NULL)
{
assert(t->root == n);
t->root = n->left;
}
else if (n->parent->left == n)
{
n->parent->left = n->left;
}
else
{
n->parent->right = n->left;
}
n->left->parent = n->parent;
if (n->parent != NULL) rebalance(t, n->parent);
n->left = NULL;
free_node(n);
}
else
{
assert(0);
}
return 0;
} /* void *_remove */
/*
* public functions
*/
c_avl_tree_t * c_avl_create(int (*compare)(const void *, const void *))
{
c_avl_tree_t * t;
if (compare == NULL) return NULL;
if ((t = malloc(sizeof(*t))) == NULL) return NULL;
t->root = NULL;
t->compare = compare;
t->size = 0;
return t;
}
void c_avl_destroy(c_avl_tree_t * t)
{
if (t == NULL) return;
free_node(t->root);
free(t);
}
int c_avl_insert(c_avl_tree_t * t, void * key, void * value)
{
c_avl_node_t * new;
c_avl_node_t * nptr;
int cmp;
if ((new = malloc(sizeof(*new))) == NULL) return -1;
new->key = key;
new->value = value;
new->height = 1;
new->left = NULL;
new->right = NULL;
if (t->root == NULL)
{
new->parent = NULL;
t->root = new;
t->size = 1;
return 0;
}
nptr = t->root;
while (42)
{
cmp = t->compare(nptr->key, new->key);
if (cmp == 0)
{
free_node(new);
return 1;
}
else if (cmp < 0)
{
/* nptr < new */
if (nptr->right == NULL)
{
nptr->right = new;
new->parent = nptr;
rebalance(t, nptr);
break;
}
else
{
nptr = nptr->right;
}
}
else /* if (cmp > 0) */
{
/* nptr > new */
if (nptr->left == NULL)
{
nptr->left = new;
new->parent = nptr;
rebalance(t, nptr);
break;
}
else
{
nptr = nptr->left;
}
}
} /* while (42) */
verify_tree(t->root);
++t->size;
return 0;
} /* int c_avl_insert */
int c_avl_remove(c_avl_tree_t * t,
const void * key,
void ** rkey,
void ** rvalue)
{
c_avl_node_t * n;
int status;
assert(t != NULL);
n = search(t, key);
if (n == NULL) return -1;
if (rkey != NULL) *rkey = n->key;
if (rvalue != NULL) *rvalue = n->value;
status = _remove(t, n);
verify_tree(t->root);
--t->size;
return status;
} /* void *c_avl_remove */
int c_avl_get(c_avl_tree_t * t, const void * key, void ** value)
{
c_avl_node_t * n;
assert(t != NULL);
n = search(t, key);
if (n == NULL) return -1;
if (value != NULL) *value = n->value;
return 0;
}
int c_avl_pick(c_avl_tree_t * t, void ** key, void ** value)
{
c_avl_node_t * n;
c_avl_node_t * p;
assert(t != NULL);
if ((key == NULL) || (value == NULL)) return -1;
if (t->root == NULL) return -1;
n = t->root;
while ((n->left != NULL) || (n->right != NULL))
{
if (n->left == NULL)
{
n = n->right;
continue;
}
else if (n->right == NULL)
{
n = n->left;
continue;
}
if (n->left->height > n->right->height)
n = n->left;
else
n = n->right;
}
p = n->parent;
if (p == NULL)
t->root = NULL;
else if (p->left == n)
p->left = NULL;
else
p->right = NULL;
*key = n->key;
*value = n->value;
free_node(n);
--t->size;
rebalance(t, p);
return 0;
} /* int c_avl_pick */
c_avl_iterator_t * c_avl_get_iterator(c_avl_tree_t * t)
{
c_avl_iterator_t * iter;
if (t == NULL) return NULL;
iter = calloc(1, sizeof(*iter));
if (iter == NULL) return NULL;
iter->tree = t;
return iter;
} /* c_avl_iterator_t *c_avl_get_iterator */
int c_avl_iterator_next(c_avl_iterator_t * iter, void ** key, void ** value)
{
c_avl_node_t * n;
if ((iter == NULL) || (key == NULL) || (value == NULL)) return -1;
if (iter->node == NULL)
{
for (n = iter->tree->root; n != NULL; n = n->left)
if (n->left == NULL) break;
iter->node = n;
}
else
{
n = c_avl_node_next(iter->node);
}
if (n == NULL) return -1;
iter->node = n;
*key = n->key;
*value = n->value;
return 0;
} /* int c_avl_iterator_next */
int c_avl_iterator_prev(c_avl_iterator_t * iter, void ** key, void ** value)
{
c_avl_node_t * n;
if ((iter == NULL) || (key == NULL) || (value == NULL)) return -1;
if (iter->node == NULL)
{
for (n = iter->tree->root; n != NULL; n = n->left)
if (n->right == NULL) break;
iter->node = n;
}
else
{
n = c_avl_node_prev(iter->node);
}
if (n == NULL) return -1;
iter->node = n;
*key = n->key;
*value = n->value;
return 0;
} /* int c_avl_iterator_prev */
void c_avl_iterator_destroy(c_avl_iterator_t * iter) { free(iter); }
int c_avl_size(c_avl_tree_t * t)
{
if (t == NULL) return 0;
return t->size;
} |
C | aircrack-ng/lib/libac/adt/circular_buffer.c | /**
* Copyright (C) 2018 Joseph Benden <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <stddef.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/adt/circular_buffer.h"
#ifndef NDEBUG
static inline bool is_power_of_two(size_t n)
{
REQUIRE(n > 0);
while ((n % 2) == 0)
{
n /= 2;
}
if (n == 1) return true;
return false;
}
#endif
// The definition of our circular buffer is hidden from the API user.
struct circular_buffer_t
{
uint8_t * buffer; /// Circular buffer's memory location.
size_t read_pos; /// Current read position, as element index.
size_t write_pos; /// Current write position, as element index.
size_t max; /// Number of bytes allocated for whole ring buffer.
size_t size; /// Number of bytes required for a single element.
};
/*
* A circular buffer uses the "Virtual Streams" approach, as described on
* the Ryg blog:
*
* https://fgiesen.wordpress.com/2010/12/14/ring-buffers-and-queues/
*/
#define CBUF_BUFFER_POS(cbuf, which) \
(cbuf->buffer + ((cbuf->which % (cbuf->max / cbuf->size)) * cbuf->size))
static inline void check_invariants(cbuf_handle_t cbuf)
{
#ifdef NDEBUG
(void) cbuf;
#endif
// All writes to structure are always ahead of the reads, unless empty.
INVARIANT(cbuf->write_pos >= cbuf->read_pos);
// All writes are restricted to the inside of our buffer's region.
INVARIANT(cbuf->write_pos - cbuf->read_pos <= (cbuf->max / cbuf->size));
}
API_EXPORT cbuf_handle_t circular_buffer_init(uint8_t * buffer,
size_t bufferSize,
size_t elementSize)
{
REQUIRE(buffer && bufferSize && elementSize);
REQUIRE(bufferSize % elementSize == 0);
REQUIRE(is_power_of_two(bufferSize));
cbuf_handle_t cbuf = calloc(1, sizeof(circular_buffer_t));
ALLEGE(cbuf);
cbuf->buffer = buffer;
cbuf->max = bufferSize;
cbuf->size = elementSize;
circular_buffer_reset(cbuf);
ENSURE(circular_buffer_is_empty(cbuf));
return cbuf;
}
API_EXPORT void circular_buffer_free(cbuf_handle_t cbuf)
{
REQUIRE(cbuf);
cbuf->buffer = NULL;
free(cbuf);
}
API_EXPORT void circular_buffer_reset(cbuf_handle_t cbuf)
{
REQUIRE(cbuf);
cbuf->read_pos = 0;
cbuf->write_pos = 0;
}
API_EXPORT bool circular_buffer_is_empty(cbuf_handle_t cbuf)
{
REQUIRE(cbuf);
return cbuf->read_pos == cbuf->write_pos;
}
API_EXPORT bool circular_buffer_is_full(cbuf_handle_t cbuf)
{
REQUIRE(cbuf);
return cbuf->write_pos == (cbuf->read_pos + (cbuf->max / cbuf->size));
}
API_EXPORT size_t circular_buffer_capacity(cbuf_handle_t cbuf)
{
REQUIRE(cbuf);
return cbuf->max / cbuf->size;
}
API_EXPORT size_t circular_buffer_size(cbuf_handle_t cbuf)
{
REQUIRE(cbuf);
return cbuf->write_pos - cbuf->read_pos;
}
API_EXPORT void
circular_buffer_put(cbuf_handle_t cbuf, void const * const data, size_t size)
{
REQUIRE(cbuf && data && size > 0);
REQUIRE(size <= cbuf->size);
memcpy(CBUF_BUFFER_POS(cbuf, write_pos), data, size); // cannot overlap
if (size < cbuf->size)
{
// zero extra buffer bytes
memset(CBUF_BUFFER_POS(cbuf, write_pos) + size, 0, cbuf->size - size);
}
++cbuf->write_pos;
check_invariants(cbuf);
}
API_EXPORT void
circular_buffer_get(cbuf_handle_t cbuf, void * const * data, size_t size)
{
REQUIRE(cbuf && data && size > 0);
REQUIRE(size <= cbuf->size);
memcpy(*data, CBUF_BUFFER_POS(cbuf, read_pos), size); // cannot overlap
++cbuf->read_pos;
check_invariants(cbuf);
} |
C | aircrack-ng/lib/libac/adt/circular_queue.c | #ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <stddef.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#include <pthread.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/adt/circular_buffer.h"
#include "aircrack-ng/adt/circular_queue.h"
// The definition of our circular queue is hidden from the API user.
struct circular_queue_t
{
cbuf_handle_t cbuf; /// Circular buffer.
pthread_mutex_t lock; /// Lock protecting whole structure.
#if !defined(__APPLE_CC__) && !defined(__APPLE__)
// NOTE: On the M1 macOS, the sizes subtract to zero.
char padding1[CACHELINE_SIZE - sizeof(pthread_mutex_t)];
#endif
pthread_cond_t full_cv; /// Signals upon no longer full.
#if !defined(__APPLE_CC__) && !defined(__APPLE__)
// NOTE: On the M1 macOS, the sizes subtract to zero.
char padding2[CACHELINE_SIZE - sizeof(pthread_cond_t)];
#endif
pthread_cond_t empty_cv; /// Signals upon no longer empty.
};
API_EXPORT cqueue_handle_t circular_queue_init(uint8_t * buffer,
size_t bufferSize,
size_t elementSize)
{
REQUIRE(buffer && bufferSize && elementSize);
REQUIRE(bufferSize % elementSize == 0);
cqueue_handle_t cq = calloc(1, sizeof(circular_queue_t));
ALLEGE(cq);
cq->cbuf = circular_buffer_init(buffer, bufferSize, elementSize);
ALLEGE(cq->cbuf);
ALLEGE(pthread_mutex_init(&(cq->lock), NULL) == 0);
ALLEGE(pthread_cond_init(&(cq->empty_cv), NULL) == 0);
ALLEGE(pthread_cond_init(&(cq->full_cv), NULL) == 0);
return cq;
}
API_EXPORT void circular_queue_free(cqueue_handle_t cq)
{
REQUIRE(cq);
circular_buffer_free(cq->cbuf);
cq->cbuf = NULL;
ALLEGE(pthread_cond_destroy(&(cq->empty_cv)) == 0);
ALLEGE(pthread_cond_destroy(&(cq->full_cv)) == 0);
ALLEGE(pthread_mutex_destroy(&(cq->lock)) == 0);
free(cq);
}
API_EXPORT void circular_queue_reset(cqueue_handle_t cq)
{
REQUIRE(cq);
ALLEGE(pthread_mutex_lock(&(cq->lock)) == 0);
circular_buffer_reset(cq->cbuf);
ALLEGE(pthread_mutex_unlock(&(cq->lock)) == 0);
}
static inline void
do_push(cqueue_handle_t cq, void const * const data, size_t size)
{
REQUIRE(cq && data && size > 0);
REQUIRE(!circular_buffer_is_full(cq->cbuf));
circular_buffer_put(cq->cbuf, data, size);
ALLEGE(pthread_cond_signal(&(cq->empty_cv)) == 0);
ALLEGE(pthread_mutex_unlock(&(cq->lock)) == 0);
}
API_EXPORT void
circular_queue_push(cqueue_handle_t cq, void const * const data, size_t size)
{
REQUIRE(cq && data && size > 0);
ALLEGE(pthread_mutex_lock(&(cq->lock)) == 0);
while (circular_buffer_is_full(cq->cbuf))
{
ALLEGE(pthread_cond_wait(&(cq->full_cv), &(cq->lock)) == 0);
}
do_push(cq, data, size);
}
API_EXPORT int circular_queue_try_push(cqueue_handle_t cq,
void const * const data,
size_t size)
{
REQUIRE(cq && data && size > 0);
ALLEGE(pthread_mutex_lock(&(cq->lock)) == 0);
if (circular_buffer_is_full(cq->cbuf))
{
ALLEGE(pthread_mutex_unlock(&(cq->lock)) == 0);
return -1;
}
do_push(cq, data, size);
return 0;
}
API_EXPORT void
circular_queue_pop(cqueue_handle_t cq, void * const * data, size_t size)
{
REQUIRE(cq && data && size > 0);
ALLEGE(pthread_mutex_lock(&(cq->lock)) == 0);
while (circular_buffer_is_empty(cq->cbuf))
{
ALLEGE(pthread_cond_wait(&(cq->empty_cv), &(cq->lock)) == 0);
}
ALLEGE(!circular_buffer_is_empty(cq->cbuf));
circular_buffer_get(cq->cbuf, data, size);
ALLEGE(pthread_cond_signal(&(cq->full_cv)) == 0);
ALLEGE(pthread_mutex_unlock(&(cq->lock)) == 0);
}
API_EXPORT bool circular_queue_is_empty(cqueue_handle_t cq)
{
REQUIRE(cq);
bool rc;
ALLEGE(pthread_mutex_lock(&(cq->lock)) == 0);
rc = circular_buffer_is_empty(cq->cbuf);
ALLEGE(pthread_mutex_unlock(&(cq->lock)) == 0);
return rc;
}
API_EXPORT bool circular_queue_is_full(cqueue_handle_t cq)
{
REQUIRE(cq);
bool rc;
ALLEGE(pthread_mutex_lock(&(cq->lock)) == 0);
rc = circular_buffer_is_full(cq->cbuf);
ALLEGE(pthread_mutex_unlock(&(cq->lock)) == 0);
return rc;
} |
C | aircrack-ng/lib/libac/cpu/cpuset_hwloc.c | /*
* Copyright (C) 2018 Joseph Benden <[email protected]>
*
* 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
* is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
* NON-INFRINGEMENT. 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.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <hwloc.h>
#include <assert.h>
#include <limits.h>
#include <sys/types.h>
#include "aircrack-ng/cpu/cpuset.h"
struct ac_cpuset
{
size_t nbThreads;
hwloc_topology_t topology;
hwloc_cpuset_t * hwloc_cpusets;
};
ac_cpuset_t * ac_cpuset_new(void) { return malloc(sizeof(struct ac_cpuset)); }
void ac_cpuset_free(ac_cpuset_t * cset) { free(cset); }
void ac_cpuset_init(ac_cpuset_t * cset)
{
assert(cset != NULL);
cset->nbThreads = 0;
cset->hwloc_cpusets = NULL;
hwloc_topology_init(&cset->topology);
hwloc_topology_load(cset->topology);
}
void ac_cpuset_destroy(ac_cpuset_t * cset)
{
assert(cset != NULL);
if (cset->hwloc_cpusets != NULL)
{
free(cset->hwloc_cpusets);
cset->hwloc_cpusets = NULL;
}
hwloc_topology_destroy(cset->topology);
}
void ac_cpuset_distribute(ac_cpuset_t * cset, size_t count)
{
assert(cset != NULL);
cset->nbThreads = count;
cset->hwloc_cpusets = calloc(count, sizeof(hwloc_cpuset_t));
if (!cset->hwloc_cpusets) return;
hwloc_obj_t root = hwloc_get_root_obj(cset->topology);
#if defined(HWLOC_API_VERSION) && HWLOC_API_VERSION > 0x00010800
hwloc_distrib(cset->topology,
&root,
1u,
cset->hwloc_cpusets,
(unsigned int) count,
INT_MAX,
0u);
#else
hwloc_distributev(cset->topology,
&root,
1u,
cset->hwloc_cpusets,
(unsigned int) count,
INT_MAX);
#endif
}
#ifdef CYGWIN
struct tid_to_handle
{
ptrdiff_t vtbl;
uint32_t magic;
HANDLE h;
};
#endif
void ac_cpuset_bind_thread_at(ac_cpuset_t * cset, pthread_t tid, size_t idx)
{
assert(cset != NULL);
if (idx > cset->nbThreads) return;
hwloc_bitmap_singlify(cset->hwloc_cpusets[idx]);
if (hwloc_set_thread_cpubind(
cset->topology,
#ifdef CYGWIN
// WARNING: This is a HACK into `class pthread` of Cygwin.
*((HANDLE *) ((char *) tid + offsetof(struct tid_to_handle, h))),
#else
tid,
#endif
cset->hwloc_cpusets[idx],
HWLOC_CPUBIND_THREAD))
{
char * str;
int error = errno;
hwloc_bitmap_asprintf(&str, cset->hwloc_cpusets[idx]);
fprintf(stderr,
"Couldn't bind thread to cpuset %s: %s\n",
str,
strerror(error));
free(str);
}
} |
C | aircrack-ng/lib/libac/cpu/cpuset_pthread.c | /*
* Copyright (C) 2018 Joseph Benden <[email protected]>
*
* 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
* is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
* NON-INFRINGEMENT. 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.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <assert.h>
#include <limits.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/types.h>
#if defined(__DragonFly__)
#include <pthread_np.h>
#endif
#include "aircrack-ng/defs.h"
#include "aircrack-ng/cpu/cpuset.h"
struct ac_cpuset
{
size_t nbThreads;
};
ac_cpuset_t * ac_cpuset_new(void) { return malloc(sizeof(struct ac_cpuset)); }
void ac_cpuset_free(ac_cpuset_t * cset) { free(cset); }
void ac_cpuset_init(ac_cpuset_t * cset)
{
assert(cset != NULL);
cset->nbThreads = 0;
}
void ac_cpuset_destroy(ac_cpuset_t * cset) { assert(cset != NULL); }
void ac_cpuset_distribute(ac_cpuset_t * cset, size_t count)
{
assert(cset != NULL);
cset->nbThreads = count;
}
void ac_cpuset_bind_thread_at(ac_cpuset_t * cset, pthread_t tid, size_t idx)
{
assert(cset != NULL);
if (idx > cset->nbThreads) return;
#if defined(HAVE_PTHREAD_AFFINITY_NP) && HAVE_PTHREAD_AFFINITY_NP
// set affinity to a specific processor, for the specified thread.
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(idx, &set);
pthread_setaffinity_np(tid, sizeof(cpu_set_t), &set);
#else
UNUSED_PARAM(tid);
UNUSED_PARAM(idx);
#endif
} |
C | aircrack-ng/lib/libac/cpu/simd_cpuid.c | /*
* CPU/SIMD identification routines by Len White <[email protected]>
*
* 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
*
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#if defined(__i386__) || defined(__x86_64__)
#define _X86 1
#include <cpuid.h>
#elif defined(__arm__) || defined(__aarch64__)
#ifdef HAS_AUXV
#include <sys/auxv.h>
#include <asm/hwcap.h>
#endif
#endif /* __arm__ */
#ifdef __linux__
#include <fcntl.h>
#include <sys/stat.h>
#include <linux/sysctl.h>
#endif
#if defined(__FreeBSD__) || defined(__OpenBSD__)
#include <sys/user.h>
#include <sys/sysctl.h>
#endif
#if defined(__APPLE__) && defined(__aarch64__)
#include <sys/sysctl.h>
#endif
#include <dirent.h>
#include "aircrack-ng/cpu/simd_cpuid.h"
#include "aircrack-ng/support/common.h"
#ifdef __linux__
#define CPUFREQ_CPU0C "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"
#define CPUFREQ_CPU0M "/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq"
#define CORETEMP_PATH "/sys/devices/platform/coretemp.0/"
static int cpuid_readsysfs(const char * file);
static int cpuid_findcpusensorpath(const char * path);
#endif
struct _cpuinfo cpuinfo = {0, NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0.0, NULL};
//
// Until better support for other arch's is added an ifdef is needed
//
static unsigned long
getRegister(const unsigned int val, const char from, const char to)
{
unsigned long mask = (1ul << (to + 1ul)) - 1ul;
if (to == 31) return val >> from;
return (val & mask) >> from;
}
#if defined(_X86) || defined(__arm__) || defined(__aarch64__)
static void sprintcat(char * restrict dest, const char * restrict src, size_t len)
{
if (*dest != '\0') (void) strncat(dest, ",", len - strlen(dest) - 1);
(void) strncat(dest, src, len - strlen(dest) - 1);
}
#endif
int is_dir(const char * dir)
{
struct stat sb;
if (!stat(dir, &sb)) return S_ISDIR(sb.st_mode);
return 0;
}
unsigned long GetCacheTotalLize(unsigned ebx, unsigned ecx)
{
unsigned long LnSz, SectorSz, WaySz, SetSz;
LnSz = getRegister(ebx, 0, 11) + 1;
SectorSz = getRegister(ebx, 12, 21) + 1;
WaySz = getRegister(ebx, 22, 31) + 1;
SetSz = getRegister(ecx, 0, 31) + 1;
return (SetSz * WaySz * SectorSz * LnSz);
}
//
// Return maximum SIMD size for the CPU.
// AVX512F = 16 / 512 bit
// AVX2 = 8 / 256 bit
// SSE2-4.2 + AVX / NEON = 4 / 128 bit
// MMX / CPU Fallback = 1 / 64 bit
//
int cpuid_simdsize(int viewmax)
{
#ifdef _X86
unsigned eax = 0, ebx = 0, ecx = 0, edx = 0;
unsigned int max_level = __get_cpuid_max(0, NULL);
if (max_level >= 7)
{
__cpuid_count(7, 0, eax, ebx, ecx, edx);
if (ebx & (1 << 16))
{ // AVX512F
return 16;
}
else if (ebx & (1 << 5))
{ // AVX2
return 8;
}
}
__cpuid(1, eax, ebx, ecx, edx);
if (edx & (1 << 26)) // SSE2
return 4;
#elif (defined(__arm__) || defined(__aarch64__)) && defined(HAS_AUXV)
long hwcaps = getauxval(AT_HWCAP);
if (hwcaps & (1 << 12)) // NEON
return 4;
#if defined(__aarch64__)
if (hwcaps & (1 << 1)) // ASIMD
return 4;
#endif
#elif defined(__aarch64__) && !defined(HAS_AUXV)
return 4; // ASIMD is required on AARCH64
#endif
(void) viewmax;
// MMX or CPU Fallback
return 1;
}
#ifdef _X86
static char * cpuid_vendor(void)
{
unsigned eax = 0, ebx = 0, ecx = 0, edx = 0;
__cpuid(0, eax, ebx, ecx, edx);
if ((ebx == 0x756E6547) && (edx == 0x49656E69))
return "Intel";
else if ((ebx == 0x68747541) || (ebx == 0x69444D41))
return "AMD";
else if (ebx == 0x746E6543)
return "Centaur (VIA)";
else if (ebx == 0x69727943)
return "Cyrix";
else if ((ebx == 0x6E617254)
|| ((ebx == 0x756E6547) && (edx == 0x54656E69)))
return "Transmeta";
else if (ebx == 0x646F6547)
return "Geode by NSC (AMD)";
else if (ebx == 0x4778654E)
return "NexGen";
else if (ebx == 0x65736952)
return "Rise";
else if (ebx == 0x20536953)
return "SiS";
else if (ebx == 0x20434D55)
return "UMC";
else if (ebx == 0x20414956)
return "VIA";
else if (ebx == 0x74726F56)
return "Vortex86 SoC";
else if (ebx == 0x4B4D564B)
return "KVM (Virtual Machine)";
else if (ebx == 0x7263694D)
return "Microsoft Hyper-V or Virtual PC";
else if (ebx == 0x70726C20)
return "Parallels (Virtual Machine)";
else if (ebx == 0x61774D56)
return "VMware";
else if (ebx == 0x566E6558)
return "Xen HVM (Virtual Machine)";
return "Unknown CPU";
}
#endif
static char * cpuid_featureflags(void)
{
char flags[64] = {0};
#ifdef _X86
unsigned eax = 0, ebx = 0, ecx = 0, edx = 0;
unsigned int max_level = __get_cpuid_max(0, NULL);
__cpuid(1, eax, ebx, ecx, edx);
if (edx & (1 << 23)) sprintcat((char *) &flags, "MMX", sizeof(flags));
if (edx & (1 << 25)) sprintcat((char *) &flags, "SSE", sizeof(flags));
if (edx & (1 << 26)) sprintcat((char *) &flags, "SSE2", sizeof(flags));
if (ecx & (1 << 0)) sprintcat((char *) &flags, "SSE3", sizeof(flags));
if (ecx & (1 << 9)) sprintcat((char *) &flags, "SSSE3", sizeof(flags));
if (ecx & (1 << 19)) sprintcat((char *) &flags, "SSE4.1", sizeof(flags));
if (ecx & (1 << 20)) sprintcat((char *) &flags, "SSE4.2", sizeof(flags));
if (ecx & (1 << 25)) sprintcat((char *) &flags, "AES-NI", sizeof(flags));
if (edx & (1 << 28)) // Hyper-threading
cpuinfo.htt = 1;
if (ecx & (1 << 28)) // AVX
sprintcat((char *) &flags, "AVX", sizeof(flags));
if (ecx & (1 << 31)) // Hypervisor
cpuinfo.hv = 1;
if (max_level >= 7)
{
__cpuid_count(7, 0, eax, ebx, ecx, edx);
if (ebx & (1 << 5)) // AVX2
sprintcat((char *) &flags, "AVX2", sizeof(flags));
if (ebx & (1 << 16)) // AVX512F
sprintcat((char *) &flags, "AVX512F", sizeof(flags));
}
#elif (defined(__arm__) || defined(__aarch64__)) && defined(HAS_AUXV)
long hwcaps = getauxval(AT_HWCAP);
#if defined(__aarch64__)
if (hwcaps & (1 << 1)) sprintcat((char *) &flags, "ASIMD", sizeof(flags));
#else
if (hwcaps & (1 << 12)) sprintcat((char *) &flags, "NEON", sizeof(flags));
if (hwcaps & (1 << 1)) sprintcat((char *) &flags, "HALF", sizeof(flags));
if (hwcaps & (1 << 2)) sprintcat((char *) &flags, "THUMB", sizeof(flags));
if (hwcaps & (1 << 11))
sprintcat((char *) &flags, "THUMBEE", sizeof(flags));
if (hwcaps & (1 << 6)) sprintcat((char *) &flags, "VFP", sizeof(flags));
if ((hwcaps & (1 << 13)) || (hwcaps & (1 << 14)))
sprintcat((char *) &flags, "VFPv3", sizeof(flags));
if (hwcaps & (1 << 16)) sprintcat((char *) &flags, "VFPv4", sizeof(flags));
if (hwcaps & (1 << 15)) sprintcat((char *) &flags, "TLS", sizeof(flags));
if (hwcaps & (1 << 10)) sprintcat((char *) &flags, "CRUNCH", sizeof(flags));
if (hwcaps & (1 << 9)) sprintcat((char *) &flags, "iwMMXt", sizeof(flags));
if ((hwcaps & (1 << 17)) || (hwcaps & (1 << 18)))
sprintcat((char *) &flags, "IDIV", sizeof(flags));
#endif
#elif defined(__aarch64__) && !defined(HAS_AUXV)
sprintcat((char *) &flags, "ASIMD", sizeof(flags));
#endif
return strdup(flags);
}
static float cpuid_getcoretemp(void)
{
#ifdef __FreeBSD__
int tempval = 0;
size_t len = sizeof(tempval);
if (sysctlbyname("dev.cpu.0.temperature", &tempval, &len, NULL, 0) == -1)
return 0;
cpuinfo.coretemp = (tempval - 2732) / 10.0f;
#elif __linux__
if (cpuinfo.cputemppath != NULL)
{
cpuinfo.coretemp
= (float) cpuid_readsysfs((const char *) cpuinfo.cputemppath)
/ 1000.0f;
}
#else
return 0;
#endif
return cpuinfo.coretemp;
}
#ifdef __linux__
//
// Locate the primary temp input on the coretemp sysfs
//
static int cpuid_findcpusensorpath(const char * path)
{
#define MAX_SENSOR_PATHS 16
DIR * dirp;
struct dirent * dp;
char tbuf[MAX_SENSOR_PATHS][32] = {{0}};
int cnt = 0, i = 0, sensorx = 0;
char sensor[8] = {0};
dirp = opendir(path);
if (dirp == NULL) return -1;
snprintf(sensor, sizeof(sensor), "temp%d", sensorx);
while (cnt < (MAX_SENSOR_PATHS - 1) && (dp = readdir(dirp)) != NULL)
{
if (!strncmp(dp->d_name, sensor, 5))
{
(void) closedir(dirp);
if (asprintf(&cpuinfo.cputemppath,
"%stemp%d_input",
CORETEMP_PATH,
sensorx)
== -1)
{
perror("asprintf");
}
return sensorx;
}
else if (!strncmp(dp->d_name, "temp", 4))
{
ALLEGE(strlcpy(tbuf[cnt], dp->d_name, 32) < 32);
if (cnt < (MAX_SENSOR_PATHS - 1)) ++cnt; //-V547
}
}
(void) closedir(dirp);
// Hopefully we found the ID on the first pass, but Linux is its infinite
// wisdom
// sometimes starts the sensors at 2-6+
for (sensorx = 1; sensorx < 8; sensorx++)
for (i = 0; i < cnt; i++)
{
snprintf(sensor, sizeof(sensor), "temp%d", sensorx);
if (!strncasecmp(tbuf[i], sensor, strlen(sensor)))
{
if (asprintf(&cpuinfo.cputemppath,
"%stemp%d_input",
CORETEMP_PATH,
sensorx)
== -1)
{
perror("asprintf");
}
return sensorx;
}
}
return -1;
}
static int cpuid_readsysfs(const char * file)
{
int fd, ival = 0;
char buf[16] = {0};
fd = open(file, O_RDONLY);
if (fd == -1) return -1;
if (read(fd, &buf, sizeof(buf)) > 0)
{
ival = atoi(buf);
}
close(fd);
return ival;
}
//
// Return CPU frequency from scaling governor when supported
//
static int cpuid_getfreq(int type)
{
int fd, ifreq = 0;
char freq[16] = {0}, *fptr;
fptr = (type == 1 ? CPUFREQ_CPU0C : CPUFREQ_CPU0M);
fd = open(fptr, O_RDONLY);
if (fd == -1) return 0;
if (read(fd, &freq, sizeof(freq)) > 0) ifreq = atoi(freq) / 1000;
close(fd);
return ifreq;
}
#endif
static char * cpuid_modelinfo(void)
{
#ifdef _X86
unsigned eax = 0, ebx = 0, ecx = 0, edx = 0;
int bi = 2, broff = 0;
char * tmpmodel = calloc(1, (size_t)((sizeof(unsigned) * 4ul) * 5ul));
#elif __linux__
FILE * cfd;
char *line = NULL, *token = NULL;
size_t linecap = 0;
ssize_t linelen;
#elif __FreeBSD__ /* ARM support for FreeBSD */
int mib[] = {CTL_HW, HW_MODEL};
char modelbuf[64];
size_t len = sizeof(modelbuf);
#elif defined(__APPLE__) && defined(__aarch64__)
char modelbuf[128];
size_t modelbuf_len = sizeof(modelbuf);
#endif
char *pm = NULL, *model = NULL;
#ifdef _X86
if (tmpmodel == NULL)
{
fprintf(stderr,
"ERROR: calloc() failed to allocate memory for "
"cpuid_modelinfo(): %s\n",
strerror(errno));
return "Unknown";
}
for (; bi < 5; bi++, broff += 16)
{
__cpuid(0x80000000 + bi, eax, ebx, ecx, edx);
memcpy(tmpmodel + broff, &eax, sizeof(unsigned));
memcpy(tmpmodel + broff + 4, &ebx, sizeof(unsigned));
memcpy(tmpmodel + broff + 8, &ecx, sizeof(unsigned));
memcpy(tmpmodel + broff + 12, &edx, sizeof(unsigned));
}
pm = tmpmodel;
#elif __linux__
cfd = fopen("/proc/cpuinfo", "r");
if (cfd == NULL)
{
fprintf(stderr,
"ERROR: Failed opening /proc/cpuinfo: %s\n",
strerror(errno));
return "Unknown";
}
while ((linelen = getline(&line, &linecap, cfd)) > 0)
{
if (!strncasecmp(line, "model", 5))
{
token = strsep(&line, ":");
token = strsep(&line, ":");
token[strlen(token) - 1] = 0;
(void) *token++;
pm = token;
break;
}
}
free(line);
line = NULL;
fclose(cfd);
if (pm == NULL) return NULL;
#elif __FreeBSD__
if (sysctl(mib, 2, modelbuf, &len, NULL, 0))
snprintf(modelbuf, sizeof(modelbuf), "Unknown");
pm = modelbuf;
#elif defined(__APPLE__) && defined(__aarch64__)
if (sysctlbyname("machdep.cpu.brand_string", &modelbuf, &modelbuf_len, NULL, 0))
snprintf(modelbuf, sizeof(modelbuf), "Unknown Apple AARCH64");
pm = modelbuf;
#endif
// Clean up the empty spaces in the model name on some intel's because they
// let their engineers fall asleep on the space bar
while (*pm == ' ')
{
pm++;
}
model = strdup(pm);
#ifdef _X86
free(tmpmodel);
tmpmodel = NULL;
#endif
if (model == NULL)
{
fprintf(stderr,
"ERROR: strdup() failed to allocate memory for "
"cpuid_modelinfo(): %s\n",
strerror(errno));
return "Unknown";
}
return model;
}
#ifdef _X86
static inline unsigned cpuid_x86_max_function_id(void)
{
unsigned eax = 0, ebx = 0, ecx = 0, edx = 0;
__cpuid(0, eax, ebx, ecx, edx);
return (eax);
}
static inline unsigned cpuid_x86_max_extended_function_id(void)
{
unsigned eax = 0, ebx = 0, ecx = 0, edx = 0;
__cpuid(0x80000000UL, eax, ebx, ecx, edx);
return (eax);
}
static unsigned int cpuid_x86_threads_per_core(void);
static unsigned int cpuid_x86_threads_per_core(void)
{
unsigned eax = 0, ebx = 0, ecx = 0, edx = 0;
unsigned int mfi = cpuid_x86_max_function_id();
unsigned int mefi = cpuid_x86_max_extended_function_id();
const char * vendor = cpuid_vendor();
if (mfi < 0x04U
|| (strcmp(vendor, "Intel") != 0 && strcmp(vendor, "AMD") != 0))
{
return (1);
}
if (strcmp(vendor, "AMD") == 0 && mefi >= 0x8000001EU)
{
__cpuid(0x8000001EU, eax, ebx, ecx, edx);
return (((ebx >> 8U) & 7U) + 1U);
}
if (mfi < 0x0BU)
{
__cpuid(1, eax, ebx, ecx, edx);
if ((edx & (1U << 28U)) != 0)
{
// v will contain logical core count
const unsigned v = (ebx >> 16) & 255;
if (v > 1)
{
__cpuid(4, eax, ebx, ecx, edx);
// physical cores
const unsigned v2 = (eax >> 26U) + 1U;
if (v2 > 0)
{
return v / v2;
}
}
}
return (1);
}
if (mfi < 0x1FU)
{
/*
CPUID leaf 1FH is a preferred superset to leaf 0BH. Intel
recommends first checking for the existence of Leaf 1FH
before using leaf 0BH.
*/
__cpuid_count(0x0BU, 0, eax, ebx, ecx, edx);
if ((ebx & 0xFFFFU) == 0)
{
return (1);
}
return (ebx & 0xFFFFU);
}
__cpuid_count(0x1FU, 0, eax, ebx, ecx, edx);
if ((ebx & 0xFFFFU) == 0)
{
return (1);
}
return (ebx & 0xFFFFU);
}
static unsigned int cpuid_x86_logical_cores(void);
static unsigned int cpuid_x86_logical_cores(void)
{
unsigned eax = 0, ebx = 0, ecx = 0, edx = 0;
unsigned int mfi = cpuid_x86_max_function_id();
const char * vendor = cpuid_vendor();
if (strcmp(vendor, "Intel") == 0)
{
// Use this on old Intel processors
if (mfi < 0x0BU)
{
if (mfi < 0x01U)
{
return (0);
}
__cpuid(1, eax, ebx, ecx, edx);
return ((ebx >> 16U) & 0xFFU);
}
if (mfi < 0x1FU)
{
/*
CPUID leaf 1FH is a preferred superset to leaf 0BH. Intel
recommends first checking for the existence of Leaf 1FH
before using leaf 0BH.
*/
__cpuid_count(0x0BU, 1, eax, ebx, ecx, edx);
return (ebx & 0xFFFFU);
}
__cpuid_count(0x1FU, 1, eax, ebx, ecx, edx);
return (ebx & 0xFFFFU);
}
else if (strcmp(vendor, "AMD") == 0)
{
__cpuid(1, eax, ebx, ecx, edx);
return ((ebx >> 16U) & 0xFFU);
}
else
{
return (0);
}
}
static unsigned int cpuid_x86_physical_cores(void);
static unsigned int cpuid_x86_physical_cores(void)
{
unsigned eax = 0, ebx = 0, ecx = 0, edx = 0;
unsigned int mfi = cpuid_x86_max_function_id();
unsigned int mefi = cpuid_x86_max_extended_function_id();
const char * vendor = cpuid_vendor();
if (strcmp(vendor, "Intel") == 0 && mfi >= 0x01U)
{
return (cpuid_x86_logical_cores() / cpuid_x86_threads_per_core());
}
else if (strcmp(vendor, "AMD") == 0 && mefi >= 0x80000008UL)
{
__cpuid(0x80000008UL, eax, ebx, ecx, edx);
return (((ecx & 0xFFU) + 1U) / cpuid_x86_threads_per_core());
}
return (1);
}
#endif
int cpuid_getinfo(void)
{
int cpu_count = get_nb_cpus();
float cpu_temp;
#ifdef _X86
cpuinfo.maxlogic = cpuid_x86_logical_cores();
cpuinfo.cores = cpuid_x86_physical_cores();
printf("Vendor = %s\n", cpuid_vendor());
#else
cpuinfo.maxlogic = cpu_count;
#endif
#ifdef __linux__
cpuid_findcpusensorpath(CORETEMP_PATH);
cpuinfo.cpufreq_cur = cpuid_getfreq(1);
cpuinfo.cpufreq_max = cpuid_getfreq(2);
#endif
cpuinfo.model = cpuid_modelinfo();
cpuinfo.flags = cpuid_featureflags();
if (cpuinfo.model != NULL) printf("Model = %s\n", cpuinfo.model);
if (cpuinfo.flags != NULL) printf("Features = %s\n", cpuinfo.flags);
if (cpuinfo.hv) printf("Hypervisor = Yes (Virtualization detected)\n");
if (cpuinfo.cpufreq_cur)
printf("CPU frequency = %d MHz (Max: %d MHz)\n",
cpuinfo.cpufreq_cur,
cpuinfo.cpufreq_max);
cpu_temp = cpuid_getcoretemp();
if (cpu_temp != 0.0) //-V550
printf("CPU temperature = %2.2f C\n", cpu_temp);
#ifdef _X86
printf("Hyper-Threading = %s\n", cpuinfo.htt ? "Yes" : "No");
#endif
printf("Logical CPUs = %d\n", cpuinfo.maxlogic);
#ifdef _X86
printf("Threads per core= %u\n", cpuid_x86_threads_per_core());
#endif
if (cpuinfo.cores > 0)
{
printf("CPU cores = %d", cpuinfo.cores);
if (cpuinfo.maxlogic > 0 && cpuinfo.maxlogic != cpu_count)
{
if (cpu_count > cpuinfo.maxlogic)
printf(" (%d total, %d sockets)",
cpu_count,
(cpu_count / cpuinfo.maxlogic));
else
printf(" (%d total)", cpu_count);
}
puts("");
}
cpuinfo.simdsize = cpuid_simdsize(1);
printf("SIMD size = %d ", cpuinfo.simdsize);
if (cpuinfo.simdsize == 1)
printf("(64 bit)\n");
else if (cpuinfo.simdsize == 4)
printf("(128 bit)\n");
else if (cpuinfo.simdsize == 8)
printf("(256 bit)\n");
else if (cpuinfo.simdsize == 16)
printf("(512 bit)\n");
else
printf("(unknown)\n");
if (cpuinfo.flags != NULL)
{
free(cpuinfo.flags);
cpuinfo.flags = NULL;
}
if (cpuinfo.model != NULL)
{
free(cpuinfo.model);
cpuinfo.model = NULL;
}
if (cpuinfo.cputemppath != NULL)
{
free(cpuinfo.cputemppath);
cpuinfo.cputemppath = NULL;
}
return 0;
} |
C | aircrack-ng/lib/libac/cpu/trampoline_arm.c | /*
* Copyright (C) 2018 Joseph Benden <[email protected]>
*
* 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
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#if defined(__arm__) || defined(__aarch64__)
#ifdef HAS_AUXV
#include <sys/auxv.h>
#include <asm/hwcap.h>
#endif
#else
#error "The wrong CPU architecture file has been included."
#endif
#include "aircrack-ng/cpu/trampoline.h"
void simd_init(void) {}
void simd_destroy(void) {}
int simd_get_supported_features(void)
{
int result = 0;
#ifdef HAS_AUXV
long hwcaps = getauxval(AT_HWCAP);
#if defined(HWCAP_ASIMD)
if (hwcaps & HWCAP_ASIMD)
{
result |= SIMD_SUPPORTS_ASIMD;
}
#endif
#if defined(HWCAP_NEON)
if (hwcaps & HWCAP_NEON)
{
result |= SIMD_SUPPORTS_NEON;
}
#endif
#elif defined(__aarch64__) && !defined(HAS_AUXV)
result |= SIMD_SUPPORTS_ASIMD;
#endif
return (result);
} |
C | aircrack-ng/lib/libac/cpu/trampoline_ppc.c | /*
* Copyright (C) 2018 Joseph Benden <[email protected]>
*
* 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
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#if defined(__ppc__) || defined(__PPC__)
#ifdef HAS_AUXV
#include <sys/auxv.h>
#include <bits/hwcap.h>
#endif
#else
#error "The wrong CPU architecture file has been included."
#endif
#include "aircrack-ng/cpu/trampoline.h"
void simd_init(void) {}
void simd_destroy(void) {}
int simd_get_supported_features(void)
{
int result = 0;
#ifdef HAS_AUXV
long hwcaps = getauxval(AT_HWCAP2);
#if defined(PPC_FEATURE2_ARCH_2_07)
if (hwcaps & PPC_FEATURE2_ARCH_2_07)
{
result |= SIMD_SUPPORTS_POWER8;
}
#endif
#endif
return (result);
} |
C | aircrack-ng/lib/libac/cpu/trampoline_stubs.c | /*
* Copyright (C) 2018 Joseph Benden <[email protected]>
*
* 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
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "aircrack-ng/cpu/trampoline.h"
void simd_init(void) {}
void simd_destroy(void) {}
int simd_get_supported_features(void)
{
int result = 0;
return (result);
} |
C | aircrack-ng/lib/libac/cpu/trampoline_x86.c | /*
* Copyright (C) 2018 Joseph Benden <[email protected]>
*
* 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
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#if defined(__i386__) || defined(__x86_64__)
#define _X86
#include <cpuid.h>
#else
#error "The wrong CPU architecture file has been included."
#endif
#include "aircrack-ng/cpu/trampoline.h"
void simd_init(void) {}
void simd_destroy(void) {}
int simd_get_supported_features(void)
{
int result = 0;
unsigned eax = 0, ebx = 0, ecx = 0, edx = 0;
unsigned int max_level = __get_cpuid_max(0, 0);
__cpuid(0, eax, ebx, ecx, edx);
if (eax >= 1)
{
__cpuid(1, eax, ebx, ecx, edx);
}
if (edx & (1 << 23)) //-V525
{
result |= SIMD_SUPPORTS_MMX;
}
if (edx & (1 << 26))
{
result |= SIMD_SUPPORTS_SSE2;
}
if (ecx & (1 << 28))
{
result |= SIMD_SUPPORTS_AVX;
}
if (max_level >= 7)
{
__cpuid_count(7, 0, eax, ebx, ecx, edx);
if (ebx & (1 << 16))
{
result |= SIMD_SUPPORTS_AVX512F;
}
if (ebx & (1 << 5))
{
result |= SIMD_SUPPORTS_AVX2;
}
}
return (result);
} |
C | aircrack-ng/lib/libac/support/common.c | /*
* Common functions for all aircrack-ng tools
*
* Copyright (C) 2006-2018 Thomas d'Otreppe <[email protected]>
*
* 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
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#define _GNU_SOURCE
#include <err.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <dirent.h>
#include <unistd.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>
#include <assert.h>
#include <aircrack-ng/support/common.h>
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) \
|| defined(__DragonFly__) || defined(__MidnightBSD__)
#include <sys/sysctl.h>
#ifndef __NetBSD__
#include <sys/user.h>
#endif
#endif
#if (defined(_WIN32) || defined(_WIN64)) || defined(__CYGWIN32__)
#include <io.h>
#include <windows.h>
#include <errno.h>
#endif
#include "aircrack-ng/defs.h"
#include "aircrack-ng/osdep/osdep.h"
#include "aircrack-ng/osdep/common.h"
#include "aircrack-ng/third-party/ethernet.h"
#define isHex(c) (hexToInt(c) != -1)
#define HEX_BASE 16
/*
* The following function comes from jumbo.c from JTR.
* It has the following license:
*
* This file is Copyright (c) 2013-2014 magnum, Lukasz and JimF,
* and is hereby released to the general public under the
following terms:
* Redistribution and use in source and binary forms, with or
without
* modifications, are permitted.
*/
#if defined(__CYGWIN32__) && !defined(__CYGWIN64__)
int fseeko64(FILE * fp, int64_t offset, int whence)
{
fpos_t pos;
if (whence == SEEK_CUR)
{
if (fgetpos(fp, &pos)) return (-1);
pos += (fpos_t) offset;
}
else if (whence == SEEK_END)
{
/* If writing, we need to flush before getting file length. */
long long size;
fflush(fp);
size = 0;
GetFileSizeEx((HANDLE) _get_osfhandle(fileno(fp)),
(PLARGE_INTEGER) &size);
pos = (fpos_t)(size + offset);
}
else if (whence == SEEK_SET)
pos = (fpos_t) offset;
else
{
errno = EINVAL;
return (-1);
}
return fsetpos(fp, &pos);
}
int64_t ftello64(FILE * fp)
{
fpos_t pos;
if (fgetpos(fp, &pos)) return -1LL;
return (int64_t) pos;
}
#endif
/*
* Print the time and percentage in readable format
*/
void calctime(time_t t, float perc)
{
int days = 0, hours = 0, mins = 0, secs = 0, remain = 0, printed = 0;
char buf[8];
days = t / 86400;
remain = t % 86400;
hours = remain / 3600;
remain = remain % 3600;
mins = remain / 60;
secs = remain % 60;
if (days) printed += printf("%d day%s, ", days, (days > 1 ? "s" : ""));
if (hours) printed += printf("%d hour%s, ", hours, (hours > 1 ? "s" : ""));
if (mins) printed += printf("%d minute%s, ", mins, (mins > 1 ? "s" : ""));
snprintf(buf, sizeof(buf), "%3.2f%%", perc);
printed += printf("%d second%s", secs, (secs != 1 ? "s" : ""));
printf("%*s %s\n", (int) (47 - (printed + strlen(buf) % 5)), " ", buf);
}
int is_string_number(const char * str)
{
int i;
if (str == NULL)
{
return 0;
}
if (*str != '-' && !(isdigit((int) (*str))))
{
return 0;
}
for (i = 1; str[i] != 0; i++)
{
if (!isdigit((int) (str[i])))
{
return 0;
}
}
return 1;
}
int get_ram_size(void)
{
int ret = -1;
#if defined (CTL_HW) && (defined(HW_PHYSMEM) || defined(HW_PHYSMEM64))
#ifdef HW_PHYSMEM64
int mib[] = {CTL_HW, HW_PHYSMEM64};
uint64_t physmem;
#else
int mib[] = {CTL_HW, HW_PHYSMEM};
size_t physmem;
#endif
size_t len;
len = sizeof(physmem);
if (!sysctl(mib, 2, &physmem, &len, NULL, 0))
ret = (physmem / 1024); // Linux returns memory size in kB, so we want
// to as well.
#elif defined(_WIN32) || defined(_WIN64)
MEMORYSTATUSEX statex;
statex.dwLength = sizeof(statex);
if (GlobalMemoryStatusEx(&statex))
{
ret = (int) (statex.ullTotalPhys / 1024);
}
#else
FILE * fp;
char str[100 + 1];
int val = 0;
if (!(fp = fopen("/proc/meminfo", "r")))
{
perror("fopen fails on /proc/meminfo");
return ret;
}
memset(str, 0x00, sizeof(str));
while (ret == -1 && !feof(fp) && fscanf(fp, "%100s %d", str, &val) != 0)
{
if (!(strncmp(str, "MemTotal", 8)))
{
ret = val;
}
}
fclose(fp);
#endif
return ret;
}
/* Return the version number */
char * getVersion(const char * progname,
const unsigned int maj,
const unsigned int min,
const unsigned int submin,
const char * rev,
const unsigned int beta,
const unsigned int rc)
{
if (progname == NULL || progname[0] == 0)
{
fprintf(stderr, "Invalid program name, cannot be NULL or empty\n");
exit(1);
}
if (rc != 0 && beta != 0)
{
fprintf(stderr, "RC and beta cannot be both used\n");
exit(1);
}
char *ret = NULL, *tmp = NULL;
// Major, minor version
int res = asprintf(&ret, "%s %u.%u", progname, maj, min);
if (res < 0) errx(EXIT_FAILURE, "asprintf failed to allocate");
// Sub-minor
if (submin > 0)
{
res = asprintf(&tmp, "%s.%u", ret, submin);
if (res < 0) errx(EXIT_FAILURE, "asprintf failed to allocate");
free(ret); // free previous
ret = tmp; // keep new
}
// Release candidate ...
if (rc > 0)
{
res = asprintf(&tmp, "%s rc%u", ret, rc);
if (res < 0) errx(EXIT_FAILURE, "asprintf failed to allocate");
free(ret); // free previous
ret = tmp; // keep new
}
else if (beta > 0)
{ // ... Or beta
res = asprintf(&tmp, "%s beta%u", ret, beta);
if (res < 0) errx(EXIT_FAILURE, "asprintf failed to allocate");
free(ret); // free previous
ret = tmp; // keep new
}
// Add revision if it comes from subversion or git
if (rev)
{
char * rev_tmp = strdup(rev);
ALLEGE(rev_tmp != NULL);
char * sep = strchr(rev_tmp, '_');
if (sep)
{
++sep;
}
else
{
sep = "";
}
char * search = strstr(sep, "rev-");
if (search)
{
search[3] = ' ';
}
res = asprintf(&tmp, "%s %s", ret, search ? search : sep);
if (res < 0) errx(EXIT_FAILURE, "asprintf failed to allocate");
free(ret); // free previous
ret = tmp; // keep new
free(rev_tmp); // free buffer modified for display to end-user
}
return (ret);
}
// Return the number of cpu. If detection fails, it will return -1;
int get_nb_cpus(void)
{
int number = -1;
#if defined(_WIN32) || defined(_WIN64)
SYSTEM_INFO sysinfo = {0};
GetSystemInfo(&sysinfo);
number = sysinfo.dwNumberOfProcessors;
#elif defined(__linux__)
char *s, *pos;
FILE * f;
f = fopen("/proc/stat", "r");
if (f != NULL)
{
s = (char *) calloc(1, 81);
if (s != NULL)
{
number = 0;
while (fgets(s, 80, f) != NULL)
{
pos = strstr(s, "cpu");
if (pos != NULL && pos + 3 <= s + 81)
{
if (isdigit(*(pos + 3)) != 0) ++number;
}
}
free(s);
}
fclose(f);
}
#elif defined (CTL_HW) && (defined(HW_NCPU) || defined(HW_NCPUONLINE))
#ifdef HW_NCPUONLINE
int mib[] = {CTL_HW, HW_NCPUONLINE};
#else
int mib[] = {CTL_HW, HW_NCPU};
#endif
size_t len;
unsigned long nbcpu;
len = sizeof(nbcpu);
if (!sysctl(mib, 2, &nbcpu, &len, NULL, 0))
{
number = (int) nbcpu;
}
#elif defined(_SC_NPROCESSORS_ONLN)
// Try the usual method if _SC_NPROCESSORS_ONLN exist
if (number == -1)
{
number = sysconf(_SC_NPROCESSORS_ONLN);
/* Fails on some archs */
if (number < 1)
{
number = -1;
}
}
#endif
return number;
}
// compares two MACs
int maccmp(unsigned char * mac1, unsigned char * mac2)
{
int i = 0;
if (mac1 == NULL || mac2 == NULL) return -1;
for (i = 0; i < 6; i++)
{
if (toupper(mac1[i]) != toupper(mac2[i])) return -1;
}
return 0;
}
/* Return -1 if it's not a hex value and return its value when it's a hex value
*/
int hexCharToInt(unsigned char c)
{
static int table_created = 0;
static int table[256];
int i;
if (table_created == 0)
{
/*
* It may seem a bit long to calculate the table
* but character position depend on the charset used
* Example: EBCDIC
* but it's only done once and then conversion will be really fast
*/
for (i = 0; i < 256; i++)
{
switch ((unsigned char) i)
{
case '0':
table[i] = 0;
break;
case '1':
table[i] = 1;
break;
case '2':
table[i] = 2;
break;
case '3':
table[i] = 3;
break;
case '4':
table[i] = 4;
break;
case '5':
table[i] = 5;
break;
case '6':
table[i] = 6;
break;
case '7':
table[i] = 7;
break;
case '8':
table[i] = 8;
break;
case '9':
table[i] = 9;
break;
case 'A':
case 'a':
table[i] = 10;
break;
case 'B':
case 'b':
table[i] = 11;
break;
case 'C':
case 'c':
table[i] = 12;
break;
case 'D':
case 'd':
table[i] = 13;
break;
case 'E':
case 'e':
table[i] = 14;
break;
case 'F':
case 'f':
table[i] = 15;
break;
default:
table[i] = -1;
}
}
table_created = 1;
}
return table[c];
}
// in: input string
// in_length: length of the string
// out: output string (needs to be already allocated).
// out_length: length of the array
// returns amount of bytes saved to 'out' or -1 if an error happened
int hexStringToArray(char * in,
int in_length,
unsigned char * out,
int out_length)
{
int i, out_pos;
int chars[2];
char * input = in;
unsigned char * output = out;
if (in_length < 2 || out_length < (in_length / 3) + 1 || input == NULL
|| output == NULL)
return -1;
out_pos = 0;
for (i = 0; i < in_length - 1; ++i)
{
if (input[i] == '-' || input[i] == ':' || input[i] == '_'
|| input[i] == ' '
|| input[i] == '.')
{
continue;
}
// Check output array is big enough
if (out_pos >= out_length)
{
return -1;
}
chars[0] = hexCharToInt(input[i]);
// If first char is invalid (or '\0'), don't bother continuing (and you
// really shouldn't).
if (chars[0] < 0 || chars[0] > 15) return -1;
chars[1] = hexCharToInt(input[++i]);
// It should always be a multiple of 2 hex characters with or without
// separator
if (chars[1] < 0 || chars[1] > 15) return -1;
output[out_pos++] = ((chars[0] << 4) + chars[1]) & 0xFF;
}
return out_pos;
}
// Return the mac address bytes (or null if it's not a mac address)
int getmac(const char * macAddress, const int strict, unsigned char * mac)
{
char byte[3];
int i, nbElem;
unsigned n;
if (macAddress == NULL) return 1;
/* Minimum length */
if ((int) strlen(macAddress) < 12) return 1;
memset(mac, 0, 6);
byte[2] = 0;
i = nbElem = 0;
while (macAddress[i] != 0)
{
if (macAddress[i] == '\n' || macAddress[i] == '\r') break;
byte[0] = macAddress[i];
byte[1] = macAddress[i + 1];
if (sscanf(byte, "%x", &n) != 1 && strlen(byte) == 2) return 1;
if (hexCharToInt(byte[1]) < 0) return 1;
mac[nbElem] = n;
i += 2;
nbElem++;
if (macAddress[i] == ':' || macAddress[i] == '-'
|| macAddress[i] == '_')
i++;
}
if ((strict && nbElem != 6) || (!strict && nbElem > 6)) return 1;
return 0;
}
int addMAC(pMAC_t pMAC, unsigned char * mac)
{
pMAC_t cur = pMAC;
if (mac == NULL) return -1;
if (pMAC == NULL) return -1;
while (cur->next != NULL) cur = cur->next;
// alloc mem
cur->next = (pMAC_t) malloc(sizeof(struct MAC_list));
ALLEGE(cur->next != NULL);
cur = cur->next;
// set mac
memcpy(cur->mac, mac, 6);
cur->next = NULL;
return 0;
}
int getMACcount(pMAC_t pMAC)
{
pMAC_t cur = pMAC;
int count = 0;
if (pMAC == NULL) return (-1);
while (cur->next != NULL)
{
cur = cur->next;
count++;
}
return (count);
}
int flushMACs(pMAC_t pMAC)
{
pMAC_t old;
pMAC_t cur;
cur = pMAC;
if (pMAC == NULL) return -1;
while (cur->next != NULL)
{
old = cur->next;
cur->next = old->next;
memset(old->mac, 0, sizeof(old->mac));
old->next = NULL;
free(old);
}
return (0);
}
// Read a line of characters inputted by the user
int readLine(char line[], int maxlength)
{
int c;
int i = -1;
do
{
// Read char
c = getchar();
if (c == EOF) c = '\0';
line[++i] = (char) c;
if (line[i] == '\n') break;
if (line[i] == '\r') break;
if (line[i] == '\0') break;
} while (i + 1 < maxlength);
// Stop at 'Enter' key pressed or EOF or max number of char read
// Return current size
return i;
}
int hexToInt(char s[], int len)
{
int i = 0;
int convert = -1;
int value = 0;
// Remove leading 0 (and also the second char that can be x or X)
while (i < len)
{
if (s[i] != '0' || (i == 1 && toupper((int) s[i]) != 'X')) break;
++i;
}
// Convert to hex
while (i < len)
{
convert = hexCharToInt((unsigned char) s[i]);
// If conversion failed, return -1
if (convert == -1) return -1;
value = (value * HEX_BASE) + convert;
++i;
}
return value;
}
char * get_current_working_directory(void)
{
char * ret = NULL;
char * wd_realloc = NULL;
size_t wd_size = 0;
do
{
wd_size += PATH_MAX;
wd_realloc = (char *) realloc(ret, wd_size);
if (wd_realloc == NULL)
{
if (ret) free(ret);
return (NULL);
}
memset(wd_realloc, 0, wd_size);
ret = wd_realloc;
wd_realloc = getcwd(ret, wd_size);
if (wd_realloc == NULL && errno != ERANGE)
{
free(ret);
return (NULL);
}
} while (wd_realloc == NULL && errno == ERANGE);
return (ret);
}
int string_has_suffix(const char * str, const char * suf)
{
assert(str && suf);
const char * a = str + strlen(str);
const char * b = suf + strlen(suf);
while (a != str && b != suf)
{
if (*--a != *--b) break;
}
return b == suf && *a == *b;
}
int is_background(void)
{
pid_t grp = tcgetpgrp(STDIN_FILENO);
if (grp == -1)
{
// Piped
return 0;
}
if (grp == getpgrp())
{
// Foreground
return 0;
}
// Background
return 1;
}
int station_compare(const void * a, const void * b)
{
REQUIRE(a != NULL);
REQUIRE(b != NULL);
return (memcmp(a, b, ETHER_ADDR_LEN));
} |
C | aircrack-ng/lib/libac/support/communications.c | /*
* Copyright (C) 2006-2018 Thomas d'Otreppe <[email protected]>
* Copyright (C) 2006-2009 Martin Beck <[email protected]>
* Copyright (C) 2018-2019 Joseph Benden <[email protected]>
*
* 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
*
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. * If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. * If you
* do not wish to do so, delete this exception statement from your
* version. * If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <errno.h>
#include <stdint.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/types.h>
#include "aircrack-ng/defs.h"
#include "aircrack-ng/support/communications.h"
#include "aircrack-ng/crypto/crypto.h"
#include "aircrack-ng/support/pcap_local.h"
#include "aircrack-ng/tui/console.h"
#include "aircrack-ng/utf8/verifyssid.h"
#include "aircrack-ng/osdep/byteorder.h"
#include "aircrack-ng/osdep/packed.h"
#include "aircrack-ng/third-party/ethernet.h"
#include "aircrack-ng/third-party/ieee80211.h"
extern struct communication_options opt;
extern struct devices dev;
struct wif *_wi_in = NULL, *_wi_out = NULL;
uint8_t h80211[4096] __attribute__((aligned(16)));
uint8_t tmpbuf[4096] __attribute__((aligned(16)));
static char strbuf[512] __attribute__((aligned(16)));
int read_packet(struct wif * wi,
void * buf,
uint32_t count,
struct rx_info * ri)
{
REQUIRE(buf != NULL && count > 0);
int rc;
rc = wi_read(wi, NULL, NULL, buf, count, ri);
if (rc == -1)
{
switch (errno)
{
case EAGAIN:
return (0);
default:
perror("wi_read()");
return (-1);
}
}
return (rc);
}
/* A beacon-frame contains a lot of data ordered like this:
* <tag (1 byte)><length(1 byte)><data (length bytes)><tag><length><data>.....
* This functions tries to find a specific tag
*/
static int get_tagged_data(uint8_t * beacon_pkt,
size_t pkt_len,
uint8_t tag,
uint8_t * tag_len, /* Receives length of the data */
uint8_t ** tag_data) /* Receives pointer to data */
{
size_t pos;
size_t
taglen; /* Length of tag-data. Does not include the two-byte tag-header */
uint8_t tagtype;
if (beacon_pkt[0] != 0x80) return -1;
pos = 0;
taglen = 22; /* First 22 bytes contains standard stuff like SRC+DST */
taglen += 12; /* The fixed tags are 12 bytes long */
do
{
pos += taglen + 2;
tagtype = beacon_pkt[pos];
taglen = beacon_pkt[pos + 1];
} while (tagtype != tag && pos < pkt_len - 2);
if (tagtype != tag)
{
/* Tag not found */
return -1;
}
if (pos + 2 + taglen > pkt_len)
{
/* Malformed packet? */
return -1;
}
if (tag_data != NULL)
{
*tag_data = &beacon_pkt[pos + 2];
}
if (tag_len != NULL)
{
*tag_len = taglen;
}
return 0;
}
int get_channel(uint8_t * beacon_pkt, size_t pkt_len)
{
uint8_t * ch;
uint8_t * ht_info;
uint8_t tag_len;
/* Look for the standard tag */
if (get_tagged_data(beacon_pkt, pkt_len, MGNT_PAR_CHANNEL, &tag_len, &ch)
== 0)
{
if (tag_len >= 1)
{
return *ch;
}
}
/* Tag not found, look for the HT information tag used by 11n devices*/
if (get_tagged_data(
beacon_pkt, pkt_len, MGNT_PAR_HT_INFO, &tag_len, &ht_info))
{
/* tag not found... */
return -1;
}
if (tag_len < 1)
{
/* Malformed packet? */
return -1;
}
/* Main channel is first in HT info */
return ht_info[0];
}
int wait_for_beacon(struct wif * wi,
uint8_t * bssid,
uint8_t * capa,
char * essid)
{
int chan = 0;
size_t len = 0;
ssize_t read_len = 0;
uint8_t taglen = 0;
uint8_t pkt_sniff[4096] __attribute__((aligned(16))) = {0};
struct timeval tv, tv2;
char essid2[33];
uint8_t * data = NULL;
gettimeofday(&tv, NULL);
while (1)
{
read_len = len = 0;
while (read_len < 22)
{
read_len = read_packet(wi, pkt_sniff, sizeof(pkt_sniff), NULL);
gettimeofday(&tv2, NULL);
if (((tv2.tv_sec - tv.tv_sec) * 1000000)
+ (tv2.tv_usec - tv.tv_usec)
> 10000 * 1000) // wait 10sec for beacon frame
{
return (-1);
}
if (read_len <= 0) usleep(1);
}
ENSURE(read_len >= 22);
len = (size_t) read_len;
/* Not a beacon-frame? */
if (pkt_sniff[0] != 0x80) continue;
chan = get_channel(pkt_sniff, len);
if (chan < 0) continue;
if (essid == NULL) continue;
/* Look for ESSID (network name), tag 0 */
if (get_tagged_data(pkt_sniff, len, MGNT_PAR_SSID, &taglen, &data))
continue;
if (taglen <= 1)
{
/* Empty ssid. Check only if the bssid match */
if (bssid != NULL
&& memcmp(bssid, pkt_sniff + 10, ETHER_ADDR_LEN) == 0)
break;
else
continue;
}
/* Only use/compare the first 32 chars of an SSID */
if (taglen > 32) taglen = 32;
/* Ignore SSID with weird chars */
if (data[0] < 32 && bssid != NULL
&& memcmp(bssid, pkt_sniff + 10, ETHER_ADDR_LEN) == 0)
{
break;
}
/* if bssid is given, copy essid */
if (bssid != NULL && memcmp(bssid, pkt_sniff + 10, ETHER_ADDR_LEN) == 0
&& *essid == '\0')
{
memset(essid, 0, 33);
memcpy(essid, data, taglen);
break;
}
/* if essid is given, copy bssid AND essid, so we can handle
* case insensitive arguments */
if (bssid != NULL && memcmp(bssid, NULL_MAC, ETHER_ADDR_LEN) == 0
&& strncasecmp(essid, (char *) data, taglen) == 0
&& strlen(essid) == (unsigned) taglen)
{
memset(essid, 0, 33);
memcpy(essid, data, taglen);
memcpy(bssid, pkt_sniff + 10, ETHER_ADDR_LEN);
printf("Found BSSID \"%02X:%02X:%02X:%02X:%02X:%02X\" to "
"given ESSID \"%s\".\n",
bssid[0],
bssid[1],
bssid[2],
bssid[3],
bssid[4],
bssid[5],
essid);
break;
}
/* if essid and bssid are given, check both */
if (bssid != NULL && memcmp(bssid, pkt_sniff + 10, ETHER_ADDR_LEN) == 0
&& *essid != '\0')
{
memset(essid2, 0, 33);
memcpy(essid2, data, taglen);
if (strncasecmp(essid, essid2, taglen) == 0
&& strlen(essid) == (unsigned) taglen)
break;
else
{
printf("For the given BSSID "
"\"%02X:%02X:%02X:%02X:%02X:%02X\", there is an "
"ESSID mismatch!\n",
bssid[0],
bssid[1],
bssid[2],
bssid[3],
bssid[4],
bssid[5]);
printf("Found ESSID \"%s\" vs. specified ESSID \"%s\"\n",
essid2,
essid);
printf("Using the given one, double check it to be "
"sure its correct!\n");
break;
}
}
}
if (capa) memcpy(capa, pkt_sniff + 34, 2);
return (chan);
}
/**
if bssid != NULL its looking for a beacon frame
*/
int attack_check(uint8_t * bssid,
char * essid,
uint8_t * capa,
struct wif * wi,
int ignore_negative_one)
{
int ap_chan = 0, iface_chan = 0;
iface_chan = wi_get_channel(wi);
if (iface_chan == -1 && !ignore_negative_one)
{
PCT;
printf("Couldn't determine current channel for %s, you should either "
"force the operation with --ignore-negative-one or apply a "
"kernel patch\n",
wi_get_ifname(wi));
return (-1);
}
if (bssid != NULL)
{
ap_chan = wait_for_beacon(wi, bssid, capa, essid);
if (ap_chan < 0)
{
PCT;
printf("No such BSSID available.\n");
return (-1);
}
if ((ap_chan != iface_chan)
&& (iface_chan != -1 || !ignore_negative_one))
{
PCT;
printf("%s is on channel %d, but the AP uses channel %d\n",
wi_get_ifname(wi),
iface_chan,
ap_chan);
return (-1);
}
}
return (0);
}
int getnet(struct wif * wi,
uint8_t * capa,
int filter,
int force,
uint8_t * f_bssid,
uint8_t * r_bssid,
uint8_t * r_essid,
int ignore_negative_one,
int nodetect)
{
uint8_t * bssid;
if (nodetect) return (0);
if (filter)
bssid = f_bssid;
else
bssid = r_bssid;
if (memcmp(bssid, NULL_MAC, ETHER_ADDR_LEN) != 0)
{
PCT;
printf("Waiting for beacon frame (BSSID: "
"%02X:%02X:%02X:%02X:%02X:%02X) on channel %d\n",
bssid[0],
bssid[1],
bssid[2],
bssid[3],
bssid[4],
bssid[5],
wi_get_channel(wi));
}
else if (*r_essid != '\0')
{
PCT;
printf("Waiting for beacon frame (ESSID: %s) on channel %d\n",
r_essid,
wi_get_channel(wi));
}
else if (force)
{
PCT;
if (filter)
{
printf("Please specify at least a BSSID (-b) or an ESSID (-e)\n");
}
else
{
printf("Please specify at least a BSSID (-a) or an ESSID (-e)\n");
}
return (1);
}
else
return (0);
if (attack_check(bssid, (char *) r_essid, capa, wi, ignore_negative_one)
!= 0)
{
if (memcmp(bssid, NULL_MAC, ETHER_ADDR_LEN) != 0)
{
if (verifyssid(r_essid) == 0)
{
printf("Please specify an ESSID (-e).\n");
}
}
else
{
if (*r_essid != '\0')
{
printf("Please specify a BSSID (-a).\n");
}
}
return (1);
}
return (0);
}
int filter_packet(unsigned char * h80211, int caplen)
{
REQUIRE(h80211 != NULL);
int z, mi_b, mi_s, mi_d, ext = 0;
if (caplen <= 0) return (1);
z = ((h80211[1] & IEEE80211_FC1_DIR_MASK) != IEEE80211_FC1_DIR_DSTODS) ? 24
: 30;
if ((h80211[0] & IEEE80211_FC0_SUBTYPE_BEACON)
== IEEE80211_FC0_SUBTYPE_BEACON)
{
/* 802.11e QoS */
z += 2;
}
if ((h80211[0] & IEEE80211_FC0_TYPE_MASK)
== IEEE80211_FC0_TYPE_DATA) // if data packet
ext = z - 24; // how many bytes longer than default ieee80211 header
/* check length */
if (caplen - ext < opt.f_minlen || caplen - ext > opt.f_maxlen) return (1);
/* check the frame control bytes */
if ((h80211[0] & IEEE80211_FC0_TYPE_MASK) != (opt.f_type << 2)
&& opt.f_type >= 0)
return (1);
if ((h80211[0] & IEEE80211_FC0_SUBTYPE_CF_ACK_CF_ACK)
!= ((opt.f_subtype << 4) & 0x70)
&& // ignore the leading bit (QoS)
opt.f_subtype >= 0)
return (1);
if ((h80211[1] & IEEE80211_FC1_DIR_TODS) != (opt.f_tods) && opt.f_tods >= 0)
return (1);
if ((h80211[1] & IEEE80211_FC1_DIR_FROMDS) != (opt.f_fromds << 1)
&& opt.f_fromds >= 0)
return (1);
if ((h80211[1] & IEEE80211_FC1_PROTECTED) != (opt.f_iswep << 6)
&& opt.f_iswep >= 0)
return (1);
/* check the extended IV (TKIP) flag */
if (opt.f_type == 2 && opt.f_iswep == 1 && (h80211[z + 3] & 0x20) != 0)
return (1);
/* MAC address checking */
switch (h80211[1] & IEEE80211_FC1_DIR_MASK)
{
case IEEE80211_FC1_DIR_NODS:
mi_b = 16;
mi_s = 10;
mi_d = 4;
break;
case IEEE80211_FC1_DIR_TODS:
mi_b = 4;
mi_s = 10;
mi_d = 16;
break;
case IEEE80211_FC1_DIR_FROMDS:
mi_b = 10;
mi_s = 16;
mi_d = 4;
break;
case IEEE80211_FC1_DIR_DSTODS:
mi_b = 10;
mi_d = 16;
mi_s = 24;
break;
default:
abort();
}
if (memcmp(opt.f_bssid, NULL_MAC, ETHER_ADDR_LEN) != 0)
if (memcmp(h80211 + mi_b, opt.f_bssid, ETHER_ADDR_LEN) != 0) return (1);
if (memcmp(opt.f_bssid, opt.f_smac, ETHER_ADDR_LEN) == 0)
{
if (memcmp(opt.f_smac, NULL_MAC, ETHER_ADDR_LEN) != 0)
if (memcmp(h80211 + mi_s, opt.f_smac, ETHER_ADDR_LEN - 1) != 0)
return (1);
}
else
{
if (memcmp(opt.f_smac, NULL_MAC, ETHER_ADDR_LEN) != 0)
if (memcmp(h80211 + mi_s, opt.f_smac, ETHER_ADDR_LEN) != 0)
return (1);
}
if (memcmp(opt.f_bssid, opt.f_dmac, ETHER_ADDR_LEN) == 0)
{
if (memcmp(opt.f_dmac, NULL_MAC, ETHER_ADDR_LEN) != 0)
if (memcmp(h80211 + mi_d, opt.f_dmac, ETHER_ADDR_LEN - 1) != 0)
return (1);
}
else
{
if (memcmp(opt.f_dmac, NULL_MAC, ETHER_ADDR_LEN) != 0)
if (memcmp(h80211 + mi_d, opt.f_dmac, ETHER_ADDR_LEN) != 0)
return (1);
}
/* this one looks good */
return (0);
}
int capture_ask_packet(int * caplen, int just_grab)
{
REQUIRE(caplen != NULL);
time_t tr;
struct timeval tv = {0};
struct tm * lt;
fd_set rfds;
long nb_pkt_read;
int i, j, n, mi_b = 0, mi_s = 0, mi_d = 0, mi_t = 0, mi_r = 0, is_wds = 0,
key_index_offset;
int ret, z;
FILE * f_cap_out;
struct pcap_file_header pfh_out;
struct pcap_pkthdr pkh;
if (opt.f_minlen < 0) opt.f_minlen = 40;
if (opt.f_maxlen < 0) opt.f_maxlen = 1500;
if (opt.f_type < 0) opt.f_type = 2;
if (opt.f_subtype < 0) opt.f_subtype = 0;
if (opt.f_iswep < 0) opt.f_iswep = 1;
tr = time(NULL);
nb_pkt_read = 0;
signal(SIGINT, SIG_DFL);
while (1)
{
if (time(NULL) - tr > 0)
{
tr = time(NULL);
printf("\rRead %ld packets...\r", nb_pkt_read);
fflush(stdout);
}
if (opt.s_file == NULL)
{
FD_ZERO(&rfds);
FD_SET(dev.fd_in, &rfds);
tv.tv_sec = 1;
tv.tv_usec = 0;
if (select(dev.fd_in + 1, &rfds, NULL, NULL, &tv) < 0)
{
if (errno == EINTR) continue;
perror("select failed");
return (EXIT_FAILURE);
}
if (!FD_ISSET(dev.fd_in, &rfds)) continue;
gettimeofday(&tv, NULL);
*caplen = read_packet(_wi_in, h80211, sizeof(h80211), NULL);
if (*caplen < 0) return (EXIT_FAILURE);
if (*caplen == 0) continue;
}
else
{
/* there are no hidden backdoors in this source code */
n = sizeof(pkh);
if (fread(&pkh, n, 1, dev.f_cap_in) != 1)
{
printf("\r");
erase_line(0);
printf("End of file.\n");
return (EXIT_FAILURE);
}
if (dev.pfh_in.magic == TCPDUMP_CIGAM)
{
SWAP32(pkh.caplen);
SWAP32(pkh.len);
}
tv.tv_sec = pkh.tv_sec;
tv.tv_usec = pkh.tv_usec;
n = *caplen = pkh.caplen;
if (n <= 0 || n > (int) sizeof(h80211) || n > (int) sizeof(tmpbuf))
{
printf("\r");
erase_line(0);
printf("Invalid packet length %d.\n", n);
return (EXIT_FAILURE);
}
if (fread(h80211, n, 1, dev.f_cap_in) != 1)
{
printf("\r");
erase_line(0);
printf("End of file.\n");
return (EXIT_FAILURE);
}
if (dev.pfh_in.linktype == LINKTYPE_PRISM_HEADER)
{
/* remove the prism header */
if (h80211[7] == 0x40)
n = 64;
else
n = *(int *) (h80211 + 4); //-V1032
if (n < 8 || n >= (int) *caplen) continue;
memcpy(tmpbuf, h80211, *caplen);
*caplen -= n;
memcpy(h80211, tmpbuf + n, *caplen);
}
if (dev.pfh_in.linktype == LINKTYPE_RADIOTAP_HDR)
{
/* remove the radiotap header */
n = *(unsigned short *) (h80211 + 2); //-V1032
if (n <= 0 || n >= (int) *caplen) continue;
memcpy(tmpbuf, h80211, *caplen);
*caplen -= n;
memcpy(h80211, tmpbuf + n, *caplen);
}
if (dev.pfh_in.linktype == LINKTYPE_PPI_HDR)
{
/* remove the PPI header */
n = le16_to_cpu(*(unsigned short *) (h80211 + 2)); //-V1032
if (n <= 0 || n >= (int) *caplen) continue;
/* for a while Kismet logged broken PPI headers */
if (n == 24
&& le16_to_cpu(*(unsigned short *) (h80211 + 8)) == 2)
n = 32;
if (n <= 0 || n >= (int) *caplen) continue; //-V560
memcpy(tmpbuf, h80211, *caplen);
*caplen -= n;
memcpy(h80211, tmpbuf + n, *caplen);
}
}
nb_pkt_read++;
if (filter_packet(h80211, *caplen) != 0) continue;
if (opt.fast) break;
z = ((h80211[1] & IEEE80211_FC1_DIR_MASK) != IEEE80211_FC1_DIR_DSTODS)
? 24
: 30;
if ((h80211[0] & IEEE80211_FC0_SUBTYPE_QOS)
== IEEE80211_FC0_SUBTYPE_QOS) /* QoS */
z += 2;
switch (h80211[1] & IEEE80211_FC1_DIR_MASK)
{
case IEEE80211_FC1_DIR_NODS:
mi_b = 16;
mi_s = 10;
mi_d = 4;
is_wds = 0;
break;
case IEEE80211_FC1_DIR_TODS:
mi_b = 4;
mi_s = 10;
mi_d = 16;
is_wds = 0;
break;
case IEEE80211_FC1_DIR_FROMDS:
mi_b = 10;
mi_s = 16;
mi_d = 4;
is_wds = 0;
break;
case IEEE80211_FC1_DIR_DSTODS:
mi_t = 10;
mi_r = 4;
mi_d = 16;
mi_s = 24;
is_wds = 1;
break; // WDS packet
default:
abort();
}
printf("\n\n Size: %d, FromDS: %d, ToDS: %d",
*caplen,
(h80211[1] & IEEE80211_FC1_DIR_FROMDS) >> 1,
(h80211[1] & IEEE80211_FC1_DIR_TODS));
if ((h80211[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_DATA
&& (h80211[1] & IEEE80211_FC1_WEP) != 0)
{
// if (is_wds) key_index_offset = 33; // WDS packets
// have an additional MAC, so the key index is at byte
// 33
// else key_index_offset = 27;
key_index_offset = z + 3;
if ((h80211[key_index_offset] & 0x20) == 0)
printf(" (WEP)");
else
printf(" (WPA)");
}
printf("\n\n");
if (is_wds)
{
printf(" Transmitter = %02X:%02X:%02X:%02X:%02X:%02X\n",
h80211[mi_t],
h80211[mi_t + 1],
h80211[mi_t + 2],
h80211[mi_t + 3],
h80211[mi_t + 4],
h80211[mi_t + 5]);
printf(" Receiver = %02X:%02X:%02X:%02X:%02X:%02X\n",
h80211[mi_r],
h80211[mi_r + 1],
h80211[mi_r + 2],
h80211[mi_r + 3],
h80211[mi_r + 4],
h80211[mi_r + 5]);
}
else
{
printf(" BSSID = %02X:%02X:%02X:%02X:%02X:%02X\n",
h80211[mi_b],
h80211[mi_b + 1],
h80211[mi_b + 2],
h80211[mi_b + 3],
h80211[mi_b + 4],
h80211[mi_b + 5]);
}
printf(" Dest. MAC = %02X:%02X:%02X:%02X:%02X:%02X\n",
h80211[mi_d],
h80211[mi_d + 1],
h80211[mi_d + 2],
h80211[mi_d + 3],
h80211[mi_d + 4],
h80211[mi_d + 5]);
printf(" Source MAC = %02X:%02X:%02X:%02X:%02X:%02X\n",
h80211[mi_s],
h80211[mi_s + 1],
h80211[mi_s + 2],
h80211[mi_s + 3],
h80211[mi_s + 4],
h80211[mi_s + 5]);
/* print a hex dump of the packet */
for (i = 0; i < *caplen; i++)
{
if ((i & 15) == 0)
{
if (i == 224)
{
printf("\n --- CUT ---");
break;
}
printf("\n 0x%04x: ", i);
}
printf("%02x", h80211[i]); //-V781
if ((i & 1) != 0) printf(" ");
if (i == *caplen - 1 && ((i + 1) & 15) != 0)
{
for (j = ((i + 1) & 15); j < 16; j++)
{
printf(" ");
if ((j & 1) != 0) printf(" ");
}
printf(" ");
for (j = 16 - ((i + 1) & 15); j < 16; j++)
printf("%c",
(h80211[i - 15 + j] < 32 || h80211[i - 15 + j] > 126)
? '.'
: h80211[i - 15 + j]);
}
if (i > 0 && ((i + 1) & 15) == 0)
{
printf(" ");
for (j = 0; j < 16; j++)
printf("%c",
(h80211[i - 15 + j] < 32 || h80211[i - 15 + j] > 127)
? '.'
: h80211[i - 15 + j]);
}
}
printf("\n\nUse this packet ? ");
fflush(stdout);
ret = 0;
while (!ret) ret = scanf("%1s", tmpbuf); //-V576
printf("\n");
if (tmpbuf[0] == 'y' || tmpbuf[0] == 'Y') break;
}
if (!just_grab)
{
pfh_out.magic = TCPDUMP_MAGIC;
pfh_out.version_major = PCAP_VERSION_MAJOR;
pfh_out.version_minor = PCAP_VERSION_MINOR;
pfh_out.thiszone = 0;
pfh_out.sigfigs = 0;
pfh_out.snaplen = 65535;
pfh_out.linktype = LINKTYPE_IEEE802_11;
lt = localtime((const time_t *) &tv.tv_sec);
REQUIRE(lt != NULL);
memset(strbuf, 0, sizeof(strbuf));
snprintf(strbuf,
sizeof(strbuf) - 1,
"replay_src-%02d%02d-%02d%02d%02d.cap",
lt->tm_mon + 1,
lt->tm_mday,
lt->tm_hour,
lt->tm_min,
lt->tm_sec);
printf("Saving chosen packet in %s\n", strbuf);
if ((f_cap_out = fopen(strbuf, "wb+")) == NULL)
{
perror("fopen failed");
return (EXIT_FAILURE);
}
n = sizeof(struct pcap_file_header);
if (fwrite(&pfh_out, n, 1, f_cap_out) != 1)
{
fclose(f_cap_out);
perror("fwrite failed\n");
return (EXIT_FAILURE);
}
pkh.tv_sec = tv.tv_sec;
pkh.tv_usec = tv.tv_usec;
pkh.caplen = *caplen;
pkh.len = *caplen;
n = sizeof(pkh);
if (fwrite(&pkh, n, 1, f_cap_out) != 1)
{
fclose(f_cap_out);
perror("fwrite failed");
return (EXIT_FAILURE);
}
n = pkh.caplen;
if (fwrite(h80211, n, 1, f_cap_out) != 1)
{
fclose(f_cap_out);
perror("fwrite failed");
return (EXIT_FAILURE);
}
fclose(f_cap_out);
}
return (EXIT_SUCCESS);
}
#define AIRODUMP_NG_CSV_EXT "csv"
#define KISMET_CSV_EXT "kismet.csv"
#define KISMET_NETXML_EXT "kismet.netxml"
#define AIRODUMP_NG_GPS_EXT "gps"
#define AIRODUMP_NG_CAP_EXT "cap"
#define AIRODUMP_NG_LOG_CSV_EXT "log.csv"
static const char * f_ext[] = {AIRODUMP_NG_CSV_EXT,
AIRODUMP_NG_GPS_EXT,
AIRODUMP_NG_CAP_EXT,
IVS2_EXTENSION,
KISMET_CSV_EXT,
KISMET_NETXML_EXT,
AIRODUMP_NG_LOG_CSV_EXT};
/* setup the output files */
int dump_initialize_multi_format(char * prefix, int ivs_only)
{
REQUIRE(prefix != NULL);
REQUIRE(*prefix != '\0');
const size_t ADDED_LENGTH = 17;
size_t i;
size_t ofn_len;
FILE * f;
char * ofn = NULL;
/* If you only want to see what happening, send all data to /dev/null */
/* Create a buffer of the length of the prefix + '-' + 2 numbers + '.'
+ longest extension ("kismet.netxml") + terminating 0. */
ofn_len = strlen(prefix) + ADDED_LENGTH + 1;
ofn = (char *) calloc(1, ofn_len);
ALLEGE(ofn != NULL);
opt.f_index = 1;
/* Make sure no file with the same name & all possible file extensions. */
do
{
for (i = 0; i < ArrayCount(f_ext); i++)
{
memset(ofn, 0, ofn_len);
snprintf(ofn, ofn_len, "%s-%02d.%s", prefix, opt.f_index, f_ext[i]);
if ((f = fopen(ofn, "rb+")) != NULL)
{
fclose(f);
opt.f_index++;
break;
}
}
}
/* If we did all extensions then no file with that name or extension exist
so we can use that number */
while (i < ArrayCount(f_ext));
opt.prefix = (char *) calloc(1, strlen(prefix) + 1);
ALLEGE(opt.prefix != NULL);
memcpy(opt.prefix, prefix, strlen(prefix) + 1);
/* create the output CSV file */
if (opt.output_format_csv)
{
memset(ofn, 0, ofn_len);
snprintf(ofn,
ofn_len,
"%s-%02d.%s",
prefix,
opt.f_index,
AIRODUMP_NG_CSV_EXT);
if ((opt.f_txt = fopen(ofn, "wb+")) == NULL)
{
perror("fopen failed");
fprintf(stderr, "Could not create \"%s\".\n", ofn);
free(ofn);
return (1);
}
}
/* create the output for a rolling log CSV file */
if (opt.output_format_log_csv)
{
memset(ofn, 0, ofn_len);
snprintf(ofn,
ofn_len,
"%s-%02d.%s",
prefix,
opt.f_index,
AIRODUMP_NG_LOG_CSV_EXT);
if ((opt.f_logcsv = fopen(ofn, "wb+")) == NULL)
{
perror("fopen failed");
fprintf(stderr, "Could not create \"%s\".\n", ofn);
free(ofn);
return (1);
}
fprintf(opt.f_logcsv,
"LocalTime, GPSTime, ESSID, BSSID, Power, "
"Security, Latitude, Longitude, Latitude Error, "
"Longitude Error, Type\r\n");
}
/* create the output Kismet CSV file */
if (opt.output_format_kismet_csv)
{
memset(ofn, 0, ofn_len);
snprintf(
ofn, ofn_len, "%s-%02d.%s", prefix, opt.f_index, KISMET_CSV_EXT);
if ((opt.f_kis = fopen(ofn, "wb+")) == NULL)
{
perror("fopen failed");
fprintf(stderr, "Could not create \"%s\".\n", ofn);
free(ofn);
return (1);
}
}
/* create the output GPS file */
if (opt.usegpsd)
{
memset(ofn, 0, ofn_len);
snprintf(ofn,
ofn_len,
"%s-%02d.%s",
prefix,
opt.f_index,
AIRODUMP_NG_GPS_EXT);
if ((opt.f_gps = fopen(ofn, "wb+")) == NULL)
{
perror("fopen failed");
fprintf(stderr, "Could not create \"%s\".\n", ofn);
free(ofn);
return (1);
}
}
/* Create the output kismet.netxml file */
if (opt.output_format_kismet_netxml)
{
memset(ofn, 0, ofn_len);
snprintf(
ofn, ofn_len, "%s-%02d.%s", prefix, opt.f_index, KISMET_NETXML_EXT);
if ((opt.f_kis_xml = fopen(ofn, "wb+")) == NULL)
{
perror("fopen failed");
fprintf(stderr, "Could not create \"%s\".\n", ofn);
free(ofn);
return (1);
}
}
/* create the output packet capture file */
if (opt.output_format_pcap)
{
struct pcap_file_header pfh;
memset(ofn, 0, ofn_len);
snprintf(ofn,
ofn_len,
"%s-%02d.%s",
prefix,
opt.f_index,
AIRODUMP_NG_CAP_EXT);
if ((opt.f_cap = fopen(ofn, "wb+")) == NULL)
{
perror("fopen failed");
fprintf(stderr, "Could not create \"%s\".\n", ofn);
free(ofn);
return (1);
}
opt.f_cap_name = (char *) calloc(1, strlen(ofn) + 1);
ALLEGE(opt.f_cap_name != NULL);
memcpy(opt.f_cap_name, ofn, strlen(ofn) + 1);
pfh.magic = TCPDUMP_MAGIC;
pfh.version_major = PCAP_VERSION_MAJOR;
pfh.version_minor = PCAP_VERSION_MINOR;
pfh.thiszone = 0;
pfh.sigfigs = 0;
pfh.snaplen = 65535;
pfh.linktype = LINKTYPE_IEEE802_11;
if (fwrite(&pfh, 1, sizeof(pfh), opt.f_cap) != (size_t) sizeof(pfh))
{
perror("fwrite(pcap file header) failed");
free(ofn);
return (1);
}
if (!opt.quiet)
{
PCT;
printf("Created capture file \"%s\".\n", ofn);
}
free(ofn);
}
else if (ivs_only)
{
struct ivs2_filehdr fivs2;
fivs2.version = IVS2_VERSION;
memset(ofn, 0, ofn_len);
snprintf(
ofn, ofn_len, "%s-%02d.%s", prefix, opt.f_index, IVS2_EXTENSION);
if ((opt.f_ivs = fopen(ofn, "wb+")) == NULL)
{
perror("fopen failed");
fprintf(stderr, "Could not create \"%s\".\n", ofn);
free(ofn);
return (1);
}
free(ofn);
if (fwrite(IVS2_MAGIC, 1, 4, opt.f_ivs) != (size_t) 4)
{
perror("fwrite(IVs file MAGIC) failed");
return (1);
}
if (fwrite(&fivs2, 1, sizeof(struct ivs2_filehdr), opt.f_ivs)
!= (size_t) sizeof(struct ivs2_filehdr))
{
perror("fwrite(IVs file header) failed");
return (1);
}
}
else
{
free(ofn);
}
return (0);
}
int dump_initialize(char * prefix)
{
opt.output_format_pcap = 1;
return dump_initialize_multi_format(prefix, 0);
}
int check_shared_key(const uint8_t * h80211, size_t caplen)
{
int m_bmac = 16;
int m_smac = 10;
int m_dmac = 4;
size_t n;
size_t textlen;
int maybe_broken;
char ofn[1024];
uint8_t text[4096];
uint8_t prga[4096 + 4];
unsigned int long crc = 0xFFFFFFFF;
if (!(h80211 != NULL && caplen > 0
&& caplen < (int) sizeof(opt.sharedkey[0])))
{
return (1);
}
if (time(NULL) - opt.sk_start > 5)
{
/* timeout(5sec) - remove all packets, restart timer */
memset(opt.sharedkey, '\x00', sizeof(opt.sharedkey));
opt.sk_start = time(NULL);
}
/* is auth packet */
if ((h80211[1] & IEEE80211_FC1_PROTECTED) != IEEE80211_FC1_PROTECTED)
{
/* not encrypted */
if ((h80211[24] + (h80211[25] << 8)) == 1)
{
/* Shared-Key Authentication */
if ((h80211[26] + (h80211[27] << 8)) == 2)
{
/* sequence == 2 */
memcpy(opt.sharedkey[0], h80211, caplen);
opt.sk_len = caplen - 24;
}
if ((h80211[26] + (h80211[27] << 8)) == 4)
{
/* sequence == 4 */
memcpy(opt.sharedkey[2], h80211, caplen);
}
}
else
return (1);
}
else
{
/* encrypted */
memcpy(opt.sharedkey[1], h80211, caplen);
opt.sk_len2 = caplen - 24 - 4;
}
/* check if the 3 packets form a proper authentication */
if ((memcmp(opt.sharedkey[0] + m_bmac, NULL_MAC, ETHER_ADDR_LEN) == 0)
|| (memcmp(opt.sharedkey[1] + m_bmac, NULL_MAC, ETHER_ADDR_LEN) == 0)
|| (memcmp(opt.sharedkey[2] + m_bmac, NULL_MAC, ETHER_ADDR_LEN)
== 0)) /* some bssids == zero */
{
return (1);
}
if ((memcmp(opt.sharedkey[0] + m_bmac,
opt.sharedkey[1] + m_bmac,
ETHER_ADDR_LEN)
!= 0)
|| (memcmp(opt.sharedkey[0] + m_bmac,
opt.sharedkey[2] + m_bmac,
ETHER_ADDR_LEN)
!= 0)) /* all bssids aren't equal */
{
return (1);
}
if ((memcmp(opt.sharedkey[0] + m_smac,
opt.sharedkey[2] + m_smac,
ETHER_ADDR_LEN)
!= 0)
|| (memcmp(opt.sharedkey[0] + m_smac,
opt.sharedkey[1] + m_dmac,
ETHER_ADDR_LEN)
!= 0)) /* SA in 2&4 != DA in 3 */
{
return (1);
}
if ((memcmp(opt.sharedkey[0] + m_dmac,
opt.sharedkey[2] + m_dmac,
ETHER_ADDR_LEN)
!= 0)
|| (memcmp(opt.sharedkey[0] + m_dmac,
opt.sharedkey[1] + m_smac,
ETHER_ADDR_LEN)
!= 0)) /* DA in 2&4 != SA in 3 */
{
return (1);
}
textlen = opt.sk_len;
maybe_broken = 0;
/* this check is probably either broken or not very reliable,
since there are known cases when it is hit with valid data.
rather than doing a hard exit here, we now set a flag so
the .xor file is only written if not already existing, in
order to make sure we don't overwrite a good .xor file with
a potentially broken one; but on the other hand if none exist
already, we do want it being written. */
if (textlen + 4 != opt.sk_len2)
{
if (!opt.quiet)
{
PCT;
printf("Broken SKA: %02X:%02X:%02X:%02X:%02X:%02X (expected: %zu, "
"got %zu bytes)\n",
*(opt.sharedkey[0] + m_dmac),
*(opt.sharedkey[0] + m_dmac + 1),
*(opt.sharedkey[0] + m_dmac + 2),
*(opt.sharedkey[0] + m_dmac + 3),
*(opt.sharedkey[0] + m_dmac + 4),
*(opt.sharedkey[0] + m_dmac + 5),
textlen + 4,
opt.sk_len2);
}
maybe_broken = 1;
}
if (textlen > sizeof(text) - 4) return (1);
memcpy(text, opt.sharedkey[0] + 24, textlen);
/* increment sequence number from 2 to 3 */
text[2] = (uint8_t)(text[2] + 1);
for (n = 0; n < textlen; n++)
crc = crc_tbl[(crc ^ text[n]) & 0xFF] ^ (crc >> 8);
crc = ~crc;
/* append crc32 over body */
text[textlen] = (uint8_t)((crc) &0xFF);
text[textlen + 1] = (uint8_t)((crc >> 8) & 0xFF);
text[textlen + 2] = (uint8_t)((crc >> 16) & 0xFF);
text[textlen + 3] = (uint8_t)((crc >> 24) & 0xFF);
/* cleartext XOR cipher */
for (n = 0u; n < (textlen + 4u); n++)
{
prga[4 + n] = (uint8_t)((text[n] ^ opt.sharedkey[1][28 + n]) & 0xFF);
}
/* write IV+index */
prga[0] = (uint8_t)(opt.sharedkey[1][24] & 0xFF);
prga[1] = (uint8_t)(opt.sharedkey[1][25] & 0xFF);
prga[2] = (uint8_t)(opt.sharedkey[1][26] & 0xFF);
prga[3] = (uint8_t)(opt.sharedkey[1][27] & 0xFF);
if (opt.f_xor != NULL)
{
fclose(opt.f_xor);
opt.f_xor = NULL;
}
snprintf(ofn,
sizeof(ofn) - 1,
"%s-%02d-%02X-%02X-%02X-%02X-%02X-%02X.%s",
opt.prefix,
opt.f_index,
*(opt.sharedkey[0] + m_bmac),
*(opt.sharedkey[0] + m_bmac + 1),
*(opt.sharedkey[0] + m_bmac + 2),
*(opt.sharedkey[0] + m_bmac + 3),
*(opt.sharedkey[0] + m_bmac + 4),
*(opt.sharedkey[0] + m_bmac + 5),
"xor");
if (maybe_broken && (opt.f_xor = fopen(ofn, "r")))
{
/* do not overwrite existing .xor file with maybe broken one */
fclose(opt.f_xor);
opt.f_xor = NULL;
return (1);
}
opt.f_xor = fopen(ofn, "w");
if (opt.f_xor == NULL) return (1);
for (n = 0; n < textlen + 8; n++) fputc((prga[n] & 0xFF), opt.f_xor);
fclose(opt.f_xor);
opt.f_xor = NULL;
if (!opt.quiet)
{
PCT;
printf("Got %zu bytes keystream: %02X:%02X:%02X:%02X:%02X:%02X\n",
textlen + 4,
*(opt.sharedkey[0] + m_dmac),
*(opt.sharedkey[0] + m_dmac + 1),
*(opt.sharedkey[0] + m_dmac + 2),
*(opt.sharedkey[0] + m_dmac + 3),
*(opt.sharedkey[0] + m_dmac + 4),
*(opt.sharedkey[0] + m_dmac + 5));
}
memset(opt.sharedkey, '\x00', sizeof(opt.sharedkey));
return (0);
}
int encrypt_data(uint8_t * data, size_t length)
{
uint8_t cipher[4096];
uint8_t K[128];
if (data == NULL) return (1);
if (length < 1 || length > 2044) return (1);
if (opt.prga == NULL && opt.crypt != CRYPT_WEP)
{
printf("Please specify a WEP key (-w).\n");
return (1);
}
if (opt.prgalen - 4 < length && opt.crypt != CRYPT_WEP)
{
printf(
"Please specify a longer PRGA file (-y) with at least %zu bytes.\n",
(length + 4));
return (1);
}
/* encrypt data */
if (opt.crypt == CRYPT_WEP)
{
K[0] = rand_u8();
K[1] = rand_u8();
K[2] = rand_u8();
memcpy(K + 3, opt.wepkey, opt.weplen);
encrypt_wep(data, (int) length, K, (int) opt.weplen + 3);
memcpy(cipher, data, length);
memcpy(data + 4, cipher, length);
memcpy(data, K, 3); //-V512
data[3] = 0x00;
}
return (0);
}
int create_wep_packet(uint8_t * packet, size_t * length, size_t hdrlen)
{
if (packet == NULL) return (1);
if (length == NULL) return (1);
if (hdrlen >= INT_MAX) return (1);
if (*length >= INT_MAX) return (1);
if (*length - hdrlen >= INT_MAX) return (1);
/* write crc32 value behind data */
if (add_crc32(packet + hdrlen, (int) (*length - hdrlen)) != 0) return (1);
/* encrypt data+crc32 and keep a 4byte hole */
if (encrypt_data(packet + hdrlen, *length - hdrlen + 4) != 0) return (1);
/* set WEP bit */
packet[1] = (uint8_t)(packet[1] | 0x40);
*length += 8;
/* now you got yourself a shiny, brand new encrypted wep packet ;) */
return (0);
}
int set_clear_arp(uint8_t * buf,
uint8_t * smac,
uint8_t * dmac) // set first 22 bytes
{
if (buf == NULL) return (-1);
memcpy(buf, S_LLC_SNAP_ARP, 8);
buf[8] = 0x00;
buf[9] = 0x01; // ethernet
buf[10] = 0x08; // IP
buf[11] = 0x00;
buf[12] = 0x06; // hardware size
buf[13] = 0x04; // protocol size
buf[14] = 0x00;
if (memcmp(dmac, BROADCAST, ETHER_ADDR_LEN) == 0)
buf[15] = 0x01; // request
else
buf[15] = 0x02; // reply
memcpy(buf + 16, smac, ETHER_ADDR_LEN);
return (0);
}
int set_final_arp(uint8_t * buf, uint8_t * mymac)
{
if (buf == NULL) return (-1);
// shifted by 10bytes to set source IP as target IP :)
buf[0] = 0x08; //-V525 // IP
buf[1] = 0x00;
buf[2] = 0x06; // hardware size
buf[3] = 0x04; // protocol size
buf[4] = 0x00;
buf[5] = 0x01; // request
memcpy(buf + 6, mymac, ETHER_ADDR_LEN); // sender mac
buf[12] = 0xA9; // sender IP 169.254.87.197
buf[13] = 0xFE;
buf[14] = 0x57;
buf[15] = 0xC5; // end sender IP
return (0);
}
int set_clear_ip(uint8_t * buf, size_t ip_len) // set first 9 bytes
{
if (buf == NULL) return (-1);
memcpy(buf, S_LLC_SNAP_IP, 8);
buf[8] = 0x45;
buf[10] = (uint8_t)((ip_len >> 8) & 0xFF);
buf[11] = (uint8_t)(ip_len & 0xFF);
return (0);
}
int set_final_ip(uint8_t * buf, uint8_t * mymac)
{
if (buf == NULL) return (-1);
// shifted by 10bytes to set source IP as target IP :)
buf[0] = 0x06; // hardware size
buf[1] = 0x04; // protocol size
buf[2] = 0x00;
buf[3] = 0x01; // request
memcpy(buf + 4, mymac, ETHER_ADDR_LEN); // sender mac
buf[10] = 0xA9; // sender IP from 169.254.XXX.XXX
buf[11] = 0xFE;
buf[12] = 0x57;
buf[13] = 0xC5; // end sender IP
return (0);
}
int msleep(int msec)
{
struct timeval tv, tv2;
float f, ticks;
int n;
ssize_t rc;
if (msec == 0) msec = 1;
ticks = 0;
while (1)
{
/* wait for the next timer interrupt, or sleep */
if (dev.fd_rtc >= 0)
{
if ((rc = read(dev.fd_rtc, &n, sizeof(n))) < 0)
{
perror("read(/dev/rtc) failed");
}
else if (rc == 0)
{
perror("EOF encountered on /dev/rtc");
}
else
{
ticks++;
}
}
else
{
/* we can't trust usleep, since it depends on the HZ */
gettimeofday(&tv, NULL);
usleep(1024);
gettimeofday(&tv2, NULL);
f = 1000000 * (float) (tv2.tv_sec - tv.tv_sec)
+ (float) (tv2.tv_usec - tv.tv_usec);
ticks += f / 1024;
}
if ((ticks / 1024 * 1000) < msec) continue;
/* threshold reached */
break;
}
return (0);
}
int read_prga(unsigned char ** dest, char * file)
{
FILE * f;
ssize_t size;
if (file == NULL) return (EXIT_FAILURE);
if (*dest == NULL)
{
*dest = (unsigned char *) malloc(1501);
ALLEGE(*dest != NULL);
}
if (memcmp(file + (strlen(file) - 4), ".xor", 4) != 0)
{
printf("Is this really a PRGA file: %s?\n", file);
}
f = fopen(file, "r");
if (f == NULL)
{
printf("Error opening %s\n", file);
return (EXIT_FAILURE);
}
fseek(f, 0, SEEK_END);
size = ftell(f);
if (size == -1)
{
fclose(f);
fprintf(stderr, "ftell failed\n");
return (EXIT_FAILURE);
}
rewind(f);
if (size > 1500) size = 1500;
if (fread((*dest), (size_t) size, 1, f) != 1)
{
fclose(f);
fprintf(stderr, "fread failed\n");
return (EXIT_FAILURE);
}
if ((*dest)[3] > 0x03)
{
printf("Are you really sure that this is a valid key-stream? Because "
"the index is out of range (0-3): %02X\n",
(*dest)[3]);
}
opt.prgalen = (size_t) size;
fclose(f);
return (EXIT_SUCCESS);
}
int set_bitrate(struct wif * wi, int rate)
{
size_t j;
int i;
int newrate;
if (wi_set_rate(wi, rate)) return (1);
// Workaround for buggy drivers (rt73) that do not accept 5.5M, but 5M
// instead
if (rate == 5500000 && wi_get_rate(wi) != 5500000)
{
if (wi_set_rate(wi, 5000000)) return (1);
}
newrate = wi_get_rate(wi);
for (j = 0; j < ArrayCount(bitrates); j++)
{
if (bitrates[j] == rate) break;
}
if (j == ArrayCount(bitrates))
i = -1;
else
i = (int) j;
if (newrate != rate)
{
if (i != -1)
{
if (i > 0)
{
if (bitrates[i - 1] >= newrate)
{
printf(
"Couldn't set rate to %.1fMBit. (%.1fMBit instead)\n",
(rate / 1000000.0),
(wi_get_rate(wi) / 1000000.0));
return (1);
}
}
if (i < (int) ArrayCount(bitrates) - 1)
{
if (bitrates[i + 1] <= newrate)
{
printf(
"Couldn't set rate to %.1fMBit. (%.1fMBit instead)\n",
(rate / 1000000.0),
(wi_get_rate(wi) / 1000000.0));
return (1);
}
}
return (0);
}
printf("Couldn't set rate to %.1fMBit. (%.1fMBit instead)\n",
(rate / 1000000.0),
(wi_get_rate(wi) / 1000000.0));
return (1);
}
return (0);
} |
C | aircrack-ng/lib/libac/support/crypto_engine_loader.c | /*
* Copyright (C) 2018 Joseph Benden <[email protected]>
*
* 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
* is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
* NON-INFRINGEMENT. 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.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#ifndef STATIC_BUILD
#include <dlfcn.h>
#endif
#include "aircrack-ng/ce-wpa/crypto_engine.h"
#include "aircrack-ng/support/crypto_engine_loader.h"
#include "aircrack-ng/support/common.h"
#include "aircrack-ng/cpu/trampoline.h"
#ifndef STATIC_BUILD
static void * module = NULL;
#endif
#ifdef STATIC_BUILD
int (*dso_ac_crypto_engine_init)(ac_crypto_engine_t * engine)
= &ac_crypto_engine_init;
void (*dso_ac_crypto_engine_destroy)(ac_crypto_engine_t * engine)
= &ac_crypto_engine_destroy;
void (*dso_ac_crypto_engine_set_essid)(ac_crypto_engine_t * engine,
const uint8_t * essid)
= &ac_crypto_engine_set_essid;
int (*dso_ac_crypto_engine_thread_init)(ac_crypto_engine_t * engine,
int threadid)
= &ac_crypto_engine_thread_init;
void (*dso_ac_crypto_engine_thread_destroy)(ac_crypto_engine_t * engine,
int threadid)
= &ac_crypto_engine_thread_destroy;
int (*dso_ac_crypto_engine_simd_width)(void) = &ac_crypto_engine_simd_width;
int (*dso_ac_crypto_engine_wpa_crack)(
ac_crypto_engine_t * engine,
const wpapsk_password key[MAX_KEYS_PER_CRYPT_SUPPORTED],
const uint8_t eapol[256],
uint32_t eapol_size,
uint8_t mic[MAX_KEYS_PER_CRYPT_SUPPORTED][20],
uint8_t keyver,
const uint8_t cmpmic[20],
int nparallel,
int threadid)
= &ac_crypto_engine_wpa_crack;
void (*dso_ac_crypto_engine_calc_pke)(ac_crypto_engine_t * engine,
const uint8_t bssid[6],
const uint8_t stmac[6],
const uint8_t anonce[32],
const uint8_t snonce[32],
int threadid)
= &ac_crypto_engine_calc_pke;
int (*dso_ac_crypto_engine_wpa_pmkid_crack)(
ac_crypto_engine_t * engine,
const wpapsk_password key[MAX_KEYS_PER_CRYPT_SUPPORTED],
const uint8_t pmkid[32],
int nparallel,
int threadid)
= &ac_crypto_engine_wpa_pmkid_crack;
void (*dso_ac_crypto_engine_set_pmkid_salt)(ac_crypto_engine_t * engine,
const uint8_t bssid[6],
const uint8_t stmac[6],
int threadid)
= &ac_crypto_engine_set_pmkid_salt;
int (*dso_ac_crypto_engine_supported_features)(void)
= &ac_crypto_engine_supported_features;
uint8_t * (*dso_ac_crypto_engine_get_pmk)(ac_crypto_engine_t * engine,
int threadid,
int index)
= &ac_crypto_engine_get_pmk;
uint8_t * (*dso_ac_crypto_engine_get_ptk)(ac_crypto_engine_t * engine,
int threadid,
int index)
= &ac_crypto_engine_get_ptk;
void (*dso_ac_crypto_engine_calc_one_pmk)(const uint8_t * key,
const uint8_t * essid,
uint32_t essid_length,
uint8_t pmk[40])
= &ac_crypto_engine_calc_one_pmk;
void (*dso_ac_crypto_engine_calc_pmk)(
ac_crypto_engine_t * engine,
const wpapsk_password key[MAX_KEYS_PER_CRYPT_SUPPORTED],
int nparallel,
int threadid)
= &ac_crypto_engine_calc_pmk;
void (*dso_ac_crypto_engine_calc_mic)(ac_crypto_engine_t * engine,
const uint8_t eapol[256],
const uint32_t eapol_size,
uint8_t mic[MAX_KEYS_PER_CRYPT_SUPPORTED]
[20],
const uint8_t keyver,
const int vectorIdx,
const int threadid)
= &ac_crypto_engine_calc_mic;
#else
int (*dso_ac_crypto_engine_init)(ac_crypto_engine_t * engine) = NULL;
void (*dso_ac_crypto_engine_destroy)(ac_crypto_engine_t * engine) = NULL;
void (*dso_ac_crypto_engine_set_essid)(ac_crypto_engine_t * engine,
const uint8_t * essid)
= NULL;
int (*dso_ac_crypto_engine_thread_init)(ac_crypto_engine_t * engine,
int threadid)
= NULL;
void (*dso_ac_crypto_engine_thread_destroy)(ac_crypto_engine_t * engine,
int threadid)
= NULL;
int (*dso_ac_crypto_engine_simd_width)(void) = NULL;
int (*dso_ac_crypto_engine_wpa_crack)(
ac_crypto_engine_t * engine,
const wpapsk_password key[MAX_KEYS_PER_CRYPT_SUPPORTED],
const uint8_t eapol[256],
uint32_t eapol_size,
uint8_t mic[MAX_KEYS_PER_CRYPT_SUPPORTED][20],
uint8_t keyver,
const uint8_t cmpmic[20],
int nparallel,
int threadid)
= NULL;
void (*dso_ac_crypto_engine_calc_pke)(ac_crypto_engine_t * engine,
const uint8_t bssid[6],
const uint8_t stmac[6],
const uint8_t anonce[32],
const uint8_t snonce[32],
int threadid)
= NULL;
int (*dso_ac_crypto_engine_wpa_pmkid_crack)(
ac_crypto_engine_t * engine,
const wpapsk_password key[MAX_KEYS_PER_CRYPT_SUPPORTED],
const uint8_t pmkid[32],
int nparallel,
int threadid)
= NULL;
void (*dso_ac_crypto_engine_set_pmkid_salt)(ac_crypto_engine_t * engine,
const uint8_t bssid[6],
const uint8_t stmac[6],
int threadid)
= NULL;
int (*dso_ac_crypto_engine_supported_features)(void) = NULL;
uint8_t * (*dso_ac_crypto_engine_get_pmk)(ac_crypto_engine_t * engine,
int threadid,
int index)
= NULL;
uint8_t * (*dso_ac_crypto_engine_get_ptk)(ac_crypto_engine_t * engine,
int threadid,
int index)
= NULL;
void (*dso_ac_crypto_engine_calc_one_pmk)(const uint8_t * key,
const uint8_t * essid,
uint32_t essid_length,
uint8_t pmk[40])
= NULL;
void (*dso_ac_crypto_engine_calc_pmk)(
ac_crypto_engine_t * engine,
const wpapsk_password key[MAX_KEYS_PER_CRYPT_SUPPORTED],
int nparallel,
int threadid)
= NULL;
void (*dso_ac_crypto_engine_calc_mic)(ac_crypto_engine_t * engine,
const uint8_t eapol[256],
const uint32_t eapol_size,
uint8_t mic[MAX_KEYS_PER_CRYPT_SUPPORTED]
[20],
const uint8_t keyver,
const int vectorIdx,
const int threadid)
= NULL;
#endif
#if defined(WIN32_PORTABLE)
/*
This is merely a hack until code refactoring can occur.
A new module is needed for handling file and path operations, because
this here is only a step towards correctly getting the executable
path for all operating systems.
It was required for Cygwin to determine the location of the
Crypto Engine DLLs which are in the same folder as the
executable.
*/
#include <stdarg.h>
#include <stdio.h>
#include <wtypes.h>
#include <wchar.h>
#include <sys/cygwin.h>
#include <windows.h>
#include <shlwapi.h>
static char * get_executable_directory(void)
{
HMODULE hModule = GetModuleHandle(NULL);
CHAR path[MAX_PATH];
GetModuleFileNameA(hModule, path, MAX_PATH);
PathRemoveFileSpecA(path);
cygwin_conv_path_t flags = CCP_WIN_A_TO_POSIX;
char * winpath = (char *) cygwin_create_path(flags, path);
return winpath;
}
#endif
EXPORT int ac_crypto_engine_loader_get_available(void)
{
int simd_flags = SIMD_SUPPORTS_NONE;
char library_path[8192];
#if defined(WIN32_PORTABLE)
char * working_directory = get_executable_directory();
#else
// are we inside of the build path?
char * working_directory = get_current_working_directory();
#endif
REQUIRE(working_directory != NULL);
if (strncmp(working_directory, ABS_TOP_BUILDDIR, strlen(ABS_TOP_BUILDDIR))
== 0)
{
// use development paths
snprintf(library_path,
sizeof(library_path) - 1,
"%s%s",
LIBAIRCRACK_CE_WPA_PATH,
LT_OBJDIR);
}
else
{
#if defined(WIN32_PORTABLE)
// use the current directory
snprintf(library_path, sizeof(library_path) - 1, working_directory);
#else
// use installation paths
snprintf(library_path, sizeof(library_path) - 1, "%s", LIBDIR);
#endif
}
free(working_directory);
// enumerate all DSOs in folder, opening, searching symbols, and testing
// them.
DIR * dsos = opendir(library_path);
if (!dsos) goto out;
struct dirent * entry = NULL;
while ((entry = readdir(dsos)) != NULL)
{
#if defined(__APPLE__)
if (string_has_suffix((char *) entry->d_name, ".dylib"))
#elif defined(WIN32) || defined(_WIN32) || defined(CYGWIN)
if (string_has_suffix((char *) entry->d_name, ".dll"))
#else
if (string_has_suffix((char *) entry->d_name, ".so"))
#endif
{
char * search = strstr(entry->d_name, "aircrack-ce-wpa-");
if (search)
{
search += 16;
int flag;
if ((flag = ac_crypto_engine_loader_string_to_flag(search))
!= -1)
simd_flags |= flag;
}
}
}
closedir(dsos);
out:
return simd_flags;
}
EXPORT char * ac_crypto_engine_loader_best_library_for(int simd_features)
{
char buffer[8192] = {"aircrack-ce-wpa"};
char library_path[8192];
char module_filename[8192];
size_t buffer_remaining = 8192 - strlen(buffer) - 1;
if (simd_features & SIMD_SUPPORTS_AVX512F)
{
strncat(buffer, "-x86-avx512", buffer_remaining);
}
else if (simd_features & SIMD_SUPPORTS_AVX2)
{
strncat(buffer, "-x86-avx2", buffer_remaining);
}
else if (simd_features & SIMD_SUPPORTS_AVX)
{
strncat(buffer, "-x86-avx", buffer_remaining);
}
else if (simd_features & SIMD_SUPPORTS_SSE2)
{
strncat(buffer, "-x86-sse2", buffer_remaining);
}
else if (simd_features & SIMD_SUPPORTS_ASIMD)
{
strncat(buffer, "-arm-neon", buffer_remaining);
}
else if (simd_features & SIMD_SUPPORTS_NEON)
{
strncat(buffer, "-arm-neon", buffer_remaining);
}
else if (simd_features & SIMD_SUPPORTS_POWER8)
{
strncat(buffer, "-ppc-power8", buffer_remaining);
}
else if (simd_features & SIMD_SUPPORTS_ALTIVEC)
{
strncat(buffer, "-ppc-altivec", buffer_remaining);
}
char * working_directory
= get_current_working_directory(); // or the binary's path?
REQUIRE(working_directory != NULL);
if (strncmp(
working_directory, ABS_TOP_BUILDDIR, sizeof(ABS_TOP_BUILDDIR) - 1)
== 0)
{
// use development paths
snprintf(library_path,
sizeof(library_path) - 1,
"%s%s",
LIBAIRCRACK_CE_WPA_PATH,
LT_OBJDIR);
}
else
{
// use installation paths
snprintf(library_path, sizeof(library_path) - 1, "%s", LIBDIR);
}
free(working_directory);
#if defined(WIN32_PORTABLE)
#define LIB_FMT "%s%s%s"
#else
#define LIB_FMT "%s/%s%s%s", library_path
#endif
#if defined(WIN32) || defined(_WIN32) || defined(CYGWIN)
#if defined(MSYS2)
#define LIB_PREFIX "msys-"
#else
#define LIB_PREFIX "cyg"
#endif
#else
#define LIB_PREFIX "lib"
#endif
#if defined(WIN32) || defined(_WIN32) || defined(CYGWIN)
#define LIB_SUFFIX LT_CYGWIN_VER
#elif defined(__APPLE__)
#define LIB_SUFFIX ".dylib"
#else
#define LIB_SUFFIX ".so"
#endif
snprintf(module_filename,
sizeof(module_filename) - 1,
LIB_FMT,
LIB_PREFIX,
buffer,
LIB_SUFFIX)
< 0
? abort()
: (void) 0;
return strdup(module_filename);
}
EXPORT int ac_crypto_engine_loader_string_to_flag(const char * const str)
{
int simd_features = -1;
if (strncmp(str, "avx512", 6) == 0 || strncmp(str, "x86-avx512", 10) == 0)
simd_features = SIMD_SUPPORTS_AVX512F;
else if (strncmp(str, "avx2", 4) == 0 || strncmp(str, "x86-avx2", 8) == 0)
simd_features = SIMD_SUPPORTS_AVX2;
else if (strncmp(str, "avx", 3) == 0 || strncmp(str, "x86-avx", 7) == 0)
simd_features = SIMD_SUPPORTS_AVX;
else if (strncmp(str, "sse2", 4) == 0 || strncmp(str, "x86-sse2", 8) == 0)
simd_features = SIMD_SUPPORTS_SSE2;
else if (strncmp(str, "neon", 4) == 0 || strncmp(str, "arm-neon", 8) == 0)
simd_features = SIMD_SUPPORTS_NEON;
else if (strncmp(str, "asimd", 5) == 0 || strncmp(str, "arm-asimd", 9) == 0)
simd_features = SIMD_SUPPORTS_ASIMD;
else if (strncmp(str, "altivec", 7) == 0
|| strncmp(str, "ppc-altivec", 11) == 0)
simd_features = SIMD_SUPPORTS_ALTIVEC;
else if (strncmp(str, "power8", 6) == 0
|| strncmp(str, "ppc-power8", 10) == 0)
simd_features = SIMD_SUPPORTS_POWER8;
else if (strncmp(str, "generic", 7) == 0)
simd_features = SIMD_SUPPORTS_NONE;
return simd_features;
}
EXPORT char * ac_crypto_engine_loader_flags_to_string(int flags)
{
char buffer[8192] = {0};
if (flags & SIMD_SUPPORTS_AVX512F) strncat(buffer, "avx512 ", 8);
if (flags & SIMD_SUPPORTS_AVX2) strncat(buffer, "avx2 ", 6);
if (flags & SIMD_SUPPORTS_AVX) strncat(buffer, "avx ", 5);
if (flags & SIMD_SUPPORTS_SSE2) strncat(buffer, "sse2 ", 6);
if (flags & SIMD_SUPPORTS_NEON) strncat(buffer, "neon ", 6);
if (flags & SIMD_SUPPORTS_ASIMD) strncat(buffer, "asimd ", 7);
if (flags & SIMD_SUPPORTS_ALTIVEC) strncat(buffer, "altivec ", 9);
if (flags & SIMD_SUPPORTS_POWER8) strncat(buffer, "power8 ", 8);
strncat(buffer, "generic", 8);
return strdup(buffer);
}
EXPORT int ac_crypto_engine_loader_load(int flags)
{
#ifndef STATIC_BUILD
if (flags == -1) flags = ac_crypto_engine_loader_get_available();
char * module_filename = ac_crypto_engine_loader_best_library_for(flags);
REQUIRE(module_filename != NULL);
module = dlopen(module_filename, RTLD_LAZY);
if (!module)
{
const char * msg = dlerror();
fprintf(stderr,
"Could not open '%s': %s\n",
module_filename,
msg ? msg : "<none reported>");
free(module_filename);
return 1;
}
// resolve symbols needed
struct _dso_symbols
{
char const * sym;
void * addr;
} dso_symbols[] = {
{"ac_crypto_engine_init", (void *) &dso_ac_crypto_engine_init},
{"ac_crypto_engine_destroy", (void *) &dso_ac_crypto_engine_destroy},
{"ac_crypto_engine_thread_init",
(void *) &dso_ac_crypto_engine_thread_init},
{"ac_crypto_engine_thread_destroy",
(void *) &dso_ac_crypto_engine_thread_destroy},
{"ac_crypto_engine_set_essid",
(void *) &dso_ac_crypto_engine_set_essid},
{"ac_crypto_engine_simd_width",
(void *) &dso_ac_crypto_engine_simd_width},
{"ac_crypto_engine_wpa_crack",
(void *) &dso_ac_crypto_engine_wpa_crack},
{"ac_crypto_engine_wpa_pmkid_crack",
(void *) &dso_ac_crypto_engine_wpa_pmkid_crack},
{"ac_crypto_engine_calc_pke", (void *) &dso_ac_crypto_engine_calc_pke},
{"ac_crypto_engine_set_pmkid_salt",
(void *) &dso_ac_crypto_engine_set_pmkid_salt},
{"ac_crypto_engine_supported_features",
(void *) &dso_ac_crypto_engine_supported_features},
{"ac_crypto_engine_get_pmk", (void *) &dso_ac_crypto_engine_get_pmk},
{"ac_crypto_engine_get_ptk", (void *) &dso_ac_crypto_engine_get_ptk},
{"ac_crypto_engine_calc_one_pmk",
(void *) &dso_ac_crypto_engine_calc_one_pmk},
{"ac_crypto_engine_calc_pmk", (void *) &dso_ac_crypto_engine_calc_pmk},
{"ac_crypto_engine_calc_mic", (void *) &dso_ac_crypto_engine_calc_mic},
{NULL, NULL}};
struct _dso_symbols * cur = &dso_symbols[0];
for (; cur->addr != NULL; ++cur)
{
if (!(*((void **) cur->addr) = dlsym(module, cur->sym)))
{
fprintf(stderr,
"Could not find symbol %s in %s.\n",
cur->sym,
module_filename);
dlclose(module);
free(module_filename);
return 1;
}
}
free(module_filename);
#else
(void) flags;
#endif
return 0;
}
EXPORT void ac_crypto_engine_loader_unload(void)
{
#ifndef STATIC_BUILD
dlclose(module);
module = NULL;
dso_ac_crypto_engine_init = NULL;
dso_ac_crypto_engine_destroy = NULL;
dso_ac_crypto_engine_thread_init = NULL;
dso_ac_crypto_engine_thread_destroy = NULL;
dso_ac_crypto_engine_set_essid = NULL;
dso_ac_crypto_engine_simd_width = NULL;
dso_ac_crypto_engine_wpa_crack = NULL;
dso_ac_crypto_engine_calc_pke = NULL;
dso_ac_crypto_engine_supported_features = NULL;
#endif
} |