コード例 #1
0
ファイル: ext_mcrypt.cpp プロジェクト: scottmac/hiphop-dev
static Variant mcrypt_generic(CObjRef td, CStrRef data, bool dencrypt) {
  MCrypt *pm = td.getTyped<MCrypt>();
  if (!pm->m_init) {
    raise_warning("Operation disallowed prior to mcrypt_generic_init().");
    return false;
  }

  if (data.empty()) {
    raise_warning("An empty string was passed");
    return false;
  }

  unsigned char* data_s;
  int block_size, data_size;
  /* Check blocksize */
  if (mcrypt_enc_is_block_mode(pm->m_td) == 1) { /* It's a block algorithm */
    block_size = mcrypt_enc_get_block_size(pm->m_td);
    data_size = (((data.size() - 1) / block_size) + 1) * block_size;
    data_s = (unsigned char*)malloc(data_size + 1);
    memset(data_s, 0, data_size);
    memcpy(data_s, data.data(), data.size());
  } else { /* It's not a block algorithm */
    data_size = data.size();
    data_s = (unsigned char*)malloc(data_size + 1);
    memcpy(data_s, data.data(), data.size());
  }

  if (dencrypt) {
    mdecrypt_generic(pm->m_td, data_s, data_size);
  } else {
    mcrypt_generic(pm->m_td, data_s, data_size);
  }
  data_s[data_size] = '\0';
  return String((char*)data_s, data_size, AttachString);
}
コード例 #2
0
/* iv should be NULL for ECB mode */
static int cached_cipher_prepare(struct cached_cipher * cipher,
                                 unsigned char * key, unsigned char * iv)
{
    int err;

    /* not yet initialized or new key */
    if(!cipher->valid ||
       memcmp(cipher->key, key, 8))
    {
        if(cipher->valid)
            mcrypt_generic_deinit(cipher->cipher);
        cipher->valid = 0;

        err = mcrypt_generic_init(cipher->cipher, key, 8, iv);
        if(err < 0)
            return err;

        memcpy(cipher->key, key, 8);
        cipher->valid = 1;
    }
    else if(iv)		/* update IV, works for CBC decryption */
    {
        unsigned char dummy[8];
        memcpy(dummy, iv, 8);
        err = mdecrypt_generic(cipher->cipher, dummy, 8);
        if(err < 0)
            return err;
    }
    return 0;
}
コード例 #3
0
ファイル: client.c プロジェクト: jjpestacio/cs111-spring2016
void *process_server_output(void *read_from_server) {

  char buffer;
  while(1) {

    // EOF read from server, so exit
    if(read(*((int *)read_from_server), &buffer, NREAD) == 0)
      signal(SIGPIPE, signal_handler);

    // Write encrypted server output to log
    if(log_on) {
      write(log_fd, &LOG_RECEIVED_PREFIX, RECEIVED_PREFIX_LENGTH);
      write(log_fd, &buffer, NREAD);
      write(log_fd, &LF, 1);
    }

    // Decrypt server output
    if(encrypt_on && mdecrypt_generic(td, &buffer, NREAD)) {
      fprintf(stderr, "Error: could not decrypt from server.\n");
      exit(RC=EXIT_FAILURE);
    }

    // Write server output to stdout
    write(STDOUT_FILENO, &buffer, NREAD);
  }
  
  return NULL;
}
コード例 #4
0
ファイル: htcaes.c プロジェクト: GCrean/ruuveal
static int decrypt_chunk(MCRYPT td, char *buf, int size, char *key, char *iv)
{
    char new_iv[HTC_AES_KEYSIZE];
    memcpy(new_iv, &buf[size - HTC_AES_KEYSIZE], HTC_AES_KEYSIZE);
    mcrypt_generic_init(td, key, HTC_AES_KEYSIZE, iv);
    mdecrypt_generic(td, buf, size);
    mcrypt_generic_deinit(td);
    memcpy(iv, new_iv, HTC_AES_KEYSIZE);
}
コード例 #5
0
ファイル: epoc.c プロジェクト: alx-s/emokit
int epoc_get_next_raw(unsigned char frame[32], unsigned char raw_frame[32]) {
    //Two blocks of 16 bytes must be read.
    if (memcpy (block_buffer, raw_frame, blocksize)) {
        mdecrypt_generic (td, block_buffer, blocksize);
        memcpy(frame, block_buffer, 16);
    }
    else {
        return -1;
    }
    
    if (memcpy(block_buffer, raw_frame + blocksize, blocksize)) {
        mdecrypt_generic (td, block_buffer, blocksize);
        memcpy(frame + 16, block_buffer, 16);
    }
    else {
        return -1;
    }
    return 0;
}
コード例 #6
0
EMOKIT_DECLSPEC int emokit_get_next_raw(emokit_device* s) {
	//Two blocks of 16 bytes must be read.
	if (memcpy (s->block_buffer, s->raw_frame, s->blocksize)) {
		mdecrypt_generic (s->td, s->block_buffer, s->blocksize);
		memcpy(s->raw_unenc_frame, s->block_buffer, 16);
	}
	else {
		return -1;
	}
    
	if (memcpy(s->block_buffer, s->raw_frame + s->blocksize, s->blocksize)) {
		mdecrypt_generic (s->td, s->block_buffer, s->blocksize);
		memcpy(s->raw_unenc_frame + 16, s->block_buffer, 16);
	}
	else {
		return -1;
	}
	return 0;
}
コード例 #7
0
ファイル: libgrg_tmp.c プロジェクト: shlomif/gringotts
int
grg_tmpfile_read (const GRG_CTX gctx, const GRG_TMPFILE tf,
		  unsigned char **data, long *data_len)
{
	long dim;
	unsigned char *enc_data;

	if (!gctx || !tf)
		return GRG_ARGUMENT_ERR;

	if (tf->rwmode != READABLE)
		return GRG_TMP_NOT_YET_WRITTEN;

	if (mcrypt_generic_init (tf->crypt, tf->key, tf->dKey, tf->IV) < 0)
		return GRG_READ_ENC_INIT_ERR;

	lseek (tf->tmpfd, 0, SEEK_SET);

	read (tf->tmpfd, &dim, sizeof (long));

	enc_data = (unsigned char *) malloc (dim + HEADER_LEN);
	if (!enc_data)
		return GRG_MEM_ALLOCATION_ERR;

	read (tf->tmpfd, enc_data, dim + HEADER_LEN);

	if (mdecrypt_generic (tf->crypt, enc_data, dim + HEADER_LEN))
	{
		grg_unsafe_free (enc_data);
		return GRG_READ_ENC_INIT_ERR;
	}

	if (memcmp (enc_data, gctx->header, HEADER_LEN) != 0)
	{
		grg_unsafe_free (enc_data);
		return GRG_READ_PWD_ERR;
	}

	*data = grg_memdup (enc_data + HEADER_LEN, dim);
	if (!data)
	{
		grg_unsafe_free (enc_data);
		return GRG_MEM_ALLOCATION_ERR;
	}

	if (data_len)
		*data_len = dim;

	grg_unsafe_free (enc_data);

	return GRG_OK;
}
コード例 #8
0
int decrypt_buffer(void* buf, int buf_len, char* key, int key_len){
    MCRYPT td = mcrypt_module_open("rijndael-128", NULL, "cbc", NULL);
    int blocksize = mcrypt_enc_get_block_size(td);
    if(buf_len % blocksize != 0){
        return -1;
    }

    mcrypt_generic_init(td, key, key_len, IV);
    mdecrypt_generic(td, buf, buf_len);
    mcrypt_generic_deinit (td);
    mcrypt_module_close(td);
    return 0;
}
コード例 #9
0
ファイル: crypto.c プロジェクト: zerot13/panox
void Decrypt(const char *encrypted, unsigned char *decrypted)
{
	int encLength = strlen(encrypted);
	HexToBinary(encrypted, decrypted);

	MCRYPT mc = mcrypt_module_open("blowfish", NULL, "ecb", NULL);
	if(mc == MCRYPT_FAILED)
	{
		printf("Failed\n");
	}
	char *key = "R=U!LH$O2B#";
	mcrypt_generic_init(mc, key, 11, "");
	mdecrypt_generic(mc, decrypted, encLength/2);
}
コード例 #10
0
ファイル: mhash.c プロジェクト: sunyangkobe/cscd43
static int
cipher_decrypt(PX_Cipher * c, const uint8 *data, unsigned dlen, uint8 *res)
{
	int			err;
	MCRYPT		ctx = (MCRYPT) c->ptr;

	memcpy(res, data, dlen);

	err = mdecrypt_generic(ctx, res, dlen);
	if (err < 0)
		ereport(ERROR,
				(errcode(ERRCODE_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION),
				 errmsg("mdecrypt_generic error"),
				 errdetail("%s", mcrypt_strerror(err))));
	return 0;
}
コード例 #11
0
ファイル: crypt.c プロジェクト: ctos/ctos-crypt
int dencrypt(char *password, char *ciphertext, char *plaintext)
{

	MCRYPT td;
	int i;
	char *key;
	char block_buffer;
	char *IV;
	char *salt;	
	
	td = mcrypt_module_open(algorithm, NULL, mode, NULL);
	if (td==MCRYPT_FAILED)
	{
		return 1;
	}

	salt = crypt_malloc(saltsize);
        IV = crypt_malloc(ivsize);

	read_meg(ciphertext, salt, IV);

        i=mcrypt_generic_init( td, key, keysize, IV);
        if (i<0) 
	{
        	mcrypt_perror(i);
        	return 1;
        }
//	printf("%d",strlen(plaintext));
        for(i=saltsize + ivsize; i<=strlen(ciphertext); i++)
	{
//		printf("%c",plaintext[i]);
		block_buffer=ciphertext[i];
//Here begin to decrypt
       		mdecrypt_generic (td, &block_buffer, 1); 
        	plaintext[i]=block_buffer; 
//		printf("%c",ciphertext[i]);
	}

         mcrypt_generic_end(td);

         return 0;

       }
