void PanelView::UniversalDelete(const char *filename)
////////////////////////////////////////////////////////////////////////
{
	BEntry entry(filename);

	key_info keyinfo;
	get_key_info(&keyinfo);
	if (keyinfo.key_states[0] & 0x40)
	{
		beep();
		return;	// ESC
	}

	// Don't delete the parent directory!!!!!!
	if (strlen(filename)>=3)
	{
		int len = strlen(filename);
		if (filename[len-1]=='.' && filename[len-2]=='.' && filename[len-3]=='/') return;
	}

	if (entry.InitCheck()==B_OK)
	{
		if (entry.Exists())
		{
			if (entry.IsDirectory())
				DeleteDirectory(filename);
		
			entry.Remove();
		}
	}
}
Example #2
0
static void read_kb (void)
{
    int keycode;
    int keyinfo_byte;
    int keyinfo_bit;

    key_info keyInfo;

    get_key_info (&keyInfo);

    if (memcmp (keyInfo.key_states, lastKeyInfo.key_states, sizeof (keyInfo.key_states))) {
	for (keycode = 0; keycode < 0x80; keycode++) {
	    keyinfo_byte = keycode >> 3;
	    keyinfo_bit = 1 << (~keycode & 7);

	    // Key state changed?
	    if ((keyInfo.key_states[keyinfo_byte] & keyinfo_bit) != (lastKeyInfo.key_states[keyinfo_byte] & keyinfo_bit)) {
		int new_state = (keyInfo.key_states[keyinfo_byte] & keyinfo_bit) != 0;
		int ievent;

		if ((ievent = match_hotkey_sequence (keycode, new_state)))
		    handle_hotkey_event (ievent, new_state);
		else
		    inputdevice_translatekeycode (0, keycode, new_state);
	    }
	}
	lastKeyInfo = keyInfo;
    }
}
Example #3
0
/**
 * Initialize crypto library, generate keys
 */
