OPCTest.java 18 KB

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