Пример #1
0
int parse_command_line(int argc, char *argv[], char ***params, int switcher_no, char *switchers[])
{
FILE *ptr	= NULL;
int i		= 0;
int j		= 0;

	if (argc!=(switcher_no*2+1))
	{
		printf("\n----------- Rencryption software for BMD 1.7.1 (Unizeto Technologies SA) ------------\n");
		printf("executive parameters:\n");
		printf("\t%s level\t\tdebug level\n",switchers[0]);
		printf("\t%s file\t\t\tbmd config file\n",switchers[1]);
		printf("\t%s .pfx file\t\tcertificate for rencrypting from\n",switchers[2]);
		printf("\t%s .pfx file\t\tcertificate for rencrypting to\n",switchers[3]);
		printf("\t%s password\t\tpassword for certificate for rencrypting from\n",switchers[4]);
		printf("\t%s password\t\tpassword for certificate for rencrypting to\n",switchers[5]);
		printf("\t%s id number\tfile's id number to rencrypt database from\n",switchers[6]);
		printf("\t%s id number\tfile's id number to rencrypt database to\n",switchers[7]);
		printf("-------------------------------------------------------------------------------------\n\n");
		printf("Error: Invalid parameters\n");
		return -1;
	}
	/********************************/
	/*	pasowanie linii polecen	*/
	/********************************/
	(*params)=(char **)malloc(switcher_no*sizeof(char*));
	for (i=1; i<argc; i++)
	{
		for (j=0; j<switcher_no; j++)
		{
			if (strcmp(argv[i],switchers[j])==0)
			{
				asprintf(&((*params)[j]),"%s",argv[i+1]);
				break;
			}
		}
	}

	/************************************************/
	/*	sprawdzenie poprawnosci parametrow	*/
	/************************************************/
	for (i=0; i<strlen((*params)[0]); i++)
	{
		if ((((*params)[0][i]<'0') || ((*params)[0][i]>'9')) && (*params)[0][i]!='-')
		{
			PRINT_ERROR("Invalid debug level format\n");
			return -2;
		}
	}

	_GLOBAL_debug_level = atoi((*params)[0]);
	if ((ptr=fopen((*params)[1],"r"))==NULL)
	{
		PRINT_ERROR("Cannot open configuration file\n");
		return -3;
	}
	else fclose(ptr);

	if ((ptr=fopen((*params)[2],"r"))==NULL)
	{
		PRINT_ERROR("Cannot open pfx file %s\n",(*params)[2]);
		return -4;
	}
	else fclose(ptr);

	if ((ptr=fopen((*params)[3],"r"))==NULL)
	{
		PRINT_ERROR("Cannot open pfx file %s\n",(*params)[3]);
		return -5;
	}
	else fclose(ptr);

	return 0;
}
Пример #2
0
void state_bcm() {
	int i, j, ret;
	struct sockaddr_can caddr;
	socklen_t caddrlen = sizeof(caddr);
	struct ifreq ifr;
	char rxmsg[RXLEN];
	char buf[MAXLEN];

	struct {
		struct bcm_msg_head msg_head;
		struct can_frame frame;
	} msg;

	struct {
		struct bcm_msg_head msg_head;
		struct can_frame frame[257]; /* MAX_NFRAMES + MUX MASK */
	} muxmsg;

	if(previous_state != STATE_BCM) {
		/* open BCM socket */
		if ((sc = socket(PF_CAN, SOCK_DGRAM, CAN_BCM)) < 0) {
			PRINT_ERROR("Error while opening BCM socket %s\n", strerror(errno));
			state = STATE_SHUTDOWN;
			return;
		}

		memset(&caddr, 0, sizeof(caddr));
		caddr.can_family = PF_CAN;
		/* can_ifindex is set to 0 (any device) => need for sendto() */

		PRINT_VERBOSE("connecting BCM socket...\n")
			if (connect(sc, (struct sockaddr *)&caddr, sizeof(caddr)) < 0) {
				PRINT_ERROR("Error while connecting BCM socket %s\n", strerror(errno));
				state = STATE_SHUTDOWN;
				return;
			}
		previous_state = STATE_BCM;
	}

	FD_ZERO(&readfds);
	FD_SET(sc, &readfds);
	FD_SET(client_socket, &readfds);

	/*
	 * Check if there are more elements in the element buffer before calling select() and
	 * blocking for new packets.
	 */
	if(more_elements) {
		FD_CLR(sc, &readfds);
	} else {
		ret = select((sc > client_socket)?sc+1:client_socket+1, &readfds, NULL, NULL, NULL);

		if(ret < 0) {
			PRINT_ERROR("Error in select()\n")
				state = STATE_SHUTDOWN;
			return;
		}
	}

	if (FD_ISSET(sc, &readfds)) {

		ret = recvfrom(sc, &msg, sizeof(msg), 0,
			       (struct sockaddr*)&caddr, &caddrlen);

		/* read timestamp data */
		if(ioctl(sc, SIOCGSTAMP, &tv) < 0) {
			PRINT_ERROR("Could not receive timestamp\n");
		}

		/* Check if this is an error frame */
		if(msg.msg_head.can_id & CAN_ERR_FLAG) {
			if(msg.frame.can_dlc != CAN_ERR_DLC) {
				PRINT_ERROR("Error frame has a wrong DLC!\n")
					} else {
				snprintf(rxmsg, RXLEN, "< error %03X %ld.%06ld ", msg.msg_head.can_id, tv.tv_sec, tv.tv_usec);

				for ( i = 0; i < msg.frame.can_dlc; i++)
					snprintf(rxmsg + strlen(rxmsg), RXLEN - strlen(rxmsg), "%02X ",
						 msg.frame.data[i]);

				snprintf(rxmsg + strlen(rxmsg), RXLEN - strlen(rxmsg), " >");
				send(client_socket, rxmsg, strlen(rxmsg), 0);
			}
		} else {
			if(msg.msg_head.can_id & CAN_EFF_FLAG) {
Пример #3
0
void CALLBACK kuhl_m_vault_list_descItem_PINLogonOrPicturePasswordOrBiometric(const VAULT_GUID_STRING * pGuidString, PVOID enumItem, PVOID getItem, BOOL is8)
{
	PVAULT_ITEM_8 enumItem8 = (PVAULT_ITEM_8) enumItem, getItem8 = (PVAULT_ITEM_8) getItem;
	PWSTR name, domain, sid, bgPath = NULL;
	UNICODE_STRING uString;
	DWORD i, dwError, szNeeded;
	PVAULT_PICTURE_PASSWORD_ELEMENT pElements;
	PVAULT_BIOMETRIC_ELEMENT bElements;
	PWCHAR bufferStart;
	HKEY hPicturePassword, hUserPicturePassword;

	if(enumItem8->Identity && (enumItem8->Identity->Type == ElementType_ByteArray))
	{
		kprintf(L"\t\tUser : "******"\t\tUser            : %s\\%s\n", domain, name);
			LocalFree(name);
			LocalFree(domain);
		}
		else kull_m_string_displaySID((PSID) enumItem8->Identity->data.ByteArray.Value);
		kprintf(L"\n");

		if(pGuidString->guid.Data1 == 0x0b4b8a12b)
		{
			dwError = RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Authentication\\LogonUI\\PicturePassword", 0, KEY_ENUMERATE_SUB_KEYS, &hPicturePassword);
			if(dwError == STATUS_SUCCESS)
			{
				if(ConvertSidToStringSid((PSID) enumItem8->Identity->data.ByteArray.Value, &sid))
				{
					dwError = RegOpenKeyEx(hPicturePassword, sid, 0, KEY_QUERY_VALUE, &hUserPicturePassword);
					if(dwError == STATUS_SUCCESS)
					{
						dwError = RegQueryValueEx(hUserPicturePassword, L"bgPath", NULL, NULL, NULL, &szNeeded);
						if(dwError == STATUS_SUCCESS)
						{
							if(bgPath = (PWSTR) LocalAlloc(LPTR, szNeeded))
							{
								dwError = RegQueryValueEx(hUserPicturePassword, L"bgPath", NULL, NULL, (LPBYTE) bgPath, &szNeeded);
								if(dwError != STATUS_SUCCESS)
								{
									PRINT_ERROR(L"RegQueryValueEx 2 : %08x\n", dwError);
									bgPath = (PWSTR) LocalFree(bgPath);
								}
							}
						}
						else PRINT_ERROR(L"RegQueryValueEx 1 : %08x\n", dwError);
						RegCloseKey(hUserPicturePassword);
					}
					else PRINT_ERROR(L"RegOpenKeyEx SID : %08x\n", dwError);
					LocalFree(sid);
				}
				else PRINT_ERROR_AUTO(L"ConvertSidToStringSid");
				RegCloseKey(hPicturePassword);
			}
			else PRINT_ERROR(L"RegOpenKeyEx PicturePassword : %08x\n", dwError);
		}
	}

	if(getItem8 && getItem8->Authenticator && (getItem8->Authenticator->Type == ElementType_ByteArray))
	{
		uString.Length = uString.MaximumLength = (USHORT) getItem8->Authenticator->data.ByteArray.Length;
		uString.Buffer = (PWSTR) getItem8->Authenticator->data.ByteArray.Value;
		kprintf(L"\t\tPassword        : "******"%s", uString.Buffer);
		else 
			kull_m_string_wprintf_hex(uString.Buffer, uString.Length, 1);
		kprintf(L"\n");
	}

	if(enumItem8->Properties && (enumItem8->cbProperties > 0) && enumItem8->Properties + 0)
	{
		switch(pGuidString->guid.Data1)
		{
		case 0x0b2e033f5:	// pin
			if((enumItem8->Properties + 0)->Type == ElementType_UnsignedShort)
				kprintf(L"\t\tPIN Code        : %04hu\n", (enumItem8->Properties + 0)->data.UnsignedShort);
			break;
		case 0x0b4b8a12b:	// picture
			if((enumItem8->Properties + 0)->Type == ElementType_ByteArray)
			{
				pElements = (PVAULT_PICTURE_PASSWORD_ELEMENT) (enumItem8->Properties + 0)->data.ByteArray.Value;
				if(bgPath)
				{
					kprintf(L"\t\tBackground path : %s\n", bgPath);
					LocalFree(bgPath);
				}
				kprintf(L"\t\tPicture password (grid is 150*100)\n");

				for(i = 0; i < 3; i++)
				{
					kprintf(L"\t\t [%u] ", i);
					switch(pElements[i].Type)
					{
					case PP_Point:
						kprintf(L"point  (x = %3u ; y = %3u)", pElements[i].point.coord.x, pElements[i].point.coord.y);
						break;
					case PP_Circle:
						kprintf(L"circle (x = %3u ; y = %3u ; r = %3u) - %s", pElements[i].circle.coord.x, pElements[i].circle.coord.y, pElements[i].circle.size, (pElements[i].circle.clockwise ? L"clockwise" : L"anticlockwise"));
						break;
					case PP_Line:
						kprintf(L"line   (x = %3u ; y = %3u) -> (x = %3u ; y = %3u)", pElements[i].line.start.x, pElements[i].line.start.y, pElements[i].line.end.x, pElements[i].line.end.y);
						break;
					default:
						kprintf(L"%u\n", pElements[i].Type);
					}
					kprintf(L"\n");
				}
			}
			break;
		case 0x0fec87291:	// biometric
			if((enumItem8->Properties + 0)->Type == ElementType_ByteArray)
			{
				bElements = (PVAULT_BIOMETRIC_ELEMENT) (enumItem8->Properties + 0)->data.ByteArray.Value;
				bufferStart = (PWCHAR) ((PBYTE) bElements + bElements->headersize);
				kprintf(L"\t\tProperty        : ");
				if(bElements->domainnameLength > 1)
					kprintf(L"%.*s\\", bElements->domainnameLength - 1, bufferStart + bElements->usernameLength);
				if(bElements->usernameLength > 1)
					kprintf(L"%.*s", bElements->usernameLength - 1, bufferStart);
				kprintf(L"\n");
			}
			break;
		default:
			kprintf(L"todo ?\n");
		}
	}

}
Пример #4
0
void rtm_read_param_reply(struct fins_module *module, struct finsFrame *ff) {
	PRINT_DEBUG("Entered: module=%p, ff=%p, meta=%p", module, ff, ff->metaData);
	struct rtm_data *md = (struct rtm_data *) module->data;

	secure_sem_wait(&md->shared_sem);
	struct rtm_command *cmd = (struct rtm_command *) list_find1(md->cmd_list, rtm_cmd_serial_test, &ff->ctrlFrame.serial_num);
	if (cmd != NULL) {
		list_remove(md->cmd_list, cmd);

		struct rtm_console *console = (struct rtm_console *) list_find1(md->console_list, rtm_console_id_test, &cmd->console_id);
		if (console != NULL) {
			//TODO extract answer
			if (ff->ctrlFrame.ret_val == FCF_TRUE) {
				char temp[100];

				int32_t val_int32;
				int64_t val_int64;
				float val_float;
				char *val_str;

				switch (cmd->param_type) {
				case META_TYPE_INT32:
					secure_metadata_readFromElement(ff->metaData, "value", &val_int32);
					sprintf(temp, "'%s'=%d", cmd->param_str, val_int32);
					break;
				case META_TYPE_INT64:
					secure_metadata_readFromElement(ff->metaData, "value", &val_int64);
					sprintf(temp, "'%s'=%lld", cmd->param_str, val_int64);
					break;
				case META_TYPE_FLOAT:
					secure_metadata_readFromElement(ff->metaData, "value", &val_float);
					sprintf(temp, "'%s'=%f", cmd->param_str, val_float);
					break;
				case META_TYPE_STRING:
					secure_metadata_readFromElement(ff->metaData, "value", &val_str);
					sprintf(temp, "'%s'='%s'", cmd->param_str, val_str);
					break;
				default:
					PRINT_ERROR("todo error");
					exit(-1);
				}

				rtm_send_text(console->fd, temp);
			} else {
				//send error
				uint32_t ret_msg;
				secure_metadata_readFromElement(ff->metaData, "ret_msg", &ret_msg);

				char temp[100];
				sprintf(temp, "unsuccessful, returned error=%u", ret_msg);
				rtm_send_text(console->fd, temp);
			}
		} else {
			PRINT_WARN("todo error");
		}
		sem_post(&md->shared_sem);

		free(cmd);
	} else {
		sem_post(&md->shared_sem);
		PRINT_WARN("todo error");
		//TODO error, drop
		freeFinsFrame(ff);
	}
}
Пример #5
0
void kull_m_rpc_drsr_free_DRS_MSG_GETCHGREPLY_data(DWORD dwOutVersion, DRS_MSG_GETCHGREPLY * reply)
{
	DWORD i, j;
	REPLENTINFLIST *pReplentinflist, *pNextReplentinflist;
	if(reply)
	{
		switch(dwOutVersion)
		{
		case 6:
			if(reply->V6.pNC)
				MIDL_user_free(reply->V6.pNC);
			if(reply->V6.pUpToDateVecSrc)
				MIDL_user_free(reply->V6.pUpToDateVecSrc);
			if(reply->V6.PrefixTableSrc.pPrefixEntry)
			{
				for(i = 0; i < reply->V6.PrefixTableSrc.PrefixCount; i++)
					if(reply->V6.PrefixTableSrc.pPrefixEntry[i].prefix.elements)
						MIDL_user_free(reply->V6.PrefixTableSrc.pPrefixEntry[i].prefix.elements);
				MIDL_user_free(reply->V6.PrefixTableSrc.pPrefixEntry);
			}
			pNextReplentinflist = reply->V6.pObjects;
			while(pReplentinflist = pNextReplentinflist)
			{
				pNextReplentinflist = pReplentinflist->pNextEntInf;
				if(pReplentinflist->Entinf.pName)
					MIDL_user_free(pReplentinflist->Entinf.pName);
				if(pReplentinflist->Entinf.AttrBlock.pAttr)
				{
					for(i = 0; i < pReplentinflist->Entinf.AttrBlock.attrCount; i++)
					{
						if(pReplentinflist->Entinf.AttrBlock.pAttr[i].AttrVal.pAVal)
						{
							for(j = 0; j < pReplentinflist->Entinf.AttrBlock.pAttr[i].AttrVal.valCount; j++)
								if(pReplentinflist->Entinf.AttrBlock.pAttr[i].AttrVal.pAVal[j].pVal)
									MIDL_user_free(pReplentinflist->Entinf.AttrBlock.pAttr[i].AttrVal.pAVal[j].pVal);
							MIDL_user_free(pReplentinflist->Entinf.AttrBlock.pAttr[i].AttrVal.pAVal);
						}
					}
					MIDL_user_free(pReplentinflist->Entinf.AttrBlock.pAttr);
				}
				if(pReplentinflist->pParentGuid)
					MIDL_user_free(pReplentinflist->pParentGuid);
				if(pReplentinflist->pMetaDataExt)
					MIDL_user_free(pReplentinflist->pMetaDataExt);
				MIDL_user_free(pReplentinflist);
			}
			if(reply->V6.rgValues)
			{
				for(i = 0; i < reply->V6.cNumValues; i++)
				{
					if(reply->V6.rgValues[i].pObject)
						MIDL_user_free(reply->V6.rgValues[i].pObject);
					if(reply->V6.rgValues[i].Aval.pVal)
						MIDL_user_free(reply->V6.rgValues[i].Aval.pVal);
				}
				MIDL_user_free(reply->V6.rgValues);
			}
			break;
		case 1:
		case 2:
		case 7:
		case 9:
			PRINT_ERROR(L"TODO (maybe?)\n");
			break;
		default:
			PRINT_ERROR(L"dwOutVersion not valid (0x%08x - %u)\n", dwOutVersion, dwOutVersion);
			break;
		}
	}
}
Пример #6
0
	RenderBuffer* D3DRenderFactory::MakeRenderBuffer( InitData& init_data, AccessType access_type, BufferUsage usage, uint32_t width, uint32_t type_size)
	{
		//TODO : Change BufferUsage to support OR operation
		D3DRenderEngine* d3d_re = static_cast<D3DRenderEngine*>(&Context::Instance().GetRenderFactory().GetRenderEngine());
		D3D11_BUFFER_DESC buffer_desc;
		buffer_desc.ByteWidth = type_size * width;
		buffer_desc.Usage = D3D11_USAGE_DEFAULT;
		buffer_desc.BindFlags = 0;
		buffer_desc.CPUAccessFlags = 0;
		buffer_desc.MiscFlags = 0;
		buffer_desc.StructureByteStride = 0;
		D3D11_SUBRESOURCE_DATA data;
		data.pSysMem = init_data.data;
		data.SysMemPitch = init_data.row_pitch;
		data.SysMemSlicePitch = init_data.slice_pitch;
		switch (usage)
		{
		case BU_VERTEX:
			{
				buffer_desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
				break;
			}
		case BU_INDEX:
			{				
				buffer_desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
				break;
			}
		case BU_SHADER_RES:
			{
				buffer_desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
				break;
			}
		case BU_SHADER_CONST:
			break;
		case  BU_STRUCTURED_BUFFER:
			break;
		case BU_SR_SB:
			{
				buffer_desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
				buffer_desc.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;
				buffer_desc.StructureByteStride = type_size;
			}
			break;
		default:
			break;
		}

		switch (access_type)
		{
		case AT_CPU_GPU_ALL:
			buffer_desc.Usage = D3D11_USAGE_STAGING;
			buffer_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
			break;
		case AT_CPU_WRITE_GPU_READ:
			buffer_desc.Usage = D3D11_USAGE_DYNAMIC;
			buffer_desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
			break;
		case AT_GPU_READ_ONLY:
			buffer_desc.Usage = D3D11_USAGE_IMMUTABLE;
			buffer_desc.CPUAccessFlags = 0;
			break;
		case AT_GPU_READ_WRITE:
			buffer_desc.Usage = D3D11_USAGE_DEFAULT;
			buffer_desc.CPUAccessFlags = 0;
			break;
		default:
			buffer_desc.Usage = D3D11_USAGE_DEFAULT;
			buffer_desc.CPUAccessFlags = 0;
			break;
		}
		ID3D11Buffer* buffer;
		HRESULT result = d3d_re->D3DDevice()->CreateBuffer(&buffer_desc, &data, &buffer);
		if(FAILED(result))
		{
			PRINT_ERROR("Cannot create Buffer");
		}
		D3DRenderBuffer* d3d_render_buffer = new D3DRenderBuffer(buffer, usage, access_type);
		return d3d_render_buffer;
		
	}
Пример #7
0
NTSTATUS kuhl_m_net_user(int argc, wchar_t * argv[])
{
	NTSTATUS status, enumDomainStatus, enumUserStatus;
	UNICODE_STRING serverName, *groupName;
	SAMPR_HANDLE hServerHandle, hBuiltinHandle = NULL, hDomainHandle, hUserHandle;
	DWORD domainEnumerationContext, domainCountRetourned, userEnumerationContext, userCountRetourned, groupsCountRetourned, i, j, k, *usage, aliasCountRetourned, *alias;
	PSAMPR_RID_ENUMERATION pEnumDomainBuffer, pEnumUsersBuffer;
	PSID domainSid, userSid;
	PGROUP_MEMBERSHIP pGroupMemberShip;
	SID builtin = {1, 1, {0, 0, 0, 0, 0, 5}, {32}};

	RtlInitUnicodeString(&serverName, argc ? argv[0] : L"");
	status = SamConnect(&serverName, &hServerHandle, SAM_SERVER_CONNECT | SAM_SERVER_ENUMERATE_DOMAINS | SAM_SERVER_LOOKUP_DOMAIN, FALSE);
	if(NT_SUCCESS(status))
	{
		status = SamOpenDomain(hServerHandle, DOMAIN_LIST_ACCOUNTS | DOMAIN_LOOKUP, &builtin, &hBuiltinHandle);
		if(!NT_SUCCESS(status))
			PRINT_ERROR(L"SamOpenDomain Builtin (?) %08x\n", status);
		
		domainEnumerationContext = 0;
		do
		{
			enumDomainStatus = SamEnumerateDomainsInSamServer(hServerHandle, &domainEnumerationContext, &pEnumDomainBuffer, 1, &domainCountRetourned);
			if(NT_SUCCESS(enumDomainStatus) || enumDomainStatus == STATUS_MORE_ENTRIES)
			{
				for(i = 0; i < domainCountRetourned; i++)
				{
					kprintf(L"\nDomain name : %wZ", &pEnumDomainBuffer[i].Name);
					status = SamLookupDomainInSamServer(hServerHandle, &pEnumDomainBuffer[i].Name, &domainSid);
					if(NT_SUCCESS(status))
					{
						kprintf(L"\nDomain SID  : ");
						kull_m_string_displaySID(domainSid);
						
						status = SamOpenDomain(hServerHandle, DOMAIN_LIST_ACCOUNTS | DOMAIN_LOOKUP, domainSid, &hDomainHandle);
						if(NT_SUCCESS(status))
						{
							userEnumerationContext = 0;
							do
							{
								enumUserStatus = SamEnumerateUsersInDomain(hDomainHandle, &userEnumerationContext, 0/*UF_NORMAL_ACCOUNT*/, &pEnumUsersBuffer, 1, &userCountRetourned);
								if(NT_SUCCESS(enumUserStatus) || enumUserStatus == STATUS_MORE_ENTRIES)
								{
									for(j = 0; j < userCountRetourned; j++)
									{
										kprintf(L"\n %-5u %wZ", pEnumUsersBuffer[j].RelativeId, &pEnumUsersBuffer[j].Name);
										status = SamOpenUser(hDomainHandle, USER_READ_GROUP_INFORMATION | USER_LIST_GROUPS | USER_READ_ACCOUNT | USER_READ_LOGON |  USER_READ_PREFERENCES | USER_READ_GENERAL, pEnumUsersBuffer[j].RelativeId, &hUserHandle);
										if(NT_SUCCESS(status))
										{
											status = SamGetGroupsForUser(hUserHandle, &pGroupMemberShip, &groupsCountRetourned);
											if(NT_SUCCESS(status))
											{
												for(k = 0; k < groupsCountRetourned; k++)
												{
													kprintf(L"\n | %-5u ", pGroupMemberShip[k].RelativeId);
													status = SamLookupIdsInDomain(hDomainHandle, 1, &pGroupMemberShip[k].RelativeId, &groupName, &usage);
													if(NT_SUCCESS(status))
													{
														kprintf(L"%wZ", groupName);
														SamFreeMemory(groupName);
														SamFreeMemory(usage);
													} else PRINT_ERROR(L"SamLookupIdsInDomain %08x", status);
												}
												SamFreeMemory(pGroupMemberShip);
											} else PRINT_ERROR(L"SamGetGroupsForUser %08x", status);

											status = SamRidToSid(hUserHandle, pEnumUsersBuffer[j].RelativeId, &userSid);
											if(NT_SUCCESS(status))
											{
												status = SamGetAliasMembership(hDomainHandle, 1, &userSid, &aliasCountRetourned, &alias);
												if(NT_SUCCESS(status))
												{
													for(k = 0; k < aliasCountRetourned; k++)
													{
														kprintf(L"\n |`%-5u ", alias[k]);
														status = SamLookupIdsInDomain(hDomainHandle, 1, &alias[k], &groupName, &usage);
														if(NT_SUCCESS(status))
														{
															kprintf(L"%wZ", groupName);
															SamFreeMemory(groupName);
															SamFreeMemory(usage);
														} else PRINT_ERROR(L"SamLookupIdsInDomain %08x", status);
													}
													SamFreeMemory(alias);
												} else PRINT_ERROR(L"SamGetAliasMembership %08x", status);

												if(hBuiltinHandle)
												{
													status = SamGetAliasMembership(hBuiltinHandle, 1, &userSid, &aliasCountRetourned, &alias);
													if(NT_SUCCESS(status))
													{
														for(k = 0; k < aliasCountRetourned; k++)
														{
															kprintf(L"\n |´%-5u ", alias[k]);
															status = SamLookupIdsInDomain(hBuiltinHandle, 1, &alias[k], &groupName, &usage);
															if(NT_SUCCESS(status))
															{
																kprintf(L"%wZ", groupName);
																SamFreeMemory(groupName);
																SamFreeMemory(usage);
															} else PRINT_ERROR(L"SamLookupIdsInDomain %08x", status);
														}
														SamFreeMemory(alias);
													} else PRINT_ERROR(L"SamGetAliasMembership %08x", status);
												}


												SamFreeMemory(userSid);
											} else PRINT_ERROR(L"SamRidToSid %08x", status);
										} else PRINT_ERROR(L"SamOpenUser %08x", status);
									}
									SamFreeMemory(pEnumUsersBuffer);
								} else PRINT_ERROR(L"SamEnumerateUsersInDomain %08x", enumUserStatus);
							} while(enumUserStatus == STATUS_MORE_ENTRIES);
							SamCloseHandle(hDomainHandle);
						} else PRINT_ERROR(L"SamOpenDomain %08x", status);
						SamFreeMemory(domainSid);
					} else PRINT_ERROR(L"SamLookupDomainInSamServer %08x", status);
				}
				SamFreeMemory(pEnumDomainBuffer);
			} else PRINT_ERROR(L"SamEnumerateDomainsInSamServer %08x\n", enumDomainStatus);
			kprintf(L"\n");
		} while(enumDomainStatus == STATUS_MORE_ENTRIES);

		if(hBuiltinHandle)
			SamCloseHandle(hBuiltinHandle);

		SamCloseHandle(hServerHandle);
	} else PRINT_ERROR(L"SamConnect %08x\n", status);
	
	return ERROR_SUCCESS;
}
Пример #8
0
static int cdrom_attach(struct scst_device *dev)
{
	int res, rc;
	uint8_t cmd[10];
	const int buffer_size = 512;
	uint8_t *buffer = NULL;
	int retries;
	unsigned char sense_buffer[SCSI_SENSE_BUFFERSIZE];
	enum dma_data_direction data_dir;

	TRACE_ENTRY();

	if (dev->scsi_dev == NULL ||
	    dev->scsi_dev->type != dev->type) {
		PRINT_ERROR("%s", "SCSI device not define or illegal type");
		res = -ENODEV;
		goto out;
	}

	buffer = kmalloc(buffer_size, GFP_KERNEL);
	if (!buffer) {
		PRINT_ERROR("Buffer memory allocation (size %d) failure",
			buffer_size);
		res = -ENOMEM;
		goto out;
	}

	/* Clear any existing UA's and get cdrom capacity (cdrom block size) */
	memset(cmd, 0, sizeof(cmd));
	cmd[0] = READ_CAPACITY;
	cmd[1] = (dev->scsi_dev->scsi_level <= SCSI_2) ?
	    ((dev->scsi_dev->lun << 5) & 0xe0) : 0;
	retries = SCST_DEV_RETRIES_ON_UA;
	while (1) {
		memset(buffer, 0, buffer_size);
		memset(sense_buffer, 0, sizeof(sense_buffer));
		data_dir = SCST_DATA_READ;

		TRACE_DBG("%s", "Doing READ_CAPACITY");
		rc = scsi_execute(dev->scsi_dev, cmd, data_dir, buffer,
				   buffer_size, sense_buffer,
				   SCST_GENERIC_CDROM_REG_TIMEOUT, 3, 0
#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,29)
				   , NULL
#endif
				  );

		TRACE_DBG("READ_CAPACITY done: %x", rc);

		if ((rc == 0) ||
		    !scst_analyze_sense(sense_buffer,
				sizeof(sense_buffer), SCST_SENSE_KEY_VALID,
				UNIT_ATTENTION, 0, 0))
			break;

		if (!--retries) {
			PRINT_ERROR("UA not cleared after %d retries",
				SCST_DEV_RETRIES_ON_UA);
			dev->block_shift = CDROM_DEF_BLOCK_SHIFT;
			res = -ENODEV;
			goto out_free_buf;
		}
	}

	if (rc == 0) {
		uint32_t sector_size = get_unaligned_be32(&buffer[4]);
		if (sector_size == 0)
			dev->block_shift = CDROM_DEF_BLOCK_SHIFT;
		else
			dev->block_shift = scst_calc_block_shift(sector_size);
		TRACE_DBG("Sector size is %i scsi_level %d(SCSI_2 %d)",
			sector_size, dev->scsi_dev->scsi_level, SCSI_2);
		if (dev->block_shift < 9) {
			PRINT_ERROR("READ CAPACITY reported an invalid sector size: %d",
				    sector_size);
			res = -EINVAL;
			goto out_free_buf;
		}
	} else {
		dev->block_shift = CDROM_DEF_BLOCK_SHIFT;
		TRACE(TRACE_MINOR, "Read capacity failed: %x, using default "
			"sector size %d", rc, dev->block_shift);
		PRINT_BUFF_FLAG(TRACE_MINOR, "Returned sense", sense_buffer,
			sizeof(sense_buffer));
	}
	dev->block_size = 1 << dev->block_shift;

	res = scst_obtain_device_parameters(dev, NULL);
	if (res != 0) {
		PRINT_ERROR("Failed to obtain control parameters for device "
			"%s", dev->virt_name);
		goto out_free_buf;
	}

out_free_buf:
	kfree(buffer);

out:
	TRACE_EXIT();
	return res;
}
Пример #9
0
void changeServerConfiguration( int signal ) {

   /* ----------------------------------------- */

      long 	        longRet         =    0; 
      GenBuf_t* 	certFile 	= NULL;

   /* ----------------------------------------- */

	PRINT_INFO("AWIZOJMSSERVERINF CHANGE AWIZO CONFIGURATION.\n" );

	if (strlen((_GLOBAL_shptr->config).smtpAddr) > 0) {
		free0(_GLOBAL_awizoConfig.smtpAddr);
		asprintf( &(_GLOBAL_awizoConfig.smtpAddr), "%s", (_GLOBAL_shptr->config).smtpAddr);
	}

	if (strlen((_GLOBAL_shptr->config).smtpPort) > 0) {
		free0(_GLOBAL_awizoConfig.smtpPort);
		asprintf( &(_GLOBAL_awizoConfig.smtpPort), "%s", (_GLOBAL_shptr->config).smtpPort);
	}

	if (strlen((_GLOBAL_shptr->config).smtpUser) > 0) {
		free0(_GLOBAL_awizoConfig.user);
		asprintf( &(_GLOBAL_awizoConfig.user), "%s", (_GLOBAL_shptr->config).smtpUser);
	}

	if (strlen((_GLOBAL_shptr->config).smtpPswd) > 0) {
		free0(_GLOBAL_awizoConfig.password);
		asprintf( &(_GLOBAL_awizoConfig.password), "%s", (_GLOBAL_shptr->config).smtpPswd);
	}

	if ( strlen((_GLOBAL_shptr->config).awizoSuccess ) > 0) {
		free0(_GLOBAL_awizoConfig.awizoSuccess);
		asprintf( &(_GLOBAL_awizoConfig.awizoSuccess), "%s", (_GLOBAL_shptr->config).awizoSuccess);
	}

	if ( strlen((_GLOBAL_shptr->config).awizoFailed ) > 0) {
		free0(_GLOBAL_awizoConfig.awizoFailed);
		asprintf( &(_GLOBAL_awizoConfig.awizoFailed), "%s", (_GLOBAL_shptr->config).awizoFailed);
	}

	if ( strlen((_GLOBAL_shptr->config).awizoFailed ) > 0) {
		free0(_GLOBAL_awizoConfig.awizoFailed);
		asprintf( &(_GLOBAL_awizoConfig.awizoFailed), "%s", (_GLOBAL_shptr->config).awizoFailed);
	}

	if ( strlen((_GLOBAL_shptr->config).csvDir ) > 0) {
		free0(_GLOBAL_awizoConfig.csvDir);
		asprintf( &(_GLOBAL_awizoConfig.csvDir), "%s", (_GLOBAL_shptr->config).csvDir);
	}

	if ( strlen((_GLOBAL_shptr->config).csvSeparator ) > 0) {
		free0(_GLOBAL_awizoConfig.csvSeparator);
		asprintf( &(_GLOBAL_awizoConfig.csvSeparator), "%s", (_GLOBAL_shptr->config).csvSeparator);
	}

	if ((_GLOBAL_shptr->config).maxImageSize > -1) {
		_GLOBAL_awizoConfig.maxImageSize = (_GLOBAL_shptr->config).maxImageSize; 
	}

	if ((_GLOBAL_shptr->config).allowImageAbsent > -1) {
		_GLOBAL_awizoConfig.allowImageAbsent = (_GLOBAL_shptr->config).allowImageAbsent;
	}

	if ((_GLOBAL_shptr->config).awizoAction > -1) {
		_GLOBAL_awizoConfig.awizoAction = (_GLOBAL_shptr->config).awizoAction;
	}

	if ((_GLOBAL_shptr->config).mailqueue > -1) {
		_GLOBAL_awizoConfig.mailqueue = (_GLOBAL_shptr->config).mailqueue;
	}

	if ((_GLOBAL_shptr->config).maxcachesize > -1) {
		_GLOBAL_awizoConfig.maxcachesize = (_GLOBAL_shptr->config).maxcachesize;
	}

	if ((_GLOBAL_shptr->config).maxmailqueue > -1) {
		_GLOBAL_awizoConfig.maxmailqueue = (_GLOBAL_shptr->config).maxmailqueue;
	}

	if (strlen((_GLOBAL_shptr->config).pfxfile) > 0 && strlen((_GLOBAL_shptr->config).pfxPin) > 0) {
		bmd_ctx_destroy(&(_GLOBAL_awizoConfig.ctx));

		/* **************************************************************** */
		/*       Pobieranie ceryfikatu podpisującego z bazy danych          */
		/* **************************************************************** */

 		longRet = bmd_db_import_blob(_GLOBAL_awizoConfig.dbase_handler, \
						(_GLOBAL_shptr->config).pfxfile, &certFile);
 
		if (longRet != BMD_OK) {
			PRINT_ERROR("Błąd pobierania certyfikatu do podpisu z bazy danych. Error = %d\n", BMD_ERR_OP_FAILED);
 		}

		longRet = bmd_set_ctx_fileInMem( certFile, (_GLOBAL_shptr->config).pfxPin, \
						 strlen((_GLOBAL_shptr->config).pfxPin), \
						 &(_GLOBAL_awizoConfig.ctx) );

 		if (longRet != BMD_OK) {
			PRINT_ERROR("Błąd w trakcie ustawiania kontekstu do podpisywania wiadomości. Error = %d\n", BMD_ERR_OP_FAILED);
		}
	}

 	sem_post(&(_GLOBAL_shptr->clientMutex));

}
Пример #10
0
/* Initializes the console */
ConsoleInformation *CON_Init(SDL_Surface *Surface, SDL_Surface *DisplayScreen, int lines, SDL_Rect rect) {
    int loop;
    SDL_Surface *Temp;
    ConsoleInformation *newinfo;


    /* Create a new console struct and init it. */
    if((newinfo = (ConsoleInformation *) malloc(sizeof(ConsoleInformation))) == NULL) {
        PRINT_ERROR("Could not allocate the space for a new console info struct.\n");
        return NULL;
    }
    newinfo->Visible = CON_CLOSED;
    newinfo->WasUnicode = 0;
    newinfo->RaiseOffset = 0;
    newinfo->ConsoleLines = NULL;
    newinfo->CommandLines = NULL;
    newinfo->TotalConsoleLines = 0;
    newinfo->ConsoleScrollBack = 0;
    newinfo->TotalCommands = 0;
    newinfo->BackgroundImage = NULL;
    newinfo->ConsoleAlpha = SDL_ALPHA_OPAQUE;
    newinfo->Offset = 0;
    newinfo->InsMode = 1;
    newinfo->CursorPos = 0;
    newinfo->CommandScrollBack = 0;
    newinfo->OutputScreen = DisplayScreen;
    newinfo->Prompt = CON_DEFAULT_PROMPT;
    newinfo->HideKey = CON_DEFAULT_HIDEKEY;

    CON_SetExecuteFunction(newinfo, Default_CmdFunction);
    CON_SetTabCompletion(newinfo, Default_TabFunction);

    /* Load the consoles font */
    if (-1 == (newinfo->FontNumber = DT_LoadFontFromSurface(Surface, TRANS_FONT, DisplayScreen))) {
        PRINT_ERROR("Could not load the font ");
        PRINT_ERROR("for the console!");
        return NULL;
    }

    newinfo->FontHeight = DT_FontHeight(newinfo->FontNumber);
    newinfo->FontWidth = DT_FontWidth(newinfo->FontNumber);

    /* make sure that the size of the console is valid */
    if(rect.w > newinfo->OutputScreen->w || rect.w < newinfo->FontWidth * 32)
        rect.w = newinfo->OutputScreen->w;
    if(rect.h > newinfo->OutputScreen->h || rect.h < newinfo->FontHeight)
        rect.h = newinfo->OutputScreen->h;
    if(rect.x < 0 || rect.x > newinfo->OutputScreen->w - rect.w)
        newinfo->DispX = 0;
    else
        newinfo->DispX = rect.x;
    if(rect.y < 0 || rect.y > newinfo->OutputScreen->h - rect.h)
        newinfo->DispY = 0;
    else
        newinfo->DispY = rect.y;

    /* load the console surface */
    Temp = SDL_CreateRGBSurface(SDL_SWSURFACE, rect.w, rect.h, newinfo->OutputScreen->format->BitsPerPixel, 0, 0, 0, 0);
    if(Temp == NULL) {
        PRINT_ERROR("Couldn't create the ConsoleSurface\n");
        return NULL;
    }
    newinfo->ConsoleSurface = SDL_ConvertSurfaceFormat(Temp, DisplayScreen->format->format, DisplayScreen->flags);
    SDL_FreeSurface(Temp);
    SDL_FillRect(newinfo->ConsoleSurface, NULL, SDL_MapRGBA(newinfo->ConsoleSurface->format, 0, 0, 0, newinfo->ConsoleAlpha));

    /* Load the dirty rectangle for user input */
    Temp = SDL_CreateRGBSurface(SDL_SWSURFACE, rect.w, newinfo->FontHeight, newinfo->OutputScreen->format->BitsPerPixel, 0, 0, 0, SDL_ALPHA_OPAQUE);
    if(Temp == NULL) {
        PRINT_ERROR("Couldn't create the InputBackground\n");
        return NULL;
    }
    newinfo->InputBackground = SDL_ConvertSurfaceFormat(Temp, DisplayScreen->format->format, DisplayScreen->flags);
    SDL_FreeSurface(Temp);
    SDL_FillRect(newinfo->InputBackground, NULL, SDL_MapRGBA(newinfo->ConsoleSurface->format, 0, 0, 0, SDL_ALPHA_OPAQUE));

    /* calculate the number of visible characters in the command line */
    newinfo->VChars = (rect.w - CON_CHAR_BORDER) / newinfo->FontWidth;
    if(newinfo->VChars > CON_CHARS_PER_LINE)
        newinfo->VChars = CON_CHARS_PER_LINE;

    /* deprecated! Memory errors disabled by C.Wacha :-)
       We would like to have a minumum # of lines to guarentee we don't create a memory error */
    /*
    if(rect.h / newinfo->FontHeight > lines)
    	newinfo->LineBuffer = rect.h / newinfo->FontHeight;
    else
    	newinfo->LineBuffer = lines;
    */
    newinfo->LineBuffer = lines;

    newinfo->ConsoleLines = (char **)malloc(sizeof(char *) * newinfo->LineBuffer);
    newinfo->CommandLines = (char **)malloc(sizeof(char *) * newinfo->LineBuffer);
    for(loop = 0; loop <= newinfo->LineBuffer - 1; loop++) {
        newinfo->ConsoleLines[loop] = (char *)calloc(CON_CHARS_PER_LINE+1, sizeof(char));
        newinfo->CommandLines[loop] = (char *)calloc(CON_CHARS_PER_LINE+1, sizeof(char));
    }
    memset(newinfo->Command, 0, CON_CHARS_PER_LINE+1);
    memset(newinfo->LCommand, 0, CON_CHARS_PER_LINE+1);
    memset(newinfo->RCommand, 0, CON_CHARS_PER_LINE+1);
    memset(newinfo->VCommand, 0, CON_CHARS_PER_LINE+1);


    CON_Out(newinfo, "Console initialised.");
    CON_NewLineConsole(newinfo);

    return newinfo;
}
Пример #11
0
/* resizes the console, has to reset alot of stuff
 * returns 1 on error */
int CON_Resize(ConsoleInformation *console, SDL_Rect rect, SDL_Surface* displayScreen) {
    SDL_Surface *Temp;
    SDL_Rect backgroundsrc, backgrounddest;

    if(!console)
        return 1;

    /* make sure that the size of the console is valid */
    if(rect.w > console->OutputScreen->w || rect.w < console->FontWidth * 32)
        rect.w = console->OutputScreen->w;
    if(rect.h > console->OutputScreen->h || rect.h < console->FontHeight)
        rect.h = console->OutputScreen->h;
    if(rect.x < 0 || rect.x > console->OutputScreen->w - rect.w)
        console->DispX = 0;
    else
        console->DispX = rect.x;
    if(rect.y < 0 || rect.y > console->OutputScreen->h - rect.h)
        console->DispY = 0;
    else
        console->DispY = rect.y;

    /* load the console surface */
    SDL_FreeSurface(console->ConsoleSurface);
    Temp = SDL_CreateRGBSurface(SDL_SWSURFACE, rect.w, rect.h, console->OutputScreen->format->BitsPerPixel, 0, 0, 0, 0);
    if(Temp == NULL) {
        PRINT_ERROR("Couldn't create the console->ConsoleSurface\n");
        return 1;
    }
    //console->ConsoleSurface = SDL_DisplayFormat(Temp);
    console->ConsoleSurface = SDL_ConvertSurfaceFormat(Temp, displayScreen->format->format, displayScreen->flags);
    SDL_FreeSurface(Temp);

    /* Load the dirty rectangle for user input */
    SDL_FreeSurface(console->InputBackground);
    Temp = SDL_CreateRGBSurface(SDL_SWSURFACE, rect.w, console->FontHeight, console->OutputScreen->format->BitsPerPixel, 0, 0, 0, 0);
    if(Temp == NULL) {
        PRINT_ERROR("Couldn't create the input background\n");
        return 1;
    }
    //console->InputBackground = SDL_DisplayFormat(Temp);
    console->InputBackground = SDL_ConvertSurfaceFormat(Temp, displayScreen->format->format, displayScreen->flags);
    SDL_FreeSurface(Temp);

    /* Now reset some stuff dependent on the previous size */
    console->ConsoleScrollBack = 0;

    /* Reload the background image (for the input text area) in the console */
    if(console->BackgroundImage) {
        backgroundsrc.x = 0;
        backgroundsrc.y = console->ConsoleSurface->h - console->FontHeight - console->BackY;
        backgroundsrc.w = console->BackgroundImage->w;
        backgroundsrc.h = console->InputBackground->h;

        backgrounddest.x = console->BackX;
        backgrounddest.y = 0;
        backgrounddest.w = console->BackgroundImage->w;
        backgrounddest.h = console->FontHeight;

        SDL_FillRect(console->InputBackground, NULL, SDL_MapRGBA(console->ConsoleSurface->format, 0, 0, 0, SDL_ALPHA_OPAQUE));
        SDL_BlitSurface(console->BackgroundImage, &backgroundsrc, console->InputBackground, &backgrounddest);
    }

    /* restore the alpha level */
    CON_Alpha(console, console->ConsoleAlpha);

    /* re-calculate the number of visible characters in the command line */
    console->VChars = (rect.w - CON_CHAR_BORDER) / console->FontWidth;
    if(console->VChars > CON_CHARS_PER_LINE)
        console->VChars = CON_CHARS_PER_LINE;

    CON_UpdateConsole(console);
    return 0;
}
Пример #12
0
/* CON_AlphaGL() -- sets the alpha channel of an SDL_Surface to the
 * specified value.  Preconditions: the surface in question is RGBA.
 * 0 <= a <= 255, where 0 is transparent and 255 is opaque. */
void CON_AlphaGL(SDL_Surface *s, int alpha) {
    Uint8 val;
    int x, y, w, h;
    Uint32 pixel;
    Uint8 r, g, b, a;
    SDL_PixelFormat *format;
    static char errorPrinted = 0;


    /* debugging assertions -- these slow you down, but hey, crashing sucks */
    if(!s) {
        PRINT_ERROR("NULL Surface passed to CON_AlphaGL\n");
        return;
    }

    /* clamp alpha value to 0...255 */
    if(alpha < SDL_ALPHA_TRANSPARENT)
        val = SDL_ALPHA_TRANSPARENT;
    else if(alpha > SDL_ALPHA_OPAQUE)
        val = SDL_ALPHA_OPAQUE;
    else
        val = alpha;

    /* loop over alpha channels of each pixel, setting them appropriately. */
    w = s->w;
    h = s->h;
    format = s->format;
    switch (format->BytesPerPixel) {
    case 2:
        /* 16-bit surfaces don't seem to support alpha channels. */
        if(!errorPrinted) {
            errorPrinted = 1;
            PRINT_ERROR("16-bit SDL surfaces do not support alpha-blending under OpenGL.\n");
        }
        break;
    case 4: {
        /* we can do this very quickly in 32-bit mode.  24-bit is more
         * difficult.  And since 24-bit mode is reall the same as 32-bit,
         * so it usually ends up taking this route too.  Win!  Unroll loop
         * and use pointer arithmetic for extra speed. */
        int numpixels = h * (w << 2);
        Uint8 *pix = (Uint8 *) (s->pixels);
        Uint8 *last = pix + numpixels;
        Uint8 *pixel;
        if((numpixels & 0x7) == 0)
            for(pixel = pix + 3; pixel < last; pixel += 32)
                *pixel = *(pixel + 4) = *(pixel + 8) = *(pixel + 12) = *(pixel + 16) = *(pixel + 20) = *(pixel + 24) = *(pixel + 28) = val;
        else
            for(pixel = pix + 3; pixel < last; pixel += 4)
                *pixel = val;
        break;
    }
    default:
        /* we have no choice but to do this slowly.  <sigh> */
        for(y = 0; y < h; ++y)
            for(x = 0; x < w; ++x) {
                char print = 0;
                /* Lock the surface for direct access to the pixels */
                if(SDL_MUSTLOCK(s) && SDL_LockSurface(s) < 0) {
                    PRINT_ERROR("Can't lock surface: ");
                    PRINT_ERROR(SDL_GetError());
                    return;
                }
                pixel = DT_GetPixel(s, x, y);
                if(x == 0 && y == 0)
                    print = 1;
                SDL_GetRGBA(pixel, format, &r, &g, &b, &a);
                pixel = SDL_MapRGBA(format, r, g, b, val);
                SDL_GetRGBA(pixel, format, &r, &g, &b, &a);
                DT_PutPixel(s, x, y, pixel);

                /* unlock surface again */
                if(SDL_MUSTLOCK(s))
                    SDL_UnlockSurface(s);
            }
        break;
    }
}
Пример #13
0
void runserver(int num_threads, unsigned short serverport) {
    struct node **sock_list[2]; //to contain pointers to head and tail for passing to threads
	struct node *head = NULL;
	struct node *tail = NULL;
	sock_list[0] = &head;
	sock_list[1] = &tail; //to pass to new threads

	pthread_t threads[num_threads];
    int i = 0;

    // start up the threads; they'll start trying to consume immeidately
    for (i = 0; i < num_threads; i++) {
        if (0 > pthread_create(&threads[i], NULL, worker, (void*)&sock_list)) {
            fprintf(stderr, "Error creating thread: %s\n", strerror(errno));
        }
    }
    
    int main_socket = prepare_server_socket(serverport);
    if (main_socket < 0){
        exit(-1);
    }
    signal(SIGINT, signal_handler);

    struct sockaddr_in client_address;
    socklen_t addr_len;

    fprintf(stderr, "Server listening on port %d.  Going into request loop.\n", serverport);


	//thread pool set up and a-okay by now
    while (still_running) {
        struct pollfd pfd = {main_socket, POLLIN};
        int prv = poll(&pfd, 1, 10000);

        if (prv == 0) {
            continue;
        } else if (prv < 0) {
            PRINT_ERROR("poll");
            still_running = FALSE;
            continue;
        }
        
        addr_len = sizeof(client_address);
        memset(&client_address, 0, addr_len);

        int new_sock = accept(main_socket, (struct sockaddr *)&client_address, &addr_len);
        if (new_sock > 0) {            
            fprintf(stderr, "Got connection from %s:%d\n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port));

			produce_cnct(new_sock, client_address, &head, &tail); //inserting socket at end of linked list. Only executed on main thread
        }
    }
    fprintf(stderr, "Server shutting down.\n");

	// threads are done doing work    
    // wait for workers to complete
	pthread_cond_broadcast(&consumer); //wakes up all the consumers, which will then escape and stop running
	for (i = 0; i < num_threads; i++) {
        pthread_join(threads[i], NULL);
    }
	printf("threads woken up");

    close(main_socket);
}
Пример #14
0
BOOL kull_m_remotelib_create(PKULL_M_MEMORY_ADDRESS aRemoteFunc, PREMOTE_LIB_INPUT_DATA input, PREMOTE_LIB_OUTPUT_DATA output)
{
	BOOL success = FALSE;
	NTSTATUS status;
	HANDLE hThread;
	KULL_M_MEMORY_HANDLE  hLocalBuffer = {KULL_M_MEMORY_TYPE_OWN, NULL};
	KULL_M_MEMORY_ADDRESS aRemoteData = {NULL, aRemoteFunc->hMemory}, aSuppData = {NULL, aRemoteFunc->hMemory}, aLocalAddr = {NULL, &hLocalBuffer};
	PREMOTE_LIB_DATA data;
	REMOTE_LIB_OUTPUT_DATA oData;
	MIMIDRV_THREAD_INFO drvInfo = {(PTHREAD_START_ROUTINE) aRemoteFunc->address, NULL};
	DWORD size = FIELD_OFFSET(REMOTE_LIB_DATA, input.inputData) + input->inputSize;

	if(!output)
		output = &oData;
	//kprintf(L"\ninput\n"
	//	L".void   = 0x%p\n"
	//	L".dword  = 0x%08x - %u\n"
	//	L".size   = %u\n"
	//	L".data[] = [ ",
	//	input->inputVoid, input->inputDword, input->inputDword, input->inputSize);
	//kull_m_string_wprintf_hex(input->inputData, input->inputSize, 1);
	//kprintf(L"]\n");
	if(data = (PREMOTE_LIB_DATA) LocalAlloc(LPTR, size))
	{
		RtlCopyMemory(&data->input, input, FIELD_OFFSET(REMOTE_LIB_INPUT_DATA, inputData) + input->inputSize);
		if(kull_m_memory_alloc(&aRemoteData, size, PAGE_READWRITE))
		{
			aLocalAddr.address = data;
			if(kull_m_memory_copy(&aRemoteData, &aLocalAddr, size))
			{
				switch(aRemoteFunc->hMemory->type)
				{
				case KULL_M_MEMORY_TYPE_PROCESS:
					if(MIMIKATZ_NT_MAJOR_VERSION > 5)
					{
						status = RtlCreateUserThread(aRemoteFunc->hMemory->pHandleProcess->hProcess, NULL, 0, 0, 0, 0, (PTHREAD_START_ROUTINE) aRemoteFunc->address, aRemoteData.address, &hThread, NULL);
						if(!NT_SUCCESS(status))
						{
							hThread = NULL;
							PRINT_ERROR(L"RtlCreateUserThread (0x%08x)\n", status);
						}
					}
					else if(!(hThread = CreateRemoteThread(aRemoteFunc->hMemory->pHandleProcess->hProcess, NULL, 0, (PTHREAD_START_ROUTINE) aRemoteFunc->address, aRemoteData.address, 0, NULL)))
						PRINT_ERROR_AUTO(L"CreateRemoteThread");

					if(hThread)
					{
						WaitForSingleObject(hThread, INFINITE);
						success = CloseHandle(hThread);
					}
					break;

				case KULL_M_MEMORY_TYPE_KERNEL:
					drvInfo.pArg = aRemoteData.address;
					kprintf(L"Th @ %p\nDa @ %p\n", drvInfo.pRoutine, drvInfo.pArg);
					if(!(success = kull_m_kernel_ioctl_handle(aRemoteFunc->hMemory->pHandleDriver->hDriver, IOCTL_MIMIDRV_CREATEREMOTETHREAD, &drvInfo, sizeof(MIMIDRV_THREAD_INFO), NULL, NULL, FALSE)))
						PRINT_ERROR_AUTO(L"kull_m_kernel_ioctl_handle");
					break;
				}
				
				if(success)
				{
					aLocalAddr.address = output;
					if(success = kull_m_memory_copy(&aLocalAddr, &aRemoteData, sizeof(REMOTE_LIB_OUTPUT_DATA)))
					{
						//kprintf(L"\noutput\n"
						//	L".void   = 0x%p\n"
						//	L".dword  = 0x%08x - %u\n"
						//	L".status = 0x%08x - %u\n"
						//	L".size   = %u\n"
						//	L".data   = 0x%p\n",
						//	output->outputVoid, output->outputDword, output->outputDword, output->outputStatus, output->outputStatus, output->outputSize, output->outputData);
						if(aSuppData.address = output->outputData)
						{
							if(output != &oData)
							{
								success = FALSE;
								output->outputData = NULL;
								if(output->outputSize)
								{
									if(aLocalAddr.address = LocalAlloc(LPTR, output->outputSize))
									{
										if(success = kull_m_memory_copy(&aLocalAddr, &aSuppData, output->outputSize))
										{
											output->outputData = aLocalAddr.address;
											//kprintf(L"\t[ "); kull_m_string_wprintf_hex(output->outputData, output->outputSize, 1); kprintf(L"]\n");
										}
										else
											LocalFree(aLocalAddr.address);
									}
								}
								if(!success)
									output->outputSize = 0;
							}
							kull_m_memory_free(&aSuppData, 0);
						}
					}
				}
			}
			kull_m_memory_free(&aRemoteData, 0);
		}
		
		LocalFree(data);
	}
	return success;
}
Пример #15
0
static ret_t
common_server_initialization (cherokee_server_t *srv)
{
	ret_t            ret;
	struct sigaction act;

	/* Signals it handles
	 */
	memset(&act, 0, sizeof(act));

	/* SIGPIPE */
	act.sa_handler = SIG_IGN;
	sigaction (SIGPIPE, &act, NULL);

	/* Signal Handler */
	act.sa_sigaction = signals_handler;
	act.sa_flags     = SA_SIGINFO;

	sigaction (SIGHUP,  &act, NULL);
	sigaction (SIGUSR2, &act, NULL);
	sigaction (SIGSEGV, &act, NULL);
	sigaction (SIGTERM, &act, NULL);
	sigaction (SIGINT,  &act, NULL);
	sigaction (SIGCHLD, &act, NULL);
#ifdef SIGBUS
	sigaction (SIGBUS,  &act, NULL);
#endif

	if (document_root != NULL) {
		cherokee_buffer_t tmp   = CHEROKEE_BUF_INIT;
		cherokee_buffer_t droot = CHEROKEE_BUF_INIT;

		/* Sanity check
		 */
		if (port > 0xFFFF) {
			PRINT_ERROR ("Port %d is out of limits\n", port);
			return ret_error;
		}

		/* Build the configuration string
		 */
		cherokee_buffer_add (&droot, document_root, strlen(document_root));
		cherokee_path_arg_eval (&droot);

		cherokee_buffer_add_va (&tmp,
					"server!bind!1!port = %d\n"
					"vserver!1!document_root = %s\n"
					BASIC_CONFIG, port, droot.buf);

		/* Apply it
		 */
		ret = cherokee_server_read_config_string (srv, &tmp);

		cherokee_buffer_mrproper (&tmp);
		cherokee_buffer_mrproper (&droot);

		if (ret != ret_ok) {
			PRINT_MSG ("Couldn't start serving directory %s\n", document_root);
			return ret_error;
		}

	} else {
		const char *config;

		/* Check parameter inconsistencies */
		if (port_set) {
			PRINT_MSG ("The -p parameter can only be used in conjunction with -r.");
			return ret_error;
		}

		/* Read the configuration file
		 */
		config = (config_file) ? config_file : DEFAULT_CONFIG_FILE;
		ret = cherokee_server_read_config_file (srv, config);

		if (ret != ret_ok) {
			PRINT_MSG ("Couldn't read the config file: %s\n", config);
			return ret_error;
		}
	}

	if (daemon_mode)
		cherokee_server_daemonize (srv);

	ret = cherokee_server_initialize (srv);
	if (ret != ret_ok) return ret_error;

	cherokee_server_unlock_threads (srv);
	return ret_ok;
}
Пример #16
0
void udp_in(struct finsFrame* ff) {
	PRINT_DEBUG("UDP_in has been just called");
	/* read the FDF and make sure everything is correct*/
	if (ff->dataOrCtrl != 0) {
		// release FDF here
		PRINT_ERROR("it is not data");
		return;
	}
	if (ff->dataFrame.directionFlag != 0) {
		// release FDF here
		PRINT_ERROR("wrong direction");
		return;
	}
	if (ff->destinationID != UDPID) {
		// release FDF here
		PRINT_ERROR("wrong destination ID");
		return;
	}

	/* point to the necessary data in the FDF */
	struct udp_packet* packet = (struct udp_packet*)ff->dataFrame.pdu;
	struct udp_metadata_parsed* meta = (struct udp_metadata_parsed*)ff->dataFrame.metaData;


	/* begins checking the UDP packets integrity */
	if (meta->u_pslen != htons(packet->u_len)) {
		PRINT_DEBUG("UDP length:%u", packet->u_len);
		udpStat.mismatchingLengths++;
		udpStat.totalBadDatagrams ++;
		PRINT_ERROR("wrong length");
		return;
	}

	if (meta->u_prcl != UDP_PROTOCOL) {
		udpStat.wrongProtocol++;
		udpStat.totalBadDatagrams++;
		PRINT_ERROR("it is not UDP segment, I wont parse it");
		return;
	}

	/* the packet is does not have an "Ignore checksum" value and fails the checksum, it is thrown away */
	if (packet->u_cksum != IGNORE_CHEKSUM ){
			if(UDP_checksum(packet, meta) != 0) {
				udpStat.badChecksum++;
				udpStat.totalBadDatagrams ++;
				PRINT_ERROR("checksum ERROR");
				return;
			}

	}else{
		udpStat.noChecksum++;
	}
	/* put the header into the meta data*/
	meta->u_destPort = packet->u_dst;
	meta->u_srcPort = packet->u_src;

	/* construct a FDF to send to the sockets */

	ff->dataFrame.pdu += U_HEADER_LEN;
	struct finsFrame newFF;
	newFF = create_ff(DATA, UP, SOCKETSTUBID, ((int)(ff->dataFrame.pdu) - U_HEADER_LEN), (ff->dataFrame.pdu), (unsigned char*)meta);

	sendToSwitch(&newFF);
}
Пример #17
0
NTSTATUS kuhl_m_minesweeper_infos(int argc, wchar_t * argv[])
{
	DWORD dwPid, r, c;
	HANDLE hProcess;
	PEB Peb;
	PIMAGE_NT_HEADERS pNtHeaders;
	PVOID G = NULL;
	STRUCT_MINESWEEPER_GAME Game;
	STRUCT_MINESWEEPER_BOARD Board;
	KULL_M_MEMORY_SEARCH sMemory = {{{NULL, NULL}, 0}, NULL};
	KULL_M_MEMORY_ADDRESS aRemote = {NULL, NULL}, aBuffer = {PTRN_WIN6_Game_SafeGetSingleton, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE};
	BOOL bAlloc = FALSE;
	LONG offsetTemp = 0;
	CHAR ** field = NULL;

	if(kull_m_process_getProcessIdForName(L"minesweeper.exe", &dwPid))
	{
		if(hProcess = OpenProcess(PROCESS_VM_READ | PROCESS_VM_OPERATION | PROCESS_QUERY_INFORMATION, FALSE, dwPid))
		{
			if(kull_m_memory_open(KULL_M_MEMORY_TYPE_PROCESS, hProcess, &aRemote.hMemory))
			{
				if(kull_m_process_peb(aRemote.hMemory, &Peb, FALSE))
				{
					aRemote.address = Peb.ImageBaseAddress;
					if(kull_m_process_ntheaders(&aRemote, &pNtHeaders))
					{
						sMemory.kull_m_memoryRange.kull_m_memoryAdress.hMemory = aRemote.hMemory;
						sMemory.kull_m_memoryRange.kull_m_memoryAdress.address = (LPVOID) pNtHeaders->OptionalHeader.ImageBase;
						sMemory.kull_m_memoryRange.size = pNtHeaders->OptionalHeader.SizeOfImage;
						if(kull_m_memory_search(&aBuffer, sizeof(PTRN_WIN6_Game_SafeGetSingleton), &sMemory, TRUE))
						{
							aRemote.address = (PBYTE) sMemory.result + OFFS_WIN6_ToG;
#ifdef _M_X64
							aBuffer.address = &offsetTemp;
							if(kull_m_memory_copy(&aBuffer, &aRemote, sizeof(LONG)))
							{
								aRemote.address = (PBYTE) aRemote.address + 1 + sizeof(LONG) + offsetTemp;
#elif defined _M_IX86
							aBuffer.address = &aRemote.address;
							if(kull_m_memory_copy(&aBuffer, &aRemote, sizeof(PVOID)))
							{
#endif
								aBuffer.address = &G;
								if(kull_m_memory_copy(&aBuffer, &aRemote, sizeof(PVOID)))
								{
									aRemote.address = G;
									aBuffer.address = &Game;
									if(kull_m_memory_copy(&aBuffer, &aRemote, sizeof(STRUCT_MINESWEEPER_GAME)))
									{
#ifdef _M_IX86
										if(MIMIKATZ_NT_BUILD_NUMBER >= KULL_M_WIN_MIN_BUILD_7)
											Game.pBoard = Game.pBoard_WIN7x86;
#endif
										aRemote.address = Game.pBoard;
										aBuffer.address = &Board;

										if(kull_m_memory_copy(&aBuffer, &aRemote, sizeof(STRUCT_MINESWEEPER_BOARD)))
										{
											kprintf(L"Field : %u r x %u c\nMines : %u\n\n", Board.cbRows, Board.cbColumns, Board.cbMines);
											if(field = (CHAR **) LocalAlloc(LPTR, sizeof(CHAR *) * Board.cbRows))
											{
												for(r = 0, bAlloc = TRUE; (r < Board.cbRows) && bAlloc; r++)
												{
													if(field[r] = (CHAR *) LocalAlloc(LPTR, sizeof(CHAR) * Board.cbColumns))
														bAlloc &= TRUE;
													else PRINT_ERROR(L"Memory C (R = %u)\n", r);
												}
											}
											else PRINT_ERROR(L"Memory R\n");

											if(bAlloc)
											{
												kuhl_m_minesweeper_infos_parseField(aRemote.hMemory, Board.ref_visibles, field, TRUE);
												kuhl_m_minesweeper_infos_parseField(aRemote.hMemory, Board.ref_mines, field, FALSE);
												for(r = 0; r < Board.cbRows; r++)
												{
													kprintf(L"\t");
													for(c = 0; c < Board.cbColumns; c++)
														kprintf(L"%C ", field[r][c]);
													kprintf(L"\n");
												}
											}

											if(field)
											{
												for(r = 0; r < Board.cbRows; r++)
												{
													if(field[r])
														LocalFree(field[r]);
												}
												LocalFree(field);
											}
										}
										else PRINT_ERROR(L"Board copy\n");
									}
									else PRINT_ERROR(L"Game copy\n");
								}
								else PRINT_ERROR(L"G copy\n");
							}
							else PRINT_ERROR(L"Global copy\n");
						}
						else PRINT_ERROR(L"Search is KO\n");
						LocalFree(pNtHeaders);
					}
					else PRINT_ERROR(L"Minesweeper NT Headers\n");
				}
				else PRINT_ERROR(L"Minesweeper PEB\n");
				kull_m_memory_close(aRemote.hMemory);
			}
			CloseHandle(hProcess);
		}
		else PRINT_ERROR_AUTO(L"OpenProcess");
	}
	else PRINT_ERROR(L"No MineSweeper in memory!\n");

	return STATUS_SUCCESS;
}

void kuhl_m_minesweeper_infos_parseField(PKULL_M_MEMORY_HANDLE hMemory, PSTRUCT_MINESWEEPER_REF_ELEMENT base, CHAR ** field, BOOL isVisible)
{
	STRUCT_MINESWEEPER_REF_ELEMENT ref_first_element;
	PSTRUCT_MINESWEEPER_REF_ELEMENT * ref_columns_elements;
	STRUCT_MINESWEEPER_REF_ELEMENT ref_column_element;	
	DWORD c, r, szFinalElement = isVisible ? sizeof(DWORD) : sizeof(BYTE);
	KULL_M_MEMORY_ADDRESS aRemote = {base, hMemory}, aLocal = {&ref_first_element, &KULL_M_MEMORY_GLOBAL_OWN_HANDLE};

	if(kull_m_memory_copy(&aLocal, &aRemote, sizeof(STRUCT_MINESWEEPER_REF_ELEMENT)))
	{
		if(ref_columns_elements = (PSTRUCT_MINESWEEPER_REF_ELEMENT *) LocalAlloc(LPTR, sizeof(PSTRUCT_MINESWEEPER_REF_ELEMENT) * ref_first_element.cbElements))
		{
			aLocal.address = ref_columns_elements;
			aRemote.address = ref_first_element.elements;
			
			if(kull_m_memory_copy(&aLocal, &aRemote, ref_first_element.cbElements * sizeof(PSTRUCT_MINESWEEPER_REF_ELEMENT)))
			{
				for(c = 0; c < ref_first_element.cbElements; c++)
				{
					aLocal.address = &ref_column_element;
					aRemote.address = ref_columns_elements[c];
					if(kull_m_memory_copy(&aLocal, &aRemote, sizeof(STRUCT_MINESWEEPER_REF_ELEMENT)))
					{
						if(aLocal.address = LocalAlloc(LPTR, szFinalElement * ref_column_element.cbElements))
						{
							aRemote.address = ref_column_element.elements;
							if(kull_m_memory_copy(&aLocal, &aRemote, szFinalElement * ref_column_element.cbElements))
							{
								for(r = 0; r < ref_column_element.cbElements; r++)
								{
									if(isVisible)
										field[r][c] = DISP_MINESWEEPER[((DWORD *)(aLocal.address))[r]];
									else if(((BYTE *)(aLocal.address))[r])
										field[r][c] = '*';
								}
							}
							else PRINT_ERROR(L"Unable to read elements from column: %u\n", c);
							LocalFree(aLocal.address);
						}
					}
					else PRINT_ERROR(L"Unable to read references from column: %u\n", c);
				}
			}
			else PRINT_ERROR(L"Unable to read references\n");
			LocalFree(ref_columns_elements);
		}
	}
	else PRINT_ERROR(L"Unable to read first element\n");		
}
Пример #18
0
void *statistics_loop(void *ptr) {
	int items, found;
	struct timeval current_time;
	int elapsed;
	char buffer[STAT_BUF_LEN];
	/*int state;
	  struct can_berr_counter errorcnt;*/
	FILE *proc_net_dev;
	struct proc_stat_entry proc_entry;
	char line[PROC_LINESIZE];

	gettimeofday(&last_fired, 0);

	while(1) {
		/* check if statistics are enabled */
		if( statistics_ival == 0 ) {
			sleep(1);
			continue;
		}

		/* read /proc/net/dev */
		proc_net_dev = fopen( "/proc/net/dev", "r" );
		if( proc_net_dev == NULL ) {
			PRINT_ERROR("could not open /proc/net/dev");
			sleep(1);
			continue;
		}

		found=0;
		while(1) {
			if(fgets( line , PROC_LINESIZE, proc_net_dev ) == NULL)
				break;

			/* extract name */
			char* s = (char *) &line;
			char* name = strsep(&s, ":");
			if(s == NULL) { /* no : in line */
				continue;
			}

			/* remove heading whitespace */
			int pos = 0;
			for(;pos<strlen(name);pos++)
				if(name[pos] != ' ')
					break;
			name += pos;

			/* do we care for this device? */
			if(strcmp(bus_name, name))
				continue;

			items = sscanf( s, " %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
					&proc_entry.rbytes,
					&proc_entry.rpackets,
					&proc_entry.rerrs,
					&proc_entry.rdrop,
					&proc_entry.rfifo,
					&proc_entry.rframe,
					&proc_entry.rcompressed,
					&proc_entry.rmulticast,
					&proc_entry.tbytes,
					&proc_entry.tpackets,
					&proc_entry.terrs,
					&proc_entry.tdrop,
					&proc_entry.tfifo,
					&proc_entry.tcolls,
					&proc_entry.tcarrier,
					&proc_entry.tcompressed );

			if( items == 16 ) {
				found=1;
				break;
			}
		}
		fclose(proc_net_dev);

		/* If we didn't find the device there is something wrong. */
		if(!found) {
			PRINT_ERROR("could not find device %s in /proc/net/dev\n", bus_name);
			sleep(1);
			continue;
		}

		gettimeofday(&current_time, 0);

		elapsed = ((current_time.tv_sec - last_fired.tv_sec) * 1000
			   + (current_time.tv_usec - last_fired.tv_usec)/1000.0) + 0.5;

		if(elapsed >= statistics_ival) {

			/*
			 * TODO this does not work for virtual devices. therefore it is commented out until
			 * a solution is found to identify virtual CAN devices
			 */
			/*if( can_get_state( current_entry.bus_name, &state ) ) {
			  printf( "unable to get state of %s\n", current_entry.bus_name );
			  continue;
			  }
			  if( can_get_berr_counter( current_entry.bus_name, &errorcnt ) ) {
			  printf( "unable to get error count of %s\n", current_entry.bus_name );
			  continue;
			  }*/

			snprintf( buffer, STAT_BUF_LEN, "< stat %u %u %u %u >",
				  proc_entry.rbytes,
				  proc_entry.rpackets,
				  proc_entry.tbytes,
				  proc_entry.tpackets);

			/* no lock needed here because POSIX send is thread-safe and does locking itself */
			send( client_socket, buffer, strlen(buffer), 0 );

			last_fired.tv_sec = current_time.tv_sec;
			last_fired.tv_usec = current_time.tv_usec;
		}

		usleep(10000);
	}

	return NULL;
}
Пример #19
0
static void
do_spawn (void)
{
	int          n;
	int          size;
	uid_t        uid;
	gid_t        gid;
	int          env_inherit;
	pid_t        child;
	int          envs         = 0;
	int          log_stderr   = 0;
	char        *interpreter  = NULL;
	char        *log_file     = NULL;
	char        *uid_str      = NULL;
	char       **envp         = NULL;
	char        *p            = spawn_shared;
	const char  *argv[]       = {"sh", "-c", NULL, NULL};

#define CHECK_MARK(val)							\
	if ((*(int *)p) != val) {					\
		goto cleanup;						\
	} else {							\
		p += sizeof(int);					\
	}

#define ALIGN4(buf) while ((long)p & 0x3) p++;

	/* Read the shared memory
	 */

	/* 1.- Interpreter */
	CHECK_MARK (0xF0);

	size = *((int *)p);
	p += sizeof(int);
	if (size <= 0) {
		goto cleanup;
	}

	interpreter = malloc (sizeof("exec ") + size);
	if (interpreter == NULL) {
		goto cleanup;
	}
	strncpy (interpreter, "exec ", 5);
	strncpy (interpreter + 5, p, size + 1);
	p += size + 1;
	ALIGN4 (p);

	/* 2.- UID & GID */
	CHECK_MARK (0xF1);

	size = *((int *)p);
	if (size > 0) {
		uid_str = strdup (p + sizeof(int));
	}
	p += sizeof(int) + size + 1;
	ALIGN4 (p);

	memcpy (&uid, p, sizeof(uid_t));
	p += sizeof(uid_t);

	memcpy (&gid, p, sizeof(gid_t));
	p += sizeof(gid_t);

	/* 3.- Environment */
	CHECK_MARK (0xF2);

	env_inherit = *((int *)p);
	p += sizeof(int);

	envs = *((int *)p);
	p += sizeof(int);

	envp = malloc (sizeof(char *) * (envs + 1));
	if (envp == NULL) {
		goto cleanup;
	}
	envp[envs] = NULL;

	for (n=0; n<envs; n++) {
		char *e;

		size = *((int *)p);
		p += sizeof(int);

		e = malloc (size + 1);
		if (e == NULL) {
			goto cleanup;
		}

		memcpy (e, p, size);
		e[size] = '\0';

		envp[n] = e;
		p += size + 1;
		ALIGN4 (p);
	}

	/* 4.- Error log */
	CHECK_MARK (0xF3);

	size = *((int *)p);
	p += sizeof(int);

	if (size > 0) {
		if (! strncmp (p, "stderr", 6)) {
			log_stderr = 1;
		} else if (! strncmp (p, "file,", 5)) {
			log_file = p+5;
		}

		p += (size + 1);
		ALIGN4 (p);
	}

	/* 5.- PID: it's -1 now */
	CHECK_MARK (0xF4);

	n = *((int *)p);
	if (n > 0) {
		kill (n, SIGTERM);
		*p = -1;
	}

	/* Spawn
	 */
	child = fork();
	switch (child) {
	case 0: {
		int              i;
		struct sigaction sig_action;

		/* Reset signal handlers */
		sig_action.sa_handler = SIG_DFL;
		sig_action.sa_flags   = 0;
		sigemptyset (&sig_action.sa_mask);

		for (i=0 ; i < NSIG ; i++) {
			sigaction (i, &sig_action, NULL);
		}

		/* Logging */
		if (log_file) {
			int fd;
			fd = open (log_file, O_WRONLY | O_APPEND | O_CREAT, 0600);
			if (fd < 0) {
				PRINT_ERROR ("(warning) Couldn't open '%s' for writing..\n", log_file);
			}
			close (STDOUT_FILENO);
			close (STDERR_FILENO);
			dup2 (fd, STDOUT_FILENO);
			dup2 (fd, STDERR_FILENO);
		} else if (log_stderr) {
			/* do nothing */
		} else {
			int tmp_fd;
			tmp_fd = open ("/dev/null", O_WRONLY);

			close (STDOUT_FILENO);
			close (STDERR_FILENO);
			dup2 (tmp_fd, STDOUT_FILENO);
			dup2 (tmp_fd, STDERR_FILENO);
		}

		/* Change user & group */
		if (uid_str != NULL) {
			n = initgroups (uid_str, gid);
			if (n == -1) {
				PRINT_ERROR ("(warning) initgroups failed User=%s, GID=%d\n", uid_str, gid);
			}
		}

		if ((int)gid != -1) {
			n = setgid (gid);
			if (n != 0) {
				PRINT_ERROR ("(warning) Couldn't set GID=%d\n", gid);
			}
		}

		if ((int)uid != -1) {
			n = setuid (uid);
			if (n != 0) {
				PRINT_ERROR ("(warning) Couldn't set UID=%d\n", uid);
			}
		}

		/* Clean the shared memory */
		size = (p - spawn_shared) - sizeof(int);
		memset (spawn_shared, 0, size);

		/* Execute the interpreter */
		argv[2] = interpreter;

		if (env_inherit) {
			do {
				execv ("/bin/sh", (char **)argv);
			} while (errno == EINTR);
		} else {
			do {
				execve ("/bin/sh", (char **)argv, envp);
			} while (errno == EINTR);
		}

		PRINT_MSG ("(critical) Couldn't spawn: sh -c %s\n", interpreter);
		exit (1);
	}

	case -1:
		/* Error */
		PRINT_MSG ("(critical) Couldn't fork(): %s\n", strerror(errno));
		goto cleanup;

	default:
		break;
	}

	/* Return the PID
	 */
	memcpy (p, (char *)&child, sizeof(int));
	printf ("PID %d: launched '/bin/sh -c %s' with uid=%d, gid=%d, env=%s\n", child, interpreter, uid, gid, env_inherit ? "inherited":"custom");

cleanup:
	/* Unlock worker
	 */
	do_sem_op (SEM_LAUNCH_READY, 1);

	/* Clean up
	 */
	free (uid_str);
	free (interpreter);

	if (envp != NULL) {
		for (n=0; n<envs; n++) {
			free (envp[n]);
		}
		free (envp);
	}
}
int main(int argc, char *argv[])
{
    ADI_BLER_RESULT      eResult;
    ADI_PWR_RESULT       ePwr;
    uint32_t             nTime;
    uint8_t *            aTemplateSensorName = (unsigned char *)"ADI_BLE_TEMPLATESENSOR";

    /* Explicitly disable the watchdog timer */ 
    *pREG_WDT0_CTL = 0x0u;

    /* Pinmux */
    adi_initpinmux();

    /* Initialize clocks */
    ePwr = adi_pwr_Init(); 
    PRINT_ERROR("Error initializing the power service.\r\n", ePwr, ADI_PWR_SUCCESS);

    ePwr = adi_pwr_SetClockDivider(ADI_CLOCK_HCLK, 1u);     
    PRINT_ERROR("Error configuring the core clock.\r\n", ePwr, ADI_PWR_SUCCESS);
    ePwr = adi_pwr_SetClockDivider(ADI_CLOCK_PCLK, 1u);

    PRINT_ERROR("Error configuring the peripheral clock.\r\n", ePwr, ADI_PWR_SUCCESS);
    
    /*Initialize Timer */
    INIT_TIME();

#ifndef ADI_DEBUG
    /* Initialize UART redirection in release mode only */
    common_Init();
#endif

    PRINTF(("Starting Template Sensor Example.\r\n"));

    /* Initialize radio */
    eResult = adi_ble_Init(ApplicationCallback, NULL);
    PRINT_ERROR("Error initializing the radio.\r\n", eResult, ADI_BLER_SUCCESS);

    eResult = adi_radio_RegisterDevice(ADI_BLE_ROLE_PERIPHERAL);
    PRINT_ERROR("Error registering the radio.\r\n", eResult, ADI_BLER_SUCCESS);

    eResult = adi_radio_SetLocalBluetoothDevName(aTemplateSensorName, strlen((const char *) aTemplateSensorName), 0u, 0u);
    PRINT_ERROR("Error setting local device name.\r\n", eResult, ADI_BLER_SUCCESS);

    SetAdvertisingMode();

    /* Initialize data exchange profile */
    eResult = adi_radio_Register_DataExchangeServer();
    PRINT_ERROR("Error registering data exchange server.\r\n", eResult, ADI_BLER_SUCCESS);

    /* Initialize static components of the data packet. For a single "sensor" example these will not change. */
    eDataPacket.nPacketHeader = ADI_SET_HEADER(ADI_DATA_PACKET_TYPE, SENSOR_ID);

    /* The sensor type that is set here is the type of sensor this demo will simulate on the Android application */
    eDataPacket.eSensorType = ADI_APP_SIMULATE_SENSOR_TYPE;

    /* Now enter infinite loop waiting for connection and then data exchange events */
    PRINTF(("Waiting for connection. Initiate connection on central device please.\r\n"));

    /* WHILE(forever) */
    while(1u)
    {
        /* Dispatch events - they will arrive in the application callback */
        eResult = adi_ble_DispatchEvents(ADI_APP_DISPATCH_TIMEOUT);
        PRINT_ERROR("Error dispatching events to the callback.\r\n", eResult, ADI_BLER_SUCCESS);
        
        /* If connected, send data */
        if (gbConnected == true)
        {
            adi_ble_GetConnectionInfo(&sConnInfo);

            /* Fill the sensor data packet according to the sensor packet documentation */
            
            nTime = GET_TIME();
            memcpy(&eDataPacket.aTimestamp ,&nTime,4u);

            TemplateSensorRead((uint8_t*)&eDataPacket.aPayload);

            eResult = adi_radio_DE_SendData(sConnInfo.nConnHandle, DATAEXCHANGE_PACKET_SIZE, (uint8_t*)&eDataPacket);
            PRINT_ERROR("Error sending the data.\r\n", eResult, ADI_BLER_SUCCESS);
        }
        /* If disconnected, make sure we are in the right mode */
        else
        {
            if (geMode != PERIPHERAL_ADV_MODE)
            {
                SetAdvertisingMode();           
            }
        }        
    }
}
Пример #21
0
void *console_to_rtm(void *local) {
	struct fins_module *module = (struct fins_module *) local;
	PRINT_DEBUG("Entered: module=%p", module);
	PRINT_IMPORTANT("Thread started: module=%p, index=%u, id=%u, name='%s'", module, module->index, module->id, module->name);
	struct rtm_data *md = (struct rtm_data *) module->data;

	int poll_num;
	struct pollfd poll_fds[MAX_CONSOLES];
	int time = 1;
	int ret;
	struct rtm_console *console;

	int i;
	for (i = 0; i < MAX_CONSOLES; i++) {
		poll_fds[i].events = POLLIN | POLLPRI | POLLRDNORM;
		//poll_fds[1].events = POLLIN | POLLPRI | POLLOUT | POLLERR | POLLHUP | POLLNVAL | POLLRDNORM | POLLRDBAND | POLLWRNORM | POLLWRBAND;
	}
	PRINT_DEBUG("events=0x%x", poll_fds[0].events);

	uint32_t cmd_len;
	uint8_t cmd_buf[MAX_CMD_LEN + 1];

	secure_sem_wait(&md->shared_sem);
	while (module->state == FMS_RUNNING) {
		poll_num = md->console_list->len;
		if (poll_num > 0) {
			for (i = 0; i < MAX_CONSOLES; i++) {
				if (md->console_fds[i] == 0) {
					poll_fds[i].fd = -1;
				} else {
					poll_fds[i].fd = md->console_fds[i];
				}
			}
			sem_post(&md->shared_sem);
			ret = poll(poll_fds, poll_num, time);
			secure_sem_wait(&md->shared_sem);
			if (ret < 0) {
				PRINT_ERROR("ret=%d, errno=%u, str='%s'", ret, errno, strerror(errno));
				break;
			} else if (ret > 0) {
				PRINT_DEBUG("poll: ret=%d", ret);

				for (i = 0; i < MAX_CONSOLES; i++) {
					if (poll_fds[i].fd > 0 && poll_fds[i].revents > 0) {
						if (1) {
							PRINT_DEBUG(
									"POLLIN=%d POLLPRI=%d POLLOUT=%d POLLERR=%d POLLHUP=%d POLLNVAL=%d POLLRDNORM=%d POLLRDBAND=%d POLLWRNORM=%d POLLWRBAND=%d",
									(poll_fds[i].revents & POLLIN) > 0, (poll_fds[i].revents & POLLPRI) > 0, (poll_fds[i].revents & POLLOUT) > 0, (poll_fds[i].revents & POLLERR) > 0, (poll_fds[i].revents & POLLHUP) > 0, (poll_fds[i].revents & POLLNVAL) > 0, (poll_fds[i].revents & POLLRDNORM) > 0, (poll_fds[i].revents & POLLRDBAND) > 0, (poll_fds[i].revents & POLLWRNORM) > 0, (poll_fds[i].revents & POLLWRBAND) > 0);
						}

						console = (struct rtm_console *) list_find1(md->console_list, rtm_console_fd_test, &poll_fds[i].fd);
						if (console != NULL) {
							if (poll_fds[i].revents & (POLLERR | POLLNVAL)) {
								//TODO ??
								PRINT_ERROR("todo: kinda error case that needs to be handled");
								list_remove(md->console_list, console);
								console_free(console);

								md->console_fds[i] = 0;
							} else if (poll_fds[i].revents & (POLLHUP)) {
								PRINT_IMPORTANT("Console closed: console=%p, id=%u", console, console->id);
								list_remove(md->console_list, console);
								console_free(console);

								md->console_fds[i] = 0;
							} else if (poll_fds[i].revents & (POLLIN | POLLRDNORM | POLLPRI | POLLRDBAND)) {
								cmd_len = (uint32_t) rtm_recv_fd(console->fd, MAX_CMD_LEN, cmd_buf);
								if (cmd_len != (uint32_t) -1) {
									cmd_buf[cmd_len] = '\0';
									rtm_process_cmd(module, console, cmd_len, cmd_buf);
								} else {
									PRINT_WARN("todo error");
								}
							}
						} else {
							PRINT_WARN("todo error");
							//console removed after poll started, before it returned, remove?
						}
					}
				}
			}
		} else {
			sem_post(&md->shared_sem);
			sleep(time);
			secure_sem_wait(&md->shared_sem);
		}
	}
	sem_post(&md->shared_sem);

	PRINT_IMPORTANT("Thread exited: module=%p, index=%u, id=%u, name='%s'", module, module->index, module->id, module->name);
	PRINT_DEBUG("Exited: module=%p", module);
	return NULL;
}
Пример #22
0
long DeleteDataSlot(	void *hDB,
			bmdDatagram_t *bmdJSRequest,
			bmdDatagram_t **bmdJSResponse,
			server_request_data_t *req)
{
char *CryptoObjectNr	= NULL;
char *ans		= NULL;
char *SQLQuery		= NULL;
char* fileType		= NULL;
long retVal		= 0;
long permissionsType	= 0; 

	PRINT_INFO("LIBBMDSQLINF Deleting file\n");
	/************************/
	/* walidacja parametrow */
	/************************/
	if (hDB==NULL)			{	BMD_FOK(BMD_ERR_PARAM1);	}
	if (bmdJSRequest==NULL)		{	BMD_FOK(BMD_ERR_PARAM2);	}
	if(bmdJSRequest->protocolDataFileId == NULL)
		{ BMD_FOK(BMD_ERR_PARAM2); }
	if(bmdJSRequest->protocolDataFileId->buf == NULL)
		{ BMD_FOK(BMD_ERR_PARAM2); }
	


	/************/
	/* usuwanie */
	/************/

	// w konfiguracji ustawione, kto moze usuwac dokument
	/*if(_GLOBAL_bmd_configuration == NULL || _GLOBAL_bmd_configuration->file_removing_permission_type == NULL)
		{ permissionsType = CONSIDER_CREATOR_OR_OWNER; }
	else if(strcmp(_GLOBAL_bmd_configuration->file_removing_permission_type, "CREATOR_OR_OWNER") == 0)
		{ permissionsType = CONSIDER_CREATOR_OR_OWNER; }
	else if(strcmp(_GLOBAL_bmd_configuration->file_removing_permission_type, "CREATOR") == 0)
		{ permissionsType = CONSIDER_ONLY_CREATOR; }
	else if(strcmp(_GLOBAL_bmd_configuration->file_removing_permission_type, "OWNER") == 0)
		{ permissionsType = CONSIDER_ONLY_OWNER; }
	else if(strcmp(_GLOBAL_bmd_configuration->file_removing_permission_type, "CREATOR_OR_OWNER_OR_GROUPS") == 0)
		{ permissionsType = CONSIDER_CREATOR_OR_OWNER_OR_GROUPS; }
	else if(strcmp(_GLOBAL_bmd_configuration->file_removing_permission_type, "CREATOR_OR_OWNER_OR_CURRENT_GROUP") == 0)
		{ permissionsType = CONSIDER_CREATOR_OR_OWNER_OR_CURRENT_GROUP; }
	else if(strcmp(_GLOBAL_bmd_configuration->file_removing_permission_type, "GROUPS") == 0)
		{ permissionsType = CONSIDER_GROUPS_GRAPH; }
	else if(strcmp(_GLOBAL_bmd_configuration->file_removing_permission_type, "CURRENT_GROUP") == 0)
		{ permissionsType = CONSIDER_CURRENT_GROUP; }
	else if(strcmp(_GLOBAL_bmd_configuration->file_removing_permission_type, "ANY") == 0)
		{ permissionsType = SKIP_AUTHORIZATION; }
	else
		{ permissionsType = CONSIDER_CREATOR_OR_OWNER; }*/
	

	BMD_FOK(bmd_db_start_transaction(hDB,BMD_TRANSACTION_LEVEL_NONE));
	BMD_FOK_TRANS(VerifyPermissionsForCryptoObject(hDB, req,
				bmdJSRequest->protocolDataFileId->buf,
				(bmdJSRequest->datagramType==BMD_DATAGRAM_DIR_DELETE ? CONSIDER_ONLY_DIRECTORY|permissionsType : permissionsType),
				NULL, &fileType, &CryptoObjectNr, NULL, NULL, NULL, NULL));
	BMD_FOK_TRANS(FillFromCryptoObjects(hDB, CryptoObjectNr, _GLOBAL_bmd_configuration->location_id, WITHOUT_SYS_METADATA, *bmdJSResponse,req));

	/************************************************************/
	/* w przypadku usuwania katalogu sprawdzamy, czy jest pusty */
	/************************************************************/
	if (bmdJSRequest->datagramType==BMD_DATAGRAM_DIR_DELETE)
	{
		asprintf(&SQLQuery, 	"SELECT count(id) FROM crypto_objects WHERE corresponding_id=%s AND location_id=%s;",
					CryptoObjectNr,
					_GLOBAL_bmd_configuration->location_id);
		BMD_FOK_TRANS(ExecuteSQLQueryWithAnswerKnownDBConnection( hDB, SQLQuery, &ans));

		if ((ans==NULL) || (strcmp(ans, "0")!=0))
		{
			BMD_FOK_TRANS(BMD_SQL_DELETE_DIR_NOT_EMPTY_ERROR);
		}
	}

	//jesli podany jest w zadaniu identyfikator linka, to ma byc usuniety tylko link
	if(strcmp(fileType, "link") == 0)
	{
		retVal=DeleteLinkFromDatabase(hDB, bmdJSRequest->protocolDataFileId->buf, req);
		if(retVal < 0)
		{
			PRINT_ERROR("ERROR: Unable to delete link from database (%li)", retVal);
			BMD_FOK_TRANS(BMD_ERR_OP_FAILED);
		}
	}
	//dla 'prawdziwego' dokumentu maja byc usuniete wszystkie jego linki, dokumenty powiazane itd. 
	else
	{
		BMD_FOK_TRANS(DeleteDocFromDatabase(hDB, bmdJSRequest, bmdJSRequest->protocolDataFileId->buf, _GLOBAL_bmd_configuration->location_id, req));
	}

	BMD_FOK(bmd_db_end_transaction(hDB));

	/************/
	/* porzadki */
	/************/
	free(fileType); fileType=NULL;
	free(CryptoObjectNr); CryptoObjectNr=NULL;
	free(SQLQuery); SQLQuery=NULL;
	free(ans); ans=NULL;

	return BMD_OK;
}
Пример #23
0
void *accept_console(void *local) {
	struct fins_module *module = (struct fins_module *) local;
	PRINT_DEBUG("Entered: module=%p", module);
	PRINT_IMPORTANT("Thread started: module=%p, index=%u, id=%u, name='%s'", module, module->index, module->id, module->name);
	struct rtm_data *md = (struct rtm_data *) module->data;

	int32_t addr_size = sizeof(struct sockaddr_un);
	struct sockaddr_un *addr;
	int console_fd;
	struct rtm_console *console;
	int i;

	secure_sem_wait(&md->shared_sem);
	while (module->state == FMS_RUNNING) {
		if (list_has_space(md->console_list)) {
			sem_post(&md->shared_sem);

			addr = (struct sockaddr_un *) secure_malloc(addr_size);
			while (module->state == FMS_RUNNING) {
				sleep(1);
				console_fd = accept(md->server_fd, (struct sockaddr *) addr, (socklen_t *) &addr_size);
				if (console_fd > 0 || (errno != EAGAIN && errno != EWOULDBLOCK)) {
					break;
				}
			}
			if (module->state != FMS_RUNNING) {
				free(addr);

				secure_sem_wait(&md->shared_sem);
				break;
			}

			if (console_fd < 0) {
				PRINT_ERROR("accept error: server_fd=%d, console_fd=%d, errno=%u, str='%s'", md->server_fd, console_fd, errno, strerror(errno));
				free(addr);

				secure_sem_wait(&md->shared_sem);
				continue;
			}

			secure_sem_wait(&md->shared_sem);
			console = (struct rtm_console *) secure_malloc(sizeof(struct rtm_console));
			console->id = md->console_counter++;
			console->fd = console_fd;
			console->addr = addr;
			console->type = RTM_TYPE_DEFAULT;
			console->listeners = (metadata *) secure_malloc(sizeof(metadata));
			metadata_create(console->listeners);

			PRINT_IMPORTANT("Console created: id=%u, fd=%d, addr='%s', type=%u", console->id, console->fd, console->addr->sun_path, console->type);
			list_append(md->console_list, console);

			for (i = 0; i < MAX_CONSOLES; i++) {
				if (md->console_fds[i] == 0) {
					md->console_fds[i] = console_fd;
					break;
				}
			}
		} else {
			sem_post(&md->shared_sem);
			sleep(5);
			secure_sem_wait(&md->shared_sem);
		}
	}
	sem_post(&md->shared_sem);

	PRINT_IMPORTANT("Thread exited: module=%p, index=%u, id=%u, name='%s'", module, module->index, module->id, module->name);
	PRINT_DEBUG("Exited: module=%p", module);
	return NULL;
}
Пример #24
0
/**
*Obsluzenie zadania ponownej wysylki awizo na poziomie datagramsetu
*
*@param[in] void *hDB		- wskaznik do uchwytu ustanowionego polaczenia z baza danych
*@param[in] bmdDatagramSet_t *bmdJSRequestSet	- wskaznik na datagram zadania
*@param[in] bmdDatagramSet_t **bmdJSResponseSet	- wskaznik na datagram odpowiedzi
*
*@retval BMD_OK 			- zakonczenie pomyslne.
*@retval BMD_ERR_OP_FAILED		- nieudana operacja
*@retval NO_MEMORY			- blad zasobow pamieci
*@retval BMD_ERR_PARAM1			- niepoprawny wskaznik do uchwytu ustanowionego polaczenia z baza danych
*@retval BMD_ERR_PARAM2			- niepoprawny wskaznik do lancucha znakowego z id crypto objecta
*@retval BMD_ERR_PARAM4			- niepoprawny wskaznik na GenBuf'a zawierajacego id grupy, do ktorej nalezy uzytkownik
*/
#ifndef WIN32
long JS_bmdDatagramSet_to_send_avizo(	void *hDB,
					bmdDatagramSet_t *bmdJSRequestSet,
					bmdDatagramSet_t **bmdJSResponseSet,
					server_request_data_t *req)
#else /*WIN32*/
long JS_bmdDatagramSet_to_send_avizo(	void *hDB,
					bmdDatagramSet_t *bmdJSRequestSet,
					bmdDatagramSet_t **bmdJSResponseSet,
					server_request_data_t *req,
					HANDLE *threadHandler)
#endif /*ifndef WIN32*/
{
long err		= 0;
long i			= 0;
long status		= 0;
char *hash		= NULL;
char *tmp_id		= NULL;


	PRINT_INFO("LIBBMDSQLINF Sending avizo (datagramset)\n");
	/******************************/
	/*	walidacja parametrow	*/
	/******************************/
	if (hDB==NULL)	{	BMD_FOK(BMD_ERR_PARAM1);	}
	if (bmdJSRequestSet==NULL)		{	BMD_FOK(BMD_ERR_PARAM2);	}

	/************************************************/
	/*	przygotowanie datagramsetu odpowiedzi	*/
	/************************************************/
	BMD_FOK(PR2_bmdDatagramSet_fill_with_datagrams(bmdJSRequestSet->bmdDatagramSetSize, bmdJSResponseSet));

	for(i=0; i < bmdJSRequestSet->bmdDatagramSetSize; i++, err=0)
	{
		free0(tmp_id);

		/************************************************/
		/* przepisanie zadajacego do odpowiedzi serwera */
		/************************************************/
		if (bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataOwner!=NULL)
		{
			if (bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataOwner->buf!=NULL)
			{
				(*bmdJSResponseSet)->bmdDatagramSetTable[i]->protocolDataOwner=(GenBuf_t *)malloc(sizeof(GenBuf_t));
				(*bmdJSResponseSet)->bmdDatagramSetTable[i]->protocolDataOwner->buf=(char*)malloc(bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataOwner->size+2);
				memset((*bmdJSResponseSet)->bmdDatagramSetTable[i]->protocolDataOwner->buf, 0,bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataOwner->size+1);
				memmove((*bmdJSResponseSet)->bmdDatagramSetTable[i]->protocolDataOwner->buf,bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataOwner->buf,bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataOwner->size);
				(*bmdJSResponseSet)->bmdDatagramSetTable[i]->protocolDataOwner->size=bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataOwner->size;
			}
		}

		/************************************************************************/
		/*	sprawdzenie, czy wczesniej nie wykryto bledu w datagramie zadania	*/
		/************************************************************************/
		if (bmdJSRequestSet->bmdDatagramSetTable[i]->datagramStatus<BMD_OK)
		{
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus=bmdJSRequestSet->bmdDatagramSetTable[i]->datagramStatus;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramType=bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100;
			continue;
		}

		// sparametryzowana wysylka awizo moze odbywac sie na podstawie bmdId albo na podstawie wartosci metadanych
		if(bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType == BMD_DATAGRAM_TYPE_SEND_ADVICE_WITH_PARAMETERS)
		{
			if(bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataFileId == NULL) // zadanie wywolane z podaniem bmdId
			{
				status = VerifyPermissionsForCryptoObjectByMetadata(hDB, req,
					bmdJSRequestSet->bmdDatagramSetTable[i],
					CONSIDER_CREATOR_OR_OWNER_OR_GROUPS,
					NULL/*fileName*/,
					NULL/*fileType*/,
					&tmp_id/*pointingId*/,
					NULL/*correspondingId*/,
					NULL/*forGrant*/,
					NULL/*additionalMetadataCount*/,
					NULL/*additionalMetadataValues*/);
			}
			else // zadanie wywolane z podaniem metadanych opisujacych dokument (nie bmdId)
			{
				status = VerifyPermissionsForCryptoObject(hDB, req,
					bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataFileId->buf,
					CONSIDER_CREATOR_OR_OWNER_OR_GROUPS,
					NULL/*fileName*/,
					NULL/*fileType*/,
					NULL/*pointingId*/,
					NULL/*correspondingId*/,
					NULL/*forGrant*/,
					NULL/*additionalMetadataCount*/,
					NULL/*additionalMetadataValues*/);

				tmp_id = strdup(bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataFileId->buf);
			}
		}
		else // dla innych typow zadan wysylka awizo moze odbyc sie tylko na podstawie bmdId
		{
			if(bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataFileId == NULL)
				{ BMD_FOK(BMD_ERR_PARAM2); }

			status = VerifyPermissionsForCryptoObject(hDB, req,
				bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataFileId->buf,
				CONSIDER_CREATOR_OR_OWNER_OR_GROUPS,
				NULL/*fileName*/,
				NULL/*fileType*/,
				NULL/*pointingId*/,
				NULL/*correspondingId*/,
				NULL/*forGrant*/,
				NULL/*additionalMetadataCount*/,
				NULL/*additionalMetadataValues*/);

			tmp_id = strdup(bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataFileId->buf);
		}
		
		//status=CheckIfCryptoObjectExist( hDB, bmdJSRequestSet->bmdDatagramSetTable[i], 0, &tmp_id, NULL, &tmp_location, NULL, NULL, NULL, NULL, req);
		if (status<BMD_OK)
		{
			PRINT_ERROR("LIBBMDSQLERR %s. Error=%li\n",GetErrorMsg(status), status);
			err=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramType=bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100;
			continue;
		}


// 		/************************************************************************/
// 		/*	przepisanie id pliku z datagramu requesta do datagramu responsa	*/
// 		/************************************************************************/
// 		asprintf(&tmp_id,"%s",(char *)bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataFileId->buf);
// 		if (tmp_id==NULL)
// 		{
// 			PRINT_ERROR("LIBBMDSQLERR Memory error. Error=%i\n",NO_MEMORY);
// 			err=NO_MEMORY;
// 			PR_bmdDatagram_PrepareResponse(	&((*bmdJSResponseSet)->bmdDatagramSetTable[i]),
// 									bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100,
// 									err);
// 			continue;
// 		}
//
// 		/************************************************/
// 		/* przepisanie id lokalizacji pliku z datagramu */
// 		/************************************************/
// 		asprintf(&tmp_location,"%s",(char *)bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataFileLocationId->buf);
// 		if (tmp_location==NULL)
// 		{
// 			PRINT_ERROR("LIBBMDSQLERR Memory error. Error=%i\n",NO_MEMORY);
// 			err=NO_MEMORY;
// 			PR_bmdDatagram_PrepareResponse(	&((*bmdJSResponseSet)->bmdDatagramSetTable[i]),
// 									bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100,
// 									err);
// 			continue;
// 		}
//

		status = set_gen_buf2( tmp_id, (long)strlen(tmp_id), &((*bmdJSResponseSet)->bmdDatagramSetTable[i]->protocolDataFileId));
		if (status!=BMD_OK)
		{
			PRINT_ERROR("LIBBMDSQLERR Memory error. Error=%i\n",NO_MEMORY);
			err=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramType=bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100;
			continue;
		}

		status = set_gen_buf2(_GLOBAL_bmd_configuration->location_id, (long)strlen(_GLOBAL_bmd_configuration->location_id), &((*bmdJSResponseSet)->bmdDatagramSetTable[i]->protocolDataFileLocationId));
		if (status!=BMD_OK)
		{
			PRINT_ERROR("LIBBMDSQLERR Memory error. Error=%i\n",NO_MEMORY);
			err=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramType=bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100;
			continue;
		}

		/******************************************************/
		/*	pobranie hasha pliku na podstawienie id pliku	*/
		/******************************************************/
		status=GetHashFromId(hDB, tmp_id, _GLOBAL_bmd_configuration->location_id, &hash);
		if (status<BMD_OK)
		{
			PRINT_ERROR("LIBBMDSQLERR Error in getting recipient's e-mail\n");
			err=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramType=bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100;
			continue;
		}

		/******************************************/
		/*	dolaczenie hasha do datagaramu	*/
		/******************************************/
		status=bmd_add_hash_to_dtg_as_data(hash,&((*bmdJSResponseSet)->bmdDatagramSetTable[i]));
		if (status<BMD_OK)
		{
			PRINT_ERROR("LIBBMDSQLERR Error adding hash to datagram. Error=%li\n",status);
			err=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramType=bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100;
			continue;
		}

		/************************************************/
		/*	ustawienie statusu bledu datagramu	*/
		/************************************************/
		(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus =(long ) err;
		(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramType = bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100;

		/************************************************************/
		/*	pobranie metadanych pliku na podstawienie id pliku	*/
		/************************************************************/
		BMD_FOK(FillFromAllMetadata(	hDB,
						tmp_id,
						_GLOBAL_bmd_configuration->location_id,
						WITHOUT_PKI_METADATA,
						WITH_ADD_METADATA,
						WITH_SYS_METADATA,
						WITHOUT_ACTION_METADATA,
						(*bmdJSResponseSet)->bmdDatagramSetTable[i],req));

		// skopiowanie pamametrow wysylki awizo z zadania do odpowiedzi (bo wysylka odbywa sie na podstawie odpowiedzi)
		if(bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType == BMD_DATAGRAM_TYPE_SEND_ADVICE_WITH_PARAMETERS)
		{
			BMD_FOK( CopySendAdviceParameters(bmdJSRequestSet->bmdDatagramSetTable[i], (*bmdJSResponseSet)->bmdDatagramSetTable[i]) );
		}
	}

	/************************************************/
	/*	wysylka maili z awizo do klientow	*/
	/************************************************/
	if(_GLOBAL_bmd_configuration->session_plugin_conf.bmd_plugin_action_post!=NULL)
	{

// 		if ((char *)_GLOBAL_bmd_configuration->additional_db_conninfo!=NULL)
// 		{
// #ifndef WIN32
//
// 			status=_GLOBAL_bmd_configuration->session_plugin_conf.bmd_plugin_action_post(	*bmdJSResponseSet,
// 																_GLOBAL_bmd_configuration->additional_db_conninfo,
// 																0,0,1,req);
// #else /*WIN32*/
//
// 			status=_GLOBAL_bmd_configuration->session_plugin_conf.bmd_plugin_action_post(	*bmdJSResponseSet,
// 																_GLOBAL_bmd_configuration->additional_db_conninfo,
// 																0,0,1,req, threadHandler);
// #endif /*ifndef WIN32*/
//
// 		}
// 		else
// 		{
#ifndef WIN32

			status=_GLOBAL_bmd_configuration->session_plugin_conf.bmd_plugin_action_post(	*bmdJSResponseSet,
																_GLOBAL_bmd_configuration->db_conninfo,
																0,0,1,req);
#else /*WIN32*/

			status=_GLOBAL_bmd_configuration->session_plugin_conf.bmd_plugin_action_post(	*bmdJSResponseSet,
																_GLOBAL_bmd_configuration->db_conninfo,
																0,0,1,req, threadHandler);

#endif /*ifndef WIN32*/
// 		}


		if (status<BMD_OK)
		{
			for(i=0; i<(long)bmdJSRequestSet->bmdDatagramSetSize; i++, err=0)
			{
				(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus=status;
				(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramType=bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100;
			}

		}

		/* rejestracja odbywa sie na zewnatrz w js.c
		// zarejestrowanie akcji w bazie danych
		if (_GLOBAL_bmd_configuration->messaging_plugin_conf.bmd_messaging_plugin_register_action)
		{
			for(i=0; i<(long)bmdJSRequestSet->bmdDatagramSetSize; i++)
			{
				status=_GLOBAL_bmd_configuration->messaging_plugin_conf.bmd_messaging_plugin_register_action(hDB, bmdJSRequestSet->bmdDatagramSetTable[i], (*bmdJSResponseSet)->bmdDatagramSetTable[i], req);
				if (status<BMD_OK)
				{
					(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus = status;
				}
			}
		}
		*/


	}
	else
	{
		BMD_FOK(PLUGIN_SESSION_NOT_RUNNING);
	}

	/************/
	/* porzadki */
	/************/
	free0(hash);
	free0(tmp_id);

	return BMD_OK;
}
Пример #25
0
BOOL kull_m_rpc_drsr_getDomainAndUserInfos(RPC_BINDING_HANDLE *hBinding, LPCWSTR ServerName, LPCWSTR Domain, GUID *DomainGUID, LPCWSTR User, LPCWSTR Guid, GUID *UserGuid)
{
	BOOL DomainGUIDfound = FALSE, ObjectGUIDfound = FALSE;
	DWORD i;
	ULONG drsStatus;
	DRS_HANDLE hDrs = NULL;
	DRS_EXTENSIONS_INT DrsExtensionsInt = {0};
	DRS_EXTENSIONS *pDrsExtensionsOutput = NULL;
	DRS_MSG_DCINFOREQ dcInfoReq = {0};
	DWORD dcOutVersion = 0;
	DRS_MSG_DCINFOREPLY dcInfoRep = {0};
	LPWSTR sGuid;
	UNICODE_STRING uGuid;

	RpcTryExcept
	{
		DrsExtensionsInt.cb = sizeof(DRS_EXTENSIONS_INT) - sizeof(DWORD);
		drsStatus = IDL_DRSBind(*hBinding, &DRSUAPI_DS_BIND_GUID_Standard, (DRS_EXTENSIONS *) &DrsExtensionsInt, &pDrsExtensionsOutput, &hDrs);
		if(drsStatus == 0)
		{
			dcInfoReq.V1.InfoLevel = 2;
			dcInfoReq.V1.Domain = (LPWSTR) Domain;
			drsStatus = IDL_DRSDomainControllerInfo(hDrs, 1, &dcInfoReq, &dcOutVersion, &dcInfoRep);
			if(drsStatus == 0)
			{
				if(dcOutVersion == 2)
				{
					for(i = 0; i < dcInfoRep.V2.cItems; i++)
					{
						if(!DomainGUIDfound && ((_wcsicmp(ServerName, dcInfoRep.V2.rItems[i].DnsHostName) == 0) || (_wcsicmp(ServerName, dcInfoRep.V2.rItems[i].NetbiosName) == 0)))
						{
							DomainGUIDfound = TRUE;
							*DomainGUID = dcInfoRep.V2.rItems[i].NtdsDsaObjectGuid;
						}
					}
					if(!DomainGUIDfound)
						PRINT_ERROR(L"DomainControllerInfo: DC \'%s\' not found\n", ServerName);
				}
				else PRINT_ERROR(L"DomainControllerInfo: bad version (%u)\n", dcOutVersion);
				kull_m_rpc_drsr_free_DRS_MSG_DCINFOREPLY_data(dcOutVersion, &dcInfoRep);
			}
			else PRINT_ERROR(L"DomainControllerInfo: 0x%08x (%u)\n", drsStatus, drsStatus);
			
			if(Guid)
			{
				RtlInitUnicodeString(&uGuid, Guid);
				ObjectGUIDfound = NT_SUCCESS(RtlGUIDFromString(&uGuid, UserGuid));
			}
			else if(User)
			{
				if(kull_m_rpc_drsr_CrackName(hDrs, wcschr(User, L'\\') ? DS_NT4_ACCOUNT_NAME : wcschr(User, L'=') ? DS_FQDN_1779_NAME : wcschr(User, L'@') ? DS_USER_PRINCIPAL_NAME : DS_NT4_ACCOUNT_NAME_SANS_DOMAIN, User, DS_UNIQUE_ID_NAME, &sGuid, NULL))
				{
					RtlInitUnicodeString(&uGuid, sGuid);
					ObjectGUIDfound = NT_SUCCESS(RtlGUIDFromString(&uGuid, UserGuid));
				}
			}
			drsStatus = IDL_DRSUnbind(&hDrs);
			MIDL_user_free(pDrsExtensionsOutput);
		}
	}
	RpcExcept(DRS_EXCEPTION)
		PRINT_ERROR(L"RPC Exception 0x%08x (%u)\n", RpcExceptionCode(), RpcExceptionCode());
	RpcEndExcept
	return (DomainGUIDfound && (ObjectGUIDfound || !(Guid || User)));
}
void IP4_receive_fdf(void) {

	struct finsFrame* pff = NULL;
	uint32_t protocol;
	do {
		sem_wait(&Switch_to_IPv4_Qsem);
		pff = read_queue(Switch_to_IPv4_Queue);
		sem_post(&Switch_to_IPv4_Qsem);
	} while (ipv4_running && pff == NULL);

	if (!ipv4_running) {
		return;
	}

	if (pff->dataOrCtrl == CONTROL) {
		PRINT_DEBUG("Received frame: D/C: %d, DestID=%d, ff=%p, meta=%p", pff->dataOrCtrl, pff->destinationID.id, pff, pff->metaData);
		ipv4_fcf(pff);
	} else if (pff->dataOrCtrl == DATA) {
		PRINT_DEBUG("Received frame: D/C: %d, DestID=%d, ff=%p, meta=%p", pff->dataOrCtrl, pff->destinationID.id, pff, pff->metaData);
		PRINT_DEBUG("PDU Length: %d", pff->dataFrame.pduLength);
		PRINT_DEBUG("Data direction: %d", pff->dataFrame.directionFlag);
		PRINT_DEBUG("pdu=%p", pff->dataFrame.pdu);

		if (pff->dataFrame.directionFlag == UP) {
			PRINT_DEBUG("IP4_in");

			IP4_in(pff, (struct ip4_packet*) pff->dataFrame.pdu, pff->dataFrame.pduLength);

		} else if (pff->dataFrame.directionFlag == DOWN) {
			PRINT_DEBUG("IP4_out");

			metadata *params = pff->metaData;
			if (params == NULL) {
				PRINT_ERROR("todo error");
				freeFinsFrame(pff);
				return;
			}

			int ret = 0;
			ret += metadata_readFromElement(params, "send_protocol", &protocol) == META_FALSE;

			if (ret) {
				PRINT_ERROR("metadata read error: ret=%d", ret);
			}

			PRINT_DEBUG("%lu", my_ip_addr);
			PRINT_DEBUG("Transport protocol going out passed to IPv4: protocol=%u", protocol);
			switch (protocol) {
			case IP4_PT_ICMP:
				IP4_out(pff, pff->dataFrame.pduLength, my_ip_addr, IP4_PT_ICMP);
				break;
			case IP4_PT_TCP:
				IP4_out(pff, pff->dataFrame.pduLength, my_ip_addr, IP4_PT_TCP);
				break;
			case IP4_PT_UDP:
				IP4_out(pff, pff->dataFrame.pduLength, my_ip_addr, IP4_PT_UDP);
				break;
			default:
				PRINT_ERROR("invalid protocol: protocol=%u", protocol);
				/**
				 * TODO investigate why the freeFinsFrame below create segmentation fault
				 */
				freeFinsFrame(pff);
				break;
			}

		} else {
			PRINT_ERROR("Error: Wrong value of fdf.directionFlag");
			freeFinsFrame(pff);
		}
	} else {
		PRINT_ERROR("Error: Wrong pff->dataOrCtrl value");
		freeFinsFrame(pff);
	}

}
Пример #27
0
NTSTATUS kuhl_m_kerberos_list(int argc, wchar_t * argv[])
{
	NTSTATUS status, packageStatus;
	KERB_QUERY_TKT_CACHE_REQUEST kerbCacheRequest = {KerbQueryTicketCacheExMessage, {0, 0}};
	PKERB_QUERY_TKT_CACHE_EX_RESPONSE pKerbCacheResponse;
	PKERB_RETRIEVE_TKT_REQUEST pKerbRetrieveRequest;
	PKERB_RETRIEVE_TKT_RESPONSE pKerbRetrieveResponse;
	DWORD szData, i;
	wchar_t * filename;
	BOOL export = kull_m_string_args_byName(argc, argv, L"export", NULL, NULL);

	status = LsaCallKerberosPackage(&kerbCacheRequest, sizeof(KERB_QUERY_TKT_CACHE_REQUEST), (PVOID *) &pKerbCacheResponse, &szData, &packageStatus);
	if(NT_SUCCESS(status))
	{
		if(NT_SUCCESS(packageStatus))
		{
			for(i = 0; i < pKerbCacheResponse->CountOfTickets; i++)
			{
				kprintf(L"\n[%08x] - 0x%08x - %s", i, pKerbCacheResponse->Tickets[i].EncryptionType, kuhl_m_kerberos_ticket_etype(pKerbCacheResponse->Tickets[i].EncryptionType));
				kprintf(L"\n   Start/End/MaxRenew: ");
				kull_m_string_displayLocalFileTime((PFILETIME) &pKerbCacheResponse->Tickets[i].StartTime); kprintf(L" ; ");
				kull_m_string_displayLocalFileTime((PFILETIME) &pKerbCacheResponse->Tickets[i].EndTime); kprintf(L" ; ");
				kull_m_string_displayLocalFileTime((PFILETIME) &pKerbCacheResponse->Tickets[i].RenewTime);
				kprintf(L"\n   Server Name       : %wZ @ %wZ", &pKerbCacheResponse->Tickets[i].ServerName, &pKerbCacheResponse->Tickets[i].ServerRealm);
				kprintf(L"\n   Client Name       : %wZ @ %wZ", &pKerbCacheResponse->Tickets[i].ClientName, &pKerbCacheResponse->Tickets[i].ClientRealm);
				kprintf(L"\n   Flags %08x    : ", pKerbCacheResponse->Tickets[i].TicketFlags);
				kuhl_m_kerberos_ticket_displayFlags(pKerbCacheResponse->Tickets[i].TicketFlags);
			
				if(export)
				{
					szData = sizeof(KERB_RETRIEVE_TKT_REQUEST) + pKerbCacheResponse->Tickets[i].ServerName.MaximumLength;
					if(pKerbRetrieveRequest = (PKERB_RETRIEVE_TKT_REQUEST) LocalAlloc(LPTR, szData)) // LPTR implicates KERB_ETYPE_NULL
					{
						pKerbRetrieveRequest->MessageType = KerbRetrieveEncodedTicketMessage;
						pKerbRetrieveRequest->CacheOptions = /*KERB_RETRIEVE_TICKET_USE_CACHE_ONLY | */KERB_RETRIEVE_TICKET_AS_KERB_CRED;
						pKerbRetrieveRequest->TicketFlags = pKerbCacheResponse->Tickets[i].TicketFlags;
						pKerbRetrieveRequest->TargetName = pKerbCacheResponse->Tickets[i].ServerName;
						pKerbRetrieveRequest->TargetName.Buffer = (PWSTR) ((PBYTE) pKerbRetrieveRequest + sizeof(KERB_RETRIEVE_TKT_REQUEST));
						RtlCopyMemory(pKerbRetrieveRequest->TargetName.Buffer, pKerbCacheResponse->Tickets[i].ServerName.Buffer, pKerbRetrieveRequest->TargetName.MaximumLength);

						status = LsaCallKerberosPackage(pKerbRetrieveRequest, szData, (PVOID *) &pKerbRetrieveResponse, &szData, &packageStatus);
						if(NT_SUCCESS(status))
						{
							if(NT_SUCCESS(packageStatus))
							{
								if(filename = kuhl_m_kerberos_generateFileName(i, &pKerbCacheResponse->Tickets[i], MIMIKATZ_KERBEROS_EXT))
								{
									if(kull_m_file_writeData(filename, pKerbRetrieveResponse->Ticket.EncodedTicket, pKerbRetrieveResponse->Ticket.EncodedTicketSize))
										kprintf(L"\n   * Saved to file     : %s", filename);
									LocalFree(filename);
								}
								LsaFreeReturnBuffer(pKerbRetrieveResponse);
							}
							else PRINT_ERROR(L"LsaCallAuthenticationPackage KerbRetrieveEncodedTicketMessage / Package : %08x\n", packageStatus);
						}
						else PRINT_ERROR(L"LsaCallAuthenticationPackage KerbRetrieveEncodedTicketMessage : %08x\n", status);

						LocalFree(pKerbRetrieveRequest);
					}
				}
				kprintf(L"\n");
			}
			LsaFreeReturnBuffer(pKerbCacheResponse);
		}
		else PRINT_ERROR(L"LsaCallAuthenticationPackage KerbQueryTicketCacheEx2Message / Package : %08x\n", packageStatus);
	}
void ipv4_exec_reply(struct finsFrame *ff) {
	PRINT_DEBUG("Entered: ff=%p, meta=%p", ff, ff->metaData);

	int ret = 0;

	metadata *params = ff->metaData;
	if (params) {
		switch (ff->ctrlFrame.param_id) {
		case EXEC_ARP_GET_ADDR:
			PRINT_DEBUG("param_id=EXEC_ARP_GET_ADDR (%d)", ff->ctrlFrame.param_id);

			if (ff->ctrlFrame.ret_val) {
				uint64_t src_mac, dst_mac;
				ret += metadata_readFromElement(params, "src_mac", &src_mac) == META_FALSE;
				ret += metadata_readFromElement(params, "dst_mac", &dst_mac) == META_FALSE;

				if (ret) {
					PRINT_ERROR("ret=%d", ret);
					//TODO send nack
				} else {
					//ipv4_exec_reply_get_addr(ff, src_mac, dst_mac);
					struct ip4_store *store = store_list_find(ff->ctrlFrame.serial_num);
					if (store) {
						PRINT_DEBUG("store=%p, ff=%p, serial_num=%u", store, store->ff, store->serial_num);
						store_list_remove(store);

						uint32_t ether_type = IP4_ETH_TYPE;
						metadata_writeToElement(store->ff->metaData, "send_ether_type", &ether_type, META_TYPE_INT32);
						metadata_writeToElement(store->ff->metaData, "send_dst_mac", &dst_mac, META_TYPE_INT64);
						metadata_writeToElement(store->ff->metaData, "send_src_mac", &src_mac, META_TYPE_INT64);

						PRINT_DEBUG("recv frame: dst=0x%12.12llx, src=0x%12.12llx, type=0x%x", dst_mac, src_mac, ether_type);

						//print_finsFrame(fins_frame);
						ipv4_to_switch(store->ff);
						store->ff = NULL;

						store_free(store);

						freeFinsFrame(ff);
					} else {
						PRINT_ERROR("todo error");
					}
				}
			} else {
				//TODO error sending back FDF as FCF? saved pdu for that
				PRINT_ERROR("todo error");
			}
			break;
		default:
			PRINT_ERROR("Error unknown param_id=%d", ff->ctrlFrame.param_id);
			//TODO implement?
			freeFinsFrame(ff);
			break;
		}
	} else {
		//TODO send nack
		PRINT_ERROR("Error fcf.metadata==NULL");
		freeFinsFrame(ff);
	}
}
Пример #29
0
NTSTATUS kuhl_m_vault_list(int argc, wchar_t * argv[])
{
	DWORD i, j, k, l, cbVaults, cbItems;
	LPGUID vaults;
	HANDLE hVault;
	PVOID items;
	PVAULT_ITEM_7 items7, pItem7;
	PVAULT_ITEM_8 items8, pItem8;
	NTSTATUS status;

	if(isVaultInit)
	{
		if(NT_SUCCESS(VaultEnumerateVaults(0, &cbVaults, &vaults)))
		{
			for(i = 0; i < cbVaults; i++)
			{
				kprintf(L"\nVault : "); kull_m_string_displayGUID(&vaults[i]); kprintf(L"\n");

				if(NT_SUCCESS(VaultOpenVault(&vaults[i], 0, &hVault)))
				{
					kuhl_m_vault_list_descVault(hVault);

					if(NT_SUCCESS(VaultEnumerateItems(hVault, 0, &cbItems, &items)))
					{
						kprintf(L"\tItems (%u)\n", cbItems);
						for(j = 0; j < cbItems; j++)
						{
							if(MIMIKATZ_NT_BUILD_NUMBER < KULL_M_WIN_MIN_BUILD_8) // to fix !
							{
								items7 = (PVAULT_ITEM_7) items;
								kprintf(L"\t %2u.\t%s\n", j, items7[j].FriendlyName);
								kprintf(L"\t\tType            : "); kull_m_string_displayGUID(&items7[j].SchemaId); kprintf(L"\n");
								kprintf(L"\t\tLastWritten     : "); kull_m_string_displayLocalFileTime(&items7[j].LastWritten); kprintf(L"\n");
								kprintf(L"\t\tFlags           : %08x\n", items7[j].Flags);

								kprintf(L"\t\tRessource       : "); kuhl_m_vault_list_descItemData(items7[j].Ressource); kprintf(L"\n");
								kprintf(L"\t\tIdentity        : "); kuhl_m_vault_list_descItemData(items7[j].Identity); kprintf(L"\n");
								kprintf(L"\t\tAuthenticator   : "); kuhl_m_vault_list_descItemData(items7[j].Authenticator); kprintf(L"\n");

								for(k = 0; k < items7[j].cbProperties; k++)
								{
									kprintf(L"\t\tProperty %2u     : ", k); kuhl_m_vault_list_descItemData(items7[j].Properties + k); kprintf(L"\n");
								}

								pItem7 = NULL;
								status = VaultGetItem7(hVault, &items7[j].SchemaId, items7[j].Ressource, items7[j].Identity, NULL, 0, &pItem7);

								kprintf(L"\t\t*Authenticator* : ");
								if(status == STATUS_SUCCESS)
									kuhl_m_vault_list_descItemData(pItem7->Authenticator);
								else
									PRINT_ERROR(L"VaultGetItem7 : %08x", status);
								kprintf(L"\n");
								;
							}
							else
							{
								items8 = (PVAULT_ITEM_8) items;

								kprintf(L"\t %2u.\t%s\n", j, items8[j].FriendlyName);
								kprintf(L"\t\tType            : "); kull_m_string_displayGUID(&items8[j].SchemaId); kprintf(L"\n");
								kprintf(L"\t\tLastWritten     : "); kull_m_string_displayLocalFileTime(&items8[j].LastWritten); kprintf(L"\n");
								kprintf(L"\t\tFlags           : %08x\n", items8[j].Flags);

								kprintf(L"\t\tRessource       : "); kuhl_m_vault_list_descItemData(items8[j].Ressource); kprintf(L"\n");
								kprintf(L"\t\tIdentity        : "); kuhl_m_vault_list_descItemData(items8[j].Identity); kprintf(L"\n");
								kprintf(L"\t\tAuthenticator   : "); kuhl_m_vault_list_descItemData(items8[j].Authenticator); kprintf(L"\n");
								kprintf(L"\t\tPackageSid      : "); kuhl_m_vault_list_descItemData(items8[j].PackageSid); kprintf(L"\n");

								for(k = 0; k < items8[j].cbProperties; k++)
								{
									kprintf(L"\t\tProperty %2u     : ", k); kuhl_m_vault_list_descItemData(items8[j].Properties + k); kprintf(L"\n");
								}

								pItem8 = NULL;
								status = VaultGetItem8(hVault, &items8[j].SchemaId, items8[j].Ressource, items8[j].Identity, items8[j].PackageSid, NULL, 0, &pItem8);

								kprintf(L"\t\t*Authenticator* : ");
								if(status == STATUS_SUCCESS)
									kuhl_m_vault_list_descItemData(pItem8->Authenticator);
								else
									PRINT_ERROR(L"VaultGetItem8 : %08x\n", status);
								kprintf(L"\n");

								for(l = 0; l < (sizeof(schemaHelper) / sizeof(VAULT_SCHEMA_HELPER)); l++)
								{
									if(RtlEqualGuid(&items8[j].SchemaId, &schemaHelper[l].guidString.guid))
									{
										kprintf(L"\n\t\t*** %s ***\n", schemaHelper[l].guidString.text);
										if(schemaHelper[l].helper)
										{
											schemaHelper[l].helper(&schemaHelper[l].guidString, &items8[j], ((status == STATUS_SUCCESS) && pItem8) ? pItem8 : NULL, TRUE);
											kprintf(L"\n");
										}
										break;
									}
								}

								if(pItem8)
									VaultFree(pItem8);
							}
						}
						VaultFree(items);
					}
					VaultCloseVault(&hVault);
				}
			}
		}
		VaultFree(vaults);
	}
	return STATUS_SUCCESS;
}
Пример #30
0
int main(int argc, char *argv[])
{
long switcher_no				= 8;
long ans_count				= 0;
long i					= 0;
char *switchers[] 			= {"-d","-c","-p","-b","-pp","-pb", "-id_from", "-id_to"};
char *lobid					= NULL;
char **params				= NULL;
char *SQLQuery				= NULL;
char *ans2					= NULL;
char *ans3					= NULL;
void *hDB		= NULL;
GenBuf_t *symkey_encrypted		= NULL;
bmd_crypt_ctx_t *symkey_decrypted	= NULL;
GenBuf_t *symkey_rencrypted		= NULL;
bmd_crypt_ctx_t *oldctx			= NULL;
bmd_crypt_ctx_t *newctx			= NULL;
char **ans					= NULL;

	/****************************/
	/* parsowanie linii polecen */
	/****************************/
	DEBUG("parsing command line...                      ");
	RENC_FOK(parse_command_line(argc,argv,&params,switcher_no,switchers));

	for (i=0; i<switcher_no; i++)
	{
		if ((params[i]==NULL) || (strcmp(params[i],"")==0))
		{
			PRINT_ERROR("RENCRYPTIONERR Invalid parameter value given at %li position\n",i);
			for (i=0; i<switcher_no; i++)
			{
				if (params[i])	{free(params[i]); params[i]=NULL;}
			}
			free(params); params=NULL;
			return -1;
		}
	}

	/***************************/
	/* stworzenie konfiguracji */
	/***************************/
	DEBUG("creating configuration struture...           ");
	//RENC_FOK(bmd_server_configuration_create(&_GLOBAL_bmd_configuration));

	/*************************************/
	/* pobranie konfiguracji serwera BMD */
	/*************************************/
	DEBUG("reading configuration values...              ");
//	RENC_FOK(bmd_get_server_configuration(params[1],_GLOBAL_bmd_configuration, TIME_FIRST));

	/****************************/
	/* polaczenie z baza danych */
	/****************************/
	DEBUG("initializing database library...             ");
	if( _GLOBAL_bmd_configuration->db_library == NULL )
	{
		RENC_FOK(bmd_db_init("libbmddb_postgres.so"));
	}
	else
	{
		RENC_FOK(bmd_db_init(_GLOBAL_bmd_configuration->db_library));
	}

	memset(&hDB,0,sizeof(char *)+2);
	DEBUG("connecting to database...                    ");
	RENC_FOK(bmd_db_connect(_GLOBAL_bmd_configuration->db_conninfo, &hDB));

	/****************************************************/
	/* wyszukanie oidow wszystkich kluczy symetrycznych */
	/****************************************************/
	asprintf(&SQLQuery, "SELECT symkey FROM crypto_objects WHERE id>=%s AND id <=%s;", params[6], params[7]);
	if (SQLQuery==NULL)	{	BMD_FOK(NO_MEMORY);	}

	DEBUG("retrieving cryto objects id list...          ");
	RENC_FOK_DB(ExecuteSQLQueryWithAnswersKnownDBConnection(	hDB, SQLQuery, &ans_count, &ans));
	free(SQLQuery); SQLQuery=NULL;

	printf("\n\n\n");
	for (i=0; i<ans_count; i++)
	{
		/***********************/
		/* wyzerowanie pamieci */
		/***********************/
		bmd_ctx_destroy(&newctx);
		bmd_ctx_destroy(&oldctx);
		free(ans2); ans2=NULL;
		free(ans3); ans3=NULL;
		free(lobid); lobid=NULL;
		free_gen_buf(&symkey_encrypted);
		free_gen_buf(&symkey_rencrypted);

		/****************************************************/
		/* sprawdzenie, czy lob znajduje sie w bazie danych */
		/****************************************************/
		asprintf(&SQLQuery,"SELECT DISTINCT loid FROM pg_largeobject WHERE loid=%s;", ans[i]);
		if (SQLQuery==NULL)	{	BMD_FOK(NO_MEMORY);	}

		BMD_FOK_DB(ExecuteSQLQueryWithAnswerKnownDBConnection(	hDB, SQLQuery, &ans2));
		free(SQLQuery); SQLQuery=NULL;

		DEBUG("importing and rencrypting symkey's lob (%.7li/%.7li) (lob id:%.7s)...          ", 	i+1, ans_count, ans2);
		/****************************************/
		/*	importuj zaszyfrowany symkey	*/
		/****************************************/
		RENC_FOK_DB(bmd_db_import_blob(hDB, ans2, &symkey_encrypted));

		/***********************************/
		/* zdeszyfrowanie pobranego klucza */
		/***********************************/
		DEBUG("preparing decrypting certificate...                                                   ");
		RENC_FOK_DB(bmd_set_ctx_file(params[2], params[4], strlen(params[4]), &(oldctx)));

		DEBUG("decrypting private key with decrypting certificate...                                 ");
		RENC_FOK_DB(bmd_decode_bmdKeyIV(symkey_encrypted, NULL, oldctx, &symkey_decrypted));

		/*******************************/
		/* zaszyfrowanie nowym kluczem */
		/*******************************/
		DEBUG("preparing encrypting certificate...                                                   ");
		RENC_FOK_DB(bmd_set_ctx_file(params[3], params[5], strlen(params[5]), &(newctx)));

		DEBUG("encrypting private key with encrypting certificate...                                 ");
		RENC_FOK_DB(bmd_create_der_bmdKeyIV(BMD_CRYPT_ALGO_RSA, BMD_CRYPT_ALGO_DES3, newctx, symkey_decrypted->sym->key, symkey_decrypted->sym->IV, NULL, &symkey_rencrypted));

		/****************************************/
		/* zapisanie nowego loba w bazie danych */
		/****************************************/
		DEBUG("exporting new symmetric key to data base...                                           ");
		RENC_FOK_DB(bmd_db_export_blob(hDB, symkey_rencrypted, &lobid));

		/****************************************/
		/* zmiana id symkeya w crypto_objectach */
		/****************************************/
		asprintf(&SQLQuery,"UPDATE crypto_objects SET symkey=%s WHERE symkey=%s;",lobid,ans2);
		if (SQLQuery==NULL)	{	BMD_FOK(NO_MEMORY);	}

		ExecuteSQLQueryWithAnswerKnownDBConnection(	hDB, SQLQuery, &ans3);
		free(ans3); ans3=NULL;
		free(SQLQuery); SQLQuery=NULL;

		/*********************************************/
		/* usuniecie poprzedniego loba z bazy danych */
		/*********************************************/
		asprintf(&SQLQuery,"SELECT lo_unlink(%s);",ans2);
		if (SQLQuery==NULL)	{	BMD_FOK(NO_MEMORY);	}

		ExecuteSQLQueryWithAnswerKnownDBConnection(	hDB, SQLQuery, &ans3);
		free(ans3); ans3=NULL;
		free(SQLQuery); SQLQuery=NULL;

		bmd_ctx_destroy(&symkey_decrypted);

		printf("\n");
	}

	bmd_db_disconnect(&hDB);

	/************/
	/* porzadki */
	/************/
	free(hDB); hDB=NULL;
	bmd_ctx_destroy(&newctx); newctx=NULL;
	bmd_ctx_destroy(&oldctx); oldctx=NULL;
	free_gen_buf(&symkey_encrypted);
	free_gen_buf(&symkey_rencrypted);
	free(ans); ans=NULL;
	free(ans2); ans2=NULL;
	free(ans3); ans3=NULL;

	/************/
	/* porzadki */
	/************/
	for (i=0; i<switcher_no; i++)
	{
		free(params[i]);params[i]=NULL;
	}

	free(params); params=NULL;
	return BMD_OK;
}