void key_init()
{
    unsigned char *prf_buf;
    time_t t;
    uint32_t t2;
    int explen, len;

    if (keytype == KEY_NONE) {
        return;
    }

    set_sys_keys(sys_keys);
    get_key_info(keytype, &keylen, &ivlen);
    hmaclen = get_hash_len(hashtype);

    memset(groupkey, 0, sizeof(groupkey));
    memset(groupsalt, 0, sizeof(groupsalt));
    memset(grouphmackey, 0, sizeof(grouphmackey));

    if (!get_random_bytes(groupmaster, sizeof(groupmaster))) {
        log(0, 0, "Failed to generate group master");
        exit(1);
    }
    groupmaster[0] = UFTP_VER_NUM;
    if (!get_random_bytes(rand1, sizeof(rand1))) {
        log(0, 0, "Failed to generate rand1");
        exit(1);
    }
    // Sets the first 4 bytes of rand1 to the current time
    t = time(NULL);
    t2 = (uint32_t)(t & 0xFFFFFFFF);
    *(uint32_t *)rand1 = t2;

    explen = hmaclen + keylen + ivlen;
    prf_buf = calloc(explen + hmaclen, 1);
    if (prf_buf == NULL) {
        syserror(0, 0, "calloc failed!");
        exit(1);
    }
    PRF(hashtype, explen, groupmaster, sizeof(groupmaster), "key expansion",
            rand1, sizeof(rand1), prf_buf, &len);
    memcpy(grouphmackey, prf_buf, hmaclen);
    memcpy(groupkey, prf_buf + hmaclen, keylen);
    memcpy(groupsalt, prf_buf + hmaclen + keylen, ivlen);
    free(prf_buf);

    if ((!strcmp(keyfile, "")) || (newkeylen != 0)) {
        privkey = gen_RSA_key(newkeylen, RSA_EXP, keyfile);
    } else {
        privkey = read_RSA_key(keyfile);
    }
    if (!privkey) {
        log(0, 0, "Failed to read/generate private key");
        exit(1);
    }

    rsalen = RSA_keylen(privkey);
}
Example #4
0
static int init_kb (void)
{
    get_key_info (&lastKeyInfo);

    default_keyboard = uaekey_make_default_kbr (beos_keymap);
    inputdevice_setkeytranslation (default_keyboard, kbmaps);
    set_default_hotkeys (beos_hotkeys);

    return 1;
}
Example #5
0
//  Poll mouse and keyboard
void handle_events(void)
{
	int be_code,be_byte,be_bit,amiga_code;
	key_info keyInfo;

	if (!lastKeyInfoInitialized)
	{
		get_key_info(&lastKeyInfo);
		lastKeyInfoInitialized = true;
	}

	// Redraw drive LEDs
	/*for (int i=0; i<4; i++)
		DriveLED[i]->SetState(LEDs[i]);*/

	if (gEmulationWindow->UpdateMouseButtons())
	{
		get_key_info(&keyInfo);

		// Keyboard
		if (memcmp(keyInfo.key_states, lastKeyInfo.key_states, sizeof(keyInfo.key_states)))
		{
			for(be_code = 0;be_code < 0x80;be_code++)
			{
				be_byte = be_code >> 3;
				be_bit = 1 << (~be_code & 7);

				// Key state changed?
				if (	(keyInfo.key_states[be_byte] & be_bit)
					!= 	(lastKeyInfo.key_states[be_byte] & be_bit))
				{
					int state = (keyInfo.key_states[be_byte] & be_bit) !=0;
					int ievent;
					if ((ievent = match_hotkey_sequence (be_code, state)))
						handle_hotkey_event (ievent, state);
					else
						inputdevice_translatekeycode (0, be_code, state);
				}
			}
			lastKeyInfo = keyInfo;
		}
	}
Example #6
0
/////////////////////////////////////////////////////////////////////
// chkKey
// check key is pressed when app start
// Thanks to Kodama Takeshi.
/////////////////////////////////////////////////////////////////////
bool
kanBeApp::chkKey(void)
{
key_info	info;
bool		ret = false;
status_t	err = get_key_info(&info);

	if (!err && info.modifiers & B_CONTROL_KEY) {
		ret = true;
	}

	return ret;
}
Example #7
0
int32
S9xMainWindow::KeyThread(void *o)
{
	S9xMainWindow *d = (S9xMainWindow *)o;
	while(1) {
		key_info info;
		if(d->IsActive() && get_key_info(&info) == B_NO_ERROR) {
			for(int i = 0; i < 128; i++)
				d->key[i].pressed = info.key_states[i >> 3] & (1 << (7 - (i % 8)));
		}
		ClearKeys(d->key);
		snooze(100000 / 30);
	}
	return 0;
}
Example #8
0
static unsigned long Update(void *pdevice)
{
	key_info TheKey;
	if (get_key_info(&TheKey)==B_OK)
    {
		sysMemCpy(sKEY->steButtons, sKEY->rgbButtons, 16);
        sysMemCpy(sKEY->rgbButtons, TheKey.key_states, 16);
		int i;
		for (i=0;i<16*8;i++)
		{
			if (sKEY_IsHeld(i))
			{
				sKEY->scanCode = i;
			}
		}
    }
    return 1;
}
void PanelView::DeleteDirectory(const char *dirname)
////////////////////////////////////////////////////////////////////////
{
	BDirectory *dir;
	key_info keyinfo;
	
	// Don't delete the parent directory!!!!!!
	if (strlen(dirname)>=3)
	{
		int len = strlen(dirname);
		if (dirname[len-1]=='.' && dirname[len-2]=='.' && dirname[len-3]=='/') return;
	}
		
	dir = new BDirectory(dirname);
	if (dir)
	{
		BEntry entry;
		
		if (dir->GetEntry(&entry)==B_OK)
		{	
			while (dir->GetNextEntry(&entry)==B_OK)			
			{
				get_key_info(&keyinfo);
				if (keyinfo.key_states[0] & 0x40)	// ESC
				{
					beep();
					delete dir;
					return;
				}

				BPath path;
				entry.GetPath(&path);
				
				if (entry.IsDirectory())
					DeleteDirectory(path.Path());

				entry.Remove();
			}
		}
	
		delete dir;
	}
}
Example #10
0
/**
* BeOS entropy poll
*/
void BeOS_EntropySource::poll(Entropy_Accumulator& accum)
   {
   system_info info_sys;
   get_system_info(&info_sys);
   accum.add(info_sys, BOTAN_ENTROPY_ESTIMATE_SYSTEM_DATA);

   key_info info_key; // current state of the keyboard
   get_key_info(&info_key);
   accum.add(info_key, BOTAN_ENTROPY_ESTIMATE_SYSTEM_DATA);

   team_info info_team;
   int32 cookie_team = 0;

   while(get_next_team_info(&cookie_team, &info_team) == B_OK)
      {
      accum.add(info_team, BOTAN_ENTROPY_ESTIMATE_SYSTEM_DATA);

      team_id id = info_team.team;
      int32 cookie = 0;

      thread_info info_thr;
      while(get_next_thread_info(id, &cookie, &info_thr) == B_OK)
         accum.add(info_thr, BOTAN_ENTROPY_ESTIMATE_SYSTEM_DATA);

      cookie = 0;
      image_info info_img;
      while(get_next_image_info(id, &cookie, &info_img) == B_OK)
         accum.add(info_img, BOTAN_ENTROPY_ESTIMATE_SYSTEM_DATA);

      cookie = 0;
      sem_info info_sem;
      while(get_next_sem_info(id, &cookie, &info_sem) == B_OK)
         accum.add(info_sem, BOTAN_ENTROPY_ESTIMATE_SYSTEM_DATA);

      cookie = 0;
      area_info info_area;
      while(get_next_area_info(id, &cookie, &info_area) == B_OK)
         accum.add(info_area, BOTAN_ENTROPY_ESTIMATE_SYSTEM_DATA);

      if(accum.polling_finished())
         break;
      }
   }
Example #11
0
void slowPoll( void )
	{
	RANDOM_STATE randomState;
	BYTE buffer[ RANDOM_BUFSIZE + 8 ];
	key_info keyInfo;
	team_info teami;
	thread_info threadi;
	area_info areai;
	port_info porti;
	sem_info semi;
	image_info imagei;
	double temperature;
	int32 devID, cookie;
	int fd, value;

	if( ( fd = open( "/dev/urandom", O_RDONLY ) ) >= 0 )
		{
		MESSAGE_DATA msgData;
		BYTE buffer[ ( DEVRANDOM_BITS / 8 ) + 8 ];
		static const int quality = 100;

		/* Read data from /dev/urandom, which won't block (although the
		   quality of the noise is lesser). */
		read( fd, buffer, DEVRANDOM_BITS / 8 );
		setMessageData( &msgData, buffer, DEVRANDOM_BITS / 8 );
		krnlSendMessage( SYSTEM_OBJECT_HANDLE, IMESSAGE_SETATTRIBUTE_S,
						 &msgData, CRYPT_IATTRIBUTE_ENTROPY );
		zeroise( buffer, DEVRANDOM_BITS / 8 );
		close( fd );

		krnlSendMessage( SYSTEM_OBJECT_HANDLE, IMESSAGE_SETATTRIBUTE,
						 ( MESSAGE_CAST ) &quality,
						 CRYPT_IATTRIBUTE_ENTROPY_QUALITY );
		return;
		}

	initRandomData( randomState, buffer, RANDOM_BUFSIZE );

	/* Get the state of all keys on the keyboard and various other
	   system states */
#if 0	/* See comment at start */
	if( get_key_info( &keyInfo ) == B_NO_ERROR )
		addRandomData( randomState, &keyInfo, sizeof( key_info ) );
#endif /* 0 */
	value = is_computer_on();	/* Returns 1 if computer is on */
	addRandomValue( randomState, value );
	temperature = is_computer_on_fire();	/* MB temp.if on fire */
	addRandomData( randomState, &temperature, sizeof( double ) );

	/* Get information on all running teams (thread groups, ie applications).
	   This returns the team ID, number of threads, images, and areas,
	   debugger port and thread ID, program args, and uid and gid */
	cookie = 0;
	while( get_next_team_info( &cookie, &teami ) == B_NO_ERROR )
		addRandomData( randomState, &teami, sizeof( teami ) );

	/* Get information on all running threads.  This returns the thread ID,
	   team ID, thread name and state (eg running, suspended, asleep,
	   blocked), the thread priority, elapsed user and kernel time, and
	   thread stack information */
	cookie = 0;
	while( get_next_thread_info( 0, &cookie, &threadi ) == B_NO_ERROR )
		{
		addRandomValue( randomState, has_data( threadi.thread ) );
		addRandomData( randomState, &threadi, sizeof( threadi ) );
		}

	/* Get information on all memory areas (chunks of virtual memory).  This
	   returns the area ID, name, size, locking scheme and protection bits,
	   ID of the owning team, start address, number of resident bytes, copy-
	   on-write count, an number of pages swapped in and out */
	cookie = 0;
	while( get_next_area_info( 0, &cookie, &areai ) == B_NO_ERROR )
		addRandomData( randomState, &areai, sizeof( areai ) );

	/* Get information on all message ports.  This returns the port ID, ID of
	   the owning team, message queue length, number of messages in the
	   queue, and total number of messages processed */
	cookie = 0;
	while( get_next_port_info( 0, &cookie, &porti ) == B_NO_ERROR )
		addRandomData( randomState, &porti, sizeof( porti ) );

	/* Get information on all semaphores.  This returns the semaphore and
	   owning team ID, the name, thread count, and the ID of the last thread
	   which acquired the semaphore */
	cookie = 0;
	while( get_next_sem_info( 0, &cookie, &semi ) == B_NO_ERROR )
		addRandomData( randomState, &semi, sizeof( semi ) );

	/* Get information on all images (code blocks, eg applications, shared
	   libraries, and add-on images (DLL's on steroids).  This returns the
	   image ID and type (app, library, or add-on), the order in which the
	   image was loaded compared to other images, the address of the init
	   and shutdown routines, the device and node where the image lives,
	   and the image text and data sizes) */
	cookie = 0;
	while( get_next_image_info( 0, &cookie, &imagei ) == B_NO_ERROR )
		addRandomData( randomState, &imagei, sizeof( imagei ) );

	/* Get information on all storage devices.  This returns the device
	   number, root inode, various device parameters such as I/O block size,
	   and the number of free and used blocks and inodes */
	devID = 0;
	while( next_dev( &devID ) >= 0 )
		{
		fs_info fsInfo;

		if( fs_stat_dev( devID, &fsInfo ) == B_NO_ERROR )
			addRandomData( randomState, &fsInfo, sizeof( fs_info ) );
		}

	/* Flush any remaining data through */
	endRandomData( randomState, 100 );
	}
Example #12
0
static void
add_listener(ns_controls_t *cp, controllistener_t **listenerp,
	     const cfg_obj_t *control, const cfg_obj_t *config,
	     isc_sockaddr_t *addr, cfg_aclconfctx_t *aclconfctx,
	     const char *socktext, isc_sockettype_t type)
{
	isc_mem_t *mctx = cp->server->mctx;
	controllistener_t *listener;
	const cfg_obj_t *allow;
	const cfg_obj_t *global_keylist = NULL;
	const cfg_obj_t *control_keylist = NULL;
	dns_acl_t *new_acl = NULL;
	isc_result_t result = ISC_R_SUCCESS;

	listener = isc_mem_get(mctx, sizeof(*listener));
	if (listener == NULL)
		result = ISC_R_NOMEMORY;

	if (result == ISC_R_SUCCESS) {
		listener->mctx = NULL;
		isc_mem_attach(mctx, &listener->mctx);
		listener->controls = cp;
		listener->task = cp->server->task;
		listener->address = *addr;
		listener->sock = NULL;
		listener->listening = ISC_FALSE;
		listener->exiting = ISC_FALSE;
		listener->acl = NULL;
		listener->type = type;
		listener->perm = 0;
		listener->owner = 0;
		listener->group = 0;
		ISC_LINK_INIT(listener, link);
		ISC_LIST_INIT(listener->keys);
		ISC_LIST_INIT(listener->connections);

		/*
		 * Make the acl.
		 */
		if (control != NULL && type == isc_sockettype_tcp) {
			allow = cfg_tuple_get(control, "allow");
			result = cfg_acl_fromconfig(allow, config, ns_g_lctx,
						    aclconfctx, mctx, 0,
						    &new_acl);
		} else {
			result = dns_acl_any(mctx, &new_acl);
		}
	}

	if (result == ISC_R_SUCCESS) {
		dns_acl_attach(new_acl, &listener->acl);
		dns_acl_detach(&new_acl);

		if (config != NULL)
			get_key_info(config, control, &global_keylist,
				     &control_keylist);

		if (control_keylist != NULL) {
			result = controlkeylist_fromcfg(control_keylist,
							listener->mctx,
							&listener->keys);
			if (result == ISC_R_SUCCESS)
				register_keys(control, global_keylist,
					      &listener->keys,
					      listener->mctx, socktext);
		} else
			result = get_rndckey(mctx, &listener->keys);

		if (result != ISC_R_SUCCESS && control != NULL)
			cfg_obj_log(control, ns_g_lctx, ISC_LOG_WARNING,
				    "couldn't install keys for "
				    "command channel %s: %s",
				    socktext, isc_result_totext(result));
	}

	if (result == ISC_R_SUCCESS) {
		int pf = isc_sockaddr_pf(&listener->address);
		if ((pf == AF_INET && isc_net_probeipv4() != ISC_R_SUCCESS) ||
#ifdef ISC_PLATFORM_HAVESYSUNH
		    (pf == AF_UNIX && isc_net_probeunix() != ISC_R_SUCCESS) ||
#endif
		    (pf == AF_INET6 && isc_net_probeipv6() != ISC_R_SUCCESS))
			result = ISC_R_FAMILYNOSUPPORT;
	}

	if (result == ISC_R_SUCCESS && type == isc_sockettype_unix)
		isc_socket_cleanunix(&listener->address, ISC_FALSE);

	if (result == ISC_R_SUCCESS)
		result = isc_socket_create(ns_g_socketmgr,
					   isc_sockaddr_pf(&listener->address),
					   type, &listener->sock);
	if (result == ISC_R_SUCCESS)
		isc_socket_setname(listener->sock, "control", NULL);

#ifndef ISC_ALLOW_MAPPED
	if (result == ISC_R_SUCCESS)
		isc_socket_ipv6only(listener->sock, ISC_TRUE);
#endif

	if (result == ISC_R_SUCCESS)
		result = isc_socket_bind(listener->sock, &listener->address,
					 ISC_SOCKET_REUSEADDRESS);

	if (result == ISC_R_SUCCESS && type == isc_sockettype_unix) {
		listener->perm = cfg_obj_asuint32(cfg_tuple_get(control,
								"perm"));
		listener->owner = cfg_obj_asuint32(cfg_tuple_get(control,
								 "owner"));
		listener->group = cfg_obj_asuint32(cfg_tuple_get(control,
								 "group"));
		result = isc_socket_permunix(&listener->address, listener->perm,
					     listener->owner, listener->group);
	}
	if (result == ISC_R_SUCCESS)
		result = control_listen(listener);

	if (result == ISC_R_SUCCESS)
		result = control_accept(listener);

	if (result == ISC_R_SUCCESS) {
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_CONTROL, ISC_LOG_NOTICE,
			      "command channel listening on %s", socktext);
		*listenerp = listener;

	} else {
		if (listener != NULL) {
			listener->exiting = ISC_TRUE;
			free_listener(listener);
		}

		if (control != NULL)
			cfg_obj_log(control, ns_g_lctx, ISC_LOG_WARNING,
				    "couldn't add command channel %s: %s",
				    socktext, isc_result_totext(result));
		else
			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
				      NS_LOGMODULE_CONTROL, ISC_LOG_NOTICE,
				      "couldn't add command channel %s: %s",
				      socktext, isc_result_totext(result));

		*listenerp = NULL;
	}

	/* XXXDCL return error results? fail hard? */
}
Example #13
0
/**
 * Calculate the master key and do key expansion to determine the symmetric
 * cypher key and IV salt, and hash key for the server
 */
