Ejemplo n.º 1
0
Archivo: geoip.c Proyecto: majek/tor
/** Return the hex-encoded SHA1 digest of the loaded GeoIP file. The
 * result does not need to be deallocated, but will be overwritten by the
 * next call of hex_str(). */
const char *
geoip_db_digest(sa_family_t family)
{
  tor_assert(family == AF_INET || family == AF_INET6);
  if (family == AF_INET)
    return hex_str(geoip_digest, DIGEST_LEN);
  else                          /* AF_INET6 */
    return hex_str(geoip6_digest, DIGEST_LEN);
}
Ejemplo n.º 2
0
void hex_dump( unsigned char * buf, int len )
{
	char str[KB(4)];
	if( dbg_term )
		puts( hex_str( buf, len, str ) );
	if( dbg_file ){
		fputs( hex_str( buf, len, str ), fp_log );
		fprintf( fp_log, "\n" );
		fflush( fp_log );
	}
	//fprintf( stderr, hex_str( buf, len ) );
}
Ejemplo n.º 3
0
/* Test helper function: Make sure that a bridge line gets parsed
 * properly. Also make sure that the resulting bridge_line_t structure
 * has its fields set correctly. */
static void
good_bridge_line_test(const char *string, const char *test_addrport,
                      const char *test_digest, const char *test_transport,
                      const smartlist_t *test_socks_args)
{
  char *tmp = NULL;
  bridge_line_t *bridge_line = parse_bridge_line(string);
  test_assert(bridge_line);

  /* test addrport */
  tmp = tor_strdup(fmt_addrport(&bridge_line->addr, bridge_line->port));
  test_streq(test_addrport, tmp);
  tor_free(tmp);

  /* If we were asked to validate a digest, but we did not get a
     digest after parsing, we failed. */
  if (test_digest && tor_digest_is_zero(bridge_line->digest))
    test_assert(0);

  /* If we were not asked to validate a digest, and we got a digest
     after parsing, we failed again. */
  if (!test_digest && !tor_digest_is_zero(bridge_line->digest))
    test_assert(0);

  /* If we were asked to validate a digest, and we got a digest after
     parsing, make sure it's correct. */
  if (test_digest) {
    tmp = tor_strdup(hex_str(bridge_line->digest, DIGEST_LEN));
    tor_strlower(tmp);
    test_streq(test_digest, tmp);
    tor_free(tmp);
  }

  /* If we were asked to validate a transport name, make sure tha it
     matches with the transport name that was parsed. */
  if (test_transport && !bridge_line->transport_name)
    test_assert(0);
  if (!test_transport && bridge_line->transport_name)
    test_assert(0);
  if (test_transport)
    test_streq(test_transport, bridge_line->transport_name);

  /* Validate the SOCKS argument smartlist. */
  if (test_socks_args && !bridge_line->socks_args)
    test_assert(0);
  if (!test_socks_args && bridge_line->socks_args)
    test_assert(0);
  if (test_socks_args)
    test_assert(smartlist_strings_eq(test_socks_args,
                                     bridge_line->socks_args));

 done:
  tor_free(tmp);
  bridge_line_free(bridge_line);
}
Ejemplo n.º 4
0
void encode_init(void)
{
    uint8_t tmp[5];

    luid_get(tmp, 5);

    /* extract device ID */
    hex_str(tmp, 5, did);
    // /* and 'pseudo-randomize' the device ID to get sensor IDs */
    // for (int i = 0; i < 3; i++) {
    //     for (int p = 0; p < 5; p++) {
    //         tmp[p] ^= rand[i];
    //     }
    //     hex_str(tmp, 5, sid[i]);
    // }
}
Ejemplo n.º 5
0
// Elliptic Curve Digital Signature Algorithm Example
void ecdsa_ex () {
	// Degree 163 Binary Field from fips186-2
	use_NIST_B_163 ();
	EC_Domain_Parameters dp = NIST_B_163;
	ECPrivKey sk (dp);// generate a key pair from the EC domain parameters

	std::string M ("correct message");

	ECDSA sig1 (sk, OS2IP(SHA1(M))); // generate the signature

	// DER encoding, is a common standard method of representing digital 
	// signatures
	DER der_str (sig1);
	HexEncoder hex_str (der_str);

	// You might save the DER ecoded signature to a file or send it over 
	// the network here.
	std::cout << "DER Encoding: " << hex_str << std::endl;
	
	ECDSA sig2;
	try { // try to catch any DER parsing errors
		sig2 = der_str.toECDSA (); // decode the DER string
	} catch (borzoiException e) { // print the error message and exit
		e.debug_print ();
		return;
	}

	ECPubKey pk (sk);
	std::cout << "Checking signature against M: " << M.c_str () << "\n->";

	std::cout << "SHA1(M): " << OS2IP(SHA1(M)) << std::endl;
	if (sig2.verify(pk, OS2IP(SHA1(M)))) // try to verify the signature
		std::cout << "valid signature\n";
	else std::cout << "invalid signature\n";

	M = "in" + M; // tamper with the message
	std::cout << "Checking signature against M: " << M.c_str () << "\n->";

	if (sig2.verify(pk, OS2IP(SHA1(M)))) // try to verify the signature
		std::cout << "valid signature\n";
	else std::cout << "invalid signature\n";
}
std::string rgb2hex(char* str) {
	std::string hex_str("#");
	std::string numb_str;
	while (*str != '\0') {
		if ('0' <= *str && *str <= '9') {
			char c[2];
			c[0] = *str;
			c[1] = '\0';
			numb_str += std::string(c);
		} else {
			if (!numb_str.empty()) {
				int n = std::stoi(numb_str);
				hex_str += int2hex_str256(n);
			}
			numb_str.clear();
		}
		str++;
	}
	return hex_str;
}
Ejemplo n.º 7
0
UIMsg::UIMsg(ErrorType errortype, unsigned char ucErrorCode, QDialog *parent, Qt::WindowFlags f) :
    QDialog(parent,f)
{
    // 初始化错误代码
    this->initalErrorMsg();
    this->initalNoticeMsg();
    this->initalFileErrorMsg();
    this->initalCommErrorMsg();
    this->initalHostErrorMsg();

    QPixmap bg;
    bg.load(":/images/commonbg.png");
    QPalette palette;
    palette.setBrush(backgroundRole(),QBrush(bg));
    this->setPalette(palette);
    this->setAutoFillBackground(true);
    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setGeometry(20,FRAME420_THVALUE+50,FRAME420_WIDTH,FRAME420_HEIGHT-50);
    this->setFixedSize(FRAME420_WIDTH-40,FRAME420_HEIGHT-80);
    this->setStyleSheet("QDialog{border: 6px solid silver;}");

    QFont font("Helvetica",12,QFont::Bold);
    QFont font2("Helvetica",14,QFont::Bold);
    QFont font3("Helvetica",8,QFont::Bold);

    //--------------define--------------------//
    lbHead=new QLabel();
    QFont fontH("Helvetica",18,QFont::Bold);
    lbHead->setFont(fontH);
    lbHead->setAlignment(Qt::AlignCenter);
    lbHead->setMinimumHeight(40);
    lbHead->setMaximumHeight(40);
    lbHead->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

    lbMsg=new QLabel();
    lbReturnCode=new QLabel();
    lbMsg->setFont(font2);
    lbReturnCode->setFont(font2);
    lbMsg->setAlignment(Qt::AlignCenter);
    lbReturnCode->setAlignment(Qt::AlignCenter);
    lbMsg->setMinimumHeight(40);
    lbReturnCode->setMinimumHeight(40);

    btnSubmit=new QPushButton;
    btnSubmit->setText(tr("OK"));
    btnSubmit->setFont(font2);
    btnSubmit->setMinimumHeight(30);
    btnSubmit->setStyleSheet(BTN_GREY_STYLE);


    this->beepTwice();   //beep

    switch(errortype)
    {
    case NORMAL_ERROR:
    {
        lbHead->setText("ERROR");
        lbHead->setStyleSheet("background-color: rgb(255,0,0);");

        lbMsg->setText(hashError.value(ErrIndex(ucErrorCode)));

        break;
    }
    case NOTICE_ERROR:
    {
        lbHead->setText("NOTICE");
        lbHead->setStyleSheet("background-color: rgb(0, 153, 255);");

        lbMsg->setText(hashNotice.value(MsgTabIndex(ucErrorCode)));

        break;
    }
    case FILE_ERROR:
    {
        lbHead->setText("FILE ERROR");
        lbHead->setStyleSheet("background-color: rgb(255,0,0);");
        lbMsg->setText(hashFileError.value(FileErrIndex(ucErrorCode)));


        break;
    }
    case COMM_ERROR:
    {
        lbHead->setText("COMM ERROR");
        lbHead->setStyleSheet("background-color: rgb(255,0,0);");
        lbMsg->setText(hashCommError.value(CommsErrIndex(ucErrorCode)));

        break;
    }
    case HOST_ERROR:
    {
        qDebug()<<"不应该在这里处理";
        break;
    }
    }

    unsigned char  ucCode;
    ucCode = ucErrorCode;

    unsigned char  aucErrorCode[PARAM_ANSWER_LEN + 1] = {0};
    hex_str(aucErrorCode, &ucCode, PARAM_ANSWER_LEN);
    lbReturnCode->setText("Return Code : "+QString::fromAscii((const char*)aucErrorCode));

    // -----------layout------------//
    QSpacerItem *sp1=new QSpacerItem(1,1,QSizePolicy::Expanding,QSizePolicy::Expanding);
    QSpacerItem *sp2=new QSpacerItem(1,1,QSizePolicy::Expanding,QSizePolicy::Expanding);
    QSpacerItem *sp3=new QSpacerItem(1,1,QSizePolicy::Expanding,QSizePolicy::Expanding);
    QHBoxLayout *h1Lay=new QHBoxLayout();
    h1Lay->addSpacing(6);
    h1Lay->addWidget(lbHead);
    h1Lay->addSpacing(6);

    QVBoxLayout *v1Lay=new QVBoxLayout();
    v1Lay->addSpacing(6);
    v1Lay->addLayout(h1Lay);
    v1Lay->addItem(sp1);
    v1Lay->addWidget(lbMsg);
    v1Lay->addItem(sp2);
    if(errortype!=NOTICE_ERROR)
    {
        v1Lay->addWidget(lbReturnCode);
    }
    v1Lay->addItem(sp3);

    QHBoxLayout *h2Lay=new QHBoxLayout();
    h2Lay->addSpacing(10);
    h2Lay->addWidget(btnSubmit);
    h2Lay->addSpacing(10);

    QVBoxLayout *layout=new QVBoxLayout(this);
    layout->addLayout(v1Lay);
    layout->addLayout(h2Lay);

    layout->setContentsMargins(0,0,0,10);

    connect(btnSubmit,SIGNAL(clicked()),this,SLOT(close()));

}
Ejemplo n.º 8
0
str
obj_str(void* p)
{
	return hex_str((reg)p);
}
Ejemplo n.º 9
0
/** Return the hex-encoded SHA1 digest of the loaded GeoIP file. The
 * result does not need to be deallocated, but will be overwritten by the
 * next call of hex_str(). */
