int hashtable_insert(hashtable_t *h, int32_t key, void *p) {
    size_t hashv = calc_hash(h, key);
    hash_item_t *item = h->T + hashv;

    if (!item->p) {
        item->key = key;
        item->p = p;
        return 0;

    } else {
        hash_item_t *new_item = calloc(1, sizeof(hash_item_t));
        if (!new_item) {
            fprintf(stderr, "out of memory in hashtable_insert()\n");
            return -1;
        }

        new_item->key = key;
        new_item->p = p;

        new_item->next = item->next;
        item->next = new_item;
        return 0;
    }
}
Exemple #2
0
/** Add or change an incidence on the calendar. This function
 * is used for events and to-dos
 */
bool KCalSharedResource::commit(OSyncDataSource *dsobj, OSyncContext *ctx, OSyncChange *chg)
{
	OSyncChangeType type = osync_change_get_changetype(chg);
	switch (type) {
		case OSYNC_CHANGE_TYPE_DELETED: {
			KCal::Incidence *e = calendar->incidence(QString::fromUtf8(osync_change_get_uid(chg)));
			if (!e) {
				osync_context_report_error(ctx, OSYNC_ERROR_FILE_NOT_FOUND, "Event not found while deleting");
				return false;
			}
			calendar->deleteIncidence(e);
			break;
		}
		case OSYNC_CHANGE_TYPE_ADDED:
		case OSYNC_CHANGE_TYPE_MODIFIED: {
			KCal::ICalFormat format;

			OSyncData *odata = osync_change_get_data(chg);

			char *databuf;
			//size_t databuf_size;
			// osync_data_get_data requires an unsigned int which is not compatible with size_t on 64bit machines
			unsigned int databuf_size = 0;
			osync_data_get_data(odata, &databuf, &databuf_size);

			/* First, parse to a temporary calendar, because
				* we should set the uid on the events
				*/

			KCal::CalendarLocal cal(QString::fromLatin1( "UTC" ));
			QString data = QString::fromUtf8(databuf, databuf_size);
			if (!format.fromString(&cal, data)) {
				osync_context_report_error(ctx, OSYNC_ERROR_CONVERT, "Couldn't import calendar data");
				return false;
			}

			KCal::Incidence *oldevt = calendar->incidence(QString::fromUtf8(osync_change_get_uid(chg)));
			if (oldevt) {
				calendar->deleteIncidence(oldevt);
                        }

			/* Add the events from the temporary calendar, setting the UID
				*
				* We iterate over the list, but it should have only one event.
				*/
			KCal::Incidence::List evts = cal.incidences();
			for (KCal::Incidence::List::ConstIterator i = evts.begin(); i != evts.end(); i++) {
				KCal::Incidence *e = (*i)->clone();
				if (type == OSYNC_CHANGE_TYPE_MODIFIED)
					e->setUid(QString::fromUtf8(osync_change_get_uid(chg)));

				// if we run with a configured category filter, but the received added incidence does
				// not contain that category, add the filter-categories so that the incidence will be
				// found again on the next sync
				if ( ! dsobj->has_category(e->categories()) )
        {
          QStringList cats = e->categories();

					for (QStringList::const_iterator it = dsobj->categories.constBegin(); it != dsobj->categories.constEnd(); ++it )
						cats.append(*it);

          e->setCategories(cats);
				}

				osync_change_set_uid(chg, e->uid().utf8());
				QString hash = calc_hash(*i);
				osync_change_set_hash(chg, hash.utf8());
				calendar->addIncidence(e);
			}
			break;
		}
		default: {
			osync_context_report_error(ctx, OSYNC_ERROR_NOT_SUPPORTED, "Invalid or unsupported change type");
			return false;
		}
	}

	return true;
}
Exemple #3
0
static ssize_t felica_cen_write(struct file *file, const char __user *buf,
					size_t count, loff_t *offset)
{
	int ret;
	char kbuf;
	u8 *src;
	u8 hash[AUTH_HASH_LEN];
	struct miscdevice *c = file->private_data;
	struct felica_dev *d = container_of(c, struct felica_dev, device_cen);

	dev_dbg(d->device_cen.this_device, "%s\n", __func__);

	if ((AUTHENTICATION_LEN+1) != count || buf == NULL) {
		dev_err(d->device_cen.this_device,
				"%s: Error. Invalid arg @CEN write.\n",
					__func__);
		ret = -EINVAL;
		goto exit;
	}

	/* Carry out user authentication */
	src = kmalloc(AUTHENTICATION_LEN, GFP_KERNEL);
	if (!src) {
		dev_err(d->device_cen.this_device,
				"%s: Error. No enough mem for Auth.\n",
					__func__);
		ret = -ENOMEM;
		goto exit;
	}
	ret = copy_from_user(src, buf, AUTHENTICATION_LEN);
	if (ret) {
		dev_err(d->device_cen.this_device,
				"%s: Error. copy_from_user failure.\n",
					__func__);
		ret = -EFAULT;
		goto end_process;
	}

	if (calc_hash(src, AUTHENTICATION_LEN, hash,
					d->device_cen.this_device)) {
		dev_err(d->device_cen.this_device,
				"%s: Error. calc hash digest failure.\n",
					__func__);
		ret = -EACCES;
		goto end_process;
	}

	if (memcmp(auth_hash, hash, AUTH_HASH_LEN)) {
		dev_err(d->device_cen.this_device,
				"%s: Error. invalid authentication.\n",
					__func__);
		ret = -EACCES;
		goto end_process;
	}

	/* Copy value from user space */
	ret = copy_from_user(&kbuf, &buf[AUTHENTICATION_LEN], sizeof(kbuf));
	if (ret) {
		dev_err(d->device_cen.this_device,
				"%s: Error. copy_from_user failure.\n",
					__func__);
		ret = -EFAULT;
		goto end_process;
	}

	ret = d->flcen->cen_write(kbuf, d);
	if (ret) {
		dev_err(d->device_cen.this_device,
				"%s: Error. Cannot write PM-nfc.\n", __func__);
		goto end_process;
	}

	/* usec delay*/
	udelay(UDELAY_CEN_WRITE);

	/* 1 byte write */
	ret = 1;

end_process:
	kfree(src);
exit:
	return ret;
}
Exemple #4
0
static void test_calc_hash(void)
{
    ok(calc_hash(H2O_STRLIT("https://example.com/style.css"), H2O_STRLIT("")) == 0xbaf9e86f03330860);
    ok(calc_hash(H2O_STRLIT("https://example.com/style.css"), H2O_STRLIT("\"deadbeef\"")) == 0xa53eb398509042d7);
}
Exemple #5
0
/**
   Initialise the state for NTLMSSP signing.
*/
NTSTATUS ntlmssp_sign_init(NTLMSSP_STATE *ntlmssp_state)
{
    unsigned char p24[24];
    ZERO_STRUCT(p24);

    DEBUG(3, ("NTLMSSP Sign/Seal - Initialising with flags:\n"));
    debug_ntlmssp_flags(ntlmssp_state->neg_flags);

    if (!ntlmssp_state->session_key.length) {
        DEBUG(3, ("NO session key, cannot intialise signing\n"));
        return NT_STATUS_NO_USER_SESSION_KEY;
    }

    if (ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_NTLM2)
    {
        const char *send_sign_const;
        const char *send_seal_const;
        const char *recv_sign_const;
        const char *recv_seal_const;

        switch (ntlmssp_state->role) {
        case NTLMSSP_CLIENT:
            send_sign_const = CLI_SIGN;
            send_seal_const = CLI_SEAL;
            recv_sign_const = SRV_SIGN;
            recv_seal_const = SRV_SEAL;
            break;
        case NTLMSSP_SERVER:
            send_sign_const = SRV_SIGN;
            send_seal_const = SRV_SEAL;
            recv_sign_const = CLI_SIGN;
            recv_seal_const = CLI_SEAL;
            break;
        }

        calc_ntlmv2_hash(ntlmssp_state->send_sign_hash,
                         ntlmssp_state->send_sign_const,
                         ntlmssp_state->session_key, send_sign_const);
        dump_data_pw("NTLMSSP send sign hash:\n",
                     ntlmssp_state->send_sign_hash,
                     sizeof(ntlmssp_state->send_sign_hash));

        calc_ntlmv2_hash(ntlmssp_state->send_seal_hash,
                         ntlmssp_state->send_seal_const,
                         ntlmssp_state->session_key, send_seal_const);
        dump_data_pw("NTLMSSP send sesl hash:\n",
                     ntlmssp_state->send_seal_hash,
                     sizeof(ntlmssp_state->send_seal_hash));

        calc_ntlmv2_hash(ntlmssp_state->recv_sign_hash,
                         ntlmssp_state->recv_sign_const,
                         ntlmssp_state->session_key, recv_sign_const);
        dump_data_pw("NTLMSSP receive sign hash:\n",
                     ntlmssp_state->recv_sign_hash,
                     sizeof(ntlmssp_state->recv_sign_hash));

        calc_ntlmv2_hash(ntlmssp_state->recv_seal_hash,
                         ntlmssp_state->recv_seal_const,
                         ntlmssp_state->session_key, recv_seal_const);
        dump_data_pw("NTLMSSP receive seal hash:\n",
                     ntlmssp_state->recv_sign_hash,
                     sizeof(ntlmssp_state->recv_sign_hash));

    }
    else if (ntlmssp_state->neg_flags & NTLMSSP_NEGOTIATE_LM_KEY) {
        if (!ntlmssp_state->session_key.data || ntlmssp_state->session_key.length < 8) {
            /* can't sign or check signatures yet */
            DEBUG(5, ("NTLMSSP Sign/Seal - cannot use LM KEY yet\n"));
            return NT_STATUS_UNSUCCESSFUL;
        }

        DEBUG(5, ("NTLMSSP Sign/Seal - using LM KEY\n"));

        calc_hash(ntlmssp_state->ntlmssp_hash, (const char *)(ntlmssp_state->session_key.data), 8);
        dump_data_pw("NTLMSSP hash:\n", ntlmssp_state->ntlmssp_hash,
                     sizeof(ntlmssp_state->ntlmssp_hash));
    } else {
        if (!ntlmssp_state->session_key.data || ntlmssp_state->session_key.length < 16) {
            /* can't sign or check signatures yet */
            DEBUG(5, ("NTLMSSP Sign/Seal - cannot use NT KEY yet\n"));
            return NT_STATUS_UNSUCCESSFUL;
        }

        DEBUG(5, ("NTLMSSP Sign/Seal - using NT KEY\n"));

        calc_hash(ntlmssp_state->ntlmssp_hash, (const char *)(ntlmssp_state->session_key.data), 16);
        dump_data_pw("NTLMSSP hash:\n", ntlmssp_state->ntlmssp_hash,
                     sizeof(ntlmssp_state->ntlmssp_hash));
    }

    ntlmssp_state->ntlmssp_seq_num = 0;

    return NT_STATUS_OK;
}
	bool write() {
		hash = calc_hash(data);
		return system_rtc_mem_write(USER_DATA_ADDR, this, sizeof(*this));
	}
