OPCTestPlain.java 14 KB

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