コード例 #12
0
ファイル: a7-decrypter.c プロジェクト: adeptex/SLAE
int main() 
{
	MCRYPT m;
	if ((m = mcrypt_module_open("rijndael-128", NULL, "cbc", NULL)) == MCRYPT_FAILED) { printf("MCRYPT failed\n"); return 0; }
	
	int key_len = strlen(vector) - mcrypt_enc_get_iv_size(m);
	unsigned char* key = malloc(key_len);
	unsigned char* iv = malloc(mcrypt_enc_get_iv_size(m));

	memcpy(key, &vector, key_len);
	memcpy(iv, &vector[key_len], mcrypt_enc_get_iv_size(m));
	
	if (mcrypt_generic_init(m, key, strlen(key), iv) < 0) { printf("init failed\n"); return 0; }
	if (mdecrypt_generic(m, code, strlen(code))) { printf("decrypt failed\n"); return 0; }
	if (mcrypt_generic_deinit(m) < 0) { printf("deinit failed\n"); return 0; }
	mcrypt_module_close(m);

	printf ("[*] Vector: ");
	for (int i = 0; i < strlen(vector); i++) { 
		printf("%02x", vector[i] & 0xff); 
	}
	printf ("\n[*] Vector Length: %d\n", strlen(vector));
	printf ("[*] Key: ");
	for (int i = 0; i < strlen(key); i++) { 
		printf("%02x", key[i] & 0xff); 
	}
	printf ("\n[*] Key Length: %d\n", key_len);
	printf ("[*] IV: ");
	for (int i = 0; i < strlen(iv); i++) { 
		printf("%02x", iv[i] & 0xff); 
	}
	printf ("\n[*] IV Length: %d\n", strlen(iv));
	printf("\n[+] Shellcode: \n\n");
	for (int i = 0; i < strlen(code); i++) { 
		printf("\\x%x", code[i] & 0xff); 
	}
	printf("\n");

	int (*ret)() = (int(*)())code;
	ret();
	return 0;
}
コード例 #13
0
ファイル: ext_mcrypt.cpp プロジェクト: bd808/hhvm
static Variant mcrypt_generic(const Resource& td, const String& data,
                              bool dencrypt) {
  auto pm = cast<MCrypt>(td);
  if (!pm->m_init) {
    raise_warning("Operation disallowed prior to mcrypt_generic_init().");
    return false;
  }

  if (data.empty()) {
    raise_warning("An empty string was passed");
    return false;
  }

  String s;
  unsigned char* data_s;
  int block_size, data_size;
  /* Check blocksize */
  if (mcrypt_enc_is_block_mode(pm->m_td) == 1) { /* It's a block algorithm */
    block_size = mcrypt_enc_get_block_size(pm->m_td);
    data_size = (((data.size() - 1) / block_size) + 1) * block_size;
    s = String(data_size, ReserveString);
    data_s = (unsigned char *)s.mutableData();
    memset(data_s, 0, data_size);
    memcpy(data_s, data.data(), data.size());
  } else { /* It's not a block algorithm */
    data_size = data.size();
    s = String(data_size, ReserveString);
    data_s = (unsigned char *)s.mutableData();
    memcpy(data_s, data.data(), data.size());
  }

  if (dencrypt) {
    mdecrypt_generic(pm->m_td, data_s, data_size);
  } else {
    mcrypt_generic(pm->m_td, data_s, data_size);
  }
  s.setSize(data_size);
  return s;
}
コード例 #14
0
int descrypt_decrypt(void * dataptr, unsigned char * block, size_t cryptlen,
                     const unsigned char * fragkey, struct himderrinfo * status)
{
    unsigned char finalfragkey[8];
    unsigned char mainkey[8];
    struct descrypt_data * data = dataptr;
    int err;

    xor_keys(finalfragkey, data->masterkey, fragkey);
    if((err = cached_cipher_prepare(&data->master, finalfragkey, NULL)) < 0)
    {
        set_status_printf(status, HIMD_ERROR_ENCRYPTION_FAILURE, _("Can't setup track key: %s"), mcrypt_strerror(err));
        return -1;
    }

    memcpy(mainkey, block+16, 8);
    if((err = mcrypt_generic(data->master.cipher, mainkey, 8)) < 0)
    {
        set_status_printf(status, HIMD_ERROR_ENCRYPTION_FAILURE, _("Can't calc block key: %s"), mcrypt_strerror(err));
        return -1;
    }

    if((err = cached_cipher_prepare(&data->block, mainkey, block + 24)) < 0)
    {
        set_status_printf(status, HIMD_ERROR_ENCRYPTION_FAILURE, _("Can't setup block key: %s"), mcrypt_strerror(err));
        return -1;
    }

    if((err = mdecrypt_generic(data->block.cipher, block+32, cryptlen)) < 0)
    {
        set_status_printf(status, HIMD_ERROR_ENCRYPTION_FAILURE, _("Can't decrypt: %s"), mcrypt_strerror(err));
        return -1;
    }

    return 0;
}
コード例 #15
0
ファイル: cipher_test.c プロジェクト: Bromvlieg/libmcrypt
int main()
{
	MCRYPT td, td2;
	int i, t, imax;
	int j, jmax, ivsize;
	int x = 0, siz;
	char **names;
	char **modes;
	char *text;
	unsigned char *IV;
	unsigned char *key;
	int keysize;
	
	names = mcrypt_list_algorithms (ALGORITHMS_DIR, &jmax);
	modes = mcrypt_list_modes (MODES_DIR, &imax);

	if (names==NULL || modes==NULL) {
		fprintf(stderr, "Error getting algorithms/modes\n");
		exit(1);
	}
	
	for (j=0;j<jmax;j++) {
		printf( "Algorithm: %s... ", names[j]);

		if (mcrypt_module_self_test( names[j], ALGORITHMS_DIR)==0) {
			printf( "ok\n");
		} else {
			x=1;
			printf( "\n");
		}
		printf( "Modes:\n");
			for (i=0;i<imax;i++) {
				td = mcrypt_module_open(names[j], ALGORITHMS_DIR, modes[i], MODES_DIR);
				td2 = mcrypt_module_open(names[j], ALGORITHMS_DIR, modes[i], MODES_DIR);
				if (td != MCRYPT_FAILED && td2 != MCRYPT_FAILED) {
					keysize = mcrypt_enc_get_key_size(td);
					key = calloc(1, keysize);
					if (key==NULL) exit(1);
					
					for (t=0;t<keysize;t++)
						key[t] = (t % 255) + 13;
					
					ivsize = mcrypt_enc_get_iv_size(td);
					if (ivsize>0) {
						IV = calloc( 1, ivsize);
						if (IV==NULL) exit(1);
						for (t=0;t<ivsize;t++)
							IV[t] = (t*2 % 255) + 15;
					}
					if (mcrypt_generic_init( td, key, keysize, IV) < 0) {
						fprintf(stderr, "Failed to Initialize algorithm!\n");
						return -1;
					}

					if (mcrypt_enc_is_block_mode(td)!=0)
						siz = (strlen(TEXT) / mcrypt_enc_get_block_size(td))*mcrypt_enc_get_block_size(td);
					else siz = strlen(TEXT);

					text = calloc( 1, siz);
					if (text==NULL) exit(1);
					
					memmove( text, TEXT, siz);

					mcrypt_generic( td, text, siz);

					if (mcrypt_generic_init( td2, key, keysize, IV) < 0) {
						fprintf(stderr, "Failed to Initialize algorithm!\n");
						return -1;
					}

					mdecrypt_generic( td2, text, siz);
					if ( memcmp( text, TEXT, siz) == 0) {
						printf( "   %s: ok\n", modes[i]);
					} else {
						printf( "   %s: failed\n", modes[i]);
						x=1;
					}
					mcrypt_generic_deinit(td);
					mcrypt_generic_deinit(td2);
					mcrypt_module_close(td);
					mcrypt_module_close(td2);					free(text);
					free(key);
					if (ivsize>0) free(IV);
				}
			}
		printf("\n");
		
	}	
	mcrypt_free_p(names, jmax);
	mcrypt_free_p(modes, imax);
	

	if (x>0) fprintf(stderr, "\nProbably some of the algorithms listed above failed. "
				"Try not to use these algorithms, and file a bug report to [email protected]\n\n");
	return x;
}
コード例 #16
0
int main(int argc, char **argv)
{
	int dev,cnt,sock;
	unsigned char buf_frame[1536+sizeof(struct ether_header)];
    unsigned char *buf = buf_frame+sizeof(struct ether_header);
    struct ether_header *header = (struct ether_header*) buf_frame;
#ifndef __NetBSD__
	struct ifreq ifr;
#endif

    MCRYPT td;
    char *key; 
    int blocksize=0;
    int keysize = 32; /* 256 bits == 32 bytes */
    char enc_state[1024];
    int enc_state_size;
    char* tun_device = "/dev/net/tun";
    char* dev_name="tun%d";

    if(getenv("TUN_DEVICE")) { tun_device = getenv("TUN_DEVICE"); }
    if(getenv("DEV_NAME")) { dev_name = getenv("DEV_NAME"); }

    if(getenv("MCRYPT_KEYFILE")) {
        if (getenv("MCRYPT_KEYSIZE")) { keysize=atoi(getenv("MCRYPT_KEYSIZE"))/8; }
        key = calloc(1, keysize);
        FILE* keyf = fopen(getenv("MCRYPT_KEYFILE"), "r");
        if (!keyf) { perror("fopen keyfile"); return 10; }
        memset(key, 0, keysize);
        fread(key, 1, keysize, keyf);
        fclose(keyf);

        char* algo="twofish";
        char* mode="cbc";

        if (getenv("MCRYPT_ALGO")) { algo = getenv("MCRYPT_ALGO"); }
        if (getenv("MCRYPT_MODE")) { mode = getenv("MCRYPT_MODE"); }


        td = mcrypt_module_open(algo, NULL, mode, NULL);
        if (td==MCRYPT_FAILED) {
            fprintf(stderr, "mcrypt_module_open failed algo=%s mode=%s keysize=%d\n", algo, mode, keysize);
            return 11;
        }
        blocksize = mcrypt_enc_get_block_size(td);
        //block_buffer = malloc(blocksize);

        mcrypt_generic_init( td, key, keysize, NULL);

        enc_state_size = sizeof enc_state;
        mcrypt_enc_get_state(td, enc_state, &enc_state_size);
    }

	if(argc<=2) {
		fprintf(stderr,
                "Usage: tap_mcrypt plaintext_interface destination_mac_address\n"
                "Example: tap_mcrypt wlan0 ff:ff:ff:ff:ff:ff\n"
                "                (note that ff:ff:ff:ff:ff:ff may work bad in Wi-Fi)\n"
                "    Environment variables:\n"
                "    TUN_DEVICE  /dev/net/tun\n"
                "    DEV_NAME    name of the device, default tun%%d\n"
                "    SOURCE_MAC_ADDRESS -- by default use interface's one\n"
                "    \n"
                "    MCRYPT_KEYFILE  -- turn on encryption, read key from this file\n"
                "    MCRYPT_KEYSIZE  -- key size in bits, default 256\n"
                "    MCRYPT_ALGO     -- algorithm, default is twofish. aes256 is called rijndael-256\n"
                "    MCRYPT_MODE     -- mode, default is CBC\n"
                );
		exit(1);
	}

    char* interface = argv[1];
    char* dest_mac = argv[2];

	if((dev = open(tun_device, O_RDWR)) < 0) {
		fprintf(stderr,"open(%s) failed: %s\n", tun_device, strerror(errno));
		exit(2);
	}

    
#ifndef __NetBSD__
	memset(&ifr, 0, sizeof(ifr));
	ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
	strncpy(ifr.ifr_name, dev_name, IFNAMSIZ);
	if(ioctl(dev, TUNSETIFF, (void*) &ifr) < 0) {
		perror("ioctl(TUNSETIFF) failed");
		exit(3);
	}

    {
	    struct ifreq ifr_tun;
	    strncpy(ifr_tun.ifr_name, ifr.ifr_name, IFNAMSIZ);
        if((sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)))==-1) {
            perror("socket() failed");
            exit(4);
        }
        
        if (ioctl(sock, SIOCGIFFLAGS, &ifr_tun) < 0) { perror("ioctl SIOCGIFFLAGS"); }
        ifr_tun.ifr_mtu=1408;
        if(ioctl(sock, SIOCSIFMTU, (void*) &ifr_tun) < 0) {
            perror("ioctl(SIOCSIFMTU) failed");
        }
        
        close(sock);
    } 