Exemple #7
0
int main(int argc, char* argv[]) {
  int i;
  int fd, len;
  char* elf;
  int entry, phoff, phnum;
  int* ph;

#if 0
  if (argc < 2)
    error("Usage: el <elf>");
  LOG("loading %s\n", argv[1]);
#endif
  fd = open("simple_hash", O_RDONLY);
  if (fd < 0)
    error("Usage: el <elf>");
  len = lseek(fd, 0, SEEK_END);
  elf = (char*)malloc(len);
  lseek(fd, 0, SEEK_SET);
  read(fd, elf, len);

  if (*(int*)elf != 0x464c457f)
    error("not elf");
  if (*(int*)(elf+16) != 0x30002)
    error("not i386 exec");

  entry = *(int*)(elf+24);
  phoff = *(int*)(elf+28);
  phnum = *(int*)(elf+42);
  LOG("%x %x %x\n", entry, phoff, phnum);

  ph = (int*)(elf + phoff);
  for (i = 0; i < phnum >> 16; i++) {
    int poff, paddr, pfsize, psize, pafsize, pflag /*, palign */;
    poff = ph[1];
    paddr = ph[2];
    pfsize = ph[4];
    psize = ph[5];
    pflag = ph[6];
    /*palign = ph[7];*/
    switch (ph[0]) {
    case 1: {
      int prot = 0;
      if (pflag & 1)
        prot |= PROT_EXEC;
      if (pflag & 2)
        prot |= PROT_WRITE;
      if (pflag & 4)
        prot |= PROT_READ;
      if (prot & PROT_EXEC) {
        prot |= PROT_WRITE;
      }

      psize += paddr & 0xfff;
      pfsize += paddr & 0xfff;
      poff -= paddr & 0xfff;
      paddr &= ~0xfff;
      pafsize = (pfsize + 0xfff) & ~0xfff;
      psize = (psize + 0xfff) & ~0xfff;
      LOG("PT_LOAD size=%d fsize=%d flag=%d addr=%x prot=%d poff=%d\n",
             psize, pafsize, pflag, paddr, prot, poff);
      if (mmap((void*)paddr, pafsize, prot, MAP_FILE|MAP_PRIVATE|MAP_FIXED,
               fd, poff) == MAP_FAILED) {
        error("mmap(file)");
      }
      if ((prot & PROT_WRITE)) {
        LOG("%p\n", (char*)paddr);
        for (; pfsize < pafsize; pfsize++) {
          char* p = (char*)paddr;
          p[pfsize] = 0;
        }
        if (pfsize != psize) {
          if (mmap((void*)(paddr + pfsize),
                   psize - pfsize, prot, MAP_ANON|MAP_PRIVATE,
                   -1, 0) == MAP_FAILED) {
            error("mmap(anon)");
          }
        }
      }

      break;
    }
    case 2: {
      char* dyn;
      char* dstr = NULL;
      char* dsym = NULL;
      char* rel = NULL;
      char* pltrel = NULL;
      int relsz, relent, pltrelsz = 0;
      int needed[999] = {}, *neededp = needed;
      puts("PT_DYNAMIC");
      dyn = elf + poff;
      for (;;) {
        short dtag = *(short*)dyn;
        int dval = *(int*)(dyn + 4);
        dyn += 8;
        if (dtag == 0)
          break;
        switch (dtag) {
        case 1: {  /* DT_NEEDED */
          *neededp++ = dval;
        }
        case 2: {
          pltrelsz = dval;
          LOG("pltrelsz: %d\n", pltrelsz);
          break;
        }
        case 5: {
          dstr = (char*)dval;
          LOG("dstr: %p %s\n", dstr, dstr+1);
          break;
        }
        case 6: {
          dsym = (char*)dval;
          LOG("dsym: %p\n", dsym);
          break;
        }
        case 17: {
          rel = (char*)dval;
          LOG("rel: %p\n", rel);
          break;
        }
        case 18: {
          relsz = dval;
          LOG("relsz: %d\n", relsz);
          break;
        }
        case 19: {
          relent = dval;
          LOG("relent: %d\n", relent);
          break;
        }
        case 20: {
          pltrel = (char*)dval;
          LOG("pltrel: %p\n", pltrel);
          break;
        }
        default:
          LOG("unknown DYN %d %d\n", dtag, dval);
        }
      }
      if (!dsym || !dstr) {
        error("no dsym or dstr");
      }

      for (neededp = needed; *neededp; neededp++) {
        LOG("needed: %s\n", dstr + *neededp);
        dlopen(dstr + *neededp, RTLD_NOW | RTLD_GLOBAL);
      }

      {
        int i, j;
        for (j = 0; j < 2; j++) {
          for (i = 0; i < relsz; rel += relent, i += relent) {
            int* addr = *(int**)rel;
            int info = *(int*)(rel + 4);
            int sym = info >> 8;
            int type = info & 0xff;

            int* ds = (int*)(dsym + 16 * sym);
            char* sname = dstr + *ds;
            void* val=0;
            int k;
#if 0
            for(k=0;T[k].n;k++){
              if(!strcmp(sname,T[k].n)){
                 val = T[k].f;
                 break;
              }
            }
#endif
            if(!val){
              if (!strcmp(sname,"stdout"))
                val = &stdout;
              else if (!strcmp(sname,"_Stdout"))
                val = stdout;
              else if (!strcmp(sname,"stderr"))
                val = &stderr;
              else if (!strcmp(sname,"_Stderr"))
                val = stderr;
              /*
              else if (!strcmp(sname, "__environ"))
                val = &environ;
              */
              else
                val = dlsym(RTLD_DEFAULT, sname);
            }

            LOG("%srel: %p %s(%d) %d => %p\n",
                   j ? "plt" : "", (void*)addr, sname, sym, type, val);

            if (!val) {
              val = (void*)&undefined;
            }

            switch (type) {
            case 1: {
              *addr += (int)val;
            }
            case 5: {
              if (val) {
                *addr = *(int*)val;
              } else {
                fprintf(stderr, "undefined: %s\n", sname);
                //abort();
              }
            }
            case 6: {
              if (val) {
                *addr = (int)val;
              } else {
                fprintf(stderr, "undefined data %s\n", sname);
              }
              break;
            }
            case 7: {
              if (val) {
                *addr = (int)val;
              } else {
                *addr = (int)&undefined;
              }
              break;
            }
            }
          }

          if ((int)pltrel != 17) {
            rel = pltrel;
          }
          relsz = pltrelsz;
        }
      }

      break;
    }
    default:
      fprintf(stderr, "unknown PT %d\n", ph[0]);
    }
    ph += 8;
  }

  //g_argc = argc-1;
  //g_argv = argv+1;

  fprintf(stderr, "start!: %s %x\n", argv[1], entry);

#define TEST(a, b) printf("%lld*%lld=%lld (%lld)\n", a, b, mm(a, b), a * b % 0x38d7ea4c68025LL)
  TEST(1LL, 2LL);
  TEST(0xdeaddeadULL, 0xdeaddeadULL);

  *(char**)(0x8048963+1) = (char*)mm_wrap - (0x8048963 + 5);

  char* str = (char*)0x80491a0;
  str[0] = 'X';
  str[1] = 'X';
  str[2] = 0;
  long long (*calc_hash)() = (long long (*)())0x08048927;
  printf("%lld\n", calc_hash());

  //run((void*)entry);
  return 0;
}
Exemple #8
0
#endif
  return sym_id;
}