const char *
geoip_db_digest(void)
{
  return hex_str(geoip_digest, DIGEST_LEN);
}
Ejemplo n.º 10
0
/* Called when a service rendezvous point circuit is done building. Given the
 * service and the circuit, this function will send a RENDEZVOUS1 cell on the
 * circuit using the information in the circuit identifier. If the cell can't
 * be sent, the circuit is closed. */
void
hs_circ_service_rp_has_opened(const hs_service_t *service,
                              origin_circuit_t *circ)
{
  size_t payload_len;
  uint8_t payload[RELAY_PAYLOAD_SIZE] = {0};

  tor_assert(service);
  tor_assert(circ);
  tor_assert(circ->hs_ident);

  /* Some useful logging. */
  log_info(LD_REND, "Rendezvous circuit %u has opened with cookie %s "
                    "for service %s",
           TO_CIRCUIT(circ)->n_circ_id,
           hex_str((const char *) circ->hs_ident->rendezvous_cookie,
                   REND_COOKIE_LEN),
           safe_str_client(service->onion_address));
  circuit_log_path(LOG_INFO, LD_REND, circ);

  /* This can't fail. */
  payload_len = hs_cell_build_rendezvous1(
                        circ->hs_ident->rendezvous_cookie,
                        sizeof(circ->hs_ident->rendezvous_cookie),
                        circ->hs_ident->rendezvous_handshake_info,
                        sizeof(circ->hs_ident->rendezvous_handshake_info),
                        payload);

  /* Pad the payload with random bytes so it matches the size of a legacy cell
   * which is normally always bigger. Also, the size of a legacy cell is
   * always smaller than the RELAY_PAYLOAD_SIZE so this is safe. */
  if (payload_len < HS_LEGACY_RENDEZVOUS_CELL_SIZE) {
    crypto_rand((char *) payload + payload_len,
                HS_LEGACY_RENDEZVOUS_CELL_SIZE - payload_len);
    payload_len = HS_LEGACY_RENDEZVOUS_CELL_SIZE;
  }

  if (relay_send_command_from_edge(CONTROL_CELL_ID, TO_CIRCUIT(circ),
                                   RELAY_COMMAND_RENDEZVOUS1,
                                   (const char *) payload, payload_len,
                                   circ->cpath->prev) < 0) {
    /* On error, circuit is closed. */
    log_warn(LD_REND, "Unable to send RENDEZVOUS1 cell on circuit %u "
                      "for service %s",
             TO_CIRCUIT(circ)->n_circ_id,
             safe_str_client(service->onion_address));
    goto done;
  }

  /* Setup end-to-end rendezvous circuit between the client and us. */
  if (hs_circuit_setup_e2e_rend_circ(circ,
                       circ->hs_ident->rendezvous_ntor_key_seed,
                       sizeof(circ->hs_ident->rendezvous_ntor_key_seed),
                       1) < 0) {
    log_warn(LD_GENERAL, "Failed to setup circ");
    goto done;
  }

 done:
  memwipe(payload, 0, sizeof(payload));
}
Ejemplo n.º 11
0
/* For a given service, the ntor onion key and a rendezvous cookie, launch a
 * circuit to the rendezvous point specified by the link specifiers. On
 * success, a circuit identifier is attached to the circuit with the needed
 * data. This function will try to open a circuit for a maximum value of
 * MAX_REND_FAILURES then it will give up. */
