Esempio n. 1
0
/*
 * smb_pwd_fputent
 *
 * If LM/NTLM hash are present, converts them to hex string
 * and write them along with user's name and Id to the smbpasswd
 * file.
 */
static int
smb_pwd_fputent(FILE *fp, const smb_pwbuf_t *pwbuf)
{
	smb_passwd_t *pw = pwbuf->pw_pwd;
	char hex_nthash[SMBAUTH_HEXHASH_SZ+1];
	char hex_lmhash[SMBAUTH_HEXHASH_SZ+1];
	int rc;

	if ((pw->pw_flags & SMB_PWF_LM) == SMB_PWF_LM) {
		(void) bintohex((char *)pw->pw_lmhash, SMBAUTH_HASH_SZ,
		    hex_lmhash, SMBAUTH_HEXHASH_SZ);
		hex_lmhash[SMBAUTH_HEXHASH_SZ] = '\0';
	} else {
		(void) strcpy(hex_lmhash, (char *)pw->pw_lmhash);
	}

	if ((pw->pw_flags & SMB_PWF_NT) == SMB_PWF_NT) {
		(void) bintohex((char *)pw->pw_nthash, SMBAUTH_HASH_SZ,
		    hex_nthash, SMBAUTH_HEXHASH_SZ);
		hex_nthash[SMBAUTH_HEXHASH_SZ] = '\0';
	} else {
		(void) strcpy(hex_nthash, (char *)pw->pw_nthash);
	}

	rc = fprintf(fp, "%s:%u:%s:%s\n", pw->pw_name, pw->pw_uid,
	    hex_lmhash, hex_nthash);

	if (rc <= 0)
		return (SMB_PWE_WRITE_FAILED);

	return (SMB_PWE_SUCCESS);
}
Esempio n. 2
0
//performs fixed xor on two Hex strings of equal length
string fixedXor(string &a,string &b) {

	string foo = "";
	string bar = "";

	for(int i = 0; i < a.size(); i++) {

		foo += hextobin(a[i]);
	}
	for(int i = 0; i < b.size(); i++) {

		bar += hextobin(b[i]);
	}

	string output = X_OR_byte(foo,bar);

	int i = 0;
	string result = "";
	while(i < output.size()) {
		string temp = "";
		temp = output[i];
		temp += output[i+1];
		temp += output[i+2];
		temp += output[i+3];

		result += bintohex(temp);
		i = i + 4;
	}
	return result;
}
Esempio n. 3
0
static void 
fprintfhex(register FILE *fp, int len, char *cp)
{
    char *hex;

    hex = bintohex(len, cp);
    fprintf(fp, "%s", hex);
    free(hex);
}
Esempio n. 4
0
int repeating_Xor(string &key) {

	string inputFile;
	cout << "Enter the name of an existing text file in the current directory: ";
	cin >> inputFile;
	//open input file for reading
	ifstream input(inputFile);
	ofstream output("repeating_xor_output.txt");
	string output_bin = "";
	string bin_text = "";

	while(input.good()) {
		char c = input.get();
		//if input is still valid
		if(input.good()) {
			//convert character from input to 8bit binary string
			bin_text += ctobin(c);
		}
	}
	string bin_key="";
	for(int i = 0; i < key.size(); i++) {
		bin_key += ctobin(key[i]);
	}
	int foo = 0;
	for(int i = 0; i < bin_text.size(); i = i + 8) {

		string temp = "";
		temp += bin_text[i];
		temp += bin_text[i+1];
		temp += bin_text[i+2];
		temp += bin_text[i+3];
		temp += bin_text[i+4];
		temp += bin_text[i+5];
		temp += bin_text[i+6];
		temp += bin_text[i+7];

		string bar = "";

		bar += bin_key[foo];
		bar += bin_key[foo+1];
		bar += bin_key[foo+2];
		bar += bin_key[foo+3];
		bar += bin_key[foo+4];
		bar += bin_key[foo+5];
		bar += bin_key[foo+6];
		bar += bin_key[foo+7];

		foo += 8;

		foo = foo % 24;

		//cout << "XORing " << temp << " with key " << bar <<", result: " << X_OR_byte(temp,bar) << "\n";
		//cout << "foo = " << foo << "\n";
		output_bin += X_OR_byte(temp,bar);
	}
	input.close();

	for(int i = 0; i < output_bin.size(); i = i +4) {
		string temp = "";
		temp += output_bin[i];
		temp += output_bin[i+1];
		temp += output_bin[i+2];
		temp += output_bin[i+3];

		output << bintohex(temp);
	}
	output.close();
	return 0;
}
Esempio n. 5
0
int main(int argc, char **argv) {
  pid_t pid;
  extern int optind, opterr, optopt;
  int opt;
  struct can_frame frame;

  int status, datalen, sd, *ip_flags;
  //const int on = 1;
  char *interface, *target, *src_ip, *dst_ip;
  struct ip iphdr;
  struct udphdr udphdr;
  unsigned char *data, *packet;
  struct addrinfo hints, *res;
  struct sockaddr_in *ipv4, sin;
  struct ifreq ifr;
  void *tmp;

  
  int sa, sc; // UDP socket , CAN socket
  struct sockaddr_in saddr;
  struct sockaddr_can caddr;
  struct ifreq CAN_ifr;
  socklen_t caddrlen = sizeof(caddr);

  fd_set readfds;

  int i, s, nbytes, ret;

  int local_port = 1470;
  int destination_port = 1470;
  // // int broadcast_address;
  int verbose = 1;
  int background = 0; //1;
  int canid = 0;
  const int on = 1;
  strcpy(CAN_ifr.ifr_name, "can0");

  char bufferHexa[40];
  int udp_bytes, raw_len, CAN_err, DCcom;
  char calc_FCS[2], UDP_CMD[2], PCID[2], Nbytes[2], FCS[2], RX_UDP_Frame[33], Data[25];
  char SID[5], EID[5];
  char bin_val[32], bin_str[32], DomoCANframe[32];
  char temp_msg[64], fcs[2], msg_out[40], tmp_string[40], frm_content[80], buf[10];
  char *hex_byte, hex_val[32], HexBuffer[32];

  // Check modified Process arguments  
  while ((opt = getopt(argc, argv, "l:d:b:i:e:fv?")) != -1) {
    switch (opt) {
                case 'l':
                        local_port = strtoul(optarg, (char **)NULL, 10);
                        break;
                case 'd':
                        destination_port = strtoul(optarg, (char **)NULL, 10);
                        break;
                case 'b':
                        s = inet_pton(AF_INET,optarg,buf);
                        if (s <= 0) {
                                if (s == 0)  {
                                        fprintf(stderr, "Not in presentation format");
                                } else {
                                        perror("inet_pton");
                                }
                                exit(1);
                        }
                        break;
                case 'i':
                        strcpy(CAN_ifr.ifr_name, optarg);
                        break;

				case 'e':
                        strcpy(interface, optarg);
                        break;

                case 'v':
                        verbose = 1;
                        break;
                case 'f':
                        background = 0;
                        break;

                case '?':
                        print_usage(basename(argv[0]));
                        exit(0);
                        break;

                default:
                        fprintf(stderr, "Unknown option %c\n", opt);
                        print_usage(basename(argv[0]));
                        exit(1);
                        break;
    } // END SWITCH
  } // END WHILE

 // Allocate memory for various arrays.
  // Maximum UDP payload size = 65535 - IPv4 header (20 bytes) - UDP header (8 bytes)
  tmp = (unsigned char *) malloc ((IP_MAXPACKET - IP4_HDRLEN - UDP_HDRLEN) * sizeof (unsigned char));
  if (tmp != NULL) {
    data = tmp;
  } else {
    fprintf (stderr, "ERROR: Cannot allocate memory for array 'data'.\n");
    exit (EXIT_FAILURE);
  }
  memset (data, 0, (IP_MAXPACKET - IP4_HDRLEN - UDP_HDRLEN) * sizeof (unsigned char));

  tmp = (unsigned char *) malloc (IP_MAXPACKET * sizeof (unsigned char));
  if (tmp != NULL) {
    packet = tmp;
  } else {
    fprintf (stderr, "ERROR: Cannot allocate memory for array 'packet'.\n");
    exit (EXIT_FAILURE);
  }
  memset (packet, 0, IP_MAXPACKET * sizeof (unsigned char));

  tmp = (char *) malloc (40 * sizeof (char));
  if (tmp != NULL) {
    interface = tmp;
  } else {
    fprintf (stderr, "ERROR: Cannot allocate memory for array 'interface'.\n");
    exit (EXIT_FAILURE);
  }
  memset (interface, 0, 40 * sizeof (char));

  tmp = (char *) malloc (40 * sizeof (char));
  if (tmp != NULL) {
    target = tmp;
  } else {
    fprintf (stderr, "ERROR: Cannot allocate memory for array 'target'.\n");
    exit (EXIT_FAILURE);
  }
  memset (target, 0, 40 * sizeof (char));

  tmp = (char *) malloc (16 * sizeof (char));
  if (tmp != NULL) {
    src_ip = tmp;
  } else {
    fprintf (stderr, "ERROR: Cannot allocate memory for array 'src_ip'.\n");
    exit (EXIT_FAILURE);
  }
  memset (src_ip, 0, 16 * sizeof (char));

    tmp = (char *) malloc (16 * sizeof (char));
  if (tmp != NULL) {
    dst_ip = tmp;
  } else {
    fprintf (stderr, "ERROR: Cannot allocate memory for array 'dst_ip'.\n");
    exit (EXIT_FAILURE);
  }
  memset (dst_ip, 0, 16 * sizeof (char));

  tmp = (int *) malloc (4 * sizeof (int));
  if (tmp != NULL) {
    ip_flags = tmp;
  } else {
    fprintf (stderr, "ERROR: Cannot allocate memory for array 'ip_flags'.\n");
    exit (EXIT_FAILURE);
  }
  memset (ip_flags, 0, 4 * sizeof (int));

// Interface to send packet through.
//  strcpy (interface, "eth0");
  strcpy (interface, Domocan_UDP_Int);
  get_IP_conf(interface, source_ip, destination_ip);
  if (verbose) printf("\nInt: %s, IP Source: %s, Dest: %s\n", interface, source_ip, destination_ip);
  
// Submit request for a socket descriptor to lookup interface.
  if ((sd = socket (AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
    perror ("socket() failed to get socket descriptor for using ioctl() ");
    exit (EXIT_FAILURE);
  }

// Use ioctl() to lookup interface.
  memset (&ifr, 0, sizeof (ifr));
  snprintf (ifr.ifr_name, sizeof (ifr.ifr_name), "%s", interface);
  if (ioctl (sd, SIOCGIFINDEX, &ifr) < 0) {
    perror ("ioctl() failed to find interface ");
    return (EXIT_FAILURE);
  }
  close (sd);
  if (verbose) printf ("Index for interface %s is %i\n", interface, ifr.ifr_ifindex);

// Source IPv4 address: you need to fill this out
  strcpy (src_ip, source_ip);

// Destination URL or IPv4 address
  strcpy (target, destination_ip);

// Fill out hints for getaddrinfo().
  memset (&hints, 0, sizeof (struct addrinfo));
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = hints.ai_flags | AI_CANONNAME;

  // Resolve target using getaddrinfo().
  if ((status = getaddrinfo (target, NULL, &hints, &res)) != 0) {
    fprintf (stderr, "getaddrinfo() failed: %s\n", gai_strerror (status));
    exit (EXIT_FAILURE);
  }
  ipv4 = (struct sockaddr_in *) res->ai_addr;
  tmp = &(ipv4->sin_addr);
  inet_ntop (AF_INET, tmp, dst_ip, 16);
  freeaddrinfo (res);

  // UDP data
  datalen = 16;

  // IPv4 header
  // IPv4 header length (4 bits): Number of 32-bit words in header = 5
  iphdr.ip_hl = IP4_HDRLEN / sizeof (unsigned long int);
  // Internet Protocol version (4 bits): IPv4
  iphdr.ip_v = 4;
  // Type of service (8 bits)
  iphdr.ip_tos = 0;
  // Total length of datagram (16 bits): IP header + UDP header + datalen
  iphdr.ip_len = htons (IP4_HDRLEN + UDP_HDRLEN + datalen);
  // ID sequence number (16 bits): unused, since single datagram
  iphdr.ip_id = htons (0);
  // Flags, and Fragmentation offset (3, 13 bits): 0 since single datagram
  // Zero (1 bit)
  ip_flags[0] = 0;
  // Do not fragment flag (1 bit)
  ip_flags[1] = 0;
  // More fragments following flag (1 bit)
  ip_flags[2] = 0;
  // Fragmentation offset (13 bits)
  ip_flags[3] = 0;
  iphdr.ip_off = htons ((ip_flags[0] << 15)
                      + (ip_flags[1] << 14)
                      + (ip_flags[2] << 13)
                      +  ip_flags[3]);
  // Time-to-Live (8 bits): default to maximum value
  iphdr.ip_ttl = 255;
  // Transport layer protocol (8 bits): 17 for UDP
  iphdr.ip_p = IPPROTO_UDP;
  // Source IPv4 address (32 bits)
  inet_pton (AF_INET, src_ip, &(iphdr.ip_src));
  // Destination IPv4 address (32 bits)
  inet_pton (AF_INET, dst_ip, &iphdr.ip_dst);
  // IPv4 header checksum (16 bits): set to 0 when calculating checksum
  iphdr.ip_sum = 0;
  iphdr.ip_sum = checksum ((unsigned short int *) &iphdr, IP4_HDRLEN);

  // UDP header
  // Source port number (16 bits): pick a number
  udphdr.source = htons (1470);
  // Destination port number (16 bits): pick a number
  udphdr.dest = htons (1470);
  // Length of UDP datagram (16 bits): UDP header + UDP data
  udphdr.len = htons (UDP_HDRLEN + datalen);
  // UDP checksum (16 bits)
  udphdr.check = udp4_checksum (iphdr, udphdr, data, datalen);
  // The kernel is going to prepare layer 2 information (ethernet frame header) for us.
  // For that, we need to specify a destination for the kernel in order for it
  // to decide where to send the raw datagram. We fill in a struct in_addr with
  // the desired destination IP address, and pass this structure to the sendto() function.
  memset (&sin, 0, sizeof (struct sockaddr_in));
  sin.sin_family = AF_INET;
  sin.sin_addr.s_addr = iphdr.ip_dst.s_addr;

  // Submit request for a raw socket descriptor.
  if ((sd = socket (AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
    perror ("socket() failed ");
    exit (EXIT_FAILURE);
  } // END IF
  // Set flag so socket expects us to provide IPv4 header.
  if (setsockopt (sd, IPPROTO_IP, IP_HDRINCL, &on, sizeof (on)) < 0) {
    perror ("setsockopt() failed to set IP_HDRINCL ");
    exit (EXIT_FAILURE);
  } // END IF
  // Bind socket to interface index.
  if (setsockopt (sd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof (ifr)) < 0) {
    perror ("setsockopt() failed to bind to interface ");
    exit (EXIT_FAILURE);
  } // END IF
  // Enable Broadcast
  if (setsockopt (sd, SOL_SOCKET, SO_BROADCAST,&ifr,sizeof(ifr)) < 0) {
    perror ("setsockopt() failed to enable Broadcast ");
    exit (EXIT_FAILURE);
  } // END IF
  
  //  if((sa = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
  if((sa = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    perror("inetsocket");
    exit(1);
  } // END IF

  //  SOCKADDR_IN saddr = { 0 };
  saddr.sin_family = AF_INET;
  saddr.sin_addr.s_addr = htonl(INADDR_ANY);
  saddr.sin_port = htons(local_port);

  while(bind(sa,(struct sockaddr*)&saddr, sizeof(saddr)) < 0) {
    printf(".");
    fflush(NULL);
    usleep(100000);
  } // END WHILE

  // CAN Interface Init
  if ((sc = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
    perror("socket");
    exit(1);
  } // END IF

  caddr.can_family = AF_CAN;
  caddr.can_ifindex = 0; // bind to all interfaces
  if (ioctl(sc, SIOCGIFINDEX, &CAN_ifr) < 0) {
    perror("SIOCGIFINDEX");
    exit(1);
  } // END IF
  caddr.can_ifindex = CAN_ifr.ifr_ifindex;

  if (bind(sc, (struct sockaddr *)&caddr, caddrlen) < 0) {
    perror("CAN bind");
    exit(1);
  } // END IF

  if (background) {
    // Fork off the parent process
    pid = fork();
    if (pid < 0) {
      exit(EXIT_FAILURE);
    } // END IF
    // If we got a good PID, then we can exit the parent process.
    if (pid > 0) {
      printf("Going into background ...\n");
      exit(EXIT_SUCCESS);
    } // END IF pid
  } // END IF background

  while (1) {

    // I/O Interup Disptach
    FD_ZERO(&readfds); // zero out the read set
    FD_SET(sc, &readfds); // add CAN socket to the read set
    FD_SET(sa, &readfds); // add UDP Serveur socket to the read set

    ret = select((sc > sa)?sc+1:sa+1, &readfds, NULL, NULL, NULL);

    //////////////////////////
    // received a CAN frame //
    //////////////////////////

    if (FD_ISSET(sc, &readfds)) {
      if ((nbytes = read(sc, &frame, sizeof(struct can_frame))) != 0) {
        // CAN frame IN
        sprintf(frm_content, "", "");
        for (i = 0; i < frame.can_dlc; i++) {
          sprintf(buf, "%02X",frame.data[i]);
          strcat(frm_content, buf);
        } // END FOR
        // printf(" (%s)\n", frm_content);
        if (verbose) printf("\n\n>RX CAN: header=%8X data=%s dlc=%d", frame.can_id, frm_content, frame.can_dlc);		
        // Transform to DomoCAN UDP Format
		hex_val[0] = '\0';
        sprintf(hex_val, "%8X", frame.can_id);
        strcpy(hex_val, hex_val);
        // Extract SDIH and SIDL
        hex_byte = strndup(hex_val, 4);
		// Convert to 16 bit binary
        htoi(hex_byte, bin_val, bin_str); bin_val[0] = '\0';
		// Transform 16bit CAN to Domocan UDP
        DomoCANaddr(bin_str, bin_val);
        //printf("\n DomoCAN binary SDIH+SIDL:%s\n", bin_val);
        // Convert back form 16bit to 2 HEX bytes
		SID[0] = '\0'; bin_str[0] = '\0';
		bintohex(bin_val,bin_str);
        sprintf(SID,"%s", bin_str);
        SID[4]='\0';
        //printf("\n DomoCAN HEX Destination:%s", SID);
	
	// Determine Length (dlc+4)
        nbytes = frame.can_dlc+4; // Frame length (CAN Header + dlc)
        sprintf(buf, "%0d", nbytes); buf[2]='\0';
        if (nbytes==0) {
          sprintf(buf, "%s",  "00"); buf[2]='\0';
        } else {
          if (nbytes<10)  { sprintf(buf, "0%d", nbytes); buf[2]='\0'; }
          if (nbytes==10) { sprintf(buf, "%s", "0A");    buf[2]='\0'; }
          if (nbytes==11) { sprintf(buf, "%s", "0B");    buf[2]='\0'; }
          if (nbytes==12) { sprintf(buf, "%s", "0C");    buf[2]='\0'; }
          if (nbytes >12) { sprintf(buf, "%s", "0C");    buf[2]='\0'; }
        } // END IF nbytes
		// Extract EIDH and EIDL
        EID[0] = '\0';
		strncpy(EID, hex_val+4, 4); EID[4]='\0';
		// Build UDP Frame
		DomoCANframe[0] = '\0';
        sprintf(DomoCANframe, "%s%s%s%s%s", "70FF", buf, SID, EID, frm_content);
		// Dummy bytes
		if (nbytes<12) {
		  for (i=6+(nbytes*2); i<=29;i++) {
		    DomoCANframe[i]='0';
		  } // END FOR
		} // END IF
		//DomoCANframe[30] = '\0';
		// Calculate Checksum (FCS)
        domocan_checksum(DomoCANframe, fcs);
		DomoCANframe[30] = fcs[0];
		DomoCANframe[31] = fcs[1];
        DomoCANframe[32] = '\0';
		// Serialize Message 
        msg_out[0] = '\0';
        raw_len = convert_raw(DomoCANframe, msg_out);
        if (verbose) printf("\n=>TX UDP Frame 0x70: %s, len=%d",DomoCANframe,raw_len);
		// Resets Interupts
	    FD_ZERO(&readfds); // zero out the read set
		FD_SET(sc, &readfds); // add CAN socket to the read set
		FD_SET(sa, &readfds); // add UDP Serveur socket to the read set
		// Prepare packet.
	    // First part is an IPv4 header.
	    memcpy (packet, &iphdr, IP4_HDRLEN);
	    // UDP checksum (16 bits)
        udphdr.check = udp4_checksum (iphdr, udphdr, msg_out, datalen);
	    // Next part of packet is upper layer protocol header.
	    memcpy ((packet + IP4_HDRLEN), &udphdr, UDP_HDRLEN);
	    // Finally, add the UDP data.
	    memcpy (packet + IP4_HDRLEN + UDP_HDRLEN, msg_out, datalen);
	    // Send packet.
	    if (sendto (sd, packet, IP4_HDRLEN + UDP_HDRLEN + datalen, 0, (struct sockaddr *) &sin, sizeof (struct sockaddr)) < 0)  {
          perror ("sendto() failed ");
          exit (EXIT_FAILURE);
        } // END IF sendto
  	  
     } // END IF nbytes
    } // END IF received a CAN frame

    ///////////////////////////
    // Received a UDP packet //
    ///////////////////////////

    if (FD_ISSET(sa, &readfds)) {

      read(sa, udpframe, 32);
//      if (read(sa, udpframe, MAXDG)!=0) {
      // UDP Packet Received
      //strncpy(tmp_string, bufferHexa, sizeof(bufferHexa));
      bufferHexa[0] = '\0'; RX_UDP_Frame[0] ='\0';
      for (i=0;i<16;i++) {
        sprintf(bufferHexa, "%s%0.2X", bufferHexa, udpframe[i]);
      }

      // Extract Command, PCID, ...
      strncpy(UDP_CMD , bufferHexa   ,  2); UDP_CMD[2]='\0'; strcpy(RX_UDP_Frame, UDP_CMD);
      strncpy(PCID    , bufferHexa+2 ,  2); PCID[2]='\0';    strcat(RX_UDP_Frame, PCID);
      strncpy(Nbytes  , bufferHexa+4 ,  2); Nbytes[2]='\0';  xtoi(Nbytes, &udp_bytes);     strcat(RX_UDP_Frame, Nbytes); udp_bytes = udp_bytes - 4;
      strncpy(SID     , bufferHexa+6 ,  4); SID[4]='\0';     strcat(RX_UDP_Frame, SID);
      strncpy(EID     , bufferHexa+10,  4); EID[4]='\0';     strcat(RX_UDP_Frame, EID);
      strncpy(Data    , bufferHexa+14, 16); Data[16]='\0';   strcat(RX_UDP_Frame, Data); RX_UDP_Frame[30]='\0';
      strncpy(FCS     , bufferHexa+30,  2); FCS[2]='\0';

      if ((verbose) && (strcmp(UDP_CMD, "70")) && (strcmp(UDP_CMD, "50"))) { printf("\n\n>RX UDP: %s", bufferHexa); }

      // FCS OK?
      domocan_checksum(RX_UDP_Frame, calc_FCS); calc_FCS[2]='\0';
      //printf("\nRX UDP: %s(UDP_CMD)-%s(PCID)-%d(DLC)-%s/%s(Header)-%s(Data)+%s(FCS)+CalcFCS=%s\nFull Frame= %s\n", UDP_CMD, PCID , udp_bytes, SID, EID, Data, FCS, calc_FCS, RX_UDP_Frame);

      if (!strcmp(FCS, calc_FCS)) {
        // Frame OK (FCS)
        // printf("...fcs OK...UDP_CMD=%s...", UDP_CMD);
        if (!strcmp(UDP_CMD, "60")) {
          // RX UDP_CMD=60 [Send CAN on Bus]
          if (verbose) printf("\nUDP_CMD=60 [Send CAN on BUS, ");

          // Convert SIDH and SIDL to binary (16 bits)
		  DomoCANframe[0]='\0'; bin_str[0]='\0';
		  htoi(SID, bin_val, bin_str);
		  // Convert SIDH and SIDL from UDP to CAN format
		  bin_val[0]='\0';
          UDPaddr_to_CAN(bin_str, bin_val);
		  // Convert back SIDH and SIDL to HEX
		  bintohex(bin_val, FCS); FCS[4]='\0';
		  DomoCANframe[0]='\0';
		  sprintf(DomoCANframe, "%s%s%s", "0x", FCS, EID);
		  DomoCANframe[10]='\0';
		  if (verbose) printf("Destination=%s]", SID);

		  frame.can_id     = strtoul(DomoCANframe, NULL, 0); //*msg_out;
		  frame.can_dlc    = udp_bytes;
		  Data[udp_bytes*2]  = '\0';
		  msg_out[0] = '\0';
          raw_len          = convert_raw(Data, msg_out); // Convert to RAW msg to send;
		  // Prepare CAN frame Data content
          for (i=0; i<=udp_bytes;i++) {
		    frame.data[i] = msg_out[i];
		  }
		  FCS[0]='\0';
          if ((nbytes = write(sc, &frame, sizeof(frame))) != sizeof(frame)) {
		    // Send NACK back to PC
			sprintf(FCS, "%s", "01"); FCS[2]='\0';
			//perror("CAN write __");
		  } else {
		    // Send ACK back to PC
		    sprintf(FCS, "%s", "00"); FCS[2]='\0';
		  } // END IF

          // CAN_err = sendto(s, &frame, sizeof(struct can_frame), 0, (struct sockaddr*)&caddr, sizeof(caddr));
          if (verbose) printf("\n=>TX CAN: Header=%s, Data=%s, DLC=%d, frame len= %d", DomoCANframe, Data, udp_bytes, sizeof(frame));

          // Send UDP Ack back to PC with error code 0=OK, 1=NOK
		  //      Frame = 50 PCID Length=1 ACK/NACK DummyBytes FCS 
          temp_msg[0]='\0';
		  sprintf(temp_msg, "%s%s%s", "50", PCID, "01",  FCS);		  
		  // Dummy bytes
		  for (i=6; i<=29;i++) {
		    temp_msg[i]='0';
		  } // END FOR
		  temp_msg[30] = '\0';
          // Calculating checksum (FCS)
		  domocan_checksum(temp_msg, fcs);
          strcat(temp_msg, fcs); temp_msg[32]='\0';
          raw_len = convert_raw(temp_msg, msg_out);
          printf("\n=>TX UDP CAN Send OK=Frame 0x50): %s",temp_msg);
          //s=sendto(sb, msg_out, 16, 0, (struct sockaddr *)&baddr, sizeof(baddr));

          //FD_ZERO(&readfds); // zero out the read set

		  // Prepare packet.
		  // First part is an IPv4 header.
		  memcpy (packet, &iphdr, IP4_HDRLEN);
		  // UDP checksum (16 bits)
          udphdr.check = udp4_checksum (iphdr, udphdr, msg_out, datalen);
		  // Next part of packet is upper layer protocol header.
		  memcpy ((packet + IP4_HDRLEN), &udphdr, UDP_HDRLEN);
		  // Finally, add the UDP data.
		  memcpy (packet + IP4_HDRLEN + UDP_HDRLEN, msg_out, datalen);
		  // Send packet.
		  if (sendto (sd, packet, IP4_HDRLEN + UDP_HDRLEN + datalen, 0, (struct sockaddr *) &sin, sizeof (struct sockaddr)) < 0)  {
			perror ("sendto() failed ");
			exit (EXIT_FAILURE);
		  } //END IF sendto


        } else { // END IF UDP_CMD=60

          if (!strcmp(UDP_CMD, "41")) {
            // RX UDP_CMD=41 [Stop Transmission]
            printf("\nRX UDP_CMD=41 [Stop Transmission]");


          } else { // END IF UDP_CMD=41
            if (!strcmp(UDP_CMD, "42")) {
              // RX UDP_CMD=42 [Change CAN Filter]
              printf("\nRX UDP_CMD=42 [Change CAN Filter]");

            } else { // END IF UDP_CMD=42
              if (!strcmp(UDP_CMD, "43")) {
                // RX UDP_CMD=43 [View CAN Filter]
                printf(" - RX UDP_CMD=43 [View CAN Filter ... ACK?]");

                // Send back Empty Filter
                msg_out[0]='\0'; temp_msg[0]='\0';
				sprintf(temp_msg, "%s%s%s", "52", PCID, "09");
				// Dummy bytes
				for (i=6; i<=30;i++) {
				  temp_msg[i]='0';
				} // END FOR
				temp_msg[30] = '\0';
                domocan_checksum(temp_msg, fcs);
                strcat(temp_msg, fcs); temp_msg[32]='\0';

                raw_len = convert_raw(temp_msg, msg_out);

                printf("\n=>TX UDP ACK! %s",temp_msg);
                //s=sendto(sb, msg_out, 16, 0, (struct sockaddr *)&baddr, sizeof(baddr));

			    // Prepare packet.
			    // First part is an IPv4 header.
			    memcpy (packet, &iphdr, IP4_HDRLEN);
				// UDP checksum (16 bits)
                udphdr.check = udp4_checksum (iphdr, udphdr, msg_out, datalen);
			    // Next part of packet is upper layer protocol header.
			    memcpy ((packet + IP4_HDRLEN), &udphdr, UDP_HDRLEN);
			    // Finally, add the UDP data.
			    memcpy (packet + IP4_HDRLEN + UDP_HDRLEN, msg_out, datalen);
			    // Send packet.
			    if (sendto (sd, packet, IP4_HDRLEN + UDP_HDRLEN + datalen, 0, (struct sockaddr *) &sin, sizeof (struct sockaddr)) < 0)  {
				  perror ("sendto() failed ");
				  exit (EXIT_FAILURE);
			    } // END IF sendto

                //sendto(sock,msg_out,raw_len,0,(struct sockaddr*)&UDPclient,clsize);

              } else { // END IF UDP_CMD=43
                if (!strcmp(UDP_CMD, "44")) {
                  // RX UDP_CMD=44 [Change CAN Param]
                  printf("\nRX UDP_CMD=44 [Change CAN Param]");

                } else { // END IF UDP_CMD=44
                  if (!strcmp(UDP_CMD, "45")) {
                    // RX UDP_CMD=45 [View CAN Param]
                    printf("\nRX UDP_CMD=45 [View CAN Param]");

                  } // END IF RX UDP_CMD=45
                } // END IF RX UDP_CMD=44
              } // END IF RX UDP_CMD=43
            } // END IF RX UDP_CMD=42
          } // END IF RX UDP_CMD=41
        } // END IF RX UDP_CMD=60

      } else {
        if ((verbose) && (!strcmp(UDP_CMD, "70")))  printf("\nRX UDP FCS NOK! (%s-%s<>%s)\n", RX_UDP_Frame, FCS, calc_FCS);
      } // END IF FCS ok




//      } // END IF read(sa)
    } // END IF Received a UDP packet
  } // END WHILE

close(sc);
close(sa);
close(sd);

// Free allocated memory.
  free (data);
  free (packet);
  free (interface);
  free (target);
  free (src_ip);
  free (dst_ip);
  free (ip_flags);

return 0;
} // END main
Esempio n. 6
0
static void do_belpic(sc_card_t *card)
{
	/* Contents of the ID file (3F00\DF01\4031) */
	struct {
		char cardnumber[12 + 1];
		char chipnumber[2 * 16 + 1];
		char validfrom[10 + 1];
		char validtill[10 + 1];
		char deliveringmunicipality[50 + 1];  /* UTF8 */
		char nationalnumber[12 + 1];
		char name[90 + 1]; /* UTF8 */
		char firstnames[75 + 1]; /* UTF8 */
		char initial[3 + 1]; /* UTF8 */
		char nationality[65 + 1]; /* UTF8 */
		char birthlocation[60 + 1]; /* UTF8 */
		char birthdate[12 + 1];
		char sex[1 + 1];
		char noblecondition[30 + 1]; /* UTF8 */
		char documenttype[5 + 1];
		char specialstatus[5 + 1];
	} id_data;
	int cardnumberlen = sizeof(id_data.cardnumber);
	int chipnumberlen = sizeof(id_data.chipnumber);
	int validfromlen = sizeof(id_data.validfrom);
	int validtilllen = sizeof(id_data.validtill);
	int deliveringmunicipalitylen = sizeof(id_data.deliveringmunicipality);
	int nationalnumberlen = sizeof(id_data.nationalnumber);
	int namelen = sizeof(id_data.name);
	int firstnameslen = sizeof(id_data.firstnames);
	int initiallen = sizeof(id_data.initial);
	int nationalitylen = sizeof(id_data.nationality);
	int birthlocationlen = sizeof(id_data.birthlocation);
	int birthdatelen = sizeof(id_data.birthdate);
	int sexlen = sizeof(id_data.sex);
	int nobleconditionlen = sizeof(id_data.noblecondition);
	int documenttypelen = sizeof(id_data.documenttype);
	int specialstatuslen = sizeof(id_data.specialstatus);

	struct sc_asn1_entry id[] = {
		{"cardnumber", SC_ASN1_UTF8STRING, 1, 0, id_data.cardnumber, &cardnumberlen},
		{"chipnumber", SC_ASN1_OCTET_STRING, 2, 0, id_data.chipnumber, &chipnumberlen},
		{"validfrom", SC_ASN1_UTF8STRING, 3, 0, id_data.validfrom, &validfromlen},
		{"validtill", SC_ASN1_UTF8STRING, 4, 0, id_data.validtill, &validtilllen},
		{"deliveringmunicipality", SC_ASN1_UTF8STRING, 5, 0, id_data.deliveringmunicipality, &deliveringmunicipalitylen},
		{"nationalnumber", SC_ASN1_UTF8STRING, 6, 0, id_data.nationalnumber, &nationalnumberlen},
		{"name", SC_ASN1_UTF8STRING, 7, 0, id_data.name, &namelen},
		{"firstname(s)", SC_ASN1_UTF8STRING, 8, 0, id_data.firstnames, &firstnameslen},
		{"initial", SC_ASN1_UTF8STRING, 9, 0, id_data.initial, &initiallen},
		{"nationality", SC_ASN1_UTF8STRING, 10, 0, id_data.nationality, &nationalitylen},
		{"birthlocation", SC_ASN1_UTF8STRING, 11, 0, id_data.birthlocation, &birthlocationlen},
		{"birthdate", SC_ASN1_UTF8STRING, 12, 0, id_data.birthdate, &birthdatelen},
		{"sex", SC_ASN1_UTF8STRING, 13, 0, id_data.sex, &sexlen},
		{"noblecondition", SC_ASN1_UTF8STRING, 14, 0, id_data.noblecondition, &nobleconditionlen},
		{"documenttype", SC_ASN1_UTF8STRING, 15, 0, id_data.documenttype, &documenttypelen},
		{"specialstatus", SC_ASN1_UTF8STRING, 16, 0, id_data.specialstatus, &specialstatuslen},
		{NULL, 0, 0, 0, NULL, NULL}
	};

	/* Contents of the Address file (3F00\DF01\4033) */
	struct {
		char streetandnumber[63 + 1]; /* UTF8 */
		char zipcode[4 + 1];
		char municipality[40 + 1]; /* UTF8 */
	} address_data;
	int streetandnumberlen = sizeof(address_data.streetandnumber);
	int zipcodelen = sizeof(address_data.zipcode);
	int municipalitylen = sizeof(address_data.municipality);
	struct sc_asn1_entry address[] = {
		{"streetandnumber", SC_ASN1_UTF8STRING, 1, 0, address_data.streetandnumber, &streetandnumberlen},
		{"zipcode", SC_ASN1_UTF8STRING, 2, 0, address_data.zipcode, &zipcodelen},
		{"municipal", SC_ASN1_UTF8STRING, 3, 0, address_data.municipality, &municipalitylen},
		{NULL, 0, 0, 0, NULL, NULL}};

	unsigned char buff[512];
	int r;

	r = read_transp(card, "3f00df014031", buff, sizeof(buff));
	if (r < 0)
		goto out;

	memset(&id_data, 0, sizeof(id_data));

	r = sc_asn1_decode(card->ctx, id, buff, r, NULL, NULL);
	if (r < 0) {
		fprintf(stderr, "\nFailed to decode the ID file: %s\n", sc_strerror(r));
		goto out;
	}

	exportprint("BELPIC_CARDNUMBER", id_data.cardnumber);
	bintohex(id_data.chipnumber, chipnumberlen);
	exportprint("BELPIC_CHIPNUMBER", id_data.chipnumber);
	exportprint("BELPIC_VALIDFROM", id_data.validfrom);
	exportprint("BELPIC_VALIDTILL", id_data.validtill);
	exportprint("BELPIC_DELIVERINGMUNICIPALITY", id_data.deliveringmunicipality);
	exportprint("BELPIC_NATIONALNUMBER", id_data.nationalnumber);
	exportprint("BELPIC_NAME", id_data.name);
	exportprint("BELPIC_FIRSTNAMES", id_data.firstnames);
	exportprint("BELPIC_INITIAL", id_data.initial);
	exportprint("BELPIC_NATIONALITY", id_data.nationality);
	exportprint("BELPIC_BIRTHLOCATION", id_data.birthlocation);
	exportprint("BELPIC_BIRTHDATE", id_data.birthdate);
	exportprint("BELPIC_SEX", id_data.sex);
	exportprint("BELPIC_NOBLECONDITION", id_data.noblecondition);
	exportprint("BELPIC_DOCUMENTTYPE", id_data.documenttype);
	exportprint("BELPIC_SPECIALSTATUS", id_data.specialstatus);

	r = read_transp(card, "3f00df014033", buff, sizeof(buff));
	if (r < 0)
		goto out;

	memset(&address_data, 0, sizeof(address_data));

	r = sc_asn1_decode(card->ctx, address, buff, r, NULL, NULL);
	if (r < 0) {
		fprintf(stderr, "\nFailed to decode the Address file: %s\n", sc_strerror(r));
		goto out;
	}

	exportprint("BELPIC_STREETANDNUMBER", address_data.streetandnumber);
	exportprint("BELPIC_ZIPCODE", address_data.zipcode);
	exportprint("BELPIC_MUNICIPALITY", address_data.municipality);

out:
	return;
}
Esempio n. 7
0
int main(int argc, char* argv[])
{
// TEST 0: test 7bit <=> 8bits conversions
//  int size;
//  char hello7[] = "E8329BFD4697D9EC37";
//  char hello8[] = "hellohello";
//  char buf[20];
//
//  size = convert_7bit_to_ascii(hello7, 5, 5, buf);
//  buf[size] = 0;
//  printf("7bits size: %d, %s\n", size, buf);
//
//  size = convert_ascii_to_7bit(hello8, 0, 10, buf);
//  printf("8bits size: %d\n", size);
//
//  exit(0);


  // TEST: Test PDU decoding
  //char pdu[] = "07914487200030232408E602710079000490306161131000047071727374";
  //char pdu[] = "07914487200030236408E6027100790004903031415260000F060504080008006162636465666768";
  //char pdu[] = "07917283010010F5040BC87238880900F10000993092516195800AE8329BFD4697D9EC37";

  // Concat SMS: 4 SMS
  //char pdu[] = "07914477581006504408A1027100790004905091312162408C050003010401DEADBEEF31062F1F2DB69181924435354641464639314446443933463538303838333342443643414131454234453034333234343400030B6A00C54601C655018711060357636D4E41504944000187070603496E73674E41504E616D650001871006AB01870806037761702E766F69636573747265616D2E636F6D00018709060341504E0001";
  //char pdu[] = "07914477581006504008A1027100790004905091315155408C050003010402871401C65A01870C06035041500001870D0603757365726E616D650001870E060370776400010101C600015501873606037737000187380603504C54000187070603504C540001870503494E49540001C6560187340603687474703A2F2F3132372E302E302E312F0001C60000530187230603383000010101870503544F2D50524F58590006";
  //char pdu[] = "07914477581006504008A1027100790004905091316163408C050003010403036C6F6750726F78790001C6000157018730068D0187310603504C54000187320603393939390001872F06033930323030000101C6570187300603434C49454E540001873106033432353938333431373732323732360001873306930187320603393939390001872F0603393032303000010101C600005101871506036C6F6750726F787900";
  //char pdu[] = "07914477581006504408A102710079000490509131716140490500030104040187070603426F6F7473747261702050726F78790001C65201872F060370687950726F7879000187200603000187210685018722060357636D4E415049440001010101";

  //char pdu[] = "099188320580200000F0040F9188320500002123F300007080708163148A13D4F29C9E769F4166F9BB0D5286E7F0B21C";
  //char pdu[] = "07913366003000F0040B913366982288F80000903031017462401DF4F71B444FD3D3207A981E06A5D9A076D81DAF9741753788DE00";
  //char pdu[] = "07914477581006500410D0F4BA9C5DA7D7E975000090601171704540087537885EC6D3CB";
  char pdu[] = "07914487200030236408E602710079000490901241440540390605040B840B8455060401C4AF872DE46143016A29441C325FEE961FE50F02F80000009E721357415645434F4D2D52444D532D534552564552";

  char buf[400];
  buf[0] = 0;
  int code;
  SMS* sms;

  code = decode_smspdu(pdu, &sms);
  bintohex(sms->message, sms->message_length, buf, 0);
  buf[sms->message_length*2] = 0;
  printf("retcode %d\n", code);
  printf("SMS:\n\tSender: %s\n\tMessage: length:%d, %s\n", sms->address, sms->message_length, sms->message);
  printf("HEX: %s\n", buf);
  if (sms->concat_maxnb>1)
  {
    printf("CONCAT SMS detected !\n");
    printf("concat_ref:%d concat_maxnb:%d, concat_seqnb:%d\n", sms->concat_ref, sms->concat_maxnb, sms->concat_seqnb);
  }
  if (sms->portbits)
  {
    printf("SMS contains ports\n");
    printf("bits=%d, dst=%d, src=%d\n", sms->portbits, sms->dstport, sms->srcport);
  }


  // TEST 3: test PDU encoding
//  int nb, i;
//  PDU* pdu;
//  char message[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcd0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcd0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcd0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcd0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcd";
//  //char message[] ="hellohello";
//
//  nb = encode_smspdu(message, sizeof(message)-1, "0622468910", &pdu);
//
//  printf("Nb of sms: %d\n", nb);
//  for (i = 0; i < nb; ++i)
//  {
//    printf("PDU %d: size:%d, [%s] [%d]\n", i, pdu[i].size, pdu[i].buffer, strlen(pdu[i].buffer)/2);
//  }



  return 0;
}
Esempio n. 8
0
    }
    else{
        std::stringstream s; s << static_cast <unsigned int> (pka);
        throw std::runtime_error("Error: PKA number " + s.str() + " not allowed or unknown.");
    }
    return {}; // should never reach here; mainly just to remove compiler warnings
}

std::vector <PGPMPI> pka_encrypt(const uint8_t pka, const std::string & data, const std::vector <PGPMPI> & pub){
    return pka_encrypt(pka, rawtompi(data), pub);
}

Packet::Ptr encrypt_data(const std::string & session_key, const std::string & data, const std::string & filename, const uint8_t sym_alg, const uint8_t comp, const bool mdc, const PGPSecretKey::Ptr & signer, const std::string & sig_passphrase){
    // generate prefix
    uint16_t BS = Symmetric_Algorithm_Block_Length.at(Symmetric_Algorithms.at(sym_alg)) >> 3;
    std::string prefix = unhexlify(zfill(bintohex(BBS().rand(BS << 3)), BS << 1, '0'));

    std::string to_encrypt;

    // put data in Literal Data Packet
    Tag11 tag11;
    tag11.set_format('t');
    tag11.set_filename(filename);
    tag11.set_time(0);
    tag11.set_literal(data);

    to_encrypt = tag11.write(2);

    // // if message is to be signed
    // if (signer){
        // // find preferred hash and compression algorithms of the signer
int main( )
{ 
FILE *fs, *ft,*fp ;
char ch ;
int myhex = 0x0001;
int b1,b2,b3,b4;
int i,j,k;
char a[14];
int a1,a2,a3,a4,a5,a6,a7;
fs = fopen ( "C:\\Users\\abhis_000\\Desktop\\project\\sampletext.txt", "r" ) ;// opening the file where we have saved the hex data to read it
ft = fopen ( "C:\\Users\\abhis_000\\Desktop\\project\\binary.txt", "w" ); // opening the file to write the binary of corresponding hex data
while ( 1 )
{	
ch = fgetc ( fs ) ;// reads single character from sampletext.txt file 
         switch(ch) // uses switch statement to convert the hexadecimal number in its corresponding binary
		 {
             		case '0':
             		{b4=0;b3=0;b2=0;b1=0; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case '1':
             			{b4=0;b3=0;b2=0;b1=1; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case '2':
			 	{b4=0;b3=0;b2=1;b1=0; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case '3':
			 	{b4=0;b3=0;b2=1;b1=1; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case '4':
			 	{b4=0;b3=1;b2=0;b1=0; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case '5':
			 	{b4=0;b3=1;b2=0;b1=1; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case '6':
			 	{b4=0;b3=1;b2=1;b1=0; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case '7':
			 	{b4=0;b3=1;b2=1;b1=1; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case '8':
			 	{b4=1;b3=0;b2=0;b1=0; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case '9':
			 	{b4=1;b3=0;b2=0;b1=1; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case 'A':
			 	{b4=1;b3=0;b2=1;b1=0; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case 'a':
			 	{b4=1;b3=0;b2=1;b1=0; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case 'B':
			 	{b4=1;b3=0;b2=1;b1=1; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case 'b':
			 	{b4=1;b3=0;b2=1;b1=1; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case 'C':
			 	{b4=1;b3=1;b2=0;b1=0; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case 'c':
			 	{b4=1;b3=1;b2=0;b1=0; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case 'D':
			 	{b4=1;b3=1;b2=0;b1=1; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case 'd':
			 	{b4=1;b3=1;b2=0;b1=1; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case 'E':
			 	{b4=1;b3=1;b2=1;b1=0; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case 'e':
			 	{b4=1;b3=1;b2=1;b1=0; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case 'F':
			 	{b4=1;b3=1;b2=1;b1=1; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
			 	case 'f':
			 	{b4=1;b3=1;b2=1;b1=1; 
			 	fprintf(ft,"%d%d%d%d",b4,b3,b2,b1);
			 	break;
			 	}
    }
if (ch == EOF)
break ;
}
fclose ( fs ) ; // closes sampletext.txt file
fclose (ft); // closes binary.txt file


fp = fopen ("C:\\Users\\abhis_000\\Desktop\\project\\binary.txt","r") ;  // opening the file in read mode to read the binary data
ff = fopen ("C:\\Users\\abhis_000\\Desktop\\project\\assembly.txt","w"); //opening a new file where we will save the assembly language code

while(1)
{
fprintf(ff,"\n%04x\t",myhex); // for printing the address of the memory location
for(i=0; i<14; i++) // loop runs 14 times so as to store 14 bits of binary data into the array a[i]
{
a[i] = fgetc(fp); // array gets stored with 14 bits of binary data
}


/* comapres the array characters with the instruction set format and then saves a instruction 
based on the bit sequence onto the file assembly.txt*/

if ((a[5]==49)&&(a[4]==49)&&(a[3]==49)&&(a[2]==48)&&(a[1]==48)&&(a[0]==48))
{
fputs("ADDWF\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7); 
fprintf(ff,"\t%c",a[6]);
 myhex++;
}
else if ((a[5]==49)&&(a[4]==48)&&(a[3]==49)&&(a[2]==48)&&(a[1]==48)&&(a[0]==48))
{
fputs("ANDWF\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fprintf(ff,"\t%c",a[6]); myhex++;
}
else if (a[6]==49&&a[5]==49&&a[4]==48&&a[3]==48&&a[2]==48&&a[1]==48&&a[0]==48)
{
fputs("CLRF\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7); myhex++;
}
else if (a[6]==48&&a[5]==49&&a[4]==48&&a[3]==48&&a[2]==48&&a[1]==48&&a[0]==48)
{
fputs("CLRW",ff); myhex++;
}
else if (a[5]==49&&a[4]==48&&a[3]==48&&a[2]==49&&a[1]==48&&a[0]==48)
{
fputs("COMF\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fprintf(ff,"\t%c",a[6]); myhex++;
}
else if (a[5]==49&&a[4]==49&&a[3]==48&&a[2]==48&&a[1]==48&&a[0]==48)
{
fputs("DECF\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fprintf(ff,"\t%c",a[6]); myhex++;
}
else if (a[5]==49&&a[4]==49&&a[3]==48&&a[2]==49&&a[1]==48&&a[0]==48)
{
fputs("DECFSZ\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fprintf(ff,"\t%c",a[6]); myhex++;
}
else if (a[5]==48&&a[4]==49&&a[3]==48&&a[2]==49&&a[1]==48&&a[0]==48)
{
fputs("INCF\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fprintf(ff,"\t%c",a[6]); myhex++;
}
else if (a[5]==49&&a[4]==49&&a[3]==49&&a[2]==49&&a[1]==48&&a[0]==48)
{
fputs("INCFSZ\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fprintf(ff,"\t%c",a[6]); myhex++;
}
else if ((a[5]==48)&&(a[4]==48)&&(a[3]==49)&&(a[2]==48)&&(a[1]==48)&&(a[0]==48))
{
fputs("IORWF\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fprintf(ff,"\t%c",a[6]); myhex++;
}
else if (a[5]==48&&a[4]==48&&a[3]==48&&a[2]==49&&a[1]==48&&a[0]==48)
{
fputs("MOVF\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fprintf(ff,"\t%c",a[6]); myhex++;
}
else if (a[5]==49&&a[4]==48&&a[3]==49&&a[2]==49&&a[1]==48&&a[0]==48)
{
fputs("RLF\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fprintf(ff,"\t%c",a[6]); myhex++;
}
else if (a[5]==48&&a[4]==48&&a[3]==49&&a[2]==49&&a[1]==48&&a[0]==48)
{
fputs("RRF\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fprintf(ff,"\t%c",a[6]); myhex++;
}
else if (a[5]==48&&a[4]==49&&a[3]==48&&a[2]==48&&a[1]==48&&a[0]==48)
{
fputs("SUBWF\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fprintf(ff,"\t%c",a[6]); myhex++;
}
else if (a[5]==48&&a[4]==49&&a[3]==49&&a[2]==49&&a[1]==48&&a[0]==48)
{
fputs("SWAPF\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fprintf(ff,"\t%c",a[6]); myhex++;
}
else if (a[5]==48&&a[4]==49&&a[3]==49&&a[2]==48&&a[1]==48&&a[0]==48)
{
fputs("XORWF\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fprintf(ff,"\t%c",a[6]); myhex++;
}
else if (a[3]==48&&a[2]==48&&a[1]==49&&a[0]==48)
{
fputs("BCF\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fputs("\t",ff);
char bin4[MAX] = {(int)a[4],(int)a[5],(int)a[6]};
bintohex(bin4); myhex++;
}
else if (a[3]==49&&a[2]==48&&a[1]==49&&a[0]==48)
{
fputs("BSF\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fputs("\t",ff);
char bin4[MAX] =  {(int)a[4],(int)a[5],(int)a[6]};
bintohex(bin4); myhex++;
}
else if (a[3]==48&&a[2]==49&&a[1]==49&&a[0]==48)
{
fputs("BTFSC\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fputs("\t",ff);
char bin4[MAX] = {(int)a[4],(int)a[5],(int)a[6]};
bintohex(bin4); myhex++;

}
else if (a[3]==49&&a[2]==49&&a[1]==49&&a[0]==48)
{
fputs("BTFSS\t0x",ff);
char bin7[MAX] = {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7);
fputs("\t",ff);
char bin4[MAX] =  {(int)a[4],(int)a[5],(int)a[6]};
bintohex(bin4); myhex++;
}
else if (a[4]==49&&a[3]==49&&a[2]==49&&a[1]==49&&a[0]==49)
{
fputs("ADDLW\t0x",ff);
char bin6[MAX] = {(int)a[6],(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin6); myhex++;
}
else if (a[5]==49&&a[4]==48&&a[3]==48&&a[2]==49&&a[1]==49&&a[0]==49)
{
fputs("ANDLW\t0x",ff);
char bin6[MAX] = {(int)a[6],(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin6); myhex++;
}
else if (a[2]==48&&a[1]==48&&a[0]==49)
{
fputs("CALL\t0x",ff);
char bin3[MAX] = {(int)a[3],(int)a[4],(int)a[5],(int)a[6],(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin3); myhex++;
}
else if (a[2]==49&&a[1]==48&&a[0]==49)
{
fputs("GOTO\t0x",ff);
char bin3[MAX] = {(int)a[3],(int)a[4],(int)a[5],(int)a[6],(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin3); myhex++;
}
else if (a[5]==48&&a[4]==48&&a[3]==48&&a[2]==49&&a[1]==49&&a[0]==49)
{
fputs("IORLW\t0x",ff);
char bin6[MAX] ={(int)a[6],(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin6); myhex++;
}
else if (a[3]==48&&a[2]==48&&a[1]==49&&a[0]==49)
{
fputs("MOVLW\t0x",ff);
char bin6[MAX] = {(int)a[6],(int)a[7],(int)a[8],(int)a[9],(int)a[10],a[11],a[12],a[13]};
bintohex(bin6); myhex++;
}
else if (a[3]==49&&a[2]==48&&a[1]==49&&a[0]==49)
{
fputs("RETLW\t0x",ff);
char bin6[MAX] =  {(int)a[6],(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin6); myhex++;
}
else if (a[4]==48&&a[3]==49&&a[2]==49&&a[1]==49&&a[0]==49)
{
fputs("SUBLW\t0x",ff);
char bin6[MAX] =  {(int)a[6],(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin6); myhex++;
}
else if (a[5]==48&&a[4]==49&&a[3]==48&&a[2]==49&&a[1]==49&&a[0]==49)
{
fputs("XORLW\t0x",ff);
char bin6[MAX] =  {(int)a[6],(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin6); myhex++;
}
else if (a[6]==49&&a[5]==48&&a[4]==48&&a[3]==48&&a[2]==48&&a[1]==48&&a[0]==48)
{
fputs("MOVWF\t0x",ff);
char bin7[MAX] =  {(int)a[7],(int)a[8],(int)a[9],(int)a[10],(int)a[11],(int)a[12],(int)a[13]};
bintohex(bin7); myhex++;
}
else if (a[13]==48&&a[12]==48&&a[11]==48&&a[10]==48&&a[9]==48&&a[6]==48&&a[5]==48&&a[4]==48&&a[3]==48&&a[2]==48&&a[1]==48&&a[0]==48)
{
fputs("NOP",ff); myhex++;
}
else if (a[13]==48&&a[12]==48&&a[11]==49&&a[10]==48&&a[9]==48&&a[8]==49&&a[7]==49&&a[6]==48&&a[5]==48&&a[4]==48&&a[3]==48&&a[2]==48&&a[1]==48&&a[0]==48)
{
fputs("CLRWDT",ff); myhex++;
}
else if (a[13]==49&&a[12]==48&&a[11]==48&&a[10]==49&&a[9]==48&&a[8]==48&&a[7]==48&&a[6]==48&&a[5]==48&&a[4]==48&&a[3]==48&&a[2]==48&&a[1]==48&&a[0]==48)
{
fputs("RETFIE",ff); myhex++;
}
else if (a[13]==49&&a[12]==49&&a[11]==48&&a[10]==48&&a[9]==48&&a[8]==49&&a[7]==49&&a[6]==48&&a[5]==48&&a[4]==48&&a[3]==48&&a[2]==48&&a[1]==48&&a[0]==48)
{
fputs("SLEEP",ff); myhex++;
}
else if (a[13]==48&&a[12]==48&&a[11]==48&&a[10]==49&&a[9]==48&&a[8]==48&&a[7]==48&&a[6]==48&&a[5]==48&&a[4]==48&&a[3]==48&&a[2]==48&&a[1]==48&&a[0]==48)
{
fputs("RETURN",ff); myhex++;
}
else
{fputs("UNDEFINED",ff);myhex++;}
}
fclose(ff); // closes assembly.txt file
fclose(fp); // closes binary.txt file
return 0;
}
Esempio n. 10
0
/*
 * generate
 */
static int
do_generate(const char *inputfilename, int lineno, int argc, const char **argv)
{
    const char *displayname;
    int major_version, minor_version;
    XSecurityAuthorization id_return;
    Xauth *auth_in, *auth_return;
    XSecurityAuthorizationAttributes attributes;
    unsigned long attrmask = 0;
    Display *dpy;
    int status;
    const char *args[4];
    const char *protoname = ".";
    int i;
    int authdatalen = 0;
    const char *hexdata;
    char *authdata = NULL;
    char *hex;

    if (argc < 2 || !argv[1]) {
	prefix (inputfilename, lineno);
	badcommandline (argv[0]);
	return 1;
    }

    displayname = argv[1];

    if (argc > 2) {
	protoname = argv[2];
    }

    for (i = 3; i < argc; i++) {
	if (0 == strcmp(argv[i], "timeout")) {
	    if (++i == argc) {
		prefix (inputfilename, lineno);
		badcommandline (argv[i-1]);
		return 1;
	    }
	    attributes.timeout = atoi(argv[i]);
	    attrmask |= XSecurityTimeout;

	} else if (0 == strcmp(argv[i], "trusted")) {
	    attributes.trust_level = XSecurityClientTrusted;
	    attrmask |= XSecurityTrustLevel;

	} else if (0 == strcmp(argv[i], "untrusted")) {
	    attributes.trust_level = XSecurityClientUntrusted;
	    attrmask |= XSecurityTrustLevel;

	} else if (0 == strcmp(argv[i], "group")) {
	    if (++i == argc) {
		prefix (inputfilename, lineno);
		badcommandline (argv[i-1]);
		return 1;
	    }
	    attributes.group = atoi(argv[i]);
	    attrmask |= XSecurityGroup;

	} else if (0 == strcmp(argv[i], "data")) {
	    if (++i == argc) {
		prefix (inputfilename, lineno);
		badcommandline (argv[i-1]);
		return 1;
	    }
	    hexdata = argv[i];
	    authdatalen = strlen(hexdata);
	    if (hexdata[0] == '"' && hexdata[authdatalen-1] == '"') {
		authdata = malloc(authdatalen-1);
		strncpy(authdata, hexdata+1, authdatalen-2);
		authdatalen -= 2;
	    } else {
		authdatalen = cvthexkey (hexdata, &authdata);
		if (authdatalen < 0) {
		    prefix (inputfilename, lineno);
		    fprintf (stderr,
			     "data contains odd number of or non-hex characters\n");
		    return 1;
		}
	    }
	} else {
	    prefix (inputfilename, lineno);
	    badcommandline (argv[i]);
	    return 1;
	}
    }

    /* generate authorization using the Security extension */

    dpy = XOpenDisplay (displayname);
    if (!dpy) {
	prefix (inputfilename, lineno);
	fprintf (stderr, "unable to open display \"%s\".\n", displayname);
	return 1;
    }

    status = XSecurityQueryExtension(dpy, &major_version, &minor_version);
    if (!status)
    {
	prefix (inputfilename, lineno);
	fprintf (stderr, "couldn't query Security extension on display \"%s\"\n",
		 displayname);
        return 1;
    }

    /* fill in input Xauth struct */

    auth_in = XSecurityAllocXauth();
    if (strcmp (protoname, DEFAULT_PROTOCOL_ABBREV) == 0) {
	 auth_in->name = copystring(DEFAULT_PROTOCOL, strlen(DEFAULT_PROTOCOL));
    }
    else
	auth_in->name = copystring (protoname, strlen(protoname));
    auth_in->name_length = strlen(auth_in->name);
    auth_in->data = authdata;
    auth_in->data_length = authdatalen;

    x_protocol_error = 0;
    XSetErrorHandler(catch_x_protocol_error);
    auth_return = XSecurityGenerateAuthorization(dpy, auth_in, attrmask,
						 &attributes, &id_return);
    XSync(dpy, False);

    if (!auth_return || x_protocol_error)
    {
	prefix (inputfilename, lineno);
	fprintf (stderr, "couldn't generate authorization\n");
	return 1;
    }

    if (verbose)
	printf("authorization id is %ld\n", id_return);

    /* create a fake input line to give to do_add */
    hex = bintohex(auth_return->data_length, auth_return->data);
    args[0] = "add";
    args[1] = displayname;
    args[2] = auth_in->name;
    args[3] = hex;

    status = do_add(inputfilename, lineno, 4, args);

    if (authdata) free(authdata);
    XSecurityFreeXauth(auth_in);
    XSecurityFreeXauth(auth_return);
    free(hex);
    XCloseDisplay(dpy);
    return status;
}