int calculate_server_keys(struct group_list_t *group,
                          const struct enc_info_he *encinfo)
{
    unsigned char *seed, *prf_buf;
    int explen, len, seedlen;
    time_t t;
    uint32_t t2;

    memcpy(group->rand1, encinfo->rand1, sizeof(encinfo->rand1));
    if (!get_random_bytes(group->rand2, sizeof(group->rand2))) {
        glog0(group, "Failed to get random bytes for rand2");
        send_abort(group, "Failed to get random bytes for rand2");
        return 0;
    }
    // Sets the first 4 bytes of rand2 to the current time
    t = time(NULL);
    t2 = (uint32_t)(t & 0xFFFFFFFF);
    *(uint32_t *)(group->rand2) = t2;
    if (group->keyextype == KEYEX_RSA) {
        if (!get_random_bytes(group->premaster, MASTER_LEN)) {
            glog0(group, "Failed to get random bytes for premaster");
            send_abort(group, "Failed to get random bytes for premaster");
            return 0;
        }
        group->premaster_len = MASTER_LEN;
    } else {
        EC_key_t pubecdh;

        if (has_proxy) {
            pubecdh = proxy_dhkey.ec;
        } else {
            pubecdh = group->server_dhkey.ec;
        }
        if (!get_ECDH_key(pubecdh, group->client_dhkey.ec,
                          group->premaster, &group->premaster_len)) {
            glog0(group, "Failed to calculate ECDH key");
            send_abort(group, "Failed to calculate ECDH key");
            return 0;
        }
    }

    get_key_info(group->keytype, &group->keylen, &group->ivlen);
    group->hmaclen = get_hash_len(group->hashtype);

    explen = group->keylen + SALT_LEN + group->hmaclen;
    seedlen = RAND_LEN * 2;
    seed = safe_calloc(seedlen, 1);
    prf_buf = safe_calloc(MASTER_LEN + explen + group->hmaclen, 1);

    memcpy(seed, group->rand1, sizeof(group->rand1));
    memcpy(seed + sizeof(group->rand1), group->rand2, sizeof(group->rand2));
    PRF(group->hashtype, MASTER_LEN, group->premaster, group->premaster_len,
            "master secret", seed, seedlen, prf_buf, &len);
    memcpy(group->master,prf_buf, sizeof(group->master));

    PRF(group->hashtype, explen, group->master, sizeof(group->master),
            "key expansion", seed, seedlen, prf_buf, &len);
    memcpy(group->hmackey, prf_buf, group->hmaclen);
    memcpy(group->key, prf_buf + group->hmaclen, group->keylen);
    memcpy(group->salt, prf_buf + group->hmaclen + group->keylen, SALT_LEN);

    free(seed);
    free(prf_buf);
    return 1;
}
Example #14
0
/**
 * Process an incoming KEYINFO message.
 * Expected in response to a REGISTER when encryption is enabled.
 */