static void
launch_rendezvous_point_circuit(const hs_service_t *service,
                                const hs_service_intro_point_t *ip,
                                const hs_cell_introduce2_data_t *data)
{
  int circ_needs_uptime;
  time_t now = time(NULL);
  extend_info_t *info = NULL;
  origin_circuit_t *circ;

  tor_assert(service);
  tor_assert(ip);
  tor_assert(data);

  circ_needs_uptime = hs_service_requires_uptime_circ(service->config.ports);

  /* Get the extend info data structure for the chosen rendezvous point
   * specified by the given link specifiers. */
  info = hs_get_extend_info_from_lspecs(data->link_specifiers,
                                        &data->onion_pk,
                                        service->config.is_single_onion);
  if (info == NULL) {
    /* We are done here, we can't extend to the rendezvous point.
     * If you're running an IPv6-only v3 single onion service on 0.3.2 or with
     * 0.3.2 clients, and somehow disable the option check, it will fail here.
     */
    log_fn(LOG_PROTOCOL_WARN, LD_REND,
           "Not enough info to open a circuit to a rendezvous point for "
           "%s service %s.",
           get_service_anonymity_string(service),
           safe_str_client(service->onion_address));
    goto end;
  }

  for (int i = 0; i < MAX_REND_FAILURES; i++) {
    int circ_flags = CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_IS_INTERNAL;
    if (circ_needs_uptime) {
      circ_flags |= CIRCLAUNCH_NEED_UPTIME;
    }
    /* Firewall and policies are checked when getting the extend info. */
    if (service->config.is_single_onion) {
      circ_flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
    }

    circ = circuit_launch_by_extend_info(CIRCUIT_PURPOSE_S_CONNECT_REND, info,
                                         circ_flags);
    if (circ != NULL) {
      /* Stop retrying, we have a circuit! */
      break;
    }
  }
  if (circ == NULL) {
    log_warn(LD_REND, "Giving up on launching a rendezvous circuit to %s "
                      "for %s service %s",
             safe_str_client(extend_info_describe(info)),
             get_service_anonymity_string(service),
             safe_str_client(service->onion_address));
    goto end;
  }
  log_info(LD_REND, "Rendezvous circuit launched to %s with cookie %s "
                    "for %s service %s",
           safe_str_client(extend_info_describe(info)),
           safe_str_client(hex_str((const char *) data->rendezvous_cookie,
                                   REND_COOKIE_LEN)),
           get_service_anonymity_string(service),
           safe_str_client(service->onion_address));
  tor_assert(circ->build_state);
  /* Rendezvous circuit have a specific timeout for the time spent on trying
   * to connect to the rendezvous point. */
  circ->build_state->expiry_time = now + MAX_REND_TIMEOUT;

  /* Create circuit identifier and key material. */
  {
    hs_ntor_rend_cell_keys_t keys;
    curve25519_keypair_t ephemeral_kp;
    /* No need for extra strong, this is only for this circuit life time. This
     * key will be used for the RENDEZVOUS1 cell that will be sent on the
     * circuit once opened. */
    curve25519_keypair_generate(&ephemeral_kp, 0);
    if (hs_ntor_service_get_rendezvous1_keys(&ip->auth_key_kp.pubkey,
                                             &ip->enc_key_kp,
                                             &ephemeral_kp, &data->client_pk,
                                             &keys) < 0) {
      /* This should not really happened but just in case, don't make tor
       * freak out, close the circuit and move on. */
      log_info(LD_REND, "Unable to get RENDEZVOUS1 key material for "
                        "service %s",
               safe_str_client(service->onion_address));
      circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
      goto end;
    }
    circ->hs_ident = create_rp_circuit_identifier(service,
                                                  data->rendezvous_cookie,
                                                  &ephemeral_kp.pubkey, &keys);
    memwipe(&ephemeral_kp, 0, sizeof(ephemeral_kp));
    memwipe(&keys, 0, sizeof(keys));
    tor_assert(circ->hs_ident);
  }

 end:
  extend_info_free(info);
}
Ejemplo n.º 12
0
 /**
  * Operator to transform this type into string form
  *
  * @note String representation format is in hex
  */
 operator std::string () const
 { return hex_str(); }