//================================================================
/*! constructor

  @param  vm	pointer to VM.
  @param  str	String
  @return 	symbol object
*/
mrbc_value mrbc_symbol_new(struct VM *vm, const char *str)
{
  mrbc_value ret = {.tt = MRBC_TT_SYMBOL};
  uint16_t h = calc_hash(str);
  mrbc_sym sym_id = search_index(h, str);

  if( sym_id >= 0 ) {
    ret.i = sym_id;
    return ret;		// already exist.
  }

  // create symbol object dynamically.
  int size = strlen(str) + 1;
  char *buf = mrbc_raw_alloc(size);
  if( buf == NULL ) return ret;		// ENOMEM raise?

  memcpy(buf, str, size);
  ret.i = add_index( h, buf );
Exemple #9
0
adlb_code xlb_xpt_index_lookup(const void *key, size_t key_len,
                               xpt_index_entry *res)
{
  assert(xpt_index_init);
  assert(key != NULL);
  adlb_datum_id id = id_for_hash(calc_hash(key, key_len));
  adlb_subscript subscript = { .key = key, .length = key_len };

  adlb_retrieve_refc refcounts = ADLB_RETRIEVE_NO_REFC;

  void *buffer = xlb_xfer; 
  adlb_data_type type;
  size_t length;
  adlb_code rc = ADLB_Retrieve(id, subscript, refcounts, &type,
                               buffer, &length);
  ADLB_CHECK_MSG(rc == ADLB_SUCCESS, "Error looking up checkpoint in "
            "container %"PRId64, id);
  if (rc == ADLB_NOTHING)
  {
    // Not present
    return ADLB_NOTHING;
  }
  ADLB_CHECK_MSG(length >= 1, "Checkpoint index val too small: %zu", length);

  // Type flag goes at end of buffer
  char in_file_flag = ((char*)buffer)[length - 1];
  if (in_file_flag != 0)
  {
    res->in_file = true;
    xpt_file_loc *res_file = &res->FILE_LOC;
    
    // Write info to binary buffer
    char *pos = (char*)buffer;
    size_t filename_len;
    ADLB_CHECK_MSG(length >= sizeof(filename_len), "Buffer not large enough "
            "for filename len: %zu v %zu", length, sizeof(filename_len));
    MSG_UNPACK_BIN(pos, &filename_len);

    // Check buffer was expected size (members plus in_file byte)
    size_t exp_length = sizeof(filename_len) + filename_len +
        sizeof(res_file->val_offset) + sizeof(res_file->val_len) + 1;
    ADLB_CHECK_MSG(length == exp_length, "Buffer not expected size: %zu vs %zu",
              length, exp_length);

    // Extract filename if needed
    if (filename_len == 0)
    {
      res_file->file = NULL;
    }
    else
    {
      res_file->file = malloc(filename_len + 1);
      ADLB_CHECK_MSG(res_file->file != NULL, "Error allocating filename");
      memcpy(res_file->file, pos, filename_len);
      res_file->file[filename_len] = '\0';
      pos += filename_len;
    }

    MSG_UNPACK_BIN(pos, &res_file->val_offset);
    MSG_UNPACK_BIN(pos, &res_file->val_len);
    pos++; // in_file byte
    assert(pos - (char*)buffer == exp_length);
  }
  else
  {
    res->in_file = false;
    adlb_binary_data *d = &res->DATA;
    d->length = length - 1; // Account for flag
    d->data = buffer;
    // Determine whether caller owns buffer
    d->caller_data = NULL;
  }
  return ADLB_SUCCESS;
}
Exemple #10
0
	hash_string::hash_string(const std::string& _s) : m_string(_s) 
	{
		calc_hash();
	}
Exemple #11
0
Song::Song(mpd_song *s)
{
	assert(s);
	m_song = std::shared_ptr<mpd_song>(s, mpd_song_free);
	m_hash = calc_hash(mpd_song_get_uri(s));
}
Exemple #12
0
	hash_string::hash_string(const char* _c, size_t _n) : m_string(_c, _n)
	{
		calc_hash();
	}
Exemple #13
0
	hash_string::hash_string(const char* _c): m_string(_c)
	{
		calc_hash();
	}
Exemple #14
0
int main(int argc, char *argv[])
{
	pev_config_t config;
	PEV_INITIALIZE(&config);

	if (argc < 2) {
		usage();
		return EXIT_FAILURE;
	}

	output_set_cmdline(argc, argv);

	OpenSSL_add_all_digests();

	options_t *options = parse_options(argc, argv);

	pe_ctx_t ctx;

	pe_err_e err = pe_load_file(&ctx, argv[argc-1]);
	if (err != LIBPE_E_OK) {
		pe_error_print(stderr, err);
		return EXIT_FAILURE;
	}

	err = pe_parse(&ctx);
	if (err != LIBPE_E_OK) {
		pe_error_print(stderr, err);
		return EXIT_FAILURE;
	}

	if (!pe_is_pe(&ctx))
		EXIT_ERROR("not a valid PE file");

	const IMAGE_SECTION_HEADER *section_ptr = NULL;
	const unsigned char *data = NULL;
	uint64_t data_size = 0;

	unsigned c = pe_sections_count(&ctx);
	IMAGE_SECTION_HEADER ** const sections = pe_sections(&ctx);
	char hash_value[EVP_MAX_MD_SIZE * 2 + 1];

	data = ctx.map_addr;
	data_size = pe_filesize(&ctx);

	output_open_document();

	if (options->all) {
		output_open_scope("file", OUTPUT_SCOPE_TYPE_OBJECT);
		output("filepath", ctx.path);
		print_basic_hash(data, data_size);
		output_close_scope(); // file
	}

	output_open_scope("headers", OUTPUT_SCOPE_TYPE_ARRAY);

	if (options->all || options->headers.all || options->headers.dos) {
		const IMAGE_DOS_HEADER *dos_hdr = pe_dos(&ctx);
		data = (const unsigned char *)dos_hdr;
		data_size = sizeof(IMAGE_DOS_HEADER);

		output_open_scope("header", OUTPUT_SCOPE_TYPE_OBJECT);
		output("header_name", "IMAGE_DOS_HEADER");
		PRINT_HASH_OR_HASHES;
		output_close_scope(); // header
	}

	if (options->all || options->headers.all || options->headers.coff) {
		const IMAGE_COFF_HEADER *coff_hdr = pe_coff(&ctx);
		data = (const unsigned char *)coff_hdr;
		data_size = sizeof(IMAGE_COFF_HEADER);

		output_open_scope("header", OUTPUT_SCOPE_TYPE_OBJECT);
		output("header_name", "IMAGE_COFF_HEADER");
		PRINT_HASH_OR_HASHES;
		output_close_scope(); // header
	}

	if (options->all || options->headers.all || options->headers.optional) {
      const IMAGE_OPTIONAL_HEADER *opt_hdr = pe_optional(&ctx);
      switch (opt_hdr->type) {
         case MAGIC_ROM:
            // Oh boy! We do not support ROM. Abort!
            fprintf(stderr, "ROM image is not supported\n");
            break;
         case MAGIC_PE32:
            if (!pe_can_read(&ctx, opt_hdr->_32, sizeof(IMAGE_OPTIONAL_HEADER_32))) {
               // TODO: Should we report something?
               break;
            }
            data = (const unsigned char *)opt_hdr->_32;
            data_size = sizeof(IMAGE_OPTIONAL_HEADER_32);
            break;
         case MAGIC_PE64:
            if (!pe_can_read(&ctx, opt_hdr->_64, sizeof(IMAGE_OPTIONAL_HEADER_64))) {
               // TODO: Should we report something?
               break;
            }
            data = (const unsigned char *)opt_hdr->_64;
            data_size = sizeof(IMAGE_OPTIONAL_HEADER_64);
            break;
		}

		output_open_scope("header", OUTPUT_SCOPE_TYPE_OBJECT);
		output("header_name", "IMAGE_OPTIONAL_HEADER");
		PRINT_HASH_OR_HASHES;
		output_close_scope(); // header
	}

	output_close_scope(); // headers

	if (options->all) {
		output_open_scope("sections", OUTPUT_SCOPE_TYPE_ARRAY);
		for (unsigned int i=0; i<c; i++) {
			data_size = sections[i]->SizeOfRawData;
			data = LIBPE_PTR_ADD(ctx.map_addr, sections[i]->PointerToRawData);

			output_open_scope("section", OUTPUT_SCOPE_TYPE_OBJECT);
			output("section_name", (char *)sections[i]->Name);
			if (data_size) {
				PRINT_HASH_OR_HASHES;
			}
			output_close_scope(); // section
		}
		output_close_scope(); // sections
	} else if (options->sections.name != NULL) {
		const IMAGE_SECTION_HEADER *section = pe_section_by_name(&ctx, options->sections.name);
		if (section == NULL) {
			EXIT_ERROR("The requested section could not be found on this binary");
		}
		section_ptr = section;
	} else if (options->sections.index > 0) {
		const uint16_t num_sections = pe_sections_count(&ctx);
		if (num_sections == 0 || options->sections.index > num_sections) {
			EXIT_ERROR("The requested section could not be found on this binary");
		}
		IMAGE_SECTION_HEADER ** const sections = pe_sections(&ctx);
		const IMAGE_SECTION_HEADER *section = sections[options->sections.index - 1];
		section_ptr = section;
	}

	if (section_ptr != NULL) {
		if (section_ptr->SizeOfRawData > 0) {
			const uint8_t *section_data_ptr = LIBPE_PTR_ADD(ctx.map_addr, section_ptr->PointerToRawData);
			// printf("map_addr = %p\n", ctx.map_addr);
			// printf("section_data_ptr = %p\n", section_data_ptr);
			// printf("SizeOfRawData = %u\n", section_ptr->SizeOfRawData);
			if (!pe_can_read(&ctx, section_data_ptr, section_ptr->SizeOfRawData)) {
				EXIT_ERROR("The requested section has an invalid size");
			}
			data = (const unsigned char *)section_data_ptr;
			data_size = section_ptr->SizeOfRawData;
		} else {
			data = (const unsigned char *)"";
			data_size = 0;
		}
	}

	if (!options->all && data != NULL) {
		char hash_value[EVP_MAX_MD_SIZE * 2 + 1];

		if (options->algorithms.all && options->all) {
			print_basic_hash(data, data_size);
		} else if (options->algorithms.alg_name != NULL) {
			calc_hash(options->algorithms.alg_name, data, data_size, hash_value);
			output(options->algorithms.alg_name, hash_value);
		} else {
			print_basic_hash(data, data_size);
		}
	}

	output_close_document();

	// free
	free_options(options);

	err = pe_unload(&ctx);
	if (err != LIBPE_E_OK) {
		pe_error_print(stderr, err);
		return EXIT_FAILURE;
	}

	EVP_cleanup(); // Clean OpenSSL_add_all_digests.

	PEV_FINALIZE(&config);

	return EXIT_SUCCESS;
}
Exemple #15
0
DescInfo *
desc_info_load (const char *filename)
{
	FILE *f;
	DescInfo *info = NULL;
	DescInfo *first = NULL;
	char line[512];

	char *ID = NULL;
	unsigned int hash = 0;
	unsigned int description_len = 0;
	char description[1024 * 2];

	/* Open file. */
	f = fopen (filename, "r");
	if (f == NULL)
		return NULL;

	/* Read file and process each desription entry. */
	while (!feof (f)) {
		fgets (line, sizeof (line), f);

		if (ID == NULL) {
			/* This should be the start of a new entry. */
			char *end;

			if (line[0] == '#' || (end = strchr (line, '#')) == NULL)
				/* Hm... doesn't look like one after all. */
				continue;

			/* Get the entry's ID. */
			end[0] = 0;
			ID = strdup (line);
			hash = calc_hash (ID);
			description_len = 0;

		} else if (line[0] == '#') {
			/* This should be the end of an entry. */
			if (ID == NULL)
				/* Or maybe not. */
				continue;

			/*
			 * Add entry to list.
			 */

			if (info == NULL) {
				/* This is the first entry. Allocate the first node. */
				info = malloc (sizeof (DescInfo));
				info->next = NULL;
				first = info;

			} else {
				/* Allocate new node and append it to linked list. */
				DescInfo *old;

				old = info;
				info = malloc (sizeof (DescInfo));
				info->next = NULL;
				old->next = info;
			}

			info->ID = ID;
			info->hash = hash;
			ID = NULL;

			postprocess (description, &description_len);
			info->description = malloc (description_len + 1);
			memcpy (info->description, description, description_len);
			info->description[description_len] = '\0';

		} else {
			/* This should be a line containing the description.
			 * Append line to description. */
			size_t len;

			len = strlen (line);
			if (description_len + len > sizeof (description))
				/* What? The total description is bigger than 2K? Ignore it. */
				continue;

			memcpy (description + description_len, line, len);
			description_len += len;
		}
	}
	fclose (f);

	return first;
}
Exemple #16
0
void * thread_fun(void * param)
{
    ShareData * p = (ShareData *)param;

    CURL *curl = curl_easy_init();
    if (curl == NULL) { return NULL; }
    CURLcode res, res_get_code= 0;

    char *buf_ptr = NULL;
    long buf_len = p->data_len_max;
    buf_ptr = malloc(buf_len);
    if (buf_ptr == NULL) { return NULL; }
    if (p->fill_char) { memset(buf_ptr, p->fill_char, buf_len); }

    for (long i=p->data_begin; i<= p->data_end; ++i) { 
	long real_len = buf_len;
	if (p->data_len_random) {
	    long diff = p->data_len_max - p->data_len_min;
	    real_len = p->data_len_min + rand()%diff;
	}

	char fname[64] = {0};
	sprintf(fname, "%ld", i);
	if (p->md5_crc32) { 
	    size_t name_len = sizeof(fname);
	    if (calc_hash(fname, &name_len, fname, strlen(fname)) < 0) {
		fprintf(stderr, "calc_hash error- %ld\n", i);
		goto err;
	    }
	}

	struct curl_httppost *formpost = NULL;
	struct curl_httppost *lastptr = NULL;
	int upload_res = 0;
	long http_code;
	if (curl) {
	    curl_formadd(&formpost, &lastptr,
		    CURLFORM_COPYNAME, "file",
		    CURLFORM_BUFFER, fname,
		    CURLFORM_BUFFERPTR, buf_ptr,
		    CURLFORM_BUFFERLENGTH, real_len,
		    CURLFORM_END);

	    curl_easy_setopt(curl, CURLOPT_URL, p->url);
	    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fun_write);
	    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
	    curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
	    res = curl_easy_perform(curl);
	    res_get_code = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
	    if ((res == CURLE_OK) && (res_get_code == CURLE_OK) && (http_code == 200)) {upload_res = 1;}
	    curl_formfree(formpost);
	}
	if (upload_res) { fprintf(stderr, "%s: ok\n", fname); }
	else { fprintf(stderr, "%s: error\n", fname); }
	//if (!upload_res) { fprintf(stderr, "%s: error\n", fname); }
    }
    curl_easy_cleanup(curl);
err:
    if (buf_ptr) { free(buf_ptr); buf_ptr = NULL;}
    return NULL;
}