using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Web.Http; using Xylem.Common.CommonCore.Configuration; using Xylem.Common.CommonCore.Exceptions; using Xylem.Common.CommonCore.Exceptions.Db; using Xylem.Common.CommonCore.Exceptions.WaterMeter; using Xylem.Common.CommonCore.Exceptions.Web; using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisCore; using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisFile; using Xylem.Common.Hardware.WaterMeter.Genesis.GenesisPwd; using Xylem.Common.Logic.ServiceCore; using Xylem.Common.Logic.SoftwareAccessHelper; namespace Xylem.Common.Service.MeterProcessState.Controllers { [RoutePrefix("api/Password")] public class PasswordController : ApiController { public static class GlobalConfig { public static Lazy connectionString = new Lazy(() => System.Configuration.ConfigurationManager.ConnectionStrings["default"].ConnectionString ); } [Route("SetPassword"), HttpGet] public async Task SetPassword(String PcbId, String password, Boolean keepOldPw = false) { try { if (keepOldPw == true) { throw new ApplicationException("Not Suppoted keepOldPw"); } using (var dataAccess = new SqlDataAccess(GlobalConfig.connectionString.Value)) { StringBuilder sb = new StringBuilder(); sb.AppendLine($"update auftrag.dbo.Genesis_PcbPassword set [password] ='{password}' where PcbId='{PcbId}'"); var dt = dataAccess.ExecuteQuery(sb.ToString()); } return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() => { return "store"; })); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex); } } public class PwProcessorId { public PwProcessorId(String password, UInt64? processorId = null) { Password = password; ProcessorId = processorId; } public PwProcessorId(String password) { Password = password; } public PwProcessorId() { } public UInt64? ProcessorId; public String Password; } public String BuildSkeletonKey(UInt64 processorUid) { return $"{(UInt16)((processorUid >> 48) ^ (processorUid >> 32)):X4}" + $"{(UInt32)((processorUid >> 16) ^ processorUid):X8}"; } [Route("GetPwProcessorId"), HttpGet] public async Task GetPasswordLU(String PcbId) { return await Task.Run(async () => { using (var dataAccess = new SqlDataAccess(GlobalConfig.connectionString.Value)) { //try //{ // var dt = dataAccess.ExecuteQuery($"SELECT top 10 [DS_ID] ,[ID_PCB] ,[ID_TEST] ,[JSON] FROM [MyOraDB]..[DELTACHEF].[GENESIS_PCBFUNCTIONALTEST_PD] where [ID_PCB] = '{PcbId}' order by ID_TEST desc"); // foreach (var item in dt.Select()) // { // var jsonString = item["JSON"].ToString(); // var o = JsonConvert.DeserializeObject(jsonString); // var logon = from p in o["TestStepResults"]["$values"] select p; // var logonnote = logon.Where(a => a["TestStepName"].ToString() == "Genesis IrDA Logon").ToList(); // var list = logonnote.Children().Where(a => ((JProperty)a).Name == "TestValue").First().Values().First(); // var pwString = list.ToString(); // var bList = new List(); // var pidNode = o.GetValue("TestBoardSerialNr").ToString(); // pidNode = pidNode.Replace("-", "").Substring(8,16); // var pId = Convert.ToUInt64(pidNode, 16); // var checkPW = BuildSkeletonKey(pId); // int NumberChars = pwString.Length; // byte[] bytes = new byte[NumberChars / 2]; // for (int i = 0; i < NumberChars; i += 2) // { // bytes[i / 2] = Convert.ToByte(pwString.Substring(i, 2), 16); // } // return new PwProcessorId(ASCIIEncoding.ASCII.GetString(bytes)); // } //} //catch (Exception e) //{ //} try { var searchKey = "Flash TestFirmware"; var dt = dataAccess.ExecuteQuery($"SELECT top 1 [DS_ID] ,[ID_PCB] ,[ID_TEST] ,[JSON] FROM [MyOraDB]..[DELTACHEF].[GENESIS_PCBMETROLOGYTEST_PD] where [ID_PCB] = '{PcbId}' order by ID_TEST desc"); if (!dt.Select().Any()) { dt = dataAccess.ExecuteQuery($"SELECT top 1 [DS_ID] ,[ID_PCB] ,[ID_TEST] ,[JSON] FROM [MyOraDB]..[DELTACHEF].[GENESIS_PCBRADIOTEST_PD] where [ID_PCB] = '{PcbId}' order by ID_TEST desc"); searchKey = "Flash Firmware"; } foreach (var item in dt.Select()) { var jsonString = item["JSON"].ToString(); var o = JsonConvert.DeserializeObject(jsonString); try { var pwString = o["JsonObject"][searchKey].ToString(); //FE081F0 E5250E5D084FA024 00 04 80 00 70 03 48 9E //0x 0413F059069BEB24 //pwString = "FE081F0 F2 30 F0 59 03 66 10 24 00 04 80 00 70 03 48 9A"; //pwString = "FE081F0 16 31 F0 59 06 9B EB 24 00 04 80 00 70 03 48 9A"; //pwString = "FE081F0 B3 F3 0D 5C 05 C3 9B 24 00 04 80 00 70 03 48 9E"; //pwString = "FE081F0 C3 30 F0 59 03 66 10 24 00 04 80 00 70 03 48 9A"; //E79E9F08AFBE var pId = Convert.ToUInt64(pwString.Replace(" ", "").Substring(7, 16), 16); var s = BuildSkeletonKey(pId); var r = ""; r += s[10]; r += s[11]; r += s[8]; r += s[9]; r += s[6]; r += s[7]; r += s[4]; r += s[5]; r += s[2]; r += s[3]; r += s[0]; r += s[1]; return new PwProcessorId(r, pId); } catch (Exception) { } var logon = from p in o["TestStepResults"]["$values"] select p; var logonnote = logon.Where(a => a["TestStepName"].ToString() == "searchKey").ToList(); var list = logonnote.Children().Where(a => ((JProperty)a).Name == "TestValue").First().Values().First(); var spId = Convert.ToUInt64(list.ToString().Replace(" ", "").Substring(7, 16), 16); var ss = BuildSkeletonKey(spId); var rr = ""; rr += ss[10]; rr += ss[11]; rr += ss[8]; rr += ss[9]; rr += ss[6]; rr += ss[7]; rr += ss[4]; rr += ss[5]; rr += ss[2]; rr += ss[3]; rr += ss[0]; rr += ss[1]; return new PwProcessorId(rr, spId); // return new PwProcessorId(ASCIIEncoding.ASCII.GetString(bytes)); } } catch (Exception e) { return new PwProcessorId(e.Message + e.StackTrace); } return new PwProcessorId(); } }); } [Route("GetPassword")] public async Task GetPassword(String PcbId, Int32 Llv = 8) { try { var returnPw = "Not assigned"; using (var dataAccess = new SqlDataAccess(GlobalConfig.connectionString.Value)) { String selectQuery = $"select [password] , [isLocked],[KeySetId] ,[orderNumber],[radioAdress] from dbo.Genesis_PcbPassword where PcbId like '{PcbId}'"; var dt = dataAccess.ExecuteQuery(selectQuery); if (dt.Rows.Count == 0) { var luPW = await GetPasswordLU(PcbId); if (!string.IsNullOrEmpty(luPW.Password)) { var ProcessorIdString = luPW.ProcessorId.HasValue ? $"'{luPW.ProcessorId.Value}'" : "null"; dt = dataAccess.ExecuteQuery($"INSERT INTO [dbo].[Genesis_PcbPassword] " + $" ([PcbId] " + $" ,[Password] " + $" ,[KeySetId] " + $" ,[orderNumber] " + $" ,[radioAdress] " + $" ,[Bemerkung] " + $" ,[KitronSkeletonKey] " + $" ,[ProcessorID] " + $" ,[IsLocked]) " + $" VALUES " + $" ('{PcbId}' " + $" ,'{luPW.Password}' " + $" ,NULL " + $" ,NULL " + $" ,NULL " + $" ,'AutoImport' " + $" ,'{luPW.Password}' " + $" ,{ProcessorIdString} " + $" ,0); " + $" { Environment.NewLine}" + $" { selectQuery}"); } } foreach (var item in dt.Select()) { returnPw = item["password"].ToString(); if (!(Boolean)item["isLocked"]) { return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() => { return returnPw; })); } if (string.IsNullOrEmpty(item["KeySetId"].ToString())) { return Request.CreateResponse(HttpStatusCode.InternalServerError, new NoKeyStoredException(new Guid("3A963893-5D8D-4A61-9D65-4B927A9331A5"))); } if (!Request.Headers.Contains("X-Node-Token")) { return Request.CreateResponse(HttpStatusCode.InternalServerError, new TokenRequiredException(new Guid("A1ED92AE-8341-4829-9A18-8249D927E777"))); } var passwords = getKeys(Request.Headers.GetValues("X-Node-Token").First(), item["orderNumber"].ToString(), item["password"].ToString()); //pw servcie stores 1,2,X,4-8 if (Llv != 3) { returnPw = passwords.Keys[Llv <= 2 ? Llv : Llv + 1].KeyKey; if (returnPw.Length > 12) { returnPw = returnPw.Substring(0, 12); } return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() => { return returnPw; })); } return Request.CreateResponse(HttpStatusCode.InternalServerError, new LvlNotSupportedException(new Guid("CEDF523B-681F-4084-93A3-C66487BA3564"))); } } return Request.CreateResponse(HttpStatusCode.InternalServerError, new PcbIdNotException(new Guid("23924333-5565-473B-BB66-ECFF8A76B429"))); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.ToString() + "
" + ex.InnerException.ToString()); } } public class MeterPasswordContainer { public Int64? orderNumber = null; public Int64? radioAdress = null; public String Skeleton = ""; public String Password = ""; public List listOfHashes = new List(); public List listOfPasswords = new List(); public String KeySetId { get; internal set; } public String PasswordFileIdent { get; internal set; } } private MeterPw getKeys(String Token, String orderNumber, String radioAdress) { ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return true; }; //var Url = $"{ServiceUrls.KeyServerCustom()}devices var Url = $"https://nodes.sms-esaap.com:8081/api/v3/custom/keysetkeys?orderNumber={orderNumber}&radioAdress={radioAdress}"; //Url = $"https://nodes.sms-esaap.com:8081/api/v3/custom/keysetkeys?setId={orderNumber}&radioAdress={radioAdress}";// var header = new Dictionary(); header.Add("Cache-Control", "no-cache"); header.Add("X-Node-Token", Token);//"d5b8c0b2-81f6-4421-80d0-44eb2093e616"); try { var responseJson = LocalWebRequest.GetRequest(url: Url, header: header, timeoutMs: 20000); responseJson = responseJson.Trim('"'); return MeterPw.FromJson(responseJson); } catch (Exception ex) { throw new ApplicationException("Fatal exception while getting keys from server", ex); } } [Route("GetPasswordHashFileContent")] public async Task GetPasswordHashFileContent(String PcbId) { try { var listOfHashes = new List(); var sbOutPut = new StringBuilder(); var sbQuery = new StringBuilder(); sbQuery.AppendLine($" SELECT "); sbQuery.AppendLine($" [Seriennummer] "); sbQuery.AppendLine($" ,mps.MapPcbIdToSerialNumber_PcbId "); sbQuery.AppendLine($" ,[Adresse] "); sbQuery.AppendLine($" ,AuftragPosSNr.AuftragNr "); sbQuery.AppendLine($" ,Auftrag.FertigungsauftragNr "); sbQuery.AppendLine($" ,[GeschlossenDatum] "); sbQuery.AppendLine($" ,[Vergabe_am] "); sbQuery.AppendLine($" ,passwordtbl.KeySetId "); sbQuery.AppendLine($" ,passwordtbl.orderNumber "); sbQuery.AppendLine($" ,passwordtbl.Password "); sbQuery.AppendLine($" ,passwordtbl.KitronSkeletonKey as Skeleton "); sbQuery.AppendLine($" ,passwordtbl.ProcessorID as ProcessorUid "); sbQuery.AppendLine($" FROM [Auftrag].[dbo].[Genesis_Meter] meter "); sbQuery.AppendLine($" inner join MapPcbIdToSerialNumber mps" + $" on mps.MapPcbIdToSerialNumber_SerialNumber = meter.Seriennummer and mps.MapPcbIdToSerialNumber_Deleted = 0 "); sbQuery.AppendLine($" inner join[Auftrag].[dbo].[AuftragPositionSerienNr] AuftragPosSNr " + $" on AuftragPosSNr.SerienNr = meter.Seriennummer and [Pruefgangnr] = 0 "); sbQuery.AppendLine($" inner join[Auftrag].[dbo].[AlleAuftragPositionen] Auftrag" + $" on Auftrag.AuftragNr = AuftragPosSNr.AuftragNr and AuftragPosSNr.PositionNr = Auftrag.PositionNr "); sbQuery.AppendLine($" left outer join[dbo].[Genesis_PcbPassword] passwordtbl" + $" on passwordtbl.PcbId = mps.MapPcbIdToSerialNumber_PcbId "); sbQuery.AppendLine($" where mps.MapPcbIdToSerialNumber_PcbId = '{PcbId}' "); var result = new MeterPwdDb(); using (var dataAccess = new SqlDataAccess(GlobalConfig.connectionString.Value)) { var dt = dataAccess.ExecuteQuery(sbQuery.ToString()); foreach (var item in dt.Select()) { result.OrderNumber = (Int32)item["FertigungsauftragNr"]; result.RadioAddress = (Int64)item["Adresse"]; result.Skeleton = (String)item["Skeleton"]; result.Password = (String)item["Password"]; result.PasswordFileIdent = result.RadioAddress.HasValue ? result.RadioAddress.Value.ToString() : PcbId; if (item["KeySetId"].GetType() != typeof(System.DBNull)) { result.KeySetId = (String)item["KeySetId"]; } } } if (!result.OrderNumber.HasValue) { return Request.CreateResponse(HttpStatusCode.InternalServerError, new PcbIdNotException(new Guid("160B4C44-6EF7-41DC-A48D-4B4105B4779B"))); } Request.Headers.Add("X-Node-Token", "d5b8c0b2-81f6-4421-80d0-44eb2093e616"); if (!Request.Headers.Contains("X-Node-Token")) { return Request.CreateResponse(HttpStatusCode.InternalServerError, new TokenRequiredException(new Guid("77895D13-CA58-48AB-8C5E-9CDB7F80C69D"))); } if (string.IsNullOrEmpty(result.KeySetId)) { result.KeySetId = CreateKeySet(Request.Headers.GetValues("X-Node-Token").First(), 7); //mapp keyset MapKeySet(Request.Headers.GetValues("X-Node-Token").First(), result.KeySetId, result.OrderNumber.Value, result.PasswordFileIdent); using (var dataAccess = new SqlDataAccess(GlobalConfig.connectionString.Value)) { var dt = dataAccess.ExecuteQuery( $"update auftrag.[dbo].[Genesis_PcbPassword] set KeySetId = '{result.KeySetId}', [orderNumber] = {result.OrderNumber.Value}, [radioAdress] = {result.PasswordFileIdent} where PcbId = '{PcbId}'; select * from auftrag.[dbo].[Genesis_PcbPassword] where PcbId = '{PcbId}'"); } } var passwords = getKeys(Request.Headers.GetValues("X-Node-Token").First(), result.OrderNumber.Value.ToString(), result.PasswordFileIdent); //pw lvl passwords.Keys.Insert(2, new Key() { Index = 2, KeyKey = result.Skeleton }); var pwdLVL8 = ""; if (passwords.Keys.Count > 7) { pwdLVL8 = passwords.Keys[7].KeyKey.Substring(0, 12); } foreach (var keyLVL in passwords.Keys) { using (System.Security.Cryptography.SHA1Managed sha1 = new System.Security.Cryptography.SHA1Managed()) { var rawKey = keyLVL.KeyKey; if (rawKey.Length > 12) { rawKey = rawKey.Substring(0, 12); } if (result.ListOfPasswords.Count <= 7) { result.ListOfPasswords.Add(Encoding.UTF8.GetBytes(rawKey)); var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(rawKey)); result.ListOfHashes.Add(hash); } } } return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() => { return result; })); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex.ToString() + "
" + ex.InnerException.ToString()); } } private String MapKeySet(String Token, String KeySetID, Int64 MeterOrderNumber, string MeterPassowrdIdent) { try { //keysets var Url = $"{ServiceUrls.KeyServerCustom()}keysetkeys/"; Url = "https://nodes.sms-esaap.com/keygenproxy/api/v3/custom/keysets/devices"; var header = new Dictionary(); header.Add("Cache-Control", "no-cache"); header.Add("X-Node-Token", Token);//"d5b8c0b2-81f6-4421-80d0-44eb2093e616"); //string postData = $"[{{\"setId\":\"{KeySetID}\", \"orderNumber\":\"{orderNumber}\", \"radioAdress\":\"{radioAdress}\"}}]"; var postData = new MapKeySetItem() { orderNumber = MeterOrderNumber.ToString(), radioAdress = MeterPassowrdIdent.ToString(), setId = KeySetID }; var helpArray = new List() { postData }; return LocalWebRequest.PostRequestAsyncAndGetContent(url: Url, header: header, json: helpArray.ToArray(), timeoutMs: 20000); } catch (Exception) { throw; } } // Root myDeserializedClass = JsonConvert.DeserializeObject(myJsonResponse); public class MapKeySetItem { public String setId { get; set; } public String orderNumber { get; set; } public String radioAdress { get; set; } } private String CreateKeySet(String Token, Int32 CountKeys) { var Url = $"https://nodes.sms-esaap.com/keygenproxy/api/v3/custom/keysets"; var http = (HttpWebRequest)WebRequest.Create(Url); http.Timeout = 20000; http.Headers.Add("Cache-Control", "no-cache"); http.Headers.Add("X-Node-Token", Token); String postData = $"{{\"setCount\": 1,\"keysPerSet\": {CountKeys} }}"; ASCIIEncoding encoding = new ASCIIEncoding(); Byte[] byte1 = encoding.GetBytes(postData); // Set the content type of the data being posted. http.ContentType = "application/json; charset=utf-8"; http.Method = "POST"; // Set the content length of the string being posted. http.ContentLength = byte1.Length; Stream newStream = http.GetRequestStream(); newStream.Write(byte1, 0, byte1.Length); newStream.Close(); var response = (HttpWebResponse)http.GetResponse(); var responseStream = response.GetResponseStream(); if (responseStream == null) { throw new InvalidOperationException(); } if (response.StatusCode != HttpStatusCode.OK) { } using (var sr = new StreamReader(responseStream)) { var responseJson = sr.ReadToEnd(); responseJson = responseJson.Trim('"'); var res = MeterPw.ArrayFromJson(responseJson); return res[0].SetId.ToString(); } } public partial class MeterPw { [JsonProperty("SetId")] public Guid SetId { get; set; } [JsonProperty("Keys")] public List Keys { get; set; } } public partial class Key { [JsonProperty("Index")] public Int64 Index { get; set; } [JsonProperty("Key")] public String KeyKey { get; set; } } public partial class MeterPw { public static MeterPw Empty() => new MeterPw() { SetId = Guid.Empty, Keys = new List() }; public static MeterPw FromJson(String json) => JsonConvert.DeserializeObject(json, Converter.Settings); public static MeterPw[] ArrayFromJson(String json) => JsonConvert.DeserializeObject(json, Converter.Settings); } internal static class Converter { public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore, DateParseHandling = DateParseHandling.None, Converters = { new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } }, }; } [Route("GetKeySetId")] public async Task GetKeySetId(String PcbId) { try { var returnKeySetId = "Not assigned"; using (var dataAccess = new SqlDataAccess(GlobalConfig.connectionString.Value)) { var dt = dataAccess.ExecuteQuery($"select [KeySetId] from dbo.Genesis_PcbPassword where PcbId like '{PcbId}'"); foreach (var item in dt.Select()) { returnKeySetId = item["KeySetId"].ToString(); } } return Request.CreateResponse(HttpStatusCode.OK, await Task.Run(() => { return returnKeySetId; })); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex.ToString() + "
" + ex.InnerException.ToString()); } } } }