EmbDev.net

Forum: µC & Digital Electronics Set callback to validate a server certificate // security protocol used in a HTTP GET request


von Sam (Guest)


Rate this post
1 useful
not useful
Hello altogether,

I am trying to program an ESP8266 with the Arduino IDE. By the help of 
https://randomnerdtutorials.com/esp8266-nodemcu-http-get-post-arduino/ I 
created a so called sketch which sends a HTTP GET request to a 
WebService running on a server:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

const char* ssid = "MyWiFiName";
const char* password = "MyWifiPassword";

//My Domain name with URL path or IP address with path
String serverName = "http://192.168.200.123:55558/api/DBGeraetestatus";

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
//unsigned long timerDelay = 5000;

void setup() {
  Serial.begin(115200); 

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
 
  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}

void loop() {
  //Send an HTTP POST request every 10 minutes
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      HTTPClient http;

      String serverPath = serverName + "?filter=ipadresse&value=192.168.200.244";
      
      // My Domain name with URL path or IP address with path
      http.begin(serverPath.c_str());
      
      // Send HTTP GET request
      int httpResponseCode = http.GET();
      
      if (httpResponseCode>0) {
        Serial.print("HTTP Response code: ");
        Serial.println(httpResponseCode);
        String payload = http.getString();
        Serial.println(payload);
      }
      else {
        Serial.print("Error code: ");
        Serial.println(httpResponseCode);
      }
      // Free resources
      http.end();
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

The answer is always a JSON which contains a 4 digit code.

The WebService on the server itself sends another HTTP GET request to a 
special machine, but by attaching NetworkCredentials (username + 
password) and setting on the one Hand the 
ServerCertificateValidationCallback to validate a server certificate and 
on the other hand the security protocol used by the ServicePoint objects 
which the ServicePointManager object manages. Please see the following 
C# code:
private string getPinFromWebservice(string ip)
{
    Uri.TryCreate(string.Format(Constants.generatePinPath, ip), UriKind.Absolute, out requestUri);

    var request = HttpWebRequest.Create(requestUri);
    request.ContentType = "application/json";
    request.Method = "GET";

    NetworkCredential nc = new NetworkCredential("MyNetworkCredentialName", "MyNetworkCredentialPassword");
    CredentialCache cache = new CredentialCache();
    cache.Add(requestUri, "Basic", nc);
    cache.Add(requestUri, "NTLM", nc);
    request.Credentials = cache;

    ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            var json = reader.ReadToEnd();
            return System.Text.RegularExpressions.Regex.Replace(json, @"[^0-9]", "").ToString();
        }
    }
}

I found out, that
http.setAuthorization(user, password); 
adds basic auth and HttpClient could theoretically handle https, but may 
require a certificate as parameter of
begin();
(Source: 
https://github.com/esp8266/Arduino/blob/5d2563eee98ae116dc3d4b6bc14225efb3c85098/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h#L153)

Is it possible to set ServerCertificateValidationCallback and the 
SecurityProtocol in Arduino/C as well? So could this C#-Code somehow be 
translated that it runs onto my ESP8266? The goal is to skip the server, 
send the request directly via https and with attached NetworkCredentials 
to this special machine and getting this 4 digit code to unlock this 
special machine.

Thanks in advance for every answer and help effort.

Best regards

Reply

Entering an e-mail address is optional. If you want to receive reply notifications by e-mail, please log in.

Rules — please read before posting

  • Post long source code as attachment, not in the text
  • Posting advertisements is forbidden.

Formatting options

  • [c]C code[/c]
  • [avrasm]AVR assembler code[/avrasm]
  • [code]code in other languages, ASCII drawings[/code]
  • [math]formula (LaTeX syntax)[/math]




Bild automatisch verkleinern, falls nötig