OcppWebsocketService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. using EVCB_OCPP.WSServer.Helper;
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.Extensions.Logging;
  7. using OCPPServer.Protocol;
  8. using System.Net.WebSockets;
  9. using System.Security.Cryptography.X509Certificates;
  10. using System.Text;
  11. namespace EVCB_OCPP.WSServer.Service.WsService;
  12. public static partial class AppExtention
  13. {
  14. public static void AddOcppWsServer(this IServiceCollection services)
  15. {
  16. services.AddTransient<CertificateService>();
  17. services.AddTransient<WsClientData>();
  18. services.AddSingleton<OcppWebsocketService>();
  19. }
  20. public static void UseOcppWsService(this WebApplication webApplication)
  21. {
  22. webApplication.UseWebSockets(new WebSocketOptions()
  23. {
  24. KeepAliveInterval = TimeSpan.FromSeconds(10)
  25. });
  26. webApplication.Use(async (context, next) =>
  27. {
  28. if (!context.WebSockets.IsWebSocketRequest)
  29. {
  30. await next(context);
  31. return;
  32. }
  33. var servcie = context.RequestServices.GetService<OcppWebsocketService>();
  34. await servcie.AcceptWebSocket(context);
  35. return;
  36. });
  37. }
  38. }
  39. public class OcppWebsocketService : WebsocketService<WsClientData>
  40. {
  41. public static List<string> protocals = new List<string>() { "", "ocpp1.6", "ocpp2.0.1" };
  42. private readonly IConfiguration configuration;
  43. private readonly IMainDbService mainDbService;
  44. private readonly CertificateService certificateService;
  45. private readonly ILogger<OcppWebsocketService> logger;
  46. private readonly QueueSemaphore handshakeSemaphore;
  47. public OcppWebsocketService(
  48. IConfiguration configuration,
  49. IServiceProvider serviceProvider,
  50. IMainDbService mainDbService,
  51. CertificateService certificateService,
  52. ILogger<OcppWebsocketService> logger
  53. ) : base(serviceProvider)
  54. {
  55. this.configuration = configuration;
  56. this.mainDbService = mainDbService;
  57. this.certificateService = certificateService;
  58. this.logger = logger;
  59. handshakeSemaphore = new QueueSemaphore(5);
  60. }
  61. internal override async ValueTask<string> ValidateSupportedPortocol(HttpContext context)
  62. {
  63. logger.LogInformation("{id} {function}:{Path}/{SubProtocol}", context.TraceIdentifier, nameof(ValidateSupportedPortocol), context.Request.Path, context.WebSockets.WebSocketRequestedProtocols);
  64. var protocol = GetSupportedPortocol(context.WebSockets.WebSocketRequestedProtocols, protocals);
  65. if (string.IsNullOrEmpty(protocol))
  66. {
  67. logger.LogInformation("{id} {function}:{Path} Protocol Not Supported, Disconnecting", context.TraceIdentifier, nameof(ValidateSupportedPortocol), context.Request.Path);
  68. using WebSocket toRejectwebSocket = await context.WebSockets.AcceptWebSocketAsync();
  69. await toRejectwebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, default);
  70. return string.Empty;
  71. }
  72. return protocol;
  73. }
  74. internal override async ValueTask<bool> ValidateHandshake(HttpContext context, WsClientData session)
  75. {
  76. try
  77. {
  78. using var canValidate = await handshakeSemaphore.GetToken();
  79. var result = await ValidateHandshakeUnsafe(context, session);
  80. return result;
  81. }
  82. catch (Exception ex)
  83. {
  84. logger.LogError(ex.Message);
  85. logger.LogError(ex.StackTrace);
  86. }
  87. return false;
  88. }
  89. internal async ValueTask<bool> ValidateHandshakeUnsafe(HttpContext context, WsClientData session)
  90. {
  91. if (context.RequestAborted.IsCancellationRequested) return false;
  92. string authHeader = context?.Request?.Headers?.Authorization;
  93. session.ISOCPP20 = context.WebSockets.WebSocketRequestedProtocols.Any(x => x.ToLower() == "ocpp2.0");
  94. int securityProfile = 0;
  95. string authorizationKey = string.Empty;
  96. if (string.IsNullOrEmpty(session.Path))
  97. {
  98. //logger.Log();
  99. logger.LogWarning("===========================================");
  100. logger.LogWarning("{id} session.Path EMPTY", context.TraceIdentifier);
  101. logger.LogWarning("===========================================");
  102. }
  103. string[] words = session.Path.ToString().Split('/');
  104. session.ChargeBoxId = words.Last();
  105. logger.LogDebug("{id} {0}:{1}", context.TraceIdentifier, session.ChargeBoxId, session.UriScheme);
  106. foreach (var denyModel in GlobalConfig.DenyModelNames)
  107. {
  108. if (string.IsNullOrEmpty(denyModel))
  109. {
  110. continue;
  111. }
  112. if (session.ChargeBoxId.StartsWith(denyModel))
  113. {
  114. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  115. logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
  116. return false;
  117. }
  118. }
  119. if (configuration["MaintainMode"] == "1")
  120. {
  121. session.ChargeBoxId = session.ChargeBoxId + "_2";
  122. }
  123. logger.LogInformation("{id} ValidateHandshake: {0}", context.TraceIdentifier, session.Path);
  124. bool isExistedSN = false;
  125. bool authorizated = false;
  126. var info = await mainDbService.GetMachineIdAndCustomerInfo(session.ChargeBoxId, context.RequestAborted);
  127. if (context.RequestAborted.IsCancellationRequested) return false;
  128. //var machine = db.Machine.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).AsNoTracking().FirstOrDefault();
  129. //session.CustomerName = machine == null ? "Unknown" : db.Customer.Where(x => x.Id == machine.CustomerId).Select(x => x.Name).FirstOrDefault();
  130. //session.CustomerId = machine == null ? Guid.Empty : machine.CustomerId;
  131. //session.MachineId = machine == null ? String.Empty : machine.Id;
  132. //isExistedSN = machine == null ? false : true;
  133. session.CustomerName = info.CustomerName;
  134. session.CustomerId = info.CustomerId;
  135. session.MachineId = info.MachineId;
  136. isExistedSN = !string.IsNullOrEmpty(info.MachineId);// machine == null ? false : true;
  137. if (!isExistedSN)
  138. {
  139. context.Response.StatusCode = StatusCodes.Status404NotFound;
  140. logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
  141. return false;
  142. }
  143. //var configVaule = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.SecurityProfile)
  144. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  145. var configVaule = await mainDbService.GetMachineSecurityProfile(session.ChargeBoxId, context.RequestAborted);
  146. if (context.RequestAborted.IsCancellationRequested) return false;
  147. int.TryParse(configVaule, out securityProfile);
  148. if (session.ISOCPP20)
  149. {
  150. // 1.6 server only support change server function
  151. securityProfile = 0;
  152. }
  153. if (securityProfile == 3 )
  154. {
  155. if (session.UriScheme == "ws")
  156. {
  157. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  158. logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
  159. return false;
  160. }
  161. X509Certificate2 clientCertificate = null;
  162. if (clientCertificate is null &&
  163. context.Connection.ClientCertificate is not null)
  164. {
  165. clientCertificate = context.Connection.ClientCertificate;
  166. }
  167. if (clientCertificate is null &&
  168. context.Request.Headers.TryGetValue("X-ARR-ClientCert", out var clientCertString))
  169. {
  170. byte[] bytes = Convert.FromBase64String(clientCertString);
  171. clientCertificate = new X509Certificate2(bytes);
  172. }
  173. if (clientCertificate is null)
  174. {
  175. clientCertificate = await context.Connection.GetClientCertificateAsync();
  176. }
  177. if (clientCertificate == null)
  178. {
  179. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  180. logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
  181. return false;
  182. }
  183. int checkResult = await certificateService.CheckClientCertificate(session.ChargeBoxId, clientCertificate);
  184. if (checkResult == -1)
  185. {
  186. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  187. logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
  188. return false;
  189. }
  190. session.IsSignedByCPO = checkResult == 0;
  191. return true;
  192. }
  193. if (securityProfile == 1 || securityProfile == 2)
  194. {
  195. if (securityProfile == 2 && session.UriScheme == "ws")
  196. {
  197. authorizated = false;
  198. }
  199. //if (session.Items.ContainsKey("Authorization") || session.Items.ContainsKey("authorization"))
  200. if (!string.IsNullOrEmpty(authHeader))
  201. {
  202. //authorizationKey = db.MachineConfigurations.Where(x => x.ChargeBoxId == session.ChargeBoxId && x.ConfigureName == StandardConfiguration.AuthorizationKey)
  203. // .Select(x => x.ConfigureSetting).FirstOrDefault();
  204. authorizationKey = await mainDbService.GetMachineAuthorizationKey(session.ChargeBoxId, context.RequestAborted);
  205. if (context.RequestAborted.IsCancellationRequested) return false;
  206. if (session.ISOCPP20)
  207. {
  208. // 1.6 server only support change server function
  209. securityProfile = 0;
  210. }
  211. logger.LogInformation("{id} ***********Authorization ", context.TraceIdentifier);
  212. if (!string.IsNullOrEmpty(authorizationKey))
  213. {
  214. //string base64Encoded = session.Items.ContainsKey("Authorization") ? session.Items["Authorization"].ToString().Replace("Basic ", "") : session.Items["authorization"].ToString().Replace("Basic ", "");
  215. string base64Encoded = authHeader.Replace("Basic ", "");
  216. byte[] data = Convert.FromBase64String(base64Encoded);
  217. string[] base64Decoded = Encoding.ASCII.GetString(data).Split(':');
  218. logger.LogInformation("{id} ***********Authorization " + Encoding.ASCII.GetString(data), context.TraceIdentifier);
  219. if (base64Decoded.Count() == 2 && base64Decoded[0] == session.ChargeBoxId && base64Decoded[1] == authorizationKey)
  220. {
  221. authorizated = true;
  222. }
  223. }
  224. }
  225. else
  226. {
  227. authorizated = true;
  228. }
  229. if (!authorizated)
  230. {
  231. context.Response.StatusCode = StatusCodes.Status401Unauthorized;
  232. logger.LogTrace("{id} {func} {Statuscode}", context.TraceIdentifier, nameof(ValidateHandshake), context.Response.StatusCode);
  233. return false;
  234. }
  235. }
  236. logger.LogInformation("{id} ValidateHandshake PASS: {0}", context.TraceIdentifier, session.Path);
  237. return true;
  238. }
  239. private static string GetSupportedPortocol(IList<string> clientProtocols, IList<string> supportedProtocols)
  240. {
  241. int supportedProtocolIndex = supportedProtocols.Count - 1;
  242. for (; supportedProtocolIndex >= 0; supportedProtocolIndex--)
  243. {
  244. var testProtocol = supportedProtocols[supportedProtocolIndex];
  245. if (clientProtocols.Contains(testProtocol))
  246. {
  247. return testProtocol;
  248. }
  249. }
  250. return string.Empty;
  251. }
  252. }