JKRhb / dtls2

A DTLS library for Dart based on OpenSSL.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

cant open ffi

spm-prasanna26 opened this issue · comments

on this, late final _SSL_connectPtr =
_lookup<ffi.NativeFunction<ffi.Int Function(ffi.Pointer)>>(
'SSL_connect');

      I lost connection to device

Thank you for opening this issue, @spm-prasanna26! Can you post some code to reproduce the issue? And which OpenSSL version do you have installed?

In which context are you using the library? If you are using it in a Flutter app, then you might need to bundle OpenSSL with it.

In which context are you using the library? If you are using it in a Flutter app, then you might need to bundle OpenSSL with it.

I am using it in flutter app. I followed what is given in example code.

import 'dart:async';
import 'dart:convert';

import 'package:dtls2/dtls2.dart';
import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:typed_data';

//GeniPro tcp constants
final saverAdvancedIp = '172.16.3.26';
final localIp = '172.16.3.20';
const clientIdentity = 'Client_identity';
const shortLivedPsk =
    '1223dfghgwed';

//port
int udpPort = 49153;
int tcpPort = 49152;

const _identity = "Client_identity";

final _serverKeyStore = {_identity: shortLivedPsk};

const _ciphers = "TLS_AES_128_GCM_SHA256";

Uint8List? _serverPskCallback(Uint8List identity) {
  final identityString = utf8.decode(identity.toList());

  final psk = _serverKeyStore[identityString];

  if (psk == null) {
    return null;
  }

  return Uint8List.fromList(utf8.encode(psk));
}

final context = DtlsClientContext(
  verify: true,
  withTrustedRoots: true,
  ciphers: _ciphers,
  pskCredentialsCallback: (identityHint) {
    return PskCredentials(
      identity: Uint8List.fromList(utf8.encode(_identity)),
      preSharedKey: Uint8List.fromList(utf8.encode(shortLivedPsk)),
    );
  },
);

void main() async {
  const bindAddress = "::";
  //final peerAddress = InternetAddress("::1");

  final dtlsClient = await DtlsClient.bind(bindAddress, 0);
  RawDatagramSocket? udpSocket; // Choose the port number you want to use
  try {
    udpSocket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);

    print('Authentication start frame is send successfully!');
  } catch (e) {
    print('Error sending authentication start frame: $e');
  }

  if (udpSocket != null) {
    udpSocket.listen((event) async {
      if (event == RawSocketEvent.read) {
        final datagram = udpSocket?.receive();
        if (datagram != null) {
 
            print('Authentication start response frame is received');
          udpSocket?.close();
        
      }
    });
  }

  final DtlsConnection connection;
  try {
    connection = await dtlsClient.connect(
      InternetAddress(saverAdvancedIp),
      49152,
      context,
      timeout: const Duration(seconds: 5),
    );
  } on Exception {
    await dtlsClient.close();
    rethrow;
  }

  connection
    ..listen(
      (datagram) async {
        print(utf8.decode(datagram.data));
        await dtlsClient.close();
      },
    );
    //..send(Uint8List.fromList(utf8.encode('Hello World')));
  udpSocket?.send([frameTypeAuthStart], InternetAddress(saverAdvancedIp), udpPort);
}
import 'dart:async';
import 'dart:convert';

import 'package:dtls2/dtls2.dart';
import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:typed_data';

//GeniPro tcp constants
final saverAdvancedIp = '172.16.3.26';
final localIp = '172.16.3.20';
const clientIdentity = 'Client_identity';
const shortLivedPsk =
    '1223dfghgwed';

//port
int udpPort = 49153;
int tcpPort = 49152;

const _identity = "Client_identity";

final _serverKeyStore = {_identity: shortLivedPsk};

const _ciphers = "TLS_AES_128_GCM_SHA256";

Uint8List? _serverPskCallback(Uint8List identity) {
  final identityString = utf8.decode(identity.toList());

  final psk = _serverKeyStore[identityString];

  if (psk == null) {
    return null;
  }

  return Uint8List.fromList(utf8.encode(psk));
}

final context = DtlsClientContext(
  verify: true,
  withTrustedRoots: true,
  ciphers: _ciphers,
  pskCredentialsCallback: (identityHint) {
    return PskCredentials(
      identity: Uint8List.fromList(utf8.encode(_identity)),
      preSharedKey: Uint8List.fromList(utf8.encode(shortLivedPsk)),
    );
  },
);

void main() async {
  const bindAddress = "::";
  //final peerAddress = InternetAddress("::1");

  final dtlsClient = await DtlsClient.bind(bindAddress, 0);
  RawDatagramSocket? udpSocket; // Choose the port number you want to use
  try {
    udpSocket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);

    print('Authentication start frame is send successfully!');
  } catch (e) {
    print('Error sending authentication start frame: $e');
  }

  if (udpSocket != null) {
    udpSocket.listen((event) async {
      if (event == RawSocketEvent.read) {
        final datagram = udpSocket?.receive();
        if (datagram != null) {
 
            print('Authentication start response frame is received');
          udpSocket?.close();
        
      }
    });
  }

  final DtlsConnection connection;
  try {
    connection = await dtlsClient.connect(
      InternetAddress(saverAdvancedIp),
      49152,
      context,
      timeout: const Duration(seconds: 5),
    );
  } on Exception {
    await dtlsClient.close();
    rethrow;
  }

  connection
    ..listen(
      (datagram) async {
        print(utf8.decode(datagram.data));
        await dtlsClient.close();
      },
    );
    //..send(Uint8List.fromList(utf8.encode('Hello World')));
  udpSocket?.send([frameTypeAuthStart], InternetAddress(saverAdvancedIp), udpPort);
}

