OPCTest.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. package at.acdp.opcur;
  2. /*
  3. * ======================================================================== Copyright (c) 2005-2015
  4. * The OPC Foundation, Inc. All rights reserved.
  5. *
  6. * OPC Foundation MIT License 1.00
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
  9. * associated documentation files (the "Software"), to deal in the Software without restriction,
  10. * including without limitation the rights to use, copy, modify, merge, publish, distribute,
  11. * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in all copies or
  15. * substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  16. * KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  17. * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  18. * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  19. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. * IN THE SOFTWARE.
  21. *
  22. * The complete license agreement can be found here: http://opcfoundation.org/License/MIT/1.00/
  23. * ======================================================================
  24. */
  25. import java.io.ByteArrayOutputStream;
  26. import java.io.IOException;
  27. import java.security.KeyPairGenerator;
  28. import java.security.SecureRandom;
  29. import java.security.Security;
  30. import java.security.interfaces.RSAPrivateKey;
  31. import java.util.Random;
  32. import java.util.UUID;
  33. import org.apache.http.conn.ssl.SSLSocketFactory;
  34. import org.opcfoundation.ua.application.Application;
  35. import org.opcfoundation.ua.application.Server;
  36. import org.opcfoundation.ua.builtintypes.ByteString;
  37. import org.opcfoundation.ua.builtintypes.DataValue;
  38. import org.opcfoundation.ua.builtintypes.LocalizedText;
  39. import org.opcfoundation.ua.builtintypes.NodeId;
  40. import org.opcfoundation.ua.builtintypes.QualifiedName;
  41. import org.opcfoundation.ua.builtintypes.StatusCode;
  42. import org.opcfoundation.ua.builtintypes.UnsignedInteger;
  43. import org.opcfoundation.ua.builtintypes.Variant;
  44. import org.opcfoundation.ua.common.ServiceFaultException;
  45. import org.opcfoundation.ua.common.ServiceResultException;
  46. import org.opcfoundation.ua.core.ActivateSessionRequest;
  47. import org.opcfoundation.ua.core.ActivateSessionResponse;
  48. import org.opcfoundation.ua.core.AddNodesRequest;
  49. import org.opcfoundation.ua.core.AddNodesResponse;
  50. import org.opcfoundation.ua.core.AddReferencesRequest;
  51. import org.opcfoundation.ua.core.AddReferencesResponse;
  52. import org.opcfoundation.ua.core.AttributeServiceSetHandler;
  53. import org.opcfoundation.ua.core.Attributes;
  54. import org.opcfoundation.ua.core.BrowseNextRequest;
  55. import org.opcfoundation.ua.core.BrowseNextResponse;
  56. import org.opcfoundation.ua.core.BrowseRequest;
  57. import org.opcfoundation.ua.core.BrowseResponse;
  58. import org.opcfoundation.ua.core.BrowseResult;
  59. import org.opcfoundation.ua.core.CancelRequest;
  60. import org.opcfoundation.ua.core.CancelResponse;
  61. import org.opcfoundation.ua.core.CloseSessionRequest;
  62. import org.opcfoundation.ua.core.CloseSessionResponse;
  63. import org.opcfoundation.ua.core.CreateSessionRequest;
  64. import org.opcfoundation.ua.core.CreateSessionResponse;
  65. import org.opcfoundation.ua.core.DeleteNodesRequest;
  66. import org.opcfoundation.ua.core.DeleteNodesResponse;
  67. import org.opcfoundation.ua.core.DeleteReferencesRequest;
  68. import org.opcfoundation.ua.core.DeleteReferencesResponse;
  69. import org.opcfoundation.ua.core.EndpointConfiguration;
  70. import org.opcfoundation.ua.core.HistoryReadRequest;
  71. import org.opcfoundation.ua.core.HistoryReadResponse;
  72. import org.opcfoundation.ua.core.HistoryUpdateRequest;
  73. import org.opcfoundation.ua.core.HistoryUpdateResponse;
  74. import org.opcfoundation.ua.core.Identifiers;
  75. import org.opcfoundation.ua.core.NodeManagementServiceSetHandler;
  76. import org.opcfoundation.ua.core.QueryFirstRequest;
  77. import org.opcfoundation.ua.core.QueryFirstResponse;
  78. import org.opcfoundation.ua.core.QueryNextRequest;
  79. import org.opcfoundation.ua.core.QueryNextResponse;
  80. import org.opcfoundation.ua.core.ReadRequest;
  81. import org.opcfoundation.ua.core.ReadResponse;
  82. import org.opcfoundation.ua.core.ReadValueId;
  83. import org.opcfoundation.ua.core.RegisterNodesRequest;
  84. import org.opcfoundation.ua.core.RegisterNodesResponse;
  85. import org.opcfoundation.ua.core.ServiceFault;
  86. import org.opcfoundation.ua.core.SessionServiceSetHandler;
  87. import org.opcfoundation.ua.core.SignatureData;
  88. import org.opcfoundation.ua.core.StatusCodes;
  89. import org.opcfoundation.ua.core.TranslateBrowsePathsToNodeIdsRequest;
  90. import org.opcfoundation.ua.core.TranslateBrowsePathsToNodeIdsResponse;
  91. import org.opcfoundation.ua.core.UnregisterNodesRequest;
  92. import org.opcfoundation.ua.core.UnregisterNodesResponse;
  93. import org.opcfoundation.ua.core.UserTokenPolicy;
  94. import org.opcfoundation.ua.core.WriteRequest;
  95. import org.opcfoundation.ua.core.WriteResponse;
  96. import org.opcfoundation.ua.transport.endpoint.EndpointServiceRequest;
  97. import org.opcfoundation.ua.transport.security.CertificateValidator;
  98. import org.opcfoundation.ua.transport.security.HttpsSecurityPolicy;
  99. import org.opcfoundation.ua.transport.security.KeyPair;
  100. import org.opcfoundation.ua.transport.security.SecurityAlgorithm;
  101. import org.opcfoundation.ua.transport.security.SecurityMode;
  102. import org.opcfoundation.ua.transport.security.SecurityPolicy;
  103. import org.opcfoundation.ua.utils.CryptoUtil;
  104. import org.opcfoundation.ua.utils.EndpointUtil;
  105. /**
  106. * Simple Server example. This server responds to stack test and endpoint discover service requests.
  107. *
  108. */
  109. public class OPCTest {
  110. static class MyAttributeServiceHandler implements AttributeServiceSetHandler {
  111. @Override
  112. public void onHistoryRead(EndpointServiceRequest<HistoryReadRequest, HistoryReadResponse> req)
  113. throws ServiceFaultException {
  114. }
  115. @Override
  116. public void onHistoryUpdate(EndpointServiceRequest<HistoryUpdateRequest, HistoryUpdateResponse> req)
  117. throws ServiceFaultException {
  118. }
  119. @Override
  120. public void onRead(EndpointServiceRequest<ReadRequest, ReadResponse> req) throws ServiceFaultException {
  121. ReadRequest request = req.getRequest();
  122. ReadValueId[] nodesToRead = request.getNodesToRead();
  123. DataValue[] results = new DataValue[nodesToRead.length];
  124. for (int i = 0; i < nodesToRead.length; i++) {
  125. if (Identifiers.RootFolder.equals(nodesToRead[i].getNodeId())) {
  126. if (Attributes.BrowseName.equals(nodesToRead[i].getAttributeId())) {
  127. results[i] = new DataValue(new Variant(new QualifiedName("Root")));
  128. } else if (Attributes.DisplayName.equals(nodesToRead[i].getAttributeId())) {
  129. results[i] = new DataValue(new Variant(new LocalizedText("Root", LocalizedText.NO_LOCALE)));
  130. } else {
  131. results[i] = new DataValue(new StatusCode(StatusCodes.Bad_AttributeIdInvalid));
  132. }
  133. } else {
  134. results[i] = new DataValue(new StatusCode(StatusCodes.Bad_NodeIdUnknown));
  135. }
  136. }
  137. ReadResponse response = new ReadResponse(null, results, null);
  138. req.sendResponse(response);
  139. }
  140. @Override
  141. public void onWrite(EndpointServiceRequest<WriteRequest, WriteResponse> req) throws ServiceFaultException {
  142. }
  143. };
  144. static class MyNodeManagementServiceHandler implements NodeManagementServiceSetHandler {
  145. @Override
  146. public void onAddNodes(EndpointServiceRequest<AddNodesRequest, AddNodesResponse> req) throws ServiceFaultException {
  147. }
  148. @Override
  149. public void onAddReferences(EndpointServiceRequest<AddReferencesRequest, AddReferencesResponse> req)
  150. throws ServiceFaultException {
  151. }
  152. @Override
  153. public void onBrowse(EndpointServiceRequest<BrowseRequest, BrowseResponse> req) throws ServiceFaultException {
  154. BrowseRequest request = req.getRequest();
  155. BrowseResult[] Results = new BrowseResult[request.getNodesToBrowse().length];
  156. for (int i = 0; i < request.getNodesToBrowse().length; i++) {
  157. StatusCode statusCode;
  158. if (Identifiers.RootFolder.equals(request.getNodesToBrowse()[i].getNodeId())) {
  159. statusCode = StatusCode.GOOD;
  160. } else {
  161. statusCode = new StatusCode(StatusCodes.Bad_NodeIdUnknown);
  162. }
  163. Results[i] = new BrowseResult(statusCode, null, null);
  164. }
  165. BrowseResponse response = new BrowseResponse(null, Results, null);
  166. req.sendResponse(response);
  167. }
  168. @Override
  169. public void onBrowseNext(EndpointServiceRequest<BrowseNextRequest, BrowseNextResponse> req)
  170. throws ServiceFaultException {
  171. }
  172. @Override
  173. public void onDeleteNodes(EndpointServiceRequest<DeleteNodesRequest, DeleteNodesResponse> req)
  174. throws ServiceFaultException {
  175. }
  176. @Override
  177. public void onDeleteReferences(EndpointServiceRequest<DeleteReferencesRequest, DeleteReferencesResponse> req)
  178. throws ServiceFaultException {
  179. }
  180. @Override
  181. public void onQueryFirst(EndpointServiceRequest<QueryFirstRequest, QueryFirstResponse> req)
  182. throws ServiceFaultException {
  183. }
  184. @Override
  185. public void onQueryNext(EndpointServiceRequest<QueryNextRequest, QueryNextResponse> req)
  186. throws ServiceFaultException {
  187. }
  188. @Override
  189. public void onRegisterNodes(EndpointServiceRequest<RegisterNodesRequest, RegisterNodesResponse> req)
  190. throws ServiceFaultException {
  191. }
  192. @Override
  193. public void onTranslateBrowsePathsToNodeIds(
  194. EndpointServiceRequest<TranslateBrowsePathsToNodeIdsRequest, TranslateBrowsePathsToNodeIdsResponse> req)
  195. throws ServiceFaultException {
  196. }
  197. @Override
  198. public void onUnregisterNodes(EndpointServiceRequest<UnregisterNodesRequest, UnregisterNodesResponse> req)
  199. throws ServiceFaultException {
  200. }
  201. }
  202. static class MyServerExample extends Server implements SessionServiceSetHandler {
  203. public MyServerExample(Application application) throws Exception {
  204. super(application);
  205. addServiceHandler(this);
  206. // Add Client Application Instance Certificate validator - Accept them all (for now)
  207. application.getOpctcpSettings().setCertificateValidator(CertificateValidator.ALLOW_ALL);
  208. application.getHttpsSettings().setCertificateValidator(CertificateValidator.ALLOW_ALL);
  209. // The HTTPS SecurityPolicies are defined separate from the endpoint securities
  210. application.getHttpsSettings().setHttpsSecurityPolicies(HttpsSecurityPolicy.ALL);
  211. // Peer verifier
  212. application.getHttpsSettings().setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  213. // Load Servers's Application Instance Certificate...
  214. KeyPair myServerApplicationInstanceCertificate = ExampleKeys.getCert("ServerExample1");
  215. application.addApplicationInstanceCertificate(myServerApplicationInstanceCertificate);
  216. // ...and HTTPS certificate
  217. KeyPair myHttpsCertificate = ExampleKeys.getHttpsCert("ServerExample1");
  218. application.getHttpsSettings().setKeyPair(myHttpsCertificate);
  219. // Add User Token Policies
  220. addUserTokenPolicy(UserTokenPolicy.ANONYMOUS);
  221. addUserTokenPolicy(UserTokenPolicy.SECURE_USERNAME_PASSWORD);
  222. // Create an endpoint for each network interface
  223. String hostname = EndpointUtil.getHostname();
  224. String bindAddress, endpointAddress;
  225. for (String addr : EndpointUtil.getInetAddressNames()) {
  226. bindAddress = "https://" + addr + ":8443/UAExample";
  227. endpointAddress = "https://" + hostname + ":8443/UAExample";
  228. System.out.println(endpointAddress + " bound at " + bindAddress);
  229. // The HTTPS ports are using NONE OPC security
  230. bind(bindAddress, endpointAddress, SecurityMode.NONE);
  231. bindAddress = "opc.tcp://" + addr + ":8666/UAExample";
  232. endpointAddress = "opc.tcp://" + hostname + ":8666/UAExample";
  233. System.out.println(endpointAddress + " bound at " + bindAddress);
  234. bind(bindAddress, endpointAddress, SecurityMode.ALL);
  235. }
  236. //////////////////////////////////////
  237. }
  238. @Override
  239. public void onActivateSession(EndpointServiceRequest<ActivateSessionRequest, ActivateSessionResponse> msgExchange)
  240. throws ServiceFaultException {
  241. ActivateSessionResponse res = new ActivateSessionResponse();
  242. res.setServerNonce(CryptoUtil.createNonce(32));
  243. res.setResults(new StatusCode[] {StatusCode.GOOD});
  244. msgExchange.sendResponse(res);
  245. }
  246. @Override
  247. public void onCancel(EndpointServiceRequest<CancelRequest, CancelResponse> msgExchange)
  248. throws ServiceFaultException {
  249. }
  250. @Override
  251. public void onCloseSession(EndpointServiceRequest<CloseSessionRequest, CloseSessionResponse> msgExchange)
  252. throws ServiceFaultException {
  253. CloseSessionResponse res = new CloseSessionResponse();
  254. msgExchange.sendResponse(res);
  255. }
  256. @Override
  257. public void onCreateSession(EndpointServiceRequest<CreateSessionRequest, CreateSessionResponse> msgExchange)
  258. throws ServiceFaultException {
  259. CreateSessionRequest req = msgExchange.getRequest();
  260. CreateSessionResponse res = new CreateSessionResponse();
  261. byte[] token = new byte[32];
  262. byte[] nonce = new byte[32];
  263. Random r = new Random();
  264. r.nextBytes(nonce);
  265. r.nextBytes(token);
  266. res.setAuthenticationToken(new NodeId(0, token));
  267. EndpointConfiguration endpointConfiguration = EndpointConfiguration.defaults();
  268. res.setMaxRequestMessageSize(UnsignedInteger
  269. .valueOf(Math.max(endpointConfiguration.getMaxMessageSize(), req.getMaxResponseMessageSize().longValue())));
  270. res.setRevisedSessionTimeout(Math.max(req.getRequestedSessionTimeout(), 60 * 1000));
  271. KeyPair cert = getApplication().getApplicationInstanceCertificates()[0];
  272. res.setServerCertificate(ByteString.valueOf(cert.getCertificate().getEncoded()));
  273. res.setServerEndpoints(this.getEndpointDescriptions());
  274. res.setServerNonce(ByteString.valueOf(nonce));
  275. ByteString clientCertificate = req.getClientCertificate();
  276. ByteString clientNonce = req.getClientNonce();
  277. SecurityPolicy securityPolicy = msgExchange.getChannel().getSecurityPolicy();
  278. res.setServerSignature(
  279. getServerSignature(clientCertificate, clientNonce, securityPolicy, cert.getPrivateKey().getPrivateKey()));
  280. res.setServerSoftwareCertificates(getApplication().getSoftwareCertificates());
  281. res.setSessionId(new NodeId(0, "Session-" + UUID.randomUUID()));
  282. msgExchange.sendResponse(res);
  283. }
  284. private SignatureData getServerSignature(ByteString clientCertificate, ByteString clientNonce,
  285. SecurityPolicy securityPolicy, final RSAPrivateKey privateKey) throws ServiceFaultException {
  286. if (clientCertificate != null) {
  287. ByteArrayOutputStream s = new ByteArrayOutputStream();
  288. try {
  289. s.write(clientCertificate.getValue());
  290. } catch (IOException e) {
  291. throw new ServiceFaultException(ServiceFault.createServiceFault(StatusCodes.Bad_SecurityChecksFailed));
  292. } catch (Exception e) {
  293. throw new ServiceFaultException(ServiceFault.createServiceFault(StatusCodes.Bad_NonceInvalid));
  294. }
  295. try {
  296. s.write(clientNonce.getValue());
  297. } catch (IOException e) {
  298. throw new ServiceFaultException(ServiceFault.createServiceFault(StatusCodes.Bad_NonceInvalid));
  299. } catch (Exception e) {
  300. throw new ServiceFaultException(ServiceFault.createServiceFault(StatusCodes.Bad_NonceInvalid));
  301. }
  302. try {
  303. SecurityAlgorithm algorithm = securityPolicy.getAsymmetricSignatureAlgorithm();
  304. return new SignatureData(algorithm.getUri(),
  305. ByteString.valueOf(CryptoUtil.getCryptoProvider().signAsymm(privateKey, algorithm, s.toByteArray())));
  306. } catch (ServiceResultException e) {
  307. throw new ServiceFaultException(e);
  308. }
  309. }
  310. return null;
  311. }
  312. }
  313. public static void main(String[] args) throws Exception {
  314. CryptoUtil.setSecurityProviderName("SunJCE");
  315. ////////////// SERVER //////////////
  316. // Create UA Server Application
  317. // Create UA Service Server
  318. Application myServerApplication = new Application();
  319. MyServerExample myServer = new MyServerExample(myServerApplication);
  320. myServer.addServiceHandler(new MyNodeManagementServiceHandler());
  321. myServer.addServiceHandler(new MyAttributeServiceHandler());
  322. //////////////////////////////////////
  323. // Press enter to shutdown
  324. System.out.println("Press enter to shutdown");
  325. System.in.read();
  326. //////////////////////////////////////
  327. ///////////// SHUTDOWN /////////////
  328. // Close the server by unbinding all endpoints
  329. myServer.getApplication().close();
  330. //////////////////////////////////////
  331. }
  332. }