~singpolyma/biboumi

021f025cb039011ad07158b0d94f1b430a409e49 — louiz’ 7 years ago 3fdae6b
Refactor the sha1 digest into its own function, and do not use sprintf
4 files changed, 37 insertions(+), 14 deletions(-)

A louloulibs/xmpp/auth.cpp
A louloulibs/xmpp/auth.hpp
M louloulibs/xmpp/xmpp_component.cpp
M tests/xmpp.cpp
A louloulibs/xmpp/auth.cpp => louloulibs/xmpp/auth.cpp +21 -0
@@ 0,0 1,21 @@
#include <xmpp/auth.hpp>

#include <utils/sha1.hpp>

#include <iomanip>
#include <sstream>

std::string get_handshake_digest(const std::string& stream_id, const std::string& secret)
{
  sha1nfo sha1;
  sha1_init(&sha1);
  sha1_write(&sha1, stream_id.data(), stream_id.size());
  sha1_write(&sha1, secret.data(), secret.size());
  const uint8_t* result = sha1_result(&sha1);

  std::ostringstream digest;
  for (int i = 0; i < HASH_LENGTH; i++)
    digest << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(result[i]);

  return digest.str();
}

A louloulibs/xmpp/auth.hpp => louloulibs/xmpp/auth.hpp +6 -0
@@ 0,0 1,6 @@
#pragma once

#include <string>

std::string get_handshake_digest(const std::string& stream_id, const std::string& secret);


M louloulibs/xmpp/xmpp_component.cpp => louloulibs/xmpp/xmpp_component.cpp +3 -14
@@ 5,15 5,14 @@

#include <xmpp/xmpp_component.hpp>
#include <config/config.hpp>
#include <xmpp/jid.hpp>
#include <utils/sha1.hpp>
#include <utils/time.hpp>
#include <xmpp/auth.hpp>
#include <xmpp/jid.hpp>

#include <stdexcept>
#include <iostream>
#include <set>

#include <stdio.h>
#include <uuid/uuid.h>

#include <cstdlib>


@@ 139,17 138,7 @@ void XmppComponent::on_remote_stream_open(const XmlNode& node)
    }

  // Try to authenticate
  char digest[HASH_LENGTH * 2 + 1];
  sha1nfo sha1;
  sha1_init(&sha1);
  sha1_write(&sha1, this->stream_id.data(), this->stream_id.size());
  sha1_write(&sha1, this->secret.data(),  this->secret.size());
  const uint8_t* result = sha1_result(&sha1);
  for (int i=0; i < HASH_LENGTH; i++)
    sprintf(digest + (i*2), "%02x", result[i]);
  digest[HASH_LENGTH * 2] = '\0';

  auto data = "<handshake xmlns='" COMPONENT_NS "'>"s + digest + "</handshake>";
  auto data = "<handshake xmlns='" COMPONENT_NS "'>"s + get_handshake_digest(this->stream_id, this->secret) + "</handshake>";
  log_debug("XMPP SENDING: ", data);
  this->send_data(std::move(data));
}

M tests/xmpp.cpp => tests/xmpp.cpp +7 -0
@@ 1,6 1,7 @@
#include "catch.hpp"

#include <xmpp/xmpp_parser.hpp>
#include <xmpp/auth.hpp>

TEST_CASE("Test basic XML parsing")
{


@@ 45,3 46,9 @@ TEST_CASE("XML escape")
  const std::string unescaped = "'coucou'<cc>/&\"gaga\"";
  CHECK(xml_escape(unescaped) == "&apos;coucou&apos;&lt;cc&gt;/&amp;&quot;gaga&quot;");
}

TEST_CASE("handshake_digest")
{
  const auto res = get_handshake_digest("id1234", "S4CR3T");
  CHECK(res == "c92901b5d376ad56269914da0cce3aab976847df");
}