CSockt Doesn't work with OpenSSL Ssl_connect Fails - visual-studio-2010

I Want to use CSocket with OpenSsl. failing in SSL_connect. with SSL_ERROR_WANT_READ error.
I am connecting so Linux SSL socket with MFC Socket. only SSL_connect fails.
sample code added below:
if(this->Create() == FALSE)
{
return false;
}
if(this->Connect(hostip.c_str(),port) == FALSE)
{
return false;
}
pSslCtx = SSL_CTX_new(SSLv23_method());
if (SSL_CTX_load_verify_locations(pSslCtx,strSslFile, NULL) != 1)
{
return false;
}
if (SSL_CTX_set_default_verify_paths(pSslCtx) != 1)
{
return false;
}
pSSLConn = SSL_new(pSslCtx);
if(!pSSLConn)
return false;
SSL_set_fd(pSSLConn, this->m_hSocket);
pBIOConn = BIO_new_socket(this->m_hSocket, BIO_NOCLOSE);
SSL_set_bio(pSSLConn, pBIOConn, pBIOConn);
SSL_set_connect_state(pSSLConn);
if (SSL_connect(pSSLConn) <= 0)
{
return false;
}

right is this :
SOCKET q = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
BIO *u7 = BIO_new_socket(q, BIO_NOCLOSE);
connect(q, (sockaddr*)&server, sizeof(server));
SSL_set_bio(cSSL, u7, u7);
SSL_connect(cSSL);
https://github.com/alexeyneu/BlockZero/blob/b8eec009208cbef5d644a1026678cb1f09e1a19b/trew/trew/trew.cpp#L81
and i do not see neither real ssl method nor cipher nor certs .

Related

TOTP Problem - Microsoft Authenticator is not matching the code generated on server

I am getting a not verified using the TOTP method I have found on the following link.
OTP code generation and validation with otp.net
!My! code is below.
The _2FAValue line at the top is embedded into the QR barcode that Microsoft Authenticator attaches too.
The _Check... Function is the server ajax call to the server which implements OTP.Net library exposing TOTP calculation.
MakeTOTPSecret creates an SHA1 version of a Guid which is applied to the User profile and stored in _gTOTPSecret. NB: This IS populated in the places it is used.
I think I must have missed something obvious to get a result, here.
loSetup2FAData._s2FAValue = $#"otpauth://totp/{loUser.UserName}?secret={loUser.MakeTOTPSecret()}&digits=6&issuer={Booking.Library.Classes.Constants._sCompanyName}&period=60&algorithm=SHA1";
[AllowAnonymous]
public JsonResult _CheckTOTPCodeOnServer([FromBody] Booking.Site.Models.Shared.CheckTotpData loCheckTotpData)
{
string lsMessage = "<ul>";
try
{
string lsEmail = this.Request.HttpContext.Session.GetString("Buku_sEmail");
Booking.Data.DB.Extensions.IdentityExtend.User loUser = this._oDbContext.Users.Where(U => U.UserName.ToLower() == lsEmail.ToLower() || U.Email == lsEmail).FirstOrDefault();
if (loUser != null && loUser.Load(this._oDbContext) && loUser._gTOTPSecret != Guid.Empty)
{
OtpNet.Totp loTotp = new Totp(Booking.Library.Classes.Utility.StringToBytes(loUser.MakeTOTPSecret()), 60, OtpHashMode.Sha1, 6);
loTotp.ComputeTotp(DateTime.Now);
long lnTimeStepMatched = 0;
bool lbVerify = loTotp.VerifyTotp(loCheckTotpData._nTotp.ToString("000000"), out lnTimeStepMatched, new VerificationWindow(2, 2));
if (lbVerify)
{
lsMessage += "<li>Successfully validated Totp code</li>";
lsMessage += "<li>Save is now activated</li>";
return this.Json(new { bResult = true, sMessage = lsMessage + "</ul>" });
}
}
}
catch (Exception loException)
{
lsMessage += "<li>" + Booking.Library.Classes.Utility.MakeExceptionMessage(true, loException, "\r\n", "_CheckTOTPCodeOnServer") + "</li>";
}
lsMessage += "<li>Unsuccessfully validated Totp code</li>";
return this.Json(new { bResult = false, sMessage = lsMessage + "</ul>" });
}
public string MakeTOTPSecret()
{
string lsReturn = String.Empty;
try
{
using (SHA1Managed loSha1 = new SHA1Managed())
{
var loHash = loSha1.ComputeHash(Encoding.UTF8.GetBytes(this._gTOTPSecret.ToString()));
var loSb = new StringBuilder(loHash.Length * 2);
foreach (byte b in loHash)
{
loSb.Append(b.ToString("X2"));
}
lsReturn = loSb.ToString();
}
}
catch (Exception loException)
{
Booking.Library.Classes.Utility.MakeExceptionMessage(true, loException, "\r\n", "Identity.MakeSHA1Secret");
}
return lsReturn;
}

