Thursday, March 21, 2024

Create an ECDSA signature with C# that can be verified using OpenSSL

 .net framework includes a handy library that can be used for generating digital signatures. However, the default output format is not DER and it cannot be verified using OpenSSL. There are many solutions in the Internet but they are super complex. The real solution is really simple, literaly half line of additional code. So here is some C# code that outputs DER encoded ECDSA signature that can be verified using OpenSSL:



  //assume data is a byte array that includes the data to be signed
  var ecdsa = ECDsa.Create(); // generates asymmetric key pair
  byte[] signature = ecdsa.SignData(data, HashAlgorithmName.SHA256, 
				DSASignatureFormat.Rfc3279DerSequence);

The last parameted of SignData does all the job :) You can find the official documentation of this method overload here

Tuesday, April 4, 2023

Authenticate users in python scripts using their Google account


Google offers user authentication through OpenID Connect. Although usually, this feature is used by web sites, it can also be used with desktop applications. In this repository you can find a Python3 script that authenticates users based on their Google account. 

What this script does is, it opens a web browser that redirects user to Google's authorization page and at the same time it begins a web server that "listens" for the access code. Upon receiving the access code it "exchanges" for an id token that includes user information.

Since the client secret of a desktop application can be easily protected, this script leverages Proof Key for Code Exchange by OAuth Public Clients, a technology defined in RFC 7636 and supported by Google. With PKCE, the script generates a random code verifier and transmits its SHA-256 hash when requesting the access code. Then, it transmits the actual code verifier when requesting the id token. 

Tuesday, March 28, 2023

A simple role-based access control system for .NET

In many cases, I need a simple solution for adding authentication and authorization in my .NET project, so as to easily develop the rest of the system. I need something simple, e.g., hardcode some user information in the configuration file. ASP.NET Identity is for most of the times an overkill. So I decided to create my own solution. You can find the source code of my solution in this GitHub repository

The most important part is in the appsettings.Development.json file where users, their passwords, and their roles are defined. For example:


  "AuthorizedUsers": {
    "administrator": {
      "Password": "admin!",
      "Roles": [ "Administrator" ]
    },
    "user1": {
      "Password": "user1!",
      "Roles": [ "User" ]
    }
  }

Then, in the Program.cs file the following code must be added:


builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/Account/Login";

    });

builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
});
...
app.UseAuthentication();
app.UseAuthorization();

User authentication is handled by the Account controller. By default all pages are accessed only by authenticated users. If you want to restrict a page to particular role a decorator can be added to the corresponding controller method, e.g.:


[Authorize(Roles = "Administrator")]
public IActionResult Admin()
{
   return View();
}

I hope you can find this code useful

Wednesday, April 6, 2022

Make fun things with your home IoT devices, securely over the internet.

I am planning to start a series of posts discussing how to put your IoT devices in the internet and do fun stuff with them. I will provide them as GitHub Wiki pages and I will also provide code and scripts when this is possible. This page will act as a placeholder.

Interact using Alexa with your IoT devices

In this first post I am using the excellent, free, Cloudflare Tunnel and I make my Raspberry Pi accessible over the internet using a custom domain and HTTPS. Only with a few clicks and no cost (apart from the cost of the domain name).

Then I provide an Amazon Alexa Skill that can be used for interacting with your Raspberry Pi using your Alexa device! In this simple example, I am implementing a simple REST API which is invoked using voice commands.

Have fun!


Monday, August 10, 2020

Create a JWT singed with RSA private key in .net core

The following example is a snippet of a C# code that generates an RSA private key out of a .pem file and uses it to sign a JWT. The privateKey variable, stores the contents of the .pem file minus the "-----BEGIN RSA PRIVATE KEY----" and "-----END RSA PRIVATE KEY-----" lines.

 
string privateKey = @"
MIIEpAIBAA
  ...
y53DdfYA==";
byte[] RSAprivateKey = Convert.FromBase64String(privateKey);
RSA rsa = RSA.Create();
rsa.ImportRSAPrivateKey(RSAprivateKey, out _);
var jwt = tokenHandler.CreateEncodedJwt(
   issuer: "...",
   audience: ...,
   ...
   signingCredentials: new SigningCredentials(
     key: new RsaSecurityKey(rsa),
     algorithm: SecurityAlgorithms.RsaSha256)
);

Thursday, April 9, 2020

Deploying smart contracts to ganache using python and web3

