Example #1
0
/**
 * @brief Waits for a certain response type. This method waits for a maximum of
 * ms_timeout milliseconds for a specified response command.
 * @param cmd command to wait for, or CMD_UNKNOWN to take any command.
 * @param response struct to copy received command into.
 * @param ms_timeout display message after 2 seconds
 * @return true if command was returned, otherwise false
 */
bool WaitForResponseTimeoutW(uint32_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning) {
  
	UsbCommand resp;

	if (response == NULL)
		response = &resp;

	uint64_t start_time = msclock();
	
	// Wait until the command is received
	while (true) {

		while ( getCommand(response) ) {
			if (cmd == CMD_UNKNOWN || response->cmd == cmd)
				return true;			
		}

		if (msclock() - start_time > ms_timeout)
			break;
		
		if (msclock() - start_time > 3000 && show_warning) {
			// 3 seconds elapsed (but this doesn't mean the timeout was exceeded)
			PrintAndLogEx(NORMAL, "Waiting for a response from the proxmark...");
			PrintAndLogEx(NORMAL, "You can cancel this operation by pressing the pm3 button");
			show_warning = false;
		}
	}
	return false;
}
Example #2
0
bool dl_it(uint8_t *dest, uint32_t bytes, uint32_t start_index, UsbCommand *response, size_t ms_timeout, bool show_warning, uint32_t rec_cmd) {
	
	uint32_t bytes_completed = 0;
	uint64_t start_time = msclock();
	
	while (true) {
		
		if (getCommand(response)) {

			// sample_buf is a array pointer, located in data.c
			// arg0 = offset in transfer. Startindex of this chunk
			// arg1 = length bytes to transfer
			// arg2 = bigbuff tracelength (?)			
			if (response->cmd == rec_cmd) {
				
				uint32_t offset = response->arg[0];
				uint32_t copy_bytes = MIN(bytes - bytes_completed, response->arg[1]);
				//uint32_t tracelen = c->arg[2];
				
				// extended bounds check1.  upper limit is USB_CMD_DATA_SIZE
				// shouldn't happen
				copy_bytes = MIN(copy_bytes, USB_CMD_DATA_SIZE);
				
				// extended bounds check2. 
				if ( offset + copy_bytes > bytes ) {
					PrintAndLogEx(FAILED, "ERROR: Out of bounds when downloading from device,  offset %u | len %u | total len %u > buf_size %u", offset, copy_bytes,  offset+copy_bytes,  bytes);
					break;
				}			
		
				memcpy(dest + offset, response->d.asBytes, copy_bytes);
				bytes_completed += copy_bytes;
			} else if (response->cmd == CMD_ACK) {
				return true;
			}
		}
		
		if (msclock() - start_time > ms_timeout) {
			PrintAndLogEx(FAILED, "Timed out while trying to download data from device");
			break;
		}
		
		if (msclock() - start_time > 3000 && show_warning) {
			// 3 seconds elapsed (but this doesn't mean the timeout was exceeded)
			PrintAndLogEx(NORMAL, "Waiting for a response from the proxmark...");
			PrintAndLogEx(NORMAL, "You can cancel this operation by pressing the pm3 button");
			show_warning = false;
		}
	}
	return false;
}
void linklocal_msg_timer(cyg_handle_t handle, cyg_addrword_t ptr){
	int need_post_linklocal = ip_conflict_cnt;

	if( start_timer_flag == 0 )
	{
		linklocal_start_time = msclock(); 
		start_timer_flag = 1;
	}
	
	linklocal_stop_time = msclock();
	
	if( (linklocal_stop_time - linklocal_start_time) > 10000)
	{
		ip_conflict_cnt = 0; // reset counter anyway
		start_timer_flag = 0;
		linklocal_stop_time = 0; 
		cyg_alarm_delete(hAlarm);				//eCos
		cyg_clock_delete(hSysClk);			    //eCos
		cyg_counter_delete(hCounter);			//eCos		
	}
	

    if( (LinkLocal_get_current_state() != IDLE) )
    {
    	ip_conflict_cnt = 0; // reset counter anyway
    	start_timer_flag = 0; 
    	cyg_semaphore_post(&linklocal_conflict);
    	cyg_alarm_delete(hAlarm);				//eCos
		cyg_clock_delete(hSysClk);			    //eCos
		cyg_counter_delete(hCounter);			//eCos
    }	
	
	if ( (need_post_linklocal > 1) && (LinkLocal_get_current_state() == IDLE) ){
//		cyg_semaphore_post(&linklocal_conflict);//signal to inform ip conflict
		ip_conflict_cnt = 0; // reset counter anyway
		start_timer_flag = 0; 
		
		if( ReadPrintStatus() != 3 )
		{	
		LinkLocal_set_state(RETRY);	
		cyg_semaphore_post(&linklocal_sem); //signal to restart set link local ip
		}
		cyg_alarm_delete(hAlarm);				//eCos
		cyg_clock_delete(hSysClk);			    //eCos
		cyg_counter_delete(hCounter);			//eCos		
	}	   
}
Example #4
0
/*===========================================================================
FUNCTION LCP_OPENING()

DESCRIPTION
  This function will be called after configuration negotiation is complete
  and PPP completes the Establish phase. It can go into the network or the
  authentication phase after that.

 If the network negotiated authentication or we need to authenticate the
 peer, then ppp will transition to the authentication phase. Otherwise, PPP
 will transition to the network phase without doing authentication.

DEPENDENCIES
  None

RETURN VALUE
  None

SIDE EFFECTS
  None
===========================================================================*/
static void lcp_opening
(
  ppp_fsm_type *fsm_ptr /* ptr to a FSM structure */
)
{
  ppp_type *ppp_cb_ptr;
  lcp_value_type *rmt_work_ptr = (lcp_value_type*)fsm_ptr->remote.work_pdv;
  ppp_event_payload_type  ppp_event_payload;
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/

  if(fsm_ptr == NULL || fsm_ptr->device >= PPP_MAX_DEV )
  {
    MSG_ERROR("Invalid fsm_ptr", 0, 0, 0);
    return;
  }

  MSG_MED("dev %d LCP Up!",fsm_ptr->device, 0, 0);
  ppp_cb_ptr = &(ppp_cb_array[fsm_ptr->device]);
  ppp_cb_ptr->upsince = msclock();

  /*-------------------------------------------------------------------------
    Set the default value for the remote MRU if it was not negotiated
  -------------------------------------------------------------------------*/
  if(!(fsm_ptr->remote.work & LCP_N_MRU))
  {
    rmt_work_ptr->mru = ppp_cb_ptr->rx_iface_ptr->v4_net_info.mtu;
  }

  /*-------------------------------------------------------------------------
    If it has changed, set new Max Transmission Unit for outgoing packets
  -------------------------------------------------------------------------*/
  if(ppp_cb_ptr->rx_iface_ptr->v4_net_info.mtu != rmt_work_ptr->mru)
  {
    ppp_cb_ptr->rx_iface_ptr->v4_net_info.mtu = rmt_work_ptr->mru;
  }

  /*-------------------------------------------------------------------------
    Delay transition to next phase to allow remote ACCM to settle
  -------------------------------------------------------------------------*/
  pppi_discard(fsm_ptr->device, NULL);

  /*-------------------------------------------------------------------------
    Fill in the fileds of ppp_event_payload
  -------------------------------------------------------------------------*/
  ppp_event_payload.ppp_event_device = fsm_ptr->device;
  ppp_event_payload.ppp_event_protocol = PPP_EV_LCP;
  ppp_event_payload.ppp_event_prev_state = PS_PPP_EVENT_UNKNOWN;
  ppp_event_payload.ppp_event_state = PS_PPP_EVENT_OPEN;
  event_report_payload(EVENT_PPP, 
                       sizeof(ppp_event_payload),
                       &ppp_event_payload);

  /*-------------------------------------------------------------------------
    kick off authentication phase
  -------------------------------------------------------------------------*/
  ppp_auth_start(fsm_ptr->device);

} /* lcp_opening() */
/****************************************************************************
do a switch on the message type, and return the response size
****************************************************************************/
static int switch_message(int type,char *inbuf,char *outbuf,
							int size,int bufsize, int ProcSockID, int threadid)
{
  int outsize = 0;
  static int num_smb_messages = 
    sizeof(smb_messages) / sizeof(struct smb_message_struct);
  int match;
//  extern int Client;
  connection_struct *conn;
//0703  last_message = type;

  /* make sure this is an SMB packet */
  if (strncmp(smb_base(inbuf),"\377SMB",4) != 0)
  {
//os  	kwait(NULL);
	cyg_thread_yield();
    return(-1);
  }

  for (match=0;match<num_smb_messages;match++)
    if (smb_messages[match].code == type)
      break;

  if (match == num_smb_messages)
  {
//Jesse      outsize = reply_unknown(inbuf,outbuf);
outsize = ERROR(ERRSRV,ERRaccess);
  }
  else
  {
    if (smb_messages[match].fn)
    {
//0609      int flags = smb_messages[match].flags;
//0609      static uint16 last_session_tag = UID_FIELD_INVALID;
	  uint16 session_tag = SVAL(inbuf,smb_uid);	

      /* Ensure this value is replaced in the incoming packet. */
      SSVAL(inbuf,smb_uid,session_tag);

//0703      last_inbuf = inbuf;
	  conn = conn_find(SVAL(inbuf, smb_tid), threadid);

	  if (conn)
	  	  conn->lastused = (msclock() /1000);  //add by ron 7/5/2001

      outsize = smb_messages[match].fn(conn,inbuf,outbuf,size,bufsize, ProcSockID, 
	   								   threadid);
    }
    else
    {
      outsize = reply_unknown(inbuf,outbuf);
    }
  }

  return(outsize);
}
int should_fail_next_srvsvc_open(const char *pipename, int threadid)
{

//  DEBUG(10,("should_fail_next_srvsvc_open: fail = %d, pipe = %s\n",
//    (int)fail_next_srvsvc, pipename));

  if(fail_next_srvsvc && ((msclock()/1000) > fail_time + HACK_FAIL_TIME)) {
  	  fail_next_srvsvc = False;
      fail_time = (msclock()/1000);
//    DEBUG(10,("should_fail_next_srvsvc_open: End of timeout close of \\srvsvc pipe for print fix.\n"));
  }

  if(fail_next_srvsvc && !strcmp(pipename, "srvsvc")) {
      fail_next_srvsvc = False;
//    DEBUG(10,("should_fail_next_srvsvc_open: Deliberately failing open of \\srvsvc pipe for print fix.\n"));
      return True;
  }
  return False;
}
/* I do not declare fail_next_srvsvc[[NUM_SMBTHREAD], since the action that WinXP 
   get printing information will send spools pipe will be rejected by me. ""BUT"" he send
   next srvsvc in different connection. That thread fail_next_srvsvc[threadid] != 1 (since 
   I did not set in this thread). Maybe I set fail_next_srvsvc[i] at previous thread, 
   and it can not reject the next srvsvc pipe, and WinXP get printer information fail.   Ron 3/8/2002  */
   
