Exemplo n.º 1
0
//--------------------------------------------------------------------------
void rpc_debmod_t::neterr(const char *module)
{
  int code = irs_error(irs);
  error("%s: %s", module, winerr(code));
}
Exemplo n.º 2
0
//--------------------------------------------------------------------------
void neterr(idarpc_stream_t *irs, const char *module)
{
  int code = irs_error(irs);
  qeprintf("%s: %s\n", module, winerr(code));
  exit(1);
}
Exemplo n.º 3
0
u8 *process_read(u8 *pname, int *fdlen) {

#ifdef WIN32

    HANDLE  process;
    DWORD   pid,
            size;
    int     len;
    u8      *baddr,
            *buff;

    if(!pname && !pname[0] && !pid) return(NULL);

    if(pname) {
        len = 0;
        sscanf(pname, "%lu%n", &pid, &len);
        if(len != strlen(pname)) pid = 0;
    }

    baddr = process_list(pid ? NULL : pname, &pid, &size);
    if(!baddr) {
        printf("\nError: process name/PID not found, use -p\n");
        exit(1);
    }

    fixed_rva = (u32)baddr;
    printf(
        "- pid %u\n"
        "- base address 0x%08x\n",
        (u32)pid, fixed_rva);

    process = OpenProcess(
        PROCESS_VM_READ,
        FALSE,
        pid);
    if(!process) winerr();

    buff = malloc(size);
    if(!buff) std_err();

    if(!ReadProcessMemory(
        process,
        (LPCVOID)baddr,
        buff,
        size,
        &size)
    ) winerr();

    CloseHandle(process);

#else

    pid_t   pid;
    u32     rva,
            size,
            memsize,
            data;
    u8      *buff;

    pid = atoi(pname);
    rva = 0x8048000;    // sorry, not completely supported at the moment

    fixed_rva = rva;
    printf(
        "- pid %u\n"
        "- try using base address 0x%08x\n",
        pid, fixed_rva);

    if(ptrace(PTRACE_ATTACH, pid, NULL, NULL) < 0) std_err();

    size     = 0;
    memsize  = 0;
    buff     = NULL;

    for(errno = 0; ; size += 4) {
        if(!(size & 0xfffff)) fputc('.', stdout);

        data = ptrace(PTRACE_PEEKDATA, pid, (void *)rva + size, NULL);
        if(errno) {
            if(errno != EIO) std_err();
            break;
        }

        if(size >= memsize) {
            memsize += 0x7ffff;
            buff = realloc(buff, memsize);
            if(!buff) std_err();
        }
        memcpy(buff + size, &data, 4);
    }
    fputc('\n', stdout);
    buff = realloc(buff, size);
    if(!buff) std_err();

    if(ptrace(PTRACE_DETACH, pid, NULL, NULL) < 0) std_err();

#endif

    *fdlen = size;
    return(buff);
}
Exemplo n.º 4
0
int idaapi maclnx_launch_process(
        debmod_t *debmod,
        const char *path,
        const char *args,
        const char *startdir,
        int flags,
        const char *input_path,
        uint32 input_file_crc32,
        void **child_pid)
{
  // immediately switch to the startdir because path/input_path may be relative.
  if ( startdir[0] != '\0' && chdir(startdir) == -1 )
  {
    debmod->dmsg("chdir '%s': %s\n", startdir, winerr(errno));
    return -2;
  }

  // input file specified in the database does not exist
  if ( input_path[0] != '\0' && !qfileexist(input_path) )
    return -2;

  // temporary thing, later we will retrieve the real file name
  // based on the process id
  debmod->input_file_path = input_path;
  debmod->is_dll = (flags & DBG_PROC_IS_DLL) != 0;

  // Parse the program path and extract in/out redirection info
  qstring wpath, redir_in, redir_out;
  bool append_out;
  if ( parse_apppath(path, &wpath, &redir_in, &redir_out, &append_out) )
    path = wpath.c_str();

  if ( !qfileexist(path) )
  {
    debmod->dmsg("%s: %s\n", path, winerr(errno));
    return -1;
  }

  int mismatch = 0;
  if ( !debmod->check_input_file_crc32(input_file_crc32) )
    mismatch = CRC32_MISMATCH;

  launch_process_params_t lpi;
  lpi.cb = sizeof(lpi);

  // Input redir?
  if ( !redir_in.empty() )
  {
    lpi.in_handle = open(redir_in.c_str(), O_RDONLY);
    if ( lpi.in_handle == -1 )
    {
      debmod->dmsg("Failed to open input redirection file '%s': %s\n", redir_in.c_str(), winerr(errno));
      return -1;
    }
  }

  // Output redir?
  if ( !redir_out.empty() )
  {
    lpi.out_handle = open(
      redir_out.c_str(),
      O_CREAT | O_WRONLY | (append_out ? O_APPEND : 0),
      S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    if ( lpi.out_handle == -1 )
    {
      if ( lpi.in_handle != -1 )
        close(lpi.in_handle);

      debmod->dmsg("Failed to open output redirection file '%s': %s\n", redir_out.c_str(), winerr(errno));
      return -1;
    }
    lpi.err_handle = lpi.out_handle;
  }

  qstring errbuf;
  lpi.path = path;
  lpi.args = args;
  lpi.flags = LP_TRACE;
  *child_pid = launch_process(lpi, &errbuf);

  // Close redir files
  if ( lpi.in_handle != -1 )
    close(lpi.in_handle);
  if ( lpi.out_handle != -1 )
    close(lpi.out_handle);

  if ( *child_pid == NULL )
  {
    debmod->dmsg("launch_process: %s", errbuf.c_str());
    return -1;
  }
  return 1 | mismatch;
}
Exemplo n.º 5
0
static void neterr(const char *module)
{
  int code = get_network_error();
  error("%s: %s", module, winerr(code));
}
Exemplo n.º 6
0
//-------------------------------------------------------------------------
idarpc_stream_t *init_client_irs(const char *hostname, int port_number)
{
  if ( hostname[0] == '\0' )
  {
    warning("AUTOHIDE NONE\n"
            "Please specify the hostname in Debugger, Process options");
    return NULL;
  }

  if ( !init_irs_layer() )
  {
    warning("AUTOHIDE NONE\n"
            "Could not initialize sockets: %s", winerr(get_network_error()));
    return NULL;
  }

  struct addrinfo ai, *res, *e;
  char port[33];

  // try to enumerate all possible addresses
  memset(&ai,0, sizeof(ai));
  ai.ai_flags = AI_CANONNAME;
  ai.ai_family = PF_UNSPEC;
  ai.ai_socktype = SOCK_STREAM;
  qsnprintf(port, sizeof(port), "%d", port_number);

  bool ok = false;
  const char *errstr = NULL;
  SOCKET sock = INVALID_SOCKET;
  int code = getaddrinfo(hostname, port, &ai, &res);
  if ( code != 0 )
  { // failed to resolve the name
    errstr = gai_strerror(code);
  }
  else
  {
    for ( e = res; !ok && e != NULL; e = e->ai_next )
    {
      char uaddr[INET6_ADDRSTRLEN+1];
      char uport[33];
      if ( getnameinfo(e->ai_addr, e->ai_addrlen, uaddr, sizeof(uaddr),
                       uport, sizeof(uport), NI_NUMERICHOST | NI_NUMERICSERV) != 0 )
      {
NETERR:
        errstr = winerr(get_network_error());
        continue;
      }
      sock = socket(e->ai_family, e->ai_socktype, e->ai_protocol);
      if ( sock == INVALID_SOCKET )
        goto NETERR;

      setup_irs((idarpc_stream_t*)sock);

      if ( connect(sock, e->ai_addr, e->ai_addrlen) == SOCKET_ERROR )
      {
        errstr = winerr(get_network_error());
        closesocket(sock);
        continue;
      }
      ok = true;
    }
    freeaddrinfo(res);
  }
  if ( !ok )
  {
    msg("Could not connect to %s: %s\n", hostname, errstr);
    return NULL;
  }

  return (idarpc_stream_t*)sock;
}
Exemplo n.º 7
0
BOOL
load_config(const char *config)
{
	char *section = NULL, *p;
	DWORD n, pids[100];
	BOOL result = FALSE;
	int line, chain, i;

	if (!read_config(config))
		return FALSE;

	// save config to global variable (for get_host_by_name)
	g_config_file = config;

	// load information about users
	if (!load_users(config)) {
		error("start: Fatal error! Can't load users information!\n");
		goto done;
	}

	// parse & add rules default and process-related

	section = (char *)malloc(MAX_SECTION_SIZE);
	if (section == NULL) {
		liberr("malloc");
		goto done;
	}

	GetPrivateProfileSection("_main_", section, MAX_SECTION_SIZE, config);
	
	// get lines
	chain = 0;
	for (p = section, line = 1; *p != '\0'; p += strlen(p) + 1, line++) {
		char *p2;

		if (*p == ';' || *p == '#')
			continue;		// comment

		p2 = strchr(p, '=');
		if (p2 == NULL) {
			error("%s:[_main_]:%d: invalid line format (no '=' character)", config, line);
			continue;
		}

		if (chain >= MAX_CHAINS_COUNT) {
			error("%s:[_main_]:%d: too many rules lines!", config, line);
			break;
		}

		*p2 = '\0';		// temporary kill '='
		add_rules_name(p, config, chain);
		*p2 = '=';		// recover '=' to make strlen(p) works right

		chain++;
	}

	// try to get names for existing processes
	if (pEnumProcesses != NULL && pEnumProcesses(pids, sizeof(pids), &n)) {
		DWORD i;

		n /= sizeof(DWORD);

		for (i = 0; i < n; i++) {
			char pname[MAX_PATH];
			if (get_pname_by_pid(pids[i], pname + sizeof(DWORD), sizeof(pname) - sizeof(DWORD))) {
				// send information to driver about pid and pname
				
				DWORD nn;
				
				*(DWORD *)pname = pids[i];

				if (!DeviceIoControl(g_device, IOCTL_CMD_SETPNAME, pname,
					sizeof(DWORD) + strlen(pname + sizeof(DWORD)) + 1,
					NULL, 0, &nn, NULL))
					winerr("DeviceIoControl");
			}
		}
	}

	// activate all chains!
	for (i = 0; i < chain; i++) {
		// activate chain #i
		if (!DeviceIoControl(g_device, IOCTL_CMD_ACTIVATECHAIN, &i, sizeof(i),
				NULL, 0, &n, NULL))
			winerr("start: DeviceIoControl");
	}

	result = TRUE;
done:
	free(section);
	return result;
}
//--------------------------------------------------------------------------
// Read/write a model specific register using the driver provided by WinDbg.
// The following requirements are imposed by this code:
//      - debugger module should be run with admin privileges
//      - System must be loaded with /debug switch (use bcdedit.exe to turn it on)
//      - Windbg local kernel debugging should be used at least once
// This code is based on a sample kindly provided by Alex Ionescu.
int win32_debmod_t::kldbgdrv_access_msr(SYSDBG_MSR *msr, bool write)
{
  NTSTATUS code;
  IO_STATUS_BLOCK IoStatusBlock;
  if ( DriverHandle == NULL )
  {
    //
    // Acquire 'load driver' privilege
    //
    BOOLEAN Old;
    code = RtlAdjustPrivilege(SE_LOAD_DRIVER_PRIVILEGE, TRUE, FALSE, &Old);
    if ( FAILED(code) )
    {
      dwarning("AUTOHIDE NONE\n"
               "Failed to acquire 'load driver' privilege, please run as admin!\n"
               "Error: %s\n", winerr(code));
      return code;
    }

    //
    // And need this for the driver to accept our commands
    // Additionally, system must be booted in /DEBUG mode
    //
    code = RtlAdjustPrivilege(SE_DEBUG_PRIVILEGE, TRUE, FALSE, &Old);
    if ( FAILED(code) )
    {
      dwarning("AUTOHIDE NONE\n"
               "Failed to acquire 'debug' privilege, is system booted in /debug mode?\n"
               "Error: %s\n", winerr(code));
      return code;
    }

    //
    // Now load the driver
    //
    code = NtLoadDriver(&DriverPath);
    if ( FAILED(code) && code != STATUS_IMAGE_ALREADY_LOADED )
    {
      dwarning("AUTOHIDE NONE\n"
               "Failed to load 'kldbgdrv', please use local kernel debugging at least once!\n"
               "Error: %s\n", winerr(code));
      return code;
    }

    //
    // Open a handle to it
    //
    OBJECT_ATTRIBUTES ObjectAttributes;
    InitializeObjectAttributes(&ObjectAttributes, &DriverName, OBJ_CASE_INSENSITIVE, NULL, NULL);
    code = NtCreateFile(&DriverHandle,
                        GENERIC_READ | GENERIC_WRITE,
                        &ObjectAttributes,
                        &IoStatusBlock,
                        NULL,
                        FILE_ATTRIBUTE_NORMAL,
                        0,
                        FILE_CREATE,
                        FILE_NON_DIRECTORY_FILE,
                        NULL,
                        0);
    if ( FAILED(code) )
    {
      dwarning("AUTOHIDE NONE\n"
               "Failed to open 'kldbgdrv'\n"
               "Error: %s\n", winerr(code));
      return code;
    }
  }

  //
  // Package the input parameters into the private structure
  //
  KLDD_DATA_DEBUG_CONTROL KldDebugCommand;
  KldDebugCommand.Command = write ? SysDbgWriteMsr : SysDbgReadMsr;
  KldDebugCommand.InputBuffer = msr;
  KldDebugCommand.InputBufferLength = sizeof(*msr);

  //
  // Send the request -- output isn't packaged, just specify directly the buffer
  //
  code = NtDeviceIoControlFile(DriverHandle,
                               NULL,
                               NULL,
                               NULL,
                               &IoStatusBlock,
                               KLDD_CODE_DEBUG_CONTROL,
                               &KldDebugCommand,
                               sizeof(KldDebugCommand),
                               msr,
                               sizeof(*msr));
  if ( FAILED(code) )
  {
    dwarning("AUTOHIDE NONE\n"
             "Failed to access model specific register, is system booted in /debug mode?\n"
             "Error: %s\n", winerr(code));
    return code;
  }

  // all ok!
  return code;
}
Exemplo n.º 9
0
BOOL
load_users(const char *config)
{
	BOOL result = FALSE;
	char *section, *p, *all_sids = NULL;
	int line, sid_id;
	ULONG all_sids_len = 0, all_sids_size = 0, n;

	section = (char *)malloc(MAX_SECTION_SIZE);
	if (section == NULL) {
		liberr("malloc");
		return FALSE;
	}
	GetPrivateProfileSection("_users_", section, MAX_SECTION_SIZE, config);
	
	// get lines
	sid_id = 0;
	for (p = section, line = 1; *p != '\0'; p += strlen(p) + 1, line++) {
		char *p2, *p3, *authority, *principal, domain[100];
		char *sid_buf;
		DWORD sid_size, domain_size;
		SID_NAME_USE use;

		if (*p == ';')
			continue;		// comment

		p2 = strchr(p, '=');
		if (p2 == NULL) {
			error("%s:[_users_]:%d: invalid line format (no '=' character)", config, line);
			continue;
		}

		*p2 = '\0';		// temporary kill '='

		if (sid_id != 0) {
			// not _default_
			p3 = strchr(p, '\\');
			if (p3 != NULL) {
				*p3 = '\0';

				authority = p;
				if (strcmp(authority, "NT AUTHORITY") == 0)
					authority = NULL;

				principal = p3 + 1;

			} else {
				authority = NULL;
				principal = p;
			}

			// try to get SID size
			sid_size = 0;
			domain_size = 0;

			LookupAccountName(authority, principal, NULL, &sid_size, NULL, &domain_size, &use);
		} else
			sid_size = 0;		// empty SID for default

		if (all_sids_len + sid_size + sizeof(ULONG) >= all_sids_size) {
			all_sids_size += sid_size + sizeof(ULONG) + 4096;
			all_sids = (char *)realloc(all_sids, all_sids_size);
			if (all_sids == NULL) {
				liberr("malloc");
				goto done;
			}
		}
		sid_buf = all_sids + all_sids_len;
		all_sids_len += sid_size + sizeof(ULONG);

		*(ULONG *)sid_buf = sid_size;

		if (sid_id != 0) {
			domain_size = sizeof(domain);

			if (!LookupAccountName(authority, principal,
				(PSID)(sid_buf + sizeof(ULONG)), &sid_size, domain, &domain_size, &use)) {
				winerr("LookupAccountName");
				error("%s:[_users_]:%d: Error getting SID for %s\\%s", config, line,
					(authority != NULL ? authority : "."), principal);
				goto done;
			}
			if (use != SidTypeUser && use != SidTypeWellKnownGroup) {
				error("%s:[_users_]:%d: Invalid SID type (%d) for %s\\%s", config, line, use,
					(authority != NULL ? authority : "."), principal);
				goto done;
			}

			if (p3 != NULL)
				*p3 = '\\';
		}
	
		*p2 = '=';		// recover '=' to make strlen(p) works right
		sid_id++;
	}

	// send all_sids buffer to filter driver!
	result = DeviceIoControl(g_device, IOCTL_CMD_SET_SIDS, all_sids, all_sids_len,
		NULL, 0, &n, NULL);
	if (!result)
		winerr("DeviceIoControl");

done:
	free(all_sids);
	free(section);
	return result;
}
Exemplo n.º 10
0
/* log filter request from filter driver */
void
dispatch_request(struct flt_request *request)
{
	u_long from_ip, to_ip;
	u_short from_port, to_port;
	char msg[1024], pname_buf[MAX_PATH], addr_from[100], addr_to[100], *pname, uname[200];

	if (request->log_skipped != 0) {
		if (_snprintf(msg, sizeof(msg), "SKIP\t%u", request->log_skipped) == -1)
			msg[sizeof(msg) - 1] = '\0';

		log_msg(msg, MSGTYPE_ERROR);	
	}

	if (request->pid != (ULONG)-1) {
		if (request->pname == NULL) {
			// try to resolve pid to pname
			if (get_pname_by_pid(request->pid, pname_buf + sizeof(DWORD), sizeof(pname_buf) - sizeof(DWORD))) {
				// send message to driver to send process name next time
				DWORD n;

				pname = pname_buf + sizeof(DWORD);
				*(DWORD *)pname_buf = request->pid;

				if (!DeviceIoControl(g_device, IOCTL_CMD_SETPNAME, pname_buf,
					sizeof(DWORD) + strlen(pname) + 1,
					NULL, 0, &n, NULL))
					winerr("DeviceIoControl");

			} else {
				error("PROCESS\tCan't resolve pid %u!", request->pid);
				sprintf(pname_buf, "pid:%u", request->pid);
				pname = pname_buf;
			}
		
		} else
			pname = (char *)&request[1];
	} else
		pname = "";

	if (request->sid_a != NULL) {
		SID_AND_ATTRIBUTES *sa;
		char user[100], domain[100];
		DWORD size1, size2;
		SID_NAME_USE type;

		if (request->pname != NULL) {
			char *buf = (char *)&request[1];
			buf += strlen(buf) + 1;
			sa = (SID_AND_ATTRIBUTES *)buf;
		} else
			sa = (SID_AND_ATTRIBUTES *)&request[1];

		// convert sid from relative pointer to absolute
		sa->Sid = (PSID)((char *)sa + (ULONG)sa->Sid);

		size1 = sizeof(user);
		size2 = sizeof(domain);

		if (LookupAccountSid(NULL, sa->Sid, user, &size1, domain, &size2, &type)) {

			if (_snprintf(uname, sizeof(uname), "{%s\\%s}", domain, user) == -1)
				uname[sizeof(uname) - 1] = '\0';

		} else
			strcpy(uname, "{??\\??}");		// TODO: convert SID to string

	} else
		uname[0] = '\0';
	
	// check is it request type "TYPE_RESOLVE_PID"
	if (request->type == TYPE_RESOLVE_PID) {

		if (_snprintf(msg, sizeof(msg), "PROCESS\t%u\t%s\t%s", request->pid, pname, uname) == -1)
			msg[sizeof(msg) - 1] = '\0';

		log_msg(msg, MSGTYPE_ALLOW);	
		
	} else if (request->type == TYPE_LISTEN || request->type == TYPE_NOT_LISTEN) {

		// using from_ip & from_port as listen_ip & listen_port
		from_ip = ((struct sockaddr_in *)&request->addr.from)->sin_addr.s_addr;
		from_port = ntohs(((struct sockaddr_in *)&request->addr.from)->sin_port);

		prepare_addr(addr_from, sizeof(addr_from), from_ip);
		sprintf(addr_from + strlen(addr_from), ":%d", from_port);

		if (_snprintf(msg, sizeof(msg),
			"%s\tTCP\t%s\t%s\t%s",
			(request->type == TYPE_LISTEN) ? "LISTEN" : "NOT_LISTEN",
			addr_from, pname, uname) == -1)
			msg[sizeof(msg) - 1] = '\0';

		log_msg(msg, MSGTYPE_ALLOW);	

	} else {
	
		// prepare message
		
		from_ip = ((struct sockaddr_in *)&request->addr.from)->sin_addr.s_addr;
		from_port = ntohs(((struct sockaddr_in *)&request->addr.from)->sin_port);
		to_ip = ((struct sockaddr_in *)&request->addr.to)->sin_addr.s_addr;
		to_port = ntohs(((struct sockaddr_in *)&request->addr.to)->sin_port);

		// prepare address "from" & "to"
		if (from_ip == 0) {
			// try to route "to" addr to get "from"
			from_ip = get_if_ip(to_ip);
		}
		prepare_addr(addr_from, sizeof(addr_from), from_ip);

		if (to_ip == 0) {
			// some kind of "reverse route" :-)
			to_ip = get_if_ip(from_ip);
		}
		prepare_addr(addr_to, sizeof(addr_to), to_ip);

		// add ports if nonzero
		if (from_port != 0)
			sprintf(addr_from + strlen(addr_from), ":%d", from_port);
		if (to_port != 0)
			sprintf(addr_to + strlen(addr_to), ":%d", to_port);

		if (request->result == FILTER_ALLOW || request->result == FILTER_DENY ||
			request->result == FILTER_DISCONNECT) {
			// log it! (TDI message)
			char tdi_msg[100 + RULE_ID_SIZE], size_str[64], *direction;

			switch (request->result) {
			case FILTER_ALLOW:
				strcpy(tdi_msg, "ALLOW");
				break;
			case FILTER_DENY:
				strcpy(tdi_msg, "DENY");
				break;
			default:
				strcpy(tdi_msg, "CLOSED");
			}

			if (request->result != FILTER_DISCONNECT) {
				int size;

				size_str[0] = '\0';

				switch (request->type) {
				case TYPE_CONNECT_CANCELED:
					strcat(tdi_msg, "(CANCELED)");
					break;
				case TYPE_CONNECT_RESET:
					strcat(tdi_msg, "(RESET)");
					break;
				case TYPE_CONNECT_TIMEOUT:
					strcat(tdi_msg, "(TIMEOUT)");
					break;
				case TYPE_CONNECT_UNREACH:
					strcat(tdi_msg, "(UNREACH)");
					break;
				case TYPE_CONNECT_ERROR:
					sprintf(tdi_msg + strlen(tdi_msg), "(ERR:%x)", request->status);
					break;
				case TYPE_DATAGRAM:
					size = (request->direction == DIRECTION_IN) ? request->log_bytes_in : request->log_bytes_out;
					if (size != (ULONG)-1)
						sprintf(size_str, "%u", size);

					break;
				}

				strcat(tdi_msg, "\t[");
				size = strlen(tdi_msg);
				memcpy(tdi_msg + size, request->log_rule_id, RULE_ID_SIZE);
				tdi_msg[size + RULE_ID_SIZE + 1] = '\0';	// string can be not zero-terminated
				strcat(tdi_msg, "]");
			
			} else
				sprintf(size_str, "%u/%u", request->log_bytes_out, request->log_bytes_in);

			switch (request->direction) {
			case DIRECTION_IN:
				direction = "IN";
				break;
			case DIRECTION_OUT:
				direction = "OUT";
				break;
			case DIRECTION_ANY:
				direction = "*";
				break;
			default:
				direction = "?";
			}

			if (_snprintf(msg, sizeof(msg),
				"%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s",
				tdi_msg,
				(request->proto == IPPROTO_TCP) ? "TCP" :
					(request->proto == IPPROTO_UDP ? "UDP" : "RawIP"),
				direction,
				addr_from, addr_to, size_str, pname, uname) == -1)
				msg[sizeof(msg) - 1] = '\0';

			// sound it!
			if (request->result == FILTER_DENY) {

				// TODO: try to sound it by voice of user!

				if (request->direction == DIRECTION_IN && wave_deny_in[0] != '\0')
					PlaySound(wave_deny_in, NULL, SND_FILENAME | SND_ASYNC);
				if (request->direction == DIRECTION_OUT && wave_deny_out[0] != '\0')
					PlaySound(wave_deny_out, NULL, SND_FILENAME | SND_ASYNC);
			}

			log_msg(msg, request->result == FILTER_ALLOW ? MSGTYPE_ALLOW : MSGTYPE_DENY);	

		} else if (request->result == FILTER_PACKET_LOG || request->result == FILTER_PACKET_BAD) {
			char flags[50], proto[50];

			// prepare TCP flags or ICMP type
			if (request->result == FILTER_PACKET_LOG) {
				if (request->proto == IPPROTO_TCP) {
					UCHAR th_flags = request->packet.tcp_flags;

					flags[0] = (th_flags & TH_FIN) ? 'F' : '-';
					flags[1] = (th_flags & TH_SYN) ? 'S' : '-';
					flags[2] = (th_flags & TH_RST) ? 'R' : '-';
					flags[3] = (th_flags & TH_PUSH) ? 'P' : '-';
					flags[4] = (th_flags & TH_ACK) ? 'A' : '-';
					flags[5] = (th_flags & TH_URG) ? 'U' : '-';
					flags[6] = '\0';
				
				} else if (request->proto == IPPROTO_ICMP)
					sprintf(flags, "%d.%d", request->packet.icmp_type, request->packet.icmp_code);
				else
					flags[0] = '\0';
			} else
				flags[0] = '\0';

			switch (request->proto) {
			case IPPROTO_TCP:
				if (request->packet.tcp_state > TCP_STATE_NONE &&
					request->packet.tcp_state < TCP_STATE_MAX)
					sprintf(proto, "TCP(%s)", g_tcp_states[request->packet.tcp_state]);
				else
					strcpy(proto, "TCP");
				break;
			case IPPROTO_UDP:
				strcpy(proto, "UDP");
				break;
			case IPPROTO_ICMP:
				strcpy(proto, "ICMP");
				break;
			default:
				sprintf(proto, "%d", request->proto);
			}


			// log it! (packet filter message)
			if (_snprintf(msg, sizeof(msg),
				"%s\t%s\t%s\t%s\t%s\t%u\t%s",
				(request->result == FILTER_PACKET_LOG) ? "PACKET" : "BAD_PACKET",
				proto,
				(request->direction == DIRECTION_IN) ? "IN" : "OUT",
				addr_from, addr_to,
				(request->direction == DIRECTION_IN) ? request->log_bytes_in : request->log_bytes_out,
				flags) == -1)
				msg[sizeof(msg) - 1] = '\0';

			log_msg(msg, request->result == FILTER_PACKET_LOG ? MSGTYPE_ALLOW : MSGTYPE_DENY);	
		
		}
	}
}
Exemplo n.º 11
0
// enum connections
void
enum_connect(void)
{
	ULONG size;
	struct tcp_conn_nfo *tn = NULL;
	int i, n;
	unsigned __int64 traffic[TRAFFIC_MAX];

	// try to dynamically link psapi.dll
	link_psapi();

	/* connect with driver */
	
	g_device = CreateFile(g_nfo_device_name, GENERIC_READ | GENERIC_WRITE, 
		FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
	if (g_device == INVALID_HANDLE_VALUE) {
		winerr(g_nfo_device_name);
		goto done;
	}

	/* get list of listening objects */

	size = sizeof(*tn) * 0x10000 * 3;	// this size is good enough :-)
	tn = (struct tcp_conn_nfo *)malloc(size);
	if (tn == NULL) {
		perror("malloc");
		goto done;
	}

	if (!DeviceIoControl(g_device, IOCTL_CMD_ENUM_TCP_CONN, NULL, 0,
		tn, size, &size, NULL)) {
		winerr("DeviceIoControl");
		goto done;
	}

	n = size / sizeof(*tn);

	// sort this list!
	qsort(tn, n, sizeof(*tn), compare_tn);

	for (i = 0; i < n ; i++) {
		char pname[MAX_PATH];

		if (tn[i].state >= TCP_STATE_MAX)
			tn[i].state = 0;
		
		// resolve pid!
		if (!get_pname_by_pid(tn[i].pid, pname, sizeof(pname)))
			pname[0] = '\0';

		printf("%s\t%d.%d.%d.%d:%d\t%d.%d.%d.%d:%d\t%s (%d)\t%u/%u\n",
			g_tcp_states[tn[i].state],
			PRINT_IP_ADDR(tn[i].laddr), ntohs(tn[i].lport),
			PRINT_IP_ADDR(tn[i].raddr), ntohs(tn[i].rport),
			pname, tn[i].pid,
			tn[i].bytes_out, tn[i].bytes_in);
	}

	// output traffic counters
	get_traffic_stats(traffic);

	printf(
		"\n"
		"Traffic counters (out/in):\n"
		"    Total:   %I64u/%I64u\n"
		"    Counted: %I64u/%I64u\n",
		traffic[TRAFFIC_TOTAL_OUT], traffic[TRAFFIC_TOTAL_IN],
		traffic[TRAFFIC_COUNTED_OUT], traffic[TRAFFIC_COUNTED_IN]);

done:
	free(tn);
	if (g_device != INVALID_HANDLE_VALUE)
		CloseHandle(g_device);
}
Exemplo n.º 12
0
int
start(const char *config)
{
	int result = FALSE;
	WSADATA wsd;
	DWORD thread_id;

	WSAStartup(MAKEWORD(1, 1), &wsd);

	// try to dynamically link psapi.dll
	link_psapi();

	/* connect with driver */
	
	g_device = CreateFile(g_device_name, GENERIC_READ | GENERIC_WRITE, 
		FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
	if (g_device == INVALID_HANDLE_VALUE) {
		winerr(g_device_name);
		goto done;
	}

	/* open event for driver communication */

	g_event = OpenEvent(SYNCHRONIZE, FALSE, "tdifw_request");
	if (g_event == NULL) {
		winerr("start: OpenEvent");
		goto done;
	}

	/* load config & rules */

	if (!load_config(config))
		goto done;

	/* start dispatcher thread */

	g_exit_event = CreateEvent(NULL, TRUE, FALSE, NULL);
	if (g_exit_event == NULL) {
		winerr("start: CreateEvent");
		goto done;
	}

	g_disp_buf = (char *)malloc(DISP_BUF_SIZE);
	if (g_disp_buf == NULL) {
		liberr("start: malloc");
		goto done;
	}

	log_msg("START", MSGTYPE_ALLOW);

	g_dispatcher = lib_CreateThread(NULL, 0, dispatcher, (LPVOID)config, 0, &thread_id);
	if (g_dispatcher == NULL) {
		winerr("start: lib_CreateThread");
		goto done;
	}
	
	result = TRUE;

done:
	if (!result)
		stop();

	return result;
}
Exemplo n.º 13
0
// enum listening objects
void
enum_listen(void)
{
	ULONG size;
	struct listen_nfo *ln = NULL;
	int i, n;

	// try to dynamically link psapi.dll
	link_psapi();

	/* connect with driver */
	
	g_device = CreateFile(g_nfo_device_name, GENERIC_READ | GENERIC_WRITE, 
		FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
	if (g_device == INVALID_HANDLE_VALUE) {
		winerr(g_nfo_device_name);
		goto done;
	}

	/* get list of listening objects */

	size = sizeof(*ln) * 0x10000 * 3;	// this size is good enough :-)
	ln = (struct listen_nfo *)malloc(size);
	if (ln == NULL) {
		perror("malloc");
		goto done;
	}

	if (!DeviceIoControl(g_device, IOCTL_CMD_ENUM_LISTEN, NULL, 0,
		ln, size, &size, NULL)) {
		winerr("DeviceIoControl");
		goto done;
	}

	n = size / sizeof(*ln);

	// sort this list!
	qsort(ln, n, sizeof(*ln), compare_ln);

	printf("IPProto\tAddress:Port\tProcess (pid)\n");
	printf("-------\t------------\t---------------------------------------------\n");

	for (i = 0; i < n ; i++) {
		char *proto, pname[MAX_PATH];
		
		if (ln[i].ipproto == IPPROTO_TCP)
			proto = "TCP";
		else if (ln[i].ipproto == IPPROTO_UDP)
			proto = "UDP";
		else if (ln[i].ipproto == IPPROTO_IP)
			proto = "RawIP";
		else
			proto = "?";

		// resolve pid!
		if (!get_pname_by_pid(ln[i].pid, pname, sizeof(pname)))
			pname[0] = '\0';

		printf("%s\t%d.%d.%d.%d:%d\t%s (%d)\n",
			proto, PRINT_IP_ADDR(ln[i].addr), ntohs(ln[i].port), pname, ln[i].pid);
	}

done:
	free(ln);
	if (g_device != INVALID_HANDLE_VALUE)
		CloseHandle(g_device);
}
Exemplo n.º 14
0
//--------------------------------------------------------------------------
// ipath==input file path
static bool ask_user_and_copy(const char *ipath)
{
  // check if the input file exists at the current dir of the remote host
  const char *input_file = ipath;
#if DEBUGGER_ID != DEBUGGER_ID_ARM_EPOC_USER
  input_file = qbasename(input_file);
#endif
  int fn = -1;
  // try to open remote file in the current dir if not tried before
  if ( input_file != ipath )
    fn = s_open_file(input_file, NULL, true);
  if ( fn != -1 )
  {
    s_close_file(fn);
    switch ( askbuttons_c("~U~se found",
                          "~C~opy new",
                          "Cancel",
                          1,
                          "IDA could not find the remote file %s.\n"
                          "But it could find remote file %s.\n"
                          "Do you want to use the found file?",
                          ipath, input_file) )
    {
      case 1:
        set_root_filename(input_file);
        return true;
      case -1:
        return false;
    }
    // the user wants to overwrite the old file
  }
  else
  {
    if ( askyn_c(1, "HIDECANCEL\n"
                    "The remote file %s could not be found.\n"
                    "Do you want IDA to copy the executable to the remote computer?",
                    ipath) <= 0 )
      return false;
  }

  // We are to copy the input file to the remote computer's current directory
  const char *lname = ipath;
  // check if the file path is valid on the local system
  if ( !qfileexist(lname) )
  {
    lname = askfile_c(false, lname, "Please select the file to copy");
    if ( lname == NULL )
      return false;
  }
#if DEBUGGER_ID == DEBUGGER_ID_ARM_EPOC_USER
  const char *rname = input_file;
#else
  const char *rname = qbasename(lname);
#endif
  int code = copy_to_remote(lname, rname);
  if ( code != 0 )
  {
#if DEBUGGER_ID == DEBUGGER_ID_ARM_WINCE_USER
    // Windows CE does not have errno and uses GetLastError()
    const char *err = winerr(code);
#else
    const char *err = qerrstr(code);
#endif
    warning("Failed to copy %s -> %s\n%s", lname, rname, err);
  }
  set_root_filename(rname);
  return true;
}
Exemplo n.º 15
0
BOOL
add_rules_name(const char *main_name, const char *config, int chain)
{
	char buf[1024], *p, *p2, *section = NULL;
	BOOL result = FALSE;
	DWORD n;

	section = (char *)malloc(MAX_SECTION_SIZE);
	if (section == NULL) {
		liberr("malloc");
		goto done;
	}

	/* 1. get ruleset string */

	GetPrivateProfileString("_main_", main_name, "", buf, sizeof(buf), config);

	if (*buf == '\0')
		goto done;		// no rules

	// reset all rules for chain
	if (!DeviceIoControl(g_device, IOCTL_CMD_CLEARCHAIN, &chain, sizeof(chain),
		NULL, 0, &n, NULL)) {
		winerr("DeviceIoControl");
		goto done;
	}

	if (chain != 0) {
		// set chain name
		int len = sizeof(int) + MAX_PATH;
		char *data = (char *)malloc(len);
		if (data == NULL) {
			liberr("malloc");
			goto done;
		}

		*(int *)data = chain;

		// try to extract environment variables from p to main_name
		ExpandEnvironmentStrings(main_name, data + sizeof(int), MAX_PATH);

		len = sizeof(int) + strlen(data + sizeof(int)) + 1;
		
		if (!DeviceIoControl(g_device, IOCTL_CMD_SETCHAINPNAME, data, len,
			NULL, 0, &n, NULL)) {
			winerr("DeviceIoControl");
			free(data);
			goto done;
		}
		free(data);
	}

	/* 2. for each word in main_name string */

	p = buf;
	
	while (p != NULL) {

		p2 = strchr(p, ' ');
		if (p2 != NULL) {
			while (*p2 == ' ')
				*(p2++) = '\0';
		}
		
		if (*p != '\0') {
			// get section by name in p
			GetPrivateProfileSection(p, section, MAX_SECTION_SIZE, config);
			if (*section == '\0')
				error("\"%s\": unexistant or empty section %s", config, p);
			else
				add_rules(config, section, p, chain);
		}

		p = p2;
	}

	result = TRUE;

done:
	free(section);
	return result;
}
Exemplo n.º 16
0
//----------------------------------------------------------------------
// Display a system error message
static void error_msg(const char *name)
{
  int code = GetLastError();
  if ( code != 0 )
    msg("%s: %s\n", name, winerr(code));
}
Exemplo n.º 17
0
int idaapi maclnx_launch_process(
        debmod_t *debmod,
        const char *path,
        const char *args,
        const char *startdir,
        int flags,
        const char *input_path,
        uint32 input_file_crc32,
        void **child_pid)
{
  // prepare full path if the input_path is relative
  char full_input[QMAXPATH];
  if ( startdir[0] != '\0' && !qisabspath(input_path) )
  {
    qmake_full_path(full_input, sizeof(full_input), input_path);
    input_path = full_input;
  }

  // input file specified in the database does not exist
  if ( input_path[0] != '\0' && !qfileexist(input_path) )
  {
    debmod->dwarning("AUTOHIDE NONE\nInput file is missing: %s", input_path);
    return -2;
  }

  // temporary thing, later we will retrieve the real file name
  // based on the process id
  debmod->input_file_path = input_path;
  debmod->is_dll = (flags & DBG_PROC_IS_DLL) != 0;

  if ( !qfileexist(path) )
  {
    debmod->dmsg("%s: %s\n", path, winerr(errno));
    return -1;
  }

  int mismatch = 0;
  if ( !debmod->check_input_file_crc32(input_file_crc32) )
    mismatch = CRC32_MISMATCH;

#ifdef __EA64__
  bool dbg_srv_64 = true;
#else
  bool dbg_srv_64 = false;
  if ( (flags & DBG_PROC_64BIT) != 0 )
  {
    debmod->dwarning("Cannot debug a 64bit process with the 32bit debugger server, sorry\n");
    return -1;
  }
#endif

  launch_process_params_t lpi;
  lpi.path = path;
  lpi.args = args;
  lpi.startdir = startdir[0] != '\0' ? startdir : NULL;
  lpi.flags = LP_NO_ASLR | LP_DETACH_TTY;
  if ( (flags & DBG_NO_TRACE) == 0 )
    lpi.flags |= LP_TRACE;

  if ( (flags & DBG_PROC_64BIT) != 0 )
  {
    lpi.flags |= LP_LAUNCH_64_BIT;
  }
  else if ( (flags & DBG_PROC_32BIT) != 0 )
  {
    lpi.flags |= LP_LAUNCH_32_BIT;
  }
  else
  {
    lpi.flags |= dbg_srv_64 ? LP_LAUNCH_64_BIT : LP_LAUNCH_32_BIT;
    debmod->dmsg("Launching as %sbit process\n", dbg_srv_64 ? "64" : "32");
  }

  qstring errbuf;
  *child_pid = launch_process(lpi, &errbuf);

  if ( *child_pid == NULL )
  {
    debmod->dmsg("launch_process: %s", errbuf.c_str());
    return -1;
  }
  return 1 | mismatch;
}