Ganache is a useful tool that emulates Ethereum blockchain in your local machine and it is very practical for testing smart contracts. Most tutorials explain how to deploy a smart contract in ganache using truffle, which is a development framework by the same company. But this is not necessary. Here, I explain how to write and compile a contract using Remix, and deploy it using python and web3.py.

Write your smart contract in remix and compile it. Then press the "ABI" button on the bottom left (see picture) and paste the output in a file. This will be our ABI_file. Do the same with the "Bytecode" bottom. This will be the bin_file. Then you can use the python script from this github repository. Make sure you have installed the dependencies and that you have modified the ABI_file and bin_file variables of the script accordingly.




Sunday, May 19, 2019

CoAP POST using libcoap

View a list of all libcoap examples here.

This example includes a CoAP server and a CoAP client. 
The client performs a CoAP POST request for the "coap://127.0.0.1/hello" resource. The server listens on port 5683 (default port) and prints the POSTed data

You can find the source code of this example, as well as, instructions for compiling it in Linux in this github repository, in the "post" folder.

Friday, November 25, 2016

A CoAP server for the riot operating system using libcoap

View a list of all libcoap examples here.

The riot operating system (https://riot-os.org/) is an operating system for the Internet of Things that currently supports many platforms. One of the main advantages of riot is that it supports programs and libraries written in C including libcoap.

In this github repository you will find an example of a CoAP server for the riot operating system https://github.com/nikosft/libcoap/tree/master/riot This server implements a default resource that outputs "Hello World!".In order to test the example, download the latest version of the rios os (https://github.com/RIOT-OS/RIOT), create a folder inside the examples directory and copy the code from https://github.com/nikosft/libcoap/tree/master/riot in that new directory. Then from a terminal type
$ make

If you encounter any problem, consult this riot wiki page https://github.com/RIOT-OS/RIOT/wiki/Family:-native In order to use the example you have to create a virtual interface in your linux machine. In order to do this invoke the following utility:
$ <riot directory>/dist/tools/tapsetup/tapsetup -c1

This utility will create a virtural interface and a bridge (for more information visit this wiki page https://github.com/RIOT-OS/RIOT/wiki/Virtual-riot-network). After this step, from the folder where you have put the example code invoke:
$ make term

This command will execute the binary created in the previous step and soon an ipv6 address will appear in the terminal. You can now access the coap server using the libcoap coap client and the displayed ipv6 address, by invoking the following command:
$ coap-client coap://[<ipv6 address>%tapbr0]

Tuesday, September 6, 2016

Asynchronous CoAP request-response using libcoap

View a list of all libcoap examples here.

This is an example of asynchronous request-response. The server listens on port 5683 (default port). When it receives a request for the "hello" resource, it sends and ACK and after 2 seconds it responds with a "Hello World!".

The client performs a CoAP GET request for the "coap://127.0.0.1/hello" resource and prints the response.

You can find the source code of this example, as well as, instructions for compiling it in Linux in this github repository, in the "seperate" folder.

Sunday, July 17, 2016

libcoap examples

libcoap is an open source C implementation of the CoAP protocol. It can be used for developing CoAP services in Linux, MacOS, as well as, in various IoT operating systems such as Contiki, LwIP, and TinyOS.

However, libcoap lacks  documentation. Apart from some installation instructions there is not any tutorial on how to use the library. Moreover, the examples included in the source code are very complex and they cause confusion. I have constructed a small set of examples that use libcoap to perform simple tasks.

All examples are available on github

List of examples




Tuesday, March 29, 2016

Share a host folder with an Ubuntu VM using VirtualBox

This post describes how an Ubuntu based virtual machine on VirtualBox can access a windows folder.

In order to achieve this functionality follow the next steps.

Step 1. Run VirtualBox Manager, right click on your VM and select settings. There select the "Shared Folders" Option and press the add button on the right. In the "Folder Path" select the folder that you want to share, and in the "Folder Name" type a name. Moreover, select "Auto-mount" and "Make Permanent".

 

Step 2. Run your VM. Your folder has been mounted in the directory /media named "sf_<Folder Name>", where <Folder Name> is the name you selected in step 1. Nevertheless, this folder cannot be accessed.

Step 3. In order to be able to access the shared folder from your VM you have to add you user account to the group "vboxsf". You can do that by executing the following command:

sudo usermod -a -G vboxsf <username> 

Where <username> is your account user name. Restart, and you will be able to access the shared folder.

Tuesday, November 24, 2015

A Hello World CoAP client-server using libcoap

View a list of all libcoap examples here.

This is a simple example of a CoAP server and a CoAP client. The server listens on port 5683 (default port) and responds with a "Hello World!" to every request for the "hello" resource. The response is piggybacked in the ACK message.

The client performs a CoAP GET request for the "coap://127.0.0.1/hello" resource and prints the response.

You can find the source code of this example, as well as, instructions for compiling it in Linux in this github repository, in the "piggybacked" folder.

Wednesday, October 21, 2015

DLNA with subtitles in D-Link DNS-320


D-Link DNS-320 is a network storage enclosure that supports DLNA. Unfortunately, the built-in DLNA server does not support subtitles. Nevertheless, this can be overcome by installing miniDLNA. miniDLNA can stream movies and subtitles, providing that the subtitles file has the same name as the movie file (minus the extension). The following has been tested successfully with UTF-8 encoded .srt files in Samsung  UE46ES6340 smart tv.

DNS-320 is a linux based device. Moreover, it's firmware can execute scripts, located in the root directory, every time the system boots. Fonz fun plug (ffp), its such a script that adds support for telnet, as well as, for installing additional software. In this post, we will use ffp ton install miniDLNA in our NAS.


Step 0 preparation

Make sure you have disabled the built-in DLNA server


Step 1 install ffp

Installing ffp is as trivial as copy pasting a file. Follow the instructions here https://nas-tweaks.net/371/hdd-installation-of-the-fun_plug-0-7-on-nas-devices/


Step 2 install miniDLNA

The web page included in step 2 has instructions about how to connect to your NAS using telnet. Follow these instructions and connect to your NAS. ffp includes a package manager for installing software.  Initially, the package manages has to be configured with download sites. This can be done using  uwsiteloader. uwsiteloader can be installed by following the instructions here https://nas-tweaks.net/371/hdd-installation-of-the-fun_plug-0-7-on-nas-devices/#Now_what.3F After downloading it and making it executable, run it. In the step when it requests to select download sites, select all of them. You can then install miniDLNA and configure following the steps here: http://forum.nas-central.org/viewtopic.php?f=249&t=5841&start=45#p56567  section "INSTALL INSTRUCTIONS". Make sure you edit /ffp/etc/minidlna.conf accordingly (vi can be used for the editing).

You are ready to go! A useful command that forces miniDLNA to rebuilt its database is /ffp/start/minidlna.sh rescan


Tuesday, July 28, 2015

Create self-singed certificate with extentions

For testing reasons I wanted to create a self-signed certificate that includes the subject alternative name extension, using openssl. Most guides require the creation of an openssl configuration file. I found out that this can be done without any configuration file, using only two openssl commands and a file that contains the subject alternative name extension parameters.

The first command is the following:

openssl req -newkey rsa:1024 -keyout server.key -out server.csr -subj '/C=GR/ST=Attiki/L=Athens/O=Fotiou Corp/OU=Security Department/CN=localhost/emailAddress=my@email.address' -nodes

This command creates a new private key and a new certificate signing request. Let's see the command parameters:

-newkey rsa:1024      It creates an RSA 1024 bits key
-keyout server.key  This is the file where the private key is stored
-out server.csr        This the file where the certificate signing request is stored
-subj ...                   This is the information included in the certificate
-nodes                          This command parameter instructs openssl to not encrypt the private key

Now create a file and insert the subject alternative name extension parameters. In this example, I have created a file named extentions.cnf which contains the following text:

subjectAltName=DNS:example.com, DNS:localhost

This line indicates that this certificate is valid for two DNS names, namely example.com and localhost. You may notice that the CN name included in the -subj command line parameter is also included here; the reason for that is because most browsers ignore the CN field when the subject alternative name extension is used. Finally the following command creates the desired certificate

openssl x509 -req -days 365 -signkey server.key -in server.csr -out server.crt -extfile extentions.cnf


Where:
-days 3650                          It is the number of days for which the certificate is valid
-signkey server.key         It is the private key generated previously and it used to sign the certificate
-in server.csr                   The certificate signing request we created with the previous command
-out server.crt                 The file in which the certificate will be stored
-extfile extentions.cnf The file we created with the subject alternative name extension parameters

Monday, October 20, 2014

Handling C#, MVC entity validation errors in a meaningful way

MVC's entity framework is a convenient tool for abstracting databases. However, when something goes wrong the debug messages are not very meaningful. Especially when an entity validation exception occurs.

The following try, catch block catches an entity validation exception and concatenates all validation error messages into a single string. Then this string can be displayed in a debug message.


try
{
   entities.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
   var errorMessages = ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage);
   //Join the list to a single string. 
   var fullErrorMessage = string.Join("; ", errorMessages);
   throw new Exception(fullErrorMessage);
}

Monday, October 14, 2013

The unfortunate cookies

Cookies sent over plain HTTP to Google websites can reveal information about a user


Disclaimer
The following has been reported to Google and is considered not an issue

Recently while visiting Google scholar I noticed that on the top right corner my Google username was displayed.

This appeared to me very strange, since I was not accessing this service using HTTPs. I fired up Wireshark and I revisited scholar once again. From the captured traffic it was obvious that my browser was sending a bunch of cookies over plain HTTP. I stored these cookies to a file, I imported them to a Firefox private browsing window and I visited Google scholar once again. To my surprise my username was still there. Moreover I was able to see my citations and my updates just like if I was signed in. By observing the cookies I noticed that most of them were for the domain *.google.gr, so as next step I visited http://www.google.gr/ig  in the same private session: all gadgets that do not require authentication (like weather) were there!

But the surprises continued. I edited the cookies file and I replaced the domain *.google.gr with *.youtube.com, I loaded the new file in a new Firefox private browsing window and I visited http://www.youtube.com. As it can be observed from the screenshot, my username, my subscriptions, as well as posts of my friends in google+, all were there!


It is astonishing how much information about a user can be gained simple by monitoring a mere HTTP session. 

Edit 1:
Even if the user logs out, the captured cookies continue to reveal the same information


Monday, August 12, 2013

Convert video files and embed subtitles using VLC

VLC player, by VideoLAN, is a handy media player with many features. VLC, among other things, enables the conversion of video files, from one format to another, enabling the same time the incorporation of subtitles.

Suppose that  we want to convert an h.254 video file to DivX with embedded subtitles. Suppose also that subtitles are stored in a separate (.srt) file with the same name as the video file.  Here are the steps that should be followed:

Run VLC and from the Media menu, select Convert/Save (Ctrl + R).

Select Convert/Save

In the file selection area, press Add, and choose the video file to be converted. Moreover, on the button-left menu press the arrow and select  Convert.

Select the Convert optionn

In the Destination area, press Browse, and select where your file should be saved (Note that you have to add the filename as well the extension). In the Settings area, select the Convertion profile and press the Edit selected profile button.

Press the button marked with the black square

In the new window select the Subtitles tab, check the Subtitles check box, select DVB subtitle on the listbox on the left, and check the Overlay subtitles on the video check box. Then press Save.

Subtitle options

Now by pressing Start, your video will be converted to desired format and the subtitles will be embedded in the output video file. 

Saturday, September 1, 2012

Send a facebook message using php

Facebook API does not provide any method for sending a message to the inbox of a user. Fortunately, messages can also be sent using XMPP, which is used by facebook chat, but can also be used for sending a message to a user that is offline (i.e., the message will appear in the user's inbox).

In this link you can find a php class that utilizes facebook's XMPP functionality and sends a message to a facebook user.

In order to use this class you need to obtain an API key, by registering your application here. In order to use this class you should provide, your API key, your user id, the current authorization token, and the user id of the user to which you wish to send a message.

In order to get your user id, you can user the facebook php sdk and use the getUser() method of the Facebook class. In order to get the authorization token you can invoke the getAccessToken() of the Facebook class

Wednesday, August 1, 2012

A proxy re-encryption implementation

Proxy re-encryption is scheme that allows a proxy to re-encrypt a ciphertext, encrypted with the public key of a user A, into a ciphertext that can be decrypted with a private key of a user B, without having access to the private key of A or B, as well as to the plaintext.

Green and Ateniese describe an Identity-based proxy re-encryption scheme in their paper and prove its security. An implementation of their solution can be found in my github repository. This is a python implementation using the Charm Crypto tool

Sunday, July 1, 2012

Export excel diagrams to pdf and use them in latex

If you are creating your diagrams using Excel 2007, there is an easy way to export them in .pdf and then use them as figures in your latex documents.

 Open your excel document, select your diagram and then press the office logo and select save as->pdf or exps. Choose a file name and select save as file type tou be PDF (*.pdf). This will result in a pdf file with the diagram and a lot of blank space. In order to remove the blank space use pdfcrop. This a utility is included both in MikTex (latex for windows) as well as in texlive-extra-utils ubuntu package. Alternatevily you can download it from here