]> git.basschouten.com Git - openhab-addons.git/blob
1c63bb82b813064dbf0e616edd137b7eb87de1d5
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.digitalstrom.internal.lib.serverconnection.impl;
14
15 import java.io.ByteArrayInputStream;
16 import java.io.File;
17 import java.io.FileInputStream;
18 import java.io.FileNotFoundException;
19 import java.io.FileWriter;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.net.HttpURLConnection;
23 import java.net.MalformedURLException;
24 import java.net.SocketTimeoutException;
25 import java.net.URL;
26 import java.nio.charset.StandardCharsets;
27 import java.security.KeyManagementException;
28 import java.security.NoSuchAlgorithmException;
29 import java.security.SecureRandom;
30 import java.security.Security;
31 import java.security.cert.CertificateEncodingException;
32 import java.security.cert.CertificateException;
33 import java.security.cert.CertificateFactory;
34 import java.security.cert.X509Certificate;
35 import java.util.Base64;
36
37 import javax.net.ssl.HostnameVerifier;
38 import javax.net.ssl.HttpsURLConnection;
39 import javax.net.ssl.SSLContext;
40 import javax.net.ssl.SSLHandshakeException;
41 import javax.net.ssl.SSLSession;
42 import javax.net.ssl.SSLSocketFactory;
43 import javax.net.ssl.TrustManager;
44 import javax.net.ssl.X509TrustManager;
45
46 import org.openhab.binding.digitalstrom.internal.lib.config.Config;
47 import org.openhab.binding.digitalstrom.internal.lib.manager.ConnectionManager;
48 import org.openhab.binding.digitalstrom.internal.lib.serverconnection.HttpTransport;
49 import org.openhab.binding.digitalstrom.internal.lib.serverconnection.simpledsrequestbuilder.constants.ParameterKeys;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 /**
54  * The {@link HttpTransportImpl} executes a request to the digitalSTROM-Server.
55  * <p>
56  * If a {@link Config} is given at the constructor. It sets the SSL-Certificate what is set in
57  * {@link Config#getCert()}. If there is no SSL-Certificate, but a path to an external SSL-Certificate file what is set
58  * in {@link Config#getTrustCertPath()} this will be set. If no SSL-Certificate is set in the {@link Config} it will be
59  * red out from the server and set in {@link Config#setCert(String)}.
60  *
61  * <p>
62  * If no {@link Config} is given the SSL-Certificate will be stored locally.
63  *
64  * <p>
65  * The method {@link #writePEMCertFile(String)} saves the SSL-Certificate in a file at the given path. If all
66  * SSL-Certificates shout be ignored the flag <i>exeptAllCerts</i> have to be true at the constructor
67  * </p>
68  * <p>
69  * If a {@link ConnectionManager} is given at the constructor, the session-token is not needed by requests and the
70  * {@link ConnectionListener}, which is registered at the {@link ConnectionManager}, will be automatically informed
71  * about
72  * connection state changes through the {@link #execute(String, int, int)} method.
73  * </p>
74  *
75  * @author Michael Ochel - Initial contribution
76  * @author Matthias Siegele - Initial contribution
77  */
78 public class HttpTransportImpl implements HttpTransport {
79
80     private static final String LINE_SEPERATOR = System.getProperty("line.separator");
81     private static final String BEGIN_CERT = "-----BEGIN CERTIFICATE-----" + LINE_SEPERATOR;
82     private static final String END_CERT = LINE_SEPERATOR + "-----END CERTIFICATE-----" + LINE_SEPERATOR;
83
84     private final Logger logger = LoggerFactory.getLogger(HttpTransportImpl.class);
85     private static final short MAY_A_NEW_SESSION_TOKEN_IS_NEEDED = 1;
86
87     private String uri;
88
89     private int connectTimeout;
90     private int readTimeout;
91
92     private Config config;
93
94     private ConnectionManager connectionManager;
95
96     private String cert;
97     private SSLSocketFactory sslSocketFactory;
98     private final HostnameVerifier hostnameVerifier = new HostnameVerifier() {
99
100         @Override
101         public boolean verify(String arg0, SSLSession arg1) {
102             return arg0.equals(arg1.getPeerHost()) || arg0.contains("dss.local.");
103         }
104     };
105
106     /**
107      * Creates a new {@link HttpTransportImpl} with registration of the given {@link ConnectionManager} and set ignore
108      * all SSL-Certificates. The {@link Config} will be automatically added from the configurations of the given
109      * {@link ConnectionManager}.
110      *
111      * @param connectionManager to check connection, can be null
112      * @param exeptAllCerts (true = all will ignore)
113      */
114     public HttpTransportImpl(ConnectionManager connectionManager, boolean exeptAllCerts) {
115         this.connectionManager = connectionManager;
116         this.config = connectionManager.getConfig();
117         init(config.getHost(), config.getConnectionTimeout(), config.getReadTimeout(), exeptAllCerts);
118     }
119
120     /**
121      * Creates a new {@link HttpTransportImpl} with configurations of the given {@link Config} and set ignore all
122      * SSL-Certificates.
123      *
124      * @param config to get configurations, must not be null
125      * @param exeptAllCerts (true = all will ignore)
126      */
127     public HttpTransportImpl(Config config, boolean exeptAllCerts) {
128         this.config = config;
129         init(config.getHost(), config.getConnectionTimeout(), config.getReadTimeout(), exeptAllCerts);
130     }
131
132     /**
133      * Creates a new {@link HttpTransportImpl} with configurations of the given {@link Config}.
134      *
135      * @param config to get configurations, must not be null
136      */
137     public HttpTransportImpl(Config config) {
138         this.config = config;
139         init(config.getHost(), config.getConnectionTimeout(), config.getReadTimeout(), false);
140     }
141
142     /**
143      * Creates a new {@link HttpTransportImpl}.
144      *
145      * @param uri of the server, must not be null
146      */
147     public HttpTransportImpl(String uri) {
148         init(uri, Config.DEFAULT_CONNECTION_TIMEOUT, Config.DEFAULT_READ_TIMEOUT, false);
149     }
150
151     /**
152      * Creates a new {@link HttpTransportImpl} and set ignore all SSL-Certificates.
153      *
154      * @param uri of the server, must not be null
155      * @param exeptAllCerts (true = all will ignore)
156      */
157     public HttpTransportImpl(String uri, boolean exeptAllCerts) {
158         init(uri, Config.DEFAULT_CONNECTION_TIMEOUT, Config.DEFAULT_READ_TIMEOUT, exeptAllCerts);
159     }
160
161     /**
162      * Creates a new {@link HttpTransportImpl}.
163      *
164      * @param uri of the server, must not be null
165      * @param connectTimeout to set
166      * @param readTimeout to set
167      */
168     public HttpTransportImpl(String uri, int connectTimeout, int readTimeout) {
169         init(uri, connectTimeout, readTimeout, false);
170     }
171
172     /**
173      * Creates a new {@link HttpTransportImpl} and set ignore all SSL-Certificates..
174      *
175      * @param uri of the server, must not be null
176      * @param connectTimeout to set
177      * @param readTimeout to set
178      * @param exeptAllCerts (true = all will ignore)
179      */
180     public HttpTransportImpl(String uri, int connectTimeout, int readTimeout, boolean exeptAllCerts) {
181         init(uri, connectTimeout, readTimeout, exeptAllCerts);
182     }
183
184     private void init(String uri, int connectTimeout, int readTimeout, boolean exeptAllCerts) {
185         logger.debug("init HttpTransportImpl");
186         this.uri = fixURI(uri);
187         this.connectTimeout = connectTimeout;
188         this.readTimeout = readTimeout;
189         // Check SSL Certificate
190         if (exeptAllCerts) {
191             sslSocketFactory = generateSSLContextWhichAcceptAllSSLCertificats();
192         } else {
193             if (config != null) {
194                 cert = config.getCert();
195                 logger.debug("generate SSLcontext from config cert");
196                 if (cert != null && !cert.isBlank()) {
197                     sslSocketFactory = generateSSLContextFromPEMCertString(cert);
198                 } else {
199                     String trustCertPath = config.getTrustCertPath();
200                     if (trustCertPath != null && !trustCertPath.isBlank()) {
201                         logger.debug("generate SSLcontext from config cert path");
202                         cert = readPEMCertificateStringFromFile(trustCertPath);
203                         if (cert != null && !cert.isBlank()) {
204                             sslSocketFactory = generateSSLContextFromPEMCertString(cert);
205                         }
206                     } else {
207                         logger.debug("generate SSLcontext from server");
208                         cert = getPEMCertificateFromServer(this.uri);
209                         sslSocketFactory = generateSSLContextFromPEMCertString(cert);
210                         if (sslSocketFactory != null) {
211                             config.setCert(cert);
212                         }
213                     }
214                 }
215             } else {
216                 logger.debug("generate SSLcontext from server");
217                 cert = getPEMCertificateFromServer(this.uri);
218                 sslSocketFactory = generateSSLContextFromPEMCertString(cert);
219             }
220         }
221     }
222
223     private String fixURI(String uri) {
224         String fixedURI = uri;
225         if (!fixedURI.startsWith("https://")) {
226             fixedURI = "https://" + fixedURI;
227         }
228         if (fixedURI.split(":").length != 3) {
229             fixedURI = fixedURI + ":8080";
230         }
231         return fixedURI;
232     }
233
234     private String fixRequest(String request) {
235         return request.replace(" ", "");
236     }
237
238     @Override
239     public String execute(String request) {
240         return execute(request, this.connectTimeout, this.readTimeout);
241     }
242
243     private short loginCounter = 0;
244
245     @Override
246     public String execute(String request, int connectTimeout, int readTimeout) {
247         // NOTE: We will only show exceptions in the debug level, because they will be handled in the checkConnection()
248         // method and this changes the bridge state. If a command was send it fails than and a sensorJob will be
249         // execute the next time, by TimeOutExceptions. By other exceptions the checkConnection() method handles it in
250         // max 1 second.
251         String response = null;
252         HttpsURLConnection connection = null;
253         try {
254             String correctedRequest = checkSessionToken(request);
255             connection = getConnection(correctedRequest, connectTimeout, readTimeout);
256             if (connection != null) {
257                 connection.connect();
258                 final int responseCode = connection.getResponseCode();
259                 if (responseCode != HttpURLConnection.HTTP_FORBIDDEN) {
260                     if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
261                         response = new String(connection.getErrorStream().readAllBytes(), StandardCharsets.UTF_8);
262                     } else {
263                         response = new String(connection.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
264                     }
265                     if (response != null) {
266                         if (!response.contains("Authentication failed")) {
267                             if (loginCounter > 0) {
268                                 connectionManager.checkConnection(responseCode);
269                             }
270                             loginCounter = 0;
271                         } else {
272                             connectionManager.checkConnection(ConnectionManager.AUTHENTIFICATION_PROBLEM);
273                             loginCounter++;
274                         }
275                     }
276
277                 }
278                 connection.disconnect();
279                 if (response == null && connectionManager != null
280                         && loginCounter <= MAY_A_NEW_SESSION_TOKEN_IS_NEEDED) {
281                     if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
282                         execute(addSessionToken(correctedRequest, connectionManager.getNewSessionToken()),
283                                 connectTimeout, readTimeout);
284                         loginCounter++;
285                     } else {
286                         connectionManager.checkConnection(responseCode);
287                         loginCounter++;
288                         return null;
289                     }
290                 }
291                 return response;
292             }
293         } catch (SocketTimeoutException e) {
294             informConnectionManager(ConnectionManager.SOCKET_TIMEOUT_EXCEPTION);
295         } catch (java.net.ConnectException e) {
296             informConnectionManager(ConnectionManager.CONNECTION_EXCEPTION);
297         } catch (MalformedURLException e) {
298             informConnectionManager(ConnectionManager.MALFORMED_URL_EXCEPTION);
299         } catch (java.net.UnknownHostException e) {
300             informConnectionManager(ConnectionManager.UNKNOWN_HOST_EXCEPTION);
301         } catch (SSLHandshakeException e) {
302             informConnectionManager(ConnectionManager.SSL_HANDSHAKE_EXCEPTION);
303         } catch (IOException e) {
304             logger.error("An IOException occurred: ", e);
305             informConnectionManager(ConnectionManager.GENERAL_EXCEPTION);
306         } finally {
307             if (connection != null) {
308                 connection.disconnect();
309             }
310         }
311         return null;
312     }
313
314     private boolean informConnectionManager(int code) {
315         if (connectionManager != null && loginCounter < MAY_A_NEW_SESSION_TOKEN_IS_NEEDED) {
316             connectionManager.checkConnection(code);
317             return true;
318         }
319         return false;
320     }
321
322     private String checkSessionToken(String request) {
323         if (checkNeededSessionToken(request)) {
324             if (connectionManager != null) {
325                 String sessionToken = connectionManager.getSessionToken();
326                 if (sessionToken == null) {
327                     return addSessionToken(request, connectionManager.getNewSessionToken());
328                 }
329                 return addSessionToken(request, sessionToken);
330             }
331         }
332         return request;
333     }
334
335     private boolean checkNeededSessionToken(String request) {
336         String requestFirstPart = request.substring(0, request.indexOf("?"));
337         String functionName = requestFirstPart.substring(requestFirstPart.lastIndexOf("/") + 1);
338         return !DsAPIImpl.METHODS_MUST_NOT_BE_LOGGED_IN.contains(functionName);
339     }
340
341     private String addSessionToken(String request, String sessionToken) {
342         String correctedRequest = request;
343         if (!correctedRequest.contains(ParameterKeys.TOKEN)) {
344             if (correctedRequest.contains("?")) {
345                 correctedRequest = correctedRequest + "&" + ParameterKeys.TOKEN + "=" + sessionToken;
346             } else {
347                 correctedRequest = correctedRequest + "?" + ParameterKeys.TOKEN + "=" + sessionToken;
348             }
349         } else {
350             String strippedRequest = correctedRequest
351                     .substring(correctedRequest.indexOf(ParameterKeys.TOKEN + "=") + ParameterKeys.TOKEN.length() + 1);
352             strippedRequest = strippedRequest.substring(0, strippedRequest.lastIndexOf("&"));
353             correctedRequest = correctedRequest.replaceFirst(strippedRequest, sessionToken);
354         }
355         return correctedRequest;
356     }
357
358     private HttpsURLConnection getConnection(String request, int connectTimeout, int readTimeout) throws IOException {
359         String correctedRequest = request;
360         if (correctedRequest != null && !correctedRequest.isBlank()) {
361             correctedRequest = fixRequest(correctedRequest);
362             URL url = new URL(this.uri + correctedRequest);
363             HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
364             if (connection != null) {
365                 connection.setConnectTimeout(connectTimeout);
366                 connection.setReadTimeout(readTimeout);
367                 if (sslSocketFactory != null) {
368                     connection.setSSLSocketFactory(sslSocketFactory);
369                 }
370                 if (hostnameVerifier != null) {
371                     connection.setHostnameVerifier(hostnameVerifier);
372                 }
373             }
374             return connection;
375         }
376         return null;
377     }
378
379     @Override
380     public int checkConnection(String testRequest) {
381         try {
382             HttpsURLConnection connection = getConnection(testRequest, connectTimeout, readTimeout);
383             if (connection != null) {
384                 connection.connect();
385                 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
386                     if (new String(connection.getInputStream().readAllBytes(), StandardCharsets.UTF_8)
387                             .contains("Authentication failed")) {
388                         return ConnectionManager.AUTHENTIFICATION_PROBLEM;
389                     }
390                 }
391                 connection.disconnect();
392                 return connection.getResponseCode();
393             } else {
394                 return ConnectionManager.GENERAL_EXCEPTION;
395             }
396         } catch (SocketTimeoutException e) {
397             return ConnectionManager.SOCKET_TIMEOUT_EXCEPTION;
398         } catch (java.net.ConnectException e) {
399             return ConnectionManager.CONNECTION_EXCEPTION;
400         } catch (MalformedURLException e) {
401             return ConnectionManager.MALFORMED_URL_EXCEPTION;
402         } catch (java.net.UnknownHostException e) {
403             return ConnectionManager.UNKNOWN_HOST_EXCEPTION;
404         } catch (IOException e) {
405             return ConnectionManager.GENERAL_EXCEPTION;
406         }
407     }
408
409     @Override
410     public int getSensordataConnectionTimeout() {
411         return config != null ? config.getSensordataConnectionTimeout() : Config.DEFAULT_SENSORDATA_CONNECTION_TIMEOUT;
412     }
413
414     @Override
415     public int getSensordataReadTimeout() {
416         return config != null ? config.getSensordataReadTimeout() : Config.DEFAULT_SENSORDATA_READ_TIMEOUT;
417     }
418
419     private String readPEMCertificateStringFromFile(String path) {
420         if (path == null || path.isBlank()) {
421             logger.error("Path is empty.");
422         } else {
423             File dssCert = new File(path);
424             if (dssCert.exists()) {
425                 if (path.endsWith(".crt")) {
426                     try (InputStream certInputStream = new FileInputStream(dssCert)) {
427                         String cert = new String(certInputStream.readAllBytes(), StandardCharsets.UTF_8);
428                         if (cert.startsWith(BEGIN_CERT)) {
429                             return cert;
430                         } else {
431                             logger.error("File is not a PEM certificate file. PEM-Certificates starts with: {}",
432                                     BEGIN_CERT);
433                         }
434                     } catch (FileNotFoundException e) {
435                         logger.error("Can't find a certificate file at the path: {}\nPlease check the path!", path);
436                     } catch (IOException e) {
437                         logger.error("An IOException occurred: ", e);
438                     }
439                 } else {
440                     logger.error("File is not a certificate (.crt) file.");
441                 }
442             } else {
443                 logger.error("File not found");
444             }
445         }
446         return null;
447     }
448
449     @Override
450     public String writePEMCertFile(String path) {
451         String correctedPath = path == null ? "" : path.trim();
452         File certFilePath;
453         if (!correctedPath.isBlank()) {
454             certFilePath = new File(correctedPath);
455             boolean pathExists = certFilePath.exists();
456             if (!pathExists) {
457                 pathExists = certFilePath.mkdirs();
458             }
459             if (pathExists && !correctedPath.endsWith("/")) {
460                 correctedPath = correctedPath + "/";
461             }
462         }
463         InputStream certInputStream = new ByteArrayInputStream(cert.getBytes(StandardCharsets.UTF_8));
464         X509Certificate trustedCert;
465         try {
466             trustedCert = (X509Certificate) CertificateFactory.getInstance("X.509")
467                     .generateCertificate(certInputStream);
468
469             certFilePath = new File(
470                     correctedPath + trustedCert.getSubjectDN().getName().split(",")[0].substring(2) + ".crt");
471             if (!certFilePath.exists()) {
472                 certFilePath.createNewFile();
473                 FileWriter writer = new FileWriter(certFilePath, true);
474                 writer.write(cert);
475                 writer.flush();
476                 writer.close();
477                 return certFilePath.getAbsolutePath();
478             } else {
479                 logger.error("File allready exists!");
480             }
481         } catch (IOException e) {
482             logger.error("An IOException occurred: ", e);
483         } catch (CertificateException e1) {
484             logger.error("A CertificateException occurred: ", e1);
485         }
486         return null;
487     }
488
489     private SSLSocketFactory generateSSLContextFromPEMCertString(String pemCert) {
490         if (pemCert != null && !pemCert.isBlank() && pemCert.startsWith(BEGIN_CERT)) {
491             try {
492                 InputStream certInputStream = new ByteArrayInputStream(pemCert.getBytes(StandardCharsets.UTF_8));
493                 final X509Certificate trustedCert = (X509Certificate) CertificateFactory.getInstance("X.509")
494                         .generateCertificate(certInputStream);
495
496                 final TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
497
498                     @Override
499                     public java.security.cert.X509Certificate[] getAcceptedIssuers() {
500                         return null;
501                     }
502
503                     @Override
504                     public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
505                             throws CertificateException {
506                         if (!certs[0].equals(trustedCert)) {
507                             throw new CertificateException();
508                         }
509                     }
510
511                     @Override
512                     public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
513                             throws CertificateException {
514                         if (!certs[0].equals(trustedCert)) {
515                             throw new CertificateException();
516                         }
517                     }
518                 } };
519
520                 SSLContext sslContext = SSLContext.getInstance("SSL");
521                 sslContext.init(null, trustManager, new java.security.SecureRandom());
522                 return sslContext.getSocketFactory();
523             } catch (NoSuchAlgorithmException e) {
524                 logger.error("A NoSuchAlgorithmException occurred: ", e);
525             } catch (KeyManagementException e) {
526                 logger.error("A KeyManagementException occurred: ", e);
527             } catch (CertificateException e) {
528                 logger.error("A CertificateException occurred: ", e);
529             }
530         } else {
531             logger.error("Cert is empty");
532         }
533         return null;
534     }
535
536     private String getPEMCertificateFromServer(String host) {
537         HttpsURLConnection connection = null;
538         try {
539             URL url = new URL(host);
540
541             connection = (HttpsURLConnection) url.openConnection();
542             connection.setHostnameVerifier(hostnameVerifier);
543             connection.setSSLSocketFactory(generateSSLContextWhichAcceptAllSSLCertificats());
544             connection.connect();
545
546             java.security.cert.Certificate[] cert = connection.getServerCertificates();
547             connection.disconnect();
548
549             byte[] by = ((X509Certificate) cert[0]).getEncoded();
550             if (by.length != 0) {
551                 return BEGIN_CERT + Base64.getEncoder().encodeToString(by) + END_CERT;
552             }
553         } catch (MalformedURLException e) {
554             if (!informConnectionManager(ConnectionManager.MALFORMED_URL_EXCEPTION)) {
555                 logger.error("A MalformedURLException occurred: ", e);
556             }
557         } catch (IOException e) {
558             short code = ConnectionManager.GENERAL_EXCEPTION;
559             if (e instanceof java.net.ConnectException) {
560                 code = ConnectionManager.CONNECTION_EXCEPTION;
561             } else if (e instanceof java.net.UnknownHostException) {
562                 code = ConnectionManager.UNKNOWN_HOST_EXCEPTION;
563             }
564             if (!informConnectionManager(code) || code == -1) {
565                 logger.error("An IOException occurred: ", e);
566             }
567         } catch (CertificateEncodingException e) {
568             logger.error("A CertificateEncodingException occurred: ", e);
569         } finally {
570             if (connection != null) {
571                 connection.disconnect();
572             }
573         }
574         return null;
575     }
576
577     private SSLSocketFactory generateSSLContextWhichAcceptAllSSLCertificats() {
578         Security.addProvider(Security.getProvider("SunJCE"));
579         TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
580
581             @Override
582             public java.security.cert.X509Certificate[] getAcceptedIssuers() {
583                 return null;
584             }
585
586             @Override
587             public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
588             }
589
590             @Override
591             public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
592             }
593         } };
594
595         try {
596             SSLContext sslContext = SSLContext.getInstance("SSL");
597
598             sslContext.init(null, trustAllCerts, new SecureRandom());
599
600             return sslContext.getSocketFactory();
601         } catch (KeyManagementException e) {
602             logger.error("A KeyManagementException occurred", e);
603         } catch (NoSuchAlgorithmException e) {
604             logger.error("A NoSuchAlgorithmException occurred", e);
605         }
606         return null;
607     }
608 }