Ejemplo n.º 13
0
 /**
  * Get a string representation of this type
  *
  * @return A string representation of this type
  *
  * @note String representation format is in hex
  */
 std::string to_string() const
 { return hex_str(); }
Ejemplo n.º 14
0
 /**
  * Get a string representation of this type
  *
  * @return A string representation of this type
  *
  * @note String representation format is in hex
  */
 std::string str() const
 { return hex_str(); }
Ejemplo n.º 15
0
/** internal functions implementation starts here **/
void os_sendpass(IRC_User *s, IRC_User *u)
{
  u_int32_t source_snid;
  u_int32_t snid;
  char *target;
  char *email;
  int lang;
  
  /* status validation */  
  CHECK_IF_IDENTIFIED_NICK
  /* syntax validation */
  target = strtok(NULL, " ");

  if (!is_soper(u->snid))
  {
    send_lang(u, s, PERMISSION_DENIED);
    return;
  }
  
  if(!irc_IsUMode(u, UMODE_OPER)) /* extra security */
    return;
  else if(IsNull(target))
    send_lang(u, s, SENDPASS_SYNTAX);
  else if( (snid = nick2snid(target)) == 0 )
    send_lang(u, s, NICK_X_NOT_REGISTERED, target);
  /* sub-command */
  else if(is_sadmin(snid) || is_sroot(snid))
  {
    log_log(os_log, mod_info.name, "Nick %s trying SENDPASS on sadmin/soper %s",
      s->nick, target);
    irc_SendSanotice(s, "Nick %s trying SENDPASS on sadmin/soper %s",
      s->nick, target);
  }
  else if((sql_singlequery("SELECT email, lang FROM nickserv WHERE snid=%d", 
    snid) < 1) || ((email = sql_field(0)) == NULL))
     send_lang(u, s, OS_SENDPASS_NO_EMAIL_X, target);
  else
  {
    char buf[512];
    char pbuf[PASSLEN+1];
    lang = sql_field_i(1);
    rand_string(pbuf, PASSLEN, PASSLEN);
    pbuf[2] = '0'+ (random() % 10);
    sql_execute("UPDATE nickserv_security SET pass=%s WHERE snid=%d",
      sql_str(hex_str(encrypted_password(pbuf), 16)), snid);
    snprintf(buf, sizeof(buf), 
    "From: \"%%from_name%%\" <%%from%%>\r\nTo:\"%s\" <%s>\r\nSubject:%s\r\n\r\n%s",
      target, email,
      "Nick Password", 
      lang_str_l(lang, SENDPASS_X_X, target, pbuf)
      );
    email_init_symbols();
    email_add_symbol("email", email);
    email_send(buf);
    memset(pbuf, 0, PASSLEN);
    send_lang(u, s, SENDPASS_X_SENT_X, target, email);
    log_log(os_log, mod_info.name, "SENDPASS for %s requested by %s", 
      target, u->nick);
    irc_SendSanotice(s, "SENDPASS for %s requested by %s",
      target, u->nick);
  }
}
Ejemplo n.º 16
0
/* Decide if the newly received <b>commit</b> should be kept depending on
 * the current phase and state of the protocol. The <b>voter_key</b> is the
 * RSA identity key fingerprint of the authority's vote from which the
 * commit comes from. The <b>phase</b> is the phase we should be validating
 * the commit for. Return 1 if the commit should be added to our state or 0
 * if not. */