void handle_keyinfo(struct group_list_t *group, unsigned char *message,
                    unsigned meslen, uint32_t src_id)
{
    struct keyinfo_h *keyinfo_hdr;
    struct destkey *keylist;
    int i, keyidx, len, destkeycnt, unauth_keytype, unauth_keylen, unauth_ivlen;
    unsigned explen, declen;
    uint8_t decgroupmaster[MASTER_LEN], *prf_buf, *iv;
    uint64_t ivctr;

    keyinfo_hdr = (struct keyinfo_h *)message;
    keylist = (struct destkey *)(message + (keyinfo_hdr->hlen * 4));

    if ((meslen < (keyinfo_hdr->hlen * 4U)) ||
            ((keyinfo_hdr->hlen * 4U) < sizeof(struct keyinfo_h))) {
        glog1(group, "Rejecting KEYINFO from server: invalid message size");
        return;
    }

    destkeycnt = (meslen - (keyinfo_hdr->hlen * 4)) / sizeof(struct destkey);
    // This duplicates uid_in_list, but here it's addressed in a struct array
    for (i = 0, keyidx = -1; (i < destkeycnt) && (keyidx == -1); i++) {
        if (uid == keylist[i].dest_id) {
            keyidx = i;
        }
    }

    // Don't use a cipher in an authentication mode to decrypt the group master
    unauth_keytype = unauth_key(group->keytype);
    get_key_info(unauth_keytype, &unauth_keylen, &unauth_ivlen);
    if (keyidx != -1) {
        glog2(group, "Received KEYINFO");
        if (group->phase == PHASE_MIDGROUP) {
            // We already got the KEYINFO, so no need to reprocess.
            // Just resend the KEYINFO_ACK and reset the timeout
            send_keyinfo_ack(group);
            set_timeout(group, 0);
            return;
        }

        iv = safe_calloc(unauth_ivlen, 1);
        ivctr = ntohl(keyinfo_hdr->iv_ctr_lo);
        ivctr |= (uint64_t)ntohl(keyinfo_hdr->iv_ctr_hi) << 32;
        build_iv(iv, group->salt, unauth_ivlen, uftp_htonll(ivctr), src_id);
        if (!decrypt_block(unauth_keytype, iv, group->key, NULL, 0,
                    keylist[keyidx].groupmaster, MASTER_LEN,
                    decgroupmaster, &declen) ||
                (declen != MASTER_LEN - 1)) {
            glog1(group, "Decrypt failed for group master");
            send_abort(group, "Decrypt failed for group master");
            free(iv);
            return;
        }
        free(iv);
        group->groupmaster[0] = group->version;
        memcpy(&group->groupmaster[1], decgroupmaster, declen);

        explen = group->keylen + SALT_LEN + group->hmaclen;
        prf_buf = safe_calloc(explen + group->hmaclen, 1);
        PRF(group->hashtype, explen, group->groupmaster,
                sizeof(group->groupmaster), "key expansion",
                group->rand1, sizeof(group->rand1), prf_buf, &len);
        memcpy(group->grouphmackey, prf_buf, group->hmaclen);
        memcpy(group->groupkey, prf_buf + group->hmaclen, group->keylen);
        memcpy(group->groupsalt, prf_buf + group->hmaclen + group->keylen,
                SALT_LEN);

        free(prf_buf);
        group->phase = PHASE_MIDGROUP;
        send_keyinfo_ack(group);
        set_timeout(group, 0);

        if (group->restart) {
            read_restart_file(group);
        }
    }
}
int
main(int argc, char *argv[])
{
	// 256 frames * 4 buffer parts * 2 channels * 2 bytes per sample
	// will give us internal buffer of 4096 bytes
	size_t framesPerBufferPart = 256;
	size_t bufferPartCount = 4;

	if (argc != 2 && argc != 4) {
		printf("Usage: %s <sound file name> [<frames per part> <parts>]\n",
			argv[0]);
		return 0;
	}

	if (argc == 4) {
		size_t size = strtoul(argv[2], NULL, 10);
		if (size > 0)
			framesPerBufferPart = size;

		size = strtoul(argv[3], NULL,  10);
		if (size == 1) {
			printf("at least 2 buffer parts are needed\n");
			return 1;
		}
		if (size > 0)
			bufferPartCount = size;
	}

	printf("frames per buffer part: %ld\n", framesPerBufferPart);
	printf("buffer part count: %ld\n", bufferPartCount);

	BEntry entry(argv[1]);
	if (entry.InitCheck() != B_OK || !entry.Exists()) {
		printf("cannot open input file\n");
		return 1;
	}

	entry_ref entryRef;
	entry.GetRef(&entryRef);

	BMediaFile mediaFile(&entryRef);
	if (mediaFile.InitCheck() != B_OK) {
		printf("file not supported\n");
		return 1;
	}

	if (mediaFile.CountTracks() == 0) {
		printf("no tracks found in file\n");
		return 1;
	}

	BMediaTrack *mediaTrack = mediaFile.TrackAt(0);
	if (mediaTrack == NULL) {
		printf("problem getting track from file\n");
		return 1;
	}

	// propose format, let it decide frame rate, channels number and buf size
	media_format format;
	memset(&format, 0, sizeof(format));
	format.type = B_MEDIA_RAW_AUDIO;
	format.u.raw_audio.format = media_raw_audio_format::B_AUDIO_SHORT;
	format.u.raw_audio.byte_order = B_MEDIA_LITTLE_ENDIAN;

	if (mediaTrack->DecodedFormat(&format) != B_OK) {
		printf("cannot set decoder output format\n");
		return 1;
	}

	printf("negotiated format:\n");
	printf("frame rate: %g Hz\n", format.u.raw_audio.frame_rate);
	printf("channel count: %ld\n", format.u.raw_audio.channel_count);
	printf("buffer size: %ld bytes\n", format.u.raw_audio.buffer_size);

	gs_audio_format gsFormat;
	memset(&gsFormat, 0, sizeof(gsFormat));
	gsFormat.frame_rate = format.u.raw_audio.frame_rate;
	gsFormat.channel_count = format.u.raw_audio.channel_count;
	gsFormat.format = format.u.raw_audio.format;
	gsFormat.byte_order = format.u.raw_audio.byte_order;

	BPushGameSound pushGameSound(framesPerBufferPart, &gsFormat,
		bufferPartCount);
	if (pushGameSound.InitCheck() != B_OK) {
		printf("trouble initializing push game sound: %s\n",
			strerror(pushGameSound.InitCheck()));
		return 1;
	}

	uint8 *buffer;
	size_t bufferSize;
	if (pushGameSound.LockForCyclic((void **)&buffer, &bufferSize)
			!= BPushGameSound::lock_ok) {
		printf("cannot lock buffer\n");
		return 1;
	}
	memset(buffer, 0, bufferSize);

	if (pushGameSound.StartPlaying() != B_OK) {
		printf("cannot start playback\n");
		return 1;
	}

	printf("playing, press [esc] to exit...\n");

	uint8 decoded[format.u.raw_audio.buffer_size * 2];
	size_t bufferPartSize = framesPerBufferPart
		* format.u.raw_audio.channel_count
		* (format.u.raw_audio.format
			& media_raw_audio_format::B_AUDIO_SIZE_MASK);
	size_t decodedSize = 0;
	size_t partPos = 0;
	size_t pos = 0; /*pushGameSound.CurrentPosition();*/
	key_info keyInfo;

	while (true) {
		// fill buffer part with data from decoded buffer
		while (partPos < bufferPartSize && decodedSize) {
			size_t size = min_c(bufferPartSize - partPos, decodedSize);

			memcpy(buffer + pos + partPos, decoded, size);
			partPos += size;

			decodedSize -= size;
			memmove(decoded, decoded + size, decodedSize);
		}

		// if there are too little data to fill next buffer part
		// read next decoded frames
		if (partPos < bufferPartSize) {
			int64 frameCount;
			if (mediaTrack->ReadFrames(decoded + decodedSize, &frameCount)
					!= B_OK)
				break;
			if (frameCount == 0)
				break;

			decodedSize += frameCount * format.u.raw_audio.channel_count
				* (format.u.raw_audio.format
					& media_raw_audio_format::B_AUDIO_SIZE_MASK);

			printf("\rtime: %.2f",
				(double)mediaTrack->CurrentTime() / 1000000LL);
			fflush(stdout);

			continue;
		}

		// this buffer part is done
		partPos = 0;
		pos += bufferPartSize;
		if (bufferSize <= pos)
			pos = 0;

		// playback sync - wait for the buffer part we're about to fill to be
		// played
		while (pushGameSound.CurrentPosition() >= pos + bufferPartSize
			|| pushGameSound.CurrentPosition() < pos)
			snooze(1000 * framesPerBufferPart / gsFormat.frame_rate);

		// check escape key state
		if (get_key_info(&keyInfo) != B_OK) {
			printf("\nkeyboard state read error\n");
			break;
		}
		if ((keyInfo.key_states[0] & 0x40) != 0)
			break;
	}

	pushGameSound.StopPlaying();

	mediaFile.ReleaseTrack(mediaTrack);
	mediaFile.CloseFile();

	printf("\nfinished.\n");

	return 0;
}
Example #16
0
/**
 * Initialize crypto library, generate keys
 */
