]> git.basschouten.com Git - openhab-addons.git/blob
90732b2564e27307bd13eed8b9d62b9124e522bb
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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
14 package org.openhab.binding.ipcamera.internal;
15
16 import java.security.MessageDigest;
17 import java.security.NoSuchAlgorithmException;
18 import java.util.Random;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.binding.ipcamera.internal.handler.IpCameraHandler;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 import io.netty.channel.ChannelDuplexHandler;
27 import io.netty.channel.ChannelHandlerContext;
28 import io.netty.handler.codec.http.HttpResponse;
29
30 /**
31  * The {@link MyNettyAuthHandler} is responsible for handling the basic and digest auths
32  *
33  *
34  * @author Matthew Skinner - Initial contribution
35  */
36
37 @NonNullByDefault
38 public class MyNettyAuthHandler extends ChannelDuplexHandler {
39     public final Logger logger = LoggerFactory.getLogger(getClass());
40     private IpCameraHandler ipCameraHandler;
41     private String username, password;
42     private String httpMethod = "", httpUrl = "";
43     private byte ncCounter = 0;
44     private String nonce = "", opaque = "", qop = "";
45     private String realm = "";
46
47     public MyNettyAuthHandler(String user, String pass, IpCameraHandler handle) {
48         ipCameraHandler = handle;
49         username = user;
50         password = pass;
51     }
52
53     public void setURL(String method, String url) {
54         httpUrl = url;
55         httpMethod = method;
56     }
57
58     private String calcMD5Hash(String toHash) {
59         try {
60             MessageDigest messageDigest = MessageDigest.getInstance("MD5");
61             byte[] array = messageDigest.digest(toHash.getBytes());
62             StringBuffer stringBuffer = new StringBuffer();
63             for (int i = 0; i < array.length; ++i) {
64                 stringBuffer.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
65             }
66             return stringBuffer.toString();
67         } catch (NoSuchAlgorithmException e) {
68             logger.warn("NoSuchAlgorithmException error when calculating MD5 hash");
69         }
70         return "";
71     }
72
73     // Method can be used a few ways. processAuth(null, string,string, false) to return the digest on demand, and
74     // processAuth(challString, string,string, true) to auto send new packet
75     // First run it should not have authenticate as null
76     // nonce is reused if authenticate is null so the NC needs to increment to allow this//
77     public void processAuth(String authenticate, String httpMethod, String requestURI, boolean reSend) {
78         if (authenticate.contains("Basic realm=\"")) {
79             if (ipCameraHandler.useDigestAuth) {
80                 // Possible downgrade authenticate attack avoided.
81                 return;
82             }
83             logger.debug("Setting up the camera to use Basic Auth and resending last request with correct auth.");
84             if (ipCameraHandler.setBasicAuth(true)) {
85                 ipCameraHandler.sendHttpRequest(httpMethod, requestURI, null);
86             }
87             return;
88         }
89
90         /////// Fresh Digest Authenticate method follows as Basic is already handled and returned ////////
91         realm = Helper.searchString(authenticate, "realm=\"");
92         if (realm.isEmpty()) {
93             logger.warn("Could not find a valid WWW-Authenticate response in :{}", authenticate);
94             return;
95         }
96         nonce = Helper.searchString(authenticate, "nonce=\"");
97         opaque = Helper.searchString(authenticate, "opaque=\"");
98         qop = Helper.searchString(authenticate, "qop=\"");
99
100         if (!qop.isEmpty() && !realm.isEmpty()) {
101             ipCameraHandler.useDigestAuth = true;
102         } else {
103             logger.warn(
104                     "!!!! Something is wrong with the reply back from the camera. WWW-Authenticate header: qop:{}, realm:{}",
105                     qop, realm);
106         }
107
108         String stale = Helper.searchString(authenticate, "stale=\"");
109         if (stale.equalsIgnoreCase("true")) {
110             logger.debug("Camera reported stale=true which normally means the NONCE has expired.");
111         }
112
113         if (password.isEmpty()) {
114             ipCameraHandler.cameraConfigError("Camera gave a 401 reply: You need to provide a password.");
115             return;
116         }
117         // create the MD5 hashes
118         String ha1 = username + ":" + realm + ":" + password;
119         ha1 = calcMD5Hash(ha1);
120         Random random = new Random();
121         String cnonce = Integer.toHexString(random.nextInt());
122         ncCounter = (ncCounter > 125) ? 1 : ++ncCounter;
123         String nc = String.format("%08X", ncCounter); // 8 digit hex number
124         String ha2 = httpMethod + ":" + requestURI;
125         ha2 = calcMD5Hash(ha2);
126
127         String response = ha1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2;
128         response = calcMD5Hash(response);
129
130         String digestString = "username=\"" + username + "\", realm=\"" + realm + "\", nonce=\"" + nonce + "\", uri=\""
131                 + requestURI + "\", cnonce=\"" + cnonce + "\", nc=" + nc + ", qop=\"" + qop + "\", response=\""
132                 + response + "\", opaque=\"" + opaque + "\"";
133
134         if (reSend) {
135             ipCameraHandler.sendHttpRequest(httpMethod, requestURI, digestString);
136             return;
137         }
138     }
139
140     @Override
141     public void channelRead(@Nullable ChannelHandlerContext ctx, @Nullable Object msg) throws Exception {
142         if (msg == null || ctx == null) {
143             return;
144         }
145         boolean closeConnection = true;
146         String authenticate = "";
147         if (msg instanceof HttpResponse) {
148             HttpResponse response = (HttpResponse) msg;
149             if (response.status().code() == 401) {
150                 if (!response.headers().isEmpty()) {
151                     for (CharSequence name : response.headers().names()) {
152                         for (CharSequence value : response.headers().getAll(name)) {
153                             if (name.toString().equalsIgnoreCase("WWW-Authenticate")) {
154                                 authenticate = value.toString();
155                             }
156                             if (name.toString().equalsIgnoreCase("Connection")
157                                     && value.toString().contains("keep-alive")) {
158                                 // closeConnection = false;
159                                 // trial this for a while to see if it solves too many bytes with digest turned on.
160                                 closeConnection = true;
161                             }
162                         }
163                     }
164                     if (!authenticate.isEmpty()) {
165                         processAuth(authenticate, httpMethod, httpUrl, true);
166                     } else {
167                         ipCameraHandler.cameraConfigError(
168                                 "Camera gave no WWW-Authenticate: Your login details must be wrong.");
169                     }
170                     if (closeConnection) {
171                         ctx.close();// needs to be here
172                     }
173                 }
174             } else if (response.status().code() != 200) {
175                 logger.debug("Camera at IP:{} gave a reply with a response code of :{}",
176                         ipCameraHandler.cameraConfig.getIp(), response.status().code());
177             }
178         }
179         // Pass the Message back to the pipeline for the next handler to process//
180         super.channelRead(ctx, msg);
181     }
182
183     @Override
184     public void handlerAdded(@Nullable ChannelHandlerContext ctx) {
185     }
186
187     @Override
188     public void handlerRemoved(@Nullable ChannelHandlerContext ctx) {
189     }
190 }