STATIC int
should_keep_commit(const sr_commit_t *commit, const char *voter_key,
                   sr_phase_t phase)
{
  const sr_commit_t *saved_commit;

  tor_assert(commit);
  tor_assert(voter_key);

  log_debug(LD_DIR, "SR: Inspecting commit from %s (voter: %s)?",
            sr_commit_get_rsa_fpr(commit),
            hex_str(voter_key, DIGEST_LEN));

  /* For a commit to be considered, it needs to be authoritative (it should
   * be the voter's own commit). */
  if (!commit_is_authoritative(commit, voter_key)) {
    log_debug(LD_DIR, "SR: Ignoring non-authoritative commit.");
    goto ignore;
  }

  /* Let's make sure, for extra safety, that this fingerprint is known to
   * us. Even though this comes from a vote, doesn't hurt to be
   * extracareful. */
  if (trusteddirserver_get_by_v3_auth_digest(commit->rsa_identity) == NULL) {
    log_warn(LD_DIR, "SR: Fingerprint %s is not from a recognized "
                     "authority. Discarding commit.",
             escaped(commit->rsa_identity));
    goto ignore;
  }

  /* Check if the authority that voted for <b>commit</b> has already posted
   * a commit before. */
  saved_commit = sr_state_get_commit(commit->rsa_identity);

  switch (phase) {
  case SR_PHASE_COMMIT:
    /* Already having a commit for an authority so ignore this one. */
    if (saved_commit) {
      /*  Receiving known commits should happen naturally since commit phase
          lasts multiple rounds. However if the commitment value changes
          during commit phase, it might be a bug so log more loudly. */
      if (!commitments_are_the_same(commit, saved_commit)) {
        log_info(LD_DIR,
                 "SR: Received altered commit from %s in commit phase.",
                 sr_commit_get_rsa_fpr(commit));
      } else {
        log_debug(LD_DIR, "SR: Ignoring known commit during commit phase.");
      }
      goto ignore;
    }

    /* A commit with a reveal value during commitment phase is very wrong. */
    if (commit_has_reveal_value(commit)) {
      log_warn(LD_DIR, "SR: Commit from authority %s has a reveal value "
                       "during COMMIT phase. (voter: %s)",
               sr_commit_get_rsa_fpr(commit),
               hex_str(voter_key, DIGEST_LEN));
      goto ignore;
    }
    break;
  case SR_PHASE_REVEAL:
    /* We are now in reveal phase. We keep a commit if and only if:
     *
     * - We have already seen a commit by this auth, AND
     * - the saved commit has the same commitment value as this one, AND
     * - the saved commit has no reveal information, AND
     * - this commit does have reveal information, AND
     * - the reveal & commit information are matching.
     *
     * If all the above are true, then we are interested in this new commit
     * for its reveal information. */

    if (!saved_commit) {
      log_debug(LD_DIR, "SR: Ignoring commit first seen in reveal phase.");
      goto ignore;
    }

    if (!commitments_are_the_same(commit, saved_commit)) {
      log_warn(LD_DIR, "SR: Commit from authority %s is different from "
                       "previous commit in our state (voter: %s)",
               sr_commit_get_rsa_fpr(commit),
               hex_str(voter_key, DIGEST_LEN));
      goto ignore;
    }

    if (commit_has_reveal_value(saved_commit)) {
      log_debug(LD_DIR, "SR: Ignoring commit with known reveal info.");
      goto ignore;
    }

    if (!commit_has_reveal_value(commit)) {
      log_debug(LD_DIR, "SR: Ignoring commit without reveal value.");
      goto ignore;
    }

    if (verify_commit_and_reveal(commit) < 0) {
      log_warn(LD_BUG, "SR: Commit from authority %s has an invalid "
                       "reveal value. (voter: %s)",
               sr_commit_get_rsa_fpr(commit),
               hex_str(voter_key, DIGEST_LEN));
      goto ignore;
    }
    break;
  default:
    tor_assert(0);
  }

  return 1;

 ignore:
  return 0;
}
Ejemplo n.º 17
0
/** Run unit tests for our SHA-1 functionality */
static void
test_crypto_sha(void)
{
  crypto_digest_t *d1 = NULL, *d2 = NULL;
  int i;
  char key[160];
  char digest[32];
  char data[50];
  char d_out1[DIGEST_LEN], d_out2[DIGEST256_LEN];
  char *mem_op_hex_tmp=NULL;

  /* Test SHA-1 with a test vector from the specification. */
  i = crypto_digest(data, "abc", 3);
  test_memeq_hex(data, "A9993E364706816ABA3E25717850C26C9CD0D89D");
  tt_int_op(i, ==, 0);

  /* Test SHA-256 with a test vector from the specification. */
  i = crypto_digest256(data, "abc", 3, DIGEST_SHA256);
  test_memeq_hex(data, "BA7816BF8F01CFEA414140DE5DAE2223B00361A3"
                       "96177A9CB410FF61F20015AD");
  tt_int_op(i, ==, 0);

  /* Test HMAC-SHA-1 with test cases from RFC2202. */

  /* Case 1. */
  memset(key, 0x0b, 20);
  crypto_hmac_sha1(digest, key, 20, "Hi There", 8);
  test_streq(hex_str(digest, 20),
             "B617318655057264E28BC0B6FB378C8EF146BE00");
  /* Case 2. */
  crypto_hmac_sha1(digest, "Jefe", 4, "what do ya want for nothing?", 28);
  test_streq(hex_str(digest, 20),
             "EFFCDF6AE5EB2FA2D27416D5F184DF9C259A7C79");

  /* Case 4. */
  base16_decode(key, 25,
                "0102030405060708090a0b0c0d0e0f10111213141516171819", 50);
  memset(data, 0xcd, 50);
  crypto_hmac_sha1(digest, key, 25, data, 50);
  test_streq(hex_str(digest, 20),
             "4C9007F4026250C6BC8414F9BF50C86C2D7235DA");

  /* Case 5. */
  memset(key, 0xaa, 80);
  crypto_hmac_sha1(digest, key, 80,
                   "Test Using Larger Than Block-Size Key - Hash Key First",
                   54);
  test_streq(hex_str(digest, 20),
             "AA4AE5E15272D00E95705637CE8A3B55ED402112");

  /* Test HMAC-SHA256 with test cases from wikipedia and RFC 4231 */

  /* Case empty (wikipedia) */
  crypto_hmac_sha256(digest, "", 0, "", 0);
  test_streq(hex_str(digest, 32),
           "B613679A0814D9EC772F95D778C35FC5FF1697C493715653C6C712144292C5AD");

  /* Case quick-brown (wikipedia) */
  crypto_hmac_sha256(digest, "key", 3,
                     "The quick brown fox jumps over the lazy dog", 43);
  test_streq(hex_str(digest, 32),
           "F7BC83F430538424B13298E6AA6FB143EF4D59A14946175997479DBC2D1A3CD8");

  /* "Test Case 1" from RFC 4231 */
  memset(key, 0x0b, 20);
  crypto_hmac_sha256(digest, key, 20, "Hi There", 8);
  test_memeq_hex(digest,
                 "b0344c61d8db38535ca8afceaf0bf12b"
                 "881dc200c9833da726e9376c2e32cff7");

  /* "Test Case 2" from RFC 4231 */
  memset(key, 0x0b, 20);
  crypto_hmac_sha256(digest, "Jefe", 4, "what do ya want for nothing?", 28);
  test_memeq_hex(digest,
                 "5bdcc146bf60754e6a042426089575c7"
                 "5a003f089d2739839dec58b964ec3843");

  /* "Test case 3" from RFC 4231 */
  memset(key, 0xaa, 20);
  memset(data, 0xdd, 50);
  crypto_hmac_sha256(digest, key, 20, data, 50);
  test_memeq_hex(digest,
                 "773ea91e36800e46854db8ebd09181a7"
                 "2959098b3ef8c122d9635514ced565fe");

  /* "Test case 4" from RFC 4231 */
  base16_decode(key, 25,
                "0102030405060708090a0b0c0d0e0f10111213141516171819", 50);
  memset(data, 0xcd, 50);
  crypto_hmac_sha256(digest, key, 25, data, 50);
  test_memeq_hex(digest,
                 "82558a389a443c0ea4cc819899f2083a"
                 "85f0faa3e578f8077a2e3ff46729665b");

  /* "Test case 5" from RFC 4231 */
  memset(key, 0x0c, 20);
  crypto_hmac_sha256(digest, key, 20, "Test With Truncation", 20);
  test_memeq_hex(digest,
                 "a3b6167473100ee06e0c796c2955552b");

  /* "Test case 6" from RFC 4231 */
  memset(key, 0xaa, 131);
  crypto_hmac_sha256(digest, key, 131,
                     "Test Using Larger Than Block-Size Key - Hash Key First",
                     54);
  test_memeq_hex(digest,
                 "60e431591ee0b67f0d8a26aacbf5b77f"
                 "8e0bc6213728c5140546040f0ee37f54");

  /* "Test case 7" from RFC 4231 */
  memset(key, 0xaa, 131);
  crypto_hmac_sha256(digest, key, 131,
                     "This is a test using a larger than block-size key and a "
                     "larger than block-size data. The key needs to be hashed "
                     "before being used by the HMAC algorithm.", 152);
  test_memeq_hex(digest,
                 "9b09ffa71b942fcb27635fbcd5b0e944"
                 "bfdc63644f0713938a7f51535c3a35e2");

  /* Incremental digest code. */
  d1 = crypto_digest_new();
  test_assert(d1);
  crypto_digest_add_bytes(d1, "abcdef", 6);
  d2 = crypto_digest_dup(d1);
  test_assert(d2);
  crypto_digest_add_bytes(d2, "ghijkl", 6);
  crypto_digest_get_digest(d2, d_out1, sizeof(d_out1));
  crypto_digest(d_out2, "abcdefghijkl", 12);
  test_memeq(d_out1, d_out2, DIGEST_LEN);
  crypto_digest_assign(d2, d1);
  crypto_digest_add_bytes(d2, "mno", 3);
  crypto_digest_get_digest(d2, d_out1, sizeof(d_out1));
  crypto_digest(d_out2, "abcdefmno", 9);
  test_memeq(d_out1, d_out2, DIGEST_LEN);
  crypto_digest_get_digest(d1, d_out1, sizeof(d_out1));
  crypto_digest(d_out2, "abcdef", 6);
  test_memeq(d_out1, d_out2, DIGEST_LEN);
  crypto_digest_free(d1);
  crypto_digest_free(d2);

  /* Incremental digest code with sha256 */
  d1 = crypto_digest256_new(DIGEST_SHA256);
  test_assert(d1);
  crypto_digest_add_bytes(d1, "abcdef", 6);
  d2 = crypto_digest_dup(d1);
  test_assert(d2);
  crypto_digest_add_bytes(d2, "ghijkl", 6);
  crypto_digest_get_digest(d2, d_out1, sizeof(d_out1));
  crypto_digest256(d_out2, "abcdefghijkl", 12, DIGEST_SHA256);
  test_memeq(d_out1, d_out2, DIGEST_LEN);
  crypto_digest_assign(d2, d1);
  crypto_digest_add_bytes(d2, "mno", 3);
  crypto_digest_get_digest(d2, d_out1, sizeof(d_out1));
  crypto_digest256(d_out2, "abcdefmno", 9, DIGEST_SHA256);
  test_memeq(d_out1, d_out2, DIGEST_LEN);
  crypto_digest_get_digest(d1, d_out1, sizeof(d_out1));
  crypto_digest256(d_out2, "abcdef", 6, DIGEST_SHA256);
  test_memeq(d_out1, d_out2, DIGEST_LEN);

 done:
  if (d1)
    crypto_digest_free(d1);
  if (d2)
    crypto_digest_free(d2);
  tor_free(mem_op_hex_tmp);
}
Ejemplo n.º 18
0
// Elliptic Curve Integrated Encryption Scheme
void ecies_ex () {
	// Degree 163 Binary Field from fips186-2
	use_NIST_B_233 ();
	EC_Domain_Parameters dp = NIST_B_233;

	ECPrivKey sk (dp);// generate a private key from the domain parameters
	ECPubKey pk (sk);// calculate the public key the private key

	// plaintext p1 = a, b, c, d
	OCTETSTR p1(4); p1[0]='a'; p1[1]='b'; p1[2]='c'; p1[3]='d';
	int i;
	for (i=0; i<4; i++) {
		std::cout << p1[i];
	}
	std::cout << std::endl;

	ECIES ct1 (p1, pk); // encrypt using the public key

	std::cout << "ct1: " << std::endl << ct1 << std::endl;
	OCTETSTR p2;
	try { // try to catch any exceptions if the tag is invalid
		p2 = ct1.decrypt(sk); // decrypt using the private key
	} catch (borzoiException e) { // print the error message and exit
		e.debug_print ();
		return;
	}
	for (i=0; i<4; i++) {
		std::cout << p2[i];
	}
	std::cout << std::endl;


	// DER encoding
	DER der_str (ct1);
	HexEncoder hex_str (der_str);

	// You might save the DER ecoded ciphertext to a file or send it over 
	// the network here.
	std::cout << "DER Encoding: " << hex_str << std::endl;
	
	ECIES ct2;
	try { // try to catch any DER parsing errors
		ct2 = der_str.toECIES (); // decode the DER string
	} catch (borzoiException e) { // print the error message and exit
		e.debug_print ();
		return;
	}

	std::cout << "ct2: " << std::endl << ct2 << std::endl;

	OCTETSTR p3;
	try { // try to catch any exceptions if the tag is invalid
		p3 = ct2.decrypt(sk); // decrypt using the private key
	} catch (borzoiException e) { // print the error message and exit
		e.debug_print ();
		return;
	}
	for (i=0; i<4; i++) {
		std::cout << p3[i];
	}
	std::cout << std::endl;

}
Ejemplo n.º 19
0
/** Process a 'netinfo' cell: read and act on its contents, and set the
 * connection state to "open". */
