Ejemplo n.º 1
0
        private Boolean getFile(string fileName)
        {
            FileProps get = new FileProps
            {
                action = "file",
                token  = client.tokenID,
                task   = taskID,
                file   = fileName
            };

            jsonClass jsC = new jsonClass {
                debugFlag = debugFlag, connectURL = client.connectURL
            };
            string jsonString = jsC.toJson(get);
            string ret        = jsC.jsonSend(jsonString);

            if (jsC.isJsonSuccess(ret))
            {
                string fileDl = jsC.getRetVar(ret, "url");
                {
                    downloadClass dlHdl  = new downloadClass();
                    string        dlFrom = Path.Combine(prefixServerdl, jsC.getRetVar(ret, "url"));
                    string        dlTo   = Path.Combine(filepath, fileName);
                    dlHdl.DownloadFile(dlFrom, dlTo);
                    Console.WriteLine("Finished downloading file");
                    //Check if file exists. check if return success
                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Create Configuration settings for producer or consumer according to parameters
        /// </summary>
        /// <param name="prodOrCons"></param>
        /// <returns></returns>
        public Dictionary <string, object> CreateConfig(string prodOrCons)
        {
            // read configuration data from a JSON file
            using (StreamReader r = new StreamReader("..\\..\\..\\config.json"))
            {
                string json = r.ReadToEnd().Replace('.', '_');
                _jsonData = JsonConvert.DeserializeObject <jsonClass>(json);
            }
            Dictionary <string, object> config;

            switch (prodOrCons.ToLower())
            {
            case "producer":
                // Create the producer configuration
                config = new Dictionary <string, object>
                {
                    { "bootstrap.servers", _jsonData.bootstrap_servers.Replace('_', '.') }
                };

                return(config);

            case "consumer":
                // Create the producer configuration
                config = new Dictionary <string, object>
                {
                    { "group.id", _jsonData.group_id },
                    { "bootstrap.servers", _jsonData.bootstrap_servers.Replace('_', '.') },
                    { "enable.auto.commit", true },
                    { "auto.offset.reset", _jsonData.auto_offset_reset }
                };
                return(config);
            }

            return(default);
Ejemplo n.º 3
0
        public Boolean init7z()
        {
            binPath = Path.Combine(appPath, "7zr");
            if (osID == 1)
            {
                binPath += ".exe";
            }

            if (!File.Exists(binPath))
            {
                Console.WriteLine("Downloading 7zip binary");
                jsonClass jsC = new jsonClass {
                    debugFlag = true, connectURL = connectURL
                };

                dlProps dlzip = new dlProps
                {
                    token = tokenID
                };


                string jsonString = jsC.toJson(dlzip);
                string ret        = jsC.jsonSend(jsonString);
                if (jsC.isJsonSuccess(ret))

                {
                    string        dlLocation = jsC.getRetVar(ret, "executable");
                    downloadClass dlClass    = new downloadClass();

                    if (!dlClass.DownloadFile(dlLocation, binPath))
                    {
                        Console.WriteLine("Unable to download requested file");
                    }
                    else
                    {
                        Console.WriteLine("Finished downloading file");
                    }
                }
                if (osID != 1) //If OS is not windows, we need to set the permissions
                {
                    try
                    {
                        Console.WriteLine("Applying execution permissions to 7zr binary");
                        Process.Start("chmod", "+x \"" + binPath + "\"");
                    }
                    catch (Exception e)
                    {
                        Console.Write(e.Data);
                        Console.WriteLine("Unable to change access permissions of 7zr, execution permissions required");
                    }
                }
            }

            if (File.Exists(binPath))
            {
                return(true);
            }

            return(false);
        }
Ejemplo n.º 4
0
        public static void writeSettings(config_data config)
        {
            string    jsonPath      = Path.Combine(AppPath, "config.json");
            jsonClass jsonProcessor = new jsonClass();
            string    saveSettings  = jsonProcessor.toJson(config);

            File.WriteAllText(jsonPath, saveSettings);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 动漫app由9miao社团研发,如有问题请登陆http://www.9miao.com/官网
        /// </summary>
        ///



        public void ProcessRequest(HttpContext context)
        {
            CallBackJson json   = new CallBackJson();
            jsonClass    jclass = new jsonClass();

            jclass.Status = "Error";
            jclass.Msg    = "服务器异常";
            try
            {
                string _id   = context.Request.Form["id"];          //小分类id
                string _name = context.Request.Form["name"];        //小分类名称
                string _type = context.Request.Form["type"];        //类型 0修改  1添加
                if (string.IsNullOrEmpty(_name.Trim()))
                {
                    throw new Exception("信息参数未空");
                }
                using (
                    CDBAccess cn =
                        new CDBAccess(System.Configuration.ConfigurationSettings.AppSettings["OledbStr"]))
                {
                    if (_type == "0")
                    {
                        cn.ExecSQL(@"UPDATE T0001 SET C00006=? WHERE C00004=?",
                                   new OleDbParameter[] {
                            new OleDbParameter("@C00003", _name),
                            new OleDbParameter("@C00001", _id)
                        });
                        jclass.Msg = "恭喜你!修改分类成功";
                    }
                    else
                    {
                        string systemid = cn.ExecScalar(@"select max(Val(C00004))+1 from T0001 where C00101 <> 6 ").ToString();
                        if (string.IsNullOrEmpty(systemid))
                        {
                            systemid = "1";
                        }
                        cn.ExecSQL(@"INSERT INTO T0001 (C00004,C00005,C00006,C00101) VALUES (?,?,?,?)",
                                   new OleDbParameter[] {
                            new OleDbParameter("@C00004", systemid),
                            new OleDbParameter("@C00005", ""),
                            new OleDbParameter("@C00006", _name),
                            new OleDbParameter("@C00101", _id)
                        });
                        jclass.Msg = "恭喜你!添加分类成功";
                    }
                    jclass.Status = "Success";
                }
            }
            catch (Exception ex)
            {
                jclass.Msg = ex.Message;
            }
            context.Response.Write(json.Serializer(jclass));
        }
Ejemplo n.º 6
0
        public Boolean getHashes(int inTask)
        {
            actualHLpath = Path.Combine(hashpath, Path.GetFileName(inTask.ToString()));

            Console.WriteLine("Downloading hashlist for this task, please wait...");

            hashlistProps hProps = new hashlistProps
            {
                token      = client.tokenID,
                hashlistId = inTask
            };
            jsonClass jsC = new jsonClass {
                debugFlag = debugFlag, connectURL = client.connectURL
            };
            string jsonString = jsC.toJson(hProps);
            string ret        = jsC.jsonSend(jsonString, 300); //300 second timeout

            if (jsC.isJsonSuccess(ret))
            {
                getURLtoFile(jsC.getRetVar(ret, "url"), actualHLpath);
            }


            /*
             * //Check if is json string, a nasty workaround copies from the javaclient to detect whether the return string is json vs hl. Should probably use a proper detector
             * if (ret[0] != '{' && ret[ret.Length - 1] != '}')
             * {
             *  File.WriteAllText(actualHLpath, ret);
             *  Directory.CreateDirectory(Path.Combine(hashpath, "zaps" + inTask.ToString()));
             * }
             * else
             * {
             *  if (jsC.isJsonSuccess(ret))
             *  {
             *      string b64data = jsC.getRetVar(ret,"data");
             *      byte[] binArray = System.Convert.FromBase64String(b64data);
             *      File.WriteAllBytes(actualHLpath, binArray);
             *      stipPath = true; //Strip path for all HL recieved binary hashlsits
             *
             *  }
             *  else
             *  {
             *      return false;
             *  }
             *
             * }
             */

            return(true);
        }
Ejemplo n.º 7
0
    public bool loginAgent()
    {
        if (!loadToken())
        {
            Console.WriteLine("Unable to find existing token, please enter voucher");
            while (registerAgent(Console.ReadLine()) == false)
            {
                Console.WriteLine("Invalid voucher, please try again");
            }
        }
        else
        {
            Console.WriteLine("Existing token found");
            jsonClass jsC = new jsonClass {
                connectURL = connectURL, debugFlag = debugFlag
            };

            var arrayKey = new Dictionary <string, string>
            {
                { "action", "login" },
                { "clientSignature", "generic-csharp" },
                { "token", tokenID },
            };

            string jsonString = jsC.toJson(arrayKey);
            string ret        = jsC.jsonSend(jsonString);

            if (jsC.isJsonSuccess(ret))
            {
                updateAgentInformation();
                return(true);
            }
            else
            {
                Console.WriteLine("Existing token is invalid, please enter voucher");
                while (registerAgent(Console.ReadLine()) == false)
                {
                    Console.WriteLine("Invalid voucher, please try again");
                    string voucher = Console.ReadLine();
                }
            }
            return(false);
        }
        return(true);
    }
Ejemplo n.º 8
0
        public static Boolean initConnect(config_data config)
        {
            jsonClass testConnect = new jsonClass {
                debugFlag = DebugMode
            };
            testProp tProp  = new testProp();
            string   urlMsg = "Please enter server connect URL (https will be used unless specified):";

            Console.WriteLine(config.url);
            while (config.url == "")
            {
                Console.WriteLine(urlMsg);
                string url = Console.ReadLine();
                if (!url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                {
                    url = "https://" + url;
                }
                Console.WriteLine("Testing connection to " + url);
                testConnect.connectURL = url;
                string jsonString = testConnect.toJson(tProp);
                string ret        = testConnect.jsonSendOnce(jsonString);
                if (ret != null)
                {
                    if (testConnect.isJsonSuccess(ret))
                    {
                        //File.WriteAllText(urlPath, url);
                        Console.WriteLine("Connecction successful");
                        config.url = url;
                        writeSettings(config);
                    }
                }
                else
                {
                    urlMsg = "Test connect failed, please enter server connect URL:";
                }
            }

            Console.WriteLine("Connecting to server {0}", serverURL);
            return(true);
        }
Ejemplo n.º 9
0
    IEnumerator Poster()
    {
        var toSerialize = new jsonClass()
        {
            Players = new List <Player>()
        };

        foreach (var Player in XDocument.Parse(String.Join("", File.ReadAllLines(xmlPath))).Root.Elements("LeaderboardEntry"))
        {
            var player = new Player();
            Func <string, string> find = (n) =>
            {
                var element = Player.Element(n);
                return(element == null ? null : element.Value);
            };
            player.UserName = find("UserName");
            var colors = Player.Element("UserColor");
            player.UserColor = new Dictionary <string, int>()
            {
                { "r", (int)(float.Parse(colors.Element("r").Value) * 100) },
                { "g", (int)(float.Parse(colors.Element("g").Value) * 100) },
                { "b", (int)(float.Parse(colors.Element("b").Value) * 100) },
            };
            player.SolveCount      = find("SolveCount");
            player.StrikeCount     = find("StrikeCount");
            player.SolveScore      = find("SolveScore");
            player.Rank            = find("Rank");
            player.TotalSoloClears = find("TotalSoloClears");
            player.SoloRank        = find("SoloRank");
            var oo = find("OptOut");
            player.OptedOut = oo == "true" ? true : false;
            toSerialize.Players.Add(player);
        }
        string Serialized = JsonConvert.SerializeObject(toSerialize, Formatting.None);

        yield return(Post(String.Format("http://{0}/setReq/{1}/{2}", tpData.IP, tpData.pwd, tpData.Name), Serialized));
    }
Ejemplo n.º 10
0
        public bool updateCracker()
        {
            hcUpdateProper hcUpd   = new hcUpdateProper();
            jsonClass      jsonUpd = new jsonClass {
                debugFlag = debugFlag, connectURL = client.connectURL
            };

            hcUpd.token           = client.tokenID;
            hcUpd.binaryVersionId = binaryVersionId;

            string jsonString = jsonUpd.toJson(hcUpd);
            string ret        = jsonUpd.jsonSend(jsonString);

            if (jsonUpd.isJsonSuccess(ret))
            {
                string crackerName = jsonUpd.getRetVar(ret, "name");
                string fullSubDir  = Path.Combine(AppPath, crackerName.ToLower(), binaryVersionId.ToString());
                if (!Directory.Exists(fullSubDir)) //We need to download
                {
                    Console.WriteLine("Client doesn't have required cracker...");
                    downloadClass dlClass = new downloadClass();
                    if (client.osID != 1)
                    {
                        dlClass.DownloadFileCurl(jsonUpd.getRetVar(ret, "url"), Path.Combine(AppPath, "crackerClient.7z"));
                    }
                    else
                    {
                        dlClass.DownloadFile(jsonUpd.getRetVar(ret, "url"), Path.Combine(AppPath, "crackerClient.7z"));
                    }

                    if (Directory.Exists(Path.Combine(AppPath, "tmp")))
                    {
                        Directory.Delete(Path.Combine(AppPath, "tmp"), true);
                    }

                    sevenZip.xtract(Path.Combine(AppPath, "crackerClient.7z"), Path.Combine(AppPath, "tmp"));

                    //check if files present

                    string[] files = Directory.GetFiles(Path.Combine(AppPath, "tmp"));
                    if (files.Length != 0)
                    {
                        Directory.Move(Path.Combine(AppPath, "tmp"), fullSubDir);
                    }
                    else
                    {
                        string[] dirs = Directory.GetDirectories(Path.Combine(AppPath, "tmp"));
                        Directory.Move(dirs[0], fullSubDir);
                    }

                    Directory.Delete(Path.Combine(AppPath, "tmp"));
                    string binLocation = Path.Combine(fullSubDir, jsonUpd.getRetVar(ret, "executable"));

                    if (client.osID != 1) //Chmod for non windows
                    {
                        Console.WriteLine("Applying execution permissions to cracker binary");
                        Process.Start("chmod", "+x \"" + binLocation + "\"");
                    }

                    //May need to inplement legacy checks if cracker is hashcat
                }
                else
                {
                    Console.WriteLine("Client already exists, skipping download");
                }
                client.crackerBinary = jsonUpd.getRetVar(ret, "executable");


                if (client.is64Bit)
                {
                    client.crackerBinary = client.crackerBinary.Replace(".", "64.");
                }
                else
                {
                    client.crackerBinary = client.crackerBinary.Replace(".", "32.");
                }



                client.crackerPath = Path.Combine(AppPath, crackerName.ToLower(), binaryVersionId.ToString());
            }


            if (Directory.Exists(client.crackerPath))
            {
                return(true);
            }
            else
            {
                Console.WriteLine("Could not locate cracker, perhaps manually delete cracker " + binaryVersionId.ToString());
                return(false);
            }
        }
Ejemplo n.º 11
0
        public Boolean getTask()
        {
            Console.WriteLine("Getting task");
            Task get = new Task
            {
                action = "task",
                token  = client.tokenID
            };

            jsonClass jsC = new jsonClass {
                debugFlag = debugFlag, connectURL = client.connectURL
            };
            string jsonString = jsC.toJson(get);
            string ret        = jsC.jsonSend(jsonString);



            if (jsC.isJsonSuccess(ret))
            {
                if (jsC.getRetVar(ret, "task") != "NONE")
                {
                    taskID     = Int32.Parse(jsC.getRetVar(ret, "task"));
                    attackcmd  = (jsC.getRetVar(ret, "attackcmd"));
                    cmdpars    = (jsC.getRetVar(ret, "cmdpars"));
                    hashlistID = Int32.Parse(jsC.getRetVar(ret, "hashlist"));
                    benchTime  = Int32.Parse(jsC.getRetVar(ret, "bench"));

                    Console.WriteLine("Server has assigned client with Task:{0} and Hashlist:{1}", taskID, hashlistID);
                    if (jsC.getRetVar(ret, "benchType") == "run")
                    {
                        benchMethod = 1;
                    }
                    else
                    {
                        benchMethod = 2;
                    }
                    statusTimer   = Int32.Parse(jsC.getRetVar(ret, "statustimer"));
                    hashlistAlias = jsC.getRetVar(ret, "hashlistAlias");
                    files         = jsC.getRetArray(ret, "files");
                    int gotChunk = 1;

                    foreach (string fileItem in files)
                    {
                        string actualFile = Path.Combine(filepath, fileItem);
                        if (!File.Exists(actualFile))
                        {
                            getFile(fileItem);

                            if (fileItem.ToLower().EndsWith(".7z"))
                            {
                                if (sevenZip.xtract(actualFile, filepath))
                                {
                                    File.WriteAllText(actualFile, "UNPACKED");
                                }
                                else
                                {
                                    return(false);
                                }
                            }
                        }
                    }

                    //Convert implied relative paths to absolute paths only applies to Mac OSX / Linux
                    //We, break up the attack command by space and check whether the file for the full path exists, we it does we replace
                    //Could potentially cause issues if the file names are attack numbers eg 1 2 3 4 5 6 7
                    //File names cannot contain spaces
                    //Altnerative method is to perform find replace on the attackcmd based on the files array
                    if (client.osID != 1)
                    {
                        string[] explode = new string[] { };
                        explode = attackcmd.Split(' ');

                        for (int i = 0; i < files.Count; i++)
                        {
                            string absolutePath = Path.Combine(filepath, files[i].ToString());
                            string match        = " " + files[i].ToString(); //Prefix a space for better matching
                            string replace      = " \"" + absolutePath + "\"";
                            if (File.Exists(absolutePath))
                            {
                                attackcmd = attackcmd.Replace(match, replace);
                            }
                        }
                    }

                    if (getHashes(hashlistID) == false)
                    {
                        return(false);
                    }


                    if (fileSize(Path.Combine(hashpath, Path.GetFileName(hashlistID.ToString()))) == 0)
                    {
                        Console.WriteLine("Hashlist is 0 bytes");
                        return(false);
                    }
                    gotChunk = getChunk(taskID);

                    while (gotChunk != 0)
                    {
                        gotChunk = getChunk(taskID);
                    }

                    return(true);
                }
                else
                {
                    Console.WriteLine("No new task assigned to agent");
                }
            }


            return(false);
        }
        public void runUpdate()
        {
            string currentBin = Environment.GetCommandLineArgs()[0]; //Grab current bin name

            if (System.AppDomain.CurrentDomain.FriendlyName == launcherProcName)
            {
                for (int i = 0; i < arguments.Length; i++)
                {
                    if (arguments[i] != "debug")
                    {
                        parentProc = (arguments[i]);
                        break;
                    }
                }

                //Looks like user isn't using custom name, use the default one
                if (string.IsNullOrEmpty(parentProc))
                {
                    parentProc = "hashtopolis.exe";
                }

                waitForProcess(parentProc);
                File.Copy(launcherProcName, parentProc, true);


                if (Type.GetType("Mono.Runtime") != null)
                {
                    Console.WriteLine("Client has now been updated, please re-launch the agent");
                }
                else
                {
                    Process reSpawn = new Process();
                    reSpawn.StartInfo.FileName = parentProc;
                    reSpawn.Start();
                }
                Environment.Exit(0);
            }
            else //We are either user-run bin or spanwed bin
            {
                waitForProcess(launcherProcName);
                if (File.Exists(launcherProcName))
                {
                    Console.WriteLine("Cleaning up files post update");
                    File.Delete(launcherProcName);
                }

                Console.WriteLine("Checking for client updates");
                updProps uProps = new updProps
                {
                    version = htpVersion,
                    token   = tokenID
                };

                jsonClass jsC = new jsonClass {
                    debugFlag = debugFlag, connectURL = connectURL
                };
                string jsonString = jsC.toJson(uProps);
                string ret        = jsC.jsonSend(jsonString);

                if (jsC.isJsonSuccess(ret))
                {
                    if (jsC.getRetVar(ret, "version") == "OK")
                    {
                        Console.WriteLine("You are using the latest client version");
                        return;
                    }
                    else
                    {
                        downloadClass dl     = new downloadClass();
                        string        dlFrom = Path.Combine(jsC.getRetVar(ret, "url"));
                        string        dlTo   = Path.Combine(parentPath, launcherProcName);
                        dl.DownloadFile(dlFrom, dlTo);
                        Console.WriteLine("Finished downloading latest client");
                        Console.WriteLine("Client will now relaunch");
                        Process Spawn = new Process();
                        Spawn.StartInfo.WorkingDirectory = parentPath;
                        if (Type.GetType("Mono.Runtime") != null)
                        {
                            Spawn.StartInfo.FileName  = "mono";
                            Spawn.StartInfo.Arguments = launcherProcName + " " + parentProc;
                        }
                        else
                        {
                            Spawn.StartInfo.FileName  = launcherProcName;
                            Spawn.StartInfo.Arguments = parentProc;
                        }

                        Spawn.Start();
                        Environment.Exit(0);
                    }
                }
                else
                {
                    Console.WriteLine("Exiting agnet");
                    Environment.Exit(0);
                }
            }
        }
Ejemplo n.º 13
0
        //This runs as an independant thread and uploads the STATUS generated from the hcAttack
        //This thread is run on a dynamic timer based on the size of the queue and will range from a base 2500ms down to 200ms
        //There is very little discruption to the attack as a very quick lock/unlock is performed on the packet list to pop the job off the queue
        public void threadPeriodicUpdate(ref List <Packets> uploadPackets, ref object objPacketlock)
        {
            System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
            customCulture.NumberFormat.NumberDecimalSeparator    = ".";
            System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;

            jsonClass jsC = new jsonClass {
                debugFlag = debugFlag, connectURL = client.connectURL
            };                                              //Initis the json class
            solveProps    sProps        = new solveProps(); //Init the properties to build our json string
            List <string> receivedZaps  = new List <string> {
            };                                              //List to store incoming zaps for writing
            string        ret           = "";               //Return string from json post
            string        jsonString    = "";
            string        zapfilePath   = zapPath + hashlistID.ToString();
            long          zapCount      = 0;
            List <string> batchList     = new List <string> {
            };
            double         chunkPercent = 0;
            double         chunkStart   = 0;
            Boolean        run          = true;
            List <Packets> singlePacket = new List <Packets> {
            };
            int  sleepTime     = 2500;
            long ulQueue       = 0;
            long lastOfileSize = 0;

            hcClass.debugFlag = debugFlag;

            string oPath = Path.Combine(tasksPath, taskID + "_" + chunkNo + ".txt"); // Path to write th -o file

            while (run)
            {
                Thread.Sleep(sleepTime); //Delay this thread for 2.5 seconds, if this falls behind it will batch the jobs
                lock (objPacketlock)
                {
                    if (uploadPackets.Count > 0)
                    {
                        singlePacket.Add(uploadPackets[0]);
                        ulQueue = uploadPackets.Count;
                        uploadPackets.RemoveAt(0);
                        if (uploadPackets.Count > 3)
                        {
                            sleepTime = 200; //Decrese the time we process the queue
                        }
                    }
                    else
                    {
                        sleepTime = 2500; //Decrese the time we process the queue
                    }
                }


                if (singlePacket.Count == 0)
                {
                    continue;
                }

                try
                {
                    {
                        //Special override as there is a possible race condition in HC, where STATUS4 doesn't give 100%
                        if (singlePacket[0].statusPackets["STATUS"] == 4 + offset)
                        {
                            singlePacket[0].statusPackets["PROGRESS1"] = singlePacket[0].statusPackets["PROGRESS2"];
                        }

                        sProps.token            = client.tokenID;
                        sProps.chunk            = chunkNo;
                        sProps.keyspaceProgress = singlePacket[0].statusPackets["CURKU"];
                        sProps.progress         = singlePacket[0].statusPackets["PROGRESS1"];
                        sProps.total            = singlePacket[0].statusPackets["PROGRESS2"];
                        sProps.speed            = singlePacket[0].statusPackets["SPEED_TOTAL"];
                        sProps.state            = singlePacket[0].statusPackets["STATUS"] - offset; //Client-side workaround for old STATUS on server

                        if (singlePacket[0].crackedPackets.Count > 200)
                        {
                            int max = 200;

                            //Process the requests in batches of 1000
                            while (singlePacket[0].crackedPackets.Count != 0)
                            {
                                List <string> subChunk = new List <string>(singlePacket[0].crackedPackets.GetRange(0, max));
                                singlePacket[0].crackedPackets.RemoveRange(0, max);
                                if (singlePacket[0].crackedPackets.Count < max)
                                {
                                    max = singlePacket[0].crackedPackets.Count;
                                }

                                if (stipPath == true)
                                {
                                    for (int i = 0; i <= subChunk.Count - 1; i++)
                                    {
                                        subChunk[i] = subChunk[i].Replace(actualHLpath + ":", "");
                                    }
                                }

                                sProps.cracks = subChunk;
                                jsonString    = jsC.toJson(sProps);
                                ret           = jsC.jsonSend(jsonString);

                                if (!jsC.isJsonSuccess(ret)) //If we received error, eg task was removed just break
                                {
                                    break;
                                }
                            }
                        }
                        else
                        {
                            if (stipPath == true)
                            {
                                for (int i = 0; i <= singlePacket[0].crackedPackets.Count - 1; i++)
                                {
                                    singlePacket[0].crackedPackets[i] = singlePacket[0].crackedPackets[i].Replace(actualHLpath + ":", "");
                                }
                            }
                            sProps.cracks = singlePacket[0].crackedPackets;

                            jsonString = jsC.toJson(sProps);
                            ret        = jsC.jsonSend(jsonString);
                        }
                    }


                    if (jsC.isJsonSuccess(ret))
                    {
                        if (jsC.getRetVar(ret, "agent") == "stop") //Special command sent by server, possibly undocumented
                        {
                            hcClass.hcProc.CancelOutputRead();
                            hcClass.hcProc.CancelErrorRead();
                            hcClass.hcProc.Kill();
                            run = false;
                            Console.WriteLine("Server has instructed the client terminate the task via stop");
                        }

                        chunkStart   = Math.Floor(singlePacket[0].statusPackets["PROGRESS2"]) / (skip + length) * skip;
                        chunkPercent = Math.Round((Convert.ToDouble(singlePacket[0].statusPackets["PROGRESS1"]) - chunkStart) / Convert.ToDouble(singlePacket[0].statusPackets["PROGRESS2"] - chunkStart), 4) * 100;


                        receivedZaps = jsC.getRetList(ret, "zaps"); //Check whether the server sent out hashes to zap
                        if (receivedZaps.Count > 0)
                        {
                            zapCount++;
                            File.WriteAllLines(Path.Combine(zapfilePath + zapCount.ToString()), receivedZaps); //Write hashes for zapping
                        }
                        Console.WriteLine("Progress:{0,7} | Speed:{1,-4} | Cracks:{2,-4} | Accepted:{3,-4} | Zapped:{4,-4} | Queue:{5,-2}", chunkPercent.ToString("F") + "%", speedCalc(singlePacket[0].statusPackets["SPEED_TOTAL"]), singlePacket[0].crackedPackets.Count, jsC.getRetVar(ret, "cracked"), receivedZaps.Count, ulQueue);
                        receivedZaps.Clear();
                    }


                    else //We received an error from the server, terminate the run
                    {
                        string writeCracked = Path.Combine(hashpath, Path.GetFileName(hashlistID.ToString())) + ".cracked";
                        Console.WriteLine("Writing any cracks in queue to file " + writeCracked);
                        File.AppendAllLines(writeCracked, singlePacket[0].crackedPackets);
                        lock (objPacketlock)
                        {
                            if (uploadPackets.Count > 0)
                            {
                                for (int i = 0; i < uploadPackets.Count; i++)
                                {
                                    if (uploadPackets[i].crackedPackets.Count > 0)
                                    {
                                        File.AppendAllLines(writeCracked, uploadPackets[i].crackedPackets);
                                    }
                                }
                            }
                        }

                        run = false; //Potentially we can change this so keep submitting the rest of the cracked queue instead of terminating

                        if (!hcClass.hcProc.HasExited)
                        {
                            hcClass.hcProc.CancelOutputRead();
                            hcClass.hcProc.CancelErrorRead();
                            hcClass.hcProc.Kill();
                            //The server would need to accept the chunk but return an error
                        }
                        break;
                    }


                    {
                        if (singlePacket[0].statusPackets["STATUS"] >= 4 + offset) //We are the last upload task
                        //if (singlePacket[0].statusPackets["STATUS"] >= 5) //Uncomment this line, and comment above line for upcoming HC > 3.6
                        {
                            Console.WriteLine("Finished processing chunk");
                            singlePacket.Clear();
                            run = false;
                        }
                        else
                        {
                            singlePacket.RemoveAt(0);
                        }
                    }
                }


                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine("Error processing packet for upload");
                }
            }
        }
Ejemplo n.º 14
0
    private bool updateAgentInformation()
    {
        Console.WriteLine("Sending server client information");
        jsonClass jsC = new jsonClass {
            debugFlag = debugFlag, connectURL = connectURL
        };

        setOS();


        List <string> deviceList;
        string        CPUModel = "";

        deviceList = new List <string> {
        };

        if (osID == 1)
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Description FROM Win32_VideoController"); //Prep object to query windows GPUs

            //Get Devices (Windows)
            foreach (ManagementObject mo in searcher.Get())
            {
                deviceList.Add(mo.Properties["Description"].Value.ToString().Trim());
            }

            //Get CPU (Windows)
            searcher = new ManagementObjectSearcher("SELECT Name from Win32_Processor"); //Prep object to query windows CPUs
            foreach (ManagementObject mo in searcher.Get())
            {
                deviceList.Add(mo.Properties["Name"].Value.ToString().Trim());
            }
        }
        else if (osID == 0)
        {
            //Get GPU Devices (Linux) use lspci to query GPU
            ProcessStartInfo pinfo = new ProcessStartInfo();
            pinfo.FileName               = "lspci";
            pinfo.UseShellExecute        = false;
            pinfo.RedirectStandardOutput = true;
            Process lspci = new Process();
            lspci.StartInfo = pinfo;
            lspci.Start();
            List <string> searchList = new List <string>(new string[] { "VGA compatible controller: ", "3D controller: " });


            while (!lspci.HasExited)
            {
                while (!lspci.StandardOutput.EndOfStream)
                {
                    string stdOut = lspci.StandardOutput.ReadLine();
                    foreach (string searchItem in searchList)
                    {
                        int pozi = stdOut.IndexOf(searchItem);
                        if (pozi != -1)
                        {
                            deviceList.Add(stdOut.Substring(pozi + searchItem.Length));
                        }
                    }
                }
            }

            //Get CPU (Linux) use lscpu to query CPU
            pinfo.FileName               = "lscpu";
            pinfo.UseShellExecute        = false;
            pinfo.RedirectStandardOutput = true;
            lspci.StartInfo              = pinfo;
            lspci.Start();
            string searchString = "Model Name: ";
            while (!lspci.HasExited)
            {
                while (!lspci.StandardOutput.EndOfStream)
                {
                    string stdOut = lspci.StandardOutput.ReadLine();
                    int    pos    = stdOut.IndexOf(searchString);
                    if (pos != -1)
                    {
                        deviceList.Add(stdOut.Substring(pos + searchString.Length));
                    }
                }
            }
        }
        else if (osID == 2)
        {
            //Get Machine Name (Mac)
            ProcessStartInfo pinfo = new ProcessStartInfo();
            pinfo.FileName               = "scutil";
            pinfo.Arguments              = " --get ComputerName";
            pinfo.UseShellExecute        = false;
            pinfo.RedirectStandardError  = true;
            pinfo.RedirectStandardOutput = true;


            //Get Devices (Mac)
            pinfo.FileName  = "system_profiler";
            pinfo.Arguments = " -detaillevel mini";
            Process getDevices = new Process();
            getDevices.StartInfo = pinfo;

            Console.WriteLine("Please wait while devices are being enumerated...");
            getDevices.Start();
            Boolean triggerRead = false;

            string searchID = "Chipset Model: ";

            while (!getDevices.StandardOutput.EndOfStream)
            {
                string stdOut = getDevices.StandardOutput.ReadLine().TrimEnd();

                if (triggerRead == true)
                {
                    if (stdOut.Contains("Total Number of Cores:")) //Just incase we go past
                    {
                        break;
                    }
                    if (stdOut.Contains("Hardware:"))
                    {
                        searchID = "Processor Name: ";
                    }
                    int pos = stdOut.IndexOf(searchID);

                    if (pos != -1)
                    {
                        if (searchID == "Chipset Model: ")
                        {
                            deviceList.Add(stdOut.Substring(pos + searchID.Length));
                        }
                        else if (searchID == "Processor Name: ")
                        {
                            CPUModel = stdOut.Substring(pos + searchID.Length);
                            searchID = "Processor Speed: ";
                        }
                        else if (searchID == "Processor Speed: ")
                        {
                            CPUModel = CPUModel + " @ " + stdOut.Substring(pos + searchID.Length);
                            deviceList.Add(CPUModel);
                            break;
                        }
                    }
                }
                else if (triggerRead == false)
                {
                    if (stdOut.Contains("Graphics/Displays:"))
                    {
                        triggerRead = true;
                    }
                }
            }
        }

        String guid = Guid.NewGuid().ToString(); //Generate GUID

        UpdateClient update = new UpdateClient
        {
            action  = "updateInformation",
            token   = tokenID,
            uid     = guid,
            os      = osID,
            devices = deviceList
        };

        string jsonString = jsC.toJson(update);
        string ret        = jsC.jsonSend(jsonString);

        if (jsC.isJsonSuccess(ret))
        {
            return(true);
        }
        return(false);
    }
Ejemplo n.º 15
0
    private bool registerAgent(string iVoucher)
    {
        jsonClass jsC = new jsonClass {
            debugFlag = debugFlag, connectURL = connectURL
        };
        string machineName = "default";

        setOS();

        if (osID == 1) //Windows
        {
            machineName = System.Environment.MachineName;
        }
        else if (osID == 0) //Linux
        {
            ProcessStartInfo pinfo = new ProcessStartInfo();
            pinfo                        = new ProcessStartInfo();
            pinfo.FileName               = "uname";
            pinfo.Arguments              = "-n";
            pinfo.UseShellExecute        = false;
            pinfo.RedirectStandardOutput = true;
            Process uname = new Process();
            uname.StartInfo = pinfo;
            uname.Start();
            while (!uname.HasExited)
            {
                while (!uname.StandardOutput.EndOfStream)
                {
                    string stdOut = uname.StandardOutput.ReadLine();
                    machineName = stdOut;
                }
            }
        }
        else if (osID == 2) //Mac
        {
            //Get Machine Name (Mac)
            ProcessStartInfo pinfo = new ProcessStartInfo();
            pinfo.FileName               = "scutil";
            pinfo.Arguments              = " --get ComputerName";
            pinfo.UseShellExecute        = false;
            pinfo.RedirectStandardError  = true;
            pinfo.RedirectStandardOutput = true;

            Process getMachineName = new Process();
            getMachineName.StartInfo = pinfo;
            getMachineName.Start();
            while (!getMachineName.HasExited)
            {
                while (!getMachineName.StandardOutput.EndOfStream)
                {
                    string stdOut = getMachineName.StandardOutput.ReadLine();
                    machineName = stdOut;
                }
            }
        }

        Register regist = new Register
        {
            action  = "register",
            voucher = iVoucher,
            name    = machineName,
        };

        string jsonString = jsC.toJson(regist);
        string ret        = jsC.jsonSend(jsonString);

        String guid = Guid.NewGuid().ToString(); //Generate GUID

        if (jsC.isJsonSuccess(ret))
        {
            tokenID = jsC.getRetVar(ret, "token");
            File.WriteAllText(tokenPath, tokenID);

            updateAgentInformation();

            return(true);
        }
        return(false);
    }
Ejemplo n.º 16
0
        public Boolean getTask()
        {
            Console.WriteLine("Getting task");
            Task get = new Task
            {
                action = "getTask",
                token  = client.tokenID
            };

            jsonClass jsC = new jsonClass {
                debugFlag = debugFlag, connectURL = client.connectURL
            };
            string jsonString = jsC.toJson(get);
            string ret        = jsC.jsonSend(jsonString);

            if (jsC.isJsonSuccess(ret))
            {
                if (jsC.getRetVar(ret, "taskId") != null)
                {
                    taskID     = Int32.Parse(jsC.getRetVar(ret, "taskId"));
                    attackcmd  = (jsC.getRetVar(ret, "attackcmd"));
                    cmdpars    = (jsC.getRetVar(ret, "cmdpars"));
                    hashlistID = Int32.Parse(jsC.getRetVar(ret, "hashlistId"));
                    benchTime  = Int32.Parse(jsC.getRetVar(ret, "bench"));
                    crackerId  = Int32.Parse(jsC.getRetVar(ret, "crackerId"));

                    Console.WriteLine("Server has assigned client with Task:{0}, Cracker:{2} and Hashlist:{1}", taskID, hashlistID, crackerId);
                    if (jsC.getRetVar(ret, "benchType") == "run")
                    {
                        benchMethod = 1;
                    }
                    else
                    {
                        benchMethod = 2;
                    }
                    statusTimer   = Int32.Parse(jsC.getRetVar(ret, "statustimer"));
                    hashlistAlias = jsC.getRetVar(ret, "hashlistAlias");
                    files         = jsC.getRetArray(ret, "files");
                    int gotChunk = 1;

                    foreach (string fileItem in files)
                    {
                        string actualFile = Path.Combine(filepath, fileItem);
                        if (!File.Exists(actualFile))
                        {
                            getFile(fileItem);

                            if (fileItem.ToLower().EndsWith(".7z"))
                            {
                                if (sevenZip.xtract(actualFile, filepath))
                                {
                                    File.WriteAllText(actualFile, "UNPACKED");
                                }
                                else
                                {
                                    return(false);
                                }
                            }
                        }
                    }

                    //Convert implied relative paths to absolute paths only applies to Mac OSX / Linux
                    //We, break up the attack command by space and check whether the file for the full path exists, we it does we replace
                    //Could potentially cause issues if the file names are attack numbers eg 1 2 3 4 5 6 7
                    //File names cannot contain spaces
                    //Altnerative method is to perform find replace on the attackcmd based on the files array
                    if (client.osID != 1)
                    {
                        string[] explode = new string[] { };
                        explode = attackcmd.Split(' ');

                        for (int i = 0; i < files.Count; i++)
                        {
                            string absolutePath = Path.Combine(filepath, files[i].ToString());
                            string match        = " " + files[i].ToString(); //Prefix a space for better matching
                            string replace      = " \"" + absolutePath + "\"";
                            if (File.Exists(absolutePath))
                            {
                                attackcmd = attackcmd.Replace(match, replace);
                            }
                        }
                    }

                    if (getHashes(hashlistID) == false)
                    {
                        return(false);
                    }


                    if (fileSize(Path.Combine(hashpath, Path.GetFileName(hashlistID.ToString()))) == 0)
                    {
                        Console.WriteLine("Hashlist is 0 bytes");
                        return(false);
                    }

                    //Check if we have the correct cracker if not we download

                    hashcatUpdateClass hcUpdater = new hashcatUpdateClass {
                        debugFlag = debugFlag, client = client, AppPath = appPath, sevenZip = sevenZip, binaryVersionId = Int32.Parse(jsC.getRetVar(ret, "crackerId"))
                    };

                    //If the cracker did not successfully initliaze then throw error and report
                    if (!hcUpdater.updateCracker())
                    {
                        errorProps eProps = new errorProps
                        {
                            token   = client.tokenID,
                            taskId  = taskID,
                            message = "Client could not locate cracker"
                        };
                        jsonString = jsC.toJson(eProps);
                        ret        = jsC.jsonSend(jsonString);
                        return(false);
                    }

                    //The client may change per task, we need to update these after the update
                    hcClass.hcDirectory = client.crackerPath;
                    hcClass.hcBinary    = client.crackerBinary;

                    gotChunk = getChunk(taskID);

                    while (gotChunk != 0)
                    {
                        gotChunk = getChunk(taskID);
                    }

                    return(true);
                }
                else
                {
                    Console.WriteLine("No new task assigned to agent");
                }
            }


            return(false);
        }
Ejemplo n.º 17
0
        public bool updateHashcat()
        {
            hcUpdateProper hcUpd   = new hcUpdateProper();
            jsonClass      jsonUpd = new jsonClass {
                debugFlag = debugFlag, connectURL = client.connectURL
            };

            hcUpd.token = client.tokenID;
            string hcBinName = "hashcat";

            if (client.osID == 0)
            {
                hcBinName = hcBinName + "64.bin";
            }
            else if (client.osID == 1)
            {
                hcBinName = hcBinName + "64.exe";
            }

            string hcBinLoc = Path.Combine(AppPath, "hashcat", hcBinName);

            if (File.Exists(hcBinLoc))
            {
                hcUpd.force = 0; //HC exists, we don't need to force
            }
            else
            {
                hcUpd.force = 1; //HC doesn't exist, we need to force
            }

            string jsonString = jsonUpd.toJson(hcUpd);
            string ret        = jsonUpd.jsonSend(jsonString);

            if (jsonUpd.getRetVar(ret, "version") == "NEW")
            {
                downloadClass dlClass = new downloadClass();

                if (client.osID != 1)
                {
                    dlClass.DownloadFileCurl(jsonUpd.getRetVar(ret, "url"), Path.Combine(AppPath, "hcClient.7z"));
                }
                else
                {
                    dlClass.DownloadFile(jsonUpd.getRetVar(ret, "url"), Path.Combine(AppPath, "hcClient.7z"));
                }

                sevenZip.xtract(Path.Combine(AppPath, "hcClient.7z"), Path.Combine(AppPath, "hcClient"));
                if (Directory.Exists(Path.Combine(AppPath, "hashcat")))
                {
                    Directory.Delete(Path.Combine(AppPath, "hashcat"), true);
                }
                Directory.Move(Path.Combine(AppPath, "hcClient", jsonUpd.getRetVar(ret, "rootdir")), Path.Combine(AppPath, "hashcat"));
                Directory.Delete(Path.Combine(AppPath, "hcClient"));


                if (client.osID != 1) //Chmod for non windows
                {
                    Console.WriteLine("Applying execution permissions to 7zr binary");
                    Process.Start("chmod", "+x \"" + hcBinLoc + "\"");
                }
            }

            if (File.Exists(hcBinLoc))
            {
                return(true);
            }

            return(false);
        }
Ejemplo n.º 18
0
 public KafkaHelper()
 {
     _jsonData = new jsonClass();
 }