#endif
	

    if((sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)))==-1) {
		perror("socket() failed");
		exit(4);
	}

    char source_mac[6];
    int card_index;
    struct sockaddr_ll device;

    memset(&device, 0, sizeof(device));
    init_MAC_addr(sock, interface, source_mac, &card_index);
    device.sll_ifindex=card_index;
    
    
    device.sll_family = AF_PACKET;
    memcpy(device.sll_addr, source_mac, 6);
    device.sll_halen = htons(6);
    
    parseMac(dest_mac, header->ether_dhost);
    memcpy(header->ether_shost, source_mac, 6);
    header->ether_type = htons(0x08F4);  
		

	if(fork())
		while(1) {
			cnt=read(dev,(void*)buf,1518);
            //printpacket("sent", buf, cnt);
            if (blocksize) {
                cnt = ((cnt-1)/blocksize+1)*blocksize; // pad to block size
                mcrypt_generic (td, buf, cnt);
                mcrypt_enc_set_state (td, enc_state, enc_state_size);
            }
            //printpacket("encr", buf, cnt);
			sendto(sock, buf_frame, cnt+sizeof(struct ether_header),0,(struct sockaddr *)&device, sizeof device);
		}
	else
		while(1) {
            size_t size = sizeof device;
			cnt=recvfrom(sock,buf_frame,1536,0,(struct sockaddr *)&device,&size);
            if(device.sll_ifindex != card_index) {
                continue; /* Not our interface */
            }
            if(header->ether_type != htons(0x08F4)) {
                continue; /* Not our protocol type */
            }
            cnt-=sizeof(struct ether_header);
            //printpacket("recv", buf, cnt);
            if (blocksize) {
                cnt = ((cnt-1)/blocksize+1)*blocksize; // pad to block size
                mdecrypt_generic (td, buf, cnt);
                mcrypt_enc_set_state (td, enc_state, enc_state_size);
            }
            //printpacket("decr", buf, cnt);
            write(dev,(void*)buf,cnt);
		}

    if (blocksize) {
        mcrypt_generic_deinit (td);
        mcrypt_module_close(td);
    }
}
コード例 #17
0
static int check_auth_cookie(request_rec *r)
{

	const char *cookies = NULL, *auth_line = NULL;
	char *cookie = NULL;

    /* Debug. */
	/*ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
	    "check_auth_cookie called");*/

	/* Get config for this directory. */
    cookie_auth_config_rec *conf = ap_get_module_config(r->per_dir_config,
		&auth_cookie_module);

    /* Check we have been configured. */
    if (!conf->cookie_auth_cookie) {
        return DECLINED;
    }

	/* Do not override real auth header, unless config instructs us to. */
	if (!conf->cookie_auth_override &&
		apr_table_get(r->headers_in, "Authorization")) {
		if (conf->cookie_auth_env) {
			unsetenv(conf->cookie_auth_env);
		}
		return DECLINED;
	}

	/* todo: protect against xxxCookieNamexxx, regex? */
	/* todo: make case insensitive? */
	/* Get the cookie (code from mod_log_config). */
	if ((cookies = apr_table_get(r->headers_in, "Cookie"))) {
		char *start_cookie, *end_cookie;
		if ((start_cookie = ap_strstr_c(cookies, conf->cookie_auth_cookie))) {
		    start_cookie += strlen(conf->cookie_auth_cookie) + 1;
		    cookie = apr_pstrdup(r->pool, start_cookie);
			/* kill everything in cookie after ';' */
			end_cookie = strchr(cookie, ';');
			if (end_cookie) {
				*end_cookie = '\0';
      }
      ap_unescape_url(cookie);
		}
	}

	/* No cookie? Nothing for us to do. */
	if (!cookie) {
                if (conf->cookie_auth_unauth_redirect) {
        	        const char* redirect = conf->cookie_auth_unauth_redirect;
        		compose_and_set_redirect(r, redirect);
                        return HTTP_MOVED_TEMPORARILY;
                }
                else {
			return DECLINED;
                }
	}

	/* Debug. */
	/*ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
	    "%s=%s", conf->cookie_auth_cookie, cookie);*/

	char* aux_auth_info = "";

	/* Construct the fake auth_line. */
	if (conf->cookie_auth_base64) {
		char* decoded_cookie = apr_palloc(r->pool, apr_base64_decode_len(cookie));
    int decoded_cookie_length = apr_base64_decode(decoded_cookie, cookie);

		int valid = 1;

		/* if the cookie is encrypted, decrypt it in place */
		if (conf->cookie_auth_encrypt) {
      MCRYPT td = mcrypt_module_open("rijndael-128", NULL, "cbc", NULL);
      int keysize = strlen(conf->cookie_auth_encrypt);
      int blocksize = mcrypt_enc_get_block_size(td);

			// We will copy the iv from the beginning of the cookie.
			// The iv does not need to be null-terminated, but we will
			// null-terminate it for convenience.
			int iv_length = mcrypt_enc_get_iv_size(td);
			char* iv = (char*) apr_palloc(r->pool, iv_length + 1);
			memcpy(iv, decoded_cookie, iv_length);
			iv[iv_length] = '\0';

			// Take the iv off the beginning of the cookie
			decoded_cookie += iv_length;
      decoded_cookie_length -= iv_length;

      mcrypt_generic_init( td, conf->cookie_auth_encrypt, keysize, iv);
      // Encryption in CBC is performed in blocks, so our
      // decryption string will always be an integral number
      // of full blocks.
      char* decrypt_ptr = decoded_cookie;
      while (decoded_cookie_length >= blocksize) {
        mdecrypt_generic(td, decrypt_ptr, blocksize);
        decrypt_ptr += blocksize;
        decoded_cookie_length -= blocksize;
      }
      if (decoded_cookie_length != 0) {
        valid = 0;
      }
      mcrypt_generic_deinit (td);
      mcrypt_module_close(td);
      /*ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
        "mdecrypt(%s)=%s", conf->cookie_auth_cookie, decoded_cookie);*/
		}

		/* if the cookie did not decrypt, then do nothing */
		if (valid) {
			char* end_auth_info = strchr(decoded_cookie, '\t');

			if (end_auth_info) {
				aux_auth_info = decoded_cookie;
				char* unencoded_cookie = end_auth_info + 1;
				*end_auth_info = 0;

				auth_line = apr_pstrcat(r->pool, "Basic ", ap_pbase64encode(r->pool, unencoded_cookie), NULL);
			}
			else {
				auth_line = apr_pstrcat(r->pool, "Basic ", ap_pbase64encode(r->pool, decoded_cookie), NULL);
			}
		}
	} else {
		// Aux auth info and cookie encrypt features only available in base64 mode
		ap_unescape_url(cookie);
		auth_line = apr_pstrcat(r->pool, "Basic ",
			ap_pbase64encode(r->pool, cookie), NULL);
	}

	/* If there is aux auth info, then set the env variable */
	if (conf->cookie_auth_env) {
	  apr_table_set(r->subprocess_env, conf->cookie_auth_env, aux_auth_info);
	}

	/* Debug. */
	/*ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
		"Authorization: %s", auth_line);*/

	/* If there is no aux auth info, then force a redirect if our conf directives say that we should */
        if (conf->cookie_auth_env_redirect && !strlen(aux_auth_info)) {
        	const char* redirect = conf->cookie_auth_env_redirect;
        	compose_and_set_redirect(r, redirect);
                return HTTP_MOVED_TEMPORARILY;
        }
        else {
	        /* Set fake auth_line. */
		if (auth_line) {
                	apr_table_set(r->headers_in, "Authorization", auth_line);
                }
	}

	/* Always return DECLINED because we don't authorize, */
	/* we just set things up for the next auth module to. */
    return DECLINED;
}
コード例 #18
0
ファイル: mcrypt_filter.c プロジェクト: PHPFORMEEGO/PHPCore
static php_stream_filter_status_t php_mcrypt_filter(
	php_stream *stream,
	php_stream_filter *thisfilter,
	php_stream_bucket_brigade *buckets_in,
	php_stream_bucket_brigade *buckets_out,
	size_t *bytes_consumed,
	int flags TSRMLS_DC)
{
	php_mcrypt_filter_data *data;
	php_stream_bucket *bucket;
	size_t consumed = 0;
	php_stream_filter_status_t exit_status = PSFS_FEED_ME;

	if (!thisfilter || !thisfilter->abstract) {
		/* Should never happen */
		return PSFS_ERR_FATAL;
	}

	data = (php_mcrypt_filter_data *)(thisfilter->abstract);
	while(buckets_in->head) {
		bucket = buckets_in->head;

		consumed += bucket->buflen;

		if (data->blocksize) {
			/* Blockmode cipher */
			char *outchunk;
			int chunklen = bucket->buflen + data->block_used, n;
			php_stream_bucket *newbucket;

			outchunk = pemalloc(chunklen, data->persistent);
			if (data->block_used) {
				memcpy(outchunk, data->block_buffer, data->block_used);
			}
			memcpy(outchunk + data->block_used, bucket->buf, bucket->buflen);

			for(n=0; (n + data->blocksize) <= chunklen; n += data->blocksize) {

				if (data->encrypt) {
					mcrypt_generic(data->module, outchunk + n, data->blocksize);
				} else {
					mdecrypt_generic(data->module, outchunk + n, data->blocksize);
				}
			}
			data->block_used = chunklen - n;
			memcpy(data->block_buffer, outchunk + n, data->block_used);

			newbucket = php_stream_bucket_new(stream, outchunk, n, 1, data->persistent TSRMLS_CC);
			php_stream_bucket_append(buckets_out, newbucket TSRMLS_CC);

			exit_status = PSFS_PASS_ON;

			php_stream_bucket_unlink(bucket TSRMLS_CC);
			php_stream_bucket_delref(bucket TSRMLS_CC);
		} else {
			/* Stream cipher */
			php_stream_bucket_make_writeable(bucket TSRMLS_CC);
			if (data->encrypt) {
				mcrypt_generic(data->module, bucket->buf, bucket->buflen);
			} else {
				mdecrypt_generic(data->module, bucket->buf, bucket->buflen);
			}
			php_stream_bucket_append(buckets_out, bucket TSRMLS_CC);

			exit_status = PSFS_PASS_ON;
		}
	}

	if ((flags & PSFS_FLAG_FLUSH_CLOSE) && data->blocksize && data->block_used) {
		php_stream_bucket *newbucket;

		memset(data->block_buffer + data->block_used, 0, data->blocksize - data->block_used);
		if (data->encrypt) {
			mcrypt_generic(data->module, data->block_buffer, data->blocksize);
		} else {
			mdecrypt_generic(data->module, data->block_buffer, data->blocksize);
		}

		newbucket = php_stream_bucket_new(stream, data->block_buffer, data->blocksize, 0, data->persistent TSRMLS_CC);
		php_stream_bucket_append(buckets_out, newbucket TSRMLS_CC);

		exit_status = PSFS_PASS_ON;
	}

	if (bytes_consumed) {
		*bytes_consumed = consumed;
	}

	return exit_status;
}
コード例 #19
0
ファイル: lab1b-client.c プロジェクト: NaimAyat/UCLA_CS111
int main(int argc, char **argv) {
	int opt, pnum;
	char *lfile;
	int lflag = 0, pflag = 0;
	static struct option long_options[] = {
		{ "port", required_argument, 0, 'p' },
		{ "log", optional_argument, 0, 'l' },
		{ "encrypt", required_argument, 0, 'e' },
		{ "debug", no_argument, 0, 'd' },
		{ 0, 0, 0, 0 }
	};
	while ((opt = getopt_long(argc, argv, "p:l:e:d", long_options, NULL)) != -1) {
		if (opt == 'p') {
			pnum = atoi(optarg);
			pflag = 1;
		}
		else if (opt == 'l') {
			lfile = optarg;
			lflag = 1;
		}
		else if (opt == 'e') {
			enckeyf = optarg;
			eflag = 1;
		}
		else if (opt == 'd') {
			dflag = 1;
		}
		else pexit();
	}

	if (!pflag) pexit();

	if (lflag) {
		logffd = creat(lfile, S_IRWXU);
		if (logffd <= -1) error_exit("failed creat()", errno);
	}

	if (eflag) setup_encryption();

	save_term();
	atexit(restore_term);

	struct termios non_canonical_input_mode;
	tcgetattr(STDIN_FILENO, &non_canonical_input_mode);

	non_canonical_input_mode.c_iflag = ISTRIP; //only lower 7 bits
	non_canonical_input_mode.c_oflag = 0; // no processing
	non_canonical_input_mode.c_lflag = 0; // no processing

	if (tcsetattr(STDIN_FILENO, TCSANOW, &non_canonical_input_mode) <= -1) error_exit("failed to establish terminal ", errno);

	struct sockaddr_in addy;
	struct hostent *server = gethostbyname("localhost");
	int socket_id = socket(AF_INET, SOCK_STREAM, 0);
	if (socket_id <= -1) error_exit("failed to open socket", errno);
	memset((char *)&addy, 0, sizeof(addy));
	addy.sin_family = AF_INET;
	addy.sin_port = htons(pnum);
	memcpy((char *)&addy.sin_addr.s_addr, (char *)server->h_addr, server->h_length);

	if (connect(socket_id, (struct sockaddr*)&addy, sizeof(addy)) <= -1) error_exit("error connecting \n", errno);

	struct pollfd poll_s[2];
	poll_s[0].fd = STDIN_FILENO;
	poll_s[1].fd = socket_id;

	poll_s[0].events = POLLIN | POLLHUP | POLLERR;
	poll_s[1].events = POLLIN | POLLHUP | POLLERR;

	for (;;) {

		if (poll(poll_s, 2, 0) <= -1) {
			fprintf(stderr, "poll failed");
			exit(1);
		}

		if (poll(poll_s, 2, 0) == 0) continue;

		if (poll_s[0].revents & POLLIN) {
			char frmstdin[256];
			int numread = sread(STDIN_FILENO, frmstdin, 256);
			do_write(frmstdin, STDOUT_FILENO, numread);
			if (eflag) {
				int n=0;
				while (n < numread) {
					if (frmstdin[n] != '\r' && frmstdin[n] != '\n' && (mcrypt_generic(td, &frmstdin[n], 1) != 0)) {
						error_exit("failed to encrypt", errno);
					}
					n++;
				}
			}
			if (lflag) do_write_log(frmstdin, numread, tserver);
			do_write(frmstdin, poll_s[1].fd, numread);
		}
		if (poll_s[1].revents & POLLIN) {
			char frmsrv[256];
			int numread = sread(poll_s[1].fd, frmsrv, 256);
			if (numread == 0) {
				if (close(socket_id) <= -1) error_exit("failed to close", errno);
				exit(0);
			}
			if (lflag) do_write_log(frmsrv, numread, fserver);
			if (eflag && (mdecrypt_generic(td, &frmsrv, numread) != 0))
				error_exit("failed to encrypt", errno);
			do_write(frmsrv, STDOUT_FILENO, numread);
		}
		if (poll_s[1].revents & (POLLHUP | POLLERR)) {
			if (close(socket_id) <= -1) error_exit("failed to close", errno);
			exit(0);
		}
	}
	exit(0);
}
コード例 #20
0
int main()
{
	MCRYPT td, td2;
	int i, t, imax;
	int j, jmax, ivsize;
	int x = 0, siz;
	char *text;
	unsigned char *IV;
	unsigned char *key;
	int keysize;
	
    td = mcrypt_module_open("idea", ALGORITHMS_DIR, "cbc", MODES_DIR);
    td2 = mcrypt_module_open("idea", ALGORITHMS_DIR, "cbc", MODES_DIR);

    if (td != MCRYPT_FAILED && td2 != MCRYPT_FAILED) {
        fprintf(stderr, "Created IDEA cipher.\n");

        keysize = mcrypt_enc_get_key_size(td);
        fprintf(stderr, "Cipher key size %d.\n", keysize);

        key = calloc(1, keysize);
        if (key==NULL) exit(1);
					
        for (t=0;t<keysize;t++)
            key[t] = (t % 255) + 13;
					
        ivsize = mcrypt_enc_get_iv_size(td);
        fprintf(stderr, "IV size %d.\n", ivsize);
        if (ivsize>0) {
            IV = calloc( 1, ivsize);
            if (IV==NULL) exit(1);
            for (t=0;t<ivsize;t++)
                IV[t] = (t*2 % 255) + 15;
        }

        if (mcrypt_generic_init( td, key, keysize, IV) < 0) {
            fprintf(stderr, "Failed to Initialize algorithm!\n");
            return -1;
        }

        if (mcrypt_enc_is_block_mode(td)!=0)
            siz = (strlen(TEXT) / mcrypt_enc_get_block_size(td))*mcrypt_enc_get_block_size(td);
        else siz = strlen(TEXT);

        text = calloc( 1, siz);
        if (text==NULL) exit(1);
					
        memmove( text, TEXT, siz);

        mcrypt_generic( td, text, siz);

        if (mcrypt_generic_init( td2, key, keysize, IV) < 0) {
            fprintf(stderr, "Failed to Initialize algorithm!\n");
            return -1;
        }

        mdecrypt_generic( td2, text, siz);
        if ( memcmp( text, TEXT, siz) == 0) {
            printf( "   %s: ok\n", "cbc");
        } else {
            printf( "   %s: failed\n", "cbc");
            x=1;
        }

        mcrypt_generic_deinit(td);
        mcrypt_generic_deinit(td2);
        mcrypt_module_close(td);
        mcrypt_module_close(td2);
        free(text);
        free(key);
        if (ivsize>0) free(IV);
    }

    return 0;
}
コード例 #21
0
ファイル: server.c プロジェクト: jcherianucla/UCLA-CS-111
//Runs the corresponding decryption algorithm on the specified buffer for the size
void decrypt(char * buff, int decrypt_len)
{
	if(mdecrypt_generic(decrypt_fd, buff, decrypt_len) != 0) { perror("Error in decryption"); exit(EXIT_FAILURE); }
}
コード例 #22
0
ファイル: ext_mcrypt.cpp プロジェクト: 7755373049/hiphop-php
static Variant php_mcrypt_do_crypt(CStrRef cipher, CStrRef key, CStrRef data,
                                   CStrRef mode, CStrRef iv, bool dencrypt) {
  MCRYPT td = mcrypt_module_open((char*)cipher.data(),
                                 (char*)MCG(algorithms_dir).data(),
                                 (char*)mode.data(),
                                 (char*)MCG(modes_dir).data());
  if (td == MCRYPT_FAILED) {
    raise_warning(MCRYPT_OPEN_MODULE_FAILED);
    return false;
  }

  /* Checking for key-length */
  int max_key_length = mcrypt_enc_get_key_size(td);
  if (key.size() > max_key_length) {
    raise_warning("Size of key is too large for this algorithm");
  }
  int count;
  int *key_length_sizes = mcrypt_enc_get_supported_key_sizes(td, &count);
  int use_key_length;
  char *key_s = NULL;
  if (count == 0 && key_length_sizes == NULL) { // all lengths 1 - k_l_s = OK
    use_key_length = key.size();
    key_s = (char*)malloc(use_key_length);
    memcpy(key_s, key.data(), use_key_length);
  } else if (count == 1) {  /* only m_k_l = OK */
    key_s = (char*)malloc(key_length_sizes[0]);
    memset(key_s, 0, key_length_sizes[0]);
    memcpy(key_s, key.data(), MIN(key.size(), key_length_sizes[0]));
    use_key_length = key_length_sizes[0];
  } else { /* dertermine smallest supported key > length of requested key */
    use_key_length = max_key_length; /* start with max key length */
    for (int i = 0; i < count; i++) {
      if (key_length_sizes[i] >= key.size() &&
          key_length_sizes[i] < use_key_length) {
        use_key_length = key_length_sizes[i];
      }
    }
    key_s = (char*)malloc(use_key_length);
    memset(key_s, 0, use_key_length);
    memcpy(key_s, key.data(), MIN(key.size(), use_key_length));
  }
  mcrypt_free(key_length_sizes);

  /* Check IV */
  char *iv_s = NULL;
  int iv_size = mcrypt_enc_get_iv_size(td);

  /* IV is required */
  if (mcrypt_enc_mode_has_iv(td) == 1) {
    if (!iv.empty()) {
      if (iv_size != iv.size()) {
        raise_warning("The IV parameter must be as long as the blocksize");
      } else {
        iv_s = (char*)malloc(iv_size + 1);
        memcpy(iv_s, iv.data(), iv_size);
      }
    } else {
      raise_warning("Attempt to use an empty IV, which is NOT recommended");
      iv_s = (char*)malloc(iv_size + 1);
      memset(iv_s, 0, iv_size + 1);
    }
  }

  int block_size;
  unsigned long int data_size;
  String s;
  char *data_s;
  /* Check blocksize */
  if (mcrypt_enc_is_block_mode(td) == 1) { /* It's a block algorithm */
    block_size = mcrypt_enc_get_block_size(td);
    data_size = (((data.size() - 1) / block_size) + 1) * block_size;
    s = String(data_size, ReserveString);
    data_s = (char*)s.mutableSlice().ptr;
    memset(data_s, 0, data_size);
    memcpy(data_s, data.data(), data.size());
  } else { /* It's not a block algorithm */
    data_size = data.size();
    s = String(data_size, ReserveString);
    data_s = (char*)s.mutableSlice().ptr;
    memcpy(data_s, data.data(), data.size());
  }

  if (mcrypt_generic_init(td, key_s, use_key_length, iv_s) < 0) {
    raise_warning("Mcrypt initialisation failed");
    return false;
  }
  if (dencrypt) {
    mdecrypt_generic(td, data_s, data_size);
  } else {
    mcrypt_generic(td, data_s, data_size);
  }

  /* freeing vars */
  mcrypt_generic_end(td);
  if (key_s != NULL) {
    free(key_s);
  }
  if (iv_s != NULL) {
    free(iv_s);
  }
  return s.setSize(data_size);
}
コード例 #23
0
ファイル: Aes256.cpp プロジェクト: el-bart/WiFiChopper
void Aes256::decryptImpl(uint8_t* data, size_t size)
{
  int ret;
  if( (ret = mdecrypt_generic( td_.get(), data, size )) < 0 )
    throw std::runtime_error( (Util::ErrStrm{}<<"mdecrypt_generic(): "<<mcrypt_strerror(ret)).str().c_str() );
}