static void
command_process_netinfo_cell(cell_t *cell, or_connection_t *conn)
{
  time_t timestamp;
  uint8_t my_addr_type;
  uint8_t my_addr_len;
  const uint8_t *my_addr_ptr;
  const uint8_t *cp, *end;
  uint8_t n_other_addrs;
  time_t now = time(NULL);

  long apparent_skew = 0;
  uint32_t my_apparent_addr = 0;

  if (conn->link_proto < 2) {
    log_fn(LOG_PROTOCOL_WARN, LD_OR,
           "Received a NETINFO cell on %s connection; dropping.",
           conn->link_proto == 0 ? "non-versioned" : "a v1");
    return;
  }
  if (conn->_base.state != OR_CONN_STATE_OR_HANDSHAKING_V2 &&
      conn->_base.state != OR_CONN_STATE_OR_HANDSHAKING_V3) {
    log_fn(LOG_PROTOCOL_WARN, LD_OR,
           "Received a NETINFO cell on non-handshaking connection; dropping.");
    return;
  }
  tor_assert(conn->handshake_state &&
             conn->handshake_state->received_versions);

  if (conn->_base.state == OR_CONN_STATE_OR_HANDSHAKING_V3) {
    tor_assert(conn->link_proto >= 3);
    if (conn->handshake_state->started_here) {
      if (!conn->handshake_state->authenticated) {
        log_fn(LOG_PROTOCOL_WARN, LD_OR, "Got a NETINFO cell from server, "
               "but no authentication.  Closing the connection.");
        connection_mark_for_close(TO_CONN(conn));
        return;
      }
    } else {
      /* we're the server.  If the client never authenticated, we have
         some housekeeping to do.*/
      if (!conn->handshake_state->authenticated) {
        tor_assert(tor_digest_is_zero(
                  (const char*)conn->handshake_state->authenticated_peer_id));
        connection_or_set_circid_type(conn, NULL);

        connection_or_init_conn_from_address(conn,
                  &conn->_base.addr,
                  conn->_base.port,
                  (const char*)conn->handshake_state->authenticated_peer_id,
                  0);
      }
    }
  }

  /* Decode the cell. */
  timestamp = ntohl(get_uint32(cell->payload));
  if (labs(now - conn->handshake_state->sent_versions_at) < 180) {
    apparent_skew = now - timestamp;
  }

  my_addr_type = (uint8_t) cell->payload[4];
  my_addr_len = (uint8_t) cell->payload[5];
  my_addr_ptr = (uint8_t*) cell->payload + 6;
  end = cell->payload + CELL_PAYLOAD_SIZE;
  cp = cell->payload + 6 + my_addr_len;
  if (cp >= end) {
    log_fn(LOG_PROTOCOL_WARN, LD_OR,
           "Addresses too long in netinfo cell; closing connection.");
    connection_mark_for_close(TO_CONN(conn));
    return;
  } else if (my_addr_type == RESOLVED_TYPE_IPV4 && my_addr_len == 4) {
    my_apparent_addr = ntohl(get_uint32(my_addr_ptr));
  }

  n_other_addrs = (uint8_t) *cp++;
  while (n_other_addrs && cp < end-2) {
    /* Consider all the other addresses; if any matches, this connection is
     * "canonical." */
    tor_addr_t addr;
    const uint8_t *next =
      decode_address_from_payload(&addr, cp, (int)(end-cp));
    if (next == NULL) {
      log_fn(LOG_PROTOCOL_WARN,  LD_OR,
             "Bad address in netinfo cell; closing connection.");
      connection_mark_for_close(TO_CONN(conn));
      return;
    }
    if (tor_addr_eq(&addr, &conn->real_addr)) {
      conn->is_canonical = 1;
      break;
    }
    cp = next;
    --n_other_addrs;
  }

  /* Act on apparent skew. */
  /** Warn when we get a netinfo skew with at least this value. */
#define NETINFO_NOTICE_SKEW 3600
  if (labs(apparent_skew) > NETINFO_NOTICE_SKEW &&
      router_get_by_id_digest(conn->identity_digest)) {
    char dbuf[64];
    int severity;
    /*XXXX be smarter about when everybody says we are skewed. */
    if (router_digest_is_trusted_dir(conn->identity_digest))
      severity = LOG_WARN;
    else
      severity = LOG_INFO;
    format_time_interval(dbuf, sizeof(dbuf), apparent_skew);
    log_fn(severity, LD_GENERAL, "Received NETINFO cell with skewed time from "
           "server at %s:%d.  It seems that our clock is %s by %s, or "
           "that theirs is %s. Tor requires an accurate clock to work: "
           "please check your time and date settings.",
           conn->_base.address, (int)conn->_base.port,
           apparent_skew>0 ? "ahead" : "behind", dbuf,
           apparent_skew>0 ? "behind" : "ahead");
    if (severity == LOG_WARN) /* only tell the controller if an authority */
      control_event_general_status(LOG_WARN,
                          "CLOCK_SKEW SKEW=%ld SOURCE=OR:%s:%d",
                          apparent_skew,
                          conn->_base.address, conn->_base.port);
  }

  /* XXX maybe act on my_apparent_addr, if the source is sufficiently
   * trustworthy. */
  (void)my_apparent_addr;

  if (connection_or_set_state_open(conn)<0) {
    log_fn(LOG_PROTOCOL_WARN, LD_OR, "Got good NETINFO cell from %s:%d; but "
           "was unable to make the OR connection become open.",
           safe_str_client(conn->_base.address),
           conn->_base.port);
    connection_mark_for_close(TO_CONN(conn));
  } else {
    log_info(LD_OR, "Got good NETINFO cell from %s:%d; OR connection is now "
             "open, using protocol version %d. Its ID digest is %s",
             safe_str_client(conn->_base.address),
             conn->_base.port, (int)conn->link_proto,
             hex_str(conn->identity_digest, DIGEST_LEN));
  }
  assert_connection_ok(TO_CONN(conn),time(NULL));
}
Ejemplo n.º 20
0
/**
 * Start at a random md5 hash and search through all possible hashes to find
 * a string that hashes to itself.
 */