void key_init(void)
{
    unsigned char *prf_buf;
    time_t t;
    uint32_t t2;
    int explen, len;

    if (keytype == KEY_NONE) {
        return;
    }

    set_sys_keys(sys_keys);
    get_key_info(keytype, &keylen, &ivlen);
    hmaclen = get_hash_len(hashtype);

    memset(groupkey, 0, sizeof(groupkey));
    memset(groupsalt, 0, sizeof(groupsalt));
    memset(grouphmackey, 0, sizeof(grouphmackey));

    if (!get_random_bytes(groupmaster, sizeof(groupmaster))) {
        log0(0, 0, 0, "Failed to generate group master");
        exit(ERR_CRYPTO);
    }
    groupmaster[0] = UFTP_VER_NUM;
    if (!get_random_bytes(rand1, sizeof(rand1))) {
        log0(0, 0, 0, "Failed to generate rand1");
        exit(ERR_CRYPTO);
    }
    // Sets the first 4 bytes of rand1 to the current time
    t = time(NULL);
    t2 = (uint32_t)(t & 0xFFFFFFFF);
    *(uint32_t *)rand1 = t2;

    explen = hmaclen + keylen + SALT_LEN;
    prf_buf = safe_calloc(explen + hmaclen, 1);
    PRF(hashtype, explen, groupmaster, sizeof(groupmaster), "key expansion",
            rand1, sizeof(rand1), prf_buf, &len);
    memcpy(grouphmackey, prf_buf, hmaclen);
    memcpy(groupkey, prf_buf + hmaclen, keylen);
    memcpy(groupsalt, prf_buf + hmaclen + keylen, SALT_LEN);
    ivctr = 0;
    free(prf_buf);

    if ((keyextype == KEYEX_RSA) || (keyextype == KEYEX_ECDH_RSA)) {
        if ((!strcmp(keyfile, "")) || (newkeylen != 0)) {
            privkey.rsa = gen_RSA_key(newkeylen, RSA_EXP, keyfile);
        } else {
            privkey.rsa = read_RSA_key(keyfile);
        }
        if (!privkey.key) {
            log0(0, 0, 0, "Failed to read/generate private key");
            exit(ERR_CRYPTO);
        }
        privkeylen = RSA_keylen(privkey.rsa);
    } else {
        if ((!strcmp(keyfile, "")) || (ecdsa_curve != 0)) {
            privkey.ec = gen_EC_key(ecdsa_curve, 0, keyfile);
        } else {
            privkey.ec = read_EC_key(keyfile);
        }
        if (!privkey.key) {
            log0(0, 0, 0, "Failed to read/generate private key");
            exit(ERR_CRYPTO);
        }
        privkeylen = ECDSA_siglen(privkey.ec);
    }
    if ((keyextype == KEYEX_ECDH_RSA) || (keyextype == KEYEX_ECDH_ECDSA)) {
        dhkey.ec = gen_EC_key(ecdh_curve, 1, NULL);
        if (!dhkey.key) {
            log0(0, 0, 0, "Failed to generate DH key");
            exit(ERR_CRYPTO);
        }
    }
}
Example #17
0
void CCellView::HandleDrop(BMessage *inMessage)
{
	long l;
	void * p;
	BPoint dp = inMessage->DropPoint();
	
	fDragIsAcceptable = false;
	
	if (inMessage->FindPointer("container", &p) == B_NO_ERROR)
	{
		key_info ki;
		get_key_info(&ki);
		
		CContainer *srcContainer;
		range srcRange, dstRange;
		CCellView *srcView;
		int action;
		
		srcContainer = (CContainer *)p;
		FailOSErr(inMessage->FindData("range", 'rang', (const void**)&p, &l), errMessageMissing);
		srcRange = *(range *)p;
		FailOSErr(inMessage->FindPointer("cellview", &p), errMessageMissing);
		srcView = (CCellView *)p;
		
		if (srcView != this)
			action = dragCopy;
		else
			action = dragMove;
		
		inMessage->FindBool("dragacopy", &fDragACopy);
		
		if (srcView == this &&
		    (ki.modifiers & B_CONTROL_KEY ||
			fDragACopy))
		{
			BPopUpMenu popup("dragpopup", false);
			popup.SetFont(be_plain_font);
			popup.AddItem(new BMenuItem(GetMessage(msgLinkHere), NULL));
			popup.AddItem(new BMenuItem(GetMessage(msgMoveHere), NULL));
			popup.AddItem(new BMenuItem(GetMessage(msgCopyHere), NULL));
			popup.AddSeparatorItem();
			popup.AddItem(new BMenuItem(GetMessage(msgCancel), NULL));
			
			BMenuItem *item = popup.Go(dp, false, true);
			int result = item ? popup.IndexOf(item) : -1;
			switch (result)
			{
				case 0: action = dragLink; break;
				case 1: action = dragMove; break;
				case 2: action = dragCopy; break;
				default:
					ClearAnts();
					fCurCell = fSelection.TopLeft();
					return;
			}
		}
	
		dstRange = srcRange;
		dstRange.OffsetBy(fCurCell.h - dstRange.left,
			fCurCell.v - dstRange.top);
		
		((CCellWindow *)Window())->
			RegisterCommand(new CDragCommand(this, srcContainer,
				fContainer, &srcRange, &dstRange, action));
	}
	else if (inMessage->FindData("text/plain", B_MIME_DATA, (const void **)&p, &l) == B_NO_ERROR)
	{
		cell dc;
		
		ConvertFromScreen(&dp);
		GetCellHitBy(dp, dc);
		
		BMemoryIO buf(p, l);
		CContainer *srcContainer = new CContainer;
		range srcRange, dstRange;
		
		CTextConverter conv(buf, srcContainer);
		conv.ConvertFromText(srcRange);
		
		dstRange = srcRange;
		dstRange.OffsetBy(dc.h - srcRange.left, dc.v - srcRange.top);
		
		((CCellWindow *)Window())->
			RegisterCommand(new CDragCommand(this, srcContainer,
				fContainer, &srcRange, &dstRange, dragMove));

		srcContainer->Release();
	}
	else
	{
		beep();
		ClearAnts();
		fCurCell = fSelection.TopLeft();
	}
} /* CCellView::HandleDrop */
Example #18
0
/**
 * Send a KEYINFO message.  Sent during the Announce phase for a group
 * with encryption enabled.
 * Returns 1 on success, 0 on fail.
 */
