public bool ParseISBPath(string pRealPage, out Guid?pSessionID, out cdeSenderType pType, out long pFID, out string pVersion) { pSessionID = null; pType = cdeSenderType.NOTSET; pFID = 0; pVersion = ""; var tRealPage = CU.cdeDecrypt(pRealPage, MySecrets?.GetAI(), true); if (tRealPage?.StartsWith(MySecrets?.GetApID5()) != true) { return(false); } string[] tQ = tRealPage.Split('&'); pType = tQ.Length == 4 ? (cdeSenderType)(CU.CInt(tQ[2])) : cdeSenderType.NOTSET; if (tQ.Length > 1) { pFID = CU.CLng(tQ[1]); } if (tQ.Length > 3) { pSessionID = CU.CGuid(tQ[3]); } if (tQ[0].Length == 7) { pVersion = tQ[0].Substring(5); } return(true); }
public string GetRealScopeIDFromEasyID(string pEasyID, bool bNoLogging = false, bool bUseEasyScope16 = false) { Guid tG = CU.CGuid(MySecrets?.GetAK()); string tg = InsertCodeIntoGUID(pEasyID, tG, bNoLogging, bUseEasyScope16).ToString(); return(CU.cdeEncrypt(CU.CGuid(tg.Substring(0, 11) + tG.ToString().Substring(11, "00-0000-0000-000000000000".Length)).ToByteArray(), MySecrets?.GetAI())); }
internal static Dictionary <string, object> GetDictionary() { TheThing tn = new TheThing(); ToThingProperties(tn, !TheCommonUtils.CBool(TheBaseAssets.MySettings.GetSetting("EnableKPIs"))); return(tn.GetPBAsDictionary()); }
public string GetISBPath(string PathPrefix, cdeSenderType pOriginType, cdeSenderType pDestinationType, long pCounter, Guid pSessionID, bool IsWS) { if (string.IsNullOrEmpty(MySecrets?.GetApID5())) { return(""); } if (string.IsNullOrEmpty(PathPrefix)) { PathPrefix = "/"; } else { if (!PathPrefix.EndsWith("/")) { PathPrefix += "/"; } } string pSessID = pSessionID.ToString(); if (pCounter == 1 && pSessionID == Guid.Empty && !(MyServiceHostInfo?.UseFixedConnectionUrl == true)) { pSessID = "P" + GetCryptoGuid().ToString().Substring(1); } MyServiceHostInfo?.MyKPIs?.IncrementKPI(eKPINames.KPI4); string tPath = PathPrefix + "ISB" + Uri.EscapeUriString(CU.cdeEncrypt($"{MySecrets?.GetApID5()}{(MyServiceHostInfo?.ProtocolVersion == null ? "40" : MyServiceHostInfo?.ProtocolVersion)}&{pCounter}&{((int)(pOriginType))}&{pSessID}", MySecrets?.GetAI())); //3.083: Must be cdeAI if (IsWS && (pDestinationType == cdeSenderType.CDE_CLOUDROUTE || pDestinationType == cdeSenderType.CDE_SERVICE || pDestinationType == cdeSenderType.CDE_CUSTOMISB)) //TODO: Might need this for Local Services that are IIS but not CloudRoutes { tPath += ".ashx"; } return(tPath); }
public bool ParseISBPath(string pRealPage, out Guid?pSessionID, out cdeSenderType pType, out long pFID, out string pVersion) { pSessionID = null; pType = cdeSenderType.NOTSET; pFID = 0; pVersion = ""; try { string[] tQ = Base64Decode(pRealPage).Split('_'); pType = tQ.Length == 4 ? (cdeSenderType)(CU.CInt(tQ[2])) : cdeSenderType.NOTSET; if (tQ.Length > 1) { pFID = CU.CLng(tQ[1]); } if (tQ.Length > 3) { pSessionID = CU.CGuid(tQ[3]); } if (tQ[0].Length == 7) { pVersion = tQ[0].Substring(5); } } catch (Exception) { // ignored } return(true); }
/// <summary> /// Calculates a hash integer that defines a unique hash for the message /// Only LVL, ENG, the Originator, OWN and the First parameter of the TXT will be taken in account. /// BEWARE: there are rare occasions where two messages are considered equal although they are not. Your code should be fault tolerant to these conditions /// The Salt can be use to add a random or other string-source to the Hash /// </summary> /// <param name="Salt"></param> /// <returns></returns> public int GetHash(string Salt) { int hash = 0; if (!string.IsNullOrEmpty(Salt)) { hash += Salt.GetHashCode(); } hash += LVL.GetHashCode(); if (!string.IsNullOrEmpty(ENG)) { hash += ENG.GetHashCode(); } hash += GetOriginator().GetHashCode(); if (!string.IsNullOrEmpty(OWN)) { hash += OWN.GetHashCode(); } string[] t = TheCommonUtils.cdeSplit(TXT, ";:;", false, false); if (t != null && t.Length > 0 && !string.IsNullOrEmpty(t[0])) { hash += t[0].GetHashCode(); } return(hash); }
/// <summary> /// Make a deep clone of the Message /// </summary> /// <param name="tMsg">Mesage to be cloned</param> /// <param name="DoClonePLB">If set to True, the PLB parameter will be block-copied, too</param> /// <returns></returns> public static TSM Clone(TSM tMsg, bool DoClonePLB) { TSM tRes = new TSM(tMsg.SID) //Save not to set ORG or SID for fast cloning { TXT = tMsg.TXT, TIM = tMsg.TIM, FLG = tMsg.FLG, ORG = tMsg.ORG,//ORG-OK QDX = tMsg.QDX, LVL = tMsg.LVL, ENG = tMsg.ENG, FID = tMsg.FID, SEID = tMsg.SEID, CST = tMsg.CST, UID = tMsg.UID, PLS = tMsg.PLS, OWN = tMsg.OWN }; if (DoClonePLB && tMsg.PLB != null && tMsg.PLB.Length > 0) { tRes.PLB = new byte[tMsg.PLB.Length]; TheCommonUtils.cdeBlockCopy(tMsg.PLB, 0, tRes.PLB, 0, tMsg.PLB.Length); } return(tRes); }
/// <summary> /// Returns the total costs of the Message in form of a TSMTotalCost receipt /// </summary> /// <returns></returns> public TSMTotalCost GetTotalCosts() { if (string.IsNullOrEmpty(CST)) { return(null); } string[] tItems = TheCommonUtils.cdeSplit(CST, ";:;", true, true); TSMTotalCost tTotal = new TSMTotalCost() { Items = new List <TSMCosting>() }; foreach (string t in tItems) { string[] tt = TheCommonUtils.cdeDecrypt(t, TheBaseAssets.MySecrets.GetAI()).Split(';'); //3.083: Must be cdeAI if (tt.Length < 4) { continue; } TSMCosting tCost = new TSMCosting(TheCommonUtils.CInt(tt[0]), TheCommonUtils.CStr(tt[1]), TheCommonUtils.CStr(tt[2]), TheCommonUtils.CStr(tt[3])); tTotal.Items.Add(tCost); tTotal.TotalCredits += tCost.Credits; tTotal.TotalItems++; } return(tTotal); }
/// <summary> /// NEW in V4: Returns the next node in GRO to optimize Route traffic /// </summary> /// <returns></returns> public Guid GetNextNode() { if (string.IsNullOrEmpty(GRO) || !GRO.Contains(TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString())) { return(Guid.Empty); } var tNodes = TheCommonUtils.cdeSplit(GRO, ';', false, false); if (tNodes.Length < 2) { return(Guid.Empty); } var tLastNode = tNodes[0].Split(':')[0]; for (int i = 1; i < tNodes.Length; i++) { var tN = tNodes[i].Split(':')[0]; if (tN == TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString()) { return(TheCommonUtils.CGuid(tLastNode)); } tLastNode = tN; } return(Guid.Empty); }
/// <summary> /// Decrypt incoming buffer array to a Dictionary. /// </summary> /// <param name="pInbuffer">incoming byte arrey to be decrypted</param> /// <returns></returns> public Dictionary <string, string> DecryptKV(byte[] pInbuffer) { try { var fromEncrypt = Decrypt(pInbuffer, MySecrets?.GetAK(), MySecrets?.GetAI()); string dec = CU.CArray2UnicodeString(fromEncrypt, 0, fromEncrypt.Length); dec = dec.TrimEnd('\0'); var pos = dec.IndexOf('@'); if (pos < 0) { return(null); } var tPref = dec.Substring(0, pos); var tP = tPref.Split(':'); if (tP.Length < 2 || CU.CInt(tP[1]) != (dec.Substring(pos + 1)).Length) { return(null); } return(CU.DeserializeJSONStringToObject <Dictionary <string, string> >(dec.Substring(pos + 1))); } catch (Exception) { MySYSLOG?.WriteToLog(0, 5015, "ICDECrypto", $"Error during KV decrypt...", eMsgLevel.l1_Error); return(null); } }
/// <summary> /// Checks if the given Originator DeviceID is in the list of Origins /// </summary> /// <param name="tGuid"></param> /// <returns></returns> public bool DoesORGContain(Guid tGuid) { if (tGuid == Guid.Empty) { return(false); } return(TheCommonUtils.DoUrlsContainAnyUrl(ORG, tGuid.ToString())); }
public Guid GenerateNewAppDeviceID(cdeSenderType tS) { string tg = Guid.NewGuid().ToString(); string t = tg.Substring(0, 35); t += ((int)tS).ToString(); return(CU.CGuid(t)); }
private static Guid GetCryptoGuid() { RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider(); byte[] data = new byte[16]; crypto.GetBytes(data); return(CU.CGuid(data)); }
/// <summary> /// Checks if a ; separated list of IDs is found in the Originators of this message. /// Only if ALL pIDs are found in the ORG, the method will return true /// </summary> /// <param name="pIDs"></param> /// <returns></returns> public bool DoesORGContainAny(string pIDs) { if (string.IsNullOrEmpty(pIDs)) { return(false); } return(TheCommonUtils.DoUrlsContainAnyUrl(ORG, pIDs)); }
private static void CreateFileWithAllStringsNotFormattedForLocalization(string engine, string originalString) { string fileName = TheCommonUtils.cdeFixupFileName(@"Localization\Workflow\need-to-be-formatted.txt"); TheCommonUtils.CreateDirectories(fileName); CreateFileForLocalizationKeyWords(fileName); WriteKeywordToFile(fileName, engine + " - " + originalString); }
/// <summary> /// Creates a new DeviceID/NodeID for the current Application Scope /// </summary> /// <param name="tS">Sender Type of the Node</param> /// <returns></returns> public Guid GenerateNewAppDeviceID(cdeSenderType tS) { string tg = GetCryptoGuid().ToString(); //return new Guid(tg.Substring(0, 11) + ((int)tS).ToString() + (new Guid(TheBaseAssets.cdeAK)).ToString().Substring(12, "0-0000-0000-000000000000".Length)); string t = tg.Substring(0, 29); t += ((int)tS).ToString(); t += (CU.CGuid(MySecrets?.GetAK())).ToString().Substring(29, 6); return(CU.CGuid(t)); }
public void OnStartInternal() { StartupLog?.Log("Service: Initializing"); try { if (!Initialize()) { StartupLog?.Log("Service: Initializing FAILED"); return; } } catch (Exception e) { StartupLog?.Log($"Service: Exception initializing: {e}"); } StartupLog?.Log("Service: Parsing parameters"); MyBaseApplication = new TheBaseApplication(); if (CU.CBool(TheBaseAssets.MySettings.GetSetting("UseRandomScope")) && CU.CBool(TheBaseAssets.MySettings.GetSetting("UseRandomDeviceID"))) { TheBaseAssets.MyServiceHostInfo.SealID = TheScopeManager.GenerateNewScopeID(); TheScopeManager.SetScopeIDFromEasyID(TheBaseAssets.MyServiceHostInfo.SealID); } StartupLog?.Log("Service: StartBaseApplication"); try { if (!MyBaseApplication.StartBaseApplication(null, MyArgList)) { StartupLog?.Log("Service: StartBaseApplication failed"); AfterStartup(false); return; } if (StartupLog != null && MyArgList.ContainsKey("DisableConsole") && CU.CBool(MyArgList["DisableConsole"])) { TheBaseAssets.MySYSLOG.RegisterEvent2("NewLogEntry", (pmsg, pNewLogEntry) => { var tLog = pmsg?.Cookie as TheEventLogEntry; if (tLog != null) { StartupLog?.Log($"ID:{tLog.EventID} SN:{tLog.Serial} {tLog.Message?.ToAllString()}", tLog.Message.LVL); } }); } } catch (Exception ee) { StartupLog?.Log($"Service: StartBaseApplication failed with Exception: {ee}"); AfterStartup(false); return; } StartupLog?.Log("Service: StartBaseApplication success"); AfterStartup(true); }
private static Guid InsertCodeIntoGUID(string pCode, Guid pGuid, bool useEasyScope16) { string tg = MD5(pCode, useEasyScope16); string tguid = pGuid.ToString().Replace("{", "").Replace("}", "").Replace("-", ""); if (tg.Length > tguid.Length) { return(CU.CGuid(tg.Substring(0, tguid.Length))); } return(CU.CGuid(tg + tguid.Substring(0, tguid.Length - tg.Length))); }
private void WriteLogToFile(bool WaitForLock) { if (string.IsNullOrEmpty(MyCurLog)) { return; } // ReSharper disable once EmptyEmbeddedStatement if (WaitForLock) { while (TheCommonUtils.cdeIsLocked(writeLock)) { ; // CODE REVIEW: This can go into a tight loop - should yield the thread or sleep for 1 few milliseconds before checking again } } if (!TheCommonUtils.cdeIsLocked(writeLock)) { lock (writeLock) { var bLogFileExists = System.IO.File.Exists(MyCurLog); if (MaxLogFileSize > 0 && bLogFileExists) { try { System.IO.FileInfo f2 = new System.IO.FileInfo(MyCurLog); if (f2.Length > MaxLogFileSize * (1024 * 1024)) { LogFilePath = mLogFilePath; System.IO.File.Move(MyCurLog, MySystemFileLogName); CheckFileRollover(); } } catch { //ignored } bLogFileExists = System.IO.File.Exists(MyCurLog); } try { using (System.IO.StreamWriter fs = new System.IO.StreamWriter(MyCurLog, bLogFileExists)) { foreach (TheEventLogEntry tLogs in MyMessageLog.MyMirrorCache.MyRecords.Values.Where(s => s.WasWritten == false).OrderBy(s => s.Serial).ToList()) //serial is more precise than CTIM { fs.WriteLine($"{tLogs.Source} : {tLogs.EventID} : {tLogs.Serial} : {tLogs.Message}"); //Serial is required to see the exact order of messages put in the log if the ms in the timestamp is the same tLogs.WasWritten = true; } } } catch { //ignored } } } }
/// <summary> /// Return a Scrambled ScopeID from an easy scopeID /// </summary> /// <param name="pEasyScope">Source EasyScope</param> /// <param name="bNoLogging">If true, errors will not be logged</param> /// <param name="bUseEasyScope16">if true, the EasyScopeID can have up to 16 characters. Attention: this might not be compatible to existing mesh setups as all nodes in a mesh need to understand 16chars ScopeIDs</param> /// <returns></returns> public string GetScrambledScopeIDFromEasyID(string pEasyScope, bool bNoLogging, bool bUseEasyScope16) { if (string.IsNullOrEmpty(pEasyScope)) { return(null); //NEW 10/20/2012 } Guid tG = CU.CGuid(TheBaseAssets.MySecrets.GetAK()); MyServiceHostInfo?.MyKPIs?.IncrementKPI(eKPINames.KPI4); return(Base64Encode($"{CU.GetRandomUInt(0, 1000)}&{InsertCodeIntoGUID(pEasyScope, tG, bUseEasyScope16)}")); }
private static string MD5(string text, bool useEasyScope16) { var result = default(string); using (var algo = new MD5CryptoServiceProvider()) { algo.ComputeHash(Encoding.UTF8.GetBytes(text)); result = CU.ToHexString(algo.Hash); } return(result.Substring(0, useEasyScope16?16:8)); }
//SECURITY-REVIEW: Is the return of this fuction security critcal? public static string GetAdditionalSigningKeyString(TheLicense[] licenses) { return(licenses.Aggregate("", (s, l) => { if (!String.IsNullOrEmpty(l.ActivationKeyValidator)) { string decryptedKeyValidator = CU.Decrypt(Encoding.UTF8.GetBytes(l.ActivationKeyValidator), TheBaseAssets.MySecrets.GetAI()); return s + decryptedKeyValidator; } return s; })); }
/// <summary> /// Return a Scrambled ScopeID from an easy scopeID /// </summary> /// <param name="pEasyScope">Source EasyScope</param> /// <param name="bNoLogging">If true, errors will not be logged</param> /// <param name="bUseEasyScope16">if true, the EasyScopeID can have up to 16 characters. Attention: this might not be compatible to existing mesh setups as all nodes in a mesh need to understand 16chars ScopeIDs</param> /// <returns></returns> public string GetScrambledScopeIDFromEasyID(string pEasyScope, bool bNoLogging, bool bUseEasyScope16) { if (string.IsNullOrEmpty(pEasyScope)) { return(null); //NEW 10/20/2012 } Guid tG = CU.CGuid(MySecrets?.GetAK()); string tg = InsertCodeIntoGUID(pEasyScope, tG, bNoLogging, bUseEasyScope16).ToString(); MyServiceHostInfo?.MyKPIs?.IncrementKPI(eKPINames.KPI4); return(CU.cdeEncrypt(CU.GetRandomUInt(0, 1000) + "&" + CU.cdeEncrypt(CU.CGuid(tg.Substring(0, 11) + tG.ToString().Substring(11, "00-0000-0000-000000000000".Length)).ToByteArray(), MySecrets?.GetAI()), MySecrets?.GetAI())); }
/// <summary> /// Finds the engine that contains the resource file in use. /// Attempts to use the engine defined as a parameter in the first localization string. /// It's assumed that all other localization strings in the list are using the same engine. /// If no engine parameter is defined, the engine provided by the CDEngine is used. /// </summary> /// <param name="engine"></param> /// <param name="localizableElement"></param> /// <returns></returns> private static string GetEngine(string engine, string localizableElement) { if (!localizableElement.Contains("#")) { return(engine); } var locElementParams = TheCommonUtils.cdeSplit(localizableElement, "#", false, false); var engineParamDefined = locElementParams.Length == 3 && !locElementParams[0].Equals(""); return(engineParamDefined ? locElementParams[0] : engine); }
internal string GetCanonicalLicense() { TheLicense tempLicense = new TheLicense(this); // Bug in original License constructor did not copy the Description field, so it was not included in the signature. Only shipped license was this one (P08 Project, OPC Client) //CODE-REVIEW: Is this still necessary? if (tempLicense.LicenseId == new Guid("6a78a4cb-1d9b-4a53-a41b-c57497085026")) { tempLicense.Description = null; } tempLicense.Signatures = new string[0]; return(CU.SerializeObjectToJSONString(tempLicense)); }
/// <summary> /// Encryptes a dictionary to a byte array /// </summary> /// <param name="pVal">Dictionary to be encrypted</param> /// <returns></returns> public byte[] EncryptKV(Dictionary <string, string> pVal) { try { string t = CU.SerializeObjectToJSONString(pVal); return(Encrypt(CU.CUnicodeString2Array(t), MySecrets?.GetAK(), MySecrets?.GetAI())); } catch (Exception) { TheBaseAssets.MySYSLOG?.WriteToLog(TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheCommonUtils", $"Error during KV encrypt...", eMsgLevel.l1_Error), 5016); return(null); } }
/// <summary> /// Encrypts an string to an encrypted string. /// </summary> /// <param name="pInBuffer">The inbuffer.</param> /// <param name="pType">Type of the buffer.</param> /// <returns>System.String.</returns> public string EncryptToString(string pInBuffer, string pType) { switch (pType) { case "CDEP": if (!pInBuffer.StartsWith("&^CDESP1^&:")) { return("&^CDESP1^&:" + CU.cdeEncrypt(pInBuffer, MySecrets?.GetNodeKey())); } break; } return(pInBuffer); }
/// <summary> /// Decrypts a byte array to a string using internal AES encryption /// </summary> /// <param name="OrgBuffer">Buffer to be decrypted</param> /// <param name="pType">Current only supported type: "AIV1"</param> /// <returns></returns> public string DecryptToString(string OrgBuffer, string pType) { switch (pType) { case "CDEP": if (OrgBuffer.StartsWith("&^CDESP1^&:")) { return(CU.cdeDecrypt(OrgBuffer.Substring(11), MySecrets?.GetNodeKey())); } break; } return(null); }
private Guid InsertCodeIntoGUID(string pCode, Guid pGuid, bool bNoLogging, bool useEasyScope16) { long calc = 0; if (pCode.Length < 8) { pCode += "00000000".Substring(0, 8 - pCode.Length); } else { if (!bNoLogging && pCode.Length > 8 && MyServiceHostInfo?.UseEasyScope16 != true) { MyServiceHostInfo?.MySYSLOG?.WriteToLog(MyServiceHostInfo?.IsCloudService == true ? eDEBUG_LEVELS.VERBOSE : eDEBUG_LEVELS.OFF, 2353, "TheScopeManager", "EasyID was longer than 8 characters: extra characters were ignored.", eMsgLevel.l2_Warning); } } var pCodeUpper = pCode.ToUpper(); var pCodeNormalized = pCodeUpper.Replace('O', '0').Replace('U', 'V').Replace('I', 'J').Replace('L', 'J'); if (!bNoLogging && !string.Equals(pCodeNormalized, pCodeUpper, StringComparison.Ordinal)) { //Do not log in cloud! This can fill the log if too many scopeIDs are using these chars (which is not a problem in the cloud) MyServiceHostInfo?.MySYSLOG?.WriteToLog(MyServiceHostInfo?.IsCloudService == true ? eDEBUG_LEVELS.VERBOSE : eDEBUG_LEVELS.OFF, 2354, "TheScopeManager", "EasyID contained reserved characters (O, V, I or L) that were normalized to (0, U, or J).", eMsgLevel.l2_Warning); } char[] tAr = pCodeNormalized.ToCharArray(); for (int i = 0; i < 8; i++) { long tt = MySecrets.GetCodeArray().IndexOf(tAr[i]); calc <<= 5; calc += tt; } string tg = string.Format("{0:x10}", calc); if (useEasyScope16) //Use16 digits ScopeID with new ApplicationID insert { for (int i = 8; i < pCode.Length; i++) { long tt = MySecrets.GetCodeArray().IndexOf(tAr[i]); calc <<= 5; calc += tt; } tg = string.Format("{0:x16}", calc); tg = tg.Substring(0, 8) + "-" + tg.Substring(8, 4) + "-" + tg.Substring(12, 4); tg += pGuid.ToString().Substring(18, "-0000-000000000000".Length); } else { tg = tg.Substring(0, 8) + "-" + tg.Substring(8, 2); tg += pGuid.ToString().Substring(11, "00-0000-0000-000000000000".Length); } return(CU.CGuid(tg)); }
/// <summary> /// Encryptes a dictionary to a byte array /// </summary> /// <param name="pVal">Dictionary to be encrypted</param> /// <returns></returns> public byte[] EncryptKV(Dictionary <string, string> pVal) { try { string t = CU.SerializeObjectToJSONString(pVal); var tFinal = $"{CU.GetRandomUInt(0, 10000)}:{t.Length}@" + t; return(Encrypt(CU.CUnicodeString2Array(tFinal), MySecrets?.GetAK(), MySecrets?.GetAI())); } catch (Exception) { MySYSLOG?.WriteToLog(0, 5016, "ICDECrypto", $"Error during KV encrypt...", eMsgLevel.l1_Error); return(null); } }