int fail_next_srvsvc = False; 
static time_t fail_time;
extern int chain_size[];

#define HACK_FAIL_TIME 2 /* In seconds. */
void fail_next_srvsvc_open(int threadid)
{
  /* Check client is WinNT proper; Win2K doesn't like Jeremy's hack - matty */
//0611  if (get_remote_arch() != RA_WINNT)
//    return;

  fail_next_srvsvc = True;
  fail_time = (msclock()/1000);
//  DEBUG(10,("fail_next_srvsvc_open: setting up timeout close of \\srvsvc pipe for print fix.\n"));
}
Example #8
0
size_t COMIOCALL comReadBuf(COM_HANDLE handle, char* buf, size_t buflen, const char* terminators, int timeout)
{
	BYTE		ch;
	size_t		len=0;
	msclock_t	start=msclock();

	while(len < buflen) {
		if(!comReadByte(handle, &ch)) {
			if(msclock()-start >= timeout)
				break;
			YIELD();
			continue;
		}
		if(len && terminators!=NULL && strchr(terminators, ch)!=NULL)
			break;
		buf[len++]=ch;
	}

	return len;
}
Example #9
0
/*
=============================================================================
This routine bails from the app in case of a panic.
=============================================================================
*/
void bail(char *msg)
{
	int endtime;

	endtime=msclock();
	puts(msg);
	printf("%-22s A:%02X F:%02X B:%02X C:%02X D:%02X E:%02X H:%02X L:%02X PC:%04X SP:%04X IM:%02X *SP:%04X\n",op,A,F,B,C,D,E,H,L,PC,SP,IM,MEM16(SP));
	printf("Start: %d  End: %d\n",starttime,endtime);
	printf("Time: %f\n",((double)(endtime-starttime))/1000);
	printf("MHz: %f\n",((UINT64)cycles/(((double)(endtime-starttime))/1000))/1000000);

	exit(1);
}
Example #10
0
static BOOL list_wait(link_list_t* list, long timeout)
{
#if defined(LINK_LIST_THREADSAFE)
	if(timeout<0)	/* infinite */
		return listSemWait(list);
	if(timeout==0)	/* poll */
		return listSemTryWait(list);

	return listSemTryWaitBlock(list,timeout);
#else
	clock_t	start;
	long	count;
	
	start=msclock();
	while((count=listCountNodes(list))==0) {
		if(timeout==0)
			break;
		if(timeout>0 && msclock()-start > timeout)
			break;
		YIELD();
	}
	return(INT_TO_BOOL(count));
#endif
}
Example #11
0
/*===========================================================================
FUNCTION LCP_CHECK()

DESCRIPTION
  This function will Check the options, updating the working values.

DEPENDENCIES
  None

RETURN VALUE
  Returns -1 if ran out of data, ACK/NAK/REJ as appropriate.

SIDE EFFECTS
  None
===========================================================================*/
static int lcp_check
(
  ppp_fsm_type      *fsm_ptr,
  struct option_hdr *ohp,
  dsm_item_type    **bpp,
  int                request
)
{
  lcp_value_type * lworkp; 
  lcp_value_type * rworkp; 
  ppp_fsm_side_type * side_p;
  lcp_value_type * s_want_ptr;
  lcp_value_type * s_work_ptr;
  int used = 0;
  int option_result = CONFIG_ACK;   /* Assume good values   */
  int n_type = 0;
  int16 rx_chap_digest; /* chap digest from peer */

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

  if( bpp == NULL )
  {
    MSG_ERROR("Invalid DSM", 0, 0, 0);
    return -1;
  }

  if( fsm_ptr == NULL || 
      ohp == NULL || 
      ohp->length < OPTION_HDR_LEN ||
      fsm_ptr->device >= PPP_MAX_DEV )
  {
    MSG_ERROR("Invalid args", 0, 0, 0);
    dsm_free_packet(bpp);
    return -1;
  }

  used = ohp->length - OPTION_HDR_LEN; 
  n_type = fsm_n_option(fsm_ptr->pdc,ohp->type);
  lworkp = (lcp_value_type *)fsm_ptr->local.work_pdv;
  rworkp = (lcp_value_type *)fsm_ptr->remote.work_pdv;
  side_p =
     (ppp_fsm_side_type *)(request ? &(fsm_ptr->remote) : &(fsm_ptr->local));
  s_want_ptr = (lcp_value_type *)side_p->want_pdv;
  s_work_ptr = (lcp_value_type *)side_p->work_pdv;

  /*-------------------------------------------------------------------------
    see if we allow this option
  -------------------------------------------------------------------------*/
  if (ohp->type > LCP_OPTION_LIMIT        ||
      ohp->length < option_length[n_type] ||
      !((side_p->will | side_p->want) & (1 << n_type)))
  {
    /*-----------------------------------------------------------------------
      toss any bytes in option
    -----------------------------------------------------------------------*/
    while( used-- > 0 )
    {
      if ( dsm_pull8(bpp) == -1 )
      {
        return -1;
      }
    }
    return CONFIG_REJ;

  } /* if(unsupported option) */

  switch(ohp->type)
  {
  case LCP_MRU: /* max receive unit */
    s_work_ptr->mru = dsm_pull16(bpp);
    used -= 2;

    /*-----------------------------------------------------------------------
      Check if new value is appropriate
   -----------------------------------------------------------------------*/
    if(s_work_ptr->mru < LCP_MRU_LO)
    {
      s_work_ptr->mru   = LCP_MRU_LO;
      option_result = CONFIG_NAK;
    }
    else if (s_work_ptr->mru > LCP_MRU_HI)
    {
      s_work_ptr->mru = LCP_MRU_HI;
      option_result = CONFIG_NAK;
    }
      
    if(request                    &&
       (side_p->want & LCP_N_MRU) &&
       s_work_ptr->mru > s_want_ptr->mru)
    {
      /*---------------------------------------------------------------------
        send a smaller packet anyway
      -----------------------------------------------------------------------*/
      s_work_ptr->mru = s_want_ptr->mru;
    }
    break;

  case LCP_ACCM: /* async control character map */
    s_work_ptr->accm = dsm_pull32(bpp);
    used -= 4;

    /*-----------------------------------------------------------------------
      Remote host may ask to escape more control characters than we require,
      but must escape at least the control chars that we require.
    -----------------------------------------------------------------------*/
    if ((side_p->want & LCP_N_ACCM) &&
        s_work_ptr->accm != (s_work_ptr->accm | s_want_ptr->accm))
    {
      s_work_ptr->accm |= s_want_ptr->accm;
      option_result = CONFIG_NAK;
    }
    break;

  case LCP_AP: /* Authentication protocol */
    s_work_ptr->authentication = dsm_pull16(bpp); /* get the protocol */
    used -= 2;

    /*-----------------------------------------------------------------------
      Check if requested authentication protocol is PAP or CHAP or NONE
    -----------------------------------------------------------------------*/
    switch (s_work_ptr->authentication)
    {
    case PPP_PAP_PROTOCOL:
      /*---------------------------------------------------------------------
        Setting it to send PAP pkts in auth. phase.
      ---------------------------------------------------------------------*/
      ppp_cb_array[fsm_ptr->device].auth.mode = PPP_DO_PAP;
      MSG_MED(" Received Config. Req. with PAP option",0,0,0);
      break;

    case PPP_CHAP_PROTOCOL:
      /*---------------------------------------------------------------------
        Setting it to send CHAP pkts in auth. phase.
      ---------------------------------------------------------------------*/
      ppp_cb_array[fsm_ptr->device].auth.mode  = PPP_DO_CHAP;

      /*---------------------------------------------------------------------
        In the incoming packet the CHAP protocol has algorithm field attached
        to it, i.e. C223 for CHAP and 05 for MD5 or 80 for MD4.  Since the
        current implementation implements only MD5, check if the algorithm is
        MD5.

        Since we pulled out one more byte from the incoming packet reduce the
        used field by one.

        If the algorithm is not MD5, then send a Config NAK to the base
        station and request for the MD5.
      ---------------------------------------------------------------------*/
      rx_chap_digest = dsm_pull8(bpp);
      if(rx_chap_digest == -1)
      {
        return -1;
      }
      used--;
      if((s_work_ptr->chap_digest = (uint8)rx_chap_digest) != PPP_CHAP_MD5)
      {
        s_work_ptr->chap_digest = PPP_CHAP_MD5;
        option_result = CONFIG_NAK;
      }
      MSG_MED("dev %d got C-req with chap digest: %d",
              fsm_ptr->device,
              rx_chap_digest,
              0);
      break;

    default:
      /*---------------------------------------------------------------------
        Got an unrecognized authentication protocol.  Ask for CHAP/PAP in the
        nak and Send a config_nak which asks for CHAP as the authentication
        protocol.
      ---------------------------------------------------------------------*/
      MSG_MED("Rxd Unknown Auth proto:0x%x ",s_work_ptr->authentication,0,0);
      s_work_ptr->authentication = PPP_CHAP_PROTOCOL;
      s_work_ptr->chap_digest    = PPP_CHAP_MD5;
      option_result = CONFIG_NAK;
      break;
    } /* switch(auth type in req) */
    break; /* case LCP_AP */

  case LCP_MAGIC: /* magic number */
    s_work_ptr->magic_number = dsm_pull32(bpp);
    used -= 4;

    /*-----------------------------------------------------------------------
      Ensure that magic numbers are different
    -----------------------------------------------------------------------*/
    if ( s_work_ptr->magic_number == 0L )
    {
      s_work_ptr->magic_number = (uint32)s_work_ptr;
      option_result = CONFIG_NAK;
    } else if ( rworkp->magic_number == lworkp->magic_number )
    {
      s_work_ptr->magic_number += msclock();
      option_result = CONFIG_NAK;
    }
    break;

  case LCP_PFC:  /* protocol field compression */
  case LCP_ACFC: /* addr/control field compression */
    /* nothing to store here */
    break;

  default:
    option_result = CONFIG_REJ;
    break;
  } /* switch(option type) */

  if ( used < 0 )
  {
    return -1;
  }

  /*-------------------------------------------------------------------------
    if there are extra bytes in option toss them.
  -------------------------------------------------------------------------*/
  if ( used > 0 )
  {
    while( used-- > 0 )
    {
      if ( dsm_pull8(bpp) == -1 )
      {
        return -1;
      }
    }
  }

  return (option_result);

} /* lcp_check() */
Example #12
0
int recv_byte(void* unused, unsigned timeout)
{
	int			i;
	long		t;
	uchar		ch;
	fd_set		socket_set;
	time_t		end;
	struct timeval	tv;
	static uchar	telnet_cmd;
	static int		telnet_cmdlen;

	end=msclock()+(timeout*MSCLOCKS_PER_SEC);
	while(!terminate) {

		FD_ZERO(&socket_set);
#ifdef __unix__
		if(stdio)
			FD_SET(STDIN_FILENO,&socket_set);
		else
#endif
			FD_SET(sock,&socket_set);
		if((t=end-msclock())<0) t=0;
		tv.tv_sec=t/MSCLOCKS_PER_SEC;
		tv.tv_usec=0;

		if((i=select(sock+1,&socket_set,NULL,NULL,&tv))<1) {
			if(i==SOCKET_ERROR) {
				lprintf(LOG_ERR,"ERROR %d selecting socket", ERROR_VALUE);
			}
			if(timeout)
				lprintf(LOG_WARNING,"Receive timeout (%u seconds)", timeout);
			return(NOINP);
		}
		
#ifdef __unix__
		if(stdio)
			i=read(STDIN_FILENO,&ch,sizeof(ch));
		else
#endif
			i=recv(sock,&ch,sizeof(ch),0);

		if(i!=sizeof(ch)) {
			if(i==0) {
				lprintf(LOG_WARNING,"Socket Disconnected");
			} else
				lprintf(LOG_ERR,"recv error %d (%d)",i,ERROR_VALUE);
			return(NOINP); 
		}

		if(telnet) {
			if(ch==TELNET_IAC) {
#if DEBUG_TELNET
				lprintf(LOG_DEBUG,"T<%s> ",telnet_cmd_desc(ch));
#endif
				if(telnet_cmdlen==0) {
					telnet_cmdlen=1;
					continue;
				}
				if(telnet_cmdlen==1) {
					telnet_cmdlen=0;
					if(debug_rx)
						lprintf(LOG_DEBUG,"RX: %s",chr(TELNET_IAC));
					return(TELNET_IAC);
				}
			}
			if(telnet_cmdlen) {
				telnet_cmdlen++;
#if DEBUG_TELNET
				if(telnet_cmdlen==2)
					lprintf(LOG_DEBUG,"T<%s> ",telnet_cmd_desc(ch));
				else
					lprintf(LOG_DEBUG,"T<%s> ",telnet_opt_desc(ch));
#endif
				if(debug_telnet && telnet_cmdlen==3)
					lprintf(LOG_DEBUG,"Received telnet command: %s %s"
						,telnet_cmd_desc(telnet_cmd),telnet_opt_desc(ch));
				if(telnet_cmdlen==3 && telnet_cmd==TELNET_DO)
					send_telnet_cmd(sock, TELNET_WILL,ch);
	/*
				else if(telnet_cmdlen==3 && telnet_cmd==TELNET_WILL)
					send_telnet_cmd(sock, TELNET_DO,ch);
	*/
				telnet_cmd=ch;
				if((telnet_cmdlen==2 && ch<TELNET_WILL) || telnet_cmdlen>2) {
					telnet_cmdlen=0;
					/* Code disabled.  Why?  ToDo */
					/* break; */
				}
				continue;
			}
		}
		if(debug_rx)
			lprintf(LOG_DEBUG,"RX: %s",chr(ch));
		return(ch);
	}

	return(NOINP);
}
Example #13
0
// 32 bit recover key from 2 nonces
int main (int argc, char *argv[]) {

  nonces_t data;
  uint32_t ks2;     // keystream used to encrypt reader response
  uint64_t key;     // recovered key

  printf("MIFARE Classic key recovery - based on 32 bits of keystream\n");
  printf("Recover key from two 32-bit reader authentication answers only!\n\n");

  if (argc != 7 && argc != 8) {
    printf(" syntax: %s <uid> <nt0> <{nr_0}> <{ar_0}> [<nt1>] <{nr_1}> <{ar_1}>\n", argv[0]);
	printf("         (you may omit nt1 if it is equal to nt0)\n\n");
    return 1;
  }

  bool moebius_attack = (argc == 8);
  
  sscanf(argv[1],"%x",&data.cuid);
  sscanf(argv[2],"%x",&data.nonce);
  data.nonce2 = data.nonce;
  sscanf(argv[3],"%x",&data.nr);
  sscanf(argv[4],"%x",&data.ar);
  if (moebius_attack) {
	  sscanf(argv[5],"%x",&data.nonce2);
	  sscanf(argv[6],"%x",&data.nr2);
	  sscanf(argv[7],"%x",&data.ar2);
  } else {
	  sscanf(argv[5],"%x",&data.nr2);
	  sscanf(argv[6],"%x",&data.ar2);
  }	  

  printf("Recovering key for:\n");
  printf("    uid: %08x\n",data.cuid);
  printf("    nt0: %08x\n",data.nonce);
  printf(" {nr_0}: %08x\n",data.nr);
  printf(" {ar_0}: %08x\n",data.ar);
  printf("    nt1: %08x\n",data.nonce2);
  printf(" {nr_1}: %08x\n",data.nr2);
  printf(" {ar_1}: %08x\n",data.ar2);

  uint64_t start_time = msclock();
  
	// Generate lfsr succesors of the tag challenge
  printf("\nLFSR succesors of the tag challenge:\n");
  printf("  nt': %08x\n",prng_successor(data.nonce, 64));
  printf(" nt'': %08x\n",prng_successor(data.nonce, 96));

  // Extract the keystream from the messages
  printf("\nKeystream used to generate {ar} and {at}:\n");
  ks2 = data.ar ^ prng_successor(data.nonce, 64);
  printf("  ks2: %08x\n",ks2);

	bool success;
	if (moebius_attack) {
		success = mfkey32_moebius(data, &key);
	} else {
		success = mfkey32(data, &key);
	}
	
	if (success) {
		printf("Recovered key: %012" PRIx64 "\n", key);
	} else {
		printf("Couldn't recover key.\n");
	}

	printf("Time spent: %1.2f seconds\n", (float)(msclock() - start_time)/1000.0);
}
Example #14
0
/*
========================================================================
emulate:	This routine contains the main loop that handles active 
			emulation and maintenance tasks.
========================================================================
*/
void emulate(void)
{
	unsigned int	i,j;
	unsigned int	v;
	int				nxtmaint=1;
	int				ins;

	starttime=msclock();
	lock_remote();
	while(!gExitApp) 
	{
		/* Run appropriate emulation loop base on ReMem support */
		if (gReMem)
			while (!gExitLoop)
			{
				/* Check for active debug monitor windows */
				if (gDebugActive)
				{
					do_debug_stuff();
					if (gExitLoop) 
						break;
				}

				/* Instruction emulation contained in header file */
				#undef NO_REMEM
				#include "cpu.h"
				#include "do_instruct.h"

				// Check if next inst is SIM
				if ((get_memory8(PC) == 0xF3) || ((IM & 0x2A) == 0x20) ||
					((IM & 0x4C) == 0x40))
				{
					check_interrupts();
				}

				// Check for return from interrupt
				if (gIntActive)
				{
					if (SP == gIntSP)
						gIntActive = FALSE;
				}
				if (gSingleStep)
				{
					if (!gIntActive)
					{
						gSingleStep = 0;
					}
				}

				/* Do maintenance tasks (Windows events, interrupts, etc.) */
#ifdef __APPLE__
				if(!(--nxtmaint)) 
#else
				if(!(--nxtmaint & 0x3FF)) 
#endif
				{
					unlock_remote();
					gOsDelay = nxtmaint == 0;
					throttle(cycle_delta);
					maint();
					ser_poll();
					check_interrupts();
					if (gOsDelay)
						nxtmaint=gMaintCount;
					lock_remote();
				}
#if 0
				exec_remem_instruction();

					if (gExitLoop) 
						break;
#endif
			}

		if (!gReMem)
		{
			while (!gExitLoop)
			{
				/* Check for active debug monitor windows */
				if (gDebugActive)
				{
					do_debug_stuff();
					if (gExitLoop)
						break;
				}

				/* Instruction emulation contained in header file */
				#define NO_REMEM
				#include "cpu.h"
				#include "do_instruct.h"

				// Check if next inst is SIM or RS-232 waiting
				if ((get_memory8(PC) == 0xF3) || ((IM & 0x2A) == 0x20) ||
					((IM & 0x4C) == 0x40))
				{
					check_interrupts();
				}

				// Check for return from interrupt
				if (gIntActive)
				{
					if (SP == gIntSP)
						gIntActive = FALSE;
				}
				if (gSingleStep)
				{
					if (!gIntActive)
					{
						gSingleStep = 0;
					}
				}

				/* Do maintenance tasks (Windows events, interrupts, etc.) */
#ifdef __APPLE__
				if(!(--nxtmaint)) 
#else
				if(!(--nxtmaint & 0x3FF)) 
#endif
				{
					unlock_remote();
					gOsDelay = nxtmaint == 0;
					throttle(cycle_delta);
					maint();
					ser_poll();
					check_interrupts();
					if (gOsDelay)
						nxtmaint=gMaintCount;
					lock_remote();
				}
			}
		}

		gExitLoop = 0;
	}
	unlock_remote();
}
Example #15
0
int main()
{
	char	str[128];
	char	compiler[128];
	char	fpath[MAX_PATH+1];
	char*	path = ".";
	char*	glob_pattern = "*wrap*";
	int		i;
	int		ch;
	uint	u;
	time_t	t;
	glob_t	g;
	DIR*	dir;
	DIRENT*	dirent;
	thread_data_t thread_data;
	int	fd;
	int	fd2;
	int	canrelock=0;
	clock_t	ticks;

	/* Show platform details */
	DESCRIBE_COMPILER(compiler);
	printf("%-15s: %s\n","Platform",PLATFORM_DESC);
	printf("%-15s: %s\n","Version",os_version(str));
	printf("%-15s: %s\n","Compiler"	,compiler);
	printf("%-15s: %d\n","Random Number",xp_random(1000));

	for(i=0;i<3;i++) {
		if(_beginthread(
			  sopen_child_thread	/* entry point */
			 ,0  					/* stack size (0=auto) */
			 ,(void*)i				/* data */
			 )==(unsigned long)-1)
			printf("_beginthread failed\n");
		else
			SLEEP(1);
	}
	printf("Waiting for all sopen_child_threads to close...\n");
	SLEEP(5000);	/* wait for all threads to quit */

	/* Exclusive sopen test */
	printf("\nsopen() test\n");
	if((fd=sopen(LOCK_FNAME,O_RDWR|O_CREAT,SH_DENYRW,S_IREAD|S_IWRITE))==-1) {
		perror(LOCK_FNAME);
		return(errno);
	}
	printf("%s is opened with an exclusive (read/write) lock\n",LOCK_FNAME);
	getkey();
	if(_beginthread(
		  sopen_test_thread	/* entry point */
		 ,0  				/* stack size (0=auto) */
		 ,NULL				/* data */
		 )==(unsigned long)-1)
		printf("_beginthread failed\n");
	else
		SLEEP(1000);
	close(fd);

	/* sopen()/lock test */
	printf("\nlock() test\n");
	if((fd=sopen(LOCK_FNAME,O_RDWR|O_CREAT,SH_DENYNO,S_IREAD|S_IWRITE))==-1) {
		perror(LOCK_FNAME);
		return(errno);
	}
	write(fd,"lock testing\n",LOCK_LEN);
	if(lock(fd,LOCK_OFFSET,LOCK_LEN)==0)
		printf("lock() succeeds\n");
	else
		printf("!FAILURE: lock() non-functional (or file already locked)\n");
	if(lock(fd,LOCK_OFFSET,LOCK_LEN)==0)  {
		printf("!FAILURE: Subsequent lock of region was allowed (will skip some tests)\n");
		canrelock=1;
	}
		
	if(_beginthread(
		  lock_test_thread	/* entry point */
		 ,0  				/* stack size (0=auto) */
		 ,NULL				/* data */
		 )==(unsigned long)-1)
		printf("_beginthread failed\n");
	else
		SLEEP(1000);
	if(canrelock)
		printf("?? Skipping some tests due to inability to detect own locks\n");
	else  {
		if(lock(fd,LOCK_OFFSET,LOCK_LEN))
			printf("Locks in first thread survive open()/close() in other thread\n");
		else
			printf("!FAILURE: lock() in first thread lost by open()/close() in other thread\n");
		if(lock(fd,LOCK_OFFSET+LOCK_LEN+1,LOCK_LEN))
			printf("!FAILURE: file locking\n");
		else
			printf("Record locking\n");
	}
	if((fd2=sopen(LOCK_FNAME,O_RDWR,SH_DENYRW))==-1) {
		printf("Cannot reopen SH_DENYRW while lock is held\n");
		close(fd2);
	}
	else  {
		printf("!FAILURE: can reopen SH_DENYRW while lock is held\n");
	}
	if(unlock(fd,LOCK_OFFSET,LOCK_LEN))
		printf("!FAILURE: unlock() non-functional\n");
	if(lock(fd,LOCK_OFFSET+LOCK_LEN+1,LOCK_LEN))
		printf("Cannot re-lock after non-overlapping unlock()\n");
	else
		printf("!FAILURE: can re-lock after non-overlappping unlock()\n");
	if(lock(fd,LOCK_OFFSET,LOCK_LEN))
		printf("!FAILURE: cannot re-lock unlocked area\n");
	close(fd);

	/* getch test */
	printf("\ngetch() test (ESC to continue)\n");
	do {
		ch=getch();
		printf("getch() returned %d\n",ch);
	} while(ch!=ESC);

	/* kbhit test */
	printf("\nkbhit() test (any key to continue)\n");
	while(!kbhit()) {
		printf(".");
		fflush(stdout);
		SLEEP(500);
	}
	getch();	/* remove character from keyboard buffer */

	/* BEEP test */
	printf("\nBEEP() test\n");
	getkey();
	for(i=750;i>250;i-=5)
		BEEP(i,15);
	for(;i<1000;i+=5)
		BEEP(i,15);

	/* SLEEP test */
	printf("\nSLEEP(5 second) test\n");
	getkey();
	t=time(NULL);
	printf("sleeping... ");
	fflush(stdout);
	ticks=msclock();
	SLEEP(5000);
	printf("slept %ld seconds (%ld according to msclock)\n",time(NULL)-t,(msclock()-ticks)/MSCLOCKS_PER_SEC);

	/* Thread SLEEP test */
	printf("\nThread SLEEP(5 second) test\n");
	getkey();
	i=0;
	if(_beginthread(
		  sleep_test_thread	/* entry point */
		 ,0					/* stack size (0=auto) */
		 ,&i				/* data */
		 )==(unsigned long)-1)
		printf("_beginthread failed\n");
	else {
		SLEEP(1);			/* yield to child thread */
		while(i==0) {
			printf(".");
			fflush(stdout);
			SLEEP(1000);
		}
	}

	/* glob test */
	printf("\nglob(%s) test\n",glob_pattern);
	getkey();
	i=glob(glob_pattern,GLOB_MARK,NULL,&g);
	if(i==0) {
		for(u=0;u<g.gl_pathc;u++)
			printf("%s\n",g.gl_pathv[u]);
		globfree(&g);
	} else
		printf("glob(%s) returned %d\n",glob_pattern,i);

	/* opendir (and other directory functions) test */
	printf("\nopendir(%s) test\n",path);
	getkey();
	printf("\nDirectory of %s\n\n",FULLPATH(fpath,path,sizeof(fpath)));
	dir=opendir(path);
	while(dir!=NULL && (dirent=readdir(dir))!=NULL) {
		t=fdate(dirent->d_name);
		printf("%.24s %10lu  %06o  %s%c\n"
			,ctime(&t)
			,flength(dirent->d_name)
			,getfattr(dirent->d_name)
			,dirent->d_name
			,isdir(dirent->d_name) ? '/':0
			);
	}
	if(dir!=NULL)
		closedir(dir);
	printf("\nFree disk space: %lu kbytes\n",getfreediskspace(path,1024));

	/* Thread (and inter-process communication) test */
	printf("\nSemaphore test\n");
	getkey();
	if(sem_init(&thread_data.parent_sem
		,0 /* shared between processes */
		,0 /* initial count */
		)) {
		printf("sem_init failed\n");
	}
	if(sem_init(&thread_data.child_sem
		,0	/* shared between processes */
		,0	/* initial count */
		)) {
		printf("sem_init failed\n");
	}
	if(_beginthread(
		  sem_test_thread	/* entry point */
		 ,0					/* stack size (0=auto) */
		 ,&thread_data		/* data */
		 )==(unsigned long)-1)
		printf("_beginthread failed\n");
	else {
		sem_wait(&thread_data.child_sem);	/* wait for thread to begin */
		for(i=0;i<10;i++) {
			printf("<parent>");
			sem_post(&thread_data.parent_sem);
			sem_wait(&thread_data.child_sem);
		}
		sem_wait(&thread_data.child_sem);	/* wait for thread to end */
	}
	sem_destroy(&thread_data.parent_sem);
	sem_destroy(&thread_data.child_sem);

	printf("\nSemaphore blocking test\n");
	getkey();
	sem_init(&thread_data.parent_sem
		,0 /* shared between processes */
		,0 /* initial count */
		);
	sem_init(&thread_data.child_sem
		,0	/* shared between processes */
		,0	/* initial count */
		);
	if(_beginthread(
		  sem_test_thread_block	/* entry point */
		 ,0					/* stack size (0=auto) */
		 ,&thread_data		/* data */
		 )==(unsigned long)-1)
		printf("_beginthread failed\n");
	else {
		sem_wait(&thread_data.child_sem);	/* wait for thread to begin */
		for(i=0;i<10;i++) {
			printf("<parent>");
			SLEEP(5000);
			sem_post(&thread_data.parent_sem);
			sem_wait(&thread_data.child_sem);
		}
		sem_wait(&thread_data.child_sem);	/* wait for thread to end */
	}
	printf("\nsem_trywait_block test...");
	t=time(NULL);
	sem_trywait_block(&thread_data.parent_sem,5000);
	printf("\ntimed-out after %ld seconds (should be 5 seconds)\n",time(NULL)-t);
	sem_destroy(&thread_data.parent_sem);
	sem_destroy(&thread_data.child_sem);
	printf("\nendian check...");
	memcpy(&i,"\x01\x02\x03\x04",4);
	if(LE_LONG(i)==67305985) {
		printf("OK!\n");
	}
	else {
		printf("FAILED!\n");
	}
	return 0;
}
static int timeout_processing(int deadtime, int threadid)
{
//0703  extern int Client;
//0703  static time_t last_keepalive_sent_time = 0;
  static time_t last_idle_closed_check[NUM_SMBTHREAD] = {0};
  time_t t;
  int allidle = True;
//0703  extern int keepalive;

  if (_forceclosethread[threadid] ==1)
    return 0;  //force closed this thread  ....By Ron 3/11/2002

//0705  *last_timeout_processing_time = t = (msclock()/1000);
  t = (msclock()/1000);

//0703  if(last_keepalive_sent_time == 0)
//    last_keepalive_sent_time = t;

  if(last_idle_closed_check[threadid] == 0)
    last_idle_closed_check[threadid] = t;

  /* automatic timeout if all connections are closed */      
//0705  if (conn_num_open()==0 && (t - last_idle_closed_check) >= IDLE_CLOSED_TIMEOUT) 
//    DEBUG( 2, ( "Closing idle connection\n" ) );
//    	  return False;
//0705  else
//      last_idle_closed_check = t;

  if (conn_num_open(threadid)==0 && 
  		(t - last_idle_closed_check[threadid]) >= IDLE_CLOSED_TIMEOUT) 
  {
//    DEBUG( 2, ( "Closing idle connection\n" ) );
	  last_idle_closed_check[threadid] = 0; //reset static variable
      return False;
  }
  else if (conn_num_open(threadid) > 0)
      last_idle_closed_check[threadid] = t;

  /* check for connection timeouts */
  allidle = conn_idle_all(t, deadtime, threadid);

//0705  if (allidle && conn_num_open()>0) {
//    DEBUG(2,("Closing idle connection 2.\n"));

  if (allidle && conn_num_open(threadid) > 0)  {
  	  last_idle_closed_check[threadid] = 0; //reset static variable	
      return False;
  }


  if (smb_read_error[threadid] == READ_EOF) 
  {
//    DEBUG(3,("end of file from client\n"));
	last_idle_closed_check[threadid] = 0; //reset static variable
    return False;
  }

  if (smb_read_error[threadid] == READ_ERROR) 
  {
//    DEBUG(3,("receive_smb error (%s) exiting\n",
//              strerror(errno)));
	last_idle_closed_check[threadid] = 0; //reset static variable
    return False;
  }


//0703  *select_timeout = setup_select_timeout();

  return True;
}