this is what I used to call.

I installed openssl by running command choco install openssl
And result is mentioned below,
openssl v1.1.1.2100 [Approved] openssl package files install completed. Performing other installation steps. Installing 64-bit openssl... openssl has been installed. WARNING: No registry key found based on 'OpenSSL-Win' PATH environment variable does not have C:\Program Files\OpenSSL-Win64\bin in it. Adding... WARNING: OPENSSL_CONF has been set to C:\Program Files\OpenSSL-Win64\bin\openssl.cfg openssl can be automatically uninstalled. Environment Vars (like PATH) have changed. Close/reopen your shell to see the changes (or in powershell/cmd.exe just type refreshenv`).
The install of openssl was successful.
Software installed to 'C:\Program Files\OpenSSL-Win64'

Chocolatey installed 11/11 packages.
See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).

Installed:

  • chocolatey-compatibility.extension v1.0.0
  • chocolatey-core.extension v1.4.0
  • chocolatey-windowsupdate.extension v1.0.5
  • KB2919355 v1.0.20160915
  • KB2919442 v1.0.20160915
  • KB2999226 v1.0.20181019
  • KB3033929 v1.0.5
  • KB3035131 v1.0.3
  • openssl v1.1.1.2100
  • vcredist140 v14.36.32532
  • vcredist2015 v14.0.24215.20170201`

Does the error also occur when you run the example within a Dart project? (For example, cloning this repository and then performing dart example/example.dart.)

No, Example is working as expected.

My scenario,
I have server in machine i.e HW(172.16.3.26) and dektop(172.16.3.20) where flutter application is running.

I have to created upd client connection and send data 3 to server and have to receive reply. Then server will send tls, I have to be ready to listen. But in that case it is not working.

No, Example is working as expected.

Okay, thank you for your feedback. I just tried a Flutter example on a Windows machine, too, and there I am not getting the error. Could you post a full stacktrace of the error you are getting?

My scenario, I have server in machine i.e HW(172.16.3.26) and dektop(172.16.3.20) where flutter application is running.

I have to created upd client connection and send data 3 to server and have to receive reply. Then server will send tls, I have to be ready to listen. But in that case it is not working.

Hmm, so the server is going to connect to the Flutter app? Or do you need to have the DTLS connection already established at this point? Or are you switching from DTLS to TLS? I think I haven't fully understood the setup here yet.

Here is my case.
UDP is working fine. TLS issue occurs.
IMG_20230717_232603

Here is my case.
UDP is working fine. TLS issue occurs.

Hmm, where does DTLS come into play here? Or do you mean DTLS when you write TLS?

Here is my case.
UDP is working fine. TLS issue occurs.

Hmm, where does DTLS come into play here? Or do you mean DTLS when you write TLS?

Do you know any flutter packages that support TLS ?

There is the "built-in" RawSecureSocket class, however, I think that one does not support Pre-Shared Keys :/ Unfortunately, doing a quick search on pub.dev also did not bring up any package that supports them. Do you need to use PSKs or would certificates also be an option for you?

There is the "built-in" RawSecureSocket class, however, I think that one does not support Pre-Shared Keys :/ Unfortunately, doing a quick search on pub.dev also did not bring up any package that supports them. Do you need to use PSKs or would certificates also be an option for you?

PSK is used in my case. just how it is done in example of dtls 2.0 flutter package. So, Any idea or possible to do it ?

PSK is used in my case. just how it is done in example of dtls 2.0 flutter package. So, Any idea or possible to do it ?

As far as I can tell, there currently seems to be no way to do it with TLS at the moment :/ You could try adapting the ffi code so that it uses TLS instead of DTLS (using an example like this one).

I created an issue regarding the PSK feature a while ago in the Dart SDK repository (see dart-lang/sdk#49636), but it has not been picked up yet by anyone, apparently.

Since it is out of the scope of this library, I will close the issue. However, feel free to leave additional comments if you have questions or want to discuss something :)

is it possible to reuse this dtls for tls ?
if yes, short explanation on how ?

Since DTLS uses UDP and TLS uses TCP, you would need to replace the RawDatagramSockets with RawSockets and then look up the necessary functions in the OpenSSL documentation or appropriate examples. You would then also need to regenerate the bindings to OpenSSL using ffigen to be able to use the necessary functions. If you find an example for a client/server that you can build upon, it should be doable.

My case is like server runs on desktop, client on hardware.
I need to connect with client using short pre shared key. once done.
I will get long pre shared key from client. then I have to secure connection with the latest key from server
.