Setting up Cipher for Open SSL - c

I want to set the cipher suit as per my requirement each time my system boots up. However, if I consider the case where I accidentally write the wrong Cipher String in SSL_CTX_set_cipher_list() it will fail to add cipher and end up no https connection to system. To over come this issue I am planning to add some recovery in which case if it fails to set the cipher defined by user it will set-up the connection using default string so my system does not boot up without https connection.If I pass the right string to SSL_CTX_set_cipher_list() function it works. In theory it seems to work perfect but when it comes to practical it fail very badly.Here is my code,
ret = SSL_CTX_set_cipher_list (pMudPort->pMudPortSSLState->pSSLCtx,"Temp");
printf("Return = %d -------------------\n",ret);
if(!ret)
{
printf("fail to set cipher -------------------\n");
printf("setting to default -------------------\n");
SSL_CTX_set_cipher_list (pMudPort->pMudPortSSLState->pSSLCtx,
pSSLConfiguration->pCipherList);
}
Here,
"Temp" is just to make sure it fails for the first time.
Even if I am overwriting cipher string second time my system does not support https.
Is it the right way to set the cipher again or I need to clean up something before assigning cipher again?

Related

How to execute net.exe from Windows Runtime in C?

To introduce my problem, I'm currently working on a project to remotely shut down stationary PCs via Siemens S7 PLC. Those PCs are used for an experimental manufactoring line for relays at my university. The principle is quiet simple, the PLC sends the IP of a computer via UDP to a special "always on" PC with monitoring functions on which a UDP server listens for packets (this PC starts up together with the manufactoring line; OS is Windows 10; the server is written in C). If it receives an UDP packet, it triggers a net use command followed by a shutdown command to that specific IP. This works just fine, if the server.exe is started manually. The goal is to get the server working when it's automatically started with e.g. the taskplaner. Exactly this is the main issue here, it's not working as background task. It receives the packets (I tested it) but then nothing happens, no computer shuts down. So I guessed it must be the net use or the shutdown command. At first I tried to set up the net use with a system()call:
char command[100] = { 0 };
snprintf(command, sizeof(command), "#NET USE \\\\%s\\IPC$ %s /USER:%s", ip, pw, usr);
system(command);
As this won't work I found following statement for system()on the Windows API reference page:
This API cannot be used in applications that execute in the Windows Runtime.
So I figured I had to find an alternative, which leads me to my next try with the ShellExecute() function. It seemed like there are no problems concerning the execution out of the runtime, cause I could't find any word about it at the reference page. I tried:
char programpath[100] = "C:\\Windows\\System32\\net.exe";
char cmdline[100] = { 0 };
snprintf(cmdline, sizeof(cmdline), "Use \\\\%s\\IPC$ %s /USER:%s", ip, pw, usr);
ShellExecute(NULL, "open", programpath, cmdline, NULL, SW_HIDE);
But nope, won't work either from the background. When I asked my prof about it, he said he is more into Linux, so he could only guess that there might be a problem with the permissions. He meant that my server has possibly no rights to open those two programs, when calling them as background process. But even after a long time of investigating through the internet, I can't find a proper solution which fits to my problem.

Testing a custom openSSL engine from the command line