int send_keyinfo(const struct finfo_t *finfo, int attempt)
{
    unsigned char *buf, *iv;
    struct uftp_h *header;
    struct keyinfo_h *keyinfo;
    struct destkey *keylist;
    unsigned int hsize, payloadlen, len;
    int maxdest, packetcnt, dests, iv_init, i;
    int unauth_keytype, unauth_keylen, unauth_ivlen;

    // Don't use a cipher in an authentication mode to encrypt the group master
    unauth_keytype = unauth_key(keytype);
    get_key_info(unauth_keytype, &unauth_keylen, &unauth_ivlen);

    buf = safe_calloc(MAXMTU, 1);
    iv = safe_calloc(unauth_ivlen, 1);
    header = (struct uftp_h *)buf;
    keyinfo = (struct keyinfo_h *)(buf + sizeof(struct uftp_h));
    keylist = (struct destkey *)((char *)keyinfo + sizeof(struct keyinfo_h));

    set_uftp_header(header, KEYINFO, finfo->group_id, finfo->group_inst,
                    grtt, destcount);
    keyinfo->func = KEYINFO;
    keyinfo->hlen = sizeof(struct keyinfo_h) / 4;
    keylist = (struct destkey *)((uint8_t *)keyinfo + (keyinfo->hlen * 4));

    iv_init = 0;
    hsize = sizeof(struct keyinfo_h);
    maxdest = blocksize / sizeof(struct destkey);
    packetcnt = 1;
    for (i = 0, dests = 0; i < destcount; i++) {
        if (destlist[i].status == DEST_REGISTERED) {
            if (!iv_init) {
                ivctr++;
                keyinfo->iv_ctr_hi =htonl((ivctr & 0xFFFFFFFF00000000LL) >> 32);
                keyinfo->iv_ctr_lo = htonl(ivctr & 0x00000000FFFFFFFFLL);
                iv_init = 1;
            }
            keylist[dests].dest_id = destlist[i].id;
            build_iv(iv, destlist[i].encinfo->salt, unauth_ivlen,
                     uftp_htonll(ivctr), header->src_id);
            if (!encrypt_block(unauth_keytype, iv,destlist[i].encinfo->key,
                               NULL,0, &groupmaster[1], sizeof(groupmaster) - 1,
                               keylist[dests].groupmaster, &len)) {
                glog0(finfo, "Error encrypting KEYINFO for %s",
                             destlist[i].name);
                free(buf);
                free(iv);
                return 0;
            }
            dests++;
        }
        if ((dests >= maxdest) || ((i == destcount - 1) && (dests > 0))) {
            header->seq = htons(send_seq++);
            payloadlen = hsize + (dests * sizeof(struct destkey));
            glog2(finfo, "Sending KEYINFO %d.%d", attempt, packetcnt);
            if (nb_sendto(sock, buf, payloadlen + sizeof(struct uftp_h), 0,
                          (struct sockaddr *)&receive_dest,
                          family_len(receive_dest)) == SOCKET_ERROR) {
                gsockerror(finfo, "Error sending KEYINFO");
                sleep(1);
                free(buf);
                free(iv);
                return 0;
            }
            if (packet_wait) usleep(packet_wait);
            memset(keylist, 0, maxdest * sizeof(struct destkey));
            iv_init = 0;
            dests = 0;
            packetcnt++;
        }
    }
Example #19
0
/**
 * Takes a block of data encrypted with a symmetric cypher and decrypts it.
 * The output buffer must be at least the size of source data.
 */
int decrypt_block(int keytype, const unsigned char *IV,
                  const unsigned char *key,
                  const unsigned char *src, unsigned int srclen,
                  unsigned char *dest, unsigned int *destlen)
{
    // TODO: right now we reimport the key each time.  Test to see if this
    // is quick enough or if we need to cache an imported key.
    HCRYPTKEY hckey;
    char keyblob[BLOBLEN];
    BLOBHEADER *bheader;
    DWORD *keysize;
    BYTE *keydata;
    int bloblen, keylen, ivlen, rval;
    ALG_ID alg;
    DWORD mode, _destlen;

    get_key_info(keytype, &keylen, &ivlen);
    alg = get_cipher(keytype);

    bheader = (BLOBHEADER *)keyblob;
    keysize = (DWORD *)(keyblob + sizeof(BLOBHEADER));
    keydata = (BYTE *)((char *)keysize + sizeof(DWORD));

    memset(keyblob, 0, sizeof(keyblob));
    bheader->bType = PLAINTEXTKEYBLOB;
    bheader->bVersion = CUR_BLOB_VERSION;
    bheader->aiKeyAlg = alg;
    *keysize = keylen;
    memcpy(keydata, key, keylen);
    bloblen = sizeof(BLOBHEADER) + sizeof(DWORD) + keylen;

    if (!CryptImportKey(base_prov, keyblob, bloblen, 0, 0, &hckey)) {
        mserror("CryptImportKey failed");
        return 0;
    }

    mode = CRYPT_MODE_CBC;
    if (!CryptSetKeyParam(hckey, KP_MODE, (BYTE *)&mode, 0)) {
        mserror("CryptSetKeyParam failed on KP_MODE");
        rval = 0;
        goto end;
    }
    if (!CryptSetKeyParam(hckey, KP_IV, IV, 0)) {
        mserror("CryptSetKeyParam failed on KP_IV");
        rval = 0;
        goto end;
    }
    memcpy(dest, src, srclen);
    _destlen = srclen;
    if (!CryptDecrypt(hckey, 0, 1, 0, dest, &_destlen)) {
        mserror("CryptDecrypt failed");
        rval = 0;
        goto end;
    }
    *destlen = _destlen;
    rval = 1;

end:
    if (!CryptDestroyKey(hckey)) {
        mserror("CryptDestroyKey failed");
    }
    return rval;
}
int
main(int argc, char *argv[])
{
	// 256 frames * 4 buffer parts * 2 channels * 2 bytes per sample
	// will give us internal buffer of 4096 bytes
	size_t framesPerBufferPart = 256;
	size_t bufferPartCount = 4;

	if (argc != 1 && argc != 3) {
		printf("Usage: %s [<frames per part> <parts>]\n",
			argv[0]);
		return 0;
	}

	if (argc == 3) {
		size_t size = strtoul(argv[1], NULL, 10);
		if (size > 0)
			framesPerBufferPart = size;

		size = strtoul(argv[2], NULL,  10);
		if (size > 0)
			bufferPartCount = size;
	}

	printf("frames per buffer part: %ld\n", framesPerBufferPart);
	printf("buffer part count: %ld\n", bufferPartCount);

	gs_audio_format gsFormat;
	memset(&gsFormat, 0, sizeof(gsFormat));
	gsFormat.frame_rate = 48000;
	gsFormat.channel_count = 1;
	gsFormat.format = gs_audio_format::B_GS_S16;
	gsFormat.byte_order = B_MEDIA_LITTLE_ENDIAN;
	gsFormat.buffer_size = framesPerBufferPart;

	BPushGameSound pushGameSound(framesPerBufferPart, &gsFormat,
		bufferPartCount);
	if (pushGameSound.InitCheck() != B_OK) {
		printf("trouble initializing push game sound: %s\n",
			strerror(pushGameSound.InitCheck()));
		return 1;
	}

	uint8 *buffer;
	size_t bufferSize;
	if (pushGameSound.LockForCyclic((void **)&buffer, &bufferSize)
			!= BPushGameSound::lock_ok) {
		printf("cannot lock buffer\n");
		return 1;
	}
	memset(buffer, 0, bufferSize);

	if (pushGameSound.StartPlaying() != B_OK) {
		printf("cannot start playback\n");
		return 1;
	}

	printf("playing, press [esc] to exit...\n");

	key_info keyInfo;

	size_t sampleCount = framesPerBufferPart * bufferPartCount;
	for(size_t pos = 0; pos < sampleCount; pos++)
	{
		*(int16_t*)(buffer + pos * sizeof(int16_t))
			= (int16_t)(2000 * sin(pos * gsFormat.frame_rate
					/ ((float)sampleCount * 440)));
	}

	while (true) {
		usleep(1000000 * framesPerBufferPart / gsFormat.frame_rate);

		// check escape key state
		if (get_key_info(&keyInfo) != B_OK) {
			printf("\nkeyboard state read error\n");
			break;
		}
		if ((keyInfo.key_states[0] & 0x40) != 0)
			break;
	}

	pushGameSound.StopPlaying();

	printf("\nfinished.\n");

	return 0;
}
Example #21
0
static void
update_listener(ns_controls_t *cp, controllistener_t **listenerp,
		const cfg_obj_t *control, const cfg_obj_t *config,
		isc_sockaddr_t *addr, cfg_aclconfctx_t *aclconfctx,
		const char *socktext, isc_sockettype_t type)
{
	controllistener_t *listener;
	const cfg_obj_t *allow;
	const cfg_obj_t *global_keylist = NULL;
	const cfg_obj_t *control_keylist = NULL;
	dns_acl_t *new_acl = NULL;
	controlkeylist_t keys;
	isc_result_t result = ISC_R_SUCCESS;

	for (listener = ISC_LIST_HEAD(cp->listeners);
	     listener != NULL;
	     listener = ISC_LIST_NEXT(listener, link))
		if (isc_sockaddr_equal(addr, &listener->address))
			break;

	if (listener == NULL) {
		*listenerp = NULL;
		return;
	}

	/*
	 * There is already a listener for this sockaddr.
	 * Update the access list and key information.
	 *
	 * First try to deal with the key situation.  There are a few
	 * possibilities:
	 *  (a)	It had an explicit keylist and still has an explicit keylist.
	 *  (b)	It had an automagic key and now has an explicit keylist.
	 *  (c)	It had an explicit keylist and now needs an automagic key.
	 *  (d) It has an automagic key and still needs the automagic key.
	 *
	 * (c) and (d) are the annoying ones.  The caller needs to know
	 * that it should use the automagic configuration for key information
	 * in place of the named.conf configuration.
	 *
	 * XXXDCL There is one other hazard that has not been dealt with,
	 * the problem that if a key change is being caused by a control
	 * channel reload, then the response will be with the new key
	 * and not able to be decrypted by the client.
	 */
	if (control != NULL)
		get_key_info(config, control, &global_keylist,
			     &control_keylist);

	if (control_keylist != NULL) {
		INSIST(global_keylist != NULL);

		ISC_LIST_INIT(keys);
		result = controlkeylist_fromcfg(control_keylist,
						listener->mctx, &keys);
		if (result == ISC_R_SUCCESS) {
			free_controlkeylist(&listener->keys, listener->mctx);
			listener->keys = keys;
			register_keys(control, global_keylist, &listener->keys,
				      listener->mctx, socktext);
		}
	} else {
		free_controlkeylist(&listener->keys, listener->mctx);
		result = get_rndckey(listener->mctx, &listener->keys);
	}

	if (result != ISC_R_SUCCESS && global_keylist != NULL) {
		/*
		 * This message might be a little misleading since the
		 * "new keys" might in fact be identical to the old ones,
		 * but tracking whether they are identical just for the
		 * sake of avoiding this message would be too much trouble.
		 */
		if (control != NULL)
			cfg_obj_log(control, ns_g_lctx, ISC_LOG_WARNING,
				    "couldn't install new keys for "
				    "command channel %s: %s",
				    socktext, isc_result_totext(result));
		else
			isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
				      NS_LOGMODULE_CONTROL, ISC_LOG_WARNING,
				      "couldn't install new keys for "
				      "command channel %s: %s",
				      socktext, isc_result_totext(result));
	}

	/*
	 * Now, keep the old access list unless a new one can be made.
	 */
	if (control != NULL && type == isc_sockettype_tcp) {
		allow = cfg_tuple_get(control, "allow");
		result = cfg_acl_fromconfig(allow, config, ns_g_lctx,
					    aclconfctx, listener->mctx, 0,
					    &new_acl);
	} else {
		result = dns_acl_any(listener->mctx, &new_acl);
	}

	if (result == ISC_R_SUCCESS) {
		dns_acl_detach(&listener->acl);
		dns_acl_attach(new_acl, &listener->acl);
		dns_acl_detach(&new_acl);
		/* XXXDCL say the old acl is still used? */
	} else if (control != NULL)
		cfg_obj_log(control, ns_g_lctx, ISC_LOG_WARNING,
			    "couldn't install new acl for "
			    "command channel %s: %s",
			    socktext, isc_result_totext(result));
	else
		isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
			      NS_LOGMODULE_CONTROL, ISC_LOG_WARNING,
			      "couldn't install new acl for "
			      "command channel %s: %s",
			      socktext, isc_result_totext(result));

	if (result == ISC_R_SUCCESS && type == isc_sockettype_unix) {
		isc_uint32_t perm, owner, group;
		perm  = cfg_obj_asuint32(cfg_tuple_get(control, "perm"));
		owner = cfg_obj_asuint32(cfg_tuple_get(control, "owner"));
		group = cfg_obj_asuint32(cfg_tuple_get(control, "group"));
		result = ISC_R_SUCCESS;
		if (listener->perm != perm || listener->owner != owner ||
		    listener->group != group)
			result = isc_socket_permunix(&listener->address, perm,
						     owner, group);
		if (result == ISC_R_SUCCESS) {
			listener->perm = perm;
			listener->owner = owner;
			listener->group = group;
		} else if (control != NULL)
			cfg_obj_log(control, ns_g_lctx, ISC_LOG_WARNING,
				    "couldn't update ownership/permission for "
				    "command channel %s", socktext);
	}

	*listenerp = listener;
}
Example #22
0
/**
 * Sends a KEYINFO to each client that the server sent a REG_CONF for.
 */