int main(void)
{
	/* there are 2^128 possible md5 hashes */
	mpz_t max;
	mpz_init(max);
	mpz_ui_pow_ui(max, 2, MD5_BITS);

	/* initialize PRNG with MT algorithm and seed with time */
	gmp_randstate_t rand_state;
	gmp_randinit_mt(rand_state);
	gmp_randseed_ui(rand_state, time(NULL));
	
	/* pick a random one to start with and free PRNG memory */
	mpz_t start;
	mpz_init(start);
	mpz_urandomb(start, rand_state, MD5_BITS);
	gmp_randclear(rand_state);

	printf("Starting with random string: \"");
	mpz_out_str(stdout, HEX_BASE, start);
	printf("\"\n");
	
	/* current hash */
	mpz_t current;
	mpz_init_set(current, start);

	/* get ready to calculate hashes */
	MD5_CTX md5_ctx;
	unsigned char input[MD5_BYTES];
	unsigned char digest[MD5_BYTES];
	char input_str[MD5_STR_LEN + 1];
	char digest_str[MD5_STR_LEN + 1];

	/* search from start until max */
	while(mpz_cmp(current, max) < 0)
	{
		/* initialize MD5 and get current as an unsigned char[] */
		MD5_Init(&md5_ctx);
		mpz_export(input, NULL, 1, 1, 0, 0, current);
		
		/* hash the input string */
		hex_str(input_str, input, MD5_BYTES);
		MD5_Update(&md5_ctx, input_str, MD5_STR_LEN);
		MD5_Final(digest, &md5_ctx);

		/* check for a match */
		if(strncmp(input, digest, MD5_BYTES) == 0)
		{
			/* we have a winner! */
			hex_str(digest_str, digest, MD5_BYTES);
			printf("md5(\"%s\") = \"%s\"\n", input_str, digest_str);
		}

		/* keep looking */
		mpz_add_ui(current, current, 1);
	}

	/* now search backwards from start */
	mpz_set(current, start);
	mpz_sub_ui(current, current, 1);

	while(mpz_cmp_ui(current, 0) >= 0)
	{
		/* initialize MD5 and get current as an unsigned char[] */
		MD5_Init(&md5_ctx);
		mpz_export(input, NULL, 1, 1, 0, 0, current);
		
		/* hash the input string */
		hex_str(input_str, input, MD5_BYTES);
		MD5_Update(&md5_ctx, input_str, MD5_STR_LEN);
		MD5_Final(digest, &md5_ctx);

		/* check for a match */
		if(strncmp(input, digest, MD5_BYTES) == 0)
		{
			/* we have a winner! */
			hex_str(digest_str, digest, MD5_BYTES);
			printf("md5(\"%s\") = \"%s\"\n", input_str, digest_str);
		}

		/* keep looking */
		mpz_sub_ui(current, current, 1);
	}

	/* clean up */
	mpz_clear(max);
	mpz_clear(start);
	mpz_clear(current);
}