Epson js SDK unable to use multiple printers

Intro
We're developing this javascript based web application that is supposed to print receipts using the epson javascript sdk.
Right now we've got this poc where multiple printers can be added to the app and where receipts can be printed per individual printer.
The problem is that the receipt will ONLY be printer from the last added printer.
Further investigating tells us that the sdk just uses the last added (connected) printer. This can be seen at the following images.
In the first image there are 2 printers setup. Notice the different ip addresses.
In the second image we log what EpsonPrinter instance is being used while printing. Notice the ip address is clearly the first printer.
In the third image we trace the network. Notice the ip address that is actually used (ignore the error).
We created our own EpsonPrinter class that can be found here or here below.
EpsonPrinter
export default class EpsonPrinter {
name = null
ipAddress = null
port = null
deviceId = null
crypto = false
buffer = false
eposdev = null
printer = null
intervalID = null
restry = 0
constructor (props) {
const {
name = 'Epson printer',
ipAddress,
port = 8008,
deviceId = 'local_printer',
crypto = false,
buffer = false
} = props
this.name = name
this.ipAddress = ipAddress
this.port = port
this.deviceId = deviceId
this.crypto = crypto
this.buffer = buffer
this.eposdev = new window.epson.ePOSDevice()
this.eposdev.onreconnecting = this.onReconnecting
this.eposdev.onreconnect = this.onReconnect
this.eposdev.ondisconnect = this.onDisconnect
this.connect()
}
onReconnecting = () => {
this.consoleLog('reconnecting')
}
onReconnect = () => {
this.consoleLog('reconnect')
}
onDisconnect = () => {
this.consoleLog('disconnect')
if (this.intervalID === null ){
this.intervalID = setInterval(() => this.reconnect(), 5000)
}
}
connect = () => {
this.consoleLog('connect')
this.eposdev.ondisconnect = null
this.eposdev.disconnect()
this.eposdev.connect(this.ipAddress, this.port, this.connectCallback)
}
reconnect = () => {
this.consoleLog('(Re)connect')
this.eposdev.connect(this.ipAddress, this.port, this.connectCallback)
}
connectCallback = (data) => {
clearInterval(this.intervalID)
this.intervalID = null
this.eposdev.ondisconnect = this.onDisconnect
if (data === 'OK' || data === 'SSL_CONNECT_OK') {
this.createDevice()
} else {
setTimeout(() => this.reconnect(), 5000)
}
}
createDevice = () => {
console.log('create device, try: ' + this.restry)
const options = {
crypto: this.crypto,
buffer: this.buffer
}
this.eposdev.createDevice(this.deviceId, this.eposdev.DEVICE_TYPE_PRINTER, options, this.createDeviceCallback)
}
createDeviceCallback = (deviceObj, code) => {
this.restry++
if (code === 'OK') {
this.printer = deviceObj
this.printer.onreceive = this.onReceive
} else if (code === 'DEVICE_IN_USE') {
if (this.restry < 5) {
setTimeout(() => this.createDevice(), 3000)
}
}
}
onReceive = (response) => {
this.consoleLog('on receive: ', response)
let message = `Print ${this.name} ${response.success ? 'success' : 'failute'}\n`
message += `Code: ${response.code}\n`
message += `Status: \n`
if (response.status === this.printer.ASB_NO_RESPONSE) { message += ' No printer response\n' }
if (response.status === this.printer.ASB_PRINT_SUCCESS) { message += ' Print complete\n' }
if (response.status === this.printer.ASB_DRAWER_KICK) { message += ' Status of the drawer kick number 3 connector pin = "H"\n' }
if (response.status === this.printer.ASB_OFF_LINE) { message += ' Offline status\n' }
if (response.status === this.printer.ASB_COVER_OPEN) { message += ' Cover is open\n' }
if (response.status === this.printer.ASB_PAPER_FEED) { message += ' Paper feed switch is feeding paper\n' }
if (response.status === this.printer.ASB_WAIT_ON_LINE) { message += ' Waiting for online recovery\n' }
if (response.status === this.printer.ASB_PANEL_SWITCH) { message += ' Panel switch is ON\n' }
if (response.status === this.printer.ASB_MECHANICAL_ERR) { message += ' Mechanical error generated\n' }
if (response.status === this.printer.ASB_AUTOCUTTER_ERR) { message += ' Auto cutter error generated\n' }
if (response.status === this.printer.ASB_UNRECOVER_ERR) { message += ' Unrecoverable error generated\n' }
if (response.status === this.printer.ASB_AUTORECOVER_ERR) { message += ' Auto recovery error generated\n' }
if (response.status === this.printer.ASB_RECEIPT_NEAR_END) { message += ' No paper in the roll paper near end detector\n' }
if (response.status === this.printer.ASB_RECEIPT_END) { message += ' No paper in the roll paper end detector\n' }
if (response.status === this.printer.ASB_SPOOLER_IS_STOPPED) { message += ' Stop the spooler\n' }
if (!response.success) {
alert(message)
// TODO: error message?
} else {
// TODO: success -> remove from queue
}
}
printReceipt = () => {
this.consoleLog(`Print receipt, `, this)
try {
if (!this.printer) {
throw `No printer created for ${this.name}`
}
this.printer.addPulse(this.printer.DRAWER_1, this.printer.PULSE_100)
this.printer.addText(`Printed from: ${this.name}\n`)
this.printer.send()
} catch (err) {
let message = `Print ${this.name} failure\n`
message += `Error: ${err}`
alert(message)
}
}
consoleLog = (...rest) => {
console.log(`${this.name}: `, ...rest)
}
}
Poc
The full working poc can be found here.
Epson javascript sdk
2.9.0
Does anyone have any experience with the epson sdk? It it supposed to be able to support multiple connections on the same time? Please let use know.
For the ones looking for a way to handle multiple printers using this SDK. We came up with the following work around:
We created a separated 'printer app' that is responsible for handling ONE printer connection and hosted it online. We then 'load' this printer app into our app that needs multiple connections using Iframes. Communication between app and printer app is done by means of window.PostMessage API to, for example, initialise the printer with the correct printer connection and providing data that has to be printed.
It takes some effort but was the most stable solution we could come up with handling multiple connections.
If anyone else comes up with a better approach please let me know!
You can checkout our printer app here for inspiration (inspect the app because it doesn't show much visiting it just like that).
For use your class EpsonPrinter, i add also myPrinters class after your class:
class myPrinters {
printers = null;
cantidad = 0;
constructor() {
console.log("Creo la coleccion de printers");
this.printers = [];
}
inicializarConeccionImpresora(idImpresora, ip, puerto, _deviceId) {
let ipAddress = ip;
let port = puerto;
let deviceId = _deviceId;
console.log("Agrego una impresora");
let myPrinter = new EpsonPrinter(ipAddress);
myPrinter.port = port;
myPrinter.deviceId = deviceId;
myPrinter.id = idImpresora;
console.log('Id impresora antes de connect es: ' + idImpresora);
myPrinter.connect();
this.printers[this.cantidad] = myPrinter;
this.cantidad ++;
}
imprimirPruebaJS(idImpresora) {
let printer = null;
let printerTemp = null
for(var i = 0; i < this.printers.length; i++) {
printerTemp = this.printers[i];
if (printerTemp.id == idImpresora) {
printer = printerTemp.printer;
}
}
if (printer == null) {
console.log("La impresora no esta iniciada en clase myPrinters");
return;
}
printer.addText('Hola mundo texto normal\n');
printer.addFeed();
printer.addCut(printer.CUT_FEED);
}
}
call myPrinters class in this way :
myEpsonPrinters = new myPrinters();
myEpsonPrinters.inicializarConeccionImpresora(1, '192.168.0.51', 8008, 'local_printer');
myEpsonPrinters.inicializarConeccionImpresora(2, '192.168.0.52', 8008, 'local_printer');
myEpsonPrinters.imprimirPruebaJS(1)
or
myEpsonPrinters.imprimirPruebaJS(2)
Test it and tell me.
Juan
Just create multiple objects for printing simple as this
this.eposdev = [];
let printersCnt = 3;
let self = this;
for(let i=1 ; i <= printersCnt ; i++){
this.eposdev[i] = new window.epson.ePOSDevice()
this.eposdev[i].onreconnecting = function (){
this.consoleLog('reConnecting')
}
this.eposdev[i].onreconnect = function (){
this.consoleLog('onReconnect')
}
this.eposdev[i].ondisconnect = function (){
this.consoleLog('onDisconnect')
}
}
function connect(printerKey) => {
this.consoleLog('connect')
this.eposdev.ondisconnect = null
this.eposdev.disconnect()
this.eposdev.connect(self.ipAddress[printerKey], self.port[printerKey], function(){
clearInterval(self.intervalID)
self.intervalID = null
self.eposdev[i].ondisconnect = self.ondisconnect
if (data === 'OK' || data === 'SSL_CONNECT_OK') {
console.log('create device, try: ' + self.restry)
const options = {
crypto: self.crypto,
buffer: self.buffer
}
self.eposdev[printerKey].createDevice(self.deviceId, self.eposdev[printerKey].DEVICE_TYPE_PRINTER, options, function(deviceObj, code){
this.restry++
if (code === 'OK') {
self.printer[printerKey] = deviceObj
self.printer.onreceive = function(){
console.log("onreceive");
}
} else if (code === 'DEVICE_IN_USE') {
if (self.restry < 5) {
setTimeout(() => self.createDevice(printerKey), 3000)
}
})
}
} else {
setTimeout(() => self.reconnect(printerKey), 5000)
}
})
}
Epson says that with version 2.12.0 you can add more than one printer.

How to verify client cert installed in system

I am trying to implement a multiplatform device/client certificate chck in my app.
I want to implement for Windows and Mac, so the common implementation in c++ with few platform specific code.
I have OpenSSL integrated too.
I have Client cert installed in Windows personal store and for Mac in login key chain.
I have a the CA chain as form of .pem file.
I wanted to get the leaf CA from Pem file using openssl, than use the issuer name and use platform specific code to get matching client cert from device.
Than I want to get the context of clinet cert and use openssl to verify againt the CA chain
The problem for me here is,
1. how to get the leaf from the PEM
2. How to retrive the public part of installed client cert in both Windos/mac?
Regards,
Birajendu
here is the piece of code
X509_STORE *openssl_store = NULL;
X509_STORE_CTX *vrfy_ctx = NULL;
OpenSSL_add_all_algorithms();
if (!(openssl_store=X509_STORE_new())) {
printf("Error creating X509_STORE_CTX object");
return false;
}
vrfy_ctx = X509_STORE_CTX_new();
if (NULL == vrfy_ctx) {
printf("X509_STORE_CTX_new failed");
return false;
}
if (1 != X509_STORE_load_locations(openssl_store, tmpCertFile.c_str(), NULL)) {
printf("Error loading CA cert or chain file");
return false;
}
HCERTSTORE hStore = NULL;
BYTE *pCert = NULL;
DWORD dwCert = 0;
PCCERT_CONTEXT pCertContext = NULL;
//Open Personal Certificate Store
hStore = CertOpenSystemStore(0, TEXT("MY"));
if (hStore == NULL) {
printf("CertOpenSystemStore failed, error : %d", GetLastError());
return false;
}
//Enumerate Certificate Store
while (pCertContext = CertEnumCertificatesInStore(hStore, pCertContext)) {
const unsigned char *cert_data = pCertContext->pbCertEncoded;
X509 *cert = d2i_X509(NULL, &cert_data, pCertContext->cbCertEncoded);
X509_STORE_CTX_init(vrfy_ctx, openssl_store, cert, NULL);
int ret = X509_verify_cert(vrfy_ctx);
X509_STORE_CTX_cleanup(vrfy_ctx);
if (1 == ret) {
printf("Matching client certificate found");
return true;
}
if (cert) {
X509_free(cert);
}
}
if (hStore) {
CertCloseStore(hStore, CERT_CLOSE_STORE_CHECK_FLAG);
}

Process gets stuck in oSession.Logoff()

Pstcreation works properly with outlook installed.
Now, I am trying to create a pst file with standalone version of MAPI . But my process is stuck in oSession.LogOff(). Further if a comment that oSession.LogOff() line and subsequently call the CreatePstWithRedemption function to create an other pst, the process gets stuck in oSession.LogonPstStore
private bool CreatePstWithRedemption(EmailJTableArgs objJTablArgs, EmailFilterArgs objFilterArgs,
EmailExportRequestParams emailExportRequestParams)
{
RDOSession oSession = null;
IRDOStore store = null;
RDOFolder fFOlder = null;
RDOFolder childFolder = null;
IRDOItems folderItems = null;
var pstCreationStatus = false;
try
{
oSession = new RDOSession();
store = oSession.LogonPstStore(_fileName, 1, "PST");
var folderName = Path.GetFileNameWithoutExtension(_fileName);
if (store != null)
{
fFOlder = store.IPMRootFolder;
foreach (RDOFolder folder in fFOlder.Folders)
{
folder.Delete();
}
childFolder = fFOlder.Folders.Add(folderName, Type.Missing);
folderItems = childFolder.Items;
var resultOfGetEmails = new ResultGetEmails();
resultOfGetEmails.TotalCount = -1;
do
{
var journalEmails = GetEmailList(objFilterArgs, objJTablArgs, emailExportRequestParams,
resultOfGetEmails);
for (var i = 0; i < journalEmails.Count; i++)
{
IRDOMail mail = null;
try
{
mail = folderItems.Add(rdoItemType.olMailItem);
// populate mail fields
mail.Sent = true;
mail.Save();
}
finally
{
if (mail != null)
Marshal.ReleaseComObject(mail);
}
}
resultOfGetEmails.TotalCount -= BatchSize;
objJTablArgs.PageStartIndex += BatchSize;
} while (resultOfGetEmails.TotalCount > 0);
pstCreationStatus = true;
}
}
finally
{
// Do cleanup
if (oSession != null && oSession.LoggedOn)
{
try
{
oSession.Logoff();
Marshal.ReleaseComObject(oSession);
}
catch
{
}
}
}
return pstCreationStatus;
}
Note: The same thing works well when run in an environment where outlook is installed.

how to send message from client-web to server-MFC-app?

My task is create a client-web communicate to server-mfc-app. That mean I am not allow to change server-mfc-app code, but must make web can talk to that server-mfc-app. That server-mfc-app uses socket and can communicate to client-mfc-app.
I created a client-web can connect to server-mfc-app successful (server-mfc-app accepts connection), but there is a problem when client-web sends message to server-mfc-app: server-MFC-app knows client-web sends message, but it can get message by function void CChatServerDlg::ReceiveData(SOCKET hSocket) (I run debug mode server-mfc-app to watch all functions).
Server-MFC-app code:
ON_MESSAGE(MSG_ASYNC, OnAsyncSelect)
LRESULT CChatServerDlg::OnAsyncSelect(WPARAM wParam, LPARAM lParam)
{
if (WSAGETSELECTERROR(lParam) != 0)
{
}
else
{
switch(WSAGETSELECTEVENT(lParam))
{
case FD_READ:
ReceiveData(wParam);
break;
case FD_ACCEPT:
{
CUserSocket *pClient = AcceptConnection();
if(pClient)
{
CString sReport;
sReport.Format(_T("Có kết nối từ IP: %s , Port: %d"),
pClient->GetRemoteIpAddr(),pClient->GetRemotePort());
m_lbStatus.AddString(sReport);
SendData(pClient->GetSocket(),_T("Server sẵn sàng"));
m_groupNewUsers.AddUser(pClient);
}
}
break;
case FD_CLOSE:
CUserGroup *gr = m_groupList.FindGroup(wParam);
if (gr!=NULL)
gr->RemoveUser(wParam);
closesocket(wParam);
OnLbnSelchangeGrouplist();
m_lbStatus.AddString(_T("Đã đóng kết nối"));
break;
}
}
return 0L;
}
void CChatServerDlg::ReceiveData(SOCKET hSocket)
{
char szBuf[MAX_LEN];
int nByteRe = recv(hSocket, szBuf, MAX_LEN, 0);//always successful
// with client-mfc-app, and always unsuccessful with client-web below.
if (nByteRe<=0)
return;
wchar_t wch[MAX_LEN];
CString s = _T("");
MultiByteToWideChar(CP_UTF8,0,szBuf,nByteRe,wch,nByteRe/2);
wch[nByteRe/2] = '\0';
s += wch;
SolveRequest(hSocket,s);
}
Client-web code:
<?php
error_reporting(E_ALL);
$port = 2012;
$address = "127.0.0.1";
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed: reason: "
.socket_strerror(socket_last_error())."<br/>";
}
$result = socket_connect($socket, $address, $port);
if ($result === false) {
echo "socket_connect() failed.\nReason: ($result) "
.socket_strerror(socket_last_error($socket)) ."<br/>";
}else{
echo "Connecting successful."."<br/>";
}
$msg = "ULIST";
$len = strlen($msg);
$flag=0;
socket_sendto($socket, $msg, $len, $flag, $address, $port);
//socket_close($socket);
?>
Please try to use socket_write($socket, $msg, $len ); instead of socket_sendto for connected socket

Resources