void send_keyinfo(struct pr_group_list_t *group, const uint32_t *addrlist,
                  int addrlen)
{
    unsigned char *buf, *iv;
    struct uftp_h *header;
    struct keyinfo_h *keyinfo_hdr;
    struct destkey *keylist;
    unsigned int payloadlen, len;
    int maxdest, packetcnt, dests, iv_init, foundaddr, i, j;
    int unauth_keytype, unauth_keylen, unauth_ivlen;
    struct pr_destinfo_t *dest;

    // Don't use a cipher in an authentication mode to encrypt the group master
    unauth_keytype = unauth_key(group->keytype);
    get_key_info(unauth_keytype, &unauth_keylen, &unauth_ivlen);

    buf = safe_calloc(MAXMTU, 1);
    iv = safe_calloc(unauth_ivlen, 1);
    header = (struct uftp_h *)buf;
    keyinfo_hdr = (struct keyinfo_h *)(buf + sizeof(struct uftp_h));
    keylist= (struct destkey *)((char *)keyinfo_hdr + sizeof(struct keyinfo_h));

    set_uftp_header(header, KEYINFO, group);
    keyinfo_hdr->func = KEYINFO;
    keyinfo_hdr->hlen = sizeof(struct keyinfo_h) / 4;

    iv_init = 0;
    maxdest = max_msg_dest(group, KEYINFO, keyinfo_hdr->hlen * 4);
    packetcnt = 1;
    for (i = 0, dests = 0; i < group->destcount; i++) {
        dest = &group->destinfo[i];
        if (dest->state == PR_CLIENT_CONF) {
            if (addrlist) {
                // We just got a REG_CONF, so only send to listed hosts
                for (j = 0, foundaddr = 0; (j < addrlen) && (!foundaddr); j++) {
                    if (dest->id == addrlist[j]) {
                        foundaddr = 1;
                    }
                }
            } else {
                foundaddr = 1;
            }
            if (foundaddr) {
                if (!iv_init) {
                    group->ivctr++;
                    keyinfo_hdr->iv_ctr_hi =
                            htonl((group->ivctr & 0xFFFFFFFF00000000LL) >> 32);
                    keyinfo_hdr->iv_ctr_lo =
                            htonl(group->ivctr & 0x00000000FFFFFFFFLL);
                    iv_init = 1;
                }
                keylist[dests].dest_id = dest->id;
                build_iv(iv, dest->salt, unauth_ivlen,
                         uftp_htonll(group->ivctr), group->src_id);
                if (!encrypt_block(unauth_keytype, iv, dest->key,
                                   NULL, 0, &group->groupmaster[1],
                                   sizeof(group->groupmaster) - 1,
                                   keylist[dests].groupmaster, &len)) {
                    glog0(group, "Error encrypting KEYINFO for %s", dest->name);
                    free(buf);
                    free(iv);
                    return;
                }
                dests++;
            }
        }
        if ((dests >= maxdest) ||
                ((i == group->destcount - 1) && (dests > 0))) {
            payloadlen = sizeof(struct keyinfo_h) +
                         (dests * sizeof(struct destkey));
            glog2(group,"Sending KEYINFO %d.%d", group->keyinfo_cnt, packetcnt);
            if (nb_sendto(listener, buf, payloadlen + sizeof(struct uftp_h), 0,
                       (struct sockaddr *)&group->privatemcast,
                        family_len(group->privatemcast)) == SOCKET_ERROR) {
                gsockerror(group, "Error sending KEYINFO");
                free(buf);
                free(iv);
                return;
            }
            // TODO: This value is good for around 100Mbps.  This is under the
            // assumption that the client proxy is local to the clients
            // it serves.  This should probably be a parameter.
            usleep(120);
            memset(keylist, 0, maxdest * sizeof(struct destkey));
            iv_init = 0;
            dests = 0;
            packetcnt++;
        }
    }