Quick question: How can I verify the functionality of a custom openSSL engine I'm writing from the command line?
Right now I am following along with this great tutorial, and am successfully able to exercise the engine (which returns a digest value of all 2's) using my test program (source code here, test program located at test/wssha256engine_test.c).
brett#wintermute:~/openssl_ws/wssha256engine$ make test
make[1]: Entering directory
/home/brett/openssl_ws/wssha256engine/test
make[1]: '../bin/test' is up to date.
make[1]: Leaving directory
/home/brett/openssl_ws/wssha256engine/test
brett#wintermute:~/openssl_ws/wssha256engine$ bin/test
Engine Loaded...
Initializing wssha256 engine...
*TEST: Successfuly initialized engine [A test engine for the ws sha256 hardware encryption module, on the Xilinx ZYNQ7000]
init result = 1
Digest NID=672 requested
SHA256 algorithm context initialized
*TEST: Digest INIT 1
SHA256 update
*TEST: Digest Update 1
SHA256 final: sizeof(EVP_MD)= 120
SHA256 cleanup
*TEST: Digest Final 1 Digest size:32
22222222222222222222222222222222
However, because reasons, I would like to also use the openssl command line interface to exercise the engine I just wrote, and have it compute the digest of a random string like in this other tutorial, just using sha256 and not md5.
But when I try and do this, the engine does not load and results in an error telling me that the NID of my digest doesn't exist, and just hashes the string with the standard algorithm instead:
brett#wintermute:~/openssl_ws/wssha256engine$ echo "Hello" | openssl dgst -engine /home/brett/Thesis/openssl_ws/wssha256engine/bin/libwssha256engine.so -sha256
ERROR: Digest is empty! (NID = 0)
engine "wssha256" set.
(stdin)= 66a045b452102c59d840ec097d59d9467e13a3f34f6494e539ffd32c1bb35f18
Why can't I use my engine on the command line, but I can create a C program to load it? And how can I use my engine to compute a digest from the command line?
Note: I am able to load the engine from the command line, just not use it.
After some digging, I was able to figure out why the CLI invocation of my engine did not work, and fix the issue.
The problem was in my digest selector function (original broken code is commented out below). Originally, I returned a failure status from the digest selector function, rather than returning the number of digest IDs that the engine supports.
static int wssha256engine_digest_selector(ENGINE *e, const EVP_MD **digest, const int **nids, int nid)
{
if (!digest)
{
*nids = wssha256_digest_ids;
// THIS ORIGINAL CODE CAUSES THE ENGINE TO NEVER INITIALIZE FROM A CLI INVOCATION
//printf("ERROR: Digest is empty! (NID = %d)\n",nid);
//return FAIL;
// THIS FIXES IT
int retnids = sizeof(wssha256_digest_ids - 1) / sizeof(wssha256_digest_ids[0]);
printf("wssha256engine: digest nids requested...returning [%d]\n",retnids);
return retnids;
}
Reading more closely, we can find that OpenSSL calls the digest selector function in following (separate) ways:
with digest being NULL. In this case, *nids is expected to be assigned a
zero-terminated array of NIDs and the call returns with the number of available NIDs. OpenSSL uses this to determine what digests are supported by this engine.
with digest being non-NULL. In this case, *digest is expected to be assigned the pointer to the EVP_MD structure corresponding to the NID given by nid. The call returns with 1 if the request NID was one supported by this engine, otherwise 0.
So even though my engine supported sha256, the CLI invocation didn't work because it must have not been initialized with a digest before the digest selector function is invoked (no clue as to the order of operations when using the CLI). However when I manually initialized it in my test program, all worked fine. Changing to a non-failure return value to support invocation 1. above fixed the problem.

Encryption Program That Works With NodeJs and mbedtls

First, let me start by stating that I am not a cryptographer by any means, and I am not very good at writing c code either, so please excuse me if the answer to this question is obvious or answered. I am developing a messaging program and cannot use TLS on the target platform. As a result, I need to find a way to encrypt each message using a symmetric pre shared key cipher, like AES.
I am seeking a method to encrypt and decrypt data between an mbedtls program (such as aescrypt2) on one end, and a nodejs program on the other. Mbedtls, formerly polarssl, is a library which provides encryption for embedded devices. Included with the source code are some sample programs, like aescrypt2, rsaencrypt, ecdsa and crypt_and_hash.
Aescrypt2 works fine when the resulting encrypted data is also decrypted using aescrypt2, but I cannot seem to get data encrypted with aescrypt to decrypt using nodejs crypto or any other program for that matter, including openssl. For example:
echo 'this is a test message' >test.txt
aescrypt 0 test.txt test.out hex:E76B2413958B00E193
aescrypt 1 test.out test.denc hex:E76B2413958B00E193
cat test.denc
this is a test message
With openssl:
openssl enc -in out.test -out outfile.txt -d -aes256 -k E76B2413958B00E193
bad magic number
Some sample node code that doesn't currently work
var crypto = require('crypto');
var AESCrypt = {};
AESCrypt.decrypt = function(cryptkey, iv, encryptdata) {
encryptdata = new Buffer(encryptdata, 'base64').toString('binary');
var decipher = crypto.createDecipheriv('aes-256-cbc', cryptkey, iv),
decoded = decipher.update(encryptdata, 'binary', 'utf8');
decoded += decipher.final('utf8');
return decoded;
}
AESCrypt.encrypt = function(cryptkey, iv, cleardata) {
var encipher = crypto.createCipheriv('aes-256-cbc', cryptkey, iv),
encryptdata = encipher.update(cleardata, 'utf8', 'binary');
encryptdata += encipher.final('binary');
encode_encryptdata = new Buffer(encryptdata, 'binary').toString('base64');
return encode_encryptdata;
}
var cryptkey = crypto.createHash('sha256').update('Nixnogen').digest(),
iv = 'a2xhcgAAAAAAAAAA',
buf = "Here is some data for the encrypt", // 32 chars
enc = AESCrypt.encrypt(cryptkey, iv, buf);
var dec = AESCrypt.decrypt(cryptkey, iv, enc);
console.warn("encrypt length: ", enc.length);
console.warn("encrypt in Base64:", enc);
console.warn("decrypt all: " + dec);
This results in either errors or garbage text every time. I have tried tweaking a variety of things as well.
I've tried this a hundred different ways, including using the -pass pass:password arg to no avail. Using nodejs, I have either gotten bad decrypt errors, or garbled nonsense back upon decryption. I have tried following many tutorials on the net, such as this one, and suggestions from this thread, and everything else I can find. I have read that different encryption programs use different standards, so compatibility across platforms/programs/languages is not always guaranteed, but I imagine somebody has been in this predicement before and knows a solution?
How would I, using nodejs, decrypt data encrypted by aescrypt2 (or a program like it)? I have only been able to make it work using a system exec call and having node execute aescrypt2 to decrypt/encrypt the data, which is not ideal, as it slows things down considerably. I am open to using a different program than aescrypt2. The only requirements are that it must run on Linux, cannot use openssl libs (because they are not supported on the target system), the program should be small and simple, due to space limitations, and foremost, the encryption/decryption needs to be compatible with nodejs. Any help would be much appreciated.
How would I, using nodejs, decrypt data encrypted by aescrypt2 (or a program like it)?
Sorry to say, but there's no better answer than: by doing the exact same thing that aescrypt2 does when decrypting a file. You've linked to the source by yourself, so just perform the same steps in node.js as they do in C in the decrypt branch.
First of all, get familiar with the layout of the file containing the encrypted data:
/*
* The encrypted file must be structured as follows:
*
* 00 .. 15 Initialization Vector
* 16 .. 31 AES Encrypted Block #1
* ..
* N*16 .. (N+1)*16 - 1 AES Encrypted Block #N
* (N+1)*16 .. (N+1)*16 + 32 HMAC-SHA-256(ciphertext)
*/
So you need to extract the IV, the encrypted blocks and the HMAC from the file, not try to decrypt the whole thing as you try with openssl (your openssl example also does not use the right IV but rather tries to derive it from the key provided - read the man page).
Next, get the key right. The actual key used to encrypt/decrypt is not the one provided on the command line, but rather 8192 iterations of hashing the IV with the key passed on the command line, using SHA256.
Finally, they decrypt, using AES-256-ECB (your openssl and node.js examples use CBC!), every 16 bytes and XOR the result with the pervious 16 bytes (the IV is used for the first 16 bytes).
There's maybe more to it, I just listed the most obvious things I saw when reading through the aescrypt2.c code.
So my advise is: try to write the same logic in node.js and try to find node.js crypto calls for the respective mbedtls counterparts.
I'm not a crypto expert, but I bet that the aescrypt implementation has so many steps that feel complicated (like generating the actual key used), because they know how to do crypto and are just doing it the right way.

How to set total length of TCP option in Linux kernel?

I'm trying to add a new TCP option inside Linux kernel. However, I find that my new option cannot coexist with other options because there are no enough spaces in the option field for it. I get the warning from wireshark as "option goes past end of options".
So I'm wondering how I can extend the length of the whole TCP option field?
In tcp_parse_options() of tcp_input.c, I find such statement:
int length = (th->doff * 4) - sizeof(struct tcphdr);
And the while loop to parse options starts with while (length > 0). However, no matter how I increase the value of th->doff in tcp_make_synack() of tcp_output.c, the problem remains. I also suspect this is because I add the option in SYN pakcet while this function is for SYN-ACK. But I cannot find similar functions such as tcp_make_synack()....
Does anyone have any insights of this problem?
Thanks!

libmpdclient: detect lost connection to MPD daemon

I'm writing a plugin for my statusbar to print MPD state, currently using the libmpdclient library. It has to be robust to properly handle lost connections in case MPD is restarted, but simple checking with mpd_connection_get_error on existing mpd_connection object does not work – it can detect the error only when the initial mpd_connection_new fails.
This is a simplified code I'm working with:
#include <stdio.h>
#include <unistd.h>
#include <mpd/client.h>
int main(void) {
struct mpd_connection* m_connection = NULL;
struct mpd_status* m_status = NULL;
char* m_state_str;
m_connection = mpd_connection_new(NULL, 0, 30000);
while (1) {
// this check works only on start up (i.e. when mpd_connection_new failed),
// not when the connection is lost later
if (mpd_connection_get_error(m_connection) != MPD_ERROR_SUCCESS) {
fprintf(stderr, "Could not connect to MPD: %s\n", mpd_connection_get_error_message(m_connection));
mpd_connection_free(m_connection);
m_connection = NULL;
}
m_status = mpd_run_status(m_connection);
if (mpd_status_get_state(m_status) == MPD_STATE_PLAY) {
m_state_str = "playing";
} else if (mpd_status_get_state(m_status) == MPD_STATE_STOP) {
m_state_str = "stopped";
} else if (mpd_status_get_state(m_status) == MPD_STATE_PAUSE) {
m_state_str = "paused";
} else {
m_state_str = "unknown";
}
printf("MPD state: %s\n", m_state_str);
sleep(1);
}
}
When MPD is stopped during the execution of the above program, it segfaults with:
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x00007fb2fd9557e0 in mpd_status_get_state () from /usr/lib/libmpdclient.so.2
The only way I can think of to make the program safe is to establish a new connection in every iteration, which I was hoping to avoid. But then what if the connection is lost between individual calls to libmpdclient functions? How often, and more importantly how exactly, should I check if the connection is still alive?
The only way I could find that really works (beyond reestablishing a connection with each run) is using the idle command. If mpd_recv_idle (or mpd_run_idle) returns 0, it is an error condition, and you can take that as a cue to free your connection and run from there.
It's not a perfect solution, but it does let you keep a live connection between runs, and it helps you avoid segfaults (though I don't think you can completely avoid them, because if you send a command and mpd is killed before you recv it, I'm pretty sure the library still segfaults). I'm not sure if there is a better solution. It would be fantastic if there was a reliable way to detect if your connection was still alive via the API, but I can't find anything of the sort. It doesn't seem like libmpdclient is well-built for very long-lived connections that have to deal with mpd instances that go up and down over time.
Another lower-level option is to use sockets to interact with MPD through its protocol directly, though in doing that you'd likely reimplement much of libmpdclient itself anyway.
EDIT: Unfortunately, the idle command does block until something happens, and can sit blocking for as long as a single audio track will last, so if you need your program to do other things in the interim, you have to find a way to implement it asynchronously or in another thread.
Assuming "conn" is a connection created with "mpd_connection_new":
if (mpd_connection_get_error(conn) == MPD_ERROR_CLOSED) {
// mpd_connection_get_error_message(conn)
// will return "Connection closed by the server"
}
You can run this check after almost any libmpdclient call, including "mpd_recv_idle" or (as per your example) "mpd_run_status".
I'm using libmpdclient 2.18, and this certainly works for me.

Resources